/*
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, { useEffect, useState, useCallback, useMemo } from 'react';
import { timestamp2string } from '../../helpers/utils';
import { useTranslation } from 'react-i18next';
import {
Typography,
Button,
Spin,
Table,
Tag,
InputNumber,
Select,
} from '@douyinfe/semi-ui';
import {
CreditCard,
Wallet,
TrendingUp,
Coins,
History,
CheckCircle,
Clock,
XCircle,
Pencil,
} from 'lucide-react';
import {
API,
showError,
showInfo,
showSuccess,
renderQuota,
getQuotaPerUnit,
} from '../../helpers';
import AmountCard from '../Recharge/AmountCard';
import WechatQRModal from '../../components/topup/modals/WechatQRModal';
import PaymentConfirmModal from '../../components/topup/modals/PaymentConfirmModal';
import OrgPageHeader from './components/OrgPageHeader';
import OrgPanel from './components/OrgPanel';
import { orgStatusColor } from './components/orgStatus';
import {
formatPayPalUSD,
getPayPalReturnState,
parsePayPalQuote,
requestPayPalOrder,
removePayPalReturnState,
} from '../../helpers/paypalPayment';
const { Text, Title } = Typography;
const OrgRecharge = ({ orgId }) => {
const { t } = useTranslation();
// 企业信息
const [orgQuota, setOrgQuota] = useState(0);
const [orgUsedQuota, setOrgUsedQuota] = useState(0);
// 充值配置
const [presetAmounts, setPresetAmounts] = useState([]);
const [payMethods, setPayMethods] = useState([]);
const [enableWechatTopUp, setEnableWechatTopUp] = useState(false);
const [enableAlipayTopUp, setEnableAlipayTopUp] = useState(false);
const [enablePayPalTopUp, setEnablePayPalTopUp] = useState(false);
const [infoLoading, setInfoLoading] = useState(true);
// 充值交互状态
const [selectedPreset, setSelectedPreset] = useState(null);
const [selectedPresetObj, setSelectedPresetObj] = useState(null);
const [payWay, setPayWay] = useState('');
const [confirmOpen, setConfirmOpen] = useState(false);
const [confirmLoading, setConfirmLoading] = useState(false);
const [amountLoading, setAmountLoading] = useState(false);
const [payPalQuote, setPayPalQuote] = useState(null);
// 自定义充值(与预设档位互斥;自定义金额无折扣,原价到账)
const [isCustomMode, setIsCustomMode] = useState(false);
const [customAmount, setCustomAmount] = useState(null);
const [customUnit, setCustomUnit] = useState(1000); // 1000=千 / 10000=万
const customEffectiveAmount = useMemo(() => {
if (!customAmount || customAmount < 1) return 0;
return Math.floor(Number(customAmount)) * customUnit;
}, [customAmount, customUnit]);
const customValid = customEffectiveAmount >= 1000;
// 当前生效的金额/折扣/赠送(自定义优先)
const effectiveAmountYuan = isCustomMode
? customEffectiveAmount
: selectedPresetObj?.value || 0;
const effectiveDiscount = isCustomMode
? 1.0
: selectedPresetObj?.discount || 1.0;
const effectiveBonus = isCustomMode ? 0 : selectedPresetObj?.bonus || 0;
// 微信二维码
const [wechatQRVisible, setWechatQRVisible] = useState(false);
const [wechatOrderData, setWechatOrderData] = useState(null);
// 充值记录
const [history, setHistory] = useState([]);
const [historyTotal, setHistoryTotal] = useState(0);
const [historyPage, setHistoryPage] = useState(1);
const [historyLoading, setHistoryLoading] = useState(false);
const [refreshHistory, setRefreshHistory] = useState(0);
const orgHeaders = { 'X-Org-Id': String(orgId) };
// 获取企业配额
const fetchOrgQuota = useCallback(async () => {
try {
const res = await API.get('/api/org/quota', { headers: orgHeaders });
if (res.data.success) {
const { quota, used_quota } = res.data.data;
setOrgQuota(quota || 0);
setOrgUsedQuota(used_quota || 0);
}
} catch (e) {
// ignore
}
}, [orgId]);
// 获取充值配置
const fetchTopUpInfo = useCallback(async () => {
setInfoLoading(true);
try {
const res = await API.get('/api/org/topup/info', { headers: orgHeaders });
if (res.data.success) {
const data = res.data.data;
setEnableWechatTopUp(data.enable_wechat_topup || false);
setEnableAlipayTopUp(data.enable_alipay_topup || false);
setEnablePayPalTopUp(data.enable_paypal_topup || false);
setPayMethods(data.pay_methods || []);
if (data.amount_options_v2 && data.amount_options_v2.length > 0) {
const sorted = [...data.amount_options_v2].sort(
(a, b) => (a.sort || 0) - (b.sort || 0),
);
setPresetAmounts(
sorted.map((opt) => ({
id: opt.id,
value: opt.amount,
discount: opt.discount || 1.0,
label: opt.label,
badge: opt.badge,
badgeColor: opt.badge_color,
isRecommend: opt.is_recommend,
isHot: opt.is_hot,
bonus: opt.bonus,
minVipLevel: opt.min_vip_level,
})),
);
}
}
} catch (e) {
showError(t('获取充值配置失败'));
} finally {
setInfoLoading(false);
}
}, [orgId]);
// 获取充值记录
const fetchHistory = useCallback(
async (page = 1) => {
setHistoryLoading(true);
try {
const res = await API.get(`/api/org/topup?p=${page}&page_size=10`, {
headers: orgHeaders,
});
if (res.data.success) {
const data = res.data.data;
setHistory(data.items || []);
setHistoryTotal(data.total || 0);
}
} catch (e) {
// ignore
} finally {
setHistoryLoading(false);
}
},
[orgId],
);
useEffect(() => {
fetchOrgQuota();
fetchTopUpInfo();
}, [fetchOrgQuota, fetchTopUpInfo]);
useEffect(() => {
fetchHistory(historyPage);
}, [fetchHistory, historyPage, refreshHistory]);
useEffect(() => {
const result = getPayPalReturnState(window.location.search);
if (!result) return;
if (result.status === 'success') showSuccess(t('PayPal 充值成功'));
else if (result.status === 'pending')
showInfo(t('PayPal 支付处理中,请稍后查看充值记录'));
else if (result.status === 'cancelled') showInfo(t('已取消 PayPal 支付'));
else showError(t('PayPal 支付确认失败,请稍后重试'));
fetchOrgQuota();
setRefreshHistory((previous) => previous + 1);
window.history.replaceState(
{},
'',
removePayPalReturnState(window.location.href),
);
// The callback query must be consumed exactly once on page entry.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const selectPreset = (preset) => {
setSelectedPreset(preset.id);
setSelectedPresetObj(preset);
setIsCustomMode(false);
setCustomAmount(null);
};
const handleCustomAmountChange = (v) => {
setCustomAmount(v);
if (v && Number(v) > 0) {
setIsCustomMode(true);
setSelectedPreset(null);
setSelectedPresetObj(null);
} else {
setIsCustomMode(false);
}
};
const handleCustomUnitChange = (v) => {
setCustomUnit(v);
if (customAmount && Number(customAmount) > 0) {
setIsCustomMode(true);
setSelectedPreset(null);
setSelectedPresetObj(null);
}
};
// 自定义充值快速选择档位
const customQuickPicks = [
{ amount: 1, unit: 1000 },
{ amount: 5, unit: 1000 },
{ amount: 1, unit: 10000 },
{ amount: 5, unit: 10000 },
{ amount: 10, unit: 10000 },
];
const applyCustomQuickPick = (amount, unit) => {
setCustomAmount(amount);
setCustomUnit(unit);
setIsCustomMode(true);
setSelectedPreset(null);
setSelectedPresetObj(null);
};
// 自定义充值预览额度(与后端 service.CalculateQuota 一致:originalMoney * QuotaPerUnit + bonus,自定义 bonus=0)
const customPreviewQuota =
customEffectiveAmount > 0
? customEffectiveAmount * (getQuotaPerUnit() || 500000)
: 0;
const handlePreTopUp = async (paymentType) => {
if (isCustomMode) {
if (!customValid) {
showError(t('自定义充值金额最少为 1000 元'));
return;
}
} else if (!selectedPresetObj) {
showError(t('请先选择充值金额'));
return;
}
setPayWay(paymentType);
if (paymentType === 'paypal') {
if (!enablePayPalTopUp) {
showError(t('管理员未开启 PayPal 充值!'));
return;
}
setAmountLoading(true);
try {
const response = await API.post(
'/api/org/topup/paypal/amount',
buildPayBody(),
{ headers: orgHeaders },
);
if (!response.data.success) {
throw new Error(response.data.message || t('获取金额失败'));
}
setPayPalQuote(parsePayPalQuote(response));
} catch (error) {
showError(error?.message || t('获取金额失败'));
return;
} finally {
setAmountLoading(false);
}
}
setConfirmOpen(true);
};
const buildPayBody = () =>
isCustomMode
? { custom_amount: customEffectiveAmount }
: { amount_option_id: selectedPresetObj.id };
const isMobile = /iPhone|Android|iPad|Mobile/i.test(navigator.userAgent);
const handleConfirmPay = async () => {
if (!isCustomMode && !selectedPresetObj) return;
if (isCustomMode && !customValid) return;
setConfirmLoading(true);
try {
let res;
const payBody = buildPayBody();
if (payWay === 'wxpay' && enableWechatTopUp) {
const wechatEndpoint = isMobile
? '/api/org/topup/wechat/h5'
: '/api/org/topup/wechat/native';
res = await API.post(wechatEndpoint, payBody, { headers: orgHeaders });
if (res.data.success) {
if (isMobile) {
// H5:直接跳转微信支付页
window.location.href = res.data.data.h5_url;
setConfirmOpen(false);
const onFocus = () => {
fetchOrgQuota();
setRefreshHistory((p) => p + 1);
window.removeEventListener('focus', onFocus);
};
window.addEventListener('focus', onFocus);
} else {
// Native:弹出二维码
setWechatOrderData(res.data.data);
setConfirmOpen(false);
setWechatQRVisible(true);
}
return;
}
} else if (payWay === 'paypal' && enablePayPalTopUp) {
res = await requestPayPalOrder(
API,
'/api/org/topup/paypal',
{ ...payBody, quote_token: payPalQuote?.quoteToken },
{ headers: orgHeaders, skipErrorHandler: true },
);
if (res.data.success && res.data.data?.approval_url) {
setPayPalQuote(parsePayPalQuote(res));
window.location.href = res.data.data.approval_url;
return;
}
if (
res.status === 202 &&
res.data?.message === 'PAYPAL_ORDER_CREATING'
) {
showInfo(t('PayPal 订单创建中,请稍后重试'));
return;
}
} else if (payWay === 'alipay' && enableAlipayTopUp) {
const alipayEndpoint = isMobile
? '/api/org/topup/alipay/wap'
: '/api/org/topup/alipay/pc';
res = await API.post(alipayEndpoint, payBody, { headers: orgHeaders });
if (res.data.success) {
// Safari 会拦截 await 之后的 window.open(用户手势已过期),改为同标签跳转
const isSafari =
navigator.userAgent.indexOf('Safari') > -1 &&
navigator.userAgent.indexOf('Chrome') < 1;
if (isSafari) {
window.location.href = res.data.data.pay_url;
return;
}
window.open(res.data.data.pay_url, '_blank');
setConfirmOpen(false);
// 用户从支付宝标签页切回时自动刷新余额和记录
const onFocus = () => {
fetchOrgQuota();
setRefreshHistory((p) => p + 1);
window.removeEventListener('focus', onFocus);
};
window.addEventListener('focus', onFocus);
return;
}
}
// 失败处理
const msg = res?.data?.message || t('支付请求失败');
showError(msg);
} catch (e) {
const code = e?.response?.data?.message;
if (payWay === 'paypal' && code?.startsWith('PAYPAL_QUOTE_')) {
try {
const response = await API.post(
'/api/org/topup/paypal/amount',
buildPayBody(),
{ headers: orgHeaders },
);
if (!response.data.success) throw new Error(response.data.message);
setPayPalQuote(parsePayPalQuote(response));
showInfo(t('PayPal 报价已更新,请重新确认'));
} catch {
showError(t('获取金额失败'));
}
} else {
showError(e?.response?.data?.message || t('支付请求失败'));
}
} finally {
setConfirmLoading(false);
}
};
const handleWechatComplete = (success) => {
setWechatQRVisible(false);
setWechatOrderData(null);
if (success) {
showSuccess(t('充值成功!'));
fetchOrgQuota();
setRefreshHistory((p) => p + 1);
}
};
const renderAmount = () => {
if (payWay === 'paypal') {
return formatPayPalUSD(payPalQuote?.payAmount);
}
if (effectiveAmountYuan <= 0) return '';
const pay = effectiveAmountYuan * effectiveDiscount;
return `${pay.toFixed(2)} ${t('元')}`;
};
// 充值记录状态渲染
const renderStatus = (status) => {
const map = {
success: {
icon: ,
text: t('成功'),
},
pending: {
icon: ,
text: t('待支付'),
},
expired: { icon: , text: t('已过期') },
};
const s = map[status] || { icon: null, text: status };
return (
{s.icon}
{s.text}
);
};
const historyColumns = [
{
title: t('订单号'),
dataIndex: 'trade_no',
render: (v) => (
{v}
),
ellipsis: true,
},
{
title: t('金额'),
dataIndex: 'money',
render: (v) => ¥{Number(v).toFixed(2)},
width: 90,
},
{
title: t('获得额度'),
dataIndex: 'amount',
render: (v) => {renderQuota(v)},
width: 110,
},
{
title: t('支付方式'),
dataIndex: 'payment_channel',
render: (v) => (
{v === 'paypal_checkout' ? 'PayPal' : v || '-'}
),
width: 110,
},
{
title: t('状态'),
dataIndex: 'status',
render: (v) => renderStatus(v),
width: 90,
},
{
title: t('时间'),
dataIndex: 'create_time',
render: (v) => {timestamp2string(v)},
width: 160,
},
];
const hasAnyPayment =
enableWechatTopUp || enableAlipayTopUp || enablePayPalTopUp;
return (
{/* 签名时刻:余额展示区(本页唯一的品牌渐变区,渐变走 --brand-* token 随预设切换) */}
{t('企业可用余额')}
{renderQuota(orgQuota)}
{t('累计消耗')}
{renderQuota(orgUsedQuota)}
{/* 充值区域 */}
{infoLoading ? (
) : presetAmounts.length > 0 ? (
<>
{presetAmounts.map((preset, idx) => (
selectPreset(preset)}
topupInfo={{ amount_options: [], discount: {} }}
priceRatio={1}
t={t}
/>
))}
{/* 自定义充值(与档位互斥;自定义金额无折扣,原价到账) */}
{/* 头部 */}
{t('自定义充值')}
{isCustomMode && (
{t('已选')}
)}
{t('原价到账,不参与折扣')}
{/* 输入区 */}
{/* 快速选择 */}
{t('快速选择:')}
{customQuickPicks.map((pick) => {
const active =
isCustomMode &&
Number(customAmount) === pick.amount &&
customUnit === pick.unit;
const label = `${pick.amount}${pick.unit === 1000 ? t('千') : t('万')}`;
return (
);
})}
{/* 实时预览(仅在金额合法时显示) */}
{customEffectiveAmount > 0 && customValid && (
{t('实付金额')}
¥{customEffectiveAmount.toLocaleString()}
{t('获得额度')}
{renderQuota(customPreviewQuota)}
)}
{/* 底部说明(金额不达标时变橙色) */}
0 && !customValid
? '!text-amber-600 dark:!text-amber-400'
: '!text-gray-400 dark:!text-gray-500'
}`}
>
{customEffectiveAmount > 0 && !customValid
? t('当前 ¥{{amount}},未达到最低 ¥1,000', {
amount: customEffectiveAmount.toLocaleString(),
})
: t('最少 1000 元,必须为 1000 元的整倍数')}
{/* 支付方式 */}
{hasAnyPayment ? (
{payMethods.map((method) => {
const isWechat = method.type === 'wxpay';
const isAlipay = method.type === 'alipay';
const isPayPal = method.type === 'paypal';
const disabled =
(isWechat && !enableWechatTopUp) ||
(isAlipay && !enableAlipayTopUp) ||
(isPayPal && !enablePayPalTopUp);
return (
);
})}
) : (
{t('暂无可用的支付方式,请联系管理员配置')}
)}
>
) : (
{t('暂无充值档位,请联系管理员配置')}
)}
{/* 充值记录 */}
{t('暂无充值记录')}}
/>
{/* 支付确认弹窗 */}
setConfirmOpen(false)}
confirmLoading={confirmLoading}
topUpCount={effectiveAmountYuan}
renderQuotaWithAmount={() => {
if (payWay === 'paypal' && payPalQuote?.quota) {
return renderQuota(payPalQuote.quota);
}
if (effectiveAmountYuan <= 0) return renderQuota(0);
// 额度 = 原始金额 × QuotaPerUnit + 赠送额度(与后端 CalculateQuota 逻辑一致,折扣只影响实付金额,不影响获得的额度)
const quotaPerUnit = getQuotaPerUnit() || 500000;
const baseQuota = effectiveAmountYuan * quotaPerUnit;
return renderQuota(baseQuota + effectiveBonus);
}}
amountLoading={amountLoading}
renderAmount={renderAmount}
payWay={payWay}
payMethods={payMethods}
amountNumber={
payWay === 'paypal' ? 0 : effectiveAmountYuan * effectiveDiscount
}
discountRate={payWay === 'paypal' ? 1 : effectiveDiscount}
payPalQuote={payPalQuote}
/>
{/* 微信二维码弹窗 */}
{
const res = await API.get(
`/api/org/topup?p=1&page_size=1&keyword=${tradeNo}`,
{ headers: orgHeaders },
);
const items = res.data.data?.items || [];
return items.length > 0 ? items[0] : null;
}}
/>
);
};
export default OrgRecharge;