Initial import of weiyuan frontend

This commit is contained in:
qiubaishen
2026-10-15 16:33:46 +08:00
commit d8f3aee261
774 changed files with 374914 additions and 0 deletions
+731
View File
@@ -0,0 +1,731 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useState, useEffect, useContext, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import {
Typography,
Button,
Input,
Table,
Tabs,
TabPane,
Modal,
Spin,
Empty,
Tag,
} from '@douyinfe/semi-ui';
import {
Copy,
Users,
BarChart2,
TrendingUp,
Gift,
Zap,
CreditCard,
DollarSign,
Sparkles,
UserPlus,
Link,
} from 'lucide-react';
import { UserContext } from '../../context/User';
import { StatusContext } from '../../context/Status';
import {
API,
showError,
showSuccess,
renderQuota,
copy,
getQuotaPerUnit,
timestamp2string,
} from '../../helpers';
import { MarkdownRenderer } from '../../components/common/markdown/MarkdownRenderer';
import QuotaInput from '../../components/common/ui/QuotaInput';
const { Text } = Typography;
const Invite = () => {
const { t } = useTranslation();
const [userState, userDispatch] = useContext(UserContext);
const [statusState] = useContext(StatusContext);
// 获取配置的奖励说明
const inviteRebateDescription =
statusState?.status?.invite_rebate_description || '';
// 统计数据
const [stats, setStats] = useState({
total_invitees: 0,
total_rebate_quota: 0,
total_rebate_count: 0,
current_aff_quota: 0,
rebate_rate: 0,
aff_code: '',
});
const [loading, setLoading] = useState(true);
// 邀请链接
const [affLink, setAffLink] = useState('');
const affFetchedRef = useRef(false);
// 划转相关
const [openTransfer, setOpenTransfer] = useState(false);
const [transferAmount, setTransferAmount] = useState(0);
const [transferLoading, setTransferLoading] = useState(false);
// 绑定邀请人相关
const [openBindInviter, setOpenBindInviter] = useState(false);
const [inviterCode, setInviterCode] = useState('');
const [bindLoading, setBindLoading] = useState(false);
// 邀请人员明细
const [invitees, setInvitees] = useState([]);
const [inviteesLoading, setInviteesLoading] = useState(false);
const [inviteesTotal, setInviteesTotal] = useState(0);
const [inviteesPage, setInviteesPage] = useState(1);
// 收益明细
const [rebates, setRebates] = useState([]);
const [rebatesLoading, setRebatesLoading] = useState(false);
const [rebatesTotal, setRebatesTotal] = useState(0);
const [rebatesPage, setRebatesPage] = useState(1);
const pageSize = 10;
// 获取统计信息
const fetchStats = async () => {
try {
const res = await API.get('/api/user/self/invite/stats');
if (res.data.success) {
setStats(res.data.data);
} else {
showError(res.data.message);
}
} catch (error) {
showError(error.message);
}
};
// 获取邀请链接
const getAffLink = async () => {
try {
const res = await API.get('/api/user/aff');
if (res.data.success) {
let link = res.data.data;
if (typeof link !== 'string' || !link.startsWith('http')) {
link = `${window.location.origin}/register?aff=${link}`;
}
setAffLink(link);
}
} catch (error) {
console.error('获取邀请链接失败:', error);
}
};
// 获取邀请人员明细
const fetchInvitees = async (page = 1) => {
setInviteesLoading(true);
try {
const res = await API.get(
`/api/user/self/invite/invitees?page=${page}&size=${pageSize}`,
);
if (res.data.success) {
setInvitees(res.data.data || []);
setInviteesTotal(res.data.total || 0);
} else {
showError(res.data.message);
}
} catch (error) {
showError(error.message);
} finally {
setInviteesLoading(false);
}
};
// 获取收益明细
const fetchRebates = async (page = 1) => {
setRebatesLoading(true);
try {
const res = await API.get(
`/api/user/self/invite/rebates?page=${page}&size=${pageSize}`,
);
if (res.data.success) {
setRebates(res.data.data || []);
setRebatesTotal(res.data.total || 0);
} else {
showError(res.data.message);
}
} catch (error) {
showError(error.message);
} finally {
setRebatesLoading(false);
}
};
// 初始化加载
useEffect(() => {
const init = async () => {
setLoading(true);
await Promise.all([fetchStats(), fetchInvitees(1), fetchRebates(1)]);
if (!affFetchedRef.current) {
affFetchedRef.current = true;
await getAffLink();
}
setLoading(false);
};
init();
}, []);
// 复制邀请链接
const handleCopyLink = () => {
if (!affLink) {
showError(t('邀请链接获取中,请稍后'));
return;
}
copy(affLink, t('邀请链接'));
};
// 划转额度
const handleTransfer = async () => {
if (transferAmount < getQuotaPerUnit()) {
showError(t('划转额度不能小于最低额度'));
return;
}
setTransferLoading(true);
try {
const res = await API.post('/api/user/aff_transfer', {
quota: transferAmount,
});
if (res.data.success) {
showSuccess(t('划转成功'));
setOpenTransfer(false);
setTransferAmount(0);
// 刷新数据
await fetchStats();
// 更新用户状态
const userRes = await API.get('/api/user/self');
if (userRes.data.success) {
userDispatch({ type: 'login', payload: userRes.data.data });
}
} else {
showError(res.data.message);
}
} catch (error) {
showError(error.message);
} finally {
setTransferLoading(false);
}
};
// 绑定邀请人
const handleBindInviter = async () => {
if (!inviterCode.trim()) {
showError(t('请输入邀请码'));
return;
}
setBindLoading(true);
try {
const res = await API.post('/api/user/bind_inviter', {
aff_code: inviterCode.trim(),
});
if (res.data.success) {
showSuccess(t('绑定邀请人成功'));
setOpenBindInviter(false);
setInviterCode('');
// 更新用户状态
const userRes = await API.get('/api/user/self');
if (userRes.data.success) {
userDispatch({ type: 'login', payload: userRes.data.data });
}
} else {
showError(res.data.message);
}
} catch (error) {
showError(error.message);
} finally {
setBindLoading(false);
}
};
// 邀请人员列配置
const inviteeColumns = [
{
title: t('用户名'),
dataIndex: 'display_name',
key: 'display_name',
},
{
title: t('注册时间'),
dataIndex: 'created_at',
key: 'created_at',
render: (text) => (text ? timestamp2string(text) : '-'),
},
{
title: t('累计消费'),
dataIndex: 'total_consume',
key: 'total_consume',
render: (text) => renderQuota(text || 0),
},
{
title: t('累计返佣'),
dataIndex: 'total_rebate',
key: 'total_rebate',
render: (text) => (
<Tag color='green' size='small'>
{renderQuota(text || 0)}
</Tag>
),
},
];
// 收益明细列配置
const rebateColumns = [
{
title: t('被邀请人'),
dataIndex: 'invitee_name',
key: 'invitee_name',
},
{
title: t('消费额度'),
dataIndex: 'consume_quota',
key: 'consume_quota',
render: (text) => renderQuota(text || 0),
},
{
title: t('返佣额度'),
dataIndex: 'rebate_quota',
key: 'rebate_quota',
render: (text) => (
<Tag color='green' size='small'>
+{renderQuota(text || 0)}
</Tag>
),
},
{
title: t('返佣比例'),
dataIndex: 'rebate_rate',
key: 'rebate_rate',
render: (text) => `${((text || 0) * 100).toFixed(0)}%`,
},
{
title: t('模型'),
dataIndex: 'model_name',
key: 'model_name',
render: (text) => text || '-',
},
{
title: t('时间'),
dataIndex: 'created_at',
key: 'created_at',
render: (text) => (text ? timestamp2string(text) : '-'),
},
];
if (loading) {
return (
<div className='flex items-center justify-center h-64'>
<Spin size='large' />
</div>
);
}
return (
<div className='relative p-4 sm:p-6'>
<div className='pointer-events-none absolute inset-0 -z-10 bg-[radial-gradient(circle_at_8%_8%,rgba(14,165,233,0.12),transparent_28%),radial-gradient(circle_at_92%_12%,rgba(244,63,94,0.10),transparent_30%)]' />
{/* Page header */}
<div className='mb-6 flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between'>
<div className='flex items-center gap-3'>
<div className='flex h-12 w-12 items-center justify-center rounded-2xl bg-white/70 text-rose-500 shadow-[0_14px_34px_rgba(244,63,94,0.16)] ring-1 ring-white/70 backdrop-blur dark:bg-white/[0.06] dark:ring-white/10'>
<Gift size={23} />
</div>
<div>
<h1 className='flex items-center gap-2 text-2xl font-bold text-gray-950 dark:text-white'>
{t('\u9080\u8bf7\u6709\u5956')}
<Sparkles size={18} className='text-rose-500' />
</h1>
<p className='text-sm text-gray-500 dark:text-gray-400'>
{t('\u9080\u8bf7\u597d\u53cb\uff0c\u5171\u4eab\u5956\u52b1')}
</p>
</div>
</div>
<div className='flex flex-wrap gap-2'>
<Button
type='primary'
theme='solid'
disabled={!stats.current_aff_quota || stats.current_aff_quota <= 0}
onClick={() => {
setTransferAmount(stats.current_aff_quota || 0);
setOpenTransfer(true);
}}
icon={<Zap size={15} />}
className='!rounded-full !border-0 !bg-gradient-to-r !from-rose-500 !to-orange-400 !px-4 !shadow-lg !shadow-rose-500/20'
>
{t('\u5212\u8f6c\u5230\u4f59\u989d')}
</Button>
{stats.inviter_id === 0 && statusState?.status?.bind_inviter_enabled && (
<Button
theme='light'
type='primary'
icon={<UserPlus size={15} />}
onClick={() => setOpenBindInviter(true)}
className='!rounded-full !border !border-sky-200 !bg-sky-50/80 !px-4 !text-sky-700 dark:!border-sky-400/20 dark:!bg-sky-400/[0.08] dark:!text-sky-300'
>
{t('\u7ed1\u5b9a\u9080\u8bf7\u4eba')}
</Button>
)}
</div>
</div>
{/* Stats overview */}
<div className='mb-5 grid grid-cols-1 gap-3 md:grid-cols-3'>
{[
{
label: t('\u9080\u8bf7\u94fe\u63a5'),
value: renderQuota(stats.current_aff_quota || 0),
icon: TrendingUp,
tone: 'text-rose-500 bg-rose-50 dark:bg-rose-500/[0.09]',
},
{
label: t('\u5f85\u4f7f\u7528\u6536\u76ca'),
value: renderQuota(stats.total_rebate_quota || 0),
icon: BarChart2,
tone: 'text-emerald-500 bg-emerald-50 dark:bg-emerald-500/[0.09]',
},
{
label: t('\u603b\u6536\u76ca'),
value: stats.total_invitees || 0,
icon: Users,
tone: 'text-sky-500 bg-sky-50 dark:bg-sky-500/[0.09]',
},
].map((item) => {
const Icon = item.icon;
return (
<div
key={item.label}
className='rounded-[24px] border border-white/70 bg-white/[0.58] p-5 shadow-[0_18px_50px_rgba(15,23,42,0.07)] backdrop-blur-xl dark:border-white/10 dark:bg-white/[0.045]'
>
<div className='mb-4 flex items-center justify-between'>
<span className={`flex h-10 w-10 items-center justify-center rounded-2xl ${item.tone}`}>
<Icon size={19} />
</span>
{item.label === t('\u9080\u8bf7\u4eba\u6570') && stats.rebate_rate > 0 && (
<span className='rounded-full bg-amber-50 px-2.5 py-1 text-xs font-semibold text-amber-700 dark:bg-amber-500/[0.10] dark:text-amber-300'>
{(stats.rebate_rate * 100).toFixed(0)}%
</span>
)}
</div>
<div className='text-2xl font-bold text-gray-950 dark:text-white'>
{item.value}
</div>
<div className='mt-1 text-sm text-gray-500 dark:text-gray-400'>
{item.label}
</div>
</div>
);
})}
</div>
{/* Invite link */}
<div className='mb-5 rounded-[24px] border border-white/70 bg-white/[0.58] p-3 shadow-[0_18px_50px_rgba(15,23,42,0.07)] backdrop-blur-xl dark:border-white/10 dark:bg-white/[0.045]'>
<div className='flex flex-col gap-3 lg:flex-row lg:items-center'>
<div className='flex min-w-0 flex-1 items-center gap-3 rounded-2xl bg-white/60 px-3 py-2 ring-1 ring-white/70 dark:bg-white/[0.055] dark:ring-white/10'>
<Link size={17} className='shrink-0 text-sky-500' />
<span className='shrink-0 text-sm font-semibold text-gray-700 dark:text-gray-200'>
{t('\u603b\u6536\u76ca')}
</span>
<Input
value={affLink}
readonly
borderless
className='min-w-0 flex-1 font-mono text-sm'
/>
</div>
<Button
type='primary'
theme='solid'
size='large'
onClick={handleCopyLink}
icon={<Copy size={16} />}
className='!rounded-full !border-0 !bg-gradient-to-r !from-rose-500 !to-orange-400 !px-6 !shadow-lg !shadow-rose-500/20'
>
{t('\u590d\u5236')}
</Button>
</div>
</div>
{/* Invite relation */}
{stats.inviter_id > 0 && (
<div className='mb-5 rounded-[22px] border border-emerald-200/70 bg-emerald-50/70 p-4 backdrop-blur-xl dark:border-emerald-400/20 dark:bg-emerald-500/[0.08]'>
<div className='flex items-center gap-3'>
<div className='flex h-10 w-10 items-center justify-center rounded-2xl bg-emerald-500 text-white'>
<Users size={19} />
</div>
<div>
<h3 className='font-semibold text-gray-900 dark:text-white'>
{t('\u6211\u7684\u9080\u8bf7\u4eba')}
</h3>
<p className='text-sm text-gray-500 dark:text-gray-400'>
{stats.inviter_name || t('\u672a\u77e5\u7528\u6237')}
<span className='ml-2 text-emerald-600 dark:text-emerald-300'>
({t('\u60a8\u7684\u6d88\u8d39\u5c06\u4e3aTA\u5e26\u6765\u8fd4\u4f63\u6536\u76ca')})
</span>
</p>
</div>
</div>
</div>
)}
{/* Bind inviter entry */}
{stats.inviter_id === 0 &&
statusState?.status?.bind_inviter_enabled &&
(() => {
const bindInviterDays = statusState?.status?.bind_inviter_days || 0;
const userCreatedAt = userState?.user?.created_at || 0;
const now = Math.floor(Date.now() / 1000);
let isInTimeRange = true;
let remainingDays = -1;
if (userCreatedAt > 0 && bindInviterDays > 0) {
const deadline = userCreatedAt + bindInviterDays * 86400;
isInTimeRange = now <= deadline;
remainingDays = Math.max(0, Math.ceil((deadline - now) / 86400));
}
if (!isInTimeRange) return null;
return (
<div className='mb-5 rounded-[22px] border border-sky-200/80 bg-sky-50/70 p-4 backdrop-blur-xl dark:border-sky-400/20 dark:bg-sky-500/[0.08]'>
<div className='flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between'>
<div className='flex items-center gap-3'>
<div className='flex h-10 w-10 items-center justify-center rounded-2xl bg-sky-500 text-white'>
<UserPlus size={19} />
</div>
<div>
<h3 className='font-semibold text-gray-900 dark:text-white'>
{t('\u7ed1\u5b9a\u9080\u8bf7\u4eba')}
</h3>
<p className='text-sm text-gray-500 dark:text-gray-400'>
{t('\u7ed1\u5b9a\u540e\u60a8\u7684\u6d88\u8d39\u5c06\u4e3a\u9080\u8bf7\u4eba\u5e26\u6765\u8fd4\u4f63\u6536\u76ca')}
{remainingDays > 0 && (
<span className='ml-2 text-amber-600 dark:text-amber-300'>
({t('\u5269\u4f59')} {remainingDays} {t('\u5929')})
</span>
)}
</p>
</div>
</div>
<Button
type='primary'
theme='solid'
onClick={() => setOpenBindInviter(true)}
icon={<Link size={16} />}
className='!rounded-full !border-0 !bg-gradient-to-r !from-sky-500 !to-cyan-400 !px-5'
>
{t('\u7ed1\u5b9a')}
</Button>
</div>
</div>
);
})()}
{/* Bind inviter entry */}
<div className='mb-5 overflow-hidden rounded-[24px] border border-white/70 bg-white/[0.58] shadow-[0_18px_50px_rgba(15,23,42,0.07)] backdrop-blur-xl dark:border-white/10 dark:bg-white/[0.045]'>
<Tabs type='button' className='invite-detail-tabs !p-4'>
<TabPane
tab={
<span className='flex items-center'>
<Users size={16} className='mr-2' />
{t('\u9080\u8bf7\u4eba\u5458\u660e\u7ec6')}
</span>
}
itemKey='invitees'
>
<Table
columns={inviteeColumns}
dataSource={invitees}
loading={inviteesLoading}
pagination={{
currentPage: inviteesPage,
pageSize: pageSize,
total: inviteesTotal,
onPageChange: (page) => {
setInviteesPage(page);
fetchInvitees(page);
},
}}
className='invite-clean-table'
empty={
<Empty
image={<Users size={48} className='text-gray-300' />}
description={t('\u6682\u65e0\u9080\u8bf7\u8bb0\u5f55')}
/>
}
/>
</TabPane>
<TabPane
tab={
<span className='flex items-center'>
<DollarSign size={16} className='mr-2' />
{t('\u6536\u76ca\u660e\u7ec6')}
</span>
}
itemKey='rebates'
>
<Table
columns={rebateColumns}
dataSource={rebates}
loading={rebatesLoading}
pagination={{
currentPage: rebatesPage,
pageSize: pageSize,
total: rebatesTotal,
onPageChange: (page) => {
setRebatesPage(page);
fetchRebates(page);
},
}}
className='invite-clean-table'
empty={
<Empty
image={<DollarSign size={48} className='text-gray-300' />}
description={t('\u6682\u65e0\u6536\u76ca\u8bb0\u5f55')}
/>
}
/>
</TabPane>
</Tabs>
</div>
{/* Detail lists */}
<div className='rounded-[24px] border border-white/70 bg-white/[0.58] p-5 shadow-[0_18px_50px_rgba(15,23,42,0.07)] backdrop-blur-xl dark:border-white/10 dark:bg-white/[0.045]'>
<h3 className='mb-4 flex items-center gap-2 text-lg font-semibold text-gray-900 dark:text-white'>
<Gift size={18} className='text-rose-500' />
{t('\u5956\u52b1\u8bf4\u660e')}
</h3>
{inviteRebateDescription ? (
<MarkdownRenderer content={inviteRebateDescription} fontSize={14} />
) : (
<div className='grid gap-3 md:grid-cols-3'>
{[
t('\u9080\u8bf7\u597d\u53cb\u6ce8\u518c\u5e76\u4f7f\u7528\uff0c\u597d\u53cb\u6d88\u8d39\u540e\u60a8\u5c06\u6309\u6bd4\u4f8b\u83b7\u5f97\u8fd4\u4f63\u5956\u52b1'),
t('\u8fd4\u4f63\u5956\u52b1\u4f1a\u7d2f\u79ef\u5230\u60a8\u7684\u9080\u8bf7\u989d\u5ea6\u4e2d\uff0c\u53ef\u901a\u8fc7"\u5212\u8f6c\u5230\u4f59\u989d"\u529f\u80fd\u8f6c\u5165\u8d26\u6237\u4f59\u989d\u4f7f\u7528'),
t('\u9080\u8bf7\u7684\u597d\u53cb\u8d8a\u591a\u3001\u597d\u53cb\u6d88\u8d39\u8d8a\u591a\uff0c\u60a8\u83b7\u5f97\u7684\u5956\u52b1\u5c31\u8d8a\u591a'),
].map((item) => (
<div
key={item}
className='rounded-2xl border border-white/70 bg-white/50 p-4 text-sm text-gray-600 dark:border-white/10 dark:bg-white/[0.04] dark:text-gray-300'
>
<span className='mb-3 block h-1.5 w-8 rounded-full bg-gradient-to-r from-rose-500 to-orange-400' />
{item}
</div>
))}
</div>
)}
</div>
<Modal
title={
<div className='flex items-center'>
<CreditCard className='mr-2 text-pink-500' size={18} />
{t('划转邀请额度')}
</div>
}
visible={openTransfer}
onOk={handleTransfer}
onCancel={() => {
setOpenTransfer(false);
setTransferAmount(0);
}}
confirmLoading={transferLoading}
maskClosable={false}
centered
>
<div className='space-y-4'>
<div>
<Typography.Text strong className='block mb-2'>
{t('可用邀请额度')}
</Typography.Text>
<Input
value={renderQuota(stats.current_aff_quota || 0)}
disabled
className='!rounded-lg'
/>
</div>
<div>
<Typography.Text strong className='block mb-2'>
{t('划转额度')} ({t('最低')} {renderQuota(getQuotaPerUnit())})
</Typography.Text>
<QuotaInput
minQuota={getQuotaPerUnit()}
maxQuota={stats.current_aff_quota || 0}
value={transferAmount}
onChange={(value) => setTransferAmount(value)}
className='w-full !rounded-lg'
/>
</div>
</div>
</Modal>
{/* 绑定邀请人Modal */}
<Modal
title={
<div className='flex items-center'>
<UserPlus className='mr-2 text-brand' size={18} />
{t('绑定邀请人')}
</div>
}
visible={openBindInviter}
onOk={handleBindInviter}
onCancel={() => {
setOpenBindInviter(false);
setInviterCode('');
}}
confirmLoading={bindLoading}
maskClosable={false}
centered
okText={t('确认绑定')}
cancelText={t('取消')}
>
<div className='space-y-4'>
<div className='p-3 bg-amber-50 dark:bg-amber-900/20 rounded-lg border border-amber-200 dark:border-amber-800'>
<Text className='text-amber-700 dark:text-amber-300 text-sm'>
{t('绑定邀请人后无法修改,请确认邀请码正确')}
</Text>
</div>
<div>
<Typography.Text strong className='block mb-2'>
{t('邀请码')}
</Typography.Text>
<Input
value={inviterCode}
onChange={(value) => setInviterCode(value)}
placeholder={t('请输入邀请人的邀请码')}
size='large'
className='!rounded-lg'
prefix={<Link size={16} className='text-gray-400' />}
/>
</div>
</div>
</Modal>
</div>
);
};
export default Invite;
+667
View File
@@ -0,0 +1,667 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useState, useEffect, useCallback, useContext } from 'react';
import { useTranslation } from 'react-i18next';
import {
Card,
Table,
Button,
Input,
Tag,
Tabs,
TabPane,
Modal,
Checkbox,
Typography,
Empty,
Spin,
} from '@douyinfe/semi-ui';
import {
Receipt,
Plus,
Download,
Eye,
X,
} from 'lucide-react';
import { API, showError, showSuccess } from '../../helpers';
import {
INVOICE_STATUS,
INVOICE_STATUS_TEXT,
INVOICE_STATUS_COLOR,
} from '../../constants';
import { StatusContext } from '../../context/Status';
const { Text } = Typography;
const paymentMethodMap = {
wechat: '微信',
alipay: '支付宝',
stripe: 'Stripe',
creem: 'Creem',
epay: '易支付',
};
const Invoice = () => {
const { t } = useTranslation();
const [statusState] = useContext(StatusContext);
const nuonuoEnabled = statusState?.status?.nuonuo_enabled === true;
// 申请开票 Tab 状态
const [availableTopups, setAvailableTopups] = useState([]);
const [selectedTopupIds, setSelectedTopupIds] = useState([]);
const [topupsLoading, setTopupsLoading] = useState(false);
const [invoiceTitle, setInvoiceTitle] = useState('');
const [taxId, setTaxId] = useState('');
const [email, setEmail] = useState('');
const [saveTitle, setSaveTitle] = useState(false);
const [submitting, setSubmitting] = useState(false);
// 常用开票信息
const [titles, setTitles] = useState([]);
const [selectedTitleId, setSelectedTitleId] = useState(null);
// 开票记录 Tab 状态
const [invoices, setInvoices] = useState([]);
const [invoicesTotal, setInvoicesTotal] = useState(0);
const [invoicesPage, setInvoicesPage] = useState(1);
const [invoicesLoading, setInvoicesLoading] = useState(false);
// 详情弹窗
const [detailVisible, setDetailVisible] = useState(false);
const [detailData, setDetailData] = useState(null);
const [detailLoading, setDetailLoading] = useState(false);
// 加载可开票的充值记录
const fetchAvailableTopups = useCallback(async () => {
setTopupsLoading(true);
try {
const res = await API.get('/api/user/invoice/available-topups');
if (res.data.success) {
setAvailableTopups(res.data.data || []);
}
} catch (err) {
showError(err.message);
} finally {
setTopupsLoading(false);
}
}, []);
// 加载常用开票信息
const fetchTitles = useCallback(async () => {
try {
const res = await API.get('/api/user/invoice/titles');
if (res.data.success) {
setTitles(res.data.data || []);
}
} catch (err) {
// 静默处理
}
}, []);
// 加载开票记录
const fetchInvoices = useCallback(async () => {
setInvoicesLoading(true);
try {
const res = await API.get('/api/user/invoice/self', {
params: { p: invoicesPage, page_size: 10 },
});
if (res.data.success) {
setInvoices(res.data.data?.items || []);
setInvoicesTotal(res.data.data?.total || 0);
}
} catch (err) {
showError(err.message);
} finally {
setInvoicesLoading(false);
}
}, [invoicesPage]);
useEffect(() => {
if (!nuonuoEnabled) return;
fetchAvailableTopups();
fetchTitles();
}, [nuonuoEnabled, fetchAvailableTopups, fetchTitles]);
useEffect(() => {
if (!nuonuoEnabled) return;
fetchInvoices();
}, [nuonuoEnabled, fetchInvoices]);
// 计算选中记录的金额合计
const selectedAmount = availableTopups
.filter((t) => selectedTopupIds.includes(t.id))
.reduce((sum, t) => sum + (t.money || 0), 0);
// 选择常用开票信息
const handleSelectTitle = (titleId) => {
setSelectedTitleId(titleId);
const title = titles.find((t) => t.id === titleId);
if (title) {
setInvoiceTitle(title.title);
setTaxId(title.tax_id);
}
};
// 提交发票申请
const handleSubmit = async () => {
if (selectedTopupIds.length === 0) {
showError(t('请选择至少一条充值记录'));
return;
}
if (!invoiceTitle.trim()) {
showError(t('请填写发票抬头'));
return;
}
if (!taxId.trim()) {
showError(t('请填写税号'));
return;
}
if (!email.trim()) {
showError(t('请填写收件邮箱'));
return;
}
setSubmitting(true);
try {
const res = await API.post('/api/user/invoice', {
topup_ids: selectedTopupIds,
invoice_title: invoiceTitle.trim(),
tax_id: taxId.trim(),
email: email.trim(),
save_title: saveTitle,
});
if (res.data.success) {
showSuccess(t('发票申请已提交'));
// 刷新可开票记录和常用信息
fetchAvailableTopups();
if (saveTitle) fetchTitles();
// 重置到第 1 页再刷新开票记录,确保新申请可见
setInvoicesPage(1);
fetchInvoices();
// 再��置表单
setSelectedTopupIds([]);
setInvoiceTitle('');
setTaxId('');
setEmail('');
setSaveTitle(false);
setSelectedTitleId(null);
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
} finally {
setSubmitting(false);
}
};
// 取消发票申请
const handleCancel = async (id) => {
Modal.confirm({
title: t('确认取消'),
content: t('确定要取消这个发票申请吗?取消后关联的充值记录将被释放。'),
onOk: async () => {
try {
const res = await API.post('/api/user/invoice/cancel', { id });
if (res.data.success) {
showSuccess(t('已取消'));
fetchInvoices();
fetchAvailableTopups();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
},
});
};
// 查看发票详情
const handleViewDetail = async (id) => {
setDetailData(null);
setDetailVisible(true);
setDetailLoading(true);
try {
const res = await API.get(`/api/user/invoice/detail/${id}`);
if (res.data.success) {
setDetailData(res.data.data);
} else {
showError(res.data.message);
setDetailVisible(false);
}
} catch (err) {
showError(err.message);
setDetailVisible(false);
} finally {
setDetailLoading(false);
}
};
// 删除常用开票信息
const handleDeleteTitle = async (id) => {
try {
const res = await API.delete(`/api/user/invoice/titles/${id}`);
if (res.data.success) {
fetchTitles();
if (selectedTitleId === id) {
setSelectedTitleId(null);
}
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
};
const formatTime = (timestamp) => {
if (!timestamp) return '-';
return new Date(timestamp * 1000).toLocaleString();
};
// 可开票充值记录列
const topupColumns = [
{
title: '',
dataIndex: 'id',
width: 50,
render: (id) => (
<Checkbox
checked={selectedTopupIds.includes(id)}
onChange={(e) => {
if (e.target.checked) {
setSelectedTopupIds([...selectedTopupIds, id]);
} else {
setSelectedTopupIds(selectedTopupIds.filter((i) => i !== id));
}
}}
/>
),
},
{
title: t('充值时间'),
dataIndex: 'complete_time',
width: 160,
render: (v) => formatTime(v),
},
{
title: t('支付方式'),
dataIndex: 'payment_method',
width: 100,
render: (v) => (v ? paymentMethodMap[v] || v : '-'),
},
{
title: t('支付金额'),
dataIndex: 'money',
width: 100,
render: (v) => (v ? `¥${Number(v).toFixed(2)}` : '-'),
},
{
title: t('订单号'),
dataIndex: 'trade_no',
width: 200,
ellipsis: true,
render: (text) => (
<span className='text-xs font-mono' title={text}>
{text}
</span>
),
},
];
// 开票记录列
const invoiceColumns = [
{ title: 'ID', dataIndex: 'id', width: 60 },
{
title: t('发票抬头'),
dataIndex: 'invoice_title',
width: 180,
ellipsis: true,
},
{
title: t('开票金额'),
dataIndex: 'amount',
width: 100,
render: (v) => `¥${Number(v).toFixed(2)}`,
},
{
title: t('状态'),
dataIndex: 'status',
width: 90,
render: (status) => (
<Tag color={INVOICE_STATUS_COLOR[status] || 'grey'}>
{t(INVOICE_STATUS_TEXT[status] || '未知')}
</Tag>
),
},
{
title: t('申请时间'),
dataIndex: 'create_time',
width: 160,
render: (v) => formatTime(v),
},
{
title: t('操作'),
width: 160,
render: (_, record) => (
<div className='flex items-center gap-1'>
<Button
size='small'
theme='borderless'
icon={<Eye size={14} />}
onClick={() => handleViewDetail(record.id)}
>
{t('详情')}
</Button>
{record.status === INVOICE_STATUS.PENDING && (
<Button
size='small'
theme='borderless'
type='danger'
icon={<X size={14} />}
onClick={() => handleCancel(record.id)}
>
{t('取消')}
</Button>
)}
{record.status === INVOICE_STATUS.INVOICED && record.pdf_url && (
<Button
size='small'
theme='borderless'
icon={<Download size={14} />}
onClick={() =>
window.open(`/api/user/invoice/download/${record.id}`, '_blank')
}
>
{t('下载')}
</Button>
)}
</div>
),
},
];
if (!nuonuoEnabled) {
return (
<div className='p-4 sm:p-6'>
<div className='flex items-center gap-2 mb-4'>
<Receipt size={22} className='text-amber-500' />
<h1 className='text-xl font-bold text-gray-900 dark:text-white'>
{t('发票管理')}
</h1>
</div>
<Empty
image={<Receipt size={64} className='text-gray-300' />}
title={t('发票功能暂未开放')}
description={t('管理员尚未启用发票功能,请联系管理员开通。')}
/>
</div>
);
}
return (
<div className='p-4 sm:p-6'>
<div className='flex items-center gap-2 mb-4'>
<Receipt size={22} className='text-amber-500' />
<h1 className='text-xl font-bold text-gray-900 dark:text-white'>
{t('发票管理')}
</h1>
</div>
<Tabs type='line'>
<TabPane tab={t('申请开票')} itemKey='apply'>
<div className='space-y-4 mt-4'>
{/* 可开票充值记录 */}
<Card title={t('选择充值记录')} bodyStyle={{ padding: '12px' }}>
<Table
columns={topupColumns}
dataSource={availableTopups}
loading={topupsLoading}
rowKey='id'
pagination={false}
scroll={{ y: 300 }}
size='small'
empty={<Empty description={t('暂无可开票的充值记录')} />}
/>
{selectedTopupIds.length > 0 && (
<div className='mt-3 p-3 bg-amber-50 dark:bg-amber-900/20 rounded-lg flex items-center justify-between'>
<span className='text-sm text-gray-600 dark:text-gray-300'>
{t('已选择')} {selectedTopupIds.length} {t('条记录')}
</span>
<span className='text-lg font-bold text-amber-600 dark:text-amber-400'>
{t('合计')}: ¥{selectedAmount.toFixed(2)}
</span>
</div>
)}
</Card>
{/* 开票信息 */}
<Card title={t('开票信息')} bodyStyle={{ padding: '16px' }}>
<div className='space-y-3'>
{/* 常用开票信息选择 */}
{titles.length > 0 && (
<div className='flex items-center gap-2 flex-wrap'>
<Text className='text-sm'>{t('常用信息')}:</Text>
{titles.map((title) => (
<Tag
key={title.id}
color={selectedTitleId === title.id ? 'blue' : 'white'}
className='cursor-pointer'
onClick={() => handleSelectTitle(title.id)}
closable
onClose={(e) => {
e.stopPropagation();
handleDeleteTitle(title.id);
}}
>
{title.title}
</Tag>
))}
</div>
)}
<Input
prefix={
<span className='text-gray-400 text-sm'>
{t('发票抬头')}
</span>
}
value={invoiceTitle}
onChange={setInvoiceTitle}
placeholder={t('请输入公司全称')}
/>
<Input
prefix={
<span className='text-gray-400 text-sm'>{t('税号')}</span>
}
value={taxId}
onChange={setTaxId}
placeholder={t('请输入统一社会信用代码')}
/>
<Input
prefix={
<span className='text-gray-400 text-sm'>
{t('收件邮箱')}
</span>
}
value={email}
onChange={setEmail}
placeholder={t('请输入接收发票的邮箱地址')}
/>
<Checkbox
checked={saveTitle}
onChange={(e) => setSaveTitle(e.target.checked)}
>
{t('保存为常用开票信息')}
</Checkbox>
<Button
theme='solid'
type='primary'
icon={<Plus size={16} />}
loading={submitting}
onClick={handleSubmit}
disabled={selectedTopupIds.length === 0}
className='mt-2'
>
{t('提交申请')}
</Button>
</div>
</Card>
</div>
</TabPane>
<TabPane tab={t('开票记录')} itemKey='records'>
<div className='mt-4'>
<Table
columns={invoiceColumns}
dataSource={invoices}
loading={invoicesLoading}
rowKey='id'
pagination={{
currentPage: invoicesPage,
total: invoicesTotal,
pageSize: 10,
onPageChange: setInvoicesPage,
showTotal: true,
}}
scroll={{ x: 800 }}
size='small'
empty={t('暂无开票记录')}
/>
</div>
</TabPane>
</Tabs>
{/* 详情弹窗 */}
<Modal
title={t('发票详情')}
visible={detailVisible}
onCancel={() => setDetailVisible(false)}
footer={null}
width={560}
>
{detailLoading ? (
<div className='flex justify-center py-8'>
<Spin />
</div>
) : detailData ? (
<div className='space-y-3'>
<div className='flex justify-between'>
<Text>{t('状态')}</Text>
<Tag color={INVOICE_STATUS_COLOR[detailData.status] || 'grey'}>
{t(INVOICE_STATUS_TEXT[detailData.status] || '未知')}
</Tag>
</div>
<div className='flex justify-between'>
<Text>{t('发票抬头')}</Text>
<Text strong>{detailData.invoice_title}</Text>
</div>
<div className='flex justify-between'>
<Text>{t('税号')}</Text>
<Text className='font-mono text-sm'>{detailData.tax_id}</Text>
</div>
<div className='flex justify-between'>
<Text>{t('开票金额')}</Text>
<Text strong className='text-amber-600'>
¥{Number(detailData.amount).toFixed(2)}
</Text>
</div>
<div className='flex justify-between'>
<Text>{t('收件邮箱')}</Text>
<Text>{detailData.email}</Text>
</div>
<div className='flex justify-between'>
<Text>{t('申请时间')}</Text>
<Text>{formatTime(detailData.create_time)}</Text>
</div>
{detailData.invoice_number && (
<div className='flex justify-between'>
<Text>{t('发票号码')}</Text>
<Text className='font-mono'>{detailData.invoice_number}</Text>
</div>
)}
{detailData.reject_reason && (
<div className='p-3 bg-red-50 dark:bg-red-900/20 rounded-lg'>
<Text className='text-red-600 dark:text-red-400 text-sm'>
{t('拒绝原因')}: {detailData.reject_reason}
</Text>
</div>
)}
{detailData.fail_reason && (
<div className='p-3 bg-red-50 dark:bg-red-900/20 rounded-lg'>
<Text className='text-red-600 dark:text-red-400 text-sm'>
{t('失败原因')}: {detailData.fail_reason}
</Text>
</div>
)}
{/* 关联充值记录 */}
{detailData.topup_list && detailData.topup_list.length > 0 && (
<div>
<Text className='text-sm text-gray-500 mb-2 block'>
{t('关联充值记录')} ({detailData.topup_list.length} {t('笔')})
</Text>
<div className='space-y-1'>
{detailData.topup_list.map((topup) => (
<div
key={topup.id}
className='flex items-center justify-between text-sm p-2 bg-gray-50 dark:bg-gray-800 rounded'
>
<span>{formatTime(topup.complete_time)}</span>
<span>
{paymentMethodMap[topup.payment_method] ||
topup.payment_method}
</span>
<span className='font-medium'>
¥{Number(topup.money).toFixed(2)}
</span>
</div>
))}
</div>
</div>
)}
{/* 下载按钮 */}
{detailData.status === INVOICE_STATUS.INVOICED &&
detailData.pdf_url && (
<Button
theme='solid'
type='primary'
icon={<Download size={16} />}
block
onClick={() =>
window.open(
`/api/user/invoice/download/${detailData.id}`,
'_blank',
)
}
>
{t('下载发票PDF')}
</Button>
)}
</div>
) : null}
</Modal>
</div>
);
};
export default Invoice;
+216
View File
@@ -0,0 +1,216 @@
.usage-record-tab-button {
display: inline-flex;
align-items: center;
gap: 8px;
min-height: 38px;
padding: 8px 16px;
border: 1px solid rgb(255 255 255 / 0.52);
border-radius: 999px;
background:
linear-gradient(180deg, rgb(255 255 255 / 0.66), rgb(255 255 255 / 0.32)),
color-mix(in srgb, var(--brand-gradient-via) 6%, transparent);
color: rgb(71 85 105);
font-size: 14px;
font-weight: 650;
box-shadow:
0 10px 24px rgb(15 23 42 / 0.06),
inset 0 1px 0 rgb(255 255 255 / 0.58);
backdrop-filter: blur(16px) saturate(1.25);
transition:
transform 160ms ease,
box-shadow 160ms ease,
border-color 160ms ease,
color 160ms ease;
}
.usage-record-tab-button:hover {
border-color: color-mix(in srgb, var(--brand-gradient-via) 38%, white);
color: var(--brand-gradient-to);
transform: translateY(-1px);
box-shadow:
0 14px 30px rgb(15 23 42 / 0.1),
inset 0 1px 0 rgb(255 255 255 / 0.66);
}
.usage-record-tab-button-active {
border-color: rgb(255 255 255 / 0.42);
background: linear-gradient(
135deg,
#0f6fff 0%,
#0958d9 54%,
#073b91 100%
) !important;
color: #fff !important;
box-shadow:
0 16px 36px rgb(9 88 217 / 0.3),
inset 0 1px 0 rgb(255 255 255 / 0.22);
text-shadow: 0 1px 2px rgb(15 23 42 / 0.35);
}
.usage-record-tab-button-active:hover {
color: #fff !important;
}
.usage-record-tab-button-active svg {
filter: drop-shadow(0 1px 1px rgb(15 23 42 / 0.28));
}
.dark .usage-record-tab-button {
border-color: rgb(255 255 255 / 0.1);
background:
linear-gradient(180deg, rgb(255 255 255 / 0.08), rgb(255 255 255 / 0.035)),
rgb(15 23 42 / 0.32);
color: rgb(203 213 225);
box-shadow: inset 0 1px 0 rgb(255 255 255 / 0.08);
}
.dark .usage-record-tab-button:hover {
border-color: color-mix(in srgb, var(--brand-gradient-from) 34%, transparent);
color: color-mix(in srgb, var(--brand-gradient-from) 82%, white);
}
html.dark .usage-record-tab-button-active,
body[theme-mode='dark'] .usage-record-tab-button-active {
border-color: rgb(125 211 252 / 0.38);
background: linear-gradient(
135deg,
#0f6fff 0%,
#0958d9 54%,
#073b91 100%
) !important;
color: #fff !important;
}
html.dark .usage-record-tab-button-active:hover,
body[theme-mode='dark'] .usage-record-tab-button-active:hover {
color: #fff !important;
}
html.dark .usage-record-page .semi-card-header,
body[theme-mode='dark'] .usage-record-page .semi-card-header {
border-bottom-color: rgb(148 163 184 / 0.14) !important;
background:
radial-gradient(
circle at 8% 0%,
color-mix(in srgb, var(--brand-gradient-from) 12%, transparent),
transparent 34%
),
linear-gradient(180deg, rgb(15 23 42 / 0.74), rgb(15 23 42 / 0.5)) !important;
box-shadow: inset 0 1px 0 rgb(255 255 255 / 0.05);
}
html.dark .usage-record-page .usage-logs-filter-form,
body[theme-mode='dark'] .usage-record-page .usage-logs-filter-form,
html.dark .usage-record-page .usage-record-filter-form,
body[theme-mode='dark'] .usage-record-page .usage-record-filter-form {
border: 1px solid rgb(148 163 184 / 0.16) !important;
border-radius: 24px;
background:
linear-gradient(180deg, rgb(15 23 42 / 0.7), rgb(15 23 42 / 0.48)),
rgb(2 6 23 / 0.42) !important;
box-shadow:
0 18px 48px rgb(0 0 0 / 0.34),
inset 0 1px 0 rgb(255 255 255 / 0.06) !important;
backdrop-filter: blur(18px) saturate(1.1);
}
html.dark .usage-record-page .usage-record-filter-form {
padding: 16px;
}
body[theme-mode='dark'] .usage-record-page .usage-record-filter-form {
padding: 16px;
}
html.dark .usage-record-page .usage-logs-filter-title,
body[theme-mode='dark'] .usage-record-page .usage-logs-filter-title,
html.dark .usage-record-page .usage-record-filter-form > div > div:first-child,
body[theme-mode='dark']
.usage-record-page
.usage-record-filter-form
> div
> div:first-child {
border-bottom-color: rgb(148 163 184 / 0.16) !important;
}
html.dark .usage-record-page .semi-card-header .semi-input-wrapper,
body[theme-mode='dark']
.usage-record-page
.semi-card-header
.semi-input-wrapper,
html.dark .usage-record-page .semi-card-header .semi-select,
body[theme-mode='dark'] .usage-record-page .semi-card-header .semi-select,
html.dark .usage-record-page .semi-card-header .semi-datepicker,
body[theme-mode='dark'] .usage-record-page .semi-card-header .semi-datepicker,
html.dark .usage-record-page .semi-card-header .semi-datepicker-range,
body[theme-mode='dark']
.usage-record-page
.semi-card-header
.semi-datepicker-range {
border-color: rgb(148 163 184 / 0.16) !important;
background: rgb(15 23 42 / 0.58) !important;
box-shadow:
inset 0 1px 0 rgb(255 255 255 / 0.05),
0 8px 24px rgb(0 0 0 / 0.16) !important;
}
html.dark .usage-record-page .semi-card-header .semi-input-wrapper:hover,
body[theme-mode='dark']
.usage-record-page
.semi-card-header
.semi-input-wrapper:hover,
html.dark .usage-record-page .semi-card-header .semi-select:hover,
body[theme-mode='dark'] .usage-record-page .semi-card-header .semi-select:hover,
html.dark .usage-record-page .semi-card-header .semi-datepicker:hover,
body[theme-mode='dark']
.usage-record-page
.semi-card-header
.semi-datepicker:hover,
html.dark .usage-record-page .semi-card-header .semi-datepicker-range:hover,
body[theme-mode='dark']
.usage-record-page
.semi-card-header
.semi-datepicker-range:hover {
border-color: color-mix(
in srgb,
var(--brand-gradient-from) 42%,
transparent
) !important;
background: rgb(15 23 42 / 0.72) !important;
}
html.dark .usage-record-page .semi-card-header .semi-input,
body[theme-mode='dark'] .usage-record-page .semi-card-header .semi-input,
html.dark .usage-record-page .semi-card-header .semi-select-selection-text,
body[theme-mode='dark']
.usage-record-page
.semi-card-header
.semi-select-selection-text,
html.dark .usage-record-page .semi-card-header .semi-datepicker-input,
body[theme-mode='dark']
.usage-record-page
.semi-card-header
.semi-datepicker-input {
color: rgb(226 232 240) !important;
}
html.dark .usage-record-page .semi-card-header .semi-input::placeholder,
body[theme-mode='dark']
.usage-record-page
.semi-card-header
.semi-input::placeholder,
html.dark
.usage-record-page
.semi-card-header
.semi-select-selection-placeholder,
body[theme-mode='dark']
.usage-record-page
.semi-card-header
.semi-select-selection-placeholder,
html.dark .usage-record-page .semi-card-header .semi-datepicker-placeholder,
body[theme-mode='dark']
.usage-record-page
.semi-card-header
.semi-datepicker-placeholder {
color: rgb(148 163 184 / 0.82) !important;
}
+185
View File
@@ -0,0 +1,185 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useSearchParams } from 'react-router-dom';
import { BadgeCheck, Sparkles, Workflow } from 'lucide-react';
import UsageLogsTable from '../../components/table/usage-logs';
import TaskLogsTable from '../../components/table/task-logs';
import '../../styles/usage-record-controls.css';
import './UsageRecord.css';
const TAB_KEYS = {
USAGE: 'usage',
TASK: 'task',
};
// 从 URL query 解析 tab,非法值回落到 USAGE
const parseTabFromSearch = (searchParams) =>
searchParams.get('tab') === TAB_KEYS.TASK ? TAB_KEYS.TASK : TAB_KEYS.USAGE;
const UsageRecord = () => {
const { t } = useTranslation();
const [searchParams, setSearchParams] = useSearchParams();
const initialTab = parseTabFromSearch(searchParams);
const [activeTab, setActiveTab] = useState(initialTab);
// 懒挂载 + 保持挂载:首次进入 tab 才挂载,切走时保留状态(过滤条件、分页、列设置、已加载数据)
const [mountedTabs, setMountedTabs] = useState(() => new Set([initialTab]));
// URL → state 单向同步:浏览器前进/后退、外部 navigate 改变 ?tab= 时跟随更新
// 同时把目标 tab 加入挂载集合,避免空白
useEffect(() => {
const tabFromUrl = parseTabFromSearch(searchParams);
if (tabFromUrl !== activeTab) {
setActiveTab(tabFromUrl);
setMountedTabs((prev) => {
if (prev.has(tabFromUrl)) return prev;
const next = new Set(prev);
next.add(tabFromUrl);
return next;
});
}
// 仅依赖 searchParams,activeTab 不列入以防止相互触发
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [searchParams]);
const tabs = [
{
key: TAB_KEYS.USAGE,
label: t('消费记录'),
// 标题随 tab 切换显示对应的"查看什么",避免"使用记录"这种笼统措辞让用户拿不准当前页面在看什么
title: t('消费记录'),
subtitle: t('查看API调用与计费明细'),
icon: BadgeCheck,
gradient: 'from-brand-from to-brand-to',
},
{
key: TAB_KEYS.TASK,
label: t('绘图与视频'),
title: t('绘图与视频'),
subtitle: t('查看异步任务的执行状态'),
icon: Workflow,
gradient: 'from-cyan-600 to-blue-600',
},
];
const handleTabChange = (key) => {
setActiveTab(key);
setMountedTabs((prev) => {
if (prev.has(key)) return prev;
const next = new Set(prev);
next.add(key);
return next;
});
// 子页面的 hook 会用 window.history.replaceState 直接把过滤条件写进 URL,react-router 的内部
// searchParams 缓存不会感知到这些变更。如果这里用 (prev) => ...,prev 就是 react-router 的
// 陈旧缓存,会把子页面刚写入的过滤参数覆盖掉。改成直接读 window.location.search 取"当前真相"
setSearchParams(
() => {
const next = new URLSearchParams(
typeof window !== 'undefined' ? window.location.search : '',
);
if (key === TAB_KEYS.USAGE) {
next.delete('tab');
} else {
next.set('tab', key);
}
return next;
},
{ replace: true },
);
};
const currentTab = tabs.find((tab) => tab.key === activeTab);
// 浏览器页面标题随 tab 切换,利于用户多标签页对照
useEffect(() => {
const prev = document.title;
document.title = `${currentTab.title} - ${t('使用记录')}`;
return () => {
document.title = prev;
};
}, [activeTab, currentTab.title, t]);
return (
<div className='usage-record-page p-4 sm:p-6'>
<header className='mb-4 sm:mb-6 flex items-center gap-2 sm:gap-3'>
<div
className={`
relative flex items-center justify-center
w-10 h-10 sm:w-12 sm:h-12 rounded-lg sm:rounded-xl
bg-gradient-to-br ${currentTab.gradient}
shadow-lg
`}
>
<currentTab.icon
className='w-5 h-5 sm:w-6 sm:h-6 text-white'
strokeWidth={1.5}
/>
<Sparkles className='absolute -top-1 -right-1 w-3 h-3 sm:w-4 sm:h-4 text-amber-400 animate-pulse' />
</div>
<div>
<h1
className={`text-2xl font-bold bg-clip-text text-transparent bg-gradient-to-r ${currentTab.gradient}`}
>
{currentTab.title}
</h1>
<p className='text-xs sm:text-sm text-gray-500 dark:text-gray-400 mt-0.5 hidden sm:block'>
{currentTab.subtitle}
</p>
</div>
</header>
<nav className='flex gap-2 mb-4' aria-label={t('使用记录')}>
{tabs.map((tab) => {
const isActive = activeTab === tab.key;
const TabIcon = tab.icon;
return (
<button
key={tab.key}
onClick={() => handleTabChange(tab.key)}
className={`usage-record-tab-button ${
isActive
? `usage-record-tab-button-active bg-gradient-to-r ${tab.gradient}`
: ''
}`}
>
<TabIcon size={16} strokeWidth={2} />
{tab.label}
</button>
);
})}
</nav>
{mountedTabs.has(TAB_KEYS.USAGE) && (
<section hidden={activeTab !== TAB_KEYS.USAGE}>
<UsageLogsTable usageRecordMode />
</section>
)}
{mountedTabs.has(TAB_KEYS.TASK) && (
<section hidden={activeTab !== TAB_KEYS.TASK}>
<TaskLogsTable usageRecordMode />
</section>
)}
</div>
);
};
export default UsageRecord;
+335
View File
@@ -0,0 +1,335 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useMemo, useContext } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import {
BarChart2,
FileText,
CreditCard,
Receipt,
Gift,
UserCog,
ChevronLeft,
ChevronRight,
User,
Activity,
MonitorDown,
} from 'lucide-react';
import { StatusContext } from '../../context/Status';
import { UserContext } from '../../context/User';
import { isGroupAllowed } from '../../helpers/navigationVisibility';
import { useSidebarCollapsed } from '../../hooks/common/useSidebarCollapsed';
import { useWeyAiDownloadEntry } from '../../hooks/common/useWeyAiWebEntry';
const UserCenterSidebar = () => {
const { t } = useTranslation();
const location = useLocation();
const [statusState] = useContext(StatusContext);
const [userState] = useContext(UserContext);
const userGroup = userState?.user?.group || 'default';
const [collapsed, toggleCollapsed] = useSidebarCollapsed();
// WeyAi 桌面端下载入口:与顶栏「下载 WeyAi」按钮共用同一套判定
//(下载页开关 + 网页端已配置时沿用其开放范围),两处入口口径一致
const { visible: weyaiDownloadEnabled } = useWeyAiDownloadEntry();
// 获取侧边栏配置
const sidebarConfig = useMemo(() => {
const defaultConfig = {
enabled: true,
groups: [],
moduleGroups: {},
dashboard: true,
usageRecord: true,
serviceDashboard: true,
topup: true,
invoice: true,
invite: true,
settings: true,
};
try {
const configStr = statusState?.status?.SidebarModulesAdmin;
if (configStr) {
const config = JSON.parse(configStr);
const uc = config.userCenter || {};
// 向后兼容:只有旧配置同时隐藏了 usageLog 和 taskLog,才隐藏合并后的 usageRecord;
// 只隐藏其中之一时保持显示,避免用户意外失去本应可见的日志入口
if (
uc.usageRecord === undefined &&
uc.usageLog === false &&
uc.taskLog === false
) {
uc.usageRecord = false;
}
const merged = { ...defaultConfig, ...uc };
return {
...merged,
enabled:
merged.enabled !== false &&
isGroupAllowed(merged.groups, userGroup),
};
}
} catch (error) {
// 使用默认配置
}
return defaultConfig;
}, [statusState?.status?.SidebarModulesAdmin, userGroup]);
// 统一单一品牌色高亮(云平台风格):菜单项不再各用一种颜色,
// 激活态统一走 brand(azure),非激活中性灰,靠图标本身区分功能。
const allItems = useMemo(
() => [
{
itemKey: '/user-center/dashboard',
configKey: 'dashboard',
text: t('数据看板'),
icon: BarChart2,
},
{
itemKey: '/user-center/usage-record',
configKey: 'usageRecord',
text: t('使用记录'),
icon: FileText,
},
{
itemKey: '/user-center/service-dashboard',
configKey: 'serviceDashboard',
text: t('服务监控'),
icon: Activity,
},
{
itemKey: '/user-center/topup',
configKey: 'topup',
text: t('在线充值'),
icon: CreditCard,
},
{
itemKey: '/user-center/invoice',
configKey: 'invoice',
text: t('发票管理'),
icon: Receipt,
},
{
itemKey: '/user-center/invite',
configKey: 'invite',
text: t('邀请有奖'),
icon: Gift,
},
{
itemKey: '/user-center/settings',
configKey: 'settings',
text: t('个人设置'),
icon: UserCog,
},
...(weyaiDownloadEnabled
? [
{
// 指向用户中心内的嵌套路由,保持侧栏不消失;独立的 /weyai/download
// 留给未登录访客与顶栏/客户端里的链接
itemKey: '/user-center/weyai-download',
configKey: 'weyaiDownload',
text: t('下载 WeyAi 桌面端'),
icon: MonitorDown,
},
]
: []),
],
[t, weyaiDownloadEnabled],
);
// 根据配置过滤菜单项
const items = useMemo(() => {
if (!sidebarConfig.enabled) {
return [];
}
return allItems.filter(
(item) =>
sidebarConfig[item.configKey] !== false &&
isGroupAllowed(sidebarConfig.moduleGroups?.[item.configKey], userGroup),
);
}, [allItems, sidebarConfig, userGroup]);
const getSelectedKey = () => {
if (items.some((item) => item.itemKey === location.pathname)) {
return location.pathname;
}
if (
location.pathname === '/user-center' ||
location.pathname === '/user-center/'
) {
return '/user-center/dashboard';
}
return '';
};
const selectedKey = getSelectedKey();
return (
<div
className={`
relative flex flex-col h-full transition-all duration-300 ease-out
bg-white/60 dark:bg-neutral-900/60 backdrop-blur-2xl backdrop-saturate-[1.8]
border-r border-white/40 dark:border-neutral-700/50
shadow-[1px_0_24px_-4px_rgba(0,0,0,0.06)] dark:shadow-[1px_0_24px_-4px_rgba(0,0,0,0.3)]
${collapsed ? 'w-[68px]' : 'w-[240px]'}
`}
>
{/* 毛玻璃内层光泽 */}
<div className='absolute inset-0 bg-gradient-to-b from-white/40 via-white/10 to-white/20 dark:from-white/[0.06] dark:via-transparent dark:to-white/[0.03] pointer-events-none' />
{/* 顶部装饰渐变 —— 跟随品牌 */}
<div className='absolute top-0 left-0 right-0 h-32 bg-gradient-to-b from-brand/10 to-transparent pointer-events-none' />
{/* Logo/标题区域 */}
{!collapsed && (
<div className='px-4 pt-5 pb-3'>
<div className='flex items-center gap-2'>
<div className='p-1.5 bg-gradient-to-br from-brand-from to-brand-to rounded-lg shadow-md shadow-brand/25'>
<User size={16} className='text-white' />
</div>
<span className='font-bold text-gray-900 dark:text-white'>
{t('用户中心')}
</span>
</div>
</div>
)}
{/* 导航区域 */}
<nav
className={`relative flex-1 px-3 ${collapsed ? 'pt-4' : 'pt-2'} space-y-1.5 overflow-y-auto overflow-x-hidden`}
>
{items.map((item) => {
const isSelected = selectedKey === item.itemKey;
const IconComponent = item.icon;
return (
<Link
key={item.itemKey}
to={item.itemKey}
className={`
group relative flex items-center gap-3 rounded-xl transition-all duration-200
${collapsed ? 'justify-center p-3' : 'px-3 py-2.5'}
${
isSelected
? 'bg-brand/10 dark:bg-brand/15 shadow-sm shadow-brand/5'
: 'hover:bg-brand/5 dark:hover:bg-brand/10'
}
`}
>
{/* 选中指示器 —— 统一品牌色 */}
{isSelected && (
<div className='absolute left-0 top-1/2 -translate-y-1/2 w-1 h-6 rounded-r-full bg-gradient-to-b from-brand-from to-brand-to' />
)}
{/* 图标 —— 激活:品牌渐变实底白图标;非激活:中性底,hover 转品牌 */}
<div
className={`
relative flex-shrink-0 p-1.5 rounded-lg transition-all duration-200
${
isSelected
? 'bg-gradient-to-br from-brand-from to-brand-to shadow-lg shadow-brand/25'
: 'bg-gray-100/80 dark:bg-neutral-800/80 group-hover:bg-brand/10 group-hover:scale-105'
}
`}
>
<IconComponent
size={18}
strokeWidth={2}
className={
isSelected
? 'text-white'
: 'text-gray-500 dark:text-gray-400 group-hover:text-brand-deep dark:group-hover:text-brand-from transition-colors'
}
/>
</div>
{/* 文字 —— 激活品牌色加粗,非激活中性、hover 转品牌 */}
{!collapsed && (
<span
className={`
text-sm transition-colors truncate
${
isSelected
? 'text-brand-deep dark:text-brand-from font-semibold'
: 'font-medium text-gray-600 dark:text-gray-300 group-hover:text-brand-deep dark:group-hover:text-brand-from'
}
`}
>
{item.text}
</span>
)}
{/* Tooltip for collapsed state */}
{collapsed && (
<div
className='
absolute left-full ml-2 px-2.5 py-1.5
bg-gray-900 dark:bg-white text-white dark:text-gray-900
text-xs font-medium rounded-lg shadow-lg
opacity-0 invisible group-hover:opacity-100 group-hover:visible
transition-all duration-200 whitespace-nowrap z-50
'
>
{item.text}
<div
className='absolute left-0 top-1/2 -translate-x-1 -translate-y-1/2
border-4 border-transparent border-r-gray-900 dark:border-r-white'
/>
</div>
)}
</Link>
);
})}
</nav>
{/* 底部分隔线装饰 */}
<div className='mx-4 h-px bg-gradient-to-r from-transparent via-gray-200/60 dark:via-neutral-700/60 to-transparent' />
{/* 底部折叠按钮 */}
<div className='relative p-3'>
<button
onClick={toggleCollapsed}
className={`
flex items-center justify-center gap-2 w-full py-2 rounded-lg
text-gray-500 dark:text-gray-400 text-sm font-medium
bg-white/50 dark:bg-neutral-800/50
border border-gray-200/40 dark:border-neutral-700/40
hover:bg-brand/10 dark:hover:bg-brand/15
hover:text-brand-deep dark:hover:text-brand-from
hover:border-brand/30
transition-all duration-200
${collapsed ? 'px-2' : 'px-3'}
`}
>
{collapsed ? (
<ChevronRight size={16} strokeWidth={2.5} />
) : (
<>
<ChevronLeft size={16} strokeWidth={2.5} />
<span>{t('收起')}</span>
</>
)}
</button>
</div>
</div>
);
};
export default UserCenterSidebar;
+446
View File
@@ -0,0 +1,446 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useContext, useEffect, useState } from 'react';
import { Button, Progress } from '@douyinfe/semi-ui';
import { IconFilter, IconRefresh } from '@douyinfe/semi-icons';
import {
BarChart2,
Sparkles,
Activity,
Calendar,
Crown,
Zap,
Clock,
TrendingUp,
} from 'lucide-react';
import { UserContext } from '../../context/User';
import { StatusContext } from '../../context/Status';
import StatsCards from '../../components/dashboard/StatsCards';
import ChartsPanel from '../../components/dashboard/ChartsPanel';
import SearchModal from '../../components/dashboard/modals/SearchModal';
import NoticeModal from '../../components/layout/NoticeModal';
import { API, renderQuota } from '../../helpers';
import { useIsMobile } from '../../hooks/common/useIsMobile';
import { useDashboardData } from '../../hooks/dashboard/useDashboardData';
import { useDashboardStats } from '../../hooks/dashboard/useDashboardStats';
import { useDashboardCharts } from '../../hooks/dashboard/useDashboardCharts';
import {
CHART_CONFIG,
CARD_PROPS,
} from '../../constants/dashboard.constants';
import { getTrendSpec } from '../../helpers/dashboard';
const UserDashboard = () => {
// ========== Context ==========
const [userState, userDispatch] = useContext(UserContext);
const [statusState] = useContext(StatusContext);
// ========== 公告弹窗状态 ==========
const [noticeVisible, setNoticeVisible] = useState(false);
const isMobile = useIsMobile();
// ========== 会员额度数据 ==========
const [membershipInfo, setMembershipInfo] = useState(null);
const [membershipLoading, setMembershipLoading] = useState(true);
const fetchMembershipInfo = async () => {
setMembershipLoading(true);
try {
const res = await API.get('/api/user/membership/info');
const { success, data } = res.data;
if (success && data?.has_membership) {
setMembershipInfo(data);
}
} catch (err) {
console.error('获取会员信息失败:', err);
} finally {
setMembershipLoading(false);
}
};
// ========== 主要数据管理 ==========
const dashboardData = useDashboardData(userState, userDispatch, statusState);
// ========== 图表管理 ==========
const dashboardCharts = useDashboardCharts(
dashboardData.dataExportDefaultTime,
dashboardData.setTrendData,
dashboardData.setConsumeQuota,
dashboardData.setTimes,
dashboardData.setConsumeTokens,
dashboardData.setPieData,
dashboardData.setLineData,
dashboardData.setModelColors,
dashboardData.t,
);
// ========== 统计数据 ==========
const { groupedStatsData } = useDashboardStats(
userState,
dashboardData.consumeQuota,
dashboardData.consumeTokens,
dashboardData.times,
dashboardData.trendData,
dashboardData.performanceMetrics,
dashboardData.navigate,
dashboardData.t,
dashboardData.tokenUsage,
);
// ========== 数据处理 ==========
const initChart = async () => {
await Promise.all([
dashboardData.loadQuotaData().then((data) => {
if (data && data.length > 0) {
dashboardCharts.updateChartData(data);
}
}),
dashboardData.loadTokenUsageData(),
dashboardData.getUserData(),
fetchMembershipInfo(),
]);
};
const handleSearchConfirm = async () => {
const [data] = await Promise.all([
dashboardData.loadQuotaData(),
dashboardData.loadTokenUsageData(),
]);
if (data && data.length > 0) {
dashboardCharts.updateChartData(data);
}
dashboardData.handleCloseModal();
};
// ========== Effects ==========
useEffect(() => {
initChart();
}, []);
// ========== 公告弹窗检查 ==========
useEffect(() => {
const checkNoticeAndShow = async () => {
const lastCloseDate = localStorage.getItem('notice_close_date');
const today = new Date().toDateString();
if (lastCloseDate !== today) {
try {
const res = await API.get('/api/notice');
const { success, data } = res.data;
if (success && data && data.trim() !== '') {
setNoticeVisible(true);
}
} catch (error) {
console.error('获取公告失败:', error);
}
}
};
checkNoticeAndShow();
}, []);
return (
<div className='p-4 md:p-5 h-full overflow-y-auto relative'>
{/* 公告弹窗 */}
<NoticeModal
visible={noticeVisible}
onClose={() => setNoticeVisible(false)}
isMobile={isMobile}
/>
{/* 页面背景由父级 UserCenter shell 的 PageBackground 统一提供,此处不再叠加装饰 blob */}
{/* 主内容 - flex 列布局,数据分析区撑满剩余视口 */}
<div className='relative z-10 flex flex-col min-h-full'>
{/* Header - 更现代的设计 */}
<div className='flex flex-col lg:flex-row justify-between items-start lg:items-center gap-3 mb-5'>
<div className='flex items-center gap-4'>
{/* 动态图标容器 */}
<div className='relative group'>
<div className='absolute inset-0 bg-gradient-to-br from-brand-from via-brand-via to-brand-to rounded-2xl blur-lg opacity-50 group-hover:opacity-70 transition-opacity' />
<div className='relative p-3 bg-gradient-to-br from-brand-from via-brand-via to-brand-to rounded-2xl shadow-lg shadow-brand/25'>
<BarChart2 size={22} className='text-white' />
<Sparkles
size={11}
className='absolute -top-1 -right-1 text-amber-300 animate-pulse'
/>
</div>
</div>
<div>
<div className='flex items-center gap-2'>
<h1 className='text-xl md:text-2xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-brand-deep via-brand to-brand-via dark:from-brand-from dark:via-brand-via dark:to-brand-to tracking-tight'>
{dashboardData.t('用量洞察中心')}
</h1>
{/* LIVE 实时脉冲指示 */}
<span className='inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md bg-emerald-50 dark:bg-emerald-950/40 border border-emerald-200/60 dark:border-emerald-800/40'>
<span className='relative flex h-1.5 w-1.5'>
<span className='absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75 animate-ping' />
<span className='relative inline-flex h-1.5 w-1.5 rounded-full bg-emerald-500' />
</span>
<span className='text-[10px] font-bold text-emerald-700 dark:text-emerald-300 tracking-wider'>
LIVE
</span>
</span>
</div>
<p className='text-xs md:text-sm text-gray-500 dark:text-gray-400 mt-0.5 flex items-center gap-1.5'>
<Activity size={12} className='text-brand' />
{dashboardData.t('实时追踪您的每一次调用与消费')}
</p>
</div>
</div>
{/* 操作按钮组 */}
<div className='flex items-center gap-3'>
{/* 时间范围显示 */}
<div className='hidden md:flex items-center gap-2 px-4 py-2 bg-white/60 dark:bg-neutral-800/70 backdrop-blur-sm rounded-xl border border-gray-200/50 dark:border-neutral-600/50'>
<Calendar size={14} className='text-gray-400' />
<span className='text-sm text-gray-600 dark:text-gray-300'>
{dashboardData.dataExportDefaultTime}
</span>
</div>
{/* 刷新按钮 */}
<Button
icon={<IconRefresh />}
onClick={initChart}
loading={dashboardData.loading || dashboardData.tokenUsageLoading}
>
{dashboardData.t('刷新')}
</Button>
{/* 筛选按钮 */}
<Button
type='tertiary'
icon={<IconFilter style={{ color: '#ffffff' }} />}
onClick={dashboardData.showSearchModal}
className='!rounded-xl !bg-gradient-to-r !from-brand-from !via-brand-via !to-brand-to !border-0 hover:!opacity-90 !transition-all !shadow-md !shadow-brand/30'
style={{ color: '#ffffff' }}
>
<span className='hidden sm:inline ml-1'>
{dashboardData.t('筛选数据')}
</span>
</Button>
</div>
</div>
<SearchModal
searchModalVisible={dashboardData.searchModalVisible}
handleSearchConfirm={handleSearchConfirm}
handleCloseModal={dashboardData.handleCloseModal}
isMobile={dashboardData.isMobile}
isAdminUser={dashboardData.isAdminUser}
inputs={dashboardData.inputs}
dataExportDefaultTime={dashboardData.dataExportDefaultTime}
timeOptions={dashboardData.timeOptions}
handleInputChange={dashboardData.handleInputChange}
t={dashboardData.t}
/>
{/* 详细统计卡片 —— 扁平化:去掉外层白 panel,实底卡直接浮在页面 bg-glow 上 */}
<div className='mb-5'>
{/* 区块标题 */}
<div className='flex items-center gap-2 mb-3'>
<div className='w-1 h-4 bg-gradient-to-b from-brand-from via-brand-via to-brand-to rounded-full' />
<h2 className='text-base font-semibold text-gray-900 dark:text-white tracking-wide'>
{dashboardData.t('核心指标')}
</h2>
</div>
<StatsCards
groupedStatsData={groupedStatsData}
loading={dashboardData.loading || dashboardData.tokenUsageLoading}
getTrendSpec={getTrendSpec}
CARD_PROPS={CARD_PROPS}
CHART_CONFIG={CHART_CONFIG}
/>
</div>
{/* 会员额度使用卡片 —— 扁平化:去掉外层白 panel,实底卡浮在 bg-glow 上 */}
{!membershipLoading && membershipInfo && (
<div className='mb-5'>
{/* 区块标题 */}
<div className='flex items-center justify-between mb-3'>
<div className='flex items-center gap-2'>
<div className='w-1 h-4 bg-gradient-to-b from-brand-from via-brand-via to-brand-to rounded-full' />
<h2 className='text-base font-semibold text-gray-900 dark:text-white tracking-wide'>
{dashboardData.t('会员权益')}
</h2>
<span className='text-xs text-gray-400 bg-gray-100 dark:bg-neutral-800 px-2 py-0.5 rounded-full'>
{membershipInfo.plan_name}
</span>
</div>
<div className='flex items-center gap-1.5 text-xs text-gray-400'>
<Clock size={12} />
<span>
{dashboardData.t('剩余')} {membershipInfo.remaining_days}{' '}
{dashboardData.t('天')}
</span>
</div>
</div>
{/* 卡片网格 */}
<div className='grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3'>
{/* 今日可用额度 —— 青 */}
<div className='group/m relative overflow-hidden rounded-xl bg-white dark:bg-neutral-900/90 border border-gray-100 dark:border-neutral-800 shadow-[0_2px_12px_-2px_rgba(0,0,0,0.06)] dark:shadow-[0_2px_12px_-2px_rgba(0,0,0,0.4)] p-3 hover:shadow-[0_12px_28px_-6px_rgba(0,0,0,0.12)] hover:-translate-y-0.5 transition-all duration-300 ease-out'>
<div className='pointer-events-none absolute top-0 left-0 right-0 h-px bg-gradient-to-r from-cyan-400 to-sky-500 opacity-70' />
<div className='absolute -top-6 -right-6 w-20 h-20 bg-gradient-to-br from-cyan-400/25 to-sky-300/5 rounded-full blur-2xl group-hover/m:scale-110 transition-transform duration-500' />
<div className='relative'>
<div className='flex items-center gap-2 mb-2'>
<div className='w-8 h-8 rounded-lg bg-gradient-to-br from-cyan-500 to-sky-600 flex items-center justify-center shadow-md shadow-cyan-500/25'>
<Sparkles size={14} className='text-white' />
</div>
<span className='text-xs text-gray-500 dark:text-gray-400'>
{dashboardData.t('今日剩余')}
</span>
</div>
<div className='text-xl font-bold text-gray-900 dark:text-white mb-2'>
{renderQuota(membershipInfo.membership_quota)}
</div>
{membershipInfo.daily_quota > 0 && (
<Progress
percent={Math.min(
100,
Math.max(
0,
Math.round(
(membershipInfo.membership_quota /
membershipInfo.daily_quota) *
100,
),
),
)}
showInfo={false}
stroke='#06b6d4'
style={{ height: 4 }}
/>
)}
</div>
</div>
{/* 今日已用额度 —— 天蓝 */}
<div className='group/m relative overflow-hidden rounded-xl bg-white dark:bg-neutral-900/90 border border-gray-100 dark:border-neutral-800 shadow-[0_2px_12px_-2px_rgba(0,0,0,0.06)] dark:shadow-[0_2px_12px_-2px_rgba(0,0,0,0.4)] p-3 hover:shadow-[0_12px_28px_-6px_rgba(0,0,0,0.12)] hover:-translate-y-0.5 transition-all duration-300 ease-out'>
<div className='pointer-events-none absolute top-0 left-0 right-0 h-px bg-gradient-to-r from-sky-400 to-blue-500 opacity-70' />
<div className='absolute -top-6 -right-6 w-20 h-20 bg-gradient-to-br from-sky-400/25 to-blue-300/5 rounded-full blur-2xl group-hover/m:scale-110 transition-transform duration-500' />
<div className='relative'>
<div className='flex items-center gap-2 mb-2'>
<div className='w-8 h-8 rounded-lg bg-gradient-to-br from-sky-500 to-blue-600 flex items-center justify-center shadow-md shadow-sky-500/25'>
<Zap size={14} className='text-white' />
</div>
<span className='text-xs text-gray-500 dark:text-gray-400'>
{dashboardData.t('今日消耗')}
</span>
</div>
<div className='text-xl font-bold text-gray-900 dark:text-white mb-2'>
{renderQuota(
Math.max(
0,
membershipInfo.daily_quota -
membershipInfo.membership_quota,
),
)}
</div>
{membershipInfo.daily_quota > 0 && (
<div className='text-xs text-gray-400'>
{dashboardData.t('使用率')}{' '}
{Math.round(
Math.max(
0,
(membershipInfo.daily_quota -
membershipInfo.membership_quota) /
membershipInfo.daily_quota,
) * 100,
)}
%
</div>
)}
</div>
</div>
{/* 每日额度上限 —— 蓝 */}
<div className='group/m relative overflow-hidden rounded-xl bg-white dark:bg-neutral-900/90 border border-gray-100 dark:border-neutral-800 shadow-[0_2px_12px_-2px_rgba(0,0,0,0.06)] dark:shadow-[0_2px_12px_-2px_rgba(0,0,0,0.4)] p-3 hover:shadow-[0_12px_28px_-6px_rgba(0,0,0,0.12)] hover:-translate-y-0.5 transition-all duration-300 ease-out'>
<div className='pointer-events-none absolute top-0 left-0 right-0 h-px bg-gradient-to-r from-blue-400 to-indigo-500 opacity-70' />
<div className='absolute -top-6 -right-6 w-20 h-20 bg-gradient-to-br from-blue-400/25 to-indigo-300/5 rounded-full blur-2xl group-hover/m:scale-110 transition-transform duration-500' />
<div className='relative'>
<div className='flex items-center gap-2 mb-2'>
<div className='w-8 h-8 rounded-lg bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center shadow-md shadow-blue-500/25'>
<Crown size={14} className='text-white' />
</div>
<span className='text-xs text-gray-500 dark:text-gray-400'>
{dashboardData.t('每日总额')}
</span>
</div>
<div className='text-xl font-bold text-gray-900 dark:text-white mb-2'>
{renderQuota(membershipInfo.daily_quota)}
</div>
<div className='text-xs text-gray-400'>
{dashboardData.t('每日自动重置')}
</div>
</div>
</div>
{/* 累计已用额度 —— 靛 */}
<div className='group/m relative overflow-hidden rounded-xl bg-white dark:bg-neutral-900/90 border border-gray-100 dark:border-neutral-800 shadow-[0_2px_12px_-2px_rgba(0,0,0,0.06)] dark:shadow-[0_2px_12px_-2px_rgba(0,0,0,0.4)] p-3 hover:shadow-[0_12px_28px_-6px_rgba(0,0,0,0.12)] hover:-translate-y-0.5 transition-all duration-300 ease-out'>
<div className='pointer-events-none absolute top-0 left-0 right-0 h-px bg-gradient-to-r from-indigo-400 to-violet-500 opacity-70' />
<div className='absolute -top-6 -right-6 w-20 h-20 bg-gradient-to-br from-indigo-400/25 to-violet-300/5 rounded-full blur-2xl group-hover/m:scale-110 transition-transform duration-500' />
<div className='relative'>
<div className='flex items-center gap-2 mb-2'>
<div className='w-8 h-8 rounded-lg bg-gradient-to-br from-indigo-500 to-violet-600 flex items-center justify-center shadow-md shadow-indigo-500/25'>
<TrendingUp size={14} className='text-white' />
</div>
<span className='text-xs text-gray-500 dark:text-gray-400'>
{dashboardData.t('累计消耗')}
</span>
</div>
<div className='text-xl font-bold text-gray-900 dark:text-white mb-2'>
{renderQuota(membershipInfo.membership_used_quota || 0)}
</div>
<div className='text-xs text-gray-400'>
{dashboardData.t('会员期间总消耗')}
</div>
</div>
</div>
</div>
</div>
)}
{/* 模型数据分析图表 - 自适应填满剩余视口高度。扁平化:去外层白 panel,图卡自身实底 */}
<div className='flex-1 flex flex-col min-h-[420px]'>
{/* 区块标题 */}
<div className='flex items-center gap-2 mb-3 shrink-0'>
<div className='w-1 h-4 bg-gradient-to-b from-brand-from via-brand-via to-brand-to rounded-full' />
<h2 className='text-base font-semibold text-gray-900 dark:text-white tracking-wide'>
{dashboardData.t('用量洞察')}
</h2>
</div>
<ChartsPanel
spec_line={dashboardCharts.spec_line}
spec_pie={dashboardCharts.spec_pie}
CHART_CONFIG={CHART_CONFIG}
hasApiInfoPanel={false}
t={dashboardData.t}
/>
</div>
</div>
</div>
);
};
export default UserDashboard;
+292
View File
@@ -0,0 +1,292 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useContext, useMemo } from 'react';
import {
Routes,
Route,
Navigate,
useLocation,
useNavigate,
} from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import {
Activity,
BarChart2,
CreditCard,
FileText,
Gift,
Receipt,
Settings,
} from 'lucide-react';
import { StatusContext } from '../../context/Status';
import PageBackground from '../../components/common/PageBackground';
import UserCenterSidebar from './UserCenterSidebar';
import UserDashboard from './UserDashboard';
import UsageRecord from './UsageRecord';
import Invite from './Invite';
import Invoice from './Invoice';
import TopUp from '../TopUp';
import PersonalSetting from '../../components/settings/PersonalSetting';
import ServiceDashboard from '../ServiceDashboard';
import WeyAiDownload from '../WeyAiDownload';
import { normalizeSidebarModulesAdmin } from '../../constants/sidebarModules';
// 移动端底部导航组件
const MobileBottomNav = ({ sidebarConfig }) => {
const { t } = useTranslation();
const location = useLocation();
const navigate = useNavigate();
const navItems = [
{
key: 'dashboard',
icon: BarChart2,
label: t('概览'),
path: '/user-center/dashboard',
},
{
key: 'usageRecord',
icon: FileText,
label: t('记录'),
path: '/user-center/usage-record',
},
{
key: 'serviceDashboard',
icon: Activity,
label: t('监控'),
path: '/user-center/service-dashboard',
},
{
key: 'invite',
icon: Gift,
label: t('邀请'),
path: '/user-center/invite',
},
{
key: 'topup',
icon: CreditCard,
label: t('充值'),
path: '/user-center/topup',
},
{
key: 'invoice',
icon: Receipt,
label: t('发票'),
path: '/user-center/invoice',
},
{
key: 'settings',
icon: Settings,
label: t('设置'),
path: '/user-center/settings',
},
];
const visibleNavItems = navItems.filter(
(item) =>
sidebarConfig?.enabled !== false && sidebarConfig?.[item.key] !== false,
);
if (visibleNavItems.length === 0) {
return null;
}
return (
<div className='md:hidden fixed bottom-0 left-0 right-0 z-50 bg-white/90 dark:bg-neutral-900/90 backdrop-blur-xl border-t border-gray-200/80 dark:border-neutral-800/80 safe-area-inset-bottom'>
<div className='flex items-center justify-around h-14'>
{visibleNavItems.map((item) => {
const isActive =
location.pathname === item.path ||
location.pathname.startsWith(`${item.path}/`);
const IconComponent = item.icon;
return (
<button
key={item.key}
onClick={() => navigate(item.path)}
className={`flex flex-col items-center justify-center flex-1 h-full transition-all ${
isActive ? 'scale-105' : 'opacity-60'
}`}
>
<div
className={`p-1.5 rounded-lg ${isActive ? 'bg-gradient-to-br from-blue-500 to-brand-to' : ''}`}
>
<IconComponent
size={20}
className={
isActive ? 'text-white' : 'text-gray-500 dark:text-gray-400'
}
/>
</div>
<span
className={`text-[10px] mt-0.5 font-medium ${
isActive
? 'text-gray-900 dark:text-white'
: 'text-gray-500 dark:text-gray-400'
}`}
>
{item.label}
</span>
</button>
);
})}
</div>
</div>
);
};
const UserCenter = () => {
const [statusState] = useContext(StatusContext);
// 跑马灯公告是否存在(用于动态计算顶部间距)
const hasMarquee = !!statusState?.status?.marquee_content?.trim();
const userCenterConfig = useMemo(
() =>
normalizeSidebarModulesAdmin(statusState?.status?.SidebarModulesAdmin)
.userCenter,
[statusState?.status?.SidebarModulesAdmin],
);
const userCenterRoutes = [
'dashboard',
'usageRecord',
'serviceDashboard',
'topup',
'invoice',
'invite',
'settings',
];
const routePathMap = {
dashboard: 'dashboard',
usageRecord: 'usage-record',
serviceDashboard: 'service-dashboard',
topup: 'topup',
invoice: 'invoice',
invite: 'invite',
settings: 'settings',
};
const firstVisiblePath =
userCenterConfig.enabled === false
? null
: routePathMap[
userCenterRoutes.find((key) => userCenterConfig[key] !== false)
] || null;
const firstVisibleRoute = firstVisiblePath
? `/user-center/${firstVisiblePath}`
: '/';
const guardUserCenterRoute = (key, element) => {
if (userCenterConfig.enabled === false || userCenterConfig[key] === false) {
return <Navigate to={firstVisibleRoute} replace />;
}
return element;
};
if (!firstVisiblePath) {
return <Navigate to='/' replace />;
}
return (
<div
className={`flex flex-col md:flex-row h-screen overflow-hidden bg-[var(--surface-bg-base)] transition-colors duration-300 ${hasMarquee ? 'pt-[96px] sm:pt-[104px]' : 'pt-14 sm:pt-16'}`}
>
{/* Sidebar - 仅桌面端 */}
<div className='hidden md:block flex-shrink-0 h-full'>
<UserCenterSidebar />
</div>
{/* Main Content */}
<div className='flex-1 h-full overflow-hidden relative pb-16 md:pb-0'>
{/* 统一页面背景层 —— 唯一背景来源,走 bg-glow-* 主题变量 */}
<PageBackground />
{/* 内容区域 */}
<div className='relative z-10 h-full overflow-y-auto uc-page-scrollbar'>
<Routes>
<Route
path='/'
element={<Navigate to={firstVisibleRoute} replace />}
/>
<Route
path='dashboard'
element={guardUserCenterRoute('dashboard', <UserDashboard />)}
/>
<Route
path='usage-record'
element={guardUserCenterRoute('usageRecord', <UsageRecord />)}
/>
{/* ServiceDashboard 组件内部有 min-h-screen pt-[88px],嵌入 UserCenter 后用 -mt-[64px] 部分抵消 pt,保留 24px 顶部间距(与其他页面 p-6 一致),[&>div]:min-h-0 避免撑高 */}
<Route
path='service-dashboard'
element={guardUserCenterRoute(
'serviceDashboard',
<div className='-mt-[64px] [&>div]:min-h-0'>
<ServiceDashboard />
</div>,
)}
/>
{/* TopUp 组件内部有 pt-[64px] 用于独立路由清除固定头部,UserCenter 已处理顶部偏移,需用 -mt 抵消。
* embedded:UserCenter shell 已提供 PageBackground,子页面不再渲染自身背景,避免双层叠加 */}
<Route
path='topup'
element={guardUserCenterRoute(
'topup',
<div className='-mt-[64px]'>
<TopUp embedded />
</div>,
)}
/>
{/* PersonalSetting 内部有 pt-16 sm:pt-20 用于独立路由清除固定头部,UserCenter 已处理顶部偏移,需用 -mt 抵消 */}
{/* 邀请返利 / 发票抬头:侧栏项、routePathMap、权限守卫此前都已配好,
唯独漏了这两个 <Route>,导致点进来是空白内容区。
手机端侧栏是 hidden md:block,底部导航是唯一入口,等于两个死路口。
两个组件根节点都是 p-4 sm:p-6、无自带顶部偏移,可直接嵌入。 */}
<Route
path='invite'
element={guardUserCenterRoute('invite', <Invite />)}
/>
<Route
path='invoice'
element={guardUserCenterRoute('invoice', <Invoice />)}
/>
<Route
path='settings'
element={guardUserCenterRoute(
'settings',
<div className='-mt-16 sm:-mt-20 [&_.sticky]:!top-4'>
<PersonalSetting />
</div>,
)}
/>
{/* WeyAi 桌面端下载:侧栏入口指到这里而不是独立的 /weyai/download,
否则点一下侧栏就整页跳走、导航栏消失。embedded:不加顶部让位、
不自绘背景(shell 已有 PageBackground)。未开放时页面自身显示空态,
侧栏项也随开关隐藏,无需再加守卫 */}
<Route path='weyai-download' element={<WeyAiDownload embedded />} />
</Routes>
</div>
</div>
{/* 移动端底部导航栏 */}
<MobileBottomNav sidebarConfig={userCenterConfig} />
</div>
);
};
export default UserCenter;