Files
monkey-ai-web/src/pages/UserCenter/UserDashboard.jsx
T

352 lines
13 KiB
React

/*
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 { useEffectEvent } from '../../hooks/common/useEffectEvent';
import React, { useContext, useEffect, useState } from 'react';
import { Select } from 'antd';
import UserCenterPageHeader from '../../components/common/UserCenterPageHeader';
import dashboardCompute from '../../assets/prototype/dashboard-compute.svg';
import { Button, Progress, Tag } from '@/components/ui';
import { IconFilter, IconRefresh } from '@/components/ui/icons';
import { Sparkles, 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 UserDashboardFilterModal from '../../components/dashboard/modals/UserDashboardFilterModal';
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.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 ==========
const onMount = useEffectEvent(() => {
initChart();
});
useEffect(() => onMount(), [onMount]);
// ========== 公告弹窗检查 ==========
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='uc-dashboard min-h-full relative'>
{/* 原型 .dashboard-hero 装饰层:渐变、网格线、底部渐隐与右侧插画(纯视觉,不参与交互) */}
<div className='uc-dashboard-hero' aria-hidden='true'>
<img src={dashboardCompute} alt='' className='ui-dashboard-art' />
</div>
{/* 公告弹窗 */}
<NoticeModal
visible={noticeVisible}
onClose={() => setNoticeVisible(false)}
isMobile={isMobile}
/>
{/* 页面背景由父级 UserCenter shell 的 PageBackground 统一提供,此处不再叠加装饰 blob */}
{/* 主内容 - flex 列布局,数据分析区撑满剩余视口 */}
<div className='relative z-10 flex flex-col min-h-full'>
<UserCenterPageHeader
title={dashboardData.t('用量洞察中心')}
subtitle={dashboardData.t(
'追踪每一次模型调用,让用量与成本清晰可见。',
)}
extra={
<div className='ui-page-actions'>
{/* 时间粒度:与筛选弹窗中的同名下拉共用 handleInputChange / 本地存储;
新粒度在下一次“刷新 / 筛选数据”加载时生效,不新增请求触发 */}
<Select
aria-label={dashboardData.t('时间粒度')}
value={dashboardData.dataExportDefaultTime}
options={dashboardData.timeOptions}
onChange={(value) =>
dashboardData.handleInputChange(
value,
'data_export_default_time',
)
}
/>
<Button
icon={<IconRefresh />}
onClick={initChart}
loading={
dashboardData.loading || dashboardData.tokenUsageLoading
}
>
{dashboardData.t('刷新')}
</Button>
<Button
theme='solid'
type='primary'
icon={<IconFilter />}
onClick={dashboardData.showSearchModal}
>
{dashboardData.t('筛选数据')}
</Button>
</div>
}
/>
<UserDashboardFilterModal
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'>
<StatsCards
groupedStatsData={groupedStatsData}
loading={dashboardData.loading || dashboardData.tokenUsageLoading}
getTrendSpec={getTrendSpec}
CARD_PROPS={CARD_PROPS}
CHART_CONFIG={CHART_CONFIG}
/>
</div>
{/* 会员额度使用卡片(原型无此状态:按统一规范使用语义底色/边框,无渐变、光晕与悬停位移) */}
{!membershipLoading && membershipInfo && (
<div className='uc-member-benefits'>
<div className='uc-member-benefits-head'>
<h2>{dashboardData.t('会员权益')}</h2>
<Tag size='small'>{membershipInfo.plan_name}</Tag>
<span className='uc-member-benefits-meta'>
<Clock size={12} />
{dashboardData.t('剩余 {{n}} 天', {
n: membershipInfo.remaining_days,
count: membershipInfo.remaining_days,
})}
</span>
</div>
<div className='uc-member-benefits-grid'>
<div className='uc-member-benefit'>
<span className='uc-member-benefit-label'>
<Sparkles size={14} />
{dashboardData.t('今日剩余')}
</span>
<strong>{renderQuota(membershipInfo.membership_quota)}</strong>
{membershipInfo.daily_quota > 0 && (
<Progress
percent={Math.min(
100,
Math.max(
0,
Math.round(
(membershipInfo.membership_quota /
membershipInfo.daily_quota) *
100,
),
),
)}
showInfo={false}
stroke='var(--ui-color-primary)'
style={{ height: 4 }}
/>
)}
</div>
<div className='uc-member-benefit'>
<span className='uc-member-benefit-label'>
<Zap size={14} />
{dashboardData.t('今日消耗')}
</span>
<strong>
{renderQuota(
Math.max(
0,
membershipInfo.daily_quota -
membershipInfo.membership_quota,
),
)}
</strong>
{membershipInfo.daily_quota > 0 && (
<small>
{dashboardData.t('使用率')}{' '}
{Math.round(
Math.max(
0,
(membershipInfo.daily_quota -
membershipInfo.membership_quota) /
membershipInfo.daily_quota,
) * 100,
)}
%
</small>
)}
</div>
<div className='uc-member-benefit'>
<span className='uc-member-benefit-label'>
<Crown size={14} />
{dashboardData.t('每日总额')}
</span>
<strong>{renderQuota(membershipInfo.daily_quota)}</strong>
<small>{dashboardData.t('每日自动重置')}</small>
</div>
<div className='uc-member-benefit'>
<span className='uc-member-benefit-label'>
<TrendingUp size={14} />
{dashboardData.t('累计消耗')}
</span>
<strong>
{renderQuota(membershipInfo.membership_used_quota || 0)}
</strong>
<small>{dashboardData.t('会员期间总消耗')}</small>
</div>
</div>
</div>
)}
{/* 模型数据分析图表 - 自适应填满剩余视口高度。扁平化:去外层白 panel,图卡自身实底 */}
<div className='flex-1 flex flex-col min-h-[420px]'>
{/* 区块标题 */}
<div className='ui-dashboard-chart-heading flex items-center gap-2 mb-3 shrink-0'>
<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;