mirror of
https://gitee.com/wanwujie/sub2api-mobile
synced 2026-04-02 22:42:14 +08:00
feat: bootstrap v2 admin app tabs
This commit is contained in:
30
.gitignore
vendored
30
.gitignore
vendored
@@ -33,6 +33,36 @@ yarn-error.*
|
|||||||
# local env files
|
# local env files
|
||||||
.env*.local
|
.env*.local
|
||||||
|
|
||||||
|
# local AI tooling
|
||||||
|
.adal/
|
||||||
|
.agent/
|
||||||
|
.agents/
|
||||||
|
.augment/
|
||||||
|
.claude/
|
||||||
|
.codebuddy/
|
||||||
|
.commandcode/
|
||||||
|
.continue/
|
||||||
|
.crush/
|
||||||
|
.factory/
|
||||||
|
.goose/
|
||||||
|
.junie/
|
||||||
|
.kilocode/
|
||||||
|
.kiro/
|
||||||
|
.kode/
|
||||||
|
.mcpjam/
|
||||||
|
.mux/
|
||||||
|
.neovate/
|
||||||
|
.openhands/
|
||||||
|
.pi/
|
||||||
|
.pochi/
|
||||||
|
.qoder/
|
||||||
|
.qwen/
|
||||||
|
.roo/
|
||||||
|
.trae/
|
||||||
|
.vibe/
|
||||||
|
.windsurf/
|
||||||
|
.zencoder/
|
||||||
|
|
||||||
# typescript
|
# typescript
|
||||||
*.tsbuildinfo
|
*.tsbuildinfo
|
||||||
|
|
||||||
|
|||||||
20
App.tsx
20
App.tsx
@@ -1,20 +0,0 @@
|
|||||||
import { StatusBar } from 'expo-status-bar';
|
|
||||||
import { StyleSheet, Text, View } from 'react-native';
|
|
||||||
|
|
||||||
export default function App() {
|
|
||||||
return (
|
|
||||||
<View style={styles.container}>
|
|
||||||
<Text>Open up App.tsx to start working on your app!</Text>
|
|
||||||
<StatusBar style="auto" />
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const styles = StyleSheet.create({
|
|
||||||
container: {
|
|
||||||
flex: 1,
|
|
||||||
backgroundColor: '#fff',
|
|
||||||
alignItems: 'center',
|
|
||||||
justifyContent: 'center',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
6
app.json
6
app.json
@@ -25,6 +25,10 @@
|
|||||||
},
|
},
|
||||||
"web": {
|
"web": {
|
||||||
"favicon": "./assets/favicon.png"
|
"favicon": "./assets/favicon.png"
|
||||||
}
|
},
|
||||||
|
"plugins": [
|
||||||
|
"expo-router",
|
||||||
|
"expo-secure-store"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
47
app/(tabs)/_layout.tsx
Normal file
47
app/(tabs)/_layout.tsx
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
import { Tabs } from 'expo-router';
|
||||||
|
import { ActivitySquare, ChartNoAxesCombined, Users } from 'lucide-react-native';
|
||||||
|
|
||||||
|
export default function TabsLayout() {
|
||||||
|
return (
|
||||||
|
<Tabs
|
||||||
|
screenOptions={{
|
||||||
|
headerShown: false,
|
||||||
|
tabBarActiveTintColor: '#1d5f55',
|
||||||
|
tabBarInactiveTintColor: '#8a8072',
|
||||||
|
tabBarStyle: {
|
||||||
|
backgroundColor: '#fbf8f2',
|
||||||
|
borderTopWidth: 0,
|
||||||
|
height: 84,
|
||||||
|
paddingTop: 10,
|
||||||
|
paddingBottom: 18,
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Tabs.Screen
|
||||||
|
name="index"
|
||||||
|
options={{
|
||||||
|
title: '概览',
|
||||||
|
tabBarIcon: ({ color, size }) => <ChartNoAxesCombined color={color} size={size} />,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Tabs.Screen
|
||||||
|
name="users"
|
||||||
|
options={{
|
||||||
|
title: '用户',
|
||||||
|
tabBarIcon: ({ color, size }) => <Users color={color} size={size} />,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Tabs.Screen
|
||||||
|
name="monitor"
|
||||||
|
options={{
|
||||||
|
title: '运维监控',
|
||||||
|
tabBarIcon: ({ color, size }) => <ActivitySquare 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 }} />
|
||||||
|
</Tabs>
|
||||||
|
);
|
||||||
|
}
|
||||||
89
app/(tabs)/accounts.tsx
Normal file
89
app/(tabs)/accounts.tsx
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
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 { ListCard } from '@/src/components/list-card';
|
||||||
|
import { ScreenShell } from '@/src/components/screen-shell';
|
||||||
|
import { listAccounts, setAccountSchedulable, testAccount } from '@/src/services/admin';
|
||||||
|
|
||||||
|
export default function AccountsScreen() {
|
||||||
|
const [search, setSearch] = useState('');
|
||||||
|
const keyword = useMemo(() => search.trim(), [search]);
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
const accountsQuery = useQuery({
|
||||||
|
queryKey: ['accounts', keyword],
|
||||||
|
queryFn: () => listAccounts(keyword),
|
||||||
|
});
|
||||||
|
|
||||||
|
const toggleMutation = useMutation({
|
||||||
|
mutationFn: ({ accountId, schedulable }: { accountId: number; schedulable: boolean }) =>
|
||||||
|
setAccountSchedulable(accountId, schedulable),
|
||||||
|
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['accounts'] }),
|
||||||
|
});
|
||||||
|
|
||||||
|
const items = accountsQuery.data?.items ?? [];
|
||||||
|
const errorMessage = accountsQuery.error instanceof Error ? accountsQuery.error.message : '';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ScreenShell title="API 密钥" subtitle="管理您的 API 密钥和访问令牌">
|
||||||
|
<View className="flex-row items-center rounded-[24px] bg-[#fbf8f2] px-4 py-3">
|
||||||
|
<Search color="#7d7468" size={18} />
|
||||||
|
<TextInput
|
||||||
|
value={search}
|
||||||
|
onChangeText={setSearch}
|
||||||
|
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}`)}>
|
||||||
|
<ListCard
|
||||||
|
title={account.name}
|
||||||
|
meta={`${account.platform} · ${account.type} · 优先级 ${account.priority ?? 0}`}
|
||||||
|
badge={account.status || 'unknown'}
|
||||||
|
icon={KeyRound}
|
||||||
|
>
|
||||||
|
<View className="flex-row items-center justify-between">
|
||||||
|
<View className="flex-row items-center gap-2">
|
||||||
|
{account.schedulable ? <ShieldCheck color="#7d7468" size={14} /> : <ShieldOff color="#7d7468" size={14} />}
|
||||||
|
<Text className="text-sm text-[#7d7468]">{account.schedulable ? '可调度' : '暂停调度'}</Text>
|
||||||
|
</View>
|
||||||
|
<View className="flex-row gap-2">
|
||||||
|
<Pressable
|
||||||
|
className="rounded-full bg-[#1b1d1f] px-4 py-2"
|
||||||
|
onPress={(event) => {
|
||||||
|
event.stopPropagation();
|
||||||
|
testAccount(account.id).catch(() => undefined);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Text className="text-xs font-semibold uppercase tracking-[1.2px] text-[#f6f1e8]">测试</Text>
|
||||||
|
</Pressable>
|
||||||
|
<Pressable
|
||||||
|
className="rounded-full bg-[#e7dfcf] px-4 py-2"
|
||||||
|
onPress={(event) => {
|
||||||
|
event.stopPropagation();
|
||||||
|
toggleMutation.mutate({
|
||||||
|
accountId: account.id,
|
||||||
|
schedulable: !account.schedulable,
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Text className="text-xs font-semibold uppercase tracking-[1.2px] text-[#4e463e]">切换</Text>
|
||||||
|
</Pressable>
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
</ListCard>
|
||||||
|
</Pressable>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</ScreenShell>
|
||||||
|
);
|
||||||
|
}
|
||||||
57
app/(tabs)/groups.tsx
Normal file
57
app/(tabs)/groups.tsx
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
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 { ListCard } from '@/src/components/list-card';
|
||||||
|
import { ScreenShell } from '@/src/components/screen-shell';
|
||||||
|
import { listGroups } from '@/src/services/admin';
|
||||||
|
|
||||||
|
export default function GroupsScreen() {
|
||||||
|
const [search, setSearch] = useState('');
|
||||||
|
const keyword = useMemo(() => search.trim(), [search]);
|
||||||
|
|
||||||
|
const groupsQuery = useQuery({
|
||||||
|
queryKey: ['groups', keyword],
|
||||||
|
queryFn: () => listGroups(keyword),
|
||||||
|
});
|
||||||
|
|
||||||
|
const items = groupsQuery.data?.items ?? [];
|
||||||
|
const errorMessage = groupsQuery.error instanceof Error ? groupsQuery.error.message : '';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ScreenShell title="分组管理" subtitle="分组决定调度、价格倍率和账号归属,是后台的核心配置之一。">
|
||||||
|
<View className="flex-row items-center rounded-[24px] bg-[#fbf8f2] px-4 py-3">
|
||||||
|
<Search color="#7d7468" size={18} />
|
||||||
|
<TextInput
|
||||||
|
value={search}
|
||||||
|
onChangeText={setSearch}
|
||||||
|
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) => (
|
||||||
|
<ListCard
|
||||||
|
key={group.id}
|
||||||
|
title={group.name}
|
||||||
|
meta={`${group.platform} · 倍率 ${group.rate_multiplier ?? 1} · ${group.subscription_type || 'standard'}`}
|
||||||
|
badge={group.status || 'active'}
|
||||||
|
icon={FolderKanban}
|
||||||
|
>
|
||||||
|
<View className="flex-row items-center gap-2">
|
||||||
|
<Layers3 color="#7d7468" size={14} />
|
||||||
|
<Text className="text-sm text-[#7d7468]">
|
||||||
|
账号数 {group.account_count ?? 0} · {group.is_exclusive ? '独占分组' : '共享分组'}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
</ListCard>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</ScreenShell>
|
||||||
|
);
|
||||||
|
}
|
||||||
101
app/(tabs)/index.tsx
Normal file
101
app/(tabs)/index.tsx
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { Activity, Coins, RefreshCw, Rows3, Zap } from 'lucide-react-native';
|
||||||
|
import { Pressable, Text, View } from 'react-native';
|
||||||
|
|
||||||
|
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>
|
||||||
|
);
|
||||||
|
}
|
||||||
105
app/(tabs)/monitor.tsx
Normal file
105
app/(tabs)/monitor.tsx
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { AlertTriangle, Gauge, Layers3, Wrench } from 'lucide-react-native';
|
||||||
|
import { Text, View } from 'react-native';
|
||||||
|
|
||||||
|
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';
|
||||||
|
|
||||||
|
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 MonitorScreen() {
|
||||||
|
const range = getDateRange();
|
||||||
|
|
||||||
|
const statsQuery = useQuery({
|
||||||
|
queryKey: ['monitor-stats'],
|
||||||
|
queryFn: getDashboardStats,
|
||||||
|
});
|
||||||
|
|
||||||
|
const trendQuery = useQuery({
|
||||||
|
queryKey: ['monitor-trend', range.start_date, range.end_date],
|
||||||
|
queryFn: () => getDashboardTrend({ ...range, granularity: 'day' }),
|
||||||
|
});
|
||||||
|
|
||||||
|
const modelsQuery = useQuery({
|
||||||
|
queryKey: ['monitor-models', range.start_date, range.end_date],
|
||||||
|
queryFn: () => getDashboardModels(range),
|
||||||
|
});
|
||||||
|
|
||||||
|
const accountsQuery = useQuery({
|
||||||
|
queryKey: ['monitor-accounts'],
|
||||||
|
queryFn: () => listAccounts(''),
|
||||||
|
});
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
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 ? (
|
||||||
|
<LineTrendChart
|
||||||
|
title="Token 监控"
|
||||||
|
subtitle="最近 7 天总 token 吞吐"
|
||||||
|
points={trendPoints}
|
||||||
|
color="#a34d2d"
|
||||||
|
formatValue={(value) => `${Math.round(value / 1000)}k`}
|
||||||
|
/>
|
||||||
|
) : 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>
|
||||||
|
|
||||||
|
<ListCard title="排障列表" meta="优先关注状态异常或带错误信息的上游账号" icon={Wrench}>
|
||||||
|
<View className="gap-3">
|
||||||
|
{incidentAccounts.map((item) => (
|
||||||
|
<View key={item.id} className="rounded-[18px] bg-[#f1ece2] px-4 py-3">
|
||||||
|
<Text className="text-sm font-semibold text-[#16181a]">{item.name}</Text>
|
||||||
|
<Text className="mt-1 text-xs text-[#7d7468]">{item.platform} · {item.status || 'unknown'} · {item.schedulable ? '可调度' : '暂停调度'}</Text>
|
||||||
|
<Text className="mt-2 text-xs text-[#a34d2d]">{item.error_message || '状态异常,建议从运维视角继续排查这个上游账号'}</Text>
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
|
{incidentAccounts.length === 0 ? <Text className="text-sm text-[#7d7468]">当前没有检测到异常账号。</Text> : null}
|
||||||
|
</View>
|
||||||
|
</ListCard>
|
||||||
|
</ScreenShell>
|
||||||
|
);
|
||||||
|
}
|
||||||
57
app/(tabs)/users.tsx
Normal file
57
app/(tabs)/users.tsx
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { Activity, 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 { ListCard } from '@/src/components/list-card';
|
||||||
|
import { ScreenShell } from '@/src/components/screen-shell';
|
||||||
|
import { listUsers } from '@/src/services/admin';
|
||||||
|
|
||||||
|
export default function UsersScreen() {
|
||||||
|
const [search, setSearch] = useState('');
|
||||||
|
const keyword = useMemo(() => search.trim(), [search]);
|
||||||
|
|
||||||
|
const usersQuery = useQuery({
|
||||||
|
queryKey: ['users', keyword],
|
||||||
|
queryFn: () => listUsers(keyword),
|
||||||
|
});
|
||||||
|
|
||||||
|
const items = usersQuery.data?.items ?? [];
|
||||||
|
const errorMessage = usersQuery.error instanceof Error ? usersQuery.error.message : '';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ScreenShell title="用户管理" subtitle="搜索用户、查看详情,并在详情页里做余额调整。">
|
||||||
|
<View className="flex-row items-center rounded-[24px] bg-[#fbf8f2] px-4 py-3">
|
||||||
|
<Search color="#7d7468" size={18} />
|
||||||
|
<TextInput
|
||||||
|
value={search}
|
||||||
|
onChangeText={setSearch}
|
||||||
|
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}
|
||||||
|
>
|
||||||
|
<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>
|
||||||
|
</Pressable>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</ScreenShell>
|
||||||
|
);
|
||||||
|
}
|
||||||
41
app/_layout.tsx
Normal file
41
app/_layout.tsx
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
import '@/src/global.css';
|
||||||
|
|
||||||
|
import { QueryClientProvider } from '@tanstack/react-query';
|
||||||
|
import { Stack } from 'expo-router';
|
||||||
|
import { useEffect } from 'react';
|
||||||
|
import { ActivityIndicator, View } from 'react-native';
|
||||||
|
import { GestureHandlerRootView } from 'react-native-gesture-handler';
|
||||||
|
|
||||||
|
import { queryClient } from '@/src/lib/query-client';
|
||||||
|
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);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const isReady = config.hydrated;
|
||||||
|
const isAuthenticated = Boolean(config.baseUrl.trim() && config.adminApiKey.trim());
|
||||||
|
|
||||||
|
return (
|
||||||
|
<GestureHandlerRootView style={{ flex: 1 }}>
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
{!isReady ? (
|
||||||
|
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: '#f4efe4' }}>
|
||||||
|
<ActivityIndicator color="#1d5f55" />
|
||||||
|
</View>
|
||||||
|
) : (
|
||||||
|
<Stack screenOptions={{ headerShown: false }}>
|
||||||
|
{isAuthenticated ? <Stack.Screen name="(tabs)" /> : <Stack.Screen name="login" />}
|
||||||
|
<Stack.Screen name="users/[id]" />
|
||||||
|
<Stack.Screen name="accounts/[id]" options={{ presentation: 'card' }} />
|
||||||
|
</Stack>
|
||||||
|
)}
|
||||||
|
</QueryClientProvider>
|
||||||
|
</GestureHandlerRootView>
|
||||||
|
);
|
||||||
|
}
|
||||||
123
app/accounts/[id].tsx
Normal file
123
app/accounts/[id].tsx
Normal file
@@ -0,0 +1,123 @@
|
|||||||
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { ChevronLeft, ShieldCheck, TestTubeDiagonal } from 'lucide-react-native';
|
||||||
|
import { router, useLocalSearchParams } from 'expo-router';
|
||||||
|
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 { ScreenShell } from '@/src/components/screen-shell';
|
||||||
|
import { getAccount, getAccountTodayStats, getDashboardTrend, refreshAccount, 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 AccountDetailScreen() {
|
||||||
|
const { id } = useLocalSearchParams<{ id: string }>();
|
||||||
|
const accountId = Number(id);
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const range = getDateRange();
|
||||||
|
|
||||||
|
const accountQuery = useQuery({
|
||||||
|
queryKey: ['account', accountId],
|
||||||
|
queryFn: () => getAccount(accountId),
|
||||||
|
enabled: Number.isFinite(accountId),
|
||||||
|
});
|
||||||
|
|
||||||
|
const todayStatsQuery = useQuery({
|
||||||
|
queryKey: ['account-today-stats', accountId],
|
||||||
|
queryFn: () => getAccountTodayStats(accountId),
|
||||||
|
enabled: Number.isFinite(accountId),
|
||||||
|
});
|
||||||
|
|
||||||
|
const trendQuery = useQuery({
|
||||||
|
queryKey: ['account-trend', accountId, range.start_date, range.end_date],
|
||||||
|
queryFn: () => getDashboardTrend({ ...range, granularity: 'day', account_id: accountId }),
|
||||||
|
enabled: Number.isFinite(accountId),
|
||||||
|
});
|
||||||
|
|
||||||
|
const refreshMutation = useMutation({
|
||||||
|
mutationFn: () => refreshAccount(accountId),
|
||||||
|
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['account', accountId] }),
|
||||||
|
});
|
||||||
|
|
||||||
|
const schedulableMutation = useMutation({
|
||||||
|
mutationFn: (schedulable: boolean) => setAccountSchedulable(accountId, schedulable),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['account', accountId] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['accounts'] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const account = accountQuery.data;
|
||||||
|
const todayStats = todayStatsQuery.data;
|
||||||
|
const trendPoints = (trendQuery.data?.trend ?? []).map((item) => ({
|
||||||
|
label: item.date.slice(5),
|
||||||
|
value: item.total_tokens,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ScreenShell
|
||||||
|
title={account?.name || '账号详情'}
|
||||||
|
subtitle="聚焦账号 token 用量、状态和几个最常用操作。"
|
||||||
|
right={
|
||||||
|
<Pressable className="h-11 w-11 items-center justify-center rounded-full bg-[#2d3134]" onPress={() => router.back()}>
|
||||||
|
<ChevronLeft color="#f6f1e8" size={18} />
|
||||||
|
</Pressable>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<ListCard title="基本信息" meta={`${account?.platform || '--'} · ${account?.type || '--'}`} badge={account?.status || 'loading'}>
|
||||||
|
<DetailRow label="可调度" value={account?.schedulable ? '是' : '否'} />
|
||||||
|
<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 || '--'} />
|
||||||
|
</ListCard>
|
||||||
|
|
||||||
|
<ListCard title="今日统计" meta="真实数据来自 /accounts/:id/today-stats" icon={ShieldCheck}>
|
||||||
|
<DetailRow label="Token" value={`${todayStats?.tokens ?? 0}`} />
|
||||||
|
<DetailRow label="请求数" value={`${todayStats?.requests ?? 0}`} />
|
||||||
|
<DetailRow label="成本" value={`$${Number(todayStats?.cost ?? 0).toFixed(4)}`} />
|
||||||
|
</ListCard>
|
||||||
|
|
||||||
|
{trendPoints.length > 1 ? (
|
||||||
|
<LineTrendChart
|
||||||
|
title="近 7 天 Token"
|
||||||
|
subtitle="按账号过滤后的真实 token 趋势"
|
||||||
|
points={trendPoints}
|
||||||
|
color="#c96d43"
|
||||||
|
formatValue={(value) => `${Math.round(value / 1000)}k`}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<ListCard title="快捷动作" meta="直接对单账号做测试、刷新和调度控制。" icon={TestTubeDiagonal}>
|
||||||
|
<View className="flex-row gap-3">
|
||||||
|
<Pressable className="flex-1 rounded-[18px] bg-[#1b1d1f] px-4 py-4" onPress={() => testAccount(accountId).catch(() => undefined)}>
|
||||||
|
<Text className="text-center text-sm font-semibold text-[#f6f1e8]">测试账号</Text>
|
||||||
|
</Pressable>
|
||||||
|
<Pressable className="flex-1 rounded-[18px] bg-[#e7dfcf] px-4 py-4" onPress={() => refreshMutation.mutate()}>
|
||||||
|
<Text className="text-center text-sm font-semibold text-[#4e463e]">{refreshMutation.isPending ? '刷新中...' : '刷新凭据'}</Text>
|
||||||
|
</Pressable>
|
||||||
|
</View>
|
||||||
|
<Pressable
|
||||||
|
className="mt-3 rounded-[18px] bg-[#1d5f55] px-4 py-4"
|
||||||
|
onPress={() => schedulableMutation.mutate(!account?.schedulable)}
|
||||||
|
>
|
||||||
|
<Text className="text-center text-sm font-semibold text-white">
|
||||||
|
{schedulableMutation.isPending ? '提交中...' : account?.schedulable ? '暂停调度' : '恢复调度'}
|
||||||
|
</Text>
|
||||||
|
</Pressable>
|
||||||
|
</ListCard>
|
||||||
|
</ScreenShell>
|
||||||
|
);
|
||||||
|
}
|
||||||
84
app/login.tsx
Normal file
84
app/login.tsx
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
|
import { Globe, KeyRound } from 'lucide-react-native';
|
||||||
|
import { Controller, useForm } from 'react-hook-form';
|
||||||
|
import { Pressable, Text, TextInput, View } from 'react-native';
|
||||||
|
import { 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';
|
||||||
|
|
||||||
|
const { useSnapshot } = require('valtio/react');
|
||||||
|
|
||||||
|
const schema = z.object({
|
||||||
|
baseUrl: z.string().min(1, '请输入 Host'),
|
||||||
|
adminApiKey: z.string().min(1, '请输入 Admin Token'),
|
||||||
|
});
|
||||||
|
|
||||||
|
type FormValues = z.infer<typeof schema>;
|
||||||
|
|
||||||
|
export default function LoginScreen() {
|
||||||
|
const config = useSnapshot(adminConfigState);
|
||||||
|
const { control, handleSubmit, formState } = useForm<FormValues>({
|
||||||
|
resolver: zodResolver(schema),
|
||||||
|
defaultValues: {
|
||||||
|
baseUrl: config.baseUrl,
|
||||||
|
adminApiKey: config.adminApiKey,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ScreenShell title="登录" subtitle="输入 host 和 adminToken 后开始管理。">
|
||||||
|
<ListCard title="Host" meta="当前站点或管理代理地址" icon={Globe}>
|
||||||
|
<Controller
|
||||||
|
control={control}
|
||||||
|
name="baseUrl"
|
||||||
|
render={({ field: { onChange, value } }) => (
|
||||||
|
<TextInput
|
||||||
|
value={value}
|
||||||
|
onChangeText={onChange}
|
||||||
|
placeholder="http://localhost:8787"
|
||||||
|
placeholderTextColor="#9b9081"
|
||||||
|
autoCapitalize="none"
|
||||||
|
className="rounded-[18px] bg-[#f1ece2] px-4 py-4 text-base text-[#16181a]"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</ListCard>
|
||||||
|
|
||||||
|
<ListCard title="Admin Token" meta="管理员 token" icon={KeyRound}>
|
||||||
|
<Controller
|
||||||
|
control={control}
|
||||||
|
name="adminApiKey"
|
||||||
|
render={({ field: { onChange, value } }) => (
|
||||||
|
<TextInput
|
||||||
|
value={value}
|
||||||
|
onChangeText={onChange}
|
||||||
|
placeholder="admin-xxxxxxxx"
|
||||||
|
placeholderTextColor="#9b9081"
|
||||||
|
autoCapitalize="none"
|
||||||
|
className="rounded-[18px] bg-[#f1ece2] px-4 py-4 text-base text-[#16181a]"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</ListCard>
|
||||||
|
|
||||||
|
{(formState.errors.baseUrl || formState.errors.adminApiKey) ? (
|
||||||
|
<View className="rounded-[20px] bg-[#fbf1eb] px-4 py-3">
|
||||||
|
<Text className="text-sm text-[#c25d35]">{formState.errors.baseUrl?.message || formState.errors.adminApiKey?.message}</Text>
|
||||||
|
</View>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<Pressable
|
||||||
|
className="rounded-[20px] bg-[#1d5f55] px-4 py-4"
|
||||||
|
onPress={handleSubmit(async (values) => {
|
||||||
|
await saveAdminConfig(values);
|
||||||
|
})}
|
||||||
|
>
|
||||||
|
<Text className="text-center text-sm font-semibold tracking-[1.2px] text-white">
|
||||||
|
{config.saving ? '登录中...' : '进入管理台'}
|
||||||
|
</Text>
|
||||||
|
</Pressable>
|
||||||
|
</ScreenShell>
|
||||||
|
);
|
||||||
|
}
|
||||||
240
app/users/[id].tsx
Normal file
240
app/users/[id].tsx
Normal file
@@ -0,0 +1,240 @@
|
|||||||
|
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 { router, useLocalSearchParams } from 'expo-router';
|
||||||
|
import { 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 { ScreenShell } from '@/src/components/screen-shell';
|
||||||
|
import { getUser, getUserUsage, listUserApiKeys, updateUserBalance } from '@/src/services/admin';
|
||||||
|
import type { BalanceOperation } from '@/src/types/admin';
|
||||||
|
|
||||||
|
const schema = z.object({
|
||||||
|
amount: z.string().min(1, '请输入金额'),
|
||||||
|
notes: z.string().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
type FormValues = z.infer<typeof schema>;
|
||||||
|
|
||||||
|
export default function UserDetailScreen() {
|
||||||
|
const { id } = useLocalSearchParams<{ id: string }>();
|
||||||
|
const userId = Number(id);
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const [operation, setOperation] = useState<BalanceOperation>('add');
|
||||||
|
const [keySearch, setKeySearch] = useState('');
|
||||||
|
const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'inactive'>('all');
|
||||||
|
const [visibleKeys, setVisibleKeys] = useState<Record<number, boolean>>({});
|
||||||
|
const [copiedKeyId, setCopiedKeyId] = useState<number | null>(null);
|
||||||
|
const { control, handleSubmit, reset, formState } = useForm<FormValues>({
|
||||||
|
resolver: zodResolver(schema),
|
||||||
|
defaultValues: {
|
||||||
|
amount: '10',
|
||||||
|
notes: '',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const userQuery = useQuery({
|
||||||
|
queryKey: ['user', userId],
|
||||||
|
queryFn: () => getUser(userId),
|
||||||
|
enabled: Number.isFinite(userId),
|
||||||
|
});
|
||||||
|
|
||||||
|
const usageQuery = useQuery({
|
||||||
|
queryKey: ['user-usage', userId],
|
||||||
|
queryFn: () => getUserUsage(userId),
|
||||||
|
enabled: Number.isFinite(userId),
|
||||||
|
});
|
||||||
|
|
||||||
|
const apiKeysQuery = useQuery({
|
||||||
|
queryKey: ['user-api-keys', userId],
|
||||||
|
queryFn: () => listUserApiKeys(userId),
|
||||||
|
enabled: Number.isFinite(userId),
|
||||||
|
});
|
||||||
|
|
||||||
|
const balanceMutation = useMutation({
|
||||||
|
mutationFn: (values: FormValues & { operation: BalanceOperation }) =>
|
||||||
|
updateUserBalance(userId, {
|
||||||
|
balance: Number(values.amount),
|
||||||
|
operation: values.operation,
|
||||||
|
notes: values.notes,
|
||||||
|
}),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['user', userId] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['users'] });
|
||||||
|
reset({ amount: '10', notes: '' });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const user = userQuery.data;
|
||||||
|
const usage = usageQuery.data;
|
||||||
|
const apiKeys = apiKeysQuery.data?.items ?? [];
|
||||||
|
const filteredApiKeys = apiKeys.filter((item) => {
|
||||||
|
const matchesStatus = statusFilter === 'all' ? true : item.status === statusFilter;
|
||||||
|
const keyword = keySearch.trim().toLowerCase();
|
||||||
|
const matchesSearch = !keyword
|
||||||
|
? true
|
||||||
|
: [item.name, item.key, item.group?.name]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(' ')
|
||||||
|
.toLowerCase()
|
||||||
|
.includes(keyword);
|
||||||
|
|
||||||
|
return matchesStatus && matchesSearch;
|
||||||
|
});
|
||||||
|
|
||||||
|
function maskKey(value: string) {
|
||||||
|
if (!value || value.length < 16) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
return `${value.slice(0, 8)}••••••${value.slice(-8)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copyKey(keyId: number, value: string) {
|
||||||
|
await Clipboard.setStringAsync(value);
|
||||||
|
setCopiedKeyId(keyId);
|
||||||
|
setTimeout(() => setCopiedKeyId((current) => (current === keyId ? null : current)), 1600);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ScreenShell
|
||||||
|
title={user?.username || user?.email || '用户详情'}
|
||||||
|
subtitle="核心看余额和 token 用量,其他内容尽量保持轻量。"
|
||||||
|
right={
|
||||||
|
<Pressable className="h-11 w-11 items-center justify-center rounded-full bg-[#2d3134]" onPress={() => router.back()}>
|
||||||
|
<ChevronLeft color="#f6f1e8" size={18} />
|
||||||
|
</Pressable>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<ListCard title="基本信息" meta={user?.email} badge={user?.status || 'loading'} icon={Wallet}>
|
||||||
|
<DetailRow label="角色" value={user?.role || '--'} />
|
||||||
|
<DetailRow label="余额" value={Number(user?.balance ?? 0).toFixed(2)} />
|
||||||
|
<DetailRow label="并发" value={`${user?.concurrency ?? 0}`} />
|
||||||
|
<DetailRow label="更新时间" value={user?.updated_at || '--'} />
|
||||||
|
</ListCard>
|
||||||
|
|
||||||
|
<ListCard title="月度用量" meta="真实数据来自 /users/:id/usage" icon={ArrowLeftRight}>
|
||||||
|
<DetailRow label="Token" value={`${Number(usage?.tokens ?? usage?.total_tokens ?? 0)}`} />
|
||||||
|
<DetailRow label="请求数" value={`${Number(usage?.requests ?? usage?.total_requests ?? 0)}`} />
|
||||||
|
<DetailRow label="成本" value={`$${Number(usage?.cost ?? usage?.total_cost ?? 0).toFixed(4)}`} />
|
||||||
|
</ListCard>
|
||||||
|
|
||||||
|
<ListCard title="API 密钥" meta="直接聚合管理员 /users/:id/api-keys" icon={KeyRound}>
|
||||||
|
<View className="gap-3">
|
||||||
|
<View className="flex-row items-center rounded-[18px] bg-[#f1ece2] px-4 py-3">
|
||||||
|
<Search color="#7d7468" size={16} />
|
||||||
|
<TextInput
|
||||||
|
value={keySearch}
|
||||||
|
onChangeText={setKeySearch}
|
||||||
|
placeholder="搜索 key 名称或分组"
|
||||||
|
placeholderTextColor="#9b9081"
|
||||||
|
className="ml-3 flex-1 text-sm text-[#16181a]"
|
||||||
|
/>
|
||||||
|
</View>
|
||||||
|
<View className="flex-row gap-2">
|
||||||
|
{(['all', 'active', 'inactive'] as const).map((item) => (
|
||||||
|
<Pressable
|
||||||
|
key={item}
|
||||||
|
className={statusFilter === item ? 'flex-1 rounded-[16px] bg-[#1d5f55] px-3 py-3' : 'flex-1 rounded-[16px] bg-[#e7dfcf] px-3 py-3'}
|
||||||
|
onPress={() => setStatusFilter(item)}
|
||||||
|
>
|
||||||
|
<Text className={statusFilter === item ? 'text-center text-sm font-semibold text-white' : 'text-center text-sm font-semibold text-[#4e463e]'}>
|
||||||
|
{item === 'all' ? '全部' : item === 'active' ? '启用' : '停用'}
|
||||||
|
</Text>
|
||||||
|
</Pressable>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
{filteredApiKeys.map((item) => (
|
||||||
|
<View key={item.id} className="rounded-[18px] bg-[#f1ece2] px-4 py-3">
|
||||||
|
<View className="flex-row items-center justify-between gap-3">
|
||||||
|
<Text className="flex-1 text-sm font-semibold text-[#16181a]">{item.name}</Text>
|
||||||
|
<Text className="text-xs uppercase tracking-[1.2px] text-[#7d7468]">{item.status}</Text>
|
||||||
|
</View>
|
||||||
|
<View 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>
|
||||||
|
<Pressable
|
||||||
|
className="rounded-full bg-[#e7dfcf] p-2"
|
||||||
|
onPress={() => setVisibleKeys((current) => ({ ...current, [item.id]: !current[item.id] }))}
|
||||||
|
>
|
||||||
|
{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} />
|
||||||
|
</Pressable>
|
||||||
|
</View>
|
||||||
|
<Text className="mt-2 text-xs text-[#7d7468]">
|
||||||
|
{copiedKeyId === item.id ? '已复制到剪贴板' : `最近使用 ${item.last_used_at || '--'}`}
|
||||||
|
</Text>
|
||||||
|
<Text className="mt-2 text-xs text-[#7d7468]">
|
||||||
|
已用 ${Number(item.quota_used ?? 0).toFixed(2)} / 配额 {item.quota ? `$${Number(item.quota).toFixed(2)}` : '无限制'}
|
||||||
|
</Text>
|
||||||
|
<Text className="mt-1 text-xs text-[#7d7468]">
|
||||||
|
分组 {item.group?.name || '未绑定'} · 5h 用量 {Number(item.usage_5h ?? 0).toFixed(2)}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
|
{filteredApiKeys.length === 0 ? <Text className="text-sm text-[#7d7468]">当前筛选条件下没有 API 密钥。</Text> : null}
|
||||||
|
</View>
|
||||||
|
</ListCard>
|
||||||
|
|
||||||
|
<ListCard title="余额调整" meta="默认执行增加余额,可继续扩成减余额和设定值。" icon={Wallet}>
|
||||||
|
<View className="gap-3">
|
||||||
|
<Controller
|
||||||
|
control={control}
|
||||||
|
name="amount"
|
||||||
|
render={({ field: { onChange, value } }) => (
|
||||||
|
<TextInput
|
||||||
|
value={value}
|
||||||
|
onChangeText={onChange}
|
||||||
|
keyboardType="decimal-pad"
|
||||||
|
placeholder="输入金额"
|
||||||
|
placeholderTextColor="#9b9081"
|
||||||
|
className="rounded-[18px] bg-[#f1ece2] px-4 py-4 text-base text-[#16181a]"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<View className="flex-row gap-2">
|
||||||
|
{(['add', 'subtract', 'set'] as BalanceOperation[]).map((item) => (
|
||||||
|
<Pressable
|
||||||
|
key={item}
|
||||||
|
className={operation === item ? 'flex-1 rounded-[16px] bg-[#1d5f55] px-3 py-3' : 'flex-1 rounded-[16px] bg-[#e7dfcf] px-3 py-3'}
|
||||||
|
onPress={() => setOperation(item)}
|
||||||
|
>
|
||||||
|
<Text className={operation === item ? 'text-center text-sm font-semibold text-white' : 'text-center text-sm font-semibold text-[#4e463e]'}>
|
||||||
|
{item === 'add' ? '增加' : item === 'subtract' ? '扣减' : '设为'}
|
||||||
|
</Text>
|
||||||
|
</Pressable>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
<Controller
|
||||||
|
control={control}
|
||||||
|
name="notes"
|
||||||
|
render={({ field: { onChange, value } }) => (
|
||||||
|
<TextInput
|
||||||
|
value={value}
|
||||||
|
onChangeText={onChange}
|
||||||
|
placeholder="备注,可留空"
|
||||||
|
placeholderTextColor="#9b9081"
|
||||||
|
className="rounded-[18px] bg-[#f1ece2] px-4 py-4 text-base text-[#16181a]"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
{formState.errors.amount ? <Text className="text-sm text-[#c25d35]">{formState.errors.amount.message}</Text> : null}
|
||||||
|
<Pressable
|
||||||
|
className="rounded-[18px] bg-[#1d5f55] px-4 py-4"
|
||||||
|
onPress={handleSubmit((values) => balanceMutation.mutate({ ...values, operation }))}
|
||||||
|
>
|
||||||
|
<Text className="text-center text-sm font-semibold tracking-[1.2px] text-white">
|
||||||
|
{balanceMutation.isPending ? '提交中...' : operation === 'add' ? '增加余额' : operation === 'subtract' ? '扣减余额' : '设置余额'}
|
||||||
|
</Text>
|
||||||
|
</Pressable>
|
||||||
|
</View>
|
||||||
|
</ListCard>
|
||||||
|
</ScreenShell>
|
||||||
|
);
|
||||||
|
}
|
||||||
81
docs/LOCAL_PROXY_SETUP.md
Normal file
81
docs/LOCAL_PROXY_SETUP.md
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
# Local Proxy Setup
|
||||||
|
|
||||||
|
本项目内置了一个最小代理层,用来解决:
|
||||||
|
|
||||||
|
- Expo Web 调用 `Sub2API` 管理接口时的 CORS
|
||||||
|
- 管理员 API Key 不直接暴露给客户端
|
||||||
|
|
||||||
|
## 启动代理
|
||||||
|
|
||||||
|
```bash
|
||||||
|
SUB2API_BASE_URL="https://x.empjs.dev" \
|
||||||
|
SUB2API_ADMIN_API_KEY="admin-xxxx" \
|
||||||
|
ALLOW_ORIGIN="http://localhost:8081" \
|
||||||
|
npm run proxy
|
||||||
|
```
|
||||||
|
|
||||||
|
默认代理地址:`http://localhost:8787`
|
||||||
|
|
||||||
|
可选环境变量:
|
||||||
|
|
||||||
|
- `PORT`:代理端口,默认 `8787`
|
||||||
|
- `ALLOW_ORIGIN`:允许的 Web 来源,默认 `*`
|
||||||
|
|
||||||
|
## 启动 Expo Web
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run web
|
||||||
|
```
|
||||||
|
|
||||||
|
## 一条命令同时启动
|
||||||
|
|
||||||
|
```bash
|
||||||
|
SUB2API_BASE_URL="https://x.empjs.dev" \
|
||||||
|
SUB2API_ADMIN_API_KEY="admin-xxxx" \
|
||||||
|
ALLOW_ORIGIN="http://localhost:8081" \
|
||||||
|
npm run dev:web-proxy
|
||||||
|
```
|
||||||
|
|
||||||
|
## 前端填写地址
|
||||||
|
|
||||||
|
设置页里把 `Base URL` 填成:
|
||||||
|
|
||||||
|
```txt
|
||||||
|
http://localhost:8787
|
||||||
|
```
|
||||||
|
|
||||||
|
## 健康检查
|
||||||
|
|
||||||
|
打开:`http://localhost:8787/healthz`
|
||||||
|
|
||||||
|
如果返回:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"ok": true,
|
||||||
|
"upstreamConfigured": true,
|
||||||
|
"apiKeyConfigured": true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
说明代理配置正常。
|
||||||
|
|
||||||
|
## API 密钥聚合接口
|
||||||
|
|
||||||
|
当前项目的管理端为了区分“用户 API 密钥”和“上游账号”,在本地代理额外提供了一个聚合接口:
|
||||||
|
|
||||||
|
- `GET /api/v1/keys`
|
||||||
|
|
||||||
|
这个接口不是直接转发上游用户态 `/api/v1/keys`,而是通过管理员接口聚合得到:
|
||||||
|
|
||||||
|
- `GET /api/v1/admin/users`
|
||||||
|
- `GET /api/v1/admin/users/:id/api-keys`
|
||||||
|
|
||||||
|
支持参数:
|
||||||
|
|
||||||
|
- `page`
|
||||||
|
- `page_size`
|
||||||
|
- `search`
|
||||||
|
- `status`
|
||||||
|
|
||||||
|
适合用在内部管理台的“用户 API 密钥”列表。
|
||||||
8
index.ts
8
index.ts
@@ -1,8 +0,0 @@
|
|||||||
import { registerRootComponent } from 'expo';
|
|
||||||
|
|
||||||
import App from './App';
|
|
||||||
|
|
||||||
// registerRootComponent calls AppRegistry.registerComponent('main', () => App);
|
|
||||||
// It also ensures that whether you load the app in Expo Go or in a native build,
|
|
||||||
// the environment is set up appropriately
|
|
||||||
registerRootComponent(App);
|
|
||||||
9
metro.config.js
Normal file
9
metro.config.js
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
const { getDefaultConfig } = require('expo/metro-config');
|
||||||
|
const { withUniwindConfig } = require('uniwind/metro');
|
||||||
|
|
||||||
|
const config = getDefaultConfig(__dirname);
|
||||||
|
|
||||||
|
module.exports = withUniwindConfig(config, {
|
||||||
|
cssEntryFile: './src/global.css',
|
||||||
|
dtsFile: './src/uniwind-types.d.ts',
|
||||||
|
});
|
||||||
3675
package-lock.json
generated
3675
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
32
package.json
32
package.json
@@ -1,21 +1,47 @@
|
|||||||
{
|
{
|
||||||
"name": "x-sapi-mobile",
|
"name": "x-sapi-mobile",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"main": "index.ts",
|
"main": "expo-router/entry",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "expo start",
|
"start": "expo start",
|
||||||
"android": "expo start --android",
|
"android": "expo start --android",
|
||||||
"ios": "expo start --ios",
|
"ios": "expo start --ios",
|
||||||
"web": "expo start --web"
|
"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\""
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@hookform/resolvers": "^5.2.2",
|
||||||
|
"@tanstack/react-query": "^5.90.21",
|
||||||
|
"cors": "^2.8.6",
|
||||||
"expo": "~55.0.5",
|
"expo": "~55.0.5",
|
||||||
|
"expo-clipboard": "~55.0.8",
|
||||||
|
"expo-constants": "~55.0.7",
|
||||||
|
"expo-linking": "~55.0.7",
|
||||||
|
"expo-router": "~55.0.4",
|
||||||
|
"expo-secure-store": "~55.0.8",
|
||||||
"expo-status-bar": "~55.0.4",
|
"expo-status-bar": "~55.0.4",
|
||||||
|
"express": "^5.2.1",
|
||||||
|
"lucide-react-native": "^0.577.0",
|
||||||
"react": "19.2.0",
|
"react": "19.2.0",
|
||||||
"react-native": "0.83.2"
|
"react-dom": "19.2.0",
|
||||||
|
"react-hook-form": "^7.71.2",
|
||||||
|
"react-native": "0.83.2",
|
||||||
|
"react-native-gesture-handler": "~2.30.0",
|
||||||
|
"react-native-reanimated": "4.2.1",
|
||||||
|
"react-native-safe-area-context": "~5.6.2",
|
||||||
|
"react-native-screens": "~4.23.0",
|
||||||
|
"react-native-svg": "15.15.3",
|
||||||
|
"react-native-web": "^0.21.2",
|
||||||
|
"react-native-worklets": "0.7.2",
|
||||||
|
"tailwindcss": "^4.2.1",
|
||||||
|
"uniwind": "^1.5.0",
|
||||||
|
"valtio": "^2.3.1",
|
||||||
|
"zod": "^4.3.6"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/react": "~19.2.2",
|
"@types/react": "~19.2.2",
|
||||||
|
"concurrently": "^9.2.1",
|
||||||
"typescript": "~5.9.2"
|
"typescript": "~5.9.2"
|
||||||
},
|
},
|
||||||
"private": true
|
"private": true
|
||||||
|
|||||||
224
server/index.js
Normal file
224
server/index.js
Normal file
@@ -0,0 +1,224 @@
|
|||||||
|
const cors = require('cors');
|
||||||
|
const express = require('express');
|
||||||
|
|
||||||
|
const app = express();
|
||||||
|
|
||||||
|
const port = Number(process.env.PORT || 8787);
|
||||||
|
const upstreamBaseUrl = (process.env.SUB2API_BASE_URL || '').trim().replace(/\/$/, '');
|
||||||
|
const adminApiKey = (process.env.SUB2API_ADMIN_API_KEY || '').trim();
|
||||||
|
const allowedOrigin = (process.env.ALLOW_ORIGIN || '*').trim();
|
||||||
|
|
||||||
|
async function fetchAdminJson(path) {
|
||||||
|
if (!upstreamBaseUrl) {
|
||||||
|
throw new Error('SUB2API_BASE_URL_NOT_CONFIGURED');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!adminApiKey) {
|
||||||
|
throw new Error('SUB2API_ADMIN_API_KEY_NOT_CONFIGURED');
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await fetch(`${upstreamBaseUrl}${path}`, {
|
||||||
|
headers: {
|
||||||
|
'x-api-key': adminApiKey,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const json = await response.json();
|
||||||
|
|
||||||
|
if (!response.ok || json.code !== 0) {
|
||||||
|
throw new Error(json.message || 'ADMIN_FETCH_FAILED');
|
||||||
|
}
|
||||||
|
|
||||||
|
return json.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
function redactAccountCredentials(payload) {
|
||||||
|
if (!payload || typeof payload !== 'object') {
|
||||||
|
return payload;
|
||||||
|
}
|
||||||
|
|
||||||
|
const walk = (value) => {
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
return value.map(walk);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!value || typeof value !== 'object') {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
const next = {};
|
||||||
|
|
||||||
|
Object.entries(value).forEach(([key, entryValue]) => {
|
||||||
|
if (key === 'credentials') {
|
||||||
|
next[key] = { redacted: true };
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
next[key] = walk(entryValue);
|
||||||
|
});
|
||||||
|
|
||||||
|
return next;
|
||||||
|
};
|
||||||
|
|
||||||
|
return walk(payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
app.use(
|
||||||
|
cors({
|
||||||
|
origin: allowedOrigin === '*' ? true : allowedOrigin,
|
||||||
|
credentials: true,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
app.use(express.json({ limit: '2mb' }));
|
||||||
|
|
||||||
|
app.get('/healthz', (_req, res) => {
|
||||||
|
res.json({
|
||||||
|
ok: true,
|
||||||
|
upstreamConfigured: Boolean(upstreamBaseUrl),
|
||||||
|
apiKeyConfigured: Boolean(adminApiKey),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get('/api/v1/keys', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const page = Math.max(Number(req.query.page || 1), 1);
|
||||||
|
const pageSize = Math.min(Math.max(Number(req.query.page_size || 10), 1), 100);
|
||||||
|
const search = String(req.query.search || '').trim().toLowerCase();
|
||||||
|
const status = String(req.query.status || '').trim();
|
||||||
|
|
||||||
|
const users = [];
|
||||||
|
let currentPage = 1;
|
||||||
|
let totalPages = 1;
|
||||||
|
|
||||||
|
do {
|
||||||
|
const userPage = await fetchAdminJson(`/api/v1/admin/users?page=${currentPage}&page_size=100`);
|
||||||
|
users.push(...(userPage.items || []));
|
||||||
|
totalPages = userPage.pages || 1;
|
||||||
|
currentPage += 1;
|
||||||
|
} while (currentPage <= totalPages);
|
||||||
|
|
||||||
|
const keyPages = await Promise.all(
|
||||||
|
users.map(async (user) => {
|
||||||
|
const result = await fetchAdminJson(`/api/v1/admin/users/${user.id}/api-keys?page=1&page_size=100`);
|
||||||
|
return (result.items || []).map((item) => ({
|
||||||
|
...item,
|
||||||
|
user: {
|
||||||
|
id: user.id,
|
||||||
|
email: user.email,
|
||||||
|
username: user.username,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
let items = keyPages.flat();
|
||||||
|
|
||||||
|
if (search) {
|
||||||
|
items = items.filter((item) => {
|
||||||
|
const haystack = [item.name, item.key, item.user?.email, item.user?.username, item.group?.name]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(' ')
|
||||||
|
.toLowerCase();
|
||||||
|
return haystack.includes(search);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (status) {
|
||||||
|
items = items.filter((item) => item.status === status);
|
||||||
|
}
|
||||||
|
|
||||||
|
items.sort((left, right) => {
|
||||||
|
const leftTime = new Date(left.updated_at || left.last_used_at || 0).getTime();
|
||||||
|
const rightTime = new Date(right.updated_at || right.last_used_at || 0).getTime();
|
||||||
|
return rightTime - leftTime;
|
||||||
|
});
|
||||||
|
|
||||||
|
const total = items.length;
|
||||||
|
const start = (page - 1) * pageSize;
|
||||||
|
const pagedItems = items.slice(start, start + pageSize);
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
code: 0,
|
||||||
|
message: 'success',
|
||||||
|
data: {
|
||||||
|
items: pagedItems,
|
||||||
|
total,
|
||||||
|
page,
|
||||||
|
page_size: pageSize,
|
||||||
|
pages: Math.max(Math.ceil(total / pageSize), 1),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
res.status(500).json({
|
||||||
|
code: 500,
|
||||||
|
message: error instanceof Error ? error.message : 'KEYS_AGGREGATION_FAILED',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.use('/api/v1/admin', async (req, res) => {
|
||||||
|
if (!upstreamBaseUrl) {
|
||||||
|
res.status(500).json({ code: 500, message: 'SUB2API_BASE_URL_NOT_CONFIGURED' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!adminApiKey) {
|
||||||
|
res.status(500).json({ code: 500, message: 'SUB2API_ADMIN_API_KEY_NOT_CONFIGURED' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const upstreamUrl = new URL(`${upstreamBaseUrl}${req.originalUrl}`);
|
||||||
|
const headers = new Headers();
|
||||||
|
|
||||||
|
headers.set('x-api-key', adminApiKey);
|
||||||
|
|
||||||
|
const contentType = req.headers['content-type'];
|
||||||
|
if (contentType) {
|
||||||
|
headers.set('content-type', contentType);
|
||||||
|
}
|
||||||
|
|
||||||
|
const idempotencyKey = req.headers['idempotency-key'];
|
||||||
|
if (typeof idempotencyKey === 'string' && idempotencyKey) {
|
||||||
|
headers.set('Idempotency-Key', idempotencyKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
const init = {
|
||||||
|
method: req.method,
|
||||||
|
headers,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!['GET', 'HEAD'].includes(req.method)) {
|
||||||
|
init.body = JSON.stringify(req.body || {});
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(upstreamUrl, init);
|
||||||
|
const upstreamContentType = response.headers.get('content-type');
|
||||||
|
const isJson = upstreamContentType?.includes('application/json');
|
||||||
|
|
||||||
|
let responseBody;
|
||||||
|
if (isJson) {
|
||||||
|
const json = await response.json();
|
||||||
|
responseBody = req.path.startsWith('/accounts') ? redactAccountCredentials(json) : json;
|
||||||
|
} else {
|
||||||
|
responseBody = await response.text();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (upstreamContentType) {
|
||||||
|
res.setHeader('content-type', upstreamContentType);
|
||||||
|
}
|
||||||
|
|
||||||
|
res.status(response.status).send(responseBody);
|
||||||
|
} catch (error) {
|
||||||
|
res.status(502).json({
|
||||||
|
code: 502,
|
||||||
|
message: 'UPSTREAM_REQUEST_FAILED',
|
||||||
|
error: error instanceof Error ? error.message : 'UNKNOWN_ERROR',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.listen(port, () => {
|
||||||
|
console.log(`Admin proxy listening on http://localhost:${port}`);
|
||||||
|
});
|
||||||
15
src/components/detail-row.tsx
Normal file
15
src/components/detail-row.tsx
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
import { Text, View } from 'react-native';
|
||||||
|
|
||||||
|
type DetailRowProps = {
|
||||||
|
label: string;
|
||||||
|
value: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function DetailRow({ label, value }: DetailRowProps) {
|
||||||
|
return (
|
||||||
|
<View className="flex-row items-start justify-between gap-4 border-b border-[#eee6d7] py-3 last:border-b-0">
|
||||||
|
<Text className="text-sm text-[#7d7468]">{label}</Text>
|
||||||
|
<Text className="max-w-[62%] text-right text-sm font-medium text-[#16181a]">{value}</Text>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
70
src/components/line-trend-chart.tsx
Normal file
70
src/components/line-trend-chart.tsx
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
import { Text, View } from 'react-native';
|
||||||
|
import Svg, { Defs, LinearGradient, Path, Stop } from 'react-native-svg';
|
||||||
|
|
||||||
|
type Point = {
|
||||||
|
label: string;
|
||||||
|
value: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type LineTrendChartProps = {
|
||||||
|
points: Point[];
|
||||||
|
color?: string;
|
||||||
|
title: string;
|
||||||
|
subtitle: string;
|
||||||
|
formatValue?: (value: number) => string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function LineTrendChart({
|
||||||
|
points,
|
||||||
|
color = '#1d5f55',
|
||||||
|
title,
|
||||||
|
subtitle,
|
||||||
|
formatValue = (value) => `${value}`,
|
||||||
|
}: LineTrendChartProps) {
|
||||||
|
const width = 320;
|
||||||
|
const height = 160;
|
||||||
|
const maxValue = Math.max(...points.map((point) => point.value), 1);
|
||||||
|
const minValue = Math.min(...points.map((point) => point.value), 0);
|
||||||
|
const range = Math.max(maxValue - minValue, 1);
|
||||||
|
|
||||||
|
const line = points
|
||||||
|
.map((point, index) => {
|
||||||
|
const x = (index / Math.max(points.length - 1, 1)) * width;
|
||||||
|
const y = height - ((point.value - minValue) / range) * (height - 18) - 12;
|
||||||
|
|
||||||
|
return `${index === 0 ? 'M' : 'L'} ${x} ${y}`;
|
||||||
|
})
|
||||||
|
.join(' ');
|
||||||
|
|
||||||
|
const area = `${line} L ${width} ${height} L 0 ${height} Z`;
|
||||||
|
const latest = points[points.length - 1]?.value ?? 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<View className="rounded-[28px] bg-[#fbf8f2] p-5">
|
||||||
|
<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>
|
||||||
|
|
||||||
|
<View className="mt-5 overflow-hidden rounded-[20px] bg-[#f4efe4] p-3">
|
||||||
|
<Svg width="100%" height={height} viewBox={`0 0 ${width} ${height}`}>
|
||||||
|
<Defs>
|
||||||
|
<LinearGradient id="trendFill" x1="0" x2="0" y1="0" y2="1">
|
||||||
|
<Stop offset="0%" stopColor={color} stopOpacity="0.28" />
|
||||||
|
<Stop offset="100%" stopColor={color} stopOpacity="0.02" />
|
||||||
|
</LinearGradient>
|
||||||
|
</Defs>
|
||||||
|
<Path d={area} fill="url(#trendFill)" />
|
||||||
|
<Path d={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]">
|
||||||
|
{point.label}
|
||||||
|
</Text>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
33
src/components/list-card.tsx
Normal file
33
src/components/list-card.tsx
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
import type { LucideIcon } from 'lucide-react-native';
|
||||||
|
import type { ReactNode } from 'react';
|
||||||
|
import { Text, View } from 'react-native';
|
||||||
|
|
||||||
|
type ListCardProps = {
|
||||||
|
title: string;
|
||||||
|
meta?: string;
|
||||||
|
badge?: string;
|
||||||
|
children?: ReactNode;
|
||||||
|
icon?: LucideIcon;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function ListCard({ title, meta, badge, children, icon: Icon }: ListCardProps) {
|
||||||
|
return (
|
||||||
|
<View className="rounded-[24px] bg-[#fbf8f2] p-4">
|
||||||
|
<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>
|
||||||
|
</View>
|
||||||
|
{meta ? <Text className="mt-1 text-sm 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>
|
||||||
|
) : null}
|
||||||
|
</View>
|
||||||
|
{children ? <View className="mt-4">{children}</View> : null}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
28
src/components/screen-shell.tsx
Normal file
28
src/components/screen-shell.tsx
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import type { PropsWithChildren, ReactNode } from 'react';
|
||||||
|
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||||
|
import { ScrollView, Text, View } from 'react-native';
|
||||||
|
|
||||||
|
type ScreenShellProps = PropsWithChildren<{
|
||||||
|
title: string;
|
||||||
|
subtitle: string;
|
||||||
|
right?: ReactNode;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export function ScreenShell({ title, subtitle, right, children }: ScreenShellProps) {
|
||||||
|
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>
|
||||||
|
</View>
|
||||||
|
{right}
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
<View className="mt-4 gap-4">{children}</View>
|
||||||
|
</ScrollView>
|
||||||
|
</SafeAreaView>
|
||||||
|
);
|
||||||
|
}
|
||||||
33
src/components/stat-card.tsx
Normal file
33
src/components/stat-card.tsx
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
import type { LucideIcon } from 'lucide-react-native';
|
||||||
|
import { TrendingDown, TrendingUp } from 'lucide-react-native';
|
||||||
|
import { Text, View } from 'react-native';
|
||||||
|
|
||||||
|
type StatCardProps = {
|
||||||
|
label: string;
|
||||||
|
value: string;
|
||||||
|
tone?: 'light' | 'dark';
|
||||||
|
trend?: 'up' | 'down';
|
||||||
|
icon?: LucideIcon;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function StatCard({ label, value, tone = 'light', trend, icon: Icon }: StatCardProps) {
|
||||||
|
const dark = tone === 'dark';
|
||||||
|
const TrendIcon = trend === 'up' ? TrendingUp : trend === 'down' ? TrendingDown : null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<View className={dark ? 'rounded-[24px] bg-[#1d5f55] p-4' : 'rounded-[24px] bg-[#fbf8f2] p-4'}>
|
||||||
|
<View className="flex-row items-center justify-between gap-3">
|
||||||
|
<Text className={dark ? 'text-xs uppercase tracking-[1.5px] text-[#d8efe7]' : 'text-xs uppercase tracking-[1.5px] text-[#7d7468]'}>
|
||||||
|
{label}
|
||||||
|
</Text>
|
||||||
|
<View className="flex-row items-center gap-2">
|
||||||
|
{TrendIcon ? <TrendIcon color={dark ? '#d8efe7' : '#7d7468'} size={14} /> : null}
|
||||||
|
{Icon ? <Icon color={dark ? '#d8efe7' : '#7d7468'} size={14} /> : null}
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
<Text className={dark ? 'mt-3 text-3xl font-bold text-white' : 'mt-3 text-3xl font-bold text-[#16181a]'}>
|
||||||
|
{value}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
2
src/global.css
Normal file
2
src/global.css
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
@import 'tailwindcss';
|
||||||
|
@import 'uniwind';
|
||||||
56
src/lib/admin-fetch.ts
Normal file
56
src/lib/admin-fetch.ts
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
import { adminConfigState } from '@/src/store/admin-config';
|
||||||
|
import type { ApiEnvelope } from '@/src/types/admin';
|
||||||
|
|
||||||
|
function isProxyBaseUrl(baseUrl: string) {
|
||||||
|
return /localhost:8787$/.test(baseUrl) || /127\.0\.0\.1:8787$/.test(baseUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isLocalProxyBaseUrl(baseUrl: string) {
|
||||||
|
return isProxyBaseUrl(baseUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function adminFetch<T>(
|
||||||
|
path: string,
|
||||||
|
init: RequestInit = {},
|
||||||
|
options?: { idempotencyKey?: string }
|
||||||
|
): Promise<T> {
|
||||||
|
const baseUrl = adminConfigState.baseUrl.trim().replace(/\/$/, '');
|
||||||
|
const adminApiKey = adminConfigState.adminApiKey.trim();
|
||||||
|
|
||||||
|
if (!baseUrl) {
|
||||||
|
throw new Error('BASE_URL_REQUIRED');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!adminApiKey && !isProxyBaseUrl(baseUrl)) {
|
||||||
|
throw new Error('ADMIN_API_KEY_REQUIRED');
|
||||||
|
}
|
||||||
|
|
||||||
|
const headers = new Headers(init.headers);
|
||||||
|
headers.set('Content-Type', 'application/json');
|
||||||
|
if (adminApiKey) {
|
||||||
|
headers.set('x-api-key', adminApiKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options?.idempotencyKey) {
|
||||||
|
headers.set('Idempotency-Key', options.idempotencyKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await fetch(`${baseUrl}${path}`, {
|
||||||
|
...init,
|
||||||
|
headers,
|
||||||
|
});
|
||||||
|
|
||||||
|
let json: ApiEnvelope<T>;
|
||||||
|
|
||||||
|
try {
|
||||||
|
json = (await response.json()) as ApiEnvelope<T>;
|
||||||
|
} catch {
|
||||||
|
throw new Error('INVALID_SERVER_RESPONSE');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.ok || json.code !== 0) {
|
||||||
|
throw new Error(json.reason || json.message || 'REQUEST_FAILED');
|
||||||
|
}
|
||||||
|
|
||||||
|
return json.data as T;
|
||||||
|
}
|
||||||
11
src/lib/query-client.ts
Normal file
11
src/lib/query-client.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import { QueryClient } from '@tanstack/react-query';
|
||||||
|
|
||||||
|
export const queryClient = new QueryClient({
|
||||||
|
defaultOptions: {
|
||||||
|
queries: {
|
||||||
|
retry: 1,
|
||||||
|
staleTime: 30_000,
|
||||||
|
refetchOnWindowFocus: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
129
src/services/admin.ts
Normal file
129
src/services/admin.ts
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
import { adminFetch } from '@/src/lib/admin-fetch';
|
||||||
|
import type {
|
||||||
|
AccountTodayStats,
|
||||||
|
AdminAccount,
|
||||||
|
AdminApiKey,
|
||||||
|
AdminGroup,
|
||||||
|
AdminSettings,
|
||||||
|
AdminUser,
|
||||||
|
BalanceOperation,
|
||||||
|
DashboardModelStats,
|
||||||
|
DashboardStats,
|
||||||
|
DashboardTrend,
|
||||||
|
PaginatedData,
|
||||||
|
UserUsageSummary,
|
||||||
|
} from '@/src/types/admin';
|
||||||
|
|
||||||
|
function buildQuery(params: Record<string, string | number | boolean | undefined>) {
|
||||||
|
const query = new URLSearchParams();
|
||||||
|
|
||||||
|
Object.entries(params).forEach(([key, value]) => {
|
||||||
|
if (value !== undefined && value !== null && value !== '') {
|
||||||
|
query.set(key, String(value));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const value = query.toString();
|
||||||
|
|
||||||
|
return value ? `?${value}` : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getDashboardStats() {
|
||||||
|
return adminFetch<DashboardStats>('/api/v1/admin/dashboard/stats');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAdminSettings() {
|
||||||
|
return adminFetch<AdminSettings>('/api/v1/admin/settings');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getDashboardTrend(params: {
|
||||||
|
start_date: string;
|
||||||
|
end_date: string;
|
||||||
|
granularity?: 'day' | 'hour';
|
||||||
|
account_id?: number;
|
||||||
|
group_id?: number;
|
||||||
|
user_id?: number;
|
||||||
|
}) {
|
||||||
|
return adminFetch<DashboardTrend>(`/api/v1/admin/dashboard/trend${buildQuery(params)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getDashboardModels(params: { start_date: string; end_date: string }) {
|
||||||
|
return adminFetch<DashboardModelStats>(`/api/v1/admin/dashboard/models${buildQuery(params)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listUsers(search = '') {
|
||||||
|
return adminFetch<PaginatedData<AdminUser>>(
|
||||||
|
`/api/v1/admin/users${buildQuery({ page: 1, page_size: 20, search: search.trim() })}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getUser(userId: number) {
|
||||||
|
return adminFetch<AdminUser>(`/api/v1/admin/users/${userId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getUserUsage(userId: number, period: 'day' | 'week' | 'month' = 'month') {
|
||||||
|
return adminFetch<UserUsageSummary>(`/api/v1/admin/users/${userId}/usage${buildQuery({ period })}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listUserApiKeys(userId: number) {
|
||||||
|
return adminFetch<PaginatedData<AdminApiKey>>(`/api/v1/admin/users/${userId}/api-keys${buildQuery({ page: 1, page_size: 100 })}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateUserBalance(
|
||||||
|
userId: number,
|
||||||
|
body: { balance: number; operation: BalanceOperation; notes?: string }
|
||||||
|
) {
|
||||||
|
return adminFetch<AdminUser>(
|
||||||
|
`/api/v1/admin/users/${userId}/balance`,
|
||||||
|
{
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
idempotencyKey: `user-balance-${userId}-${Date.now()}`,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listGroups(search = '') {
|
||||||
|
return adminFetch<PaginatedData<AdminGroup>>(
|
||||||
|
`/api/v1/admin/groups${buildQuery({ page: 1, page_size: 20, search: search.trim() })}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getGroup(groupId: number) {
|
||||||
|
return adminFetch<AdminGroup>(`/api/v1/admin/groups/${groupId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listAccounts(search = '') {
|
||||||
|
return adminFetch<PaginatedData<AdminAccount>>(
|
||||||
|
`/api/v1/admin/accounts${buildQuery({ page: 1, page_size: 20, search: search.trim() })}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAccount(accountId: number) {
|
||||||
|
return adminFetch<AdminAccount>(`/api/v1/admin/accounts/${accountId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAccountTodayStats(accountId: number) {
|
||||||
|
return adminFetch<AccountTodayStats>(`/api/v1/admin/accounts/${accountId}/today-stats`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function testAccount(accountId: number) {
|
||||||
|
return adminFetch(`/api/v1/admin/accounts/${accountId}/test`, {
|
||||||
|
method: 'POST',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function refreshAccount(accountId: number) {
|
||||||
|
return adminFetch(`/api/v1/admin/accounts/${accountId}/refresh`, {
|
||||||
|
method: 'POST',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setAccountSchedulable(accountId: number, schedulable: boolean) {
|
||||||
|
return adminFetch<AdminAccount>(`/api/v1/admin/accounts/${accountId}/schedulable`, {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ schedulable }),
|
||||||
|
});
|
||||||
|
}
|
||||||
71
src/store/admin-config.ts
Normal file
71
src/store/admin-config.ts
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
import * as SecureStore from 'expo-secure-store';
|
||||||
|
const { proxy } = require('valtio');
|
||||||
|
|
||||||
|
const BASE_URL_KEY = 'sub2api_base_url';
|
||||||
|
const ADMIN_KEY_KEY = 'sub2api_admin_api_key';
|
||||||
|
|
||||||
|
export function getDefaultAdminConfig() {
|
||||||
|
return {
|
||||||
|
baseUrl: '',
|
||||||
|
adminApiKey: '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getItem(key: string) {
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
if (typeof localStorage === 'undefined') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return localStorage.getItem(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
return SecureStore.getItemAsync(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function setItem(key: string, value: string) {
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
if (typeof localStorage !== 'undefined') {
|
||||||
|
localStorage.setItem(key, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await SecureStore.setItemAsync(key, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const adminConfigState = proxy({
|
||||||
|
...getDefaultAdminConfig(),
|
||||||
|
hydrated: false,
|
||||||
|
saving: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
export async function hydrateAdminConfig() {
|
||||||
|
const defaults = getDefaultAdminConfig();
|
||||||
|
const [baseUrl, adminApiKey] = await Promise.all([
|
||||||
|
getItem(BASE_URL_KEY),
|
||||||
|
getItem(ADMIN_KEY_KEY),
|
||||||
|
]);
|
||||||
|
|
||||||
|
adminConfigState.baseUrl = baseUrl ?? defaults.baseUrl;
|
||||||
|
adminConfigState.adminApiKey = adminApiKey ?? defaults.adminApiKey;
|
||||||
|
|
||||||
|
adminConfigState.hydrated = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
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),
|
||||||
|
]);
|
||||||
|
|
||||||
|
adminConfigState.baseUrl = nextBaseUrl;
|
||||||
|
adminConfigState.adminApiKey = nextAdminApiKey;
|
||||||
|
adminConfigState.saving = false;
|
||||||
|
}
|
||||||
174
src/types/admin.ts
Normal file
174
src/types/admin.ts
Normal file
@@ -0,0 +1,174 @@
|
|||||||
|
export type ApiEnvelope<T> = {
|
||||||
|
code: number;
|
||||||
|
message: string;
|
||||||
|
reason?: string;
|
||||||
|
metadata?: Record<string, string>;
|
||||||
|
data?: T;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PaginatedData<T> = {
|
||||||
|
items: T[];
|
||||||
|
total: number;
|
||||||
|
page: number;
|
||||||
|
page_size: number;
|
||||||
|
pages: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type DashboardStats = {
|
||||||
|
total_users: number;
|
||||||
|
today_new_users: number;
|
||||||
|
active_users: number;
|
||||||
|
total_api_keys: number;
|
||||||
|
active_api_keys: number;
|
||||||
|
total_accounts: number;
|
||||||
|
normal_accounts: number;
|
||||||
|
error_accounts: number;
|
||||||
|
total_requests: number;
|
||||||
|
total_cost: number;
|
||||||
|
total_tokens: number;
|
||||||
|
today_requests: number;
|
||||||
|
today_cost: number;
|
||||||
|
today_tokens: number;
|
||||||
|
today_input_tokens?: number;
|
||||||
|
today_output_tokens?: number;
|
||||||
|
today_cache_read_tokens?: number;
|
||||||
|
rpm: number;
|
||||||
|
tpm: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type TrendPoint = {
|
||||||
|
date: string;
|
||||||
|
requests: number;
|
||||||
|
input_tokens: number;
|
||||||
|
output_tokens: number;
|
||||||
|
cache_creation_tokens: number;
|
||||||
|
cache_read_tokens: number;
|
||||||
|
total_tokens: number;
|
||||||
|
cost: number;
|
||||||
|
actual_cost: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type DashboardTrend = {
|
||||||
|
start_date: string;
|
||||||
|
end_date: string;
|
||||||
|
granularity: 'day' | 'hour' | string;
|
||||||
|
trend: TrendPoint[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ModelStat = {
|
||||||
|
model: string;
|
||||||
|
requests: number;
|
||||||
|
input_tokens: number;
|
||||||
|
output_tokens: number;
|
||||||
|
cache_creation_tokens: number;
|
||||||
|
cache_read_tokens: number;
|
||||||
|
total_tokens: number;
|
||||||
|
cost: number;
|
||||||
|
actual_cost: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type DashboardModelStats = {
|
||||||
|
start_date: string;
|
||||||
|
end_date: string;
|
||||||
|
models: ModelStat[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AdminSettings = {
|
||||||
|
site_name?: string;
|
||||||
|
[key: string]: string | number | boolean | null | string[] | undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AdminUser = {
|
||||||
|
id: number;
|
||||||
|
email: string;
|
||||||
|
username?: string | null;
|
||||||
|
balance?: number;
|
||||||
|
concurrency?: number;
|
||||||
|
status?: string;
|
||||||
|
role?: string;
|
||||||
|
current_concurrency?: number;
|
||||||
|
notes?: string | null;
|
||||||
|
created_at?: string;
|
||||||
|
updated_at?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type UserUsageSummary = {
|
||||||
|
total_requests?: number;
|
||||||
|
total_tokens?: number;
|
||||||
|
total_cost?: number;
|
||||||
|
requests?: number;
|
||||||
|
tokens?: number;
|
||||||
|
cost?: number;
|
||||||
|
[key: string]: string | number | boolean | null | undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AdminApiKey = {
|
||||||
|
id: number;
|
||||||
|
user_id: number;
|
||||||
|
key: string;
|
||||||
|
name: string;
|
||||||
|
group_id?: number | null;
|
||||||
|
status: string;
|
||||||
|
quota: number;
|
||||||
|
quota_used: number;
|
||||||
|
last_used_at?: string | null;
|
||||||
|
expires_at?: string | null;
|
||||||
|
created_at?: string;
|
||||||
|
updated_at?: string;
|
||||||
|
usage_5h?: number;
|
||||||
|
usage_1d?: number;
|
||||||
|
usage_7d?: number;
|
||||||
|
group?: AdminGroup;
|
||||||
|
user?: {
|
||||||
|
id: number;
|
||||||
|
email?: string;
|
||||||
|
username?: string | null;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export type BalanceOperation = 'set' | 'add' | 'subtract';
|
||||||
|
|
||||||
|
export type AdminGroup = {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
description?: string | null;
|
||||||
|
platform: string;
|
||||||
|
rate_multiplier?: number;
|
||||||
|
is_exclusive?: boolean;
|
||||||
|
status?: string;
|
||||||
|
subscription_type?: string;
|
||||||
|
daily_limit_usd?: number | null;
|
||||||
|
weekly_limit_usd?: number | null;
|
||||||
|
monthly_limit_usd?: number | null;
|
||||||
|
account_count?: number;
|
||||||
|
sort_order?: number;
|
||||||
|
created_at?: string;
|
||||||
|
updated_at?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AccountTodayStats = {
|
||||||
|
requests: number;
|
||||||
|
tokens: number;
|
||||||
|
cost: number;
|
||||||
|
standard_cost?: number;
|
||||||
|
user_cost?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AdminAccount = {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
platform: string;
|
||||||
|
type: string;
|
||||||
|
status?: string;
|
||||||
|
schedulable?: boolean;
|
||||||
|
priority?: number;
|
||||||
|
concurrency?: number;
|
||||||
|
current_concurrency?: number;
|
||||||
|
rate_multiplier?: number;
|
||||||
|
error_message?: string;
|
||||||
|
updated_at?: string;
|
||||||
|
last_used_at?: string | null;
|
||||||
|
group_ids?: number[];
|
||||||
|
groups?: AdminGroup[];
|
||||||
|
extra?: Record<string, string | number | boolean | null>;
|
||||||
|
};
|
||||||
9
src/uniwind-env.d.ts
vendored
Normal file
9
src/uniwind-env.d.ts
vendored
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import 'react-native';
|
||||||
|
import 'react-native-safe-area-context';
|
||||||
|
import 'uniwind/types';
|
||||||
|
|
||||||
|
declare module 'react-native-safe-area-context' {
|
||||||
|
interface NativeSafeAreaViewProps {
|
||||||
|
className?: string;
|
||||||
|
}
|
||||||
|
}
|
||||||
10
src/uniwind-types.d.ts
vendored
Normal file
10
src/uniwind-types.d.ts
vendored
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
// NOTE: This file is generated by uniwind and it should not be edited manually.
|
||||||
|
/// <reference types="uniwind/types" />
|
||||||
|
|
||||||
|
declare module 'uniwind' {
|
||||||
|
export interface UniwindConfig {
|
||||||
|
themes: readonly ['light', 'dark']
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export {}
|
||||||
@@ -1,6 +1,21 @@
|
|||||||
{
|
{
|
||||||
"extends": "expo/tsconfig.base",
|
"extends": "expo/tsconfig.base",
|
||||||
|
"exclude": [
|
||||||
|
"dist",
|
||||||
|
"node_modules",
|
||||||
|
".agents",
|
||||||
|
"skills"
|
||||||
|
],
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"strict": true
|
"strict": true,
|
||||||
|
"baseUrl": ".",
|
||||||
|
"types": [
|
||||||
|
"uniwind/types"
|
||||||
|
],
|
||||||
|
"paths": {
|
||||||
|
"@/*": [
|
||||||
|
"./*"
|
||||||
|
]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user