mirror of
https://gitee.com/wanwujie/sub2api-mobile
synced 2026-04-29 19:04:49 +08:00
feat: refine expo admin mobile flows
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { Tabs } from 'expo-router';
|
||||
import { Redirect, Tabs } from 'expo-router';
|
||||
import { ChartNoAxesCombined, Settings2, Users } from 'lucide-react-native';
|
||||
|
||||
import { adminConfigState } from '@/src/store/admin-config';
|
||||
@@ -9,6 +9,10 @@ export default function TabsLayout() {
|
||||
const config = useSnapshot(adminConfigState);
|
||||
const hasAccount = Boolean(config.baseUrl.trim());
|
||||
|
||||
if (!hasAccount) {
|
||||
return <Redirect href="/login" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<Tabs
|
||||
initialRouteName={hasAccount ? 'monitor' : 'settings'}
|
||||
@@ -53,7 +57,6 @@ export default function TabsLayout() {
|
||||
}}
|
||||
/>
|
||||
<Tabs.Screen name="groups" options={{ href: null }} />
|
||||
<Tabs.Screen name="keys" options={{ href: null }} />
|
||||
<Tabs.Screen name="accounts" options={{ href: null }} />
|
||||
</Tabs>
|
||||
);
|
||||
|
||||
@@ -2,12 +2,13 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { KeyRound, Search, ShieldCheck, ShieldOff } from 'lucide-react-native';
|
||||
import { router } from 'expo-router';
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { FlatList, Pressable, Text, TextInput, View } from 'react-native';
|
||||
import { FlatList, Pressable, RefreshControl, Text, TextInput, View } from 'react-native';
|
||||
|
||||
import { ListCard } from '@/src/components/list-card';
|
||||
import { ScreenShell } from '@/src/components/screen-shell';
|
||||
import { useDebouncedValue } from '@/src/hooks/use-debounced-value';
|
||||
import { getAccount, getAccountTodayStats, getDashboardTrend, listAccounts, setAccountSchedulable, testAccount } from '@/src/services/admin';
|
||||
import type { AdminAccount } from '@/src/types/admin';
|
||||
|
||||
function getDateRange() {
|
||||
const end = new Date();
|
||||
@@ -22,8 +23,20 @@ function getDateRange() {
|
||||
};
|
||||
}
|
||||
|
||||
function formatTime(value?: string | null) {
|
||||
if (!value) return '--';
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return '--';
|
||||
return `${date.getFullYear()}/${String(date.getMonth() + 1).padStart(2, '0')}/${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
function getAccountError(account: AdminAccount) {
|
||||
return Boolean(account.status === 'error' || account.error_message);
|
||||
}
|
||||
|
||||
export default function AccountsScreen() {
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const [filter, setFilter] = useState<'all' | 'schedulable' | 'paused' | 'error'>('all');
|
||||
const keyword = useDebouncedValue(searchText.trim(), 300);
|
||||
const queryClient = useQueryClient();
|
||||
const range = getDateRange();
|
||||
@@ -40,95 +53,161 @@ export default function AccountsScreen() {
|
||||
});
|
||||
|
||||
const items = accountsQuery.data?.items ?? [];
|
||||
const filteredItems = useMemo(() => {
|
||||
return items.filter((account) => {
|
||||
if (filter === 'schedulable') return account.schedulable !== false && !getAccountError(account);
|
||||
if (filter === 'paused') return account.schedulable === false && !getAccountError(account);
|
||||
if (filter === 'error') return getAccountError(account);
|
||||
return true;
|
||||
});
|
||||
}, [filter, items]);
|
||||
const errorMessage = accountsQuery.error instanceof Error ? accountsQuery.error.message : '';
|
||||
|
||||
const summary = useMemo(() => {
|
||||
const total = items.length;
|
||||
const errors = items.filter(getAccountError).length;
|
||||
const paused = items.filter((item) => item.schedulable === false && !getAccountError(item)).length;
|
||||
const active = items.filter((item) => item.schedulable !== false && !getAccountError(item)).length;
|
||||
return { total, active, paused, errors };
|
||||
}, [items]);
|
||||
|
||||
const listHeader = useMemo(
|
||||
() => (
|
||||
<View className="pb-4">
|
||||
<View className="flex-row items-center rounded-[24px] bg-[#fbf8f2] px-4 py-3">
|
||||
<Search color="#7d7468" size={18} />
|
||||
<TextInput
|
||||
defaultValue=""
|
||||
onChangeText={setSearchText}
|
||||
placeholder="搜索 key 名称"
|
||||
placeholderTextColor="#9b9081"
|
||||
className="ml-3 flex-1 text-base text-[#16181a]"
|
||||
/>
|
||||
<View className="rounded-[24px] bg-[#fbf8f2] p-3">
|
||||
<View className="flex-row items-center rounded-[18px] bg-[#f1ece2] px-4 py-3">
|
||||
<Search color="#7d7468" size={18} />
|
||||
<TextInput
|
||||
defaultValue=""
|
||||
onChangeText={setSearchText}
|
||||
placeholder="搜索账号名称 / 平台"
|
||||
placeholderTextColor="#9b9081"
|
||||
className="ml-3 flex-1 text-base text-[#16181a]"
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View className="mt-3 flex-row gap-2">
|
||||
{([
|
||||
['all', `全部 ${summary.total}`],
|
||||
['schedulable', `可调度 ${summary.active}`],
|
||||
['paused', `暂停 ${summary.paused}`],
|
||||
['error', `异常 ${summary.errors}`],
|
||||
] as const).map(([key, label]) => {
|
||||
const active = filter === key;
|
||||
return (
|
||||
<Pressable
|
||||
key={key}
|
||||
onPress={() => setFilter(key)}
|
||||
className={active ? 'rounded-full bg-[#1d5f55] px-3 py-2' : 'rounded-full bg-[#e7dfcf] px-3 py-2'}
|
||||
>
|
||||
<Text className={active ? 'text-xs font-semibold text-white' : 'text-xs font-semibold text-[#4e463e]'}>{label}</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
),
|
||||
[]
|
||||
[filter, summary.active, summary.errors, summary.paused, summary.total]
|
||||
);
|
||||
|
||||
const renderItem = useCallback(
|
||||
({ item: account }: { item: (typeof items)[number] }) => (
|
||||
<Pressable
|
||||
onPress={() => {
|
||||
void queryClient.prefetchQuery({ queryKey: ['account', account.id], queryFn: () => getAccount(account.id) });
|
||||
void queryClient.prefetchQuery({ queryKey: ['account-today-stats', account.id], queryFn: () => getAccountTodayStats(account.id) });
|
||||
void queryClient.prefetchQuery({
|
||||
queryKey: ['account-trend', account.id, range.start_date, range.end_date],
|
||||
queryFn: () => getDashboardTrend({ ...range, granularity: 'day', account_id: account.id }),
|
||||
});
|
||||
router.push(`/accounts/${account.id}`);
|
||||
}}
|
||||
>
|
||||
<ListCard
|
||||
title={account.name}
|
||||
meta={`${account.platform} · ${account.type} · 优先级 ${account.priority ?? 0}`}
|
||||
badge={account.status || 'unknown'}
|
||||
icon={KeyRound}
|
||||
({ item: account }: { item: (typeof filteredItems)[number] }) => {
|
||||
const isError = getAccountError(account);
|
||||
const statusText = isError ? '异常' : account.schedulable ? '可调度' : '暂停调度';
|
||||
const groupsText = account.groups?.map((group) => group.name).filter(Boolean).slice(0, 3).join(' · ');
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
onPress={() => {
|
||||
void queryClient.prefetchQuery({ queryKey: ['account', account.id], queryFn: () => getAccount(account.id) });
|
||||
void queryClient.prefetchQuery({ queryKey: ['account-today-stats', account.id], queryFn: () => getAccountTodayStats(account.id) });
|
||||
void queryClient.prefetchQuery({
|
||||
queryKey: ['account-trend', account.id, range.start_date, range.end_date],
|
||||
queryFn: () => getDashboardTrend({ ...range, granularity: 'day', account_id: account.id }),
|
||||
});
|
||||
router.push(`/accounts/${account.id}`);
|
||||
}}
|
||||
>
|
||||
<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>
|
||||
<ListCard
|
||||
title={account.name}
|
||||
meta={`${account.platform} · ${account.type} · 优先级 ${account.priority ?? 0}`}
|
||||
badge={account.status || 'unknown'}
|
||||
icon={KeyRound}
|
||||
>
|
||||
<View className="gap-3">
|
||||
<View className="flex-row items-center justify-between">
|
||||
<View className="flex-row items-center gap-2">
|
||||
{account.schedulable && !isError ? <ShieldCheck color="#7d7468" size={14} /> : <ShieldOff color="#7d7468" size={14} />}
|
||||
<Text className="text-sm text-[#7d7468]">{statusText}</Text>
|
||||
</View>
|
||||
<Text className="text-xs text-[#7d7468]">最近使用 {formatTime(account.last_used_at || account.updated_at)}</Text>
|
||||
</View>
|
||||
|
||||
<View className="flex-row gap-2">
|
||||
<View className="flex-1 rounded-[14px] bg-[#f1ece2] px-3 py-3">
|
||||
<Text className="text-[11px] text-[#7d7468]">并发</Text>
|
||||
<Text className="mt-1 text-sm font-bold text-[#16181a]">{account.current_concurrency ?? 0} / {account.concurrency ?? 0}</Text>
|
||||
</View>
|
||||
<View className="flex-1 rounded-[14px] bg-[#f1ece2] px-3 py-3">
|
||||
<Text className="text-[11px] text-[#7d7468]">倍率</Text>
|
||||
<Text className="mt-1 text-sm font-bold text-[#16181a]">{(account.rate_multiplier ?? 1).toFixed(2)}x</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{groupsText ? <Text className="text-xs text-[#7d7468]">分组 {groupsText}</Text> : null}
|
||||
{account.error_message ? <Text className="text-xs text-[#a4512b]">异常信息:{account.error_message}</Text> : null}
|
||||
|
||||
<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]">{account.schedulable ? '暂停' : '恢复'}</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</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>
|
||||
),
|
||||
[queryClient, range.end_date, range.start_date, toggleMutation]
|
||||
</ListCard>
|
||||
</Pressable>
|
||||
);
|
||||
},
|
||||
[filteredItems, queryClient, range.end_date, range.start_date, toggleMutation]
|
||||
);
|
||||
|
||||
const emptyState = useMemo(
|
||||
() => <ListCard title="暂无 Key" meta={errorMessage || '连上后这里会展示 key 列表。'} icon={KeyRound} />,
|
||||
() => <ListCard title="暂无账号" meta={errorMessage || '连上后这里会展示账号列表。'} icon={KeyRound} />,
|
||||
[errorMessage]
|
||||
);
|
||||
|
||||
return (
|
||||
<ScreenShell
|
||||
title="API 密钥"
|
||||
subtitle=""
|
||||
titleAside={<Text className="text-[11px] text-[#a2988a]">查看密钥状态与调度能力。</Text>}
|
||||
title="账号管理"
|
||||
subtitle="看单账号状态、并发、最近使用和异常信息。"
|
||||
titleAside={<Text className="text-[11px] text-[#a2988a]">更接近网页后台的账号视图。</Text>}
|
||||
variant="minimal"
|
||||
scroll={false}
|
||||
>
|
||||
<FlatList
|
||||
data={items}
|
||||
data={filteredItems}
|
||||
renderItem={renderItem}
|
||||
keyExtractor={(item) => `${item.id}`}
|
||||
showsVerticalScrollIndicator={false}
|
||||
refreshControl={<RefreshControl refreshing={accountsQuery.isRefetching} onRefresh={() => void accountsQuery.refetch()} tintColor="#1d5f55" />}
|
||||
ListHeaderComponent={listHeader}
|
||||
ListEmptyComponent={emptyState}
|
||||
ItemSeparatorComponent={() => <View className="h-4" />}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { FolderKanban, Layers3, Search } from 'lucide-react-native';
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { FlatList, Text, TextInput, View } from 'react-native';
|
||||
import { FlatList, RefreshControl, Text, TextInput, View } from 'react-native';
|
||||
|
||||
import { ListCard } from '@/src/components/list-card';
|
||||
import { ScreenShell } from '@/src/components/screen-shell';
|
||||
@@ -72,6 +72,7 @@ export default function GroupsScreen() {
|
||||
renderItem={renderItem}
|
||||
keyExtractor={(item) => `${item.id}`}
|
||||
showsVerticalScrollIndicator={false}
|
||||
refreshControl={<RefreshControl refreshing={groupsQuery.isRefetching} onRefresh={() => void groupsQuery.refetch()} tintColor="#1d5f55" />}
|
||||
ListHeaderComponent={listHeader}
|
||||
ListEmptyComponent={emptyState}
|
||||
ItemSeparatorComponent={() => <View className="h-4" />}
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
import { Redirect } from 'expo-router';
|
||||
|
||||
import { adminConfigState } from '@/src/store/admin-config';
|
||||
|
||||
const { useSnapshot } = require('valtio/react');
|
||||
|
||||
export default function IndexScreen() {
|
||||
return <Redirect href="/monitor" />;
|
||||
const config = useSnapshot(adminConfigState);
|
||||
const hasAccount = Boolean(config.baseUrl.trim());
|
||||
|
||||
return <Redirect href={hasAccount ? '/monitor' : '/login'} />;
|
||||
}
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { AlertTriangle, Coins, Gauge, RefreshCw, Rows3, Wrench, Zap } from 'lucide-react-native';
|
||||
import { router } from 'expo-router';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Platform, Pressable, Text, View, useWindowDimensions } from 'react-native';
|
||||
import { Pressable, RefreshControl, ScrollView, Text, View } from 'react-native';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
|
||||
import { BarChartCard } from '@/src/components/bar-chart-card';
|
||||
import { formatTokenValue } from '@/src/lib/formatters';
|
||||
import { DonutChartCard } from '@/src/components/donut-chart-card';
|
||||
import { LineTrendChart } from '@/src/components/line-trend-chart';
|
||||
import { ListCard } from '@/src/components/list-card';
|
||||
import { ScreenShell } from '@/src/components/screen-shell';
|
||||
import { useScreenInteractive } from '@/src/hooks/use-screen-interactive';
|
||||
import { formatTokenValue } from '@/src/lib/formatters';
|
||||
import { getAdminSettings, getDashboardModels, getDashboardStats, getDashboardTrend, listAccounts } from '@/src/services/admin';
|
||||
import { adminConfigState } from '@/src/store/admin-config';
|
||||
|
||||
@@ -17,6 +15,32 @@ const { useSnapshot } = require('valtio/react');
|
||||
|
||||
type RangeKey = '24h' | '7d' | '30d';
|
||||
|
||||
const colors = {
|
||||
page: '#f4efe4',
|
||||
card: '#fbf8f2',
|
||||
mutedCard: '#f1ece2',
|
||||
primary: '#1d5f55',
|
||||
text: '#16181a',
|
||||
subtext: '#6f665c',
|
||||
border: '#e7dfcf',
|
||||
dangerBg: '#fbf1eb',
|
||||
danger: '#c25d35',
|
||||
successBg: '#e6f4ee',
|
||||
success: '#1d5f55',
|
||||
};
|
||||
|
||||
const RANGE_OPTIONS: Array<{ key: RangeKey; label: string }> = [
|
||||
{ key: '24h', label: '24H' },
|
||||
{ key: '7d', label: '7D' },
|
||||
{ key: '30d', label: '30D' },
|
||||
];
|
||||
|
||||
const RANGE_TITLE_MAP: Record<RangeKey, string> = {
|
||||
'24h': '24H',
|
||||
'7d': '7D',
|
||||
'30d': '30D',
|
||||
};
|
||||
|
||||
function getDateRange(rangeKey: RangeKey) {
|
||||
const end = new Date();
|
||||
const start = new Date();
|
||||
@@ -38,11 +62,27 @@ function getDateRange(rangeKey: RangeKey) {
|
||||
};
|
||||
}
|
||||
|
||||
const RANGE_OPTIONS: Array<{ key: RangeKey; label: string }> = [
|
||||
{ key: '24h', label: '24H' },
|
||||
{ key: '7d', label: '7D' },
|
||||
{ key: '30d', label: '30D' },
|
||||
];
|
||||
function formatNumber(value?: number) {
|
||||
if (typeof value !== 'number' || Number.isNaN(value)) return '--';
|
||||
return new Intl.NumberFormat('en-US').format(value);
|
||||
}
|
||||
|
||||
function formatMoney(value?: number) {
|
||||
if (typeof value !== 'number' || Number.isNaN(value)) return '--';
|
||||
return `$${value.toFixed(2)}`;
|
||||
}
|
||||
|
||||
function formatCompactNumber(value?: number) {
|
||||
if (typeof value !== 'number' || Number.isNaN(value)) return '--';
|
||||
if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`;
|
||||
if (value >= 1_000) return `${(value / 1_000).toFixed(1)}K`;
|
||||
return String(value);
|
||||
}
|
||||
|
||||
function formatTokenDisplay(value?: number) {
|
||||
if (typeof value !== 'number' || Number.isNaN(value)) return '--';
|
||||
return formatTokenValue(value);
|
||||
}
|
||||
|
||||
function getPointLabel(value: string, rangeKey: RangeKey) {
|
||||
if (rangeKey === '24h') {
|
||||
@@ -52,49 +92,97 @@ function getPointLabel(value: string, rangeKey: RangeKey) {
|
||||
return value.slice(5, 10);
|
||||
}
|
||||
|
||||
function getErrorMessage(error: unknown) {
|
||||
if (error instanceof Error && error.message) {
|
||||
switch (error.message) {
|
||||
case 'BASE_URL_REQUIRED':
|
||||
return '请先去服务器页填写服务地址。';
|
||||
case 'ADMIN_API_KEY_REQUIRED':
|
||||
return '请先去服务器页填写 Admin Token。';
|
||||
case 'INVALID_SERVER_RESPONSE':
|
||||
return '当前服务返回的数据格式不正确,请确认它是可用的 Sub2API 管理接口。';
|
||||
default:
|
||||
return error.message;
|
||||
}
|
||||
}
|
||||
|
||||
return '当前无法加载概览数据,请检查服务地址、Token 和网络。';
|
||||
}
|
||||
|
||||
function Section({ title, subtitle, children, right }: { title: string; subtitle?: string; children: React.ReactNode; right?: React.ReactNode }) {
|
||||
return (
|
||||
<View style={{ backgroundColor: colors.card, borderRadius: 18, padding: 16 }}>
|
||||
<View style={{ flexDirection: 'row', justifyContent: 'space-between', gap: 12 }}>
|
||||
<View style={{ flex: 1 }}>
|
||||
<Text style={{ fontSize: 18, fontWeight: '700', color: colors.text }}>{title}</Text>
|
||||
{subtitle ? <Text style={{ marginTop: 6, fontSize: 12, color: colors.subtext }}>{subtitle}</Text> : null}
|
||||
</View>
|
||||
{right}
|
||||
</View>
|
||||
<View style={{ marginTop: 14 }}>{children}</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function StatCard({ title, value, detail }: { title: string; value: string; detail?: string }) {
|
||||
return (
|
||||
<View style={{ flex: 1, backgroundColor: colors.card, borderRadius: 16, padding: 14 }}>
|
||||
<Text style={{ fontSize: 12, color: '#8a8072' }}>{title}</Text>
|
||||
<Text style={{ marginTop: 8, fontSize: 24, fontWeight: '700', color: colors.text }}>{value}</Text>
|
||||
{detail ? <Text style={{ marginTop: 6, fontSize: 12, color: colors.subtext }}>{detail}</Text> : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export default function MonitorScreen() {
|
||||
useScreenInteractive('monitor_interactive');
|
||||
const config = useSnapshot(adminConfigState);
|
||||
const { width } = useWindowDimensions();
|
||||
const contentWidth = Math.max(width - 24, 280);
|
||||
const hasAccount = Boolean(config.baseUrl.trim());
|
||||
const [rangeKey, setRangeKey] = useState<RangeKey>('7d');
|
||||
const range = useMemo(() => getDateRange(rangeKey), [rangeKey]);
|
||||
const hasAccount = Boolean(config.baseUrl.trim());
|
||||
|
||||
const statsQuery = useQuery({
|
||||
queryKey: ['monitor-stats'],
|
||||
queryFn: getDashboardStats,
|
||||
enabled: hasAccount,
|
||||
});
|
||||
|
||||
const statsQuery = useQuery({ queryKey: ['monitor-stats'], queryFn: getDashboardStats, enabled: hasAccount });
|
||||
const settingsQuery = useQuery({ queryKey: ['admin-settings'], queryFn: getAdminSettings, enabled: hasAccount });
|
||||
const accountsQuery = useQuery({ queryKey: ['monitor-accounts'], queryFn: () => listAccounts(''), enabled: hasAccount });
|
||||
const trendQuery = useQuery({
|
||||
queryKey: ['monitor-trend', rangeKey, range.start_date, range.end_date, range.granularity],
|
||||
queryFn: () => getDashboardTrend(range),
|
||||
enabled: hasAccount,
|
||||
});
|
||||
|
||||
const modelsQuery = useQuery({
|
||||
queryKey: ['monitor-models', rangeKey, range.start_date, range.end_date],
|
||||
queryFn: () => getDashboardModels(range),
|
||||
enabled: hasAccount,
|
||||
});
|
||||
|
||||
const settingsQuery = useQuery({
|
||||
queryKey: ['admin-settings'],
|
||||
queryFn: getAdminSettings,
|
||||
enabled: hasAccount,
|
||||
});
|
||||
|
||||
const accountsQuery = useQuery({
|
||||
queryKey: ['monitor-accounts'],
|
||||
queryFn: () => listAccounts(''),
|
||||
enabled: hasAccount,
|
||||
});
|
||||
function refetchAll() {
|
||||
statsQuery.refetch();
|
||||
settingsQuery.refetch();
|
||||
accountsQuery.refetch();
|
||||
trendQuery.refetch();
|
||||
modelsQuery.refetch();
|
||||
}
|
||||
|
||||
const stats = statsQuery.data;
|
||||
const trend = trendQuery.data?.trend ?? [];
|
||||
const accounts = accountsQuery.data?.items ?? [];
|
||||
const siteName = settingsQuery.data?.site_name?.trim() || '管理控制台';
|
||||
const accounts = accountsQuery.data?.items ?? [];
|
||||
const trend = trendQuery.data?.trend ?? [];
|
||||
const topModels = (modelsQuery.data?.models ?? []).slice(0, 5);
|
||||
const errorMessage = getErrorMessage(statsQuery.error ?? settingsQuery.error ?? accountsQuery.error ?? trendQuery.error ?? modelsQuery.error);
|
||||
const currentPageErrorAccounts = accounts.filter((item) => item.status === 'error' || item.error_message).length;
|
||||
const currentPagePausedAccounts = accounts.filter((item) => item.schedulable === false && item.status !== 'error' && !item.error_message).length;
|
||||
const currentPageBusyAccounts = accounts.filter((item) => (item.current_concurrency ?? 0) > 0 && item.status !== 'error' && !item.error_message).length;
|
||||
const totalAccounts = stats?.total_accounts ?? accountsQuery.data?.total ?? accounts.length;
|
||||
const aggregatedErrorAccounts = stats?.error_accounts ?? 0;
|
||||
const errorAccounts = Math.max(aggregatedErrorAccounts, currentPageErrorAccounts);
|
||||
const healthyAccounts = stats?.normal_accounts ?? Math.max(totalAccounts - errorAccounts, 0);
|
||||
const latestTrendPoints = trend.slice(-6).reverse();
|
||||
const selectedTokenTotal = trend.reduce((sum, item) => sum + item.total_tokens, 0);
|
||||
const selectedCostTotal = trend.reduce((sum, item) => sum + item.cost, 0);
|
||||
const selectedOutputTotal = trend.reduce((sum, item) => sum + item.output_tokens, 0);
|
||||
const rangeTitle = RANGE_TITLE_MAP[rangeKey];
|
||||
const isLoading = statsQuery.isLoading || settingsQuery.isLoading || accountsQuery.isLoading;
|
||||
const hasError = Boolean(statsQuery.error || settingsQuery.error || accountsQuery.error || trendQuery.error || modelsQuery.error);
|
||||
|
||||
const throughputPoints = useMemo(
|
||||
() => trend.map((item) => ({ label: getPointLabel(item.date, rangeKey), value: item.total_tokens })),
|
||||
[rangeKey, trend]
|
||||
@@ -107,281 +195,196 @@ export default function MonitorScreen() {
|
||||
() => trend.map((item) => ({ label: getPointLabel(item.date, rangeKey), value: item.cost })),
|
||||
[rangeKey, trend]
|
||||
);
|
||||
const topModels = useMemo(() => (modelsQuery.data?.models ?? []).slice(0, 5), [modelsQuery.data?.models]);
|
||||
const incidentAccounts = useMemo(
|
||||
() => accounts.filter((item) => item.status === 'error' || item.error_message).slice(0, 5),
|
||||
[accounts]
|
||||
);
|
||||
const totalInputTokens = useMemo(() => trend.reduce((sum, item) => sum + item.input_tokens, 0), [trend]);
|
||||
const totalOutputTokens = useMemo(() => trend.reduce((sum, item) => sum + item.output_tokens, 0), [trend]);
|
||||
const totalCacheReadTokens = useMemo(() => trend.reduce((sum, item) => sum + item.cache_read_tokens, 0), [trend]);
|
||||
const busyAccounts = useMemo(
|
||||
() => accounts.filter((item) => (item.current_concurrency ?? 0) > 0 && item.status !== 'error' && !item.error_message).length,
|
||||
[accounts]
|
||||
);
|
||||
const pausedAccounts = useMemo(
|
||||
() => accounts.filter((item) => item.schedulable === false && item.status !== 'error' && !item.error_message).length,
|
||||
[accounts]
|
||||
);
|
||||
const errorAccounts = useMemo(
|
||||
() => accounts.filter((item) => item.status === 'error' || item.error_message).length,
|
||||
[accounts]
|
||||
);
|
||||
const healthyAccounts = Math.max(accounts.length - busyAccounts - pausedAccounts - errorAccounts, 0);
|
||||
const summaryCards = [
|
||||
{
|
||||
label: 'Token',
|
||||
value: stats ? formatTokenValue(stats.today_tokens ?? 0) : '--',
|
||||
icon: Zap,
|
||||
tone: 'dark' as const,
|
||||
},
|
||||
{
|
||||
label: '成本',
|
||||
value: stats ? `$${Number(stats.today_cost ?? 0).toFixed(2)}` : '--',
|
||||
icon: Coins,
|
||||
},
|
||||
{
|
||||
label: '输出',
|
||||
value: stats ? formatTokenValue(stats.today_output_tokens ?? 0) : '--',
|
||||
icon: Rows3,
|
||||
},
|
||||
{
|
||||
label: '账号',
|
||||
value: String(accounts.length || stats?.total_accounts || 0),
|
||||
detail: `${errorAccounts} 异常 / ${pausedAccounts} 暂停`,
|
||||
icon: Rows3,
|
||||
},
|
||||
{
|
||||
label: 'TPM',
|
||||
value: String(stats?.tpm ?? '--'),
|
||||
icon: Gauge,
|
||||
},
|
||||
{
|
||||
label: '健康',
|
||||
value: String(healthyAccounts),
|
||||
detail: `${busyAccounts} 繁忙`,
|
||||
icon: AlertTriangle,
|
||||
},
|
||||
];
|
||||
const summaryRows = [0, 3].map((index) => summaryCards.slice(index, index + 3));
|
||||
const useMasonry = Platform.OS === 'web' || width >= 640;
|
||||
const summaryCardWidth = Math.floor((contentWidth - 16) / 3);
|
||||
|
||||
const cards = [
|
||||
{
|
||||
key: 'throughput',
|
||||
node: throughputPoints.length > 1 ? (
|
||||
<LineTrendChart
|
||||
title="Token 吞吐"
|
||||
subtitle="整体负载曲线"
|
||||
points={throughputPoints}
|
||||
color="#a34d2d"
|
||||
formatValue={formatTokenValue}
|
||||
compact={useMasonry}
|
||||
/>
|
||||
) : null,
|
||||
},
|
||||
{
|
||||
key: 'requests',
|
||||
node: requestPoints.length > 1 ? (
|
||||
<LineTrendChart
|
||||
title="请求趋势"
|
||||
subtitle="调用波峰变化"
|
||||
points={requestPoints}
|
||||
color="#1d5f55"
|
||||
compact={useMasonry}
|
||||
/>
|
||||
) : null,
|
||||
},
|
||||
{
|
||||
key: 'cost',
|
||||
node: costPoints.length > 1 ? (
|
||||
<LineTrendChart
|
||||
title="成本趋势"
|
||||
subtitle="花费变化"
|
||||
points={costPoints}
|
||||
color="#7651c8"
|
||||
formatValue={(value) => `$${value.toFixed(2)}`}
|
||||
compact={useMasonry}
|
||||
/>
|
||||
) : null,
|
||||
},
|
||||
{
|
||||
key: 'token-structure',
|
||||
node: (
|
||||
<BarChartCard
|
||||
title="Token 结构"
|
||||
subtitle="输入、输出、缓存读占比"
|
||||
items={[
|
||||
{
|
||||
label: '输入 Token',
|
||||
value: totalInputTokens,
|
||||
color: '#1d5f55',
|
||||
hint: '输入 Token 指请求进入模型前消耗的 token,通常由提示词、上下文和历史消息组成。',
|
||||
},
|
||||
{
|
||||
label: '输出 Token',
|
||||
value: totalOutputTokens,
|
||||
color: '#d38b36',
|
||||
hint: '输出 Token 指模型返回内容消耗的 token,越长通常代表生成内容越多、成本越高。',
|
||||
},
|
||||
{
|
||||
label: '缓存读取 Token',
|
||||
value: totalCacheReadTokens,
|
||||
color: '#7d7468',
|
||||
hint: '缓存读取 Token 表示命中缓存后复用的 token,数值越高通常意味着缓存策略更有效。',
|
||||
},
|
||||
]}
|
||||
formatValue={formatTokenValue}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'health',
|
||||
node: (
|
||||
<DonutChartCard
|
||||
title="账号健康"
|
||||
subtitle="健康、繁忙、暂停、异常"
|
||||
centerLabel="总账号"
|
||||
centerValue={String(accounts.length || stats?.total_accounts || 0)}
|
||||
segments={[
|
||||
{ label: '健康', value: healthyAccounts, color: '#1d5f55' },
|
||||
{ label: '繁忙', value: busyAccounts, color: '#d38b36' },
|
||||
{ label: '暂停', value: pausedAccounts, color: '#7d7468' },
|
||||
{ label: '异常', value: errorAccounts, color: '#a34d2d' },
|
||||
]}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'models',
|
||||
node: (
|
||||
<BarChartCard
|
||||
title="热点模型"
|
||||
subtitle="模型负载分布"
|
||||
items={topModels.map((item) => ({
|
||||
label: item.model,
|
||||
value: item.total_tokens,
|
||||
color: '#a34d2d',
|
||||
meta: `请求 ${item.requests} · 成本 $${Number(item.cost).toFixed(2)}`,
|
||||
}))}
|
||||
formatValue={formatTokenValue}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'incidents',
|
||||
node: (
|
||||
<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>
|
||||
),
|
||||
},
|
||||
].filter((item) => item.node);
|
||||
|
||||
const leftColumn = cards.filter((_, index) => index % 2 === 0);
|
||||
const rightColumn = cards.filter((_, index) => index % 2 === 1);
|
||||
const isRefreshing = statsQuery.isRefetching || settingsQuery.isRefetching || accountsQuery.isRefetching || trendQuery.isRefetching || modelsQuery.isRefetching;
|
||||
|
||||
return (
|
||||
<ScreenShell
|
||||
title="概览"
|
||||
subtitle=""
|
||||
titleAside={<Text className="text-[11px] text-[#a2988a]">{siteName} 的关键运行指标。</Text>}
|
||||
variant="minimal"
|
||||
horizontalInsetClassName="px-3"
|
||||
contentGapClassName="mt-3 gap-2"
|
||||
right={
|
||||
<View className="flex-row items-center gap-2">
|
||||
<View className="flex-row items-center rounded-full bg-[#ece3d6] p-1">
|
||||
{RANGE_OPTIONS.map((item) => {
|
||||
const active = item.key === rangeKey;
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
key={item.key}
|
||||
className={active ? 'rounded-full bg-[#1d5f55] px-3 py-1.5' : 'rounded-full bg-transparent px-3 py-1.5'}
|
||||
onPress={() => setRangeKey(item.key)}
|
||||
>
|
||||
<Text className={active ? 'text-[10px] font-semibold uppercase leading-4 tracking-[1px] text-white' : 'text-[10px] font-semibold uppercase leading-4 tracking-[1px] text-[#7d7468]'}>
|
||||
{item.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
<SafeAreaView style={{ flex: 1, backgroundColor: colors.page }}>
|
||||
<ScrollView
|
||||
style={{ flex: 1 }}
|
||||
contentContainerStyle={{ paddingHorizontal: 16, paddingTop: 16, paddingBottom: 110 }}
|
||||
showsVerticalScrollIndicator={false}
|
||||
refreshControl={<RefreshControl refreshing={isRefreshing} onRefresh={() => void refetchAll()} tintColor="#1d5f55" />}
|
||||
>
|
||||
<View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12, marginBottom: 16 }}>
|
||||
<View style={{ flex: 1 }}>
|
||||
<Text style={{ fontSize: 28, fontWeight: '700', color: colors.text }}>概览</Text>
|
||||
<Text style={{ marginTop: 6, fontSize: 13, color: '#8a8072' }}>{siteName} 的当前运行状态。</Text>
|
||||
</View>
|
||||
<View style={{ alignItems: 'flex-end' }}>
|
||||
<View style={{ flexDirection: 'row', gap: 8 }}>
|
||||
{RANGE_OPTIONS.map((option) => {
|
||||
const active = option.key === rangeKey;
|
||||
return (
|
||||
<Pressable
|
||||
key={option.key}
|
||||
style={{ backgroundColor: active ? colors.primary : colors.border, borderRadius: 999, paddingHorizontal: 12, paddingVertical: 8 }}
|
||||
onPress={() => setRangeKey(option.key)}
|
||||
>
|
||||
<Text style={{ color: active ? '#fff' : '#4e463e', fontSize: 12, fontWeight: '700' }}>{option.label}</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
<Text style={{ marginTop: 8, fontSize: 12, color: colors.subtext }}>{range.start_date} 到 {range.end_date}</Text>
|
||||
</View>
|
||||
<Pressable
|
||||
className="h-10 w-10 items-center justify-center rounded-full bg-[#2d3134]"
|
||||
onPress={() => {
|
||||
statsQuery.refetch();
|
||||
trendQuery.refetch();
|
||||
modelsQuery.refetch();
|
||||
accountsQuery.refetch();
|
||||
settingsQuery.refetch();
|
||||
}}
|
||||
>
|
||||
<RefreshCw color="#f6f1e8" size={16} />
|
||||
</Pressable>
|
||||
</View>
|
||||
}
|
||||
>
|
||||
<View className="gap-2">
|
||||
{summaryRows.map((row, rowIndex) => (
|
||||
<View key={`summary-row-${rowIndex}`} className="flex-row gap-2">
|
||||
{row.map((item) => {
|
||||
const Icon = item.icon;
|
||||
|
||||
return (
|
||||
<View
|
||||
key={item.label}
|
||||
className={item.tone === 'dark' ? 'rounded-[18px] bg-[#1d5f55] px-2.5 py-2.5' : 'rounded-[18px] bg-[#fbf8f2] px-2.5 py-2.5'}
|
||||
style={{ width: summaryCardWidth }}
|
||||
>
|
||||
<View className="flex-row items-center justify-between gap-2">
|
||||
<Text className={item.tone === 'dark' ? 'text-[10px] uppercase tracking-[1.1px] text-[#d8efe7]' : 'text-[10px] uppercase tracking-[1.1px] text-[#8a8072]'}>
|
||||
{item.label}
|
||||
</Text>
|
||||
<Icon color={item.tone === 'dark' ? '#d8efe7' : '#7d7468'} size={13} />
|
||||
</View>
|
||||
<Text className={item.tone === 'dark' ? 'mt-2 text-[17px] font-bold text-white' : 'mt-2 text-[17px] font-bold text-[#16181a]'}>
|
||||
{item.value}
|
||||
</Text>
|
||||
{'detail' in item && item.detail ? (
|
||||
<Text numberOfLines={1} className={item.tone === 'dark' ? 'mt-1 text-[10px] text-[#d8efe7]' : 'mt-1 text-[10px] text-[#8a8072]'}>
|
||||
{item.detail}
|
||||
</Text>
|
||||
) : null}
|
||||
{!hasAccount ? (
|
||||
<Section title="未连接服务器" subtitle="需要先配置连接">
|
||||
<Text style={{ fontSize: 14, lineHeight: 22, color: colors.subtext }}>请先前往“服务器”页填写服务地址和 Admin Token,再返回查看概览数据。</Text>
|
||||
<Pressable style={{ marginTop: 14, alignSelf: 'flex-start', backgroundColor: colors.primary, borderRadius: 14, paddingHorizontal: 16, paddingVertical: 12 }} onPress={() => router.push('/settings')}>
|
||||
<Text style={{ color: '#fff', fontSize: 13, fontWeight: '700' }}>去配置服务器</Text>
|
||||
</Pressable>
|
||||
</Section>
|
||||
) : isLoading ? (
|
||||
<Section title="正在加载概览" subtitle="请稍候">
|
||||
<Text style={{ fontSize: 14, lineHeight: 22, color: colors.subtext }}>已连接服务器,正在拉取概览、模型和账号状态数据。</Text>
|
||||
</Section>
|
||||
) : hasError ? (
|
||||
<Section title="加载失败" subtitle="请检查连接配置">
|
||||
<View style={{ borderRadius: 14, backgroundColor: colors.dangerBg, paddingHorizontal: 14, paddingVertical: 12 }}>
|
||||
<Text style={{ color: colors.danger, fontSize: 14, lineHeight: 20 }}>{errorMessage}</Text>
|
||||
</View>
|
||||
<View style={{ flexDirection: 'row', gap: 12, marginTop: 14 }}>
|
||||
<Pressable style={{ flex: 1, backgroundColor: colors.primary, borderRadius: 14, paddingVertical: 12, alignItems: 'center' }} onPress={refetchAll}>
|
||||
<Text style={{ color: '#fff', fontSize: 13, fontWeight: '700' }}>重试</Text>
|
||||
</Pressable>
|
||||
<Pressable style={{ flex: 1, backgroundColor: colors.border, borderRadius: 14, paddingVertical: 12, alignItems: 'center' }} onPress={() => router.push('/settings')}>
|
||||
<Text style={{ color: '#4e463e', fontSize: 13, fontWeight: '700' }}>检查服务器</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</Section>
|
||||
) : (
|
||||
<View style={{ gap: 12 }}>
|
||||
<View style={{ flexDirection: 'row', gap: 12 }}>
|
||||
<StatCard
|
||||
title={`${rangeTitle} Token`}
|
||||
value={formatTokenDisplay(rangeKey === '24h' ? selectedTokenTotal || stats?.today_tokens : selectedTokenTotal)}
|
||||
detail={`输出 ${formatTokenDisplay(rangeKey === '24h' ? selectedOutputTotal || stats?.today_output_tokens : selectedOutputTotal)}`}
|
||||
/>
|
||||
<StatCard
|
||||
title={`${rangeTitle} 成本`}
|
||||
value={formatMoney(rangeKey === '24h' ? selectedCostTotal || stats?.today_cost : selectedCostTotal)}
|
||||
detail={`TPM ${formatNumber(stats?.tpm)}`}
|
||||
/>
|
||||
</View>
|
||||
<Section title="账号概览" subtitle="总数、健康、异常和暂停状态一览">
|
||||
<View style={{ flexDirection: 'row', gap: 8 }}>
|
||||
<View style={{ flex: 1, backgroundColor: colors.mutedCard, borderRadius: 14, padding: 12 }}>
|
||||
<Text style={{ fontSize: 11, color: '#8a8072' }}>总数</Text>
|
||||
<Text style={{ marginTop: 6, fontSize: 18, fontWeight: '700', color: colors.text }}>{formatNumber(totalAccounts)}</Text>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
<View style={{ flex: 1, backgroundColor: colors.mutedCard, borderRadius: 14, padding: 12 }}>
|
||||
<Text style={{ fontSize: 11, color: '#8a8072' }}>健康</Text>
|
||||
<Text style={{ marginTop: 6, fontSize: 18, fontWeight: '700', color: colors.text }}>{formatNumber(healthyAccounts)}</Text>
|
||||
</View>
|
||||
<View style={{ flex: 1, backgroundColor: colors.dangerBg, borderRadius: 14, padding: 12 }}>
|
||||
<Text style={{ fontSize: 11, color: colors.danger }}>异常</Text>
|
||||
<Text style={{ marginTop: 6, fontSize: 18, fontWeight: '700', color: colors.danger }}>{formatNumber(errorAccounts)}</Text>
|
||||
</View>
|
||||
<View style={{ flex: 1, backgroundColor: colors.mutedCard, borderRadius: 14, padding: 12 }}>
|
||||
<Text style={{ fontSize: 11, color: '#8a8072' }}>暂停</Text>
|
||||
<Text style={{ marginTop: 6, fontSize: 18, fontWeight: '700', color: colors.text }}>{formatNumber(currentPagePausedAccounts)}</Text>
|
||||
</View>
|
||||
</View>
|
||||
<Text style={{ marginTop: 10, fontSize: 12, color: colors.subtext }}>总数 / 健康 / 异常优先使用后端聚合字段;暂停与繁忙基于当前页账号列表。</Text>
|
||||
</Section>
|
||||
|
||||
{throughputPoints.length > 1 ? (
|
||||
<LineTrendChart title="Token 吞吐" subtitle="当前时间范围内的 Token 变化趋势" points={throughputPoints} color="#a34d2d" formatValue={formatTokenDisplay} />
|
||||
) : null}
|
||||
|
||||
{requestPoints.length > 1 ? (
|
||||
<LineTrendChart title="请求趋势" subtitle="当前时间范围内的请求变化趋势" points={requestPoints} color="#1d5f55" formatValue={formatCompactNumber} />
|
||||
) : null}
|
||||
|
||||
{costPoints.length > 1 ? (
|
||||
<LineTrendChart title="成本趋势" subtitle="当前时间范围内的成本变化趋势" points={costPoints} color="#7651c8" formatValue={formatMoney} />
|
||||
) : null}
|
||||
|
||||
<BarChartCard
|
||||
title="Token 结构"
|
||||
subtitle="输入、输出、缓存读取占比"
|
||||
items={[
|
||||
{ label: '输入 Token', value: totalInputTokens, color: '#1d5f55', hint: '请求进入模型前消耗的 token。' },
|
||||
{ label: '输出 Token', value: totalOutputTokens, color: '#d38b36', hint: '模型返回内容消耗的 token。' },
|
||||
{ label: '缓存读取 Token', value: totalCacheReadTokens, color: '#7d7468', hint: '命中缓存后复用的 token。' },
|
||||
]}
|
||||
formatValue={formatTokenDisplay}
|
||||
/>
|
||||
|
||||
<DonutChartCard
|
||||
title="账号健康"
|
||||
subtitle="健康、繁忙、暂停、异常分布"
|
||||
centerLabel="总账号"
|
||||
centerValue={formatNumber(totalAccounts)}
|
||||
segments={[
|
||||
{ label: '健康', value: healthyAccounts, color: '#1d5f55' },
|
||||
{ label: '繁忙', value: currentPageBusyAccounts, color: '#d38b36' },
|
||||
{ label: '暂停', value: currentPagePausedAccounts, color: '#7d7468' },
|
||||
{ label: '异常', value: errorAccounts, color: '#a34d2d' },
|
||||
]}
|
||||
/>
|
||||
|
||||
<BarChartCard
|
||||
title="热点模型"
|
||||
subtitle="当前时间范围内最活跃的模型"
|
||||
items={topModels.map((model) => ({
|
||||
label: model.model,
|
||||
value: model.total_tokens,
|
||||
color: '#a34d2d',
|
||||
meta: `请求 ${formatNumber(model.requests)} · 成本 ${formatMoney(model.cost)}`,
|
||||
}))}
|
||||
formatValue={formatCompactNumber}
|
||||
/>
|
||||
|
||||
<Section title="趋势摘要" subtitle="图表 + 最近几个统计点的请求、Token 和成本变化">
|
||||
{latestTrendPoints.length === 0 ? (
|
||||
<Text style={{ fontSize: 14, color: colors.subtext }}>当前时间范围没有趋势数据。</Text>
|
||||
) : (
|
||||
<View style={{ gap: 12 }}>
|
||||
{throughputPoints.length > 1 ? (
|
||||
<LineTrendChart
|
||||
title="摘要 Token 趋势"
|
||||
subtitle="最近统计点的 Token 变化"
|
||||
points={throughputPoints.slice(-6)}
|
||||
color="#a34d2d"
|
||||
formatValue={formatTokenDisplay}
|
||||
compact
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<View style={{ gap: 10 }}>
|
||||
{latestTrendPoints.map((point) => (
|
||||
<View key={point.date} style={{ backgroundColor: colors.mutedCard, borderRadius: 14, padding: 12 }}>
|
||||
<Text style={{ fontSize: 13, fontWeight: '700', color: colors.text }}>{point.date}</Text>
|
||||
<View style={{ flexDirection: 'row', gap: 12, marginTop: 8 }}>
|
||||
<View style={{ flex: 1 }}>
|
||||
<Text style={{ fontSize: 11, color: '#8a8072' }}>请求</Text>
|
||||
<Text style={{ marginTop: 4, fontSize: 15, fontWeight: '700', color: colors.text }}>{formatCompactNumber(point.requests)}</Text>
|
||||
</View>
|
||||
<View style={{ flex: 1 }}>
|
||||
<Text style={{ fontSize: 11, color: '#8a8072' }}>Token</Text>
|
||||
<Text style={{ marginTop: 4, fontSize: 15, fontWeight: '700', color: colors.text }}>{formatTokenDisplay(point.total_tokens)}</Text>
|
||||
</View>
|
||||
<View style={{ flex: 1 }}>
|
||||
<Text style={{ fontSize: 11, color: '#8a8072' }}>成本</Text>
|
||||
<Text style={{ marginTop: 4, fontSize: 15, fontWeight: '700', color: colors.text }}>{formatMoney(point.cost)}</Text>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
{useMasonry ? (
|
||||
<View className="flex-row items-start gap-3">
|
||||
<View className="flex-1 gap-3">
|
||||
{leftColumn.map((item) => (
|
||||
<View key={item.key}>{item.node}</View>
|
||||
))}
|
||||
</View>
|
||||
<View className="flex-1 gap-3">
|
||||
{rightColumn.map((item) => (
|
||||
<View key={item.key}>{item.node}</View>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
) : (
|
||||
cards.map((item) => <View key={item.key}>{item.node}</View>)
|
||||
)}
|
||||
</ScreenShell>
|
||||
)}
|
||||
</ScrollView>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,197 +1,299 @@
|
||||
import { router } from 'expo-router';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { Controller, useForm } from 'react-hook-form';
|
||||
import { Pressable, Text, TextInput, View } from 'react-native';
|
||||
import { Pressable, RefreshControl, ScrollView, Text, TextInput, View } from 'react-native';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
import { useState } from 'react';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { ListCard } from '@/src/components/list-card';
|
||||
import { ScreenShell } from '@/src/components/screen-shell';
|
||||
import { isLocalProxyBaseUrl } from '@/src/lib/admin-fetch';
|
||||
import { getAdminSettings, getDashboardStats } from '@/src/services/admin';
|
||||
import { queryClient } from '@/src/lib/query-client';
|
||||
import {
|
||||
adminConfigState,
|
||||
logoutAdminAccount,
|
||||
removeAdminAccount,
|
||||
saveAdminConfig,
|
||||
setAdminAccountEnabled,
|
||||
switchAdminAccount,
|
||||
type AdminAccountProfile,
|
||||
} from '@/src/store/admin-config';
|
||||
import { adminConfigState, removeAdminAccount, saveAdminConfig, switchAdminAccount, type AdminAccountProfile } from '@/src/store/admin-config';
|
||||
|
||||
const { useSnapshot } = require('valtio/react');
|
||||
|
||||
const schema = z
|
||||
.object({
|
||||
baseUrl: z.string().min(1, '请输入 Host'),
|
||||
baseUrl: z.string().min(1, '请输入服务器地址'),
|
||||
adminApiKey: z.string(),
|
||||
})
|
||||
.superRefine((values, ctx) => {
|
||||
if (!isLocalProxyBaseUrl(values.baseUrl.trim()) && !values.adminApiKey.trim()) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: ['adminApiKey'],
|
||||
message: '请输入 Admin Token',
|
||||
});
|
||||
}
|
||||
.refine((values) => values.adminApiKey.trim().length > 0, {
|
||||
path: ['adminApiKey'],
|
||||
message: '请输入 Admin Key',
|
||||
});
|
||||
|
||||
type FormValues = z.infer<typeof schema>;
|
||||
type ConnectionState = 'idle' | 'checking' | 'success' | 'error';
|
||||
|
||||
const colors = {
|
||||
page: '#f4efe4',
|
||||
card: '#fbf8f2',
|
||||
mutedCard: '#f1ece2',
|
||||
primary: '#1d5f55',
|
||||
text: '#16181a',
|
||||
subtext: '#6f665c',
|
||||
border: '#e7dfcf',
|
||||
dangerBg: '#fbf1eb',
|
||||
danger: '#c25d35',
|
||||
successBg: '#e6f4ee',
|
||||
success: '#1d5f55',
|
||||
};
|
||||
|
||||
function getConnectionErrorMessage(error: unknown) {
|
||||
if (error instanceof Error && error.message) {
|
||||
switch (error.message) {
|
||||
case 'BASE_URL_REQUIRED':
|
||||
return '请先填写服务器地址。';
|
||||
case 'ADMIN_API_KEY_REQUIRED':
|
||||
return '请先填写 Admin Key。';
|
||||
case 'INVALID_SERVER_RESPONSE':
|
||||
return '当前地址返回的数据不正确,请确认它是可用的管理接口。';
|
||||
default:
|
||||
return error.message;
|
||||
}
|
||||
}
|
||||
|
||||
return '连接失败,请检查服务器地址、Admin Key 和网络连通性。';
|
||||
}
|
||||
|
||||
function ServerCard({
|
||||
account,
|
||||
active,
|
||||
onSelect,
|
||||
onDelete,
|
||||
}: {
|
||||
account: AdminAccountProfile;
|
||||
active: boolean;
|
||||
onSelect: () => Promise<void>;
|
||||
onDelete: () => Promise<void>;
|
||||
}) {
|
||||
return (
|
||||
<Pressable
|
||||
onPress={onSelect}
|
||||
style={{
|
||||
backgroundColor: active ? '#e6f4ee' : colors.card,
|
||||
borderRadius: 18,
|
||||
padding: 16,
|
||||
borderWidth: 1,
|
||||
borderColor: active ? colors.success : colors.border,
|
||||
}}
|
||||
>
|
||||
<View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
|
||||
<View style={{ flex: 1 }}>
|
||||
<Text style={{ fontSize: 16, fontWeight: '700', color: colors.text }}>{account.label}</Text>
|
||||
<Text style={{ marginTop: 6, fontSize: 13, lineHeight: 20, color: colors.subtext }}>{account.baseUrl}</Text>
|
||||
<Text style={{ marginTop: 8, fontSize: 11, color: '#8a8072' }}>更新时间 {new Date(account.updatedAt).toLocaleString()}</Text>
|
||||
</View>
|
||||
{active ? (
|
||||
<View style={{ backgroundColor: colors.success, borderRadius: 999, paddingHorizontal: 10, paddingVertical: 6 }}>
|
||||
<Text style={{ color: '#fff', fontSize: 11, fontWeight: '700' }}>当前使用</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<View style={{ flexDirection: 'row', gap: 10, marginTop: 14 }}>
|
||||
<Pressable onPress={onSelect} style={{ flex: 1, backgroundColor: active ? '#d7eee4' : colors.primary, borderRadius: 14, paddingVertical: 11, alignItems: 'center' }}>
|
||||
<Text style={{ color: active ? colors.success : '#fff', fontSize: 13, fontWeight: '700' }}>{active ? '已选中' : '切换到此服务器'}</Text>
|
||||
</Pressable>
|
||||
<Pressable onPress={onDelete} style={{ backgroundColor: colors.border, borderRadius: 14, paddingHorizontal: 16, justifyContent: 'center' }}>
|
||||
<Text style={{ color: '#7a3d31', fontSize: 13, fontWeight: '700' }}>删除</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
export default function SettingsScreen() {
|
||||
const config = useSnapshot(adminConfigState);
|
||||
const [showForm, setShowForm] = useState(config.accounts.length === 0);
|
||||
const [connectionState, setConnectionState] = useState<ConnectionState>('idle');
|
||||
const [connectionMessage, setConnectionMessage] = useState('');
|
||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||
const { control, handleSubmit, formState, reset } = useForm<FormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
values: {
|
||||
baseUrl: config.baseUrl,
|
||||
adminApiKey: config.adminApiKey,
|
||||
defaultValues: {
|
||||
baseUrl: '',
|
||||
adminApiKey: '',
|
||||
},
|
||||
});
|
||||
|
||||
async function handleSwitch(account: AdminAccountProfile) {
|
||||
async function verifyAndEnter(successMessage: string) {
|
||||
setConnectionState('checking');
|
||||
setConnectionMessage('正在检测当前服务是否可用...');
|
||||
|
||||
try {
|
||||
queryClient.clear();
|
||||
await queryClient.fetchQuery({ queryKey: ['admin-settings'], queryFn: getAdminSettings });
|
||||
await queryClient.prefetchQuery({ queryKey: ['monitor-stats'], queryFn: getDashboardStats });
|
||||
setConnectionState('success');
|
||||
setConnectionMessage(successMessage);
|
||||
router.replace('/monitor');
|
||||
} catch (error) {
|
||||
setConnectionState('error');
|
||||
setConnectionMessage(getConnectionErrorMessage(error));
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAdd(values: FormValues) {
|
||||
await saveAdminConfig(values);
|
||||
reset({ baseUrl: '', adminApiKey: '' });
|
||||
setShowForm(false);
|
||||
await verifyAndEnter('服务器已添加并切换成功。');
|
||||
}
|
||||
|
||||
async function handleSelect(account: AdminAccountProfile) {
|
||||
await switchAdminAccount(account.id);
|
||||
queryClient.clear();
|
||||
reset({ baseUrl: account.baseUrl, adminApiKey: account.adminApiKey });
|
||||
await verifyAndEnter(`已切换到 ${account.label}。`);
|
||||
}
|
||||
|
||||
async function handleDelete(account: AdminAccountProfile) {
|
||||
await removeAdminAccount(account.id);
|
||||
queryClient.clear();
|
||||
reset({ baseUrl: adminConfigState.baseUrl, adminApiKey: adminConfigState.adminApiKey });
|
||||
}
|
||||
|
||||
async function handleLogout() {
|
||||
await logoutAdminAccount();
|
||||
queryClient.clear();
|
||||
reset({ baseUrl: '', adminApiKey: '' });
|
||||
}
|
||||
async function handleRefresh() {
|
||||
if (!config.baseUrl.trim()) {
|
||||
return;
|
||||
}
|
||||
|
||||
async function handleToggleEnabled(account: AdminAccountProfile) {
|
||||
await setAdminAccountEnabled(account.id, account.enabled === false);
|
||||
queryClient.clear();
|
||||
reset({ baseUrl: adminConfigState.baseUrl, adminApiKey: adminConfigState.adminApiKey });
|
||||
setIsRefreshing(true);
|
||||
setConnectionState('idle');
|
||||
setConnectionMessage('');
|
||||
|
||||
try {
|
||||
await Promise.all([
|
||||
queryClient.fetchQuery({ queryKey: ['admin-settings'], queryFn: getAdminSettings }),
|
||||
queryClient.prefetchQuery({ queryKey: ['monitor-stats'], queryFn: getDashboardStats }),
|
||||
]);
|
||||
} catch (error) {
|
||||
setConnectionState('error');
|
||||
setConnectionMessage(getConnectionErrorMessage(error));
|
||||
} finally {
|
||||
setIsRefreshing(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<ScreenShell
|
||||
title="服务器"
|
||||
subtitle=""
|
||||
titleAside={<Text className="text-[11px] text-[#a2988a]">管理 Sub2API 连接。</Text>}
|
||||
variant="minimal"
|
||||
>
|
||||
<ListCard title="当前连接" meta={config.baseUrl || '未连接'}>
|
||||
<View className="gap-3">
|
||||
<Text className="text-sm text-[#6f665c]">
|
||||
{config.baseUrl || '当前没有激活服务器,可在下方直接新增或切换。'}
|
||||
</Text>
|
||||
<View className="flex-row gap-3">
|
||||
<Pressable className="flex-1 rounded-[18px] bg-[#1d5f55] px-4 py-3" onPress={handleSubmit(async (values) => {
|
||||
await saveAdminConfig(values);
|
||||
queryClient.clear();
|
||||
})}>
|
||||
<Text className="text-center text-sm font-semibold text-white">保存并连接</Text>
|
||||
</Pressable>
|
||||
<Pressable className="flex-1 rounded-[18px] bg-[#e7dfcf] px-4 py-3" onPress={handleLogout}>
|
||||
<Text className="text-center text-sm font-semibold text-[#4e463e]">退出当前</Text>
|
||||
</Pressable>
|
||||
<SafeAreaView style={{ flex: 1, backgroundColor: colors.page }}>
|
||||
<ScrollView
|
||||
style={{ flex: 1 }}
|
||||
contentContainerStyle={{ paddingHorizontal: 16, paddingTop: 16, paddingBottom: 110, gap: 14 }}
|
||||
showsVerticalScrollIndicator={false}
|
||||
refreshControl={<RefreshControl refreshing={isRefreshing} onRefresh={() => void handleRefresh()} tintColor="#1d5f55" />}
|
||||
>
|
||||
<View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
|
||||
<View style={{ flex: 1 }}>
|
||||
<Text style={{ fontSize: 28, fontWeight: '700', color: colors.text }}>服务器</Text>
|
||||
<Text style={{ marginTop: 6, fontSize: 13, color: '#8a8072' }}>选择当前管理的服务器,或添加新的服务器。</Text>
|
||||
</View>
|
||||
<Pressable
|
||||
onPress={() => {
|
||||
setShowForm((value) => !value);
|
||||
setConnectionState('idle');
|
||||
setConnectionMessage('');
|
||||
}}
|
||||
style={{ backgroundColor: colors.primary, borderRadius: 999, width: 42, height: 42, alignItems: 'center', justifyContent: 'center' }}
|
||||
>
|
||||
<Text style={{ color: '#fff', fontSize: 24, lineHeight: 24 }}>+</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</ListCard>
|
||||
|
||||
<ListCard title="连接配置" meta="Host 与 Admin Token 合并配置">
|
||||
<View className="gap-3">
|
||||
<View>
|
||||
<Text className="mb-2 text-[11px] text-[#7d7468]">Host</Text>
|
||||
<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]"
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{showForm ? (
|
||||
<View style={{ backgroundColor: colors.card, borderRadius: 18, padding: 16, gap: 14 }}>
|
||||
<Text style={{ fontSize: 18, fontWeight: '700', color: colors.text }}>添加服务器</Text>
|
||||
|
||||
<View>
|
||||
<Text style={{ marginBottom: 8, fontSize: 12, color: colors.subtext }}>服务器地址</Text>
|
||||
<Controller
|
||||
control={control}
|
||||
name="baseUrl"
|
||||
render={({ field: { onChange, value } }) => (
|
||||
<TextInput
|
||||
value={value}
|
||||
onChangeText={onChange}
|
||||
placeholder="例如:https://api.example.com"
|
||||
placeholderTextColor="#9b9081"
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
style={{ backgroundColor: colors.mutedCard, borderRadius: 16, paddingHorizontal: 16, paddingVertical: 14, fontSize: 16, color: colors.text }}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View>
|
||||
<Text style={{ marginBottom: 8, fontSize: 12, color: colors.subtext }}>Admin Key</Text>
|
||||
<Controller
|
||||
control={control}
|
||||
name="adminApiKey"
|
||||
render={({ field: { onChange, value } }) => (
|
||||
<TextInput
|
||||
value={value}
|
||||
onChangeText={onChange}
|
||||
placeholder="admin-xxxxxxxx"
|
||||
placeholderTextColor="#9b9081"
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
style={{ backgroundColor: colors.mutedCard, borderRadius: 16, paddingHorizontal: 16, paddingVertical: 14, fontSize: 16, color: colors.text }}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</View>
|
||||
|
||||
{formState.errors.baseUrl || formState.errors.adminApiKey ? (
|
||||
<View style={{ borderRadius: 14, backgroundColor: colors.dangerBg, paddingHorizontal: 14, paddingVertical: 12 }}>
|
||||
<Text style={{ color: colors.danger, fontSize: 14 }}>{formState.errors.baseUrl?.message || formState.errors.adminApiKey?.message}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{connectionMessage ? (
|
||||
<View style={{ borderRadius: 14, backgroundColor: connectionState === 'success' ? colors.successBg : colors.dangerBg, paddingHorizontal: 14, paddingVertical: 12 }}>
|
||||
<Text style={{ color: connectionState === 'success' ? colors.success : colors.danger, fontSize: 14 }}>{connectionMessage}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
<View style={{ flexDirection: 'row', gap: 12 }}>
|
||||
<Pressable
|
||||
onPress={handleSubmit(handleAdd)}
|
||||
disabled={connectionState === 'checking'}
|
||||
style={{ flex: 1, backgroundColor: connectionState === 'checking' ? '#7ca89f' : colors.primary, borderRadius: 16, paddingVertical: 14, alignItems: 'center' }}
|
||||
>
|
||||
<Text style={{ color: '#fff', fontSize: 14, fontWeight: '700' }}>{connectionState === 'checking' ? '检测中...' : '保存并使用'}</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
onPress={() => {
|
||||
setShowForm(false);
|
||||
setConnectionState('idle');
|
||||
setConnectionMessage('');
|
||||
reset({ baseUrl: '', adminApiKey: '' });
|
||||
}}
|
||||
style={{ flex: 1, backgroundColor: colors.border, borderRadius: 16, paddingVertical: 14, alignItems: 'center' }}
|
||||
>
|
||||
<Text style={{ color: '#4e463e', fontSize: 14, fontWeight: '700' }}>取消</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
<View>
|
||||
<Text className="mb-2 text-[11px] text-[#7d7468]">Admin Token</Text>
|
||||
<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]"
|
||||
/>
|
||||
)}
|
||||
<View style={{ gap: 12 }}>
|
||||
{config.accounts.map((account: AdminAccountProfile) => (
|
||||
<ServerCard
|
||||
key={account.id}
|
||||
account={account}
|
||||
active={account.id === config.activeAccountId}
|
||||
onSelect={() => handleSelect(account)}
|
||||
onDelete={() => handleDelete(account)}
|
||||
/>
|
||||
</View>
|
||||
))}
|
||||
|
||||
<Text className="text-[11px] text-[#8a8072]">使用本地代理时可留空 token;直连上游时必须填写。</Text>
|
||||
|
||||
{(formState.errors.baseUrl || formState.errors.adminApiKey) ? (
|
||||
<View className="rounded-[16px] bg-[#fbf1eb] px-4 py-3">
|
||||
<Text className="text-sm text-[#c25d35]">{formState.errors.baseUrl?.message || formState.errors.adminApiKey?.message}</Text>
|
||||
{config.accounts.length === 0 ? (
|
||||
<View style={{ backgroundColor: colors.card, borderRadius: 18, padding: 18 }}>
|
||||
<Text style={{ fontSize: 15, fontWeight: '700', color: colors.text }}>还没有服务器</Text>
|
||||
<Text style={{ marginTop: 8, fontSize: 13, lineHeight: 21, color: colors.subtext }}>点击右上角 + 添加服务器,保存成功后会自动切换并进入概览。</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
</ListCard>
|
||||
|
||||
<ListCard title="已保存服务器" meta={`共 ${config.accounts.length} 个`}>
|
||||
<View className="gap-3">
|
||||
{config.accounts.map((account: AdminAccountProfile) => {
|
||||
const active = account.id === config.activeAccountId;
|
||||
const enabled = account.enabled !== false;
|
||||
|
||||
return (
|
||||
<View key={account.id} className="rounded-[18px] bg-[#f1ece2] px-4 py-3">
|
||||
<View className="flex-row items-start justify-between gap-3">
|
||||
<View className="flex-1">
|
||||
<Text className="text-sm font-semibold text-[#16181a]">{account.label}</Text>
|
||||
<Text className="mt-1 text-xs text-[#7d7468]">{account.baseUrl}</Text>
|
||||
</View>
|
||||
{active ? (
|
||||
<View className="rounded-full bg-[#1d5f55] px-3 py-1">
|
||||
<Text className="text-[10px] font-semibold uppercase tracking-[1px] text-white">当前</Text>
|
||||
</View>
|
||||
) : !enabled ? (
|
||||
<View className="rounded-full bg-[#cfc5b7] px-3 py-1">
|
||||
<Text className="text-[10px] font-semibold uppercase tracking-[1px] text-[#6f665c]">已禁用</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<View className="mt-3 flex-row gap-3">
|
||||
<Pressable
|
||||
className={active ? 'flex-1 rounded-[16px] bg-[#d7eee4] px-3 py-2.5' : !enabled ? 'flex-1 rounded-[16px] bg-[#d8d1c4] px-3 py-2.5' : 'flex-1 rounded-[16px] bg-[#1d5f55] px-3 py-2.5'}
|
||||
onPress={() => handleSwitch(account)}
|
||||
disabled={!enabled}
|
||||
>
|
||||
<Text className={active ? 'text-center text-xs font-semibold text-[#1d5f55]' : !enabled ? 'text-center text-xs font-semibold text-[#7d7468]' : 'text-center text-xs font-semibold text-white'}>
|
||||
{active ? '使用中' : '启用连接'}
|
||||
</Text>
|
||||
</Pressable>
|
||||
<Pressable className="rounded-[16px] bg-[#e7dfcf] px-4 py-2.5" onPress={() => handleToggleEnabled(account)}>
|
||||
<Text className="text-center text-xs font-semibold text-[#4e463e]">{enabled ? '禁用' : '启用'}</Text>
|
||||
</Pressable>
|
||||
<Pressable className="rounded-[16px] bg-[#e7dfcf] px-4 py-2.5" onPress={() => handleDelete(account)}>
|
||||
<Text className="text-center text-xs font-semibold text-[#7a3d31]">删除</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
|
||||
{config.accounts.length === 0 ? <Text className="text-sm text-[#7d7468]">还没有保存的服务器。</Text> : null}
|
||||
</View>
|
||||
</ListCard>
|
||||
</ScreenShell>
|
||||
</ScrollView>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,264 +1,223 @@
|
||||
import { useQueries, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import * as Clipboard from 'expo-clipboard';
|
||||
import { Copy, Search, UserRound } from 'lucide-react-native';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { router } from 'expo-router';
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { FlatList, Pressable, Text, TextInput, View } from 'react-native';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { FlatList, Pressable, RefreshControl, Text, TextInput, View } from 'react-native';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
|
||||
import { ListCard } from '@/src/components/list-card';
|
||||
import { ScreenShell } from '@/src/components/screen-shell';
|
||||
import { useDebouncedValue } from '@/src/hooks/use-debounced-value';
|
||||
import { useScreenInteractive } from '@/src/hooks/use-screen-interactive';
|
||||
import { getUser, getUserUsage, listUserApiKeys, listUsers } from '@/src/services/admin';
|
||||
import { queryClient } from '@/src/lib/query-client';
|
||||
import { getUser, listUserApiKeys, listUsers } from '@/src/services/admin';
|
||||
import { adminConfigState } from '@/src/store/admin-config';
|
||||
import type { AdminApiKey, AdminUser, UserUsageSummary } from '@/src/types/admin';
|
||||
import type { AdminUser } from '@/src/types/admin';
|
||||
|
||||
const { useSnapshot } = require('valtio/react');
|
||||
|
||||
type UserSupplement = {
|
||||
usage?: UserUsageSummary;
|
||||
apiKeys: AdminApiKey[];
|
||||
const colors = {
|
||||
page: '#f4efe4',
|
||||
card: '#fbf8f2',
|
||||
mutedCard: '#f1ece2',
|
||||
primary: '#1d5f55',
|
||||
text: '#16181a',
|
||||
subtext: '#6f665c',
|
||||
dangerBg: '#fbf1eb',
|
||||
danger: '#c25d35',
|
||||
accentBg: '#efe4cf',
|
||||
accentText: '#8c5a22',
|
||||
};
|
||||
|
||||
function getUserTitle(user: AdminUser) {
|
||||
return user.username?.trim() || user.email;
|
||||
}
|
||||
type SortOrder = 'desc' | 'asc';
|
||||
|
||||
function getUserSortValue(user: AdminUser) {
|
||||
const raw = user.updated_at || user.created_at || '';
|
||||
const value = raw ? new Date(raw).getTime() : 0;
|
||||
return Number.isNaN(value) ? 0 : value;
|
||||
}
|
||||
|
||||
function formatQuotaValue(value: number) {
|
||||
function formatBalance(value?: number) {
|
||||
if (typeof value !== 'number' || Number.isNaN(value)) return '$0.00';
|
||||
return `$${value.toFixed(2)}`;
|
||||
}
|
||||
|
||||
function formatActivityTime(value?: string) {
|
||||
if (!value) return '时间未知';
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return '时间未知';
|
||||
|
||||
const year = date.getFullYear();
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
const hours = String(date.getHours()).padStart(2, '0');
|
||||
const minutes = String(date.getMinutes()).padStart(2, '0');
|
||||
const seconds = String(date.getSeconds()).padStart(2, '0');
|
||||
|
||||
return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
|
||||
}
|
||||
|
||||
function toTimeValue(value?: string | null) {
|
||||
if (!value) return 0;
|
||||
const time = new Date(value).getTime();
|
||||
return Number.isNaN(time) ? 0 : time;
|
||||
}
|
||||
|
||||
function getTimeValue(user: AdminUser) {
|
||||
return toTimeValue(user.last_used_at) || toTimeValue(user.updated_at) || toTimeValue(user.created_at) || user.id || 0;
|
||||
}
|
||||
|
||||
function getUserNameLabel(user: AdminUser) {
|
||||
if (user.username?.trim()) return user.username.trim();
|
||||
if (user.notes?.trim()) return user.notes.trim();
|
||||
return user.email.split('@')[0] || '未命名';
|
||||
}
|
||||
|
||||
function getErrorMessage(error: unknown) {
|
||||
if (error instanceof Error && error.message) {
|
||||
switch (error.message) {
|
||||
case 'BASE_URL_REQUIRED':
|
||||
return '请先到服务器页填写服务地址。';
|
||||
case 'ADMIN_API_KEY_REQUIRED':
|
||||
return '请先到服务器页填写 Admin Token。';
|
||||
default:
|
||||
return error.message;
|
||||
}
|
||||
}
|
||||
|
||||
return '当前无法加载页面数据,请检查服务地址、Token 和网络。';
|
||||
}
|
||||
|
||||
function MetricTile({ title, value, tone = 'default' }: { title: string; value: string; tone?: 'default' | 'accent' }) {
|
||||
const backgroundColor = tone === 'accent' ? colors.accentBg : colors.mutedCard;
|
||||
const valueColor = tone === 'accent' ? colors.accentText : colors.text;
|
||||
|
||||
return (
|
||||
<View style={{ flex: 1, minWidth: 0, backgroundColor, borderRadius: 14, paddingHorizontal: 10, paddingVertical: 12 }}>
|
||||
<Text style={{ fontSize: 11, color: colors.subtext }}>{title}</Text>
|
||||
<Text numberOfLines={1} style={{ marginTop: 6, fontSize: tone === 'accent' ? 20 : 16, fontWeight: '800', color: valueColor }}>
|
||||
{value}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function UserCard({ user }: { user: AdminUser }) {
|
||||
const isAdmin = user.role?.trim().toLowerCase() === 'admin';
|
||||
const statusLabel = `${isAdmin ? 'admin · ' : ''}${user.status || 'active'}`;
|
||||
|
||||
return (
|
||||
<View style={{ backgroundColor: colors.card, borderRadius: 18, padding: 14 }}>
|
||||
<View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
|
||||
<View style={{ flex: 1 }}>
|
||||
<Text numberOfLines={1} style={{ fontSize: 16, fontWeight: '800', color: colors.text }}>{user.email}</Text>
|
||||
<Text style={{ marginTop: 4, fontSize: 12, color: colors.subtext }}>最近使用 {formatActivityTime(user.last_used_at || user.updated_at || user.created_at)}</Text>
|
||||
</View>
|
||||
<View style={{ alignSelf: 'flex-start', backgroundColor: user.status === 'inactive' ? '#cfc5b7' : colors.primary, borderRadius: 999, paddingHorizontal: 10, paddingVertical: 6 }}>
|
||||
<Text style={{ fontSize: 10, fontWeight: '700', color: '#fff' }}>{statusLabel}</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View style={{ flexDirection: 'row', gap: 8, marginTop: 12 }}>
|
||||
<MetricTile title="金额" value={formatBalance(Number(user.balance ?? 0))} tone="accent" />
|
||||
<MetricTile title="名称" value={getUserNameLabel(user)} />
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export default function UsersScreen() {
|
||||
useScreenInteractive('users_interactive');
|
||||
const config = useSnapshot(adminConfigState);
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const [sortOrder, setSortOrder] = useState<'desc' | 'asc'>('desc');
|
||||
const [copiedKeyId, setCopiedKeyId] = useState<number | null>(null);
|
||||
const keyword = useDebouncedValue(searchText.trim(), 300);
|
||||
const queryClient = useQueryClient();
|
||||
const hasAccount = Boolean(config.baseUrl.trim());
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const [sortOrder, setSortOrder] = useState<SortOrder>('desc');
|
||||
const debouncedSearchText = useDebouncedValue(searchText, 250);
|
||||
|
||||
const usersQuery = useQuery({
|
||||
queryKey: ['users', keyword],
|
||||
queryFn: () => listUsers(keyword),
|
||||
queryKey: ['users', debouncedSearchText],
|
||||
queryFn: () => listUsers(debouncedSearchText),
|
||||
enabled: hasAccount,
|
||||
});
|
||||
|
||||
const items = usersQuery.data?.items ?? [];
|
||||
const userDetailQueries = useQueries({
|
||||
queries: items.map((user) => ({
|
||||
queryKey: ['user-list-supplement', user.id],
|
||||
queryFn: async () => {
|
||||
const [usage, apiKeysData] = await Promise.all([getUserUsage(user.id), listUserApiKeys(user.id)]);
|
||||
const users = useMemo(() => {
|
||||
const items = [...(usersQuery.data?.items ?? [])];
|
||||
items.sort((left, right) => {
|
||||
const value = getTimeValue(left) - getTimeValue(right);
|
||||
return sortOrder === 'desc' ? -value : value;
|
||||
});
|
||||
return items;
|
||||
}, [sortOrder, usersQuery.data?.items]);
|
||||
|
||||
return {
|
||||
usage,
|
||||
apiKeys: apiKeysData.items ?? [],
|
||||
} satisfies UserSupplement;
|
||||
},
|
||||
enabled: hasAccount,
|
||||
staleTime: 60_000,
|
||||
})),
|
||||
});
|
||||
|
||||
const errorMessage = usersQuery.error instanceof Error ? usersQuery.error.message : '';
|
||||
const supplementsByUserId = useMemo(
|
||||
() =>
|
||||
items.reduce<Record<number, UserSupplement | undefined>>((result, user, index) => {
|
||||
result[user.id] = userDetailQueries[index]?.data;
|
||||
return result;
|
||||
}, {}),
|
||||
[items, userDetailQueries]
|
||||
);
|
||||
const sortedItems = useMemo(
|
||||
() =>
|
||||
[...items].sort((left, right) => {
|
||||
const delta = getUserSortValue(right) - getUserSortValue(left);
|
||||
return sortOrder === 'desc' ? delta : -delta;
|
||||
}),
|
||||
[items, sortOrder]
|
||||
);
|
||||
|
||||
async function copyKey(keyId: number, value: string) {
|
||||
await Clipboard.setStringAsync(value);
|
||||
setCopiedKeyId(keyId);
|
||||
setTimeout(() => setCopiedKeyId((current) => (current === keyId ? null : current)), 1600);
|
||||
}
|
||||
|
||||
const renderItem = useCallback(
|
||||
({ item: user }: { item: (typeof sortedItems)[number] }) => {
|
||||
const keyItems = (supplementsByUserId[user.id]?.apiKeys ?? []).slice(0, 3);
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
className="px-1"
|
||||
onPress={() => {
|
||||
void queryClient.prefetchQuery({ queryKey: ['user', user.id], queryFn: () => getUser(user.id) });
|
||||
void queryClient.prefetchQuery({ queryKey: ['user-usage', user.id], queryFn: () => getUserUsage(user.id) });
|
||||
void queryClient.prefetchQuery({ queryKey: ['user-api-keys', user.id], queryFn: () => listUserApiKeys(user.id) });
|
||||
router.push(`/users/${user.id}`);
|
||||
}}
|
||||
>
|
||||
<ListCard title={getUserTitle(user)} meta={user.email} badge={user.status || 'active'} icon={UserRound}>
|
||||
<View className="gap-2">
|
||||
<View className="rounded-[14px] bg-[#f7f2e9] px-3 py-2.5">
|
||||
<View className="flex-row items-center justify-between">
|
||||
<Text className="text-[11px] text-[#6f665c]">余额</Text>
|
||||
<Text className="text-sm font-semibold text-[#16181a]">${Number(user.balance ?? 0).toFixed(2)}</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View className="rounded-[14px] bg-[#f7f2e9] px-3 py-2">
|
||||
<View className="mb-1.5 flex-row items-center justify-between">
|
||||
<Text className="text-[11px] text-[#6f665c]">Keys</Text>
|
||||
<Text className="text-[10px] text-[#8a8072]">{keyItems.length} 个</Text>
|
||||
</View>
|
||||
|
||||
<View className="gap-0">
|
||||
{keyItems.map((apiKey, index) => (
|
||||
<View
|
||||
key={apiKey.id}
|
||||
style={{ paddingVertical: 4 }}
|
||||
>
|
||||
{(() => {
|
||||
const quota = Number(apiKey.quota ?? 0);
|
||||
const used = Number(apiKey.quota_used ?? 0);
|
||||
const isUnlimited = quota <= 0;
|
||||
const progressWidth = isUnlimited ? '16%' : (`${Math.max(Math.min((used / quota) * 100, 100), 6)}%` as `${number}%`);
|
||||
|
||||
return (
|
||||
<>
|
||||
<View className="flex-row items-center gap-2">
|
||||
<Text numberOfLines={1} className="flex-1 text-[11px] font-semibold text-[#16181a]">
|
||||
{apiKey.name}
|
||||
</Text>
|
||||
<Text numberOfLines={1} className="text-[10px] text-[#6f665c]">
|
||||
{isUnlimited ? `${formatQuotaValue(used)} / 无限` : `${formatQuotaValue(used)} / ${formatQuotaValue(quota)}`}
|
||||
</Text>
|
||||
<Pressable
|
||||
className="rounded-full bg-[#e7dfcf] p-1.5"
|
||||
onPress={(event) => {
|
||||
event.stopPropagation();
|
||||
void copyKey(apiKey.id, apiKey.key);
|
||||
}}
|
||||
>
|
||||
<Copy color="#4e463e" size={11} />
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
<View className="h-1.5 overflow-hidden rounded-full bg-[#ddd2c0]" style={{ marginTop: 3 }}>
|
||||
<View
|
||||
className={
|
||||
isUnlimited
|
||||
? 'h-full rounded-full bg-[#7d7468]'
|
||||
: used / Math.max(quota, 1) >= 0.85
|
||||
? 'h-full rounded-full bg-[#c25d35]'
|
||||
: used / Math.max(quota, 1) >= 0.6
|
||||
? 'h-full rounded-full bg-[#d38b36]'
|
||||
: 'h-full rounded-full bg-[#1d5f55]'
|
||||
}
|
||||
style={{ width: progressWidth }}
|
||||
/>
|
||||
</View>
|
||||
|
||||
{copiedKeyId === apiKey.id ? <Text className="text-[10px] text-[#1d5f55]" style={{ paddingTop: 3 }}>已复制</Text> : null}
|
||||
</>
|
||||
);
|
||||
})()}
|
||||
</View>
|
||||
))}
|
||||
|
||||
{keyItems.length === 0 ? (
|
||||
<View className="py-[10px]">
|
||||
<Text className="text-[11px] text-[#6f665c]">当前用户还没有可展示的 token 额度信息。</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
</ListCard>
|
||||
</Pressable>
|
||||
);
|
||||
},
|
||||
[copiedKeyId, queryClient, sortedItems, supplementsByUserId]
|
||||
);
|
||||
|
||||
const emptyState = useMemo(
|
||||
() => (
|
||||
<ListCard
|
||||
title={hasAccount ? '暂无匹配用户' : '未连接服务器'}
|
||||
meta={hasAccount ? errorMessage || '调整搜索词后再试。' : '请先前往服务器标签连接 Sub2API。'}
|
||||
icon={UserRound}
|
||||
/>
|
||||
),
|
||||
[errorMessage, hasAccount]
|
||||
);
|
||||
const errorMessage = getErrorMessage(usersQuery.error);
|
||||
|
||||
return (
|
||||
<ScreenShell
|
||||
title="用户管理"
|
||||
subtitle=""
|
||||
titleAside={<Text className="text-[11px] text-[#a2988a]">搜索结果 {sortedItems.length}</Text>}
|
||||
variant="minimal"
|
||||
scroll={false}
|
||||
bottomInsetClassName="pb-12"
|
||||
>
|
||||
<View className="flex-1">
|
||||
<View className="rounded-[16px] bg-[#fbf8f2] px-2.5 py-2.5">
|
||||
<View className="flex-row items-center gap-2">
|
||||
<View className="flex-1 flex-row items-center rounded-[14px] bg-[#f1ece2] px-3 py-2.5">
|
||||
<Search color="#7d7468" size={18} />
|
||||
<TextInput
|
||||
value={searchText}
|
||||
onChangeText={setSearchText}
|
||||
placeholder="搜索邮箱或用户名"
|
||||
placeholderTextColor="#9b9081"
|
||||
className="ml-3 flex-1 text-base text-[#16181a]"
|
||||
/>
|
||||
</View>
|
||||
<Pressable
|
||||
className={sortOrder === 'desc' ? 'rounded-[14px] bg-[#1d5f55] px-3 py-2.5' : 'rounded-[14px] bg-[#e7dfcf] px-3 py-2.5'}
|
||||
onPress={() => setSortOrder('desc')}
|
||||
>
|
||||
<Text className={sortOrder === 'desc' ? 'text-[11px] font-semibold text-white' : 'text-[11px] font-semibold text-[#4e463e]'}>
|
||||
最新
|
||||
</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
className={sortOrder === 'asc' ? 'rounded-[14px] bg-[#1d5f55] px-3 py-2.5' : 'rounded-[14px] bg-[#e7dfcf] px-3 py-2.5'}
|
||||
onPress={() => setSortOrder('asc')}
|
||||
>
|
||||
<Text className={sortOrder === 'asc' ? 'text-[11px] font-semibold text-white' : 'text-[11px] font-semibold text-[#4e463e]'}>
|
||||
最早
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
<SafeAreaView style={{ flex: 1, backgroundColor: colors.page }}>
|
||||
<View style={{ flex: 1, paddingHorizontal: 16, paddingTop: 14 }}>
|
||||
<View style={{ marginBottom: 10 }}>
|
||||
<Text style={{ fontSize: 28, fontWeight: '700', color: colors.text }}>用户</Text>
|
||||
<Text style={{ marginTop: 4, fontSize: 12, color: '#8a8072' }}>查看用户列表并进入详情页管理账号。</Text>
|
||||
</View>
|
||||
|
||||
<View className="mt-2.5 flex-1">
|
||||
<View style={{ flexDirection: 'row', gap: 10, alignItems: 'center' }}>
|
||||
<View style={{ flex: 1, backgroundColor: colors.card, borderRadius: 16, padding: 10 }}>
|
||||
<TextInput
|
||||
value={searchText}
|
||||
onChangeText={setSearchText}
|
||||
placeholder="搜索邮箱、用户名或备注"
|
||||
placeholderTextColor="#9b9081"
|
||||
style={{ backgroundColor: colors.mutedCard, borderRadius: 14, paddingHorizontal: 14, paddingVertical: 11, fontSize: 15, color: colors.text }}
|
||||
/>
|
||||
</View>
|
||||
<Pressable
|
||||
onPress={() => setSortOrder((value) => (value === 'desc' ? 'asc' : 'desc'))}
|
||||
style={{ backgroundColor: colors.card, borderRadius: 16, paddingHorizontal: 14, paddingVertical: 14, minWidth: 92, alignItems: 'center' }}
|
||||
>
|
||||
<Text style={{ fontSize: 11, color: colors.subtext }}>时间</Text>
|
||||
<Text style={{ marginTop: 4, fontSize: 13, fontWeight: '700', color: colors.text }}>{sortOrder === 'desc' ? '倒序' : '正序'}</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
{!hasAccount ? (
|
||||
<View style={{ marginTop: 10, backgroundColor: colors.card, borderRadius: 18, padding: 16 }}>
|
||||
<Text style={{ fontSize: 18, fontWeight: '700', color: colors.text }}>未连接服务器</Text>
|
||||
<Text style={{ marginTop: 8, fontSize: 14, lineHeight: 22, color: colors.subtext }}>请先到“服务器”页完成连接,再查看用户列表。</Text>
|
||||
<Pressable
|
||||
style={{ marginTop: 14, alignSelf: 'flex-start', backgroundColor: colors.primary, borderRadius: 14, paddingHorizontal: 16, paddingVertical: 12 }}
|
||||
onPress={() => router.push('/settings')}
|
||||
>
|
||||
<Text style={{ color: '#fff', fontSize: 13, fontWeight: '700' }}>去配置服务器</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
) : usersQuery.isLoading ? (
|
||||
<View style={{ marginTop: 10, backgroundColor: colors.card, borderRadius: 18, padding: 16 }}>
|
||||
<Text style={{ fontSize: 18, fontWeight: '700', color: colors.text }}>正在加载用户</Text>
|
||||
<Text style={{ marginTop: 8, fontSize: 14, lineHeight: 22, color: colors.subtext }}>已连接服务器,正在拉取用户列表。</Text>
|
||||
</View>
|
||||
) : usersQuery.error ? (
|
||||
<View style={{ marginTop: 10, backgroundColor: colors.card, borderRadius: 18, padding: 16 }}>
|
||||
<Text style={{ fontSize: 18, fontWeight: '700', color: colors.text }}>加载失败</Text>
|
||||
<View style={{ marginTop: 12, borderRadius: 14, backgroundColor: colors.dangerBg, paddingHorizontal: 14, paddingVertical: 12 }}>
|
||||
<Text style={{ color: colors.danger, fontSize: 14, lineHeight: 20 }}>{errorMessage}</Text>
|
||||
</View>
|
||||
</View>
|
||||
) : (
|
||||
<FlatList
|
||||
data={sortedItems}
|
||||
renderItem={renderItem}
|
||||
style={{ marginTop: 10, flex: 1 }}
|
||||
data={users}
|
||||
keyExtractor={(item) => `${item.id}`}
|
||||
showsVerticalScrollIndicator={false}
|
||||
ListHeaderComponent={() => <View className="h-2" />}
|
||||
ListEmptyComponent={emptyState}
|
||||
ListFooterComponent={() => <View className="h-4" />}
|
||||
ItemSeparatorComponent={() => <View className="h-3" />}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
removeClippedSubviews
|
||||
initialNumToRender={8}
|
||||
maxToRenderPerBatch={8}
|
||||
windowSize={5}
|
||||
refreshControl={<RefreshControl refreshing={usersQuery.isRefetching} onRefresh={() => void usersQuery.refetch()} tintColor="#1d5f55" />}
|
||||
contentContainerStyle={{ paddingBottom: 8, gap: 12, flexGrow: users.length === 0 ? 1 : 0 }}
|
||||
ListEmptyComponent={
|
||||
<View style={{ backgroundColor: colors.card, borderRadius: 18, padding: 16 }}>
|
||||
<Text style={{ fontSize: 18, fontWeight: '700', color: colors.text }}>暂无用户</Text>
|
||||
<Text style={{ marginTop: 8, fontSize: 14, lineHeight: 22, color: colors.subtext }}>当前搜索条件下没有匹配结果,可以修改关键词后重试。</Text>
|
||||
</View>
|
||||
}
|
||||
renderItem={({ item }) => (
|
||||
<Pressable
|
||||
onPress={() => {
|
||||
void queryClient.prefetchQuery({ queryKey: ['user', item.id], queryFn: () => getUser(item.id) });
|
||||
void queryClient.prefetchQuery({ queryKey: ['user-api-keys', item.id], queryFn: () => listUserApiKeys(item.id) });
|
||||
router.push(`/users/${item.id}`);
|
||||
}}
|
||||
>
|
||||
<UserCard user={item} />
|
||||
</Pressable>
|
||||
)}
|
||||
/>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
</ScreenShell>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -12,16 +12,20 @@ import { adminConfigState, hydrateAdminConfig } from '@/src/store/admin-config';
|
||||
|
||||
const { useSnapshot } = require('valtio/react');
|
||||
|
||||
export const unstable_settings = {
|
||||
initialRouteName: '(tabs)',
|
||||
};
|
||||
|
||||
export default function RootLayout() {
|
||||
const config = useSnapshot(adminConfigState);
|
||||
|
||||
useEffect(() => {
|
||||
hydrateAdminConfig()
|
||||
.then(() => markPerformance('config_hydrated'))
|
||||
.catch(() => undefined);
|
||||
}, []);
|
||||
|
||||
const config = useSnapshot(adminConfigState);
|
||||
const isReady = config.hydrated;
|
||||
|
||||
return (
|
||||
<GestureHandlerRootView style={{ flex: 1 }}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
@@ -30,10 +34,22 @@ export default function RootLayout() {
|
||||
<ActivityIndicator color="#1d5f55" />
|
||||
</View>
|
||||
) : (
|
||||
<Stack screenOptions={{ headerShown: false }}>
|
||||
<Stack initialRouteName="(tabs)" screenOptions={{ headerShown: false }}>
|
||||
<Stack.Screen name="(tabs)" />
|
||||
<Stack.Screen name="login" />
|
||||
<Stack.Screen name="users/[id]" options={{ animation: 'slide_from_right', presentation: 'card' }} />
|
||||
<Stack.Screen
|
||||
name="users/[id]"
|
||||
options={{
|
||||
animation: 'slide_from_right',
|
||||
presentation: 'card',
|
||||
headerShown: true,
|
||||
title: '用户详情',
|
||||
headerBackTitle: '返回',
|
||||
headerTintColor: '#16181a',
|
||||
headerStyle: { backgroundColor: '#f4efe4' },
|
||||
headerShadowVisible: false,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen name="accounts/[id]" options={{ presentation: 'card' }} />
|
||||
</Stack>
|
||||
)}
|
||||
|
||||
@@ -66,11 +66,18 @@ export default function AccountDetailScreen() {
|
||||
label: item.date.slice(5),
|
||||
value: item.total_tokens,
|
||||
}));
|
||||
const isRefreshing = accountQuery.isRefetching || todayStatsQuery.isRefetching || trendQuery.isRefetching;
|
||||
|
||||
function handleRefresh() {
|
||||
void Promise.all([accountQuery.refetch(), todayStatsQuery.refetch(), trendQuery.refetch()]);
|
||||
}
|
||||
|
||||
return (
|
||||
<ScreenShell
|
||||
title={account?.name || '账号详情'}
|
||||
subtitle="聚焦账号 token 用量、状态和几个最常用操作。"
|
||||
refreshing={isRefreshing}
|
||||
onRefresh={handleRefresh}
|
||||
right={
|
||||
<Pressable className="h-11 w-11 items-center justify-center rounded-full bg-[#2d3134]" onPress={() => router.back()}>
|
||||
<ChevronLeft color="#f6f1e8" size={18} />
|
||||
|
||||
261
app/login.tsx
261
app/login.tsx
@@ -1,39 +1,62 @@
|
||||
import { router } from 'expo-router';
|
||||
import { Redirect, router } from 'expo-router';
|
||||
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 { Pressable, ScrollView, Text, TextInput, View } from 'react-native';
|
||||
import { useState } from 'react';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { ListCard } from '@/src/components/list-card';
|
||||
import { ScreenShell } from '@/src/components/screen-shell';
|
||||
import { useScreenInteractive } from '@/src/hooks/use-screen-interactive';
|
||||
import { isLocalProxyBaseUrl } from '@/src/lib/admin-fetch';
|
||||
import { getAdminSettings, getDashboardStats } from '@/src/services/admin';
|
||||
import { queryClient } from '@/src/lib/query-client';
|
||||
import { adminConfigState, removeAdminAccount, saveAdminConfig, setAdminAccountEnabled, switchAdminAccount, type AdminAccountProfile } from '@/src/store/admin-config';
|
||||
import { adminConfigState, saveAdminConfig } from '@/src/store/admin-config';
|
||||
|
||||
const { useSnapshot } = require('valtio/react');
|
||||
|
||||
const schema = z
|
||||
.object({
|
||||
baseUrl: z.string().min(1, '请输入 Host'),
|
||||
baseUrl: z.string().min(1, '请输入服务器地址'),
|
||||
adminApiKey: z.string(),
|
||||
})
|
||||
.superRefine((values, ctx) => {
|
||||
if (!isLocalProxyBaseUrl(values.baseUrl.trim()) && !values.adminApiKey.trim()) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: ['adminApiKey'],
|
||||
message: '请输入 Admin Token',
|
||||
});
|
||||
}
|
||||
.refine((values) => values.adminApiKey.trim().length > 0, {
|
||||
path: ['adminApiKey'],
|
||||
message: '请输入 Admin Key',
|
||||
});
|
||||
|
||||
type FormValues = z.infer<typeof schema>;
|
||||
type ConnectionState = 'idle' | 'checking' | 'error';
|
||||
|
||||
const colors = {
|
||||
page: '#f4efe4',
|
||||
card: '#fbf8f2',
|
||||
mutedCard: '#f1ece2',
|
||||
primary: '#1d5f55',
|
||||
text: '#16181a',
|
||||
subtext: '#6f665c',
|
||||
border: '#e7dfcf',
|
||||
dangerBg: '#fbf1eb',
|
||||
danger: '#c25d35',
|
||||
};
|
||||
|
||||
function getConnectionErrorMessage(error: unknown) {
|
||||
if (error instanceof Error && error.message) {
|
||||
switch (error.message) {
|
||||
case 'BASE_URL_REQUIRED':
|
||||
return '请先填写服务器地址。';
|
||||
case 'ADMIN_API_KEY_REQUIRED':
|
||||
return '请先填写 Admin Key。';
|
||||
case 'INVALID_SERVER_RESPONSE':
|
||||
return '当前地址返回的数据不正确,请确认它是可用的管理接口。';
|
||||
default:
|
||||
return error.message;
|
||||
}
|
||||
}
|
||||
|
||||
return '连接失败,请检查服务器地址、Admin Key 和网络连通性。';
|
||||
}
|
||||
|
||||
export default function LoginScreen() {
|
||||
useScreenInteractive('login_interactive');
|
||||
const config = useSnapshot(adminConfigState);
|
||||
const hasAccount = Boolean(config.baseUrl.trim());
|
||||
const { control, handleSubmit, formState } = useForm<FormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: {
|
||||
@@ -41,115 +64,111 @@ export default function LoginScreen() {
|
||||
adminApiKey: config.adminApiKey,
|
||||
},
|
||||
});
|
||||
const [connectionState, setConnectionState] = useState<ConnectionState>('idle');
|
||||
const [connectionMessage, setConnectionMessage] = useState('');
|
||||
|
||||
if (hasAccount) {
|
||||
return <Redirect href="/monitor" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<ScreenShell
|
||||
title="登录"
|
||||
subtitle=""
|
||||
titleAside={<Text className="text-[11px] text-[#a2988a]">添加、切换或恢复 Sub2API 账号。</Text>}
|
||||
variant="minimal"
|
||||
>
|
||||
{config.accounts.length > 0 ? (
|
||||
<ListCard title="已保存账号" meta="可直接切换到其他 Sub2API 账号">
|
||||
<View className="gap-3">
|
||||
{config.accounts.map((account: AdminAccountProfile) => {
|
||||
const active = account.id === config.activeAccountId;
|
||||
const enabled = account.enabled !== false;
|
||||
|
||||
return (
|
||||
<View key={account.id} className="rounded-[18px] bg-[#f1ece2] px-4 py-3">
|
||||
<Text className="text-sm font-semibold text-[#16181a]">{account.label}</Text>
|
||||
<Text className="mt-1 text-xs text-[#7d7468]">{account.baseUrl}</Text>
|
||||
<View className="mt-3 flex-row gap-3">
|
||||
<Pressable
|
||||
className={active ? 'flex-1 rounded-[16px] bg-[#d7eee4] px-3 py-2.5' : !enabled ? 'flex-1 rounded-[16px] bg-[#d8d1c4] px-3 py-2.5' : 'flex-1 rounded-[16px] bg-[#1d5f55] px-3 py-2.5'}
|
||||
onPress={async () => {
|
||||
await switchAdminAccount(account.id);
|
||||
queryClient.clear();
|
||||
router.replace('/monitor');
|
||||
}}
|
||||
disabled={!enabled}
|
||||
>
|
||||
<Text className={active ? 'text-center text-xs font-semibold text-[#1d5f55]' : !enabled ? 'text-center text-xs font-semibold text-[#7d7468]' : 'text-center text-xs font-semibold text-white'}>
|
||||
{active ? '使用中' : '切换账号'}
|
||||
</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
className="rounded-[16px] bg-[#e7dfcf] px-4 py-2.5"
|
||||
onPress={async () => {
|
||||
await setAdminAccountEnabled(account.id, account.enabled === false);
|
||||
}}
|
||||
>
|
||||
<Text className="text-center text-xs font-semibold text-[#4e463e]">{enabled ? '禁用' : '启用'}</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
className="rounded-[16px] bg-[#e7dfcf] px-4 py-2.5"
|
||||
onPress={async () => {
|
||||
await removeAdminAccount(account.id);
|
||||
}}
|
||||
>
|
||||
<Text className="text-center text-xs font-semibold text-[#7a3d31]">删除</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
<SafeAreaView style={{ flex: 1, backgroundColor: colors.page }}>
|
||||
<ScrollView contentContainerStyle={{ flexGrow: 1, paddingHorizontal: 20, paddingVertical: 24 }} keyboardShouldPersistTaps="handled">
|
||||
<View style={{ flex: 1, justifyContent: 'center', gap: 20 }}>
|
||||
<View style={{ gap: 8 }}>
|
||||
<Text style={{ fontSize: 34, fontWeight: '800', color: colors.text }}>管理员入口</Text>
|
||||
<Text style={{ fontSize: 14, lineHeight: 22, color: colors.subtext }}>
|
||||
首次进入请填写服务器地址和 Admin Key。连接成功后即可进入应用,并在“服务器”页管理多个服务器。
|
||||
</Text>
|
||||
</View>
|
||||
</ListCard>
|
||||
) : null}
|
||||
|
||||
<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>
|
||||
<View style={{ backgroundColor: colors.card, borderRadius: 22, padding: 18, gap: 16 }}>
|
||||
<View>
|
||||
<Text style={{ marginBottom: 8, fontSize: 12, color: colors.subtext }}>服务器地址</Text>
|
||||
<Controller
|
||||
control={control}
|
||||
name="baseUrl"
|
||||
render={({ field: { onChange, value } }) => (
|
||||
<TextInput
|
||||
value={value}
|
||||
onChangeText={(text) => {
|
||||
if (connectionState !== 'idle') {
|
||||
setConnectionState('idle');
|
||||
setConnectionMessage('');
|
||||
}
|
||||
onChange(text);
|
||||
}}
|
||||
placeholder="例如:https://api.example.com"
|
||||
placeholderTextColor="#9b9081"
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
style={{ backgroundColor: colors.mutedCard, borderRadius: 16, paddingHorizontal: 16, paddingVertical: 14, fontSize: 16, color: colors.text }}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<ListCard title="Admin Token" meta="直连上游时必填;使用本地代理可留空" 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>
|
||||
<View>
|
||||
<Text style={{ marginBottom: 8, fontSize: 12, color: colors.subtext }}>Admin Key</Text>
|
||||
<Controller
|
||||
control={control}
|
||||
name="adminApiKey"
|
||||
render={({ field: { onChange, value } }) => (
|
||||
<TextInput
|
||||
value={value}
|
||||
onChangeText={(text) => {
|
||||
if (connectionState !== 'idle') {
|
||||
setConnectionState('idle');
|
||||
setConnectionMessage('');
|
||||
}
|
||||
onChange(text);
|
||||
}}
|
||||
placeholder="admin-xxxxxxxx"
|
||||
placeholderTextColor="#9b9081"
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
style={{ backgroundColor: colors.mutedCard, borderRadius: 16, paddingHorizontal: 16, paddingVertical: 14, fontSize: 16, color: colors.text }}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</View>
|
||||
|
||||
{(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>
|
||||
{formState.errors.baseUrl || formState.errors.adminApiKey ? (
|
||||
<View style={{ borderRadius: 14, backgroundColor: colors.dangerBg, paddingHorizontal: 14, paddingVertical: 12 }}>
|
||||
<Text style={{ color: colors.danger, fontSize: 14 }}>{formState.errors.baseUrl?.message || formState.errors.adminApiKey?.message}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{connectionMessage ? (
|
||||
<View style={{ borderRadius: 14, backgroundColor: colors.dangerBg, paddingHorizontal: 14, paddingVertical: 12 }}>
|
||||
<Text style={{ color: colors.danger, fontSize: 14 }}>{connectionMessage}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
<Pressable
|
||||
style={{ backgroundColor: connectionState === 'checking' ? '#7ca89f' : colors.primary, borderRadius: 18, paddingVertical: 15, alignItems: 'center' }}
|
||||
disabled={connectionState === 'checking'}
|
||||
onPress={handleSubmit(async (values) => {
|
||||
setConnectionState('checking');
|
||||
setConnectionMessage('正在验证服务器连接...');
|
||||
|
||||
try {
|
||||
await saveAdminConfig(values);
|
||||
queryClient.clear();
|
||||
await queryClient.fetchQuery({ queryKey: ['admin-settings'], queryFn: getAdminSettings });
|
||||
await queryClient.prefetchQuery({ queryKey: ['monitor-stats'], queryFn: getDashboardStats });
|
||||
router.replace('/monitor');
|
||||
} catch (error) {
|
||||
setConnectionState('error');
|
||||
setConnectionMessage(getConnectionErrorMessage(error));
|
||||
}
|
||||
})}
|
||||
>
|
||||
<Text style={{ color: '#fff', fontSize: 15, fontWeight: '700' }}>{connectionState === 'checking' ? '连接中...' : '进入应用'}</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
<Pressable
|
||||
className="rounded-[20px] bg-[#1d5f55] px-4 py-4"
|
||||
onPress={handleSubmit(async (values) => {
|
||||
await saveAdminConfig(values);
|
||||
queryClient.clear();
|
||||
router.replace('/monitor');
|
||||
})}
|
||||
>
|
||||
<Text className="text-center text-sm font-semibold tracking-[1.2px] text-white">
|
||||
{config.saving ? '登录中...' : '进入管理台'}
|
||||
</Text>
|
||||
</Pressable>
|
||||
</ScreenShell>
|
||||
</ScrollView>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,44 +1,252 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import * as Clipboard from 'expo-clipboard';
|
||||
import { ArrowLeftRight, ChevronLeft, Copy, KeyRound, Search, Wallet } from 'lucide-react-native';
|
||||
import { router, useLocalSearchParams } from 'expo-router';
|
||||
import { Stack, useLocalSearchParams } from 'expo-router';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Controller, useForm } from 'react-hook-form';
|
||||
import { Pressable, Text, TextInput, View } from 'react-native';
|
||||
import { z } from 'zod';
|
||||
import { Pressable, ScrollView, Text, TextInput, View } from 'react-native';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
|
||||
import { DetailRow } from '@/src/components/detail-row';
|
||||
import { ListCard } from '@/src/components/list-card';
|
||||
import { formatDisplayTime } from '@/src/lib/formatters';
|
||||
import { ScreenShell } from '@/src/components/screen-shell';
|
||||
import { useDebouncedValue } from '@/src/hooks/use-debounced-value';
|
||||
import { getUser, getUserUsage, listUserApiKeys, updateUserBalance } from '@/src/services/admin';
|
||||
import type { BalanceOperation } from '@/src/types/admin';
|
||||
import { LineTrendChart } from '@/src/components/line-trend-chart';
|
||||
import { getDashboardSnapshot, getUsageStats, getUser, listUserApiKeys, updateUserBalance } from '@/src/services/admin';
|
||||
import type { AdminApiKey, BalanceOperation } from '@/src/types/admin';
|
||||
|
||||
const schema = z.object({
|
||||
amount: z.string().min(1, '请输入金额'),
|
||||
notes: z.string().optional(),
|
||||
});
|
||||
const colors = {
|
||||
page: '#f4efe4',
|
||||
card: '#fbf8f2',
|
||||
text: '#16181a',
|
||||
subtext: '#6f665c',
|
||||
border: '#e7dfcf',
|
||||
primary: '#1d5f55',
|
||||
dark: '#1b1d1f',
|
||||
errorBg: '#f7e1d6',
|
||||
errorText: '#a4512b',
|
||||
muted: '#f7f1e6',
|
||||
};
|
||||
|
||||
type FormValues = z.infer<typeof schema>;
|
||||
type RangeKey = '24h' | '7d' | '30d';
|
||||
|
||||
const RANGE_OPTIONS: Array<{ key: RangeKey; label: string }> = [
|
||||
{ key: '24h', label: '24H' },
|
||||
{ key: '7d', label: '7D' },
|
||||
{ key: '30d', label: '30D' },
|
||||
];
|
||||
|
||||
function getDateRange(rangeKey: RangeKey) {
|
||||
const end = new Date();
|
||||
const start = new Date();
|
||||
|
||||
if (rangeKey === '24h') {
|
||||
start.setHours(end.getHours() - 23, 0, 0, 0);
|
||||
} else if (rangeKey === '30d') {
|
||||
start.setDate(end.getDate() - 29);
|
||||
} else {
|
||||
start.setDate(end.getDate() - 6);
|
||||
}
|
||||
|
||||
const toDate = (value: Date) => value.toISOString().slice(0, 10);
|
||||
|
||||
return {
|
||||
start_date: toDate(start),
|
||||
end_date: toDate(end),
|
||||
granularity: rangeKey === '24h' ? ('hour' as const) : ('day' as const),
|
||||
};
|
||||
}
|
||||
|
||||
function getErrorMessage(error: unknown) {
|
||||
if (error instanceof Error && error.message) {
|
||||
switch (error.message) {
|
||||
case 'BASE_URL_REQUIRED':
|
||||
return '请先到服务器页填写服务地址。';
|
||||
case 'ADMIN_API_KEY_REQUIRED':
|
||||
return '请先到服务器页填写 Admin Token。';
|
||||
default:
|
||||
return error.message;
|
||||
}
|
||||
}
|
||||
|
||||
return '加载失败,请稍后重试。';
|
||||
}
|
||||
|
||||
function formatMoney(value?: number | null) {
|
||||
return `$${Number(value ?? 0).toFixed(2)}`;
|
||||
}
|
||||
|
||||
function formatUsageCost(stats?: { total_account_cost?: number | null; total_actual_cost?: number | null; total_cost?: number | null }) {
|
||||
const value = Number(stats?.total_account_cost ?? stats?.total_actual_cost ?? stats?.total_cost ?? 0);
|
||||
return `$${value.toFixed(4)}`;
|
||||
}
|
||||
|
||||
function formatTokenValue(value?: number | null) {
|
||||
const number = Number(value ?? 0);
|
||||
if (number >= 1_000_000_000) return `${(number / 1_000_000_000).toFixed(2)}B`;
|
||||
if (number >= 1_000_000) return `${(number / 1_000_000).toFixed(2)}M`;
|
||||
if (number >= 1_000) return `${(number / 1_000).toFixed(2)}K`;
|
||||
return new Intl.NumberFormat('en-US').format(number);
|
||||
}
|
||||
|
||||
|
||||
function formatQuota(quotaUsed?: number | null, quota?: number | null) {
|
||||
const used = Number(quotaUsed ?? 0);
|
||||
const limit = Number(quota ?? 0);
|
||||
|
||||
if (limit <= 0) {
|
||||
return '∞';
|
||||
}
|
||||
|
||||
return `${used} / ${limit}`;
|
||||
}
|
||||
|
||||
function formatTime(value?: string | null) {
|
||||
if (!value) return '--';
|
||||
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return value;
|
||||
|
||||
const year = date.getFullYear();
|
||||
const month = `${date.getMonth() + 1}`.padStart(2, '0');
|
||||
const day = `${date.getDate()}`.padStart(2, '0');
|
||||
const hours = `${date.getHours()}`.padStart(2, '0');
|
||||
const minutes = `${date.getMinutes()}`.padStart(2, '0');
|
||||
|
||||
return `${year}-${month}-${day} ${hours}:${minutes}`;
|
||||
}
|
||||
|
||||
function Section({ title, children }: { title: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
backgroundColor: colors.card,
|
||||
borderRadius: 16,
|
||||
padding: 16,
|
||||
marginBottom: 12,
|
||||
borderWidth: 1,
|
||||
borderColor: colors.border,
|
||||
}}
|
||||
>
|
||||
<Text style={{ fontSize: 18, fontWeight: '700', color: colors.text }}>{title}</Text>
|
||||
<View style={{ marginTop: 12 }}>{children}</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function GridField({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
width: '48.5%',
|
||||
backgroundColor: colors.muted,
|
||||
borderRadius: 12,
|
||||
paddingHorizontal: 12,
|
||||
paddingVertical: 12,
|
||||
borderWidth: 1,
|
||||
borderColor: colors.border,
|
||||
}}
|
||||
>
|
||||
<Text style={{ fontSize: 12, color: colors.subtext }}>{label}</Text>
|
||||
<Text style={{ marginTop: 6, fontSize: 15, fontWeight: '600', color: colors.text }}>{value}</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function MetricCard({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
flex: 1,
|
||||
backgroundColor: colors.muted,
|
||||
borderRadius: 12,
|
||||
paddingHorizontal: 12,
|
||||
paddingVertical: 12,
|
||||
borderWidth: 1,
|
||||
borderColor: colors.border,
|
||||
}}
|
||||
>
|
||||
<Text style={{ fontSize: 12, color: colors.subtext }}>{label}</Text>
|
||||
<Text style={{ marginTop: 6, fontSize: 16, fontWeight: '700', color: colors.text }}>{value}</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function StatusBadge({ text }: { text: string }) {
|
||||
const normalized = text.toLowerCase();
|
||||
const backgroundColor = normalized === 'active' ? '#dff4ea' : normalized === 'inactive' ? '#ece5da' : '#f7e1d6';
|
||||
const color = normalized === 'active' ? '#17663f' : normalized === 'inactive' ? '#6f665c' : '#a4512b';
|
||||
|
||||
return (
|
||||
<View style={{ backgroundColor, borderRadius: 999, paddingHorizontal: 10, paddingVertical: 6 }}>
|
||||
<Text style={{ fontSize: 12, fontWeight: '700', color }}>{text}</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function CopyInlineButton({ copied, onPress }: { copied: boolean; onPress: () => void }) {
|
||||
return (
|
||||
<Pressable
|
||||
onPress={onPress}
|
||||
style={{
|
||||
marginLeft: 8,
|
||||
backgroundColor: copied ? '#dff4ea' : '#e7dfcf',
|
||||
borderRadius: 999,
|
||||
paddingHorizontal: 10,
|
||||
paddingVertical: 6,
|
||||
}}
|
||||
>
|
||||
<Text style={{ fontSize: 11, fontWeight: '700', color: copied ? '#17663f' : '#4e463e' }}>{copied ? '已复制' : '复制'}</Text>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
function KeyItem({ item, copied, onCopy }: { item: AdminApiKey; copied: boolean; onCopy: () => void }) {
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
backgroundColor: colors.muted,
|
||||
borderRadius: 14,
|
||||
padding: 12,
|
||||
borderWidth: 1,
|
||||
borderColor: colors.border,
|
||||
marginBottom: 10,
|
||||
}}
|
||||
>
|
||||
<View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
|
||||
<View style={{ flex: 1 }}>
|
||||
<View style={{ flexDirection: 'row', alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<Text style={{ fontSize: 15, fontWeight: '700', color: colors.text }}>{item.name || `Key #${item.id}`}</Text>
|
||||
<CopyInlineButton copied={copied} onPress={onCopy} />
|
||||
</View>
|
||||
<Text style={{ marginTop: 4, fontSize: 12, color: colors.subtext }}>{item.group?.name || '未分组'}</Text>
|
||||
</View>
|
||||
<StatusBadge text={item.status || '--'} />
|
||||
</View>
|
||||
|
||||
<Text style={{ marginTop: 10, fontSize: 12, lineHeight: 18, color: colors.text }}>{item.key || '--'}</Text>
|
||||
|
||||
<View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12, marginTop: 12 }}>
|
||||
<View style={{ flex: 1 }}>
|
||||
<Text style={{ fontSize: 11, color: colors.subtext }}>已用额度</Text>
|
||||
<Text style={{ marginTop: 4, fontSize: 16, fontWeight: '700', color: colors.text }}>{formatQuota(item.quota_used, item.quota)}</Text>
|
||||
</View>
|
||||
<View style={{ flex: 1, alignItems: 'flex-end' }}>
|
||||
<Text style={{ fontSize: 11, color: colors.subtext }}>最后使用时间</Text>
|
||||
<Text style={{ marginTop: 4, fontSize: 13, color: colors.subtext }}>{formatTime(item.last_used_at || item.updated_at || item.created_at)}</Text>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export default function UserDetailScreen() {
|
||||
const { id } = useLocalSearchParams<{ id: string }>();
|
||||
const userId = Number(id);
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const [operation, setOperation] = useState<BalanceOperation>('add');
|
||||
const [keySearchText, setKeySearchText] = useState('');
|
||||
const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'inactive'>('all');
|
||||
const [amount, setAmount] = useState('10');
|
||||
const [notes, setNotes] = useState('');
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const [copiedKeyId, setCopiedKeyId] = useState<number | null>(null);
|
||||
const keySearch = useDebouncedValue(keySearchText.trim().toLowerCase(), 250);
|
||||
const { control, handleSubmit, reset, formState } = useForm<FormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: {
|
||||
amount: '10',
|
||||
notes: '',
|
||||
},
|
||||
});
|
||||
const [rangeKey, setRangeKey] = useState<RangeKey>('7d');
|
||||
const range = getDateRange(rangeKey);
|
||||
|
||||
const userQuery = useQuery({
|
||||
queryKey: ['user', userId],
|
||||
@@ -46,199 +254,329 @@ export default function UserDetailScreen() {
|
||||
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 usageStatsQuery = useQuery({
|
||||
queryKey: ['usage-stats', 'user', userId, rangeKey, range.start_date, range.end_date],
|
||||
queryFn: () => getUsageStats({ ...range, user_id: userId }),
|
||||
enabled: Number.isFinite(userId),
|
||||
});
|
||||
|
||||
const usageSnapshotQuery = useQuery({
|
||||
queryKey: ['usage-snapshot', 'user', userId, rangeKey, range.start_date, range.end_date, range.granularity],
|
||||
queryFn: () =>
|
||||
getDashboardSnapshot({
|
||||
...range,
|
||||
user_id: userId,
|
||||
include_stats: false,
|
||||
include_trend: true,
|
||||
include_model_stats: false,
|
||||
include_group_stats: false,
|
||||
include_users_trend: false,
|
||||
}),
|
||||
enabled: Number.isFinite(userId),
|
||||
});
|
||||
;
|
||||
;
|
||||
|
||||
const balanceMutation = useMutation({
|
||||
mutationFn: (values: FormValues & { operation: BalanceOperation }) =>
|
||||
mutationFn: (payload: { amount: number; notes?: string; operation: BalanceOperation }) =>
|
||||
updateUserBalance(userId, {
|
||||
balance: Number(values.amount),
|
||||
operation: values.operation,
|
||||
notes: values.notes,
|
||||
balance: payload.amount,
|
||||
notes: payload.notes,
|
||||
operation: payload.operation,
|
||||
}),
|
||||
onSuccess: () => {
|
||||
setFormError(null);
|
||||
setAmount('10');
|
||||
setNotes('');
|
||||
queryClient.invalidateQueries({ queryKey: ['user', userId] });
|
||||
queryClient.invalidateQueries({ queryKey: ['users'] });
|
||||
reset({ amount: '10', notes: '' });
|
||||
},
|
||||
onError: (error) => setFormError(getErrorMessage(error)),
|
||||
});
|
||||
|
||||
const user = userQuery.data;
|
||||
const usage = usageQuery.data;
|
||||
const apiKeys = apiKeysQuery.data?.items ?? [];
|
||||
const filteredApiKeys = useMemo(
|
||||
() =>
|
||||
apiKeys.filter((item) => {
|
||||
const matchesStatus = statusFilter === 'all' ? true : item.status === statusFilter;
|
||||
const matchesSearch = !keySearch
|
||||
? true
|
||||
: [item.name, item.key, item.group?.name]
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
.toLowerCase()
|
||||
.includes(keySearch);
|
||||
|
||||
return matchesStatus && matchesSearch;
|
||||
}),
|
||||
[apiKeys, keySearch, statusFilter]
|
||||
);
|
||||
const filteredApiKeys = useMemo(() => {
|
||||
const keyword = searchText.trim().toLowerCase();
|
||||
|
||||
function maskKey(value: string) {
|
||||
if (!value || value.length < 16) {
|
||||
return value;
|
||||
return apiKeys.filter((item) => {
|
||||
const haystack = [item.name, item.key, item.group?.name].filter(Boolean).join(' ').toLowerCase();
|
||||
return keyword ? haystack.includes(keyword) : true;
|
||||
});
|
||||
}, [apiKeys, searchText]);
|
||||
const trendPoints = (usageSnapshotQuery.data?.trend ?? []).map((item) => ({
|
||||
label: rangeKey === '24h' ? item.date.slice(11, 13) : item.date.slice(5, 10),
|
||||
value: item.total_tokens,
|
||||
}));
|
||||
|
||||
function submitBalance() {
|
||||
const numericAmount = Number(amount);
|
||||
|
||||
if (!amount.trim()) {
|
||||
setFormError('请输入金额。');
|
||||
return;
|
||||
}
|
||||
|
||||
return `${value.slice(0, 8)}••••••${value.slice(-8)}`;
|
||||
if (!Number.isFinite(numericAmount) || numericAmount < 0) {
|
||||
setFormError('金额格式不正确。');
|
||||
return;
|
||||
}
|
||||
|
||||
balanceMutation.mutate({
|
||||
amount: numericAmount,
|
||||
notes: notes.trim() || undefined,
|
||||
operation,
|
||||
});
|
||||
}
|
||||
|
||||
async function copyKey(keyId: number, value: string) {
|
||||
await Clipboard.setStringAsync(value);
|
||||
setCopiedKeyId(keyId);
|
||||
setTimeout(() => setCopiedKeyId((current) => (current === keyId ? null : current)), 1600);
|
||||
async function copyKey(item: AdminApiKey) {
|
||||
await Clipboard.setStringAsync(item.key || '');
|
||||
setCopiedKeyId(item.id);
|
||||
setTimeout(() => {
|
||||
setCopiedKeyId((current) => (current === item.id ? null : current));
|
||||
}, 1500);
|
||||
}
|
||||
|
||||
return (
|
||||
<ScreenShell
|
||||
title={user?.username || user?.email || '用户详情'}
|
||||
subtitle=""
|
||||
titleAside={<Text className="text-[11px] text-[#a2988a]">用户余额、用量与密钥概览。</Text>}
|
||||
variant="minimal"
|
||||
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={formatDisplayTime(user?.updated_at)} />
|
||||
</ListCard>
|
||||
<>
|
||||
<Stack.Screen options={{ title: user?.email || '用户详情' }} />
|
||||
<SafeAreaView edges={['bottom']} style={{ flex: 1, backgroundColor: colors.page }}>
|
||||
<ScrollView style={{ flex: 1 }} contentContainerStyle={{ padding: 16, paddingBottom: 40 }}>
|
||||
{userQuery.isLoading ? (
|
||||
<Section title="状态">
|
||||
<Text style={{ color: colors.subtext }}>正在加载用户详情...</Text>
|
||||
</Section>
|
||||
) : null}
|
||||
|
||||
<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
|
||||
defaultValue=""
|
||||
onChangeText={setKeySearchText}
|
||||
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>
|
||||
{userQuery.error ? (
|
||||
<Section title="状态">
|
||||
<View style={{ backgroundColor: colors.errorBg, borderRadius: 12, padding: 12 }}>
|
||||
<Text style={{ color: colors.errorText, fontWeight: '700' }}>用户信息加载失败</Text>
|
||||
<Text style={{ marginTop: 6, color: colors.errorText }}>{getErrorMessage(userQuery.error)}</Text>
|
||||
</View>
|
||||
<View className="mt-2 flex-row items-center gap-2">
|
||||
<Text className="flex-1 text-xs text-[#7d7468]">{maskKey(item.key)}</Text>
|
||||
<Pressable
|
||||
className="rounded-full bg-[#e7dfcf] p-2"
|
||||
onPress={() => copyKey(item.id, item.key)}
|
||||
</Section>
|
||||
) : null}
|
||||
|
||||
{user ? (
|
||||
<Section title="基础信息">
|
||||
<View style={{ flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-between', rowGap: 10 }}>
|
||||
<View
|
||||
style={{
|
||||
width: '48.5%',
|
||||
justifyContent: 'center',
|
||||
paddingHorizontal: 4,
|
||||
paddingVertical: 8,
|
||||
}}
|
||||
>
|
||||
<Copy color="#4e463e" size={14} />
|
||||
</Pressable>
|
||||
<Text style={{ fontSize: 11, color: colors.subtext }}>邮箱</Text>
|
||||
<Text style={{ marginTop: 4, fontSize: 13, color: colors.subtext }}>{user.email || '--'}</Text>
|
||||
</View>
|
||||
<GridField label="用户名" value={user.username || '--'} />
|
||||
<GridField label="余额" value={formatMoney(user.balance)} />
|
||||
<View
|
||||
style={{
|
||||
width: '48.5%',
|
||||
justifyContent: 'center',
|
||||
paddingHorizontal: 4,
|
||||
paddingVertical: 8,
|
||||
}}
|
||||
>
|
||||
<Text style={{ fontSize: 11, color: colors.subtext }}>最后使用时间</Text>
|
||||
<Text style={{ marginTop: 4, fontSize: 13, color: colors.subtext }}>{formatTime(user.last_used_at || user.updated_at || user.created_at)}</Text>
|
||||
</View>
|
||||
</View>
|
||||
<Text className="mt-2 text-xs text-[#7d7468]">
|
||||
{copiedKeyId === item.id ? '已复制到剪贴板' : `最近使用 ${formatDisplayTime(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>
|
||||
</Section>
|
||||
) : null}
|
||||
|
||||
<Section title="总用量">
|
||||
<View style={{ flexDirection: 'row', gap: 8, marginBottom: 12 }}>
|
||||
{RANGE_OPTIONS.map((item) => {
|
||||
const active = item.key === rangeKey;
|
||||
return (
|
||||
<Pressable
|
||||
key={item.key}
|
||||
onPress={() => setRangeKey(item.key)}
|
||||
style={{
|
||||
backgroundColor: active ? colors.primary : colors.muted,
|
||||
borderRadius: 999,
|
||||
paddingHorizontal: 12,
|
||||
paddingVertical: 8,
|
||||
borderWidth: 1,
|
||||
borderColor: active ? colors.primary : colors.border,
|
||||
}}
|
||||
>
|
||||
<Text style={{ color: active ? '#fff' : colors.text, fontSize: 12, fontWeight: '700' }}>{item.label}</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</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>
|
||||
<View style={{ flexDirection: 'row', gap: 8 }}>
|
||||
<MetricCard label="请求" value={formatTokenValue(usageStatsQuery.data?.total_requests)} />
|
||||
<MetricCard label="Token" value={formatTokenValue(usageStatsQuery.data?.total_tokens)} />
|
||||
<MetricCard label="成本" value={formatUsageCost(usageStatsQuery.data)} />
|
||||
</View>
|
||||
|
||||
{usageStatsQuery.data ? (
|
||||
<Text style={{ marginTop: 10, fontSize: 12, color: colors.subtext }}>
|
||||
输入 {formatTokenValue(usageStatsQuery.data.total_input_tokens)} · 输出 {formatTokenValue(usageStatsQuery.data.total_output_tokens)}
|
||||
</Text>
|
||||
) : null}
|
||||
|
||||
{usageStatsQuery.isLoading ? <Text style={{ marginTop: 12, color: colors.subtext }}>正在加载用量统计...</Text> : null}
|
||||
|
||||
{usageStatsQuery.error ? (
|
||||
<View style={{ marginTop: 12, backgroundColor: colors.errorBg, borderRadius: 12, padding: 12 }}>
|
||||
<Text style={{ color: colors.errorText, fontWeight: '700' }}>用量统计加载失败</Text>
|
||||
<Text style={{ marginTop: 6, color: colors.errorText }}>{getErrorMessage(usageStatsQuery.error)}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{!usageSnapshotQuery.isLoading && trendPoints.length > 1 ? (
|
||||
<View style={{ marginTop: 14 }}>
|
||||
<LineTrendChart
|
||||
title="用量趋势"
|
||||
subtitle={`${range.start_date} 到 ${range.end_date}`}
|
||||
points={trendPoints}
|
||||
color="#1d5f55"
|
||||
formatValue={(value) => formatTokenValue(value)}
|
||||
compact
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{usageSnapshotQuery.isLoading ? <Text style={{ marginTop: 12, color: colors.subtext }}>正在加载趋势图...</Text> : null}
|
||||
|
||||
{usageSnapshotQuery.error ? (
|
||||
<View style={{ marginTop: 12, backgroundColor: colors.errorBg, borderRadius: 12, padding: 12 }}>
|
||||
<Text style={{ color: colors.errorText, fontWeight: '700' }}>趋势加载失败</Text>
|
||||
<Text style={{ marginTop: 6, color: colors.errorText }}>{getErrorMessage(usageSnapshotQuery.error)}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</Section>
|
||||
|
||||
<Section title="API Keys">
|
||||
<TextInput
|
||||
value={searchText}
|
||||
onChangeText={setSearchText}
|
||||
placeholder="搜索名称 / Key / 分组"
|
||||
placeholderTextColor="#9a9082"
|
||||
style={{
|
||||
backgroundColor: colors.muted,
|
||||
borderWidth: 1,
|
||||
borderColor: colors.border,
|
||||
borderRadius: 12,
|
||||
paddingHorizontal: 12,
|
||||
paddingVertical: 12,
|
||||
color: colors.text,
|
||||
marginBottom: 10,
|
||||
}}
|
||||
/>
|
||||
|
||||
{apiKeysQuery.isLoading ? <Text style={{ color: colors.subtext }}>正在加载 API Keys...</Text> : null}
|
||||
|
||||
{apiKeysQuery.error ? (
|
||||
<View style={{ backgroundColor: colors.errorBg, borderRadius: 12, padding: 12 }}>
|
||||
<Text style={{ color: colors.errorText, fontWeight: '700' }}>API Keys 加载失败</Text>
|
||||
<Text style={{ marginTop: 6, color: colors.errorText }}>{getErrorMessage(apiKeysQuery.error)}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{!apiKeysQuery.isLoading && !apiKeysQuery.error ? (
|
||||
filteredApiKeys.length > 0 ? (
|
||||
<View>
|
||||
{filteredApiKeys.map((item) => (
|
||||
<KeyItem key={item.id} item={item} copied={copiedKeyId === item.id} onCopy={() => copyKey(item)} />
|
||||
))}
|
||||
</View>
|
||||
) : (
|
||||
<Text style={{ color: colors.subtext }}>当前筛选条件下没有 Key。</Text>
|
||||
)
|
||||
) : null}
|
||||
</Section>
|
||||
|
||||
<Section title="余额操作">
|
||||
<View style={{ flexDirection: 'row', gap: 8, marginBottom: 12 }}>
|
||||
{([
|
||||
{ label: '充值', value: 'add' },
|
||||
{ label: '扣减', value: 'subtract' },
|
||||
{ label: '设为', value: 'set' },
|
||||
] as const).map((item) => {
|
||||
const active = operation === item.value;
|
||||
return (
|
||||
<Pressable
|
||||
key={item.value}
|
||||
onPress={() => setOperation(item.value)}
|
||||
style={{
|
||||
flex: 1,
|
||||
backgroundColor: active ? colors.primary : colors.muted,
|
||||
borderRadius: 12,
|
||||
paddingVertical: 12,
|
||||
alignItems: 'center',
|
||||
borderWidth: 1,
|
||||
borderColor: active ? colors.primary : colors.border,
|
||||
}}
|
||||
>
|
||||
<Text style={{ color: active ? '#fff' : colors.text, fontWeight: '700' }}>{item.label}</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
|
||||
<TextInput
|
||||
value={amount}
|
||||
onChangeText={setAmount}
|
||||
placeholder="输入金额,例如 10"
|
||||
placeholderTextColor="#9a9082"
|
||||
keyboardType="decimal-pad"
|
||||
style={{
|
||||
backgroundColor: colors.muted,
|
||||
borderWidth: 1,
|
||||
borderColor: colors.border,
|
||||
borderRadius: 12,
|
||||
paddingHorizontal: 12,
|
||||
paddingVertical: 12,
|
||||
color: colors.text,
|
||||
marginBottom: 10,
|
||||
}}
|
||||
/>
|
||||
|
||||
<TextInput
|
||||
value={notes}
|
||||
onChangeText={setNotes}
|
||||
placeholder="备注(可选)"
|
||||
placeholderTextColor="#9a9082"
|
||||
style={{
|
||||
backgroundColor: colors.muted,
|
||||
borderWidth: 1,
|
||||
borderColor: colors.border,
|
||||
borderRadius: 12,
|
||||
paddingHorizontal: 12,
|
||||
paddingVertical: 12,
|
||||
color: colors.text,
|
||||
marginBottom: 10,
|
||||
}}
|
||||
/>
|
||||
|
||||
{formError ? (
|
||||
<View style={{ backgroundColor: colors.errorBg, borderRadius: 12, padding: 12, marginBottom: 10 }}>
|
||||
<Text style={{ color: colors.errorText }}>{formError}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
<Pressable onPress={submitBalance} style={{ backgroundColor: colors.dark, borderRadius: 12, paddingVertical: 14, alignItems: 'center' }}>
|
||||
<Text style={{ color: '#fff', fontWeight: '700' }}>{balanceMutation.isPending ? '提交中...' : '确认提交'}</Text>
|
||||
</Pressable>
|
||||
</Section>
|
||||
</ScrollView>
|
||||
</SafeAreaView>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user