mirror of
https://gitee.com/wanwujie/sub2api-mobile
synced 2026-04-02 22:42:14 +08:00
feat: refine expo admin mobile flows
This commit is contained in:
15
app.json
15
app.json
@@ -7,12 +7,6 @@
|
|||||||
"orientation": "portrait",
|
"orientation": "portrait",
|
||||||
"icon": "./icons/ios/AppIcon.appiconset/icon-1024.png",
|
"icon": "./icons/ios/AppIcon.appiconset/icon-1024.png",
|
||||||
"userInterfaceStyle": "light",
|
"userInterfaceStyle": "light",
|
||||||
"runtimeVersion": {
|
|
||||||
"policy": "appVersion"
|
|
||||||
},
|
|
||||||
"updates": {
|
|
||||||
"url": "https://u.expo.dev/acaedd05-5a2a-4843-a648-e025c08ce7b3"
|
|
||||||
},
|
|
||||||
"splash": {
|
"splash": {
|
||||||
"image": "./assets/splash-icon.png",
|
"image": "./assets/splash-icon.png",
|
||||||
"resizeMode": "contain",
|
"resizeMode": "contain",
|
||||||
@@ -47,6 +41,13 @@
|
|||||||
"eas": {
|
"eas": {
|
||||||
"projectId": "acaedd05-5a2a-4843-a648-e025c08ce7b3"
|
"projectId": "acaedd05-5a2a-4843-a648-e025c08ce7b3"
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
"runtimeVersion": {
|
||||||
|
"policy": "appVersion"
|
||||||
|
},
|
||||||
|
"updates": {
|
||||||
|
"url": "https://u.expo.dev/acaedd05-5a2a-4843-a648-e025c08ce7b3"
|
||||||
|
},
|
||||||
|
"scheme": "sub2apimobile"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Tabs } from 'expo-router';
|
import { Redirect, Tabs } from 'expo-router';
|
||||||
import { ChartNoAxesCombined, Settings2, Users } from 'lucide-react-native';
|
import { ChartNoAxesCombined, Settings2, Users } from 'lucide-react-native';
|
||||||
|
|
||||||
import { adminConfigState } from '@/src/store/admin-config';
|
import { adminConfigState } from '@/src/store/admin-config';
|
||||||
@@ -9,6 +9,10 @@ export default function TabsLayout() {
|
|||||||
const config = useSnapshot(adminConfigState);
|
const config = useSnapshot(adminConfigState);
|
||||||
const hasAccount = Boolean(config.baseUrl.trim());
|
const hasAccount = Boolean(config.baseUrl.trim());
|
||||||
|
|
||||||
|
if (!hasAccount) {
|
||||||
|
return <Redirect href="/login" />;
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Tabs
|
<Tabs
|
||||||
initialRouteName={hasAccount ? 'monitor' : 'settings'}
|
initialRouteName={hasAccount ? 'monitor' : 'settings'}
|
||||||
@@ -53,7 +57,6 @@ export default function TabsLayout() {
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<Tabs.Screen name="groups" options={{ href: null }} />
|
<Tabs.Screen name="groups" options={{ href: null }} />
|
||||||
<Tabs.Screen name="keys" options={{ href: null }} />
|
|
||||||
<Tabs.Screen name="accounts" options={{ href: null }} />
|
<Tabs.Screen name="accounts" options={{ href: null }} />
|
||||||
</Tabs>
|
</Tabs>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -2,12 +2,13 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
|||||||
import { KeyRound, Search, ShieldCheck, ShieldOff } from 'lucide-react-native';
|
import { KeyRound, Search, ShieldCheck, ShieldOff } from 'lucide-react-native';
|
||||||
import { router } from 'expo-router';
|
import { router } from 'expo-router';
|
||||||
import { useCallback, useMemo, useState } from 'react';
|
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 { ListCard } from '@/src/components/list-card';
|
||||||
import { ScreenShell } from '@/src/components/screen-shell';
|
import { ScreenShell } from '@/src/components/screen-shell';
|
||||||
import { useDebouncedValue } from '@/src/hooks/use-debounced-value';
|
import { useDebouncedValue } from '@/src/hooks/use-debounced-value';
|
||||||
import { getAccount, getAccountTodayStats, getDashboardTrend, listAccounts, setAccountSchedulable, testAccount } from '@/src/services/admin';
|
import { getAccount, getAccountTodayStats, getDashboardTrend, listAccounts, setAccountSchedulable, testAccount } from '@/src/services/admin';
|
||||||
|
import type { AdminAccount } from '@/src/types/admin';
|
||||||
|
|
||||||
function getDateRange() {
|
function getDateRange() {
|
||||||
const end = new Date();
|
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() {
|
export default function AccountsScreen() {
|
||||||
const [searchText, setSearchText] = useState('');
|
const [searchText, setSearchText] = useState('');
|
||||||
|
const [filter, setFilter] = useState<'all' | 'schedulable' | 'paused' | 'error'>('all');
|
||||||
const keyword = useDebouncedValue(searchText.trim(), 300);
|
const keyword = useDebouncedValue(searchText.trim(), 300);
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const range = getDateRange();
|
const range = getDateRange();
|
||||||
@@ -40,95 +53,161 @@ export default function AccountsScreen() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const items = accountsQuery.data?.items ?? [];
|
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 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(
|
const listHeader = useMemo(
|
||||||
() => (
|
() => (
|
||||||
<View className="pb-4">
|
<View className="pb-4">
|
||||||
<View className="flex-row items-center rounded-[24px] bg-[#fbf8f2] px-4 py-3">
|
<View className="rounded-[24px] bg-[#fbf8f2] p-3">
|
||||||
<Search color="#7d7468" size={18} />
|
<View className="flex-row items-center rounded-[18px] bg-[#f1ece2] px-4 py-3">
|
||||||
<TextInput
|
<Search color="#7d7468" size={18} />
|
||||||
defaultValue=""
|
<TextInput
|
||||||
onChangeText={setSearchText}
|
defaultValue=""
|
||||||
placeholder="搜索 key 名称"
|
onChangeText={setSearchText}
|
||||||
placeholderTextColor="#9b9081"
|
placeholder="搜索账号名称 / 平台"
|
||||||
className="ml-3 flex-1 text-base text-[#16181a]"
|
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>
|
||||||
</View>
|
</View>
|
||||||
),
|
),
|
||||||
[]
|
[filter, summary.active, summary.errors, summary.paused, summary.total]
|
||||||
);
|
);
|
||||||
|
|
||||||
const renderItem = useCallback(
|
const renderItem = useCallback(
|
||||||
({ item: account }: { item: (typeof items)[number] }) => (
|
({ item: account }: { item: (typeof filteredItems)[number] }) => {
|
||||||
<Pressable
|
const isError = getAccountError(account);
|
||||||
onPress={() => {
|
const statusText = isError ? '异常' : account.schedulable ? '可调度' : '暂停调度';
|
||||||
void queryClient.prefetchQuery({ queryKey: ['account', account.id], queryFn: () => getAccount(account.id) });
|
const groupsText = account.groups?.map((group) => group.name).filter(Boolean).slice(0, 3).join(' · ');
|
||||||
void queryClient.prefetchQuery({ queryKey: ['account-today-stats', account.id], queryFn: () => getAccountTodayStats(account.id) });
|
|
||||||
void queryClient.prefetchQuery({
|
return (
|
||||||
queryKey: ['account-trend', account.id, range.start_date, range.end_date],
|
<Pressable
|
||||||
queryFn: () => getDashboardTrend({ ...range, granularity: 'day', account_id: account.id }),
|
onPress={() => {
|
||||||
});
|
void queryClient.prefetchQuery({ queryKey: ['account', account.id], queryFn: () => getAccount(account.id) });
|
||||||
router.push(`/accounts/${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],
|
||||||
<ListCard
|
queryFn: () => getDashboardTrend({ ...range, granularity: 'day', account_id: account.id }),
|
||||||
title={account.name}
|
});
|
||||||
meta={`${account.platform} · ${account.type} · 优先级 ${account.priority ?? 0}`}
|
router.push(`/accounts/${account.id}`);
|
||||||
badge={account.status || 'unknown'}
|
}}
|
||||||
icon={KeyRound}
|
|
||||||
>
|
>
|
||||||
<View className="flex-row items-center justify-between">
|
<ListCard
|
||||||
<View className="flex-row items-center gap-2">
|
title={account.name}
|
||||||
{account.schedulable ? <ShieldCheck color="#7d7468" size={14} /> : <ShieldOff color="#7d7468" size={14} />}
|
meta={`${account.platform} · ${account.type} · 优先级 ${account.priority ?? 0}`}
|
||||||
<Text className="text-sm text-[#7d7468]">{account.schedulable ? '可调度' : '暂停调度'}</Text>
|
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>
|
||||||
<View className="flex-row gap-2">
|
</ListCard>
|
||||||
<Pressable
|
</Pressable>
|
||||||
className="rounded-full bg-[#1b1d1f] px-4 py-2"
|
);
|
||||||
onPress={(event) => {
|
},
|
||||||
event.stopPropagation();
|
[filteredItems, queryClient, range.end_date, range.start_date, toggleMutation]
|
||||||
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]
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const emptyState = useMemo(
|
const emptyState = useMemo(
|
||||||
() => <ListCard title="暂无 Key" meta={errorMessage || '连上后这里会展示 key 列表。'} icon={KeyRound} />,
|
() => <ListCard title="暂无账号" meta={errorMessage || '连上后这里会展示账号列表。'} icon={KeyRound} />,
|
||||||
[errorMessage]
|
[errorMessage]
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ScreenShell
|
<ScreenShell
|
||||||
title="API 密钥"
|
title="账号管理"
|
||||||
subtitle=""
|
subtitle="看单账号状态、并发、最近使用和异常信息。"
|
||||||
titleAside={<Text className="text-[11px] text-[#a2988a]">查看密钥状态与调度能力。</Text>}
|
titleAside={<Text className="text-[11px] text-[#a2988a]">更接近网页后台的账号视图。</Text>}
|
||||||
variant="minimal"
|
variant="minimal"
|
||||||
scroll={false}
|
scroll={false}
|
||||||
>
|
>
|
||||||
<FlatList
|
<FlatList
|
||||||
data={items}
|
data={filteredItems}
|
||||||
renderItem={renderItem}
|
renderItem={renderItem}
|
||||||
keyExtractor={(item) => `${item.id}`}
|
keyExtractor={(item) => `${item.id}`}
|
||||||
showsVerticalScrollIndicator={false}
|
showsVerticalScrollIndicator={false}
|
||||||
|
refreshControl={<RefreshControl refreshing={accountsQuery.isRefetching} onRefresh={() => void accountsQuery.refetch()} tintColor="#1d5f55" />}
|
||||||
ListHeaderComponent={listHeader}
|
ListHeaderComponent={listHeader}
|
||||||
ListEmptyComponent={emptyState}
|
ListEmptyComponent={emptyState}
|
||||||
ItemSeparatorComponent={() => <View className="h-4" />}
|
ItemSeparatorComponent={() => <View className="h-4" />}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { useQuery } from '@tanstack/react-query';
|
import { useQuery } from '@tanstack/react-query';
|
||||||
import { FolderKanban, Layers3, Search } from 'lucide-react-native';
|
import { FolderKanban, Layers3, Search } from 'lucide-react-native';
|
||||||
import { useCallback, useMemo, useState } from 'react';
|
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 { ListCard } from '@/src/components/list-card';
|
||||||
import { ScreenShell } from '@/src/components/screen-shell';
|
import { ScreenShell } from '@/src/components/screen-shell';
|
||||||
@@ -72,6 +72,7 @@ export default function GroupsScreen() {
|
|||||||
renderItem={renderItem}
|
renderItem={renderItem}
|
||||||
keyExtractor={(item) => `${item.id}`}
|
keyExtractor={(item) => `${item.id}`}
|
||||||
showsVerticalScrollIndicator={false}
|
showsVerticalScrollIndicator={false}
|
||||||
|
refreshControl={<RefreshControl refreshing={groupsQuery.isRefetching} onRefresh={() => void groupsQuery.refetch()} tintColor="#1d5f55" />}
|
||||||
ListHeaderComponent={listHeader}
|
ListHeaderComponent={listHeader}
|
||||||
ListEmptyComponent={emptyState}
|
ListEmptyComponent={emptyState}
|
||||||
ItemSeparatorComponent={() => <View className="h-4" />}
|
ItemSeparatorComponent={() => <View className="h-4" />}
|
||||||
|
|||||||
@@ -1,5 +1,12 @@
|
|||||||
import { Redirect } from 'expo-router';
|
import { Redirect } from 'expo-router';
|
||||||
|
|
||||||
|
import { adminConfigState } from '@/src/store/admin-config';
|
||||||
|
|
||||||
|
const { useSnapshot } = require('valtio/react');
|
||||||
|
|
||||||
export default function IndexScreen() {
|
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 { 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 { 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 { BarChartCard } from '@/src/components/bar-chart-card';
|
||||||
|
import { formatTokenValue } from '@/src/lib/formatters';
|
||||||
import { DonutChartCard } from '@/src/components/donut-chart-card';
|
import { DonutChartCard } from '@/src/components/donut-chart-card';
|
||||||
import { LineTrendChart } from '@/src/components/line-trend-chart';
|
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 { getAdminSettings, getDashboardModels, getDashboardStats, getDashboardTrend, listAccounts } from '@/src/services/admin';
|
||||||
import { adminConfigState } from '@/src/store/admin-config';
|
import { adminConfigState } from '@/src/store/admin-config';
|
||||||
|
|
||||||
@@ -17,6 +15,32 @@ const { useSnapshot } = require('valtio/react');
|
|||||||
|
|
||||||
type RangeKey = '24h' | '7d' | '30d';
|
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) {
|
function getDateRange(rangeKey: RangeKey) {
|
||||||
const end = new Date();
|
const end = new Date();
|
||||||
const start = new Date();
|
const start = new Date();
|
||||||
@@ -38,11 +62,27 @@ function getDateRange(rangeKey: RangeKey) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const RANGE_OPTIONS: Array<{ key: RangeKey; label: string }> = [
|
function formatNumber(value?: number) {
|
||||||
{ key: '24h', label: '24H' },
|
if (typeof value !== 'number' || Number.isNaN(value)) return '--';
|
||||||
{ key: '7d', label: '7D' },
|
return new Intl.NumberFormat('en-US').format(value);
|
||||||
{ key: '30d', label: '30D' },
|
}
|
||||||
];
|
|
||||||
|
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) {
|
function getPointLabel(value: string, rangeKey: RangeKey) {
|
||||||
if (rangeKey === '24h') {
|
if (rangeKey === '24h') {
|
||||||
@@ -52,49 +92,97 @@ function getPointLabel(value: string, rangeKey: RangeKey) {
|
|||||||
return value.slice(5, 10);
|
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() {
|
export default function MonitorScreen() {
|
||||||
useScreenInteractive('monitor_interactive');
|
|
||||||
const config = useSnapshot(adminConfigState);
|
const config = useSnapshot(adminConfigState);
|
||||||
const { width } = useWindowDimensions();
|
const hasAccount = Boolean(config.baseUrl.trim());
|
||||||
const contentWidth = Math.max(width - 24, 280);
|
|
||||||
const [rangeKey, setRangeKey] = useState<RangeKey>('7d');
|
const [rangeKey, setRangeKey] = useState<RangeKey>('7d');
|
||||||
const range = useMemo(() => getDateRange(rangeKey), [rangeKey]);
|
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({
|
const trendQuery = useQuery({
|
||||||
queryKey: ['monitor-trend', rangeKey, range.start_date, range.end_date, range.granularity],
|
queryKey: ['monitor-trend', rangeKey, range.start_date, range.end_date, range.granularity],
|
||||||
queryFn: () => getDashboardTrend(range),
|
queryFn: () => getDashboardTrend(range),
|
||||||
enabled: hasAccount,
|
enabled: hasAccount,
|
||||||
});
|
});
|
||||||
|
|
||||||
const modelsQuery = useQuery({
|
const modelsQuery = useQuery({
|
||||||
queryKey: ['monitor-models', rangeKey, range.start_date, range.end_date],
|
queryKey: ['monitor-models', rangeKey, range.start_date, range.end_date],
|
||||||
queryFn: () => getDashboardModels(range),
|
queryFn: () => getDashboardModels(range),
|
||||||
enabled: hasAccount,
|
enabled: hasAccount,
|
||||||
});
|
});
|
||||||
|
|
||||||
const settingsQuery = useQuery({
|
function refetchAll() {
|
||||||
queryKey: ['admin-settings'],
|
statsQuery.refetch();
|
||||||
queryFn: getAdminSettings,
|
settingsQuery.refetch();
|
||||||
enabled: hasAccount,
|
accountsQuery.refetch();
|
||||||
});
|
trendQuery.refetch();
|
||||||
|
modelsQuery.refetch();
|
||||||
const accountsQuery = useQuery({
|
}
|
||||||
queryKey: ['monitor-accounts'],
|
|
||||||
queryFn: () => listAccounts(''),
|
|
||||||
enabled: hasAccount,
|
|
||||||
});
|
|
||||||
|
|
||||||
const stats = statsQuery.data;
|
const stats = statsQuery.data;
|
||||||
const trend = trendQuery.data?.trend ?? [];
|
|
||||||
const accounts = accountsQuery.data?.items ?? [];
|
|
||||||
const siteName = settingsQuery.data?.site_name?.trim() || '管理控制台';
|
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(
|
const throughputPoints = useMemo(
|
||||||
() => trend.map((item) => ({ label: getPointLabel(item.date, rangeKey), value: item.total_tokens })),
|
() => trend.map((item) => ({ label: getPointLabel(item.date, rangeKey), value: item.total_tokens })),
|
||||||
[rangeKey, trend]
|
[rangeKey, trend]
|
||||||
@@ -107,281 +195,196 @@ export default function MonitorScreen() {
|
|||||||
() => trend.map((item) => ({ label: getPointLabel(item.date, rangeKey), value: item.cost })),
|
() => trend.map((item) => ({ label: getPointLabel(item.date, rangeKey), value: item.cost })),
|
||||||
[rangeKey, trend]
|
[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 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 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 totalCacheReadTokens = useMemo(() => trend.reduce((sum, item) => sum + item.cache_read_tokens, 0), [trend]);
|
||||||
const busyAccounts = useMemo(
|
const isRefreshing = statsQuery.isRefetching || settingsQuery.isRefetching || accountsQuery.isRefetching || trendQuery.isRefetching || modelsQuery.isRefetching;
|
||||||
() => 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);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ScreenShell
|
<SafeAreaView style={{ flex: 1, backgroundColor: colors.page }}>
|
||||||
title="概览"
|
<ScrollView
|
||||||
subtitle=""
|
style={{ flex: 1 }}
|
||||||
titleAside={<Text className="text-[11px] text-[#a2988a]">{siteName} 的关键运行指标。</Text>}
|
contentContainerStyle={{ paddingHorizontal: 16, paddingTop: 16, paddingBottom: 110 }}
|
||||||
variant="minimal"
|
showsVerticalScrollIndicator={false}
|
||||||
horizontalInsetClassName="px-3"
|
refreshControl={<RefreshControl refreshing={isRefreshing} onRefresh={() => void refetchAll()} tintColor="#1d5f55" />}
|
||||||
contentGapClassName="mt-3 gap-2"
|
>
|
||||||
right={
|
<View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12, marginBottom: 16 }}>
|
||||||
<View className="flex-row items-center gap-2">
|
<View style={{ flex: 1 }}>
|
||||||
<View className="flex-row items-center rounded-full bg-[#ece3d6] p-1">
|
<Text style={{ fontSize: 28, fontWeight: '700', color: colors.text }}>概览</Text>
|
||||||
{RANGE_OPTIONS.map((item) => {
|
<Text style={{ marginTop: 6, fontSize: 13, color: '#8a8072' }}>{siteName} 的当前运行状态。</Text>
|
||||||
const active = item.key === rangeKey;
|
</View>
|
||||||
|
<View style={{ alignItems: 'flex-end' }}>
|
||||||
return (
|
<View style={{ flexDirection: 'row', gap: 8 }}>
|
||||||
<Pressable
|
{RANGE_OPTIONS.map((option) => {
|
||||||
key={item.key}
|
const active = option.key === rangeKey;
|
||||||
className={active ? 'rounded-full bg-[#1d5f55] px-3 py-1.5' : 'rounded-full bg-transparent px-3 py-1.5'}
|
return (
|
||||||
onPress={() => setRangeKey(item.key)}
|
<Pressable
|
||||||
>
|
key={option.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]'}>
|
style={{ backgroundColor: active ? colors.primary : colors.border, borderRadius: 999, paddingHorizontal: 12, paddingVertical: 8 }}
|
||||||
{item.label}
|
onPress={() => setRangeKey(option.key)}
|
||||||
</Text>
|
>
|
||||||
</Pressable>
|
<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>
|
</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>
|
||||||
}
|
|
||||||
>
|
|
||||||
<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 (
|
{!hasAccount ? (
|
||||||
<View
|
<Section title="未连接服务器" subtitle="需要先配置连接">
|
||||||
key={item.label}
|
<Text style={{ fontSize: 14, lineHeight: 22, color: colors.subtext }}>请先前往“服务器”页填写服务地址和 Admin Token,再返回查看概览数据。</Text>
|
||||||
className={item.tone === 'dark' ? 'rounded-[18px] bg-[#1d5f55] px-2.5 py-2.5' : 'rounded-[18px] bg-[#fbf8f2] px-2.5 py-2.5'}
|
<Pressable style={{ marginTop: 14, alignSelf: 'flex-start', backgroundColor: colors.primary, borderRadius: 14, paddingHorizontal: 16, paddingVertical: 12 }} onPress={() => router.push('/settings')}>
|
||||||
style={{ width: summaryCardWidth }}
|
<Text style={{ color: '#fff', fontSize: 13, fontWeight: '700' }}>去配置服务器</Text>
|
||||||
>
|
</Pressable>
|
||||||
<View className="flex-row items-center justify-between gap-2">
|
</Section>
|
||||||
<Text className={item.tone === 'dark' ? 'text-[10px] uppercase tracking-[1.1px] text-[#d8efe7]' : 'text-[10px] uppercase tracking-[1.1px] text-[#8a8072]'}>
|
) : isLoading ? (
|
||||||
{item.label}
|
<Section title="正在加载概览" subtitle="请稍候">
|
||||||
</Text>
|
<Text style={{ fontSize: 14, lineHeight: 22, color: colors.subtext }}>已连接服务器,正在拉取概览、模型和账号状态数据。</Text>
|
||||||
<Icon color={item.tone === 'dark' ? '#d8efe7' : '#7d7468'} size={13} />
|
</Section>
|
||||||
</View>
|
) : hasError ? (
|
||||||
<Text className={item.tone === 'dark' ? 'mt-2 text-[17px] font-bold text-white' : 'mt-2 text-[17px] font-bold text-[#16181a]'}>
|
<Section title="加载失败" subtitle="请检查连接配置">
|
||||||
{item.value}
|
<View style={{ borderRadius: 14, backgroundColor: colors.dangerBg, paddingHorizontal: 14, paddingVertical: 12 }}>
|
||||||
</Text>
|
<Text style={{ color: colors.danger, fontSize: 14, lineHeight: 20 }}>{errorMessage}</Text>
|
||||||
{'detail' in item && item.detail ? (
|
</View>
|
||||||
<Text numberOfLines={1} className={item.tone === 'dark' ? 'mt-1 text-[10px] text-[#d8efe7]' : 'mt-1 text-[10px] text-[#8a8072]'}>
|
<View style={{ flexDirection: 'row', gap: 12, marginTop: 14 }}>
|
||||||
{item.detail}
|
<Pressable style={{ flex: 1, backgroundColor: colors.primary, borderRadius: 14, paddingVertical: 12, alignItems: 'center' }} onPress={refetchAll}>
|
||||||
</Text>
|
<Text style={{ color: '#fff', fontSize: 13, fontWeight: '700' }}>重试</Text>
|
||||||
) : null}
|
</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 style={{ flex: 1, backgroundColor: colors.mutedCard, borderRadius: 14, padding: 12 }}>
|
||||||
})}
|
<Text style={{ fontSize: 11, color: '#8a8072' }}>健康</Text>
|
||||||
</View>
|
<Text style={{ marginTop: 6, fontSize: 18, fontWeight: '700', color: colors.text }}>{formatNumber(healthyAccounts)}</Text>
|
||||||
))}
|
</View>
|
||||||
</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>
|
||||||
<View className="flex-1 gap-3">
|
)}
|
||||||
{rightColumn.map((item) => (
|
</ScrollView>
|
||||||
<View key={item.key}>{item.node}</View>
|
</SafeAreaView>
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
</View>
|
|
||||||
) : (
|
|
||||||
cards.map((item) => <View key={item.key}>{item.node}</View>)
|
|
||||||
)}
|
|
||||||
</ScreenShell>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,197 +1,299 @@
|
|||||||
|
import { router } from 'expo-router';
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
import { Controller, useForm } from 'react-hook-form';
|
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 { z } from 'zod';
|
||||||
|
|
||||||
import { ListCard } from '@/src/components/list-card';
|
import { getAdminSettings, getDashboardStats } from '@/src/services/admin';
|
||||||
import { ScreenShell } from '@/src/components/screen-shell';
|
|
||||||
import { isLocalProxyBaseUrl } from '@/src/lib/admin-fetch';
|
|
||||||
import { queryClient } from '@/src/lib/query-client';
|
import { queryClient } from '@/src/lib/query-client';
|
||||||
import {
|
import { adminConfigState, removeAdminAccount, saveAdminConfig, switchAdminAccount, type AdminAccountProfile } from '@/src/store/admin-config';
|
||||||
adminConfigState,
|
|
||||||
logoutAdminAccount,
|
|
||||||
removeAdminAccount,
|
|
||||||
saveAdminConfig,
|
|
||||||
setAdminAccountEnabled,
|
|
||||||
switchAdminAccount,
|
|
||||||
type AdminAccountProfile,
|
|
||||||
} from '@/src/store/admin-config';
|
|
||||||
|
|
||||||
const { useSnapshot } = require('valtio/react');
|
const { useSnapshot } = require('valtio/react');
|
||||||
|
|
||||||
const schema = z
|
const schema = z
|
||||||
.object({
|
.object({
|
||||||
baseUrl: z.string().min(1, '请输入 Host'),
|
baseUrl: z.string().min(1, '请输入服务器地址'),
|
||||||
adminApiKey: z.string(),
|
adminApiKey: z.string(),
|
||||||
})
|
})
|
||||||
.superRefine((values, ctx) => {
|
.refine((values) => values.adminApiKey.trim().length > 0, {
|
||||||
if (!isLocalProxyBaseUrl(values.baseUrl.trim()) && !values.adminApiKey.trim()) {
|
path: ['adminApiKey'],
|
||||||
ctx.addIssue({
|
message: '请输入 Admin Key',
|
||||||
code: 'custom',
|
|
||||||
path: ['adminApiKey'],
|
|
||||||
message: '请输入 Admin Token',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
type FormValues = z.infer<typeof schema>;
|
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() {
|
export default function SettingsScreen() {
|
||||||
const config = useSnapshot(adminConfigState);
|
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>({
|
const { control, handleSubmit, formState, reset } = useForm<FormValues>({
|
||||||
resolver: zodResolver(schema),
|
resolver: zodResolver(schema),
|
||||||
values: {
|
defaultValues: {
|
||||||
baseUrl: config.baseUrl,
|
baseUrl: '',
|
||||||
adminApiKey: config.adminApiKey,
|
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);
|
await switchAdminAccount(account.id);
|
||||||
queryClient.clear();
|
await verifyAndEnter(`已切换到 ${account.label}。`);
|
||||||
reset({ baseUrl: account.baseUrl, adminApiKey: account.adminApiKey });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handleDelete(account: AdminAccountProfile) {
|
async function handleDelete(account: AdminAccountProfile) {
|
||||||
await removeAdminAccount(account.id);
|
await removeAdminAccount(account.id);
|
||||||
queryClient.clear();
|
queryClient.clear();
|
||||||
reset({ baseUrl: adminConfigState.baseUrl, adminApiKey: adminConfigState.adminApiKey });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handleLogout() {
|
async function handleRefresh() {
|
||||||
await logoutAdminAccount();
|
if (!config.baseUrl.trim()) {
|
||||||
queryClient.clear();
|
return;
|
||||||
reset({ baseUrl: '', adminApiKey: '' });
|
}
|
||||||
}
|
|
||||||
|
|
||||||
async function handleToggleEnabled(account: AdminAccountProfile) {
|
setIsRefreshing(true);
|
||||||
await setAdminAccountEnabled(account.id, account.enabled === false);
|
setConnectionState('idle');
|
||||||
queryClient.clear();
|
setConnectionMessage('');
|
||||||
reset({ baseUrl: adminConfigState.baseUrl, adminApiKey: adminConfigState.adminApiKey });
|
|
||||||
|
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 (
|
return (
|
||||||
<ScreenShell
|
<SafeAreaView style={{ flex: 1, backgroundColor: colors.page }}>
|
||||||
title="服务器"
|
<ScrollView
|
||||||
subtitle=""
|
style={{ flex: 1 }}
|
||||||
titleAside={<Text className="text-[11px] text-[#a2988a]">管理 Sub2API 连接。</Text>}
|
contentContainerStyle={{ paddingHorizontal: 16, paddingTop: 16, paddingBottom: 110, gap: 14 }}
|
||||||
variant="minimal"
|
showsVerticalScrollIndicator={false}
|
||||||
>
|
refreshControl={<RefreshControl refreshing={isRefreshing} onRefresh={() => void handleRefresh()} tintColor="#1d5f55" />}
|
||||||
<ListCard title="当前连接" meta={config.baseUrl || '未连接'}>
|
>
|
||||||
<View className="gap-3">
|
<View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
|
||||||
<Text className="text-sm text-[#6f665c]">
|
<View style={{ flex: 1 }}>
|
||||||
{config.baseUrl || '当前没有激活服务器,可在下方直接新增或切换。'}
|
<Text style={{ fontSize: 28, fontWeight: '700', color: colors.text }}>服务器</Text>
|
||||||
</Text>
|
<Text style={{ marginTop: 6, fontSize: 13, color: '#8a8072' }}>选择当前管理的服务器,或添加新的服务器。</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>
|
|
||||||
</View>
|
</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>
|
</View>
|
||||||
</ListCard>
|
|
||||||
|
|
||||||
<ListCard title="连接配置" meta="Host 与 Admin Token 合并配置">
|
{showForm ? (
|
||||||
<View className="gap-3">
|
<View style={{ backgroundColor: colors.card, borderRadius: 18, padding: 16, gap: 14 }}>
|
||||||
<View>
|
<Text style={{ fontSize: 18, fontWeight: '700', color: colors.text }}>添加服务器</Text>
|
||||||
<Text className="mb-2 text-[11px] text-[#7d7468]">Host</Text>
|
|
||||||
<Controller
|
<View>
|
||||||
control={control}
|
<Text style={{ marginBottom: 8, fontSize: 12, color: colors.subtext }}>服务器地址</Text>
|
||||||
name="baseUrl"
|
<Controller
|
||||||
render={({ field: { onChange, value } }) => (
|
control={control}
|
||||||
<TextInput
|
name="baseUrl"
|
||||||
value={value}
|
render={({ field: { onChange, value } }) => (
|
||||||
onChangeText={onChange}
|
<TextInput
|
||||||
placeholder="http://localhost:8787"
|
value={value}
|
||||||
placeholderTextColor="#9b9081"
|
onChangeText={onChange}
|
||||||
autoCapitalize="none"
|
placeholder="例如:https://api.example.com"
|
||||||
className="rounded-[18px] bg-[#f1ece2] px-4 py-4 text-base text-[#16181a]"
|
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>
|
</View>
|
||||||
|
) : null}
|
||||||
|
|
||||||
<View>
|
<View style={{ gap: 12 }}>
|
||||||
<Text className="mb-2 text-[11px] text-[#7d7468]">Admin Token</Text>
|
{config.accounts.map((account: AdminAccountProfile) => (
|
||||||
<Controller
|
<ServerCard
|
||||||
control={control}
|
key={account.id}
|
||||||
name="adminApiKey"
|
account={account}
|
||||||
render={({ field: { onChange, value } }) => (
|
active={account.id === config.activeAccountId}
|
||||||
<TextInput
|
onSelect={() => handleSelect(account)}
|
||||||
value={value}
|
onDelete={() => handleDelete(account)}
|
||||||
onChangeText={onChange}
|
|
||||||
placeholder="admin-xxxxxxxx"
|
|
||||||
placeholderTextColor="#9b9081"
|
|
||||||
autoCapitalize="none"
|
|
||||||
className="rounded-[18px] bg-[#f1ece2] px-4 py-4 text-base text-[#16181a]"
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
/>
|
/>
|
||||||
</View>
|
))}
|
||||||
|
|
||||||
<Text className="text-[11px] text-[#8a8072]">使用本地代理时可留空 token;直连上游时必须填写。</Text>
|
{config.accounts.length === 0 ? (
|
||||||
|
<View style={{ backgroundColor: colors.card, borderRadius: 18, padding: 18 }}>
|
||||||
{(formState.errors.baseUrl || formState.errors.adminApiKey) ? (
|
<Text style={{ fontSize: 15, fontWeight: '700', color: colors.text }}>还没有服务器</Text>
|
||||||
<View className="rounded-[16px] bg-[#fbf1eb] px-4 py-3">
|
<Text style={{ marginTop: 8, fontSize: 13, lineHeight: 21, color: colors.subtext }}>点击右上角 + 添加服务器,保存成功后会自动切换并进入概览。</Text>
|
||||||
<Text className="text-sm text-[#c25d35]">{formState.errors.baseUrl?.message || formState.errors.adminApiKey?.message}</Text>
|
|
||||||
</View>
|
</View>
|
||||||
) : null}
|
) : null}
|
||||||
</View>
|
</View>
|
||||||
</ListCard>
|
</ScrollView>
|
||||||
|
</SafeAreaView>
|
||||||
<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>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,264 +1,223 @@
|
|||||||
import { useQueries, useQuery, useQueryClient } from '@tanstack/react-query';
|
import { useQuery } from '@tanstack/react-query';
|
||||||
import * as Clipboard from 'expo-clipboard';
|
|
||||||
import { Copy, Search, UserRound } from 'lucide-react-native';
|
|
||||||
import { router } from 'expo-router';
|
import { router } from 'expo-router';
|
||||||
import { useCallback, useMemo, useState } from 'react';
|
import { useMemo, useState } from 'react';
|
||||||
import { FlatList, Pressable, Text, TextInput, View } from 'react-native';
|
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 { useDebouncedValue } from '@/src/hooks/use-debounced-value';
|
||||||
import { useScreenInteractive } from '@/src/hooks/use-screen-interactive';
|
import { queryClient } from '@/src/lib/query-client';
|
||||||
import { getUser, getUserUsage, listUserApiKeys, listUsers } from '@/src/services/admin';
|
import { getUser, listUserApiKeys, listUsers } from '@/src/services/admin';
|
||||||
import { adminConfigState } from '@/src/store/admin-config';
|
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');
|
const { useSnapshot } = require('valtio/react');
|
||||||
|
|
||||||
type UserSupplement = {
|
const colors = {
|
||||||
usage?: UserUsageSummary;
|
page: '#f4efe4',
|
||||||
apiKeys: AdminApiKey[];
|
card: '#fbf8f2',
|
||||||
|
mutedCard: '#f1ece2',
|
||||||
|
primary: '#1d5f55',
|
||||||
|
text: '#16181a',
|
||||||
|
subtext: '#6f665c',
|
||||||
|
dangerBg: '#fbf1eb',
|
||||||
|
danger: '#c25d35',
|
||||||
|
accentBg: '#efe4cf',
|
||||||
|
accentText: '#8c5a22',
|
||||||
};
|
};
|
||||||
|
|
||||||
function getUserTitle(user: AdminUser) {
|
type SortOrder = 'desc' | 'asc';
|
||||||
return user.username?.trim() || user.email;
|
|
||||||
}
|
|
||||||
|
|
||||||
function getUserSortValue(user: AdminUser) {
|
function formatBalance(value?: number) {
|
||||||
const raw = user.updated_at || user.created_at || '';
|
if (typeof value !== 'number' || Number.isNaN(value)) return '$0.00';
|
||||||
const value = raw ? new Date(raw).getTime() : 0;
|
|
||||||
return Number.isNaN(value) ? 0 : value;
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatQuotaValue(value: number) {
|
|
||||||
return `$${value.toFixed(2)}`;
|
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() {
|
export default function UsersScreen() {
|
||||||
useScreenInteractive('users_interactive');
|
|
||||||
const config = useSnapshot(adminConfigState);
|
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 hasAccount = Boolean(config.baseUrl.trim());
|
||||||
|
const [searchText, setSearchText] = useState('');
|
||||||
|
const [sortOrder, setSortOrder] = useState<SortOrder>('desc');
|
||||||
|
const debouncedSearchText = useDebouncedValue(searchText, 250);
|
||||||
|
|
||||||
const usersQuery = useQuery({
|
const usersQuery = useQuery({
|
||||||
queryKey: ['users', keyword],
|
queryKey: ['users', debouncedSearchText],
|
||||||
queryFn: () => listUsers(keyword),
|
queryFn: () => listUsers(debouncedSearchText),
|
||||||
enabled: hasAccount,
|
enabled: hasAccount,
|
||||||
});
|
});
|
||||||
|
|
||||||
const items = usersQuery.data?.items ?? [];
|
const users = useMemo(() => {
|
||||||
const userDetailQueries = useQueries({
|
const items = [...(usersQuery.data?.items ?? [])];
|
||||||
queries: items.map((user) => ({
|
items.sort((left, right) => {
|
||||||
queryKey: ['user-list-supplement', user.id],
|
const value = getTimeValue(left) - getTimeValue(right);
|
||||||
queryFn: async () => {
|
return sortOrder === 'desc' ? -value : value;
|
||||||
const [usage, apiKeysData] = await Promise.all([getUserUsage(user.id), listUserApiKeys(user.id)]);
|
});
|
||||||
|
return items;
|
||||||
|
}, [sortOrder, usersQuery.data?.items]);
|
||||||
|
|
||||||
return {
|
const errorMessage = getErrorMessage(usersQuery.error);
|
||||||
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]
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ScreenShell
|
<SafeAreaView style={{ flex: 1, backgroundColor: colors.page }}>
|
||||||
title="用户管理"
|
<View style={{ flex: 1, paddingHorizontal: 16, paddingTop: 14 }}>
|
||||||
subtitle=""
|
<View style={{ marginBottom: 10 }}>
|
||||||
titleAside={<Text className="text-[11px] text-[#a2988a]">搜索结果 {sortedItems.length}</Text>}
|
<Text style={{ fontSize: 28, fontWeight: '700', color: colors.text }}>用户</Text>
|
||||||
variant="minimal"
|
<Text style={{ marginTop: 4, fontSize: 12, color: '#8a8072' }}>查看用户列表并进入详情页管理账号。</Text>
|
||||||
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>
|
|
||||||
</View>
|
</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
|
<FlatList
|
||||||
data={sortedItems}
|
style={{ marginTop: 10, flex: 1 }}
|
||||||
renderItem={renderItem}
|
data={users}
|
||||||
keyExtractor={(item) => `${item.id}`}
|
keyExtractor={(item) => `${item.id}`}
|
||||||
showsVerticalScrollIndicator={false}
|
showsVerticalScrollIndicator={false}
|
||||||
ListHeaderComponent={() => <View className="h-2" />}
|
refreshControl={<RefreshControl refreshing={usersQuery.isRefetching} onRefresh={() => void usersQuery.refetch()} tintColor="#1d5f55" />}
|
||||||
ListEmptyComponent={emptyState}
|
contentContainerStyle={{ paddingBottom: 8, gap: 12, flexGrow: users.length === 0 ? 1 : 0 }}
|
||||||
ListFooterComponent={() => <View className="h-4" />}
|
ListEmptyComponent={
|
||||||
ItemSeparatorComponent={() => <View className="h-3" />}
|
<View style={{ backgroundColor: colors.card, borderRadius: 18, padding: 16 }}>
|
||||||
keyboardShouldPersistTaps="handled"
|
<Text style={{ fontSize: 18, fontWeight: '700', color: colors.text }}>暂无用户</Text>
|
||||||
removeClippedSubviews
|
<Text style={{ marginTop: 8, fontSize: 14, lineHeight: 22, color: colors.subtext }}>当前搜索条件下没有匹配结果,可以修改关键词后重试。</Text>
|
||||||
initialNumToRender={8}
|
</View>
|
||||||
maxToRenderPerBatch={8}
|
}
|
||||||
windowSize={5}
|
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>
|
</View>
|
||||||
</ScreenShell>
|
</SafeAreaView>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,16 +12,20 @@ import { adminConfigState, hydrateAdminConfig } from '@/src/store/admin-config';
|
|||||||
|
|
||||||
const { useSnapshot } = require('valtio/react');
|
const { useSnapshot } = require('valtio/react');
|
||||||
|
|
||||||
|
export const unstable_settings = {
|
||||||
|
initialRouteName: '(tabs)',
|
||||||
|
};
|
||||||
|
|
||||||
export default function RootLayout() {
|
export default function RootLayout() {
|
||||||
|
const config = useSnapshot(adminConfigState);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
hydrateAdminConfig()
|
hydrateAdminConfig()
|
||||||
.then(() => markPerformance('config_hydrated'))
|
.then(() => markPerformance('config_hydrated'))
|
||||||
.catch(() => undefined);
|
.catch(() => undefined);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const config = useSnapshot(adminConfigState);
|
|
||||||
const isReady = config.hydrated;
|
const isReady = config.hydrated;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<GestureHandlerRootView style={{ flex: 1 }}>
|
<GestureHandlerRootView style={{ flex: 1 }}>
|
||||||
<QueryClientProvider client={queryClient}>
|
<QueryClientProvider client={queryClient}>
|
||||||
@@ -30,10 +34,22 @@ export default function RootLayout() {
|
|||||||
<ActivityIndicator color="#1d5f55" />
|
<ActivityIndicator color="#1d5f55" />
|
||||||
</View>
|
</View>
|
||||||
) : (
|
) : (
|
||||||
<Stack screenOptions={{ headerShown: false }}>
|
<Stack initialRouteName="(tabs)" screenOptions={{ headerShown: false }}>
|
||||||
<Stack.Screen name="(tabs)" />
|
<Stack.Screen name="(tabs)" />
|
||||||
<Stack.Screen name="login" />
|
<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.Screen name="accounts/[id]" options={{ presentation: 'card' }} />
|
||||||
</Stack>
|
</Stack>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -66,11 +66,18 @@ export default function AccountDetailScreen() {
|
|||||||
label: item.date.slice(5),
|
label: item.date.slice(5),
|
||||||
value: item.total_tokens,
|
value: item.total_tokens,
|
||||||
}));
|
}));
|
||||||
|
const isRefreshing = accountQuery.isRefetching || todayStatsQuery.isRefetching || trendQuery.isRefetching;
|
||||||
|
|
||||||
|
function handleRefresh() {
|
||||||
|
void Promise.all([accountQuery.refetch(), todayStatsQuery.refetch(), trendQuery.refetch()]);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ScreenShell
|
<ScreenShell
|
||||||
title={account?.name || '账号详情'}
|
title={account?.name || '账号详情'}
|
||||||
subtitle="聚焦账号 token 用量、状态和几个最常用操作。"
|
subtitle="聚焦账号 token 用量、状态和几个最常用操作。"
|
||||||
|
refreshing={isRefreshing}
|
||||||
|
onRefresh={handleRefresh}
|
||||||
right={
|
right={
|
||||||
<Pressable className="h-11 w-11 items-center justify-center rounded-full bg-[#2d3134]" onPress={() => router.back()}>
|
<Pressable className="h-11 w-11 items-center justify-center rounded-full bg-[#2d3134]" onPress={() => router.back()}>
|
||||||
<ChevronLeft color="#f6f1e8" size={18} />
|
<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 { zodResolver } from '@hookform/resolvers/zod';
|
||||||
import { Globe, KeyRound } from 'lucide-react-native';
|
|
||||||
import { Controller, useForm } from 'react-hook-form';
|
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 { z } from 'zod';
|
||||||
|
|
||||||
import { ListCard } from '@/src/components/list-card';
|
import { getAdminSettings, getDashboardStats } from '@/src/services/admin';
|
||||||
import { ScreenShell } from '@/src/components/screen-shell';
|
|
||||||
import { useScreenInteractive } from '@/src/hooks/use-screen-interactive';
|
|
||||||
import { isLocalProxyBaseUrl } from '@/src/lib/admin-fetch';
|
|
||||||
import { queryClient } from '@/src/lib/query-client';
|
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 { useSnapshot } = require('valtio/react');
|
||||||
|
|
||||||
const schema = z
|
const schema = z
|
||||||
.object({
|
.object({
|
||||||
baseUrl: z.string().min(1, '请输入 Host'),
|
baseUrl: z.string().min(1, '请输入服务器地址'),
|
||||||
adminApiKey: z.string(),
|
adminApiKey: z.string(),
|
||||||
})
|
})
|
||||||
.superRefine((values, ctx) => {
|
.refine((values) => values.adminApiKey.trim().length > 0, {
|
||||||
if (!isLocalProxyBaseUrl(values.baseUrl.trim()) && !values.adminApiKey.trim()) {
|
path: ['adminApiKey'],
|
||||||
ctx.addIssue({
|
message: '请输入 Admin Key',
|
||||||
code: 'custom',
|
|
||||||
path: ['adminApiKey'],
|
|
||||||
message: '请输入 Admin Token',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
type FormValues = z.infer<typeof schema>;
|
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() {
|
export default function LoginScreen() {
|
||||||
useScreenInteractive('login_interactive');
|
|
||||||
const config = useSnapshot(adminConfigState);
|
const config = useSnapshot(adminConfigState);
|
||||||
|
const hasAccount = Boolean(config.baseUrl.trim());
|
||||||
const { control, handleSubmit, formState } = useForm<FormValues>({
|
const { control, handleSubmit, formState } = useForm<FormValues>({
|
||||||
resolver: zodResolver(schema),
|
resolver: zodResolver(schema),
|
||||||
defaultValues: {
|
defaultValues: {
|
||||||
@@ -41,115 +64,111 @@ export default function LoginScreen() {
|
|||||||
adminApiKey: config.adminApiKey,
|
adminApiKey: config.adminApiKey,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
const [connectionState, setConnectionState] = useState<ConnectionState>('idle');
|
||||||
|
const [connectionMessage, setConnectionMessage] = useState('');
|
||||||
|
|
||||||
|
if (hasAccount) {
|
||||||
|
return <Redirect href="/monitor" />;
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ScreenShell
|
<SafeAreaView style={{ flex: 1, backgroundColor: colors.page }}>
|
||||||
title="登录"
|
<ScrollView contentContainerStyle={{ flexGrow: 1, paddingHorizontal: 20, paddingVertical: 24 }} keyboardShouldPersistTaps="handled">
|
||||||
subtitle=""
|
<View style={{ flex: 1, justifyContent: 'center', gap: 20 }}>
|
||||||
titleAside={<Text className="text-[11px] text-[#a2988a]">添加、切换或恢复 Sub2API 账号。</Text>}
|
<View style={{ gap: 8 }}>
|
||||||
variant="minimal"
|
<Text style={{ fontSize: 34, fontWeight: '800', color: colors.text }}>管理员入口</Text>
|
||||||
>
|
<Text style={{ fontSize: 14, lineHeight: 22, color: colors.subtext }}>
|
||||||
{config.accounts.length > 0 ? (
|
首次进入请填写服务器地址和 Admin Key。连接成功后即可进入应用,并在“服务器”页管理多个服务器。
|
||||||
<ListCard title="已保存账号" meta="可直接切换到其他 Sub2API 账号">
|
</Text>
|
||||||
<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>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</View>
|
</View>
|
||||||
</ListCard>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
<ListCard title="Host" meta="当前站点或管理代理地址" icon={Globe}>
|
<View style={{ backgroundColor: colors.card, borderRadius: 22, padding: 18, gap: 16 }}>
|
||||||
<Controller
|
<View>
|
||||||
control={control}
|
<Text style={{ marginBottom: 8, fontSize: 12, color: colors.subtext }}>服务器地址</Text>
|
||||||
name="baseUrl"
|
<Controller
|
||||||
render={({ field: { onChange, value } }) => (
|
control={control}
|
||||||
<TextInput
|
name="baseUrl"
|
||||||
value={value}
|
render={({ field: { onChange, value } }) => (
|
||||||
onChangeText={onChange}
|
<TextInput
|
||||||
placeholder="http://localhost:8787"
|
value={value}
|
||||||
placeholderTextColor="#9b9081"
|
onChangeText={(text) => {
|
||||||
autoCapitalize="none"
|
if (connectionState !== 'idle') {
|
||||||
className="rounded-[18px] bg-[#f1ece2] px-4 py-4 text-base text-[#16181a]"
|
setConnectionState('idle');
|
||||||
/>
|
setConnectionMessage('');
|
||||||
)}
|
}
|
||||||
/>
|
onChange(text);
|
||||||
</ListCard>
|
}}
|
||||||
|
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}>
|
<View>
|
||||||
<Controller
|
<Text style={{ marginBottom: 8, fontSize: 12, color: colors.subtext }}>Admin Key</Text>
|
||||||
control={control}
|
<Controller
|
||||||
name="adminApiKey"
|
control={control}
|
||||||
render={({ field: { onChange, value } }) => (
|
name="adminApiKey"
|
||||||
<TextInput
|
render={({ field: { onChange, value } }) => (
|
||||||
value={value}
|
<TextInput
|
||||||
onChangeText={onChange}
|
value={value}
|
||||||
placeholder="admin-xxxxxxxx"
|
onChangeText={(text) => {
|
||||||
placeholderTextColor="#9b9081"
|
if (connectionState !== 'idle') {
|
||||||
autoCapitalize="none"
|
setConnectionState('idle');
|
||||||
className="rounded-[18px] bg-[#f1ece2] px-4 py-4 text-base text-[#16181a]"
|
setConnectionMessage('');
|
||||||
/>
|
}
|
||||||
)}
|
onChange(text);
|
||||||
/>
|
}}
|
||||||
</ListCard>
|
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) ? (
|
{formState.errors.baseUrl || formState.errors.adminApiKey ? (
|
||||||
<View className="rounded-[20px] bg-[#fbf1eb] px-4 py-3">
|
<View style={{ borderRadius: 14, backgroundColor: colors.dangerBg, paddingHorizontal: 14, paddingVertical: 12 }}>
|
||||||
<Text className="text-sm text-[#c25d35]">{formState.errors.baseUrl?.message || formState.errors.adminApiKey?.message}</Text>
|
<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>
|
</View>
|
||||||
) : null}
|
</ScrollView>
|
||||||
|
</SafeAreaView>
|
||||||
<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>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,44 +1,252 @@
|
|||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
|
||||||
import * as Clipboard from 'expo-clipboard';
|
import * as Clipboard from 'expo-clipboard';
|
||||||
import { ArrowLeftRight, ChevronLeft, Copy, KeyRound, Search, Wallet } from 'lucide-react-native';
|
import { Stack, useLocalSearchParams } from 'expo-router';
|
||||||
import { router, useLocalSearchParams } from 'expo-router';
|
|
||||||
import { useMemo, useState } from 'react';
|
import { useMemo, useState } from 'react';
|
||||||
import { Controller, useForm } from 'react-hook-form';
|
import { Pressable, ScrollView, Text, TextInput, View } from 'react-native';
|
||||||
import { Pressable, Text, TextInput, View } from 'react-native';
|
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||||
import { z } from 'zod';
|
|
||||||
|
|
||||||
import { DetailRow } from '@/src/components/detail-row';
|
import { LineTrendChart } from '@/src/components/line-trend-chart';
|
||||||
import { ListCard } from '@/src/components/list-card';
|
import { getDashboardSnapshot, getUsageStats, getUser, listUserApiKeys, updateUserBalance } from '@/src/services/admin';
|
||||||
import { formatDisplayTime } from '@/src/lib/formatters';
|
import type { AdminApiKey, BalanceOperation } from '@/src/types/admin';
|
||||||
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';
|
|
||||||
|
|
||||||
const schema = z.object({
|
const colors = {
|
||||||
amount: z.string().min(1, '请输入金额'),
|
page: '#f4efe4',
|
||||||
notes: z.string().optional(),
|
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() {
|
export default function UserDetailScreen() {
|
||||||
const { id } = useLocalSearchParams<{ id: string }>();
|
const { id } = useLocalSearchParams<{ id: string }>();
|
||||||
const userId = Number(id);
|
const userId = Number(id);
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
const [operation, setOperation] = useState<BalanceOperation>('add');
|
const [operation, setOperation] = useState<BalanceOperation>('add');
|
||||||
const [keySearchText, setKeySearchText] = useState('');
|
const [amount, setAmount] = useState('10');
|
||||||
const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'inactive'>('all');
|
const [notes, setNotes] = useState('');
|
||||||
|
const [formError, setFormError] = useState<string | null>(null);
|
||||||
|
const [searchText, setSearchText] = useState('');
|
||||||
const [copiedKeyId, setCopiedKeyId] = useState<number | null>(null);
|
const [copiedKeyId, setCopiedKeyId] = useState<number | null>(null);
|
||||||
const keySearch = useDebouncedValue(keySearchText.trim().toLowerCase(), 250);
|
const [rangeKey, setRangeKey] = useState<RangeKey>('7d');
|
||||||
const { control, handleSubmit, reset, formState } = useForm<FormValues>({
|
const range = getDateRange(rangeKey);
|
||||||
resolver: zodResolver(schema),
|
|
||||||
defaultValues: {
|
|
||||||
amount: '10',
|
|
||||||
notes: '',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const userQuery = useQuery({
|
const userQuery = useQuery({
|
||||||
queryKey: ['user', userId],
|
queryKey: ['user', userId],
|
||||||
@@ -46,199 +254,329 @@ export default function UserDetailScreen() {
|
|||||||
enabled: Number.isFinite(userId),
|
enabled: Number.isFinite(userId),
|
||||||
});
|
});
|
||||||
|
|
||||||
const usageQuery = useQuery({
|
|
||||||
queryKey: ['user-usage', userId],
|
|
||||||
queryFn: () => getUserUsage(userId),
|
|
||||||
enabled: Number.isFinite(userId),
|
|
||||||
});
|
|
||||||
|
|
||||||
const apiKeysQuery = useQuery({
|
const apiKeysQuery = useQuery({
|
||||||
queryKey: ['user-api-keys', userId],
|
queryKey: ['user-api-keys', userId],
|
||||||
queryFn: () => listUserApiKeys(userId),
|
queryFn: () => listUserApiKeys(userId),
|
||||||
enabled: Number.isFinite(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({
|
const balanceMutation = useMutation({
|
||||||
mutationFn: (values: FormValues & { operation: BalanceOperation }) =>
|
mutationFn: (payload: { amount: number; notes?: string; operation: BalanceOperation }) =>
|
||||||
updateUserBalance(userId, {
|
updateUserBalance(userId, {
|
||||||
balance: Number(values.amount),
|
balance: payload.amount,
|
||||||
operation: values.operation,
|
notes: payload.notes,
|
||||||
notes: values.notes,
|
operation: payload.operation,
|
||||||
}),
|
}),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
|
setFormError(null);
|
||||||
|
setAmount('10');
|
||||||
|
setNotes('');
|
||||||
queryClient.invalidateQueries({ queryKey: ['user', userId] });
|
queryClient.invalidateQueries({ queryKey: ['user', userId] });
|
||||||
queryClient.invalidateQueries({ queryKey: ['users'] });
|
queryClient.invalidateQueries({ queryKey: ['users'] });
|
||||||
reset({ amount: '10', notes: '' });
|
|
||||||
},
|
},
|
||||||
|
onError: (error) => setFormError(getErrorMessage(error)),
|
||||||
});
|
});
|
||||||
|
|
||||||
const user = userQuery.data;
|
const user = userQuery.data;
|
||||||
const usage = usageQuery.data;
|
|
||||||
const apiKeys = apiKeysQuery.data?.items ?? [];
|
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;
|
const filteredApiKeys = useMemo(() => {
|
||||||
}),
|
const keyword = searchText.trim().toLowerCase();
|
||||||
[apiKeys, keySearch, statusFilter]
|
|
||||||
);
|
|
||||||
|
|
||||||
function maskKey(value: string) {
|
return apiKeys.filter((item) => {
|
||||||
if (!value || value.length < 16) {
|
const haystack = [item.name, item.key, item.group?.name].filter(Boolean).join(' ').toLowerCase();
|
||||||
return value;
|
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) {
|
async function copyKey(item: AdminApiKey) {
|
||||||
await Clipboard.setStringAsync(value);
|
await Clipboard.setStringAsync(item.key || '');
|
||||||
setCopiedKeyId(keyId);
|
setCopiedKeyId(item.id);
|
||||||
setTimeout(() => setCopiedKeyId((current) => (current === keyId ? null : current)), 1600);
|
setTimeout(() => {
|
||||||
|
setCopiedKeyId((current) => (current === item.id ? null : current));
|
||||||
|
}, 1500);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ScreenShell
|
<>
|
||||||
title={user?.username || user?.email || '用户详情'}
|
<Stack.Screen options={{ title: user?.email || '用户详情' }} />
|
||||||
subtitle=""
|
<SafeAreaView edges={['bottom']} style={{ flex: 1, backgroundColor: colors.page }}>
|
||||||
titleAside={<Text className="text-[11px] text-[#a2988a]">用户余额、用量与密钥概览。</Text>}
|
<ScrollView style={{ flex: 1 }} contentContainerStyle={{ padding: 16, paddingBottom: 40 }}>
|
||||||
variant="minimal"
|
{userQuery.isLoading ? (
|
||||||
right={
|
<Section title="状态">
|
||||||
<Pressable className="h-11 w-11 items-center justify-center rounded-full bg-[#2d3134]" onPress={() => router.back()}>
|
<Text style={{ color: colors.subtext }}>正在加载用户详情...</Text>
|
||||||
<ChevronLeft color="#f6f1e8" size={18} />
|
</Section>
|
||||||
</Pressable>
|
) : null}
|
||||||
}
|
|
||||||
>
|
|
||||||
<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>
|
|
||||||
|
|
||||||
<ListCard title="月度用量" meta="真实数据来自 /users/:id/usage" icon={ArrowLeftRight}>
|
{userQuery.error ? (
|
||||||
<DetailRow label="Token" value={`${Number(usage?.tokens ?? usage?.total_tokens ?? 0)}`} />
|
<Section title="状态">
|
||||||
<DetailRow label="请求数" value={`${Number(usage?.requests ?? usage?.total_requests ?? 0)}`} />
|
<View style={{ backgroundColor: colors.errorBg, borderRadius: 12, padding: 12 }}>
|
||||||
<DetailRow label="成本" value={`$${Number(usage?.cost ?? usage?.total_cost ?? 0).toFixed(4)}`} />
|
<Text style={{ color: colors.errorText, fontWeight: '700' }}>用户信息加载失败</Text>
|
||||||
</ListCard>
|
<Text style={{ marginTop: 6, color: colors.errorText }}>{getErrorMessage(userQuery.error)}</Text>
|
||||||
|
|
||||||
<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>
|
|
||||||
</View>
|
</View>
|
||||||
<View className="mt-2 flex-row items-center gap-2">
|
</Section>
|
||||||
<Text className="flex-1 text-xs text-[#7d7468]">{maskKey(item.key)}</Text>
|
) : null}
|
||||||
<Pressable
|
|
||||||
className="rounded-full bg-[#e7dfcf] p-2"
|
{user ? (
|
||||||
onPress={() => copyKey(item.id, item.key)}
|
<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} />
|
<Text style={{ fontSize: 11, color: colors.subtext }}>邮箱</Text>
|
||||||
</Pressable>
|
<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>
|
</View>
|
||||||
<Text className="mt-2 text-xs text-[#7d7468]">
|
</Section>
|
||||||
{copiedKeyId === item.id ? '已复制到剪贴板' : `最近使用 ${formatDisplayTime(item.last_used_at)}`}
|
) : null}
|
||||||
</Text>
|
|
||||||
<Text className="mt-2 text-xs text-[#7d7468]">
|
<Section title="总用量">
|
||||||
已用 ${Number(item.quota_used ?? 0).toFixed(2)} / 配额 {item.quota ? `$${Number(item.quota).toFixed(2)}` : '无限制'}
|
<View style={{ flexDirection: 'row', gap: 8, marginBottom: 12 }}>
|
||||||
</Text>
|
{RANGE_OPTIONS.map((item) => {
|
||||||
<Text className="mt-1 text-xs text-[#7d7468]">
|
const active = item.key === rangeKey;
|
||||||
分组 {item.group?.name || '未绑定'} · 5h 用量 {Number(item.usage_5h ?? 0).toFixed(2)}
|
return (
|
||||||
</Text>
|
<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>
|
</View>
|
||||||
))}
|
|
||||||
{filteredApiKeys.length === 0 ? <Text className="text-sm text-[#7d7468]">当前筛选条件下没有 API 密钥。</Text> : null}
|
|
||||||
</View>
|
|
||||||
</ListCard>
|
|
||||||
|
|
||||||
<ListCard title="余额调整" meta="默认执行增加余额,可继续扩成减余额和设定值。" icon={Wallet}>
|
<View style={{ flexDirection: 'row', gap: 8 }}>
|
||||||
<View className="gap-3">
|
<MetricCard label="请求" value={formatTokenValue(usageStatsQuery.data?.total_requests)} />
|
||||||
<Controller
|
<MetricCard label="Token" value={formatTokenValue(usageStatsQuery.data?.total_tokens)} />
|
||||||
control={control}
|
<MetricCard label="成本" value={formatUsageCost(usageStatsQuery.data)} />
|
||||||
name="amount"
|
</View>
|
||||||
render={({ field: { onChange, value } }) => (
|
|
||||||
<TextInput
|
{usageStatsQuery.data ? (
|
||||||
value={value}
|
<Text style={{ marginTop: 10, fontSize: 12, color: colors.subtext }}>
|
||||||
onChangeText={onChange}
|
输入 {formatTokenValue(usageStatsQuery.data.total_input_tokens)} · 输出 {formatTokenValue(usageStatsQuery.data.total_output_tokens)}
|
||||||
keyboardType="decimal-pad"
|
</Text>
|
||||||
placeholder="输入金额"
|
) : null}
|
||||||
placeholderTextColor="#9b9081"
|
|
||||||
className="rounded-[18px] bg-[#f1ece2] px-4 py-4 text-base text-[#16181a]"
|
{usageStatsQuery.isLoading ? <Text style={{ marginTop: 12, color: colors.subtext }}>正在加载用量统计...</Text> : null}
|
||||||
/>
|
|
||||||
)}
|
{usageStatsQuery.error ? (
|
||||||
/>
|
<View style={{ marginTop: 12, backgroundColor: colors.errorBg, borderRadius: 12, padding: 12 }}>
|
||||||
<View className="flex-row gap-2">
|
<Text style={{ color: colors.errorText, fontWeight: '700' }}>用量统计加载失败</Text>
|
||||||
{(['add', 'subtract', 'set'] as BalanceOperation[]).map((item) => (
|
<Text style={{ marginTop: 6, color: colors.errorText }}>{getErrorMessage(usageStatsQuery.error)}</Text>
|
||||||
<Pressable
|
</View>
|
||||||
key={item}
|
) : null}
|
||||||
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)}
|
{!usageSnapshotQuery.isLoading && trendPoints.length > 1 ? (
|
||||||
>
|
<View style={{ marginTop: 14 }}>
|
||||||
<Text className={operation === item ? 'text-center text-sm font-semibold text-white' : 'text-center text-sm font-semibold text-[#4e463e]'}>
|
<LineTrendChart
|
||||||
{item === 'add' ? '增加' : item === 'subtract' ? '扣减' : '设为'}
|
title="用量趋势"
|
||||||
</Text>
|
subtitle={`${range.start_date} 到 ${range.end_date}`}
|
||||||
</Pressable>
|
points={trendPoints}
|
||||||
))}
|
color="#1d5f55"
|
||||||
</View>
|
formatValue={(value) => formatTokenValue(value)}
|
||||||
<Controller
|
compact
|
||||||
control={control}
|
/>
|
||||||
name="notes"
|
</View>
|
||||||
render={({ field: { onChange, value } }) => (
|
) : null}
|
||||||
<TextInput
|
|
||||||
value={value}
|
{usageSnapshotQuery.isLoading ? <Text style={{ marginTop: 12, color: colors.subtext }}>正在加载趋势图...</Text> : null}
|
||||||
onChangeText={onChange}
|
|
||||||
placeholder="备注,可留空"
|
{usageSnapshotQuery.error ? (
|
||||||
placeholderTextColor="#9b9081"
|
<View style={{ marginTop: 12, backgroundColor: colors.errorBg, borderRadius: 12, padding: 12 }}>
|
||||||
className="rounded-[18px] bg-[#f1ece2] px-4 py-4 text-base text-[#16181a]"
|
<Text style={{ color: colors.errorText, fontWeight: '700' }}>趋势加载失败</Text>
|
||||||
/>
|
<Text style={{ marginTop: 6, color: colors.errorText }}>{getErrorMessage(usageSnapshotQuery.error)}</Text>
|
||||||
)}
|
</View>
|
||||||
/>
|
) : null}
|
||||||
{formState.errors.amount ? <Text className="text-sm text-[#c25d35]">{formState.errors.amount.message}</Text> : null}
|
</Section>
|
||||||
<Pressable
|
|
||||||
className="rounded-[18px] bg-[#1d5f55] px-4 py-4"
|
<Section title="API Keys">
|
||||||
onPress={handleSubmit((values) => balanceMutation.mutate({ ...values, operation }))}
|
<TextInput
|
||||||
>
|
value={searchText}
|
||||||
<Text className="text-center text-sm font-semibold tracking-[1.2px] text-white">
|
onChangeText={setSearchText}
|
||||||
{balanceMutation.isPending ? '提交中...' : operation === 'add' ? '增加余额' : operation === 'subtract' ? '扣减余额' : '设置余额'}
|
placeholder="搜索名称 / Key / 分组"
|
||||||
</Text>
|
placeholderTextColor="#9a9082"
|
||||||
</Pressable>
|
style={{
|
||||||
</View>
|
backgroundColor: colors.muted,
|
||||||
</ListCard>
|
borderWidth: 1,
|
||||||
</ScreenShell>
|
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>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,8 +9,10 @@
|
|||||||
## 已完成配置
|
## 已完成配置
|
||||||
|
|
||||||
- `app.json` 已配置 `owner`
|
- `app.json` 已配置 `owner`
|
||||||
|
- `app.json` 已配置 `scheme = sub2apimobile`
|
||||||
- `app.json` 已配置 `runtimeVersion.policy = appVersion`
|
- `app.json` 已配置 `runtimeVersion.policy = appVersion`
|
||||||
- `app.json` 已配置 `updates.url`
|
- `app.json` 已配置 `updates.url`
|
||||||
|
- `package.json` 已包含 `expo-dev-client`
|
||||||
- `eas.json` 已配置 `development / preview / production` 三套 profile
|
- `eas.json` 已配置 `development / preview / production` 三套 profile
|
||||||
|
|
||||||
## 登录状态检查
|
## 登录状态检查
|
||||||
@@ -20,6 +22,45 @@ npx expo whoami
|
|||||||
npx eas whoami
|
npx eas whoami
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## 关键结论
|
||||||
|
|
||||||
|
### 1. Expo Go 适合什么
|
||||||
|
|
||||||
|
`Expo Go` 适合:
|
||||||
|
|
||||||
|
- `npx expo start`
|
||||||
|
- 本地 Metro 联调
|
||||||
|
- 快速查看 JS / RN 页面改动
|
||||||
|
|
||||||
|
### 2. Expo Go 不适合什么
|
||||||
|
|
||||||
|
这次已经实测确认:
|
||||||
|
|
||||||
|
- 不能把 `Expo Go` 当成 `EAS Update branch` 的稳定预览壳
|
||||||
|
- 想在 Expo Updates 里通过 branch 打开新版本,应该使用 `development build / dev client`
|
||||||
|
|
||||||
|
### 3. branch 预览要满足什么
|
||||||
|
|
||||||
|
要稳定预览 branch/update,需要同时满足:
|
||||||
|
|
||||||
|
- 已发布 `eas update --branch <branch>`
|
||||||
|
- App 壳支持 `expo-updates`
|
||||||
|
- App 壳包含 `expo-dev-client` 或对应原生构建
|
||||||
|
- 项目配置了自定义 `scheme`
|
||||||
|
- `runtimeVersion` 与 update 一致
|
||||||
|
|
||||||
|
## 本地开发
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run start
|
||||||
|
```
|
||||||
|
|
||||||
|
如果要用 dev client 连本地:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run start:dev-client
|
||||||
|
```
|
||||||
|
|
||||||
## 预览包
|
## 预览包
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -34,6 +75,13 @@ npm run eas:build:preview
|
|||||||
npm run eas:build:development
|
npm run eas:build:development
|
||||||
```
|
```
|
||||||
|
|
||||||
|
也可以分平台:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run eas:build:development:android
|
||||||
|
npm run eas:build:development:ios
|
||||||
|
```
|
||||||
|
|
||||||
当前 `development` profile 已配置:
|
当前 `development` profile 已配置:
|
||||||
|
|
||||||
- `developmentClient: true`
|
- `developmentClient: true`
|
||||||
@@ -42,6 +90,92 @@ npm run eas:build:development
|
|||||||
|
|
||||||
适合先生成一个测试壳,后续再配合 `Expo / EAS Update` 做快速验证。
|
适合先生成一个测试壳,后续再配合 `Expo / EAS Update` 做快速验证。
|
||||||
|
|
||||||
|
## 推荐发布流程
|
||||||
|
|
||||||
|
### 方案 A:本地开发调试
|
||||||
|
|
||||||
|
适用于:
|
||||||
|
|
||||||
|
- UI 改动
|
||||||
|
- 页面白屏排查
|
||||||
|
- 路由调试
|
||||||
|
|
||||||
|
命令:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run start
|
||||||
|
```
|
||||||
|
|
||||||
|
### 方案 B:发 branch 给 dev client 验证
|
||||||
|
|
||||||
|
适用于:
|
||||||
|
|
||||||
|
- 想在 Expo Updates 里看到新的 branch/update
|
||||||
|
- 想让测试壳直接吃 OTA
|
||||||
|
|
||||||
|
步骤:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx eas-cli@latest update --branch preview --message "your message"
|
||||||
|
```
|
||||||
|
|
||||||
|
然后在 dev client / development build 中验证对应 branch。
|
||||||
|
|
||||||
|
### 方案 C:先出壳,再吃 OTA
|
||||||
|
|
||||||
|
如果还没有合适的 dev client:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run eas:build:development:android
|
||||||
|
npm run eas:build:development:ios
|
||||||
|
```
|
||||||
|
|
||||||
|
装好开发壳后,再发:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx eas-cli@latest update --branch preview --message "your message"
|
||||||
|
```
|
||||||
|
|
||||||
|
## 本次实战记录
|
||||||
|
|
||||||
|
本次已经验证通过的 OTA 发布命令:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx eas-cli@latest update --branch preview --message "align dev-client and user detail 2026-03-08"
|
||||||
|
```
|
||||||
|
|
||||||
|
本次成功发布结果:
|
||||||
|
|
||||||
|
- Branch: `preview`
|
||||||
|
- Message: `align dev-client and user detail 2026-03-08`
|
||||||
|
- Update group ID: `b6744438-929d-4206-b1eb-0887eaf3f97d`
|
||||||
|
- iOS update ID: `019ccd68-a2af-7ba1-af68-7958f454e93c`
|
||||||
|
- Android update ID: `019ccd68-a2af-7166-9e9d-9619bd1b8e0e`
|
||||||
|
|
||||||
|
## 常见问题
|
||||||
|
|
||||||
|
### 1. 本地正常,发到 branch 后白屏
|
||||||
|
|
||||||
|
先排查:
|
||||||
|
|
||||||
|
- 当前打开的是不是 `Expo Go`
|
||||||
|
- 当前壳是不是 `development build`
|
||||||
|
- 项目是否配置了 `scheme`
|
||||||
|
- `runtimeVersion` 是否匹配
|
||||||
|
|
||||||
|
### 2. branch 发上去了,但设备没更新
|
||||||
|
|
||||||
|
先确认:
|
||||||
|
|
||||||
|
- 看的是不是正确 project
|
||||||
|
- branch 是否是 `preview`
|
||||||
|
- 壳的 channel 是否匹配
|
||||||
|
- 使用的是不是 dev client / 原生预览壳
|
||||||
|
|
||||||
|
### 3. Deep link 报错 no custom scheme defined
|
||||||
|
|
||||||
|
说明 `app.json` 没有自定义 `scheme`,或者当前原生壳太旧,需要重新构建。
|
||||||
|
|
||||||
## GitHub Actions 构建
|
## GitHub Actions 构建
|
||||||
|
|
||||||
仓库已提供工作流:`.github/workflows/eas-build.yml`
|
仓库已提供工作流:`.github/workflows/eas-build.yml`
|
||||||
@@ -85,10 +219,3 @@ npx eas update --branch preview --message "preview update"
|
|||||||
```bash
|
```bash
|
||||||
npx eas update --branch production --message "production update"
|
npx eas update --branch production --message "production update"
|
||||||
```
|
```
|
||||||
|
|
||||||
## 当前还需要你补的内容
|
|
||||||
|
|
||||||
- iOS 的 `bundleIdentifier`
|
|
||||||
- Android 的 `package`
|
|
||||||
|
|
||||||
如果不补这两个标识,原生构建时 EAS 还会继续要求你确认或生成。
|
|
||||||
|
|||||||
6324
package-lock.json
generated
6324
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
50
package.json
50
package.json
@@ -13,43 +13,47 @@
|
|||||||
"eas:build:preview": "eas build --profile preview",
|
"eas:build:preview": "eas build --profile preview",
|
||||||
"eas:build:production": "eas build --profile production",
|
"eas:build:production": "eas build --profile production",
|
||||||
"eas:update:preview": "eas update --branch preview --message",
|
"eas:update:preview": "eas update --branch preview --message",
|
||||||
"eas:update:production": "eas update --branch production --message"
|
"eas:update:production": "eas update --branch production --message",
|
||||||
|
"start:dev-client": "expo start --dev-client",
|
||||||
|
"eas:build:development:android": "eas build -p android --profile development",
|
||||||
|
"eas:build:development:ios": "eas build -p ios --profile development"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@expo/vector-icons": "^15.1.1",
|
||||||
"@hookform/resolvers": "^5.2.2",
|
"@hookform/resolvers": "^5.2.2",
|
||||||
"@tanstack/react-query": "^5.90.21",
|
"@tanstack/react-query": "^5.90.21",
|
||||||
"cors": "^2.8.6",
|
"cors": "^2.8.6",
|
||||||
"expo": "~55.0.5",
|
"expo": "~54.0.33",
|
||||||
"expo-clipboard": "~55.0.8",
|
"expo-clipboard": "~8.0.8",
|
||||||
"expo-constants": "~55.0.7",
|
"expo-constants": "~18.0.13",
|
||||||
"expo-dev-client": "~6.0.16",
|
"expo-dev-client": "~6.0.20",
|
||||||
"expo-linking": "~55.0.7",
|
"expo-font": "~14.0.11",
|
||||||
"expo-router": "~55.0.4",
|
"expo-linking": "~8.0.11",
|
||||||
"expo-secure-store": "~55.0.8",
|
"expo-router": "~6.0.23",
|
||||||
"expo-status-bar": "~55.0.4",
|
"expo-secure-store": "~15.0.8",
|
||||||
"expo-updates": "~55.0.12",
|
"expo-status-bar": "~3.0.9",
|
||||||
|
"expo-updates": "~29.0.16",
|
||||||
"express": "^5.2.1",
|
"express": "^5.2.1",
|
||||||
"lucide-react-native": "^0.577.0",
|
"lucide-react-native": "^0.577.0",
|
||||||
"react": "19.2.0",
|
"react": "19.1.0",
|
||||||
"react-dom": "19.2.0",
|
"react-dom": "19.1.0",
|
||||||
"react-hook-form": "^7.71.2",
|
"react-hook-form": "^7.71.2",
|
||||||
"react-native": "0.83.2",
|
"react-native": "0.81.5",
|
||||||
"react-native-gesture-handler": "~2.30.0",
|
"react-native-gesture-handler": "~2.28.0",
|
||||||
"react-native-reanimated": "4.2.1",
|
"react-native-reanimated": "~4.1.1",
|
||||||
"react-native-safe-area-context": "~5.6.2",
|
"react-native-safe-area-context": "~5.6.0",
|
||||||
"react-native-screens": "~4.23.0",
|
"react-native-screens": "~4.16.0",
|
||||||
"react-native-svg": "15.15.3",
|
"react-native-svg": "15.12.1",
|
||||||
"react-native-web": "^0.21.2",
|
"react-native-web": "~0.21.0",
|
||||||
"react-native-worklets": "0.7.2",
|
"react-native-worklets": "0.5.1",
|
||||||
"tailwindcss": "^4.2.1",
|
"tailwindcss": "^4.2.1",
|
||||||
"uniwind": "^1.5.0",
|
"uniwind": "^1.3.2",
|
||||||
"valtio": "^2.3.1",
|
"valtio": "^2.3.1",
|
||||||
"zod": "^4.3.6"
|
"zod": "^4.3.6"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/react": "~19.2.2",
|
"@types/react": "~19.1.0",
|
||||||
"concurrently": "^9.2.1",
|
"concurrently": "^9.2.1",
|
||||||
"eas-cli": "^18.1.0",
|
|
||||||
"typescript": "~5.9.2"
|
"typescript": "~5.9.2"
|
||||||
},
|
},
|
||||||
"private": true
|
"private": true
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { useMemo } from 'react';
|
||||||
import { Text, View } from 'react-native';
|
import { Text, View } from 'react-native';
|
||||||
import Svg, { Defs, LinearGradient, Path, Stop } from 'react-native-svg';
|
import Svg, { Defs, LinearGradient, Path, Stop } from 'react-native-svg';
|
||||||
|
|
||||||
@@ -28,6 +29,10 @@ export function LineTrendChart({
|
|||||||
const maxValue = Math.max(...points.map((point) => point.value), 1);
|
const maxValue = Math.max(...points.map((point) => point.value), 1);
|
||||||
const minValue = Math.min(...points.map((point) => point.value), 0);
|
const minValue = Math.min(...points.map((point) => point.value), 0);
|
||||||
const range = Math.max(maxValue - minValue, 1);
|
const range = Math.max(maxValue - minValue, 1);
|
||||||
|
const gradientId = useMemo(
|
||||||
|
() => `trendFill-${title.replace(/[^a-zA-Z0-9_-]/g, '')}-${compact ? 'compact' : 'full'}`,
|
||||||
|
[compact, title]
|
||||||
|
);
|
||||||
|
|
||||||
const line = points
|
const line = points
|
||||||
.map((point, index) => {
|
.map((point, index) => {
|
||||||
@@ -53,18 +58,18 @@ export function LineTrendChart({
|
|||||||
<View className={`overflow-hidden rounded-[14px] bg-[#f4efe4] p-3 ${compact ? 'mt-3' : 'mt-4'}`}>
|
<View className={`overflow-hidden rounded-[14px] bg-[#f4efe4] p-3 ${compact ? 'mt-3' : 'mt-4'}`}>
|
||||||
<Svg width="100%" height={height} viewBox={`0 0 ${width} ${height}`}>
|
<Svg width="100%" height={height} viewBox={`0 0 ${width} ${height}`}>
|
||||||
<Defs>
|
<Defs>
|
||||||
<LinearGradient id="trendFill" x1="0" x2="0" y1="0" y2="1">
|
<LinearGradient id={gradientId} x1="0" x2="0" y1="0" y2="1">
|
||||||
<Stop offset="0%" stopColor={color} stopOpacity="0.28" />
|
<Stop offset="0%" stopColor={color} stopOpacity="0.28" />
|
||||||
<Stop offset="100%" stopColor={color} stopOpacity="0.02" />
|
<Stop offset="100%" stopColor={color} stopOpacity="0.02" />
|
||||||
</LinearGradient>
|
</LinearGradient>
|
||||||
</Defs>
|
</Defs>
|
||||||
<Path d={area} fill="url(#trendFill)" />
|
<Path d={area} fill={`url(#${gradientId})`} />
|
||||||
<Path d={line} fill="none" stroke={color} strokeWidth="3" strokeLinejoin="round" strokeLinecap="round" />
|
<Path d={line} fill="none" stroke={color} strokeWidth="3" strokeLinejoin="round" strokeLinecap="round" />
|
||||||
</Svg>
|
</Svg>
|
||||||
|
|
||||||
<View className="mt-2 flex-row justify-between">
|
<View className="mt-2 flex-row justify-between">
|
||||||
{tickPoints.map((point) => (
|
{tickPoints.map((point, index) => (
|
||||||
<Text key={point.label} className={`text-[#7d7468] ${compact ? 'text-[10px]' : 'text-xs'}`}>
|
<Text key={`${point.label}-${index}`} className={`text-[#7d7468] ${compact ? 'text-[10px]' : 'text-xs'}`}>
|
||||||
{point.label}
|
{point.label}
|
||||||
</Text>
|
</Text>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { PropsWithChildren, ReactNode } from 'react';
|
import type { PropsWithChildren, ReactNode } from 'react';
|
||||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||||
import { ScrollView, Text, View } from 'react-native';
|
import { RefreshControl, ScrollView, Text, View } from 'react-native';
|
||||||
|
|
||||||
type ScreenShellProps = PropsWithChildren<{
|
type ScreenShellProps = PropsWithChildren<{
|
||||||
title: string;
|
title: string;
|
||||||
@@ -12,6 +12,8 @@ type ScreenShellProps = PropsWithChildren<{
|
|||||||
bottomInsetClassName?: string;
|
bottomInsetClassName?: string;
|
||||||
horizontalInsetClassName?: string;
|
horizontalInsetClassName?: string;
|
||||||
contentGapClassName?: string;
|
contentGapClassName?: string;
|
||||||
|
refreshing?: boolean;
|
||||||
|
onRefresh?: () => void | Promise<void>;
|
||||||
}>;
|
}>;
|
||||||
|
|
||||||
function ScreenHeader({
|
function ScreenHeader({
|
||||||
@@ -66,6 +68,8 @@ export function ScreenShell({
|
|||||||
bottomInsetClassName = 'pb-24',
|
bottomInsetClassName = 'pb-24',
|
||||||
horizontalInsetClassName = 'px-5',
|
horizontalInsetClassName = 'px-5',
|
||||||
contentGapClassName = 'mt-4 gap-4',
|
contentGapClassName = 'mt-4 gap-4',
|
||||||
|
refreshing = false,
|
||||||
|
onRefresh,
|
||||||
}: ScreenShellProps) {
|
}: ScreenShellProps) {
|
||||||
if (!scroll) {
|
if (!scroll) {
|
||||||
return (
|
return (
|
||||||
@@ -80,9 +84,15 @@ export function ScreenShell({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<SafeAreaView className="flex-1 bg-[#f4efe4]">
|
<SafeAreaView className="flex-1 bg-[#f4efe4]">
|
||||||
<ScrollView className="flex-1" contentContainerClassName={`${horizontalInsetClassName} ${bottomInsetClassName}`}>
|
<ScrollView
|
||||||
<ScreenHeader title={title} subtitle={subtitle} titleAside={titleAside} right={right} variant={variant} />
|
className="flex-1"
|
||||||
<View className={contentGapClassName}>{children}</View>
|
showsVerticalScrollIndicator={false}
|
||||||
|
refreshControl={onRefresh ? <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor="#1d5f55" /> : undefined}
|
||||||
|
>
|
||||||
|
<View className={`${horizontalInsetClassName} ${bottomInsetClassName}`}>
|
||||||
|
<ScreenHeader title={title} subtitle={subtitle} titleAside={titleAside} right={right} variant={variant} />
|
||||||
|
<View className={contentGapClassName}>{children}</View>
|
||||||
|
</View>
|
||||||
</ScrollView>
|
</ScrollView>
|
||||||
</SafeAreaView>
|
</SafeAreaView>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,14 +1,6 @@
|
|||||||
import { adminConfigState } from '@/src/store/admin-config';
|
import { adminConfigState } from '@/src/store/admin-config';
|
||||||
import type { ApiEnvelope } from '@/src/types/admin';
|
import type { ApiEnvelope } from '@/src/types/admin';
|
||||||
|
|
||||||
function isProxyBaseUrl(baseUrl: string) {
|
|
||||||
return /localhost:8787$/.test(baseUrl) || /127\.0\.0\.1:8787$/.test(baseUrl);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isLocalProxyBaseUrl(baseUrl: string) {
|
|
||||||
return isProxyBaseUrl(baseUrl);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function adminFetch<T>(
|
export async function adminFetch<T>(
|
||||||
path: string,
|
path: string,
|
||||||
init: RequestInit = {},
|
init: RequestInit = {},
|
||||||
@@ -21,7 +13,7 @@ export async function adminFetch<T>(
|
|||||||
throw new Error('BASE_URL_REQUIRED');
|
throw new Error('BASE_URL_REQUIRED');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!adminApiKey && !isProxyBaseUrl(baseUrl)) {
|
if (!adminApiKey) {
|
||||||
throw new Error('ADMIN_API_KEY_REQUIRED');
|
throw new Error('ADMIN_API_KEY_REQUIRED');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,13 +8,15 @@ import type {
|
|||||||
AdminUser,
|
AdminUser,
|
||||||
BalanceOperation,
|
BalanceOperation,
|
||||||
DashboardModelStats,
|
DashboardModelStats,
|
||||||
|
DashboardSnapshot,
|
||||||
DashboardStats,
|
DashboardStats,
|
||||||
DashboardTrend,
|
DashboardTrend,
|
||||||
PaginatedData,
|
PaginatedData,
|
||||||
|
UsageStats,
|
||||||
UserUsageSummary,
|
UserUsageSummary,
|
||||||
} from '@/src/types/admin';
|
} from '@/src/types/admin';
|
||||||
|
|
||||||
function buildQuery(params: Record<string, string | number | boolean | undefined>) {
|
function buildQuery(params: Record<string, string | number | boolean | null | undefined>) {
|
||||||
const query = new URLSearchParams();
|
const query = new URLSearchParams();
|
||||||
|
|
||||||
Object.entries(params).forEach(([key, value]) => {
|
Object.entries(params).forEach(([key, value]) => {
|
||||||
@@ -51,6 +53,38 @@ export function getDashboardModels(params: { start_date: string; end_date: strin
|
|||||||
return adminFetch<DashboardModelStats>(`/api/v1/admin/dashboard/models${buildQuery(params)}`);
|
return adminFetch<DashboardModelStats>(`/api/v1/admin/dashboard/models${buildQuery(params)}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function getDashboardSnapshot(params: {
|
||||||
|
start_date: string;
|
||||||
|
end_date: string;
|
||||||
|
granularity?: 'day' | 'hour';
|
||||||
|
account_id?: number;
|
||||||
|
user_id?: number;
|
||||||
|
group_id?: number;
|
||||||
|
model?: string;
|
||||||
|
request_type?: string;
|
||||||
|
billing_type?: string | null;
|
||||||
|
include_stats?: boolean;
|
||||||
|
include_trend?: boolean;
|
||||||
|
include_model_stats?: boolean;
|
||||||
|
include_group_stats?: boolean;
|
||||||
|
include_users_trend?: boolean;
|
||||||
|
}) {
|
||||||
|
return adminFetch<DashboardSnapshot>(`/api/v1/admin/dashboard/snapshot-v2${buildQuery(params)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getUsageStats(params: {
|
||||||
|
start_date: string;
|
||||||
|
end_date: string;
|
||||||
|
user_id?: number;
|
||||||
|
account_id?: number;
|
||||||
|
group_id?: number;
|
||||||
|
model?: string;
|
||||||
|
request_type?: string;
|
||||||
|
billing_type?: string | null;
|
||||||
|
}) {
|
||||||
|
return adminFetch<UsageStats>(`/api/v1/admin/usage/stats${buildQuery(params)}`);
|
||||||
|
}
|
||||||
|
|
||||||
export function listUsers(search = '') {
|
export function listUsers(search = '') {
|
||||||
return adminFetch<PaginatedData<AdminUser>>(
|
return adminFetch<PaginatedData<AdminUser>>(
|
||||||
`/api/v1/admin/users${buildQuery({ page: 1, page_size: 20, search: search.trim() })}`
|
`/api/v1/admin/users${buildQuery({ page: 1, page_size: 20, search: search.trim() })}`
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import * as SecureStore from 'expo-secure-store';
|
import * as SecureStore from 'expo-secure-store';
|
||||||
|
import { Platform } from 'react-native';
|
||||||
const { proxy } = require('valtio');
|
const { proxy } = require('valtio');
|
||||||
|
|
||||||
const BASE_URL_KEY = 'sub2api_base_url';
|
const BASE_URL_KEY = 'sub2api_base_url';
|
||||||
@@ -67,39 +68,51 @@ export function getDefaultAdminConfig() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function getItem(key: string) {
|
async function getItem(key: string) {
|
||||||
if (typeof window !== 'undefined') {
|
try {
|
||||||
if (typeof localStorage === 'undefined') {
|
if (Platform.OS === 'web') {
|
||||||
return null;
|
if (typeof localStorage === 'undefined') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return localStorage.getItem(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
return localStorage.getItem(key);
|
return await SecureStore.getItemAsync(key);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return SecureStore.getItemAsync(key);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function setItem(key: string, value: string) {
|
async function setItem(key: string, value: string) {
|
||||||
if (typeof window !== 'undefined') {
|
try {
|
||||||
if (typeof localStorage !== 'undefined') {
|
if (Platform.OS === 'web') {
|
||||||
localStorage.setItem(key, value);
|
if (typeof localStorage !== 'undefined') {
|
||||||
|
localStorage.setItem(key, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await SecureStore.setItemAsync(key, value);
|
||||||
|
} catch {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await SecureStore.setItemAsync(key, value);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function deleteItem(key: string) {
|
async function deleteItem(key: string) {
|
||||||
if (typeof window !== 'undefined') {
|
try {
|
||||||
if (typeof localStorage !== 'undefined') {
|
if (Platform.OS === 'web') {
|
||||||
localStorage.removeItem(key);
|
if (typeof localStorage !== 'undefined') {
|
||||||
|
localStorage.removeItem(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await SecureStore.deleteItemAsync(key);
|
||||||
|
} catch {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await SecureStore.deleteItemAsync(key);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const adminConfigState = proxy({
|
export const adminConfigState = proxy({
|
||||||
@@ -112,98 +125,104 @@ export const adminConfigState = proxy({
|
|||||||
|
|
||||||
export async function hydrateAdminConfig() {
|
export async function hydrateAdminConfig() {
|
||||||
const defaults = getDefaultAdminConfig();
|
const defaults = getDefaultAdminConfig();
|
||||||
const [baseUrl, adminApiKey, rawAccounts, activeAccountId] = await Promise.all([
|
|
||||||
getItem(BASE_URL_KEY),
|
|
||||||
getItem(ADMIN_KEY_KEY),
|
|
||||||
getItem(ACCOUNTS_KEY),
|
|
||||||
getItem(ACTIVE_ACCOUNT_ID_KEY),
|
|
||||||
]);
|
|
||||||
|
|
||||||
let accounts: AdminAccountProfile[] = [];
|
try {
|
||||||
|
const [baseUrl, adminApiKey, rawAccounts, activeAccountId] = await Promise.all([
|
||||||
|
getItem(BASE_URL_KEY),
|
||||||
|
getItem(ADMIN_KEY_KEY),
|
||||||
|
getItem(ACCOUNTS_KEY),
|
||||||
|
getItem(ACTIVE_ACCOUNT_ID_KEY),
|
||||||
|
]);
|
||||||
|
|
||||||
if (rawAccounts) {
|
let accounts: AdminAccountProfile[] = [];
|
||||||
try {
|
|
||||||
const parsed = JSON.parse(rawAccounts) as AdminAccountProfile[];
|
if (rawAccounts) {
|
||||||
accounts = Array.isArray(parsed) ? parsed.map((account) => normalizeAccount(account)) : [];
|
try {
|
||||||
} catch {
|
const parsed = JSON.parse(rawAccounts) as AdminAccountProfile[];
|
||||||
accounts = [];
|
accounts = Array.isArray(parsed) ? parsed.map((account) => normalizeAccount(account)) : [];
|
||||||
|
} catch {
|
||||||
|
accounts = [];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (accounts.length === 0 && baseUrl) {
|
||||||
|
const legacyConfig = normalizeConfig({
|
||||||
|
baseUrl,
|
||||||
|
adminApiKey: adminApiKey ?? defaults.adminApiKey,
|
||||||
|
});
|
||||||
|
|
||||||
|
accounts = [
|
||||||
|
{
|
||||||
|
id: createAccountId(),
|
||||||
|
label: getAccountLabel(legacyConfig.baseUrl),
|
||||||
|
...legacyConfig,
|
||||||
|
updatedAt: new Date().toISOString(),
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
const sortedAccounts = sortAccounts(accounts);
|
||||||
|
const activeAccount = getNextActiveAccount(sortedAccounts, activeAccountId ?? undefined);
|
||||||
|
const nextActiveAccountId = activeAccount?.id || '';
|
||||||
|
|
||||||
|
adminConfigState.accounts = sortedAccounts;
|
||||||
|
adminConfigState.activeAccountId = nextActiveAccountId;
|
||||||
|
adminConfigState.baseUrl = activeAccount?.baseUrl ?? defaults.baseUrl;
|
||||||
|
adminConfigState.adminApiKey = activeAccount?.adminApiKey ?? defaults.adminApiKey;
|
||||||
|
|
||||||
|
await Promise.all([
|
||||||
|
setItem(ACCOUNTS_KEY, JSON.stringify(sortedAccounts)),
|
||||||
|
nextActiveAccountId ? setItem(ACTIVE_ACCOUNT_ID_KEY, nextActiveAccountId) : deleteItem(ACTIVE_ACCOUNT_ID_KEY),
|
||||||
|
setItem(BASE_URL_KEY, activeAccount?.baseUrl ?? defaults.baseUrl),
|
||||||
|
setItem(ADMIN_KEY_KEY, activeAccount?.adminApiKey ?? defaults.adminApiKey),
|
||||||
|
]);
|
||||||
|
} finally {
|
||||||
|
adminConfigState.hydrated = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (accounts.length === 0 && baseUrl) {
|
|
||||||
const legacyConfig = normalizeConfig({
|
|
||||||
baseUrl,
|
|
||||||
adminApiKey: adminApiKey ?? defaults.adminApiKey,
|
|
||||||
});
|
|
||||||
|
|
||||||
accounts = [
|
|
||||||
{
|
|
||||||
id: createAccountId(),
|
|
||||||
label: getAccountLabel(legacyConfig.baseUrl),
|
|
||||||
...legacyConfig,
|
|
||||||
updatedAt: new Date().toISOString(),
|
|
||||||
enabled: true,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
const sortedAccounts = sortAccounts(accounts);
|
|
||||||
const activeAccount = getNextActiveAccount(sortedAccounts, activeAccountId ?? undefined);
|
|
||||||
const nextActiveAccountId = activeAccount?.id || '';
|
|
||||||
|
|
||||||
adminConfigState.accounts = sortedAccounts;
|
|
||||||
adminConfigState.activeAccountId = nextActiveAccountId;
|
|
||||||
adminConfigState.baseUrl = activeAccount?.baseUrl ?? defaults.baseUrl;
|
|
||||||
adminConfigState.adminApiKey = activeAccount?.adminApiKey ?? defaults.adminApiKey;
|
|
||||||
|
|
||||||
adminConfigState.hydrated = true;
|
|
||||||
|
|
||||||
await Promise.all([
|
|
||||||
setItem(ACCOUNTS_KEY, JSON.stringify(sortedAccounts)),
|
|
||||||
nextActiveAccountId ? setItem(ACTIVE_ACCOUNT_ID_KEY, nextActiveAccountId) : deleteItem(ACTIVE_ACCOUNT_ID_KEY),
|
|
||||||
setItem(BASE_URL_KEY, activeAccount?.baseUrl ?? defaults.baseUrl),
|
|
||||||
setItem(ADMIN_KEY_KEY, activeAccount?.adminApiKey ?? defaults.adminApiKey),
|
|
||||||
]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function saveAdminConfig(input: { baseUrl: string; adminApiKey: string }) {
|
export async function saveAdminConfig(input: { baseUrl: string; adminApiKey: string }) {
|
||||||
adminConfigState.saving = true;
|
adminConfigState.saving = true;
|
||||||
|
|
||||||
const normalized = normalizeConfig(input);
|
try {
|
||||||
const nextUpdatedAt = new Date().toISOString();
|
const normalized = normalizeConfig(input);
|
||||||
const existingAccount = adminConfigState.accounts.find(
|
const nextUpdatedAt = new Date().toISOString();
|
||||||
(account: AdminAccountProfile) => account.baseUrl === normalized.baseUrl && account.adminApiKey === normalized.adminApiKey
|
const existingAccount = adminConfigState.accounts.find(
|
||||||
);
|
(account: AdminAccountProfile) => account.baseUrl === normalized.baseUrl && account.adminApiKey === normalized.adminApiKey
|
||||||
const nextAccount: AdminAccountProfile = existingAccount
|
);
|
||||||
? {
|
const nextAccount: AdminAccountProfile = existingAccount
|
||||||
...existingAccount,
|
? {
|
||||||
label: getAccountLabel(normalized.baseUrl),
|
...existingAccount,
|
||||||
updatedAt: nextUpdatedAt,
|
label: getAccountLabel(normalized.baseUrl),
|
||||||
}
|
updatedAt: nextUpdatedAt,
|
||||||
: {
|
}
|
||||||
id: createAccountId(),
|
: {
|
||||||
label: getAccountLabel(normalized.baseUrl),
|
id: createAccountId(),
|
||||||
...normalized,
|
label: getAccountLabel(normalized.baseUrl),
|
||||||
updatedAt: nextUpdatedAt,
|
...normalized,
|
||||||
enabled: true,
|
updatedAt: nextUpdatedAt,
|
||||||
};
|
enabled: true,
|
||||||
const nextAccounts = sortAccounts([
|
};
|
||||||
nextAccount,
|
const nextAccounts = sortAccounts([
|
||||||
...adminConfigState.accounts.filter((account: AdminAccountProfile) => account.id !== nextAccount.id),
|
nextAccount,
|
||||||
]);
|
...adminConfigState.accounts.filter((account: AdminAccountProfile) => account.id !== nextAccount.id),
|
||||||
|
]);
|
||||||
|
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
setItem(BASE_URL_KEY, normalized.baseUrl),
|
setItem(BASE_URL_KEY, normalized.baseUrl),
|
||||||
setItem(ADMIN_KEY_KEY, normalized.adminApiKey),
|
setItem(ADMIN_KEY_KEY, normalized.adminApiKey),
|
||||||
setItem(ACCOUNTS_KEY, JSON.stringify(nextAccounts)),
|
setItem(ACCOUNTS_KEY, JSON.stringify(nextAccounts)),
|
||||||
setItem(ACTIVE_ACCOUNT_ID_KEY, nextAccount.id),
|
setItem(ACTIVE_ACCOUNT_ID_KEY, nextAccount.id),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
adminConfigState.accounts = nextAccounts;
|
adminConfigState.accounts = nextAccounts;
|
||||||
adminConfigState.activeAccountId = nextAccount.id;
|
adminConfigState.activeAccountId = nextAccount.id;
|
||||||
adminConfigState.baseUrl = normalized.baseUrl;
|
adminConfigState.baseUrl = normalized.baseUrl;
|
||||||
adminConfigState.adminApiKey = normalized.adminApiKey;
|
adminConfigState.adminApiKey = normalized.adminApiKey;
|
||||||
adminConfigState.saving = false;
|
} finally {
|
||||||
|
adminConfigState.saving = false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function switchAdminAccount(accountId: string) {
|
export async function switchAdminAccount(accountId: string) {
|
||||||
|
|||||||
@@ -73,6 +73,30 @@ export type DashboardModelStats = {
|
|||||||
models: ModelStat[];
|
models: ModelStat[];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type UsageStats = {
|
||||||
|
total_requests?: number;
|
||||||
|
total_tokens?: number;
|
||||||
|
total_input_tokens?: number;
|
||||||
|
total_output_tokens?: number;
|
||||||
|
total_cost?: number;
|
||||||
|
total_actual_cost?: number;
|
||||||
|
total_account_cost?: number;
|
||||||
|
average_duration_ms?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type DashboardSnapshot = {
|
||||||
|
trend?: TrendPoint[];
|
||||||
|
models?: ModelStat[];
|
||||||
|
groups?: Array<{
|
||||||
|
group_id?: number;
|
||||||
|
group_name?: string;
|
||||||
|
requests?: number;
|
||||||
|
total_tokens?: number;
|
||||||
|
total_cost?: number;
|
||||||
|
total_actual_cost?: number;
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
|
||||||
export type AdminSettings = {
|
export type AdminSettings = {
|
||||||
site_name?: string;
|
site_name?: string;
|
||||||
[key: string]: string | number | boolean | null | string[] | undefined;
|
[key: string]: string | number | boolean | null | string[] | undefined;
|
||||||
@@ -88,6 +112,7 @@ export type AdminUser = {
|
|||||||
role?: string;
|
role?: string;
|
||||||
current_concurrency?: number;
|
current_concurrency?: number;
|
||||||
notes?: string | null;
|
notes?: string | null;
|
||||||
|
last_used_at?: string | null;
|
||||||
created_at?: string;
|
created_at?: string;
|
||||||
updated_at?: string;
|
updated_at?: string;
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user