feat: refine expo admin mobile flows

This commit is contained in:
xuhongbin
2026-03-08 20:53:15 +08:00
parent c70ca1641a
commit 434bbf258a
21 changed files with 3128 additions and 6381 deletions

View File

@@ -7,12 +7,6 @@
"orientation": "portrait",
"icon": "./icons/ios/AppIcon.appiconset/icon-1024.png",
"userInterfaceStyle": "light",
"runtimeVersion": {
"policy": "appVersion"
},
"updates": {
"url": "https://u.expo.dev/acaedd05-5a2a-4843-a648-e025c08ce7b3"
},
"splash": {
"image": "./assets/splash-icon.png",
"resizeMode": "contain",
@@ -47,6 +41,13 @@
"eas": {
"projectId": "acaedd05-5a2a-4843-a648-e025c08ce7b3"
}
}
},
"runtimeVersion": {
"policy": "appVersion"
},
"updates": {
"url": "https://u.expo.dev/acaedd05-5a2a-4843-a648-e025c08ce7b3"
},
"scheme": "sub2apimobile"
}
}

View File

@@ -1,4 +1,4 @@
import { Tabs } from 'expo-router';
import { Redirect, Tabs } from 'expo-router';
import { ChartNoAxesCombined, Settings2, Users } from 'lucide-react-native';
import { adminConfigState } from '@/src/store/admin-config';
@@ -9,6 +9,10 @@ export default function TabsLayout() {
const config = useSnapshot(adminConfigState);
const hasAccount = Boolean(config.baseUrl.trim());
if (!hasAccount) {
return <Redirect href="/login" />;
}
return (
<Tabs
initialRouteName={hasAccount ? 'monitor' : 'settings'}
@@ -53,7 +57,6 @@ export default function TabsLayout() {
}}
/>
<Tabs.Screen name="groups" options={{ href: null }} />
<Tabs.Screen name="keys" options={{ href: null }} />
<Tabs.Screen name="accounts" options={{ href: null }} />
</Tabs>
);

View File

@@ -2,12 +2,13 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { KeyRound, Search, ShieldCheck, ShieldOff } from 'lucide-react-native';
import { router } from 'expo-router';
import { useCallback, useMemo, useState } from 'react';
import { FlatList, Pressable, Text, TextInput, View } from 'react-native';
import { FlatList, Pressable, RefreshControl, Text, TextInput, View } from 'react-native';
import { ListCard } from '@/src/components/list-card';
import { ScreenShell } from '@/src/components/screen-shell';
import { useDebouncedValue } from '@/src/hooks/use-debounced-value';
import { getAccount, getAccountTodayStats, getDashboardTrend, listAccounts, setAccountSchedulable, testAccount } from '@/src/services/admin';
import type { AdminAccount } from '@/src/types/admin';
function getDateRange() {
const end = new Date();
@@ -22,8 +23,20 @@ function getDateRange() {
};
}
function formatTime(value?: string | null) {
if (!value) return '--';
const date = new Date(value);
if (Number.isNaN(date.getTime())) return '--';
return `${date.getFullYear()}/${String(date.getMonth() + 1).padStart(2, '0')}/${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
}
function getAccountError(account: AdminAccount) {
return Boolean(account.status === 'error' || account.error_message);
}
export default function AccountsScreen() {
const [searchText, setSearchText] = useState('');
const [filter, setFilter] = useState<'all' | 'schedulable' | 'paused' | 'error'>('all');
const keyword = useDebouncedValue(searchText.trim(), 300);
const queryClient = useQueryClient();
const range = getDateRange();
@@ -40,26 +53,71 @@ export default function AccountsScreen() {
});
const items = accountsQuery.data?.items ?? [];
const filteredItems = useMemo(() => {
return items.filter((account) => {
if (filter === 'schedulable') return account.schedulable !== false && !getAccountError(account);
if (filter === 'paused') return account.schedulable === false && !getAccountError(account);
if (filter === 'error') return getAccountError(account);
return true;
});
}, [filter, items]);
const errorMessage = accountsQuery.error instanceof Error ? accountsQuery.error.message : '';
const summary = useMemo(() => {
const total = items.length;
const errors = items.filter(getAccountError).length;
const paused = items.filter((item) => item.schedulable === false && !getAccountError(item)).length;
const active = items.filter((item) => item.schedulable !== false && !getAccountError(item)).length;
return { total, active, paused, errors };
}, [items]);
const listHeader = useMemo(
() => (
<View className="pb-4">
<View className="flex-row items-center rounded-[24px] bg-[#fbf8f2] px-4 py-3">
<View className="rounded-[24px] bg-[#fbf8f2] p-3">
<View className="flex-row items-center rounded-[18px] bg-[#f1ece2] px-4 py-3">
<Search color="#7d7468" size={18} />
<TextInput
defaultValue=""
onChangeText={setSearchText}
placeholder="搜索 key 名称"
placeholder="搜索账号名称 / 平台"
placeholderTextColor="#9b9081"
className="ml-3 flex-1 text-base text-[#16181a]"
/>
</View>
<View className="mt-3 flex-row gap-2">
{([
['all', `全部 ${summary.total}`],
['schedulable', `可调度 ${summary.active}`],
['paused', `暂停 ${summary.paused}`],
['error', `异常 ${summary.errors}`],
] as const).map(([key, label]) => {
const active = filter === key;
return (
<Pressable
key={key}
onPress={() => setFilter(key)}
className={active ? 'rounded-full bg-[#1d5f55] px-3 py-2' : 'rounded-full bg-[#e7dfcf] px-3 py-2'}
>
<Text className={active ? 'text-xs font-semibold text-white' : 'text-xs font-semibold text-[#4e463e]'}>{label}</Text>
</Pressable>
);
})}
</View>
</View>
</View>
),
[]
[filter, summary.active, summary.errors, summary.paused, summary.total]
);
const renderItem = useCallback(
({ item: account }: { item: (typeof items)[number] }) => (
({ item: account }: { item: (typeof filteredItems)[number] }) => {
const isError = getAccountError(account);
const statusText = isError ? '异常' : account.schedulable ? '可调度' : '暂停调度';
const groupsText = account.groups?.map((group) => group.name).filter(Boolean).slice(0, 3).join(' · ');
return (
<Pressable
onPress={() => {
void queryClient.prefetchQuery({ queryKey: ['account', account.id], queryFn: () => getAccount(account.id) });
@@ -77,11 +135,29 @@ export default function AccountsScreen() {
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 ? <ShieldCheck color="#7d7468" size={14} /> : <ShieldOff color="#7d7468" size={14} />}
<Text className="text-sm text-[#7d7468]">{account.schedulable ? '可调度' : '暂停调度'}</Text>
{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"
@@ -102,33 +178,36 @@ export default function AccountsScreen() {
});
}}
>
<Text className="text-xs font-semibold uppercase tracking-[1.2px] text-[#4e463e]"></Text>
<Text className="text-xs font-semibold uppercase tracking-[1.2px] text-[#4e463e]">{account.schedulable ? '暂停' : '恢复'}</Text>
</Pressable>
</View>
</View>
</ListCard>
</Pressable>
),
[queryClient, range.end_date, range.start_date, toggleMutation]
);
},
[filteredItems, queryClient, range.end_date, range.start_date, toggleMutation]
);
const emptyState = useMemo(
() => <ListCard title="暂无 Key" meta={errorMessage || '连上后这里会展示 key 列表。'} icon={KeyRound} />,
() => <ListCard title="暂无账号" meta={errorMessage || '连上后这里会展示账号列表。'} icon={KeyRound} />,
[errorMessage]
);
return (
<ScreenShell
title="API 密钥"
subtitle=""
titleAside={<Text className="text-[11px] text-[#a2988a]"></Text>}
title="账号管理"
subtitle="看单账号状态、并发、最近使用和异常信息。"
titleAside={<Text className="text-[11px] text-[#a2988a]"></Text>}
variant="minimal"
scroll={false}
>
<FlatList
data={items}
data={filteredItems}
renderItem={renderItem}
keyExtractor={(item) => `${item.id}`}
showsVerticalScrollIndicator={false}
refreshControl={<RefreshControl refreshing={accountsQuery.isRefetching} onRefresh={() => void accountsQuery.refetch()} tintColor="#1d5f55" />}
ListHeaderComponent={listHeader}
ListEmptyComponent={emptyState}
ItemSeparatorComponent={() => <View className="h-4" />}

View File

@@ -1,7 +1,7 @@
import { useQuery } from '@tanstack/react-query';
import { FolderKanban, Layers3, Search } from 'lucide-react-native';
import { useCallback, useMemo, useState } from 'react';
import { FlatList, Text, TextInput, View } from 'react-native';
import { FlatList, RefreshControl, Text, TextInput, View } from 'react-native';
import { ListCard } from '@/src/components/list-card';
import { ScreenShell } from '@/src/components/screen-shell';
@@ -72,6 +72,7 @@ export default function GroupsScreen() {
renderItem={renderItem}
keyExtractor={(item) => `${item.id}`}
showsVerticalScrollIndicator={false}
refreshControl={<RefreshControl refreshing={groupsQuery.isRefetching} onRefresh={() => void groupsQuery.refetch()} tintColor="#1d5f55" />}
ListHeaderComponent={listHeader}
ListEmptyComponent={emptyState}
ItemSeparatorComponent={() => <View className="h-4" />}

View File

@@ -1,5 +1,12 @@
import { Redirect } from 'expo-router';
import { adminConfigState } from '@/src/store/admin-config';
const { useSnapshot } = require('valtio/react');
export default function IndexScreen() {
return <Redirect href="/monitor" />;
const config = useSnapshot(adminConfigState);
const hasAccount = Boolean(config.baseUrl.trim());
return <Redirect href={hasAccount ? '/monitor' : '/login'} />;
}

View File

@@ -1,15 +1,13 @@
import { useQuery } from '@tanstack/react-query';
import { AlertTriangle, Coins, Gauge, RefreshCw, Rows3, Wrench, Zap } from 'lucide-react-native';
import { router } from 'expo-router';
import { useMemo, useState } from 'react';
import { Platform, Pressable, Text, View, useWindowDimensions } from 'react-native';
import { Pressable, RefreshControl, ScrollView, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { BarChartCard } from '@/src/components/bar-chart-card';
import { formatTokenValue } from '@/src/lib/formatters';
import { DonutChartCard } from '@/src/components/donut-chart-card';
import { LineTrendChart } from '@/src/components/line-trend-chart';
import { ListCard } from '@/src/components/list-card';
import { ScreenShell } from '@/src/components/screen-shell';
import { useScreenInteractive } from '@/src/hooks/use-screen-interactive';
import { formatTokenValue } from '@/src/lib/formatters';
import { getAdminSettings, getDashboardModels, getDashboardStats, getDashboardTrend, listAccounts } from '@/src/services/admin';
import { adminConfigState } from '@/src/store/admin-config';
@@ -17,6 +15,32 @@ const { useSnapshot } = require('valtio/react');
type RangeKey = '24h' | '7d' | '30d';
const colors = {
page: '#f4efe4',
card: '#fbf8f2',
mutedCard: '#f1ece2',
primary: '#1d5f55',
text: '#16181a',
subtext: '#6f665c',
border: '#e7dfcf',
dangerBg: '#fbf1eb',
danger: '#c25d35',
successBg: '#e6f4ee',
success: '#1d5f55',
};
const RANGE_OPTIONS: Array<{ key: RangeKey; label: string }> = [
{ key: '24h', label: '24H' },
{ key: '7d', label: '7D' },
{ key: '30d', label: '30D' },
];
const RANGE_TITLE_MAP: Record<RangeKey, string> = {
'24h': '24H',
'7d': '7D',
'30d': '30D',
};
function getDateRange(rangeKey: RangeKey) {
const end = new Date();
const start = new Date();
@@ -38,11 +62,27 @@ function getDateRange(rangeKey: RangeKey) {
};
}
const RANGE_OPTIONS: Array<{ key: RangeKey; label: string }> = [
{ key: '24h', label: '24H' },
{ key: '7d', label: '7D' },
{ key: '30d', label: '30D' },
];
function formatNumber(value?: number) {
if (typeof value !== 'number' || Number.isNaN(value)) return '--';
return new Intl.NumberFormat('en-US').format(value);
}
function formatMoney(value?: number) {
if (typeof value !== 'number' || Number.isNaN(value)) return '--';
return `$${value.toFixed(2)}`;
}
function formatCompactNumber(value?: number) {
if (typeof value !== 'number' || Number.isNaN(value)) return '--';
if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`;
if (value >= 1_000) return `${(value / 1_000).toFixed(1)}K`;
return String(value);
}
function formatTokenDisplay(value?: number) {
if (typeof value !== 'number' || Number.isNaN(value)) return '--';
return formatTokenValue(value);
}
function getPointLabel(value: string, rangeKey: RangeKey) {
if (rangeKey === '24h') {
@@ -52,49 +92,97 @@ function getPointLabel(value: string, rangeKey: RangeKey) {
return value.slice(5, 10);
}
function getErrorMessage(error: unknown) {
if (error instanceof Error && error.message) {
switch (error.message) {
case 'BASE_URL_REQUIRED':
return '请先去服务器页填写服务地址。';
case 'ADMIN_API_KEY_REQUIRED':
return '请先去服务器页填写 Admin Token。';
case 'INVALID_SERVER_RESPONSE':
return '当前服务返回的数据格式不正确,请确认它是可用的 Sub2API 管理接口。';
default:
return error.message;
}
}
return '当前无法加载概览数据请检查服务地址、Token 和网络。';
}
function Section({ title, subtitle, children, right }: { title: string; subtitle?: string; children: React.ReactNode; right?: React.ReactNode }) {
return (
<View style={{ backgroundColor: colors.card, borderRadius: 18, padding: 16 }}>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', gap: 12 }}>
<View style={{ flex: 1 }}>
<Text style={{ fontSize: 18, fontWeight: '700', color: colors.text }}>{title}</Text>
{subtitle ? <Text style={{ marginTop: 6, fontSize: 12, color: colors.subtext }}>{subtitle}</Text> : null}
</View>
{right}
</View>
<View style={{ marginTop: 14 }}>{children}</View>
</View>
);
}
function StatCard({ title, value, detail }: { title: string; value: string; detail?: string }) {
return (
<View style={{ flex: 1, backgroundColor: colors.card, borderRadius: 16, padding: 14 }}>
<Text style={{ fontSize: 12, color: '#8a8072' }}>{title}</Text>
<Text style={{ marginTop: 8, fontSize: 24, fontWeight: '700', color: colors.text }}>{value}</Text>
{detail ? <Text style={{ marginTop: 6, fontSize: 12, color: colors.subtext }}>{detail}</Text> : null}
</View>
);
}
export default function MonitorScreen() {
useScreenInteractive('monitor_interactive');
const config = useSnapshot(adminConfigState);
const { width } = useWindowDimensions();
const contentWidth = Math.max(width - 24, 280);
const hasAccount = Boolean(config.baseUrl.trim());
const [rangeKey, setRangeKey] = useState<RangeKey>('7d');
const range = useMemo(() => getDateRange(rangeKey), [rangeKey]);
const hasAccount = Boolean(config.baseUrl.trim());
const statsQuery = useQuery({
queryKey: ['monitor-stats'],
queryFn: getDashboardStats,
enabled: hasAccount,
});
const statsQuery = useQuery({ queryKey: ['monitor-stats'], queryFn: getDashboardStats, enabled: hasAccount });
const settingsQuery = useQuery({ queryKey: ['admin-settings'], queryFn: getAdminSettings, enabled: hasAccount });
const accountsQuery = useQuery({ queryKey: ['monitor-accounts'], queryFn: () => listAccounts(''), enabled: hasAccount });
const trendQuery = useQuery({
queryKey: ['monitor-trend', rangeKey, range.start_date, range.end_date, range.granularity],
queryFn: () => getDashboardTrend(range),
enabled: hasAccount,
});
const modelsQuery = useQuery({
queryKey: ['monitor-models', rangeKey, range.start_date, range.end_date],
queryFn: () => getDashboardModels(range),
enabled: hasAccount,
});
const settingsQuery = useQuery({
queryKey: ['admin-settings'],
queryFn: getAdminSettings,
enabled: hasAccount,
});
const accountsQuery = useQuery({
queryKey: ['monitor-accounts'],
queryFn: () => listAccounts(''),
enabled: hasAccount,
});
function refetchAll() {
statsQuery.refetch();
settingsQuery.refetch();
accountsQuery.refetch();
trendQuery.refetch();
modelsQuery.refetch();
}
const stats = statsQuery.data;
const trend = trendQuery.data?.trend ?? [];
const accounts = accountsQuery.data?.items ?? [];
const siteName = settingsQuery.data?.site_name?.trim() || '管理控制台';
const accounts = accountsQuery.data?.items ?? [];
const trend = trendQuery.data?.trend ?? [];
const topModels = (modelsQuery.data?.models ?? []).slice(0, 5);
const errorMessage = getErrorMessage(statsQuery.error ?? settingsQuery.error ?? accountsQuery.error ?? trendQuery.error ?? modelsQuery.error);
const currentPageErrorAccounts = accounts.filter((item) => item.status === 'error' || item.error_message).length;
const currentPagePausedAccounts = accounts.filter((item) => item.schedulable === false && item.status !== 'error' && !item.error_message).length;
const currentPageBusyAccounts = accounts.filter((item) => (item.current_concurrency ?? 0) > 0 && item.status !== 'error' && !item.error_message).length;
const totalAccounts = stats?.total_accounts ?? accountsQuery.data?.total ?? accounts.length;
const aggregatedErrorAccounts = stats?.error_accounts ?? 0;
const errorAccounts = Math.max(aggregatedErrorAccounts, currentPageErrorAccounts);
const healthyAccounts = stats?.normal_accounts ?? Math.max(totalAccounts - errorAccounts, 0);
const latestTrendPoints = trend.slice(-6).reverse();
const selectedTokenTotal = trend.reduce((sum, item) => sum + item.total_tokens, 0);
const selectedCostTotal = trend.reduce((sum, item) => sum + item.cost, 0);
const selectedOutputTotal = trend.reduce((sum, item) => sum + item.output_tokens, 0);
const rangeTitle = RANGE_TITLE_MAP[rangeKey];
const isLoading = statsQuery.isLoading || settingsQuery.isLoading || accountsQuery.isLoading;
const hasError = Boolean(statsQuery.error || settingsQuery.error || accountsQuery.error || trendQuery.error || modelsQuery.error);
const throughputPoints = useMemo(
() => trend.map((item) => ({ label: getPointLabel(item.date, rangeKey), value: item.total_tokens })),
[rangeKey, trend]
@@ -107,281 +195,196 @@ export default function MonitorScreen() {
() => trend.map((item) => ({ label: getPointLabel(item.date, rangeKey), value: item.cost })),
[rangeKey, trend]
);
const topModels = useMemo(() => (modelsQuery.data?.models ?? []).slice(0, 5), [modelsQuery.data?.models]);
const incidentAccounts = useMemo(
() => accounts.filter((item) => item.status === 'error' || item.error_message).slice(0, 5),
[accounts]
);
const totalInputTokens = useMemo(() => trend.reduce((sum, item) => sum + item.input_tokens, 0), [trend]);
const totalOutputTokens = useMemo(() => trend.reduce((sum, item) => sum + item.output_tokens, 0), [trend]);
const totalCacheReadTokens = useMemo(() => trend.reduce((sum, item) => sum + item.cache_read_tokens, 0), [trend]);
const busyAccounts = useMemo(
() => accounts.filter((item) => (item.current_concurrency ?? 0) > 0 && item.status !== 'error' && !item.error_message).length,
[accounts]
);
const pausedAccounts = useMemo(
() => accounts.filter((item) => item.schedulable === false && item.status !== 'error' && !item.error_message).length,
[accounts]
);
const errorAccounts = useMemo(
() => accounts.filter((item) => item.status === 'error' || item.error_message).length,
[accounts]
);
const healthyAccounts = Math.max(accounts.length - busyAccounts - pausedAccounts - errorAccounts, 0);
const summaryCards = [
{
label: 'Token',
value: stats ? formatTokenValue(stats.today_tokens ?? 0) : '--',
icon: Zap,
tone: 'dark' as const,
},
{
label: '成本',
value: stats ? `$${Number(stats.today_cost ?? 0).toFixed(2)}` : '--',
icon: Coins,
},
{
label: '输出',
value: stats ? formatTokenValue(stats.today_output_tokens ?? 0) : '--',
icon: Rows3,
},
{
label: '账号',
value: String(accounts.length || stats?.total_accounts || 0),
detail: `${errorAccounts} 异常 / ${pausedAccounts} 暂停`,
icon: Rows3,
},
{
label: 'TPM',
value: String(stats?.tpm ?? '--'),
icon: Gauge,
},
{
label: '健康',
value: String(healthyAccounts),
detail: `${busyAccounts} 繁忙`,
icon: AlertTriangle,
},
];
const summaryRows = [0, 3].map((index) => summaryCards.slice(index, index + 3));
const useMasonry = Platform.OS === 'web' || width >= 640;
const summaryCardWidth = Math.floor((contentWidth - 16) / 3);
const isRefreshing = statsQuery.isRefetching || settingsQuery.isRefetching || accountsQuery.isRefetching || trendQuery.isRefetching || modelsQuery.isRefetching;
const cards = [
{
key: 'throughput',
node: throughputPoints.length > 1 ? (
<LineTrendChart
title="Token 吞吐"
subtitle="整体负载曲线"
points={throughputPoints}
color="#a34d2d"
formatValue={formatTokenValue}
compact={useMasonry}
return (
<SafeAreaView style={{ flex: 1, backgroundColor: colors.page }}>
<ScrollView
style={{ flex: 1 }}
contentContainerStyle={{ paddingHorizontal: 16, paddingTop: 16, paddingBottom: 110 }}
showsVerticalScrollIndicator={false}
refreshControl={<RefreshControl refreshing={isRefreshing} onRefresh={() => void refetchAll()} tintColor="#1d5f55" />}
>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12, marginBottom: 16 }}>
<View style={{ flex: 1 }}>
<Text style={{ fontSize: 28, fontWeight: '700', color: colors.text }}></Text>
<Text style={{ marginTop: 6, fontSize: 13, color: '#8a8072' }}>{siteName} </Text>
</View>
<View style={{ alignItems: 'flex-end' }}>
<View style={{ flexDirection: 'row', gap: 8 }}>
{RANGE_OPTIONS.map((option) => {
const active = option.key === rangeKey;
return (
<Pressable
key={option.key}
style={{ backgroundColor: active ? colors.primary : colors.border, borderRadius: 999, paddingHorizontal: 12, paddingVertical: 8 }}
onPress={() => setRangeKey(option.key)}
>
<Text style={{ color: active ? '#fff' : '#4e463e', fontSize: 12, fontWeight: '700' }}>{option.label}</Text>
</Pressable>
);
})}
</View>
<Text style={{ marginTop: 8, fontSize: 12, color: colors.subtext }}>{range.start_date} {range.end_date}</Text>
</View>
</View>
{!hasAccount ? (
<Section title="未连接服务器" subtitle="需要先配置连接">
<Text style={{ fontSize: 14, lineHeight: 22, color: colors.subtext }}> Admin Token</Text>
<Pressable style={{ marginTop: 14, alignSelf: 'flex-start', backgroundColor: colors.primary, borderRadius: 14, paddingHorizontal: 16, paddingVertical: 12 }} onPress={() => router.push('/settings')}>
<Text style={{ color: '#fff', fontSize: 13, fontWeight: '700' }}></Text>
</Pressable>
</Section>
) : isLoading ? (
<Section title="正在加载概览" subtitle="请稍候">
<Text style={{ fontSize: 14, lineHeight: 22, color: colors.subtext }}></Text>
</Section>
) : hasError ? (
<Section title="加载失败" subtitle="请检查连接配置">
<View style={{ borderRadius: 14, backgroundColor: colors.dangerBg, paddingHorizontal: 14, paddingVertical: 12 }}>
<Text style={{ color: colors.danger, fontSize: 14, lineHeight: 20 }}>{errorMessage}</Text>
</View>
<View style={{ flexDirection: 'row', gap: 12, marginTop: 14 }}>
<Pressable style={{ flex: 1, backgroundColor: colors.primary, borderRadius: 14, paddingVertical: 12, alignItems: 'center' }} onPress={refetchAll}>
<Text style={{ color: '#fff', fontSize: 13, fontWeight: '700' }}></Text>
</Pressable>
<Pressable style={{ flex: 1, backgroundColor: colors.border, borderRadius: 14, paddingVertical: 12, alignItems: 'center' }} onPress={() => router.push('/settings')}>
<Text style={{ color: '#4e463e', fontSize: 13, fontWeight: '700' }}></Text>
</Pressable>
</View>
</Section>
) : (
<View style={{ gap: 12 }}>
<View style={{ flexDirection: 'row', gap: 12 }}>
<StatCard
title={`${rangeTitle} Token`}
value={formatTokenDisplay(rangeKey === '24h' ? selectedTokenTotal || stats?.today_tokens : selectedTokenTotal)}
detail={`输出 ${formatTokenDisplay(rangeKey === '24h' ? selectedOutputTotal || stats?.today_output_tokens : selectedOutputTotal)}`}
/>
) : null,
},
{
key: 'requests',
node: requestPoints.length > 1 ? (
<LineTrendChart
title="请求趋势"
subtitle="调用波峰变化"
points={requestPoints}
color="#1d5f55"
compact={useMasonry}
<StatCard
title={`${rangeTitle} 成本`}
value={formatMoney(rangeKey === '24h' ? selectedCostTotal || stats?.today_cost : selectedCostTotal)}
detail={`TPM ${formatNumber(stats?.tpm)}`}
/>
) : 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: (
</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 style={{ flex: 1, backgroundColor: colors.mutedCard, borderRadius: 14, padding: 12 }}>
<Text style={{ fontSize: 11, color: '#8a8072' }}></Text>
<Text style={{ marginTop: 6, fontSize: 18, fontWeight: '700', color: colors.text }}>{formatNumber(healthyAccounts)}</Text>
</View>
<View style={{ flex: 1, backgroundColor: colors.dangerBg, borderRadius: 14, padding: 12 }}>
<Text style={{ fontSize: 11, color: colors.danger }}></Text>
<Text style={{ marginTop: 6, fontSize: 18, fontWeight: '700', color: colors.danger }}>{formatNumber(errorAccounts)}</Text>
</View>
<View style={{ flex: 1, backgroundColor: colors.mutedCard, borderRadius: 14, padding: 12 }}>
<Text style={{ fontSize: 11, color: '#8a8072' }}></Text>
<Text style={{ marginTop: 6, fontSize: 18, fontWeight: '700', color: colors.text }}>{formatNumber(currentPagePausedAccounts)}</Text>
</View>
</View>
<Text style={{ marginTop: 10, fontSize: 12, color: colors.subtext }}> / / 使</Text>
</Section>
{throughputPoints.length > 1 ? (
<LineTrendChart title="Token 吞吐" subtitle="当前时间范围内的 Token 变化趋势" points={throughputPoints} color="#a34d2d" formatValue={formatTokenDisplay} />
) : null}
{requestPoints.length > 1 ? (
<LineTrendChart title="请求趋势" subtitle="当前时间范围内的请求变化趋势" points={requestPoints} color="#1d5f55" formatValue={formatCompactNumber} />
) : null}
{costPoints.length > 1 ? (
<LineTrendChart title="成本趋势" subtitle="当前时间范围内的成本变化趋势" points={costPoints} color="#7651c8" formatValue={formatMoney} />
) : null}
<BarChartCard
title="Token 结构"
subtitle="输入、输出、缓存读占比"
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数值越高通常意味着缓存策略更有效。',
},
{ 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={formatTokenValue}
formatValue={formatTokenDisplay}
/>
),
},
{
key: 'health',
node: (
<DonutChartCard
title="账号健康"
subtitle="健康、繁忙、暂停、异常"
subtitle="健康、繁忙、暂停、异常分布"
centerLabel="总账号"
centerValue={String(accounts.length || stats?.total_accounts || 0)}
centerValue={formatNumber(totalAccounts)}
segments={[
{ label: '健康', value: healthyAccounts, color: '#1d5f55' },
{ label: '繁忙', value: busyAccounts, color: '#d38b36' },
{ label: '暂停', value: pausedAccounts, color: '#7d7468' },
{ label: '繁忙', value: currentPageBusyAccounts, color: '#d38b36' },
{ label: '暂停', value: currentPagePausedAccounts, color: '#7d7468' },
{ label: '异常', value: errorAccounts, color: '#a34d2d' },
]}
/>
),
},
{
key: 'models',
node: (
<BarChartCard
title="热点模型"
subtitle="模型负载分布"
items={topModels.map((item) => ({
label: item.model,
value: item.total_tokens,
subtitle="当前时间范围内最活跃的模型"
items={topModels.map((model) => ({
label: model.model,
value: model.total_tokens,
color: '#a34d2d',
meta: `请求 ${item.requests} · 成本 $${Number(item.cost).toFixed(2)}`,
meta: `请求 ${formatNumber(model.requests)} · 成本 ${formatMoney(model.cost)}`,
}))}
formatValue={formatTokenValue}
formatValue={formatCompactNumber}
/>
),
},
{
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 (
<ScreenShell
title="概览"
subtitle=""
titleAside={<Text className="text-[11px] text-[#a2988a]">{siteName} </Text>}
variant="minimal"
horizontalInsetClassName="px-3"
contentGapClassName="mt-3 gap-2"
right={
<View className="flex-row items-center gap-2">
<View className="flex-row items-center rounded-full bg-[#ece3d6] p-1">
{RANGE_OPTIONS.map((item) => {
const active = item.key === rangeKey;
return (
<Pressable
key={item.key}
className={active ? 'rounded-full bg-[#1d5f55] px-3 py-1.5' : 'rounded-full bg-transparent px-3 py-1.5'}
onPress={() => setRangeKey(item.key)}
>
<Text className={active ? 'text-[10px] font-semibold uppercase leading-4 tracking-[1px] text-white' : 'text-[10px] font-semibold uppercase leading-4 tracking-[1px] text-[#7d7468]'}>
{item.label}
</Text>
</Pressable>
);
})}
</View>
<Pressable
className="h-10 w-10 items-center justify-center rounded-full bg-[#2d3134]"
onPress={() => {
statsQuery.refetch();
trendQuery.refetch();
modelsQuery.refetch();
accountsQuery.refetch();
settingsQuery.refetch();
}}
>
<RefreshCw color="#f6f1e8" size={16} />
</Pressable>
</View>
}
>
<View className="gap-2">
{summaryRows.map((row, rowIndex) => (
<View key={`summary-row-${rowIndex}`} className="flex-row gap-2">
{row.map((item) => {
const Icon = item.icon;
return (
<View
key={item.label}
className={item.tone === 'dark' ? 'rounded-[18px] bg-[#1d5f55] px-2.5 py-2.5' : 'rounded-[18px] bg-[#fbf8f2] px-2.5 py-2.5'}
style={{ width: summaryCardWidth }}
>
<View className="flex-row items-center justify-between gap-2">
<Text className={item.tone === 'dark' ? 'text-[10px] uppercase tracking-[1.1px] text-[#d8efe7]' : 'text-[10px] uppercase tracking-[1.1px] text-[#8a8072]'}>
{item.label}
</Text>
<Icon color={item.tone === 'dark' ? '#d8efe7' : '#7d7468'} size={13} />
</View>
<Text className={item.tone === 'dark' ? 'mt-2 text-[17px] font-bold text-white' : 'mt-2 text-[17px] font-bold text-[#16181a]'}>
{item.value}
</Text>
{'detail' in item && item.detail ? (
<Text numberOfLines={1} className={item.tone === 'dark' ? 'mt-1 text-[10px] text-[#d8efe7]' : 'mt-1 text-[10px] text-[#8a8072]'}>
{item.detail}
</Text>
) : null}
</View>
);
})}
</View>
))}
</View>
{useMasonry ? (
<View className="flex-row items-start gap-3">
<View className="flex-1 gap-3">
{leftColumn.map((item) => (
<View key={item.key}>{item.node}</View>
))}
</View>
<View className="flex-1 gap-3">
{rightColumn.map((item) => (
<View key={item.key}>{item.node}</View>
))}
</View>
</View>
<Section title="趋势摘要" subtitle="图表 + 最近几个统计点的请求、Token 和成本变化">
{latestTrendPoints.length === 0 ? (
<Text style={{ fontSize: 14, color: colors.subtext }}></Text>
) : (
cards.map((item) => <View key={item.key}>{item.node}</View>)
<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>
)}
</ScreenShell>
</Section>
</View>
)}
</ScrollView>
</SafeAreaView>
);
}

View File

@@ -1,105 +1,209 @@
import { router } from 'expo-router';
import { zodResolver } from '@hookform/resolvers/zod';
import { Controller, useForm } from 'react-hook-form';
import { Pressable, Text, TextInput, View } from 'react-native';
import { Pressable, RefreshControl, ScrollView, Text, TextInput, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useState } from 'react';
import { z } from 'zod';
import { ListCard } from '@/src/components/list-card';
import { ScreenShell } from '@/src/components/screen-shell';
import { isLocalProxyBaseUrl } from '@/src/lib/admin-fetch';
import { getAdminSettings, getDashboardStats } from '@/src/services/admin';
import { queryClient } from '@/src/lib/query-client';
import {
adminConfigState,
logoutAdminAccount,
removeAdminAccount,
saveAdminConfig,
setAdminAccountEnabled,
switchAdminAccount,
type AdminAccountProfile,
} from '@/src/store/admin-config';
import { adminConfigState, removeAdminAccount, saveAdminConfig, switchAdminAccount, type AdminAccountProfile } from '@/src/store/admin-config';
const { useSnapshot } = require('valtio/react');
const schema = z
.object({
baseUrl: z.string().min(1, '请输入 Host'),
baseUrl: z.string().min(1, '请输入服务器地址'),
adminApiKey: z.string(),
})
.superRefine((values, ctx) => {
if (!isLocalProxyBaseUrl(values.baseUrl.trim()) && !values.adminApiKey.trim()) {
ctx.addIssue({
code: 'custom',
.refine((values) => values.adminApiKey.trim().length > 0, {
path: ['adminApiKey'],
message: '请输入 Admin Token',
});
}
message: '请输入 Admin Key',
});
type FormValues = z.infer<typeof schema>;
type ConnectionState = 'idle' | 'checking' | 'success' | 'error';
const colors = {
page: '#f4efe4',
card: '#fbf8f2',
mutedCard: '#f1ece2',
primary: '#1d5f55',
text: '#16181a',
subtext: '#6f665c',
border: '#e7dfcf',
dangerBg: '#fbf1eb',
danger: '#c25d35',
successBg: '#e6f4ee',
success: '#1d5f55',
};
function getConnectionErrorMessage(error: unknown) {
if (error instanceof Error && error.message) {
switch (error.message) {
case 'BASE_URL_REQUIRED':
return '请先填写服务器地址。';
case 'ADMIN_API_KEY_REQUIRED':
return '请先填写 Admin Key。';
case 'INVALID_SERVER_RESPONSE':
return '当前地址返回的数据不正确,请确认它是可用的管理接口。';
default:
return error.message;
}
}
return '连接失败请检查服务器地址、Admin Key 和网络连通性。';
}
function ServerCard({
account,
active,
onSelect,
onDelete,
}: {
account: AdminAccountProfile;
active: boolean;
onSelect: () => Promise<void>;
onDelete: () => Promise<void>;
}) {
return (
<Pressable
onPress={onSelect}
style={{
backgroundColor: active ? '#e6f4ee' : colors.card,
borderRadius: 18,
padding: 16,
borderWidth: 1,
borderColor: active ? colors.success : colors.border,
}}
>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
<View style={{ flex: 1 }}>
<Text style={{ fontSize: 16, fontWeight: '700', color: colors.text }}>{account.label}</Text>
<Text style={{ marginTop: 6, fontSize: 13, lineHeight: 20, color: colors.subtext }}>{account.baseUrl}</Text>
<Text style={{ marginTop: 8, fontSize: 11, color: '#8a8072' }}> {new Date(account.updatedAt).toLocaleString()}</Text>
</View>
{active ? (
<View style={{ backgroundColor: colors.success, borderRadius: 999, paddingHorizontal: 10, paddingVertical: 6 }}>
<Text style={{ color: '#fff', fontSize: 11, fontWeight: '700' }}>使</Text>
</View>
) : null}
</View>
<View style={{ flexDirection: 'row', gap: 10, marginTop: 14 }}>
<Pressable onPress={onSelect} style={{ flex: 1, backgroundColor: active ? '#d7eee4' : colors.primary, borderRadius: 14, paddingVertical: 11, alignItems: 'center' }}>
<Text style={{ color: active ? colors.success : '#fff', fontSize: 13, fontWeight: '700' }}>{active ? '已选中' : '切换到此服务器'}</Text>
</Pressable>
<Pressable onPress={onDelete} style={{ backgroundColor: colors.border, borderRadius: 14, paddingHorizontal: 16, justifyContent: 'center' }}>
<Text style={{ color: '#7a3d31', fontSize: 13, fontWeight: '700' }}></Text>
</Pressable>
</View>
</Pressable>
);
}
export default function SettingsScreen() {
const config = useSnapshot(adminConfigState);
const [showForm, setShowForm] = useState(config.accounts.length === 0);
const [connectionState, setConnectionState] = useState<ConnectionState>('idle');
const [connectionMessage, setConnectionMessage] = useState('');
const [isRefreshing, setIsRefreshing] = useState(false);
const { control, handleSubmit, formState, reset } = useForm<FormValues>({
resolver: zodResolver(schema),
values: {
baseUrl: config.baseUrl,
adminApiKey: config.adminApiKey,
defaultValues: {
baseUrl: '',
adminApiKey: '',
},
});
async function handleSwitch(account: AdminAccountProfile) {
await switchAdminAccount(account.id);
async function verifyAndEnter(successMessage: string) {
setConnectionState('checking');
setConnectionMessage('正在检测当前服务是否可用...');
try {
queryClient.clear();
reset({ baseUrl: account.baseUrl, adminApiKey: account.adminApiKey });
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 verifyAndEnter(`已切换到 ${account.label}`);
}
async function handleDelete(account: AdminAccountProfile) {
await removeAdminAccount(account.id);
queryClient.clear();
reset({ baseUrl: adminConfigState.baseUrl, adminApiKey: adminConfigState.adminApiKey });
}
async function handleLogout() {
await logoutAdminAccount();
queryClient.clear();
reset({ baseUrl: '', adminApiKey: '' });
async function handleRefresh() {
if (!config.baseUrl.trim()) {
return;
}
async function handleToggleEnabled(account: AdminAccountProfile) {
await setAdminAccountEnabled(account.id, account.enabled === false);
queryClient.clear();
reset({ baseUrl: adminConfigState.baseUrl, adminApiKey: adminConfigState.adminApiKey });
setIsRefreshing(true);
setConnectionState('idle');
setConnectionMessage('');
try {
await Promise.all([
queryClient.fetchQuery({ queryKey: ['admin-settings'], queryFn: getAdminSettings }),
queryClient.prefetchQuery({ queryKey: ['monitor-stats'], queryFn: getDashboardStats }),
]);
} catch (error) {
setConnectionState('error');
setConnectionMessage(getConnectionErrorMessage(error));
} finally {
setIsRefreshing(false);
}
}
return (
<ScreenShell
title="服务器"
subtitle=""
titleAside={<Text className="text-[11px] text-[#a2988a]"> Sub2API </Text>}
variant="minimal"
<SafeAreaView style={{ flex: 1, backgroundColor: colors.page }}>
<ScrollView
style={{ flex: 1 }}
contentContainerStyle={{ paddingHorizontal: 16, paddingTop: 16, paddingBottom: 110, gap: 14 }}
showsVerticalScrollIndicator={false}
refreshControl={<RefreshControl refreshing={isRefreshing} onRefresh={() => void handleRefresh()} tintColor="#1d5f55" />}
>
<ListCard title="当前连接" meta={config.baseUrl || '未连接'}>
<View className="gap-3">
<Text className="text-sm text-[#6f665c]">
{config.baseUrl || '当前没有激活服务器,可在下方直接新增或切换。'}
</Text>
<View className="flex-row gap-3">
<Pressable className="flex-1 rounded-[18px] bg-[#1d5f55] px-4 py-3" onPress={handleSubmit(async (values) => {
await saveAdminConfig(values);
queryClient.clear();
})}>
<Text className="text-center text-sm font-semibold text-white"></Text>
</Pressable>
<Pressable className="flex-1 rounded-[18px] bg-[#e7dfcf] px-4 py-3" onPress={handleLogout}>
<Text className="text-center text-sm font-semibold text-[#4e463e]">退</Text>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
<View style={{ flex: 1 }}>
<Text style={{ fontSize: 28, fontWeight: '700', color: colors.text }}></Text>
<Text style={{ marginTop: 6, fontSize: 13, color: '#8a8072' }}></Text>
</View>
<Pressable
onPress={() => {
setShowForm((value) => !value);
setConnectionState('idle');
setConnectionMessage('');
}}
style={{ backgroundColor: colors.primary, borderRadius: 999, width: 42, height: 42, alignItems: 'center', justifyContent: 'center' }}
>
<Text style={{ color: '#fff', fontSize: 24, lineHeight: 24 }}>+</Text>
</Pressable>
</View>
</View>
</ListCard>
<ListCard title="连接配置" meta="Host 与 Admin Token 合并配置">
<View className="gap-3">
{showForm ? (
<View style={{ backgroundColor: colors.card, borderRadius: 18, padding: 16, gap: 14 }}>
<Text style={{ fontSize: 18, fontWeight: '700', color: colors.text }}></Text>
<View>
<Text className="mb-2 text-[11px] text-[#7d7468]">Host</Text>
<Text style={{ marginBottom: 8, fontSize: 12, color: colors.subtext }}></Text>
<Controller
control={control}
name="baseUrl"
@@ -107,17 +211,18 @@ export default function SettingsScreen() {
<TextInput
value={value}
onChangeText={onChange}
placeholder="http://localhost:8787"
placeholder="例如:https://api.example.com"
placeholderTextColor="#9b9081"
autoCapitalize="none"
className="rounded-[18px] bg-[#f1ece2] px-4 py-4 text-base text-[#16181a]"
autoCorrect={false}
style={{ backgroundColor: colors.mutedCard, borderRadius: 16, paddingHorizontal: 16, paddingVertical: 14, fontSize: 16, color: colors.text }}
/>
)}
/>
</View>
<View>
<Text className="mb-2 text-[11px] text-[#7d7468]">Admin Token</Text>
<Text style={{ marginBottom: 8, fontSize: 12, color: colors.subtext }}>Admin Key</Text>
<Controller
control={control}
name="adminApiKey"
@@ -128,70 +233,67 @@ export default function SettingsScreen() {
placeholder="admin-xxxxxxxx"
placeholderTextColor="#9b9081"
autoCapitalize="none"
className="rounded-[18px] bg-[#f1ece2] px-4 py-4 text-base text-[#16181a]"
autoCorrect={false}
style={{ backgroundColor: colors.mutedCard, borderRadius: 16, paddingHorizontal: 16, paddingVertical: 14, fontSize: 16, color: colors.text }}
/>
)}
/>
</View>
<Text className="text-[11px] text-[#8a8072]">使 token</Text>
{(formState.errors.baseUrl || formState.errors.adminApiKey) ? (
<View className="rounded-[16px] bg-[#fbf1eb] px-4 py-3">
<Text className="text-sm text-[#c25d35]">{formState.errors.baseUrl?.message || formState.errors.adminApiKey?.message}</Text>
{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}
</View>
</ListCard>
<ListCard title="已保存服务器" meta={`${config.accounts.length}`}>
<View className="gap-3">
{config.accounts.map((account: AdminAccountProfile) => {
const active = account.id === config.activeAccountId;
const enabled = account.enabled !== false;
return (
<View key={account.id} className="rounded-[18px] bg-[#f1ece2] px-4 py-3">
<View className="flex-row items-start justify-between gap-3">
<View className="flex-1">
<Text className="text-sm font-semibold text-[#16181a]">{account.label}</Text>
<Text className="mt-1 text-xs text-[#7d7468]">{account.baseUrl}</Text>
</View>
{active ? (
<View className="rounded-full bg-[#1d5f55] px-3 py-1">
<Text className="text-[10px] font-semibold uppercase tracking-[1px] text-white"></Text>
</View>
) : !enabled ? (
<View className="rounded-full bg-[#cfc5b7] px-3 py-1">
<Text className="text-[10px] font-semibold uppercase tracking-[1px] text-[#6f665c]"></Text>
{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>
<View className="mt-3 flex-row gap-3">
<View style={{ flexDirection: 'row', gap: 12 }}>
<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}
onPress={handleSubmit(handleAdd)}
disabled={connectionState === 'checking'}
style={{ flex: 1, backgroundColor: connectionState === 'checking' ? '#7ca89f' : colors.primary, borderRadius: 16, paddingVertical: 14, alignItems: 'center' }}
>
<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>
<Text style={{ color: '#fff', fontSize: 14, fontWeight: '700' }}>{connectionState === 'checking' ? '检测中...' : '保存并使用'}</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
onPress={() => {
setShowForm(false);
setConnectionState('idle');
setConnectionMessage('');
reset({ baseUrl: '', adminApiKey: '' });
}}
style={{ flex: 1, backgroundColor: colors.border, borderRadius: 16, paddingVertical: 14, alignItems: 'center' }}
>
<Text style={{ color: '#4e463e', fontSize: 14, fontWeight: '700' }}></Text>
</Pressable>
</View>
</View>
);
})}
) : null}
{config.accounts.length === 0 ? <Text className="text-sm text-[#7d7468]"></Text> : null}
<View style={{ gap: 12 }}>
{config.accounts.map((account: AdminAccountProfile) => (
<ServerCard
key={account.id}
account={account}
active={account.id === config.activeAccountId}
onSelect={() => handleSelect(account)}
onDelete={() => handleDelete(account)}
/>
))}
{config.accounts.length === 0 ? (
<View style={{ backgroundColor: colors.card, borderRadius: 18, padding: 18 }}>
<Text style={{ fontSize: 15, fontWeight: '700', color: colors.text }}></Text>
<Text style={{ marginTop: 8, fontSize: 13, lineHeight: 21, color: colors.subtext }}> + </Text>
</View>
</ListCard>
</ScreenShell>
) : null}
</View>
</ScrollView>
</SafeAreaView>
);
}

View File

@@ -1,264 +1,223 @@
import { useQueries, useQuery, useQueryClient } from '@tanstack/react-query';
import * as Clipboard from 'expo-clipboard';
import { Copy, Search, UserRound } from 'lucide-react-native';
import { useQuery } from '@tanstack/react-query';
import { router } from 'expo-router';
import { useCallback, useMemo, useState } from 'react';
import { FlatList, Pressable, Text, TextInput, View } from 'react-native';
import { useMemo, useState } from 'react';
import { FlatList, Pressable, RefreshControl, Text, TextInput, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { ListCard } from '@/src/components/list-card';
import { ScreenShell } from '@/src/components/screen-shell';
import { useDebouncedValue } from '@/src/hooks/use-debounced-value';
import { useScreenInteractive } from '@/src/hooks/use-screen-interactive';
import { getUser, getUserUsage, listUserApiKeys, listUsers } from '@/src/services/admin';
import { queryClient } from '@/src/lib/query-client';
import { getUser, listUserApiKeys, listUsers } from '@/src/services/admin';
import { adminConfigState } from '@/src/store/admin-config';
import type { AdminApiKey, AdminUser, UserUsageSummary } from '@/src/types/admin';
import type { AdminUser } from '@/src/types/admin';
const { useSnapshot } = require('valtio/react');
type UserSupplement = {
usage?: UserUsageSummary;
apiKeys: AdminApiKey[];
const colors = {
page: '#f4efe4',
card: '#fbf8f2',
mutedCard: '#f1ece2',
primary: '#1d5f55',
text: '#16181a',
subtext: '#6f665c',
dangerBg: '#fbf1eb',
danger: '#c25d35',
accentBg: '#efe4cf',
accentText: '#8c5a22',
};
function getUserTitle(user: AdminUser) {
return user.username?.trim() || user.email;
}
type SortOrder = 'desc' | 'asc';
function getUserSortValue(user: AdminUser) {
const raw = user.updated_at || user.created_at || '';
const value = raw ? new Date(raw).getTime() : 0;
return Number.isNaN(value) ? 0 : value;
}
function formatQuotaValue(value: number) {
function formatBalance(value?: number) {
if (typeof value !== 'number' || Number.isNaN(value)) return '$0.00';
return `$${value.toFixed(2)}`;
}
function formatActivityTime(value?: string) {
if (!value) return '时间未知';
const date = new Date(value);
if (Number.isNaN(date.getTime())) return '时间未知';
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
}
function toTimeValue(value?: string | null) {
if (!value) return 0;
const time = new Date(value).getTime();
return Number.isNaN(time) ? 0 : time;
}
function getTimeValue(user: AdminUser) {
return toTimeValue(user.last_used_at) || toTimeValue(user.updated_at) || toTimeValue(user.created_at) || user.id || 0;
}
function getUserNameLabel(user: AdminUser) {
if (user.username?.trim()) return user.username.trim();
if (user.notes?.trim()) return user.notes.trim();
return user.email.split('@')[0] || '未命名';
}
function getErrorMessage(error: unknown) {
if (error instanceof Error && error.message) {
switch (error.message) {
case 'BASE_URL_REQUIRED':
return '请先到服务器页填写服务地址。';
case 'ADMIN_API_KEY_REQUIRED':
return '请先到服务器页填写 Admin Token。';
default:
return error.message;
}
}
return '当前无法加载页面数据请检查服务地址、Token 和网络。';
}
function MetricTile({ title, value, tone = 'default' }: { title: string; value: string; tone?: 'default' | 'accent' }) {
const backgroundColor = tone === 'accent' ? colors.accentBg : colors.mutedCard;
const valueColor = tone === 'accent' ? colors.accentText : colors.text;
return (
<View style={{ flex: 1, minWidth: 0, backgroundColor, borderRadius: 14, paddingHorizontal: 10, paddingVertical: 12 }}>
<Text style={{ fontSize: 11, color: colors.subtext }}>{title}</Text>
<Text numberOfLines={1} style={{ marginTop: 6, fontSize: tone === 'accent' ? 20 : 16, fontWeight: '800', color: valueColor }}>
{value}
</Text>
</View>
);
}
function UserCard({ user }: { user: AdminUser }) {
const isAdmin = user.role?.trim().toLowerCase() === 'admin';
const statusLabel = `${isAdmin ? 'admin · ' : ''}${user.status || 'active'}`;
return (
<View style={{ backgroundColor: colors.card, borderRadius: 18, padding: 14 }}>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
<View style={{ flex: 1 }}>
<Text numberOfLines={1} style={{ fontSize: 16, fontWeight: '800', color: colors.text }}>{user.email}</Text>
<Text style={{ marginTop: 4, fontSize: 12, color: colors.subtext }}>使 {formatActivityTime(user.last_used_at || user.updated_at || user.created_at)}</Text>
</View>
<View style={{ alignSelf: 'flex-start', backgroundColor: user.status === 'inactive' ? '#cfc5b7' : colors.primary, borderRadius: 999, paddingHorizontal: 10, paddingVertical: 6 }}>
<Text style={{ fontSize: 10, fontWeight: '700', color: '#fff' }}>{statusLabel}</Text>
</View>
</View>
<View style={{ flexDirection: 'row', gap: 8, marginTop: 12 }}>
<MetricTile title="金额" value={formatBalance(Number(user.balance ?? 0))} tone="accent" />
<MetricTile title="名称" value={getUserNameLabel(user)} />
</View>
</View>
);
}
export default function UsersScreen() {
useScreenInteractive('users_interactive');
const config = useSnapshot(adminConfigState);
const [searchText, setSearchText] = useState('');
const [sortOrder, setSortOrder] = useState<'desc' | 'asc'>('desc');
const [copiedKeyId, setCopiedKeyId] = useState<number | null>(null);
const keyword = useDebouncedValue(searchText.trim(), 300);
const queryClient = useQueryClient();
const hasAccount = Boolean(config.baseUrl.trim());
const [searchText, setSearchText] = useState('');
const [sortOrder, setSortOrder] = useState<SortOrder>('desc');
const debouncedSearchText = useDebouncedValue(searchText, 250);
const usersQuery = useQuery({
queryKey: ['users', keyword],
queryFn: () => listUsers(keyword),
queryKey: ['users', debouncedSearchText],
queryFn: () => listUsers(debouncedSearchText),
enabled: hasAccount,
});
const items = usersQuery.data?.items ?? [];
const userDetailQueries = useQueries({
queries: items.map((user) => ({
queryKey: ['user-list-supplement', user.id],
queryFn: async () => {
const [usage, apiKeysData] = await Promise.all([getUserUsage(user.id), listUserApiKeys(user.id)]);
return {
usage,
apiKeys: apiKeysData.items ?? [],
} satisfies UserSupplement;
},
enabled: hasAccount,
staleTime: 60_000,
})),
const users = useMemo(() => {
const items = [...(usersQuery.data?.items ?? [])];
items.sort((left, right) => {
const value = getTimeValue(left) - getTimeValue(right);
return sortOrder === 'desc' ? -value : value;
});
return items;
}, [sortOrder, usersQuery.data?.items]);
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);
const errorMessage = getErrorMessage(usersQuery.error);
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>
<SafeAreaView style={{ flex: 1, backgroundColor: colors.page }}>
<View style={{ flex: 1, paddingHorizontal: 16, paddingTop: 14 }}>
<View style={{ marginBottom: 10 }}>
<Text style={{ fontSize: 28, fontWeight: '700', color: colors.text }}></Text>
<Text style={{ marginTop: 4, fontSize: 12, color: '#8a8072' }}></Text>
</View>
<View className="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 (
<ScreenShell
title="用户管理"
subtitle=""
titleAside={<Text className="text-[11px] text-[#a2988a]"> {sortedItems.length}</Text>}
variant="minimal"
scroll={false}
bottomInsetClassName="pb-12"
>
<View className="flex-1">
<View className="rounded-[16px] bg-[#fbf8f2] px-2.5 py-2.5">
<View className="flex-row items-center gap-2">
<View className="flex-1 flex-row items-center rounded-[14px] bg-[#f1ece2] px-3 py-2.5">
<Search color="#7d7468" size={18} />
<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="搜索邮箱用户名"
placeholder="搜索邮箱用户名或备注"
placeholderTextColor="#9b9081"
className="ml-3 flex-1 text-base text-[#16181a]"
style={{ backgroundColor: colors.mutedCard, borderRadius: 14, paddingHorizontal: 14, paddingVertical: 11, fontSize: 15, color: colors.text }}
/>
</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')}
onPress={() => setSortOrder((value) => (value === 'desc' ? 'asc' : 'desc'))}
style={{ backgroundColor: colors.card, borderRadius: 16, paddingHorizontal: 14, paddingVertical: 14, minWidth: 92, alignItems: 'center' }}
>
<Text className={sortOrder === 'desc' ? 'text-[11px] font-semibold text-white' : 'text-[11px] font-semibold text-[#4e463e]'}>
</Text>
<Text style={{ fontSize: 11, color: colors.subtext }}></Text>
<Text style={{ marginTop: 4, fontSize: 13, fontWeight: '700', color: colors.text }}>{sortOrder === 'desc' ? '倒序' : '正序'}</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 className="mt-2.5 flex-1">
{!hasAccount ? (
<View style={{ marginTop: 10, backgroundColor: colors.card, borderRadius: 18, padding: 16 }}>
<Text style={{ fontSize: 18, fontWeight: '700', color: colors.text }}></Text>
<Text style={{ marginTop: 8, fontSize: 14, lineHeight: 22, color: colors.subtext }}></Text>
<Pressable
style={{ marginTop: 14, alignSelf: 'flex-start', backgroundColor: colors.primary, borderRadius: 14, paddingHorizontal: 16, paddingVertical: 12 }}
onPress={() => router.push('/settings')}
>
<Text style={{ color: '#fff', fontSize: 13, fontWeight: '700' }}></Text>
</Pressable>
</View>
) : usersQuery.isLoading ? (
<View style={{ marginTop: 10, backgroundColor: colors.card, borderRadius: 18, padding: 16 }}>
<Text style={{ fontSize: 18, fontWeight: '700', color: colors.text }}></Text>
<Text style={{ marginTop: 8, fontSize: 14, lineHeight: 22, color: colors.subtext }}></Text>
</View>
) : usersQuery.error ? (
<View style={{ marginTop: 10, backgroundColor: colors.card, borderRadius: 18, padding: 16 }}>
<Text style={{ fontSize: 18, fontWeight: '700', color: colors.text }}></Text>
<View style={{ marginTop: 12, borderRadius: 14, backgroundColor: colors.dangerBg, paddingHorizontal: 14, paddingVertical: 12 }}>
<Text style={{ color: colors.danger, fontSize: 14, lineHeight: 20 }}>{errorMessage}</Text>
</View>
</View>
) : (
<FlatList
data={sortedItems}
renderItem={renderItem}
style={{ marginTop: 10, flex: 1 }}
data={users}
keyExtractor={(item) => `${item.id}`}
showsVerticalScrollIndicator={false}
ListHeaderComponent={() => <View className="h-2" />}
ListEmptyComponent={emptyState}
ListFooterComponent={() => <View className="h-4" />}
ItemSeparatorComponent={() => <View className="h-3" />}
keyboardShouldPersistTaps="handled"
removeClippedSubviews
initialNumToRender={8}
maxToRenderPerBatch={8}
windowSize={5}
refreshControl={<RefreshControl refreshing={usersQuery.isRefetching} onRefresh={() => void usersQuery.refetch()} tintColor="#1d5f55" />}
contentContainerStyle={{ paddingBottom: 8, gap: 12, flexGrow: users.length === 0 ? 1 : 0 }}
ListEmptyComponent={
<View style={{ backgroundColor: colors.card, borderRadius: 18, padding: 16 }}>
<Text style={{ fontSize: 18, fontWeight: '700', color: colors.text }}></Text>
<Text style={{ marginTop: 8, fontSize: 14, lineHeight: 22, color: colors.subtext }}></Text>
</View>
}
renderItem={({ item }) => (
<Pressable
onPress={() => {
void queryClient.prefetchQuery({ queryKey: ['user', item.id], queryFn: () => getUser(item.id) });
void queryClient.prefetchQuery({ queryKey: ['user-api-keys', item.id], queryFn: () => listUserApiKeys(item.id) });
router.push(`/users/${item.id}`);
}}
>
<UserCard user={item} />
</Pressable>
)}
/>
)}
</View>
</View>
</ScreenShell>
</SafeAreaView>
);
}

View File

@@ -12,16 +12,20 @@ import { adminConfigState, hydrateAdminConfig } from '@/src/store/admin-config';
const { useSnapshot } = require('valtio/react');
export const unstable_settings = {
initialRouteName: '(tabs)',
};
export default function RootLayout() {
const config = useSnapshot(adminConfigState);
useEffect(() => {
hydrateAdminConfig()
.then(() => markPerformance('config_hydrated'))
.catch(() => undefined);
}, []);
const config = useSnapshot(adminConfigState);
const isReady = config.hydrated;
return (
<GestureHandlerRootView style={{ flex: 1 }}>
<QueryClientProvider client={queryClient}>
@@ -30,10 +34,22 @@ export default function RootLayout() {
<ActivityIndicator color="#1d5f55" />
</View>
) : (
<Stack screenOptions={{ headerShown: false }}>
<Stack initialRouteName="(tabs)" screenOptions={{ headerShown: false }}>
<Stack.Screen name="(tabs)" />
<Stack.Screen name="login" />
<Stack.Screen name="users/[id]" options={{ animation: 'slide_from_right', presentation: 'card' }} />
<Stack.Screen
name="users/[id]"
options={{
animation: 'slide_from_right',
presentation: 'card',
headerShown: true,
title: '用户详情',
headerBackTitle: '返回',
headerTintColor: '#16181a',
headerStyle: { backgroundColor: '#f4efe4' },
headerShadowVisible: false,
}}
/>
<Stack.Screen name="accounts/[id]" options={{ presentation: 'card' }} />
</Stack>
)}

View File

@@ -66,11 +66,18 @@ export default function AccountDetailScreen() {
label: item.date.slice(5),
value: item.total_tokens,
}));
const isRefreshing = accountQuery.isRefetching || todayStatsQuery.isRefetching || trendQuery.isRefetching;
function handleRefresh() {
void Promise.all([accountQuery.refetch(), todayStatsQuery.refetch(), trendQuery.refetch()]);
}
return (
<ScreenShell
title={account?.name || '账号详情'}
subtitle="聚焦账号 token 用量、状态和几个最常用操作。"
refreshing={isRefreshing}
onRefresh={handleRefresh}
right={
<Pressable className="h-11 w-11 items-center justify-center rounded-full bg-[#2d3134]" onPress={() => router.back()}>
<ChevronLeft color="#f6f1e8" size={18} />

View File

@@ -1,39 +1,62 @@
import { router } from 'expo-router';
import { Redirect, router } from 'expo-router';
import { zodResolver } from '@hookform/resolvers/zod';
import { Globe, KeyRound } from 'lucide-react-native';
import { Controller, useForm } from 'react-hook-form';
import { Pressable, Text, TextInput, View } from 'react-native';
import { Pressable, ScrollView, Text, TextInput, View } from 'react-native';
import { useState } from 'react';
import { SafeAreaView } from 'react-native-safe-area-context';
import { z } from 'zod';
import { ListCard } from '@/src/components/list-card';
import { ScreenShell } from '@/src/components/screen-shell';
import { useScreenInteractive } from '@/src/hooks/use-screen-interactive';
import { isLocalProxyBaseUrl } from '@/src/lib/admin-fetch';
import { getAdminSettings, getDashboardStats } from '@/src/services/admin';
import { queryClient } from '@/src/lib/query-client';
import { adminConfigState, removeAdminAccount, saveAdminConfig, setAdminAccountEnabled, switchAdminAccount, type AdminAccountProfile } from '@/src/store/admin-config';
import { adminConfigState, saveAdminConfig } from '@/src/store/admin-config';
const { useSnapshot } = require('valtio/react');
const schema = z
.object({
baseUrl: z.string().min(1, '请输入 Host'),
baseUrl: z.string().min(1, '请输入服务器地址'),
adminApiKey: z.string(),
})
.superRefine((values, ctx) => {
if (!isLocalProxyBaseUrl(values.baseUrl.trim()) && !values.adminApiKey.trim()) {
ctx.addIssue({
code: 'custom',
.refine((values) => values.adminApiKey.trim().length > 0, {
path: ['adminApiKey'],
message: '请输入 Admin Token',
});
}
message: '请输入 Admin Key',
});
type FormValues = z.infer<typeof schema>;
type ConnectionState = 'idle' | 'checking' | 'error';
const colors = {
page: '#f4efe4',
card: '#fbf8f2',
mutedCard: '#f1ece2',
primary: '#1d5f55',
text: '#16181a',
subtext: '#6f665c',
border: '#e7dfcf',
dangerBg: '#fbf1eb',
danger: '#c25d35',
};
function getConnectionErrorMessage(error: unknown) {
if (error instanceof Error && error.message) {
switch (error.message) {
case 'BASE_URL_REQUIRED':
return '请先填写服务器地址。';
case 'ADMIN_API_KEY_REQUIRED':
return '请先填写 Admin Key。';
case 'INVALID_SERVER_RESPONSE':
return '当前地址返回的数据不正确,请确认它是可用的管理接口。';
default:
return error.message;
}
}
return '连接失败请检查服务器地址、Admin Key 和网络连通性。';
}
export default function LoginScreen() {
useScreenInteractive('login_interactive');
const config = useSnapshot(adminConfigState);
const hasAccount = Boolean(config.baseUrl.trim());
const { control, handleSubmit, formState } = useForm<FormValues>({
resolver: zodResolver(schema),
defaultValues: {
@@ -41,115 +64,111 @@ export default function LoginScreen() {
adminApiKey: config.adminApiKey,
},
});
const [connectionState, setConnectionState] = useState<ConnectionState>('idle');
const [connectionMessage, setConnectionMessage] = useState('');
if (hasAccount) {
return <Redirect href="/monitor" />;
}
return (
<ScreenShell
title="登录"
subtitle=""
titleAside={<Text className="text-[11px] text-[#a2988a]"> Sub2API </Text>}
variant="minimal"
>
{config.accounts.length > 0 ? (
<ListCard title="已保存账号" meta="可直接切换到其他 Sub2API 账号">
<View className="gap-3">
{config.accounts.map((account: AdminAccountProfile) => {
const active = account.id === config.activeAccountId;
const enabled = account.enabled !== false;
return (
<View key={account.id} className="rounded-[18px] bg-[#f1ece2] px-4 py-3">
<Text className="text-sm font-semibold text-[#16181a]">{account.label}</Text>
<Text className="mt-1 text-xs text-[#7d7468]">{account.baseUrl}</Text>
<View className="mt-3 flex-row gap-3">
<Pressable
className={active ? 'flex-1 rounded-[16px] bg-[#d7eee4] px-3 py-2.5' : !enabled ? 'flex-1 rounded-[16px] bg-[#d8d1c4] px-3 py-2.5' : 'flex-1 rounded-[16px] bg-[#1d5f55] px-3 py-2.5'}
onPress={async () => {
await switchAdminAccount(account.id);
queryClient.clear();
router.replace('/monitor');
}}
disabled={!enabled}
>
<Text className={active ? 'text-center text-xs font-semibold text-[#1d5f55]' : !enabled ? 'text-center text-xs font-semibold text-[#7d7468]' : 'text-center text-xs font-semibold text-white'}>
{active ? '使用中' : '切换账号'}
<SafeAreaView style={{ flex: 1, backgroundColor: colors.page }}>
<ScrollView contentContainerStyle={{ flexGrow: 1, paddingHorizontal: 20, paddingVertical: 24 }} keyboardShouldPersistTaps="handled">
<View style={{ flex: 1, justifyContent: 'center', gap: 20 }}>
<View style={{ gap: 8 }}>
<Text style={{ fontSize: 34, fontWeight: '800', color: colors.text }}></Text>
<Text style={{ fontSize: 14, lineHeight: 22, color: colors.subtext }}>
Admin Key
</Text>
</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>
</ListCard>
) : null}
<ListCard title="Host" meta="当前站点或管理代理地址" icon={Globe}>
<View style={{ backgroundColor: colors.card, borderRadius: 22, padding: 18, gap: 16 }}>
<View>
<Text style={{ marginBottom: 8, fontSize: 12, color: colors.subtext }}></Text>
<Controller
control={control}
name="baseUrl"
render={({ field: { onChange, value } }) => (
<TextInput
value={value}
onChangeText={onChange}
placeholder="http://localhost:8787"
onChangeText={(text) => {
if (connectionState !== 'idle') {
setConnectionState('idle');
setConnectionMessage('');
}
onChange(text);
}}
placeholder="例如https://api.example.com"
placeholderTextColor="#9b9081"
autoCapitalize="none"
className="rounded-[18px] bg-[#f1ece2] px-4 py-4 text-base text-[#16181a]"
autoCorrect={false}
style={{ backgroundColor: colors.mutedCard, borderRadius: 16, paddingHorizontal: 16, paddingVertical: 14, fontSize: 16, color: colors.text }}
/>
)}
/>
</ListCard>
</View>
<ListCard title="Admin Token" meta="直连上游时必填;使用本地代理可留空" icon={KeyRound}>
<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}
onChangeText={(text) => {
if (connectionState !== 'idle') {
setConnectionState('idle');
setConnectionMessage('');
}
onChange(text);
}}
placeholder="admin-xxxxxxxx"
placeholderTextColor="#9b9081"
autoCapitalize="none"
className="rounded-[18px] bg-[#f1ece2] px-4 py-4 text-base text-[#16181a]"
autoCorrect={false}
style={{ backgroundColor: colors.mutedCard, borderRadius: 16, paddingHorizontal: 16, paddingVertical: 14, fontSize: 16, color: colors.text }}
/>
)}
/>
</ListCard>
</View>
{(formState.errors.baseUrl || formState.errors.adminApiKey) ? (
<View className="rounded-[20px] bg-[#fbf1eb] px-4 py-3">
<Text className="text-sm text-[#c25d35]">{formState.errors.baseUrl?.message || formState.errors.adminApiKey?.message}</Text>
{formState.errors.baseUrl || formState.errors.adminApiKey ? (
<View style={{ borderRadius: 14, backgroundColor: colors.dangerBg, paddingHorizontal: 14, paddingVertical: 12 }}>
<Text style={{ color: colors.danger, fontSize: 14 }}>{formState.errors.baseUrl?.message || formState.errors.adminApiKey?.message}</Text>
</View>
) : null}
{connectionMessage ? (
<View style={{ borderRadius: 14, backgroundColor: colors.dangerBg, paddingHorizontal: 14, paddingVertical: 12 }}>
<Text style={{ color: colors.danger, fontSize: 14 }}>{connectionMessage}</Text>
</View>
) : null}
<Pressable
className="rounded-[20px] bg-[#1d5f55] px-4 py-4"
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 className="text-center text-sm font-semibold tracking-[1.2px] text-white">
{config.saving ? '登录中...' : '进入管理台'}
</Text>
<Text style={{ color: '#fff', fontSize: 15, fontWeight: '700' }}>{connectionState === 'checking' ? '连接中...' : '进入应用'}</Text>
</Pressable>
</ScreenShell>
</View>
</View>
</ScrollView>
</SafeAreaView>
);
}

View File

@@ -1,44 +1,252 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { zodResolver } from '@hookform/resolvers/zod';
import * as Clipboard from 'expo-clipboard';
import { ArrowLeftRight, ChevronLeft, Copy, KeyRound, Search, Wallet } from 'lucide-react-native';
import { router, useLocalSearchParams } from 'expo-router';
import { Stack, useLocalSearchParams } from 'expo-router';
import { useMemo, useState } from 'react';
import { Controller, useForm } from 'react-hook-form';
import { Pressable, Text, TextInput, View } from 'react-native';
import { z } from 'zod';
import { Pressable, ScrollView, Text, TextInput, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { DetailRow } from '@/src/components/detail-row';
import { ListCard } from '@/src/components/list-card';
import { formatDisplayTime } from '@/src/lib/formatters';
import { ScreenShell } from '@/src/components/screen-shell';
import { useDebouncedValue } from '@/src/hooks/use-debounced-value';
import { getUser, getUserUsage, listUserApiKeys, updateUserBalance } from '@/src/services/admin';
import type { BalanceOperation } from '@/src/types/admin';
import { LineTrendChart } from '@/src/components/line-trend-chart';
import { getDashboardSnapshot, getUsageStats, getUser, listUserApiKeys, updateUserBalance } from '@/src/services/admin';
import type { AdminApiKey, BalanceOperation } from '@/src/types/admin';
const schema = z.object({
amount: z.string().min(1, '请输入金额'),
notes: z.string().optional(),
});
const colors = {
page: '#f4efe4',
card: '#fbf8f2',
text: '#16181a',
subtext: '#6f665c',
border: '#e7dfcf',
primary: '#1d5f55',
dark: '#1b1d1f',
errorBg: '#f7e1d6',
errorText: '#a4512b',
muted: '#f7f1e6',
};
type FormValues = z.infer<typeof schema>;
type RangeKey = '24h' | '7d' | '30d';
const RANGE_OPTIONS: Array<{ key: RangeKey; label: string }> = [
{ key: '24h', label: '24H' },
{ key: '7d', label: '7D' },
{ key: '30d', label: '30D' },
];
function getDateRange(rangeKey: RangeKey) {
const end = new Date();
const start = new Date();
if (rangeKey === '24h') {
start.setHours(end.getHours() - 23, 0, 0, 0);
} else if (rangeKey === '30d') {
start.setDate(end.getDate() - 29);
} else {
start.setDate(end.getDate() - 6);
}
const toDate = (value: Date) => value.toISOString().slice(0, 10);
return {
start_date: toDate(start),
end_date: toDate(end),
granularity: rangeKey === '24h' ? ('hour' as const) : ('day' as const),
};
}
function getErrorMessage(error: unknown) {
if (error instanceof Error && error.message) {
switch (error.message) {
case 'BASE_URL_REQUIRED':
return '请先到服务器页填写服务地址。';
case 'ADMIN_API_KEY_REQUIRED':
return '请先到服务器页填写 Admin Token。';
default:
return error.message;
}
}
return '加载失败,请稍后重试。';
}
function formatMoney(value?: number | null) {
return `$${Number(value ?? 0).toFixed(2)}`;
}
function formatUsageCost(stats?: { total_account_cost?: number | null; total_actual_cost?: number | null; total_cost?: number | null }) {
const value = Number(stats?.total_account_cost ?? stats?.total_actual_cost ?? stats?.total_cost ?? 0);
return `$${value.toFixed(4)}`;
}
function formatTokenValue(value?: number | null) {
const number = Number(value ?? 0);
if (number >= 1_000_000_000) return `${(number / 1_000_000_000).toFixed(2)}B`;
if (number >= 1_000_000) return `${(number / 1_000_000).toFixed(2)}M`;
if (number >= 1_000) return `${(number / 1_000).toFixed(2)}K`;
return new Intl.NumberFormat('en-US').format(number);
}
function formatQuota(quotaUsed?: number | null, quota?: number | null) {
const used = Number(quotaUsed ?? 0);
const limit = Number(quota ?? 0);
if (limit <= 0) {
return '∞';
}
return `${used} / ${limit}`;
}
function formatTime(value?: string | null) {
if (!value) return '--';
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value;
const year = date.getFullYear();
const month = `${date.getMonth() + 1}`.padStart(2, '0');
const day = `${date.getDate()}`.padStart(2, '0');
const hours = `${date.getHours()}`.padStart(2, '0');
const minutes = `${date.getMinutes()}`.padStart(2, '0');
return `${year}-${month}-${day} ${hours}:${minutes}`;
}
function Section({ title, children }: { title: string; children: React.ReactNode }) {
return (
<View
style={{
backgroundColor: colors.card,
borderRadius: 16,
padding: 16,
marginBottom: 12,
borderWidth: 1,
borderColor: colors.border,
}}
>
<Text style={{ fontSize: 18, fontWeight: '700', color: colors.text }}>{title}</Text>
<View style={{ marginTop: 12 }}>{children}</View>
</View>
);
}
function GridField({ label, value }: { label: string; value: string }) {
return (
<View
style={{
width: '48.5%',
backgroundColor: colors.muted,
borderRadius: 12,
paddingHorizontal: 12,
paddingVertical: 12,
borderWidth: 1,
borderColor: colors.border,
}}
>
<Text style={{ fontSize: 12, color: colors.subtext }}>{label}</Text>
<Text style={{ marginTop: 6, fontSize: 15, fontWeight: '600', color: colors.text }}>{value}</Text>
</View>
);
}
function MetricCard({ label, value }: { label: string; value: string }) {
return (
<View
style={{
flex: 1,
backgroundColor: colors.muted,
borderRadius: 12,
paddingHorizontal: 12,
paddingVertical: 12,
borderWidth: 1,
borderColor: colors.border,
}}
>
<Text style={{ fontSize: 12, color: colors.subtext }}>{label}</Text>
<Text style={{ marginTop: 6, fontSize: 16, fontWeight: '700', color: colors.text }}>{value}</Text>
</View>
);
}
function StatusBadge({ text }: { text: string }) {
const normalized = text.toLowerCase();
const backgroundColor = normalized === 'active' ? '#dff4ea' : normalized === 'inactive' ? '#ece5da' : '#f7e1d6';
const color = normalized === 'active' ? '#17663f' : normalized === 'inactive' ? '#6f665c' : '#a4512b';
return (
<View style={{ backgroundColor, borderRadius: 999, paddingHorizontal: 10, paddingVertical: 6 }}>
<Text style={{ fontSize: 12, fontWeight: '700', color }}>{text}</Text>
</View>
);
}
function CopyInlineButton({ copied, onPress }: { copied: boolean; onPress: () => void }) {
return (
<Pressable
onPress={onPress}
style={{
marginLeft: 8,
backgroundColor: copied ? '#dff4ea' : '#e7dfcf',
borderRadius: 999,
paddingHorizontal: 10,
paddingVertical: 6,
}}
>
<Text style={{ fontSize: 11, fontWeight: '700', color: copied ? '#17663f' : '#4e463e' }}>{copied ? '已复制' : '复制'}</Text>
</Pressable>
);
}
function KeyItem({ item, copied, onCopy }: { item: AdminApiKey; copied: boolean; onCopy: () => void }) {
return (
<View
style={{
backgroundColor: colors.muted,
borderRadius: 14,
padding: 12,
borderWidth: 1,
borderColor: colors.border,
marginBottom: 10,
}}
>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
<View style={{ flex: 1 }}>
<View style={{ flexDirection: 'row', alignItems: 'center', flexWrap: 'wrap' }}>
<Text style={{ fontSize: 15, fontWeight: '700', color: colors.text }}>{item.name || `Key #${item.id}`}</Text>
<CopyInlineButton copied={copied} onPress={onCopy} />
</View>
<Text style={{ marginTop: 4, fontSize: 12, color: colors.subtext }}>{item.group?.name || '未分组'}</Text>
</View>
<StatusBadge text={item.status || '--'} />
</View>
<Text style={{ marginTop: 10, fontSize: 12, lineHeight: 18, color: colors.text }}>{item.key || '--'}</Text>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12, marginTop: 12 }}>
<View style={{ flex: 1 }}>
<Text style={{ fontSize: 11, color: colors.subtext }}></Text>
<Text style={{ marginTop: 4, fontSize: 16, fontWeight: '700', color: colors.text }}>{formatQuota(item.quota_used, item.quota)}</Text>
</View>
<View style={{ flex: 1, alignItems: 'flex-end' }}>
<Text style={{ fontSize: 11, color: colors.subtext }}>使</Text>
<Text style={{ marginTop: 4, fontSize: 13, color: colors.subtext }}>{formatTime(item.last_used_at || item.updated_at || item.created_at)}</Text>
</View>
</View>
</View>
);
}
export default function UserDetailScreen() {
const { id } = useLocalSearchParams<{ id: string }>();
const userId = Number(id);
const queryClient = useQueryClient();
const [operation, setOperation] = useState<BalanceOperation>('add');
const [keySearchText, setKeySearchText] = useState('');
const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'inactive'>('all');
const [amount, setAmount] = useState('10');
const [notes, setNotes] = useState('');
const [formError, setFormError] = useState<string | null>(null);
const [searchText, setSearchText] = useState('');
const [copiedKeyId, setCopiedKeyId] = useState<number | null>(null);
const keySearch = useDebouncedValue(keySearchText.trim().toLowerCase(), 250);
const { control, handleSubmit, reset, formState } = useForm<FormValues>({
resolver: zodResolver(schema),
defaultValues: {
amount: '10',
notes: '',
},
});
const [rangeKey, setRangeKey] = useState<RangeKey>('7d');
const range = getDateRange(rangeKey);
const userQuery = useQuery({
queryKey: ['user', userId],
@@ -46,199 +254,329 @@ export default function UserDetailScreen() {
enabled: Number.isFinite(userId),
});
const usageQuery = useQuery({
queryKey: ['user-usage', userId],
queryFn: () => getUserUsage(userId),
enabled: Number.isFinite(userId),
});
const apiKeysQuery = useQuery({
queryKey: ['user-api-keys', userId],
queryFn: () => listUserApiKeys(userId),
enabled: Number.isFinite(userId),
});
const usageStatsQuery = useQuery({
queryKey: ['usage-stats', 'user', userId, rangeKey, range.start_date, range.end_date],
queryFn: () => getUsageStats({ ...range, user_id: userId }),
enabled: Number.isFinite(userId),
});
const usageSnapshotQuery = useQuery({
queryKey: ['usage-snapshot', 'user', userId, rangeKey, range.start_date, range.end_date, range.granularity],
queryFn: () =>
getDashboardSnapshot({
...range,
user_id: userId,
include_stats: false,
include_trend: true,
include_model_stats: false,
include_group_stats: false,
include_users_trend: false,
}),
enabled: Number.isFinite(userId),
});
;
;
const balanceMutation = useMutation({
mutationFn: (values: FormValues & { operation: BalanceOperation }) =>
mutationFn: (payload: { amount: number; notes?: string; operation: BalanceOperation }) =>
updateUserBalance(userId, {
balance: Number(values.amount),
operation: values.operation,
notes: values.notes,
balance: payload.amount,
notes: payload.notes,
operation: payload.operation,
}),
onSuccess: () => {
setFormError(null);
setAmount('10');
setNotes('');
queryClient.invalidateQueries({ queryKey: ['user', userId] });
queryClient.invalidateQueries({ queryKey: ['users'] });
reset({ amount: '10', notes: '' });
},
onError: (error) => setFormError(getErrorMessage(error)),
});
const user = userQuery.data;
const usage = usageQuery.data;
const apiKeys = apiKeysQuery.data?.items ?? [];
const filteredApiKeys = useMemo(
() =>
apiKeys.filter((item) => {
const matchesStatus = statusFilter === 'all' ? true : item.status === statusFilter;
const matchesSearch = !keySearch
? true
: [item.name, item.key, item.group?.name]
.filter(Boolean)
.join(' ')
.toLowerCase()
.includes(keySearch);
return matchesStatus && matchesSearch;
}),
[apiKeys, keySearch, statusFilter]
);
const filteredApiKeys = useMemo(() => {
const keyword = searchText.trim().toLowerCase();
function maskKey(value: string) {
if (!value || value.length < 16) {
return value;
return apiKeys.filter((item) => {
const haystack = [item.name, item.key, item.group?.name].filter(Boolean).join(' ').toLowerCase();
return keyword ? haystack.includes(keyword) : true;
});
}, [apiKeys, searchText]);
const trendPoints = (usageSnapshotQuery.data?.trend ?? []).map((item) => ({
label: rangeKey === '24h' ? item.date.slice(11, 13) : item.date.slice(5, 10),
value: item.total_tokens,
}));
function submitBalance() {
const numericAmount = Number(amount);
if (!amount.trim()) {
setFormError('请输入金额。');
return;
}
return `${value.slice(0, 8)}••••••${value.slice(-8)}`;
if (!Number.isFinite(numericAmount) || numericAmount < 0) {
setFormError('金额格式不正确。');
return;
}
async function copyKey(keyId: number, value: string) {
await Clipboard.setStringAsync(value);
setCopiedKeyId(keyId);
setTimeout(() => setCopiedKeyId((current) => (current === keyId ? null : current)), 1600);
balanceMutation.mutate({
amount: numericAmount,
notes: notes.trim() || undefined,
operation,
});
}
async function copyKey(item: AdminApiKey) {
await Clipboard.setStringAsync(item.key || '');
setCopiedKeyId(item.id);
setTimeout(() => {
setCopiedKeyId((current) => (current === item.id ? null : current));
}, 1500);
}
return (
<ScreenShell
title={user?.username || user?.email || '用户详情'}
subtitle=""
titleAside={<Text className="text-[11px] text-[#a2988a]"></Text>}
variant="minimal"
right={
<Pressable className="h-11 w-11 items-center justify-center rounded-full bg-[#2d3134]" onPress={() => router.back()}>
<ChevronLeft color="#f6f1e8" size={18} />
</Pressable>
}
<>
<Stack.Screen options={{ title: user?.email || '用户详情' }} />
<SafeAreaView edges={['bottom']} style={{ flex: 1, backgroundColor: colors.page }}>
<ScrollView style={{ flex: 1 }} contentContainerStyle={{ padding: 16, paddingBottom: 40 }}>
{userQuery.isLoading ? (
<Section title="状态">
<Text style={{ color: colors.subtext }}>...</Text>
</Section>
) : null}
{userQuery.error ? (
<Section title="状态">
<View style={{ backgroundColor: colors.errorBg, borderRadius: 12, padding: 12 }}>
<Text style={{ color: colors.errorText, fontWeight: '700' }}></Text>
<Text style={{ marginTop: 6, color: colors.errorText }}>{getErrorMessage(userQuery.error)}</Text>
</View>
</Section>
) : null}
{user ? (
<Section title="基础信息">
<View style={{ flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-between', rowGap: 10 }}>
<View
style={{
width: '48.5%',
justifyContent: 'center',
paddingHorizontal: 4,
paddingVertical: 8,
}}
>
<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>
<Text style={{ fontSize: 11, color: colors.subtext }}></Text>
<Text style={{ marginTop: 4, fontSize: 13, color: colors.subtext }}>{user.email || '--'}</Text>
</View>
<GridField label="用户名" value={user.username || '--'} />
<GridField label="余额" value={formatMoney(user.balance)} />
<View
style={{
width: '48.5%',
justifyContent: 'center',
paddingHorizontal: 4,
paddingVertical: 8,
}}
>
<Text style={{ fontSize: 11, color: colors.subtext }}>使</Text>
<Text style={{ marginTop: 4, fontSize: 13, color: colors.subtext }}>{formatTime(user.last_used_at || user.updated_at || user.created_at)}</Text>
</View>
</View>
</Section>
) : null}
<ListCard title="月度用量" meta="真实数据来自 /users/:id/usage" icon={ArrowLeftRight}>
<DetailRow label="Token" value={`${Number(usage?.tokens ?? usage?.total_tokens ?? 0)}`} />
<DetailRow label="请求数" value={`${Number(usage?.requests ?? usage?.total_requests ?? 0)}`} />
<DetailRow label="成本" value={`$${Number(usage?.cost ?? usage?.total_cost ?? 0).toFixed(4)}`} />
</ListCard>
<Section title="用量">
<View style={{ flexDirection: 'row', gap: 8, marginBottom: 12 }}>
{RANGE_OPTIONS.map((item) => {
const active = item.key === rangeKey;
return (
<Pressable
key={item.key}
onPress={() => setRangeKey(item.key)}
style={{
backgroundColor: active ? colors.primary : colors.muted,
borderRadius: 999,
paddingHorizontal: 12,
paddingVertical: 8,
borderWidth: 1,
borderColor: active ? colors.primary : colors.border,
}}
>
<Text style={{ color: active ? '#fff' : colors.text, fontSize: 12, fontWeight: '700' }}>{item.label}</Text>
</Pressable>
);
})}
</View>
<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 style={{ flexDirection: 'row', gap: 8 }}>
<MetricCard label="请求" value={formatTokenValue(usageStatsQuery.data?.total_requests)} />
<MetricCard label="Token" value={formatTokenValue(usageStatsQuery.data?.total_tokens)} />
<MetricCard label="成本" value={formatUsageCost(usageStatsQuery.data)} />
</View>
{usageStatsQuery.data ? (
<Text style={{ marginTop: 10, fontSize: 12, color: colors.subtext }}>
{formatTokenValue(usageStatsQuery.data.total_input_tokens)} · {formatTokenValue(usageStatsQuery.data.total_output_tokens)}
</Text>
) : null}
{usageStatsQuery.isLoading ? <Text style={{ marginTop: 12, color: colors.subtext }}>...</Text> : null}
{usageStatsQuery.error ? (
<View style={{ marginTop: 12, backgroundColor: colors.errorBg, borderRadius: 12, padding: 12 }}>
<Text style={{ color: colors.errorText, fontWeight: '700' }}></Text>
<Text style={{ marginTop: 6, color: colors.errorText }}>{getErrorMessage(usageStatsQuery.error)}</Text>
</View>
) : null}
{!usageSnapshotQuery.isLoading && trendPoints.length > 1 ? (
<View style={{ marginTop: 14 }}>
<LineTrendChart
title="用量趋势"
subtitle={`${range.start_date}${range.end_date}`}
points={trendPoints}
color="#1d5f55"
formatValue={(value) => formatTokenValue(value)}
compact
/>
</View>
<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>
))}
) : null}
{usageSnapshotQuery.isLoading ? <Text style={{ marginTop: 12, color: colors.subtext }}>...</Text> : null}
{usageSnapshotQuery.error ? (
<View style={{ marginTop: 12, backgroundColor: colors.errorBg, borderRadius: 12, padding: 12 }}>
<Text style={{ color: colors.errorText, fontWeight: '700' }}></Text>
<Text style={{ marginTop: 6, color: colors.errorText }}>{getErrorMessage(usageSnapshotQuery.error)}</Text>
</View>
) : null}
</Section>
<Section title="API Keys">
<TextInput
value={searchText}
onChangeText={setSearchText}
placeholder="搜索名称 / Key / 分组"
placeholderTextColor="#9a9082"
style={{
backgroundColor: colors.muted,
borderWidth: 1,
borderColor: colors.border,
borderRadius: 12,
paddingHorizontal: 12,
paddingVertical: 12,
color: colors.text,
marginBottom: 10,
}}
/>
{apiKeysQuery.isLoading ? <Text style={{ color: colors.subtext }}> API Keys...</Text> : null}
{apiKeysQuery.error ? (
<View style={{ backgroundColor: colors.errorBg, borderRadius: 12, padding: 12 }}>
<Text style={{ color: colors.errorText, fontWeight: '700' }}>API Keys </Text>
<Text style={{ marginTop: 6, color: colors.errorText }}>{getErrorMessage(apiKeysQuery.error)}</Text>
</View>
) : null}
{!apiKeysQuery.isLoading && !apiKeysQuery.error ? (
filteredApiKeys.length > 0 ? (
<View>
{filteredApiKeys.map((item) => (
<View key={item.id} className="rounded-[18px] bg-[#f1ece2] px-4 py-3">
<View className="flex-row items-center justify-between gap-3">
<Text className="flex-1 text-sm font-semibold text-[#16181a]">{item.name}</Text>
<Text className="text-xs uppercase tracking-[1.2px] text-[#7d7468]">{item.status}</Text>
</View>
<View className="mt-2 flex-row items-center gap-2">
<Text className="flex-1 text-xs text-[#7d7468]">{maskKey(item.key)}</Text>
<Pressable
className="rounded-full bg-[#e7dfcf] p-2"
onPress={() => copyKey(item.id, item.key)}
>
<Copy color="#4e463e" size={14} />
</Pressable>
</View>
<Text className="mt-2 text-xs text-[#7d7468]">
{copiedKeyId === item.id ? '已复制到剪贴板' : `最近使用 ${formatDisplayTime(item.last_used_at)}`}
</Text>
<Text className="mt-2 text-xs text-[#7d7468]">
${Number(item.quota_used ?? 0).toFixed(2)} / {item.quota ? `$${Number(item.quota).toFixed(2)}` : '无限制'}
</Text>
<Text className="mt-1 text-xs text-[#7d7468]">
{item.group?.name || '未绑定'} · 5h {Number(item.usage_5h ?? 0).toFixed(2)}
</Text>
</View>
<KeyItem key={item.id} item={item} copied={copiedKeyId === item.id} onCopy={() => copyKey(item)} />
))}
{filteredApiKeys.length === 0 ? <Text className="text-sm text-[#7d7468]"> API </Text> : null}
</View>
</ListCard>
) : (
<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>
<ListCard title="余额调整" meta="默认执行增加余额,可继续扩成减余额和设定值。" icon={Wallet}>
<View className="gap-3">
<Controller
control={control}
name="amount"
render={({ field: { onChange, value } }) => (
<TextInput
value={value}
onChangeText={onChange}
value={amount}
onChangeText={setAmount}
placeholder="输入金额,例如 10"
placeholderTextColor="#9a9082"
keyboardType="decimal-pad"
placeholder="输入金额"
placeholderTextColor="#9b9081"
className="rounded-[18px] bg-[#f1ece2] px-4 py-4 text-base text-[#16181a]"
style={{
backgroundColor: colors.muted,
borderWidth: 1,
borderColor: colors.border,
borderRadius: 12,
paddingHorizontal: 12,
paddingVertical: 12,
color: colors.text,
marginBottom: 10,
}}
/>
)}
/>
<View className="flex-row gap-2">
{(['add', 'subtract', 'set'] as BalanceOperation[]).map((item) => (
<Pressable
key={item}
className={operation === item ? 'flex-1 rounded-[16px] bg-[#1d5f55] px-3 py-3' : 'flex-1 rounded-[16px] bg-[#e7dfcf] px-3 py-3'}
onPress={() => setOperation(item)}
>
<Text className={operation === item ? 'text-center text-sm font-semibold text-white' : 'text-center text-sm font-semibold text-[#4e463e]'}>
{item === 'add' ? '增加' : item === 'subtract' ? '扣减' : '设为'}
</Text>
</Pressable>
))}
</View>
<Controller
control={control}
name="notes"
render={({ field: { onChange, value } }) => (
<TextInput
value={value}
onChangeText={onChange}
placeholder="备注,可留空"
placeholderTextColor="#9b9081"
className="rounded-[18px] bg-[#f1ece2] px-4 py-4 text-base text-[#16181a]"
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,
}}
/>
)}
/>
{formState.errors.amount ? <Text className="text-sm text-[#c25d35]">{formState.errors.amount.message}</Text> : null}
<Pressable
className="rounded-[18px] bg-[#1d5f55] px-4 py-4"
onPress={handleSubmit((values) => balanceMutation.mutate({ ...values, operation }))}
>
<Text className="text-center text-sm font-semibold tracking-[1.2px] text-white">
{balanceMutation.isPending ? '提交中...' : operation === 'add' ? '增加余额' : operation === 'subtract' ? '扣减余额' : '设置余额'}
</Text>
</Pressable>
{formError ? (
<View style={{ backgroundColor: colors.errorBg, borderRadius: 12, padding: 12, marginBottom: 10 }}>
<Text style={{ color: colors.errorText }}>{formError}</Text>
</View>
</ListCard>
</ScreenShell>
) : 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>
</>
);
}

View File

@@ -9,8 +9,10 @@
## 已完成配置
- `app.json` 已配置 `owner`
- `app.json` 已配置 `scheme = sub2apimobile`
- `app.json` 已配置 `runtimeVersion.policy = appVersion`
- `app.json` 已配置 `updates.url`
- `package.json` 已包含 `expo-dev-client`
- `eas.json` 已配置 `development / preview / production` 三套 profile
## 登录状态检查
@@ -20,6 +22,45 @@ npx expo 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
@@ -34,6 +75,13 @@ npm run eas:build:preview
npm run eas:build:development
```
也可以分平台:
```bash
npm run eas:build:development:android
npm run eas:build:development:ios
```
当前 `development` profile 已配置:
- `developmentClient: true`
@@ -42,6 +90,92 @@ npm run eas:build:development
适合先生成一个测试壳,后续再配合 `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/workflows/eas-build.yml`
@@ -85,10 +219,3 @@ npx eas update --branch preview --message "preview update"
```bash
npx eas update --branch production --message "production update"
```
## 当前还需要你补的内容
- iOS 的 `bundleIdentifier`
- Android 的 `package`
如果不补这两个标识,原生构建时 EAS 还会继续要求你确认或生成。

6322
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -13,43 +13,47 @@
"eas:build:preview": "eas build --profile preview",
"eas:build:production": "eas build --profile production",
"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": {
"@expo/vector-icons": "^15.1.1",
"@hookform/resolvers": "^5.2.2",
"@tanstack/react-query": "^5.90.21",
"cors": "^2.8.6",
"expo": "~55.0.5",
"expo-clipboard": "~55.0.8",
"expo-constants": "~55.0.7",
"expo-dev-client": "~6.0.16",
"expo-linking": "~55.0.7",
"expo-router": "~55.0.4",
"expo-secure-store": "~55.0.8",
"expo-status-bar": "~55.0.4",
"expo-updates": "~55.0.12",
"expo": "~54.0.33",
"expo-clipboard": "~8.0.8",
"expo-constants": "~18.0.13",
"expo-dev-client": "~6.0.20",
"expo-font": "~14.0.11",
"expo-linking": "~8.0.11",
"expo-router": "~6.0.23",
"expo-secure-store": "~15.0.8",
"expo-status-bar": "~3.0.9",
"expo-updates": "~29.0.16",
"express": "^5.2.1",
"lucide-react-native": "^0.577.0",
"react": "19.2.0",
"react-dom": "19.2.0",
"react": "19.1.0",
"react-dom": "19.1.0",
"react-hook-form": "^7.71.2",
"react-native": "0.83.2",
"react-native-gesture-handler": "~2.30.0",
"react-native-reanimated": "4.2.1",
"react-native-safe-area-context": "~5.6.2",
"react-native-screens": "~4.23.0",
"react-native-svg": "15.15.3",
"react-native-web": "^0.21.2",
"react-native-worklets": "0.7.2",
"react-native": "0.81.5",
"react-native-gesture-handler": "~2.28.0",
"react-native-reanimated": "~4.1.1",
"react-native-safe-area-context": "~5.6.0",
"react-native-screens": "~4.16.0",
"react-native-svg": "15.12.1",
"react-native-web": "~0.21.0",
"react-native-worklets": "0.5.1",
"tailwindcss": "^4.2.1",
"uniwind": "^1.5.0",
"uniwind": "^1.3.2",
"valtio": "^2.3.1",
"zod": "^4.3.6"
},
"devDependencies": {
"@types/react": "~19.2.2",
"@types/react": "~19.1.0",
"concurrently": "^9.2.1",
"eas-cli": "^18.1.0",
"typescript": "~5.9.2"
},
"private": true

View File

@@ -1,3 +1,4 @@
import { useMemo } from 'react';
import { Text, View } from 'react-native';
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 minValue = Math.min(...points.map((point) => point.value), 0);
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
.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'}`}>
<Svg width="100%" height={height} viewBox={`0 0 ${width} ${height}`}>
<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="100%" stopColor={color} stopOpacity="0.02" />
</LinearGradient>
</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" />
</Svg>
<View className="mt-2 flex-row justify-between">
{tickPoints.map((point) => (
<Text key={point.label} className={`text-[#7d7468] ${compact ? 'text-[10px]' : 'text-xs'}`}>
{tickPoints.map((point, index) => (
<Text key={`${point.label}-${index}`} className={`text-[#7d7468] ${compact ? 'text-[10px]' : 'text-xs'}`}>
{point.label}
</Text>
))}

View File

@@ -1,6 +1,6 @@
import type { PropsWithChildren, ReactNode } from 'react';
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<{
title: string;
@@ -12,6 +12,8 @@ type ScreenShellProps = PropsWithChildren<{
bottomInsetClassName?: string;
horizontalInsetClassName?: string;
contentGapClassName?: string;
refreshing?: boolean;
onRefresh?: () => void | Promise<void>;
}>;
function ScreenHeader({
@@ -66,6 +68,8 @@ export function ScreenShell({
bottomInsetClassName = 'pb-24',
horizontalInsetClassName = 'px-5',
contentGapClassName = 'mt-4 gap-4',
refreshing = false,
onRefresh,
}: ScreenShellProps) {
if (!scroll) {
return (
@@ -80,9 +84,15 @@ export function ScreenShell({
return (
<SafeAreaView className="flex-1 bg-[#f4efe4]">
<ScrollView className="flex-1" contentContainerClassName={`${horizontalInsetClassName} ${bottomInsetClassName}`}>
<ScrollView
className="flex-1"
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>
</SafeAreaView>
);

View File

@@ -1,14 +1,6 @@
import { adminConfigState } from '@/src/store/admin-config';
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>(
path: string,
init: RequestInit = {},
@@ -21,7 +13,7 @@ export async function adminFetch<T>(
throw new Error('BASE_URL_REQUIRED');
}
if (!adminApiKey && !isProxyBaseUrl(baseUrl)) {
if (!adminApiKey) {
throw new Error('ADMIN_API_KEY_REQUIRED');
}

View File

@@ -8,13 +8,15 @@ import type {
AdminUser,
BalanceOperation,
DashboardModelStats,
DashboardSnapshot,
DashboardStats,
DashboardTrend,
PaginatedData,
UsageStats,
UserUsageSummary,
} 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();
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)}`);
}
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 = '') {
return adminFetch<PaginatedData<AdminUser>>(
`/api/v1/admin/users${buildQuery({ page: 1, page_size: 20, search: search.trim() })}`

View File

@@ -1,4 +1,5 @@
import * as SecureStore from 'expo-secure-store';
import { Platform } from 'react-native';
const { proxy } = require('valtio');
const BASE_URL_KEY = 'sub2api_base_url';
@@ -67,7 +68,8 @@ export function getDefaultAdminConfig() {
}
async function getItem(key: string) {
if (typeof window !== 'undefined') {
try {
if (Platform.OS === 'web') {
if (typeof localStorage === 'undefined') {
return null;
}
@@ -75,11 +77,15 @@ async function getItem(key: string) {
return localStorage.getItem(key);
}
return SecureStore.getItemAsync(key);
return await SecureStore.getItemAsync(key);
} catch {
return null;
}
}
async function setItem(key: string, value: string) {
if (typeof window !== 'undefined') {
try {
if (Platform.OS === 'web') {
if (typeof localStorage !== 'undefined') {
localStorage.setItem(key, value);
}
@@ -88,10 +94,14 @@ async function setItem(key: string, value: string) {
}
await SecureStore.setItemAsync(key, value);
} catch {
return;
}
}
async function deleteItem(key: string) {
if (typeof window !== 'undefined') {
try {
if (Platform.OS === 'web') {
if (typeof localStorage !== 'undefined') {
localStorage.removeItem(key);
}
@@ -100,6 +110,9 @@ async function deleteItem(key: string) {
}
await SecureStore.deleteItemAsync(key);
} catch {
return;
}
}
export const adminConfigState = proxy({
@@ -112,6 +125,8 @@ export const adminConfigState = proxy({
export async function hydrateAdminConfig() {
const defaults = getDefaultAdminConfig();
try {
const [baseUrl, adminApiKey, rawAccounts, activeAccountId] = await Promise.all([
getItem(BASE_URL_KEY),
getItem(ADMIN_KEY_KEY),
@@ -156,19 +171,21 @@ export async function hydrateAdminConfig() {
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),
]);
} finally {
adminConfigState.hydrated = true;
}
}
export async function saveAdminConfig(input: { baseUrl: string; adminApiKey: string }) {
adminConfigState.saving = true;
try {
const normalized = normalizeConfig(input);
const nextUpdatedAt = new Date().toISOString();
const existingAccount = adminConfigState.accounts.find(
@@ -203,8 +220,10 @@ export async function saveAdminConfig(input: { baseUrl: string; adminApiKey: str
adminConfigState.activeAccountId = nextAccount.id;
adminConfigState.baseUrl = normalized.baseUrl;
adminConfigState.adminApiKey = normalized.adminApiKey;
} finally {
adminConfigState.saving = false;
}
}
export async function switchAdminAccount(accountId: string) {
const account = adminConfigState.accounts.find((item: AdminAccountProfile) => item.id === accountId);

View File

@@ -73,6 +73,30 @@ export type DashboardModelStats = {
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 = {
site_name?: string;
[key: string]: string | number | boolean | null | string[] | undefined;
@@ -88,6 +112,7 @@ export type AdminUser = {
role?: string;
current_concurrency?: number;
notes?: string | null;
last_used_at?: string | null;
created_at?: string;
updated_at?: string;
};