Files
monkey-ai-web/src/components/membership/MembershipHistoryModal.jsx
T
zhanjunhao 9760e28cb4 fix(*): 全量 UI 审查与 undefined 展示异常修复
分析模块:补齐看板、排行、趋势及报表数值兜底
企业与用户中心:修复统计、成员、技能及资金字段展示
充值与交易:修复充值、发票、订单、订阅及支付字段拼接
平台页面:修复渠道、模型、服务监控与状态空值展示
通用能力:新增安全展示工具,补齐九语言文案与回归测试
文档记录:更新修复范围、影响及回滚说明
2026-11-20 10:18:17 +08:00

320 lines
9.4 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 React, { useState, useEffect, useCallback, useRef } from 'react';
import { Empty as AntEmpty, Tag as AntTag } from 'antd';
import { Modal, Table, Typography, Pagination, Toast } from '@/components/ui';
import i18next from 'i18next';
import { API, renderQuota } from '../../helpers';
import { formatCurrency } from '../../helpers/safeDisplay';
const { Text } = Typography;
// 会员状态配置(Ant Design 预设标签色)
const STATUS_CONFIG = {
active: { label: '生效中', color: 'success' },
expired: { label: '已过期', color: undefined },
pending: { label: '待生效', color: 'warning' },
canceled: { label: '已取消', color: 'error' },
};
// 方案类型映射
const PLAN_TYPE_MAP = {
weekly: '周卡',
monthly: '月卡',
quarterly: '季卡',
};
// 档位映射
const TIER_MAP = {
lite: '轻度版',
pro: '重度版',
};
/**
* 会员购买记录内容:数据加载、统计、表格与分页。
* 弹窗与在线充值页“会员购买记录”页签共用;visible 为 true 时按原逻辑加载。
*/
export const MembershipHistoryContent = ({ visible, t, inline = false }) => {
const [loading, setLoading] = useState(false);
const [memberships, setMemberships] = useState([]);
const [total, setTotal] = useState(0);
const [activeCount, setActiveCount] = useState(0);
const [pendingCount, setPendingCount] = useState(0);
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
// 格式化时间戳为日期字符串(使用 useCallback 避免每次渲染都创建新函数)
const formatDate = useCallback((timestamp) => {
if (!timestamp) return '-';
return new Date(timestamp * 1000).toLocaleDateString(i18next.language, {
year: 'numeric',
month: '2-digit',
day: '2-digit',
});
}, []);
// 格式化时间戳为完整时间字符串
const formatDateTime = useCallback((timestamp) => {
if (!timestamp) return '-';
return new Date(timestamp * 1000).toLocaleString(i18next.language, {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
});
}, []);
// 计算会员状态
const getMembershipStatus = (membership) => {
const now = Math.floor(Date.now() / 1000);
if (membership.status === 'canceled') return 'canceled';
if (membership.status === 'expired') return 'expired';
if (membership.start_date > now && membership.status === 'active')
return 'pending';
if (membership.end_date > now && membership.status === 'active')
return 'active';
return 'expired';
};
// 加载会员购买历史
const loadMembershipHistory = async (currentPage, currentPageSize) => {
setLoading(true);
try {
const res = await API.get(
`/api/user/membership/history?page=${currentPage}&page_size=${currentPageSize}`,
);
const { success, data, message } = res.data;
if (success) {
setMemberships(data.list || []);
setTotal(data.total || 0);
setActiveCount(data.active_count || 0);
setPendingCount(data.pending_count || 0);
} else {
console.error('加载会员历史失败:', message);
Toast.error({ content: message || t('加载失败'), duration: 3 });
}
} catch (error) {
console.error('Load membership history error:', error);
Toast.error({
content: t('加载会员购买记录失败,请稍后重试'),
duration: 3,
});
} finally {
setLoading(false);
}
};
// 追踪上一次 visible 状态,用于检测弹窗刚打开的时机
const prevVisibleRef = useRef(false);
useEffect(() => {
if (visible && !prevVisibleRef.current) {
// 弹窗刚打开:重置到第一页
prevVisibleRef.current = true;
if (page !== 1) {
setPage(1); // page 变化会再次触发此 effect,届时加载数据
return;
}
loadMembershipHistory(1, pageSize);
return;
}
if (!visible) {
prevVisibleRef.current = false;
return;
}
// 弹窗已打开状态下翻页 / 切换每页条数
loadMembershipHistory(page, pageSize);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [visible, page, pageSize]);
// 渲染状态标签
const renderStatusTag = (membership) => {
const status = getMembershipStatus(membership);
const config = STATUS_CONFIG[status] || STATUS_CONFIG.expired;
return (
<AntTag variant='filled' color={config.color}>
{t(config.label)}
</AntTag>
);
};
// 表格列定义(使用 useCallback 的格式化函数作为依赖)
const columns = [
{
title: t('方案名称'),
dataIndex: 'plan_name',
key: 'plan_name',
width: 180,
render: (text, record) => (
<div>
<Text>{text || '-'}</Text>
<Text type='tertiary' size='small' className='block'>
{PLAN_TYPE_MAP[record.plan_type]
? t(PLAN_TYPE_MAP[record.plan_type])
: record.plan_type}{' '}
· {TIER_MAP[record.tier] ? t(TIER_MAP[record.tier]) : record.tier}
</Text>
</div>
),
},
{
title: t('每日额度'),
dataIndex: 'daily_quota',
key: 'daily_quota',
width: 120,
render: (quota) => renderQuota(quota),
},
{
title: t('天数'),
key: 'duration_days',
width: 80,
align: 'center',
render: (_, record) => {
// duration_days 不在 UserMembership 模型中,需从 end_date - start_date 计算
const days =
record.end_date && record.start_date
? Math.round((record.end_date - record.start_date) / 86400)
: '-';
return t('{{days}} 天', { days });
},
},
{
title: t('购买价格'),
dataIndex: 'price_paid',
key: 'price_paid',
width: 100,
render: (price) => formatCurrency(price, '¥', 2, '¥0.00'),
},
{
title: t('生效日期'),
dataIndex: 'start_date',
key: 'start_date',
width: 110,
render: (date) => formatDate(date),
},
{
title: t('到期日期'),
dataIndex: 'end_date',
key: 'end_date',
width: 110,
render: (date) => formatDate(date),
},
{
title: t('状态'),
key: 'status',
width: 100,
render: (_, record) => renderStatusTag(record),
},
{
title: t('购买时间'),
dataIndex: 'created_at',
key: 'created_at',
width: 140,
render: (time) => formatDateTime(time),
},
];
return (
<div className={inline ? 'rc-member-history' : 'flex flex-col h-full'}>
{/* 统计信息 */}
{(inline || total > 0) && (
<div
className={inline ? 'rc-member-counts' : 'px-6 pt-4 rc-member-counts'}
>
{!inline && (
<span>
{t('总购买次数')}
<strong>{total}</strong>
</span>
)}
<span>
{t('生效中')}
<strong>{activeCount}</strong>
</span>
<span>
{t('待生效')}
<strong>{pendingCount}</strong>
</span>
</div>
)}
{/* 表格区域 */}
<div className={inline ? undefined : 'flex-1 overflow-auto px-6 pb-4'}>
<Table
columns={columns}
dataSource={memberships}
loading={loading}
rowKey='id'
scroll={{ x: 'max-content' }}
size='middle'
pagination={false}
empty={
<AntEmpty
image={AntEmpty.PRESENTED_IMAGE_SIMPLE}
description={t('暂无会员购买记录')}
/>
}
/>
</div>
{/* 分页器 */}
{total > 0 && (
<div
className={
inline ? 'rc-history-pagination' : 'px-6 pb-4 rc-history-pagination'
}
>
<Pagination
total={total}
currentPage={page}
pageSize={pageSize}
showSizeChanger
pageSizeOpts={[10, 20, 50]}
onPageChange={(p) => setPage(p)}
onPageSizeChange={(size) => {
setPageSize(size);
setPage(1);
}}
size='small'
showTotal={(count) => t('共 {{total}} 条', { total: count })}
/>
</div>
)}
</div>
);
};
const MembershipHistoryModal = ({ visible, onClose, t }) => (
<Modal
title={t('会员购买记录')}
visible={visible}
onCancel={onClose}
footer={null}
width={1100}
bodyStyle={{ padding: 0, maxHeight: '70vh' }}
style={{ top: 40 }}
>
<MembershipHistoryContent visible={visible} t={t} />
</Modal>
);
export default MembershipHistoryModal;