/* 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 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 '@/components/ui'; import { Receipt, Plus, Download, Eye, X, } from 'lucide-react'; import UserCenterPageHeader from '../../components/common/UserCenterPageHeader'; 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) => ( { 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) => ( {text} ), }, ]; // 开票记录列 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) => ( {t(INVOICE_STATUS_TEXT[status] || '未知')} ), }, { title: t('申请时间'), dataIndex: 'create_time', width: 160, render: (v) => formatTime(v), }, { title: t('操作'), width: 160, render: (_, record) => (
{record.status === INVOICE_STATUS.PENDING && ( )} {record.status === INVOICE_STATUS.INVOICED && record.pdf_url && ( )}
), }, ]; if (!nuonuoEnabled) { return (
} title={t('发票功能暂未开放')} description={t('管理员尚未启用发票功能,请联系管理员开通。')} />
); } return (
{/* 可开票充值记录 */} } /> {selectedTopupIds.length > 0 && (
{t('已选择')} {selectedTopupIds.length} {t('条记录')} {t('合计')}: ¥{selectedAmount.toFixed(2)}
)} {/* 开票信息 */}
{/* 常用开票信息选择 */} {titles.length > 0 && (
{t('常用信息')}: {titles.map((title) => ( handleSelectTitle(title.id)} closable onClose={(e) => { e.stopPropagation(); handleDeleteTitle(title.id); }} > {title.title} ))}
)} {t('发票抬头')} } value={invoiceTitle} onChange={setInvoiceTitle} placeholder={t('请输入公司全称')} /> {t('税号')} } value={taxId} onChange={setTaxId} placeholder={t('请输入统一社会信用代码')} /> {t('收件邮箱')} } value={email} onChange={setEmail} placeholder={t('请输入接收发票的邮箱地址')} /> setSaveTitle(e.target.checked)} > {t('保存为常用开票信息')}
{/* 详情弹窗 */} setDetailVisible(false)} footer={null} width={560} > {detailLoading ? (
) : detailData ? (
{t('状态')} {t(INVOICE_STATUS_TEXT[detailData.status] || '未知')}
{t('发票抬头')} {detailData.invoice_title}
{t('税号')} {detailData.tax_id}
{t('开票金额')} ¥{Number(detailData.amount).toFixed(2)}
{t('收件邮箱')} {detailData.email}
{t('申请时间')} {formatTime(detailData.create_time)}
{detailData.invoice_number && (
{t('发票号码')} {detailData.invoice_number}
)} {detailData.reject_reason && (
{t('拒绝原因')}: {detailData.reject_reason}
)} {detailData.fail_reason && (
{t('失败原因')}: {detailData.fail_reason}
)} {/* 关联充值记录 */} {detailData.topup_list && detailData.topup_list.length > 0 && (
{t('关联充值记录')} ({detailData.topup_list.length} {t('笔')})
{detailData.topup_list.map((topup) => (
{formatTime(topup.complete_time)} {paymentMethodMap[topup.payment_method] || topup.payment_method} ¥{Number(topup.money).toFixed(2)}
))}
)} {/* 下载按钮 */} {detailData.status === INVOICE_STATUS.INVOICED && detailData.pdf_url && ( )}
) : null}
); }; export default Invoice;