/* 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 . 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 —; const days = remainingDays(endDate); if (days === null) return —; if (days < 0) { return ( {t('已过期 {{n}} 天', { n: Math.abs(days), count: Math.abs(days) })} ); } 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 ( {t('剩余 {{n}} 天', { n: days, count: days })} ); }; 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 (
{formatUserReference(display || username, r.user_id)} #{r.user_id} {username ? ` @${username}` : ''}
); }, }, { title: t('套餐'), width: 180, render: (_, r) => ( {r.plan_name || r.plan_type} {r.tier ? ( {r.tier} ) : null} ), }, { title: t('状态'), dataIndex: 'status', width: 90, render: (s) => ( {t(s || '未知')} ), }, { title: t('起始时间'), dataIndex: 'start_date', width: 110, render: formatDateOnly, }, { title: t('到期时间'), width: 160, render: (_, r) => (
{formatDateOnly(r.end_date)}
), }, { 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) => ( {admin && r.status !== 'banned' && ( )} {admin && r.status === 'banned' && ( )} {admin && r.status !== 'canceled' && r.status !== 'banned' && ( )} {admin && ( )} {admin && r.status === 'active' && ( doGrant(r)} > )} ), }, ]; return (
} placeholder={t('搜索用户名/昵称/订单号')} value={keyword} onChange={setKeyword} /> { setPage(1); setTiers(v || []); }} multiple maxTagCount={2} optionList={[ { label: 'Lite', value: 'lite' }, { label: 'Pro', value: 'pro' }, ]} />