RechargeCard.jsx 26 KB

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