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

1531 lines
45 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
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 {
formatIdReference,
formatUserReference,
} from '../../helpers/safeDisplay';
import { Trans } from 'react-i18next';
import {
Ban as ActionBan,
ShieldCheck as ActionShieldCheck,
CalendarClock as ActionCalendarClock,
Pencil as ActionPencil,
Plus as ActionPlus,
CreditCard as ActionCreditCard,
} from '@/components/common/icons/ActionIcons';
import {
ConsoleFilterField,
ConsoleFilterGrid,
ConsoleListTable,
} from '../../components/console/ConsolePrimitives';
import ConsoleCollection from '../../components/console/ConsoleCollection';
import { useIsMobile } from '../../hooks/common/useIsMobile';
import { createCardProPagination } from '../../helpers/utils';
import { Button as AntButton } from 'antd';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useEffectEvent } from '../../hooks/common/useEffectEvent';
import { useTranslation } from 'react-i18next';
import { formatCurrency } from '../../helpers/safeDisplay';
import { useNavigate } from 'react-router-dom';
import { CreditCard, Search, History } from 'lucide-react';
import {
Button,
Checkbox,
DatePicker,
SideSheet,
Input,
InputNumber,
Modal,
Popconfirm,
Select,
Space,
Tag,
TextArea,
Timeline,
Tooltip,
} from '@/components/ui';
import { API } from '../../helpers/api';
import { isAdmin, showError, showSuccess } from '../../helpers';
import { renderQuota } from '../../helpers/render';
import QuotaInput from '../../components/common/ui/QuotaInput';
const statusColorMap = {
active: 'green',
expired: 'grey',
canceled: 'orange',
banned: 'red',
};
const planTypeColorMap = {
weekly: 'blue',
monthly: 'cyan',
quarterly: 'violet',
};
const tierColorMap = {
lite: 'light-blue',
pro: 'pink',
};
const actionColorMap = {
create: 'green',
ban: 'red',
unban: 'green',
extend: 'blue',
update: 'orange',
grant: 'cyan',
};
const formatTs = (ts) => {
if (!ts || ts <= 0) return '-';
return new Date(ts * 1000).toLocaleString();
};
const formatDateOnly = (ts) => {
if (!ts || ts <= 0) return '-';
return new Date(ts * 1000).toLocaleDateString();
};
const remainingDays = (endDate) => {
if (!endDate) return null;
const now = Math.floor(Date.now() / 1000);
return Math.floor((endDate - now) / 86400);
};
const RemainingTag = ({ endDate, status, t }) => {
if (status === 'banned')
return <span className='text-xs text-gray-400'>—</span>;
const days = remainingDays(endDate);
if (days === null) return <span className='text-xs text-gray-400'>—</span>;
if (days < 0) {
return (
<span className='text-xs text-gray-400'>
{t('已过期 {{n}} 天', { n: Math.abs(days), count: Math.abs(days) })}
</span>
);
}
let cls = 'text-xs text-gray-500';
if (days <= 3) cls = 'text-xs text-red-500 font-semibold';
else if (days <= 7) cls = 'text-xs text-amber-500 font-medium';
return (
<span className={cls}>{t('剩余 {{n}} 天', { n: days, count: days })}</span>
);
};
const Subscription = () => {
const { t } = useTranslation();
const navigate = useNavigate();
const isMobile = useIsMobile();
const admin = isAdmin();
// 列表数据
const [list, setList] = useState([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false);
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(20);
// 过滤条件
const [keyword, setKeyword] = useState('');
const [appliedKeyword, setAppliedKeyword] = useState('');
const [userId, setUserId] = useState();
const [appliedUserId, setAppliedUserId] = useState();
const [planTypes, setPlanTypes] = useState([]);
const [tiers, setTiers] = useState([]);
const [statuses, setStatuses] = useState([]);
const [endDateRange, setEndDateRange] = useState(null);
const [quickFilter, setQuickFilter] = useState(null); // expiring3 / expiring7 / overdue
// 操作弹窗
const [banVisible, setBanVisible] = useState(false);
const [unbanVisible, setUnbanVisible] = useState(false);
const [extendVisible, setExtendVisible] = useState(false);
const [editVisible, setEditVisible] = useState(false);
const [createVisible, setCreateVisible] = useState(false);
const [detailVisible, setDetailVisible] = useState(false);
const [currentRow, setCurrentRow] = useState(null);
const [membershipPlans, setMembershipPlans] = useState([]);
const [plansLoading, setPlansLoading] = useState(false);
const [refreshToken, setRefreshToken] = useState(0);
// 详情数据
const [detailLoading, setDetailLoading] = useState(false);
const [auditLogs, setAuditLogs] = useState([]);
const fetchMembershipPlans = useCallback(async () => {
setPlansLoading(true);
try {
const res = await API.get('/api/user/membership/manage/plans');
if (res.data.success) {
setMembershipPlans(res.data.data || []);
} else {
showError(res.data.message || t('加载会员方案失败'));
}
} catch (err) {
showError(err.message);
} finally {
setPlansLoading(false);
}
}, [t]);
const fetchList = useCallback(async () => {
setLoading(true);
try {
const params = { page, page_size: pageSize };
if (appliedKeyword) params.keyword = appliedKeyword;
if (appliedUserId) params.user_id = appliedUserId;
if (planTypes.length) params.plan_types = planTypes.join(',');
if (tiers.length) params.tiers = tiers.join(',');
if (statuses.length) params.statuses = statuses.join(',');
if (endDateRange && endDateRange[0]) {
params.end_date_from = Math.floor(endDateRange[0].getTime() / 1000);
}
if (endDateRange && endDateRange[1]) {
params.end_date_to = Math.floor(endDateRange[1].getTime() / 1000);
}
// 快捷筛选 (优先级覆盖 endDateRange)
const now = Math.floor(Date.now() / 1000);
if (quickFilter === 'expiring3') {
params.end_date_from = now;
params.end_date_to = now + 3 * 86400;
params.statuses = 'active';
} else if (quickFilter === 'expiring7') {
params.end_date_from = now;
params.end_date_to = now + 7 * 86400;
params.statuses = 'active';
} else if (quickFilter === 'overdue') {
params.end_date_to = now;
params.statuses = 'expired';
}
const res = await API.get('/api/user/membership/manage/subscriptions', {
params,
});
if (res.data.success) {
setList(res.data.data?.list || []);
setTotal(res.data.data?.total || 0);
} else {
showError(res.data.message || t('查询失败'));
}
} catch (err) {
showError(err.message);
} finally {
setLoading(false);
}
}, [
page,
pageSize,
appliedKeyword,
appliedUserId,
planTypes,
tiers,
statuses,
endDateRange,
quickFilter,
t,
]);
useEffect(() => {
fetchList();
}, [fetchList, refreshToken]);
const handleSearch = () => {
setPage(1);
setAppliedKeyword(keyword);
setAppliedUserId(userId);
setQuickFilter(null);
};
const handleReset = () => {
setPage(1);
setKeyword('');
setAppliedKeyword('');
setUserId(undefined);
setAppliedUserId(undefined);
setPlanTypes([]);
setTiers([]);
setStatuses([]);
setEndDateRange(null);
setQuickFilter(null);
};
const applyQuickFilter = (key) => {
setPage(1);
setQuickFilter((prev) => (prev === key ? null : key));
};
// 打开详情
const openDetail = async (row) => {
setCurrentRow(row);
setDetailVisible(true);
setDetailLoading(true);
setAuditLogs([]);
try {
const res = await API.get(
`/api/user/membership/manage/subscriptions/${row.id}`,
);
if (res.data.success) {
setAuditLogs(res.data.data?.audit_logs || []);
} else {
showError(res.data.message || t('加载详情失败'));
}
} catch (err) {
showError(err.message);
} finally {
setDetailLoading(false);
}
};
const openBan = (row) => {
setCurrentRow(row);
setBanVisible(true);
};
const openUnban = (row) => {
setCurrentRow(row);
setUnbanVisible(true);
};
const openExtend = (row) => {
setCurrentRow(row);
setExtendVisible(true);
};
const openEdit = (row) => {
setCurrentRow(row);
setEditVisible(true);
};
const openCreate = () => {
setMembershipPlans([]);
setCreateVisible(true);
fetchMembershipPlans();
};
const handleCreateDone = (createdUserId) => {
const numericUserId = Number(createdUserId);
setCreateVisible(false);
if (Number.isInteger(numericUserId) && numericUserId > 0) {
setKeyword('');
setAppliedKeyword('');
setUserId(numericUserId);
setAppliedUserId(numericUserId);
setPlanTypes([]);
setTiers([]);
setStatuses([]);
setEndDateRange(null);
setQuickFilter(null);
setPage(1);
}
setRefreshToken((prev) => prev + 1);
};
const doGrant = async (row) => {
try {
const res = await API.post(
`/api/user/membership/manage/subscriptions/${row.id}/grant`,
{
reason: '管理员手动补发',
},
);
if (res.data.success) {
showSuccess(t('补发成功'));
fetchList();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
};
const columns = [
{ title: 'ID', dataIndex: 'id', width: 70 },
{
title: t('用户'),
width: 180,
render: (_, r) => {
const display = r.display_name || '';
const username = r.username || '';
return (
<div className='flex flex-col'>
<span className='font-medium'>
{formatUserReference(display || username, r.user_id)}
</span>
<span className='text-xs text-gray-400'>
#{r.user_id}
{username ? ` @${username}` : ''}
</span>
</div>
);
},
},
{
title: t('套餐'),
width: 180,
render: (_, r) => (
<Space spacing={4} wrap>
<Tag color={planTypeColorMap[r.plan_type] || 'grey'} size='small'>
{r.plan_name || r.plan_type}
</Tag>
{r.tier ? (
<Tag
color={tierColorMap[r.tier] || 'grey'}
size='small'
type='ghost'
>
{r.tier}
</Tag>
) : null}
</Space>
),
},
{
title: t('状态'),
dataIndex: 'status',
width: 90,
render: (s) => (
<Tag color={statusColorMap[s] || 'grey'}>{t(s || '未知')}</Tag>
),
},
{
title: t('起始时间'),
dataIndex: 'start_date',
width: 110,
render: formatDateOnly,
},
{
title: t('到期时间'),
width: 160,
render: (_, r) => (
<div className='flex flex-col'>
<span>{formatDateOnly(r.end_date)}</span>
<RemainingTag endDate={r.end_date} status={r.status} t={t} />
</div>
),
},
{
title: t('每日额度'),
dataIndex: 'daily_quota',
width: 110,
render: (v) => renderQuota(v, 2),
},
{
title: t('支付金额'),
dataIndex: 'price_paid',
width: 100,
render: (v) => (v != null ? formatCurrency(v) : '-'),
},
{
title: t('操作'),
key: 'actions',
width: 300,
fixed: 'right',
render: (_, r) => (
<Space spacing={4} wrap>
<Button size='small' theme='borderless' onClick={() => openDetail(r)}>
{t('详情')}
</Button>
{admin && r.status !== 'banned' && (
<Button
size='small'
theme='borderless'
type='danger'
icon={<ActionBan size={12} />}
onClick={() => openBan(r)}
>
{t('封禁')}
</Button>
)}
{admin && r.status === 'banned' && (
<Button
size='small'
theme='borderless'
type='primary'
icon={<ActionShieldCheck size={12} />}
onClick={() => openUnban(r)}
>
{t('解封')}
</Button>
)}
{admin && r.status !== 'canceled' && r.status !== 'banned' && (
<Button
size='small'
theme='borderless'
icon={<ActionCalendarClock size={12} />}
onClick={() => openExtend(r)}
>
{t('延长')}
</Button>
)}
{admin && (
<Button
size='small'
theme='borderless'
icon={<ActionPencil size={12} />}
onClick={() => openEdit(r)}
>
{t('编辑')}
</Button>
)}
{admin && r.status === 'active' && (
<Popconfirm
title={t('确认手动补发今日额度?')}
onConfirm={() => doGrant(r)}
>
<Button
size='small'
theme='borderless'
icon={<Sparkles size={12} />}
>
{t('补发')}
</Button>
</Popconfirm>
)}
</Space>
),
},
];
return (
<div className='console-content'>
<ConsoleCollection
searchArea={
<ConsoleFilterGrid
onReset={handleReset}
onSearch={handleSearch}
loading={loading}
>
<ConsoleFilterField
label={t('搜索关键字')}
id='subscription-keyword'
>
<Input
id='subscription-keyword'
prefix={<Search size={14} />}
placeholder={t('搜索用户名/昵称/订单号')}
value={keyword}
onChange={setKeyword}
/>
</ConsoleFilterField>
<ConsoleFilterField label={t('用户ID')} id='subscription-user-id'>
<InputNumber
id='subscription-user-id'
placeholder={t('用户ID')}
value={userId}
onChange={setUserId}
min={0}
hideButtons
/>
</ConsoleFilterField>
<ConsoleFilterField
label={t('套餐类型')}
id='subscription-plan-type'
>
<Select
id='subscription-plan-type'
placeholder={t('套餐类型')}
value={planTypes}
onChange={(v) => {
setPage(1);
setPlanTypes(v || []);
}}
multiple
maxTagCount={2}
optionList={[
{ label: t('周卡'), value: 'weekly' },
{ label: t('月卡'), value: 'monthly' },
{ label: t('季卡'), value: 'quarterly' },
]}
/>
</ConsoleFilterField>
<ConsoleFilterField label={t('档位')} id='subscription-tier'>
<Select
id='subscription-tier'
placeholder={t('档位')}
value={tiers}
onChange={(v) => {
setPage(1);
setTiers(v || []);
}}
multiple
maxTagCount={2}
optionList={[
{ label: 'Lite', value: 'lite' },
{ label: 'Pro', value: 'pro' },
]}
/>
</ConsoleFilterField>
<ConsoleFilterField label={t('状态')} id='subscription-status'>
<Select
id='subscription-status'
placeholder={t('状态')}
value={statuses}
onChange={(v) => {
setPage(1);
setStatuses(v || []);
}}
multiple
maxTagCount={2}
optionList={[
{ label: t('active'), value: 'active' },
{ label: t('expired'), value: 'expired' },
{ label: t('canceled'), value: 'canceled' },
{ label: t('banned'), value: 'banned' },
]}
/>
</ConsoleFilterField>
<ConsoleFilterField
label={t('到期时间')}
id='subscription-end-date'
>
<DatePicker
id={{
start: 'subscription-end-date',
end: 'subscription-end-date-end',
}}
type='dateRange'
value={endDateRange}
onChange={(d) => {
setPage(1);
setEndDateRange(d || null);
}}
placeholder={[t('到期开始'), t('到期结束')]}
density='compact'
/>
</ConsoleFilterField>
</ConsoleFilterGrid>
}
actionsArea={
<div className='console-list-tools'>
<div
className='console-list-quick-filters'
role='group'
aria-label={t('快捷筛选')}
>
{[
['expiring3', t('3 天内到期')],
['expiring7', t('7 天内到期')],
['overdue', t('已过期未处理')],
].map(([key, label]) => (
<AntButton
key={key}
type={quickFilter === key ? 'primary' : 'default'}
aria-pressed={quickFilter === key}
onClick={() => applyQuickFilter(key)}
>
{label}
</AntButton>
))}
</div>
{admin && (
<div className='console-list-tool-actions'>
<Button
icon={<ActionCreditCard size={16} />}
onClick={() => navigate('/console/setting?tab=membership')}
>
{t('会员管理')}
</Button>
<Button
type='primary'
icon={<ActionPlus size={16} />}
onClick={openCreate}
>
{t('新建会员')}
</Button>
</div>
)}
</div>
}
paginationArea={createCardProPagination({
currentPage: page,
pageSize,
total,
onPageChange: setPage,
onPageSizeChange: (size) => {
setPage(1);
setPageSize(size);
},
isMobile,
t,
})}
>
<ConsoleListTable
columns={columns}
dataSource={list}
loading={loading}
rowKey='id'
pagination={false}
/>
</ConsoleCollection>
{/* 封禁弹窗 */}
<BanModal
visible={banVisible}
row={currentRow}
onCancel={() => setBanVisible(false)}
onDone={() => {
setBanVisible(false);
fetchList();
}}
t={t}
/>
{/* 解封弹窗 */}
<UnbanModal
visible={unbanVisible}
row={currentRow}
onCancel={() => setUnbanVisible(false)}
onDone={() => {
setUnbanVisible(false);
fetchList();
}}
t={t}
/>
{/* 延长弹窗 */}
<ExtendModal
visible={extendVisible}
row={currentRow}
onCancel={() => setExtendVisible(false)}
onDone={() => {
setExtendVisible(false);
fetchList();
}}
t={t}
/>
{/* 编辑弹窗 */}
<EditModal
visible={editVisible}
row={currentRow}
onCancel={() => setEditVisible(false)}
onDone={() => {
setEditVisible(false);
fetchList();
}}
t={t}
/>
{/* 新建会员弹窗 */}
<CreateMembershipModal
visible={createVisible}
plans={membershipPlans}
plansLoading={plansLoading}
onCancel={() => setCreateVisible(false)}
onDone={handleCreateDone}
t={t}
/>
{/* 详情抽屉 */}
<DetailDrawer
visible={detailVisible}
row={currentRow}
loading={detailLoading}
auditLogs={auditLogs}
onClose={() => setDetailVisible(false)}
t={t}
/>
</div>
);
};
// =============== 弹窗组件 ===============
const ReasonRow = ({ value, onChange, t, label, required = false }) => (
<div className='space-y-1'>
<div className='text-sm font-medium text-gray-700 dark:text-gray-200'>
{label || t('原因')}
{required && <span className='ml-1 text-red-500'>*</span>}
</div>
<TextArea
value={value}
onChange={onChange}
placeholder={t('请填写原因,将记入审计日志')}
rows={3}
maxLength={500}
showClear
/>
</div>
);
const CreateMembershipModal = ({
visible,
plans,
plansLoading,
onCancel,
onDone,
t,
}) => {
const [userId, setUserId] = useState();
const [planId, setPlanId] = useState();
const [days, setDays] = useState(30);
const [reason, setReason] = useState(() => t('管理员手动开通会员'));
const [submitting, setSubmitting] = useState(false);
const resetForm = useEffectEvent(() => {
setUserId(undefined);
setPlanId(undefined);
setDays(30);
setReason(t('管理员手动开通会员'));
});
useEffect(() => {
if (visible) resetForm();
}, [visible, resetForm]);
const enabledPlans = useMemo(
() => plans.filter((plan) => plan.is_enabled),
[plans],
);
const selectedPlan = useMemo(
() => enabledPlans.find((plan) => Number(plan.id) === Number(planId)),
[enabledPlans, planId],
);
const submit = async () => {
const numericUserId = Number(userId);
const numericPlanId = Number(planId);
const numericDays = Number(days);
if (!Number.isInteger(numericUserId) || numericUserId <= 0) {
showError(t('请输入有效的用户ID'));
return;
}
if (!Number.isInteger(numericPlanId) || numericPlanId <= 0) {
showError(t('请选择会员方案'));
return;
}
if (!selectedPlan) {
showError(t('请选择可用的会员方案'));
return;
}
if (!Number.isInteger(numericDays) || numericDays <= 0) {
showError(t('到期天数必须大于 0'));
return;
}
if (numericDays > 3650) {
showError(t('到期天数不能超过 3650 天'));
return;
}
setSubmitting(true);
try {
const res = await API.post('/api/user/membership/manage/subscriptions', {
user_id: numericUserId,
plan_id: numericPlanId,
days: numericDays,
reason: String(reason || '').trim(),
});
if (res.data.success) {
showSuccess(t('开通成功,已切换到该用户的会员记录'));
onDone(numericUserId);
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
} finally {
setSubmitting(false);
}
};
const planOptions = enabledPlans.map((plan) => ({
value: plan.id,
label: `${plan.name} / ${plan.tier || '-'} / ${t('{{days}} 天', {
days: plan.duration_days,
})}`,
}));
return (
<Modal
title={t('新建会员')}
visible={visible}
onCancel={onCancel}
onOk={submit}
okText={t('确认开通')}
cancelText={t('取消')}
confirmLoading={submitting}
okButtonProps={{ disabled: plansLoading || enabledPlans.length === 0 }}
width={560}
>
<div className='space-y-4'>
<div className='rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-700 dark:border-amber-700/40 dark:bg-amber-900/20 dark:text-amber-200'>
{t(
'若用户已有未过期会员,新会员会自动从最后一个未过期会员到期后开始,避免会员期重叠。',
)}
</div>
<div className='grid grid-cols-1 gap-3 sm:grid-cols-2'>
<div className='space-y-1'>
<div className='text-sm font-medium text-gray-700 dark:text-gray-200'>
{t('用户ID')}
<span className='ml-1 text-red-500'>*</span>
</div>
<InputNumber
value={userId}
onChange={setUserId}
min={1}
precision={0}
hideButtons
placeholder={t('请输入用户ID')}
style={{ width: '100%' }}
/>
</div>
<div className='space-y-1'>
<div className='text-sm font-medium text-gray-700 dark:text-gray-200'>
{t('到期天数')}
<span className='ml-1 text-red-500'>*</span>
</div>
<InputNumber
value={days}
onChange={setDays}
min={1}
max={3650}
precision={0}
style={{ width: '100%' }}
/>
</div>
</div>
<div className='space-y-1'>
<div className='text-sm font-medium text-gray-700 dark:text-gray-200'>
{t('会员方案')}
<span className='ml-1 text-red-500'>*</span>
</div>
<Select
value={planId}
onChange={setPlanId}
loading={plansLoading}
placeholder={t('请选择会员方案')}
optionList={planOptions}
style={{ width: '100%' }}
/>
{!plansLoading && enabledPlans.length === 0 && (
<div className='text-xs text-red-500'>
{t('暂无可用会员方案,请先启用会员方案后再开通。')}
</div>
)}
</div>
{selectedPlan && (
<div className='grid grid-cols-2 gap-2 rounded-md bg-gray-50 p-3 text-xs text-gray-600 dark:bg-slate-800/70 dark:text-gray-300'>
<div>
{t('方案类型')}:{selectedPlan.plan_type}
</div>
<div>
{t('档位')}:{selectedPlan.tier || '-'}
</div>
<div>
{t('每日额度')}:{renderQuota(selectedPlan.daily_quota, 2)}
</div>
<div>
<Trans
t={t}
i18nKey='原方案天数:{{duration_days}} 天'
values={{ duration_days: selectedPlan.duration_days }}
/>
</div>
</div>
)}
<ReasonRow
value={reason}
onChange={setReason}
t={t}
label={t('开通原因')}
/>
</div>
</Modal>
);
};
const BanModal = ({ visible, row, onCancel, onDone, t }) => {
const [reason, setReason] = useState('');
const [submitting, setSubmitting] = useState(false);
useEffect(() => {
if (visible) setReason('');
}, [visible]);
const submit = async () => {
if (!reason.trim()) {
showError(t('请填写封禁原因'));
return;
}
setSubmitting(true);
try {
const res = await API.post(
`/api/user/membership/manage/subscriptions/${row.id}/ban`,
{
reason: reason.trim(),
},
);
if (res.data.success) {
showSuccess(t('封禁成功'));
onDone();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
} finally {
setSubmitting(false);
}
};
return (
<Modal
title={t('封禁会员卡')}
visible={visible}
onCancel={onCancel}
onOk={submit}
okText={t('确认封禁')}
cancelText={t('取消')}
confirmLoading={submitting}
okButtonProps={{ type: 'danger', theme: 'solid' }}
>
{row && (
<div className='space-y-3'>
<div className='text-sm text-gray-500'>
{t('用户')}:
<span className='font-medium text-gray-900 dark:text-white'>
{formatUserReference(
row.display_name || row.username,
row.user_id,
)}
</span>
<span className='ml-2 text-xs text-gray-400'>#{row.user_id}</span>
</div>
<div className='text-sm text-gray-500'>
{t('套餐')}:<span className='font-medium'>{row.plan_name}</span>
</div>
<div className='text-sm text-gray-500'>
{t('到期时间')}:{formatDateOnly(row.end_date)}
</div>
<ReasonRow
value={reason}
onChange={setReason}
t={t}
label={t('封禁原因')}
required
/>
<div className='text-xs text-red-500'>
{t(
'封禁后该订阅立即失效,停止发放日额度。封禁不会退款,需要人工另行处理。',
)}
</div>
</div>
)}
</Modal>
);
};
const UnbanModal = ({ visible, row, onCancel, onDone, t }) => {
const [reason, setReason] = useState('');
const [submitting, setSubmitting] = useState(false);
useEffect(() => {
if (visible) setReason('');
}, [visible]);
const submit = async () => {
if (!reason.trim()) {
showError(t('请填写解封原因'));
return;
}
setSubmitting(true);
try {
const res = await API.post(
`/api/user/membership/manage/subscriptions/${row.id}/unban`,
{
reason: reason.trim(),
},
);
if (res.data.success) {
showSuccess(t('解封成功'));
onDone();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
} finally {
setSubmitting(false);
}
};
return (
<Modal
title={t('解封会员卡')}
visible={visible}
onCancel={onCancel}
onOk={submit}
okText={t('确认解封')}
cancelText={t('取消')}
confirmLoading={submitting}
>
{row && (
<div className='space-y-3'>
<div className='text-sm text-gray-500'>
{t('用户')}:{row.display_name || row.username} #{row.user_id}
</div>
<div className='text-sm text-gray-500'>
{t('套餐')}:{row.plan_name}
</div>
<ReasonRow
value={reason}
onChange={setReason}
t={t}
label={t('解封原因')}
required
/>
<div className='text-xs text-gray-500'>
{t('解封后将根据到期时间自动恢复为有效或已过期状态。')}
</div>
</div>
)}
</Modal>
);
};
const ExtendModal = ({ visible, row, onCancel, onDone, t }) => {
const [mode, setMode] = useState('days'); // days | date
const [days, setDays] = useState(7);
const [endDate, setEndDate] = useState(null);
const [reason, setReason] = useState('');
const [submitting, setSubmitting] = useState(false);
useEffect(() => {
if (visible) {
setMode('days');
setDays(7);
setEndDate(null);
setReason('');
}
}, [visible]);
const submit = async () => {
if (!reason.trim()) {
showError(t('请填写延长原因'));
return;
}
const payload = { reason: reason.trim() };
if (mode === 'days') {
if (!days || days <= 0) {
showError(t('天数必须大于 0'));
return;
}
payload.days = days;
} else {
if (!endDate) {
showError(t('请选择新的到期日期'));
return;
}
payload.end_date = Math.floor(endDate.getTime() / 1000);
}
setSubmitting(true);
try {
const res = await API.post(
`/api/user/membership/manage/subscriptions/${row.id}/extend`,
payload,
);
if (res.data.success) {
showSuccess(t('延长成功'));
onDone();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
} finally {
setSubmitting(false);
}
};
return (
<Modal
title={t('延长有效期')}
visible={visible}
onCancel={onCancel}
onOk={submit}
okText={t('确认延长')}
cancelText={t('取消')}
confirmLoading={submitting}
>
{row && (
<div className='space-y-3'>
<div className='text-sm text-gray-500'>
{t('用户')}:{row.display_name || row.username} #{row.user_id}
</div>
<div className='text-sm text-gray-500'>
{t('当前到期')}:{formatTs(row.end_date)}
</div>
<div>
<Button
size='small'
theme={mode === 'days' ? 'solid' : 'borderless'}
type='primary'
onClick={() => setMode('days')}
>
{t('+ 天数')}
</Button>
<Button
size='small'
theme={mode === 'date' ? 'solid' : 'borderless'}
type='primary'
onClick={() => setMode('date')}
className='ml-2'
>
{t('指定日期')}
</Button>
</div>
{mode === 'days' ? (
<div className='flex items-center gap-2'>
<span className='text-sm'>{t('延长天数')}:</span>
<InputNumber
value={days}
onChange={setDays}
min={1}
max={3650}
style={{ width: 120 }}
/>
<Space spacing={4}>
{[7, 30, 90].map((d) => (
<Tag
key={d}
className='cursor-pointer'
color={days === d ? 'blue' : 'white'}
type={days === d ? 'solid' : 'ghost'}
onClick={() => setDays(d)}
>
+{d}
</Tag>
))}
</Space>
</div>
) : (
<div className='flex items-center gap-2'>
<span className='text-sm'>{t('新到期日期')}:</span>
<DatePicker
type='date'
value={endDate}
onChange={setEndDate}
placeholder={t('选择日期')}
style={{ width: 200 }}
/>
</div>
)}
<ReasonRow
value={reason}
onChange={setReason}
t={t}
label={t('延长原因')}
required
/>
</div>
)}
</Modal>
);
};
const EditModal = ({ visible, row, onCancel, onDone, t }) => {
const [tier, setTier] = useState('');
const [dailyQuota, setDailyQuota] = useState();
const [reason, setReason] = useState('');
const [skipRefresh, setSkipRefresh] = useState(false);
const [submitting, setSubmitting] = useState(false);
useEffect(() => {
if (visible && row) {
setTier(row.tier || '');
setDailyQuota(row.daily_quota);
setReason('');
setSkipRefresh(false);
}
}, [visible, row]);
const submit = async () => {
const payload = { reason: reason.trim() };
const hasTier = tier && tier !== row.tier;
const hasQuota = dailyQuota != null && dailyQuota !== row.daily_quota;
if (!hasTier && !hasQuota) {
showError(t('请至少修改一个字段'));
return;
}
if (hasTier) payload.tier = tier;
if (hasQuota) {
payload.daily_quota = dailyQuota;
// 只有真的改 quota 时才传 skip 标志,避免无谓字段
payload.skip_daily_refresh = skipRefresh;
}
setSubmitting(true);
try {
const res = await API.put(
`/api/user/membership/manage/subscriptions/${row.id}`,
payload,
);
if (res.data.success) {
showSuccess(t('保存成功'));
onDone();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
} finally {
setSubmitting(false);
}
};
const isActiveToday =
row &&
row.status === 'active' &&
row.last_grant_date === new Date().toISOString().slice(0, 10);
return (
<Modal
title={t('编辑会员卡')}
visible={visible}
onCancel={onCancel}
onOk={submit}
okText={t('保存')}
cancelText={t('取消')}
confirmLoading={submitting}
>
{row && (
<div className='space-y-3'>
<div className='text-sm text-gray-500'>
{t('用户')}:{row.display_name || row.username} #{row.user_id}
</div>
<div className='flex items-center gap-2'>
<span className='w-20 text-sm'>{t('档位')}:</span>
<Select
value={tier}
onChange={setTier}
style={{ width: 160 }}
optionList={[
{ label: 'Lite', value: 'lite' },
{ label: 'Pro', value: 'pro' },
]}
/>
</div>
<div className='flex items-center gap-2'>
<span className='w-20 text-sm'>{t('每日额度')}:</span>
{/* dailyQuota 为内部额度单位;QuotaInput 负责与货币金额互相换算,
与表格列 renderQuota 的展示口径保持一致 */}
<QuotaInput
value={dailyQuota}
onChange={setDailyQuota}
minQuota={0}
style={{ width: 200 }}
/>
<Tooltip
content={t(
'默认会立即刷新用户的会员日额度上限(视为补发);如想保留用户当日已消耗数据,可勾选下方"仅保存不重发",新值会在下次定时发放生效。',
)}
>
<span className='text-xs text-gray-400'>?</span>
</Tooltip>
</div>
{isActiveToday && dailyQuota !== row.daily_quota && (
<div className='flex items-center gap-2 pl-20'>
<Checkbox
checked={skipRefresh}
onChange={(e) => setSkipRefresh(e.target.checked)}
>
<span className='text-xs'>
{t('仅保存,不立即重发额度(下次定时发放生效)')}
</span>
</Checkbox>
</div>
)}
<ReasonRow
value={reason}
onChange={setReason}
t={t}
label={t('备注')}
/>
</div>
)}
</Modal>
);
};
const DetailDrawer = ({ visible, row, loading, auditLogs, onClose, t }) => {
if (!row) return null;
const fmtAction = (a) =>
({
create: t('新建'),
ban: t('封禁'),
unban: t('解封'),
extend: t('延长'),
update: t('编辑'),
grant: t('补发'),
})[a] || a;
return (
<SideSheet
title={
<Space>
<CreditCard size={16} />
{t('订阅详情')} #{row.id}
</Space>
}
visible={visible}
onCancel={onClose}
width={520}
placement='right'
>
<div className='space-y-4'>
<section className='space-y-1'>
<div className='flex justify-between'>
<span className='text-gray-500'>{t('用户')}</span>
<span>
{formatUserReference(
row.display_name || row.username,
row.user_id,
)}
<span className='ml-2 text-xs text-gray-400'>#{row.user_id}</span>
</span>
</div>
<div className='flex justify-between'>
<span className='text-gray-500'>{t('套餐')}</span>
<span>
<Tag
color={planTypeColorMap[row.plan_type] || 'grey'}
size='small'
>
{row.plan_name}
</Tag>
{row.tier && (
<Tag
color={tierColorMap[row.tier] || 'grey'}
size='small'
type='ghost'
className='ml-1'
>
{row.tier}
</Tag>
)}
</span>
</div>
<div className='flex justify-between'>
<span className='text-gray-500'>{t('状态')}</span>
<Tag color={statusColorMap[row.status] || 'grey'}>{row.status}</Tag>
</div>
<div className='flex justify-between'>
<span className='text-gray-500'>{t('起始时间')}</span>
<span>{formatTs(row.start_date)}</span>
</div>
<div className='flex justify-between'>
<span className='text-gray-500'>{t('到期时间')}</span>
<span>
{formatTs(row.end_date)}
<span className='ml-2'>
<RemainingTag
endDate={row.end_date}
status={row.status}
t={t}
/>
</span>
</span>
</div>
<div className='flex justify-between'>
<span className='text-gray-500'>{t('每日额度')}</span>
<span>{renderQuota(row.daily_quota, 2)}</span>
</div>
<div className='flex justify-between'>
<span className='text-gray-500'>{t('支付金额')}</span>
<span>{formatCurrency(row.price_paid, '¥', 2, '¥0.00')}</span>
</div>
<div className='flex justify-between'>
<span className='text-gray-500'>{t('支付方式')}</span>
<span>{row.payment_method || '-'}</span>
</div>
<div className='flex justify-between'>
<span className='text-gray-500'>{t('订单号')}</span>
<span className='font-mono text-xs'>{row.trade_no || '-'}</span>
</div>
<div className='flex justify-between'>
<span className='text-gray-500'>{t('创建时间')}</span>
<span>{formatTs(row.created_at)}</span>
</div>
{row.status === 'banned' && (
<>
<div className='flex justify-between'>
<span className='text-gray-500'>{t('封禁时间')}</span>
<span>{formatTs(row.banned_at)}</span>
</div>
<div className='flex justify-between'>
<span className='text-gray-500'>{t('封禁原因')}</span>
<span className='text-red-500'>{row.banned_reason || '-'}</span>
</div>
</>
)}
</section>
<section>
<div className='flex items-center gap-2 mb-3 text-sm font-semibold'>
<History size={14} />
{t('操作历史')}
</div>
{loading ? (
<div className='text-sm text-gray-400'>{t('加载中...')}</div>
) : auditLogs.length === 0 ? (
<div className='text-sm text-gray-400'>{t('暂无操作记录')}</div>
) : (
<Timeline mode='left'>
{auditLogs.map((log) => (
<Timeline.Item
key={log.id}
type={
actionColorMap[log.action] === 'red'
? 'error'
: actionColorMap[log.action] === 'green'
? 'success'
: actionColorMap[log.action] === 'blue'
? 'ongoing'
: 'default'
}
time={formatTs(log.created_at)}
>
<div className='text-sm'>
<Tag
size='small'
color={actionColorMap[log.action] || 'grey'}
>
{fmtAction(log.action)}
</Tag>
<span className='ml-2 text-gray-700 dark:text-gray-200'>
{log.admin_display_name ||
log.admin_username ||
(log.admin_id == null
? t('未知管理员')
: `Admin${formatIdReference(log.admin_id)}`)}
</span>
</div>
{log.reason && (
<div className='text-xs text-gray-500 mt-1'>
{log.reason}
</div>
)}
</Timeline.Item>
))}
</Timeline>
)}
</section>
</div>
</SideSheet>
);
};
export default Subscription;