RechargeCard.jsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. /*
  2. Copyright (C) 2025 QuantumNous
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <https://www.gnu.org/licenses/>.
  13. For commercial licensing, please contact support@quantumnous.com
  14. */
  15. import React, { useEffect, useRef, useState } from 'react';
  16. import {
  17. Avatar,
  18. Typography,
  19. Tag,
  20. Card,
  21. Button,
  22. Banner,
  23. Skeleton,
  24. Form,
  25. Space,
  26. Row,
  27. Col,
  28. Spin,
  29. Tooltip,
  30. Tabs,
  31. TabPane,
  32. } from '@douyinfe/semi-ui';
  33. import { SiAlipay, SiWechat, SiStripe } from 'react-icons/si';
  34. import {
  35. CreditCard,
  36. Coins,
  37. Wallet,
  38. BarChart2,
  39. TrendingUp,
  40. Receipt,
  41. Sparkles,
  42. } from 'lucide-react';
  43. import { IconGift } from '@douyinfe/semi-icons';
  44. import { useMinimumLoadingTime } from '../../hooks/common/useMinimumLoadingTime';
  45. import { getCurrencyConfig } from '../../helpers/render';
  46. import SubscriptionPlansCard from './SubscriptionPlansCard';
  47. const { Text } = Typography;
  48. const RechargeCard = ({
  49. t,
  50. enableOnlineTopUp,
  51. enableStripeTopUp,
  52. enableCreemTopUp,
  53. creemProducts,
  54. creemPreTopUp,
  55. presetAmounts,
  56. selectedPreset,
  57. selectPresetAmount,
  58. formatLargeNumber,
  59. priceRatio,
  60. topUpCount,
  61. minTopUp,
  62. renderQuotaWithAmount,
  63. getAmount,
  64. setTopUpCount,
  65. setSelectedPreset,
  66. renderAmount,
  67. amountLoading,
  68. payMethods,
  69. preTopUp,
  70. paymentLoading,
  71. payWay,
  72. redemptionCode,
  73. setRedemptionCode,
  74. topUp,
  75. isSubmitting,
  76. topUpLink,
  77. openTopUpLink,
  78. userState,
  79. renderQuota,
  80. statusLoading,
  81. topupInfo,
  82. onOpenHistory,
  83. subscriptionLoading = false,
  84. subscriptionPlans = [],
  85. billingPreference,
  86. onChangeBillingPreference,
  87. activeSubscriptions = [],
  88. allSubscriptions = [],
  89. reloadSubscriptionSelf,
  90. }) => {
  91. const onlineFormApiRef = useRef(null);
  92. const redeemFormApiRef = useRef(null);
  93. const initialTabSetRef = useRef(false);
  94. const showAmountSkeleton = useMinimumLoadingTime(amountLoading);
  95. const [activeTab, setActiveTab] = useState('topup');
  96. const shouldShowSubscription =
  97. !subscriptionLoading && subscriptionPlans.length > 0;
  98. useEffect(() => {
  99. if (initialTabSetRef.current) return;
  100. if (subscriptionLoading) return;
  101. setActiveTab(shouldShowSubscription ? 'subscription' : 'topup');
  102. initialTabSetRef.current = true;
  103. }, [shouldShowSubscription, subscriptionLoading]);
  104. useEffect(() => {
  105. if (!shouldShowSubscription && activeTab !== 'topup') {
  106. setActiveTab('topup');
  107. }
  108. }, [shouldShowSubscription, activeTab]);
  109. const topupContent = (
  110. <Space vertical style={{ width: '100%' }}>
  111. {/* 统计数据 */}
  112. <Card
  113. className='!rounded-xl w-full'
  114. cover={
  115. <div
  116. className='relative h-30'
  117. style={{
  118. '--palette-primary-darkerChannel': '37 99 235',
  119. backgroundImage: `linear-gradient(0deg, rgba(var(--palette-primary-darkerChannel) / 80%), rgba(var(--palette-primary-darkerChannel) / 80%)), url('/cover-4.webp')`,
  120. backgroundSize: 'cover',
  121. backgroundPosition: 'center',
  122. backgroundRepeat: 'no-repeat',
  123. }}
  124. >
  125. <div className='relative z-10 h-full flex flex-col justify-between p-4'>
  126. <div className='flex justify-between items-center'>
  127. <Text strong style={{ color: 'white', fontSize: '16px' }}>
  128. {t('账户统计')}
  129. </Text>
  130. </div>
  131. {/* 统计数据 */}
  132. <div className='grid grid-cols-3 gap-6 mt-4'>
  133. {/* 当前余额 */}
  134. <div className='text-center'>
  135. <div
  136. className='text-base sm:text-2xl font-bold mb-2'
  137. style={{ color: 'white' }}
  138. >
  139. {renderQuota(userState?.user?.quota)}
  140. </div>
  141. <div className='flex items-center justify-center text-sm'>
  142. <Wallet
  143. size={14}
  144. className='mr-1'
  145. style={{ color: 'rgba(255,255,255,0.8)' }}
  146. />
  147. <Text
  148. style={{
  149. color: 'rgba(255,255,255,0.8)',
  150. fontSize: '12px',
  151. }}
  152. >
  153. {t('当前余额')}
  154. </Text>
  155. </div>
  156. </div>
  157. {/* 历史消耗 */}
  158. <div className='text-center'>
  159. <div
  160. className='text-base sm:text-2xl font-bold mb-2'
  161. style={{ color: 'white' }}
  162. >
  163. {renderQuota(userState?.user?.used_quota)}
  164. </div>
  165. <div className='flex items-center justify-center text-sm'>
  166. <TrendingUp
  167. size={14}
  168. className='mr-1'
  169. style={{ color: 'rgba(255,255,255,0.8)' }}
  170. />
  171. <Text
  172. style={{
  173. color: 'rgba(255,255,255,0.8)',
  174. fontSize: '12px',
  175. }}
  176. >
  177. {t('历史消耗')}
  178. </Text>
  179. </div>
  180. </div>
  181. {/* 请求次数 */}
  182. <div className='text-center'>
  183. <div
  184. className='text-base sm:text-2xl font-bold mb-2'
  185. style={{ color: 'white' }}
  186. >
  187. {userState?.user?.request_count || 0}
  188. </div>
  189. <div className='flex items-center justify-center text-sm'>
  190. <BarChart2
  191. size={14}
  192. className='mr-1'
  193. style={{ color: 'rgba(255,255,255,0.8)' }}
  194. />
  195. <Text
  196. style={{
  197. color: 'rgba(255,255,255,0.8)',
  198. fontSize: '12px',
  199. }}
  200. >
  201. {t('请求次数')}
  202. </Text>
  203. </div>
  204. </div>
  205. </div>
  206. </div>
  207. </div>
  208. }
  209. >
  210. {/* 在线充值表单 */}
  211. {statusLoading ? (
  212. <div className='py-8 flex justify-center'>
  213. <Spin size='large' />
  214. </div>
  215. ) : enableOnlineTopUp || enableStripeTopUp || enableCreemTopUp ? (
  216. <Form
  217. getFormApi={(api) => (onlineFormApiRef.current = api)}
  218. initValues={{ topUpCount: topUpCount }}
  219. >
  220. <div className='space-y-6'>
  221. {(enableOnlineTopUp || enableStripeTopUp) && (
  222. <Row gutter={12}>
  223. <Col xs={24} sm={24} md={24} lg={10} xl={10}>
  224. <Form.InputNumber
  225. field='topUpCount'
  226. label={t('充值数量')}
  227. disabled={!enableOnlineTopUp && !enableStripeTopUp}
  228. placeholder={
  229. t('充值数量,最低 ') + renderQuotaWithAmount(minTopUp)
  230. }
  231. value={topUpCount}
  232. min={minTopUp}
  233. max={999999999}
  234. step={1}
  235. precision={0}
  236. onChange={async (value) => {
  237. if (value && value >= 1) {
  238. setTopUpCount(value);
  239. setSelectedPreset(null);
  240. await getAmount(value);
  241. }
  242. }}
  243. onBlur={(e) => {
  244. const value = parseInt(e.target.value);
  245. if (!value || value < 1) {
  246. setTopUpCount(1);
  247. getAmount(1);
  248. }
  249. }}
  250. formatter={(value) => (value ? `${value}` : '')}
  251. parser={(value) =>
  252. value ? parseInt(value.replace(/[^\d]/g, '')) : 0
  253. }
  254. extraText={
  255. <Skeleton
  256. loading={showAmountSkeleton}
  257. active
  258. placeholder={
  259. <Skeleton.Title
  260. style={{
  261. width: 120,
  262. height: 20,
  263. borderRadius: 6,
  264. }}
  265. />
  266. }
  267. >
  268. <Text type='secondary' className='text-red-600'>
  269. {t('实付金额:')}
  270. <span style={{ color: 'red' }}>
  271. {renderAmount()}
  272. </span>
  273. </Text>
  274. </Skeleton>
  275. }
  276. style={{ width: '100%' }}
  277. />
  278. </Col>
  279. <Col xs={24} sm={24} md={24} lg={14} xl={14}>
  280. <Form.Slot label={t('选择支付方式')}>
  281. {payMethods && payMethods.length > 0 ? (
  282. <Space wrap>
  283. {payMethods.map((payMethod) => {
  284. const minTopupVal = Number(payMethod.min_topup) || 0;
  285. const isStripe = payMethod.type === 'stripe';
  286. const disabled =
  287. (!enableOnlineTopUp && !isStripe) ||
  288. (!enableStripeTopUp && isStripe) ||
  289. minTopupVal > Number(topUpCount || 0);
  290. const buttonEl = (
  291. <Button
  292. key={payMethod.type}
  293. theme='outline'
  294. type='tertiary'
  295. onClick={() => preTopUp(payMethod.type)}
  296. disabled={disabled}
  297. loading={
  298. paymentLoading && payWay === payMethod.type
  299. }
  300. icon={
  301. payMethod.type === 'alipay' ? (
  302. <SiAlipay size={18} color='#1677FF' />
  303. ) : payMethod.type === 'wxpay' ? (
  304. <SiWechat size={18} color='#07C160' />
  305. ) : payMethod.type === 'stripe' ? (
  306. <SiStripe size={18} color='#635BFF' />
  307. ) : (
  308. <CreditCard
  309. size={18}
  310. color={
  311. payMethod.color ||
  312. 'var(--semi-color-text-2)'
  313. }
  314. />
  315. )
  316. }
  317. className='!rounded-lg !px-4 !py-2'
  318. >
  319. {payMethod.name}
  320. </Button>
  321. );
  322. return disabled &&
  323. minTopupVal > Number(topUpCount || 0) ? (
  324. <Tooltip
  325. content={
  326. t('此支付方式最低充值金额为') +
  327. ' ' +
  328. minTopupVal
  329. }
  330. key={payMethod.type}
  331. >
  332. {buttonEl}
  333. </Tooltip>
  334. ) : (
  335. <React.Fragment key={payMethod.type}>
  336. {buttonEl}
  337. </React.Fragment>
  338. );
  339. })}
  340. </Space>
  341. ) : (
  342. <div className='text-gray-500 text-sm p-3 bg-gray-50 rounded-lg border border-dashed border-gray-300'>
  343. {t('暂无可用的支付方式,请联系管理员配置')}
  344. </div>
  345. )}
  346. </Form.Slot>
  347. </Col>
  348. </Row>
  349. )}
  350. {(enableOnlineTopUp || enableStripeTopUp) && (
  351. <Form.Slot
  352. label={
  353. <div className='flex items-center gap-2'>
  354. <span>{t('选择充值额度')}</span>
  355. {(() => {
  356. const { symbol, rate, type } = getCurrencyConfig();
  357. if (type === 'USD') return null;
  358. return (
  359. <span
  360. style={{
  361. color: 'var(--semi-color-text-2)',
  362. fontSize: '12px',
  363. fontWeight: 'normal',
  364. }}
  365. >
  366. (1 $ = {rate.toFixed(2)} {symbol})
  367. </span>
  368. );
  369. })()}
  370. </div>
  371. }
  372. >
  373. <div className='grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2'>
  374. {presetAmounts.map((preset, index) => {
  375. const discount =
  376. preset.discount || topupInfo?.discount?.[preset.value] || 1.0;
  377. const originalPrice = preset.value * priceRatio;
  378. const discountedPrice = originalPrice * discount;
  379. const hasDiscount = discount < 1.0;
  380. const actualPay = discountedPrice;
  381. const save = originalPrice - discountedPrice;
  382. // 根据当前货币类型换算显示金额和数量
  383. const { symbol, rate, type } = getCurrencyConfig();
  384. const statusStr = localStorage.getItem('status');
  385. let usdRate = 7; // 默认CNY汇率
  386. try {
  387. if (statusStr) {
  388. const s = JSON.parse(statusStr);
  389. usdRate = s?.usd_exchange_rate || 7;
  390. }
  391. } catch (e) { }
  392. let displayValue = preset.value; // 显示的数量
  393. let displayActualPay = actualPay;
  394. let displaySave = save;
  395. if (type === 'USD') {
  396. // 数量保持USD,价格从CNY转USD
  397. displayActualPay = actualPay / usdRate;
  398. displaySave = save / usdRate;
  399. } else if (type === 'CNY') {
  400. // 数量转CNY,价格已是CNY
  401. displayValue = preset.value * usdRate;
  402. } else if (type === 'CUSTOM') {
  403. // 数量和价格都转自定义货币
  404. displayValue = preset.value * rate;
  405. displayActualPay = (actualPay / usdRate) * rate;
  406. displaySave = (save / usdRate) * rate;
  407. }
  408. return (
  409. <Card
  410. key={index}
  411. style={{
  412. cursor: 'pointer',
  413. border:
  414. selectedPreset === preset.value
  415. ? '2px solid var(--semi-color-primary)'
  416. : '1px solid var(--semi-color-border)',
  417. height: '100%',
  418. width: '100%',
  419. }}
  420. bodyStyle={{ padding: '12px' }}
  421. onClick={() => {
  422. selectPresetAmount(preset);
  423. onlineFormApiRef.current?.setValue(
  424. 'topUpCount',
  425. preset.value,
  426. );
  427. }}
  428. >
  429. <div style={{ textAlign: 'center' }}>
  430. <Typography.Title
  431. heading={6}
  432. style={{ margin: '0 0 8px 0' }}
  433. >
  434. <Coins size={18} />
  435. {formatLargeNumber(displayValue)} {symbol}
  436. {hasDiscount && (
  437. <Tag style={{ marginLeft: 4 }} color='green'>
  438. {t('折').includes('off')
  439. ? ((1 - parseFloat(discount)) * 100).toFixed(1)
  440. : (discount * 10).toFixed(1)}
  441. {t('折')}
  442. </Tag>
  443. )}
  444. </Typography.Title>
  445. <div
  446. style={{
  447. color: 'var(--semi-color-text-2)',
  448. fontSize: '12px',
  449. margin: '4px 0',
  450. }}
  451. >
  452. {t('实付')} {symbol}
  453. {displayActualPay.toFixed(2)},
  454. {hasDiscount
  455. ? `${t('节省')} ${symbol}${displaySave.toFixed(2)}`
  456. : `${t('节省')} ${symbol}0.00`}
  457. </div>
  458. </div>
  459. </Card>
  460. );
  461. })}
  462. </div>
  463. </Form.Slot>
  464. )}
  465. {/* Creem 充值区域 */}
  466. {enableCreemTopUp && creemProducts.length > 0 && (
  467. <Form.Slot label={t('Creem 充值')}>
  468. <div className='grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3'>
  469. {creemProducts.map((product, index) => (
  470. <Card
  471. key={index}
  472. onClick={() => creemPreTopUp(product)}
  473. className='cursor-pointer !rounded-2xl transition-all hover:shadow-md border-gray-200 hover:border-gray-300'
  474. bodyStyle={{ textAlign: 'center', padding: '16px' }}
  475. >
  476. <div className='font-medium text-lg mb-2'>
  477. {product.name}
  478. </div>
  479. <div className='text-sm text-gray-600 mb-2'>
  480. {t('充值额度')}: {product.quota}
  481. </div>
  482. <div className='text-lg font-semibold text-blue-600'>
  483. {product.currency === 'EUR' ? '€' : '$'}
  484. {product.price}
  485. </div>
  486. </Card>
  487. ))}
  488. </div>
  489. </Form.Slot>
  490. )}
  491. </div>
  492. </Form>
  493. ) : (
  494. <Banner
  495. type='info'
  496. description={t(
  497. '管理员未开启在线充值功能,请联系管理员开启或使用兑换码充值。',
  498. )}
  499. className='!rounded-xl'
  500. closeIcon={null}
  501. />
  502. )}
  503. </Card>
  504. {/* 兑换码充值 */}
  505. <Card
  506. className='!rounded-xl w-full'
  507. title={
  508. <Text type='tertiary' strong>
  509. {t('兑换码充值')}
  510. </Text>
  511. }
  512. >
  513. <Form
  514. getFormApi={(api) => (redeemFormApiRef.current = api)}
  515. initValues={{ redemptionCode: redemptionCode }}
  516. >
  517. <Form.Input
  518. field='redemptionCode'
  519. noLabel={true}
  520. placeholder={t('请输入兑换码')}
  521. value={redemptionCode}
  522. onChange={(value) => setRedemptionCode(value)}
  523. prefix={<IconGift />}
  524. suffix={
  525. <div className='flex items-center gap-2'>
  526. <Button
  527. type='primary'
  528. theme='solid'
  529. onClick={topUp}
  530. loading={isSubmitting}
  531. >
  532. {t('兑换额度')}
  533. </Button>
  534. </div>
  535. }
  536. showClear
  537. style={{ width: '100%' }}
  538. extraText={
  539. topUpLink && (
  540. <Text type='tertiary'>
  541. {t('在找兑换码?')}
  542. <Text
  543. type='secondary'
  544. underline
  545. className='cursor-pointer'
  546. onClick={openTopUpLink}
  547. >
  548. {t('购买兑换码')}
  549. </Text>
  550. </Text>
  551. )
  552. }
  553. />
  554. </Form>
  555. </Card>
  556. </Space>
  557. );
  558. return (
  559. <Card className='!rounded-2xl shadow-sm border-0'>
  560. {/* 卡片头部 */}
  561. <div className='flex items-center justify-between mb-4'>
  562. <div className='flex items-center'>
  563. <Avatar size='small' color='blue' className='mr-3 shadow-md'>
  564. <CreditCard size={16} />
  565. </Avatar>
  566. <div>
  567. <Typography.Text className='text-lg font-medium'>
  568. {t('账户充值')}
  569. </Typography.Text>
  570. <div className='text-xs'>{t('多种充值方式,安全便捷')}</div>
  571. </div>
  572. </div>
  573. <Button
  574. icon={<Receipt size={16} />}
  575. theme='solid'
  576. onClick={onOpenHistory}
  577. >
  578. {t('账单')}
  579. </Button>
  580. </div>
  581. {shouldShowSubscription ? (
  582. <Tabs type='card' activeKey={activeTab} onChange={setActiveTab}>
  583. <TabPane
  584. tab={
  585. <div className='flex items-center gap-2'>
  586. <Sparkles size={16} />
  587. {t('订阅套餐')}
  588. </div>
  589. }
  590. itemKey='subscription'
  591. >
  592. <div className='py-2'>
  593. <SubscriptionPlansCard
  594. t={t}
  595. loading={subscriptionLoading}
  596. plans={subscriptionPlans}
  597. payMethods={payMethods}
  598. enableOnlineTopUp={enableOnlineTopUp}
  599. enableStripeTopUp={enableStripeTopUp}
  600. enableCreemTopUp={enableCreemTopUp}
  601. billingPreference={billingPreference}
  602. onChangeBillingPreference={onChangeBillingPreference}
  603. activeSubscriptions={activeSubscriptions}
  604. allSubscriptions={allSubscriptions}
  605. reloadSubscriptionSelf={reloadSubscriptionSelf}
  606. withCard={false}
  607. />
  608. </div>
  609. </TabPane>
  610. <TabPane
  611. tab={
  612. <div className='flex items-center gap-2'>
  613. <Wallet size={16} />
  614. {t('额度充值')}
  615. </div>
  616. }
  617. itemKey='topup'
  618. >
  619. <div className='py-2'>{topupContent}</div>
  620. </TabPane>
  621. </Tabs>
  622. ) : (
  623. topupContent
  624. )}
  625. </Card>
  626. );
  627. };
  628. export default RechargeCard;