阶段七:完成OrderList React feature化与导入刷新边界
This commit is contained in:
1 parent
66ac84b32d
commit
b128ce60db
20 files changed
+1454
-1366
No files matched your search
@@ -0,0 +1,13 @@
|
||||
export {
|
||||
deleteOrder,
|
||||
getAccountDetails,
|
||||
getItems,
|
||||
getOrders,
|
||||
importOrders,
|
||||
manualShipOrder,
|
||||
syncOrders,
|
||||
syncSingleOrder,
|
||||
updateOrder,
|
||||
} from '../../../services/api';
|
||||
|
||||
// 订单 feature 通过本文件声明服务 API 来源,页面不再直接依赖通用 API 模块。
|
||||
@@ -0,0 +1,90 @@
|
||||
import React from 'react';
|
||||
import { Search, User as UserIcon } from 'lucide-react';
|
||||
import type { AccountDetail } from '../../../../types';
|
||||
import { orderStatusOptions } from '../state';
|
||||
|
||||
// OrderFilterBarProps 描述订单状态、账号和文本筛选所需的页面状态。
|
||||
export interface OrderFilterBarProps {
|
||||
// filter 是当前订单状态筛选值。
|
||||
filter: string;
|
||||
// onFilterChange 响应订单状态筛选切换。
|
||||
onFilterChange: (value: string) => void;
|
||||
// accountFilter 是当前账号筛选值。
|
||||
accountFilter: string;
|
||||
// onAccountFilterChange 响应账号筛选切换。
|
||||
onAccountFilterChange: (value: string) => void;
|
||||
// accounts 是账号下拉框的数据源。
|
||||
accounts: AccountDetail[];
|
||||
// accountName 将账号 ID 转换为展示名称。
|
||||
accountName: (cookieId: string) => string;
|
||||
// searchText 是搜索框当前输入值。
|
||||
searchText: string;
|
||||
// onSearchChange 响应订单搜索输入。
|
||||
onSearchChange: (value: string) => void;
|
||||
}
|
||||
|
||||
// OrderFilterBar 渲染订单状态、账号和关键词筛选工具栏。
|
||||
export const OrderFilterBar: React.FC<OrderFilterBarProps> = ({
|
||||
filter,
|
||||
onFilterChange,
|
||||
accountFilter,
|
||||
onAccountFilterChange,
|
||||
accounts,
|
||||
accountName,
|
||||
searchText,
|
||||
onSearchChange,
|
||||
}) => {
|
||||
// handleStatusClick 将用户选择的状态传回订单页面。
|
||||
const handleStatusClick = (event: React.MouseEvent<HTMLButtonElement>) => onFilterChange(event.currentTarget.dataset.status || 'all');
|
||||
// handleAccountChange 将用户选择的账号传回订单页面。
|
||||
const handleAccountChange = (event: React.ChangeEvent<HTMLSelectElement>) => onAccountFilterChange(event.target.value);
|
||||
// handleSearchChange 将用户输入传回订单页面。
|
||||
const handleSearchChange = (event: React.ChangeEvent<HTMLInputElement>) => onSearchChange(event.target.value);
|
||||
|
||||
return (
|
||||
<div className="p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-surface-muted">
|
||||
<div className="flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full">
|
||||
{orderStatusOptions.map(
|
||||
// option 是当前订单状态筛选标签配置。
|
||||
option => (
|
||||
<button
|
||||
key={option.key}
|
||||
data-status={option.key}
|
||||
onClick={handleStatusClick}
|
||||
className={`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${filter === option.key ? 'bg-white text-black shadow-sm' : 'text-gray-500 hover:text-gray-700'}`}
|
||||
>
|
||||
{option.label}
|
||||
</button>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
<div className="flex w-full md:w-auto flex-col sm:flex-row gap-3">
|
||||
<div className="relative">
|
||||
<UserIcon className="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none" />
|
||||
<select
|
||||
aria-label="按账号筛选订单"
|
||||
value={accountFilter}
|
||||
onChange={handleAccountChange}
|
||||
className="ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm"
|
||||
>
|
||||
<option value="">全部账号</option>
|
||||
{accounts.map(
|
||||
// account 是当前账号筛选下拉项。
|
||||
account => <option key={account.id} value={account.id}>{accountName(account.id)}</option>,
|
||||
)}
|
||||
</select>
|
||||
</div>
|
||||
<div className="relative group">
|
||||
<Search className="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="搜索订单号/商品/买家..."
|
||||
value={searchText}
|
||||
onChange={handleSearchChange}
|
||||
className="ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,94 @@
|
||||
import React from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Upload, X } from 'lucide-react';
|
||||
import { failedOrderImportRows } from '../state';
|
||||
import type { OrderImportState } from '../types';
|
||||
|
||||
// OrderImportModalProps 描述订单导入弹窗所需的状态和事件。
|
||||
export type OrderImportModalProps = OrderImportState;
|
||||
|
||||
// OrderImportModal 渲染订单文件选择、结果展示和重试操作。
|
||||
export const OrderImportModal: React.FC<OrderImportModalProps> = (state) => {
|
||||
// handleFileChange 保存用户选择的订单文件并清理旧错误。
|
||||
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
state.setImportFile(event.target.files?.[0] || null);
|
||||
};
|
||||
// handleClose 关闭订单导入弹窗。
|
||||
const handleClose = () => state.closeImportModal();
|
||||
// handleSubmit 提交当前订单导入文件。
|
||||
const handleSubmit = () => void state.handleImportOrders();
|
||||
// handleRetry 重试最近一次失败的订单导入。
|
||||
const handleRetry = () => void state.handleRetryImport();
|
||||
|
||||
if (!state.showImportModal) return null;
|
||||
|
||||
return createPortal(
|
||||
<div className="modal-overlay-centered">
|
||||
<div className="modal-container">
|
||||
<div className="modal-header">
|
||||
<div className="flex items-center justify-between w-full">
|
||||
<h3 className="text-2xl font-extrabold text-gray-900">插入订单</h3>
|
||||
<button onClick={handleClose} className="p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors">
|
||||
<X className="w-5 h-5 text-gray-600" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="modal-body space-y-5">
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">选择Excel文件</label>
|
||||
<input type="file" accept=".xlsx,.csv,.tsv,.json" onChange={handleFileChange} className="w-full ios-input px-4 py-3 rounded-xl text-sm" />
|
||||
<p className="text-xs text-gray-500 mt-2">支持 .xlsx、.csv、.tsv、.json 格式</p>
|
||||
</div>
|
||||
{state.importFile && (
|
||||
<div className="p-3 bg-blue-50 rounded-xl">
|
||||
<div className="flex items-center gap-2">
|
||||
<Upload className="w-4 h-4 text-blue-600" />
|
||||
<span className="text-sm font-medium text-blue-900">{state.importFile.name}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{state.importError && (
|
||||
<div className="rounded-xl bg-red-50 border border-red-100 p-3 text-sm text-red-700 flex items-center justify-between gap-3">
|
||||
<span>{state.importError}</span>
|
||||
<button type="button" onClick={handleRetry} disabled={state.importing || !state.importFile} className="font-bold whitespace-nowrap">重试</button>
|
||||
</div>
|
||||
)}
|
||||
{state.importResult && state.importResult.failed_count > 0 && (
|
||||
<div className="space-y-3">
|
||||
<div className="rounded-xl bg-amber-50 border border-amber-100 p-3 text-sm font-bold text-amber-800">
|
||||
导入完成:成功 {state.importResult.success_count} 条,失败 {state.importResult.failed_count} 条
|
||||
</div>
|
||||
<div className="max-h-64 overflow-y-auto rounded-xl border border-gray-100">
|
||||
<table className="w-full text-left text-xs">
|
||||
<thead className="sticky top-0 bg-gray-50 text-gray-500">
|
||||
<tr><th className="px-3 py-2">订单ID</th><th className="px-3 py-2">失败原因</th></tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100">
|
||||
{failedOrderImportRows(state.importResult).map(
|
||||
// row 是需要展示失败原因的导入结果行。
|
||||
(row, index) => (
|
||||
<tr key={`${row.order_id}-${index}`}>
|
||||
<td className="px-3 py-2 font-mono">{row.order_id}</td>
|
||||
<td className="px-3 py-2 text-red-600">{row.message || '导入失败'}</td>
|
||||
</tr>
|
||||
),
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="modal-footer">
|
||||
<div className="flex gap-3 w-full">
|
||||
<button onClick={handleClose} className="flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors">取消</button>
|
||||
<button onClick={handleSubmit} disabled={!state.importFile || state.importing} className="flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50">
|
||||
{state.importing ? '正在导入…' : '导入订单'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,349 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type Dispatch, type SetStateAction } from 'react';
|
||||
import type { AccountDetail, Item, Order } from '../../../types';
|
||||
import { getAccountDetails, getItems, getOrders, importOrders } from './api';
|
||||
import { canSubmitOrderImport, isCurrentOrderRequest, normalizeOrderImportResult, orderErrorMessage, validateOrderImportFile } from './state';
|
||||
import type { OrderImportState, OrderQueryState } from './types';
|
||||
|
||||
// OrderQueryOptions 描述订单查询 Hook 的固定分页参数。
|
||||
interface OrderQueryOptions {
|
||||
// pageSize 是每页请求的订单数量。
|
||||
pageSize: number;
|
||||
}
|
||||
|
||||
// useOrderQuery 统一管理订单列表加载、筛选、防抖和过期响应保护。
|
||||
export const useOrderQuery = (options: OrderQueryOptions = { pageSize: 20 }): OrderQueryState => {
|
||||
// orders 保存当前页订单。
|
||||
const [orders, setOrders] = useState<Order[]>([]);
|
||||
// items 保存用于补充订单商品名称的商品列表。
|
||||
const [items, setItems] = useState<Item[]>([]);
|
||||
// accounts 保存订单账号筛选下拉框的数据。
|
||||
const [accounts, setAccounts] = useState<AccountDetail[]>([]);
|
||||
// filter 保存订单状态筛选值。
|
||||
const [filter, setFilter] = useState('all');
|
||||
// accountFilter 保存账号筛选值。
|
||||
const [accountFilter, setAccountFilter] = useState('');
|
||||
// searchText 保存搜索框实时输入值。
|
||||
const [searchText, setSearchText] = useState('');
|
||||
// debouncedSearch 保存防抖后的服务端搜索值。
|
||||
const [debouncedSearch, setDebouncedSearch] = useState('');
|
||||
// page 保存当前分页页码。
|
||||
const [page, setPage] = useState(1);
|
||||
// totalPages 保存服务端返回的总页数。
|
||||
const [totalPages, setTotalPages] = useState(1);
|
||||
// loading 表示当前订单查询是否正在执行。
|
||||
const [loading, setLoading] = useState(false);
|
||||
// orderGeneration 隔离筛选变化和手动刷新的旧订单响应。
|
||||
const orderGeneration = useRef(0);
|
||||
// orderAbort 保存当前订单查询的取消控制器。
|
||||
const orderAbort = useRef<AbortController | null>(null);
|
||||
// auxiliaryAbort 保存账号和商品辅助数据请求的取消控制器。
|
||||
const auxiliaryAbort = useRef<AbortController | null>(null);
|
||||
|
||||
// loadOrders 按当前筛选条件加载订单并取消上一轮请求。
|
||||
const loadOrders = useCallback(
|
||||
// 订单加载回调读取当前筛选条件并更新列表。
|
||||
async () => {
|
||||
// generation 标记本次订单查询请求的代次。
|
||||
const generation = ++orderGeneration.current;
|
||||
orderAbort.current?.abort();
|
||||
// controller 允许筛选条件变化时取消旧查询。
|
||||
const controller = new AbortController();
|
||||
orderAbort.current = controller;
|
||||
setLoading(true);
|
||||
try {
|
||||
// result 是当前筛选条件下的分页订单结果。
|
||||
const result = await getOrders(accountFilter || undefined, filter, page, options.pageSize, debouncedSearch, { signal: controller.signal });
|
||||
if (!isCurrentOrderRequest(generation, orderGeneration.current)) return;
|
||||
setOrders(result.data);
|
||||
setTotalPages(result.total_pages);
|
||||
} catch (error /* 订单查询异常 */) {
|
||||
if (isCurrentOrderRequest(generation, orderGeneration.current) && !controller.signal.aborted) {
|
||||
console.error('加载订单失败:', error);
|
||||
}
|
||||
} finally {
|
||||
if (isCurrentOrderRequest(generation, orderGeneration.current)) setLoading(false);
|
||||
}
|
||||
},
|
||||
[accountFilter, debouncedSearch, filter, options.pageSize, page],
|
||||
);
|
||||
|
||||
// useEffect 防抖搜索输入,避免每次键入都立即请求服务端。
|
||||
useEffect(
|
||||
// 搜索防抖副作用延迟提交用户输入。
|
||||
() => {
|
||||
// timer 是当前搜索输入对应的防抖定时器。
|
||||
const timer = window.setTimeout(
|
||||
// 防抖定时器回调提交标准化搜索文本。
|
||||
() => {
|
||||
setPage(1);
|
||||
setDebouncedSearch(searchText.trim());
|
||||
},
|
||||
300,
|
||||
);
|
||||
return (
|
||||
// 防抖清理回调取消上一次搜索定时器。
|
||||
() => window.clearTimeout(timer)
|
||||
);
|
||||
},
|
||||
[searchText],
|
||||
);
|
||||
|
||||
// useEffect 在筛选条件变化时加载订单,并在离开页面时取消请求。
|
||||
useEffect(
|
||||
// 订单查询副作用响应筛选变化并在卸载时取消请求。
|
||||
() => {
|
||||
void loadOrders();
|
||||
return (
|
||||
// 订单查询清理回调使旧请求代次失效并取消网络请求。
|
||||
() => {
|
||||
orderGeneration.current += 1;
|
||||
orderAbort.current?.abort();
|
||||
}
|
||||
);
|
||||
},
|
||||
[loadOrders],
|
||||
);
|
||||
|
||||
// useEffect 加载订单展示所需的账号和商品辅助数据。
|
||||
useEffect(
|
||||
// 辅助数据副作用并行读取账号和商品列表。
|
||||
() => {
|
||||
// controller 允许页面卸载时取消辅助数据请求。
|
||||
const controller = new AbortController();
|
||||
auxiliaryAbort.current?.abort();
|
||||
auxiliaryAbort.current = controller;
|
||||
void Promise.all([
|
||||
getAccountDetails({ signal: controller.signal }),
|
||||
getItems(undefined, { signal: controller.signal }),
|
||||
]).then(
|
||||
// 辅助数据成功回调只接受尚未取消的响应。
|
||||
([accountList, itemsList]) => {
|
||||
if (controller.signal.aborted) return;
|
||||
setAccounts(accountList);
|
||||
setItems(itemsList);
|
||||
},
|
||||
).catch(
|
||||
// 辅助数据失败回调忽略主动取消产生的异常。
|
||||
(error: unknown) => {
|
||||
if (!controller.signal.aborted) console.error('加载订单辅助数据失败:', error);
|
||||
},
|
||||
);
|
||||
return (
|
||||
// 辅助数据清理回调取消账号和商品请求。
|
||||
() => controller.abort()
|
||||
);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
// accountMap 将账号 ID 映射为账号详情,避免订单列表重复线性查找。
|
||||
const accountMap = useMemo(
|
||||
// 账号索引回调构建稳定的 ID 到详情映射。
|
||||
() => new Map(accounts.map(
|
||||
// account 是当前账号详情。
|
||||
account => [account.id, account],
|
||||
)),
|
||||
[accounts],
|
||||
);
|
||||
// itemNames 将商品 ID 映射为商品标题,供订单行快速读取。
|
||||
const itemNames = useMemo(
|
||||
// 商品索引回调构建稳定的商品 ID 到标题映射。
|
||||
() => {
|
||||
// namesMap 是商品名称索引的可变构建结果。
|
||||
const namesMap: Record<string, string> = {};
|
||||
items.forEach(
|
||||
// item 是当前商品列表项。
|
||||
item => {
|
||||
if (item.item_id) namesMap[`${item.cookie_id}:${item.item_id}`] = item.item_title || item.item_id;
|
||||
},
|
||||
);
|
||||
return namesMap;
|
||||
},
|
||||
[items],
|
||||
);
|
||||
|
||||
// accountName 将账号 ID 格式化为筛选下拉框名称。
|
||||
const accountName = useCallback(
|
||||
// 账号名称回调格式化筛选下拉框文本。
|
||||
(cookieId: string): string => {
|
||||
// account 是当前订单所属账号详情。
|
||||
const account = accountMap.get(cookieId);
|
||||
// name 是优先使用备注或昵称的展示名称。
|
||||
const name = account?.remark || account?.nickname;
|
||||
return name ? `${name} · ${cookieId.slice(0, 6)}` : `账号 ${cookieId.slice(0, 8)}`;
|
||||
},
|
||||
[accountMap],
|
||||
);
|
||||
|
||||
// accountNickname 将账号 ID 格式化为订单行中的短名称。
|
||||
const accountNickname = useCallback(
|
||||
// 账号昵称回调格式化订单行文本。
|
||||
(cookieId: string): string => {
|
||||
// account 是当前订单所属账号详情。
|
||||
const account = accountMap.get(cookieId);
|
||||
return account?.remark || account?.nickname || '未命名账号';
|
||||
},
|
||||
[accountMap],
|
||||
);
|
||||
|
||||
// getItemNameById 按订单标题、商品索引和相似标题依次解析商品名称。
|
||||
const getItemNameById = useCallback(
|
||||
// 商品名称回调按订单信息解析展示标题。
|
||||
(cookieId: string, itemId: string, orderItemTitle?: string): string => {
|
||||
if (orderItemTitle?.trim()) return orderItemTitle;
|
||||
// mappedName 是商品索引中直接命中的标题。
|
||||
const mappedName = itemNames[`${cookieId}:${itemId}`];
|
||||
if (mappedName) return mappedName;
|
||||
// matchingItem 是标题相似度匹配到的商品。
|
||||
const matchingItem = items.find(
|
||||
// item 是参与标题相似度匹配的商品。
|
||||
item => {
|
||||
if (!orderItemTitle || !item.item_title) return false;
|
||||
// orderTitleLower 是订单标题的标准化小写文本。
|
||||
const orderTitleLower = orderItemTitle.toLowerCase();
|
||||
// itemTitleLower 是商品标题的标准化小写文本。
|
||||
const itemTitleLower = item.item_title.toLowerCase();
|
||||
return itemTitleLower.includes(orderTitleLower) || orderTitleLower.includes(itemTitleLower);
|
||||
},
|
||||
);
|
||||
return matchingItem?.item_title || '未知商品';
|
||||
},
|
||||
[itemNames, items],
|
||||
);
|
||||
|
||||
return {
|
||||
orders,
|
||||
items,
|
||||
accounts,
|
||||
filter,
|
||||
setFilter,
|
||||
accountFilter,
|
||||
setAccountFilter,
|
||||
searchText,
|
||||
setSearchText,
|
||||
page,
|
||||
setPage,
|
||||
totalPages,
|
||||
loading,
|
||||
loadOrders,
|
||||
accountName,
|
||||
accountNickname,
|
||||
getItemNameById,
|
||||
};
|
||||
};
|
||||
|
||||
// useOrderImport 统一管理订单导入文件、取消、重试和导入后刷新。
|
||||
export const useOrderImport = (loadOrders: () => Promise<void>): OrderImportState => {
|
||||
// showImportModal 表示订单导入弹窗是否打开。
|
||||
const [showImportModal, setShowImportModal] = useState(false);
|
||||
// importFile 保存当前选择的导入文件。
|
||||
const [importFile, setImportFile] = useState<File | null>(null);
|
||||
// importResult 保存最近一次导入的逐行结果。
|
||||
const [importResult, setImportResult] = useState<ReturnType<typeof normalizeOrderImportResult> | null>(null);
|
||||
// importing 表示导入请求是否正在执行。
|
||||
const [importing, setImporting] = useState(false);
|
||||
// importError 保存导入失败后的可重试错误。
|
||||
const [importError, setImportError] = useState('');
|
||||
// importGeneration 隔离关闭弹窗后的旧导入响应。
|
||||
const importGeneration = useRef(0);
|
||||
// importAbort 保存当前导入请求的取消控制器。
|
||||
const importAbort = useRef<AbortController | null>(null);
|
||||
|
||||
// openImportModal 打开订单导入弹窗并重置上一次结果。
|
||||
const openImportModal = useCallback(
|
||||
// 打开弹窗回调清理上一次导入状态。
|
||||
() => {
|
||||
setImportFile(null);
|
||||
setImportResult(null);
|
||||
setImportError('');
|
||||
setShowImportModal(true);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
// closeImportModal 关闭弹窗并取消未完成的导入请求。
|
||||
const closeImportModal = useCallback(
|
||||
// 关闭弹窗回调取消上传并使旧响应失效。
|
||||
() => {
|
||||
importGeneration.current += 1;
|
||||
importAbort.current?.abort();
|
||||
setImporting(false);
|
||||
setShowImportModal(false);
|
||||
setImportFile(null);
|
||||
setImportResult(null);
|
||||
setImportError('');
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
// handleImportOrders 提交文件,刷新列表并保留失败文件供重试。
|
||||
const handleImportOrders = useCallback(
|
||||
// 订单导入回调执行预检、上传和列表刷新。
|
||||
async () => {
|
||||
if (!canSubmitOrderImport(importFile, importing)) return;
|
||||
// file 是经过提交门禁确认存在的本次上传文件。
|
||||
const file = importFile;
|
||||
if (!file) return;
|
||||
// validationError 是文件预检失败时展示给用户的说明。
|
||||
const validationError = validateOrderImportFile(file);
|
||||
if (validationError) {
|
||||
setImportError(validationError);
|
||||
return;
|
||||
}
|
||||
// generation 标记当前订单导入请求的代次。
|
||||
const generation = ++importGeneration.current;
|
||||
importAbort.current?.abort();
|
||||
// controller 允许关闭弹窗时取消文件上传。
|
||||
const controller = new AbortController();
|
||||
importAbort.current = controller;
|
||||
setImporting(true);
|
||||
setImportResult(null);
|
||||
setImportError('');
|
||||
try {
|
||||
// formData 是上传订单文件的 multipart 请求体。
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
// result 是后端返回的订单导入统计。
|
||||
const result = normalizeOrderImportResult(await importOrders(formData, { signal: controller.signal }));
|
||||
if (!isCurrentOrderRequest(generation, importGeneration.current)) return;
|
||||
setImportResult(result);
|
||||
setImportFile(null);
|
||||
await loadOrders();
|
||||
if (result.failed_count === 0 && isCurrentOrderRequest(generation, importGeneration.current)) {
|
||||
alert(`订单导入成功,共 ${result.success_count} 条`);
|
||||
setShowImportModal(false);
|
||||
setImportResult(null);
|
||||
}
|
||||
} catch (error: unknown /* 订单导入异常 */) {
|
||||
if (isCurrentOrderRequest(generation, importGeneration.current) && !controller.signal.aborted) {
|
||||
setImportError(orderErrorMessage(error, '导入失败,请检查文件格式'));
|
||||
}
|
||||
} finally {
|
||||
if (isCurrentOrderRequest(generation, importGeneration.current)) setImporting(false);
|
||||
}
|
||||
},
|
||||
[importFile, importing, loadOrders],
|
||||
);
|
||||
|
||||
// handleRetryImport 复用当前文件重试最近一次失败的导入。
|
||||
const handleRetryImport = useCallback(
|
||||
// 导入重试回调复用当前文件和请求边界。
|
||||
async () => {
|
||||
await handleImportOrders();
|
||||
},
|
||||
[handleImportOrders],
|
||||
);
|
||||
|
||||
return {
|
||||
showImportModal,
|
||||
importFile,
|
||||
setImportFile,
|
||||
importResult,
|
||||
importing,
|
||||
importError,
|
||||
openImportModal,
|
||||
closeImportModal,
|
||||
handleImportOrders,
|
||||
handleRetryImport,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,54 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import {
|
||||
canSubmitOrderImport,
|
||||
failedOrderImportRows,
|
||||
isCurrentOrderRequest,
|
||||
normalizeOrderImportResult,
|
||||
orderStatusOptions,
|
||||
validateOrderImportFile,
|
||||
} from './state';
|
||||
|
||||
// createFile 创建订单导入预检使用的最小浏览器文件对象。
|
||||
const createFile = (name: string): File => new File(['order'], name, { type: 'text/plain' });
|
||||
|
||||
test('订单导入响应归一化并保留失败行详情',
|
||||
// 导入结果测试验证汇总字段和失败行展示数据。
|
||||
() => {
|
||||
// result 是包含成功和失败行的后端兼容响应。
|
||||
const result = normalizeOrderImportResult({
|
||||
total: 2,
|
||||
success_count: 1,
|
||||
failed_count: 1,
|
||||
results: [
|
||||
{ order_id: 'ok', success: true, message: '订单已导入' },
|
||||
{ order_id: 'bad', success: false, message: '不支持的订单状态' },
|
||||
],
|
||||
});
|
||||
expect(result.failed_count).toBe(1);
|
||||
expect(failedOrderImportRows(result)).toEqual([
|
||||
{ order_id: 'bad', success: false, message: '不支持的订单状态' },
|
||||
]);
|
||||
});
|
||||
|
||||
test('订单导入预检阻止重复提交和不支持的文件格式',
|
||||
// 导入预检测试验证文件格式和重复提交门禁。
|
||||
() => {
|
||||
expect(canSubmitOrderImport(createFile('orders.csv'), false)).toBe(true);
|
||||
expect(canSubmitOrderImport(createFile('orders.csv'), true)).toBe(false);
|
||||
expect(validateOrderImportFile(createFile('orders.xlsx'))).toBe('');
|
||||
expect(validateOrderImportFile(createFile('orders.exe'))).toContain('仅支持');
|
||||
expect(validateOrderImportFile(null)).toBe('请选择订单文件');
|
||||
});
|
||||
|
||||
test('订单请求代次和筛选标签保持稳定边界',
|
||||
// 查询边界测试验证旧响应隔离和筛选项顺序。
|
||||
() => {
|
||||
expect(isCurrentOrderRequest(4, 4)).toBe(true);
|
||||
expect(isCurrentOrderRequest(3, 4)).toBe(false);
|
||||
expect(orderStatusOptions.map(
|
||||
// option 是待验证顺序的筛选配置。
|
||||
option => option.key,
|
||||
)).toEqual([
|
||||
'all', 'processing', 'shipped', 'pending_ship', 'completed', 'cancelled', 'refunding',
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { OrderImportResult, OrderImportRowResult } from './types';
|
||||
|
||||
// orderStatusOptions 是订单状态筛选标签的稳定配置。
|
||||
export const orderStatusOptions = [
|
||||
{ key: 'all', label: '全部' },
|
||||
{ key: 'processing', label: '处理中' },
|
||||
{ key: 'shipped', label: '已发货' },
|
||||
{ key: 'pending_ship', label: '待发货' },
|
||||
{ key: 'completed', label: '已完成' },
|
||||
{ key: 'cancelled', label: '已取消' },
|
||||
{ key: 'refunding', label: '退款中' },
|
||||
] as const;
|
||||
|
||||
// normalizeOrderImportResult 将后端兼容响应归一化为稳定的导入结果。
|
||||
export const normalizeOrderImportResult = (value: unknown): OrderImportResult => {
|
||||
// payload 是待读取字段的未知响应对象。
|
||||
const payload = typeof value === 'object' && value !== null ? value as Record<string, unknown> : {};
|
||||
// rawResults 是后端返回的逐行结果数组。
|
||||
const rawResults = Array.isArray(payload.results) ? payload.results : [];
|
||||
return {
|
||||
total: Number(payload.total || 0),
|
||||
success_count: Number(payload.success_count || 0),
|
||||
failed_count: Number(payload.failed_count || 0),
|
||||
results: rawResults.map(normalizeOrderImportRow),
|
||||
};
|
||||
};
|
||||
|
||||
// normalizeOrderImportRow 将单行未知响应转换为导入结果行。
|
||||
const normalizeOrderImportRow = (value: unknown): OrderImportRowResult => {
|
||||
// row 是待归一化的单行未知对象。
|
||||
const row = typeof value === 'object' && value !== null ? value as Record<string, unknown> : {};
|
||||
return {
|
||||
order_id: String(row.order_id || 'unknown'),
|
||||
success: row.success === true,
|
||||
message: String(row.message || ''),
|
||||
};
|
||||
};
|
||||
|
||||
// failedOrderImportRows 筛出需要在导入弹窗中展示的失败行。
|
||||
export const failedOrderImportRows = (result: OrderImportResult | null): OrderImportRowResult[] =>
|
||||
result?.results.filter(isFailedOrderImportRow) || [];
|
||||
|
||||
// isFailedOrderImportRow 判断导入结果行是否失败。
|
||||
const isFailedOrderImportRow = (row: OrderImportRowResult): boolean => !row.success;
|
||||
|
||||
// canSubmitOrderImport 检查订单导入是否具备文件且没有重复提交。
|
||||
export const canSubmitOrderImport = (file: File | null, importing: boolean): boolean =>
|
||||
file !== null && !importing;
|
||||
|
||||
// validateOrderImportFile 检查订单导入文件是否使用支持的扩展名。
|
||||
export const validateOrderImportFile = (file: File | null): string => {
|
||||
if (!file) return '请选择订单文件';
|
||||
// extension 是文件名中最后一个点号后的标准化扩展名。
|
||||
const extension = file.name.toLowerCase().split('.').pop() || '';
|
||||
return ['xlsx', 'csv', 'tsv', 'json'].includes(extension) ? '' : '仅支持 .xlsx、.csv、.tsv、.json 格式';
|
||||
};
|
||||
|
||||
// isCurrentOrderRequest 判断异步订单请求响应是否仍属于当前代次。
|
||||
export const isCurrentOrderRequest = (generation: number, currentGeneration: number): boolean =>
|
||||
generation === currentGeneration;
|
||||
|
||||
// orderErrorMessage 将未知异常提取为稳定的用户可见说明。
|
||||
export const orderErrorMessage = (error: unknown, fallback: string): string =>
|
||||
error instanceof Error && error.message ? error.message : fallback;
|
||||
@@ -0,0 +1,96 @@
|
||||
import type { Dispatch, SetStateAction } from 'react';
|
||||
import type { AccountDetail, Item, Order, OrderStatus } from '../../../types';
|
||||
|
||||
// OrderImportRowResult 描述订单导入接口返回的单行处理结果。
|
||||
export interface OrderImportRowResult {
|
||||
// order_id 是当前导入行对应的订单号。
|
||||
order_id: string;
|
||||
// success 表示当前订单是否导入成功。
|
||||
success: boolean;
|
||||
// message 是当前订单的成功或失败说明。
|
||||
message: string;
|
||||
}
|
||||
|
||||
// OrderImportResult 描述订单导入接口返回的汇总结果。
|
||||
export interface OrderImportResult {
|
||||
// total 是本次提交的订单总数。
|
||||
total: number;
|
||||
// success_count 是成功导入的订单数。
|
||||
success_count: number;
|
||||
// failed_count 是失败订单数。
|
||||
failed_count: number;
|
||||
// results 保存每一行的处理详情。
|
||||
results: OrderImportRowResult[];
|
||||
}
|
||||
|
||||
// OrderQueryState 暴露订单列表的查询数据、筛选条件和展示辅助方法。
|
||||
export interface OrderQueryState {
|
||||
// orders 是当前页的订单列表。
|
||||
orders: Order[];
|
||||
// items 是用于补充商品标题的商品列表。
|
||||
items: Item[];
|
||||
// accounts 是订单账号筛选下拉框的数据源。
|
||||
accounts: AccountDetail[];
|
||||
// filter 是当前订单状态筛选条件。
|
||||
filter: string;
|
||||
// setFilter 更新订单状态筛选条件。
|
||||
setFilter: Dispatch<SetStateAction<string>>;
|
||||
// accountFilter 是当前账号筛选条件。
|
||||
accountFilter: string;
|
||||
// setAccountFilter 更新账号筛选条件。
|
||||
setAccountFilter: Dispatch<SetStateAction<string>>;
|
||||
// searchText 是搜索框当前输入值。
|
||||
searchText: string;
|
||||
// setSearchText 更新搜索框当前输入值。
|
||||
setSearchText: Dispatch<SetStateAction<string>>;
|
||||
// page 是当前分页页码。
|
||||
page: number;
|
||||
// setPage 更新当前分页页码。
|
||||
setPage: Dispatch<SetStateAction<number>>;
|
||||
// totalPages 是服务端返回的总页数。
|
||||
totalPages: number;
|
||||
// loading 表示订单列表或刷新请求是否正在执行。
|
||||
loading: boolean;
|
||||
// loadOrders 刷新当前筛选条件下的订单列表。
|
||||
loadOrders: () => Promise<void>;
|
||||
// accountName 将账号 ID 转换为筛选下拉框展示名称。
|
||||
accountName: (cookieId: string) => string;
|
||||
// accountNickname 将账号 ID 转换为订单行展示名称。
|
||||
accountNickname: (cookieId: string) => string;
|
||||
// getItemNameById 根据订单信息解析商品展示名称。
|
||||
getItemNameById: (cookieId: string, itemId: string, orderItemTitle?: string) => string;
|
||||
}
|
||||
|
||||
// OrderImportState 暴露订单导入弹窗的状态和事件处理函数。
|
||||
export interface OrderImportState {
|
||||
// showImportModal 表示导入弹窗是否打开。
|
||||
showImportModal: boolean;
|
||||
// importFile 是当前待提交的订单文件。
|
||||
importFile: File | null;
|
||||
// setImportFile 更新当前待提交的订单文件。
|
||||
setImportFile: Dispatch<SetStateAction<File | null>>;
|
||||
// importResult 保存最近一次导入的逐行结果。
|
||||
importResult: OrderImportResult | null;
|
||||
// importing 表示订单导入请求是否正在执行。
|
||||
importing: boolean;
|
||||
// importError 保存最近一次导入请求的错误说明。
|
||||
importError: string;
|
||||
// openImportModal 打开弹窗并清理上一次导入状态。
|
||||
openImportModal: () => void;
|
||||
// closeImportModal 关闭弹窗并取消当前导入请求。
|
||||
closeImportModal: () => void;
|
||||
// handleImportOrders 提交当前文件并刷新订单列表。
|
||||
handleImportOrders: () => Promise<void>;
|
||||
// handleRetryImport 重试最近一次失败的导入请求。
|
||||
handleRetryImport: () => Promise<void>;
|
||||
}
|
||||
|
||||
// OrderStatusOption 描述订单状态筛选标签的显示配置。
|
||||
export interface OrderStatusOption {
|
||||
// key 是传给订单查询接口的状态值。
|
||||
key: string;
|
||||
// label 是筛选标签的中文名称。
|
||||
label: string;
|
||||
// status 是可选的强类型订单状态。
|
||||
status?: OrderStatus;
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import React, { useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { AccountDetail, Order, OrderStatus, Item } from '../types';
|
||||
import { getOrders, syncOrders, syncSingleOrder, manualShipOrder, updateOrder, deleteOrder, importOrders, getItems, getAccountDetails } from '../services/api';
|
||||
import { Search, MoreHorizontal, Truck, RefreshCw, Copy, ChevronLeft, ChevronRight, PackageCheck, Edit, Eye, Plus, Save, X, User as UserIcon, Phone, MapPin, Upload, ExternalLink, Trash2 } from 'lucide-react';
|
||||
import { failedOrderImportRows, normalizeOrderImportResult, OrderImportResult } from './orderImportState';
|
||||
import type { Order, OrderStatus } from '../types';
|
||||
import { deleteOrder, manualShipOrder, syncOrders, syncSingleOrder, updateOrder } from '../app/features/orders/api';
|
||||
import { OrderFilterBar } from '../app/features/orders/components/OrderFilterBar';
|
||||
import { OrderImportModal } from '../app/features/orders/components/OrderImportModal';
|
||||
import { useOrderImport, useOrderQuery } from '../app/features/orders/hooks';
|
||||
import { Truck, RefreshCw, ChevronLeft, ChevronRight, PackageCheck, Edit, Eye, Plus, Save, X, User as UserIcon, ExternalLink, Trash2 } from 'lucide-react';
|
||||
import { formatLocalDateTime } from '../dateTime';
|
||||
|
||||
const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
|
||||
@@ -35,142 +37,40 @@ const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
|
||||
};
|
||||
|
||||
const OrderList: React.FC = () => {
|
||||
const [orders, setOrders] = useState<Order[]>([]);
|
||||
const [items, setItems] = useState<Item[]>([]);
|
||||
const [accounts, setAccounts] = useState<AccountDetail[]>([]);
|
||||
const [itemNames, setItemNames] = useState<Record<string, string>>({});
|
||||
const [filter, setFilter] = useState('all');
|
||||
const [accountFilter, setAccountFilter] = useState('');
|
||||
const [searchText, setSearchText] = useState(''); // 搜索文本
|
||||
const [debouncedSearch, setDebouncedSearch] = useState('');
|
||||
const requestSequence = useRef(0);
|
||||
const [page, setPage] = useState(1);
|
||||
const [totalPages, setTotalPages] = useState(1);
|
||||
const [loading, setLoading] = useState(false);
|
||||
// orderQuery 负责订单查询、筛选、分页和展示辅助数据。
|
||||
const orderQuery = useOrderQuery();
|
||||
// importState 负责订单导入弹窗、上传取消和失败重试。
|
||||
const importState = useOrderImport(orderQuery.loadOrders);
|
||||
const { orders, accounts, filter, setFilter, accountFilter, setAccountFilter, searchText, setSearchText, page, setPage, totalPages, loading, loadOrders, accountName, accountNickname, getItemNameById } = orderQuery;
|
||||
const [showDetailModal, setShowDetailModal] = useState(false);
|
||||
const [showEditModal, setShowEditModal] = useState(false);
|
||||
const [showImportModal, setShowImportModal] = useState(false);
|
||||
const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);
|
||||
const [editingOrder, setEditingOrder] = useState<Partial<Order> | null>(null);
|
||||
const [editForm, setEditForm] = useState<Partial<Order>>({});
|
||||
const [showShipModal, setShowShipModal] = useState(false);
|
||||
const [shipOrderId, setShipOrderId] = useState<string>('');
|
||||
const [shipLoading, setShipLoading] = useState(false);
|
||||
const [shipResult, setShipResult] = useState<{success: boolean; message: string} | null>(null);
|
||||
const [importFile, setImportFile] = useState<File | null>(null);
|
||||
const [importResult, setImportResult] = useState<OrderImportResult | null>(null);
|
||||
const [importing, setImporting] = useState(false);
|
||||
const [syncingOrderId, setSyncingOrderId] = useState<string | null>(null);
|
||||
const [deletingOrderId, setDeletingOrderId] = useState<string | null>(null);
|
||||
|
||||
const loadOrders = async () => {
|
||||
const sequence = ++requestSequence.current;
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const res = await getOrders(accountFilter || undefined, filter, page, 20, debouncedSearch);
|
||||
if (sequence !== requestSequence.current) return;
|
||||
setOrders(res.data);
|
||||
setTotalPages(res.total_pages);
|
||||
} catch (e) {
|
||||
console.error('加载订单失败:', e);
|
||||
} finally {
|
||||
if (sequence === requestSequence.current) setLoading(false);
|
||||
}
|
||||
// handleFilterChange 切换订单状态筛选并回到第一页。
|
||||
const handleFilterChange = (value: string) => {
|
||||
setFilter(value);
|
||||
setPage(1);
|
||||
setSearchText('');
|
||||
};
|
||||
|
||||
// 从订单的 item_id 查找对应的商品名称(通过标题匹配)
|
||||
const getItemNameById = (cookieId: string, orderId: string, orderItemTitle?: string): string => {
|
||||
// 如果订单有 item_title,优先使用
|
||||
if (orderItemTitle && orderItemTitle.trim()) {
|
||||
return orderItemTitle;
|
||||
}
|
||||
|
||||
// 尝试通过 item_id 直接匹配
|
||||
if (itemNames[`${cookieId}:${orderId}`]) {
|
||||
return itemNames[`${cookieId}:${orderId}`];
|
||||
}
|
||||
|
||||
// 尝试在商品列表中查找相似标题的商品
|
||||
const matchingItem = items.find(item => {
|
||||
// 如果订单有标题,尝试匹配商品标题
|
||||
if (orderItemTitle && item.item_title) {
|
||||
// 检查是否包含关键词
|
||||
const orderTitleLower = orderItemTitle.toLowerCase();
|
||||
const itemTitleLower = item.item_title.toLowerCase();
|
||||
return itemTitleLower.includes(orderTitleLower) || orderTitleLower.includes(itemTitleLower);
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
if (matchingItem?.item_title) {
|
||||
return matchingItem.item_title;
|
||||
}
|
||||
|
||||
return '未知商品';
|
||||
// handleAccountFilterChange 切换账号筛选并回到第一页。
|
||||
const handleAccountFilterChange = (value: string) => {
|
||||
setAccountFilter(value);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
// 从商品列表构建商品ID到商品名的映射
|
||||
const buildItemNamesMap = () => {
|
||||
const namesMap: Record<string, string> = {};
|
||||
items.forEach(item => {
|
||||
// 使用 item_id 作为键,商品标题作为值
|
||||
if (item.item_id) {
|
||||
namesMap[`${item.cookie_id}:${item.item_id}`] = item.item_title || item.item_id;
|
||||
}
|
||||
});
|
||||
setItemNames(namesMap);
|
||||
};
|
||||
|
||||
const buildItemNamesMapFrom = (itemsList: Item[]) => {
|
||||
const namesMap: Record<string, string> = {};
|
||||
itemsList.forEach(item => {
|
||||
if (item.item_id) {
|
||||
namesMap[`${item.cookie_id}:${item.item_id}`] = item.item_title || item.item_id;
|
||||
}
|
||||
});
|
||||
setItemNames(namesMap);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const timer = window.setTimeout(() => {
|
||||
setPage(1);
|
||||
setDebouncedSearch(searchText.trim());
|
||||
}, 300);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [searchText]);
|
||||
|
||||
useEffect(() => {
|
||||
loadOrders();
|
||||
}, [accountFilter, filter, page, debouncedSearch]);
|
||||
|
||||
useEffect(() => {
|
||||
Promise.all([getAccountDetails(), getItems()]).then(([accountList, itemsList]) => {
|
||||
setAccounts(accountList);
|
||||
setItems(itemsList);
|
||||
buildItemNamesMapFrom(itemsList);
|
||||
}).catch((e) => {
|
||||
console.error('加载商品列表失败:', e);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const accountMap = useMemo(
|
||||
() => new Map(accounts.map(account => [account.id, account])),
|
||||
[accounts],
|
||||
);
|
||||
|
||||
const accountName = (cookieId: string) => {
|
||||
const account = accountMap.get(cookieId);
|
||||
const name = account?.remark || account?.nickname;
|
||||
return name ? `${name} · ${cookieId.slice(0, 6)}` : `账号 ${cookieId.slice(0, 8)}`;
|
||||
};
|
||||
const accountNickname = (cookieId: string) => {
|
||||
const account = accountMap.get(cookieId);
|
||||
return account?.remark || account?.nickname || '未命名账号';
|
||||
// handleSearchChange 更新订单搜索文本并回到第一页。
|
||||
const handleSearchChange = (value: string) => {
|
||||
setSearchText(value);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const handleSync = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const result = await syncOrders(accountFilter || undefined, filter);
|
||||
await loadOrders();
|
||||
@@ -180,8 +80,6 @@ const OrderList: React.FC = () => {
|
||||
} catch (error: any) {
|
||||
console.error('同步订单失败:', error);
|
||||
alert(error?.message || '同步失败,请重试');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -264,35 +162,6 @@ const OrderList: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleImportOrders = async () => {
|
||||
if (!importFile) return;
|
||||
setImporting(true);
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('file', importFile);
|
||||
const result = normalizeOrderImportResult(await importOrders(formData));
|
||||
setImportResult(result);
|
||||
setImportFile(null);
|
||||
await loadOrders();
|
||||
if (result.failed_count === 0) {
|
||||
setShowImportModal(false);
|
||||
setImportResult(null);
|
||||
alert(`订单导入成功,共 ${result.success_count} 条`);
|
||||
}
|
||||
} catch (error: any) {
|
||||
alert(error?.message || '导入失败,请检查文件格式');
|
||||
} finally {
|
||||
setImporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const closeImportModal = () => {
|
||||
if (importing) return;
|
||||
setShowImportModal(false);
|
||||
setImportFile(null);
|
||||
setImportResult(null);
|
||||
};
|
||||
|
||||
const handleSyncSingle = async (orderId: string) => {
|
||||
setSyncingOrderId(orderId);
|
||||
try {
|
||||
@@ -341,7 +210,7 @@ const OrderList: React.FC = () => {
|
||||
<RefreshCw className={`w-5 h-5 ${loading ? 'animate-spin' : ''}`} />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => { setImportResult(null); setShowImportModal(true); }}
|
||||
onClick={importState.openImportModal}
|
||||
className="px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors text-sm flex items-center gap-2 shadow-lg"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
@@ -355,54 +224,16 @@ const OrderList: React.FC = () => {
|
||||
</div>
|
||||
|
||||
<div className="ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white">
|
||||
{/* Toolbar */}
|
||||
<div className="p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-surface-muted">
|
||||
<div className="flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full">
|
||||
{[
|
||||
{k:'all', v:'全部'},
|
||||
{k:'processing', v:'处理中'},
|
||||
{k:'shipped', v:'已发货'},
|
||||
{k:'pending_ship', v:'待发货'},
|
||||
{k:'completed', v:'已完成'},
|
||||
{k:'cancelled', v:'已取消'},
|
||||
{k:'refunding', v:'退款中'}
|
||||
].map(opt => (
|
||||
<button
|
||||
key={opt.k}
|
||||
onClick={() => { setFilter(opt.k); setPage(1); setSearchText(''); }}
|
||||
className={`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${filter === opt.k ? 'bg-white text-black shadow-sm' : 'text-gray-500 hover:text-gray-700'}`}
|
||||
>
|
||||
{opt.v}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex w-full md:w-auto flex-col sm:flex-row gap-3">
|
||||
<div className="relative">
|
||||
<UserIcon className="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none" />
|
||||
<select
|
||||
aria-label="按账号筛选订单"
|
||||
value={accountFilter}
|
||||
onChange={(event) => { setAccountFilter(event.target.value); setPage(1); }}
|
||||
className="ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm"
|
||||
>
|
||||
<option value="">全部账号</option>
|
||||
{accounts.map(account => (
|
||||
<option key={account.id} value={account.id}>{accountName(account.id)}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="relative group">
|
||||
<Search className="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="搜索订单号/商品/买家..."
|
||||
value={searchText}
|
||||
onChange={(e) => { setSearchText(e.target.value); setPage(1); }}
|
||||
className="ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<OrderFilterBar
|
||||
filter={filter}
|
||||
onFilterChange={handleFilterChange}
|
||||
accountFilter={accountFilter}
|
||||
onAccountFilterChange={handleAccountFilterChange}
|
||||
accounts={accounts}
|
||||
accountName={accountName}
|
||||
searchText={searchText}
|
||||
onSearchChange={handleSearchChange}
|
||||
/>
|
||||
|
||||
{/* Table */}
|
||||
<div className="overflow-x-auto min-h-[400px]">
|
||||
@@ -673,89 +504,7 @@ const OrderList: React.FC = () => {
|
||||
document.body
|
||||
)}
|
||||
|
||||
{/* Import Modal - 使用 Portal */}
|
||||
{showImportModal && createPortal(
|
||||
<div className="modal-overlay-centered">
|
||||
<div className="modal-container">
|
||||
<div className="modal-header">
|
||||
<div className="flex items-center justify-between w-full">
|
||||
<h3 className="text-2xl font-extrabold text-gray-900">插入订单</h3>
|
||||
<button
|
||||
onClick={closeImportModal}
|
||||
className="p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors"
|
||||
>
|
||||
<X className="w-5 h-5 text-gray-600" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="modal-body space-y-5">
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">选择Excel文件</label>
|
||||
<input
|
||||
type="file"
|
||||
accept=".xlsx,.csv,.tsv,.json"
|
||||
onChange={(e) => setImportFile(e.target.files?.[0] || null)}
|
||||
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
|
||||
/>
|
||||
<p className="text-xs text-gray-500 mt-2">支持 .xlsx、.csv、.tsv、.json 格式</p>
|
||||
</div>
|
||||
|
||||
{importFile && (
|
||||
<div className="p-3 bg-blue-50 rounded-xl">
|
||||
<div className="flex items-center gap-2">
|
||||
<Upload className="w-4 h-4 text-blue-600" />
|
||||
<span className="text-sm font-medium text-blue-900">{importFile.name}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{importResult && importResult.failed_count > 0 && (
|
||||
<div className="space-y-3">
|
||||
<div className="rounded-xl bg-amber-50 border border-amber-100 p-3 text-sm font-bold text-amber-800">
|
||||
导入完成:成功 {importResult.success_count} 条,失败 {importResult.failed_count} 条
|
||||
</div>
|
||||
<div className="max-h-64 overflow-y-auto rounded-xl border border-gray-100">
|
||||
<table className="w-full text-left text-xs">
|
||||
<thead className="sticky top-0 bg-gray-50 text-gray-500">
|
||||
<tr><th className="px-3 py-2">订单ID</th><th className="px-3 py-2">失败原因</th></tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100">
|
||||
{failedOrderImportRows(importResult).map((row, index) => (
|
||||
<tr key={`${row.order_id}-${index}`}>
|
||||
<td className="px-3 py-2 font-mono">{row.order_id}</td>
|
||||
<td className="px-3 py-2 text-red-600">{row.message || '导入失败'}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="modal-footer">
|
||||
<div className="flex gap-3 w-full">
|
||||
<button
|
||||
onClick={closeImportModal}
|
||||
disabled={importing}
|
||||
className="flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors"
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
<button
|
||||
onClick={handleImportOrders}
|
||||
disabled={!importFile || importing}
|
||||
className="flex-1 px-6 py-3 rounded-xl ios-btn-primary font-bold shadow-lg shadow-blue-200 disabled:opacity-50"
|
||||
>
|
||||
{importing ? '正在导入…' : '导入订单'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>,
|
||||
document.body
|
||||
)}
|
||||
<OrderImportModal {...importState} />
|
||||
|
||||
{/* Ship Modal - 发货方式选择 */}
|
||||
{showShipModal && createPortal(
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import { failedOrderImportRows, normalizeOrderImportResult } from './orderImportState';
|
||||
|
||||
test('order import state preserves row-level failure details for display', () => {
|
||||
const result = normalizeOrderImportResult({
|
||||
total: 2,
|
||||
success_count: 1,
|
||||
failed_count: 1,
|
||||
results: [
|
||||
{ order_id: 'ok', success: true, message: '订单已导入' },
|
||||
{ order_id: 'bad', success: false, message: '不支持的订单状态' },
|
||||
],
|
||||
});
|
||||
expect(result.failed_count).toBe(1);
|
||||
expect(failedOrderImportRows(result)).toEqual([
|
||||
{ order_id: 'bad', success: false, message: '不支持的订单状态' },
|
||||
]);
|
||||
});
|
||||
@@ -1,26 +1,8 @@
|
||||
export interface OrderImportRowResult {
|
||||
order_id: string;
|
||||
success: boolean;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface OrderImportResult {
|
||||
total: number;
|
||||
success_count: number;
|
||||
failed_count: number;
|
||||
results: OrderImportRowResult[];
|
||||
}
|
||||
|
||||
export const normalizeOrderImportResult = (value: any): OrderImportResult => ({
|
||||
total: Number(value?.total || 0),
|
||||
success_count: Number(value?.success_count || 0),
|
||||
failed_count: Number(value?.failed_count || 0),
|
||||
results: Array.isArray(value?.results) ? value.results.map((row: any) => ({
|
||||
order_id: String(row?.order_id || 'unknown'),
|
||||
success: row?.success === true,
|
||||
message: String(row?.message || ''),
|
||||
})) : [],
|
||||
});
|
||||
|
||||
export const failedOrderImportRows = (result: OrderImportResult | null): OrderImportRowResult[] =>
|
||||
result?.results.filter(row => !row.success) || [];
|
||||
export {
|
||||
failedOrderImportRows,
|
||||
normalizeOrderImportResult,
|
||||
} from '../app/features/orders/state';
|
||||
export type {
|
||||
OrderImportResult,
|
||||
OrderImportRowResult,
|
||||
} from '../app/features/orders/types';
|
||||
@@ -146,6 +146,20 @@ test('getOrders maps unsupported backend statuses to unknown', async () => {
|
||||
expect(result.data[0].status).toBe('unknown');
|
||||
});
|
||||
|
||||
test('订单查询和导入 API 转发外部取消信号', async () => {
|
||||
// fetchMock 是同时验证订单查询和文件上传请求控制参数的替身。
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(jsonResponse({ data: [], total_pages: 1 }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success_count: 1, failed_count: 0, results: [] }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
// controller 是 feature Hook 传入 API 的取消控制器。
|
||||
const controller = new AbortController();
|
||||
await getOrders(undefined, 'all', 1, 20, '', { signal: controller.signal });
|
||||
await importOrders(new FormData(), { signal: controller.signal });
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/v1/orders?page=1&page_size=20', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/v1/orders/import', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
});
|
||||
|
||||
test('getShippingRulesPage sends filters and preserves pagination metadata', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({
|
||||
data: [{ id: 7, name: '付款规则', trigger_type: 'order_paid', enabled: false, actions: [] }],
|
||||
|
||||
@@ -308,13 +308,14 @@ export const getOrders = async (
|
||||
page: number = 1,
|
||||
pageSize: number = 20,
|
||||
search?: string,
|
||||
options?: RequestControlOptions,
|
||||
): Promise<PaginatedResponse<Order>> => {
|
||||
const params: any = { page, page_size: pageSize };
|
||||
if (cookieId) params.cookie_id = cookieId;
|
||||
if (status && status !== 'all') params.status = status;
|
||||
if (search?.trim()) params.search = search.trim();
|
||||
|
||||
const res = await get<PaginatedResponse<Order> & { orders?: Order[] /* 后端兼容的订单列表字段。 */ }>('/api/v1/orders', params);
|
||||
const res = await get<PaginatedResponse<Order> & { orders?: Order[] /* 后端兼容的订单列表字段。 */ }>('/api/v1/orders', params, options);
|
||||
|
||||
// Handle backend response variations
|
||||
const rawOrders = res.orders || res.data || [];
|
||||
@@ -369,9 +370,9 @@ export const manualShipOrder = async (orderIds: string[], shipMode: 'status_only
|
||||
});
|
||||
}
|
||||
|
||||
export const importOrders = async (data: Partial<Order>[] | FormData): Promise<OrderBatchResponse> => {
|
||||
export const importOrders = async (data: Partial<Order>[] | FormData, options?: RequestControlOptions): Promise<OrderBatchResponse> => {
|
||||
const isFormData = data instanceof FormData;
|
||||
return isFormData ? postForm('/api/v1/orders/import', data) : post('/api/v1/orders/import', data);
|
||||
return isFormData ? postForm('/api/v1/orders/import', data, options) : post('/api/v1/orders/import', data, options);
|
||||
}
|
||||
|
||||
// Stats
|
||||
@@ -493,8 +494,8 @@ export const appendCardData = async (cardId: string | number, content: string, o
|
||||
const normalizeBooleanFlag = (value: unknown): boolean =>
|
||||
value === true || value === 1 || value === '1';
|
||||
|
||||
export const getItems = async (cookieId?: string): Promise<Item[]> => {
|
||||
const res = await get<Item[] | ItemListEnvelope>('/api/v1/items', cookieId ? { cookie_id: cookieId } : undefined);
|
||||
export const getItems = async (cookieId?: string, options?: RequestControlOptions): Promise<Item[]> => {
|
||||
const res = await get<Item[] | ItemListEnvelope>('/api/v1/items', cookieId ? { cookie_id: cookieId } : undefined, options);
|
||||
const items = Array.isArray(res) ? res : (res.items || []);
|
||||
return items.map((item: any) => ({
|
||||
...item,
|
||||
|
||||
Reference in new issue
Block a user