feat: 数据获取架构重构 + Mac指纹采集 + Token刷新容错 + 账单页面 (0.0.19)

## 架构重构
  - useAsyncData 集成 AbortController:cleanup 时真正中断 HTTP 请求,
    不再仅丢弃响应(解决 StrictMode 双重请求问题)
  - API 模块统一 signal?: AbortSignal 参数,透传 axios config
  - use-api.ts 成为数据 Hook 集中管理中心,新增 useAccountInfo、
    useBillingBalance、useBillingLedger
  - 页面组件改为纯渲染:const {data,loading,error,refetch} = useXxx()

  ## 新功能
  - Mac 硬件指纹采集(electron/preload/device.ts):
    ioreg(UUID) + sysctl(CPU) + system_profiler(HDD三级回退)
  - 账单页面 BillingInfo(余额卡片 + 账单表格 + 分页)
  - PageDispatcher 注册 /billing 页面(FloatingPanel 960×680)
  - 共享工具函数 centToYuan / formatDate(src/utils/display.ts)

  ## Bug 修复
  - Token 刷新容错:网络错误时保留 refresh_token,等网络恢复后重试;
    仅 RefreshError(token 过期)时清除(auth-token.ts)
  - AppProvider 自动登录时 nullable 字段默认值(email→''、admin_permissions→[])
  - AccountInfo 重构消除 ~40 行手写状态管理代码

  ## 代码质量
  - AccountInfo 消除 centToYuan/formatDate 重复定义
  - BillingInfo 标题层级精简(移除冗余页面/Card标题)
  - antd Table align 字面量类型修正('left' as const)
  - billing.ts signal 参数位置修复(params→config)
  - modelFirstFetchDone 模块级变量移除(StrictMode 不安全)
This commit is contained in:
2026-06-11 20:08:44 +08:00
parent 95019316b2
commit 4237dcbaf6
24 changed files with 808 additions and 172 deletions

View File

@@ -1,4 +1,3 @@
import {useEffect, useState, useCallback} from 'react';
import {
Card,
Descriptions,
@@ -18,48 +17,16 @@ import {
BarChartOutlined,
RightOutlined,
} from '@ant-design/icons';
import {AuthAPI, type UserInfoBody, UserAccountTypeLabelMap} from '@/services/modules/auth';
import {VipAPI, VipLevelsItem} from "@/services/modules/vip-api.ts";
import { UserAccountTypeLabelMap } from '@/services/modules/auth';
import type { VipLevelsItem } from '@/services/modules/vip-api';
import { useAccountInfo } from '@/hooks/use-api';
import { centToYuan, formatDate } from '@/utils/display';
const {Text, Title} = Typography;
/** 将分转为元,保留两位小数 */
function centToYuan(cent: number): string {
return (cent / 100).toFixed(2);
}
/** 格式化日期 */
function formatDate(date: Date | string | undefined): string {
if (!date) return '—';
const d = typeof date === 'string' ? new Date(date) : date;
return d.toLocaleDateString('zh-CN', {year: 'numeric', month: '2-digit', day: '2-digit'});
}
export function AccountInfo() {
const {token} = antTheme.useToken();
const [userInfo, setUserInfo] = useState<UserInfoBody | null>(null);
const [vipsInfo, setVipsInfo] = useState<VipLevelsItem[] | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const load = useCallback(async () => {
setLoading(true);
setError(null);
try {
const info: UserInfoBody = await AuthAPI.getUserInfo();
const vips: VipLevelsItem[] = await VipAPI.getVipLevels();
setVipsInfo(vips);
setUserInfo(info);
} catch (err) {
setError((err as Error).message || '加载账户信息失败');
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
void load();
}, [load]);
const { data, loading, error, errorMessage, refetch } = useAccountInfo();
// ======== 加载态 ========
if (loading) {
@@ -71,14 +38,14 @@ export function AccountInfo() {
}
// ======== 错误态 ========
if (error || !userInfo) {
if (error || !data) {
return (
<Result
status="error"
title="加载失败"
subTitle={error || '未能获取账户信息'}
subTitle={errorMessage || '未能获取账户信息'}
extra={
<Button type="primary" onClick={load}>
<Button type="primary" onClick={refetch}>
</Button>
}
@@ -87,6 +54,7 @@ export function AccountInfo() {
}
// ======== 数据展示 ========
const [userInfo, vipsInfo] = data;
const totalBalance: number = userInfo.balance_cent + userInfo.gift_balance_cent;
// 匹配当前 VIP 等级vip_level_id → VipLevelsItem

View File

@@ -0,0 +1,281 @@
import {useState, useMemo} from 'react';
import {
Card,
Table,
Button,
Typography,
Skeleton,
Result,
Space,
Tag,
theme as antTheme,
} from 'antd';
import {
WalletOutlined,
RiseOutlined,
ApiOutlined,
} from '@ant-design/icons';
import {useBillingBalance, useBillingLedger} from '@/hooks/use-api';
import type {LedgerItemResponseBody, LedgerReqeustParam} from '@/services/modules/billing';
import {centToYuan, formatDate} from '@/utils/display';
const {Text, Title} = Typography;
// ============================================================
// 余额卡片
// ============================================================
function BalanceCard() {
const {token} = antTheme.useToken();
const {data, loading, error, errorMessage, refetch} = useBillingBalance();
// ======== 加载态 ========
if (loading) {
return (
<Card size="small" className="rounded-md!">
<Skeleton active paragraph={{rows: 3}} />
</Card>
);
}
// ======== 错误态 ========
if (error || !data) {
return (
<Card size="small" className="rounded-md!">
<Result
status="error"
title="余额加载失败"
subTitle={errorMessage}
extra={
<Button type="primary" size="small" onClick={refetch}>
</Button>
}
/>
</Card>
);
}
// ======== 正常展示 ========
const totalBalance = (data.balance_cent ?? 0) + (data.gift_balance_cent ?? 0);
return (
<Card
size="small"
styles={{body: {padding: '16px 20px'}}}
className="rounded-md!"
>
<Text type="secondary" style={{fontSize: 12, marginBottom: 8, display: 'block'}}>
<WalletOutlined style={{marginRight: 6}} />
</Text>
<Title level={3} style={{margin: '0 0 12px 0'}}>
{centToYuan(totalBalance)}
<Text type="secondary" style={{fontSize: 14, marginLeft: 4}}>
{data.currency}
</Text>
</Title>
<Space size={32}>
<div>
<Text type="secondary" style={{fontSize: 12}}></Text>
<br />
<Text strong>{centToYuan(data.balance_cent ?? 0)}</Text>
</div>
<div>
<Text type="secondary" style={{fontSize: 12}}></Text>
<br />
<Text strong>{centToYuan(data.gift_balance_cent ?? 0)}</Text>
</div>
<div>
<Space size={4}>
<RiseOutlined style={{color: token.colorWarning}} />
<Text type="secondary" style={{fontSize: 12}}></Text>
</Space>
<br />
<Text strong>{centToYuan(data.today_spent_cent)}</Text>
</div>
<div>
<Space size={4}>
<ApiOutlined style={{color: token.colorPrimary}} />
<Text type="secondary" style={{fontSize: 12}}></Text>
</Space>
<br />
<Text strong>{data.today_calls} </Text>
</div>
</Space>
</Card>
);
}
// ============================================================
// 账单表格
// ============================================================
/** entry_type → 中文标签映射(按需扩展) */
const ENTRY_TYPE_LABELS: Record<string, string> = {
task_cost: '任务消耗',
recharge: '充值',
gift: '赠送',
refund: '退款',
vip_purchase: '套餐购买',
};
function resolveEntryLabel(type: string): string {
return ENTRY_TYPE_LABELS[type] || type;
}
/** entry_type → Tag 颜色映射 */
function entryTypeColor(type: string): string {
if (type === 'task_cost' || type === 'vip_purchase') return 'orange';
if (type === 'recharge' || type === 'gift') return 'green';
if (type === 'refund') return 'blue';
return 'default';
}
function LedgerTable() {
const {token} = antTheme.useToken();
const [pagination, setPagination] = useState({page: 1, page_size: 10});
const params: LedgerReqeustParam = useMemo(() => ({
month: null,
page: pagination.page,
page_size: pagination.page_size,
}), [pagination]);
const {data, loading, error, errorMessage, refetch} = useBillingLedger(params);
const columns = [
{
title: '时间',
dataIndex: 'created_at',
key: 'created_at',
width: 120,
align: 'center' as const,
render: (_: unknown, record: LedgerItemResponseBody) => (
<Text style={{fontSize: 12, whiteSpace: 'nowrap'}}>
{formatDate(record.created_at)}
</Text>
),
},
{
title: '类型',
dataIndex: 'entry_type',
key: 'entry_type',
width: 100,
align: 'center' as const,
render: (type: string) => (
<Tag color={entryTypeColor(type)} style={{fontSize: 11, lineHeight: '18px'}}>
{resolveEntryLabel(type)}
</Tag>
),
},
{
title: '金额',
dataIndex: 'amount_cent',
key: 'amount_cent',
width: 100,
align: 'center' as const,
render: (amount: number): React.ReactNode => {
const isNegative = amount < 0;
return (
<Text
strong
style={{
fontSize: 13,
color: isNegative ? token.colorError : token.colorSuccess,
}}
>
{isNegative ? '-' : '+'}
{centToYuan(Math.abs(amount))}
</Text>
);
},
},
{
title: '余额',
dataIndex: 'balance_after_cent',
key: 'balance_after_cent',
width: 100,
align: 'center' as const,
render: (val: number) => (
<Text style={{fontSize: 12}}>{centToYuan(val)}</Text>
),
},
{
title: '描述',
dataIndex: 'description',
key: 'description',
ellipsis: true,
align: 'left' as const,
render: (desc: string) => (
<Text style={{fontSize: 12}}>{desc || '—'}</Text>
),
},
];
// ======== 错误态 ========
if (error) {
return (
<Card size="small" className="rounded-md!">
<Result
status="error"
title="账单加载失败"
subTitle={errorMessage}
extra={
<Button type="primary" size="small" onClick={refetch}>
</Button>
}
/>
</Card>
);
}
// ======== 正常 / 加载态 ========
return (
<Card
size="small"
styles={{body: {padding: 0}}}
className="rounded-md!"
>
<Table<LedgerItemResponseBody>
columns={columns}
dataSource={data ?? []}
rowKey="id"
loading={loading}
size="small"
pagination={{
current: pagination.page,
pageSize: pagination.page_size,
total: (data ?? []).length >= pagination.page_size
? pagination.page * pagination.page_size + 1
: pagination.page * pagination.page_size,
showSizeChanger: true,
pageSizeOptions: ['10', '20', '50'],
showTotal: (total: number, range: [number, number]) =>
`${range[0]}-${range[1]},共 ${total}+ 条`,
onChange: (page: number, pageSize: number) => {
setPagination({page, page_size: pageSize});
},
position: ['bottomCenter'],
}}
locale={{emptyText: '暂无消费记录'}}
/>
</Card>
);
}
// ============================================================
// 页面入口
// ============================================================
export function BillingInfo() {
return (
<div style={{padding: '8px 0', width: '100%'}}>
<div className="flex flex-col gap-4" style={{width: '100%'}}>
<BalanceCard />
<LedgerTable />
</div>
</div>
);
}

View File

@@ -1,9 +0,0 @@
import {Component} from "react";
export class Test1 extends Component {
render() {
return (
<></>
);
}
}

View File

@@ -714,7 +714,7 @@ export function TaskHistory({ allModels }: TaskHistoryProps) {
</div>
{/* 表格 — 横向 + 纵向滚动,筛选/排序通过列头操作 */}
<div ref={tableWrapperRef} style={{ flex: 1, overflow: 'hidden', minHeight: 0 }}>
<div ref={tableWrapperRef} style={{ flex: 1, overflow: 'hidden', minHeight: Math.min(window.outerHeight, window.outerHeight, 630) }}>
<style>{tableCss}</style>
<Table<TaskInfoItemResponseBody>
className="task-table"