重构:完成架构一致性整改与生命周期收口
This commit is contained in:
1 parent
55904cc409
commit
9eb6be2875
344 files changed
+15961
-13926
No files matched your search
@@ -198,7 +198,7 @@ export interface PasswordLoginStatusResponse {
|
||||
/** verification_url 表示验证地址。 */ verification_url?: string;
|
||||
/** screenshot_path 表示验证截图路径。 */ screenshot_path?: string;
|
||||
/** qr_code_url 表示二维码地址。 */ qr_code_url?: string;
|
||||
/** error 表示错误信息。 */ error?: string;
|
||||
/** error 保存密码登录流程返回的失败说明;前端只用于界面提示,不应记录或序列化登录凭证。 */ error?: string;
|
||||
/** reason 表示失败原因。 */ reason?: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -135,7 +135,7 @@ const AccountList: React.FC = () => {
|
||||
await deleteAccount(account.id);
|
||||
setAccounts(/* 当前回调处理集合中的单个元素。 */ current => current.filter(/* 当前回调处理集合中的单个元素。 */ item => item.id !== account.id));
|
||||
setDeleteDialogAccount(null);
|
||||
} catch (/* error 表示错误。 */ error: any) {
|
||||
} catch (/* error 保存账号删除请求的失败原因,仅转换为界面提示。 */ error: any) {
|
||||
console.error('删除账号失败:', error);
|
||||
setDeleteError(error?.message || '删除账号失败,请稍后重试');
|
||||
} finally {
|
||||
@@ -153,7 +153,7 @@ const AccountList: React.FC = () => {
|
||||
alert('资料刷新失败:' + res.profile_error);
|
||||
}
|
||||
await loadAccounts();
|
||||
} catch (/* error 表示错误。 */ error: any) {
|
||||
} catch (/* error 保存资料刷新请求的失败原因,仅转换为界面提示。 */ error: any) {
|
||||
console.error('刷新账号资料失败:', error);
|
||||
alert(error?.message || '刷新账号资料失败,请先重新授权该账号');
|
||||
} finally {
|
||||
|
||||
@@ -146,7 +146,7 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct
|
||||
// result 保存长登录设置接口返回值。
|
||||
const result = await setLongLoginSettings(editingAccount.id, enabled);
|
||||
setLongLogin({ loading: false, saving: false, canOpen: result.can_open_long_login, enabled: result.enabled, error: '' });
|
||||
} catch (/* error 表示错误。 */ error) {
|
||||
} catch (/* error 保存长登录开关请求的失败原因,供弹窗展示且不泄露凭证。 */ error) {
|
||||
// error 保存长登录设置保存失败原因。
|
||||
setLongLogin(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, saving: false, error: error instanceof Error ? error.message : '保存登录信息设置失败' }));
|
||||
}
|
||||
@@ -169,7 +169,7 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct
|
||||
const settings = await getAccountAISettings(account.id, { signal: controller.signal });
|
||||
if (!isCurrentAccountRequest(sequence, aiSequence.current, account.id, account.id)) return;
|
||||
setAiSettings({ ai_enabled: settings.ai_enabled ?? false, max_discount_percent: settings.max_discount_percent ?? 10, max_discount_amount: settings.max_discount_amount ?? 100, max_bargain_rounds: settings.max_bargain_rounds ?? 3, custom_prompts: settings.custom_prompts ?? '' });
|
||||
} catch (/* error 表示错误。 */ error) {
|
||||
} catch (/* error 保存 AI 设置读取请求的失败原因,过期请求不会更新当前界面。 */ error) {
|
||||
// error 保存 AI 设置读取失败原因。
|
||||
if (isCurrentAccountRequest(sequence, aiSequence.current, account.id, account.id)) console.error('加载 AI 设置失败:', error);
|
||||
} finally {
|
||||
@@ -186,7 +186,7 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct
|
||||
await updateAccountAISettings(editingAccount.id, aiSettings);
|
||||
setActiveModal(null);
|
||||
await loadAccounts();
|
||||
} catch (/* error 表示错误。 */ error) {
|
||||
} catch (/* error 保存 AI 设置提交请求的失败原因,转换为通用错误提示。 */ error) {
|
||||
// error 保存 AI 设置保存失败原因。
|
||||
console.error('更新 AI 设置失败:', error);
|
||||
} finally { setSaving(false); }
|
||||
@@ -212,7 +212,7 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct
|
||||
if (Object.keys(payload).length > 0) await updateAccountSettings(editingAccount.id, payload);
|
||||
setActiveModal(null);
|
||||
await loadAccounts();
|
||||
} catch (/* error 表示错误。 */ error) {
|
||||
} catch (/* error 保存账号设置提交请求的失败原因,转换为通用错误提示。 */ error) {
|
||||
// error 保存账号编辑保存失败原因。
|
||||
console.error('更新账号失败:', error);
|
||||
} finally { setSaving(false); }
|
||||
@@ -228,7 +228,7 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct
|
||||
const result = await updateAccountPauseDuration(editingAccount.id, editForm.pause_duration);
|
||||
setEditingAccount(/* 当前回调处理用户交互或异步状态变化。 */ current => current ? { ...current, pause_duration: editForm.pause_duration, paused: result?.paused === true, paused_until: Number(result?.paused_until || 0) } : current);
|
||||
await loadAccounts();
|
||||
} catch (/* error 表示错误。 */ error) { console.error('重新暂停失败:', error); }
|
||||
} catch (/* error 保存重新暂停请求的失败原因,仅输出不含凭证的诊断信息。 */ error) { console.error('重新暂停失败:', error); }
|
||||
finally { setSaving(false); }
|
||||
}, [editForm.pause_duration, editingAccount, loadAccounts, saving, setEditingAccount]);
|
||||
|
||||
@@ -260,7 +260,7 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct
|
||||
}
|
||||
clearPasswordTimer();
|
||||
setPasswordLoginView(nextView);
|
||||
} catch (/* error 表示错误。 */ error) {
|
||||
} catch (/* error 保存密码登录状态查询的失败原因,过期代次不会覆盖当前状态。 */ error) {
|
||||
// error 保存密码登录状态查询失败原因。
|
||||
if (!isCurrentAccountRequest(generation, passwordGeneration.current, accountId, passwordAccount.current)) return;
|
||||
clearPasswordTimer();
|
||||
@@ -291,7 +291,7 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct
|
||||
if (!result.success || !result.session_id) throw new Error(result.message || '无法启动密码登录');
|
||||
setPasswordLoginView({ sessionId: result.session_id, status: 'processing', message: result.message || '登录处理中', qrCodeUrl: '' });
|
||||
await pollPasswordLogin(result.session_id, generation, editingAccount.id);
|
||||
} catch (/* error 表示错误。 */ error) {
|
||||
} catch (/* error 保存密码登录启动请求的失败原因,转换为安全的登录提示。 */ error) {
|
||||
// error 保存密码登录启动失败原因。
|
||||
if (!isCurrentAccountRequest(generation, passwordGeneration.current, editingAccount.id, passwordAccount.current)) return;
|
||||
setPasswordLoginView({ sessionId: '', status: 'failed', message: error instanceof Error ? error.message : '启动密码登录失败', qrCodeUrl: '' });
|
||||
|
||||
@@ -27,7 +27,7 @@ import { getHealth } from './system/api';
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:全局 API 适配器测试环境清理。 */);
|
||||
|
||||
test('updateSystemSettings uses one atomic bulk request', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
@@ -36,7 +36,7 @@ test('updateSystemSettings uses one atomic bulk request', async () => {
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/settings/system', expect.objectContaining({ method: 'PUT', credentials: 'include' }));
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ theme_color: 'blue', renewal_log_retention_days: 15 });
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:updateSystemSettings uses one atomic bulk request。 */);
|
||||
|
||||
test('updateSystemSettings separates sensitive values into explicit commands', /* 当前回调验证敏感设置三态命令请求体。 */ async () => {
|
||||
// fetchMock 是系统设置更新请求的 HTTP 替身。
|
||||
@@ -60,13 +60,13 @@ test('health API exposes build metadata through the request boundary', async ()
|
||||
|
||||
await expect(getHealth({ signal: controller.signal })).resolves.toEqual({ version: '1.2.3', commit: 'abc123' });
|
||||
expect(fetchMock).toHaveBeenCalledWith('/health', expect.objectContaining({ method: 'GET', signal: expect.any(AbortSignal) }));
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:health API exposes build metadata through the request boundary。 */);
|
||||
|
||||
test('chat APIs preserve account and conversation scope', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(jsonResponse({ sessions: [{ account_id: 'a1', chat_id: 'c1' }] }))
|
||||
.mockResolvedValueOnce(jsonResponse({ messages: [{ account_id: 'a1', chat_id: 'c1', id: 1 }] }))
|
||||
.mockImplementation(() => Promise.resolve(jsonResponse({ success: true, message: { id: 2 } })) /* 回调函数负责当前业务流程。 */); /* fetchMock 表示fetchMock。 */
|
||||
.mockImplementation(() => Promise.resolve(jsonResponse({ success: true, message: { id: 2 } })) /* 模拟新增动作接口返回包含标识的成功响应。 */); /* fetchMock 是本测试替代浏览器网络层的请求桩。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await getChatSessions('a1');
|
||||
await getChatMessages('a1', 'c1', 9);
|
||||
@@ -76,7 +76,7 @@ test('chat APIs preserve account and conversation scope', async () => {
|
||||
expect(fetchMock.mock.calls[1][0]).toBe('/api/v1/chat/messages?account_id=a1&chat_id=c1&before_id=9');
|
||||
expect(JSON.parse(fetchMock.mock.calls[2][1].body)).toMatchObject({ account_id: 'a1', chat_id: 'c1', buyer_id: 'b1' });
|
||||
expect(JSON.parse(fetchMock.mock.calls[3][1].body)).toEqual({ account_id: 'a1', chat_id: 'c1', message_ids: [{ messageId: 'm1', sessionId: 'c1', cid: 'c1@goofish', conversationType: 1 }] });
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:chat APIs preserve account and conversation scope。 */);
|
||||
|
||||
test('Chat 会话、消息和发送 API 转发外部取消信号', async () => {
|
||||
// fetchMock 验证会话切换、消息分页和文本/图片发送共享取消控制能力。
|
||||
@@ -99,10 +99,10 @@ test('Chat 会话、消息和发送 API 转发外部取消信号', async () => {
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(3, '/api/v1/chat/messages', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(4, '/api/v1/chat/images', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(5, '/api/v1/chat/read', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:Chat 会话、消息和发送 API 转发外部取消信号。 */);
|
||||
|
||||
test('account task APIs keep rating and polish account-scoped', async () => {
|
||||
const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(jsonResponse({ success: true, summary: { task_type: 'auto_rate' } })) /* 回调函数负责当前业务流程。 */); /* fetchMock 表示fetchMock。 */
|
||||
const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(jsonResponse({ success: true, summary: { task_type: 'auto_rate' } })) /* 模拟账号任务执行后返回任务摘要。 */); /* fetchMock 是本测试替代浏览器网络层的请求桩。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await updateAccountTaskSettings('a1', {
|
||||
account_id: 'a1', auto_rate_enabled: true, rate_content: '交易愉快',
|
||||
@@ -113,7 +113,7 @@ test('account task APIs keep rating and polish account-scoped', async () => {
|
||||
expect(fetchMock.mock.calls[0][1].method).toBe('PUT');
|
||||
expect(fetchMock.mock.calls[1][0]).toBe('/api/v1/account-tasks/a1/run');
|
||||
expect(JSON.parse(fetchMock.mock.calls[1][1].body)).toEqual({ task_type: 'auto_rate' });
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:account task APIs keep rating and polish account-scoped。 */);
|
||||
|
||||
test('账号自动任务 API 转发外部取消信号', async () => {
|
||||
// fetchMock 验证读取、保存和执行账号任务都支持请求取消。
|
||||
@@ -131,19 +131,19 @@ test('账号自动任务 API 转发外部取消信号', async () => {
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/v1/account-tasks/a1', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/v1/account-tasks/a1', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(3, '/api/v1/account-tasks/a1/run', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:账号自动任务 API 转发外部取消信号。 */);
|
||||
|
||||
test('getItemPublishBatches unwraps persisted batch list', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ batches: [{ id: 'batch-1', status: 'running' }] })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await expect(getItemPublishBatches(10)).resolves.toEqual([{ id: 'batch-1', status: 'running' }]);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/items/publish-batches?limit=10', expect.objectContaining({ credentials: 'include' }));
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:getItemPublishBatches unwraps persisted batch list。 */);
|
||||
|
||||
test('automation issue APIs expose and resolve quarantined work', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(jsonResponse({ runs: [{ id: 1 }], pending_tasks: [{ id: 2 }] }))
|
||||
.mockImplementation(() => Promise.resolve(jsonResponse({ success: true })) /* 回调函数负责当前业务流程。 */); /* fetchMock 表示fetchMock。 */
|
||||
.mockImplementation(() => Promise.resolve(jsonResponse({ success: true })) /* 模拟无消息体的成功操作响应。 */); /* fetchMock 是本测试替代浏览器网络层的请求桩。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await expect(getAutomationIssues()).resolves.toEqual({ runs: [{ id: 1 }], pending_tasks: [{ id: 2 }] });
|
||||
await resolveAutomationRun(1, 'continue');
|
||||
@@ -151,7 +151,7 @@ test('automation issue APIs expose and resolve quarantined work', async () => {
|
||||
expect(fetchMock.mock.calls[1][0]).toBe('/api/v1/automation-runs/1/resolve');
|
||||
expect(JSON.parse(fetchMock.mock.calls[1][1].body)).toEqual({ resolution: 'continue' });
|
||||
expect(fetchMock.mock.calls[2][0]).toBe('/api/v1/automation-pending-tasks/2/resolve');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:automation issue APIs expose and resolve quarantined work。 */);
|
||||
|
||||
test('order multipart requests use the shared authenticated form request path', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
@@ -164,7 +164,7 @@ test('order multipart requests use the shared authenticated form request path',
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/v1/orders/refresh', expect.objectContaining({ method: 'POST', credentials: 'include', body: expect.any(FormData) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/v1/orders/refresh/job-1', expect.objectContaining({ method: 'GET', credentials: 'include' }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(3, '/api/v1/orders/import', expect.objectContaining({ method: 'POST', credentials: 'include', body: expect.any(FormData) }));
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:order multipart requests use the shared authenticated form request path。 */);
|
||||
|
||||
test('syncOrders surfaces failed persisted job status', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
@@ -172,7 +172,7 @@ test('syncOrders surfaces failed persisted job status', async () => {
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-failed', status: 'failed', error_message: '平台会话已过期' })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await expect(syncOrders()).rejects.toThrow('平台会话已过期');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:syncOrders surfaces failed persisted job status。 */);
|
||||
|
||||
test('syncOrders aborts while waiting for persisted job status', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
@@ -188,20 +188,20 @@ test('syncOrders aborts while waiting for persisted job status', async () => {
|
||||
controller.abort();
|
||||
await expect(pending).rejects.toThrow('请求已取消');
|
||||
await vi.waitFor(/* 等待取消命令发出。 */ () => expect(fetchMock).toHaveBeenCalledWith('/api/v1/orders/refresh/job-running', expect.objectContaining({ method: 'DELETE', credentials: 'include' })));
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:syncOrders aborts while waiting for persisted job status。 */);
|
||||
|
||||
test('cancelOrderRefreshJob sends a user-scoped delete command', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, job_id: 'job-cancel', status: 'cancelled' })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await expect(cancelOrderRefreshJob('job-cancel')).resolves.toEqual({ success: true, job_id: 'job-cancel', status: 'cancelled' });
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/orders/refresh/job-cancel', expect.objectContaining({ method: 'DELETE', credentials: 'include' }));
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:cancelOrderRefreshJob sends a user-scoped delete command。 */);
|
||||
|
||||
test('legacy notification channel aliases are normalized for the editor', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([{ id: 1, name: '旧飞书', type: 'lark', config: 'not-json', enabled: true }])));
|
||||
const result = await getNotificationChannels(); /* result 表示处理结果。 */
|
||||
expect(result.data?.[0]).toMatchObject({ type: 'feishu', config: {} });
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:legacy notification channel aliases are normalized for the editor。 */);
|
||||
|
||||
const jsonResponse = (body: unknown) => new Response(JSON.stringify(body), {
|
||||
status: 200,
|
||||
@@ -218,7 +218,7 @@ test('getOrders normalizes backend order fields', async () => {
|
||||
expect(result.data[0]).toMatchObject({ id: 'o1', status: 'shipped', quantity: 2 });
|
||||
expect(result.total).toBe(1);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/orders?page=1&page_size=20&search=buyer', expect.objectContaining({ method: 'GET' }));
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:getOrders normalizes backend order fields。 */);
|
||||
|
||||
test('getOrders maps unsupported backend statuses to unknown', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({
|
||||
@@ -226,7 +226,7 @@ test('getOrders maps unsupported backend statuses to unknown', async () => {
|
||||
})));
|
||||
const result = await getOrders(); /* result 表示处理结果。 */
|
||||
expect(result.data[0].status).toBe('unknown');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:getOrders maps unsupported backend statuses to unknown。 */);
|
||||
|
||||
test('订单查询和导入 API 转发外部取消信号', async () => {
|
||||
// fetchMock 是同时验证订单查询和文件上传请求控制参数的替身。
|
||||
@@ -240,7 +240,7 @@ test('订单查询和导入 API 转发外部取消信号', async () => {
|
||||
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) }));
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:订单查询和导入 API 转发外部取消信号。 */);
|
||||
|
||||
test('Dashboard 统计 API 转发外部取消信号', async () => {
|
||||
// fetchMock 验证 Dashboard 的概览、趋势和订单明细共用同一个取消信号。
|
||||
@@ -260,7 +260,7 @@ test('Dashboard 统计 API 转发外部取消信号', async () => {
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/v1/analytics/dashboard', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(3, expect.stringContaining('/api/v1/analytics/orders?'), expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(4, expect.stringContaining('/api/v1/analytics/orders/valid?'), expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:Dashboard 统计 API 转发外部取消信号。 */);
|
||||
|
||||
test('Settings 配置、模型和凭据 API 转发外部取消信号', async () => {
|
||||
// fetchMock 验证 Settings 的读取、模型发现和凭据保存共享取消控制能力。
|
||||
@@ -280,7 +280,7 @@ test('Settings 配置、模型和凭据 API 转发外部取消信号', async ()
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/v1/settings/ai-models', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(3, '/api/v1/session', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(4, '/api/v1/session/credentials', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:Settings 配置、模型和凭据 API 转发外部取消信号。 */);
|
||||
|
||||
test('通知渠道和 SMTP API 转发外部取消信号', async () => {
|
||||
// fetchMock 验证渠道读取、保存和 SMTP 读写都支持取消控制。
|
||||
@@ -300,7 +300,7 @@ test('通知渠道和 SMTP API 转发外部取消信号', async () => {
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/v1/notifications/channels/channel-1', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(3, '/api/v1/settings/system', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(4, '/api/v1/settings/system', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:通知渠道和 SMTP API 转发外部取消信号。 */);
|
||||
|
||||
test('getShippingRulesPage sends filters and preserves pagination metadata', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({
|
||||
@@ -334,7 +334,7 @@ test('getShippingRulesPage sends filters and preserves pagination metadata', asy
|
||||
'/api/v1/automation-rules?page=2&page_size=20&cookie_id=acc1&trigger_type=order_paid&enabled=false&search=%E5%95%86%E5%93%81',
|
||||
expect.objectContaining({ method: 'GET', credentials: 'include' }),
|
||||
);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:getShippingRulesPage sends filters and preserves pagination metadata。 */);
|
||||
|
||||
test('getValidOrders accepts wrapped responses', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({
|
||||
@@ -349,7 +349,7 @@ test('getValidOrders accepts wrapped responses', async () => {
|
||||
truncated: false,
|
||||
});
|
||||
expect(fetchMock.mock.calls[0][0]).toContain('timezone_offset_minutes=480');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:getValidOrders accepts wrapped responses。 */);
|
||||
|
||||
test('getOrderAnalytics sends the browser timezone offset', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ revenue_stats: {}, daily_stats: [], status_stats: [], city_stats: [] })); /* fetchMock 表示fetchMock。 */
|
||||
@@ -357,7 +357,7 @@ test('getOrderAnalytics sends the browser timezone offset', async () => {
|
||||
vi.spyOn(Date.prototype, 'getTimezoneOffset').mockReturnValue(-330);
|
||||
await getOrderAnalytics({ start_date: '2026-01-01', end_date: '2026-01-02' });
|
||||
expect(fetchMock.mock.calls[0][0]).toContain('timezone_offset_minutes=330');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:getOrderAnalytics sends the browser timezone offset。 */);
|
||||
|
||||
test('getOrderAnalytics 支持数字天数参数', /* 当前回调验证订单分析默认日期范围构造。 */ async () => {
|
||||
// fetchMock 是数字天数分析请求的网络替身。
|
||||
@@ -382,7 +382,7 @@ test('paid orders are normalized to pending shipment', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({ data: [{ order_id: 'o-paid', order_status: 'paid' }] })));
|
||||
const result = await getOrders(); /* result 表示处理结果。 */
|
||||
expect(result.data[0].status).toBe('pending_ship');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:paid orders are normalized to pending shipment。 */);
|
||||
|
||||
test('completeQRVerification sends only the immutable target account', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, account_id: 'acc1' })); /* fetchMock 表示fetchMock。 */
|
||||
@@ -392,7 +392,7 @@ test('completeQRVerification sends only the immutable target account', async ()
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ target_account_id: 'acc1' }),
|
||||
}));
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:completeQRVerification sends only the immutable target account。 */);
|
||||
|
||||
test('deleteItemPublishBatch removes an abandoned preview', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
@@ -402,7 +402,7 @@ test('deleteItemPublishBatch removes an abandoned preview', async () => {
|
||||
method: 'DELETE',
|
||||
credentials: 'include',
|
||||
}));
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:deleteItemPublishBatch removes an abandoned preview。 */);
|
||||
|
||||
test('publishItem allows virtual publishing without an optional location', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
@@ -418,7 +418,7 @@ test('publishItem allows virtual publishing without an optional location', async
|
||||
});
|
||||
const body = fetchMock.mock.calls[0][1].body as FormData; /* body 表示请求体。 */
|
||||
expect(body.get('location')).toBeNull();
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:publishItem allows virtual publishing without an optional location。 */);
|
||||
|
||||
test('getItems normalizes multi-spec flags from backend values', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([{
|
||||
@@ -448,7 +448,7 @@ test('getItems normalizes multi-spec flags from backend values', async () => {
|
||||
is_multi_qty_ship: true,
|
||||
multi_quantity_delivery: true,
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:getItems normalizes multi-spec flags from backend values。 */);
|
||||
|
||||
test('getItems forwards the selected account filter', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse([])); /* fetchMock 表示fetchMock。 */
|
||||
@@ -460,7 +460,7 @@ test('getItems forwards the selected account filter', async () => {
|
||||
method: 'GET',
|
||||
credentials: 'include',
|
||||
}));
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:getItems forwards the selected account filter。 */);
|
||||
|
||||
test('getSystemSettings normalizes numeric renewal retention', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({
|
||||
@@ -471,7 +471,7 @@ test('getSystemSettings normalizes numeric renewal retention', async () => {
|
||||
const settings = await getSystemSettings(); /* settings 表示settings。 */
|
||||
expect(settings.ai_model).toBe('qwen-plus');
|
||||
expect(settings.renewal_log_retention_days).toBe(10);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:getSystemSettings normalizes numeric renewal retention。 */);
|
||||
|
||||
// getSystemSettings 脱敏响应测试验证客户端只接收敏感配置状态。
|
||||
test('getSystemSettings keeps only sensitive configuration markers', /* 当前回调验证脱敏设置归一化。 */ async () => {
|
||||
@@ -498,10 +498,10 @@ test('logout calls backend session invalidation route', async () => {
|
||||
credentials: 'include',
|
||||
}));
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:logout calls backend session invalidation route。 */);
|
||||
|
||||
test('account cookie APIs include login_method when provided', async () => {
|
||||
const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(jsonResponse({ success: true })) /* 回调函数负责当前业务流程。 */); /* fetchMock 表示fetchMock。 */
|
||||
const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(jsonResponse({ success: true })) /* 模拟取消操作的成功响应。 */); /* fetchMock 是本测试替代浏览器网络层的请求桩。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await addAccount('acc1', 'unb=acc1', 'qr_scan');
|
||||
@@ -525,7 +525,7 @@ test('account cookie APIs include login_method when provided', async () => {
|
||||
value: 'unb=acc1; x=1',
|
||||
login_method: 'qr_scan',
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:account cookie APIs include login_method when provided。 */);
|
||||
|
||||
test('account editor settings use one aggregate request', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
@@ -540,7 +540,7 @@ test('account editor settings use one aggregate request', async () => {
|
||||
remark: 'main', auto_confirm: false, pause_duration: 5,
|
||||
username: 'user', show_browser: true, channel_ids: [1, 2],
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:account editor settings use one aggregate request。 */);
|
||||
|
||||
test('getAccountDetails normalizes show_browser and never exposes password', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([{
|
||||
@@ -566,7 +566,7 @@ test('getAccountDetails normalizes show_browser and never exposes password', asy
|
||||
});
|
||||
expect(accounts[0]).not.toHaveProperty('login_password');
|
||||
expect(accounts[0]).not.toHaveProperty('value');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:getAccountDetails normalizes show_browser and never exposes password。 */);
|
||||
|
||||
test('列表 API 将 null 和历史 data 包裹统一为空数组', async () => {
|
||||
// fetchMock 依次模拟账号、商品、订单和规则接口的历史空响应。
|
||||
@@ -626,7 +626,7 @@ test('updateAccountLoginInfo sends exactly provided fields', async () => {
|
||||
username: 'login-user',
|
||||
show_browser: false,
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:updateAccountLoginInfo sends exactly provided fields。 */);
|
||||
|
||||
test('updateAccountLoginInfo can request explicit password clearing', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
@@ -638,7 +638,7 @@ test('updateAccountLoginInfo can request explicit password clearing', async () =
|
||||
clear_password: true,
|
||||
show_browser: false,
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:updateAccountLoginInfo can request explicit password clearing。 */);
|
||||
|
||||
test('updateItem sends only the fields selected by the editor', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
@@ -652,7 +652,7 @@ test('updateItem sends only the fields selected by the editor', async () => {
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
|
||||
item_title: '改名商品',
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:updateItem sends only the fields selected by the editor。 */);
|
||||
|
||||
test('password login service uses upstream-compatible routes', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
@@ -678,7 +678,7 @@ test('password login service uses upstream-compatible routes', async () => {
|
||||
|
||||
await cancelPasswordLogin('sid');
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(3, '/api/v1/password-login/cancel/sid', expect.objectContaining({ method: 'DELETE' }));
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:password login service uses upstream-compatible routes。 */);
|
||||
|
||||
test('账号编辑子模块请求支持取消过期响应', async () => {
|
||||
// fetchMock 是验证请求取消信号透传的测试替身。
|
||||
@@ -696,7 +696,7 @@ test('账号编辑子模块请求支持取消过期响应', async () => {
|
||||
expect(fetchMock.mock.calls[0][1].signal).toBeInstanceOf(AbortSignal);
|
||||
expect(fetchMock.mock.calls[1][1].signal).toBeInstanceOf(AbortSignal);
|
||||
expect(fetchMock.mock.calls[2][1].signal).toBeInstanceOf(AbortSignal);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:账号编辑子模块请求支持取消过期响应。 */);
|
||||
|
||||
test('getShippingRules exposes buyer reviewed gift rules as automation rules', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([{
|
||||
@@ -733,7 +733,7 @@ test('getShippingRules exposes buyer reviewed gift rules as automation rules', a
|
||||
spec_value: '赠品',
|
||||
card_id: 7,
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:getShippingRules exposes buyer reviewed gift rules as automation rules。 */);
|
||||
|
||||
test('getReplyRules labels keyword matching according to engine contains behavior', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse([{
|
||||
@@ -755,7 +755,7 @@ test('getReplyRules labels keyword matching according to engine contains behavio
|
||||
type: 'image',
|
||||
image_url: 'https://img.example/reply.png',
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:getReplyRules labels keyword matching according to engine contains behavior。 */);
|
||||
|
||||
test('getReplyRules 没有账号时直接返回空列表', /* 当前回调验证关键词规则的账号守卫。 */ async () => {
|
||||
await expect(getReplyRules()).resolves.toEqual([]);
|
||||
@@ -806,7 +806,7 @@ test('updateReplyRule preserves keyword image metadata when saving text edits',
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
|
||||
keyword: '发货', reply: '稍后安排', item_id: 'item-1', type: 'text', image_url: '',
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:updateReplyRule preserves keyword image metadata when saving text edits。 */);
|
||||
|
||||
test('updateReplyRule clears stale content when switching reply type', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
@@ -816,7 +816,7 @@ test('updateReplyRule clears stale content when switching reply type', async ()
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
|
||||
keyword: '发货', reply: '', item_id: '', type: 'image', image_url: 'https://img.example/new.png',
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:updateReplyRule clears stale content when switching reply type。 */);
|
||||
|
||||
test('deleteReplyRule deletes one stable keyword row instead of replacing the list', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
@@ -828,7 +828,7 @@ test('deleteReplyRule deletes one stable keyword row instead of replacing the li
|
||||
method: 'DELETE',
|
||||
credentials: 'include',
|
||||
}));
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:deleteReplyRule deletes one stable keyword row instead of replacing the list。 */);
|
||||
|
||||
test('createNotificationChannel persists email recipient as to_email config', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
@@ -852,7 +852,7 @@ test('createNotificationChannel persists email recipient as to_email config', as
|
||||
to_email: '[email protected]',
|
||||
});
|
||||
expect(JSON.parse(body.config)).not.toHaveProperty('from');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:createNotificationChannel persists email recipient as to_email config。 */);
|
||||
|
||||
test('createNotificationChannel allows email channel to rely on system SMTP settings', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
@@ -871,7 +871,7 @@ test('createNotificationChannel allows email channel to rely on system SMTP sett
|
||||
expect(JSON.parse(body.config)).toEqual({
|
||||
to_email: '[email protected]',
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:createNotificationChannel allows email channel to rely on system SMTP settings。 */);
|
||||
|
||||
test('updateNotificationChannel supports partial enabled updates', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
@@ -886,7 +886,7 @@ test('updateNotificationChannel supports partial enabled updates', async () => {
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
|
||||
enabled: false,
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:updateNotificationChannel supports partial enabled updates。 */);
|
||||
|
||||
test('updateNotificationChannel serializes config and event types', /* 当前回调验证通知渠道请求体序列化。 */ async () => {
|
||||
// fetchMock 是通知渠道更新接口的网络替身。
|
||||
@@ -973,7 +973,7 @@ test('updateShippingRule posts buyer reviewed gift payload to automation-rules',
|
||||
sort_order: 1,
|
||||
}),
|
||||
]);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:updateShippingRule posts buyer reviewed gift payload to automation-rules。 */);
|
||||
|
||||
test('updateShippingRule posts every matching card action before confirm shipment', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, id: 3 })); /* fetchMock 表示fetchMock。 */
|
||||
@@ -1026,7 +1026,7 @@ test('updateShippingRule posts every matching card action before confirm shipmen
|
||||
expect(JSON.parse(body.actions[0].config_json)).toEqual({ spec_name: '套餐', spec_value: '30天', delay_override: false });
|
||||
expect(JSON.parse(body.actions[1].config_json)).toEqual({ spec_name: '套餐', spec_value: '30天', delay_override: true });
|
||||
expect(body.actions[1].delay_seconds).toBe(0);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:updateShippingRule posts every matching card action before confirm shipment。 */);
|
||||
|
||||
test('updateShippingRule preserves text actions while editing card variants', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, id: 4 })); /* fetchMock 表示fetchMock。 */
|
||||
@@ -1042,13 +1042,13 @@ test('updateShippingRule preserves text actions while editing card variants', as
|
||||
});
|
||||
|
||||
const body = JSON.parse(fetchMock.mock.calls[0][1].body); /* body 表示请求体。 */
|
||||
expect(body.actions.map((action: { /* action_type 表示actiontype。 */ action_type: string }) => action.action_type /* 回调函数负责当前业务流程。 */)).toEqual([
|
||||
expect(body.actions.map((action: { /* action_type 表示自动化动作类型。 */ action_type: string }) => action.action_type /* action 是当前待断言排序的自动化动作。 */)).toEqual([
|
||||
'send_card',
|
||||
'send_text',
|
||||
'confirm_shipment',
|
||||
]);
|
||||
expect(body.actions[1].message_template).toBe('发货提示');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:updateShippingRule preserves text actions while editing card variants。 */);
|
||||
|
||||
test('updateShippingRule posts review request text action without card requirement', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, id: 2 })); /* fetchMock 表示fetchMock。 */
|
||||
@@ -1077,7 +1077,7 @@ test('updateShippingRule posts review request text action without card requireme
|
||||
message_template: '亲,方便的话麻烦给个评价~',
|
||||
}),
|
||||
]);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:updateShippingRule posts review request text action without card requirement。 */);
|
||||
|
||||
// 会话 API 使用版本化兼容入口。
|
||||
const runVersionedSessionAPITest = async () => {
|
||||
|
||||
@@ -166,7 +166,7 @@ export const useChat = (): UseChatResult => {
|
||||
setContactCursors(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, [accountID]: page.next_cursor }));
|
||||
setHasMoreContacts(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, [accountID]: page.has_more }));
|
||||
return sessions;
|
||||
} catch (/* error 表示错误。 */ error) {
|
||||
} catch (/* error 保存会话列表请求的失败原因;仅最新请求可以更新错误状态。 */ error) {
|
||||
if (isCurrentChatRequest(sessionSequence.current, sequence, controller.signal) && !isChatAbortError(error)) setError(error instanceof Error ? error.message : '同步会话失败');
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -83,7 +83,7 @@ export const useDashboard = (options: UseDashboardOptions): UseDashboardResult =
|
||||
let dateRange;
|
||||
try {
|
||||
dateRange = getDateRange(range, new Date(), customStartDate, customEndDate);
|
||||
} catch (/* error 表示错误。 */ error) {
|
||||
} catch (/* error 保存经营数据请求失败原因;取消请求和过期代次均被忽略。 */ error) {
|
||||
setStatus(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, range: 'error', error: errorMessage(error, '日期范围无效') }));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ import type { PublishLocation } from '../../../shared/api-contract';
|
||||
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => get('/api/v1/accounts/details', undefined, options);
|
||||
|
||||
/** 商品页面读取自动化发货规则的兼容列表。 */
|
||||
export const getShippingRules = async (): Promise<ShippingRule[]> => get('/api/v1/automation-rules');
|
||||
export const getShippingRules = async (options?: RequestControlOptions): Promise<ShippingRule[]> => get('/api/v1/automation-rules', undefined, options);
|
||||
|
||||
export { getPublishLocations };
|
||||
export type { PublishLocation } from '../../../shared/api-contract';
|
||||
@@ -60,7 +60,7 @@ export const publishItem = async (form: {
|
||||
/** description 表示描述。 */ description: string;
|
||||
/** price 表示售价。 */ price: string;
|
||||
/** original_price 表示原始售价。 */ original_price?: string;
|
||||
/** quantity 表示数量。 */ quantity: string | number;
|
||||
/** quantity 表示待发布商品的件数,提交前会转换为表单字符串。 */ quantity: string | number;
|
||||
/** postage_mode 表示运费模式。 */ postage_mode: string;
|
||||
/** postage 表示运费。 */ postage?: string;
|
||||
/** images 表示图片列表。 */ images: File[];
|
||||
@@ -85,7 +85,7 @@ file of form.images) {
|
||||
}
|
||||
|
||||
// recommendPublishCategory 推荐商品发布分类。
|
||||
export const recommendPublishCategory = async (cookieId: string, keyword: string): Promise<CategoryRecommendationResponse> => {
|
||||
export const recommendPublishCategory = async (cookieId: string, keyword: string, options?: RequestControlOptions): Promise<CategoryRecommendationResponse> => {
|
||||
// 类目推荐成功响应使用共享 CategoryRecommendationResponse。
|
||||
// category 字段保留平台类目 ID、名称和频道类目 ID。
|
||||
// tb_cat_id 继续保持可选,兼容电子资料类目。
|
||||
@@ -94,7 +94,7 @@ export const recommendPublishCategory = async (cookieId: string, keyword: string
|
||||
// 该类型收口不改变凭证刷新和错误处理。
|
||||
// 前端批量发布流程可直接复用 category。
|
||||
// 旧路径继续由现有 Vite 代理转发。
|
||||
return post('/api/v1/items/publish-categories/recommend', { cookie_id: cookieId, keyword });
|
||||
return post('/api/v1/items/publish-categories/recommend', { cookie_id: cookieId, keyword }, options);
|
||||
};
|
||||
|
||||
// previewItemPublishBatch 预览商品批量发布。
|
||||
@@ -109,7 +109,7 @@ export const previewItemPublishBatch = async (form: {
|
||||
/** tbCatId 表示淘宝分类标识。 */ tbCatId?: string;
|
||||
};
|
||||
/** location 表示地址。 */ location?: PublishLocation;
|
||||
}): Promise<ItemPublishBatchPreviewResponse> => {
|
||||
}, options?: RequestControlOptions): Promise<ItemPublishBatchPreviewResponse> => {
|
||||
// body 请求体,用于当前 API 处理流程。
|
||||
const body = new FormData();
|
||||
body.set('file', form.file);
|
||||
@@ -120,39 +120,39 @@ export const previewItemPublishBatch = async (form: {
|
||||
body.set('fallback_channel_category_id', form.fallbackCategory.channelCatId || '');
|
||||
body.set('fallback_tb_category_id', form.fallbackCategory.tbCatId || '');
|
||||
if (form.location) body.set('location', JSON.stringify(form.location));
|
||||
return postForm('/api/v1/items/publish-batches/preview', body);
|
||||
return postForm('/api/v1/items/publish-batches/preview', body, options);
|
||||
}
|
||||
|
||||
// startItemPublishBatch 启动商品批量发布。
|
||||
export const startItemPublishBatch = async (previewId: string): Promise<BatchIDResponse> => {
|
||||
return post('/api/v1/items/publish-batches', { preview_id: previewId });
|
||||
export const startItemPublishBatch = async (previewId: string, options?: RequestControlOptions): Promise<BatchIDResponse> => {
|
||||
return post('/api/v1/items/publish-batches', { preview_id: previewId }, options);
|
||||
}
|
||||
|
||||
// getItemPublishBatch 读取商品发布批次。
|
||||
export const getItemPublishBatch = async (batchId: string): Promise<ItemPublishBatchResponse> => {
|
||||
return get(`/api/v1/items/publish-batches/${batchId}`);
|
||||
export const getItemPublishBatch = async (batchId: string, options?: RequestControlOptions): Promise<ItemPublishBatchResponse> => {
|
||||
return get(`/api/v1/items/publish-batches/${batchId}`, undefined, options);
|
||||
}
|
||||
|
||||
// getItemPublishBatches 读取商品发布批次列表。
|
||||
export const getItemPublishBatches = async (limit = 20): Promise<ItemPublishBatchResponse[]> => {
|
||||
export const getItemPublishBatches = async (limit = 20, options?: RequestControlOptions): Promise<ItemPublishBatchResponse[]> => {
|
||||
// res 接口响应结果,用于当前 API 处理流程。
|
||||
const res = await get<unknown>('/api/v1/items/publish-batches', { limit });
|
||||
const res = await get<unknown>('/api/v1/items/publish-batches', { limit }, options);
|
||||
return collectionFrom<ItemPublishBatchResponse>(res, ['batches', 'data', 'items']);
|
||||
}
|
||||
|
||||
// deleteItemPublishBatch 删除商品发布批次。
|
||||
export const deleteItemPublishBatch = async (batchId: string): Promise<OperationResponse> => {
|
||||
return del(`/api/v1/items/publish-batches/${batchId}`);
|
||||
export const deleteItemPublishBatch = async (batchId: string, options?: RequestControlOptions): Promise<OperationResponse> => {
|
||||
return del(`/api/v1/items/publish-batches/${batchId}`, undefined, options);
|
||||
}
|
||||
|
||||
// cancelItemPublishBatch 取消商品发布批次。
|
||||
export const cancelItemPublishBatch = async (batchId: string): Promise<BatchCancelResponse> => {
|
||||
return post(`/api/v1/items/publish-batches/${batchId}/cancel`, {});
|
||||
export const cancelItemPublishBatch = async (batchId: string, options?: RequestControlOptions): Promise<BatchCancelResponse> => {
|
||||
return post(`/api/v1/items/publish-batches/${batchId}/cancel`, {}, options);
|
||||
}
|
||||
|
||||
// retryFailedItemPublishBatch 重试失败的商品发布任务。
|
||||
export const retryFailedItemPublishBatch = async (batchId: string): Promise<BatchIDResponse> => {
|
||||
return post(`/api/v1/items/publish-batches/${batchId}/retry-failed`, {});
|
||||
export const retryFailedItemPublishBatch = async (batchId: string, options?: RequestControlOptions): Promise<BatchIDResponse> => {
|
||||
return post(`/api/v1/items/publish-batches/${batchId}/retry-failed`, {}, options);
|
||||
}
|
||||
|
||||
// updateItem 更新商品。
|
||||
|
||||
@@ -93,7 +93,7 @@ describe('useItemPublishBatch', /* 当前回调处理批量发布的表单、任
|
||||
// recommendAction 请求推荐类目。
|
||||
async () => hook.result.current.handleRecommendBatchCategory(),
|
||||
);
|
||||
expect(recommendCategoryMock).toHaveBeenCalledWith('account-1', '服饰');
|
||||
expect(recommendCategoryMock).toHaveBeenCalledWith('account-1', '服饰', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(hook.result.current.batchFallbackCategory.catId).toBe('cat-1');
|
||||
|
||||
await act(
|
||||
@@ -112,14 +112,14 @@ describe('useItemPublishBatch', /* 当前回调处理批量发布的表单、任
|
||||
// startAction 启动预检通过的任务。
|
||||
async () => hook.result.current.handleStartBatch(),
|
||||
);
|
||||
expect(startBatchMock).toHaveBeenCalledWith('preview-1');
|
||||
expect(startBatchMock).toHaveBeenCalledWith('preview-1', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(hook.result.current.batchDetail).toEqual(runningBatchFixture);
|
||||
|
||||
await act(
|
||||
// cancelAction 请求安全取消任务。
|
||||
async () => hook.result.current.handleCancelBatch(),
|
||||
);
|
||||
expect(cancelBatchMock).toHaveBeenCalledWith('batch-1');
|
||||
expect(cancelBatchMock).toHaveBeenCalledWith('batch-1', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
|
||||
getBatchMock.mockResolvedValueOnce(failedBatchFixture);
|
||||
await act(
|
||||
@@ -135,7 +135,7 @@ describe('useItemPublishBatch', /* 当前回调处理批量发布的表单、任
|
||||
// retryAction 重试失败行。
|
||||
async () => hook.result.current.handleRetryBatchFailed(),
|
||||
);
|
||||
expect(retryBatchMock).toHaveBeenCalledWith('batch-1');
|
||||
expect(retryBatchMock).toHaveBeenCalledWith('batch-1', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
|
||||
await act(
|
||||
// closeAction 关闭弹窗并清理临时预检。
|
||||
@@ -441,4 +441,36 @@ describe('useItemPublishBatch', /* 当前回调处理批量发布的表单、任
|
||||
hook.unmount();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
test('快速重开弹窗时丢弃上一次恢复请求的晚到响应', /* 当前回调验证用户动作请求代次隔离。 */ async () => {
|
||||
// resolveFirstOpen 是首次打开弹窗的延迟批次列表完成函数。
|
||||
let resolveFirstOpen: (value: ItemPublishBatchResponse[]) => void = () => undefined;
|
||||
// firstOpenBatches 是故意晚到的首次恢复请求。
|
||||
const firstOpenBatches = new Promise<ItemPublishBatchResponse[]>(/* firstOpenExecutor 保存首次恢复响应完成函数。 */ resolve => { resolveFirstOpen = resolve; });
|
||||
getBatchesMock.mockReset();
|
||||
getBatchesMock.mockReturnValueOnce(firstOpenBatches).mockResolvedValueOnce([]);
|
||||
// hook 是快速关闭并重新打开批量弹窗时的状态容器。
|
||||
const hook = renderHook(/* reopenHookFactory 创建快速重开场景的批量 Hook。 */ () => useItemPublishBatch({ selectedAccount: 'account-1', loadItems: vi.fn(), loadShippingRules: vi.fn() }));
|
||||
await act(
|
||||
// firstOpenAction 启动会延迟返回的首次恢复请求。
|
||||
async () => { void hook.result.current.openBatchModal(); },
|
||||
);
|
||||
await act(
|
||||
// closeAction 关闭首次弹窗并使其请求代次失效。
|
||||
async () => hook.result.current.closeBatchModal(),
|
||||
);
|
||||
await act(
|
||||
// secondOpenAction 创建新的弹窗会话;该会话没有待恢复任务。
|
||||
async () => hook.result.current.openBatchModal(),
|
||||
);
|
||||
resolveFirstOpen([runningBatchFixture]);
|
||||
await act(
|
||||
// staleResponseAction 交付首次弹窗的晚到响应。
|
||||
async () => { await firstOpenBatches; },
|
||||
);
|
||||
expect(hook.result.current.showBatchModal).toBe(true);
|
||||
expect(hook.result.current.batchDetail).toBeNull();
|
||||
expect(hook.result.current.batchPhase).toBe('upload');
|
||||
hook.unmount();
|
||||
});
|
||||
});
|
||||
@@ -51,11 +51,43 @@ export const useItemPublishBatch = (options: ItemPublishBatchOptions): ItemPubli
|
||||
const batchPollInFlight = useRef(false);
|
||||
// batchRequestGeneration 用于丢弃弹窗关闭后返回的过期轮询响应。
|
||||
const batchRequestGeneration = useRef(0);
|
||||
// batchRequestController 保存当前用户触发请求的取消器;新动作或组件卸载时必须中止旧请求。
|
||||
const batchRequestController = useRef<AbortController | null>(null);
|
||||
|
||||
// beginBatchRequest 取消上一个用户动作并返回当前动作独占的代次与取消器。
|
||||
const beginBatchRequest = useCallback(/* beginBatchRequest 的回调负责取消旧动作并创建新请求代次。 */ () => {
|
||||
batchRequestController.current?.abort();
|
||||
// controller 是当前用户动作独占的 HTTP 取消器。
|
||||
const controller = new AbortController();
|
||||
batchRequestController.current = controller;
|
||||
// requestGeneration 是当前动作的单调递增代次,晚到响应只能在代次仍匹配时回写状态。
|
||||
const requestGeneration = ++batchRequestGeneration.current;
|
||||
return { controller, requestGeneration };
|
||||
}, []);
|
||||
|
||||
// isCurrentBatchOperation 判断给定用户动作是否仍是当前弹窗会话的最新请求。
|
||||
const isCurrentBatchOperation = useCallback(/* isCurrentBatchOperation 的回调负责验证异步响应是否仍归属当前动作。 */ (requestGeneration: number, controller: AbortController) => (
|
||||
requestGeneration === batchRequestGeneration.current && controller === batchRequestController.current && !controller.signal.aborted
|
||||
), []);
|
||||
|
||||
useEffect(
|
||||
// 组件卸载时中止未完成请求并使所有尚未返回的操作响应失效。
|
||||
() => (
|
||||
/* 卸载清理回调中止网络请求并使晚到响应失效。 */
|
||||
() => {
|
||||
batchRequestController.current?.abort();
|
||||
batchRequestGeneration.current += 1;
|
||||
}
|
||||
),
|
||||
[],
|
||||
);
|
||||
|
||||
// openBatchModal 初始化上传表单,并恢复仍在执行的批量任务。
|
||||
const openBatchModal = useCallback(
|
||||
// 批量弹窗打开器负责初始化临时表单和恢复任务。
|
||||
async () => {
|
||||
// request 是本次打开弹窗及恢复任务读取的独占请求控制器。
|
||||
const request = beginBatchRequest();
|
||||
setBatchPhase('upload');
|
||||
setBatchPreview(null);
|
||||
setBatchDetail(null);
|
||||
@@ -69,23 +101,26 @@ export const useItemPublishBatch = (options: ItemPublishBatchOptions): ItemPubli
|
||||
setBatchLoading(true);
|
||||
try {
|
||||
// batches 是最近批量任务摘要,用于寻找可恢复任务。
|
||||
const batches = await getItemPublishBatches(20);
|
||||
const batches = await getItemPublishBatches(20, { signal: request.controller.signal });
|
||||
if (!isCurrentBatchOperation(request.requestGeneration, request.controller)) return;
|
||||
// recoverable 是仍处于运行或安全取消阶段的任务。
|
||||
const recoverable = selectActivePublishBatch(batches);
|
||||
if (recoverable?.id) {
|
||||
// detail 是可恢复任务的完整详情。
|
||||
const detail = await getItemPublishBatch(recoverable.id);
|
||||
const detail = await getItemPublishBatch(recoverable.id, { signal: request.controller.signal });
|
||||
if (!isCurrentBatchOperation(request.requestGeneration, request.controller)) return;
|
||||
setRecentBatch(detail);
|
||||
setBatchDetail(detail);
|
||||
setBatchPhase(['running', 'canceling'].includes(detail.status) ? 'running' : 'done');
|
||||
}
|
||||
} catch (error /* 恢复任务错误 */) {
|
||||
if (!isCurrentBatchOperation(request.requestGeneration, request.controller)) return;
|
||||
console.error('恢复最近批量铺货任务失败:', error);
|
||||
} finally {
|
||||
setBatchLoading(false);
|
||||
if (isCurrentBatchOperation(request.requestGeneration, request.controller)) setBatchLoading(false);
|
||||
}
|
||||
},
|
||||
[],
|
||||
[beginBatchRequest, isCurrentBatchOperation],
|
||||
);
|
||||
|
||||
// handleRecommendBatchCategory 请求默认发布账号对应的推荐类目。
|
||||
@@ -102,10 +137,13 @@ export const useItemPublishBatch = (options: ItemPublishBatchOptions): ItemPubli
|
||||
alert('请输入类目关键词');
|
||||
return;
|
||||
}
|
||||
// request 是本次类目推荐请求的独占取消器和代次。
|
||||
const request = beginBatchRequest();
|
||||
setBatchCategoryLoading(true);
|
||||
try {
|
||||
// result 是类目推荐接口返回的具名响应。
|
||||
const result = await recommendPublishCategory(options.selectedAccount, keyword);
|
||||
const result = await recommendPublishCategory(options.selectedAccount, keyword, { signal: request.controller.signal });
|
||||
if (!isCurrentBatchOperation(request.requestGeneration, request.controller)) return;
|
||||
// category 是后端返回的推荐类目。
|
||||
const category = result.category;
|
||||
setBatchFallbackCategory({
|
||||
@@ -115,13 +153,14 @@ export const useItemPublishBatch = (options: ItemPublishBatchOptions): ItemPubli
|
||||
tbCatId: category.tb_cat_id || '',
|
||||
});
|
||||
} catch (error: any /* 推荐类目错误 */) {
|
||||
if (!isCurrentBatchOperation(request.requestGeneration, request.controller)) return;
|
||||
console.error('获取推荐类目失败:', error);
|
||||
alert(error?.message || '没有匹配到类目,请换一个更具体的关键词');
|
||||
} finally {
|
||||
setBatchCategoryLoading(false);
|
||||
if (isCurrentBatchOperation(request.requestGeneration, request.controller)) setBatchCategoryLoading(false);
|
||||
}
|
||||
},
|
||||
[batchCategoryKeyword, options.selectedAccount],
|
||||
[batchCategoryKeyword, beginBatchRequest, isCurrentBatchOperation, options.selectedAccount],
|
||||
);
|
||||
|
||||
// openRecentBatchResult 加载最近批量任务详情并打开结果弹窗。
|
||||
@@ -129,20 +168,24 @@ export const useItemPublishBatch = (options: ItemPublishBatchOptions): ItemPubli
|
||||
// 最近结果打开器只读取已存在的批量任务。
|
||||
async () => {
|
||||
if (!recentBatch?.id) return;
|
||||
// request 是本次最近结果读取的独占取消器和代次。
|
||||
const request = beginBatchRequest();
|
||||
setBatchLoading(true);
|
||||
setShowBatchModal(true);
|
||||
try {
|
||||
// detail 是最近任务的最新服务端状态。
|
||||
const detail = await getItemPublishBatch(recentBatch.id);
|
||||
const detail = await getItemPublishBatch(recentBatch.id, { signal: request.controller.signal });
|
||||
if (!isCurrentBatchOperation(request.requestGeneration, request.controller)) return;
|
||||
setBatchDetail(detail);
|
||||
setBatchPhase(['running', 'canceling'].includes(detail.status) ? 'running' : 'done');
|
||||
} catch (error /* 最近结果读取错误 */) {
|
||||
if (!isCurrentBatchOperation(request.requestGeneration, request.controller)) return;
|
||||
console.error('加载最近批量铺货结果失败:', error);
|
||||
} finally {
|
||||
setBatchLoading(false);
|
||||
if (isCurrentBatchOperation(request.requestGeneration, request.controller)) setBatchLoading(false);
|
||||
}
|
||||
},
|
||||
[recentBatch?.id],
|
||||
[beginBatchRequest, isCurrentBatchOperation, recentBatch?.id],
|
||||
);
|
||||
|
||||
// handlePreviewBatch 上传表格并执行批量预检。
|
||||
@@ -157,6 +200,8 @@ export const useItemPublishBatch = (options: ItemPublishBatchOptions): ItemPubli
|
||||
alert('请先选择默认发布账号');
|
||||
return;
|
||||
}
|
||||
// request 是本次批量预检上传的独占取消器和代次。
|
||||
const request = beginBatchRequest();
|
||||
setBatchLoading(true);
|
||||
try {
|
||||
// result 是批量预检接口返回的行级校验结果。
|
||||
@@ -166,18 +211,20 @@ export const useItemPublishBatch = (options: ItemPublishBatchOptions): ItemPubli
|
||||
defaultCookieId: options.selectedAccount,
|
||||
fallbackCategory: batchFallbackCategory,
|
||||
location: batchLocation || undefined,
|
||||
});
|
||||
}, { signal: request.controller.signal });
|
||||
if (!isCurrentBatchOperation(request.requestGeneration, request.controller)) return;
|
||||
setBatchPreview(result);
|
||||
setBatchDetail(null);
|
||||
setBatchPhase('preview');
|
||||
} catch (error: any /* 预检失败错误 */) {
|
||||
if (!isCurrentBatchOperation(request.requestGeneration, request.controller)) return;
|
||||
console.error('批量铺货预检失败:', error);
|
||||
alert(error?.message || '预检失败,请检查表格和图片 zip');
|
||||
} finally {
|
||||
setBatchLoading(false);
|
||||
if (isCurrentBatchOperation(request.requestGeneration, request.controller)) setBatchLoading(false);
|
||||
}
|
||||
},
|
||||
[batchFallbackCategory, batchFile, batchImagesZip, batchLocation, options.selectedAccount],
|
||||
[batchFallbackCategory, batchFile, batchImagesZip, batchLocation, beginBatchRequest, isCurrentBatchOperation, options.selectedAccount],
|
||||
);
|
||||
|
||||
// handleStartBatch 启动预检通过的批量任务并读取首个详情。
|
||||
@@ -189,23 +236,28 @@ export const useItemPublishBatch = (options: ItemPublishBatchOptions): ItemPubli
|
||||
alert('没有可发布的商品行');
|
||||
return;
|
||||
}
|
||||
// request 是本次启动任务及读取首个详情的独占取消器和代次。
|
||||
const request = beginBatchRequest();
|
||||
setBatchLoading(true);
|
||||
try {
|
||||
// started 是批量任务启动接口返回的任务标识。
|
||||
const started = await startItemPublishBatch(batchPreview.preview_id);
|
||||
const started = await startItemPublishBatch(batchPreview.preview_id, { signal: request.controller.signal });
|
||||
if (!isCurrentBatchOperation(request.requestGeneration, request.controller)) return;
|
||||
// detail 是启动后用于驱动轮询的任务详情。
|
||||
const detail = await getItemPublishBatch(started.batch_id || batchPreview.preview_id);
|
||||
const detail = await getItemPublishBatch(started.batch_id || batchPreview.preview_id, { signal: request.controller.signal });
|
||||
if (!isCurrentBatchOperation(request.requestGeneration, request.controller)) return;
|
||||
setBatchDetail(detail);
|
||||
setRecentBatch(detail);
|
||||
setBatchPhase(detail.status === 'running' ? 'running' : 'done');
|
||||
} catch (error: any /* 启动失败错误 */) {
|
||||
if (!isCurrentBatchOperation(request.requestGeneration, request.controller)) return;
|
||||
console.error('启动批量铺货失败:', error);
|
||||
alert(error?.message || '启动发布任务失败');
|
||||
} finally {
|
||||
setBatchLoading(false);
|
||||
if (isCurrentBatchOperation(request.requestGeneration, request.controller)) setBatchLoading(false);
|
||||
}
|
||||
},
|
||||
[batchPreview],
|
||||
[batchPreview, beginBatchRequest, isCurrentBatchOperation],
|
||||
);
|
||||
|
||||
// handleCancelBatch 请求安全取消当前批量任务,并保留远端收尾状态。
|
||||
@@ -214,21 +266,26 @@ export const useItemPublishBatch = (options: ItemPublishBatchOptions): ItemPubli
|
||||
async () => {
|
||||
if (!batchDetail?.id) return;
|
||||
if (!confirm('确认取消当前批量铺货任务吗?正在发布的单个商品可能会继续完成。')) return;
|
||||
// request 是本次安全取消和状态回读的独占取消器和代次。
|
||||
const request = beginBatchRequest();
|
||||
setBatchLoading(true);
|
||||
try {
|
||||
// result 是取消请求返回的过渡状态。
|
||||
const result = await cancelItemPublishBatch(batchDetail.id);
|
||||
const result = await cancelItemPublishBatch(batchDetail.id, { signal: request.controller.signal });
|
||||
if (!isCurrentBatchOperation(request.requestGeneration, request.controller)) return;
|
||||
// detail 是取消请求后的最新任务状态。
|
||||
const detail = await getItemPublishBatch(batchDetail.id);
|
||||
const detail = await getItemPublishBatch(batchDetail.id, { signal: request.controller.signal });
|
||||
if (!isCurrentBatchOperation(request.requestGeneration, request.controller)) return;
|
||||
setBatchDetail(detail);
|
||||
setBatchPhase(result?.status === 'canceling' || detail.status === 'canceling' ? 'running' : 'done');
|
||||
} catch (error: any /* 取消失败错误 */) {
|
||||
if (!isCurrentBatchOperation(request.requestGeneration, request.controller)) return;
|
||||
alert(error?.message || '取消失败');
|
||||
} finally {
|
||||
setBatchLoading(false);
|
||||
if (isCurrentBatchOperation(request.requestGeneration, request.controller)) setBatchLoading(false);
|
||||
}
|
||||
},
|
||||
[batchDetail?.id],
|
||||
[batchDetail?.id, beginBatchRequest, isCurrentBatchOperation],
|
||||
);
|
||||
|
||||
// abandonBatchPreview 删除未启动的预检任务并恢复上传步骤。
|
||||
@@ -237,27 +294,44 @@ export const useItemPublishBatch = (options: ItemPublishBatchOptions): ItemPubli
|
||||
async () => {
|
||||
// previewId 是当前临时预检任务标识。
|
||||
const previewId = batchPreview?.preview_id;
|
||||
// request 是本次预检清理操作的独占取消器和代次。
|
||||
const request = beginBatchRequest();
|
||||
if (previewId && batchPhase === 'preview') {
|
||||
try {
|
||||
await deleteItemPublishBatch(previewId);
|
||||
await deleteItemPublishBatch(previewId, { signal: request.controller.signal });
|
||||
} catch (error /* 删除预检错误 */) {
|
||||
if (!isCurrentBatchOperation(request.requestGeneration, request.controller)) return;
|
||||
console.error('清理批量铺货预检失败:', error);
|
||||
}
|
||||
}
|
||||
if (!isCurrentBatchOperation(request.requestGeneration, request.controller)) return;
|
||||
setBatchPreview(null);
|
||||
setBatchPhase('upload');
|
||||
},
|
||||
[batchPhase, batchPreview?.preview_id],
|
||||
[batchPhase, batchPreview?.preview_id, beginBatchRequest, isCurrentBatchOperation],
|
||||
);
|
||||
|
||||
// closeBatchModal 清理临时预检后关闭批量弹窗。
|
||||
const closeBatchModal = useCallback(
|
||||
// 批量弹窗关闭动作先清理临时预检任务。
|
||||
async () => {
|
||||
await abandonBatchPreview();
|
||||
// previewId 是关闭前可安全删除的未启动预检任务标识。
|
||||
const previewId = batchPreview?.preview_id;
|
||||
// batchRequestGeneration 在关闭时递增,确保所有弹窗动作和轮询响应立即失效。
|
||||
batchRequestController.current?.abort();
|
||||
batchRequestGeneration.current += 1;
|
||||
setBatchPreview(null);
|
||||
setBatchPhase('upload');
|
||||
setShowBatchModal(false);
|
||||
if (previewId && batchPhase === 'preview') {
|
||||
try {
|
||||
await deleteItemPublishBatch(previewId);
|
||||
} catch (error /* 关闭时预检清理错误 */) {
|
||||
console.error('关闭批量铺货弹窗时清理预检失败:', error);
|
||||
}
|
||||
}
|
||||
},
|
||||
[abandonBatchPreview],
|
||||
[batchPhase, batchPreview?.preview_id],
|
||||
);
|
||||
|
||||
// handleRetryBatchFailed 重新执行当前批次中可重试的失败行。
|
||||
@@ -265,18 +339,25 @@ export const useItemPublishBatch = (options: ItemPublishBatchOptions): ItemPubli
|
||||
// 失败重试动作只提交后端允许重试的行。
|
||||
async () => {
|
||||
if (!batchDetail?.id || !canRetryBatch(batchDetail)) return;
|
||||
// request 是本次失败行重试和详情读取的独占取消器和代次。
|
||||
const request = beginBatchRequest();
|
||||
setBatchLoading(true);
|
||||
try {
|
||||
await retryFailedItemPublishBatch(batchDetail.id);
|
||||
setBatchDetail(await getItemPublishBatch(batchDetail.id));
|
||||
await retryFailedItemPublishBatch(batchDetail.id, { signal: request.controller.signal });
|
||||
if (!isCurrentBatchOperation(request.requestGeneration, request.controller)) return;
|
||||
// detail 是重试请求返回后读取的权威任务详情。
|
||||
const detail = await getItemPublishBatch(batchDetail.id, { signal: request.controller.signal });
|
||||
if (!isCurrentBatchOperation(request.requestGeneration, request.controller)) return;
|
||||
setBatchDetail(detail);
|
||||
setBatchPhase('running');
|
||||
} catch (error: any /* 重试失败错误 */) {
|
||||
if (!isCurrentBatchOperation(request.requestGeneration, request.controller)) return;
|
||||
alert(error?.message || '重试失败');
|
||||
} finally {
|
||||
setBatchLoading(false);
|
||||
if (isCurrentBatchOperation(request.requestGeneration, request.controller)) setBatchLoading(false);
|
||||
}
|
||||
},
|
||||
[batchDetail],
|
||||
[batchDetail, beginBatchRequest, isCurrentBatchOperation],
|
||||
);
|
||||
|
||||
useEffect(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import type { Item } from '../../../../shared/api-contract';
|
||||
import {
|
||||
@@ -35,16 +35,26 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
const [selectedAccount, setSelectedAccount] = useState<string>('');
|
||||
// [accountFilter, 解构得到当前 Hook 返回的状态和操作函数。
|
||||
const [accountFilter, setAccountFilter] = useState<string>('');
|
||||
// itemsRequestGeneration 标识商品列表最新一次读取,旧响应不得覆盖较新的同步或刷新结果。
|
||||
const itemsRequestGeneration = useRef(0);
|
||||
// shippingRulesRequestGeneration 标识发货规则最新一次读取,旧响应不得覆盖较新的规则配置。
|
||||
const shippingRulesRequestGeneration = useRef(0);
|
||||
// loadItems 刷新商品列表,供普通操作和批量任务完成后复用。
|
||||
const loadItems = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async () => {
|
||||
// requestGeneration 是本次商品刷新请求的单调递增代次。
|
||||
const requestGeneration = ++itemsRequestGeneration.current;
|
||||
// itemsList 商品列表列表,负责当前功能中的对应处理。
|
||||
const itemsList = await getItems();
|
||||
setItems(itemsList);
|
||||
if (requestGeneration === itemsRequestGeneration.current) setItems(itemsList);
|
||||
}, []);
|
||||
|
||||
// loadShippingRules 刷新商品关联的自动化规则。
|
||||
const loadShippingRules = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async () => {
|
||||
setShippingRules(await getShippingRules());
|
||||
// requestGeneration 是本次规则刷新请求的单调递增代次。
|
||||
const requestGeneration = ++shippingRulesRequestGeneration.current;
|
||||
// rules 是当前规则读取返回的非敏感自动化规则集合。
|
||||
const rules = await getShippingRules();
|
||||
if (requestGeneration === shippingRulesRequestGeneration.current) setShippingRules(rules);
|
||||
}, []);
|
||||
|
||||
// batchState 是 ItemList feature 提供的批量铺货状态和动作边界。
|
||||
@@ -52,7 +62,6 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
// 解构数据 解构得到当前 Hook 返回的状态和操作函数。
|
||||
const {
|
||||
showBatchModal,
|
||||
setShowBatchModal,
|
||||
batchLoading,
|
||||
batchPhase,
|
||||
batchFile,
|
||||
@@ -130,8 +139,16 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
} = itemActions;
|
||||
|
||||
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
|
||||
Promise.all([getAccountDetails(), getItems(), getShippingRules(), getItemPublishBatches(20)])
|
||||
// controller 取消组件卸载前仍在执行的首屏并行请求。
|
||||
const controller = new AbortController();
|
||||
// initialItemsGeneration、initialRulesGeneration 分别记录首屏请求对应的列表与规则代次。
|
||||
const initialItemsGeneration = ++itemsRequestGeneration.current;
|
||||
const initialRulesGeneration = ++shippingRulesRequestGeneration.current;
|
||||
// active 标识当前组件实例是否仍接受首屏响应。
|
||||
let active = true;
|
||||
Promise.all([getAccountDetails({ signal: controller.signal }), getItems(undefined, { signal: controller.signal }), getShippingRules({ signal: controller.signal }), getItemPublishBatches(20, { signal: controller.signal })])
|
||||
.then(/* 当前回调处理异步操作结果。 */ ([accountList, itemList, ruleList, batches]) => {
|
||||
if (!active || controller.signal.aborted || initialItemsGeneration !== itemsRequestGeneration.current || initialRulesGeneration !== shippingRulesRequestGeneration.current) return;
|
||||
setAccounts(accountList);
|
||||
setItems(itemList);
|
||||
setShippingRules(ruleList);
|
||||
@@ -140,7 +157,13 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
|| batches.find(/* 当前回调处理集合中的单个元素。 */ batch => batch.status !== 'preview');
|
||||
setRecentBatch(recoverable || null);
|
||||
})
|
||||
.catch(/* 当前回调处理异步操作结果。 */ (e) => console.error('加载商品配置失败:', e));
|
||||
.catch(/* 当前回调处理异步操作结果。 */ (e) => {
|
||||
if (!controller.signal.aborted) console.error('加载商品配置失败:', e);
|
||||
});
|
||||
return /* 首屏请求清理回调在卸载时取消请求并阻止状态回写。 */ () => {
|
||||
active = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, []);
|
||||
|
||||
// rulesForItem 规则列表For商品,负责当前功能中的对应处理。
|
||||
@@ -892,7 +915,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
</button>
|
||||
)}
|
||||
{!['running', 'canceling'].includes(batchDetail.status) && (
|
||||
<button onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => { setShowBatchModal(false); loadItems(); loadShippingRules(); }} className="flex-1 px-6 py-3.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold">
|
||||
<button onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => { void closeBatchModal(); void loadItems(); void loadShippingRules(); }} className="flex-1 px-6 py-3.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold">
|
||||
完成
|
||||
</button>
|
||||
)}
|
||||
|
||||
@@ -207,7 +207,7 @@ export interface AutomationRunIssue {
|
||||
/** cookie_id 表示登录凭证标识。 */ cookie_id: string;
|
||||
/** order_id 表示订单标识。 */ order_id: string;
|
||||
/** trigger_type 表示触发条件类型。 */ trigger_type: string;
|
||||
/** error_message 表示错误消息。 */ error_message: string;
|
||||
/** error_message 保存自动化运行失败的可展示说明,不包含账号凭证。 */ error_message: string;
|
||||
/** issue_kind 表示问题类型。 */ issue_kind: 'external_result_unknown' | 'invalid_snapshot' | 'rule_unavailable' | 'partial_failure' | 'execution_failed';
|
||||
/** allowed_resolutions 表示允许的解决方式。 */ allowed_resolutions: Array<'continue' | 'retry' | 'cancel'>;
|
||||
/** action_cursor 表示动作游标。 */ action_cursor: number;
|
||||
@@ -219,7 +219,7 @@ export interface DeferredAutomationIssue {
|
||||
/** id 表示标识。 */ id: number;
|
||||
/** cookie_id 表示登录凭证标识。 */ cookie_id: string;
|
||||
/** trigger_type 表示触发条件类型。 */ trigger_type: string;
|
||||
/** error_message 表示错误消息。 */ error_message: string;
|
||||
/** error_message 保存延迟自动化任务的失败说明,不包含账号凭证。 */ error_message: string;
|
||||
/** attempt_count 表示尝试次数。 */ attempt_count: number;
|
||||
/** updated_at 表示最后更新时间。 */ updated_at: string;
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ export const useSettings = (): UseSettingsResult => {
|
||||
if (!current?.ai_model && models.length > 0) {
|
||||
setSettings(/* 当前回调处理用户交互或异步状态变化。 */ previous => previous ? { ...previous, ai_model: models[0] } : previous);
|
||||
}
|
||||
} catch (/* error 表示错误。 */ error) {
|
||||
} catch (/* error 保存模型发现请求的失败原因;取消请求不会进入页面错误状态。 */ error) {
|
||||
if (signal?.aborted || isSettingsAbortError(error)) return;
|
||||
setAiModels([]);
|
||||
setModelDropdownOpen(false);
|
||||
@@ -174,7 +174,7 @@ export const useSettings = (): UseSettingsResult => {
|
||||
await updateSystemSettings(buildPersistableSettings(settings), { signal: controller.signal });
|
||||
if (!isCurrentSettingsRequest(requestSequence.current, sequence, controller.signal)) return;
|
||||
window.alert('系统配置已保存');
|
||||
} catch (/* error 表示错误。 */ error) {
|
||||
} catch (/* error 保存系统设置提交请求的失败原因;过期响应不会覆盖当前表单。 */ error) {
|
||||
if (!isCurrentSettingsRequest(requestSequence.current, sequence, controller.signal) || isSettingsAbortError(error)) return;
|
||||
setSaveError(settingsErrorMessage(error, '保存配置失败'));
|
||||
} finally {
|
||||
@@ -210,7 +210,7 @@ export const useSettings = (): UseSettingsResult => {
|
||||
}
|
||||
setCredentialsMessage(createCredentialsMessage('success', result.message || '登录凭据已更新'));
|
||||
window.setTimeout(/* 当前回调处理用户交互或异步状态变化。 */ () => window.location.reload(), 1400);
|
||||
} catch (/* error 表示错误。 */ error) {
|
||||
} catch (/* error 保存登录凭据提交请求的失败原因;不写入日志或持久化状态。 */ error) {
|
||||
if (!isCurrentSettingsRequest(requestSequence.current, sequence, controller.signal) || isSettingsAbortError(error)) return;
|
||||
setCredentialsMessage(createCredentialsMessage('error', settingsErrorMessage(error, '登录凭据更新失败')));
|
||||
} finally {
|
||||
|
||||
Reference in new issue
Block a user