下沉 CardList 动作协调器
This commit is contained in:
1 parent
cd65334fec
commit
48a0a2c4bd
17 files changed
+630
-248
No files matched your search
@@ -0,0 +1,139 @@
|
||||
// @vitest-environment jsdom
|
||||
import React from 'react';
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { Card } from '../types';
|
||||
|
||||
// cardListMocks 保存卡密页面测试使用的 Hook、API 和批量弹窗替身。
|
||||
const cardListMocks = vi.hoisted(/* cardListMockFactory 创建卡密页面共享替身。 */ () => ({
|
||||
cards: [] as Card[],
|
||||
loadCards: vi.fn(),
|
||||
openBatchModal: vi.fn(),
|
||||
createCard: vi.fn(),
|
||||
deleteCard: vi.fn(),
|
||||
updateCard: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../app/features/cards/hooks', /* cardsHooksMockFactory 提供卡密库存和批量 Hook 替身。 */ () => ({
|
||||
useCardsData: /* useCardsDataMock 返回固定卡密库存。 */ () => ({
|
||||
cards: cardListMocks.cards,
|
||||
setCards: vi.fn(),
|
||||
loading: false,
|
||||
loadCards: cardListMocks.loadCards,
|
||||
}),
|
||||
useCardBatchActions: /* useCardBatchActionsMock 返回批量弹窗状态。 */ () => ({
|
||||
showBatchModal: false,
|
||||
setShowBatchModal: vi.fn(),
|
||||
batchTab: 'create',
|
||||
setBatchTab: vi.fn(),
|
||||
batchFile: null,
|
||||
setBatchFile: vi.fn(),
|
||||
batchResult: null,
|
||||
batchBusy: false,
|
||||
appendTargetId: '',
|
||||
setAppendTargetId: vi.fn(),
|
||||
appendContent: '',
|
||||
setAppendContent: vi.fn(),
|
||||
appendResult: null,
|
||||
appendError: '',
|
||||
appendPreview: [],
|
||||
openBatchModal: cardListMocks.openBatchModal,
|
||||
closeBatchModal: vi.fn(),
|
||||
handleBatchCreate: vi.fn(),
|
||||
handleBatchAppend: vi.fn(),
|
||||
handleRetryBatchCreate: vi.fn(),
|
||||
handleRetryBatchAppend: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('../app/features/cards/api', /* cardsApiMockFactory 提供卡密页面动作 API 替身。 */ () => ({
|
||||
createCard: cardListMocks.createCard,
|
||||
deleteCard: cardListMocks.deleteCard,
|
||||
updateCard: cardListMocks.updateCard,
|
||||
}));
|
||||
|
||||
vi.mock('../app/features/cards/components/BatchCardImportModal', /* batchModalMockFactory 提供批量弹窗替身。 */ () => ({
|
||||
BatchCardImportModal: /* BatchCardImportModalMock 表示批量导入弹窗替身。 */ () => null,
|
||||
}));
|
||||
|
||||
import CardList from './CardList';
|
||||
|
||||
// cardFixture 表示卡密页面中的 data 类型库存。
|
||||
const cardFixture: Card = {
|
||||
id: 1,
|
||||
name: '库存一',
|
||||
type: 'data',
|
||||
data_content: 'A\nB',
|
||||
description: '测试库存',
|
||||
enabled: true,
|
||||
delay_seconds: 0,
|
||||
created_at: '2026-08-15T00:00:00Z',
|
||||
updated_at: '2026-08-15T00:00:00Z',
|
||||
};
|
||||
|
||||
// textCardFixture 表示卡密页面中的文本类型卡密组。
|
||||
const textCardFixture: Card = {
|
||||
...cardFixture,
|
||||
id: 2,
|
||||
name: '文案二',
|
||||
type: 'text',
|
||||
data_content: undefined,
|
||||
text_content: '感谢购买',
|
||||
};
|
||||
|
||||
describe('CardList 页面组合行为', /* 当前回调验证卡密筛选、批量入口、新增、编辑、启停和删除流程。 */ () => {
|
||||
beforeEach(/* 当前回调重置卡密页面 API、库存和浏览器提示替身。 */ () => {
|
||||
vi.clearAllMocks();
|
||||
cardListMocks.cards = [cardFixture, textCardFixture];
|
||||
cardListMocks.loadCards.mockResolvedValue(undefined);
|
||||
cardListMocks.createCard.mockResolvedValue({ success: true, id: 3 });
|
||||
cardListMocks.deleteCard.mockResolvedValue({ success: true });
|
||||
cardListMocks.updateCard.mockResolvedValue({ success: true });
|
||||
vi.spyOn(window, 'alert').mockImplementation(/* alertImplementation 屏蔽卡密页面提示。 */ () => undefined);
|
||||
vi.spyOn(window, 'confirm').mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterEach(/* 当前回调清理卡密页面 DOM 和浏览器提示替身。 */ () => {
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
test('筛选卡密并打开批量导入入口', /* 当前回调验证卡密列表筛选和批量操作转发。 */ () => {
|
||||
render(<CardList />);
|
||||
expect(screen.getByText('显示 2 / 2 组')).toBeTruthy();
|
||||
fireEvent.change(screen.getByLabelText('按卡密类型筛选'), { target: { value: 'data' } });
|
||||
expect(screen.getByText('显示 1 / 2 组')).toBeTruthy();
|
||||
fireEvent.change(screen.getByLabelText('按卡密名称搜索'), { target: { value: '库存' } });
|
||||
expect(screen.getByText('显示 1 / 2 组')).toBeTruthy();
|
||||
fireEvent.click(screen.getByText('批量导入'));
|
||||
expect(cardListMocks.openBatchModal).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('新增和编辑卡密会映射表单字段并刷新库存', /* 当前回调验证卡密新增与编辑页面行为。 */ async () => {
|
||||
render(<CardList />);
|
||||
fireEvent.click(screen.getByText('添加新卡密'));
|
||||
fireEvent.change(screen.getByPlaceholderText('例如:VIP会员卡密'), { target: { value: '新文案' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: '文本' }));
|
||||
fireEvent.change(screen.getByPlaceholderText('请输入每次发货时发送的固定文字'), { target: { value: '欢迎购买' } });
|
||||
fireEvent.click(screen.getByText('添加卡密'));
|
||||
await waitFor(/* addAssertion 等待卡密创建请求完成。 */ () => expect(cardListMocks.createCard).toHaveBeenCalledWith(expect.objectContaining({ name: '新文案', type: 'text', text_content: '欢迎购买' })));
|
||||
expect(cardListMocks.loadCards).toHaveBeenCalledTimes(1);
|
||||
|
||||
fireEvent.click(screen.getAllByTitle('编辑')[0]);
|
||||
fireEvent.change(screen.getByDisplayValue('库存一'), { target: { value: '库存更新' } });
|
||||
fireEvent.click(screen.getByText('保存更改'));
|
||||
await waitFor(/* editAssertion 等待卡密更新请求完成。 */ () => expect(cardListMocks.updateCard).toHaveBeenCalledWith(1, expect.objectContaining({ name: '库存更新', data_content: 'A\nB' })));
|
||||
expect(cardListMocks.loadCards).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
test('启停、复制和删除按钮调用对应页面动作', /* 当前回调验证卡密行级动作边界。 */ async () => {
|
||||
render(<CardList />);
|
||||
fireEvent.click(screen.getByRole('button', { name: '切换卡密 库存一 状态' }));
|
||||
await waitFor(/* toggleAssertion 等待卡密启停请求完成。 */ () => expect(cardListMocks.updateCard).toHaveBeenCalledWith(1, expect.objectContaining({ enabled: false })));
|
||||
Object.assign(navigator, { clipboard: { writeText: vi.fn().mockResolvedValue(undefined) } });
|
||||
fireEvent.click(screen.getAllByTitle('复制卡密组ID,用于批量铺货表格')[0]);
|
||||
fireEvent.click(screen.getByRole('button', { name: '删除卡密 库存一' }));
|
||||
await waitFor(/* deleteAssertion 等待卡密删除请求完成。 */ () => expect(cardListMocks.deleteCard).toHaveBeenCalledWith(1));
|
||||
expect(cardListMocks.loadCards).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -1,237 +1,46 @@
|
||||
import React, { useMemo, useState } from 'react';
|
||||
import React from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Card } from '../types';
|
||||
import { createCard, deleteCard, updateCard } from '../app/features/cards/api';
|
||||
import { Plus, CreditCard, FileText, Image as ImageIcon, Edit, Trash2, Save, X, Eye, EyeOff, Package, Copy, Upload, Loader2, Search, SlidersHorizontal } from 'lucide-react';
|
||||
import { BatchCardImportModal } from '../app/features/cards/components/BatchCardImportModal';
|
||||
import { CardIcon } from '../app/features/cards/components/CardIcon';
|
||||
import { useCardBatchActions, useCardsData } from '../app/features/cards/hooks';
|
||||
import { filterCards } from '../app/features/cards/batchState';
|
||||
import type { AddCardForm, EditCardForm } from '../app/features/cards/types';
|
||||
|
||||
// emptyAddForm 新增卡密表单初始值。
|
||||
const emptyAddForm = (): AddCardForm => ({
|
||||
name: '',
|
||||
type: 'data',
|
||||
content: '',
|
||||
description: '',
|
||||
enabled: true,
|
||||
delay_seconds: 0,
|
||||
api_method: 'GET',
|
||||
api_timeout: 10,
|
||||
api_headers: '',
|
||||
api_params: '',
|
||||
});
|
||||
import { useCardActions } from '../app/features/cards/cardActions';
|
||||
|
||||
// CardList 渲染卡密列表组件。
|
||||
const CardList: React.FC = () => {
|
||||
// { 解构得到当前 Hook 返回的状态和操作函数。
|
||||
const { cards, loadCards } = useCardsData();
|
||||
// [showEditModal, 解构得到当前 Hook 返回的状态和操作函数。
|
||||
const [showEditModal, setShowEditModal] = useState(false);
|
||||
// [showAddModal, 解构得到当前 Hook 返回的状态和操作函数。
|
||||
const [showAddModal, setShowAddModal] = useState(false);
|
||||
// [selectedCard, 解构得到当前 Hook 返回的状态和操作函数。
|
||||
const [selectedCard, setSelectedCard] = useState<Card | null>(null);
|
||||
// [editForm, 解构得到当前 Hook 返回的状态和操作函数。
|
||||
const [editForm, setEditForm] = useState<EditCardForm>({});
|
||||
// [addForm, 解构得到当前 Hook 返回的状态和操作函数。
|
||||
const [addForm, setAddForm] = useState<AddCardForm>(emptyAddForm);
|
||||
|
||||
// [typeFilter, 解构得到当前 Hook 返回的状态和操作函数。
|
||||
const [typeFilter, setTypeFilter] = useState<Card['type'] | ''>('');
|
||||
// [nameSearch, 解构得到当前 Hook 返回的状态和操作函数。
|
||||
const [nameSearch, setNameSearch] = useState('');
|
||||
// dataCards 只保留可追加库存的卡密组,并在卡密数据未变化时保持引用稳定。
|
||||
const dataCards = useMemo(/* 当前回调处理集合中的单个元素。 */ () => cards.filter(/* 当前回调处理集合中的单个元素。 */ card => card.type === 'data'), [cards]);
|
||||
// cardActions 集中管理卡密编辑、新增、删除、筛选和模板动作。
|
||||
const cardActions = useCardActions({ cards, loadCards });
|
||||
// actionState 解构得到卡密页面动作协调器状态和方法。
|
||||
const {
|
||||
dataCards,
|
||||
filteredCards,
|
||||
typeFilter,
|
||||
setTypeFilter,
|
||||
nameSearch,
|
||||
setNameSearch,
|
||||
showEditModal,
|
||||
setShowEditModal,
|
||||
showAddModal,
|
||||
setShowAddModal,
|
||||
selectedCard,
|
||||
editForm,
|
||||
setEditForm,
|
||||
addForm,
|
||||
setAddForm,
|
||||
handleEdit,
|
||||
handleSaveEdit,
|
||||
handleDelete,
|
||||
handleAddCard,
|
||||
toggleCardStatus,
|
||||
copyCardID,
|
||||
downloadCardTemplate,
|
||||
} = cardActions;
|
||||
// batchState 批量发布状态。
|
||||
const batchState = useCardBatchActions({ dataCards, loadCards });
|
||||
|
||||
// handleEdit 处理当前用户操作(Edit)。
|
||||
const handleEdit = (card: Card) => {
|
||||
setSelectedCard(card);
|
||||
setEditForm({
|
||||
id: card.id,
|
||||
name: card.name || '',
|
||||
type: card.type || 'text',
|
||||
// API 配置
|
||||
api_url: card.api_config?.url || '',
|
||||
api_method: card.api_config?.method || 'GET',
|
||||
api_timeout: card.api_config?.timeout || 10,
|
||||
api_headers: card.api_config?.headers || '',
|
||||
api_params: card.api_config?.params || '',
|
||||
// 文本配置
|
||||
text_content: card.text_content || '',
|
||||
// 批量数据配置
|
||||
data_content: card.data_content || '',
|
||||
// 图片配置
|
||||
image_url: card.image_url || '',
|
||||
// 通用配置
|
||||
delay_seconds: card.delay_seconds || 0,
|
||||
description: card.description || '',
|
||||
enabled: card.enabled
|
||||
});
|
||||
setShowEditModal(true);
|
||||
};
|
||||
|
||||
// handleSaveEdit 处理当前用户操作(SaveEdit)。
|
||||
const handleSaveEdit = async () => {
|
||||
if (!selectedCard) return;
|
||||
|
||||
// 验证必填字段
|
||||
if (!editForm.name?.trim()) {
|
||||
alert('请输入卡密名称');
|
||||
return;
|
||||
}
|
||||
if (!editForm.type) {
|
||||
alert('请选择卡密类型');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// updateData 更新当前数据(返回数据)。
|
||||
const updateData: Partial<Card> = {
|
||||
name: editForm.name.trim(),
|
||||
type: editForm.type as any,
|
||||
description: editForm.description?.trim(),
|
||||
delay_seconds: editForm.delay_seconds || 0,
|
||||
enabled: editForm.enabled ?? true,
|
||||
};
|
||||
|
||||
// 根据类型设置内容
|
||||
if (editForm.type === 'api') {
|
||||
updateData.api_config = {
|
||||
url: editForm.api_url?.trim() || '',
|
||||
method: editForm.api_method as 'GET' | 'POST',
|
||||
timeout: editForm.api_timeout || 10,
|
||||
headers: editForm.api_headers?.trim() || undefined,
|
||||
params: editForm.api_params?.trim() || undefined
|
||||
};
|
||||
} else if (editForm.type === 'text') {
|
||||
updateData.text_content = editForm.text_content?.trim() || '';
|
||||
} else if (editForm.type === 'data') {
|
||||
updateData.data_content = editForm.data_content?.trim() || '';
|
||||
} else if (editForm.type === 'image') {
|
||||
updateData.image_url = editForm.image_url?.trim() || '';
|
||||
}
|
||||
|
||||
await updateCard(selectedCard.id, updateData);
|
||||
setShowEditModal(false);
|
||||
await loadCards();
|
||||
} catch (/* error 表示错误。 */ error) {
|
||||
console.error('更新卡密失败:', error);
|
||||
alert('更新失败,请重试');
|
||||
}
|
||||
};
|
||||
|
||||
// handleDelete 处理当前用户操作(Delete)。
|
||||
const handleDelete = async (id: string | number) => {
|
||||
if (confirm('确认删除该卡密吗?')) {
|
||||
try {
|
||||
await deleteCard(id);
|
||||
await loadCards();
|
||||
} catch (/* error 表示错误。 */ error) {
|
||||
console.error('删除卡密失败:', error);
|
||||
alert('删除失败,请重试');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// handleAddCard 处理当前用户操作(Add卡密)。
|
||||
const handleAddCard = async () => {
|
||||
if (!addForm.name.trim()) {
|
||||
alert('请输入卡密名称');
|
||||
return;
|
||||
}
|
||||
if (!addForm.content.trim()) {
|
||||
alert(addForm.type === 'api' ? '请输入 API 地址' : '请输入卡密内容');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
// payload 请求载荷。
|
||||
const payload: Partial<Card> = {
|
||||
name: addForm.name.trim(),
|
||||
type: addForm.type,
|
||||
description: addForm.description.trim(),
|
||||
enabled: addForm.enabled,
|
||||
delay_seconds: addForm.delay_seconds,
|
||||
};
|
||||
if (addForm.type === 'text') payload.text_content = addForm.content.trim();
|
||||
if (addForm.type === 'data') payload.data_content = addForm.content.trim();
|
||||
if (addForm.type === 'image') payload.image_url = addForm.content.trim();
|
||||
if (addForm.type === 'api') {
|
||||
payload.api_config = {
|
||||
url: addForm.content.trim(),
|
||||
method: addForm.api_method,
|
||||
timeout: addForm.api_timeout,
|
||||
headers: addForm.api_headers.trim() || undefined,
|
||||
params: addForm.api_params.trim() || undefined,
|
||||
};
|
||||
}
|
||||
await createCard(payload);
|
||||
setShowAddModal(false);
|
||||
setAddForm(emptyAddForm());
|
||||
await loadCards();
|
||||
} catch (/* error 表示错误。 */ error) {
|
||||
console.error('添加卡密失败:', error);
|
||||
alert('添加失败,请重试');
|
||||
}
|
||||
};
|
||||
|
||||
// toggleCardStatus 切换当前状态(卡密状态)。
|
||||
const toggleCardStatus = async (card: Card) => {
|
||||
try {
|
||||
await updateCard(card.id, { ...card, enabled: !card.enabled });
|
||||
await loadCards();
|
||||
} catch (/* error 表示错误。 */ error) {
|
||||
console.error('切换状态失败:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// copyCardID 复制卡密标识函数。
|
||||
const copyCardID = async (id: string | number) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(String(id));
|
||||
alert(`已复制卡密组ID:${id}`);
|
||||
} catch {
|
||||
prompt('复制卡密组ID', String(id));
|
||||
}
|
||||
};
|
||||
|
||||
// filteredCards 过滤后的卡密列表,负责当前功能中的对应处理。
|
||||
const filteredCards = useMemo(
|
||||
/* 当前回调计算并缓存派生数据。 */ () => filterCards(cards, typeFilter, nameSearch),
|
||||
[cards, nameSearch, typeFilter],
|
||||
);
|
||||
|
||||
// downloadCardTemplate 下载卡密模板函数。
|
||||
const downloadCardTemplate = () => {
|
||||
// headers 请求头。
|
||||
const headers = ['名称', '类型', '内容', '描述', '启用', '延迟秒', '多规格', '规格名', '规格值'];
|
||||
// rows 行数据。
|
||||
const rows = [
|
||||
['VIP月卡', 'data', 'VIP-MONTH-001\nVIP-MONTH-002\nVIP-MONTH-003', '按行消费的卡密队列', '是', '0', '否', '', ''],
|
||||
['感谢文案', 'text', '感谢购买,如有问题联系客服~', '固定文本', '是', '0', '否', '', ''],
|
||||
['教程图', 'image', 'https://cdn.example.com/tutorial.jpg', '图片URL', '是', '0', '否', '', ''],
|
||||
];
|
||||
// csv csv,负责当前功能中的对应处理。
|
||||
const csv = [headers, ...rows]
|
||||
.map(/* 当前回调处理集合中的单个元素。 */ row => row.map(/* 当前回调处理集合中的单个元素。 */ cell => `"${String(cell).replace(/"/g, '""')}"`).join(','))
|
||||
.join('\n');
|
||||
// blob blob,负责当前功能中的对应处理。
|
||||
const blob = new Blob(['' + csv], { type: 'text/csv;charset=utf-8' });
|
||||
// url 地址。
|
||||
const url = URL.createObjectURL(blob);
|
||||
// link 链接。
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = '卡密组批量导入模板.csv';
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6 animate-fade-in">
|
||||
<div className="flex flex-col md:flex-row justify-between md:items-end gap-4">
|
||||
@@ -368,6 +177,7 @@ const CardList: React.FC = () => {
|
||||
<td className="px-2 py-5">
|
||||
<button
|
||||
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => toggleCardStatus(card)}
|
||||
aria-label={`切换卡密 ${card.name} 状态`}
|
||||
className={`w-12 h-8 rounded-full relative transition-colors ${
|
||||
card.enabled ? 'bg-green-500' : 'bg-gray-300'
|
||||
}`}
|
||||
@@ -388,6 +198,7 @@ const CardList: React.FC = () => {
|
||||
</button>
|
||||
<button
|
||||
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => handleDelete(card.id)}
|
||||
aria-label={`删除卡密 ${card.name}`}
|
||||
className="rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
|
||||
Reference in new issue
Block a user