♻️ refactor(components): restructure RedemptionsTable to modular architecture

Refactor the monolithic RedemptionsTable component (614 lines) into a clean,
modular structure following the established tokens component pattern.

### Changes Made:

**New Components:**
- `RedemptionsColumnDefs.js` - Extract table column definitions and render logic
- `RedemptionsActions.jsx` - Extract action buttons (add, batch copy, clear invalid)
- `RedemptionsFilters.jsx` - Extract search and filter form components
- `RedemptionsDescription.jsx` - Extract description area component
- `redemptions/index.jsx` - Main container component managing state and composition

**New Hook:**
- `useRedemptionsData.js` - Extract all data management, CRUD operations, and business logic

**New Constants:**
- `redemption.constants.js` - Extract redemption status, actions, and form constants

**Architecture Changes:**
- Transform RedemptionsTable.jsx into pure table rendering component
- Move state management and component composition to index.jsx
- Implement consistent prop drilling pattern matching tokens module
- Add memoization for performance optimization
- Centralize translation function distribution

### Benefits:
- **Maintainability**: Each component has single responsibility
- **Reusability**: Components and hooks can be used elsewhere
- **Testability**: Individual modules can be unit tested
- **Team Collaboration**: Multiple developers can work on different modules
- **Consistency**: Follows established architectural patterns

### File Structure:
```
redemptions/
├── index.jsx                    # Main container (state + composition)
├── RedemptionsTable.jsx        # Pure table component
├── RedemptionsActions.jsx      # Action buttons
├── RedemptionsFilters.jsx      # Search/filter form
├── RedemptionsDescription.jsx  # Description area
└── RedemptionsColumnDefs.js    # Column definitions
This commit is contained in:
t0ng7u
2025-07-19 00:12:04 +08:00
parent 67df60e76c
commit 1e0b56ac51
19 changed files with 1117 additions and 730 deletions

View File

@@ -0,0 +1,53 @@
import React from 'react';
import { Button } from '@douyinfe/semi-ui';
const RedemptionsActions = ({
selectedKeys,
setEditingRedemption,
setShowEdit,
batchCopyRedemptions,
batchDeleteRedemptions,
t
}) => {
// Add new redemption code
const handleAddRedemption = () => {
setEditingRedemption({
id: undefined,
});
setShowEdit(true);
};
return (
<div className="flex flex-wrap gap-2 w-full md:w-auto order-2 md:order-1">
<Button
type="primary"
className="flex-1 md:flex-initial"
onClick={handleAddRedemption}
size="small"
>
{t('添加兑换码')}
</Button>
<Button
type='tertiary'
className="flex-1 md:flex-initial"
onClick={batchCopyRedemptions}
size="small"
>
{t('复制所选兑换码到剪贴板')}
</Button>
<Button
type='danger'
className="w-full md:w-auto"
onClick={batchDeleteRedemptions}
size="small"
>
{t('清除失效兑换码')}
</Button>
</div>
);
};
export default RedemptionsActions;

View File

@@ -0,0 +1,198 @@
import React from 'react';
import { Tag, Button, Space, Popover, Dropdown } from '@douyinfe/semi-ui';
import { IconMore } from '@douyinfe/semi-icons';
import { renderQuota, timestamp2string } from '../../../helpers';
import { REDEMPTION_STATUS, REDEMPTION_STATUS_MAP, REDEMPTION_ACTIONS } from '../../../constants/redemption.constants';
/**
* Check if redemption code is expired
*/
export const isExpired = (record) => {
return record.status === REDEMPTION_STATUS.UNUSED &&
record.expired_time !== 0 &&
record.expired_time < Math.floor(Date.now() / 1000);
};
/**
* Render timestamp
*/
const renderTimestamp = (timestamp) => {
return <>{timestamp2string(timestamp)}</>;
};
/**
* Render redemption code status
*/
const renderStatus = (status, record, t) => {
if (isExpired(record)) {
return (
<Tag color='orange' shape='circle'>{t('已过期')}</Tag>
);
}
const statusConfig = REDEMPTION_STATUS_MAP[status];
if (statusConfig) {
return (
<Tag color={statusConfig.color} shape='circle'>
{t(statusConfig.text)}
</Tag>
);
}
return (
<Tag color='black' shape='circle'>
{t('未知状态')}
</Tag>
);
};
/**
* Get redemption code table column definitions
*/
export const getRedemptionsColumns = ({
t,
manageRedemption,
copyText,
setEditingRedemption,
setShowEdit,
refresh,
redemptions,
activePage,
showDeleteRedemptionModal
}) => {
return [
{
title: t('ID'),
dataIndex: 'id',
},
{
title: t('名称'),
dataIndex: 'name',
},
{
title: t('状态'),
dataIndex: 'status',
key: 'status',
render: (text, record) => {
return <div>{renderStatus(text, record, t)}</div>;
},
},
{
title: t('额度'),
dataIndex: 'quota',
render: (text) => {
return (
<div>
<Tag color='grey' shape='circle'>
{renderQuota(parseInt(text))}
</Tag>
</div>
);
},
},
{
title: t('创建时间'),
dataIndex: 'created_time',
render: (text) => {
return <div>{renderTimestamp(text)}</div>;
},
},
{
title: t('过期时间'),
dataIndex: 'expired_time',
render: (text) => {
return <div>{text === 0 ? t('永不过期') : renderTimestamp(text)}</div>;
},
},
{
title: t('兑换人ID'),
dataIndex: 'used_user_id',
render: (text) => {
return <div>{text === 0 ? t('无') : text}</div>;
},
},
{
title: '',
dataIndex: 'operate',
fixed: 'right',
width: 205,
render: (text, record) => {
// Create dropdown menu items for more operations
const moreMenuItems = [
{
node: 'item',
name: t('删除'),
type: 'danger',
onClick: () => {
showDeleteRedemptionModal(record);
},
}
];
if (record.status === REDEMPTION_STATUS.UNUSED && !isExpired(record)) {
moreMenuItems.push({
node: 'item',
name: t('禁用'),
type: 'warning',
onClick: () => {
manageRedemption(record.id, REDEMPTION_ACTIONS.DISABLE, record);
},
});
} else if (!isExpired(record)) {
moreMenuItems.push({
node: 'item',
name: t('启用'),
type: 'secondary',
onClick: () => {
manageRedemption(record.id, REDEMPTION_ACTIONS.ENABLE, record);
},
disabled: record.status === REDEMPTION_STATUS.USED,
});
}
return (
<Space>
<Popover content={record.key} style={{ padding: 20 }} position='top'>
<Button
type='tertiary'
size="small"
>
{t('查看')}
</Button>
</Popover>
<Button
size="small"
onClick={async () => {
await copyText(record.key);
}}
>
{t('复制')}
</Button>
<Button
type='tertiary'
size="small"
onClick={() => {
setEditingRedemption(record);
setShowEdit(true);
}}
disabled={record.status !== REDEMPTION_STATUS.UNUSED}
>
{t('编辑')}
</Button>
<Dropdown
trigger='click'
position='bottomRight'
menu={moreMenuItems}
>
<Button
type='tertiary'
size="small"
icon={<IconMore />}
/>
</Dropdown>
</Space>
);
},
},
];
};

View File

@@ -0,0 +1,27 @@
import React from 'react';
import { Button, Typography } from '@douyinfe/semi-ui';
import { Ticket } from 'lucide-react';
const { Text } = Typography;
const RedemptionsDescription = ({ compactMode, setCompactMode, t }) => {
return (
<div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-2 w-full">
<div className="flex items-center text-orange-500">
<Ticket size={16} className="mr-2" />
<Text>{t('兑换码可以批量生成和分发,适合用于推广活动或批量充值。')}</Text>
</div>
<Button
type="tertiary"
className="w-full md:w-auto"
onClick={() => setCompactMode(!compactMode)}
size="small"
>
{compactMode ? t('自适应列表') : t('紧凑列表')}
</Button>
</div>
);
};
export default RedemptionsDescription;

View File

@@ -0,0 +1,72 @@
import React from 'react';
import { Form, Button } from '@douyinfe/semi-ui';
import { IconSearch } from '@douyinfe/semi-icons';
const RedemptionsFilters = ({
formInitValues,
setFormApi,
searchRedemptions,
loading,
searching,
t
}) => {
// Handle form reset and immediate search
const handleReset = (formApi) => {
if (formApi) {
formApi.reset();
// Reset and search immediately
setTimeout(() => {
searchRedemptions();
}, 100);
}
};
return (
<Form
initValues={formInitValues}
getFormApi={(api) => setFormApi(api)}
onSubmit={searchRedemptions}
allowEmpty={true}
autoComplete="off"
layout="horizontal"
trigger="change"
stopValidateWithError={false}
className="w-full md:w-auto order-1 md:order-2"
>
<div className="flex flex-col md:flex-row items-center gap-2 w-full md:w-auto">
<div className="relative w-full md:w-64">
<Form.Input
field="searchKeyword"
prefix={<IconSearch />}
placeholder={t('关键字(id或者名称)')}
showClear
pure
size="small"
/>
</div>
<div className="flex gap-2 w-full md:w-auto">
<Button
type="tertiary"
htmlType="submit"
loading={loading || searching}
className="flex-1 md:flex-initial md:w-auto"
size="small"
>
{t('查询')}
</Button>
<Button
type="tertiary"
onClick={(_, formApi) => handleReset(formApi)}
className="flex-1 md:flex-initial md:w-auto"
size="small"
>
{t('重置')}
</Button>
</div>
</div>
</Form>
);
};
export default RedemptionsFilters;

View File

@@ -0,0 +1,119 @@
import React, { useMemo, useState } from 'react';
import { Table, Empty } from '@douyinfe/semi-ui';
import {
IllustrationNoResult,
IllustrationNoResultDark
} from '@douyinfe/semi-illustrations';
import { getRedemptionsColumns, isExpired } from './RedemptionsColumnDefs';
import DeleteRedemptionModal from './modals/DeleteRedemptionModal';
const RedemptionsTable = (redemptionsData) => {
const {
redemptions,
loading,
activePage,
pageSize,
tokenCount,
compactMode,
handlePageChange,
rowSelection,
handleRow,
manageRedemption,
copyText,
setEditingRedemption,
setShowEdit,
refresh,
t,
} = redemptionsData;
// Modal states
const [showDeleteModal, setShowDeleteModal] = useState(false);
const [deletingRecord, setDeletingRecord] = useState(null);
// Handle show delete modal
const showDeleteRedemptionModal = (record) => {
setDeletingRecord(record);
setShowDeleteModal(true);
};
// Get all columns
const columns = useMemo(() => {
return getRedemptionsColumns({
t,
manageRedemption,
copyText,
setEditingRedemption,
setShowEdit,
refresh,
redemptions,
activePage,
showDeleteRedemptionModal
});
}, [
t,
manageRedemption,
copyText,
setEditingRedemption,
setShowEdit,
refresh,
redemptions,
activePage,
showDeleteRedemptionModal,
]);
// Handle compact mode by removing fixed positioning
const tableColumns = useMemo(() => {
return compactMode ? columns.map(col => {
if (col.dataIndex === 'operate') {
const { fixed, ...rest } = col;
return rest;
}
return col;
}) : columns;
}, [compactMode, columns]);
return (
<>
<Table
columns={tableColumns}
dataSource={redemptions}
scroll={compactMode ? undefined : { x: 'max-content' }}
pagination={{
currentPage: activePage,
pageSize: pageSize,
total: tokenCount,
showSizeChanger: true,
pageSizeOptions: [10, 20, 50, 100],
onPageSizeChange: redemptionsData.handlePageSizeChange,
onPageChange: handlePageChange,
}}
loading={loading}
rowSelection={rowSelection}
onRow={handleRow}
empty={
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={<IllustrationNoResultDark style={{ width: 150, height: 150 }} />}
description={t('搜索无结果')}
style={{ padding: 30 }}
/>
}
className="rounded-xl overflow-hidden"
size="middle"
/>
<DeleteRedemptionModal
visible={showDeleteModal}
onCancel={() => setShowDeleteModal(false)}
record={deletingRecord}
manageRedemption={manageRedemption}
refresh={refresh}
redemptions={redemptions}
activePage={activePage}
t={t}
/>
</>
);
};
export default RedemptionsTable;

View File

@@ -0,0 +1,90 @@
import React from 'react';
import CardPro from '../../common/ui/CardPro';
import RedemptionsTable from './RedemptionsTable.jsx';
import RedemptionsActions from './RedemptionsActions.jsx';
import RedemptionsFilters from './RedemptionsFilters.jsx';
import RedemptionsDescription from './RedemptionsDescription.jsx';
import EditRedemptionModal from './modals/EditRedemptionModal';
import { useRedemptionsData } from '../../../hooks/redemptions/useRedemptionsData';
const RedemptionsPage = () => {
const redemptionsData = useRedemptionsData();
const {
// Edit state
showEdit,
editingRedemption,
closeEdit,
refresh,
// Actions state
selectedKeys,
setEditingRedemption,
setShowEdit,
batchCopyRedemptions,
batchDeleteRedemptions,
// Filters state
formInitValues,
setFormApi,
searchRedemptions,
loading,
searching,
// UI state
compactMode,
setCompactMode,
// Translation
t,
} = redemptionsData;
return (
<>
<EditRedemptionModal
refresh={refresh}
editingRedemption={editingRedemption}
visiable={showEdit}
handleClose={closeEdit}
/>
<CardPro
type="type1"
descriptionArea={
<RedemptionsDescription
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
}
actionsArea={
<div className="flex flex-col md:flex-row justify-between items-center gap-2 w-full">
<RedemptionsActions
selectedKeys={selectedKeys}
setEditingRedemption={setEditingRedemption}
setShowEdit={setShowEdit}
batchCopyRedemptions={batchCopyRedemptions}
batchDeleteRedemptions={batchDeleteRedemptions}
t={t}
/>
<div className="w-full md:w-full lg:w-auto order-1 md:order-2">
<RedemptionsFilters
formInitValues={formInitValues}
setFormApi={setFormApi}
searchRedemptions={searchRedemptions}
loading={loading}
searching={searching}
t={t}
/>
</div>
</div>
}
>
<RedemptionsTable {...redemptionsData} />
</CardPro>
</>
);
};
export default RedemptionsPage;

View File

@@ -0,0 +1,39 @@
import React from 'react';
import { Modal } from '@douyinfe/semi-ui';
import { REDEMPTION_ACTIONS } from '../../../../constants/redemption.constants';
const DeleteRedemptionModal = ({
visible,
onCancel,
record,
manageRedemption,
refresh,
redemptions,
activePage,
t
}) => {
const handleConfirm = async () => {
await manageRedemption(record.id, REDEMPTION_ACTIONS.DELETE, record);
await refresh();
setTimeout(() => {
if (redemptions.length === 0 && activePage > 1) {
refresh(activePage - 1);
}
}, 100);
onCancel(); // Close modal after success
};
return (
<Modal
title={t('确定是否要删除此兑换码?')}
visible={visible}
onCancel={onCancel}
onOk={handleConfirm}
type="warning"
>
{t('此修改将不可逆')}
</Modal>
);
};
export default DeleteRedemptionModal;

View File

@@ -0,0 +1,305 @@
import React, { useEffect, useState, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import {
API,
downloadTextAsFile,
showError,
showSuccess,
renderQuota,
renderQuotaWithPrompt,
} from '../../../../helpers';
import { useIsMobile } from '../../../../hooks/common/useIsMobile.js';
import {
Button,
Modal,
SideSheet,
Space,
Spin,
Typography,
Card,
Tag,
Form,
Avatar,
Row,
Col,
} from '@douyinfe/semi-ui';
import {
IconCreditCard,
IconSave,
IconClose,
IconGift,
} from '@douyinfe/semi-icons';
const { Text, Title } = Typography;
const EditRedemptionModal = (props) => {
const { t } = useTranslation();
const isEdit = props.editingRedemption.id !== undefined;
const [loading, setLoading] = useState(isEdit);
const isMobile = useIsMobile();
const formApiRef = useRef(null);
const getInitValues = () => ({
name: '',
quota: 100000,
count: 1,
expired_time: null,
});
const handleCancel = () => {
props.handleClose();
};
const loadRedemption = async () => {
setLoading(true);
let res = await API.get(`/api/redemption/${props.editingRedemption.id}`);
const { success, message, data } = res.data;
if (success) {
if (data.expired_time === 0) {
data.expired_time = null;
} else {
data.expired_time = new Date(data.expired_time * 1000);
}
formApiRef.current?.setValues({ ...getInitValues(), ...data });
} else {
showError(message);
}
setLoading(false);
};
useEffect(() => {
if (formApiRef.current) {
if (isEdit) {
loadRedemption();
} else {
formApiRef.current.setValues(getInitValues());
}
}
}, [props.editingRedemption.id]);
const submit = async (values) => {
let name = values.name;
if (!isEdit && (!name || name === '')) {
name = renderQuota(values.quota);
}
setLoading(true);
let localInputs = { ...values };
localInputs.count = parseInt(localInputs.count) || 0;
localInputs.quota = parseInt(localInputs.quota) || 0;
localInputs.name = name;
if (!localInputs.expired_time) {
localInputs.expired_time = 0;
} else {
localInputs.expired_time = Math.floor(localInputs.expired_time.getTime() / 1000);
}
let res;
if (isEdit) {
res = await API.put(`/api/redemption/`, {
...localInputs,
id: parseInt(props.editingRedemption.id),
});
} else {
res = await API.post(`/api/redemption/`, {
...localInputs,
});
}
const { success, message, data } = res.data;
if (success) {
if (isEdit) {
showSuccess(t('兑换码更新成功!'));
props.refresh();
props.handleClose();
} else {
showSuccess(t('兑换码创建成功!'));
props.refresh();
formApiRef.current?.setValues(getInitValues());
props.handleClose();
}
} else {
showError(message);
}
if (!isEdit && data) {
let text = '';
for (let i = 0; i < data.length; i++) {
text += data[i] + '\n';
}
Modal.confirm({
title: t('兑换码创建成功'),
content: (
<div>
<p>{t('兑换码创建成功,是否下载兑换码?')}</p>
<p>{t('兑换码将以文本文件的形式下载,文件名为兑换码的名称。')}</p>
</div>
),
onOk: () => {
downloadTextAsFile(text, `${localInputs.name}.txt`);
},
});
}
setLoading(false);
};
return (
<>
<SideSheet
placement={isEdit ? 'right' : 'left'}
title={
<Space>
{isEdit ?
<Tag color="blue" shape="circle">{t('更新')}</Tag> :
<Tag color="green" shape="circle">{t('新建')}</Tag>
}
<Title heading={4} className="m-0">
{isEdit ? t('更新兑换码信息') : t('创建新的兑换码')}
</Title>
</Space>
}
bodyStyle={{ padding: '0' }}
visible={props.visiable}
width={isMobile ? '100%' : 600}
footer={
<div className="flex justify-end bg-white">
<Space>
<Button
theme="solid"
onClick={() => formApiRef.current?.submitForm()}
icon={<IconSave />}
loading={loading}
>
{t('提交')}
</Button>
<Button
theme="light"
type="primary"
onClick={handleCancel}
icon={<IconClose />}
>
{t('取消')}
</Button>
</Space>
</div>
}
closeIcon={null}
onCancel={() => handleCancel()}
>
<Spin spinning={loading}>
<Form
initValues={getInitValues()}
getFormApi={(api) => formApiRef.current = api}
onSubmit={submit}
>
{({ values }) => (
<div className="p-2">
<Card className="!rounded-2xl shadow-sm border-0 mb-6">
{/* Header: Basic Info */}
<div className="flex items-center mb-2">
<Avatar size="small" color="blue" className="mr-2 shadow-md">
<IconGift size={16} />
</Avatar>
<div>
<Text className="text-lg font-medium">{t('基本信息')}</Text>
<div className="text-xs text-gray-600">{t('设置兑换码的基本信息')}</div>
</div>
</div>
<Row gutter={12}>
<Col span={24}>
<Form.Input
field='name'
label={t('名称')}
placeholder={t('请输入名称')}
style={{ width: '100%' }}
rules={!isEdit ? [] : [{ required: true, message: t('请输入名称') }]}
showClear
/>
</Col>
<Col span={24}>
<Form.DatePicker
field='expired_time'
label={t('过期时间')}
type='dateTime'
placeholder={t('选择过期时间(可选,留空为永久)')}
style={{ width: '100%' }}
showClear
/>
</Col>
</Row>
</Card>
<Card className="!rounded-2xl shadow-sm border-0">
{/* Header: Quota Settings */}
<div className="flex items-center mb-2">
<Avatar size="small" color="green" className="mr-2 shadow-md">
<IconCreditCard size={16} />
</Avatar>
<div>
<Text className="text-lg font-medium">{t('额度设置')}</Text>
<div className="text-xs text-gray-600">{t('设置兑换码的额度和数量')}</div>
</div>
</div>
<Row gutter={12}>
<Col span={12}>
<Form.AutoComplete
field='quota'
label={t('额度')}
placeholder={t('请输入额度')}
style={{ width: '100%' }}
type='number'
rules={[
{ required: true, message: t('请输入额度') },
{
validator: (rule, v) => {
const num = parseInt(v, 10);
return num > 0
? Promise.resolve()
: Promise.reject(t('额度必须大于0'));
},
},
]}
extraText={renderQuotaWithPrompt(Number(values.quota) || 0)}
data={[
{ value: 500000, label: '1$' },
{ value: 5000000, label: '10$' },
{ value: 25000000, label: '50$' },
{ value: 50000000, label: '100$' },
{ value: 250000000, label: '500$' },
{ value: 500000000, label: '1000$' },
]}
showClear
/>
</Col>
{!isEdit && (
<Col span={12}>
<Form.InputNumber
field='count'
label={t('生成数量')}
min={1}
rules={[
{ required: true, message: t('请输入生成数量') },
{
validator: (rule, v) => {
const num = parseInt(v, 10);
return num > 0
? Promise.resolve()
: Promise.reject(t('生成数量必须大于0'));
},
},
]}
style={{ width: '100%' }}
showClear
/>
</Col>
)}
</Row>
</Card>
</div>
)}
</Form>
</Spin>
</SideSheet>
</>
);
};
export default EditRedemptionModal;