feat: refine admin UI and add EAS release workflow
50
.github/workflows/eas-build.yml
vendored
Normal file
@@ -0,0 +1,50 @@
|
||||
name: EAS Build
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
profile:
|
||||
description: EAS build profile
|
||||
required: true
|
||||
default: preview
|
||||
type: choice
|
||||
options:
|
||||
- preview
|
||||
- production
|
||||
platform:
|
||||
description: Target platform
|
||||
required: true
|
||||
default: android
|
||||
type: choice
|
||||
options:
|
||||
- android
|
||||
- ios
|
||||
- all
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
|
||||
- name: Setup Expo and EAS
|
||||
uses: expo/expo-github-action@v8
|
||||
with:
|
||||
eas-version: latest
|
||||
token: ${{ secrets.EXPO_TOKEN }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Trigger EAS build
|
||||
run: npx eas build --non-interactive --profile "${{ inputs.profile }}" --platform "${{ inputs.platform }}"
|
||||
33
app.json
@@ -1,34 +1,49 @@
|
||||
{
|
||||
"expo": {
|
||||
"name": "x-sapi-mobile",
|
||||
"slug": "x-sapi-mobile",
|
||||
"name": "sub2api-mobile",
|
||||
"slug": "sub2api-mobile",
|
||||
"owner": "ckken",
|
||||
"version": "1.0.0",
|
||||
"orientation": "portrait",
|
||||
"icon": "./assets/icon.png",
|
||||
"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",
|
||||
"backgroundColor": "#ffffff"
|
||||
},
|
||||
"ios": {
|
||||
"supportsTablet": true
|
||||
"supportsTablet": true,
|
||||
"icon": "./icons/ios/AppIcon.appiconset/icon-1024.png",
|
||||
"bundleIdentifier": "com.ppx.sub2apimobile"
|
||||
},
|
||||
"android": {
|
||||
"icon": "./icons/android/playstore-icon.png",
|
||||
"package": "com.ppx.sub2apimobile",
|
||||
"adaptiveIcon": {
|
||||
"backgroundColor": "#E6F4FE",
|
||||
"foregroundImage": "./assets/android-icon-foreground.png",
|
||||
"backgroundImage": "./assets/android-icon-background.png",
|
||||
"monochromeImage": "./assets/android-icon-monochrome.png"
|
||||
"foregroundImage": "./icons/android/playstore-icon.png"
|
||||
},
|
||||
"predictiveBackGestureEnabled": false
|
||||
},
|
||||
"web": {
|
||||
"favicon": "./assets/favicon.png"
|
||||
"favicon": "./icons/ios/AppIcon.appiconset/icon-1024.png"
|
||||
},
|
||||
"plugins": [
|
||||
"expo-router",
|
||||
"expo-secure-store"
|
||||
]
|
||||
],
|
||||
"extra": {
|
||||
"router": {},
|
||||
"eas": {
|
||||
"projectId": "acaedd05-5a2a-4843-a648-e025c08ce7b3"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
import { Tabs } from 'expo-router';
|
||||
import { ActivitySquare, ChartNoAxesCombined, Users } from 'lucide-react-native';
|
||||
import { ChartNoAxesCombined, Settings2, Users } from 'lucide-react-native';
|
||||
|
||||
import { adminConfigState } from '@/src/store/admin-config';
|
||||
|
||||
const { useSnapshot } = require('valtio/react');
|
||||
|
||||
export default function TabsLayout() {
|
||||
const config = useSnapshot(adminConfigState);
|
||||
const hasAccount = Boolean(config.baseUrl.trim());
|
||||
|
||||
return (
|
||||
<Tabs
|
||||
initialRouteName={hasAccount ? 'monitor' : 'settings'}
|
||||
screenOptions={{
|
||||
headerShown: false,
|
||||
tabBarActiveTintColor: '#1d5f55',
|
||||
@@ -19,6 +27,12 @@ export default function TabsLayout() {
|
||||
>
|
||||
<Tabs.Screen
|
||||
name="index"
|
||||
options={{
|
||||
href: null,
|
||||
}}
|
||||
/>
|
||||
<Tabs.Screen
|
||||
name="monitor"
|
||||
options={{
|
||||
title: '概览',
|
||||
tabBarIcon: ({ color, size }) => <ChartNoAxesCombined color={color} size={size} />,
|
||||
@@ -32,13 +46,12 @@ export default function TabsLayout() {
|
||||
}}
|
||||
/>
|
||||
<Tabs.Screen
|
||||
name="monitor"
|
||||
name="settings"
|
||||
options={{
|
||||
title: '运维监控',
|
||||
tabBarIcon: ({ color, size }) => <ActivitySquare color={color} size={size} />,
|
||||
title: '服务器',
|
||||
tabBarIcon: ({ color, size }) => <Settings2 color={color} size={size} />,
|
||||
}}
|
||||
/>
|
||||
<Tabs.Screen name="settings" options={{ href: null }} />
|
||||
<Tabs.Screen name="groups" options={{ href: null }} />
|
||||
<Tabs.Screen name="keys" options={{ href: null }} />
|
||||
<Tabs.Screen name="accounts" options={{ href: null }} />
|
||||
|
||||
@@ -1,17 +1,32 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { KeyRound, Search, ShieldCheck, ShieldOff } from 'lucide-react-native';
|
||||
import { router } from 'expo-router';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Pressable, Text, TextInput, View } from 'react-native';
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { FlatList, Pressable, Text, TextInput, View } from 'react-native';
|
||||
|
||||
import { ListCard } from '@/src/components/list-card';
|
||||
import { ScreenShell } from '@/src/components/screen-shell';
|
||||
import { listAccounts, setAccountSchedulable, testAccount } from '@/src/services/admin';
|
||||
import { useDebouncedValue } from '@/src/hooks/use-debounced-value';
|
||||
import { getAccount, getAccountTodayStats, getDashboardTrend, listAccounts, setAccountSchedulable, testAccount } from '@/src/services/admin';
|
||||
|
||||
function getDateRange() {
|
||||
const end = new Date();
|
||||
const start = new Date();
|
||||
start.setDate(end.getDate() - 6);
|
||||
|
||||
const toDate = (value: Date) => value.toISOString().slice(0, 10);
|
||||
|
||||
return {
|
||||
start_date: toDate(start),
|
||||
end_date: toDate(end),
|
||||
};
|
||||
}
|
||||
|
||||
export default function AccountsScreen() {
|
||||
const [search, setSearch] = useState('');
|
||||
const keyword = useMemo(() => search.trim(), [search]);
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const keyword = useDebouncedValue(searchText.trim(), 300);
|
||||
const queryClient = useQueryClient();
|
||||
const range = getDateRange();
|
||||
|
||||
const accountsQuery = useQuery({
|
||||
queryKey: ['accounts', keyword],
|
||||
@@ -26,25 +41,36 @@ export default function AccountsScreen() {
|
||||
|
||||
const items = accountsQuery.data?.items ?? [];
|
||||
const errorMessage = accountsQuery.error instanceof Error ? accountsQuery.error.message : '';
|
||||
|
||||
return (
|
||||
<ScreenShell title="API 密钥" subtitle="管理您的 API 密钥和访问令牌">
|
||||
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
|
||||
value={search}
|
||||
onChangeText={setSearch}
|
||||
defaultValue=""
|
||||
onChangeText={setSearchText}
|
||||
placeholder="搜索 key 名称"
|
||||
placeholderTextColor="#9b9081"
|
||||
className="ml-3 flex-1 text-base text-[#16181a]"
|
||||
/>
|
||||
</View>
|
||||
|
||||
{items.length === 0 ? (
|
||||
<ListCard title="暂无 Key" meta={errorMessage || '连上后这里会展示 key 列表。'} icon={KeyRound} />
|
||||
) : (
|
||||
items.map((account) => (
|
||||
<Pressable key={account.id} onPress={() => router.push(`/accounts/${account.id}`)}>
|
||||
</View>
|
||||
),
|
||||
[]
|
||||
);
|
||||
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}`}
|
||||
@@ -82,8 +108,36 @@ export default function AccountsScreen() {
|
||||
</View>
|
||||
</ListCard>
|
||||
</Pressable>
|
||||
))
|
||||
)}
|
||||
),
|
||||
[queryClient, range.end_date, range.start_date, toggleMutation]
|
||||
);
|
||||
const emptyState = useMemo(
|
||||
() => <ListCard title="暂无 Key" meta={errorMessage || '连上后这里会展示 key 列表。'} icon={KeyRound} />,
|
||||
[errorMessage]
|
||||
);
|
||||
|
||||
return (
|
||||
<ScreenShell
|
||||
title="API 密钥"
|
||||
subtitle=""
|
||||
titleAside={<Text className="text-[11px] text-[#a2988a]">查看密钥状态与调度能力。</Text>}
|
||||
variant="minimal"
|
||||
scroll={false}
|
||||
>
|
||||
<FlatList
|
||||
data={items}
|
||||
renderItem={renderItem}
|
||||
keyExtractor={(item) => `${item.id}`}
|
||||
showsVerticalScrollIndicator={false}
|
||||
ListHeaderComponent={listHeader}
|
||||
ListEmptyComponent={emptyState}
|
||||
ItemSeparatorComponent={() => <View className="h-4" />}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
removeClippedSubviews
|
||||
initialNumToRender={8}
|
||||
maxToRenderPerBatch={8}
|
||||
windowSize={5}
|
||||
/>
|
||||
</ScreenShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { FolderKanban, Layers3, Search } from 'lucide-react-native';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Text, TextInput, View } from 'react-native';
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { FlatList, 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 { listGroups } from '@/src/services/admin';
|
||||
|
||||
export default function GroupsScreen() {
|
||||
const [search, setSearch] = useState('');
|
||||
const keyword = useMemo(() => search.trim(), [search]);
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const keyword = useDebouncedValue(searchText.trim(), 300);
|
||||
|
||||
const groupsQuery = useQuery({
|
||||
queryKey: ['groups', keyword],
|
||||
@@ -18,26 +19,26 @@ export default function GroupsScreen() {
|
||||
|
||||
const items = groupsQuery.data?.items ?? [];
|
||||
const errorMessage = groupsQuery.error instanceof Error ? groupsQuery.error.message : '';
|
||||
|
||||
return (
|
||||
<ScreenShell title="分组管理" subtitle="分组决定调度、价格倍率和账号归属,是后台的核心配置之一。">
|
||||
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
|
||||
value={search}
|
||||
onChangeText={setSearch}
|
||||
defaultValue=""
|
||||
onChangeText={setSearchText}
|
||||
placeholder="搜索分组名称"
|
||||
placeholderTextColor="#9b9081"
|
||||
className="ml-3 flex-1 text-base text-[#16181a]"
|
||||
/>
|
||||
</View>
|
||||
|
||||
{items.length === 0 ? (
|
||||
<ListCard title="暂无分组" meta={errorMessage || '连上 Sub2API 后,这里会展示分组列表。'} icon={FolderKanban} />
|
||||
) : (
|
||||
items.map((group) => (
|
||||
</View>
|
||||
),
|
||||
[]
|
||||
);
|
||||
const renderItem = useCallback(
|
||||
({ item: group }: { item: (typeof items)[number] }) => (
|
||||
<ListCard
|
||||
key={group.id}
|
||||
title={group.name}
|
||||
meta={`${group.platform} · 倍率 ${group.rate_multiplier ?? 1} · ${group.subscription_type || 'standard'}`}
|
||||
badge={group.status || 'active'}
|
||||
@@ -50,8 +51,36 @@ export default function GroupsScreen() {
|
||||
</Text>
|
||||
</View>
|
||||
</ListCard>
|
||||
))
|
||||
)}
|
||||
),
|
||||
[]
|
||||
);
|
||||
const emptyState = useMemo(
|
||||
() => <ListCard title="暂无分组" meta={errorMessage || '连上 Sub2API 后,这里会展示分组列表。'} icon={FolderKanban} />,
|
||||
[errorMessage]
|
||||
);
|
||||
|
||||
return (
|
||||
<ScreenShell
|
||||
title="分组管理"
|
||||
subtitle=""
|
||||
titleAside={<Text className="text-[11px] text-[#a2988a]">查看分组与调度归属。</Text>}
|
||||
variant="minimal"
|
||||
scroll={false}
|
||||
>
|
||||
<FlatList
|
||||
data={items}
|
||||
renderItem={renderItem}
|
||||
keyExtractor={(item) => `${item.id}`}
|
||||
showsVerticalScrollIndicator={false}
|
||||
ListHeaderComponent={listHeader}
|
||||
ListEmptyComponent={emptyState}
|
||||
ItemSeparatorComponent={() => <View className="h-4" />}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
removeClippedSubviews
|
||||
initialNumToRender={8}
|
||||
maxToRenderPerBatch={8}
|
||||
windowSize={5}
|
||||
/>
|
||||
</ScreenShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,101 +1,5 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Activity, Coins, RefreshCw, Rows3, Zap } from 'lucide-react-native';
|
||||
import { Pressable, Text, View } from 'react-native';
|
||||
import { Redirect } from 'expo-router';
|
||||
|
||||
import { LineTrendChart } from '@/src/components/line-trend-chart';
|
||||
import { ScreenShell } from '@/src/components/screen-shell';
|
||||
import { StatCard } from '@/src/components/stat-card';
|
||||
import { getAdminSettings, getDashboardStats, getDashboardTrend } from '@/src/services/admin';
|
||||
|
||||
function getDateRange() {
|
||||
const end = new Date();
|
||||
const start = new Date();
|
||||
start.setDate(end.getDate() - 6);
|
||||
|
||||
const toDate = (value: Date) => value.toISOString().slice(0, 10);
|
||||
|
||||
return {
|
||||
start_date: toDate(start),
|
||||
end_date: toDate(end),
|
||||
};
|
||||
}
|
||||
|
||||
export default function DashboardScreen() {
|
||||
const range = getDateRange();
|
||||
|
||||
const statsQuery = useQuery({
|
||||
queryKey: ['dashboard-stats'],
|
||||
queryFn: getDashboardStats,
|
||||
});
|
||||
|
||||
const trendQuery = useQuery({
|
||||
queryKey: ['dashboard-trend', range.start_date, range.end_date],
|
||||
queryFn: () => getDashboardTrend({ ...range, granularity: 'day' }),
|
||||
});
|
||||
|
||||
const settingsQuery = useQuery({
|
||||
queryKey: ['admin-settings'],
|
||||
queryFn: getAdminSettings,
|
||||
});
|
||||
|
||||
const stats = statsQuery.data;
|
||||
const errorMessage = statsQuery.error instanceof Error ? statsQuery.error.message : '';
|
||||
const siteName = settingsQuery.data?.site_name?.trim() || '管理控制台';
|
||||
const trendPoints = (trendQuery.data?.trend ?? []).map((item) => ({
|
||||
label: item.date.slice(5),
|
||||
value: item.total_tokens,
|
||||
}));
|
||||
|
||||
return (
|
||||
<ScreenShell
|
||||
title={siteName}
|
||||
subtitle="把最常看的管理指标和关键动作先搬到手机里,方便随时巡检。"
|
||||
right={
|
||||
<Pressable
|
||||
className="h-11 w-11 items-center justify-center rounded-full bg-[#2d3134]"
|
||||
onPress={() => {
|
||||
statsQuery.refetch();
|
||||
trendQuery.refetch();
|
||||
}}
|
||||
>
|
||||
<RefreshCw color="#f6f1e8" size={18} />
|
||||
</Pressable>
|
||||
}
|
||||
>
|
||||
<View className="flex-row gap-4">
|
||||
<View className="flex-1">
|
||||
<StatCard label="今日 Token" value={stats ? `${Math.round((stats.today_tokens ?? 0) / 1000)}k` : '--'} tone="dark" trend="up" icon={Zap} />
|
||||
</View>
|
||||
<View className="flex-1">
|
||||
<StatCard label="今日成本" value={stats ? `$${Number(stats.today_cost ?? 0).toFixed(2)}` : '--'} icon={Coins} />
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View className="flex-row gap-4">
|
||||
<View className="flex-1">
|
||||
<StatCard label="输出 Token" value={stats ? `${Math.round((stats.today_output_tokens ?? 0) / 1000)}k` : '--'} trend="up" icon={Rows3} />
|
||||
</View>
|
||||
<View className="flex-1">
|
||||
<StatCard label="吞吐 TPM" value={String(stats?.tpm ?? '--')} icon={Activity} />
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{trendPoints.length > 1 ? (
|
||||
<LineTrendChart
|
||||
title="近 7 天 Token 趋势"
|
||||
subtitle="聚焦 token 消耗,而不是大 banner"
|
||||
points={trendPoints}
|
||||
formatValue={(value) => `${Math.round(value / 1000)}k`}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<View className="rounded-[24px] border border-[#e6dece] bg-[#fbf8f2] p-4">
|
||||
<Text className="text-sm leading-6 text-[#7d7468]">
|
||||
{stats
|
||||
? `今日请求 ${stats.today_requests} · 活跃用户 ${stats.active_users} · 总账号 ${stats.total_accounts}`
|
||||
: errorMessage || '正在等待代理或后台连接。'}
|
||||
</Text>
|
||||
</View>
|
||||
</ScreenShell>
|
||||
);
|
||||
export default function IndexScreen() {
|
||||
return <Redirect href="/monitor" />;
|
||||
}
|
||||
|
||||
@@ -1,93 +1,277 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { AlertTriangle, Gauge, Layers3, Wrench } from 'lucide-react-native';
|
||||
import { Text, View } from 'react-native';
|
||||
import { AlertTriangle, Coins, Gauge, RefreshCw, Rows3, Wrench, Zap } from 'lucide-react-native';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Platform, Pressable, Text, View, useWindowDimensions } from 'react-native';
|
||||
|
||||
import { BarChartCard } from '@/src/components/bar-chart-card';
|
||||
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 { StatCard } from '@/src/components/stat-card';
|
||||
import { getDashboardModels, getDashboardStats, getDashboardTrend, listAccounts } from '@/src/services/admin';
|
||||
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';
|
||||
|
||||
function getDateRange() {
|
||||
const { useSnapshot } = require('valtio/react');
|
||||
|
||||
type RangeKey = '24h' | '7d' | '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),
|
||||
};
|
||||
}
|
||||
|
||||
const RANGE_OPTIONS: Array<{ key: RangeKey; label: string }> = [
|
||||
{ key: '24h', label: '24H' },
|
||||
{ key: '7d', label: '7D' },
|
||||
{ key: '30d', label: '30D' },
|
||||
];
|
||||
|
||||
function getPointLabel(value: string, rangeKey: RangeKey) {
|
||||
if (rangeKey === '24h') {
|
||||
return value.slice(11, 13);
|
||||
}
|
||||
|
||||
return value.slice(5, 10);
|
||||
}
|
||||
|
||||
export default function MonitorScreen() {
|
||||
const range = getDateRange();
|
||||
useScreenInteractive('monitor_interactive');
|
||||
const config = useSnapshot(adminConfigState);
|
||||
const { width } = useWindowDimensions();
|
||||
const contentWidth = Math.max(width - 24, 280);
|
||||
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 trendQuery = useQuery({
|
||||
queryKey: ['monitor-trend', range.start_date, range.end_date],
|
||||
queryFn: () => getDashboardTrend({ ...range, granularity: 'day' }),
|
||||
queryKey: ['monitor-trend', rangeKey, range.start_date, range.end_date, range.granularity],
|
||||
queryFn: () => getDashboardTrend(range),
|
||||
enabled: hasAccount,
|
||||
});
|
||||
|
||||
const modelsQuery = useQuery({
|
||||
queryKey: ['monitor-models', range.start_date, range.end_date],
|
||||
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,
|
||||
});
|
||||
|
||||
const stats = statsQuery.data;
|
||||
const trendPoints = (trendQuery.data?.trend ?? []).map((item) => ({
|
||||
label: item.date.slice(5),
|
||||
value: item.total_tokens,
|
||||
}));
|
||||
const topModels = (modelsQuery.data?.models ?? []).slice(0, 3);
|
||||
const incidentAccounts = (accountsQuery.data?.items ?? []).filter((item) => item.status === 'error' || item.error_message).slice(0, 5);
|
||||
const trend = trendQuery.data?.trend ?? [];
|
||||
const accounts = accountsQuery.data?.items ?? [];
|
||||
const siteName = settingsQuery.data?.site_name?.trim() || '管理控制台';
|
||||
const throughputPoints = useMemo(
|
||||
() => trend.map((item) => ({ label: getPointLabel(item.date, rangeKey), value: item.total_tokens })),
|
||||
[rangeKey, trend]
|
||||
);
|
||||
const requestPoints = useMemo(
|
||||
() => trend.map((item) => ({ label: getPointLabel(item.date, rangeKey), value: item.requests })),
|
||||
[rangeKey, trend]
|
||||
);
|
||||
const costPoints = useMemo(
|
||||
() => 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);
|
||||
|
||||
return (
|
||||
<ScreenShell title="运维监控" subtitle="运维监控与排障">
|
||||
<View className="flex-row gap-4">
|
||||
<View className="flex-1">
|
||||
<StatCard label="异常账号" value={String(stats?.error_accounts ?? incidentAccounts.length ?? '--')} tone="dark" trend="down" icon={AlertTriangle} />
|
||||
</View>
|
||||
<View className="flex-1">
|
||||
<StatCard label="实时 TPM" value={String(stats?.tpm ?? '--')} icon={Gauge} />
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{trendPoints.length > 1 ? (
|
||||
const cards = [
|
||||
{
|
||||
key: 'throughput',
|
||||
node: throughputPoints.length > 1 ? (
|
||||
<LineTrendChart
|
||||
title="Token 监控"
|
||||
subtitle="最近 7 天总 token 吞吐"
|
||||
points={trendPoints}
|
||||
title="Token 吞吐"
|
||||
subtitle="整体负载曲线"
|
||||
points={throughputPoints}
|
||||
color="#a34d2d"
|
||||
formatValue={(value) => `${Math.round(value / 1000)}k`}
|
||||
formatValue={formatTokenValue}
|
||||
compact={useMasonry}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<ListCard title="热点模型" meta="按请求与 token 用量排序" icon={Layers3}>
|
||||
<View className="gap-3">
|
||||
{topModels.map((item) => (
|
||||
<View key={item.model} className="flex-row items-center justify-between border-b border-[#eee6d7] pb-3 last:border-b-0 last:pb-0">
|
||||
<View className="flex-1 pr-4">
|
||||
<Text className="text-sm font-semibold text-[#16181a]">{item.model}</Text>
|
||||
<Text className="mt-1 text-xs text-[#7d7468]">请求 {item.requests} · Token {Math.round(item.total_tokens / 1000)}k</Text>
|
||||
</View>
|
||||
<Text className="text-sm font-semibold text-[#4e463e]">${Number(item.cost).toFixed(2)}</Text>
|
||||
</View>
|
||||
))}
|
||||
{topModels.length === 0 ? <Text className="text-sm text-[#7d7468]">暂无模型统计</Text> : null}
|
||||
</View>
|
||||
</ListCard>
|
||||
|
||||
) : 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) => (
|
||||
@@ -100,6 +284,104 @@ export default function MonitorScreen() {
|
||||
{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>
|
||||
) : (
|
||||
cards.map((item) => <View key={item.key}>{item.node}</View>)
|
||||
)}
|
||||
</ScreenShell>
|
||||
);
|
||||
}
|
||||
|
||||
197
app/(tabs)/settings.tsx
Normal file
@@ -0,0 +1,197 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { Controller, useForm } from 'react-hook-form';
|
||||
import { Pressable, Text, TextInput, View } from 'react-native';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { ListCard } from '@/src/components/list-card';
|
||||
import { ScreenShell } from '@/src/components/screen-shell';
|
||||
import { isLocalProxyBaseUrl } from '@/src/lib/admin-fetch';
|
||||
import { queryClient } from '@/src/lib/query-client';
|
||||
import {
|
||||
adminConfigState,
|
||||
logoutAdminAccount,
|
||||
removeAdminAccount,
|
||||
saveAdminConfig,
|
||||
setAdminAccountEnabled,
|
||||
switchAdminAccount,
|
||||
type AdminAccountProfile,
|
||||
} from '@/src/store/admin-config';
|
||||
|
||||
const { useSnapshot } = require('valtio/react');
|
||||
|
||||
const schema = z
|
||||
.object({
|
||||
baseUrl: z.string().min(1, '请输入 Host'),
|
||||
adminApiKey: z.string(),
|
||||
})
|
||||
.superRefine((values, ctx) => {
|
||||
if (!isLocalProxyBaseUrl(values.baseUrl.trim()) && !values.adminApiKey.trim()) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: ['adminApiKey'],
|
||||
message: '请输入 Admin Token',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
type FormValues = z.infer<typeof schema>;
|
||||
|
||||
export default function SettingsScreen() {
|
||||
const config = useSnapshot(adminConfigState);
|
||||
const { control, handleSubmit, formState, reset } = useForm<FormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
values: {
|
||||
baseUrl: config.baseUrl,
|
||||
adminApiKey: config.adminApiKey,
|
||||
},
|
||||
});
|
||||
|
||||
async function handleSwitch(account: AdminAccountProfile) {
|
||||
await switchAdminAccount(account.id);
|
||||
queryClient.clear();
|
||||
reset({ baseUrl: account.baseUrl, adminApiKey: account.adminApiKey });
|
||||
}
|
||||
|
||||
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 handleToggleEnabled(account: AdminAccountProfile) {
|
||||
await setAdminAccountEnabled(account.id, account.enabled === false);
|
||||
queryClient.clear();
|
||||
reset({ baseUrl: adminConfigState.baseUrl, adminApiKey: adminConfigState.adminApiKey });
|
||||
}
|
||||
|
||||
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>
|
||||
</View>
|
||||
</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]"
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<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>
|
||||
|
||||
<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>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
@@ -1,57 +1,264 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Activity, Search, UserRound } from 'lucide-react-native';
|
||||
import { useQueries, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import * as Clipboard from 'expo-clipboard';
|
||||
import { Copy, Search, UserRound } from 'lucide-react-native';
|
||||
import { router } from 'expo-router';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Pressable, Text, TextInput, View } from 'react-native';
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { FlatList, Pressable, Text, TextInput, View } from 'react-native';
|
||||
|
||||
import { ListCard } from '@/src/components/list-card';
|
||||
import { ScreenShell } from '@/src/components/screen-shell';
|
||||
import { listUsers } from '@/src/services/admin';
|
||||
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 { adminConfigState } from '@/src/store/admin-config';
|
||||
import type { AdminApiKey, AdminUser, UserUsageSummary } from '@/src/types/admin';
|
||||
|
||||
const { useSnapshot } = require('valtio/react');
|
||||
|
||||
type UserSupplement = {
|
||||
usage?: UserUsageSummary;
|
||||
apiKeys: AdminApiKey[];
|
||||
};
|
||||
|
||||
function getUserTitle(user: AdminUser) {
|
||||
return user.username?.trim() || user.email;
|
||||
}
|
||||
|
||||
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) {
|
||||
return `$${value.toFixed(2)}`;
|
||||
}
|
||||
|
||||
export default function UsersScreen() {
|
||||
const [search, setSearch] = useState('');
|
||||
const keyword = useMemo(() => search.trim(), [search]);
|
||||
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 usersQuery = useQuery({
|
||||
queryKey: ['users', keyword],
|
||||
queryFn: () => listUsers(keyword),
|
||||
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 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 (
|
||||
<ScreenShell title="用户管理" subtitle="搜索用户、查看详情,并在详情页里做余额调整。">
|
||||
<View className="flex-row items-center rounded-[24px] bg-[#fbf8f2] px-4 py-3">
|
||||
<Pressable
|
||||
className="px-1"
|
||||
onPress={() => {
|
||||
void queryClient.prefetchQuery({ queryKey: ['user', user.id], queryFn: () => getUser(user.id) });
|
||||
void queryClient.prefetchQuery({ queryKey: ['user-usage', user.id], queryFn: () => getUserUsage(user.id) });
|
||||
void queryClient.prefetchQuery({ queryKey: ['user-api-keys', user.id], queryFn: () => listUserApiKeys(user.id) });
|
||||
router.push(`/users/${user.id}`);
|
||||
}}
|
||||
>
|
||||
<ListCard title={getUserTitle(user)} meta={user.email} badge={user.status || 'active'} icon={UserRound}>
|
||||
<View className="gap-2">
|
||||
<View className="rounded-[14px] bg-[#f7f2e9] px-3 py-2.5">
|
||||
<View className="flex-row items-center justify-between">
|
||||
<Text className="text-[11px] text-[#6f665c]">余额</Text>
|
||||
<Text className="text-sm font-semibold text-[#16181a]">${Number(user.balance ?? 0).toFixed(2)}</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View className="rounded-[14px] bg-[#f7f2e9] px-3 py-2">
|
||||
<View className="mb-1.5 flex-row items-center justify-between">
|
||||
<Text className="text-[11px] text-[#6f665c]">Keys</Text>
|
||||
<Text className="text-[10px] text-[#8a8072]">{keyItems.length} 个</Text>
|
||||
</View>
|
||||
|
||||
<View className="gap-0">
|
||||
{keyItems.map((apiKey, index) => (
|
||||
<View
|
||||
key={apiKey.id}
|
||||
style={{ paddingVertical: 4 }}
|
||||
>
|
||||
{(() => {
|
||||
const quota = Number(apiKey.quota ?? 0);
|
||||
const used = Number(apiKey.quota_used ?? 0);
|
||||
const isUnlimited = quota <= 0;
|
||||
const progressWidth = isUnlimited ? '16%' : (`${Math.max(Math.min((used / quota) * 100, 100), 6)}%` as `${number}%`);
|
||||
|
||||
return (
|
||||
<>
|
||||
<View className="flex-row items-center gap-2">
|
||||
<Text numberOfLines={1} className="flex-1 text-[11px] font-semibold text-[#16181a]">
|
||||
{apiKey.name}
|
||||
</Text>
|
||||
<Text numberOfLines={1} className="text-[10px] text-[#6f665c]">
|
||||
{isUnlimited ? `${formatQuotaValue(used)} / 无限` : `${formatQuotaValue(used)} / ${formatQuotaValue(quota)}`}
|
||||
</Text>
|
||||
<Pressable
|
||||
className="rounded-full bg-[#e7dfcf] p-1.5"
|
||||
onPress={(event) => {
|
||||
event.stopPropagation();
|
||||
void copyKey(apiKey.id, apiKey.key);
|
||||
}}
|
||||
>
|
||||
<Copy color="#4e463e" size={11} />
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
<View className="h-1.5 overflow-hidden rounded-full bg-[#ddd2c0]" style={{ marginTop: 3 }}>
|
||||
<View
|
||||
className={
|
||||
isUnlimited
|
||||
? 'h-full rounded-full bg-[#7d7468]'
|
||||
: used / Math.max(quota, 1) >= 0.85
|
||||
? 'h-full rounded-full bg-[#c25d35]'
|
||||
: used / Math.max(quota, 1) >= 0.6
|
||||
? 'h-full rounded-full bg-[#d38b36]'
|
||||
: 'h-full rounded-full bg-[#1d5f55]'
|
||||
}
|
||||
style={{ width: progressWidth }}
|
||||
/>
|
||||
</View>
|
||||
|
||||
{copiedKeyId === apiKey.id ? <Text className="text-[10px] text-[#1d5f55]" style={{ paddingTop: 3 }}>已复制</Text> : null}
|
||||
</>
|
||||
);
|
||||
})()}
|
||||
</View>
|
||||
))}
|
||||
|
||||
{keyItems.length === 0 ? (
|
||||
<View className="py-[10px]">
|
||||
<Text className="text-[11px] text-[#6f665c]">当前用户还没有可展示的 token 额度信息。</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
</ListCard>
|
||||
</Pressable>
|
||||
);
|
||||
},
|
||||
[copiedKeyId, queryClient, sortedItems, supplementsByUserId]
|
||||
);
|
||||
|
||||
const emptyState = useMemo(
|
||||
() => (
|
||||
<ListCard
|
||||
title={hasAccount ? '暂无匹配用户' : '未连接服务器'}
|
||||
meta={hasAccount ? errorMessage || '调整搜索词后再试。' : '请先前往服务器标签连接 Sub2API。'}
|
||||
icon={UserRound}
|
||||
/>
|
||||
),
|
||||
[errorMessage, hasAccount]
|
||||
);
|
||||
|
||||
return (
|
||||
<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={search}
|
||||
onChangeText={setSearch}
|
||||
value={searchText}
|
||||
onChangeText={setSearchText}
|
||||
placeholder="搜索邮箱或用户名"
|
||||
placeholderTextColor="#9b9081"
|
||||
className="ml-3 flex-1 text-base text-[#16181a]"
|
||||
/>
|
||||
</View>
|
||||
|
||||
{items.length === 0 ? (
|
||||
<ListCard title="暂无数据" meta={errorMessage || '配置好后台连接后,这里会展示管理员用户列表。'} icon={UserRound} />
|
||||
) : (
|
||||
items.map((user) => (
|
||||
<Pressable key={user.id} onPress={() => router.push(`/users/${user.id}`)}>
|
||||
<ListCard
|
||||
title={user.username || user.email}
|
||||
meta={`${user.email} · 余额 ${Number(user.balance ?? 0).toFixed(2)} · 并发 ${user.concurrency ?? 0}`}
|
||||
badge={user.status || 'active'}
|
||||
icon={UserRound}
|
||||
<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')}
|
||||
>
|
||||
<View className="flex-row items-center gap-2">
|
||||
<Activity color="#7d7468" size={14} />
|
||||
<Text className="text-sm text-[#7d7468]">当前并发 {user.current_concurrency ?? 0}</Text>
|
||||
</View>
|
||||
</ListCard>
|
||||
<Text className={sortOrder === 'desc' ? 'text-[11px] font-semibold text-white' : 'text-[11px] font-semibold text-[#4e463e]'}>
|
||||
最新
|
||||
</Text>
|
||||
</Pressable>
|
||||
))
|
||||
)}
|
||||
<Pressable
|
||||
className={sortOrder === 'asc' ? 'rounded-[14px] bg-[#1d5f55] px-3 py-2.5' : 'rounded-[14px] bg-[#e7dfcf] px-3 py-2.5'}
|
||||
onPress={() => setSortOrder('asc')}
|
||||
>
|
||||
<Text className={sortOrder === 'asc' ? 'text-[11px] font-semibold text-white' : 'text-[11px] font-semibold text-[#4e463e]'}>
|
||||
最早
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View className="mt-2.5 flex-1">
|
||||
<FlatList
|
||||
data={sortedItems}
|
||||
renderItem={renderItem}
|
||||
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}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
</ScreenShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,19 +7,20 @@ import { ActivityIndicator, View } from 'react-native';
|
||||
import { GestureHandlerRootView } from 'react-native-gesture-handler';
|
||||
|
||||
import { queryClient } from '@/src/lib/query-client';
|
||||
import { markPerformance } from '@/src/lib/performance';
|
||||
import { adminConfigState, hydrateAdminConfig } from '@/src/store/admin-config';
|
||||
|
||||
const { useSnapshot } = require('valtio/react');
|
||||
|
||||
export default function RootLayout() {
|
||||
const config = useSnapshot(adminConfigState);
|
||||
|
||||
useEffect(() => {
|
||||
hydrateAdminConfig().catch(() => undefined);
|
||||
hydrateAdminConfig()
|
||||
.then(() => markPerformance('config_hydrated'))
|
||||
.catch(() => undefined);
|
||||
}, []);
|
||||
|
||||
const config = useSnapshot(adminConfigState);
|
||||
const isReady = config.hydrated;
|
||||
const isAuthenticated = Boolean(config.baseUrl.trim() && config.adminApiKey.trim());
|
||||
|
||||
return (
|
||||
<GestureHandlerRootView style={{ flex: 1 }}>
|
||||
@@ -30,8 +31,9 @@ export default function RootLayout() {
|
||||
</View>
|
||||
) : (
|
||||
<Stack screenOptions={{ headerShown: false }}>
|
||||
{isAuthenticated ? <Stack.Screen name="(tabs)" /> : <Stack.Screen name="login" />}
|
||||
<Stack.Screen name="users/[id]" />
|
||||
<Stack.Screen name="(tabs)" />
|
||||
<Stack.Screen name="login" />
|
||||
<Stack.Screen name="users/[id]" options={{ animation: 'slide_from_right', presentation: 'card' }} />
|
||||
<Stack.Screen name="accounts/[id]" options={{ presentation: 'card' }} />
|
||||
</Stack>
|
||||
)}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Pressable, Text, View } from 'react-native';
|
||||
import { DetailRow } from '@/src/components/detail-row';
|
||||
import { LineTrendChart } from '@/src/components/line-trend-chart';
|
||||
import { ListCard } from '@/src/components/list-card';
|
||||
import { formatDisplayTime, formatTokenValue } from '@/src/lib/formatters';
|
||||
import { ScreenShell } from '@/src/components/screen-shell';
|
||||
import { getAccount, getAccountTodayStats, getDashboardTrend, refreshAccount, setAccountSchedulable, testAccount } from '@/src/services/admin';
|
||||
|
||||
@@ -81,11 +82,11 @@ export default function AccountDetailScreen() {
|
||||
<DetailRow label="优先级" value={`${account?.priority ?? 0}`} />
|
||||
<DetailRow label="并发" value={`${account?.concurrency ?? 0}`} />
|
||||
<DetailRow label="当前并发" value={`${account?.current_concurrency ?? 0}`} />
|
||||
<DetailRow label="最后使用" value={account?.last_used_at || '--'} />
|
||||
<DetailRow label="最后使用" value={formatDisplayTime(account?.last_used_at)} />
|
||||
</ListCard>
|
||||
|
||||
<ListCard title="今日统计" meta="真实数据来自 /accounts/:id/today-stats" icon={ShieldCheck}>
|
||||
<DetailRow label="Token" value={`${todayStats?.tokens ?? 0}`} />
|
||||
<DetailRow label="Token" value={formatTokenValue(todayStats?.tokens ?? 0)} />
|
||||
<DetailRow label="请求数" value={`${todayStats?.requests ?? 0}`} />
|
||||
<DetailRow label="成本" value={`$${Number(todayStats?.cost ?? 0).toFixed(4)}`} />
|
||||
</ListCard>
|
||||
@@ -96,7 +97,7 @@ export default function AccountDetailScreen() {
|
||||
subtitle="按账号过滤后的真实 token 趋势"
|
||||
points={trendPoints}
|
||||
color="#c96d43"
|
||||
formatValue={(value) => `${Math.round(value / 1000)}k`}
|
||||
formatValue={formatTokenValue}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { router } from 'expo-router';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { Globe, KeyRound } from 'lucide-react-native';
|
||||
import { Controller, useForm } from 'react-hook-form';
|
||||
@@ -6,18 +7,32 @@ import { z } from 'zod';
|
||||
|
||||
import { ListCard } from '@/src/components/list-card';
|
||||
import { ScreenShell } from '@/src/components/screen-shell';
|
||||
import { adminConfigState, saveAdminConfig } from '@/src/store/admin-config';
|
||||
import { useScreenInteractive } from '@/src/hooks/use-screen-interactive';
|
||||
import { isLocalProxyBaseUrl } from '@/src/lib/admin-fetch';
|
||||
import { queryClient } from '@/src/lib/query-client';
|
||||
import { adminConfigState, removeAdminAccount, saveAdminConfig, setAdminAccountEnabled, switchAdminAccount, type AdminAccountProfile } from '@/src/store/admin-config';
|
||||
|
||||
const { useSnapshot } = require('valtio/react');
|
||||
|
||||
const schema = z.object({
|
||||
const schema = z
|
||||
.object({
|
||||
baseUrl: z.string().min(1, '请输入 Host'),
|
||||
adminApiKey: z.string().min(1, '请输入 Admin Token'),
|
||||
});
|
||||
adminApiKey: z.string(),
|
||||
})
|
||||
.superRefine((values, ctx) => {
|
||||
if (!isLocalProxyBaseUrl(values.baseUrl.trim()) && !values.adminApiKey.trim()) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: ['adminApiKey'],
|
||||
message: '请输入 Admin Token',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
type FormValues = z.infer<typeof schema>;
|
||||
|
||||
export default function LoginScreen() {
|
||||
useScreenInteractive('login_interactive');
|
||||
const config = useSnapshot(adminConfigState);
|
||||
const { control, handleSubmit, formState } = useForm<FormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
@@ -28,7 +43,61 @@ export default function LoginScreen() {
|
||||
});
|
||||
|
||||
return (
|
||||
<ScreenShell title="登录" subtitle="输入 host 和 adminToken 后开始管理。">
|
||||
<ScreenShell
|
||||
title="登录"
|
||||
subtitle=""
|
||||
titleAside={<Text className="text-[11px] text-[#a2988a]">添加、切换或恢复 Sub2API 账号。</Text>}
|
||||
variant="minimal"
|
||||
>
|
||||
{config.accounts.length > 0 ? (
|
||||
<ListCard title="已保存账号" meta="可直接切换到其他 Sub2API 账号">
|
||||
<View className="gap-3">
|
||||
{config.accounts.map((account: AdminAccountProfile) => {
|
||||
const active = account.id === config.activeAccountId;
|
||||
const enabled = account.enabled !== false;
|
||||
|
||||
return (
|
||||
<View key={account.id} className="rounded-[18px] bg-[#f1ece2] px-4 py-3">
|
||||
<Text className="text-sm font-semibold text-[#16181a]">{account.label}</Text>
|
||||
<Text className="mt-1 text-xs text-[#7d7468]">{account.baseUrl}</Text>
|
||||
<View className="mt-3 flex-row gap-3">
|
||||
<Pressable
|
||||
className={active ? 'flex-1 rounded-[16px] bg-[#d7eee4] px-3 py-2.5' : !enabled ? 'flex-1 rounded-[16px] bg-[#d8d1c4] px-3 py-2.5' : 'flex-1 rounded-[16px] bg-[#1d5f55] px-3 py-2.5'}
|
||||
onPress={async () => {
|
||||
await switchAdminAccount(account.id);
|
||||
queryClient.clear();
|
||||
router.replace('/monitor');
|
||||
}}
|
||||
disabled={!enabled}
|
||||
>
|
||||
<Text className={active ? 'text-center text-xs font-semibold text-[#1d5f55]' : !enabled ? 'text-center text-xs font-semibold text-[#7d7468]' : 'text-center text-xs font-semibold text-white'}>
|
||||
{active ? '使用中' : '切换账号'}
|
||||
</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
className="rounded-[16px] bg-[#e7dfcf] px-4 py-2.5"
|
||||
onPress={async () => {
|
||||
await setAdminAccountEnabled(account.id, account.enabled === false);
|
||||
}}
|
||||
>
|
||||
<Text className="text-center text-xs font-semibold text-[#4e463e]">{enabled ? '禁用' : '启用'}</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
className="rounded-[16px] bg-[#e7dfcf] px-4 py-2.5"
|
||||
onPress={async () => {
|
||||
await removeAdminAccount(account.id);
|
||||
}}
|
||||
>
|
||||
<Text className="text-center text-xs font-semibold text-[#7a3d31]">删除</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
</ListCard>
|
||||
) : null}
|
||||
|
||||
<ListCard title="Host" meta="当前站点或管理代理地址" icon={Globe}>
|
||||
<Controller
|
||||
control={control}
|
||||
@@ -46,7 +115,7 @@ export default function LoginScreen() {
|
||||
/>
|
||||
</ListCard>
|
||||
|
||||
<ListCard title="Admin Token" meta="管理员 token" icon={KeyRound}>
|
||||
<ListCard title="Admin Token" meta="直连上游时必填;使用本地代理可留空" icon={KeyRound}>
|
||||
<Controller
|
||||
control={control}
|
||||
name="adminApiKey"
|
||||
@@ -73,6 +142,8 @@ export default function LoginScreen() {
|
||||
className="rounded-[20px] bg-[#1d5f55] px-4 py-4"
|
||||
onPress={handleSubmit(async (values) => {
|
||||
await saveAdminConfig(values);
|
||||
queryClient.clear();
|
||||
router.replace('/monitor');
|
||||
})}
|
||||
>
|
||||
<Text className="text-center text-sm font-semibold tracking-[1.2px] text-white">
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import * as Clipboard from 'expo-clipboard';
|
||||
import { ArrowLeftRight, ChevronLeft, Copy, Eye, EyeOff, KeyRound, Search, Wallet } from 'lucide-react-native';
|
||||
import { ArrowLeftRight, ChevronLeft, Copy, KeyRound, Search, Wallet } from 'lucide-react-native';
|
||||
import { router, useLocalSearchParams } from 'expo-router';
|
||||
import { useState } from 'react';
|
||||
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 { 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';
|
||||
|
||||
@@ -26,10 +28,10 @@ export default function UserDetailScreen() {
|
||||
const userId = Number(id);
|
||||
const queryClient = useQueryClient();
|
||||
const [operation, setOperation] = useState<BalanceOperation>('add');
|
||||
const [keySearch, setKeySearch] = useState('');
|
||||
const [keySearchText, setKeySearchText] = useState('');
|
||||
const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'inactive'>('all');
|
||||
const [visibleKeys, setVisibleKeys] = useState<Record<number, boolean>>({});
|
||||
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: {
|
||||
@@ -73,19 +75,22 @@ export default function UserDetailScreen() {
|
||||
const user = userQuery.data;
|
||||
const usage = usageQuery.data;
|
||||
const apiKeys = apiKeysQuery.data?.items ?? [];
|
||||
const filteredApiKeys = apiKeys.filter((item) => {
|
||||
const filteredApiKeys = useMemo(
|
||||
() =>
|
||||
apiKeys.filter((item) => {
|
||||
const matchesStatus = statusFilter === 'all' ? true : item.status === statusFilter;
|
||||
const keyword = keySearch.trim().toLowerCase();
|
||||
const matchesSearch = !keyword
|
||||
const matchesSearch = !keySearch
|
||||
? true
|
||||
: [item.name, item.key, item.group?.name]
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
.toLowerCase()
|
||||
.includes(keyword);
|
||||
.includes(keySearch);
|
||||
|
||||
return matchesStatus && matchesSearch;
|
||||
});
|
||||
}),
|
||||
[apiKeys, keySearch, statusFilter]
|
||||
);
|
||||
|
||||
function maskKey(value: string) {
|
||||
if (!value || value.length < 16) {
|
||||
@@ -104,7 +109,9 @@ export default function UserDetailScreen() {
|
||||
return (
|
||||
<ScreenShell
|
||||
title={user?.username || user?.email || '用户详情'}
|
||||
subtitle="核心看余额和 token 用量,其他内容尽量保持轻量。"
|
||||
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} />
|
||||
@@ -115,7 +122,7 @@ export default function UserDetailScreen() {
|
||||
<DetailRow label="角色" value={user?.role || '--'} />
|
||||
<DetailRow label="余额" value={Number(user?.balance ?? 0).toFixed(2)} />
|
||||
<DetailRow label="并发" value={`${user?.concurrency ?? 0}`} />
|
||||
<DetailRow label="更新时间" value={user?.updated_at || '--'} />
|
||||
<DetailRow label="更新时间" value={formatDisplayTime(user?.updated_at)} />
|
||||
</ListCard>
|
||||
|
||||
<ListCard title="月度用量" meta="真实数据来自 /users/:id/usage" icon={ArrowLeftRight}>
|
||||
@@ -129,8 +136,8 @@ export default function UserDetailScreen() {
|
||||
<View className="flex-row items-center rounded-[18px] bg-[#f1ece2] px-4 py-3">
|
||||
<Search color="#7d7468" size={16} />
|
||||
<TextInput
|
||||
value={keySearch}
|
||||
onChangeText={setKeySearch}
|
||||
defaultValue=""
|
||||
onChangeText={setKeySearchText}
|
||||
placeholder="搜索 key 名称或分组"
|
||||
placeholderTextColor="#9b9081"
|
||||
className="ml-3 flex-1 text-sm text-[#16181a]"
|
||||
@@ -156,19 +163,16 @@ export default function UserDetailScreen() {
|
||||
<Text className="text-xs uppercase tracking-[1.2px] text-[#7d7468]">{item.status}</Text>
|
||||
</View>
|
||||
<View className="mt-2 flex-row items-center gap-2">
|
||||
<Text className="flex-1 text-xs text-[#7d7468]">{visibleKeys[item.id] ? item.key : maskKey(item.key)}</Text>
|
||||
<Text className="flex-1 text-xs text-[#7d7468]">{maskKey(item.key)}</Text>
|
||||
<Pressable
|
||||
className="rounded-full bg-[#e7dfcf] p-2"
|
||||
onPress={() => setVisibleKeys((current) => ({ ...current, [item.id]: !current[item.id] }))}
|
||||
onPress={() => copyKey(item.id, item.key)}
|
||||
>
|
||||
{visibleKeys[item.id] ? <EyeOff color="#4e463e" size={14} /> : <Eye color="#4e463e" size={14} />}
|
||||
</Pressable>
|
||||
<Pressable className="rounded-full bg-[#1b1d1f] p-2" onPress={() => copyKey(item.id, item.key)}>
|
||||
<Copy color="#f6f1e8" size={14} />
|
||||
<Copy color="#4e463e" size={14} />
|
||||
</Pressable>
|
||||
</View>
|
||||
<Text className="mt-2 text-xs text-[#7d7468]">
|
||||
{copiedKeyId === item.id ? '已复制到剪贴板' : `最近使用 ${item.last_used_at || '--'}`}
|
||||
{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)}` : '无限制'}
|
||||
|
||||
78
docs/EXPO_RELEASE.md
Normal file
@@ -0,0 +1,78 @@
|
||||
# Expo Release
|
||||
|
||||
当前项目已绑定新的 Expo / EAS 项目:
|
||||
|
||||
- Owner: `ckken`
|
||||
- Slug: `sub2api-mobile`
|
||||
- Project ID: `acaedd05-5a2a-4843-a648-e025c08ce7b3`
|
||||
|
||||
## 已完成配置
|
||||
|
||||
- `app.json` 已配置 `owner`
|
||||
- `app.json` 已配置 `runtimeVersion.policy = appVersion`
|
||||
- `app.json` 已配置 `updates.url`
|
||||
- `eas.json` 已配置 `development / preview / production` 三套 profile
|
||||
|
||||
## 登录状态检查
|
||||
|
||||
```bash
|
||||
npx expo whoami
|
||||
npx eas whoami
|
||||
```
|
||||
|
||||
## 预览包
|
||||
|
||||
```bash
|
||||
npm run eas:build:preview
|
||||
```
|
||||
|
||||
## GitHub Actions 构建
|
||||
|
||||
仓库已提供工作流:`.github/workflows/eas-build.yml`
|
||||
|
||||
使用前需要在 GitHub 仓库 Secrets 里配置:
|
||||
|
||||
- `EXPO_TOKEN`
|
||||
|
||||
触发方式:
|
||||
|
||||
1. 打开 GitHub 仓库的 `Actions`
|
||||
2. 选择 `EAS Build`
|
||||
3. 点击 `Run workflow`
|
||||
4. 选择:
|
||||
- `profile`: `preview` 或 `production`
|
||||
- `platform`: `android` / `ios` / `all`
|
||||
|
||||
工作流会执行:
|
||||
|
||||
```bash
|
||||
npm ci
|
||||
npx eas build --non-interactive --profile <profile> --platform <platform>
|
||||
```
|
||||
|
||||
## 正式包
|
||||
|
||||
```bash
|
||||
npm run eas:build:production
|
||||
```
|
||||
|
||||
## OTA 更新
|
||||
|
||||
预发:
|
||||
|
||||
```bash
|
||||
npx eas update --branch preview --message "preview update"
|
||||
```
|
||||
|
||||
正式:
|
||||
|
||||
```bash
|
||||
npx eas update --branch production --message "production update"
|
||||
```
|
||||
|
||||
## 当前还需要你补的内容
|
||||
|
||||
- iOS 的 `bundleIdentifier`
|
||||
- Android 的 `package`
|
||||
|
||||
如果不补这两个标识,原生构建时 EAS 还会继续要求你确认或生成。
|
||||
@@ -27,6 +27,18 @@ npm run proxy
|
||||
npm run web
|
||||
```
|
||||
|
||||
## 打包优化开关
|
||||
|
||||
当前项目已在 `metro.config.js` 打开更积极的导入优化,并建议在本地或 CI 增加:
|
||||
|
||||
```bash
|
||||
EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH=1 \
|
||||
EXPO_UNSTABLE_TREE_SHAKING=1 \
|
||||
npx expo export --platform web
|
||||
```
|
||||
|
||||
这组环境变量更适合生产打包或包体分析,不建议把日常开发体验和正式构建混在一起看。
|
||||
|
||||
## 一条命令同时启动
|
||||
|
||||
```bash
|
||||
|
||||
23
eas.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"cli": {
|
||||
"version": ">= 16.21.0",
|
||||
"appVersionSource": "remote"
|
||||
},
|
||||
"build": {
|
||||
"development": {
|
||||
"developmentClient": true,
|
||||
"distribution": "internal"
|
||||
},
|
||||
"preview": {
|
||||
"distribution": "internal",
|
||||
"channel": "preview"
|
||||
},
|
||||
"production": {
|
||||
"autoIncrement": true,
|
||||
"channel": "production"
|
||||
}
|
||||
},
|
||||
"submit": {
|
||||
"production": {}
|
||||
}
|
||||
}
|
||||
BIN
icons/android/mipmap-hdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 5.5 KiB |
BIN
icons/android/mipmap-ldpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 1.6 KiB |
BIN
icons/android/mipmap-mdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 3.0 KiB |
BIN
icons/android/mipmap-xhdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 9.2 KiB |
BIN
icons/android/mipmap-xxhdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 19 KiB |
BIN
icons/android/mipmap-xxxhdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 33 KiB |
BIN
icons/android/playstore-icon.png
Normal file
|
After Width: | Height: | Size: 189 KiB |
120
icons/ios/AppIcon.appiconset/Contents.json
Normal file
@@ -0,0 +1,120 @@
|
||||
{
|
||||
"images": [
|
||||
{
|
||||
"size": "20x20",
|
||||
"idiom": "universal",
|
||||
"filename": "icon-20@2x.png",
|
||||
"scale": "2x",
|
||||
"platform": "ios"
|
||||
},
|
||||
{
|
||||
"size": "20x20",
|
||||
"idiom": "universal",
|
||||
"filename": "icon-20@3x.png",
|
||||
"scale": "3x",
|
||||
"platform": "ios"
|
||||
},
|
||||
{
|
||||
"size": "29x29",
|
||||
"idiom": "universal",
|
||||
"filename": "icon-29@2x.png",
|
||||
"scale": "2x",
|
||||
"platform": "ios"
|
||||
},
|
||||
{
|
||||
"size": "29x29",
|
||||
"idiom": "universal",
|
||||
"filename": "icon-29@3x.png",
|
||||
"scale": "3x",
|
||||
"platform": "ios"
|
||||
},
|
||||
{
|
||||
"size": "38x38",
|
||||
"idiom": "universal",
|
||||
"filename": "icon-38@2x.png",
|
||||
"scale": "2x",
|
||||
"platform": "ios"
|
||||
},
|
||||
{
|
||||
"size": "38x38",
|
||||
"idiom": "universal",
|
||||
"filename": "icon-38@3x.png",
|
||||
"scale": "3x",
|
||||
"platform": "ios"
|
||||
},
|
||||
{
|
||||
"size": "40x40",
|
||||
"idiom": "universal",
|
||||
"filename": "icon-40@2x.png",
|
||||
"scale": "2x",
|
||||
"platform": "ios"
|
||||
},
|
||||
{
|
||||
"size": "40x40",
|
||||
"idiom": "universal",
|
||||
"filename": "icon-40@3x.png",
|
||||
"scale": "3x",
|
||||
"platform": "ios"
|
||||
},
|
||||
{
|
||||
"size": "60x60",
|
||||
"idiom": "universal",
|
||||
"filename": "icon-60@2x.png",
|
||||
"scale": "2x",
|
||||
"platform": "ios"
|
||||
},
|
||||
{
|
||||
"size": "60x60",
|
||||
"idiom": "universal",
|
||||
"filename": "icon-60@3x.png",
|
||||
"scale": "3x",
|
||||
"platform": "ios"
|
||||
},
|
||||
{
|
||||
"size": "64x64",
|
||||
"idiom": "universal",
|
||||
"filename": "icon-64@2x.png",
|
||||
"scale": "2x",
|
||||
"platform": "ios"
|
||||
},
|
||||
{
|
||||
"size": "64x64",
|
||||
"idiom": "universal",
|
||||
"filename": "icon-64@3x.png",
|
||||
"scale": "3x",
|
||||
"platform": "ios"
|
||||
},
|
||||
{
|
||||
"size": "68x68",
|
||||
"idiom": "universal",
|
||||
"filename": "icon-68@2x.png",
|
||||
"scale": "2x",
|
||||
"platform": "ios"
|
||||
},
|
||||
{
|
||||
"size": "76x76",
|
||||
"idiom": "universal",
|
||||
"filename": "icon-76@2x.png",
|
||||
"scale": "2x",
|
||||
"platform": "ios"
|
||||
},
|
||||
{
|
||||
"size": "83.5x83.5",
|
||||
"idiom": "universal",
|
||||
"filename": "icon-83.5@2x.png",
|
||||
"scale": "2x",
|
||||
"platform": "ios"
|
||||
},
|
||||
{
|
||||
"size": "1024x1024",
|
||||
"idiom": "universal",
|
||||
"filename": "icon-1024.png",
|
||||
"scale": "1x",
|
||||
"platform": "ios"
|
||||
}
|
||||
],
|
||||
"info": {
|
||||
"version": 1,
|
||||
"author": "icon.wuruihong.com"
|
||||
}
|
||||
}
|
||||
BIN
icons/ios/AppIcon.appiconset/icon-1024.png
Normal file
|
After Width: | Height: | Size: 470 KiB |
BIN
icons/ios/AppIcon.appiconset/icon-20@2x.png
Normal file
|
After Width: | Height: | Size: 1.9 KiB |
BIN
icons/ios/AppIcon.appiconset/icon-20@3x.png
Normal file
|
After Width: | Height: | Size: 3.7 KiB |
BIN
icons/ios/AppIcon.appiconset/icon-29@2x.png
Normal file
|
After Width: | Height: | Size: 3.4 KiB |
BIN
icons/ios/AppIcon.appiconset/icon-29@3x.png
Normal file
|
After Width: | Height: | Size: 6.7 KiB |
BIN
icons/ios/AppIcon.appiconset/icon-38@2x.png
Normal file
|
After Width: | Height: | Size: 5.4 KiB |
BIN
icons/ios/AppIcon.appiconset/icon-38@3x.png
Normal file
|
After Width: | Height: | Size: 11 KiB |
BIN
icons/ios/AppIcon.appiconset/icon-40@2x.png
Normal file
|
After Width: | Height: | Size: 5.9 KiB |
BIN
icons/ios/AppIcon.appiconset/icon-40@3x.png
Normal file
|
After Width: | Height: | Size: 12 KiB |
BIN
icons/ios/AppIcon.appiconset/icon-60@2x.png
Normal file
|
After Width: | Height: | Size: 12 KiB |
BIN
icons/ios/AppIcon.appiconset/icon-60@3x.png
Normal file
|
After Width: | Height: | Size: 26 KiB |
BIN
icons/ios/AppIcon.appiconset/icon-64@2x.png
Normal file
|
After Width: | Height: | Size: 14 KiB |
BIN
icons/ios/AppIcon.appiconset/icon-64@3x.png
Normal file
|
After Width: | Height: | Size: 29 KiB |
BIN
icons/ios/AppIcon.appiconset/icon-68@2x.png
Normal file
|
After Width: | Height: | Size: 15 KiB |
BIN
icons/ios/AppIcon.appiconset/icon-76@2x.png
Normal file
|
After Width: | Height: | Size: 19 KiB |
BIN
icons/ios/AppIcon.appiconset/icon-83.5@2x.png
Normal file
|
After Width: | Height: | Size: 22 KiB |
@@ -3,6 +3,13 @@ const { withUniwindConfig } = require('uniwind/metro');
|
||||
|
||||
const config = getDefaultConfig(__dirname);
|
||||
|
||||
config.transformer.getTransformOptions = async () => ({
|
||||
transform: {
|
||||
experimentalImportSupport: true,
|
||||
inlineRequires: true,
|
||||
},
|
||||
});
|
||||
|
||||
module.exports = withUniwindConfig(config, {
|
||||
cssEntryFile: './src/global.css',
|
||||
dtsFile: './src/uniwind-types.d.ts',
|
||||
|
||||
4163
package-lock.json
generated
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "x-sapi-mobile",
|
||||
"name": "sub2api-mobile",
|
||||
"version": "1.0.0",
|
||||
"main": "expo-router/entry",
|
||||
"scripts": {
|
||||
@@ -8,7 +8,11 @@
|
||||
"ios": "expo start --ios",
|
||||
"web": "expo start --web",
|
||||
"proxy": "node server/index.js",
|
||||
"dev:web-proxy": "concurrently -n proxy,web -c green,blue \"npm run proxy\" \"npm run web\""
|
||||
"dev:web-proxy": "concurrently -n proxy,web -c green,blue \"npm run proxy\" \"npm run web\"",
|
||||
"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"
|
||||
},
|
||||
"dependencies": {
|
||||
"@hookform/resolvers": "^5.2.2",
|
||||
@@ -42,6 +46,7 @@
|
||||
"devDependencies": {
|
||||
"@types/react": "~19.2.2",
|
||||
"concurrently": "^9.2.1",
|
||||
"eas-cli": "^18.1.0",
|
||||
"typescript": "~5.9.2"
|
||||
},
|
||||
"private": true
|
||||
|
||||
86
src/components/bar-chart-card.tsx
Normal file
@@ -0,0 +1,86 @@
|
||||
import { CircleHelp } from 'lucide-react-native';
|
||||
import { useState } from 'react';
|
||||
import { Pressable, Text, View } from 'react-native';
|
||||
|
||||
type BarChartItem = {
|
||||
label: string;
|
||||
value: number;
|
||||
color?: string;
|
||||
meta?: string;
|
||||
hint?: string;
|
||||
};
|
||||
|
||||
type BarChartCardProps = {
|
||||
title: string;
|
||||
subtitle: string;
|
||||
items: BarChartItem[];
|
||||
formatValue?: (value: number) => string;
|
||||
};
|
||||
|
||||
export function BarChartCard({
|
||||
title,
|
||||
subtitle,
|
||||
items,
|
||||
formatValue = (value) => `${value}`,
|
||||
}: BarChartCardProps) {
|
||||
const [activeHint, setActiveHint] = useState<string | null>(null);
|
||||
const maxValue = Math.max(...items.map((item) => item.value), 1);
|
||||
|
||||
return (
|
||||
<View className="rounded-[18px] bg-[#fbf8f2] p-4">
|
||||
<Text className="text-xs uppercase tracking-[1.6px] text-[#7d7468]">{title}</Text>
|
||||
<Text numberOfLines={1} className="mt-1 text-xs text-[#8a8072]">{subtitle}</Text>
|
||||
|
||||
<View className="mt-4 gap-3">
|
||||
{items.map((item) => {
|
||||
const barWidth = `${Math.max((item.value / maxValue) * 100, item.value > 0 ? 8 : 0)}%` as `${number}%`;
|
||||
|
||||
return (
|
||||
<View key={item.label} className="w-full">
|
||||
<View className="w-full flex-row items-center justify-between gap-3">
|
||||
<View className="flex-1 flex-row items-center gap-1.5 pr-3">
|
||||
<Text numberOfLines={1} className="text-sm font-semibold text-[#16181a]">
|
||||
{item.label}
|
||||
</Text>
|
||||
{item.hint ? (
|
||||
<Pressable
|
||||
className="h-4 w-4 items-center justify-center rounded-full bg-[#efe7d9]"
|
||||
onPress={() => setActiveHint(activeHint === item.label ? null : item.label)}
|
||||
>
|
||||
<CircleHelp color="#7d7468" size={11} />
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
<Text className="text-sm font-semibold text-[#4e463e]">{formatValue(item.value)}</Text>
|
||||
</View>
|
||||
|
||||
{item.hint && activeHint === item.label ? (
|
||||
<View className="mt-2 rounded-[10px] bg-[#f1ece2] px-3 py-2">
|
||||
<Text className="text-[11px] leading-4 text-[#6f665c]">{item.hint}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
<View className="mt-1 flex-row items-end justify-between gap-3">
|
||||
<View className="flex-1 pr-3">
|
||||
{item.meta ? <Text numberOfLines={1} className="text-[11px] text-[#7d7468]">{item.meta}</Text> : null}
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View className="mt-2 h-[10px] overflow-hidden rounded-full bg-[#ece4d6]">
|
||||
<View
|
||||
className="h-full rounded-full"
|
||||
style={{
|
||||
width: barWidth,
|
||||
backgroundColor: item.color || '#1d5f55',
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
|
||||
{items.length === 0 ? <Text className="text-sm text-[#7d7468]">暂无可视化数据</Text> : null}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
99
src/components/donut-chart-card.tsx
Normal file
@@ -0,0 +1,99 @@
|
||||
import { Text, View } from 'react-native';
|
||||
import Svg, { Circle } from 'react-native-svg';
|
||||
|
||||
type DonutSegment = {
|
||||
label: string;
|
||||
value: number;
|
||||
color: string;
|
||||
};
|
||||
|
||||
type DonutChartCardProps = {
|
||||
title: string;
|
||||
subtitle: string;
|
||||
segments: DonutSegment[];
|
||||
centerLabel: string;
|
||||
centerValue: string;
|
||||
};
|
||||
|
||||
export function DonutChartCard({
|
||||
title,
|
||||
subtitle,
|
||||
segments,
|
||||
centerLabel,
|
||||
centerValue,
|
||||
}: DonutChartCardProps) {
|
||||
const total = Math.max(
|
||||
segments.reduce((sum, segment) => sum + segment.value, 0),
|
||||
1
|
||||
);
|
||||
const size = 152;
|
||||
const strokeWidth = 16;
|
||||
const radius = (size - strokeWidth) / 2;
|
||||
const circumference = 2 * Math.PI * radius;
|
||||
|
||||
let offset = 0;
|
||||
|
||||
return (
|
||||
<View className="rounded-[18px] bg-[#fbf8f2] p-4">
|
||||
<Text className="text-xs uppercase tracking-[1.6px] text-[#7d7468]">{title}</Text>
|
||||
<Text numberOfLines={1} className="mt-1 text-xs text-[#8a8072]">{subtitle}</Text>
|
||||
|
||||
<View className="mt-4 items-center justify-center">
|
||||
<View className="items-center justify-center">
|
||||
<Svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
|
||||
<Circle
|
||||
cx={size / 2}
|
||||
cy={size / 2}
|
||||
r={radius}
|
||||
stroke="#ece4d6"
|
||||
strokeWidth={strokeWidth}
|
||||
fill="none"
|
||||
/>
|
||||
{segments.map((segment) => {
|
||||
const length = (segment.value / total) * circumference;
|
||||
const circleOffset = circumference - offset;
|
||||
offset += length;
|
||||
|
||||
return (
|
||||
<Circle
|
||||
key={segment.label}
|
||||
cx={size / 2}
|
||||
cy={size / 2}
|
||||
r={radius}
|
||||
stroke={segment.color}
|
||||
strokeWidth={strokeWidth}
|
||||
fill="none"
|
||||
strokeDasharray={`${length} ${circumference - length}`}
|
||||
strokeDashoffset={circleOffset}
|
||||
strokeLinecap="round"
|
||||
transform={`rotate(-90 ${size / 2} ${size / 2})`}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</Svg>
|
||||
|
||||
<View className="absolute items-center">
|
||||
<Text className="text-xs uppercase tracking-[1.4px] text-[#7d7468]">{centerLabel}</Text>
|
||||
<Text className="mt-1 text-[28px] font-bold text-[#16181a]">{centerValue}</Text>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View className="mt-4 gap-2.5">
|
||||
{segments.map((segment) => {
|
||||
const percentage = Math.round((segment.value / total) * 100);
|
||||
|
||||
return (
|
||||
<View key={segment.label} className="flex-row items-center justify-between rounded-[12px] bg-[#f4efe4] px-3 py-2.5">
|
||||
<View className="flex-row items-center gap-3">
|
||||
<View className="h-3 w-3 rounded-full" style={{ backgroundColor: segment.color }} />
|
||||
<Text className="text-sm font-semibold text-[#16181a]">{segment.label}</Text>
|
||||
</View>
|
||||
<Text className="text-xs text-[#5d564d]">{segment.value} · {percentage}%</Text>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -12,6 +12,7 @@ type LineTrendChartProps = {
|
||||
title: string;
|
||||
subtitle: string;
|
||||
formatValue?: (value: number) => string;
|
||||
compact?: boolean;
|
||||
};
|
||||
|
||||
export function LineTrendChart({
|
||||
@@ -20,9 +21,10 @@ export function LineTrendChart({
|
||||
title,
|
||||
subtitle,
|
||||
formatValue = (value) => `${value}`,
|
||||
compact = false,
|
||||
}: LineTrendChartProps) {
|
||||
const width = 320;
|
||||
const height = 160;
|
||||
const height = compact ? 104 : 144;
|
||||
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);
|
||||
@@ -38,14 +40,17 @@ export function LineTrendChart({
|
||||
|
||||
const area = `${line} L ${width} ${height} L 0 ${height} Z`;
|
||||
const latest = points[points.length - 1]?.value ?? 0;
|
||||
const maxTicks = compact ? 6 : 7;
|
||||
const tickStep = Math.max(Math.ceil(points.length / maxTicks), 1);
|
||||
const tickPoints = points.filter((_, index) => index === 0 || index === points.length - 1 || index % tickStep === 0);
|
||||
|
||||
return (
|
||||
<View className="rounded-[28px] bg-[#fbf8f2] p-5">
|
||||
<View className="rounded-[18px] bg-[#fbf8f2] p-4">
|
||||
<Text className="text-xs uppercase tracking-[1.6px] text-[#7d7468]">{title}</Text>
|
||||
<Text className="mt-2 text-3xl font-bold text-[#16181a]">{formatValue(latest)}</Text>
|
||||
<Text className="mt-1 text-sm text-[#7d7468]">{subtitle}</Text>
|
||||
<Text className={`mt-1 font-bold text-[#16181a] ${compact ? 'text-[22px]' : 'text-[28px]'}`}>{formatValue(latest)}</Text>
|
||||
<Text numberOfLines={1} className="mt-1 text-xs text-[#8a8072]">{subtitle}</Text>
|
||||
|
||||
<View className="mt-5 overflow-hidden rounded-[20px] bg-[#f4efe4] p-3">
|
||||
<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">
|
||||
@@ -57,9 +62,9 @@ export function LineTrendChart({
|
||||
<Path d={line} fill="none" stroke={color} strokeWidth="3" strokeLinejoin="round" strokeLinecap="round" />
|
||||
</Svg>
|
||||
|
||||
<View className="mt-3 flex-row justify-between">
|
||||
{points.map((point) => (
|
||||
<Text key={point.label} className="text-xs text-[#7d7468]">
|
||||
<View className="mt-2 flex-row justify-between">
|
||||
{tickPoints.map((point) => (
|
||||
<Text key={point.label} className={`text-[#7d7468] ${compact ? 'text-[10px]' : 'text-xs'}`}>
|
||||
{point.label}
|
||||
</Text>
|
||||
))}
|
||||
|
||||
@@ -12,22 +12,22 @@ type ListCardProps = {
|
||||
|
||||
export function ListCard({ title, meta, badge, children, icon: Icon }: ListCardProps) {
|
||||
return (
|
||||
<View className="rounded-[24px] bg-[#fbf8f2] p-4">
|
||||
<View className="rounded-[16px] border border-[#efe7d9] bg-[#fbf8f2] p-3.5">
|
||||
<View className="flex-row items-start justify-between gap-3">
|
||||
<View className="flex-1">
|
||||
<View className="flex-row items-center gap-2">
|
||||
{Icon ? <Icon color="#7d7468" size={16} /> : null}
|
||||
<Text className="text-lg font-semibold text-[#16181a]">{title}</Text>
|
||||
<Text className="text-base font-semibold text-[#16181a]">{title}</Text>
|
||||
</View>
|
||||
{meta ? <Text className="mt-1 text-sm text-[#7d7468]">{meta}</Text> : null}
|
||||
{meta ? <Text numberOfLines={1} className="mt-1 text-xs text-[#7d7468]">{meta}</Text> : null}
|
||||
</View>
|
||||
{badge ? (
|
||||
<View className="rounded-full bg-[#e7dfcf] px-3 py-1">
|
||||
<Text className="text-xs font-semibold uppercase tracking-[1.2px] text-[#5d564d]">{badge}</Text>
|
||||
<View className="rounded-full bg-[#e7dfcf] px-2.5 py-1">
|
||||
<Text className="text-[10px] font-semibold uppercase tracking-[1px] text-[#5d564d]">{badge}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
{children ? <View className="mt-4">{children}</View> : null}
|
||||
{children ? <View className="mt-3">{children}</View> : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,23 +5,84 @@ import { ScrollView, Text, View } from 'react-native';
|
||||
type ScreenShellProps = PropsWithChildren<{
|
||||
title: string;
|
||||
subtitle: string;
|
||||
titleAside?: ReactNode;
|
||||
right?: ReactNode;
|
||||
variant?: 'card' | 'minimal';
|
||||
scroll?: boolean;
|
||||
bottomInsetClassName?: string;
|
||||
horizontalInsetClassName?: string;
|
||||
contentGapClassName?: string;
|
||||
}>;
|
||||
|
||||
export function ScreenShell({ title, subtitle, right, children }: ScreenShellProps) {
|
||||
function ScreenHeader({
|
||||
title,
|
||||
subtitle,
|
||||
titleAside,
|
||||
right,
|
||||
variant,
|
||||
}: Pick<ScreenShellProps, 'title' | 'subtitle' | 'titleAside' | 'right' | 'variant'>) {
|
||||
if (variant === 'minimal') {
|
||||
return (
|
||||
<View className="mt-4 flex-row items-start justify-between gap-4 px-1 py-1">
|
||||
<View className="flex-1">
|
||||
<View className="flex-row items-center gap-2">
|
||||
<Text className="text-[20px] font-bold tracking-tight text-[#16181a]">{title}</Text>
|
||||
{titleAside}
|
||||
</View>
|
||||
{subtitle ? (
|
||||
<Text numberOfLines={1} className="mt-1 text-[11px] leading-4 text-[#a2988a]">
|
||||
{subtitle}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
{right ? <View className="items-end justify-start">{right}</View> : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SafeAreaView className="flex-1 bg-[#f4efe4]">
|
||||
<ScrollView className="flex-1" contentContainerClassName="px-5 pb-24">
|
||||
<View className="mt-4 rounded-[24px] border border-[#e6dece] bg-[#fbf8f2] px-4 py-4">
|
||||
<View className="flex-row items-start justify-between gap-4">
|
||||
<View className="flex-1">
|
||||
<Text className="text-[24px] font-bold tracking-tight text-[#16181a]">{title}</Text>
|
||||
<Text className="mt-1 text-sm leading-6 text-[#7d7468]">{subtitle}</Text>
|
||||
<Text numberOfLines={1} className="mt-1 text-xs leading-4 text-[#9a9082]">
|
||||
{subtitle}
|
||||
</Text>
|
||||
</View>
|
||||
{right}
|
||||
</View>
|
||||
</View>
|
||||
<View className="mt-4 gap-4">{children}</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function ScreenShell({
|
||||
title,
|
||||
subtitle,
|
||||
titleAside,
|
||||
right,
|
||||
children,
|
||||
variant = 'card',
|
||||
scroll = true,
|
||||
bottomInsetClassName = 'pb-24',
|
||||
horizontalInsetClassName = 'px-5',
|
||||
contentGapClassName = 'mt-4 gap-4',
|
||||
}: ScreenShellProps) {
|
||||
if (!scroll) {
|
||||
return (
|
||||
<SafeAreaView className="flex-1 bg-[#f4efe4]">
|
||||
<View className={`flex-1 ${horizontalInsetClassName} ${bottomInsetClassName}`}>
|
||||
<ScreenHeader title={title} subtitle={subtitle} titleAside={titleAside} right={right} variant={variant} />
|
||||
<View className={`flex-1 ${contentGapClassName}`}>{children}</View>
|
||||
</View>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SafeAreaView className="flex-1 bg-[#f4efe4]">
|
||||
<ScrollView className="flex-1" contentContainerClassName={`${horizontalInsetClassName} ${bottomInsetClassName}`}>
|
||||
<ScreenHeader title={title} subtitle={subtitle} titleAside={titleAside} right={right} variant={variant} />
|
||||
<View className={contentGapClassName}>{children}</View>
|
||||
</ScrollView>
|
||||
</SafeAreaView>
|
||||
);
|
||||
|
||||
13
src/hooks/use-debounced-value.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
export function useDebouncedValue<T>(value: T, delay = 250) {
|
||||
const [debouncedValue, setDebouncedValue] = useState(value);
|
||||
|
||||
useEffect(() => {
|
||||
const timeoutId = setTimeout(() => setDebouncedValue(value), delay);
|
||||
|
||||
return () => clearTimeout(timeoutId);
|
||||
}, [delay, value]);
|
||||
|
||||
return debouncedValue;
|
||||
}
|
||||
15
src/hooks/use-screen-interactive.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { useEffect } from 'react';
|
||||
|
||||
import { markPerformance } from '@/src/lib/performance';
|
||||
|
||||
export function useScreenInteractive(
|
||||
name: 'login_interactive' | 'dashboard_interactive' | 'users_interactive' | 'monitor_interactive'
|
||||
) {
|
||||
useEffect(() => {
|
||||
const timeoutId = setTimeout(() => {
|
||||
markPerformance(name);
|
||||
}, 0);
|
||||
|
||||
return () => clearTimeout(timeoutId);
|
||||
}, [name]);
|
||||
}
|
||||
45
src/lib/formatters.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
export function formatCompactNumber(value: number, digits = 1) {
|
||||
const abs = Math.abs(value);
|
||||
|
||||
if (abs >= 1_000_000_000_000) {
|
||||
return `${(value / 1_000_000_000_000).toFixed(digits).replace(/\.0$/, '')}T`;
|
||||
}
|
||||
|
||||
if (abs >= 1_000_000_000) {
|
||||
return `${(value / 1_000_000_000).toFixed(digits).replace(/\.0$/, '')}B`;
|
||||
}
|
||||
|
||||
if (abs >= 1_000_000) {
|
||||
return `${(value / 1_000_000).toFixed(digits).replace(/\.0$/, '')}M`;
|
||||
}
|
||||
|
||||
if (abs >= 1_000) {
|
||||
return `${(value / 1_000).toFixed(digits).replace(/\.0$/, '')}K`;
|
||||
}
|
||||
|
||||
return `${Math.round(value)}`;
|
||||
}
|
||||
|
||||
export function formatTokenValue(value: number) {
|
||||
return formatCompactNumber(value, 1);
|
||||
}
|
||||
|
||||
export function formatDisplayTime(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}`;
|
||||
}
|
||||
57
src/lib/performance.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
type PerfMarkName =
|
||||
| 'app_start'
|
||||
| 'config_hydrated'
|
||||
| 'login_interactive'
|
||||
| 'dashboard_interactive'
|
||||
| 'users_interactive'
|
||||
| 'monitor_interactive';
|
||||
|
||||
declare global {
|
||||
var __xSapiPerfStartedAt: number | undefined;
|
||||
var __xSapiPerfMarks: Partial<Record<PerfMarkName, number>> | undefined;
|
||||
}
|
||||
|
||||
function now() {
|
||||
if (typeof globalThis !== 'undefined' && globalThis.performance?.now) {
|
||||
return globalThis.performance.now();
|
||||
}
|
||||
|
||||
return Date.now();
|
||||
}
|
||||
|
||||
function ensureStore() {
|
||||
if (!globalThis.__xSapiPerfMarks) {
|
||||
globalThis.__xSapiPerfMarks = {};
|
||||
}
|
||||
|
||||
return globalThis.__xSapiPerfMarks;
|
||||
}
|
||||
|
||||
export function markAppStart() {
|
||||
if (!globalThis.__xSapiPerfStartedAt) {
|
||||
globalThis.__xSapiPerfStartedAt = now();
|
||||
ensureStore().app_start = globalThis.__xSapiPerfStartedAt;
|
||||
}
|
||||
}
|
||||
|
||||
export function markPerformance(name: PerfMarkName) {
|
||||
ensureStore()[name] = now();
|
||||
|
||||
if (__DEV__) {
|
||||
reportPerformance(name);
|
||||
}
|
||||
}
|
||||
|
||||
export function reportPerformance(name: PerfMarkName) {
|
||||
const startedAt = globalThis.__xSapiPerfStartedAt;
|
||||
const mark = ensureStore()[name];
|
||||
|
||||
if (!startedAt || !mark) {
|
||||
return;
|
||||
}
|
||||
|
||||
const duration = Math.round(mark - startedAt);
|
||||
console.info(`[perf] ${name}: ${duration}ms since app_start`);
|
||||
}
|
||||
|
||||
markAppStart();
|
||||
@@ -3,6 +3,61 @@ const { proxy } = require('valtio');
|
||||
|
||||
const BASE_URL_KEY = 'sub2api_base_url';
|
||||
const ADMIN_KEY_KEY = 'sub2api_admin_api_key';
|
||||
const ACCOUNTS_KEY = 'sub2api_accounts';
|
||||
const ACTIVE_ACCOUNT_ID_KEY = 'sub2api_active_account_id';
|
||||
|
||||
export type AdminAccountProfile = {
|
||||
id: string;
|
||||
label: string;
|
||||
baseUrl: string;
|
||||
adminApiKey: string;
|
||||
updatedAt: string;
|
||||
enabled?: boolean;
|
||||
};
|
||||
|
||||
function createAccountId() {
|
||||
return `acct_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
||||
}
|
||||
|
||||
function getAccountLabel(baseUrl: string) {
|
||||
try {
|
||||
const url = new URL(baseUrl);
|
||||
return url.host || baseUrl;
|
||||
} catch {
|
||||
return baseUrl;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeConfig(input: { baseUrl: string; adminApiKey: string }) {
|
||||
return {
|
||||
baseUrl: input.baseUrl.trim().replace(/\/$/, ''),
|
||||
adminApiKey: input.adminApiKey.trim(),
|
||||
};
|
||||
}
|
||||
|
||||
function sortAccounts(accounts: AdminAccountProfile[]) {
|
||||
return [...accounts].sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
|
||||
}
|
||||
|
||||
function normalizeAccount(account: AdminAccountProfile): AdminAccountProfile {
|
||||
return {
|
||||
...account,
|
||||
enabled: account.enabled ?? true,
|
||||
};
|
||||
}
|
||||
|
||||
function getNextActiveAccount(accounts: AdminAccountProfile[], activeAccountId?: string) {
|
||||
const enabledAccounts = accounts.filter((account) => account.enabled !== false);
|
||||
|
||||
if (activeAccountId) {
|
||||
const preferred = enabledAccounts.find((account) => account.id === activeAccountId);
|
||||
if (preferred) {
|
||||
return preferred;
|
||||
}
|
||||
}
|
||||
|
||||
return enabledAccounts[0];
|
||||
}
|
||||
|
||||
export function getDefaultAdminConfig() {
|
||||
return {
|
||||
@@ -35,37 +90,197 @@ async function setItem(key: string, value: string) {
|
||||
await SecureStore.setItemAsync(key, value);
|
||||
}
|
||||
|
||||
async function deleteItem(key: string) {
|
||||
if (typeof window !== 'undefined') {
|
||||
if (typeof localStorage !== 'undefined') {
|
||||
localStorage.removeItem(key);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
await SecureStore.deleteItemAsync(key);
|
||||
}
|
||||
|
||||
export const adminConfigState = proxy({
|
||||
...getDefaultAdminConfig(),
|
||||
accounts: [] as AdminAccountProfile[],
|
||||
activeAccountId: '',
|
||||
hydrated: false,
|
||||
saving: false,
|
||||
});
|
||||
|
||||
export async function hydrateAdminConfig() {
|
||||
const defaults = getDefaultAdminConfig();
|
||||
const [baseUrl, adminApiKey] = await Promise.all([
|
||||
const [baseUrl, adminApiKey, rawAccounts, activeAccountId] = await Promise.all([
|
||||
getItem(BASE_URL_KEY),
|
||||
getItem(ADMIN_KEY_KEY),
|
||||
getItem(ACCOUNTS_KEY),
|
||||
getItem(ACTIVE_ACCOUNT_ID_KEY),
|
||||
]);
|
||||
|
||||
adminConfigState.baseUrl = baseUrl ?? defaults.baseUrl;
|
||||
adminConfigState.adminApiKey = adminApiKey ?? defaults.adminApiKey;
|
||||
let accounts: AdminAccountProfile[] = [];
|
||||
|
||||
if (rawAccounts) {
|
||||
try {
|
||||
const parsed = JSON.parse(rawAccounts) as AdminAccountProfile[];
|
||||
accounts = Array.isArray(parsed) ? parsed.map((account) => normalizeAccount(account)) : [];
|
||||
} catch {
|
||||
accounts = [];
|
||||
}
|
||||
}
|
||||
|
||||
if (accounts.length === 0 && baseUrl) {
|
||||
const legacyConfig = normalizeConfig({
|
||||
baseUrl,
|
||||
adminApiKey: adminApiKey ?? defaults.adminApiKey,
|
||||
});
|
||||
|
||||
accounts = [
|
||||
{
|
||||
id: createAccountId(),
|
||||
label: getAccountLabel(legacyConfig.baseUrl),
|
||||
...legacyConfig,
|
||||
updatedAt: new Date().toISOString(),
|
||||
enabled: true,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const sortedAccounts = sortAccounts(accounts);
|
||||
const activeAccount = getNextActiveAccount(sortedAccounts, activeAccountId ?? undefined);
|
||||
const nextActiveAccountId = activeAccount?.id || '';
|
||||
|
||||
adminConfigState.accounts = sortedAccounts;
|
||||
adminConfigState.activeAccountId = nextActiveAccountId;
|
||||
adminConfigState.baseUrl = activeAccount?.baseUrl ?? defaults.baseUrl;
|
||||
adminConfigState.adminApiKey = activeAccount?.adminApiKey ?? defaults.adminApiKey;
|
||||
|
||||
adminConfigState.hydrated = true;
|
||||
|
||||
await Promise.all([
|
||||
setItem(ACCOUNTS_KEY, JSON.stringify(sortedAccounts)),
|
||||
nextActiveAccountId ? setItem(ACTIVE_ACCOUNT_ID_KEY, nextActiveAccountId) : deleteItem(ACTIVE_ACCOUNT_ID_KEY),
|
||||
setItem(BASE_URL_KEY, activeAccount?.baseUrl ?? defaults.baseUrl),
|
||||
setItem(ADMIN_KEY_KEY, activeAccount?.adminApiKey ?? defaults.adminApiKey),
|
||||
]);
|
||||
}
|
||||
|
||||
export async function saveAdminConfig(input: { baseUrl: string; adminApiKey: string }) {
|
||||
adminConfigState.saving = true;
|
||||
|
||||
const nextBaseUrl = input.baseUrl.trim().replace(/\/$/, '');
|
||||
const nextAdminApiKey = input.adminApiKey.trim();
|
||||
|
||||
await Promise.all([
|
||||
setItem(BASE_URL_KEY, nextBaseUrl),
|
||||
setItem(ADMIN_KEY_KEY, nextAdminApiKey),
|
||||
const normalized = normalizeConfig(input);
|
||||
const nextUpdatedAt = new Date().toISOString();
|
||||
const existingAccount = adminConfigState.accounts.find(
|
||||
(account: AdminAccountProfile) => account.baseUrl === normalized.baseUrl && account.adminApiKey === normalized.adminApiKey
|
||||
);
|
||||
const nextAccount: AdminAccountProfile = existingAccount
|
||||
? {
|
||||
...existingAccount,
|
||||
label: getAccountLabel(normalized.baseUrl),
|
||||
updatedAt: nextUpdatedAt,
|
||||
}
|
||||
: {
|
||||
id: createAccountId(),
|
||||
label: getAccountLabel(normalized.baseUrl),
|
||||
...normalized,
|
||||
updatedAt: nextUpdatedAt,
|
||||
enabled: true,
|
||||
};
|
||||
const nextAccounts = sortAccounts([
|
||||
nextAccount,
|
||||
...adminConfigState.accounts.filter((account: AdminAccountProfile) => account.id !== nextAccount.id),
|
||||
]);
|
||||
|
||||
adminConfigState.baseUrl = nextBaseUrl;
|
||||
adminConfigState.adminApiKey = nextAdminApiKey;
|
||||
await Promise.all([
|
||||
setItem(BASE_URL_KEY, normalized.baseUrl),
|
||||
setItem(ADMIN_KEY_KEY, normalized.adminApiKey),
|
||||
setItem(ACCOUNTS_KEY, JSON.stringify(nextAccounts)),
|
||||
setItem(ACTIVE_ACCOUNT_ID_KEY, nextAccount.id),
|
||||
]);
|
||||
|
||||
adminConfigState.accounts = nextAccounts;
|
||||
adminConfigState.activeAccountId = nextAccount.id;
|
||||
adminConfigState.baseUrl = normalized.baseUrl;
|
||||
adminConfigState.adminApiKey = normalized.adminApiKey;
|
||||
adminConfigState.saving = false;
|
||||
}
|
||||
|
||||
export async function switchAdminAccount(accountId: string) {
|
||||
const account = adminConfigState.accounts.find((item: AdminAccountProfile) => item.id === accountId);
|
||||
|
||||
if (!account) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (account.enabled === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextAccount = {
|
||||
...account,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
const nextAccounts = sortAccounts([
|
||||
nextAccount,
|
||||
...adminConfigState.accounts.filter((item: AdminAccountProfile) => item.id !== accountId),
|
||||
]);
|
||||
|
||||
await Promise.all([
|
||||
setItem(BASE_URL_KEY, nextAccount.baseUrl),
|
||||
setItem(ADMIN_KEY_KEY, nextAccount.adminApiKey),
|
||||
setItem(ACCOUNTS_KEY, JSON.stringify(nextAccounts)),
|
||||
setItem(ACTIVE_ACCOUNT_ID_KEY, nextAccount.id),
|
||||
]);
|
||||
|
||||
adminConfigState.accounts = nextAccounts;
|
||||
adminConfigState.activeAccountId = nextAccount.id;
|
||||
adminConfigState.baseUrl = nextAccount.baseUrl;
|
||||
adminConfigState.adminApiKey = nextAccount.adminApiKey;
|
||||
}
|
||||
|
||||
export async function removeAdminAccount(accountId: string) {
|
||||
const nextAccounts = adminConfigState.accounts.filter((item: AdminAccountProfile) => item.id !== accountId);
|
||||
const nextActiveAccount = getNextActiveAccount(nextAccounts, adminConfigState.activeAccountId === accountId ? '' : adminConfigState.activeAccountId);
|
||||
|
||||
await Promise.all([
|
||||
setItem(ACCOUNTS_KEY, JSON.stringify(nextAccounts)),
|
||||
nextActiveAccount ? setItem(ACTIVE_ACCOUNT_ID_KEY, nextActiveAccount.id) : deleteItem(ACTIVE_ACCOUNT_ID_KEY),
|
||||
setItem(BASE_URL_KEY, nextActiveAccount?.baseUrl ?? ''),
|
||||
setItem(ADMIN_KEY_KEY, nextActiveAccount?.adminApiKey ?? ''),
|
||||
]);
|
||||
|
||||
adminConfigState.accounts = nextAccounts;
|
||||
adminConfigState.activeAccountId = nextActiveAccount?.id ?? '';
|
||||
adminConfigState.baseUrl = nextActiveAccount?.baseUrl ?? '';
|
||||
adminConfigState.adminApiKey = nextActiveAccount?.adminApiKey ?? '';
|
||||
}
|
||||
|
||||
export async function logoutAdminAccount() {
|
||||
await Promise.all([setItem(BASE_URL_KEY, ''), setItem(ADMIN_KEY_KEY, ''), deleteItem(ACTIVE_ACCOUNT_ID_KEY)]);
|
||||
|
||||
adminConfigState.activeAccountId = '';
|
||||
adminConfigState.baseUrl = '';
|
||||
adminConfigState.adminApiKey = '';
|
||||
}
|
||||
|
||||
export async function setAdminAccountEnabled(accountId: string, enabled: boolean) {
|
||||
const nextAccounts = sortAccounts(
|
||||
adminConfigState.accounts.map((account: AdminAccountProfile) =>
|
||||
account.id === accountId ? { ...account, enabled, updatedAt: new Date().toISOString() } : account
|
||||
)
|
||||
);
|
||||
const nextActiveAccount = getNextActiveAccount(nextAccounts, enabled ? accountId : adminConfigState.activeAccountId);
|
||||
|
||||
await Promise.all([
|
||||
setItem(ACCOUNTS_KEY, JSON.stringify(nextAccounts)),
|
||||
nextActiveAccount ? setItem(ACTIVE_ACCOUNT_ID_KEY, nextActiveAccount.id) : deleteItem(ACTIVE_ACCOUNT_ID_KEY),
|
||||
setItem(BASE_URL_KEY, nextActiveAccount?.baseUrl ?? ''),
|
||||
setItem(ADMIN_KEY_KEY, nextActiveAccount?.adminApiKey ?? ''),
|
||||
]);
|
||||
|
||||
adminConfigState.accounts = nextAccounts;
|
||||
adminConfigState.activeAccountId = nextActiveAccount?.id ?? '';
|
||||
adminConfigState.baseUrl = nextActiveAccount?.baseUrl ?? '';
|
||||
adminConfigState.adminApiKey = nextActiveAccount?.adminApiKey ?? '';
|
||||
}
|
||||
|
||||