Files
monkey-ai-web/src/pages/AdminInvoice/index.jsx
T

605 lines
18 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 React, { useEffect, useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import {
Table,
Button,
Input,
Tag,
Select,
Modal,
TextArea,
Spin,
Typography,
} from '@/components/ui';
import { Receipt, Search, Eye, Check, X, RotateCw, Ban } from 'lucide-react';
import { API, showError, showSuccess } from '../../helpers';
import {
INVOICE_STATUS,
INVOICE_STATUS_TEXT,
INVOICE_STATUS_COLOR,
} from '../../constants';
const { Text } = Typography;
const paymentMethodMap = {
wechat: '微信',
alipay: '支付宝',
stripe: 'Stripe',
creem: 'Creem',
epay: '易支付',
};
const AdminInvoice = () => {
const { t } = useTranslation();
const [invoices, setInvoices] = useState([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false);
const [page, setPage] = useState(1);
const [keyword, setKeyword] = useState('');
const [searchKeyword, setSearchKeyword] = useState('');
const [statusFilter, setStatusFilter] = useState('');
// 详情弹窗
const [detailVisible, setDetailVisible] = useState(false);
const [detailData, setDetailData] = useState(null);
const [detailLoading, setDetailLoading] = useState(false);
// 拒绝弹窗
const [rejectVisible, setRejectVisible] = useState(false);
const [rejectId, setRejectId] = useState(null);
const [rejectReason, setRejectReason] = useState('');
const [rejectLoading, setRejectLoading] = useState(false);
// 审核通过弹窗
const [approveVisible, setApproveVisible] = useState(false);
const [approveId, setApproveId] = useState(null);
const [adminRemark, setAdminRemark] = useState('');
const [approveLoading, setApproveLoading] = useState(false);
const fetchInvoices = useCallback(async () => {
setLoading(true);
try {
const params = { p: page, page_size: 20 };
if (searchKeyword) params.keyword = searchKeyword;
if (statusFilter) params.status = statusFilter;
const res = await API.get('/api/invoice/list', { params });
if (res.data.success) {
setInvoices(res.data.data?.items || []);
setTotal(res.data.data?.total || 0);
}
} catch (err) {
showError(err.message);
} finally {
setLoading(false);
}
}, [page, searchKeyword, statusFilter]);
useEffect(() => {
fetchInvoices();
}, [fetchInvoices]);
const handleSearch = () => {
setPage(1);
setSearchKeyword(keyword);
};
const handleStatusFilterChange = (value) => {
setPage(1);
setStatusFilter(value || '');
};
// 查看详情
const handleViewDetail = async (id) => {
setDetailData(null);
setDetailVisible(true);
setDetailLoading(true);
try {
const res = await API.get(`/api/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 handleApprove = async () => {
setApproveLoading(true);
try {
const res = await API.post('/api/invoice/approve', {
id: approveId,
admin_remark: adminRemark,
});
if (res.data.success) {
showSuccess(t('审核通过'));
setApproveVisible(false);
setApproveId(null);
setAdminRemark('');
fetchInvoices();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
} finally {
setApproveLoading(false);
}
};
// 拒绝
const handleReject = async () => {
if (!rejectReason.trim()) {
showError(t('请填写拒绝理由'));
return;
}
setRejectLoading(true);
try {
const res = await API.post('/api/invoice/reject', {
id: rejectId,
reject_reason: rejectReason.trim(),
});
if (res.data.success) {
showSuccess(t('已拒绝'));
setRejectVisible(false);
setRejectId(null);
setRejectReason('');
fetchInvoices();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
} finally {
setRejectLoading(false);
}
};
// 重试开票
const handleRetry = async (id) => {
try {
const res = await API.post('/api/invoice/retry', { id });
if (res.data.success) {
showSuccess(t('已重新发起开票'));
fetchInvoices();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
};
// 取消失败订单
const handleFailCancel = async (id) => {
Modal.confirm({
title: t('确认取消'),
content: t('取消后关联的充值记录将被释放,用户可重新申请开票。'),
onOk: async () => {
try {
const res = await API.post('/api/invoice/fail-cancel', { id });
if (res.data.success) {
showSuccess(t('已取消'));
fetchInvoices();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
},
});
};
const formatTime = (timestamp) => {
if (!timestamp) return '-';
return new Date(timestamp * 1000).toLocaleString();
};
const columns = [
{ title: 'ID', dataIndex: 'id', width: 60 },
{
title: t('用户'),
width: 120,
ellipsis: true,
render: (_, record) => {
const displayName = record.display_name || '';
const username = record.username || '';
if (displayName && username) {
return (
<span title={`${displayName} (${username})`}>
{displayName}{' '}
<span className='text-xs text-gray-400'>({username})</span>
</span>
);
}
return (
displayName ||
username || (
<span className='text-gray-400'>User#{record.user_id}</span>
)
);
},
},
{
title: t('发票抬头'),
dataIndex: 'invoice_title',
width: 160,
ellipsis: true,
},
{
title: t('税号'),
dataIndex: 'tax_id',
width: 140,
ellipsis: true,
render: (text) => <span className='font-mono text-xs'>{text}</span>,
},
{
title: t('金额'),
dataIndex: 'amount',
width: 90,
render: (v) => `¥${Number(v).toFixed(2)}`,
},
{
title: t('状态'),
dataIndex: 'status',
width: 90,
render: (status) => (
<Tag color={INVOICE_STATUS_COLOR[status] || 'grey'}>
{t(INVOICE_STATUS_TEXT[status] || '未知')}
</Tag>
),
},
{
title: t('申请时间'),
dataIndex: 'create_time',
width: 150,
render: (v) => formatTime(v),
},
{
title: t('操作'),
width: 200,
fixed: 'right',
render: (_, record) => (
<div className='flex items-center gap-1 flex-wrap'>
<Button
size='small'
theme='borderless'
icon={<Eye size={14} />}
onClick={() => handleViewDetail(record.id)}
/>
{record.status === INVOICE_STATUS.PENDING && (
<>
<Button
size='small'
theme='borderless'
type='primary'
icon={<Check size={14} />}
onClick={() => {
setApproveId(record.id);
setApproveVisible(true);
}}
>
{t('通过')}
</Button>
<Button
size='small'
theme='borderless'
type='danger'
icon={<X size={14} />}
onClick={() => {
setRejectId(record.id);
setRejectVisible(true);
}}
>
{t('拒绝')}
</Button>
</>
)}
{(record.status === INVOICE_STATUS.APPROVED ||
record.status === INVOICE_STATUS.INVOICING) && (
<Button
size='small'
theme='borderless'
type='danger'
icon={<Ban size={14} />}
onClick={() => handleFailCancel(record.id)}
>
{t('取消')}
</Button>
)}
{record.status === INVOICE_STATUS.FAILED && (
<>
<Button
size='small'
theme='borderless'
icon={<RotateCw size={14} />}
onClick={() => handleRetry(record.id)}
>
{t('重试')}
</Button>
<Button
size='small'
theme='borderless'
type='danger'
icon={<Ban size={14} />}
onClick={() => handleFailCancel(record.id)}
>
{t('取消')}
</Button>
</>
)}
</div>
),
},
];
return (
<div className='mt-[60px] p-4 sm:p-6'>
{/* 筛选区:标题与筛选项同行 */}
<div className='flex flex-wrap items-center gap-2 mb-4'>
<div className='flex items-center gap-1.5 mr-2 flex-shrink-0'>
<Receipt size={18} className='text-amber-500' />
<span className='text-base font-bold text-gray-900 dark:text-white'>
{t('发票管理')}
</span>
</div>
<Input
prefix={<Search size={14} />}
placeholder={t('搜索抬头/税号/订单号/用户')}
value={keyword}
onChange={setKeyword}
onEnterPress={handleSearch}
style={{ width: 240 }}
/>
<Select
placeholder={t('状态')}
value={statusFilter || undefined}
onChange={handleStatusFilterChange}
style={{ width: 120 }}
allowClear
optionList={[
{ label: t('待审核'), value: '1' },
{ label: t('审核通过'), value: '2' },
{ label: t('已拒绝'), value: '3' },
{ label: t('开票中'), value: '4' },
{ label: t('已开票'), value: '5' },
{ label: t('已取消'), value: '6' },
{ label: t('开票失败'), value: '7' },
]}
/>
<Button theme='solid' type='primary' onClick={handleSearch}>
{t('搜索')}
</Button>
</div>
{/* 表格 */}
<Table
columns={columns}
dataSource={invoices}
loading={loading}
rowKey='id'
pagination={{
currentPage: page,
total,
pageSize: 20,
onPageChange: setPage,
showTotal: true,
}}
scroll={{ x: 1100 }}
size='small'
empty={t('暂无发票数据')}
/>
{/* 审核通过弹窗 */}
<Modal
title={t('审核通过')}
visible={approveVisible}
onCancel={() => {
setApproveVisible(false);
setApproveId(null);
setAdminRemark('');
}}
onOk={handleApprove}
okText={t('确认通过')}
confirmLoading={approveLoading}
>
<div className='space-y-3'>
<Text>{t('确认审核通过此发票申请?')}</Text>
<TextArea
placeholder={t('管理员备注(选填)')}
value={adminRemark}
onChange={setAdminRemark}
rows={3}
/>
</div>
</Modal>
{/* 拒绝弹窗 */}
<Modal
title={t('拒绝发票申请')}
visible={rejectVisible}
onCancel={() => {
setRejectVisible(false);
setRejectId(null);
setRejectReason('');
}}
onOk={handleReject}
okText={t('确认拒绝')}
okButtonProps={{ type: 'danger' }}
confirmLoading={rejectLoading}
>
<TextArea
placeholder={t('请填写拒绝理由(必填)')}
value={rejectReason}
onChange={setRejectReason}
rows={3}
/>
</Modal>
{/* 详情弹窗 */}
<Modal
title={t('发票详情')}
visible={detailVisible}
onCancel={() => setDetailVisible(false)}
footer={null}
width={600}
>
{detailLoading ? (
<div className='flex justify-center py-8'>
<Spin />
</div>
) : detailData ? (
<div className='space-y-3'>
<div className='grid grid-cols-2 gap-3'>
<div>
<Text className='text-gray-400 text-sm'>{t('状态')}</Text>
<div>
<Tag
color={INVOICE_STATUS_COLOR[detailData.status] || 'grey'}
>
{t(INVOICE_STATUS_TEXT[detailData.status] || '未知')}
</Tag>
</div>
</div>
<div>
<Text className='text-gray-400 text-sm'>{t('申请人')}</Text>
<div>
{detailData.display_name ||
detailData.username ||
`User#${detailData.user_id}`}
</div>
</div>
<div>
<Text className='text-gray-400 text-sm'>{t('发票抬头')}</Text>
<div className='font-medium'>{detailData.invoice_title}</div>
</div>
<div>
<Text className='text-gray-400 text-sm'>{t('税号')}</Text>
<div className='font-mono text-sm'>{detailData.tax_id}</div>
</div>
<div>
<Text className='text-gray-400 text-sm'>{t('开票金额')}</Text>
<div className='font-bold text-amber-600'>
¥{Number(detailData.amount).toFixed(2)}
</div>
</div>
<div>
<Text className='text-gray-400 text-sm'>{t('收件邮箱')}</Text>
<div>{detailData.email}</div>
</div>
<div>
<Text className='text-gray-400 text-sm'>{t('订单号')}</Text>
<div className='font-mono text-xs'>{detailData.order_no}</div>
</div>
<div>
<Text className='text-gray-400 text-sm'>{t('申请时间')}</Text>
<div>{formatTime(detailData.create_time)}</div>
</div>
</div>
{detailData.invoice_number && (
<div className='p-3 bg-green-50 dark:bg-green-900/20 rounded-lg'>
<Text className='text-sm text-green-600'>
{t('发票号码')}: {detailData.invoice_number}
</Text>
</div>
)}
{detailData.reject_reason && (
<div className='p-3 bg-red-50 dark:bg-red-900/20 rounded-lg'>
<Text className='text-sm text-red-600'>
{t('拒绝原因')}: {detailData.reject_reason}
</Text>
</div>
)}
{detailData.fail_reason && (
<div className='p-3 bg-red-50 dark:bg-red-900/20 rounded-lg'>
<Text className='text-sm text-red-600'>
{t('失败原因')}: {detailData.fail_reason}
</Text>
</div>
)}
{detailData.admin_remark && (
<div className='p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg'>
<Text className='text-sm text-blue-600'>
{t('管理员备注')}: {detailData.admin_remark}
</Text>
</div>
)}
{/* 关联充值记录 */}
{detailData.topup_list && detailData.topup_list.length > 0 && (
<div>
<Text className='text-sm text-gray-500 mb-2 block'>
{t('关联充值记录')} ({detailData.topup_list.length} {t('笔')}
,{t('合计')} ¥
{detailData.topup_list
.reduce((s, item) => s + (item.money || 0), 0)
.toFixed(2)}
)
</Text>
<Table
dataSource={detailData.topup_list}
rowKey='id'
pagination={false}
size='small'
columns={[
{ title: 'ID', dataIndex: 'id', width: 60 },
{
title: t('时间'),
dataIndex: 'complete_time',
width: 150,
render: (v) => formatTime(v),
},
{
title: t('方式'),
dataIndex: 'payment_method',
width: 80,
render: (v) => paymentMethodMap[v] || v,
},
{
title: t('金额'),
dataIndex: 'money',
width: 90,
render: (v) => `¥${Number(v).toFixed(2)}`,
},
]}
/>
</div>
)}
</div>
) : null}
</Modal>
</div>
);
};
export default AdminInvoice;