阶段七:完成CardList React feature化与批量追加边界

This commit is contained in:
Christ committed 2026-08-15 00:45:16 +08:00
1 parent 03f108639d
commit 66ac84b32d
18 files changed
+1105 -975

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
// 卡密 feature 只通过本适配层访问库存和批量接口,页面不直接依赖共享 API 文件。
export {
appendCardData,
batchCreateCards,
createCard,
deleteCard,
getCards,
updateCard,
} from '../../../services/api';
// 卡密 feature 重新导出接口响应类型,保持批量结果契约稳定。
export type { CardAppendResponse, CardBatchResponse } from '../../../types';
@@ -0,0 +1,34 @@
import { expect, test } from 'vitest';
import type { Card } from '../../../types';
import { canSubmitAppend, filterCards, isCurrentCardRequest, previewAppendContent } from './batchState';
// cards 是卡密筛选测试使用的最小卡密组列表。
const cards = [
{ id: 1, name: '年终总结 PPT', type: 'text', enabled: true },
{ id: 2, name: '年终总结兑换码', type: 'data', enabled: true },
{ id: 3, name: '产品介绍 PPT', type: 'text', enabled: false },
] as Card[];
test('卡密筛选同时满足类型和名称条件',
// 类型和名称筛选必须使用 AND 语义,避免展示无关库存。
() => {
expect(filterCards(cards, 'text', '年终')).toEqual([cards[0]]);
expect(filterCards(cards, '', ' ppt ')).toEqual([cards[0], cards[2]]);
});
test('追加预览会去除空行并裁剪每行空白',
// 预览数量与最终提交内容共用同一套规范化规则。
() => {
expect(previewAppendContent(' VIP-001\n\nVIP-002 \n ')).toEqual(['VIP-001', 'VIP-002']);
expect(canSubmitAppend('2', ' VIP-001\n', false)).toBe(true);
expect(canSubmitAppend('2', '\n', false)).toBe(false);
expect(canSubmitAppend('2', 'VIP-001', true)).toBe(false);
});
test('追加目标切换后拒绝旧请求响应和旧代次响应',
// 用户切换卡密组或关闭弹窗后,旧追加请求不能覆盖当前状态。
() => {
expect(isCurrentCardRequest(3, 3, '2', '2')).toBe(true);
expect(isCurrentCardRequest(2, 3, '2', '2')).toBe(false);
expect(isCurrentCardRequest(3, 3, '2', '3')).toBe(false);
});
+40
View File
@@ -0,0 +1,40 @@
import type { Card } from '../../../types';
// filterCards 按类型和名称筛选卡密组,两个条件同时满足才保留。
export const filterCards = (
cards: Card[],
typeFilter: Card['type'] | '',
nameSearch: string,
): Card[] => {
// keyword 是去除首尾空格并转为小写的名称搜索词。
const keyword = nameSearch.trim().toLocaleLowerCase();
return cards.filter(
// card 是待判断是否符合筛选条件的卡密组。
card => (
(!typeFilter || card.type === typeFilter)
&& (!keyword || card.name.toLocaleLowerCase().includes(keyword))
),
);
};
// previewAppendContent 将追加文本转换为去除空行后的卡密预览列表。
export const previewAppendContent = (content: string): string[] => content
.split('\n')
.map(
// line 是追加文本中的单行原始内容。
line => line.trim(),
)
.filter(Boolean);
// canSubmitAppend 判断当前追加表单是否具备目标卡密组和有效内容。
export const canSubmitAppend = (targetId: string, content: string, busy: boolean): boolean => Boolean(
targetId && previewAppendContent(content).length > 0 && !busy,
);
// isCurrentCardRequest 判断卡密目标切换后响应是否仍属于当前请求。
export const isCurrentCardRequest = (
requestGeneration: number,
currentGeneration: number,
requestTargetId: string,
currentTargetId: string,
): boolean => requestGeneration === currentGeneration && requestTargetId === currentTargetId;
@@ -0,0 +1,152 @@
import React from 'react';
import { createPortal } from 'react-dom';
import { FileDown, ListPlus, Loader2, Plus, Upload, X } from 'lucide-react';
import type { Card } from '../../../../types';
import type { CardBatchModalProps } from '../types';
// BatchCardImportModal 负责卡密批量创建和单组库存追加的交互界面。
export const BatchCardImportModal: React.FC<CardBatchModalProps> = ({
dataCards,
downloadCardTemplate,
...state
}) => {
// handleFileChange 保存用户选择的批量导入文件。
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
state.setBatchFile(event.target.files?.[0] || null);
};
// handleAppendContentChange 更新追加文本并保留原始换行,预览由 Hook 派生。
const handleAppendContentChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
state.setAppendContent(event.target.value);
};
// handleTargetChange 切换追加库存目标卡密组。
const handleTargetChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
state.setAppendTargetId(event.target.value);
};
// handleClose 关闭弹窗并取消当前批量请求。
const handleClose = () => state.closeBatchModal();
// handleCreateTab 切换到批量创建页签。
const handleCreateTab = () => state.setBatchTab('create');
// handleAppendTab 切换到库存追加页签。
const handleAppendTab = () => state.setBatchTab('append');
// handleRetryCreate 重试最近一次批量创建。
const handleRetryCreate = () => void state.handleRetryBatchCreate();
// handleRetryAppend 重试最近一次库存追加。
const handleRetryAppend = () => void state.handleRetryBatchAppend();
// completedBatchResult 只保留包含逐行统计的成功批量结果。
const completedBatchResult = state.batchResult && 'rows' in state.batchResult ? state.batchResult : null;
// renderCardOption 渲染追加目标卡密组的下拉选项。
const renderCardOption = (card: Card) => <option key={card.id} value={String(card.id)}>{card.name}(ID: {card.id})</option>;
// handleSubmitCreate 提交批量创建请求。
const handleSubmitCreate = () => void state.handleBatchCreate();
// handleSubmitAppend 提交批量追加请求。
const handleSubmitAppend = () => void state.handleBatchAppend();
if (!state.showBatchModal) return null;
return createPortal(
<div className="modal-overlay">
<div className="modal-container" style={{ maxWidth: '40rem' }}>
<div className="px-6 py-5 border-b border-gray-100 flex items-center justify-between">
<h3 className="text-xl font-extrabold text-gray-900">批量导入卡密</h3>
<button onClick={handleClose} className="w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center">
<X className="w-5 h-5 text-gray-600" />
</button>
</div>
<div className="px-6 py-5 space-y-5">
<div className="flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl">
<button onClick={handleCreateTab} className={`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${state.batchTab === 'create' ? 'bg-brand text-white shadow-md' : 'bg-white text-gray-600 hover:bg-gray-50'}`}>
<ListPlus className="w-4 h-4" />批量创建卡密组
</button>
<button onClick={handleAppendTab} className={`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${state.batchTab === 'append' ? 'bg-brand text-white shadow-md' : 'bg-white text-gray-600 hover:bg-gray-50'}`}>
<Upload className="w-4 h-4" />往单个组充卡密
</button>
</div>
{state.batchTab === 'create' ? (
<div className="space-y-4">
<div className="rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5">
上传表格,每行一个卡密组。表头:<code className="bg-blue-100/70 px-1.5 py-0.5 rounded">名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值</code>。
类型填 text/data/image;data 类型的“内容”按行存卡密(CSV 单元格内换行需用引号包裹)。
</div>
<div className="flex items-center gap-3">
<button onClick={downloadCardTemplate} className="px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm transition-colors">
<FileDown className="w-4 h-4" />下载模板
</button>
<label className="flex-1 px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm cursor-pointer transition-colors">
<Upload className="w-4 h-4" />{state.batchFile ? state.batchFile.name : '选择 .xlsx / .csv / .tsv'}
<input type="file" accept=".xlsx,.csv,.tsv" className="hidden" onChange={handleFileChange} />
</label>
</div>
{state.batchResult?.error && (
<div className="rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700 flex items-center justify-between gap-3">
<span>{state.batchResult.error}</span>
<button type="button" onClick={handleRetryCreate} disabled={!state.batchFile || state.batchBusy} className="font-bold whitespace-nowrap">重试</button>
</div>
)}
{completedBatchResult && (
<div className="rounded-xl border border-gray-200 p-4 space-y-2">
<div className="text-sm font-bold text-gray-900">共 {completedBatchResult.total} 行 · 成功 {completedBatchResult.created} · 失败 {completedBatchResult.failed}</div>
{completedBatchResult.failed > 0 && (
<div className="max-h-48 overflow-y-auto space-y-1">
{completedBatchResult.rows.filter(
// row 是批量结果中的单行处理记录。
row => !row.success,
).map(
// row 是待展示失败说明的单行结果。
row => (
<div key={row.row_no} className="text-xs text-red-600">第 {row.row_no} 行「{row.name}」:{row.error}</div>
),
)}
</div>
)}
</div>
)}
</div>
) : (
<div className="space-y-4">
{dataCards.length === 0 ? (
<div className="rounded-xl bg-amber-50 border border-amber-200 p-4 text-sm text-amber-800">暂无 data(批量卡密)类型的卡密组,请先创建一个再充卡密。</div>
) : (
<>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">选择卡密组</label>
<select value={state.appendTargetId} onChange={handleTargetChange} className="w-full ios-input px-4 py-3 rounded-xl text-sm">
{dataCards.map(renderCardOption)}
</select>
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">卡密号(每行一个)</label>
<textarea value={state.appendContent} onChange={handleAppendContentChange} placeholder={'VIP-001\nVIP-002\nVIP-003'} className="w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y" />
<p className="text-xs text-gray-500">预览:{state.appendPreview.length} 个有效卡密,空行自动忽略。</p>
</div>
{state.appendError && (
<div className="rounded-xl bg-red-50 border border-red-200 p-3 text-sm text-red-700 flex items-center justify-between gap-3">
<span>{state.appendError}</span>
<button type="button" onClick={handleRetryAppend} disabled={state.batchBusy} className="font-bold whitespace-nowrap">重试</button>
</div>
)}
{state.appendResult && <div className="rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold">已追加 {state.appendResult.added} 个卡密</div>}
</>
)}
</div>
)}
</div>
<div className="px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3">
<button onClick={handleClose} className="px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors">关闭</button>
{state.batchTab === 'create' ? (
<button onClick={handleSubmitCreate} disabled={!state.batchFile || state.batchBusy} className="ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50">
{state.batchBusy ? <Loader2 className="w-4 h-4 animate-spin" /> : <Upload className="w-4 h-4" />}{state.batchBusy ? '处理中...' : '上传创建'}
</button>
) : (
<button onClick={handleSubmitAppend} disabled={!state.appendTargetId || state.appendPreview.length === 0 || state.batchBusy || dataCards.length === 0} className="ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50">
{state.batchBusy ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}{state.batchBusy ? '处理中...' : '追加卡密'}
</button>
)}
</div>
</div>
</div>,
document.body,
);
};
@@ -0,0 +1,23 @@
import React from 'react';
import { Code, CreditCard, FileText, Image as ImageIcon } from 'lucide-react';
import type { Card } from '../../../../types';
// CardIconProps 描述库存图标所需的卡密类型参数。
interface CardIconProps {
// type 是当前卡密组的交付类型。
type: Card['type'];
}
// CardIcon 根据卡密类型渲染稳定的库存图标,避免在列表组件内声明子组件。
export const CardIcon: React.FC<CardIconProps> = ({ type }) => {
switch (type) {
case 'text':
return <FileText className="w-5 h-5 text-blue-500" />;
case 'image':
return <ImageIcon className="w-5 h-5 text-purple-500" />;
case 'api':
return <Code className="w-5 h-5 text-blue-500" />;
default:
return <CreditCard className="w-5 h-5 text-gray-500" />;
}
};
+253
View File
@@ -0,0 +1,253 @@
import { useCallback, useEffect, useMemo, useRef, useState, type Dispatch, type SetStateAction } from 'react';
import { appendCardData, batchCreateCards, getCards } from './api';
import type { Card } from '../../../types';
import { canSubmitAppend, isCurrentCardRequest, previewAppendContent } from './batchState';
import type { CardBatchState } from './types';
// CardsDataResult 暴露卡密库存、加载状态和可复用刷新动作。
export interface CardsDataResult {
// cards 是当前库存中的全部卡密组。
cards: Card[];
// setCards 允许页面在编辑、删除和批量操作后局部更新库存。
setCards: Dispatch<SetStateAction<Card[]>>;
// loading 表示卡密库存是否正在加载。
loading: boolean;
// loadCards 刷新卡密库存并丢弃旧请求响应。
loadCards: () => Promise<void>;
}
// CardBatchOptions 描述批量操作 Hook 所需的库存数据和刷新回调。
export interface CardBatchOptions {
// dataCards 是可用于追加库存的 data 类型卡密组。
dataCards: Card[];
// loadCards 在批量操作完成后刷新库存。
loadCards: () => Promise<void>;
}
// useCardsData 统一管理卡密库存首次加载、刷新、取消和请求代次。
export const useCardsData = (): CardsDataResult => {
// cards 保存当前卡密组列表。
const [cards, setCards] = useState<Card[]>([]);
// loading 表示库存加载状态。
const [loading, setLoading] = useState(true);
// loadGeneration 用于隔离连续刷新产生的旧响应。
const loadGeneration = useRef(0);
// loadAbort 保存当前库存请求的取消控制器。
const loadAbort = useRef<AbortController | null>(null);
// loadCards 并行无依赖请求只有一个,但通过代次和 AbortController 保证刷新安全。
const loadCards = useCallback(
// 货架加载回调读取最新卡密库存。
async () => {
// generation 标记本次库存加载请求。
const generation = ++loadGeneration.current;
loadAbort.current?.abort();
// controller 允许新刷新取消旧的网络请求。
const controller = new AbortController();
loadAbort.current = controller;
setLoading(true);
try {
// result 是当前请求返回的规范化卡密列表。
const result = await getCards({ signal: controller.signal });
if (generation !== loadGeneration.current) return;
setCards(result);
} catch (error /* 卡密库存加载错误 */) {
if (generation === loadGeneration.current && !controller.signal.aborted) {
console.error('加载卡密库存失败:', error);
}
} finally {
if (generation === loadGeneration.current) setLoading(false);
}
},
[],
);
useEffect(
// 库存副作用负责首次加载,并在组件卸载时取消请求。
() => {
void loadCards();
// cleanup 在库存页面卸载时终止当前请求。
const cleanup = () => {
loadGeneration.current += 1;
loadAbort.current?.abort();
};
return cleanup;
},
[loadCards],
);
return { cards, setCards, loading, loadCards };
};
// useCardBatchActions 统一管理批量创建、追加、取消和失败重试状态。
export const useCardBatchActions = (options: CardBatchOptions): CardBatchState => {
// dataCards 是当前可用于追加库存的 data 类型卡密组。
const dataCards = options.dataCards;
// loadCards 是批量操作完成后的库存刷新动作。
const loadCards = options.loadCards;
// showBatchModal 表示批量导入弹窗是否打开。
const [showBatchModal, setShowBatchModal] = useState(false);
// batchTab 保存当前批量操作页签。
const [batchTab, setBatchTab] = useState<'create' | 'append'>('create');
// batchFile 保存最近一次选择的批量文件。
const [batchFile, setBatchFile] = useState<File | null>(null);
// batchResult 保存批量创建成功或失败结果。
const [batchResult, setBatchResult] = useState<CardBatchState['batchResult']>(null);
// batchBusy 表示批量请求正在执行。
const [batchBusy, setBatchBusy] = useState(false);
// appendTargetId 保存当前追加目标卡密组。
const [appendTargetId, setAppendTargetId] = useState('');
// appendContent 保存待追加的原始卡密文本。
const [appendContent, setAppendContent] = useState('');
// appendResult 保存追加成功数量。
const [appendResult, setAppendResult] = useState<CardBatchState['appendResult']>(null);
// appendError 保存追加失败说明。
const [appendError, setAppendError] = useState('');
// requestGeneration 让关闭弹窗或切换目标后旧响应失效。
const requestGeneration = useRef(0);
// requestAbort 取消当前批量创建或追加请求。
const requestAbort = useRef<AbortController | null>(null);
// lastAppendTarget 保存最近一次提交追加的目标 ID,供失败重试使用。
const lastAppendTarget = useRef('');
// appendPreview 按行派生追加预览,不重复存储派生状态。
const appendPreview = useMemo(
// 追加预览回调根据当前文本派生有效卡密行。
() => previewAppendContent(appendContent),
[appendContent],
);
// openBatchModal 重置批量表单,并默认选择第一个 data 卡密组。
const openBatchModal = useCallback(
// 批量弹窗打开回调重置上一次操作的短暂状态。
() => {
setBatchTab('create');
setBatchFile(null);
setBatchResult(null);
setAppendTargetId(dataCards[0]?.id ? String(dataCards[0].id) : '');
setAppendContent('');
setAppendResult(null);
setAppendError('');
setShowBatchModal(true);
},
[dataCards],
);
// closeBatchModal 使当前请求失效并关闭批量操作弹窗。
const closeBatchModal = useCallback(
// 批量弹窗关闭回调取消网络请求并使旧响应失效。
() => {
requestGeneration.current += 1;
requestAbort.current?.abort();
setBatchBusy(false);
setShowBatchModal(false);
},
[],
);
// handleBatchCreate 执行批量创建并在成功后刷新库存。
const handleBatchCreate = useCallback(
// 批量创建回调上传文件并刷新库存。
async () => {
if (!batchFile || batchBusy) return;
// generation 标记当前批量创建请求的代次。
const generation = ++requestGeneration.current;
requestAbort.current?.abort();
// controller 取消上一轮批量创建请求。
const controller = new AbortController();
requestAbort.current = controller;
setBatchBusy(true);
setBatchResult(null);
try {
// result 是批量创建接口返回的逐行统计结果。
const result = await batchCreateCards(batchFile, { signal: controller.signal });
if (!isCurrentCardRequest(generation, requestGeneration.current, '', '')) return;
setBatchResult(result);
if (result.created > 0) await loadCards();
} catch (error: any /* 批量创建错误 */) {
if (!isCurrentCardRequest(generation, requestGeneration.current, '', '')) return;
setBatchResult({ error: error?.message || '上传失败' });
} finally {
if (isCurrentCardRequest(generation, requestGeneration.current, '', '')) setBatchBusy(false);
}
},
[batchBusy, batchFile, loadCards],
);
// handleBatchAppend 预览并提交当前卡密组的追加内容。
const handleBatchAppend = useCallback(
// 批量追加回调提交当前目标卡密组的有效行。
async () => {
if (!canSubmitAppend(appendTargetId, appendContent, batchBusy)) return;
// targetId 保存提交时的目标卡密组,防止切换目标后误写状态。
const targetId = appendTargetId;
// generation 标记当前追加请求的代次。
const generation = ++requestGeneration.current;
lastAppendTarget.current = targetId;
requestAbort.current?.abort();
// controller 取消上一轮追加库存请求。
const controller = new AbortController();
requestAbort.current = controller;
setBatchBusy(true);
setAppendResult(null);
setAppendError('');
try {
// result 是当前卡密组追加成功的数量。
const result = await appendCardData(targetId, appendContent, { signal: controller.signal });
if (!isCurrentCardRequest(generation, requestGeneration.current, targetId, appendTargetId)) return;
setAppendResult({ added: result.added });
setAppendContent('');
await loadCards();
} catch (error: any /* 追加库存错误 */) {
if (!isCurrentCardRequest(generation, requestGeneration.current, targetId, appendTargetId)) return;
setAppendError(error?.message || '追加失败');
} finally {
if (isCurrentCardRequest(generation, requestGeneration.current, targetId, appendTargetId)) setBatchBusy(false);
}
},
[appendContent, appendTargetId, batchBusy, loadCards],
);
// handleRetryBatchCreate 重试仍然保留在表单中的批量文件。
const handleRetryBatchCreate = useCallback(
// 批量创建重试回调复用当前文件。
async () => {
await handleBatchCreate();
},
[handleBatchCreate],
);
// handleRetryBatchAppend 重试最近一次追加目标的当前内容。
const handleRetryBatchAppend = useCallback(
// 追加重试回调只允许重试仍处于当前目标的请求。
async () => {
if (lastAppendTarget.current && appendTargetId !== lastAppendTarget.current) return;
await handleBatchAppend();
},
[appendTargetId, handleBatchAppend],
);
return {
showBatchModal,
setShowBatchModal,
batchTab,
setBatchTab,
batchFile,
setBatchFile,
batchResult,
batchBusy,
appendTargetId,
setAppendTargetId,
appendContent,
setAppendContent,
appendResult,
appendError,
appendPreview,
openBatchModal,
closeBatchModal,
handleBatchCreate,
handleBatchAppend,
handleRetryBatchCreate,
handleRetryBatchAppend,
};
};
+115
View File
@@ -0,0 +1,115 @@
import type { Dispatch, SetStateAction } from 'react';
import type { Card, CardAppendResponse, CardBatchResponse } from '../../../types';
// AddCardForm 描述新增卡密组弹窗中的可编辑字段。
export interface AddCardForm {
// name 是卡密组名称。
name: string;
// type 是卡密交付类型。
type: Card['type'];
// content 是当前类型对应的主要内容。
content: string;
// description 是卡密组说明。
description: string;
// enabled 表示新建后是否启用。
enabled: boolean;
// delay_seconds 是自动发货延迟秒数。
delay_seconds: number;
// api_method 是 API 卡密请求方法。
api_method: 'GET' | 'POST';
// api_timeout 是 API 请求超时时间。
api_timeout: number;
// api_headers 是 API 请求头 JSON 文本。
api_headers: string;
// api_params 是 API 请求参数 JSON 文本。
api_params: string;
}
// EditCardForm 描述编辑卡密组时的表单字段和 API 扩展字段。
export type EditCardForm = Partial<Card> & {
// api_url 是编辑中的 API 地址。
api_url?: string;
// api_method 是编辑中的 API 请求方法。
api_method?: 'GET' | 'POST';
// api_timeout 是编辑中的 API 超时时间。
api_timeout?: number;
// api_headers 是编辑中的 API 请求头 JSON 文本。
api_headers?: string;
// api_params 是编辑中的 API 请求参数 JSON 文本。
api_params?: string;
};
// CardBatchTab 表示批量导入弹窗当前展示的操作页签。
export type CardBatchTab = 'create' | 'append';
// CardBatchResponseResult 保存包含逐行统计的批量创建响应和可选错误说明。
export interface CardBatchResponseResult extends CardBatchResponse {
// error 是批量请求失败时的用户可见说明。
error?: string;
}
// CardBatchError 保存没有统计数据时的批量创建错误。
export interface CardBatchError {
// error 是批量请求失败时的用户可见说明。
error: string;
}
// CardBatchResult 保存批量创建接口返回的成功、失败统计或错误说明。
export type CardBatchResult = CardBatchResponseResult | CardBatchError | null;
// CardAppendResult 保存批量追加接口返回的新增数量。
export type CardAppendResult = Pick<CardAppendResponse, 'added'> | null;
// CardBatchState 描述批量创建和追加弹窗的全部短暂 UI 状态。
export interface CardBatchState {
// showBatchModal 表示批量操作弹窗是否打开。
showBatchModal: boolean;
// setShowBatchModal 更新弹窗展示状态。
setShowBatchModal: Dispatch<SetStateAction<boolean>>;
// batchTab 表示当前是批量创建还是追加库存。
batchTab: CardBatchTab;
// setBatchTab 切换批量操作页签。
setBatchTab: Dispatch<SetStateAction<CardBatchTab>>;
// batchFile 是待上传的批量文件。
batchFile: File | null;
// setBatchFile 更新待上传文件。
setBatchFile: Dispatch<SetStateAction<File | null>>;
// batchResult 保存最近一次批量创建结果。
batchResult: CardBatchResult;
// batchBusy 表示批量创建或追加请求正在执行。
batchBusy: boolean;
// appendTargetId 是当前追加库存目标卡密组 ID。
appendTargetId: string;
// setAppendTargetId 切换追加库存目标卡密组。
setAppendTargetId: Dispatch<SetStateAction<string>>;
// appendContent 是待追加的原始卡密文本。
appendContent: string;
// setAppendContent 更新待追加卡密文本。
setAppendContent: Dispatch<SetStateAction<string>>;
// appendResult 保存最近一次追加成功的数量。
appendResult: CardAppendResult;
// appendError 保存追加失败说明,供用户重试。
appendError: string;
// appendPreview 是按行过滤空白后的追加预览。
appendPreview: string[];
// openBatchModal 重置批量状态并打开弹窗。
openBatchModal: () => void;
// closeBatchModal 关闭弹窗并取消未完成的批量请求。
closeBatchModal: () => void;
// handleBatchCreate 执行批量创建请求。
handleBatchCreate: () => Promise<void>;
// handleBatchAppend 执行批量追加请求。
handleBatchAppend: () => Promise<void>;
// handleRetryBatchCreate 重试最近一次批量创建请求。
handleRetryBatchCreate: () => Promise<void>;
// handleRetryBatchAppend 重试最近一次追加请求。
handleRetryBatchAppend: () => Promise<void>;
}
// CardBatchModalProps 描述批量导入/追加组件的状态和动作边界。
export interface CardBatchModalProps extends CardBatchState {
// dataCards 是可追加库存的 data 类型卡密组。
dataCards: Card[];
// downloadCardTemplate 下载批量创建模板。
downloadCardTemplate: () => void;
}
+23 -237
View File
@@ -1,30 +1,13 @@
import React, { useEffect, useMemo, useState } from 'react';
import React, { useMemo, useState } from 'react';
import { createPortal } from 'react-dom';
import { Card } from '../types';
import { getCards, createCard, updateCard, deleteCard, batchCreateCards, appendCardData } from '../services/api';
import { Plus, CreditCard, Clock, FileText, Image as ImageIcon, Code, Edit, Trash2, Save, X, Eye, EyeOff, Package, Copy, Upload, Loader2, FileDown, ListPlus, Search, SlidersHorizontal } from 'lucide-react';
import { filterCards } from './cardListState';
type AddCardForm = {
name: string;
type: Card['type'];
content: string;
description: string;
enabled: boolean;
delay_seconds: number;
api_method: 'GET' | 'POST';
api_timeout: number;
api_headers: string;
api_params: string;
};
type EditCardForm = Partial<Card> & {
api_url?: string;
api_method?: 'GET' | 'POST';
api_timeout?: number;
api_headers?: string;
api_params?: string;
};
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';
const emptyAddForm = (): AddCardForm => ({
name: '',
@@ -40,37 +23,18 @@ const emptyAddForm = (): AddCardForm => ({
});
const CardList: React.FC = () => {
const [cards, setCards] = useState<Card[]>([]);
const { cards, loadCards } = useCardsData();
const [showEditModal, setShowEditModal] = useState(false);
const [showAddModal, setShowAddModal] = useState(false);
const [selectedCard, setSelectedCard] = useState<Card | null>(null);
const [editForm, setEditForm] = useState<EditCardForm>({});
const [addForm, setAddForm] = useState<AddCardForm>(emptyAddForm);
// 批量导入
const [showBatchModal, setShowBatchModal] = useState(false);
const [batchTab, setBatchTab] = useState<'create' | 'append'>('create');
const [batchFile, setBatchFile] = useState<File | null>(null);
const [batchResult, setBatchResult] = useState<any>(null);
const [batchBusy, setBatchBusy] = useState(false);
const [appendTargetId, setAppendTargetId] = useState<string>('');
const [appendContent, setAppendContent] = useState('');
const [appendResult, setAppendResult] = useState<{ added: number } | null>(null);
const [typeFilter, setTypeFilter] = useState<Card['type'] | ''>('');
const [nameSearch, setNameSearch] = useState('');
useEffect(() => {
getCards().then(setCards);
}, []);
const CardIcon = ({ type }: { type: string }) => {
switch(type) {
case 'text': return <FileText className="w-5 h-5 text-blue-500" />;
case 'image': return <ImageIcon className="w-5 h-5 text-purple-500" />;
case 'api': return <Code className="w-5 h-5 text-blue-500" />;
default: return <CreditCard className="w-5 h-5 text-gray-500" />;
}
};
// dataCards 只保留可追加库存的卡密组,并在卡密数据未变化时保持引用稳定。
const dataCards = useMemo(() => cards.filter(card => card.type === 'data'), [cards]);
const batchState = useCardBatchActions({ dataCards, loadCards });
const handleEdit = (card: Card) => {
setSelectedCard(card);
@@ -139,7 +103,7 @@ const CardList: React.FC = () => {
await updateCard(selectedCard.id, updateData);
setShowEditModal(false);
getCards().then(setCards);
await loadCards();
} catch (error) {
console.error('更新卡密失败:', error);
alert('更新失败,请重试');
@@ -150,7 +114,7 @@ const CardList: React.FC = () => {
if (confirm('确认删除该卡密吗?')) {
try {
await deleteCard(id);
getCards().then(setCards);
await loadCards();
} catch (error) {
console.error('删除卡密失败:', error);
alert('删除失败,请重试');
@@ -190,7 +154,7 @@ const CardList: React.FC = () => {
await createCard(payload);
setShowAddModal(false);
setAddForm(emptyAddForm());
getCards().then(setCards);
await loadCards();
} catch (error) {
console.error('添加卡密失败:', error);
alert('添加失败,请重试');
@@ -200,7 +164,7 @@ const CardList: React.FC = () => {
const toggleCardStatus = async (card: Card) => {
try {
await updateCard(card.id, { ...card, enabled: !card.enabled });
getCards().then(setCards);
await loadCards();
} catch (error) {
console.error('切换状态失败:', error);
}
@@ -215,7 +179,6 @@ const CardList: React.FC = () => {
}
};
const dataCards = cards.filter(c => c.type === 'data');
const filteredCards = useMemo(
() => filterCards(cards, typeFilter, nameSearch),
[cards, nameSearch, typeFilter],
@@ -242,51 +205,6 @@ const CardList: React.FC = () => {
URL.revokeObjectURL(url);
};
const handleBatchCreate = async () => {
if (!batchFile) return;
setBatchBusy(true);
setBatchResult(null);
try {
const res = await batchCreateCards(batchFile);
setBatchResult(res);
if (res.created > 0) {
const fresh = await getCards();
setCards(fresh);
}
} catch (e: any) {
setBatchResult({ error: e?.message || '上传失败' });
} finally {
setBatchBusy(false);
}
};
const handleBatchAppend = async () => {
if (!appendTargetId || !appendContent.trim()) return;
setBatchBusy(true);
setAppendResult(null);
try {
const res = await appendCardData(appendTargetId, appendContent);
setAppendResult({ added: res.added });
setAppendContent('');
const fresh = await getCards();
setCards(fresh);
} catch (e: any) {
alert('追加失败:' + (e?.message || '未知错误'));
} finally {
setBatchBusy(false);
}
};
const openBatchModal = () => {
setBatchTab('create');
setBatchFile(null);
setBatchResult(null);
setAppendTargetId(dataCards[0]?.id ? String(dataCards[0].id) : '');
setAppendContent('');
setAppendResult(null);
setShowBatchModal(true);
};
return (
<div className="space-y-6 animate-fade-in">
<div className="flex flex-col md:flex-row justify-between md:items-end gap-4">
@@ -296,7 +214,7 @@ const CardList: React.FC = () => {
</div>
<div className="flex items-center gap-3">
<button
onClick={openBatchModal}
onClick={batchState.openBatchModal}
className="px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors"
>
<Upload className="w-5 h-5" />
@@ -860,146 +778,14 @@ const CardList: React.FC = () => {
document.body
)}
{/* 批量导入弹窗 */}
{showBatchModal && createPortal(
<div className="modal-overlay">
<div className="modal-container" style={{ maxWidth: '40rem' }}>
<div className="px-6 py-5 border-b border-gray-100 flex items-center justify-between">
<h3 className="text-xl font-extrabold text-gray-900">批量导入卡密</h3>
<button
onClick={() => setShowBatchModal(false)}
className="w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center"
>
<X className="w-5 h-5 text-gray-600" />
</button>
</div>
{/* 批量导入弹窗由 cards feature 组件负责渲染和请求边界。 */}
<BatchCardImportModal
dataCards={dataCards}
downloadCardTemplate={downloadCardTemplate}
{...batchState}
/>
<div className="px-6 py-5 space-y-5">
{/* Tab 切换 */}
<div className="flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl">
<button
onClick={() => setBatchTab('create')}
className={`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${batchTab === 'create' ? 'bg-brand text-white shadow-md' : 'bg-white text-gray-600 hover:bg-gray-50'}`}
>
<ListPlus className="w-4 h-4" />
批量创建卡密组
</button>
<button
onClick={() => setBatchTab('append')}
className={`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${batchTab === 'append' ? 'bg-brand text-white shadow-md' : 'bg-white text-gray-600 hover:bg-gray-50'}`}
>
<Upload className="w-4 h-4" />
往单个组充卡密
</button>
</div>
{batchTab === 'create' ? (
<div className="space-y-4">
<div className="rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5">
上传表格,每行一个卡密组。表头:<code className="bg-blue-100/70 px-1.5 py-0.5 rounded">名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值</code>。
类型填 text/data/image;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。
</div>
<div className="flex items-center gap-3">
<button
onClick={downloadCardTemplate}
className="px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm transition-colors"
>
<FileDown className="w-4 h-4" />
下载模板
</button>
<label className="flex-1 px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm cursor-pointer transition-colors">
<Upload className="w-4 h-4" />
{batchFile ? batchFile.name : '选择 .xlsx / .csv / .tsv'}
<input type="file" accept=".xlsx,.csv,.tsv" className="hidden" onChange={e => setBatchFile(e.target.files?.[0] || null)} />
</label>
</div>
{batchResult && !batchResult.error && (
<div className="rounded-xl border border-gray-200 p-4 space-y-2">
<div className="text-sm font-bold text-gray-900">
共 {batchResult.total} 行 · 成功 {batchResult.created} · 失败 {batchResult.failed}
</div>
{batchResult.failed > 0 && (
<div className="max-h-48 overflow-y-auto space-y-1">
{batchResult.rows.filter((r: any) => !r.success).map((r: any) => (
<div key={r.row_no} className="text-xs text-red-600">第 {r.row_no} 行「{r.name}」:{r.error}</div>
))}
</div>
)}
</div>
)}
</div>
) : (
<div className="space-y-4">
{dataCards.length === 0 ? (
<div className="rounded-xl bg-amber-50 border border-amber-200 p-4 text-sm text-amber-800">
暂无 data(批量卡密)类型的卡密组,请先创建一个再充卡密。
</div>
) : (
<>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">选择卡密组</label>
<select
value={appendTargetId}
onChange={e => setAppendTargetId(e.target.value)}
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
>
{dataCards.map(c => (
<option key={c.id} value={String(c.id)}>{c.name}(ID: {c.id})</option>
))}
</select>
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">卡密号(每行一个)</label>
<textarea
value={appendContent}
onChange={e => setAppendContent(e.target.value)}
placeholder={'VIP-001\nVIP-002\nVIP-003'}
className="w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"
/>
<p className="text-xs text-gray-500">一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。</p>
</div>
{appendResult && (
<div className="rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold">
已追加 {appendResult.added} 个卡密
</div>
)}
</>
)}
</div>
)}
</div>
<div className="px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3">
<button
onClick={() => setShowBatchModal(false)}
className="px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors"
>
关闭
</button>
{batchTab === 'create' ? (
<button
onClick={handleBatchCreate}
disabled={!batchFile || batchBusy}
className="ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50"
>
{batchBusy ? <Loader2 className="w-4 h-4 animate-spin" /> : <Upload className="w-4 h-4" />}
{batchBusy ? '处理中...' : '上传创建'}
</button>
) : (
<button
onClick={handleBatchAppend}
disabled={!appendTargetId || !appendContent.trim() || batchBusy || dataCards.length === 0}
className="ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50"
>
{batchBusy ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}
{batchBusy ? '处理中...' : '追加卡密'}
</button>
)}
</div>
</div>
</div>,
document.body
)}
</div>
);
};
+7 -13
View File
@@ -1,13 +1,7 @@
import type { Card } from '../types';
export const filterCards = (
cards: Card[],
typeFilter: Card['type'] | '',
nameSearch: string,
): Card[] => {
const keyword = nameSearch.trim().toLocaleLowerCase();
return cards.filter(card => (
(!typeFilter || card.type === typeFilter)
&& (!keyword || card.name.toLocaleLowerCase().includes(keyword))
));
};
// 旧目录保留兼容入口,实际卡密筛选和批量状态逻辑已归入 cards feature。
export {
canSubmitAppend,
filterCards,
isCurrentCardRequest,
previewAppendContent,
} from '../app/features/cards/batchState';
+6 -6
View File
@@ -448,8 +448,8 @@ const cardPayload = (data: Partial<Card>): Record<string, unknown> => ({
api_config: data.api_config ? JSON.stringify(data.api_config) : '',
});
export const getCards = async (): Promise<Card[]> => {
const res = await get<Card[] | CardListResponse>('/api/v1/cards');
export const getCards = async (options?: RequestControlOptions): Promise<Card[]> => {
const res = await get<Card[] | CardListResponse>('/api/v1/cards', undefined, options);
const cards = Array.isArray(res) ? res : (res.cards || []);
return cards.map(normalizeCard);
};
@@ -472,7 +472,7 @@ export const getCardDetails = async (cardId: string | number): Promise<Card> =>
};
// 批量创建卡密组(上传表格)
export const batchCreateCards = async (file: File): Promise<CardBatchResponse> => {
export const batchCreateCards = async (file: File, options?: RequestControlOptions): Promise<CardBatchResponse> => {
// 批量创建接口返回总行数、成功数、失败数和逐行结果。
// CardBatchResponse 保留旧字段名称,调用方无需转换统计字段。
// rows 中的 id 只在创建成功时返回。
@@ -481,12 +481,12 @@ export const batchCreateCards = async (file: File): Promise<CardBatchResponse> =
// 此处只收紧 TypeScript 响应契约。
const body = new FormData();
body.append('file', file);
return postForm('/api/v1/cards/batch', body);
return postForm('/api/v1/cards/batch', body, options);
};
// 往 data 类型卡密组批量追加卡密号
export const appendCardData = async (cardId: string | number, content: string): Promise<CardAppendResponse> => {
return post(`/api/v1/cards/${cardId}/append-data`, { content });
export const appendCardData = async (cardId: string | number, content: string, options?: RequestControlOptions): Promise<CardAppendResponse> => {
return post(`/api/v1/cards/${cardId}/append-data`, { content }, options);
};
// Items