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

@@ -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,95 +53,161 @@ export default function AccountsScreen() {
});
const items = accountsQuery.data?.items ?? [];
const filteredItems = useMemo(() => {
return items.filter((account) => {
if (filter === 'schedulable') return account.schedulable !== false && !getAccountError(account);
if (filter === 'paused') return account.schedulable === false && !getAccountError(account);
if (filter === 'error') return getAccountError(account);
return true;
});
}, [filter, items]);
const errorMessage = accountsQuery.error instanceof Error ? accountsQuery.error.message : '';
const summary = useMemo(() => {
const total = items.length;
const errors = items.filter(getAccountError).length;
const paused = items.filter((item) => item.schedulable === false && !getAccountError(item)).length;
const active = items.filter((item) => item.schedulable !== false && !getAccountError(item)).length;
return { total, active, paused, errors };
}, [items]);
const listHeader = useMemo(
() => (
<View className="pb-4">
<View className="flex-row items-center rounded-[24px] bg-[#fbf8f2] px-4 py-3">
<Search color="#7d7468" size={18} />
<TextInput
defaultValue=""
onChangeText={setSearchText}
placeholder="搜索 key 名称"
placeholderTextColor="#9b9081"
className="ml-3 flex-1 text-base text-[#16181a]"
/>
<View className="rounded-[24px] bg-[#fbf8f2] p-3">
<View className="flex-row items-center rounded-[18px] bg-[#f1ece2] px-4 py-3">
<Search color="#7d7468" size={18} />
<TextInput
defaultValue=""
onChangeText={setSearchText}
placeholder="搜索账号名称 / 平台"
placeholderTextColor="#9b9081"
className="ml-3 flex-1 text-base text-[#16181a]"
/>
</View>
<View className="mt-3 flex-row gap-2">
{([
['all', `全部 ${summary.total}`],
['schedulable', `可调度 ${summary.active}`],
['paused', `暂停 ${summary.paused}`],
['error', `异常 ${summary.errors}`],
] as const).map(([key, label]) => {
const active = filter === key;
return (
<Pressable
key={key}
onPress={() => setFilter(key)}
className={active ? 'rounded-full bg-[#1d5f55] px-3 py-2' : 'rounded-full bg-[#e7dfcf] px-3 py-2'}
>
<Text className={active ? 'text-xs font-semibold text-white' : 'text-xs font-semibold text-[#4e463e]'}>{label}</Text>
</Pressable>
);
})}
</View>
</View>
</View>
),
[]
[filter, summary.active, summary.errors, summary.paused, summary.total]
);
const renderItem = useCallback(
({ item: account }: { item: (typeof items)[number] }) => (
<Pressable
onPress={() => {
void queryClient.prefetchQuery({ queryKey: ['account', account.id], queryFn: () => getAccount(account.id) });
void queryClient.prefetchQuery({ queryKey: ['account-today-stats', account.id], queryFn: () => getAccountTodayStats(account.id) });
void queryClient.prefetchQuery({
queryKey: ['account-trend', account.id, range.start_date, range.end_date],
queryFn: () => getDashboardTrend({ ...range, granularity: 'day', account_id: account.id }),
});
router.push(`/accounts/${account.id}`);
}}
>
<ListCard
title={account.name}
meta={`${account.platform} · ${account.type} · 优先级 ${account.priority ?? 0}`}
badge={account.status || 'unknown'}
icon={KeyRound}
({ item: account }: { item: (typeof filteredItems)[number] }) => {
const isError = getAccountError(account);
const statusText = isError ? '异常' : account.schedulable ? '可调度' : '暂停调度';
const groupsText = account.groups?.map((group) => group.name).filter(Boolean).slice(0, 3).join(' · ');
return (
<Pressable
onPress={() => {
void queryClient.prefetchQuery({ queryKey: ['account', account.id], queryFn: () => getAccount(account.id) });
void queryClient.prefetchQuery({ queryKey: ['account-today-stats', account.id], queryFn: () => getAccountTodayStats(account.id) });
void queryClient.prefetchQuery({
queryKey: ['account-trend', account.id, range.start_date, range.end_date],
queryFn: () => getDashboardTrend({ ...range, granularity: 'day', account_id: account.id }),
});
router.push(`/accounts/${account.id}`);
}}
>
<View className="flex-row items-center justify-between">
<View className="flex-row items-center gap-2">
{account.schedulable ? <ShieldCheck color="#7d7468" size={14} /> : <ShieldOff color="#7d7468" size={14} />}
<Text className="text-sm text-[#7d7468]">{account.schedulable ? '可调度' : '暂停调度'}</Text>
<ListCard
title={account.name}
meta={`${account.platform} · ${account.type} · 优先级 ${account.priority ?? 0}`}
badge={account.status || 'unknown'}
icon={KeyRound}
>
<View className="gap-3">
<View className="flex-row items-center justify-between">
<View className="flex-row items-center gap-2">
{account.schedulable && !isError ? <ShieldCheck color="#7d7468" size={14} /> : <ShieldOff color="#7d7468" size={14} />}
<Text className="text-sm text-[#7d7468]">{statusText}</Text>
</View>
<Text className="text-xs text-[#7d7468]">使 {formatTime(account.last_used_at || account.updated_at)}</Text>
</View>
<View className="flex-row gap-2">
<View className="flex-1 rounded-[14px] bg-[#f1ece2] px-3 py-3">
<Text className="text-[11px] text-[#7d7468]"></Text>
<Text className="mt-1 text-sm font-bold text-[#16181a]">{account.current_concurrency ?? 0} / {account.concurrency ?? 0}</Text>
</View>
<View className="flex-1 rounded-[14px] bg-[#f1ece2] px-3 py-3">
<Text className="text-[11px] text-[#7d7468]"></Text>
<Text className="mt-1 text-sm font-bold text-[#16181a]">{(account.rate_multiplier ?? 1).toFixed(2)}x</Text>
</View>
</View>
{groupsText ? <Text className="text-xs text-[#7d7468]"> {groupsText}</Text> : null}
{account.error_message ? <Text className="text-xs text-[#a4512b]">{account.error_message}</Text> : null}
<View className="flex-row gap-2">
<Pressable
className="rounded-full bg-[#1b1d1f] px-4 py-2"
onPress={(event) => {
event.stopPropagation();
testAccount(account.id).catch(() => undefined);
}}
>
<Text className="text-xs font-semibold uppercase tracking-[1.2px] text-[#f6f1e8]"></Text>
</Pressable>
<Pressable
className="rounded-full bg-[#e7dfcf] px-4 py-2"
onPress={(event) => {
event.stopPropagation();
toggleMutation.mutate({
accountId: account.id,
schedulable: !account.schedulable,
});
}}
>
<Text className="text-xs font-semibold uppercase tracking-[1.2px] text-[#4e463e]">{account.schedulable ? '暂停' : '恢复'}</Text>
</Pressable>
</View>
</View>
<View className="flex-row gap-2">
<Pressable
className="rounded-full bg-[#1b1d1f] px-4 py-2"
onPress={(event) => {
event.stopPropagation();
testAccount(account.id).catch(() => undefined);
}}
>
<Text className="text-xs font-semibold uppercase tracking-[1.2px] text-[#f6f1e8]"></Text>
</Pressable>
<Pressable
className="rounded-full bg-[#e7dfcf] px-4 py-2"
onPress={(event) => {
event.stopPropagation();
toggleMutation.mutate({
accountId: account.id,
schedulable: !account.schedulable,
});
}}
>
<Text className="text-xs font-semibold uppercase tracking-[1.2px] text-[#4e463e]"></Text>
</Pressable>
</View>
</View>
</ListCard>
</Pressable>
),
[queryClient, range.end_date, range.start_date, toggleMutation]
</ListCard>
</Pressable>
);
},
[filteredItems, queryClient, range.end_date, range.start_date, toggleMutation]
);
const emptyState = useMemo(
() => <ListCard title="暂无 Key" meta={errorMessage || '连上后这里会展示 key 列表。'} icon={KeyRound} />,
() => <ListCard title="暂无账号" meta={errorMessage || '连上后这里会展示账号列表。'} icon={KeyRound} />,
[errorMessage]
);
return (
<ScreenShell
title="API 密钥"
subtitle=""
titleAside={<Text className="text-[11px] text-[#a2988a]"></Text>}
title="账号管理"
subtitle="看单账号状态、并发、最近使用和异常信息。"
titleAside={<Text className="text-[11px] text-[#a2988a]"></Text>}
variant="minimal"
scroll={false}
>
<FlatList
data={items}
data={filteredItems}
renderItem={renderItem}
keyExtractor={(item) => `${item.id}`}
showsVerticalScrollIndicator={false}
refreshControl={<RefreshControl refreshing={accountsQuery.isRefetching} onRefresh={() => void accountsQuery.refetch()} tintColor="#1d5f55" />}
ListHeaderComponent={listHeader}
ListEmptyComponent={emptyState}
ItemSeparatorComponent={() => <View className="h-4" />}

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 cards = [
{
key: 'throughput',
node: throughputPoints.length > 1 ? (
<LineTrendChart
title="Token 吞吐"
subtitle="整体负载曲线"
points={throughputPoints}
color="#a34d2d"
formatValue={formatTokenValue}
compact={useMasonry}
/>
) : null,
},
{
key: 'requests',
node: requestPoints.length > 1 ? (
<LineTrendChart
title="请求趋势"
subtitle="调用波峰变化"
points={requestPoints}
color="#1d5f55"
compact={useMasonry}
/>
) : null,
},
{
key: 'cost',
node: costPoints.length > 1 ? (
<LineTrendChart
title="成本趋势"
subtitle="花费变化"
points={costPoints}
color="#7651c8"
formatValue={(value) => `$${value.toFixed(2)}`}
compact={useMasonry}
/>
) : null,
},
{
key: 'token-structure',
node: (
<BarChartCard
title="Token 结构"
subtitle="输入、输出、缓存读占比"
items={[
{
label: '输入 Token',
value: totalInputTokens,
color: '#1d5f55',
hint: '输入 Token 指请求进入模型前消耗的 token通常由提示词、上下文和历史消息组成。',
},
{
label: '输出 Token',
value: totalOutputTokens,
color: '#d38b36',
hint: '输出 Token 指模型返回内容消耗的 token越长通常代表生成内容越多、成本越高。',
},
{
label: '缓存读取 Token',
value: totalCacheReadTokens,
color: '#7d7468',
hint: '缓存读取 Token 表示命中缓存后复用的 token数值越高通常意味着缓存策略更有效。',
},
]}
formatValue={formatTokenValue}
/>
),
},
{
key: 'health',
node: (
<DonutChartCard
title="账号健康"
subtitle="健康、繁忙、暂停、异常"
centerLabel="总账号"
centerValue={String(accounts.length || stats?.total_accounts || 0)}
segments={[
{ label: '健康', value: healthyAccounts, color: '#1d5f55' },
{ label: '繁忙', value: busyAccounts, color: '#d38b36' },
{ label: '暂停', value: pausedAccounts, color: '#7d7468' },
{ label: '异常', value: errorAccounts, color: '#a34d2d' },
]}
/>
),
},
{
key: 'models',
node: (
<BarChartCard
title="热点模型"
subtitle="模型负载分布"
items={topModels.map((item) => ({
label: item.model,
value: item.total_tokens,
color: '#a34d2d',
meta: `请求 ${item.requests} · 成本 $${Number(item.cost).toFixed(2)}`,
}))}
formatValue={formatTokenValue}
/>
),
},
{
key: 'incidents',
node: (
<ListCard title="排障列表" meta="优先关注状态异常或带错误信息的上游账号" icon={Wrench}>
<View className="gap-3">
{incidentAccounts.map((item) => (
<View key={item.id} className="rounded-[18px] bg-[#f1ece2] px-4 py-3">
<Text className="text-sm font-semibold text-[#16181a]">{item.name}</Text>
<Text className="mt-1 text-xs text-[#7d7468]">{item.platform} · {item.status || 'unknown'} · {item.schedulable ? '可调度' : '暂停调度'}</Text>
<Text className="mt-2 text-xs text-[#a34d2d]">{item.error_message || '状态异常,建议从运维视角继续排查这个上游账号'}</Text>
</View>
))}
{incidentAccounts.length === 0 ? <Text className="text-sm text-[#7d7468]"></Text> : null}
</View>
</ListCard>
),
},
].filter((item) => item.node);
const leftColumn = cards.filter((_, index) => index % 2 === 0);
const rightColumn = cards.filter((_, index) => index % 2 === 1);
const isRefreshing = statsQuery.isRefetching || settingsQuery.isRefetching || accountsQuery.isRefetching || trendQuery.isRefetching || modelsQuery.isRefetching;
return (
<ScreenShell
title="概览"
subtitle=""
titleAside={<Text className="text-[11px] text-[#a2988a]">{siteName} </Text>}
variant="minimal"
horizontalInsetClassName="px-3"
contentGapClassName="mt-3 gap-2"
right={
<View className="flex-row items-center gap-2">
<View className="flex-row items-center rounded-full bg-[#ece3d6] p-1">
{RANGE_OPTIONS.map((item) => {
const active = item.key === rangeKey;
return (
<Pressable
key={item.key}
className={active ? 'rounded-full bg-[#1d5f55] px-3 py-1.5' : 'rounded-full bg-transparent px-3 py-1.5'}
onPress={() => setRangeKey(item.key)}
>
<Text className={active ? 'text-[10px] font-semibold uppercase leading-4 tracking-[1px] text-white' : 'text-[10px] font-semibold uppercase leading-4 tracking-[1px] text-[#7d7468]'}>
{item.label}
</Text>
</Pressable>
);
})}
<SafeAreaView style={{ flex: 1, backgroundColor: colors.page }}>
<ScrollView
style={{ flex: 1 }}
contentContainerStyle={{ paddingHorizontal: 16, paddingTop: 16, paddingBottom: 110 }}
showsVerticalScrollIndicator={false}
refreshControl={<RefreshControl refreshing={isRefreshing} onRefresh={() => void refetchAll()} tintColor="#1d5f55" />}
>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12, marginBottom: 16 }}>
<View style={{ flex: 1 }}>
<Text style={{ fontSize: 28, fontWeight: '700', color: colors.text }}></Text>
<Text style={{ marginTop: 6, fontSize: 13, color: '#8a8072' }}>{siteName} </Text>
</View>
<View style={{ alignItems: 'flex-end' }}>
<View style={{ flexDirection: 'row', gap: 8 }}>
{RANGE_OPTIONS.map((option) => {
const active = option.key === rangeKey;
return (
<Pressable
key={option.key}
style={{ backgroundColor: active ? colors.primary : colors.border, borderRadius: 999, paddingHorizontal: 12, paddingVertical: 8 }}
onPress={() => setRangeKey(option.key)}
>
<Text style={{ color: active ? '#fff' : '#4e463e', fontSize: 12, fontWeight: '700' }}>{option.label}</Text>
</Pressable>
);
})}
</View>
<Text style={{ marginTop: 8, fontSize: 12, color: colors.subtext }}>{range.start_date} {range.end_date}</Text>
</View>
<Pressable
className="h-10 w-10 items-center justify-center rounded-full bg-[#2d3134]"
onPress={() => {
statsQuery.refetch();
trendQuery.refetch();
modelsQuery.refetch();
accountsQuery.refetch();
settingsQuery.refetch();
}}
>
<RefreshCw color="#f6f1e8" size={16} />
</Pressable>
</View>
}
>
<View className="gap-2">
{summaryRows.map((row, rowIndex) => (
<View key={`summary-row-${rowIndex}`} className="flex-row gap-2">
{row.map((item) => {
const Icon = item.icon;
return (
<View
key={item.label}
className={item.tone === 'dark' ? 'rounded-[18px] bg-[#1d5f55] px-2.5 py-2.5' : 'rounded-[18px] bg-[#fbf8f2] px-2.5 py-2.5'}
style={{ width: summaryCardWidth }}
>
<View className="flex-row items-center justify-between gap-2">
<Text className={item.tone === 'dark' ? 'text-[10px] uppercase tracking-[1.1px] text-[#d8efe7]' : 'text-[10px] uppercase tracking-[1.1px] text-[#8a8072]'}>
{item.label}
</Text>
<Icon color={item.tone === 'dark' ? '#d8efe7' : '#7d7468'} size={13} />
</View>
<Text className={item.tone === 'dark' ? 'mt-2 text-[17px] font-bold text-white' : 'mt-2 text-[17px] font-bold text-[#16181a]'}>
{item.value}
</Text>
{'detail' in item && item.detail ? (
<Text numberOfLines={1} className={item.tone === 'dark' ? 'mt-1 text-[10px] text-[#d8efe7]' : 'mt-1 text-[10px] text-[#8a8072]'}>
{item.detail}
</Text>
) : null}
{!hasAccount ? (
<Section title="未连接服务器" subtitle="需要先配置连接">
<Text style={{ fontSize: 14, lineHeight: 22, color: colors.subtext }}> Admin Token</Text>
<Pressable style={{ marginTop: 14, alignSelf: 'flex-start', backgroundColor: colors.primary, borderRadius: 14, paddingHorizontal: 16, paddingVertical: 12 }} onPress={() => router.push('/settings')}>
<Text style={{ color: '#fff', fontSize: 13, fontWeight: '700' }}></Text>
</Pressable>
</Section>
) : isLoading ? (
<Section title="正在加载概览" subtitle="请稍候">
<Text style={{ fontSize: 14, lineHeight: 22, color: colors.subtext }}></Text>
</Section>
) : hasError ? (
<Section title="加载失败" subtitle="请检查连接配置">
<View style={{ borderRadius: 14, backgroundColor: colors.dangerBg, paddingHorizontal: 14, paddingVertical: 12 }}>
<Text style={{ color: colors.danger, fontSize: 14, lineHeight: 20 }}>{errorMessage}</Text>
</View>
<View style={{ flexDirection: 'row', gap: 12, marginTop: 14 }}>
<Pressable style={{ flex: 1, backgroundColor: colors.primary, borderRadius: 14, paddingVertical: 12, alignItems: 'center' }} onPress={refetchAll}>
<Text style={{ color: '#fff', fontSize: 13, fontWeight: '700' }}></Text>
</Pressable>
<Pressable style={{ flex: 1, backgroundColor: colors.border, borderRadius: 14, paddingVertical: 12, alignItems: 'center' }} onPress={() => router.push('/settings')}>
<Text style={{ color: '#4e463e', fontSize: 13, fontWeight: '700' }}></Text>
</Pressable>
</View>
</Section>
) : (
<View style={{ gap: 12 }}>
<View style={{ flexDirection: 'row', gap: 12 }}>
<StatCard
title={`${rangeTitle} Token`}
value={formatTokenDisplay(rangeKey === '24h' ? selectedTokenTotal || stats?.today_tokens : selectedTokenTotal)}
detail={`输出 ${formatTokenDisplay(rangeKey === '24h' ? selectedOutputTotal || stats?.today_output_tokens : selectedOutputTotal)}`}
/>
<StatCard
title={`${rangeTitle} 成本`}
value={formatMoney(rangeKey === '24h' ? selectedCostTotal || stats?.today_cost : selectedCostTotal)}
detail={`TPM ${formatNumber(stats?.tpm)}`}
/>
</View>
<Section title="账号概览" subtitle="总数、健康、异常和暂停状态一览">
<View style={{ flexDirection: 'row', gap: 8 }}>
<View style={{ flex: 1, backgroundColor: colors.mutedCard, borderRadius: 14, padding: 12 }}>
<Text style={{ fontSize: 11, color: '#8a8072' }}></Text>
<Text style={{ marginTop: 6, fontSize: 18, fontWeight: '700', color: colors.text }}>{formatNumber(totalAccounts)}</Text>
</View>
);
})}
</View>
))}
</View>
<View style={{ flex: 1, backgroundColor: colors.mutedCard, borderRadius: 14, padding: 12 }}>
<Text style={{ fontSize: 11, color: '#8a8072' }}></Text>
<Text style={{ marginTop: 6, fontSize: 18, fontWeight: '700', color: colors.text }}>{formatNumber(healthyAccounts)}</Text>
</View>
<View style={{ flex: 1, backgroundColor: colors.dangerBg, borderRadius: 14, padding: 12 }}>
<Text style={{ fontSize: 11, color: colors.danger }}></Text>
<Text style={{ marginTop: 6, fontSize: 18, fontWeight: '700', color: colors.danger }}>{formatNumber(errorAccounts)}</Text>
</View>
<View style={{ flex: 1, backgroundColor: colors.mutedCard, borderRadius: 14, padding: 12 }}>
<Text style={{ fontSize: 11, color: '#8a8072' }}></Text>
<Text style={{ marginTop: 6, fontSize: 18, fontWeight: '700', color: colors.text }}>{formatNumber(currentPagePausedAccounts)}</Text>
</View>
</View>
<Text style={{ marginTop: 10, fontSize: 12, color: colors.subtext }}> / / 使</Text>
</Section>
{throughputPoints.length > 1 ? (
<LineTrendChart title="Token 吞吐" subtitle="当前时间范围内的 Token 变化趋势" points={throughputPoints} color="#a34d2d" formatValue={formatTokenDisplay} />
) : null}
{requestPoints.length > 1 ? (
<LineTrendChart title="请求趋势" subtitle="当前时间范围内的请求变化趋势" points={requestPoints} color="#1d5f55" formatValue={formatCompactNumber} />
) : null}
{costPoints.length > 1 ? (
<LineTrendChart title="成本趋势" subtitle="当前时间范围内的成本变化趋势" points={costPoints} color="#7651c8" formatValue={formatMoney} />
) : null}
<BarChartCard
title="Token 结构"
subtitle="输入、输出、缓存读取占比"
items={[
{ label: '输入 Token', value: totalInputTokens, color: '#1d5f55', hint: '请求进入模型前消耗的 token。' },
{ label: '输出 Token', value: totalOutputTokens, color: '#d38b36', hint: '模型返回内容消耗的 token。' },
{ label: '缓存读取 Token', value: totalCacheReadTokens, color: '#7d7468', hint: '命中缓存后复用的 token。' },
]}
formatValue={formatTokenDisplay}
/>
<DonutChartCard
title="账号健康"
subtitle="健康、繁忙、暂停、异常分布"
centerLabel="总账号"
centerValue={formatNumber(totalAccounts)}
segments={[
{ label: '健康', value: healthyAccounts, color: '#1d5f55' },
{ label: '繁忙', value: currentPageBusyAccounts, color: '#d38b36' },
{ label: '暂停', value: currentPagePausedAccounts, color: '#7d7468' },
{ label: '异常', value: errorAccounts, color: '#a34d2d' },
]}
/>
<BarChartCard
title="热点模型"
subtitle="当前时间范围内最活跃的模型"
items={topModels.map((model) => ({
label: model.model,
value: model.total_tokens,
color: '#a34d2d',
meta: `请求 ${formatNumber(model.requests)} · 成本 ${formatMoney(model.cost)}`,
}))}
formatValue={formatCompactNumber}
/>
<Section title="趋势摘要" subtitle="图表 + 最近几个统计点的请求、Token 和成本变化">
{latestTrendPoints.length === 0 ? (
<Text style={{ fontSize: 14, color: colors.subtext }}></Text>
) : (
<View style={{ gap: 12 }}>
{throughputPoints.length > 1 ? (
<LineTrendChart
title="摘要 Token 趋势"
subtitle="最近统计点的 Token 变化"
points={throughputPoints.slice(-6)}
color="#a34d2d"
formatValue={formatTokenDisplay}
compact
/>
) : null}
<View style={{ gap: 10 }}>
{latestTrendPoints.map((point) => (
<View key={point.date} style={{ backgroundColor: colors.mutedCard, borderRadius: 14, padding: 12 }}>
<Text style={{ fontSize: 13, fontWeight: '700', color: colors.text }}>{point.date}</Text>
<View style={{ flexDirection: 'row', gap: 12, marginTop: 8 }}>
<View style={{ flex: 1 }}>
<Text style={{ fontSize: 11, color: '#8a8072' }}></Text>
<Text style={{ marginTop: 4, fontSize: 15, fontWeight: '700', color: colors.text }}>{formatCompactNumber(point.requests)}</Text>
</View>
<View style={{ flex: 1 }}>
<Text style={{ fontSize: 11, color: '#8a8072' }}>Token</Text>
<Text style={{ marginTop: 4, fontSize: 15, fontWeight: '700', color: colors.text }}>{formatTokenDisplay(point.total_tokens)}</Text>
</View>
<View style={{ flex: 1 }}>
<Text style={{ fontSize: 11, color: '#8a8072' }}></Text>
<Text style={{ marginTop: 4, fontSize: 15, fontWeight: '700', color: colors.text }}>{formatMoney(point.cost)}</Text>
</View>
</View>
</View>
))}
</View>
</View>
)}
</Section>
{useMasonry ? (
<View className="flex-row items-start gap-3">
<View className="flex-1 gap-3">
{leftColumn.map((item) => (
<View key={item.key}>{item.node}</View>
))}
</View>
<View className="flex-1 gap-3">
{rightColumn.map((item) => (
<View key={item.key}>{item.node}</View>
))}
</View>
</View>
) : (
cards.map((item) => <View key={item.key}>{item.node}</View>)
)}
</ScreenShell>
)}
</ScrollView>
</SafeAreaView>
);
}

View File

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

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)]);
const users = useMemo(() => {
const items = [...(usersQuery.data?.items ?? [])];
items.sort((left, right) => {
const value = getTimeValue(left) - getTimeValue(right);
return sortOrder === 'desc' ? -value : value;
});
return items;
}, [sortOrder, usersQuery.data?.items]);
return {
usage,
apiKeys: apiKeysData.items ?? [],
} satisfies UserSupplement;
},
enabled: hasAccount,
staleTime: 60_000,
})),
});
const errorMessage = usersQuery.error instanceof Error ? usersQuery.error.message : '';
const supplementsByUserId = useMemo(
() =>
items.reduce<Record<number, UserSupplement | undefined>>((result, user, index) => {
result[user.id] = userDetailQueries[index]?.data;
return result;
}, {}),
[items, userDetailQueries]
);
const sortedItems = useMemo(
() =>
[...items].sort((left, right) => {
const delta = getUserSortValue(right) - getUserSortValue(left);
return sortOrder === 'desc' ? delta : -delta;
}),
[items, sortOrder]
);
async function copyKey(keyId: number, value: string) {
await Clipboard.setStringAsync(value);
setCopiedKeyId(keyId);
setTimeout(() => setCopiedKeyId((current) => (current === keyId ? null : current)), 1600);
}
const renderItem = useCallback(
({ item: user }: { item: (typeof sortedItems)[number] }) => {
const keyItems = (supplementsByUserId[user.id]?.apiKeys ?? []).slice(0, 3);
return (
<Pressable
className="px-1"
onPress={() => {
void queryClient.prefetchQuery({ queryKey: ['user', user.id], queryFn: () => getUser(user.id) });
void queryClient.prefetchQuery({ queryKey: ['user-usage', user.id], queryFn: () => getUserUsage(user.id) });
void queryClient.prefetchQuery({ queryKey: ['user-api-keys', user.id], queryFn: () => listUserApiKeys(user.id) });
router.push(`/users/${user.id}`);
}}
>
<ListCard title={getUserTitle(user)} meta={user.email} badge={user.status || 'active'} icon={UserRound}>
<View className="gap-2">
<View className="rounded-[14px] bg-[#f7f2e9] px-3 py-2.5">
<View className="flex-row items-center justify-between">
<Text className="text-[11px] text-[#6f665c]"></Text>
<Text className="text-sm font-semibold text-[#16181a]">${Number(user.balance ?? 0).toFixed(2)}</Text>
</View>
</View>
<View className="rounded-[14px] bg-[#f7f2e9] px-3 py-2">
<View className="mb-1.5 flex-row items-center justify-between">
<Text className="text-[11px] text-[#6f665c]">Keys</Text>
<Text className="text-[10px] text-[#8a8072]">{keyItems.length} </Text>
</View>
<View className="gap-0">
{keyItems.map((apiKey, index) => (
<View
key={apiKey.id}
style={{ paddingVertical: 4 }}
>
{(() => {
const quota = Number(apiKey.quota ?? 0);
const used = Number(apiKey.quota_used ?? 0);
const isUnlimited = quota <= 0;
const progressWidth = isUnlimited ? '16%' : (`${Math.max(Math.min((used / quota) * 100, 100), 6)}%` as `${number}%`);
return (
<>
<View className="flex-row items-center gap-2">
<Text numberOfLines={1} className="flex-1 text-[11px] font-semibold text-[#16181a]">
{apiKey.name}
</Text>
<Text numberOfLines={1} className="text-[10px] text-[#6f665c]">
{isUnlimited ? `${formatQuotaValue(used)} / 无限` : `${formatQuotaValue(used)} / ${formatQuotaValue(quota)}`}
</Text>
<Pressable
className="rounded-full bg-[#e7dfcf] p-1.5"
onPress={(event) => {
event.stopPropagation();
void copyKey(apiKey.id, apiKey.key);
}}
>
<Copy color="#4e463e" size={11} />
</Pressable>
</View>
<View className="h-1.5 overflow-hidden rounded-full bg-[#ddd2c0]" style={{ marginTop: 3 }}>
<View
className={
isUnlimited
? 'h-full rounded-full bg-[#7d7468]'
: used / Math.max(quota, 1) >= 0.85
? 'h-full rounded-full bg-[#c25d35]'
: used / Math.max(quota, 1) >= 0.6
? 'h-full rounded-full bg-[#d38b36]'
: 'h-full rounded-full bg-[#1d5f55]'
}
style={{ width: progressWidth }}
/>
</View>
{copiedKeyId === apiKey.id ? <Text className="text-[10px] text-[#1d5f55]" style={{ paddingTop: 3 }}></Text> : null}
</>
);
})()}
</View>
))}
{keyItems.length === 0 ? (
<View className="py-[10px]">
<Text className="text-[11px] text-[#6f665c]"> token </Text>
</View>
) : null}
</View>
</View>
</View>
</ListCard>
</Pressable>
);
},
[copiedKeyId, queryClient, sortedItems, supplementsByUserId]
);
const emptyState = useMemo(
() => (
<ListCard
title={hasAccount ? '暂无匹配用户' : '未连接服务器'}
meta={hasAccount ? errorMessage || '调整搜索词后再试。' : '请先前往服务器标签连接 Sub2API。'}
icon={UserRound}
/>
),
[errorMessage, hasAccount]
);
const errorMessage = getErrorMessage(usersQuery.error);
return (
<ScreenShell
title="用户管理"
subtitle=""
titleAside={<Text className="text-[11px] text-[#a2988a]"> {sortedItems.length}</Text>}
variant="minimal"
scroll={false}
bottomInsetClassName="pb-12"
>
<View className="flex-1">
<View className="rounded-[16px] bg-[#fbf8f2] px-2.5 py-2.5">
<View className="flex-row items-center gap-2">
<View className="flex-1 flex-row items-center rounded-[14px] bg-[#f1ece2] px-3 py-2.5">
<Search color="#7d7468" size={18} />
<TextInput
value={searchText}
onChangeText={setSearchText}
placeholder="搜索邮箱或用户名"
placeholderTextColor="#9b9081"
className="ml-3 flex-1 text-base text-[#16181a]"
/>
</View>
<Pressable
className={sortOrder === 'desc' ? 'rounded-[14px] bg-[#1d5f55] px-3 py-2.5' : 'rounded-[14px] bg-[#e7dfcf] px-3 py-2.5'}
onPress={() => setSortOrder('desc')}
>
<Text className={sortOrder === 'desc' ? 'text-[11px] font-semibold text-white' : 'text-[11px] font-semibold text-[#4e463e]'}>
</Text>
</Pressable>
<Pressable
className={sortOrder === 'asc' ? 'rounded-[14px] bg-[#1d5f55] px-3 py-2.5' : 'rounded-[14px] bg-[#e7dfcf] px-3 py-2.5'}
onPress={() => setSortOrder('asc')}
>
<Text className={sortOrder === 'asc' ? 'text-[11px] font-semibold text-white' : 'text-[11px] font-semibold text-[#4e463e]'}>
</Text>
</Pressable>
</View>
<SafeAreaView style={{ flex: 1, backgroundColor: colors.page }}>
<View style={{ flex: 1, paddingHorizontal: 16, paddingTop: 14 }}>
<View style={{ marginBottom: 10 }}>
<Text style={{ fontSize: 28, fontWeight: '700', color: colors.text }}></Text>
<Text style={{ marginTop: 4, fontSize: 12, color: '#8a8072' }}></Text>
</View>
<View className="mt-2.5 flex-1">
<View style={{ flexDirection: 'row', gap: 10, alignItems: 'center' }}>
<View style={{ flex: 1, backgroundColor: colors.card, borderRadius: 16, padding: 10 }}>
<TextInput
value={searchText}
onChangeText={setSearchText}
placeholder="搜索邮箱、用户名或备注"
placeholderTextColor="#9b9081"
style={{ backgroundColor: colors.mutedCard, borderRadius: 14, paddingHorizontal: 14, paddingVertical: 11, fontSize: 15, color: colors.text }}
/>
</View>
<Pressable
onPress={() => setSortOrder((value) => (value === 'desc' ? 'asc' : 'desc'))}
style={{ backgroundColor: colors.card, borderRadius: 16, paddingHorizontal: 14, paddingVertical: 14, minWidth: 92, alignItems: 'center' }}
>
<Text style={{ fontSize: 11, color: colors.subtext }}></Text>
<Text style={{ marginTop: 4, fontSize: 13, fontWeight: '700', color: colors.text }}>{sortOrder === 'desc' ? '倒序' : '正序'}</Text>
</Pressable>
</View>
{!hasAccount ? (
<View style={{ marginTop: 10, backgroundColor: colors.card, borderRadius: 18, padding: 16 }}>
<Text style={{ fontSize: 18, fontWeight: '700', color: colors.text }}></Text>
<Text style={{ marginTop: 8, fontSize: 14, lineHeight: 22, color: colors.subtext }}></Text>
<Pressable
style={{ marginTop: 14, alignSelf: 'flex-start', backgroundColor: colors.primary, borderRadius: 14, paddingHorizontal: 16, paddingVertical: 12 }}
onPress={() => router.push('/settings')}
>
<Text style={{ color: '#fff', fontSize: 13, fontWeight: '700' }}></Text>
</Pressable>
</View>
) : usersQuery.isLoading ? (
<View style={{ marginTop: 10, backgroundColor: colors.card, borderRadius: 18, padding: 16 }}>
<Text style={{ fontSize: 18, fontWeight: '700', color: colors.text }}></Text>
<Text style={{ marginTop: 8, fontSize: 14, lineHeight: 22, color: colors.subtext }}></Text>
</View>
) : usersQuery.error ? (
<View style={{ marginTop: 10, backgroundColor: colors.card, borderRadius: 18, padding: 16 }}>
<Text style={{ fontSize: 18, fontWeight: '700', color: colors.text }}></Text>
<View style={{ marginTop: 12, borderRadius: 14, backgroundColor: colors.dangerBg, paddingHorizontal: 14, paddingVertical: 12 }}>
<Text style={{ color: colors.danger, fontSize: 14, lineHeight: 20 }}>{errorMessage}</Text>
</View>
</View>
) : (
<FlatList
data={sortedItems}
renderItem={renderItem}
style={{ marginTop: 10, flex: 1 }}
data={users}
keyExtractor={(item) => `${item.id}`}
showsVerticalScrollIndicator={false}
ListHeaderComponent={() => <View className="h-2" />}
ListEmptyComponent={emptyState}
ListFooterComponent={() => <View className="h-4" />}
ItemSeparatorComponent={() => <View className="h-3" />}
keyboardShouldPersistTaps="handled"
removeClippedSubviews
initialNumToRender={8}
maxToRenderPerBatch={8}
windowSize={5}
refreshControl={<RefreshControl refreshing={usersQuery.isRefetching} onRefresh={() => void usersQuery.refetch()} tintColor="#1d5f55" />}
contentContainerStyle={{ paddingBottom: 8, gap: 12, flexGrow: users.length === 0 ? 1 : 0 }}
ListEmptyComponent={
<View style={{ backgroundColor: colors.card, borderRadius: 18, padding: 16 }}>
<Text style={{ fontSize: 18, fontWeight: '700', color: colors.text }}></Text>
<Text style={{ marginTop: 8, fontSize: 14, lineHeight: 22, color: colors.subtext }}></Text>
</View>
}
renderItem={({ item }) => (
<Pressable
onPress={() => {
void queryClient.prefetchQuery({ queryKey: ['user', item.id], queryFn: () => getUser(item.id) });
void queryClient.prefetchQuery({ queryKey: ['user-api-keys', item.id], queryFn: () => listUserApiKeys(item.id) });
router.push(`/users/${item.id}`);
}}
>
<UserCard user={item} />
</Pressable>
)}
/>
</View>
)}
</View>
</ScreenShell>
</SafeAreaView>
);
}