feat: bootstrap v2 admin app tabs

This commit is contained in:
xuhongbin
2026-03-07 18:12:39 +08:00
parent c0d1ab377a
commit 28348f76cf
33 changed files with 5536 additions and 151 deletions

47
app/(tabs)/_layout.tsx Normal file
View File

@@ -0,0 +1,47 @@
import { Tabs } from 'expo-router';
import { ActivitySquare, ChartNoAxesCombined, Users } from 'lucide-react-native';
export default function TabsLayout() {
return (
<Tabs
screenOptions={{
headerShown: false,
tabBarActiveTintColor: '#1d5f55',
tabBarInactiveTintColor: '#8a8072',
tabBarStyle: {
backgroundColor: '#fbf8f2',
borderTopWidth: 0,
height: 84,
paddingTop: 10,
paddingBottom: 18,
},
}}
>
<Tabs.Screen
name="index"
options={{
title: '概览',
tabBarIcon: ({ color, size }) => <ChartNoAxesCombined color={color} size={size} />,
}}
/>
<Tabs.Screen
name="users"
options={{
title: '用户',
tabBarIcon: ({ color, size }) => <Users color={color} size={size} />,
}}
/>
<Tabs.Screen
name="monitor"
options={{
title: '运维监控',
tabBarIcon: ({ color, size }) => <ActivitySquare color={color} size={size} />,
}}
/>
<Tabs.Screen name="settings" options={{ href: null }} />
<Tabs.Screen name="groups" options={{ href: null }} />
<Tabs.Screen name="keys" options={{ href: null }} />
<Tabs.Screen name="accounts" options={{ href: null }} />
</Tabs>
);
}

89
app/(tabs)/accounts.tsx Normal file
View File

@@ -0,0 +1,89 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { KeyRound, Search, ShieldCheck, ShieldOff } from 'lucide-react-native';
import { router } from 'expo-router';
import { useMemo, useState } from 'react';
import { Pressable, Text, TextInput, View } from 'react-native';
import { ListCard } from '@/src/components/list-card';
import { ScreenShell } from '@/src/components/screen-shell';
import { listAccounts, setAccountSchedulable, testAccount } from '@/src/services/admin';
export default function AccountsScreen() {
const [search, setSearch] = useState('');
const keyword = useMemo(() => search.trim(), [search]);
const queryClient = useQueryClient();
const accountsQuery = useQuery({
queryKey: ['accounts', keyword],
queryFn: () => listAccounts(keyword),
});
const toggleMutation = useMutation({
mutationFn: ({ accountId, schedulable }: { accountId: number; schedulable: boolean }) =>
setAccountSchedulable(accountId, schedulable),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['accounts'] }),
});
const items = accountsQuery.data?.items ?? [];
const errorMessage = accountsQuery.error instanceof Error ? accountsQuery.error.message : '';
return (
<ScreenShell title="API 密钥" subtitle="管理您的 API 密钥和访问令牌">
<View className="flex-row items-center rounded-[24px] bg-[#fbf8f2] px-4 py-3">
<Search color="#7d7468" size={18} />
<TextInput
value={search}
onChangeText={setSearch}
placeholder="搜索 key 名称"
placeholderTextColor="#9b9081"
className="ml-3 flex-1 text-base text-[#16181a]"
/>
</View>
{items.length === 0 ? (
<ListCard title="暂无 Key" meta={errorMessage || '连上后这里会展示 key 列表。'} icon={KeyRound} />
) : (
items.map((account) => (
<Pressable key={account.id} onPress={() => router.push(`/accounts/${account.id}`)}>
<ListCard
title={account.name}
meta={`${account.platform} · ${account.type} · 优先级 ${account.priority ?? 0}`}
badge={account.status || 'unknown'}
icon={KeyRound}
>
<View className="flex-row items-center justify-between">
<View className="flex-row items-center gap-2">
{account.schedulable ? <ShieldCheck color="#7d7468" size={14} /> : <ShieldOff color="#7d7468" size={14} />}
<Text className="text-sm text-[#7d7468]">{account.schedulable ? '可调度' : '暂停调度'}</Text>
</View>
<View className="flex-row gap-2">
<Pressable
className="rounded-full bg-[#1b1d1f] px-4 py-2"
onPress={(event) => {
event.stopPropagation();
testAccount(account.id).catch(() => undefined);
}}
>
<Text className="text-xs font-semibold uppercase tracking-[1.2px] text-[#f6f1e8]"></Text>
</Pressable>
<Pressable
className="rounded-full bg-[#e7dfcf] px-4 py-2"
onPress={(event) => {
event.stopPropagation();
toggleMutation.mutate({
accountId: account.id,
schedulable: !account.schedulable,
});
}}
>
<Text className="text-xs font-semibold uppercase tracking-[1.2px] text-[#4e463e]"></Text>
</Pressable>
</View>
</View>
</ListCard>
</Pressable>
))
)}
</ScreenShell>
);
}

57
app/(tabs)/groups.tsx Normal file
View File

@@ -0,0 +1,57 @@
import { useQuery } from '@tanstack/react-query';
import { FolderKanban, Layers3, Search } from 'lucide-react-native';
import { useMemo, useState } from 'react';
import { Text, TextInput, View } from 'react-native';
import { ListCard } from '@/src/components/list-card';
import { ScreenShell } from '@/src/components/screen-shell';
import { listGroups } from '@/src/services/admin';
export default function GroupsScreen() {
const [search, setSearch] = useState('');
const keyword = useMemo(() => search.trim(), [search]);
const groupsQuery = useQuery({
queryKey: ['groups', keyword],
queryFn: () => listGroups(keyword),
});
const items = groupsQuery.data?.items ?? [];
const errorMessage = groupsQuery.error instanceof Error ? groupsQuery.error.message : '';
return (
<ScreenShell title="分组管理" subtitle="分组决定调度、价格倍率和账号归属,是后台的核心配置之一。">
<View className="flex-row items-center rounded-[24px] bg-[#fbf8f2] px-4 py-3">
<Search color="#7d7468" size={18} />
<TextInput
value={search}
onChangeText={setSearch}
placeholder="搜索分组名称"
placeholderTextColor="#9b9081"
className="ml-3 flex-1 text-base text-[#16181a]"
/>
</View>
{items.length === 0 ? (
<ListCard title="暂无分组" meta={errorMessage || '连上 Sub2API 后,这里会展示分组列表。'} icon={FolderKanban} />
) : (
items.map((group) => (
<ListCard
key={group.id}
title={group.name}
meta={`${group.platform} · 倍率 ${group.rate_multiplier ?? 1} · ${group.subscription_type || 'standard'}`}
badge={group.status || 'active'}
icon={FolderKanban}
>
<View className="flex-row items-center gap-2">
<Layers3 color="#7d7468" size={14} />
<Text className="text-sm text-[#7d7468]">
{group.account_count ?? 0} · {group.is_exclusive ? '独占分组' : '共享分组'}
</Text>
</View>
</ListCard>
))
)}
</ScreenShell>
);
}

101
app/(tabs)/index.tsx Normal file
View File

@@ -0,0 +1,101 @@
import { useQuery } from '@tanstack/react-query';
import { Activity, Coins, RefreshCw, Rows3, Zap } from 'lucide-react-native';
import { Pressable, Text, View } from 'react-native';
import { LineTrendChart } from '@/src/components/line-trend-chart';
import { ScreenShell } from '@/src/components/screen-shell';
import { StatCard } from '@/src/components/stat-card';
import { getAdminSettings, getDashboardStats, getDashboardTrend } from '@/src/services/admin';
function getDateRange() {
const end = new Date();
const start = new Date();
start.setDate(end.getDate() - 6);
const toDate = (value: Date) => value.toISOString().slice(0, 10);
return {
start_date: toDate(start),
end_date: toDate(end),
};
}
export default function DashboardScreen() {
const range = getDateRange();
const statsQuery = useQuery({
queryKey: ['dashboard-stats'],
queryFn: getDashboardStats,
});
const trendQuery = useQuery({
queryKey: ['dashboard-trend', range.start_date, range.end_date],
queryFn: () => getDashboardTrend({ ...range, granularity: 'day' }),
});
const settingsQuery = useQuery({
queryKey: ['admin-settings'],
queryFn: getAdminSettings,
});
const stats = statsQuery.data;
const errorMessage = statsQuery.error instanceof Error ? statsQuery.error.message : '';
const siteName = settingsQuery.data?.site_name?.trim() || '管理控制台';
const trendPoints = (trendQuery.data?.trend ?? []).map((item) => ({
label: item.date.slice(5),
value: item.total_tokens,
}));
return (
<ScreenShell
title={siteName}
subtitle="把最常看的管理指标和关键动作先搬到手机里,方便随时巡检。"
right={
<Pressable
className="h-11 w-11 items-center justify-center rounded-full bg-[#2d3134]"
onPress={() => {
statsQuery.refetch();
trendQuery.refetch();
}}
>
<RefreshCw color="#f6f1e8" size={18} />
</Pressable>
}
>
<View className="flex-row gap-4">
<View className="flex-1">
<StatCard label="今日 Token" value={stats ? `${Math.round((stats.today_tokens ?? 0) / 1000)}k` : '--'} tone="dark" trend="up" icon={Zap} />
</View>
<View className="flex-1">
<StatCard label="今日成本" value={stats ? `$${Number(stats.today_cost ?? 0).toFixed(2)}` : '--'} icon={Coins} />
</View>
</View>
<View className="flex-row gap-4">
<View className="flex-1">
<StatCard label="输出 Token" value={stats ? `${Math.round((stats.today_output_tokens ?? 0) / 1000)}k` : '--'} trend="up" icon={Rows3} />
</View>
<View className="flex-1">
<StatCard label="吞吐 TPM" value={String(stats?.tpm ?? '--')} icon={Activity} />
</View>
</View>
{trendPoints.length > 1 ? (
<LineTrendChart
title="近 7 天 Token 趋势"
subtitle="聚焦 token 消耗,而不是大 banner"
points={trendPoints}
formatValue={(value) => `${Math.round(value / 1000)}k`}
/>
) : null}
<View className="rounded-[24px] border border-[#e6dece] bg-[#fbf8f2] p-4">
<Text className="text-sm leading-6 text-[#7d7468]">
{stats
? `今日请求 ${stats.today_requests} · 活跃用户 ${stats.active_users} · 总账号 ${stats.total_accounts}`
: errorMessage || '正在等待代理或后台连接。'}
</Text>
</View>
</ScreenShell>
);
}

105
app/(tabs)/monitor.tsx Normal file
View File

@@ -0,0 +1,105 @@
import { useQuery } from '@tanstack/react-query';
import { AlertTriangle, Gauge, Layers3, Wrench } from 'lucide-react-native';
import { Text, View } from 'react-native';
import { LineTrendChart } from '@/src/components/line-trend-chart';
import { ListCard } from '@/src/components/list-card';
import { ScreenShell } from '@/src/components/screen-shell';
import { StatCard } from '@/src/components/stat-card';
import { getDashboardModels, getDashboardStats, getDashboardTrend, listAccounts } from '@/src/services/admin';
function getDateRange() {
const end = new Date();
const start = new Date();
start.setDate(end.getDate() - 6);
const toDate = (value: Date) => value.toISOString().slice(0, 10);
return {
start_date: toDate(start),
end_date: toDate(end),
};
}
export default function MonitorScreen() {
const range = getDateRange();
const statsQuery = useQuery({
queryKey: ['monitor-stats'],
queryFn: getDashboardStats,
});
const trendQuery = useQuery({
queryKey: ['monitor-trend', range.start_date, range.end_date],
queryFn: () => getDashboardTrend({ ...range, granularity: 'day' }),
});
const modelsQuery = useQuery({
queryKey: ['monitor-models', range.start_date, range.end_date],
queryFn: () => getDashboardModels(range),
});
const accountsQuery = useQuery({
queryKey: ['monitor-accounts'],
queryFn: () => listAccounts(''),
});
const stats = statsQuery.data;
const trendPoints = (trendQuery.data?.trend ?? []).map((item) => ({
label: item.date.slice(5),
value: item.total_tokens,
}));
const topModels = (modelsQuery.data?.models ?? []).slice(0, 3);
const incidentAccounts = (accountsQuery.data?.items ?? []).filter((item) => item.status === 'error' || item.error_message).slice(0, 5);
return (
<ScreenShell title="运维监控" subtitle="运维监控与排障">
<View className="flex-row gap-4">
<View className="flex-1">
<StatCard label="异常账号" value={String(stats?.error_accounts ?? incidentAccounts.length ?? '--')} tone="dark" trend="down" icon={AlertTriangle} />
</View>
<View className="flex-1">
<StatCard label="实时 TPM" value={String(stats?.tpm ?? '--')} icon={Gauge} />
</View>
</View>
{trendPoints.length > 1 ? (
<LineTrendChart
title="Token 监控"
subtitle="最近 7 天总 token 吞吐"
points={trendPoints}
color="#a34d2d"
formatValue={(value) => `${Math.round(value / 1000)}k`}
/>
) : null}
<ListCard title="热点模型" meta="按请求与 token 用量排序" icon={Layers3}>
<View className="gap-3">
{topModels.map((item) => (
<View key={item.model} className="flex-row items-center justify-between border-b border-[#eee6d7] pb-3 last:border-b-0 last:pb-0">
<View className="flex-1 pr-4">
<Text className="text-sm font-semibold text-[#16181a]">{item.model}</Text>
<Text className="mt-1 text-xs text-[#7d7468]"> {item.requests} · Token {Math.round(item.total_tokens / 1000)}k</Text>
</View>
<Text className="text-sm font-semibold text-[#4e463e]">${Number(item.cost).toFixed(2)}</Text>
</View>
))}
{topModels.length === 0 ? <Text className="text-sm text-[#7d7468]"></Text> : null}
</View>
</ListCard>
<ListCard title="排障列表" meta="优先关注状态异常或带错误信息的上游账号" icon={Wrench}>
<View className="gap-3">
{incidentAccounts.map((item) => (
<View key={item.id} className="rounded-[18px] bg-[#f1ece2] px-4 py-3">
<Text className="text-sm font-semibold text-[#16181a]">{item.name}</Text>
<Text className="mt-1 text-xs text-[#7d7468]">{item.platform} · {item.status || 'unknown'} · {item.schedulable ? '可调度' : '暂停调度'}</Text>
<Text className="mt-2 text-xs text-[#a34d2d]">{item.error_message || '状态异常,建议从运维视角继续排查这个上游账号'}</Text>
</View>
))}
{incidentAccounts.length === 0 ? <Text className="text-sm text-[#7d7468]"></Text> : null}
</View>
</ListCard>
</ScreenShell>
);
}

57
app/(tabs)/users.tsx Normal file
View File

@@ -0,0 +1,57 @@
import { useQuery } from '@tanstack/react-query';
import { Activity, Search, UserRound } from 'lucide-react-native';
import { router } from 'expo-router';
import { useMemo, useState } from 'react';
import { Pressable, Text, TextInput, View } from 'react-native';
import { ListCard } from '@/src/components/list-card';
import { ScreenShell } from '@/src/components/screen-shell';
import { listUsers } from '@/src/services/admin';
export default function UsersScreen() {
const [search, setSearch] = useState('');
const keyword = useMemo(() => search.trim(), [search]);
const usersQuery = useQuery({
queryKey: ['users', keyword],
queryFn: () => listUsers(keyword),
});
const items = usersQuery.data?.items ?? [];
const errorMessage = usersQuery.error instanceof Error ? usersQuery.error.message : '';
return (
<ScreenShell title="用户管理" subtitle="搜索用户、查看详情,并在详情页里做余额调整。">
<View className="flex-row items-center rounded-[24px] bg-[#fbf8f2] px-4 py-3">
<Search color="#7d7468" size={18} />
<TextInput
value={search}
onChangeText={setSearch}
placeholder="搜索邮箱或用户名"
placeholderTextColor="#9b9081"
className="ml-3 flex-1 text-base text-[#16181a]"
/>
</View>
{items.length === 0 ? (
<ListCard title="暂无数据" meta={errorMessage || '配置好后台连接后,这里会展示管理员用户列表。'} icon={UserRound} />
) : (
items.map((user) => (
<Pressable key={user.id} onPress={() => router.push(`/users/${user.id}`)}>
<ListCard
title={user.username || user.email}
meta={`${user.email} · 余额 ${Number(user.balance ?? 0).toFixed(2)} · 并发 ${user.concurrency ?? 0}`}
badge={user.status || 'active'}
icon={UserRound}
>
<View className="flex-row items-center gap-2">
<Activity color="#7d7468" size={14} />
<Text className="text-sm text-[#7d7468]"> {user.current_concurrency ?? 0}</Text>
</View>
</ListCard>
</Pressable>
))
)}
</ScreenShell>
);
}