Merge branch 'main' into feat_subscribe_sp1

This commit is contained in:
Little Write
2025-09-27 22:54:52 +08:00
617 changed files with 64415 additions and 27156 deletions

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;

View File

@@ -0,0 +1,482 @@
/*
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 {
Avatar,
Typography,
Tag,
Card,
Button,
Banner,
Skeleton,
Form,
Space,
Row,
Col,
Spin, Tooltip
} from '@douyinfe/semi-ui';
import { SiAlipay, SiWechat, SiStripe } from 'react-icons/si';
import { CreditCard, Coins, Wallet, BarChart2, TrendingUp } from 'lucide-react';
import { IconGift } from '@douyinfe/semi-icons';
import { useMinimumLoadingTime } from '../../hooks/common/useMinimumLoadingTime';
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,
}) => {
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-sm border-0'>
{/* 卡片头部 */}
<div className='flex items-center mb-4'>
<Avatar size='small' color='blue' className='mr-3 shadow-md'>
<CreditCard 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': '37 99 235',
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>
</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?.quota)}
</div>
<div className='flex items-center justify-center text-sm'>
<Wallet
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?.used_quota)}
</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' }}
>
{userState?.user?.request_count || 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>
</div>
</div>
}
>
{/* 在线充值表单 */}
{statusLoading ? (
<div className='py-8 flex justify-center'>
<Spin size='large' />
</div>
) : enableOnlineTopUp || enableStripeTopUp || enableCreemTopUp ? (
<Form
getFormApi={(api) => (onlineFormApiRef.current = api)}
initValues={{ topUpCount: topUpCount }}
>
<div className='space-y-6'>
{(enableOnlineTopUp || enableStripeTopUp) && (
<Row gutter={12}>
<Col xs={24} sm={24} md={24} lg={10} xl={10}>
<Form.InputNumber
field='topUpCount'
label={t('充值数量')}
disabled={!enableOnlineTopUp && !enableStripeTopUp}
placeholder={
t('充值数量,最低 ') + renderQuotaWithAmount(minTopUp)
}
value={topUpCount}
min={minTopUp}
max={999999999}
step={1}
precision={0}
onChange={async (value) => {
if (value && value >= 1) {
setTopUpCount(value);
setSelectedPreset(null);
await getAmount(value);
}
}}
onBlur={(e) => {
const value = parseInt(e.target.value);
if (!value || value < 1) {
setTopUpCount(1);
getAmount(1);
}
}}
formatter={(value) => (value ? `${value}` : '')}
parser={(value) =>
value ? parseInt(value.replace(/[^\d]/g, '')) : 0
}
extraText={
<Skeleton
loading={showAmountSkeleton}
active
placeholder={
<Skeleton.Title
style={{
width: 120,
height: 20,
borderRadius: 6,
}}
/>
}
>
<Text type='secondary' className='text-red-600'>
{t('实付金额:')}
<span style={{ color: 'red' }}>
{renderAmount()}
</span>
</Text>
</Skeleton>
}
style={{ width: '100%' }}
/>
</Col>
<Col xs={24} sm={24} md={24} lg={14} xl={14}>
<Form.Slot label={t('选择支付方式')}>
{payMethods && payMethods.length > 0 ? (
<Space wrap>
{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 buttonEl = (
<Button
key={payMethod.type}
theme='outline'
type='tertiary'
onClick={() => preTopUp(payMethod.type)}
disabled={disabled}
loading={paymentLoading && payWay === payMethod.type}
icon={
payMethod.type === 'alipay' ? (
<SiAlipay size={18} color='#1677FF' />
) : payMethod.type === 'wxpay' ? (
<SiWechat size={18} color='#07C160' />
) : payMethod.type === 'stripe' ? (
<SiStripe size={18} color='#635BFF' />
) : (
<CreditCard
size={18}
color={payMethod.color || 'var(--semi-color-text-2)'}
/>
)
}
className='!rounded-lg !px-4 !py-2'
>
{payMethod.name}
</Button>
);
return disabled && minTopupVal > Number(topUpCount || 0) ? (
<Tooltip content={t('此支付方式最低充值金额为') + ' ' + minTopupVal} key={payMethod.type}>
{buttonEl}
</Tooltip>
) : (
<React.Fragment key={payMethod.type}>{buttonEl}</React.Fragment>
);
})}
</Space>
) : (
<div className='text-gray-500 text-sm p-3 bg-gray-50 rounded-lg border border-dashed border-gray-300'>
{t('暂无可用的支付方式,请联系管理员配置')}
</div>
)}
</Form.Slot>
</Col>
</Row>
)}
{(enableOnlineTopUp || enableStripeTopUp) && (
<Form.Slot label={t('选择充值额度')}>
<div className='grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2'>
{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;
return (
<Card
key={index}
style={{
cursor: 'pointer',
border: selectedPreset === preset.value
? '2px solid var(--semi-color-primary)'
: '1px solid var(--semi-color-border)',
height: '100%',
width: '100%'
}}
bodyStyle={{ padding: '12px' }}
onClick={() => {
selectPresetAmount(preset);
onlineFormApiRef.current?.setValue(
'topUpCount',
preset.value,
);
}}
>
<div style={{ textAlign: 'center' }}>
<Typography.Title heading={6} style={{ margin: '0 0 8px 0' }}>
<Coins size={18} />
{formatLargeNumber(preset.value)}
{hasDiscount && (
<Tag style={{ marginLeft: 4 }} color="green">
{t('折').includes('off') ?
((1 - parseFloat(discount)) * 100).toFixed(1) :
(discount * 10).toFixed(1)}{t('折')}
</Tag>
)}
</Typography.Title>
<div style={{
color: 'var(--semi-color-text-2)',
fontSize: '12px',
margin: '4px 0'
}}>
{t('实付')} {actualPay.toFixed(2)}
{hasDiscount ? `${t('节省')} ${save.toFixed(2)}` : `${t('节省')} 0.00`}
</div>
</div>
</Card>
);
})}
</div>
</Form.Slot>
)}
{/* Creem 充值区域 */}
{enableCreemTopUp && creemProducts.length > 0 && (
<Form.Slot label={t('Creem 充值')}>
<div className='grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3'>
{creemProducts.map((product, index) => (
<Card
key={index}
onClick={() => creemPreTopUp(product)}
className='cursor-pointer !rounded-2xl transition-all hover:shadow-md border-gray-200 hover:border-gray-300'
bodyStyle={{ textAlign: 'center', padding: '16px' }}
>
<div className='font-medium text-lg mb-2'>
{product.name}
</div>
<div className='text-sm text-gray-600 mb-2'>
{t('充值额度')}: {product.quota}
</div>
<div className='text-lg font-semibold text-blue-600'>
{product.currency === 'EUR' ? '€' : '$'}{product.price}
</div>
</Card>
))}
</div>
</Form.Slot>
)}
</div>
</Form>
) : (
<Banner
type='info'
description={t(
'管理员未开启在线充值功能,请联系管理员开启或使用兑换码充值。',
)}
className='!rounded-xl'
closeIcon={null}
/>
)}
</Card>
{/* 兑换码充值 */}
<Card
className='!rounded-xl w-full'
title={
<Text type='tertiary' strong>
{t('兑换码充值')}
</Text>
}
>
<Form
getFormApi={(api) => (redeemFormApiRef.current = api)}
initValues={{ redemptionCode: redemptionCode }}
>
<Form.Input
field='redemptionCode'
noLabel={true}
placeholder={t('请输入兑换码')}
value={redemptionCode}
onChange={(value) => setRedemptionCode(value)}
prefix={<IconGift />}
suffix={
<div className='flex items-center gap-2'>
<Button
type='primary'
theme='solid'
onClick={topUp}
loading={isSubmitting}
>
{t('兑换额度')}
</Button>
</div>
}
showClear
style={{ width: '100%' }}
extraText={
topUpLink && (
<Text type='tertiary'>
{t('在找兑换码?')}
<Text
type='secondary'
underline
className='cursor-pointer'
onClick={openTopUpLink}
>
{t('购买兑换码')}
</Text>
</Text>
)
}
/>
</Form>
</Card>
</Space>
</Card>
);
};
export default RechargeCard;

View File

@@ -0,0 +1,696 @@
/*
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';
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);
// 预设充值额度选项
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 (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 { message, 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));
}
// 初始化显示实付金额
getAmount(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 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}
/>
{/* 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}
/>
</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;

View File

@@ -0,0 +1,209 @@
/*
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, Card, Skeleton } from '@douyinfe/semi-ui';
import { SiAlipay, SiWechat, SiStripe } from 'react-icons/si';
import { CreditCard } from 'lucide-react';
const { Text } = Typography;
const PaymentConfirmModal = ({
t,
open,
onlineTopUp,
handleCancel,
confirmLoading,
topUpCount,
renderQuotaWithAmount,
amountLoading,
renderAmount,
payWay,
payMethods,
// 新增:用于显示折扣明细
amountNumber,
discountRate,
}) => {
const hasDiscount = discountRate && discountRate > 0 && discountRate < 1 && amountNumber > 0;
const originalAmount = hasDiscount ? (amountNumber / discountRate) : 0;
const discountAmount = hasDiscount ? (originalAmount - amountNumber) : 0;
return (
<Modal
title={
<div className='flex items-center'>
<CreditCard className='mr-2' size={18} />
{t('充值确认')}
</div>
}
visible={open}
onOk={onlineTopUp}
onCancel={handleCancel}
maskClosable={false}
size='small'
centered
confirmLoading={confirmLoading}
>
<div className='space-y-4'>
<Card className='!rounded-xl !border-0 bg-slate-50 dark:bg-slate-800'>
<div className='space-y-3'>
<div className='flex justify-between items-center'>
<Text strong className='text-slate-700 dark:text-slate-200'>
{t('充值数量')}
</Text>
<Text className='text-slate-900 dark:text-slate-100'>
{renderQuotaWithAmount(topUpCount)}
</Text>
</div>
<div className='flex justify-between items-center'>
<Text strong className='text-slate-700 dark:text-slate-200'>
{t('实付金额')}
</Text>
{amountLoading ? (
<Skeleton.Title style={{ width: '60px', height: '16px' }} />
) : (
<div className='flex items-baseline space-x-2'>
<Text strong className='font-bold' style={{ color: 'red' }}>
{renderAmount()}
</Text>
{hasDiscount && (
<Text size='small' className='text-rose-500'>
{Math.round(discountRate * 100)}%
</Text>
)}
</div>
)}
</div>
{hasDiscount && !amountLoading && (
<>
<div className='flex justify-between items-center'>
<Text className='text-slate-500 dark:text-slate-400'>
{t('原价')}
</Text>
<Text delete className='text-slate-500 dark:text-slate-400'>
{`${originalAmount.toFixed(2)} ${t('元')}`}
</Text>
</div>
<div className='flex justify-between items-center'>
<Text className='text-slate-500 dark:text-slate-400'>
{t('优惠')}
</Text>
<Text className='text-emerald-600 dark:text-emerald-400'>
{`- ${discountAmount.toFixed(2)} ${t('元')}`}
</Text>
</div>
</>
)}
<div className='flex justify-between items-center'>
<Text strong className='text-slate-700 dark:text-slate-200'>
{t('支付方式')}
</Text>
<div className='flex items-center'>
{(() => {
const payMethod = payMethods.find(
(method) => method.type === payWay,
);
if (payMethod) {
return (
<>
{payMethod.type === 'alipay' ? (
<SiAlipay
className='mr-2'
size={16}
color='#1677FF'
/>
) : payMethod.type === 'wxpay' ? (
<SiWechat
className='mr-2'
size={16}
color='#07C160'
/>
) : payMethod.type === 'stripe' ? (
<SiStripe
className='mr-2'
size={16}
color='#635BFF'
/>
) : (
<CreditCard
className='mr-2'
size={16}
color={
payMethod.color || 'var(--semi-color-text-2)'
}
/>
)}
<Text className='text-slate-900 dark:text-slate-100'>
{payMethod.name}
</Text>
</>
);
} else {
// 默认充值方式
if (payWay === 'alipay') {
return (
<>
<SiAlipay
className='mr-2'
size={16}
color='#1677FF'
/>
<Text className='text-slate-900 dark:text-slate-100'>
{t('支付宝')}
</Text>
</>
);
} else if (payWay === 'stripe') {
return (
<>
<SiStripe
className='mr-2'
size={16}
color='#635BFF'
/>
<Text className='text-slate-900 dark:text-slate-100'>
Stripe
</Text>
</>
);
} else {
return (
<>
<SiWechat
className='mr-2'
size={16}
color='#07C160'
/>
<Text className='text-slate-900 dark:text-slate-100'>
{t('微信')}
</Text>
</>
);
}
}
})()}
</div>
</div>
</div>
</Card>
</div>
</Modal>
);
};
export default PaymentConfirmModal;

View File

@@ -0,0 +1,77 @@
/*
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, InputNumber } from '@douyinfe/semi-ui';
import { CreditCard } from 'lucide-react';
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>
<InputNumber
min={getQuotaPerUnit()}
max={userState?.user?.aff_quota || 0}
value={transferAmount}
onChange={(value) => setTransferAmount(value)}
className='w-full !rounded-lg'
/>
</div>
</div>
</Modal>
);
};
export default TransferModal;