RedemptionsTable.js 17 KB

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