1033 lines
34 KiB
React
1033 lines
34 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, {
|
||
useCallback,
|
||
useEffect,
|
||
useMemo,
|
||
useRef,
|
||
useState,
|
||
} from 'react';
|
||
import {
|
||
Banner,
|
||
Button,
|
||
Checkbox,
|
||
Col,
|
||
Form,
|
||
Modal,
|
||
Row,
|
||
Spin,
|
||
Table,
|
||
TextArea,
|
||
Typography,
|
||
} from '@/components/ui';
|
||
import { useTranslation } from 'react-i18next';
|
||
import {
|
||
API,
|
||
isRoot,
|
||
removeTrailingSlash,
|
||
showError,
|
||
showSuccess,
|
||
} from '../../../helpers';
|
||
import { mergePayPalFeePolicyFormValues } from '../../../helpers/paypalPayment';
|
||
|
||
const { Text } = Typography;
|
||
const SECRET_PLACEHOLDER = '***ALREADY_SET***';
|
||
|
||
function normalizePayPalOperations(data) {
|
||
if (!data || typeof data !== 'object' || Array.isArray(data)) {
|
||
return null;
|
||
}
|
||
return {
|
||
...data,
|
||
pending_count: Number.isFinite(Number(data.pending_count))
|
||
? Number(data.pending_count)
|
||
: 0,
|
||
pending_page: Number.isFinite(Number(data.pending_page))
|
||
? Number(data.pending_page)
|
||
: 1,
|
||
pending_page_size: Number.isFinite(Number(data.pending_page_size))
|
||
? Number(data.pending_page_size)
|
||
: 20,
|
||
pending_orders: Array.isArray(data.pending_orders)
|
||
? data.pending_orders.filter(
|
||
(order) =>
|
||
order &&
|
||
typeof order === 'object' &&
|
||
typeof order.trade_no === 'string' &&
|
||
order.trade_no.trim() !== '',
|
||
)
|
||
: [],
|
||
config_history: Array.isArray(data.config_history)
|
||
? data.config_history
|
||
: [],
|
||
can_change_config: Boolean(data.can_change_config),
|
||
};
|
||
}
|
||
|
||
export default function SettingsPaymentGatewayPayPal(props) {
|
||
const { t } = useTranslation();
|
||
const [loading, setLoading] = useState(false);
|
||
const [fxStatus, setFxStatus] = useState(null);
|
||
const [feePolicy, setFeePolicy] = useState(null);
|
||
const [feeAudits, setFeeAudits] = useState([]);
|
||
const [feeAuditLoading, setFeeAuditLoading] = useState(false);
|
||
const feeAuditSizeRef = useRef(20);
|
||
const [feeAuditPageSize, setFeeAuditPageSize] = useState(20);
|
||
const [feeAuditPage, setFeeAuditPage] = useState(1);
|
||
const [feeAuditTotal, setFeeAuditTotal] = useState(0);
|
||
const [operations, setOperations] = useState(null);
|
||
const [operationsLoading, setOperationsLoading] = useState(false);
|
||
const operationsSizeRef = useRef(20);
|
||
const [operationsPageSize, setOperationsPageSize] = useState(20);
|
||
const [operationsPage, setOperationsPage] = useState(1);
|
||
const [selectedOperationOrderKeys, setSelectedOperationOrderKeys] = useState(
|
||
[],
|
||
);
|
||
const [expireOrder, setExpireOrder] = useState(null);
|
||
const [expireReason, setExpireReason] = useState('');
|
||
const [forceExpire, setForceExpire] = useState(false);
|
||
const [forceExpireConfirmed, setForceExpireConfirmed] = useState(false);
|
||
const [batchExpire, setBatchExpire] = useState(null);
|
||
const [batchExpireReason, setBatchExpireReason] = useState('');
|
||
const [batchForceConfirmed, setBatchForceConfirmed] = useState(false);
|
||
const formApiRef = useRef(null);
|
||
const [inputs, setInputs] = useState({
|
||
PayPalClientID: '',
|
||
PayPalClientSecret: '',
|
||
PayPalWebhookID: '',
|
||
PayPalSandbox: true,
|
||
PayPalMinTopUp: 1,
|
||
PayPalFXMode: 'manual',
|
||
PayPalFXProvider: 'open_exchange_rates',
|
||
PayPalFXAPIKey: '',
|
||
PayPalFXAdjustmentBps: 0,
|
||
PayPalUserPaysFee: false,
|
||
PayPalFeeRatePercent: 0,
|
||
});
|
||
|
||
const initialValues = useRef(inputs).current;
|
||
const handleValuesChange = useCallback((values) => {
|
||
setInputs((current) =>
|
||
Object.keys(current).length === Object.keys(values).length &&
|
||
Object.keys(values).every((key) => Object.is(current[key], values[key]))
|
||
? current
|
||
: { ...values },
|
||
);
|
||
}, []);
|
||
|
||
useEffect(() => {
|
||
const values = {
|
||
PayPalClientID: props.options?.PayPalClientID || '',
|
||
PayPalClientSecret: props.options?.PayPalClientSecret || '',
|
||
PayPalWebhookID: props.options?.PayPalWebhookID || '',
|
||
PayPalSandbox: props.options?.PayPalSandbox ?? true,
|
||
PayPalMinTopUp: Number(props.options?.PayPalMinTopUp) || 1,
|
||
PayPalFXMode: props.options?.PayPalFXMode || 'manual',
|
||
PayPalFXProvider:
|
||
props.options?.PayPalFXProvider || 'open_exchange_rates',
|
||
PayPalFXAPIKey: props.options?.PayPalFXAPIKey || '',
|
||
PayPalFXAdjustmentBps: Number(props.options?.PayPalFXAdjustmentBps) || 0,
|
||
};
|
||
setInputs((current) => ({
|
||
...values,
|
||
PayPalUserPaysFee: current.PayPalUserPaysFee,
|
||
PayPalFeeRatePercent: current.PayPalFeeRatePercent,
|
||
}));
|
||
// setValues invokes onValueChange, so it must run outside state updaters.
|
||
if (formApiRef.current) {
|
||
formApiRef.current.setValues({
|
||
...formApiRef.current.getValues(),
|
||
...values,
|
||
});
|
||
}
|
||
}, [props.options]);
|
||
|
||
const refreshFXStatus = useCallback(async () => {
|
||
try {
|
||
const response = await API.get('/api/option/paypal/fx/status');
|
||
if (response.data.success) setFxStatus(response.data.data);
|
||
} catch {
|
||
setFxStatus(null);
|
||
}
|
||
}, []);
|
||
|
||
useEffect(() => {
|
||
refreshFXStatus();
|
||
}, [refreshFXStatus]);
|
||
|
||
const refreshFeePolicy = useCallback(
|
||
async (page = 1, preserveDraft = false) => {
|
||
if (!isRoot()) return;
|
||
setFeeAuditLoading(true);
|
||
try {
|
||
const [policyResponse, auditResponse] = await Promise.all([
|
||
API.get('/api/option/paypal/fee-policy'),
|
||
API.get(
|
||
`/api/option/paypal/fee-policy/audits?p=${page}&page_size=${feeAuditSizeRef.current}`,
|
||
),
|
||
]);
|
||
if (policyResponse.data.success) {
|
||
const policy = policyResponse.data.data;
|
||
setFeePolicy(policy);
|
||
if (!preserveDraft) {
|
||
setInputs((current) =>
|
||
mergePayPalFeePolicyFormValues(current, policy),
|
||
);
|
||
if (formApiRef.current) {
|
||
formApiRef.current.setValues(
|
||
mergePayPalFeePolicyFormValues(
|
||
formApiRef.current.getValues(),
|
||
policy,
|
||
),
|
||
);
|
||
}
|
||
}
|
||
}
|
||
if (auditResponse.data.success) {
|
||
const auditData = auditResponse.data.data;
|
||
setFeeAudits(auditData?.items || []);
|
||
setFeeAuditPage(page);
|
||
setFeeAuditTotal(Number(auditData?.total || 0));
|
||
} else {
|
||
showError(auditResponse.data.message || t('获取手续费策略失败'));
|
||
}
|
||
} catch (error) {
|
||
showError(error?.response?.data?.message || t('获取手续费策略失败'));
|
||
} finally {
|
||
setFeeAuditLoading(false);
|
||
}
|
||
},
|
||
[t],
|
||
);
|
||
|
||
useEffect(() => {
|
||
refreshFeePolicy(1);
|
||
}, [refreshFeePolicy]);
|
||
|
||
const refreshOperations = useCallback(
|
||
async (page = 1) => {
|
||
if (!isRoot()) return;
|
||
setOperationsLoading(true);
|
||
try {
|
||
const response = await API.get(
|
||
`/api/option/paypal/operations/preflight?p=${page}&page_size=${operationsSizeRef.current}`,
|
||
);
|
||
if (response?.data?.success) {
|
||
setOperations(normalizePayPalOperations(response.data.data));
|
||
setOperationsPage(page);
|
||
} else {
|
||
showError(response.data.message || t('获取 PayPal 订单预检信息失败'));
|
||
}
|
||
} catch (error) {
|
||
showError(
|
||
error?.response?.data?.message || t('获取 PayPal 订单预检信息失败'),
|
||
);
|
||
} finally {
|
||
setOperationsLoading(false);
|
||
}
|
||
},
|
||
[t],
|
||
);
|
||
|
||
useEffect(() => {
|
||
refreshOperations(1);
|
||
}, [refreshOperations]);
|
||
|
||
const inspectOperationOrder = useCallback(
|
||
async (tradeNo) => {
|
||
setLoading(true);
|
||
try {
|
||
const response = await API.post(
|
||
`/api/option/paypal/operations/orders/${encodeURIComponent(tradeNo)}/inspect`,
|
||
);
|
||
if (!response.data.success)
|
||
throw new Error(response.data.message || t('查询失败'));
|
||
const data = response.data.data;
|
||
showSuccess(`${tradeNo}:PayPal 状态 ${data.remote_status}`);
|
||
setSelectedOperationOrderKeys((keys) =>
|
||
keys.filter((key) => key !== String(tradeNo)),
|
||
);
|
||
await refreshOperations(operationsPage);
|
||
} catch (error) {
|
||
showError(
|
||
error?.response?.data?.message || error?.message || t('查询失败'),
|
||
);
|
||
} finally {
|
||
setLoading(false);
|
||
}
|
||
},
|
||
[t, refreshOperations, operationsPage],
|
||
);
|
||
|
||
const reconcileOperationOrder = useCallback(
|
||
async (tradeNo) => {
|
||
setLoading(true);
|
||
try {
|
||
const response = await API.post(
|
||
`/api/option/paypal/operations/orders/${encodeURIComponent(tradeNo)}/reconcile`,
|
||
);
|
||
if (!response.data.success)
|
||
throw new Error(response.data.message || t('对账失败'));
|
||
showSuccess(t('PayPal 订单已触发对账'));
|
||
setSelectedOperationOrderKeys((keys) =>
|
||
keys.filter((key) => key !== String(tradeNo)),
|
||
);
|
||
await refreshOperations(operationsPage);
|
||
} catch (error) {
|
||
showError(
|
||
error?.response?.data?.message || error?.message || t('对账失败'),
|
||
);
|
||
} finally {
|
||
setLoading(false);
|
||
}
|
||
},
|
||
[t, refreshOperations, operationsPage],
|
||
);
|
||
|
||
const expireOperationOrder = async () => {
|
||
const reason =
|
||
typeof expireReason === 'string'
|
||
? expireReason.trim()
|
||
: String(expireReason ?? '').trim();
|
||
if (!expireOrder || reason.length < 6) {
|
||
showError(t('请填写至少 6 个字符的过期原因'));
|
||
return;
|
||
}
|
||
if (forceExpire && !forceExpireConfirmed) {
|
||
showError(t('请先确认强制过期风险'));
|
||
return;
|
||
}
|
||
setLoading(true);
|
||
try {
|
||
const response = await API.post(
|
||
`/api/option/paypal/operations/orders/${encodeURIComponent(expireOrder.trade_no)}/expire`,
|
||
{
|
||
confirm_trade_no: expireOrder.trade_no,
|
||
reason,
|
||
force: forceExpire,
|
||
},
|
||
);
|
||
if (!response.data.success)
|
||
throw new Error(response.data.message || t('过期失败'));
|
||
showSuccess(t('PayPal 订单已标记为过期'));
|
||
setExpireOrder(null);
|
||
setExpireReason('');
|
||
setForceExpire(false);
|
||
setForceExpireConfirmed(false);
|
||
setSelectedOperationOrderKeys((keys) =>
|
||
keys.filter((key) => key !== String(expireOrder.trade_no)),
|
||
);
|
||
await refreshOperations(operationsPage);
|
||
} catch (error) {
|
||
showError(
|
||
error?.response?.data?.message || error?.message || t('过期失败'),
|
||
);
|
||
} finally {
|
||
setLoading(false);
|
||
}
|
||
};
|
||
|
||
const runBatchOperation = async (operation) => {
|
||
if (selectedOperationOrderKeys.length === 0) {
|
||
showError(t('请先勾选 PayPal 订单'));
|
||
return;
|
||
}
|
||
setLoading(true);
|
||
try {
|
||
const response = await API.post(
|
||
'/api/option/paypal/operations/orders/batch',
|
||
{
|
||
trade_nos: selectedOperationOrderKeys,
|
||
operation,
|
||
},
|
||
);
|
||
if (!response?.data?.success) {
|
||
throw new Error(response?.data?.message || t('批量操作失败'));
|
||
}
|
||
const data = response.data.data || {};
|
||
const failedResults = (data.results || []).filter(
|
||
(item) => !item.success,
|
||
);
|
||
showSuccess(
|
||
`批量${operation === 'inspect' ? '查询' : '对账'}完成:成功 ${data.succeeded || 0} 笔,失败 ${data.failed || 0} 笔`,
|
||
);
|
||
if (failedResults.length > 0) {
|
||
showError(
|
||
failedResults
|
||
.slice(0, 3)
|
||
.map((item) => `${item.trade_no}:${item.message || t('操作失败')}`)
|
||
.join(';'),
|
||
);
|
||
}
|
||
setSelectedOperationOrderKeys([]);
|
||
await refreshOperations(operationsPage);
|
||
} catch (error) {
|
||
showError(
|
||
error?.response?.data?.message || error?.message || t('批量操作失败'),
|
||
);
|
||
} finally {
|
||
setLoading(false);
|
||
}
|
||
};
|
||
|
||
const openBatchExpire = (force) => {
|
||
if (selectedOperationOrderKeys.length === 0) {
|
||
showError(t('请先勾选 PayPal 订单'));
|
||
return;
|
||
}
|
||
setBatchExpire({ tradeNos: selectedOperationOrderKeys, force });
|
||
setBatchForceConfirmed(false);
|
||
setBatchExpireReason(
|
||
force
|
||
? '管理员确认远端状态无法核验,强制关闭所选 PayPal 订单'
|
||
: '确认所选 PayPal 订单均未完成支付',
|
||
);
|
||
};
|
||
|
||
const confirmBatchExpire = async () => {
|
||
const reason = batchExpireReason.trim();
|
||
if (!batchExpire || reason.length < 6) {
|
||
showError(t('请填写至少 6 个字符的过期原因'));
|
||
return;
|
||
}
|
||
if (batchExpire.force && !batchForceConfirmed) {
|
||
showError(t('请先确认强制过期风险'));
|
||
return;
|
||
}
|
||
setLoading(true);
|
||
try {
|
||
const response = await API.post(
|
||
'/api/option/paypal/operations/orders/batch',
|
||
{
|
||
trade_nos: batchExpire.tradeNos,
|
||
operation: 'expire',
|
||
reason,
|
||
force: batchExpire.force,
|
||
},
|
||
);
|
||
if (!response?.data?.success) {
|
||
throw new Error(response?.data?.message || t('批量过期失败'));
|
||
}
|
||
const data = response.data.data || {};
|
||
const failedResults = (data.results || []).filter(
|
||
(item) => !item.success,
|
||
);
|
||
showSuccess(
|
||
`批量${batchExpire.force ? '强制' : ''}过期完成:成功 ${data.succeeded || 0} 笔,失败 ${data.failed || 0} 笔`,
|
||
);
|
||
if (failedResults.length > 0) {
|
||
showError(
|
||
failedResults
|
||
.slice(0, 3)
|
||
.map((item) => `${item.trade_no}:${item.message || t('操作失败')}`)
|
||
.join(';'),
|
||
);
|
||
}
|
||
setBatchExpire(null);
|
||
setBatchExpireReason('');
|
||
setBatchForceConfirmed(false);
|
||
setSelectedOperationOrderKeys([]);
|
||
await refreshOperations(operationsPage);
|
||
} catch (error) {
|
||
showError(
|
||
error?.response?.data?.message || error?.message || t('批量过期失败'),
|
||
);
|
||
} finally {
|
||
setLoading(false);
|
||
}
|
||
};
|
||
|
||
const submit = async () => {
|
||
if (!props.options?.ServerAddress) {
|
||
showError(t('请先填写服务器地址'));
|
||
return;
|
||
}
|
||
const options = [
|
||
{ key: 'PayPalClientID', value: inputs.PayPalClientID?.trim() },
|
||
{ key: 'PayPalWebhookID', value: inputs.PayPalWebhookID?.trim() },
|
||
{ key: 'PayPalSandbox', value: String(inputs.PayPalSandbox) },
|
||
{ key: 'PayPalMinTopUp', value: String(inputs.PayPalMinTopUp || 1) },
|
||
{ key: 'PayPalFXMode', value: inputs.PayPalFXMode || 'manual' },
|
||
{
|
||
key: 'PayPalFXProvider',
|
||
value: inputs.PayPalFXProvider || 'open_exchange_rates',
|
||
},
|
||
{
|
||
key: 'PayPalFXAdjustmentBps',
|
||
value: String(inputs.PayPalFXAdjustmentBps || 0),
|
||
},
|
||
];
|
||
if (
|
||
inputs.PayPalClientSecret &&
|
||
inputs.PayPalClientSecret !== SECRET_PLACEHOLDER
|
||
) {
|
||
options.push({
|
||
key: 'PayPalClientSecret',
|
||
value: inputs.PayPalClientSecret,
|
||
});
|
||
}
|
||
if (inputs.PayPalFXAPIKey && inputs.PayPalFXAPIKey !== SECRET_PLACEHOLDER) {
|
||
options.push({ key: 'PayPalFXAPIKey', value: inputs.PayPalFXAPIKey });
|
||
}
|
||
setLoading(true);
|
||
try {
|
||
for (const option of options) {
|
||
const response = await API.put('/api/option/', option);
|
||
if (!response.data.success) {
|
||
throw new Error(response.data.message || t('更新失败'));
|
||
}
|
||
}
|
||
if (isRoot()) {
|
||
const rateBps = Math.round(
|
||
Number(inputs.PayPalFeeRatePercent || 0) * 100,
|
||
);
|
||
if (
|
||
rateBps < 0 ||
|
||
rateBps > 2000 ||
|
||
(inputs.PayPalUserPaysFee && rateBps < 1)
|
||
) {
|
||
throw new Error(t('手续费比例必须在有效范围内'));
|
||
}
|
||
const response = await API.put('/api/option/paypal/fee-policy', {
|
||
user_pays_fee: Boolean(inputs.PayPalUserPaysFee),
|
||
rate_bps: rateBps,
|
||
expected_version: feePolicy?.version,
|
||
});
|
||
if (!response.data.success) {
|
||
throw new Error(response.data.message || t('更新失败'));
|
||
}
|
||
}
|
||
showSuccess(t('更新成功'));
|
||
await props.refresh?.();
|
||
await refreshFXStatus();
|
||
await refreshFeePolicy(1);
|
||
} catch (error) {
|
||
if (error?.response?.status === 409) {
|
||
await refreshFeePolicy(feeAuditPage, true);
|
||
showError(t('手续费策略已被其他管理员更新,请重新确认'));
|
||
} else {
|
||
showError(
|
||
error?.response?.data?.message || error?.message || t('更新失败'),
|
||
);
|
||
}
|
||
} finally {
|
||
setLoading(false);
|
||
}
|
||
};
|
||
|
||
const feeAuditColumns = useMemo(
|
||
() => [
|
||
{
|
||
title: t('版本'),
|
||
dataIndex: 'policy_version',
|
||
width: 80,
|
||
},
|
||
{
|
||
title: t('承担方'),
|
||
dataIndex: 'new_user_pays_fee',
|
||
render: (value) => t(value ? '用户承担' : '平台承担'),
|
||
},
|
||
{
|
||
title: t('费率'),
|
||
dataIndex: 'new_rate_bps',
|
||
render: (value) => `${(Number(value) / 100).toFixed(2)}%`,
|
||
},
|
||
{
|
||
title: t('操作人'),
|
||
dataIndex: 'operator_id',
|
||
},
|
||
{
|
||
title: t('更新时间'),
|
||
dataIndex: 'created_at',
|
||
render: (value) =>
|
||
value ? new Date(value * 1000).toLocaleString() : '-',
|
||
},
|
||
],
|
||
[t],
|
||
);
|
||
|
||
const operationColumns = useMemo(
|
||
() => [
|
||
{ title: '本地订单号', dataIndex: 'trade_no' },
|
||
{ title: 'PayPal Order ID', dataIndex: 'third_trade_no' },
|
||
{ title: '环境', dataIndex: 'payment_environment' },
|
||
{
|
||
title: '创建时间',
|
||
dataIndex: 'create_time',
|
||
render: (value) =>
|
||
value ? new Date(value * 1000).toLocaleString() : '-',
|
||
},
|
||
{
|
||
title: '操作',
|
||
render: (_, row) => (
|
||
<div className='flex flex-wrap gap-2'>
|
||
<Button
|
||
size='small'
|
||
htmlType='button'
|
||
onClick={() => inspectOperationOrder(row.trade_no)}
|
||
>
|
||
查询远端状态
|
||
</Button>
|
||
<Button
|
||
size='small'
|
||
theme='solid'
|
||
htmlType='button'
|
||
onClick={() => reconcileOperationOrder(row.trade_no)}
|
||
disabled={!row.third_trade_no}
|
||
>
|
||
触发对账
|
||
</Button>
|
||
<Button
|
||
size='small'
|
||
type='danger'
|
||
htmlType='button'
|
||
onClick={() => {
|
||
setExpireOrder(row);
|
||
setForceExpire(false);
|
||
setForceExpireConfirmed(false);
|
||
setExpireReason('确认该订单未完成 PayPal 支付');
|
||
}}
|
||
>
|
||
确认未付款并过期
|
||
</Button>
|
||
<Button
|
||
size='small'
|
||
type='warning'
|
||
htmlType='button'
|
||
onClick={() => {
|
||
setExpireOrder(row);
|
||
setForceExpire(true);
|
||
setForceExpireConfirmed(false);
|
||
setExpireReason(
|
||
'管理员确认远端状态无法核验,强制关闭该 PayPal 订单',
|
||
);
|
||
}}
|
||
>
|
||
强制过期
|
||
</Button>
|
||
</div>
|
||
),
|
||
},
|
||
],
|
||
[inspectOperationOrder, reconcileOperationOrder],
|
||
);
|
||
|
||
const webhookBase = props.options?.ServerAddress
|
||
? removeTrailingSlash(props.options.ServerAddress)
|
||
: t('网站地址');
|
||
const pendingOrders = Array.isArray(operations?.pending_orders)
|
||
? operations.pending_orders
|
||
: [];
|
||
|
||
const runFXAction = async (action) => {
|
||
setLoading(true);
|
||
try {
|
||
const response = await API.post(`/api/option/paypal/fx/${action}`);
|
||
if (!response.data.success) {
|
||
throw new Error(response.data.message || t('操作失败'));
|
||
}
|
||
showSuccess(
|
||
t(action === 'refresh' ? '汇率刷新成功' : '已确认手工兜底汇率'),
|
||
);
|
||
await refreshFXStatus();
|
||
} catch (error) {
|
||
showError(error?.message || t('操作失败'));
|
||
} finally {
|
||
setLoading(false);
|
||
}
|
||
};
|
||
|
||
return (
|
||
<Spin spinning={loading}>
|
||
<Form
|
||
initValues={initialValues}
|
||
onValueChange={handleValuesChange}
|
||
getFormApi={(api) => (formApiRef.current = api)}
|
||
>
|
||
<Form.Section text={t('PayPal 设置')}>
|
||
<Banner
|
||
type='info'
|
||
description={`${t('Webhook 地址')}:${webhookBase}/api/paypal/webhook`}
|
||
/>
|
||
{isRoot() && (
|
||
<>
|
||
<Row gutter={16} style={{ marginTop: 16 }}>
|
||
<Col xs={24} md={8}>
|
||
<Form.Switch
|
||
field='PayPalUserPaysFee'
|
||
label={t('用户承担支付服务费')}
|
||
checkedText='|'
|
||
uncheckedText='〇'
|
||
/>
|
||
</Col>
|
||
<Col xs={24} md={8}>
|
||
<Form.InputNumber
|
||
field='PayPalFeeRatePercent'
|
||
label={t('支付服务费比例(%)')}
|
||
min={inputs.PayPalUserPaysFee ? 0.01 : 0}
|
||
max={20}
|
||
precision={2}
|
||
disabled={!inputs.PayPalUserPaysFee}
|
||
/>
|
||
</Col>
|
||
<Col xs={24} md={8}>
|
||
<Text type='tertiary'>
|
||
{t('手续费策略版本')}:{feePolicy?.version || '-'}
|
||
<br />
|
||
{t('最后更新')}:
|
||
{feePolicy?.updated_at
|
||
? new Date(feePolicy.updated_at * 1000).toLocaleString()
|
||
: '-'}
|
||
<br />
|
||
{t('最后更新人')}:{feePolicy?.updated_by || '-'}
|
||
</Text>
|
||
</Col>
|
||
</Row>
|
||
<Banner
|
||
type='info'
|
||
description={t(
|
||
'默认由平台承担;启用后将按配置比例向用户展示并收取支付服务费',
|
||
)}
|
||
style={{ marginTop: 16 }}
|
||
/>
|
||
<Table
|
||
size='small'
|
||
pagination={{
|
||
currentPage: feeAuditPage,
|
||
pageSize: feeAuditPageSize,
|
||
total: feeAuditTotal,
|
||
showTotal: (total) => t('共 {{total}} 条', { total }),
|
||
onPageChange: (page) => refreshFeePolicy(page, true),
|
||
onPageSizeChange: (size) => {
|
||
feeAuditSizeRef.current = size;
|
||
setFeeAuditPageSize(size);
|
||
refreshFeePolicy(1, true);
|
||
},
|
||
}}
|
||
dataSource={feeAudits}
|
||
loading={feeAuditLoading}
|
||
rowKey='id'
|
||
style={{ marginTop: 16 }}
|
||
columns={feeAuditColumns}
|
||
/>
|
||
<Banner
|
||
type={operations?.pending_count ? 'warning' : 'success'}
|
||
description={
|
||
operations
|
||
? `配置切换预检:${operations.pending_count || 0} 笔 PayPal pending 订单;${
|
||
operations.can_change_config
|
||
? '可以切换环境或应用配置'
|
||
: '请先隐藏新订单并完成历史订单排空'
|
||
}`
|
||
: '正在读取 PayPal 配置切换预检状态'
|
||
}
|
||
style={{ marginTop: 16 }}
|
||
/>
|
||
{pendingOrders.length > 0 && (
|
||
<div
|
||
className='flex flex-wrap items-center gap-2'
|
||
style={{ marginTop: 12 }}
|
||
>
|
||
<Text type='tertiary'>
|
||
已选 {selectedOperationOrderKeys.length} 笔
|
||
</Text>
|
||
<Button
|
||
size='small'
|
||
htmlType='button'
|
||
disabled={selectedOperationOrderKeys.length === 0}
|
||
onClick={() => runBatchOperation('inspect')}
|
||
>
|
||
批量查询远端状态
|
||
</Button>
|
||
<Button
|
||
size='small'
|
||
theme='solid'
|
||
htmlType='button'
|
||
disabled={selectedOperationOrderKeys.length === 0}
|
||
onClick={() => runBatchOperation('reconcile')}
|
||
>
|
||
批量触发对账
|
||
</Button>
|
||
<Button
|
||
size='small'
|
||
type='danger'
|
||
htmlType='button'
|
||
disabled={selectedOperationOrderKeys.length === 0}
|
||
onClick={() => openBatchExpire(false)}
|
||
>
|
||
批量确认过期
|
||
</Button>
|
||
<Button
|
||
size='small'
|
||
type='warning'
|
||
htmlType='button'
|
||
disabled={selectedOperationOrderKeys.length === 0}
|
||
onClick={() => openBatchExpire(true)}
|
||
>
|
||
批量强制过期
|
||
</Button>
|
||
</div>
|
||
)}
|
||
{pendingOrders.length > 0 && (
|
||
<Table
|
||
size='small'
|
||
rowKey='trade_no'
|
||
dataSource={pendingOrders}
|
||
loading={operationsLoading}
|
||
rowSelection={{
|
||
selectedRowKeys: selectedOperationOrderKeys,
|
||
onChange: (keys) =>
|
||
setSelectedOperationOrderKeys(keys.map(String)),
|
||
}}
|
||
pagination={{
|
||
onPageSizeChange: (size) => {
|
||
operationsSizeRef.current = size;
|
||
setOperationsPageSize(size);
|
||
setSelectedOperationOrderKeys([]);
|
||
refreshOperations(1);
|
||
},
|
||
currentPage: operationsPage,
|
||
pageSize: operationsPageSize,
|
||
total: Number(operations?.pending_count || 0),
|
||
showTotal: (total) => t('共 {{total}} 条', { total }),
|
||
onPageChange: (page) => {
|
||
setSelectedOperationOrderKeys([]);
|
||
refreshOperations(page);
|
||
},
|
||
}}
|
||
scroll={{ x: 900 }}
|
||
style={{ marginTop: 12 }}
|
||
columns={operationColumns}
|
||
/>
|
||
)}
|
||
<Button
|
||
size='small'
|
||
type='tertiary'
|
||
htmlType='button'
|
||
onClick={() => refreshOperations(operationsPage)}
|
||
style={{ marginTop: 12 }}
|
||
>
|
||
刷新配置切换预检
|
||
</Button>
|
||
</>
|
||
)}
|
||
<Banner
|
||
type='warning'
|
||
description={t(
|
||
'订阅 CHECKOUT.ORDER.APPROVED、PAYMENT.CAPTURE.COMPLETED、PAYMENT.CAPTURE.PENDING、PAYMENT.CAPTURE.DECLINED、PAYMENT.CAPTURE.DENIED 和 CHECKOUT.PAYMENT-APPROVAL.REVERSED 事件',
|
||
)}
|
||
/>
|
||
<Row gutter={16}>
|
||
<Col xs={24} md={8}>
|
||
<Form.Input field='PayPalClientID' label='Client ID' />
|
||
</Col>
|
||
<Col xs={24} md={8}>
|
||
<Form.Input
|
||
field='PayPalClientSecret'
|
||
label='Client Secret'
|
||
type='password'
|
||
placeholder={t('敏感信息不会显示')}
|
||
/>
|
||
</Col>
|
||
<Col xs={24} md={8}>
|
||
<Form.Input field='PayPalWebhookID' label='Webhook ID' />
|
||
</Col>
|
||
</Row>
|
||
<Row gutter={16} style={{ marginTop: 16 }}>
|
||
<Col xs={24} md={8}>
|
||
<Form.Switch
|
||
field='PayPalSandbox'
|
||
label={t('Sandbox 测试环境')}
|
||
checkedText='|'
|
||
uncheckedText='〇'
|
||
/>
|
||
</Col>
|
||
<Col xs={24} md={8}>
|
||
<Form.InputNumber
|
||
field='PayPalMinTopUp'
|
||
label={t('最低充值单位')}
|
||
min={1}
|
||
precision={0}
|
||
/>
|
||
</Col>
|
||
<Col xs={24} md={8}>
|
||
<Text type='tertiary'>
|
||
{t('结算币种')}:USD
|
||
<br />
|
||
{t('换算汇率')}:USDExchangeRate ={' '}
|
||
{props.options?.USDExchangeRate || '-'}
|
||
</Text>
|
||
</Col>
|
||
</Row>
|
||
<Row gutter={16} style={{ marginTop: 16 }}>
|
||
<Col xs={24} md={8}>
|
||
<Form.Select
|
||
field='PayPalFXMode'
|
||
label={t('汇率模式')}
|
||
optionList={[
|
||
{ label: t('手工汇率'), value: 'manual' },
|
||
{ label: t('准实时汇率'), value: 'realtime' },
|
||
]}
|
||
/>
|
||
</Col>
|
||
<Col xs={24} md={8}>
|
||
<Form.Input
|
||
field='PayPalFXAPIKey'
|
||
label='Open Exchange Rates API Key'
|
||
type='password'
|
||
placeholder={t('敏感信息不会显示')}
|
||
/>
|
||
</Col>
|
||
<Col xs={24} md={8}>
|
||
<Form.InputNumber
|
||
field='PayPalFXAdjustmentBps'
|
||
label={t('汇率保护加点(基点)')}
|
||
min={0}
|
||
max={300}
|
||
precision={0}
|
||
/>
|
||
</Col>
|
||
</Row>
|
||
<Banner
|
||
type={fxStatus?.latest_valid ? 'success' : 'warning'}
|
||
description={
|
||
fxStatus?.latest_valid
|
||
? `${t('当前市场汇率')}:1 USD = ${fxStatus.latest_valid.market_rate} CNY`
|
||
: t('暂无可用的市场汇率快照')
|
||
}
|
||
style={{ marginTop: 16 }}
|
||
/>
|
||
<div className='flex flex-wrap gap-2' style={{ marginTop: 12 }}>
|
||
<Button onClick={submit} disabled={isRoot() && !feePolicy}>
|
||
{t('更新 PayPal 设置')}
|
||
</Button>
|
||
<Button type='tertiary' onClick={() => runFXAction('refresh')}>
|
||
{t('立即刷新汇率')}
|
||
</Button>
|
||
<Button type='warning' onClick={() => runFXAction('acknowledge')}>
|
||
{t('确认手工兜底汇率')}
|
||
</Button>
|
||
</div>
|
||
</Form.Section>
|
||
</Form>
|
||
<Modal
|
||
title={
|
||
forceExpire ? '确认强制过期 PayPal 订单' : '确认 PayPal 订单过期'
|
||
}
|
||
visible={Boolean(expireOrder)}
|
||
onCancel={() => setExpireOrder(null)}
|
||
onOk={expireOperationOrder}
|
||
okText='确认过期'
|
||
cancelText='取消'
|
||
>
|
||
{expireOrder && (
|
||
<div className='space-y-3'>
|
||
<Text>
|
||
订单:<strong>{expireOrder.trade_no}</strong>
|
||
</Text>
|
||
<Banner
|
||
type={forceExpire ? 'danger' : 'warning'}
|
||
description={
|
||
forceExpire
|
||
? '强制过期会绕过远端查询失败或仍可支付状态,可能导致 PayPal 后续付款无法入账。已确认完成支付的订单仍会被拒绝。'
|
||
: '系统会再次查询 PayPal 远端状态;如果已完成支付,将拒绝过期操作。请确认未付款后再提交。'
|
||
}
|
||
/>
|
||
{forceExpire && (
|
||
<Checkbox
|
||
checked={forceExpireConfirmed}
|
||
onChange={(event) =>
|
||
setForceExpireConfirmed(
|
||
Boolean(event?.target?.checked ?? event?.checked),
|
||
)
|
||
}
|
||
>
|
||
我确认已核对 PayPal 后台或业务记录,同意强制关闭该订单
|
||
</Checkbox>
|
||
)}
|
||
<TextArea
|
||
value={expireReason}
|
||
onChange={(value) =>
|
||
setExpireReason(
|
||
typeof value === 'string'
|
||
? value
|
||
: value?.target?.value || '',
|
||
)
|
||
}
|
||
rows={3}
|
||
placeholder='填写处置原因,至少 6 个字符'
|
||
/>
|
||
</div>
|
||
)}
|
||
</Modal>
|
||
<Modal
|
||
title={
|
||
batchExpire?.force
|
||
? '确认批量强制过期 PayPal 订单'
|
||
: '确认批量 PayPal 订单过期'
|
||
}
|
||
visible={Boolean(batchExpire)}
|
||
onCancel={() => setBatchExpire(null)}
|
||
onOk={confirmBatchExpire}
|
||
okText='确认批量过期'
|
||
cancelText='取消'
|
||
>
|
||
{batchExpire && (
|
||
<div className='space-y-3'>
|
||
<Text>已选择 {batchExpire.tradeNos.length} 笔 PayPal 订单。</Text>
|
||
<Banner
|
||
type={batchExpire.force ? 'danger' : 'warning'}
|
||
description={
|
||
batchExpire.force
|
||
? '批量强制过期会绕过远端查询失败或仍可支付状态;已确认完成支付的订单仍会逐笔拒绝。'
|
||
: '系统会逐笔查询 PayPal 远端状态,已完成或仍可支付的订单会逐笔失败并返回原因。'
|
||
}
|
||
/>
|
||
{batchExpire.force && (
|
||
<Checkbox
|
||
checked={batchForceConfirmed}
|
||
onChange={(event) =>
|
||
setBatchForceConfirmed(
|
||
Boolean(event?.target?.checked ?? event?.checked),
|
||
)
|
||
}
|
||
>
|
||
我确认已核对所选订单,同意批量强制关闭
|
||
</Checkbox>
|
||
)}
|
||
<TextArea
|
||
value={batchExpireReason}
|
||
onChange={(value) =>
|
||
setBatchExpireReason(
|
||
typeof value === 'string'
|
||
? value
|
||
: value?.target?.value || '',
|
||
)
|
||
}
|
||
rows={3}
|
||
placeholder='填写处置原因,至少 6 个字符'
|
||
/>
|
||
</div>
|
||
)}
|
||
</Modal>
|
||
</Spin>
|
||
);
|
||
}
|