Files
monkey-ai-web/src/pages/AdminOrder/index.jsx
T
2026-10-15 16:33:46 +08:00

458 lines
13 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, { useEffect, useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { ShoppingCart, Search, Copy, Check } from 'lucide-react';
import {
Table,
Button,
Input,
Tag,
Select,
Toast,
DatePicker,
InputNumber,
} from '@douyinfe/semi-ui';
import { API } from '../../helpers/api';
import { showError } from '../../helpers';
import { renderQuota } from '../../helpers/render';
const paymentMethodMap = {
wechat: '微信',
alipay: '支付宝',
stripe: 'Stripe',
paypal: 'PayPal',
creem: 'Creem',
epay: '易支付',
};
const statusColorMap = {
pending: 'orange',
success: 'green',
expired: 'red',
};
const statusTextMap = {
pending: '待支付',
success: '已完成',
expired: '已过期',
};
const payPalSettlementStateMap = {
pending: '待回填',
complete: '已完整',
unavailable: '不可获取',
};
const formatUSDMinor = (value) => {
if (value === null || value === undefined) return '-';
return `$${(Number(value) / 100).toFixed(2)}`;
};
const AdminOrder = () => {
const { t } = useTranslation();
const [orders, setOrders] = 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 [orderId, setOrderId] = useState(undefined);
const [appliedOrderId, setAppliedOrderId] = useState(undefined);
const [userId, setUserId] = useState(undefined);
const [appliedUserId, setAppliedUserId] = useState(undefined);
const [statusFilter, setStatusFilter] = useState('');
const [copiedId, setCopiedId] = useState(null);
const [paymentMethodFilter, setPaymentMethodFilter] = useState('');
const [dateRange, setDateRange] = useState(null);
const [minMoney, setMinMoney] = useState(undefined);
const [maxMoney, setMaxMoney] = useState(undefined);
const [appliedMinMoney, setAppliedMinMoney] = useState(undefined);
const [appliedMaxMoney, setAppliedMaxMoney] = useState(undefined);
const fetchOrders = useCallback(async () => {
setLoading(true);
try {
const params = { p: page, page_size: 20 };
if (searchKeyword) params.keyword = searchKeyword;
if (appliedOrderId) params.order_id = appliedOrderId;
if (appliedUserId) params.user_id = appliedUserId;
if (statusFilter) params.status = statusFilter;
if (paymentMethodFilter) params.payment_method = paymentMethodFilter;
if (dateRange && dateRange[0])
params.start_time = Math.floor(dateRange[0].getTime() / 1000);
if (dateRange && dateRange[1])
params.end_time = Math.floor(dateRange[1].getTime() / 1000);
if (appliedMinMoney !== undefined && appliedMinMoney !== null)
params.min_money = appliedMinMoney;
if (appliedMaxMoney !== undefined && appliedMaxMoney !== null)
params.max_money = appliedMaxMoney;
const res = await API.get('/api/order/search', { params });
if (res.data.success) {
setOrders(res.data.data?.items || []);
setTotal(res.data.data?.total || 0);
}
} catch (err) {
showError(err.message);
} finally {
setLoading(false);
}
}, [
page,
searchKeyword,
appliedOrderId,
appliedUserId,
statusFilter,
paymentMethodFilter,
dateRange,
appliedMinMoney,
appliedMaxMoney,
]);
useEffect(() => {
fetchOrders();
}, [fetchOrders]);
const handleSearch = () => {
const trimmedKeyword = keyword.trim();
const normalizedOrderId =
orderId && Number(orderId) > 0 ? Math.floor(Number(orderId)) : undefined;
const normalizedUserId =
userId && Number(userId) > 0 ? Math.floor(Number(userId)) : undefined;
const numericKeywordAsOrderId =
!normalizedOrderId && /^\d+$/.test(trimmedKeyword)
? Number(trimmedKeyword)
: undefined;
const ignoreNumericKeyword =
normalizedOrderId && /^\d+$/.test(trimmedKeyword);
setPage(1);
setSearchKeyword(
numericKeywordAsOrderId || ignoreNumericKeyword ? '' : trimmedKeyword,
);
setAppliedOrderId(normalizedOrderId || numericKeywordAsOrderId);
setAppliedUserId(normalizedUserId);
setAppliedMinMoney(minMoney);
setAppliedMaxMoney(maxMoney);
};
const handleStatusFilterChange = (value) => {
setPage(1);
setStatusFilter(value || '');
};
const handlePaymentMethodChange = (value) => {
setPage(1);
setPaymentMethodFilter(value || '');
};
const handleDateRangeChange = (dates) => {
setPage(1);
setDateRange(dates || null);
};
const handleMinMoneyChange = (value) => {
setMinMoney(value);
};
const handleMaxMoneyChange = (value) => {
setMaxMoney(value);
};
const handleReset = () => {
setPage(1);
setKeyword('');
setSearchKeyword('');
setOrderId(undefined);
setAppliedOrderId(undefined);
setUserId(undefined);
setAppliedUserId(undefined);
setStatusFilter('');
setPaymentMethodFilter('');
setDateRange(null);
setMinMoney(undefined);
setMaxMoney(undefined);
setAppliedMinMoney(undefined);
setAppliedMaxMoney(undefined);
};
const copyText = (text, id) => {
navigator.clipboard
.writeText(text)
.then(() => {
setCopiedId(id);
Toast.success(t('已复制'));
setTimeout(() => setCopiedId(null), 2000);
})
.catch(() => {
showError(t('复制失败'));
});
};
const formatTime = (timestamp) => {
if (!timestamp) return '-';
return new Date(timestamp * 1000).toLocaleString();
};
const columns = [
{ title: 'ID', dataIndex: 'id', width: 60 },
{
title: t('订单号'),
dataIndex: 'trade_no',
width: 180,
ellipsis: true,
render: (text, record) => (
<div className='flex items-center gap-1'>
<span className='truncate text-xs font-mono' title={text}>
{text}
</span>
<button
className='flex-shrink-0 p-0.5 rounded hover:bg-gray-100 dark:hover:bg-neutral-700 cursor-pointer bg-transparent border-none'
onClick={() => copyText(text, `trade-${record.id}`)}
title={t('复制订单号')}
>
{copiedId === `trade-${record.id}` ? (
<Check size={12} className='text-green-500' />
) : (
<Copy size={12} className='text-gray-400' />
)}
</button>
</div>
),
},
{
title: t('用户'),
width: 140,
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>
);
}
if (displayName || username) {
return displayName || username;
}
return <span className='text-gray-400'>User#{record.user_id}</span>;
},
},
{ title: t('用户ID'), dataIndex: 'user_id', width: 70 },
{
title: t('充值额度'),
dataIndex: 'amount',
width: 100,
render: (v) => renderQuota(v, 2),
},
{
title: t('支付金额'),
dataIndex: 'money',
width: 90,
render: (v) => (v ? `¥${Number(v).toFixed(2)}` : '-'),
},
{
title: t('支付方式'),
dataIndex: 'payment_method',
width: 80,
render: (v) => (v ? paymentMethodMap[v] || v : '-'),
},
{
title: t('PayPal 结算'),
width: 210,
render: (_, record) => {
if (record.payment_method !== 'paypal') return '-';
return (
<div className='text-xs leading-5'>
<div>
{t('基础金额')}:{' '}
{formatUSDMinor(record.provider_base_amount_minor)}
</div>
<div>
{t('支付服务费')}:{' '}
{formatUSDMinor(record.payment_service_fee_minor)}
</div>
<div>
{t('PayPal 实际手续费')}:{' '}
{formatUSDMinor(record.provider_fee_minor)}
</div>
<div>
{t('PayPal 净收金额')}:{' '}
{formatUSDMinor(record.provider_net_amount_minor)}
</div>
<div>
{t('结算状态')}:{' '}
{t(
payPalSettlementStateMap[record.paypal_settlement_state] ||
record.paypal_settlement_state ||
'未知',
)}
</div>
</div>
);
},
},
{
title: t('状态'),
dataIndex: 'status',
width: 80,
render: (status) => (
<Tag color={statusColorMap[status] || 'grey'}>
{t(statusTextMap[status] || status || '未知')}
</Tag>
),
},
{
title: t('创建时间'),
dataIndex: 'create_time',
width: 150,
render: (v) => formatTime(v),
},
{
title: t('完成时间'),
dataIndex: 'complete_time',
width: 150,
render: (v) => formatTime(v),
},
];
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'>
<ShoppingCart size={18} className='text-blue-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: 220 }}
/>
<InputNumber
placeholder={t('订单ID')}
value={orderId}
onChange={setOrderId}
min={1}
style={{ width: 110 }}
hideButtons
/>
<InputNumber
placeholder={t('用户ID')}
value={userId}
onChange={setUserId}
min={1}
style={{ width: 110 }}
hideButtons
/>
<Select
placeholder={t('状态')}
value={statusFilter || undefined}
onChange={handleStatusFilterChange}
style={{ width: 110 }}
allowClear
optionList={[
{ label: t('待支付'), value: 'pending' },
{ label: t('已完成'), value: 'success' },
{ label: t('已过期'), value: 'expired' },
]}
/>
<Select
placeholder={t('支付方式')}
value={paymentMethodFilter || undefined}
onChange={handlePaymentMethodChange}
style={{ width: 120 }}
allowClear
optionList={Object.entries(paymentMethodMap).map(
([value, label]) => ({ label, value }),
)}
/>
<DatePicker
type='dateTimeRange'
value={dateRange}
onChange={handleDateRangeChange}
placeholder={[t('开始时间'), t('结束时间')]}
style={{ width: 340 }}
density='compact'
/>
<div className='flex items-center gap-1'>
<InputNumber
placeholder={t('最小金额')}
value={minMoney}
onChange={handleMinMoneyChange}
min={0}
precision={2}
style={{ width: 100 }}
prefix='¥'
/>
<span className='text-gray-400'>-</span>
<InputNumber
placeholder={t('最大金额')}
value={maxMoney}
onChange={handleMaxMoneyChange}
min={0}
precision={2}
style={{ width: 100 }}
prefix='¥'
/>
</div>
<Button
theme='solid'
type='primary'
size='default'
onClick={handleSearch}
>
{t('搜索')}
</Button>
<Button type='tertiary' size='default' onClick={handleReset}>
{t('重置')}
</Button>
</div>
{/* 表格 */}
<Table
columns={columns}
dataSource={orders}
loading={loading}
rowKey='id'
pagination={{
currentPage: page,
total,
pageSize: 20,
onPageChange: setPage,
showTotal: true,
showSizeChanger: false,
}}
scroll={{ x: 1100 }}
size='small'
empty={t('暂无订单数据')}
/>
</div>
);
};
export default AdminOrder;