RedemptionsTable.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. import React, { useEffect, useState } from 'react';
  2. import {
  3. API,
  4. copy,
  5. showError,
  6. showSuccess,
  7. timestamp2string,
  8. renderQuota
  9. } from '../../helpers';
  10. import { Ticket } from 'lucide-react';
  11. import { ITEMS_PER_PAGE } from '../../constants';
  12. import {
  13. Button,
  14. Card,
  15. Divider,
  16. Dropdown,
  17. Empty,
  18. Form,
  19. Modal,
  20. Popover,
  21. Space,
  22. Table,
  23. Tag,
  24. Typography
  25. } from '@douyinfe/semi-ui';
  26. import {
  27. IllustrationNoResult,
  28. IllustrationNoResultDark
  29. } from '@douyinfe/semi-illustrations';
  30. import {
  31. IconSearch,
  32. IconMore,
  33. } from '@douyinfe/semi-icons';
  34. import EditRedemption from '../../pages/Redemption/EditRedemption';
  35. import { useTranslation } from 'react-i18next';
  36. import { useTableCompactMode } from '../../hooks/useTableCompactMode';
  37. const { Text } = Typography;
  38. function renderTimestamp(timestamp) {
  39. return <>{timestamp2string(timestamp)}</>;
  40. }
  41. const RedemptionsTable = () => {
  42. const { t } = useTranslation();
  43. const isExpired = (rec) => {
  44. return rec.status === 1 && rec.expired_time !== 0 && rec.expired_time < Math.floor(Date.now() / 1000);
  45. };
  46. const renderStatus = (status, record) => {
  47. if (isExpired(record)) {
  48. return (
  49. <Tag color='orange' size='large' shape='circle'>{t('已过期')}</Tag>
  50. );
  51. }
  52. switch (status) {
  53. case 1:
  54. return (
  55. <Tag color='green' size='large' shape='circle'>
  56. {t('未使用')}
  57. </Tag>
  58. );
  59. case 2:
  60. return (
  61. <Tag color='red' size='large' shape='circle'>
  62. {t('已禁用')}
  63. </Tag>
  64. );
  65. case 3:
  66. return (
  67. <Tag color='grey' size='large' shape='circle'>
  68. {t('已使用')}
  69. </Tag>
  70. );
  71. default:
  72. return (
  73. <Tag color='black' size='large' shape='circle'>
  74. {t('未知状态')}
  75. </Tag>
  76. );
  77. }
  78. };
  79. const columns = [
  80. {
  81. title: t('ID'),
  82. dataIndex: 'id',
  83. },
  84. {
  85. title: t('名称'),
  86. dataIndex: 'name',
  87. },
  88. {
  89. title: t('状态'),
  90. dataIndex: 'status',
  91. key: 'status',
  92. render: (text, record, index) => {
  93. return <div>{renderStatus(text, record)}</div>;
  94. },
  95. },
  96. {
  97. title: t('额度'),
  98. dataIndex: 'quota',
  99. render: (text, record, index) => {
  100. return (
  101. <div>
  102. <Tag size={'large'} color={'grey'} shape='circle'>
  103. {renderQuota(parseInt(text))}
  104. </Tag>
  105. </div>
  106. );
  107. },
  108. },
  109. {
  110. title: t('创建时间'),
  111. dataIndex: 'created_time',
  112. render: (text, record, index) => {
  113. return <div>{renderTimestamp(text)}</div>;
  114. },
  115. },
  116. {
  117. title: t('过期时间'),
  118. dataIndex: 'expired_time',
  119. render: (text) => {
  120. return <div>{text === 0 ? t('永不过期') : renderTimestamp(text)}</div>;
  121. },
  122. },
  123. {
  124. title: t('兑换人ID'),
  125. dataIndex: 'used_user_id',
  126. render: (text, record, index) => {
  127. return <div>{text === 0 ? t('无') : text}</div>;
  128. },
  129. },
  130. {
  131. title: '',
  132. dataIndex: 'operate',
  133. fixed: 'right',
  134. render: (text, record, index) => {
  135. // 创建更多操作的下拉菜单项
  136. const moreMenuItems = [
  137. {
  138. node: 'item',
  139. name: t('删除'),
  140. type: 'danger',
  141. onClick: () => {
  142. Modal.confirm({
  143. title: t('确定是否要删除此兑换码?'),
  144. content: t('此修改将不可逆'),
  145. onOk: () => {
  146. manageRedemption(record.id, 'delete', record).then(() => {
  147. removeRecord(record.key);
  148. });
  149. },
  150. });
  151. },
  152. }
  153. ];
  154. if (record.status === 1 && !isExpired(record)) {
  155. moreMenuItems.push({
  156. node: 'item',
  157. name: t('禁用'),
  158. type: 'warning',
  159. onClick: () => {
  160. manageRedemption(record.id, 'disable', record);
  161. },
  162. });
  163. } else if (!isExpired(record)) {
  164. moreMenuItems.push({
  165. node: 'item',
  166. name: t('启用'),
  167. type: 'secondary',
  168. onClick: () => {
  169. manageRedemption(record.id, 'enable', record);
  170. },
  171. disabled: record.status === 3,
  172. });
  173. }
  174. return (
  175. <Space>
  176. <Popover content={record.key} style={{ padding: 20 }} position='top'>
  177. <Button
  178. theme='light'
  179. type='tertiary'
  180. size="small"
  181. >
  182. {t('查看')}
  183. </Button>
  184. </Popover>
  185. <Button
  186. theme='light'
  187. type='secondary'
  188. size="small"
  189. onClick={async () => {
  190. await copyText(record.key);
  191. }}
  192. >
  193. {t('复制')}
  194. </Button>
  195. <Button
  196. theme='light'
  197. type='tertiary'
  198. size="small"
  199. onClick={() => {
  200. setEditingRedemption(record);
  201. setShowEdit(true);
  202. }}
  203. disabled={record.status !== 1}
  204. >
  205. {t('编辑')}
  206. </Button>
  207. <Dropdown
  208. trigger='click'
  209. position='bottomRight'
  210. menu={moreMenuItems}
  211. >
  212. <Button
  213. theme='light'
  214. type='tertiary'
  215. size="small"
  216. icon={<IconMore />}
  217. />
  218. </Dropdown>
  219. </Space>
  220. );
  221. },
  222. },
  223. ];
  224. const [redemptions, setRedemptions] = useState([]);
  225. const [loading, setLoading] = useState(true);
  226. const [activePage, setActivePage] = useState(1);
  227. const [searching, setSearching] = useState(false);
  228. const [tokenCount, setTokenCount] = useState(ITEMS_PER_PAGE);
  229. const [selectedKeys, setSelectedKeys] = useState([]);
  230. const [pageSize, setPageSize] = useState(ITEMS_PER_PAGE);
  231. const [editingRedemption, setEditingRedemption] = useState({
  232. id: undefined,
  233. });
  234. const [showEdit, setShowEdit] = useState(false);
  235. const [compactMode, setCompactMode] = useTableCompactMode('redemptions');
  236. const formInitValues = {
  237. searchKeyword: '',
  238. };
  239. const [formApi, setFormApi] = useState(null);
  240. const getFormValues = () => {
  241. const formValues = formApi ? formApi.getValues() : {};
  242. return {
  243. searchKeyword: formValues.searchKeyword || '',
  244. };
  245. };
  246. const closeEdit = () => {
  247. setShowEdit(false);
  248. setTimeout(() => {
  249. setEditingRedemption({
  250. id: undefined,
  251. });
  252. }, 500);
  253. };
  254. const setRedemptionFormat = (redeptions) => {
  255. setRedemptions(redeptions);
  256. };
  257. const loadRedemptions = async (page = 1, pageSize) => {
  258. setLoading(true);
  259. const res = await API.get(
  260. `/api/redemption/?p=${page}&page_size=${pageSize}`,
  261. );
  262. const { success, message, data } = res.data;
  263. if (success) {
  264. const newPageData = data.items;
  265. setActivePage(data.page <= 0 ? 1 : data.page);
  266. setTokenCount(data.total);
  267. setRedemptionFormat(newPageData);
  268. } else {
  269. showError(message);
  270. }
  271. setLoading(false);
  272. };
  273. const removeRecord = (key) => {
  274. let newDataSource = [...redemptions];
  275. if (key != null) {
  276. let idx = newDataSource.findIndex((data) => data.key === key);
  277. if (idx > -1) {
  278. newDataSource.splice(idx, 1);
  279. setRedemptions(newDataSource);
  280. }
  281. }
  282. };
  283. const copyText = async (text) => {
  284. if (await copy(text)) {
  285. showSuccess(t('已复制到剪贴板!'));
  286. } else {
  287. Modal.error({
  288. title: t('无法复制到剪贴板,请手动复制'),
  289. content: text,
  290. size: 'large'
  291. });
  292. }
  293. };
  294. useEffect(() => {
  295. loadRedemptions(1, pageSize)
  296. .then()
  297. .catch((reason) => {
  298. showError(reason);
  299. });
  300. }, [pageSize]);
  301. const refresh = async () => {
  302. await loadRedemptions(activePage - 1, pageSize);
  303. };
  304. const manageRedemption = async (id, action, record) => {
  305. setLoading(true);
  306. let data = { id };
  307. let res;
  308. switch (action) {
  309. case 'delete':
  310. res = await API.delete(`/api/redemption/${id}/`);
  311. break;
  312. case 'enable':
  313. data.status = 1;
  314. res = await API.put('/api/redemption/?status_only=true', data);
  315. break;
  316. case 'disable':
  317. data.status = 2;
  318. res = await API.put('/api/redemption/?status_only=true', data);
  319. break;
  320. }
  321. const { success, message } = res.data;
  322. if (success) {
  323. showSuccess(t('操作成功完成!'));
  324. let redemption = res.data.data;
  325. let newRedemptions = [...redemptions];
  326. if (action === 'delete') {
  327. } else {
  328. record.status = redemption.status;
  329. }
  330. setRedemptions(newRedemptions);
  331. } else {
  332. showError(message);
  333. }
  334. setLoading(false);
  335. };
  336. const searchRedemptions = async (keyword = null, page, pageSize) => {
  337. // 如果没有传递keyword参数,从表单获取值
  338. if (keyword === null) {
  339. const formValues = getFormValues();
  340. keyword = formValues.searchKeyword;
  341. }
  342. if (keyword === '') {
  343. await loadRedemptions(page, pageSize);
  344. return;
  345. }
  346. setSearching(true);
  347. const res = await API.get(
  348. `/api/redemption/search?keyword=${keyword}&p=${page}&page_size=${pageSize}`,
  349. );
  350. const { success, message, data } = res.data;
  351. if (success) {
  352. const newPageData = data.items;
  353. setActivePage(data.page);
  354. setTokenCount(data.total);
  355. setRedemptionFormat(newPageData);
  356. } else {
  357. showError(message);
  358. }
  359. setSearching(false);
  360. };
  361. const handlePageChange = (page) => {
  362. setActivePage(page);
  363. const { searchKeyword } = getFormValues();
  364. if (searchKeyword === '') {
  365. loadRedemptions(page, pageSize).then();
  366. } else {
  367. searchRedemptions(searchKeyword, page, pageSize).then();
  368. }
  369. };
  370. let pageData = redemptions;
  371. const rowSelection = {
  372. onSelect: (record, selected) => { },
  373. onSelectAll: (selected, selectedRows) => { },
  374. onChange: (selectedRowKeys, selectedRows) => {
  375. setSelectedKeys(selectedRows);
  376. },
  377. };
  378. const handleRow = (record, index) => {
  379. if (record.status !== 1 || isExpired(record)) {
  380. return {
  381. style: {
  382. background: 'var(--semi-color-disabled-border)',
  383. },
  384. };
  385. } else {
  386. return {};
  387. }
  388. };
  389. const renderHeader = () => (
  390. <div className="flex flex-col w-full">
  391. <div className="mb-2">
  392. <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-2 w-full">
  393. <div className="flex items-center text-orange-500">
  394. <Ticket size={16} className="mr-2" />
  395. <Text>{t('兑换码可以批量生成和分发,适合用于推广活动或批量充值。')}</Text>
  396. </div>
  397. <Button
  398. theme='light'
  399. type='secondary'
  400. className="w-full md:w-auto"
  401. onClick={() => setCompactMode(!compactMode)}
  402. >
  403. {compactMode ? t('自适应列表') : t('紧凑列表')}
  404. </Button>
  405. </div>
  406. </div>
  407. <Divider margin="12px" />
  408. <div className="flex flex-col md:flex-row justify-between items-center gap-4 w-full">
  409. <div className="flex flex-col sm:flex-row gap-2 w-full md:w-auto order-2 md:order-1">
  410. <div className="flex gap-2 w-full sm:w-auto">
  411. <Button
  412. theme='light'
  413. type='primary'
  414. className="w-full sm:w-auto"
  415. onClick={() => {
  416. setEditingRedemption({
  417. id: undefined,
  418. });
  419. setShowEdit(true);
  420. }}
  421. >
  422. {t('添加兑换码')}
  423. </Button>
  424. <Button
  425. type='warning'
  426. className="w-full sm:w-auto"
  427. onClick={async () => {
  428. if (selectedKeys.length === 0) {
  429. showError(t('请至少选择一个兑换码!'));
  430. return;
  431. }
  432. let keys = '';
  433. for (let i = 0; i < selectedKeys.length; i++) {
  434. keys +=
  435. selectedKeys[i].name + ' ' + selectedKeys[i].key + '\n';
  436. }
  437. await copyText(keys);
  438. }}
  439. >
  440. {t('复制所选兑换码到剪贴板')}
  441. </Button>
  442. </div>
  443. <Button
  444. type='danger'
  445. className="w-full sm:w-auto"
  446. onClick={() => {
  447. Modal.confirm({
  448. title: t('确定清除所有失效兑换码?'),
  449. content: t('将删除已使用、已禁用及过期的兑换码,此操作不可撤销。'),
  450. onOk: async () => {
  451. setLoading(true);
  452. const res = await API.delete('/api/redemption/invalid');
  453. const { success, message, data } = res.data;
  454. if (success) {
  455. showSuccess(t('已删除 {{count}} 条失效兑换码', { count: data }));
  456. await refresh();
  457. } else {
  458. showError(message);
  459. }
  460. setLoading(false);
  461. },
  462. });
  463. }}
  464. >
  465. {t('清除失效兑换码')}
  466. </Button>
  467. </div>
  468. <Form
  469. initValues={formInitValues}
  470. getFormApi={(api) => setFormApi(api)}
  471. onSubmit={() => {
  472. setActivePage(1);
  473. searchRedemptions(null, 1, pageSize);
  474. }}
  475. allowEmpty={true}
  476. autoComplete="off"
  477. layout="horizontal"
  478. trigger="change"
  479. stopValidateWithError={false}
  480. className="w-full md:w-auto order-1 md:order-2"
  481. >
  482. <div className="flex flex-col md:flex-row items-center gap-4 w-full md:w-auto">
  483. <div className="relative w-full md:w-64">
  484. <Form.Input
  485. field="searchKeyword"
  486. prefix={<IconSearch />}
  487. placeholder={t('关键字(id或者名称)')}
  488. showClear
  489. pure
  490. />
  491. </div>
  492. <div className="flex gap-2 w-full md:w-auto">
  493. <Button
  494. type="primary"
  495. htmlType="submit"
  496. loading={loading || searching}
  497. className="flex-1 md:flex-initial md:w-auto"
  498. >
  499. {t('查询')}
  500. </Button>
  501. <Button
  502. theme="light"
  503. onClick={() => {
  504. if (formApi) {
  505. formApi.reset();
  506. // 重置后立即查询,使用setTimeout确保表单重置完成
  507. setTimeout(() => {
  508. setActivePage(1);
  509. loadRedemptions(1, pageSize);
  510. }, 100);
  511. }
  512. }}
  513. className="flex-1 md:flex-initial md:w-auto"
  514. >
  515. {t('重置')}
  516. </Button>
  517. </div>
  518. </div>
  519. </Form>
  520. </div>
  521. </div>
  522. );
  523. return (
  524. <>
  525. <EditRedemption
  526. refresh={refresh}
  527. editingRedemption={editingRedemption}
  528. visiable={showEdit}
  529. handleClose={closeEdit}
  530. ></EditRedemption>
  531. <Card
  532. className="!rounded-2xl"
  533. title={renderHeader()}
  534. shadows='always'
  535. bordered={false}
  536. >
  537. <Table
  538. columns={compactMode ? columns.map(({ fixed, ...rest }) => rest) : columns}
  539. dataSource={pageData}
  540. scroll={compactMode ? undefined : { x: 'max-content' }}
  541. pagination={{
  542. currentPage: activePage,
  543. pageSize: pageSize,
  544. total: tokenCount,
  545. showSizeChanger: true,
  546. pageSizeOptions: [10, 20, 50, 100],
  547. formatPageText: (page) =>
  548. t('第 {{start}} - {{end}} 条,共 {{total}} 条', {
  549. start: page.currentStart,
  550. end: page.currentEnd,
  551. total: tokenCount,
  552. }),
  553. onPageSizeChange: (size) => {
  554. setPageSize(size);
  555. setActivePage(1);
  556. const { searchKeyword } = getFormValues();
  557. if (searchKeyword === '') {
  558. loadRedemptions(1, size).then();
  559. } else {
  560. searchRedemptions(searchKeyword, 1, size).then();
  561. }
  562. },
  563. onPageChange: handlePageChange,
  564. }}
  565. loading={loading}
  566. rowSelection={rowSelection}
  567. onRow={handleRow}
  568. empty={
  569. <Empty
  570. image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
  571. darkModeImage={<IllustrationNoResultDark style={{ width: 150, height: 150 }} />}
  572. description={t('搜索无结果')}
  573. style={{ padding: 30 }}
  574. />
  575. }
  576. className="rounded-xl overflow-hidden"
  577. size="middle"
  578. ></Table>
  579. </Card>
  580. </>
  581. );
  582. };
  583. export default RedemptionsTable;