mirror of
https://gitee.com/wanwujie/sub2api-mobile
synced 2026-04-13 11:34:45 +08:00
feat: bootstrap v2 admin app tabs
This commit is contained in:
47
app/(tabs)/_layout.tsx
Normal file
47
app/(tabs)/_layout.tsx
Normal 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
89
app/(tabs)/accounts.tsx
Normal 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
57
app/(tabs)/groups.tsx
Normal 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
101
app/(tabs)/index.tsx
Normal 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
105
app/(tabs)/monitor.tsx
Normal 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
57
app/(tabs)/users.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
41
app/_layout.tsx
Normal file
41
app/_layout.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
import '@/src/global.css';
|
||||
|
||||
import { QueryClientProvider } from '@tanstack/react-query';
|
||||
import { Stack } from 'expo-router';
|
||||
import { useEffect } from 'react';
|
||||
import { ActivityIndicator, View } from 'react-native';
|
||||
import { GestureHandlerRootView } from 'react-native-gesture-handler';
|
||||
|
||||
import { queryClient } from '@/src/lib/query-client';
|
||||
import { adminConfigState, hydrateAdminConfig } from '@/src/store/admin-config';
|
||||
|
||||
const { useSnapshot } = require('valtio/react');
|
||||
|
||||
export default function RootLayout() {
|
||||
const config = useSnapshot(adminConfigState);
|
||||
|
||||
useEffect(() => {
|
||||
hydrateAdminConfig().catch(() => undefined);
|
||||
}, []);
|
||||
|
||||
const isReady = config.hydrated;
|
||||
const isAuthenticated = Boolean(config.baseUrl.trim() && config.adminApiKey.trim());
|
||||
|
||||
return (
|
||||
<GestureHandlerRootView style={{ flex: 1 }}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
{!isReady ? (
|
||||
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: '#f4efe4' }}>
|
||||
<ActivityIndicator color="#1d5f55" />
|
||||
</View>
|
||||
) : (
|
||||
<Stack screenOptions={{ headerShown: false }}>
|
||||
{isAuthenticated ? <Stack.Screen name="(tabs)" /> : <Stack.Screen name="login" />}
|
||||
<Stack.Screen name="users/[id]" />
|
||||
<Stack.Screen name="accounts/[id]" options={{ presentation: 'card' }} />
|
||||
</Stack>
|
||||
)}
|
||||
</QueryClientProvider>
|
||||
</GestureHandlerRootView>
|
||||
);
|
||||
}
|
||||
123
app/accounts/[id].tsx
Normal file
123
app/accounts/[id].tsx
Normal file
@@ -0,0 +1,123 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { ChevronLeft, ShieldCheck, TestTubeDiagonal } from 'lucide-react-native';
|
||||
import { router, useLocalSearchParams } from 'expo-router';
|
||||
import { Pressable, Text, View } from 'react-native';
|
||||
|
||||
import { DetailRow } from '@/src/components/detail-row';
|
||||
import { LineTrendChart } from '@/src/components/line-trend-chart';
|
||||
import { ListCard } from '@/src/components/list-card';
|
||||
import { ScreenShell } from '@/src/components/screen-shell';
|
||||
import { getAccount, getAccountTodayStats, getDashboardTrend, refreshAccount, setAccountSchedulable, testAccount } 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 AccountDetailScreen() {
|
||||
const { id } = useLocalSearchParams<{ id: string }>();
|
||||
const accountId = Number(id);
|
||||
const queryClient = useQueryClient();
|
||||
const range = getDateRange();
|
||||
|
||||
const accountQuery = useQuery({
|
||||
queryKey: ['account', accountId],
|
||||
queryFn: () => getAccount(accountId),
|
||||
enabled: Number.isFinite(accountId),
|
||||
});
|
||||
|
||||
const todayStatsQuery = useQuery({
|
||||
queryKey: ['account-today-stats', accountId],
|
||||
queryFn: () => getAccountTodayStats(accountId),
|
||||
enabled: Number.isFinite(accountId),
|
||||
});
|
||||
|
||||
const trendQuery = useQuery({
|
||||
queryKey: ['account-trend', accountId, range.start_date, range.end_date],
|
||||
queryFn: () => getDashboardTrend({ ...range, granularity: 'day', account_id: accountId }),
|
||||
enabled: Number.isFinite(accountId),
|
||||
});
|
||||
|
||||
const refreshMutation = useMutation({
|
||||
mutationFn: () => refreshAccount(accountId),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['account', accountId] }),
|
||||
});
|
||||
|
||||
const schedulableMutation = useMutation({
|
||||
mutationFn: (schedulable: boolean) => setAccountSchedulable(accountId, schedulable),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['account', accountId] });
|
||||
queryClient.invalidateQueries({ queryKey: ['accounts'] });
|
||||
},
|
||||
});
|
||||
|
||||
const account = accountQuery.data;
|
||||
const todayStats = todayStatsQuery.data;
|
||||
const trendPoints = (trendQuery.data?.trend ?? []).map((item) => ({
|
||||
label: item.date.slice(5),
|
||||
value: item.total_tokens,
|
||||
}));
|
||||
|
||||
return (
|
||||
<ScreenShell
|
||||
title={account?.name || '账号详情'}
|
||||
subtitle="聚焦账号 token 用量、状态和几个最常用操作。"
|
||||
right={
|
||||
<Pressable className="h-11 w-11 items-center justify-center rounded-full bg-[#2d3134]" onPress={() => router.back()}>
|
||||
<ChevronLeft color="#f6f1e8" size={18} />
|
||||
</Pressable>
|
||||
}
|
||||
>
|
||||
<ListCard title="基本信息" meta={`${account?.platform || '--'} · ${account?.type || '--'}`} badge={account?.status || 'loading'}>
|
||||
<DetailRow label="可调度" value={account?.schedulable ? '是' : '否'} />
|
||||
<DetailRow label="优先级" value={`${account?.priority ?? 0}`} />
|
||||
<DetailRow label="并发" value={`${account?.concurrency ?? 0}`} />
|
||||
<DetailRow label="当前并发" value={`${account?.current_concurrency ?? 0}`} />
|
||||
<DetailRow label="最后使用" value={account?.last_used_at || '--'} />
|
||||
</ListCard>
|
||||
|
||||
<ListCard title="今日统计" meta="真实数据来自 /accounts/:id/today-stats" icon={ShieldCheck}>
|
||||
<DetailRow label="Token" value={`${todayStats?.tokens ?? 0}`} />
|
||||
<DetailRow label="请求数" value={`${todayStats?.requests ?? 0}`} />
|
||||
<DetailRow label="成本" value={`$${Number(todayStats?.cost ?? 0).toFixed(4)}`} />
|
||||
</ListCard>
|
||||
|
||||
{trendPoints.length > 1 ? (
|
||||
<LineTrendChart
|
||||
title="近 7 天 Token"
|
||||
subtitle="按账号过滤后的真实 token 趋势"
|
||||
points={trendPoints}
|
||||
color="#c96d43"
|
||||
formatValue={(value) => `${Math.round(value / 1000)}k`}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<ListCard title="快捷动作" meta="直接对单账号做测试、刷新和调度控制。" icon={TestTubeDiagonal}>
|
||||
<View className="flex-row gap-3">
|
||||
<Pressable className="flex-1 rounded-[18px] bg-[#1b1d1f] px-4 py-4" onPress={() => testAccount(accountId).catch(() => undefined)}>
|
||||
<Text className="text-center text-sm font-semibold text-[#f6f1e8]">测试账号</Text>
|
||||
</Pressable>
|
||||
<Pressable className="flex-1 rounded-[18px] bg-[#e7dfcf] px-4 py-4" onPress={() => refreshMutation.mutate()}>
|
||||
<Text className="text-center text-sm font-semibold text-[#4e463e]">{refreshMutation.isPending ? '刷新中...' : '刷新凭据'}</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
<Pressable
|
||||
className="mt-3 rounded-[18px] bg-[#1d5f55] px-4 py-4"
|
||||
onPress={() => schedulableMutation.mutate(!account?.schedulable)}
|
||||
>
|
||||
<Text className="text-center text-sm font-semibold text-white">
|
||||
{schedulableMutation.isPending ? '提交中...' : account?.schedulable ? '暂停调度' : '恢复调度'}
|
||||
</Text>
|
||||
</Pressable>
|
||||
</ListCard>
|
||||
</ScreenShell>
|
||||
);
|
||||
}
|
||||
84
app/login.tsx
Normal file
84
app/login.tsx
Normal file
@@ -0,0 +1,84 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { Globe, KeyRound } from 'lucide-react-native';
|
||||
import { Controller, useForm } from 'react-hook-form';
|
||||
import { Pressable, Text, TextInput, View } from 'react-native';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { ListCard } from '@/src/components/list-card';
|
||||
import { ScreenShell } from '@/src/components/screen-shell';
|
||||
import { adminConfigState, saveAdminConfig } from '@/src/store/admin-config';
|
||||
|
||||
const { useSnapshot } = require('valtio/react');
|
||||
|
||||
const schema = z.object({
|
||||
baseUrl: z.string().min(1, '请输入 Host'),
|
||||
adminApiKey: z.string().min(1, '请输入 Admin Token'),
|
||||
});
|
||||
|
||||
type FormValues = z.infer<typeof schema>;
|
||||
|
||||
export default function LoginScreen() {
|
||||
const config = useSnapshot(adminConfigState);
|
||||
const { control, handleSubmit, formState } = useForm<FormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: {
|
||||
baseUrl: config.baseUrl,
|
||||
adminApiKey: config.adminApiKey,
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<ScreenShell title="登录" subtitle="输入 host 和 adminToken 后开始管理。">
|
||||
<ListCard title="Host" meta="当前站点或管理代理地址" icon={Globe}>
|
||||
<Controller
|
||||
control={control}
|
||||
name="baseUrl"
|
||||
render={({ field: { onChange, value } }) => (
|
||||
<TextInput
|
||||
value={value}
|
||||
onChangeText={onChange}
|
||||
placeholder="http://localhost:8787"
|
||||
placeholderTextColor="#9b9081"
|
||||
autoCapitalize="none"
|
||||
className="rounded-[18px] bg-[#f1ece2] px-4 py-4 text-base text-[#16181a]"
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</ListCard>
|
||||
|
||||
<ListCard title="Admin Token" meta="管理员 token" icon={KeyRound}>
|
||||
<Controller
|
||||
control={control}
|
||||
name="adminApiKey"
|
||||
render={({ field: { onChange, value } }) => (
|
||||
<TextInput
|
||||
value={value}
|
||||
onChangeText={onChange}
|
||||
placeholder="admin-xxxxxxxx"
|
||||
placeholderTextColor="#9b9081"
|
||||
autoCapitalize="none"
|
||||
className="rounded-[18px] bg-[#f1ece2] px-4 py-4 text-base text-[#16181a]"
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</ListCard>
|
||||
|
||||
{(formState.errors.baseUrl || formState.errors.adminApiKey) ? (
|
||||
<View className="rounded-[20px] bg-[#fbf1eb] px-4 py-3">
|
||||
<Text className="text-sm text-[#c25d35]">{formState.errors.baseUrl?.message || formState.errors.adminApiKey?.message}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
<Pressable
|
||||
className="rounded-[20px] bg-[#1d5f55] px-4 py-4"
|
||||
onPress={handleSubmit(async (values) => {
|
||||
await saveAdminConfig(values);
|
||||
})}
|
||||
>
|
||||
<Text className="text-center text-sm font-semibold tracking-[1.2px] text-white">
|
||||
{config.saving ? '登录中...' : '进入管理台'}
|
||||
</Text>
|
||||
</Pressable>
|
||||
</ScreenShell>
|
||||
);
|
||||
}
|
||||
240
app/users/[id].tsx
Normal file
240
app/users/[id].tsx
Normal file
@@ -0,0 +1,240 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import * as Clipboard from 'expo-clipboard';
|
||||
import { ArrowLeftRight, ChevronLeft, Copy, Eye, EyeOff, KeyRound, Search, Wallet } from 'lucide-react-native';
|
||||
import { router, useLocalSearchParams } from 'expo-router';
|
||||
import { useState } from 'react';
|
||||
import { Controller, useForm } from 'react-hook-form';
|
||||
import { Pressable, Text, TextInput, View } from 'react-native';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { DetailRow } from '@/src/components/detail-row';
|
||||
import { ListCard } from '@/src/components/list-card';
|
||||
import { ScreenShell } from '@/src/components/screen-shell';
|
||||
import { getUser, getUserUsage, listUserApiKeys, updateUserBalance } from '@/src/services/admin';
|
||||
import type { BalanceOperation } from '@/src/types/admin';
|
||||
|
||||
const schema = z.object({
|
||||
amount: z.string().min(1, '请输入金额'),
|
||||
notes: z.string().optional(),
|
||||
});
|
||||
|
||||
type FormValues = z.infer<typeof schema>;
|
||||
|
||||
export default function UserDetailScreen() {
|
||||
const { id } = useLocalSearchParams<{ id: string }>();
|
||||
const userId = Number(id);
|
||||
const queryClient = useQueryClient();
|
||||
const [operation, setOperation] = useState<BalanceOperation>('add');
|
||||
const [keySearch, setKeySearch] = useState('');
|
||||
const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'inactive'>('all');
|
||||
const [visibleKeys, setVisibleKeys] = useState<Record<number, boolean>>({});
|
||||
const [copiedKeyId, setCopiedKeyId] = useState<number | null>(null);
|
||||
const { control, handleSubmit, reset, formState } = useForm<FormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: {
|
||||
amount: '10',
|
||||
notes: '',
|
||||
},
|
||||
});
|
||||
|
||||
const userQuery = useQuery({
|
||||
queryKey: ['user', userId],
|
||||
queryFn: () => getUser(userId),
|
||||
enabled: Number.isFinite(userId),
|
||||
});
|
||||
|
||||
const usageQuery = useQuery({
|
||||
queryKey: ['user-usage', userId],
|
||||
queryFn: () => getUserUsage(userId),
|
||||
enabled: Number.isFinite(userId),
|
||||
});
|
||||
|
||||
const apiKeysQuery = useQuery({
|
||||
queryKey: ['user-api-keys', userId],
|
||||
queryFn: () => listUserApiKeys(userId),
|
||||
enabled: Number.isFinite(userId),
|
||||
});
|
||||
|
||||
const balanceMutation = useMutation({
|
||||
mutationFn: (values: FormValues & { operation: BalanceOperation }) =>
|
||||
updateUserBalance(userId, {
|
||||
balance: Number(values.amount),
|
||||
operation: values.operation,
|
||||
notes: values.notes,
|
||||
}),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['user', userId] });
|
||||
queryClient.invalidateQueries({ queryKey: ['users'] });
|
||||
reset({ amount: '10', notes: '' });
|
||||
},
|
||||
});
|
||||
|
||||
const user = userQuery.data;
|
||||
const usage = usageQuery.data;
|
||||
const apiKeys = apiKeysQuery.data?.items ?? [];
|
||||
const filteredApiKeys = apiKeys.filter((item) => {
|
||||
const matchesStatus = statusFilter === 'all' ? true : item.status === statusFilter;
|
||||
const keyword = keySearch.trim().toLowerCase();
|
||||
const matchesSearch = !keyword
|
||||
? true
|
||||
: [item.name, item.key, item.group?.name]
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
.toLowerCase()
|
||||
.includes(keyword);
|
||||
|
||||
return matchesStatus && matchesSearch;
|
||||
});
|
||||
|
||||
function maskKey(value: string) {
|
||||
if (!value || value.length < 16) {
|
||||
return value;
|
||||
}
|
||||
|
||||
return `${value.slice(0, 8)}••••••${value.slice(-8)}`;
|
||||
}
|
||||
|
||||
async function copyKey(keyId: number, value: string) {
|
||||
await Clipboard.setStringAsync(value);
|
||||
setCopiedKeyId(keyId);
|
||||
setTimeout(() => setCopiedKeyId((current) => (current === keyId ? null : current)), 1600);
|
||||
}
|
||||
|
||||
return (
|
||||
<ScreenShell
|
||||
title={user?.username || user?.email || '用户详情'}
|
||||
subtitle="核心看余额和 token 用量,其他内容尽量保持轻量。"
|
||||
right={
|
||||
<Pressable className="h-11 w-11 items-center justify-center rounded-full bg-[#2d3134]" onPress={() => router.back()}>
|
||||
<ChevronLeft color="#f6f1e8" size={18} />
|
||||
</Pressable>
|
||||
}
|
||||
>
|
||||
<ListCard title="基本信息" meta={user?.email} badge={user?.status || 'loading'} icon={Wallet}>
|
||||
<DetailRow label="角色" value={user?.role || '--'} />
|
||||
<DetailRow label="余额" value={Number(user?.balance ?? 0).toFixed(2)} />
|
||||
<DetailRow label="并发" value={`${user?.concurrency ?? 0}`} />
|
||||
<DetailRow label="更新时间" value={user?.updated_at || '--'} />
|
||||
</ListCard>
|
||||
|
||||
<ListCard title="月度用量" meta="真实数据来自 /users/:id/usage" icon={ArrowLeftRight}>
|
||||
<DetailRow label="Token" value={`${Number(usage?.tokens ?? usage?.total_tokens ?? 0)}`} />
|
||||
<DetailRow label="请求数" value={`${Number(usage?.requests ?? usage?.total_requests ?? 0)}`} />
|
||||
<DetailRow label="成本" value={`$${Number(usage?.cost ?? usage?.total_cost ?? 0).toFixed(4)}`} />
|
||||
</ListCard>
|
||||
|
||||
<ListCard title="API 密钥" meta="直接聚合管理员 /users/:id/api-keys" icon={KeyRound}>
|
||||
<View className="gap-3">
|
||||
<View className="flex-row items-center rounded-[18px] bg-[#f1ece2] px-4 py-3">
|
||||
<Search color="#7d7468" size={16} />
|
||||
<TextInput
|
||||
value={keySearch}
|
||||
onChangeText={setKeySearch}
|
||||
placeholder="搜索 key 名称或分组"
|
||||
placeholderTextColor="#9b9081"
|
||||
className="ml-3 flex-1 text-sm text-[#16181a]"
|
||||
/>
|
||||
</View>
|
||||
<View className="flex-row gap-2">
|
||||
{(['all', 'active', 'inactive'] as const).map((item) => (
|
||||
<Pressable
|
||||
key={item}
|
||||
className={statusFilter === item ? 'flex-1 rounded-[16px] bg-[#1d5f55] px-3 py-3' : 'flex-1 rounded-[16px] bg-[#e7dfcf] px-3 py-3'}
|
||||
onPress={() => setStatusFilter(item)}
|
||||
>
|
||||
<Text className={statusFilter === item ? 'text-center text-sm font-semibold text-white' : 'text-center text-sm font-semibold text-[#4e463e]'}>
|
||||
{item === 'all' ? '全部' : item === 'active' ? '启用' : '停用'}
|
||||
</Text>
|
||||
</Pressable>
|
||||
))}
|
||||
</View>
|
||||
{filteredApiKeys.map((item) => (
|
||||
<View key={item.id} className="rounded-[18px] bg-[#f1ece2] px-4 py-3">
|
||||
<View className="flex-row items-center justify-between gap-3">
|
||||
<Text className="flex-1 text-sm font-semibold text-[#16181a]">{item.name}</Text>
|
||||
<Text className="text-xs uppercase tracking-[1.2px] text-[#7d7468]">{item.status}</Text>
|
||||
</View>
|
||||
<View className="mt-2 flex-row items-center gap-2">
|
||||
<Text className="flex-1 text-xs text-[#7d7468]">{visibleKeys[item.id] ? item.key : maskKey(item.key)}</Text>
|
||||
<Pressable
|
||||
className="rounded-full bg-[#e7dfcf] p-2"
|
||||
onPress={() => setVisibleKeys((current) => ({ ...current, [item.id]: !current[item.id] }))}
|
||||
>
|
||||
{visibleKeys[item.id] ? <EyeOff color="#4e463e" size={14} /> : <Eye color="#4e463e" size={14} />}
|
||||
</Pressable>
|
||||
<Pressable className="rounded-full bg-[#1b1d1f] p-2" onPress={() => copyKey(item.id, item.key)}>
|
||||
<Copy color="#f6f1e8" size={14} />
|
||||
</Pressable>
|
||||
</View>
|
||||
<Text className="mt-2 text-xs text-[#7d7468]">
|
||||
{copiedKeyId === item.id ? '已复制到剪贴板' : `最近使用 ${item.last_used_at || '--'}`}
|
||||
</Text>
|
||||
<Text className="mt-2 text-xs text-[#7d7468]">
|
||||
已用 ${Number(item.quota_used ?? 0).toFixed(2)} / 配额 {item.quota ? `$${Number(item.quota).toFixed(2)}` : '无限制'}
|
||||
</Text>
|
||||
<Text className="mt-1 text-xs text-[#7d7468]">
|
||||
分组 {item.group?.name || '未绑定'} · 5h 用量 {Number(item.usage_5h ?? 0).toFixed(2)}
|
||||
</Text>
|
||||
</View>
|
||||
))}
|
||||
{filteredApiKeys.length === 0 ? <Text className="text-sm text-[#7d7468]">当前筛选条件下没有 API 密钥。</Text> : null}
|
||||
</View>
|
||||
</ListCard>
|
||||
|
||||
<ListCard title="余额调整" meta="默认执行增加余额,可继续扩成减余额和设定值。" icon={Wallet}>
|
||||
<View className="gap-3">
|
||||
<Controller
|
||||
control={control}
|
||||
name="amount"
|
||||
render={({ field: { onChange, value } }) => (
|
||||
<TextInput
|
||||
value={value}
|
||||
onChangeText={onChange}
|
||||
keyboardType="decimal-pad"
|
||||
placeholder="输入金额"
|
||||
placeholderTextColor="#9b9081"
|
||||
className="rounded-[18px] bg-[#f1ece2] px-4 py-4 text-base text-[#16181a]"
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<View className="flex-row gap-2">
|
||||
{(['add', 'subtract', 'set'] as BalanceOperation[]).map((item) => (
|
||||
<Pressable
|
||||
key={item}
|
||||
className={operation === item ? 'flex-1 rounded-[16px] bg-[#1d5f55] px-3 py-3' : 'flex-1 rounded-[16px] bg-[#e7dfcf] px-3 py-3'}
|
||||
onPress={() => setOperation(item)}
|
||||
>
|
||||
<Text className={operation === item ? 'text-center text-sm font-semibold text-white' : 'text-center text-sm font-semibold text-[#4e463e]'}>
|
||||
{item === 'add' ? '增加' : item === 'subtract' ? '扣减' : '设为'}
|
||||
</Text>
|
||||
</Pressable>
|
||||
))}
|
||||
</View>
|
||||
<Controller
|
||||
control={control}
|
||||
name="notes"
|
||||
render={({ field: { onChange, value } }) => (
|
||||
<TextInput
|
||||
value={value}
|
||||
onChangeText={onChange}
|
||||
placeholder="备注,可留空"
|
||||
placeholderTextColor="#9b9081"
|
||||
className="rounded-[18px] bg-[#f1ece2] px-4 py-4 text-base text-[#16181a]"
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{formState.errors.amount ? <Text className="text-sm text-[#c25d35]">{formState.errors.amount.message}</Text> : null}
|
||||
<Pressable
|
||||
className="rounded-[18px] bg-[#1d5f55] px-4 py-4"
|
||||
onPress={handleSubmit((values) => balanceMutation.mutate({ ...values, operation }))}
|
||||
>
|
||||
<Text className="text-center text-sm font-semibold tracking-[1.2px] text-white">
|
||||
{balanceMutation.isPending ? '提交中...' : operation === 'add' ? '增加余额' : operation === 'subtract' ? '扣减余额' : '设置余额'}
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</ListCard>
|
||||
</ScreenShell>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user