Initial import of weiyuan frontend

This commit is contained in:
qiubaishen
2026-10-15 16:33:46 +08:00
commit d8f3aee261
774 changed files with 374914 additions and 0 deletions
+229
View File
@@ -0,0 +1,229 @@
/*
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 from 'react';
import {
Avatar,
Typography,
Card,
Button,
Input,
Badge,
Space,
} from '@douyinfe/semi-ui';
import { Copy, Users, BarChart2, TrendingUp, Gift, Zap } from 'lucide-react';
const { Text } = Typography;
const InvitationCard = ({
t,
userState,
renderQuota,
setOpenTransfer,
affLink,
handleAffLinkClick,
}) => {
return (
<Card className='!rounded-2xl shadow-sm border-0'>
{/* 卡片头部 */}
<div className='flex items-center mb-4'>
<Avatar size='small' color='green' className='mr-3 shadow-md'>
<Gift size={16} />
</Avatar>
<div>
<Typography.Text className='text-lg font-medium'>
{t('邀请奖励')}
</Typography.Text>
<div className='text-xs'>{t('邀请好友获得额外奖励')}</div>
</div>
</div>
{/* 收益展示区域 */}
<Space vertical style={{ width: '100%' }}>
{/* 统计数据统一卡片 */}
<Card
className='!rounded-xl w-full'
cover={
<div
className='relative h-30'
style={{
'--palette-primary-darkerChannel': '0 75 80',
backgroundImage: `linear-gradient(0deg, rgba(var(--palette-primary-darkerChannel) / 80%), rgba(var(--palette-primary-darkerChannel) / 80%)), url('/cover-4.webp')`,
backgroundSize: 'cover',
backgroundPosition: 'center',
backgroundRepeat: 'no-repeat',
}}
>
{/* 标题和按钮 */}
<div className='relative z-10 h-full flex flex-col justify-between p-4'>
<div className='flex justify-between items-center'>
<Text strong style={{ color: 'white', fontSize: '16px' }}>
{t('收益统计')}
</Text>
<Button
type='primary'
theme='solid'
size='small'
disabled={
!userState?.user?.aff_quota ||
userState?.user?.aff_quota <= 0
}
onClick={() => setOpenTransfer(true)}
className='!rounded-lg'
>
<Zap size={12} className='mr-1' />
{t('划转到余额')}
</Button>
</div>
{/* 统计数据 */}
<div className='grid grid-cols-3 gap-6 mt-4'>
{/* 待使用收益 */}
<div className='text-center'>
<div
className='text-base sm:text-2xl font-bold mb-2'
style={{ color: 'white' }}
>
{renderQuota(userState?.user?.aff_quota || 0)}
</div>
<div className='flex items-center justify-center text-sm'>
<TrendingUp
size={14}
className='mr-1'
style={{ color: 'rgba(255,255,255,0.8)' }}
/>
<Text
style={{
color: 'rgba(255,255,255,0.8)',
fontSize: '12px',
}}
>
{t('待使用收益')}
</Text>
</div>
</div>
{/* 总收益 */}
<div className='text-center'>
<div
className='text-base sm:text-2xl font-bold mb-2'
style={{ color: 'white' }}
>
{renderQuota(userState?.user?.aff_history_quota || 0)}
</div>
<div className='flex items-center justify-center text-sm'>
<BarChart2
size={14}
className='mr-1'
style={{ color: 'rgba(255,255,255,0.8)' }}
/>
<Text
style={{
color: 'rgba(255,255,255,0.8)',
fontSize: '12px',
}}
>
{t('总收益')}
</Text>
</div>
</div>
{/* 邀请人数 */}
<div className='text-center'>
<div
className='text-base sm:text-2xl font-bold mb-2'
style={{ color: 'white' }}
>
{userState?.user?.aff_count || 0}
</div>
<div className='flex items-center justify-center text-sm'>
<Users
size={14}
className='mr-1'
style={{ color: 'rgba(255,255,255,0.8)' }}
/>
<Text
style={{
color: 'rgba(255,255,255,0.8)',
fontSize: '12px',
}}
>
{t('邀请人数')}
</Text>
</div>
</div>
</div>
</div>
</div>
}
>
{/* 邀请链接部分 */}
<Input
value={affLink}
readonly
className='!rounded-lg'
prefix={t('邀请链接')}
suffix={
<Button
type='primary'
theme='solid'
onClick={handleAffLinkClick}
icon={<Copy size={14} />}
className='!rounded-lg'
>
{t('复制')}
</Button>
}
/>
</Card>
{/* 奖励说明 */}
<Card
className='!rounded-xl w-full'
title={<Text type='tertiary'>{t('奖励说明')}</Text>}
>
<div className='space-y-3'>
<div className='flex items-start gap-2'>
<Badge dot type='success' />
<Text type='tertiary' className='text-sm'>
{t('邀请好友注册,好友充值后您可获得相应奖励')}
</Text>
</div>
<div className='flex items-start gap-2'>
<Badge dot type='success' />
<Text type='tertiary' className='text-sm'>
{t('通过划转功能将奖励额度转入到您的账户余额中')}
</Text>
</div>
<div className='flex items-start gap-2'>
<Badge dot type='success' />
<Text type='tertiary' className='text-sm'>
{t('邀请的好友越多,获得的奖励越多')}
</Text>
</div>
</div>
</Card>
</Space>
</Card>
);
};
export default InvitationCard;
+524
View File
@@ -0,0 +1,524 @@
/*
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, { useRef } from 'react';
import {
Typography,
Card,
Button,
Banner,
Form,
Space,
Spin,
Tooltip,
} from '@douyinfe/semi-ui';
import {
CreditCard,
Coins,
Wallet,
Receipt,
} from 'lucide-react';
import {
AlipayBrandIcon,
WechatBrandIcon,
StripeBrandIcon,
} from '../common/icons/BrandIcons';
import { IconGift } from '@douyinfe/semi-icons';
import { useMinimumLoadingTime } from '../../hooks/common/useMinimumLoadingTime';
import { getCurrencyConfig } from '../../helpers/render';
const { Text } = Typography;
const RechargeCard = ({
t,
enableOnlineTopUp,
enableStripeTopUp,
enableCreemTopUp,
creemProducts,
creemPreTopUp,
presetAmounts,
selectedPreset,
selectPresetAmount,
formatLargeNumber,
priceRatio,
topUpCount,
minTopUp,
renderQuotaWithAmount,
getAmount,
setTopUpCount,
setSelectedPreset,
renderAmount,
amountLoading,
payMethods,
preTopUp,
paymentLoading,
payWay,
redemptionCode,
setRedemptionCode,
topUp,
isSubmitting,
topUpLink,
openTopUpLink,
userState,
renderQuota,
statusLoading,
topupInfo,
onOpenHistory,
}) => {
const onlineFormApiRef = useRef(null);
const redeemFormApiRef = useRef(null);
const _showAmountSkeleton = useMinimumLoadingTime(amountLoading);
console.log(
' enabled screem ?',
enableCreemTopUp,
' products ?',
creemProducts,
);
return (
<Card className='!rounded-2xl shadow-lg border-0 bg-white/50 backdrop-blur-sm dark:bg-zinc-800/50 transition-all duration-300 hover:shadow-xl'>
{/* 卡片头部 */}
<div className='flex items-center justify-between mb-6 pb-4 border-b border-gray-100 dark:border-gray-700'>
<div className='flex items-center gap-4'>
<div className='p-3 bg-gradient-to-br from-blue-500 to-brand-to rounded-xl shadow-lg shadow-blue-500/30 text-white'>
<CreditCard size={24} />
</div>
<div>
<Typography.Text className='text-xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-gray-900 to-gray-600 dark:from-white dark:to-gray-300'>
{t('账户充值')}
</Typography.Text>
<div className='text-sm text-gray-500 dark:text-gray-400 mt-1'>
{t('多种充值方式,安全便捷')}
</div>
</div>
</div>
<Button
icon={<Receipt size={18} />}
theme='solid'
type='secondary'
className='!rounded-xl !px-4 hover:scale-105 transition-transform'
onClick={onOpenHistory}
>
{t('账单')}
</Button>
</div>
<Space vertical style={{ width: '100%' }} spacing='loose'>
{/* 统计数据 */}
<div className='relative overflow-hidden rounded-2xl bg-gradient-to-r from-blue-600 to-brand-to shadow-xl shadow-blue-500/20'>
<div className='absolute top-0 right-0 w-64 h-64 bg-white/10 rounded-full -mr-16 -mt-16 blur-3xl'></div>
<div className='absolute bottom-0 left-0 w-48 h-48 bg-black/10 rounded-full -ml-12 -mb-12 blur-2xl'></div>
<div className='relative z-10 p-6'>
<div className='flex justify-between items-center mb-6'>
<div className='flex items-center gap-2'>
<div className='p-1.5 bg-white/20 rounded-lg backdrop-blur-md'>
<Wallet size={16} className='text-white' />
</div>
<span className='text-blue-100 font-medium'>
{t('账户概览')}
</span>
</div>
</div>
<div className='grid grid-cols-3 gap-8'>
<div className='text-center relative group'>
<div className='text-3xl font-bold text-white mb-2 tracking-tight group-hover:scale-110 transition-transform duration-300'>
{renderQuota(userState?.user?.quota)}
</div>
<div className='text-blue-100/80 text-sm font-medium'>
{t('当前余额')}
</div>
<div className='absolute right-0 top-1/2 -translate-y-1/2 w-px h-8 bg-gradient-to-b from-transparent via-white/20 to-transparent'></div>
</div>
<div className='text-center relative group'>
<div className='text-3xl font-bold text-white mb-2 tracking-tight group-hover:scale-110 transition-transform duration-300'>
{renderQuota(userState?.user?.used_quota)}
</div>
<div className='text-blue-100/80 text-sm font-medium'>
{t('历史消耗')}
</div>
<div className='absolute right-0 top-1/2 -translate-y-1/2 w-px h-8 bg-gradient-to-b from-transparent via-white/20 to-transparent'></div>
</div>
<div className='text-center group'>
<div className='text-3xl font-bold text-white mb-2 tracking-tight group-hover:scale-110 transition-transform duration-300'>
{userState?.user?.request_count || 0}
</div>
<div className='text-blue-100/80 text-sm font-medium'>
{t('请求次数')}
</div>
</div>
</div>
</div>
</div>
{/* 在线充值表单 */}
{statusLoading ? (
<div className='py-12 flex justify-center'>
<Spin size='large' />
</div>
) : enableOnlineTopUp ||
enableStripeTopUp ||
enableCreemTopUp ||
(payMethods && payMethods.length > 0) ? (
<div className='bg-gray-50/50 dark:bg-gray-800/50 rounded-2xl p-6 border border-gray-100 dark:border-gray-700'>
<Form
getFormApi={(api) => (onlineFormApiRef.current = api)}
initValues={{ topUpCount: topUpCount }}
>
<div className='space-y-8'>
{/* 自定义金额输入区域 - 已隐藏,不允许用户自己输入金额 */}
{(enableOnlineTopUp ||
enableStripeTopUp ||
(payMethods && payMethods.length > 0)) && (
<div className='grid grid-cols-1 lg:grid-cols-12 gap-8'>
<div className='lg:col-span-12'>
<Form.Slot
label={
<span className='text-base font-semibold text-gray-700 dark:text-gray-200'>
{t('支付方式')}
</span>
}
>
{payMethods && payMethods.length > 0 ? (
<div className='grid grid-cols-2 sm:grid-cols-3 gap-3'>
{payMethods.map((payMethod) => {
const minTopupVal =
Number(payMethod.min_topup) || 0;
const isStripe = payMethod.type === 'stripe';
const disabled =
(!enableOnlineTopUp && !isStripe) ||
(!enableStripeTopUp && isStripe) ||
minTopupVal > Number(topUpCount || 0);
const buttonContent = (
<div
className={`flex flex-col items-center justify-center p-3 h-full gap-2 transition-all duration-200 ${disabled ? 'opacity-50' : 'group-hover:scale-105'}`}
>
{payMethod.type === 'alipay' ? (
<AlipayBrandIcon
size={28}
color='#1677FF'
/>
) : payMethod.type === 'wxpay' ? (
<WechatBrandIcon
size={28}
color='#07C160'
/>
) : payMethod.type === 'stripe' ? (
<StripeBrandIcon
size={28}
color='#635BFF'
/>
) : (
<CreditCard
size={28}
color={
payMethod.color ||
'var(--semi-color-text-2)'
}
/>
)}
<span className='font-medium text-sm'>
{payMethod.name}
</span>
</div>
);
const containerClass = `h-24 rounded-xl border-2 cursor-pointer transition-all duration-200 ${
payWay === payMethod.type
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20 shadow-md ring-2 ring-blue-200 dark:ring-blue-800'
: 'border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 hover:border-blue-300 dark:hover:border-blue-600 hover:shadow-md'
} ${disabled ? 'cursor-not-allowed grayscale' : 'group'}`;
const buttonEl = (
<div
key={payMethod.type}
className={containerClass}
onClick={() =>
!disabled && preTopUp(payMethod.type)
}
>
{buttonContent}
</div>
);
return disabled &&
minTopupVal > Number(topUpCount || 0) ? (
<Tooltip
content={t('最低充值') + ' ' + minTopupVal}
key={payMethod.type}
>
{buttonEl}
</Tooltip>
) : (
<React.Fragment key={payMethod.type}>
{buttonEl}
</React.Fragment>
);
})}
</div>
) : (
<div className='text-gray-500 text-sm p-4 bg-gray-100 rounded-xl border border-dashed border-gray-300 text-center'>
{t('暂无可用的支付方式')}
</div>
)}
</Form.Slot>
</div>
</div>
)}
{(enableOnlineTopUp ||
enableStripeTopUp ||
(payMethods && payMethods.length > 0)) && (
<Form.Slot
label={
<div className='flex items-center gap-2 mb-2'>
<span className='text-base font-semibold text-gray-700 dark:text-gray-200'>
{t('快捷选择')}
</span>
{(() => {
const { symbol, rate, type } = getCurrencyConfig();
if (type === 'USD') return null;
return (
<span className='text-xs font-normal px-2 py-0.5 bg-gray-100 dark:bg-gray-700 rounded-full text-gray-500'>
1 $ ≈ {rate.toFixed(2)} {symbol}
</span>
);
})()}
</div>
}
>
<div className='grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4'>
{presetAmounts.map((preset, index) => {
const discount =
preset.discount ||
topupInfo?.discount?.[preset.value] ||
1.0;
const originalPrice = preset.value * priceRatio;
const discountedPrice = originalPrice * discount;
const hasDiscount = discount < 1.0;
const actualPay = discountedPrice;
const save = originalPrice - discountedPrice;
const { symbol, rate, type } = getCurrencyConfig();
const statusStr = localStorage.getItem('status');
let usdRate = 1;
try {
if (statusStr) {
const s = JSON.parse(statusStr);
// 注意:如果设置了汇率值(包括1),使用设置值;只有未设置(undefined/null)时才用默认值1
usdRate =
s?.usd_exchange_rate !== undefined &&
s?.usd_exchange_rate !== null
? s.usd_exchange_rate
: 1;
}
} catch (e) {}
let displayValue = preset.value;
let displayActualPay = actualPay;
let displaySave = save;
if (type === 'USD') {
displayActualPay = actualPay / usdRate;
displaySave = save / usdRate;
} else if (type === 'CNY') {
displayValue = preset.value * usdRate;
} else if (type === 'CUSTOM') {
displayValue = preset.value * rate;
displayActualPay = (actualPay / usdRate) * rate;
displaySave = (save / usdRate) * rate;
}
const isSelected = selectedPreset === preset.value;
return (
<div
key={index}
className={`relative cursor-pointer rounded-xl p-4 transition-all duration-200 border-2 overflow-hidden group ${
isSelected
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20 shadow-md transform scale-105'
: 'border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 hover:border-blue-300 hover:shadow-lg'
}`}
onClick={() => {
selectPresetAmount(preset);
onlineFormApiRef.current?.setValue(
'topUpCount',
preset.value,
);
}}
>
{hasDiscount && (
<div className='absolute -right-8 top-3 rotate-45 bg-red-500 text-white text-xs py-0.5 px-8 font-bold shadow-sm'>
{t('优惠')}
</div>
)}
<div className='flex flex-col items-center justify-center text-center'>
<div
className={`text-xl font-bold mb-1 flex items-center gap-1 ${isSelected ? 'text-blue-600 dark:text-blue-400' : 'text-gray-700 dark:text-gray-200'}`}
>
<Coins
size={18}
className={
isSelected
? 'text-blue-500'
: 'text-gray-400'
}
/>
{formatLargeNumber(displayValue)}{' '}
<span className='text-sm font-normal'>
{symbol}
</span>
</div>
{hasDiscount && (
<div className='text-xs font-semibold px-2 py-0.5 bg-green-100 text-green-700 rounded-full mb-2'>
{t('省')} {symbol}
{displaySave.toFixed(0)}
</div>
)}
<div className='text-sm text-gray-500'>
{t('实付')}{' '}
<span
className={`font-bold ${isSelected ? 'text-blue-600' : 'text-gray-900 dark:text-gray-100'}`}
>
{symbol}
{displayActualPay.toFixed(2)}
</span>
</div>
</div>
</div>
);
})}
</div>
</Form.Slot>
)}
{/* Creem 充值区域 */}
{enableCreemTopUp && creemProducts.length > 0 && (
<Form.Slot
label={
<span className='text-base font-semibold text-gray-700 dark:text-gray-200'>
Creem {t('套餐')}
</span>
}
>
<div className='grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4'>
{creemProducts.map((product, index) => (
<div
key={index}
onClick={() => creemPreTopUp(product)}
className='cursor-pointer rounded-xl border-2 border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-5 hover:border-blue-400 hover:shadow-lg transition-all duration-300 group'
>
<div className='font-bold text-lg mb-2 text-gray-800 dark:text-gray-200 group-hover:text-blue-600 transition-colors'>
{product.name}
</div>
<div className='flex justify-between items-end'>
<div className='text-sm text-gray-500'>
{t('额度')}:{' '}
<span className='font-medium text-gray-700 dark:text-gray-300'>
{product.quota}
</span>
</div>
<div className='text-xl font-bold text-blue-600'>
{product.currency === 'EUR' ? '€' : '¥'}
{product.price}
</div>
</div>
</div>
))}
</div>
</Form.Slot>
)}
</div>
</Form>
</div>
) : (
<Banner
type='info'
description={t(
'管理员未开启在线充值功能,请联系管理员开启或使用兑换码充值。',
)}
className='!rounded-xl border-blue-100 bg-blue-50'
closeIcon={null}
/>
)}
{/* 兑换码充值 */}
<div className='bg-white dark:bg-zinc-800 rounded-2xl p-6 border border-dashed border-gray-300 dark:border-gray-600'>
<div className='flex items-center gap-2 mb-4'>
<div className='p-2 bg-brand/10 dark:bg-brand-deep/30 rounded-lg text-brand-deep dark:text-brand-from'>
<IconGift size='large' />
</div>
<span className='font-bold text-gray-700 dark:text-gray-200'>
{t('兑换码充值')}
</span>
</div>
<Form
getFormApi={(api) => (redeemFormApiRef.current = api)}
initValues={{ redemptionCode: redemptionCode }}
className='flex flex-col sm:flex-row gap-4'
>
<div className='flex-1'>
<Form.Input
field='redemptionCode'
noLabel={true}
placeholder={t('请输入您的兑换码')}
value={redemptionCode}
onChange={(value) => setRedemptionCode(value)}
className='w-full'
size='large'
showClear
/>
</div>
<Button
theme='solid'
type='primary'
onClick={topUp}
loading={isSubmitting}
size='large'
className='!rounded-lg !px-8 !font-semibold bg-gradient-to-r from-brand-from to-brand-to hover:from-brand-from hover:to-brand-to border-none'
>
{t('立即兑换')}
</Button>
</Form>
{topUpLink && (
<div className='mt-3 text-right'>
<Text type='tertiary' className='text-sm'>
{t('没有兑换码?')}
<span
className='text-blue-600 hover:text-blue-700 cursor-pointer font-medium ml-1 transition-colors'
onClick={openTopUpLink}
>
{t('去购买')} &rarr;
</span>
</Text>
</div>
)}
</div>
</Space>
</Card>
);
};
export default RechargeCard;
+729
View File
@@ -0,0 +1,729 @@
/*
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, useContext, useRef } from 'react';
import {
API,
showError,
showInfo,
showSuccess,
renderQuota,
renderQuotaWithAmount,
copy,
getQuotaPerUnit,
} from '../../helpers';
import { Modal, Toast } from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import { UserContext } from '../../context/User';
import { StatusContext } from '../../context/Status';
import RechargeCard from './RechargeCard';
import InvitationCard from './InvitationCard';
import TransferModal from './modals/TransferModal';
import PaymentConfirmModal from './modals/PaymentConfirmModal';
import TopupHistoryModal from './modals/TopupHistoryModal';
const TopUp = () => {
const { t } = useTranslation();
const [userState, userDispatch] = useContext(UserContext);
const [statusState] = useContext(StatusContext);
const [redemptionCode, setRedemptionCode] = useState('');
const [amount, setAmount] = useState(0.0);
const [minTopUp, setMinTopUp] = useState(statusState?.status?.min_topup || 1);
const [topUpCount, setTopUpCount] = useState(
statusState?.status?.min_topup || 1,
);
const [topUpLink, setTopUpLink] = useState(
statusState?.status?.top_up_link || '',
);
const [enableOnlineTopUp, setEnableOnlineTopUp] = useState(
statusState?.status?.enable_online_topup || false,
);
const [priceRatio, setPriceRatio] = useState(statusState?.status?.price || 1);
const [enableStripeTopUp, setEnableStripeTopUp] = useState(
statusState?.status?.enable_stripe_topup || false,
);
const [statusLoading, setStatusLoading] = useState(true);
// Creem 相关状态
const [creemProducts, setCreemProducts] = useState([]);
const [enableCreemTopUp, setEnableCreemTopUp] = useState(false);
const [creemOpen, setCreemOpen] = useState(false);
const [selectedCreemProduct, setSelectedCreemProduct] = useState(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const [open, setOpen] = useState(false);
const [payWay, setPayWay] = useState('');
const [amountLoading, setAmountLoading] = useState(false);
const [paymentLoading, setPaymentLoading] = useState(false);
const [confirmLoading, setConfirmLoading] = useState(false);
const [payMethods, setPayMethods] = useState([]);
const affFetchedRef = useRef(false);
// 邀请相关状态
const [affLink, setAffLink] = useState('');
const [openTransfer, setOpenTransfer] = useState(false);
const [transferAmount, setTransferAmount] = useState(0);
// 账单Modal状态
const [openHistory, setOpenHistory] = useState(false);
// 预设充值额度选项
const [presetAmounts, setPresetAmounts] = useState([]);
const [selectedPreset, setSelectedPreset] = useState(null);
// 充值配置信息
const [topupInfo, setTopupInfo] = useState({
amount_options: [],
discount: {},
});
const topUp = async () => {
if (redemptionCode === '') {
showInfo(t('请输入兑换码!'));
return;
}
setIsSubmitting(true);
try {
const res = await API.post('/api/user/topup', {
key: redemptionCode,
});
const { success, message, data } = res.data;
if (success) {
showSuccess(t('兑换成功!'));
Modal.success({
title: t('兑换成功!'),
content: t('成功兑换额度:') + renderQuota(data),
centered: true,
});
if (userState.user) {
const updatedUser = {
...userState.user,
quota: userState.user.quota + data,
};
userDispatch({ type: 'login', payload: updatedUser });
}
setRedemptionCode('');
} else {
showError(message);
}
} catch (err) {
showError(t('请求失败'));
} finally {
setIsSubmitting(false);
}
};
const openTopUpLink = () => {
if (!topUpLink) {
showError(t('超级管理员未设置充值链接!'));
return;
}
window.open(topUpLink, '_blank');
};
const preTopUp = async (payment) => {
// 必须先选择充值档位
if (selectedPreset === null) {
showError(t('请先选择充值金额'));
return;
}
if (payment === 'stripe') {
if (!enableStripeTopUp) {
showError(t('管理员未开启Stripe充值!'));
return;
}
} else {
if (!enableOnlineTopUp) {
showError(t('管理员未开启在线充值!'));
return;
}
}
setPayWay(payment);
setPaymentLoading(true);
try {
if (payment === 'stripe') {
await getStripeAmount();
} else {
await getAmount();
}
if (topUpCount < minTopUp) {
showError(t('充值数量不能小于') + minTopUp);
return;
}
setOpen(true);
} catch (error) {
showError(t('获取金额失败'));
} finally {
setPaymentLoading(false);
}
};
const onlineTopUp = async () => {
if (payWay === 'stripe') {
// Stripe 支付处理
if (amount === 0) {
await getStripeAmount();
}
} else {
// 普通支付处理
if (amount === 0) {
await getAmount();
}
}
if (topUpCount < minTopUp) {
showError('充值数量不能小于' + minTopUp);
return;
}
setConfirmLoading(true);
try {
let res;
if (payWay === 'stripe') {
// Stripe 支付请求
res = await API.post('/api/user/stripe/pay', {
amount: parseInt(topUpCount),
payment_method: 'stripe',
});
} else {
// 普通支付请求
res = await API.post('/api/user/pay', {
amount: parseInt(topUpCount),
payment_method: payWay,
});
}
if (res !== undefined) {
const { message, data } = res.data;
if (message === 'success') {
if (payWay === 'stripe') {
// Stripe 支付回调处理
window.open(data.pay_link, '_blank');
} else {
// 普通支付表单提交
let params = data;
let url = res.data.url;
let form = document.createElement('form');
form.action = url;
form.method = 'POST';
let isSafari =
navigator.userAgent.indexOf('Safari') > -1 &&
navigator.userAgent.indexOf('Chrome') < 1;
if (!isSafari) {
form.target = '_blank';
}
for (let key in params) {
let input = document.createElement('input');
input.type = 'hidden';
input.name = key;
input.value = params[key];
form.appendChild(input);
}
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
} else {
showError(data);
}
} else {
showError(res);
}
} catch (err) {
console.log(err);
showError(t('支付请求失败'));
} finally {
setOpen(false);
setConfirmLoading(false);
}
};
const creemPreTopUp = async (product) => {
if (!enableCreemTopUp) {
showError(t('管理员未开启 Creem 充值!'));
return;
}
setSelectedCreemProduct(product);
setCreemOpen(true);
};
const onlineCreemTopUp = async () => {
if (!selectedCreemProduct) {
showError(t('请选择产品'));
return;
}
// Validate product has required fields
if (!selectedCreemProduct.productId) {
showError(t('产品配置错误,请联系管理员'));
return;
}
setConfirmLoading(true);
try {
const res = await API.post('/api/user/creem/pay', {
product_id: selectedCreemProduct.productId,
payment_method: 'creem',
});
if (res !== undefined) {
const { message, data } = res.data;
if (message === 'success') {
processCreemCallback(data);
} else {
showError(data);
}
} else {
showError(res);
}
} catch (err) {
console.log(err);
showError(t('支付请求失败'));
} finally {
setCreemOpen(false);
setConfirmLoading(false);
}
};
const processCreemCallback = (data) => {
// 与 Stripe 保持一致的实现方式
window.open(data.checkout_url, '_blank');
};
const getUserQuota = async () => {
let res = await API.get(`/api/user/self`);
const { success, message, data } = res.data;
if (success) {
userDispatch({ type: 'login', payload: data });
} else {
showError(message);
}
};
// 获取充值配置信息
const getTopupInfo = async () => {
try {
const res = await API.get('/api/user/topup/info');
const { data, success } = res.data;
if (success) {
setTopupInfo({
amount_options: data.amount_options || [],
discount: data.discount || {},
});
// 处理支付方式
let payMethods = data.pay_methods || [];
try {
if (typeof payMethods === 'string') {
payMethods = JSON.parse(payMethods);
}
if (payMethods && payMethods.length > 0) {
// 检查name和type是否为空
payMethods = payMethods.filter((method) => {
return method.name && method.type;
});
// 如果没有color,则设置默认颜色
payMethods = payMethods.map((method) => {
// 规范化最小充值数
const normalizedMinTopup = Number(method.min_topup);
method.min_topup = Number.isFinite(normalizedMinTopup)
? normalizedMinTopup
: 0;
// Stripe 的最小充值从后端字段回填
if (
method.type === 'stripe' &&
(!method.min_topup || method.min_topup <= 0)
) {
const stripeMin = Number(data.stripe_min_topup);
if (Number.isFinite(stripeMin)) {
method.min_topup = stripeMin;
}
}
if (!method.color) {
if (method.type === 'alipay') {
method.color = 'rgba(var(--semi-blue-5), 1)';
} else if (method.type === 'wxpay') {
method.color = 'rgba(var(--semi-green-5), 1)';
} else if (method.type === 'stripe') {
method.color = 'rgba(var(--semi-purple-5), 1)';
} else {
method.color = 'rgba(var(--semi-primary-5), 1)';
}
}
return method;
});
} else {
payMethods = [];
}
// 如果启用了 Stripe 支付,添加到支付方法列表
// 这个逻辑现在由后端处理,如果 Stripe 启用,后端会在 pay_methods 中包含它
setPayMethods(payMethods);
const enableStripeTopUp = data.enable_stripe_topup || false;
const enableOnlineTopUp = data.enable_online_topup || false;
const enableCreemTopUp = data.enable_creem_topup || false;
const minTopUpValue = enableOnlineTopUp
? data.min_topup
: enableStripeTopUp
? data.stripe_min_topup
: 1;
setEnableOnlineTopUp(enableOnlineTopUp);
setEnableStripeTopUp(enableStripeTopUp);
setEnableCreemTopUp(enableCreemTopUp);
setMinTopUp(minTopUpValue);
setTopUpCount(minTopUpValue);
// 设置 Creem 产品
try {
console.log(' data is ?', data);
console.log(' creem products is ?', data.creem_products);
const products = JSON.parse(data.creem_products || '[]');
setCreemProducts(products);
} catch (e) {
setCreemProducts([]);
}
// 如果没有自定义充值数量选项,根据最小充值金额生成预设充值额度选项
if (topupInfo.amount_options.length === 0) {
setPresetAmounts(generatePresetAmounts(minTopUpValue));
}
} catch (e) {
console.log('解析支付方式失败:', e);
setPayMethods([]);
}
// 如果有自定义充值数量选项,使用它们替换默认的预设选项
if (data.amount_options && data.amount_options.length > 0) {
const customPresets = data.amount_options.map((amount) => ({
value: amount,
discount: data.discount[amount] || 1.0,
}));
setPresetAmounts(customPresets);
}
} else {
console.error('获取充值配置失败:', data);
}
} catch (error) {
console.error('获取充值配置异常:', error);
}
};
// 获取邀请链接
const getAffLink = async () => {
const res = await API.get('/api/user/aff');
const { success, message, data } = res.data;
if (success) {
let link = `${window.location.origin}/register?aff=${data}`;
setAffLink(link);
} else {
showError(message);
}
};
// 划转邀请额度
const transfer = async () => {
if (transferAmount < getQuotaPerUnit()) {
showError(t('划转金额最低为') + ' ' + renderQuota(getQuotaPerUnit()));
return;
}
const res = await API.post(`/api/user/aff_transfer`, {
quota: transferAmount,
});
const { success, message } = res.data;
if (success) {
showSuccess(message);
setOpenTransfer(false);
getUserQuota().then();
} else {
showError(message);
}
};
// 复制邀请链接
const handleAffLinkClick = async () => {
await copy(affLink);
showSuccess(t('邀请链接已复制到剪切板'));
};
useEffect(() => {
if (!userState?.user?.id) {
getUserQuota().then();
}
setTransferAmount(getQuotaPerUnit());
}, []);
useEffect(() => {
if (affFetchedRef.current) return;
affFetchedRef.current = true;
getAffLink().then();
}, []);
// 在 statusState 可用时获取充值信息
useEffect(() => {
getTopupInfo().then();
}, []);
useEffect(() => {
if (statusState?.status) {
// const minTopUpValue = statusState.status.min_topup || 1;
// setMinTopUp(minTopUpValue);
// setTopUpCount(minTopUpValue);
setTopUpLink(statusState.status.top_up_link || '');
setPriceRatio(statusState.status.price || 1);
setStatusLoading(false);
}
}, [statusState?.status]);
const renderAmount = () => {
return amount + ' ' + t('元');
};
const getAmount = async (value) => {
if (value === undefined) {
value = topUpCount;
}
setAmountLoading(true);
try {
const res = await API.post('/api/user/amount', {
amount: parseFloat(value),
});
if (res !== undefined) {
const { message, data } = res.data;
if (message === 'success') {
setAmount(parseFloat(data));
} else {
setAmount(0);
Toast.error({ content: '错误:' + data, id: 'getAmount' });
}
} else {
showError(res);
}
} catch (err) {
console.log(err);
}
setAmountLoading(false);
};
const getStripeAmount = async (value) => {
if (value === undefined) {
value = topUpCount;
}
setAmountLoading(true);
try {
const res = await API.post('/api/user/stripe/amount', {
amount: parseFloat(value),
});
if (res !== undefined) {
const { message, data } = res.data;
if (message === 'success') {
setAmount(parseFloat(data));
} else {
setAmount(0);
Toast.error({ content: '错误:' + data, id: 'getAmount' });
}
} else {
showError(res);
}
} catch (err) {
console.log(err);
} finally {
setAmountLoading(false);
}
};
const handleCancel = () => {
setOpen(false);
};
const handleTransferCancel = () => {
setOpenTransfer(false);
};
const handleOpenHistory = () => {
setOpenHistory(true);
};
const handleHistoryCancel = () => {
setOpenHistory(false);
};
const handleCreemCancel = () => {
setCreemOpen(false);
setSelectedCreemProduct(null);
};
// 选择预设充值额度
const selectPresetAmount = (preset) => {
setTopUpCount(preset.value);
setSelectedPreset(preset.value);
// 计算实际支付金额,考虑折扣
const discount = preset.discount || topupInfo.discount[preset.value] || 1.0;
const discountedAmount = preset.value * priceRatio * discount;
setAmount(discountedAmount);
};
// 格式化大数字显示
const formatLargeNumber = (num) => {
return num.toString();
};
// 根据最小充值金额生成预设充值额度选项
const generatePresetAmounts = (minAmount) => {
const multipliers = [1, 5, 10, 30, 50, 100, 300, 500];
return multipliers.map((multiplier) => ({
value: minAmount * multiplier,
}));
};
return (
<div className='w-full max-w-7xl mx-auto relative min-h-screen lg:min-h-0 mt-[60px] px-2'>
{/* 划转模态框 */}
<TransferModal
t={t}
openTransfer={openTransfer}
transfer={transfer}
handleTransferCancel={handleTransferCancel}
userState={userState}
renderQuota={renderQuota}
getQuotaPerUnit={getQuotaPerUnit}
transferAmount={transferAmount}
setTransferAmount={setTransferAmount}
/>
{/* 充值确认模态框 */}
<PaymentConfirmModal
t={t}
open={open}
onlineTopUp={onlineTopUp}
handleCancel={handleCancel}
confirmLoading={confirmLoading}
topUpCount={topUpCount}
renderQuotaWithAmount={renderQuotaWithAmount}
amountLoading={amountLoading}
renderAmount={renderAmount}
payWay={payWay}
payMethods={payMethods}
amountNumber={amount}
discountRate={topupInfo?.discount?.[topUpCount] || 1.0}
/>
{/* 充值账单模态框 */}
<TopupHistoryModal
visible={openHistory}
onCancel={handleHistoryCancel}
t={t}
/>
{/* Creem 充值确认模态框 */}
<Modal
title={t('确定要充值 $')}
visible={creemOpen}
onOk={onlineCreemTopUp}
onCancel={handleCreemCancel}
maskClosable={false}
size='small'
centered
confirmLoading={confirmLoading}
>
{selectedCreemProduct && (
<>
<p>
{t('产品名称')}:{selectedCreemProduct.name}
</p>
<p>
{t('价格')}:{selectedCreemProduct.currency === 'EUR' ? '€' : '¥'}
{selectedCreemProduct.price}
</p>
<p>
{t('充值额度')}:{selectedCreemProduct.quota}
</p>
<p>{t('是否确认充值?')}</p>
</>
)}
</Modal>
{/* 用户信息头部 */}
<div className='space-y-6'>
<div className='grid grid-cols-1 lg:grid-cols-12 gap-6'>
{/* 左侧充值区域 */}
<div className='lg:col-span-7 space-y-6 w-full'>
<RechargeCard
t={t}
enableOnlineTopUp={enableOnlineTopUp}
enableStripeTopUp={enableStripeTopUp}
enableCreemTopUp={enableCreemTopUp}
creemProducts={creemProducts}
creemPreTopUp={creemPreTopUp}
presetAmounts={presetAmounts}
selectedPreset={selectedPreset}
selectPresetAmount={selectPresetAmount}
formatLargeNumber={formatLargeNumber}
priceRatio={priceRatio}
topUpCount={topUpCount}
minTopUp={minTopUp}
renderQuotaWithAmount={renderQuotaWithAmount}
getAmount={getAmount}
setTopUpCount={setTopUpCount}
setSelectedPreset={setSelectedPreset}
renderAmount={renderAmount}
amountLoading={amountLoading}
payMethods={payMethods}
preTopUp={preTopUp}
paymentLoading={paymentLoading}
payWay={payWay}
redemptionCode={redemptionCode}
setRedemptionCode={setRedemptionCode}
topUp={topUp}
isSubmitting={isSubmitting}
topUpLink={topUpLink}
openTopUpLink={openTopUpLink}
userState={userState}
renderQuota={renderQuota}
statusLoading={statusLoading}
topupInfo={topupInfo}
onOpenHistory={handleOpenHistory}
/>
</div>
{/* 右侧信息区域 */}
<div className='lg:col-span-5'>
<InvitationCard
t={t}
userState={userState}
renderQuota={renderQuota}
setOpenTransfer={setOpenTransfer}
affLink={affLink}
handleAffLinkClick={handleAffLinkClick}
/>
</div>
</div>
</div>
</div>
);
};
export default TopUp;
@@ -0,0 +1,326 @@
/*
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 } from 'react';
import { Modal, Typography, Skeleton } from '@douyinfe/semi-ui';
import {
CreditCard,
Sparkles,
Coins,
BadgePercent,
Wallet,
Tag,
CheckCircle2,
Clock3,
} from 'lucide-react';
import {
AlipayBrandIcon,
WechatBrandIcon,
StripeBrandIcon,
PayPalBrandIcon,
} from '../../common/icons/BrandIcons';
const { Text } = Typography;
const PaymentConfirmModal = ({
t,
open,
onlineTopUp,
handleCancel,
confirmLoading,
topUpCount,
renderQuotaWithAmount,
amountLoading,
renderAmount,
payWay,
payMethods,
// 新增:用于显示折扣明细
amountNumber,
discountRate,
payPalQuote,
}) => {
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
if (!open || payWay !== 'paypal') return undefined;
setNow(Date.now());
const timer = window.setInterval(() => setNow(Date.now()), 1000);
return () => window.clearInterval(timer);
}, [open, payWay]);
const quoteRemaining = Math.max(
0,
Math.ceil((payPalQuote?.quoteExpiresAt || 0) - now / 1000),
);
const payPalQuoteExpired = payWay === 'paypal' && quoteRemaining === 0;
const hasDiscount =
discountRate && discountRate > 0 && discountRate < 1 && amountNumber > 0;
const originalAmount = hasDiscount ? amountNumber / discountRate : 0;
const discountAmount = hasDiscount ? originalAmount - amountNumber : 0;
// 获取支付方式图标和颜色
const getPaymentInfo = () => {
const payMethod = payMethods?.find((method) => method.type === payWay);
if (payMethod) {
return {
name: payMethod.name,
type: payMethod.type,
color: payMethod.color,
};
}
if (payWay === 'alipay') return { name: t('支付宝'), type: 'alipay' };
if (payWay === 'stripe') return { name: 'Stripe', type: 'stripe' };
if (payWay === 'paypal') return { name: 'PayPal', type: 'paypal' };
return { name: t('微信'), type: 'wxpay' };
};
const paymentInfo = getPaymentInfo();
const renderPayIcon = (type, size = 20) => {
if (type === 'alipay')
return <AlipayBrandIcon size={size} color='#1677FF' />;
if (type === 'wxpay')
return <WechatBrandIcon size={size} color='#07C160' />;
if (type === 'stripe')
return <StripeBrandIcon size={size} color='#635BFF' />;
if (type === 'paypal') return <PayPalBrandIcon size={size} />;
return <CreditCard size={size} className='text-brand' />;
};
return (
<Modal
title={null}
visible={open}
onOk={onlineTopUp}
onCancel={handleCancel}
maskClosable={false}
size='small'
centered
confirmLoading={confirmLoading}
okButtonProps={{ disabled: payPalQuoteExpired || amountLoading }}
okText={t('确认支付')}
cancelText={t('取消')}
className='payment-confirm-modal'
bodyStyle={{ padding: 0 }}
style={{ overflow: 'hidden' }}
>
{/* 自定义头部 */}
<div className='relative overflow-hidden'>
{/* 背景渐变 */}
<div className='absolute inset-0 bg-gradient-to-br from-brand-from via-brand-via to-brand-to' />
{/* 装饰圆形 */}
<div className='absolute top-0 right-0 w-32 h-32 bg-white/10 rounded-full -mr-16 -mt-16 blur-2xl' />
<div className='absolute bottom-0 left-0 w-24 h-24 bg-black/10 rounded-full -ml-12 -mb-12 blur-xl' />
{/* 头部内容 */}
<div className='relative px-6 py-5'>
<div className='flex items-center gap-3'>
<div className='relative'>
<div className='absolute -inset-1 bg-white/30 rounded-xl blur-sm' />
<div className='relative w-12 h-12 rounded-xl bg-white/20 backdrop-blur-sm flex items-center justify-center border border-white/30'>
<CreditCard size={24} className='text-white' />
</div>
<Sparkles
size={14}
className='absolute -top-1 -right-1 text-amber-300'
/>
</div>
<div>
<h3 className='text-white font-bold text-lg'>{t('充值确认')}</h3>
<p className='text-white/70 text-sm'>{t('请确认您的充值信息')}</p>
</div>
</div>
</div>
</div>
{/* 主内容区域 */}
<div className='p-5 space-y-4'>
{/* 充值金额卡片 */}
<div className='relative group'>
<div className='absolute -inset-0.5 bg-gradient-to-r from-brand-from/30 to-brand-to/30 rounded-2xl blur-sm opacity-0 group-hover:opacity-100 transition-opacity' />
<div className='relative bg-gradient-to-br from-slate-50 to-slate-100 dark:from-neutral-800 dark:to-neutral-900 rounded-xl p-4 border border-slate-200/50 dark:border-neutral-700/50'>
{/* 充值金额 */}
<div className='flex items-center justify-between mb-3 pb-3 border-b border-slate-200 dark:border-neutral-700'>
<div className='flex items-center gap-2'>
<div className='w-8 h-8 rounded-lg bg-gradient-to-br from-amber-400 to-orange-500 flex items-center justify-center shadow-md shadow-amber-500/20'>
<Coins size={16} className='text-white' />
</div>
<Text className='text-slate-600 dark:text-slate-300 font-medium'>
{t('获得额度')}
</Text>
</div>
<Text className='text-lg font-bold bg-clip-text text-transparent bg-gradient-to-r from-amber-600 to-orange-600 dark:from-amber-400 dark:to-orange-400'>
{renderQuotaWithAmount(topUpCount)}
</Text>
</div>
{/* 实付金额 */}
<div className='flex items-center justify-between'>
<div className='flex items-center gap-2'>
<div className='w-8 h-8 rounded-lg bg-gradient-to-br from-rose-400 to-red-500 flex items-center justify-center shadow-md shadow-rose-500/20'>
<Wallet size={16} className='text-white' />
</div>
<Text className='text-slate-600 dark:text-slate-300 font-medium'>
{t('实付金额')}
</Text>
</div>
{amountLoading ? (
<Skeleton.Title style={{ width: '80px', height: '24px' }} />
) : (
<div className='flex items-center gap-2'>
<span className='text-2xl font-bold text-rose-500'>
{renderAmount()}
</span>
{hasDiscount && (
<span className='px-2 py-0.5 rounded-full bg-emerald-100 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400 text-xs font-bold'>
{Math.round((1 - discountRate) * 100)}% OFF
</span>
)}
</div>
)}
</div>
</div>
</div>
{/* 折扣明细 */}
{hasDiscount && !amountLoading && (
<div className='relative overflow-hidden rounded-xl bg-gradient-to-r from-emerald-50 to-teal-50 dark:from-emerald-900/20 dark:to-teal-900/20 border border-emerald-200/50 dark:border-emerald-800/30 p-4'>
{/* 装饰 */}
<div className='absolute top-0 right-0 w-20 h-20 bg-emerald-400/10 rounded-full -mr-10 -mt-10 blur-xl' />
<div className='relative flex items-center gap-2 mb-3'>
<div className='w-6 h-6 rounded-full bg-gradient-to-br from-emerald-400 to-teal-500 flex items-center justify-center'>
<BadgePercent size={14} className='text-white' />
</div>
<Text className='text-emerald-700 dark:text-emerald-300 font-semibold text-sm'>
{t('优惠明细')}
</Text>
</div>
<div className='relative space-y-2'>
<div className='flex justify-between items-center'>
<Text className='text-slate-500 dark:text-slate-400 text-sm'>
{t('原价')}
</Text>
<Text delete className='text-slate-400 dark:text-slate-500'>
¥{originalAmount.toFixed(2)}
</Text>
</div>
<div className='flex justify-between items-center'>
<div className='flex items-center gap-1'>
<Tag size={12} className='text-emerald-500' />
<Text className='text-emerald-600 dark:text-emerald-400 text-sm'>
{t('优惠减免')}
</Text>
</div>
<Text className='text-emerald-600 dark:text-emerald-400 font-semibold'>
- ¥{discountAmount.toFixed(2)}
</Text>
</div>
</div>
</div>
)}
{/* 支付方式 */}
<div className='relative group'>
<div className='absolute -inset-0.5 bg-gradient-to-r from-blue-400/20 to-cyan-400/20 rounded-2xl blur-sm opacity-0 group-hover:opacity-100 transition-opacity' />
<div className='relative flex items-center justify-between bg-slate-50 dark:bg-neutral-800/50 rounded-xl p-4 border border-slate-200/50 dark:border-neutral-700/50'>
<div className='flex items-center gap-2'>
<div className='w-8 h-8 rounded-lg bg-gradient-to-br from-blue-400 to-cyan-500 flex items-center justify-center shadow-md shadow-blue-500/20'>
<CheckCircle2 size={16} className='text-white' />
</div>
<Text className='text-slate-600 dark:text-slate-300 font-medium'>
{t('支付方式')}
</Text>
</div>
<div className='flex items-center gap-2 px-3 py-1.5 rounded-lg bg-white dark:bg-neutral-700 shadow-sm border border-slate-200 dark:border-neutral-600'>
{renderPayIcon(paymentInfo.type, 18)}
<Text className='font-medium text-slate-700 dark:text-slate-200'>
{paymentInfo.name}
</Text>
</div>
</div>
</div>
{payWay === 'paypal' && payPalQuote ? (
<div className='space-y-3 border-t border-slate-200 pt-3 dark:border-neutral-700'>
<div className='space-y-2'>
<div className='flex items-center justify-between gap-4'>
<Text type='tertiary' size='small'>
{t('充值金额')}
</Text>
<Text strong>
{formatPayPalAmount(payPalQuote.basePayAmount)}
</Text>
</div>
<div className='flex items-center justify-between gap-4'>
<Text type='tertiary' size='small'>
{t('支付服务费')}
</Text>
<Text strong>
{payPalQuote.feePayer === 'platform'
? t('平台承担')
: formatPayPalAmount(payPalQuote.serviceFee)}
</Text>
</div>
<div className='flex items-center justify-between gap-4'>
<Text type='tertiary' size='small'>
{t('实际支付')}
</Text>
<Text strong>{formatPayPalAmount(payPalQuote.payAmount)}</Text>
</div>
</div>
<div className='flex items-start justify-between gap-4'>
<div>
<Text className='block text-sm font-medium'>
{t('汇率来源')}:{t(payPalQuote.exchangeRateSource)}
</Text>
<Text type='tertiary' size='small'>
1 USD = {payPalQuote.exchangeRate} CNY
</Text>
</div>
<div className='flex items-center gap-1'>
<Clock3 size={14} />
<Text
type={payPalQuoteExpired ? 'danger' : 'tertiary'}
size='small'
>
{payPalQuoteExpired
? t('报价已过期,请重新获取')
: `${t('报价剩余')} ${quoteRemaining}s`}
</Text>
</div>
</div>
</div>
) : null}
{/* 底部提示 */}
<div className='flex items-center justify-center gap-2 pt-2'>
<div className='w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse' />
<Text className='text-xs text-slate-400 dark:text-slate-500'>
{t('点击确认后将跳转至支付页面')}
</Text>
</div>
</div>
</Modal>
);
};
const formatPayPalAmount = (amount) => `$${Number(amount || 0).toFixed(2)} USD`;
export default PaymentConfirmModal;
@@ -0,0 +1,346 @@
/*
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, { useState, useEffect, useMemo } from 'react';
import {
Modal,
Table,
Typography,
Toast,
Empty,
Button,
Input,
} from '@douyinfe/semi-ui';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../common/illustrations';
import {
CheckCircle2,
Clock3,
Coins,
Copy,
ReceiptText,
XCircle,
} from 'lucide-react';
import { IconSearch } from '@douyinfe/semi-icons';
import { API, timestamp2string } from '../../../helpers';
import { isAdmin } from '../../../helpers/utils';
import { useIsMobile } from '../../../hooks/common/useIsMobile';
const { Text } = Typography;
// 状态映射配置
const STATUS_CONFIG = {
success: {
type: 'success',
key: '成功',
icon: CheckCircle2,
className:
'border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-700/40 dark:bg-emerald-900/20 dark:text-emerald-300',
},
pending: {
type: 'warning',
key: '待支付',
icon: Clock3,
className:
'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-700/40 dark:bg-amber-900/20 dark:text-amber-300',
},
expired: {
type: 'danger',
key: '已过期',
icon: XCircle,
className:
'border-rose-200 bg-rose-50 text-rose-700 dark:border-rose-700/40 dark:bg-rose-900/20 dark:text-rose-300',
},
};
// 支付方式映射
const PAYMENT_METHOD_MAP = {
stripe: 'Stripe',
paypal: 'PayPal',
alipay: '支付宝',
wxpay: '微信',
};
const TopupHistoryModal = ({ visible, onCancel, t }) => {
const [loading, setLoading] = useState(false);
const [topups, setTopups] = useState([]);
const [total, setTotal] = useState(0);
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
const [keyword, setKeyword] = useState('');
const isMobile = useIsMobile();
const loadTopups = async (currentPage, currentPageSize) => {
setLoading(true);
try {
const base = isAdmin() ? '/api/user/topup' : '/api/user/topup/self';
const qs =
`p=${currentPage}&page_size=${currentPageSize}` +
(keyword ? `&keyword=${encodeURIComponent(keyword)}` : '');
const endpoint = `${base}?${qs}`;
const res = await API.get(endpoint);
const { success, message, data } = res.data;
if (success) {
setTopups(data.items || []);
setTotal(data.total || 0);
} else {
Toast.error({ content: message || t('加载失败') });
}
} catch (error) {
console.error('Load topups error:', error);
Toast.error({ content: t('加载账单失败') });
} finally {
setLoading(false);
}
};
useEffect(() => {
if (visible) {
loadTopups(page, pageSize);
}
}, [visible, page, pageSize, keyword]);
const handlePageChange = (currentPage) => {
setPage(currentPage);
};
const handlePageSizeChange = (currentPageSize) => {
setPageSize(currentPageSize);
setPage(1);
};
const handleKeywordChange = (value) => {
setKeyword(value);
setPage(1);
};
// 管理员补单
const handleAdminComplete = async (tradeNo) => {
try {
const res = await API.post('/api/user/topup/complete', {
trade_no: tradeNo,
});
const { success, message } = res.data;
if (success) {
Toast.success({ content: t('补单成功') });
await loadTopups(page, pageSize);
} else {
Toast.error({ content: message || t('补单失败') });
}
} catch (e) {
Toast.error({ content: t('补单失败') });
}
};
const confirmAdminComplete = (tradeNo) => {
Modal.confirm({
title: t('确认补单'),
content: t('是否将该订单标记为成功并为用户入账?'),
onOk: () => handleAdminComplete(tradeNo),
});
};
// 渲染状态徽章
const renderStatusBadge = (status) => {
const config = STATUS_CONFIG[status] || {
type: 'primary',
key: status,
icon: Clock3,
className:
'border-slate-200 bg-slate-50 text-slate-600 dark:border-slate-700 dark:bg-slate-800/60 dark:text-slate-300',
};
const Icon = config.icon;
return (
<span
className={`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-semibold ${config.className}`}
>
<Icon size={14} />
<span>{t(config.key)}</span>
</span>
);
};
// 渲染支付方式
const renderPaymentMethod = (pm) => {
const displayName = PAYMENT_METHOD_MAP[pm];
return <Text>{displayName ? t(displayName) : pm || '-'}</Text>;
};
// 检查是否为管理员
const userIsAdmin = useMemo(() => isAdmin(), []);
const columns = useMemo(() => {
const baseColumns = [
{
title: t('订单号'),
dataIndex: 'trade_no',
key: 'trade_no',
render: (text) => (
<div className='group flex min-w-[260px] items-center gap-2'>
<span className='inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-xl bg-blue-50 text-blue-600 dark:bg-blue-900/25 dark:text-blue-300'>
<ReceiptText size={15} />
</span>
<Text
copyable={{ icon: <Copy size={14} /> }}
ellipsis={{ showTooltip: true }}
className='font-mono text-sm text-gray-900 dark:text-gray-100'
>
{text}
</Text>
</div>
),
},
{
title: t('支付方式'),
dataIndex: 'payment_method',
key: 'payment_method',
render: renderPaymentMethod,
},
{
title: t('充值额度'),
dataIndex: 'amount',
key: 'amount',
render: (amount) => (
<span className='inline-flex items-center gap-1.5 rounded-full bg-sky-50 px-2.5 py-1 text-sm font-semibold text-sky-700 dark:bg-sky-900/25 dark:text-sky-300'>
<Coins size={15} />
{amount}
</span>
),
},
{
title: t('支付金额'),
dataIndex: 'money',
key: 'money',
render: (money) => (
<span className='text-base font-semibold text-rose-500'>
¥{Number(money || 0).toFixed(2)}
</span>
),
},
{
title: t('状态'),
dataIndex: 'status',
key: 'status',
render: renderStatusBadge,
},
];
// 管理员才显示操作列
if (userIsAdmin) {
baseColumns.push({
title: t('操作'),
key: 'action',
render: (_, record) => {
if (record.status !== 'pending') return null;
return (
<Button
size='small'
type='primary'
theme='solid'
onClick={() => confirmAdminComplete(record.trade_no)}
className='!rounded-full !bg-gradient-to-r !from-blue-500 !to-cyan-500 !border-0 !px-4 !shadow-md !shadow-blue-500/20'
>
{t('补单')}
</Button>
);
},
});
}
baseColumns.push({
title: t('创建时间'),
dataIndex: 'create_time',
key: 'create_time',
render: (time) => timestamp2string(time),
});
return baseColumns;
}, [t, userIsAdmin]);
return (
<Modal
title={
<div className='flex items-center gap-2 text-lg font-semibold'>
<div className='p-1.5 bg-blue-50 dark:bg-blue-900/30 rounded-lg text-blue-600 dark:text-blue-400'>
<Coins size={20} />
</div>
{t('充值账单')}
</div>
}
visible={visible}
onCancel={onCancel}
footer={null}
size={isMobile ? 'full-width' : 'large'}
className='!rounded-2xl'
bodyStyle={{ padding: isMobile ? '16px' : '24px' }}
>
<div className='mb-4 rounded-2xl border border-white/70 bg-white/[0.55] p-3 shadow-sm backdrop-blur-xl dark:border-white/10 dark:bg-white/[0.045]'>
<Input
prefix={<IconSearch className='text-gray-400' />}
placeholder={t('搜索订单号...')}
value={keyword}
onChange={handleKeywordChange}
showClear
className='topup-history-search !rounded-xl'
/>
</div>
<div className='topup-history-table overflow-hidden rounded-2xl border border-white/70 bg-white/[0.55] shadow-[0_18px_50px_rgba(15,23,42,0.08)] backdrop-blur-xl dark:border-white/10 dark:bg-white/[0.045]'>
<Table
columns={columns}
dataSource={topups}
loading={loading}
rowKey='id'
pagination={{
currentPage: page,
pageSize: pageSize,
total: total,
showSizeChanger: true,
pageSizeOpts: [10, 20, 50, 100],
onPageChange: handlePageChange,
onPageSizeChange: handlePageSizeChange,
className: 'p-4',
}}
size='small'
className='modern-table'
rowClassName='hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors'
empty={
<Empty
image={
<IllustrationNoResult style={{ width: 150, height: 150 }} />
}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={
<span className='text-gray-500 dark:text-gray-400 font-medium'>
{t('暂无充值记录')}
</span>
}
style={{ padding: 40 }}
/>
}
/>
</div>
</Modal>
);
};
export default TopupHistoryModal;
@@ -0,0 +1,78 @@
/*
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 from 'react';
import { Modal, Typography, Input } from '@douyinfe/semi-ui';
import { CreditCard } from 'lucide-react';
import QuotaInput from '../../common/ui/QuotaInput';
const TransferModal = ({
t,
openTransfer,
transfer,
handleTransferCancel,
userState,
renderQuota,
getQuotaPerUnit,
transferAmount,
setTransferAmount,
}) => {
return (
<Modal
title={
<div className='flex items-center'>
<CreditCard className='mr-2' size={18} />
{t('划转邀请额度')}
</div>
}
visible={openTransfer}
onOk={transfer}
onCancel={handleTransferCancel}
maskClosable={false}
centered
>
<div className='space-y-4'>
<div>
<Typography.Text strong className='block mb-2'>
{t('可用邀请额度')}
</Typography.Text>
<Input
value={renderQuota(userState?.user?.aff_quota)}
disabled
className='!rounded-lg'
/>
</div>
<div>
<Typography.Text strong className='block mb-2'>
{t('划转额度')} · {t('最低') + renderQuota(getQuotaPerUnit())}
</Typography.Text>
<QuotaInput
minQuota={getQuotaPerUnit()}
maxQuota={userState?.user?.aff_quota || 0}
value={transferAmount}
onChange={(value) => setTransferAmount(value)}
className='w-full !rounded-lg'
/>
</div>
</div>
</Modal>
);
};
export default TransferModal;
@@ -0,0 +1,267 @@
/*
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, { useState, useEffect, useRef } from 'react';
import {
Modal,
Button,
Spin,
Typography,
Space,
Toast,
} from '@douyinfe/semi-ui';
import { IconRefresh, IconClose } from '@douyinfe/semi-icons';
import { useTranslation } from 'react-i18next';
import QRCode from 'qrcode';
import { API, renderQuota } from '../../../helpers';
const { Text } = Typography;
// pollFn: 可选,自定义轮询函数,签名为 async (tradeNo: string) => { status: string } | null
// 默认走个人充值接口 /api/user/topup/self
const WechatQRModal = ({ visible, onClose, orderData, pollFn }) => {
const { t } = useTranslation();
const [qrCodeUrl, setQrCodeUrl] = useState('');
const [_loading, _setLoading] = useState(false);
const [polling, setPolling] = useState(false);
const [expired, setExpired] = useState(false);
const pollingTimerRef = useRef(null);
const expireTimerRef = useRef(null);
const errorCountRef = useRef(0); // 错误计数
// 生成二维码
useEffect(() => {
if (visible && orderData && orderData.code_url) {
// 【Bug#5修复】重置过期状态,避免上一个过期订单影响新订单的展示
setExpired(false);
setQrCodeUrl(''); // 清空旧二维码,避免短暂显示上一个订单的二维码
generateQRCode(orderData.code_url);
startPolling();
startExpireTimer();
}
return () => {
stopPolling();
stopExpireTimer();
};
}, [visible, orderData]);
const generateQRCode = async (url) => {
try {
const qrUrl = await QRCode.toDataURL(url, {
width: 300,
margin: 2,
});
setQrCodeUrl(qrUrl);
} catch (error) {
Toast.error(t('生成二维码失败'));
}
};
// 开始轮询订单状态
const startPolling = () => {
if (!orderData || !orderData.trade_no) return;
setPolling(true);
errorCountRef.current = 0; // 重置错误计数
const defaultPollFn = async (tradeNo) => {
const res = await API.get(`/api/user/topup/self?keyword=${tradeNo}`);
const items = res.data.data?.items || res.data.data || [];
return items.length > 0 ? items[0] : null;
};
const activePollFn = pollFn || defaultPollFn;
pollingTimerRef.current = setInterval(async () => {
try {
const order = await activePollFn(orderData.trade_no);
errorCountRef.current = 0;
if (order) {
if (order.status === 'success') {
stopPolling();
Toast.success(t('支付成功!'));
onClose(true);
} else if (order.status === 'expired' || order.status === 'closed') {
stopPolling();
setExpired(true);
}
}
} catch (error) {
console.error('查询订单状态失败:', error);
errorCountRef.current++;
if (errorCountRef.current >= 3) {
stopPolling();
Toast.error(t('网络异常,请刷新页面重试'));
setExpired(true);
}
}
}, 3000);
};
// 停止轮询
const stopPolling = () => {
if (pollingTimerRef.current) {
clearInterval(pollingTimerRef.current);
pollingTimerRef.current = null;
}
setPolling(false);
};
// 开始过期计时器
const startExpireTimer = () => {
if (!orderData || !orderData.expire_at) return;
const now = Math.floor(Date.now() / 1000);
const expireIn = orderData.expire_at - now;
if (expireIn > 0) {
expireTimerRef.current = setTimeout(() => {
setExpired(true);
stopPolling();
Toast.warning(t('订单已过期'));
}, expireIn * 1000);
}
};
// 停止过期计时器
const stopExpireTimer = () => {
if (expireTimerRef.current) {
clearTimeout(expireTimerRef.current);
expireTimerRef.current = null;
}
};
// 刷新二维码
const handleRefresh = () => {
if (orderData && orderData.code_url) {
generateQRCode(orderData.code_url);
Toast.success(t('二维码已刷新'));
}
};
// 关闭弹窗
const handleClose = () => {
stopPolling();
stopExpireTimer();
onClose(false);
};
return (
<Modal
title={t('微信支付')}
visible={visible}
onCancel={handleClose}
footer={null}
width={450}
centered
>
<div style={{ textAlign: 'center', padding: '20px 0' }}>
{expired ? (
<div>
<Text type='danger' style={{ fontSize: 18 }}>
{t('订单已过期,请重新下单')}
</Text>
<br />
<Button
type='primary'
style={{ marginTop: 20 }}
onClick={handleClose}
>
{t('关闭')}
</Button>
</div>
) : (
<>
<Space vertical align='center' spacing='large'>
{/* 二维码 */}
<div style={{ position: 'relative' }}>
{qrCodeUrl ? (
<img
src={qrCodeUrl}
alt={t('支付二维码')}
style={{
width: 300,
height: 300,
border: '1px solid #e8e8e8',
}}
/>
) : (
<div
style={{
width: 300,
height: 300,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
border: '1px solid #e8e8e8',
}}
>
<Spin size='large' />
</div>
)}
</div>
{/* 支付信息 */}
{orderData && (
<Space vertical align='start' spacing='small'>
<div>
<Text type='secondary'>{t('订单号:')}</Text>
<Text copyable>{orderData.trade_no}</Text>
</div>
<div>
<Text type='secondary'>{t('支付金额:')}</Text>
<Text strong style={{ fontSize: 20, color: '#f5222d' }}>
¥{orderData.amount?.toFixed(2)}
</Text>
</div>
<div>
<Text type='secondary'>{t('获得额度:')}</Text>
<Text strong>{renderQuota(orderData.quota)}</Text>
</div>
</Space>
)}
{/* 提示文字 */}
<Text type='tertiary' style={{ fontSize: 14 }}>
{polling
? `🔄 ${t('正在等待支付...')}`
: t('请使用微信扫码支付')}
</Text>
{/* 操作按钮 */}
<Space>
<Button icon={<IconRefresh />} onClick={handleRefresh}>
{t('刷新二维码')}
</Button>
<Button icon={<IconClose />} onClick={handleClose}>
{t('取消支付')}
</Button>
</Space>
</Space>
</>
)}
</div>
</Modal>
);
};
export default WechatQRModal;