重构:完成架构一致性整改与生命周期收口
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 {
|
||||
|
||||
@@ -7,8 +7,8 @@ describe('official Xianyu emoji mapping', () => {
|
||||
expect(xianyuEmojis).toHaveLength(126);
|
||||
expect(xianyuEmojis[0][0]).toBe('尊嘟假嘟');
|
||||
expect(xianyuEmojis.at(-1)?.[0]).toBe('爱心');
|
||||
expect(new Set(xianyuEmojis.map(([name]) => name /* 回调函数负责当前业务流程。 */)).size).toBe(126);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
expect(new Set(xianyuEmojis.map(([name]) => name /* name 是官方表情面板中的显示名称。 */)).size).toBe(126);
|
||||
} /* 测试回调断言官方表情目录的数量、顺序和名称唯一性。 */);
|
||||
|
||||
test('uses official CDN assets and renders bracket codes inline', () => {
|
||||
for (const [, url] /* [, url] 表示请求地址。 */ of xianyuEmojis) {
|
||||
@@ -18,5 +18,5 @@ describe('official Xianyu emoji mapping', () => {
|
||||
expect(html).toContain('你好');
|
||||
expect(html).toContain('alt="[捂脸哭]"');
|
||||
expect(html).toContain('alt="[送花]"');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言 CDN 地址及文本表情节点的渲染结果。 */);
|
||||
} /* 测试套件回调汇总表情目录和文本转换契约。 */);
|
||||
@@ -508,9 +508,10 @@ export const xianyuEmojis = [
|
||||
] as const; /* xianyuEmojis 表示xianyuEmojis。 */
|
||||
|
||||
export const emojiURL = (url: string) => url; /* emojiURL 表示emoji请求地址。 */
|
||||
const emojiLookup = new Map<string, string>(xianyuEmojis.map(([name, url]) => [name, url] /* 回调函数负责当前业务流程。 */)); /* emojiLookup 表示emojiLookup。 */
|
||||
// emojiLookup 将闲鱼文本表情名称映射为图片地址,供渲染函数快速查找。
|
||||
const emojiLookup = new Map<string, string>(xianyuEmojis.map(([name, url]) => [name, url] /* name 和 url 是表情目录中的名称及静态地址。 */));
|
||||
|
||||
export const renderXianyuText = (text: string) => text.split(/(\[[^\]]+\])/g).map((part, index) => {
|
||||
const url = part.startsWith('[') ? emojiLookup.get(part.slice(1, -1)) : undefined; /* url 表示请求地址。 */
|
||||
return url ? <img key={index} src={url} alt={part} title={part} className="mx-0.5 inline-block h-7 w-7 align-middle" /> : <React.Fragment key={index}>{part}</React.Fragment>;
|
||||
}) /* 回调函数负责当前业务流程。 */; /* renderXianyuText 表示renderXianyuText。 */
|
||||
}) /* part 是待解析文本片段,index 为 React 列表键。 */; /* renderXianyuText 将文本中的表情标记替换为图片节点。 */
|
||||
@@ -13,20 +13,20 @@ describe('online chat UI contract', () => {
|
||||
expect(chat).not.toContain('grid-cols-[320px_minmax(0,1fr)_');
|
||||
expect(chat).toContain('activeAccountID');
|
||||
expect(chat).toContain('activeChatID');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言聊天页的账号标签和双栏布局契约。 */);
|
||||
|
||||
test('uses neutral user labels instead of assuming buyer role', () => {
|
||||
const chat = source('app/features/chat/pages/Chat.tsx'); /* chat 表示chat。 */
|
||||
expect(chat).toContain('用户 ID:');
|
||||
expect(chat).not.toContain('买家 ID:');
|
||||
expect(chat).not.toContain('选择一个买家');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言用户标签不误用买家角色。 */);
|
||||
|
||||
test('frontend connects only to the application chat websocket', () => {
|
||||
const chatHook = source('app/features/chat/hooks.ts'); /* chatHook 表示chatHook。 */
|
||||
expect(chatHook).toContain('/api/v1/chat/ws');
|
||||
expect(chatHook).not.toContain('wss-goofish.dingtalk.com');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言前端只连接应用层聊天 WebSocket。 */);
|
||||
|
||||
test('renders peer/self identity and verified media capabilities', () => {
|
||||
const chat = source('app/features/chat/pages/Chat.tsx'); /* chat 表示chat。 */
|
||||
@@ -36,13 +36,13 @@ describe('online chat UI contract', () => {
|
||||
expect(chat).toContain("message.message_type === 'image'");
|
||||
expect(chat).toContain("message.message_type === 'video'");
|
||||
expect(chatHook).toContain('sendChatImage');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言头像、媒体类型及发送 API 的渲染能力。 */);
|
||||
|
||||
test('renders official notices as neutral system messages', () => {
|
||||
const chat = source('app/features/chat/pages/Chat.tsx'); /* chat 表示chat。 */
|
||||
expect(chat).toContain("message.message_type === 'system'");
|
||||
expect(chat).toContain('justify-center py-1');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言平台通知以居中的系统消息呈现。 */);
|
||||
|
||||
test('keeps the active chat at the bottom when new messages arrive', () => {
|
||||
const chat = source('app/features/chat/pages/Chat.tsx'); /* chat 表示chat。 */
|
||||
@@ -52,12 +52,12 @@ describe('online chat UI contract', () => {
|
||||
expect(chat).toContain('onScroll={handleMessageScroll}');
|
||||
expect(chatHook).toContain('container.scrollHeight - container.scrollTop - container.clientHeight');
|
||||
expect(chatHook).toContain('[activeAccountID, activeChatID, messages, messagesLoading]');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言新消息到达时当前会话保持滚动到底部。 */);
|
||||
|
||||
test('sidebar exposes collapse control and chat primary navigation', () => {
|
||||
const sidebar = source('shared/ui/Sidebar.tsx'); /* sidebar 表示sidebar。 */
|
||||
expect(sidebar).toContain("id: 'chat'");
|
||||
expect(sidebar).toContain('onToggleCollapsed');
|
||||
expect(sidebar).toContain('collapsed ? \'w-16\' : \'w-64\'');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言侧边栏折叠控制和聊天主导航入口。 */);
|
||||
} /* 测试套件回调汇总聊天页面结构契约。 */);
|
||||
@@ -28,11 +28,11 @@ describe('global color token contract', () => {
|
||||
test('page components do not contain hard-coded color values', () => {
|
||||
const violations = pageSources.flatMap((filePath) => {
|
||||
const source = readFileSync(filePath, 'utf8'); /* source 表示source。 */
|
||||
return [...source.matchAll(hardCodedColorPattern)].map((match) => `${filePath}:${match[0]}` /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */); /* violations 表示violations。 */
|
||||
return [...source.matchAll(hardCodedColorPattern)].map((match) => `${filePath}:${match[0]}` /* match 是命中的硬编码颜色及其源码位置。 */);
|
||||
} /* flatMap 回调读取单个页面源码并收集其中的颜色令牌违规项。 */); /* violations 汇总每个页面绕过设计令牌的颜色值。 */
|
||||
|
||||
expect(violations).toEqual([]);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言页面源码不直接写入色值。 */);
|
||||
|
||||
test('the primary brand and highlight colors are defined in the central stylesheet', () => {
|
||||
const globalStyles = readFileSync(resolve(__dirname, 'index.css'), 'utf8'); /* globalStyles 表示globalStyles。 */
|
||||
@@ -42,5 +42,5 @@ describe('global color token contract', () => {
|
||||
expect(globalStyles).toContain('--color-success-500:');
|
||||
expect(globalStyles).toContain('--color-warning-500:');
|
||||
expect(globalStyles).toContain('--color-danger-500:');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言全局样式提供全部核心色彩令牌。 */);
|
||||
} /* 测试套件回调汇总页面颜色令牌的静态契约。 */);
|
||||
@@ -10,27 +10,27 @@ describe('date ranges', () => {
|
||||
['30days', '2026-06-11'],
|
||||
] as const)('%s includes exactly the requested number of days', (range, startDate) => {
|
||||
expect(getDateRange(range, now)).toEqual({ startDate, endDate: '2026-07-10' });
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 参数化测试回调断言预设范围包含正确的起始日期。 */);
|
||||
|
||||
test('previous range has the same length without overlap', () => {
|
||||
const current = getDateRange('7days', now); /* current 表示current。 */
|
||||
expect(getPreviousDateRange(current)).toEqual({ startDate: '2026-06-27', endDate: '2026-07-03' });
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言上一周期等长且不与当前周期重叠。 */);
|
||||
|
||||
test('works across year boundaries', () => {
|
||||
expect(getDateRange('3days', new Date('2026-01-01T12:00:00'))).toEqual({
|
||||
startDate: '2025-12-30',
|
||||
endDate: '2026-01-01',
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言跨年日期计算保持日历正确性。 */);
|
||||
|
||||
test('rejects reversed custom dates', () => {
|
||||
expect(() => getDateRange('custom', now, '2026-07-11', '2026-07-10') /* 回调函数负责当前业务流程。 */).toThrow('开始日期不能晚于结束日期');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
expect(() => getDateRange('custom', now, '2026-07-11', '2026-07-10') /* 断言回调调用日期范围函数并触发参数校验。 */).toThrow('开始日期不能晚于结束日期');
|
||||
} /* 测试回调断言反向自定义日期被拒绝。 */);
|
||||
|
||||
test('支持自定义日期和昨天范围', () => {
|
||||
expect(getDateRange('custom', now, '2026-07-01', '2026-07-05')).toEqual({ startDate: '2026-07-01', endDate: '2026-07-05' });
|
||||
expect(getDateRange('yesterday', now)).toEqual({ startDate: '2026-07-09', endDate: '2026-07-09' });
|
||||
expect(getDateRange('today', now)).toEqual({ startDate: '2026-07-10', endDate: '2026-07-10' });
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言自定义、今天和昨天范围的边界。 */);
|
||||
} /* 测试套件回调汇总日期范围计算契约。 */);
|
||||
@@ -4,10 +4,10 @@ import { formatLocalDateTime } from './dateTime';
|
||||
describe('formatLocalDateTime', () => {
|
||||
test('uses the browser local timezone and the standard second-level format', () => {
|
||||
expect(formatLocalDateTime(new Date(2026, 6, 15, 10, 54, 12))).toBe('2026-07-15 10:54:12');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言本地时区下的秒级日期时间格式。 */);
|
||||
|
||||
test('returns a placeholder for missing or invalid timestamps', () => {
|
||||
expect(formatLocalDateTime()).toBe('-');
|
||||
expect(formatLocalDateTime('not-a-date')).toBe('-');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言缺失或非法时间戳使用占位符。 */);
|
||||
} /* 测试套件回调汇总日期时间格式化契约。 */);
|
||||
@@ -15,15 +15,15 @@ const collectSourceFiles = (directory: string): string[] => readdirSync(director
|
||||
return collectSourceFiles(filePath);
|
||||
}
|
||||
return /\.(ts|tsx)$/.test(entry.name) ? [filePath] : [];
|
||||
}) /* 回调函数负责当前业务流程。 */;
|
||||
}) /* flatMap 回调递归汇总当前目录下的生产 TypeScript/TSX 文件。 */;
|
||||
|
||||
// productionSources 返回排除测试文件后的生产源码及其相对路径。
|
||||
const productionSources = (): Array<{ /* relativePath 表示relative当前路径。 */ relativePath: string; /* source 表示source。 */ source: string }> => collectSourceFiles(sourceRoot)
|
||||
.filter(filePath => !filePath.endsWith('.test.ts') && !filePath.endsWith('.test.tsx') /* 回调函数负责当前业务流程。 */)
|
||||
.filter(filePath => !filePath.endsWith('.test.ts') && !filePath.endsWith('.test.tsx') /* filePath 为待排除测试文件的源码路径。 */)
|
||||
.map(filePath => ({
|
||||
relativePath: relative(sourceRoot, filePath).split('/').join('/'),
|
||||
source: readFileSync(filePath, 'utf8'),
|
||||
}) /* 回调函数负责当前业务流程。 */);
|
||||
}) /* map 回调读取单个生产文件并保留稳定相对路径。 */);
|
||||
|
||||
// extractModuleSpecifiers 提取静态 import、re-export 与动态 import 的模块路径,用于检查目录边界而不依赖编译器私有 AST。
|
||||
const extractModuleSpecifiers = (source: string): string[] => {
|
||||
@@ -87,46 +87,56 @@ describe('React feature dependency boundaries', () => {
|
||||
}
|
||||
})();
|
||||
expect(exists).toBe(false);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言旧集中式 API 入口已从源码树移除。 */);
|
||||
|
||||
test('network clients are only imported by feature API adapters', () => {
|
||||
// violations 保存页面、组件或非 API feature 文件中的共享网络客户端依赖。
|
||||
const violations = productionSources()
|
||||
.filter(file => file.source.includes("from '../../../shared/http/client'") || file.source.includes("from '../../../../shared/http/client'") /* 回调函数负责当前业务流程。 */)
|
||||
.filter(file => !/(?:\/api|Api)\.ts$/.test(file.relativePath) /* 回调函数负责当前业务流程。 */)
|
||||
.map(file => file.relativePath /* 回调函数负责当前业务流程。 */);
|
||||
.filter(file => file.source.includes("from '../../../shared/http/client'") || file.source.includes("from '../../../../shared/http/client'") /* file 是当前待检查的生产模块。 */)
|
||||
.filter(file => !/(?:\/api|Api)\.ts$/.test(file.relativePath) /* 仅保留不属于特性 API 适配器的模块。 */)
|
||||
.map(file => file.relativePath /* 输出违规模块的相对路径以便定位。 */);
|
||||
|
||||
expect(violations).toEqual([]);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言共享 HTTP 客户端只由特性 API 适配器导入。 */);
|
||||
|
||||
test('production React code does not call fetch or axios outside the request boundary', () => {
|
||||
// violations 保存页面或组件中直接发起网络请求的源码路径。
|
||||
const violations = productionSources()
|
||||
.filter(file => file.relativePath !== 'shared/http/client.ts' && /\bfetch\s*\(|\baxios\b/.test(file.source) /* 回调函数负责当前业务流程。 */)
|
||||
.map(file => file.relativePath /* 回调函数负责当前业务流程。 */);
|
||||
.filter(file => file.relativePath !== 'shared/http/client.ts' && /\bfetch\s*\(|\baxios\b/.test(file.source) /* file 是当前待审计直接网络调用的生产模块。 */)
|
||||
.map(file => file.relativePath /* 输出越过 HTTP 客户端的模块路径。 */);
|
||||
|
||||
expect(violations).toEqual([]);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言生产组件不会绕过共享 HTTP 边界。 */);
|
||||
|
||||
test('production dynamic imports are limited to route-level page loading', () => {
|
||||
// violations 保存业务模块内部通过动态导入隐藏依赖或绕过路由边界的源码路径。
|
||||
const violations = productionSources()
|
||||
.filter(file => /\bimport\s*\(/.test(file.source) /* 回调检查当前文件是否包含动态模块导入。 */)
|
||||
.filter(file => file.relativePath !== 'app/shell/AuthenticatedShell.tsx' /* 路由壳允许按页面拆分懒加载。 */)
|
||||
.map(file => file.relativePath /* 将违规文件转换为稳定的断言值。 */);
|
||||
|
||||
expect(violations).toEqual([]);
|
||||
} /* 测试回调断言动态导入仅用于路由级页面懒加载。 */);
|
||||
|
||||
test('feature API adapters are the only feature files allowed to depend on shared HTTP', () => {
|
||||
// violations 保存 feature 内部绕过 API 适配层的共享服务依赖。
|
||||
const violations = productionSources()
|
||||
.filter(file => file.relativePath.startsWith('app/features/') && file.source.includes("shared/http/client") /* 回调函数负责当前业务流程。 */)
|
||||
.filter(file => !/(?:\/api|Api)\.ts$/.test(file.relativePath) /* 回调函数负责当前业务流程。 */)
|
||||
.map(file => file.relativePath /* 回调函数负责当前业务流程。 */);
|
||||
.filter(file => file.relativePath.startsWith('app/features/') && file.source.includes("shared/http/client") /* file 是使用共享 HTTP 客户端的特性模块。 */)
|
||||
.filter(file => !/(?:\/api|Api)\.ts$/.test(file.relativePath) /* 仅保留越过 API 适配层的模块。 */)
|
||||
.map(file => file.relativePath /* 输出违规特性模块的路径。 */);
|
||||
|
||||
expect(violations).toEqual([]);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言特性内部网络访问经过 API 适配层。 */);
|
||||
|
||||
test('production API adapters use versioned HTTP paths', () => {
|
||||
// violations 保存 API 适配层中仍然指向未版本化前缀的生产源码路径。
|
||||
const violations = productionSources()
|
||||
.filter(file => /(?:\/api|Api)\.ts$/.test(file.relativePath) /* 回调函数负责当前业务流程。 */)
|
||||
.filter(file => /['"`]\/api\/(?!v1(?:\/|['"`]))/.test(file.source) /* 回调函数负责当前业务流程。 */)
|
||||
.map(file => file.relativePath /* 回调函数负责当前业务流程。 */);
|
||||
.filter(file => /(?:\/api|Api)\.ts$/.test(file.relativePath) /* file 是待检查路径前缀的 API 适配器。 */)
|
||||
.filter(file => /['"`]\/api\/(?!v1(?:\/|['"`]))/.test(file.source) /* 保留仍请求未版本化 API 的适配器。 */)
|
||||
.map(file => file.relativePath /* 输出使用旧 API 路径的适配器路径。 */);
|
||||
|
||||
expect(violations).toEqual([]);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言生产 API 适配器统一使用 v1 路径。 */);
|
||||
|
||||
test('legacy component state compatibility entrypoints have been removed', () => {
|
||||
// legacyEntrypoints 是不应重新引入页面层状态转发文件的旧路径。
|
||||
@@ -147,8 +157,8 @@ describe('React feature dependency boundaries', () => {
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
} /* 回调函数负责当前业务流程。 */)).toEqual([]);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* filter 回调探测每个历史状态入口是否仍可被读取。 */)).toEqual([]);
|
||||
} /* 测试回调断言旧页面状态转发入口全部移除。 */);
|
||||
|
||||
test('feature source files do not import another feature implementation', () => {
|
||||
// violations 保存 feature 源文件解析后指向其他 feature 目录的导入关系。
|
||||
@@ -170,7 +180,7 @@ describe('React feature dependency boundaries', () => {
|
||||
});
|
||||
|
||||
expect(violations).toEqual([]);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言 feature 之间没有实现层依赖。 */);
|
||||
|
||||
test('shared source files do not import application or feature implementations', () => {
|
||||
// violations 保存 shared 代码反向依赖 app 或 feature 的本地导入关系。
|
||||
@@ -182,7 +192,7 @@ describe('React feature dependency boundaries', () => {
|
||||
.map(/* reverseViolationFormatter 输出可定位的反向依赖。 */ importPath => `${file.relativePath} -> ${importPath}`));
|
||||
|
||||
expect(violations).toEqual([]);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言 shared 不会反向依赖应用或特性实现。 */);
|
||||
|
||||
test('application root only composes global boundaries and no legacy root components remain', () => {
|
||||
// appRootEntries 是 app 目录允许存在的顶层架构职责目录。
|
||||
@@ -198,7 +208,7 @@ describe('React feature dependency boundaries', () => {
|
||||
expect(appSource).toContain("from './app/router/AppRouter'");
|
||||
expect(appSource).not.toMatch(/app\/features|services\/|shared\/http/);
|
||||
expect(existsSync(resolve(sourceRoot, 'components'))).toBe(false);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言应用根目录只保留全局装配职责。 */);
|
||||
|
||||
test('all canonical page entrypoints live under their owning feature pages directory', () => {
|
||||
// actualPageEntrypoints 是全部位于 feature pages 目录的生产页面入口;认证页可使用具名导出,其余页面由路由壳懒加载默认导出。
|
||||
@@ -208,5 +218,5 @@ describe('React feature dependency boundaries', () => {
|
||||
.sort();
|
||||
|
||||
expect(actualPageEntrypoints).toEqual([...canonicalPageEntrypoints].sort());
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言页面入口归属各自 feature 的 pages 目录。 */);
|
||||
} /* 测试套件回调汇总前端依赖方向与目录边界门禁。 */);
|
||||
@@ -8,10 +8,10 @@ describe('item list primary action colors', () => {
|
||||
test('uses the shared primary blue for batch publishing', () => {
|
||||
expect(itemList).toContain('bg-brand text-white hover:bg-brand-highlight');
|
||||
expect(itemList).not.toContain('bg-blue-600 text-white hover:bg-blue-700');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言批量发布使用共享品牌主色。 */);
|
||||
|
||||
test('uses the lighter emerald tone for publishing actions', () => {
|
||||
expect(itemList).toContain('bg-emerald-500 text-white hover:bg-emerald-600');
|
||||
expect(itemList).not.toContain('bg-emerald-600 text-white hover:bg-emerald-700');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言发布操作使用约定的浅色绿色令牌。 */);
|
||||
} /* 测试套件回调汇总商品列表视觉令牌契约。 */);
|
||||
@@ -4,7 +4,7 @@ import { buildEmailChannelConfig, enableCustomSMTP, normalizeEmailChannelConfig
|
||||
describe('email notification SMTP modes', () => {
|
||||
test('recognizes legacy channel overrides as custom SMTP', () => {
|
||||
expect(normalizeEmailChannelConfig({ to_email: '[email protected]', smtp_server: 'legacy.example.com' }).use_custom_smtp).toBe(true);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言旧 SMTP 覆盖字段会选择自定义模式。 */);
|
||||
|
||||
test('inherit mode removes every channel-level SMTP override', () => {
|
||||
expect(buildEmailChannelConfig({
|
||||
@@ -13,7 +13,7 @@ describe('email notification SMTP modes', () => {
|
||||
smtp_server: 'stale.example.com',
|
||||
smtp_use_tls: false,
|
||||
})).toEqual({ to_email: '[email protected]', use_custom_smtp: false });
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言继承系统 SMTP 模式会清除渠道级覆盖。 */);
|
||||
|
||||
test('custom mode starts from a complete copy of system SMTP settings', () => {
|
||||
const result = enableCustomSMTP({ to_email: '[email protected]' }, {
|
||||
@@ -32,13 +32,13 @@ describe('email notification SMTP modes', () => {
|
||||
smtp_use_tls: false,
|
||||
smtp_use_ssl: true,
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言自定义模式复制完整的系统 SMTP 设置。 */);
|
||||
|
||||
test('显式字符串开关和未知值遵循默认策略', () => {
|
||||
expect(normalizeEmailChannelConfig({ use_custom_smtp: 'true' }).use_custom_smtp).toBe(true);
|
||||
expect(normalizeEmailChannelConfig({ use_custom_smtp: 'off' }).use_custom_smtp).toBe(false);
|
||||
expect(normalizeEmailChannelConfig({ use_custom_smtp: 'unknown' }).use_custom_smtp).toBe(false);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言字符串开关和未知值的兼容归一化策略。 */);
|
||||
|
||||
test('启用自定义 SMTP 时补齐默认端口和发件地址', () => {
|
||||
// result 是仅提供账号信息时补齐默认 SMTP 字段的配置。
|
||||
@@ -47,11 +47,11 @@ describe('email notification SMTP modes', () => {
|
||||
expect(result.smtp_from_address).toBe('[email protected]');
|
||||
expect(result.smtp_use_tls).toBe(true);
|
||||
expect(result.smtp_use_ssl).toBe(false);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言缺省 SMTP 端口和发件地址的补全规则。 */);
|
||||
|
||||
test('构建自定义模式配置时保留完整 SMTP 覆盖字段', () => {
|
||||
// result 是自定义 SMTP 渠道的规范化配置。
|
||||
const result = buildEmailChannelConfig({ to_email: ' [email protected] ', use_custom_smtp: true, smtp_server: 'smtp.example.com', smtp_port: 465 });
|
||||
expect(result).toMatchObject({ to_email: '[email protected]', use_custom_smtp: true, smtp_server: 'smtp.example.com', smtp_port: 465 });
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言自定义 SMTP 配置保留所有覆盖字段。 */);
|
||||
} /* 测试套件回调汇总邮件通知配置兼容契约。 */);
|
||||
@@ -20,7 +20,8 @@ const parseBoolean = (value: unknown, fallback: boolean): boolean => {
|
||||
|
||||
export const normalizeEmailChannelConfig = (config: Record<string, unknown>): Record<string, unknown> => {
|
||||
const hasExplicitMode = Object.prototype.hasOwnProperty.call(config, 'use_custom_smtp'); /* hasExplicitMode 表示hasExplicitMode。 */
|
||||
const hasLegacyOverrides = smtpOverrideKeys.some(key => String(config[key] ?? '').trim() !== '' /* 回调函数负责当前业务流程。 */); /* hasLegacyOverrides 表示hasLegacyOverrides。 */
|
||||
// hasLegacyOverrides 表示旧 SMTP 字段中是否仍有非空值,以便兼容层推断配置模式。
|
||||
const hasLegacyOverrides = smtpOverrideKeys.some(key => String(config[key] ?? '').trim() !== '' /* key 是当前检查的旧 SMTP 字段名。 */);
|
||||
return {
|
||||
...config,
|
||||
use_custom_smtp: hasExplicitMode
|
||||
|
||||
@@ -9,8 +9,7 @@
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"test:coverage": "vitest run --coverage",
|
||||
"comments:check": "node scripts/check-comments.mjs --mode check --root . --baseline ../.commentlint/frontend-baseline.json",
|
||||
"comments:baseline": "node scripts/check-comments.mjs --mode baseline --root . --baseline ../.commentlint/frontend-baseline.json",
|
||||
"comments:check": "node scripts/check-comments.mjs --mode check --root .",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
+19
-19
@@ -24,14 +24,14 @@ describe('frontend navigation routing', () => {
|
||||
const appRouteIDs = extractSingleQuotedValues(app, /case\s+'([^']+)'/g); /* appRouteIDs 表示appRouteIDs。 */
|
||||
|
||||
expect([...sidebarIDs].sort()).toEqual([...appRouteIDs].sort());
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言已登录应用的路由、访问控制或延迟加载契约。 */);
|
||||
|
||||
test('active navigation uses the primary action blue', () => {
|
||||
const sidebar = readFrontendFile('shared/ui/Sidebar.tsx'); /* sidebar 表示sidebar。 */
|
||||
|
||||
expect(sidebar).toContain("'bg-brand text-white shadow-brand-active'");
|
||||
expect(sidebar).not.toContain("'bg-sky-500 text-white'");
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言已登录应用的路由、访问控制或延迟加载契约。 */);
|
||||
|
||||
test('route pages are lazy-loaded behind a shared Suspense boundary', () => {
|
||||
const app = readFrontendFile('app/shell/AuthenticatedShell.tsx'); /* app 表示认证后页面组合器源码。 */
|
||||
@@ -42,7 +42,7 @@ describe('frontend navigation routing', () => {
|
||||
expect(app).toContain('<Suspense fallback={<PageLoading />}>');
|
||||
expect(app).not.toContain("import Dashboard from '../../components/Dashboard'");
|
||||
expect(app).toContain("import('../features/dashboard/pages/Dashboard')");
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言已登录应用的路由、访问控制或延迟加载契约。 */);
|
||||
|
||||
test('authenticated shell owns sidebar and page composition', () => {
|
||||
const app = readFrontendFile('app/router/AppRouter.tsx'); /* app 表示认证后的路由组合器源码。 */
|
||||
@@ -53,7 +53,7 @@ describe('frontend navigation routing', () => {
|
||||
expect(shell).toContain('const AuthenticatedShell: React.FC<AuthenticatedShellProps>');
|
||||
expect(shell).toContain('<Sidebar');
|
||||
expect(shell).toContain('<AppContent');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言已登录应用的路由、访问控制或延迟加载契约。 */);
|
||||
|
||||
test('logout button invalidates the backend session before clearing UI state', () => {
|
||||
const app = readFrontendFile('app/router/AppRouter.tsx'); /* app 表示认证后路由组合器源码。 */
|
||||
@@ -63,7 +63,7 @@ describe('frontend navigation routing', () => {
|
||||
expect(sessionProvider).toContain('await logout();');
|
||||
expect(sessionProvider).toContain("window.addEventListener('auth:logout'");
|
||||
expect(app).toContain('onLogout={handleLogout}');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言已登录应用的路由、访问控制或延迟加载契约。 */);
|
||||
|
||||
test('settings page does not expose backend-inactive system controls', () => {
|
||||
const settings = readFrontendFile('app/features/settings/pages/Settings.tsx'); /* settings 表示settings。 */
|
||||
@@ -76,7 +76,7 @@ describe('frontend navigation routing', () => {
|
||||
expect(settings).not.toContain('默认自动回复内容');
|
||||
expect(settingsConstants).toContain('SETTINGS_SAVE_OMIT_KEYS');
|
||||
expect(settings).toContain('保存后需重启服务生效');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言已登录应用的路由、访问控制或延迟加载契约。 */);
|
||||
|
||||
test('admin-only settings navigation is gated by session role', () => {
|
||||
const app = readFrontendFile('app/router/AppRouter.tsx'); /* app 表示认证后路由组合器源码。 */
|
||||
@@ -92,7 +92,7 @@ describe('frontend navigation routing', () => {
|
||||
expect(sidebar).toContain('isAdmin = false');
|
||||
expect(sidebar).toContain("...(isAdmin ? [{ id: 'settings'");
|
||||
expect(settingsHook).toContain('setLoadError');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言已登录应用的路由、访问控制或延迟加载契约。 */);
|
||||
|
||||
test('captcha remote settings expose the reference privacy and fallback semantics', () => {
|
||||
const settings = readFrontendFile('app/features/settings/pages/Settings.tsx'); /* settings 表示settings。 */
|
||||
@@ -103,7 +103,7 @@ describe('frontend navigation routing', () => {
|
||||
expect(settings).toContain("'captcha.remote_pass_cookies'");
|
||||
expect(settings).toContain('默认关闭');
|
||||
expect(settings).toContain('只有网络不可用或超时才回退本机引擎');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言已登录应用的路由、访问控制或延迟加载契约。 */);
|
||||
|
||||
test('email notification config separates system and custom SMTP modes', () => {
|
||||
const notifications = readFrontendFile('app/features/notifications/pages/Notifications.tsx'); /* notifications 表示notifications。 */
|
||||
@@ -117,7 +117,7 @@ describe('frontend navigation routing', () => {
|
||||
expect(notificationModal).toContain('use_custom_smtp');
|
||||
expect(notificationState).not.toContain("key: 'from'");
|
||||
expect(notifications).not.toContain('注册验证码');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言已登录应用的路由、访问控制或延迟加载契约。 */);
|
||||
|
||||
test('keyword reply UI matches contains-based backend behavior', () => {
|
||||
const rules = readFrontendFile('app/features/rules/pages/Rules.tsx'); /* rules 表示规则集合。 */
|
||||
@@ -126,7 +126,7 @@ describe('frontend navigation routing', () => {
|
||||
expect(rules).not.toContain('精确匹配');
|
||||
expect(rules).not.toContain('模糊包含');
|
||||
expect(rules).not.toContain('匹配类型');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言已登录应用的路由、访问控制或延迟加载契约。 */);
|
||||
|
||||
test('vite proxy does not advertise removed backend routes', () => {
|
||||
const vite = readFrontendFile('vite.config.ts'); /* vite 表示vite。 */
|
||||
@@ -142,21 +142,21 @@ describe('frontend navigation routing', () => {
|
||||
]) {
|
||||
expect(vite).not.toContain(`'${staleRoute}'`);
|
||||
}
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言已登录应用的路由、访问控制或延迟加载契约。 */);
|
||||
|
||||
test('item delivery shortcut opens existing automation rule modal', () => {
|
||||
const actions = readFrontendFile('app/features/rules/ruleActions.ts'); /* actions 表示规则动作协调器源码。 */
|
||||
const existingRuleBranch = actions.match(/if \(rule\) \{([\s\S]*?)\} else \{/); /* existingRuleBranch 表示existing当前规则Branch。 */
|
||||
|
||||
expect(existingRuleBranch?.[1]).toContain('openAutomationRule(rule)');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言已登录应用的路由、访问控制或延迟加载契约。 */);
|
||||
|
||||
test('item delivery shortcut is not marked handled before async open completes', () => {
|
||||
const actions = readFrontendFile('app/features/rules/ruleActions.ts'); /* actions 表示规则动作协调器源码。 */
|
||||
|
||||
expect(actions).not.toContain('handledDeliveryTarget.current = initialDeliveryTarget.requestId');
|
||||
expect(actions).toContain('onDeliveryTargetHandled?.();');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言已登录应用的路由、访问控制或延迟加载契约。 */);
|
||||
|
||||
test('automation editor keeps multiple delivery contents for normal products', () => {
|
||||
const rules = readFrontendFile('app/features/rules/pages/Rules.tsx'); /* rules 表示规则集合。 */
|
||||
@@ -166,7 +166,7 @@ describe('frontend navigation routing', () => {
|
||||
expect(rules).toContain('{displayVariants.map((variant, index) => (');
|
||||
expect(actions).toContain('variants.map(');
|
||||
expect(rules).not.toContain(': (isMultiSpecRule ? variants : [variants[0]]).map');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言已登录应用的路由、访问控制或延迟加载契约。 */);
|
||||
|
||||
test('batch publishing help explains card fields without required-field jargon', () => {
|
||||
const itemList = readFrontendFile('app/features/items/pages/ItemList.tsx'); /* itemList 表示当前商品List。 */
|
||||
@@ -175,7 +175,7 @@ describe('frontend navigation routing', () => {
|
||||
expect(itemList).toContain('“付款后发送的卡密”怎么填');
|
||||
expect(itemList).toContain('101:1:0;102:2:3');
|
||||
expect(itemList).toContain('买家购买 3 件时会发送 6 份');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言已登录应用的路由、访问控制或延迟加载契约。 */);
|
||||
|
||||
test('item publish image previews revoke object urls', () => {
|
||||
const itemList = readFrontendFile('app/features/items/itemActions.ts'); /* itemList 表示商品动作协调器源码。 */
|
||||
@@ -184,7 +184,7 @@ describe('frontend navigation routing', () => {
|
||||
expect(itemList).toContain('URL.createObjectURL(file)');
|
||||
expect(itemList).toContain('URL.revokeObjectURL(preview.url)');
|
||||
expect(itemList).not.toContain('src={URL.createObjectURL(file)}');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言已登录应用的路由、访问控制或延迟加载契约。 */);
|
||||
|
||||
test('QR verification removes the external link and clearly requires in-app risk verification', () => {
|
||||
const accounts = readFrontendFile('app/features/accounts/pages/AccountList.tsx'); /* accounts 表示账号集合。 */
|
||||
@@ -199,7 +199,7 @@ describe('frontend navigation routing', () => {
|
||||
expect(riskPanel).not.toContain('我已在闲鱼 App 完成验证');
|
||||
expect(riskPanel).not.toContain('<button');
|
||||
expect(riskPanel).not.toContain('重试');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言已登录应用的路由、访问控制或延迟加载契约。 */);
|
||||
|
||||
test('account editor exposes password-login refresh and never renders its verification URL', () => {
|
||||
const accounts = [
|
||||
@@ -212,5 +212,5 @@ describe('frontend navigation routing', () => {
|
||||
expect(accounts).toContain('密码登录刷新授权');
|
||||
expect(accounts).toContain('账号已触发平台风控,需要完成人脸识别');
|
||||
expect(accounts).not.toContain('result.verification_url');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言已登录应用的路由、访问控制或延迟加载契约。 */);
|
||||
} /* 测试套件回调汇总路由装配与访问边界契约。 */);
|
||||
@@ -12,8 +12,8 @@ describe('responsive rules layout', () => {
|
||||
expect(rules).toContain('min-w-0 space-y-8');
|
||||
expect(rules).toContain('xl:grid-cols-[minmax(270px,0.72fr)_minmax(0,1.28fr)]');
|
||||
expect(rules).not.toContain('2xl:grid-cols-[360px_1fr]');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言规则列表中的卡密动作表单字段。 */);
|
||||
} /* 测试套件回调汇总自动化规则页面契约。 */);
|
||||
|
||||
describe('rules summary counts', () => {
|
||||
test('uses server-side aggregate counts instead of the current page length', () => {
|
||||
@@ -24,5 +24,5 @@ describe('rules summary counts', () => {
|
||||
expect(rules).toContain('筛选结果构成');
|
||||
expect(rules).not.toContain('rulesByTrigger[trigger].length');
|
||||
expect(api).toContain('trigger_counts');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言规则页使用服务端聚合计数。 */);
|
||||
} /* 测试套件回调汇总规则统计和布局契约。 */);
|
||||
@@ -7,18 +7,26 @@ import ts from "typescript";
|
||||
// HAN_PATTERN 用于识别至少包含一个汉字的注释文本。
|
||||
const HAN_PATTERN = /\p{Script=Han}/u;
|
||||
|
||||
// TEMPLATE_COMMENT_PATTERNS 是阶段 10 禁止继续保留的机械注释句式。
|
||||
const TEMPLATE_COMMENT_PATTERNS = [
|
||||
{ name: '保存当前处理流程', expression: /保存.{0,80}供当前处理流程使用/u },
|
||||
{ name: '负责相关处理', expression: /负责.{0,80}相关处理/u },
|
||||
{ name: '泛化回调职责', expression: /回调函数负责当前业务流程/u },
|
||||
{ name: '泛化错误说明', expression: /表示错误/u },
|
||||
{ name: '泛化数量说明', expression: /表示数量/u },
|
||||
];
|
||||
|
||||
// parseArguments 解析注释门禁所需的少量命令行参数。
|
||||
function parseArguments(argv) {
|
||||
// options 保存命令行参数及其默认值。
|
||||
const options = {
|
||||
mode: "check",
|
||||
root: ".",
|
||||
baseline: ".commentlint/frontend-baseline.json",
|
||||
};
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
// argument 是当前处理的命令行参数。
|
||||
const argument = argv[index];
|
||||
if (argument === "--mode" || argument === "--root" || argument === "--baseline") {
|
||||
if (argument === "--mode" || argument === "--root") {
|
||||
// value 是当前选项紧随其后的值。
|
||||
const value = argv[index + 1];
|
||||
if (!value) {
|
||||
@@ -28,12 +36,35 @@ function parseArguments(argv) {
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
if (options.mode !== "check" && options.mode !== "baseline") {
|
||||
if (options.mode !== "check" && options.mode !== "template-audit") {
|
||||
throw new Error(`不支持的模式:${options.mode}`);
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
// collectTemplateFindings 逐行收集 TypeScript/TSX 中不具备实际语义的历史模板注释。
|
||||
function collectTemplateFindings(rootDirectory) {
|
||||
// findings 保存模板注释的相对路径、行号与命中规则,便于阶段 10 按文件替换。
|
||||
const findings = [];
|
||||
// filePath 是当前待审计的 TypeScript 或 TSX 源码文件。
|
||||
for (const filePath of collectSourceFiles(rootDirectory)) {
|
||||
// relativePath 是跨平台稳定的源码相对路径。
|
||||
const relativePath = path.relative(rootDirectory, filePath).split(path.sep).join("/");
|
||||
// lines 是保留原始行号的源码文本行集合。
|
||||
const lines = fs.readFileSync(filePath, "utf8").split(/\r?\n/u);
|
||||
// sourceLine、lineIndex 是当前待匹配的源码文本及其零基行号。
|
||||
for (const [lineIndex, sourceLine] of lines.entries()) {
|
||||
// pattern 是当前禁止模板句式的审计规则。
|
||||
for (const pattern of TEMPLATE_COMMENT_PATTERNS) {
|
||||
if (pattern.expression.test(sourceLine)) {
|
||||
findings.push({ file: relativePath, line: lineIndex + 1, kind: pattern.name, name: "template-comment" });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return sortFindings(findings);
|
||||
}
|
||||
|
||||
// collectSourceFiles 递归找到需要检查的 TypeScript 和 TSX 源文件。
|
||||
function collectSourceFiles(rootDirectory) {
|
||||
// sourceFiles 保存按路径排序后的源码文件。
|
||||
@@ -131,7 +162,7 @@ function getNodeName(node) {
|
||||
return "anonymous";
|
||||
}
|
||||
|
||||
// findingFor 将一个 AST 节点转换成稳定的基线记录。
|
||||
// findingFor 将一个 AST 节点转换成稳定的门禁记录。
|
||||
function findingFor(relativePath, sourceFile, node, kind) {
|
||||
// line 是声明所在的一基行号。
|
||||
const line = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
|
||||
@@ -144,7 +175,7 @@ function inspectSourceFile(rootDirectory, filePath) {
|
||||
const sourceText = fs.readFileSync(filePath, "utf8");
|
||||
// sourceFile 是开启父节点信息的 TypeScript AST。
|
||||
const sourceFile = ts.createSourceFile(filePath, sourceText, ts.ScriptTarget.Latest, true, filePath.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
|
||||
// relativePath 使基线在不同机器上保持可复用。
|
||||
// relativePath 使门禁输出在不同机器上保持稳定。
|
||||
const relativePath = path.relative(rootDirectory, filePath).split(path.sep).join("/");
|
||||
// findings 保存当前文件的注释问题。
|
||||
const findings = [];
|
||||
@@ -167,7 +198,7 @@ function inspectSourceFile(rootDirectory, filePath) {
|
||||
return findings;
|
||||
}
|
||||
|
||||
// findingKey 生成历史基线中的稳定键。
|
||||
// findingKey 生成排序和输出使用的稳定键。
|
||||
function findingKey(finding) {
|
||||
return `${finding.file}:${finding.line}:${finding.kind}:${finding.name}`;
|
||||
}
|
||||
@@ -177,51 +208,35 @@ function sortFindings(findings) {
|
||||
return findings.sort((left, right) => findingKey(left).localeCompare(findingKey(right)));
|
||||
}
|
||||
|
||||
// writeBaseline 写入缩进格式的前端历史问题基线。
|
||||
function writeBaseline(filePath, findings) {
|
||||
// parentDirectory 是基线文件所属目录。
|
||||
const parentDirectory = path.dirname(filePath);
|
||||
fs.mkdirSync(parentDirectory, { recursive: true });
|
||||
fs.writeFileSync(filePath, `${JSON.stringify(findings, null, 2)}\n`, "utf8");
|
||||
}
|
||||
|
||||
// readBaseline 读取历史问题并建立快速查询集合。
|
||||
function readBaseline(filePath) {
|
||||
// baselineMissing 表示最终严格门禁已删除历史基线文件,此时必须按空集合执行。
|
||||
if (!fs.existsSync(filePath)) return new Set();
|
||||
// baselineText 是基线文件的 JSON 文本。
|
||||
const baselineText = fs.readFileSync(filePath, "utf8");
|
||||
// baselineFindings 是反序列化后的历史问题数组。
|
||||
const baselineFindings = JSON.parse(baselineText);
|
||||
return new Set(baselineFindings.map(findingKey));
|
||||
}
|
||||
|
||||
// main 执行前端源码扫描、基线生成或新增问题检查。
|
||||
// main 执行前端源码严格注释检查或输出模板注释审计结果。
|
||||
function main() {
|
||||
// options 保存解析后的命令行选项。
|
||||
const options = parseArguments(process.argv.slice(2));
|
||||
// rootDirectory 是规范化后的源码根目录。
|
||||
const rootDirectory = path.resolve(options.root);
|
||||
// baselinePath 是规范化后的历史基线路径。
|
||||
const baselinePath = path.resolve(options.baseline);
|
||||
// findings 是当前所有 TypeScript/TSX 文件的检查结果。
|
||||
const findings = sortFindings(collectSourceFiles(rootDirectory).flatMap((filePath) => inspectSourceFile(rootDirectory, filePath)));
|
||||
if (options.mode === "baseline") {
|
||||
writeBaseline(baselinePath, findings);
|
||||
console.log(`commentlint: 已记录 ${findings.length} 个历史问题到 ${options.baseline}`);
|
||||
if (options.mode === "template-audit") {
|
||||
// templateFindings 是按稳定顺序排列的前端模板注释记录。
|
||||
const templateFindings = collectTemplateFindings(rootDirectory);
|
||||
for (const finding of templateFindings) {
|
||||
console.log(`${finding.file}:${finding.line}: [${finding.kind}] 模板化注释`);
|
||||
}
|
||||
console.log(`commentlint: 发现 ${templateFindings.length} 条模板化注释`);
|
||||
return;
|
||||
}
|
||||
// baselineKeys 保存允许继续存在的历史问题。
|
||||
const baselineKeys = readBaseline(baselinePath);
|
||||
// newFindings 只包含本次新增或位置变化的问题。
|
||||
const newFindings = findings.filter((finding) => !baselineKeys.has(findingKey(finding)));
|
||||
for (const finding of newFindings) {
|
||||
// findings 是当前所有 TypeScript/TSX 文件的检查结果。
|
||||
const findings = sortFindings(collectSourceFiles(rootDirectory).flatMap((filePath) => inspectSourceFile(rootDirectory, filePath)));
|
||||
for (const finding of findings) {
|
||||
console.log(`${finding.file}:${finding.line}: [${finding.kind}] ${finding.name} 缺少中文注释`);
|
||||
}
|
||||
if (newFindings.length > 0) {
|
||||
throw new Error(`发现 ${newFindings.length} 个新增问题`);
|
||||
// templateFindings 是阶段 10 不允许保留的机械注释位置。
|
||||
const templateFindings = collectTemplateFindings(rootDirectory);
|
||||
for (const finding of templateFindings) {
|
||||
console.log(`${finding.file}:${finding.line}: [${finding.kind}] 模板化注释`);
|
||||
}
|
||||
console.log(`commentlint: 通过(扫描 ${findings.length} 个历史问题)`);
|
||||
if (findings.length > 0 || templateFindings.length > 0) {
|
||||
throw new Error(`发现 ${findings.length} 个缺少中文注释项和 ${templateFindings.length} 条模板化注释`);
|
||||
}
|
||||
console.log("commentlint: 通过(无缺少中文注释或模板化注释)");
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
@@ -21,7 +21,7 @@ test('maps AMap POI fields to the publish location shape', () => {
|
||||
poi_name: '人民广场',
|
||||
province: '上海市',
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言高德 POI 字段能够转换为发布地点 DTO。 */);
|
||||
|
||||
test('drops incomplete or invalid AMap POIs', () => {
|
||||
expect(amapPOIToPublishLocation({
|
||||
@@ -32,4 +32,4 @@ test('drops incomplete or invalid AMap POIs', () => {
|
||||
cityname: '上海市',
|
||||
location: { lng: 0, lat: 31.2 },
|
||||
})).toBeNull();
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言缺少或非法坐标的 POI 会被丢弃。 */);
|
||||
@@ -102,7 +102,7 @@ const loadAMap = (): Promise<AMapAPI> => {
|
||||
const timeout = window.setTimeout(() => {
|
||||
cleanup();
|
||||
reject(new Error('高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置'));
|
||||
} /* 回调函数负责当前业务流程。 */, 15_000); /* timeout 表示timeout。 */
|
||||
} /* 定时器到期时终止脚本加载并返回网络配置错误。 */, 15_000); /* timeout 是高德脚本加载的毫秒上限。 */
|
||||
|
||||
window.__ydisksAmapLoaded = finish;
|
||||
script.id = AMAP_SCRIPT_ID;
|
||||
@@ -111,12 +111,12 @@ const loadAMap = (): Promise<AMapAPI> => {
|
||||
script.onerror = () => {
|
||||
cleanup();
|
||||
reject(new Error('高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置'));
|
||||
} /* 回调函数负责当前业务流程。 */;
|
||||
} /* 脚本节点触发 error 时释放监听并拒绝加载 Promise。 */;
|
||||
if (!existing) document.head.appendChild(script);
|
||||
} /* 回调函数负责当前业务流程。 */).catch(error => {
|
||||
} /* 单例加载过程只创建一次脚本节点并复用完成 Promise。 */).catch(error => {
|
||||
amapLoadPromise = null;
|
||||
throw error;
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 失败时清空单例 Promise,允许后续调用重新加载脚本。 */);
|
||||
|
||||
return amapLoadPromise;
|
||||
}; /* loadAMap 表示loadAMap。 */
|
||||
@@ -162,10 +162,11 @@ export const getPublishLocations = async (longitude: number, latitude: number):
|
||||
reject(new Error('高德地图附近地址查询失败,请稍后重试'));
|
||||
return;
|
||||
}
|
||||
// locations 是过滤无效坐标后的发布地点列表,供商品发布表单使用。
|
||||
const locations = (result?.poiList?.pois || [])
|
||||
.map(amapPOIToPublishLocation)
|
||||
.filter((location): location is PublishLocation => location !== null /* 回调函数负责当前业务流程。 */); /* locations 表示locations。 */
|
||||
.filter((location): location is PublishLocation => location !== null /* location 是转换后仍具备有效坐标的地点。 */);
|
||||
resolve(locations);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 搜索完成后将地点结果交给调用方并结束本次高德回调。 */);
|
||||
} /* 高德回调只处理当前请求,组件卸载后由 cleanup 移除监听。 */);
|
||||
}; /* getPublishLocations 表示getPublishLocations。 */
|
||||
@@ -1,7 +1,7 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { del, get, post, postForm, put } from './client';
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals() /* 回调函数负责当前业务流程。 */);
|
||||
afterEach(() => vi.unstubAllGlobals() /* 清理测试安装的全局网络替身,避免跨用例泄漏。 */);
|
||||
|
||||
describe('request helpers', () => {
|
||||
test('encodes query parameters and includes credentials', async () => {
|
||||
@@ -16,7 +16,7 @@ describe('request helpers', () => {
|
||||
method: 'GET',
|
||||
credentials: 'include',
|
||||
}));
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:encodes query parameters and includes credentials。 */);
|
||||
|
||||
test('serializes JSON bodies', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ success: true }), {
|
||||
@@ -31,7 +31,7 @@ describe('request helpers', () => {
|
||||
body: JSON.stringify({ username: 'admin' }),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}));
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:serializes JSON bodies。 */);
|
||||
|
||||
test('支持 PUT 和 DELETE 请求及查询参数', async () => {
|
||||
// fetchMock 是 PUT/DELETE 请求的网络替身。
|
||||
@@ -45,7 +45,7 @@ describe('request helpers', () => {
|
||||
await expect(del('/items/1', { force: true })).resolves.toEqual({ ok: true });
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(1, '/items/1', expect.objectContaining({ method: 'PUT', body: JSON.stringify({ enabled: true }) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(2, '/items/1?force=true', expect.objectContaining({ method: 'DELETE' }));
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:支持 PUT 和 DELETE 请求及查询参数。 */);
|
||||
|
||||
test('surfaces unified backend errors', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ code: 'bad_request', message: 'bad request' }), {
|
||||
@@ -53,7 +53,7 @@ describe('request helpers', () => {
|
||||
headers: { 'content-type': 'application/json' },
|
||||
})));
|
||||
await expect(get('/bad')).rejects.toThrow('bad request');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:surfaces unified backend errors。 */);
|
||||
|
||||
test('使用非 JSON 错误文本作为失败消息', async () => {
|
||||
// fetchMock 是返回纯文本错误的网络替身。
|
||||
@@ -64,7 +64,7 @@ describe('request helpers', () => {
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await expect(get('/gateway')).rejects.toThrow('网关暂时不可用');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:使用非 JSON 错误文本作为失败消息。 */);
|
||||
|
||||
test('成功的非 JSON 响应直接返回文本', async () => {
|
||||
// fetchMock 是返回纯文本成功响应的网络替身。
|
||||
@@ -75,7 +75,7 @@ describe('request helpers', () => {
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await expect(get('/text')).resolves.toBe('ok');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:成功的非 JSON 响应直接返回文本。 */);
|
||||
|
||||
test('JSON 错误体无法解析时使用 HTTP 状态兜底', async () => {
|
||||
// fetchMock 是返回损坏 JSON 错误体的网络替身。
|
||||
@@ -86,14 +86,14 @@ describe('request helpers', () => {
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await expect(get('/broken')).rejects.toThrow('请求失败: 500');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:JSON 错误体无法解析时使用 HTTP 状态兜底。 */);
|
||||
|
||||
test('普通请求纯文本错误体读取失败时使用状态码兜底', /* 当前回调验证普通请求文本错误读取失败分支。 */ async () => {
|
||||
// response 是文本读取失败的普通请求响应替身。
|
||||
const response = { ok: false, status: 502, headers: { get: /* contentTypeGetter 返回纯文本类型。 */ () => 'text/plain' }, text: vi.fn().mockRejectedValue(new Error('读取失败')) } as unknown as Response;
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response));
|
||||
await expect(get('/broken-text')).rejects.toThrow('请求失败: 502');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:普通请求纯文本错误体读取失败时使用状态码兜底。 */);
|
||||
|
||||
test('网络层异常原样透传', async () => {
|
||||
// fetchMock 是抛出非取消网络异常的替身。
|
||||
@@ -101,7 +101,7 @@ describe('request helpers', () => {
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await expect(get('/network-error')).rejects.toThrow('网络断开');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:网络层异常原样透传。 */);
|
||||
|
||||
test('notifies the app when an authenticated request returns 401', async () => {
|
||||
const events = new EventTarget(); /* events 表示events。 */
|
||||
@@ -115,7 +115,7 @@ describe('request helpers', () => {
|
||||
|
||||
await expect(get('/private')).rejects.toThrow();
|
||||
expect(listener).toHaveBeenCalledOnce();
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:notifies the app when an authenticated request returns 401。 */);
|
||||
|
||||
test('并发认证失败只触发一次登出事件', /* 当前回调验证认证失效通知的并发去重。 */ async () => {
|
||||
// events 是认证失效事件分发目标。
|
||||
@@ -131,7 +131,7 @@ describe('request helpers', () => {
|
||||
|
||||
await Promise.allSettled([get('/private-a'), get('/private-b')]);
|
||||
expect(listener).toHaveBeenCalledOnce();
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:并发认证失败只触发一次登出事件。 */);
|
||||
|
||||
test('does not notify logout for a failed login request', async () => {
|
||||
const events = new EventTarget(); /* events 表示events。 */
|
||||
@@ -145,7 +145,7 @@ describe('request helpers', () => {
|
||||
|
||||
await expect(post('/login', {}, { skipAuthLogout: true })).rejects.toThrow();
|
||||
expect(listener).not.toHaveBeenCalled();
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:does not notify logout for a failed login request。 */);
|
||||
|
||||
test('posts FormData without forcing a content type', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response('ok', { status: 200 })); /* fetchMock 表示fetchMock。 */
|
||||
@@ -158,20 +158,20 @@ describe('request helpers', () => {
|
||||
credentials: 'include',
|
||||
body: form,
|
||||
}));
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:posts FormData without forcing a content type。 */);
|
||||
|
||||
test('aborts requests at the configured timeout', async () => {
|
||||
vi.useFakeTimers();
|
||||
const fetchMock = vi.fn((_url: string, init: RequestInit) => new Promise<Response>((_resolve, reject) => {
|
||||
init.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')) /* 回调函数负责当前业务流程。 */, { once: true });
|
||||
} /* 回调函数负责当前业务流程。 */) /* 回调函数负责当前业务流程。 */); /* fetchMock 表示fetchMock。 */
|
||||
init.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')) /* 请求被取消时拒绝网络替身 Promise。 */, { once: true });
|
||||
} /* 网络替身只在测试显式取消前保持挂起。 */) /* mockImplementation 回调模拟永不完成的上传请求。 */); /* fetchMock 是用于观察上传请求取消的网络替身。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const pending = get('/slow', undefined, { timeoutMs: 50 }); /* pending 表示pending。 */
|
||||
const rejection = expect(pending).rejects.toThrow('请求超时'); /* rejection 表示rejection。 */
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
await rejection;
|
||||
vi.useRealTimers();
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:aborts requests at the configured timeout。 */);
|
||||
|
||||
test('上传请求超时后返回上传专用错误', /* 当前回调验证上传请求的超时错误分支。 */ async () => {
|
||||
vi.useFakeTimers();
|
||||
@@ -190,7 +190,7 @@ describe('request helpers', () => {
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:上传请求超时后返回上传专用错误。 */);
|
||||
|
||||
test('外部 AbortSignal 取消请求时返回取消错误', async () => {
|
||||
// controller 是调用方主动取消请求的控制器。
|
||||
@@ -207,7 +207,7 @@ describe('request helpers', () => {
|
||||
const pending = get('/cancelled', undefined, { signal: controller.signal });
|
||||
controller.abort();
|
||||
await expect(pending).rejects.toThrow('请求已取消');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:外部 AbortSignal 取消请求时返回取消错误。 */);
|
||||
|
||||
test('上传请求支持外部取消并返回取消错误', async () => {
|
||||
// controller 是上传调用方主动取消请求的控制器。
|
||||
@@ -224,7 +224,7 @@ describe('request helpers', () => {
|
||||
const pending = postForm('/upload', new FormData(), { signal: controller.signal });
|
||||
controller.abort();
|
||||
await expect(pending).rejects.toThrow('请求已取消');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:上传请求支持外部取消并返回取消错误。 */);
|
||||
|
||||
test('上传网络层异常原样透传', async () => {
|
||||
// fetchMock 是抛出非取消上传异常的替身。
|
||||
@@ -232,7 +232,7 @@ describe('request helpers', () => {
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await expect(postForm('/upload', new FormData())).rejects.toThrow('上传网络断开');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:上传网络层异常原样透传。 */);
|
||||
|
||||
test('上传失败保留原始错误载荷', async () => {
|
||||
// payload 是服务端返回的上传错误详情。
|
||||
@@ -251,14 +251,14 @@ describe('request helpers', () => {
|
||||
expect(uploadError.message).toBe('文件格式不支持');
|
||||
expect(uploadError.payload).toEqual(payload);
|
||||
}
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:上传失败保留原始错误载荷。 */);
|
||||
|
||||
test('非 JSON 上传错误体读取失败时使用状态码兜底', /* 当前回调验证上传错误文本读取失败分支。 */ async () => {
|
||||
// response 是文本读取失败的上传响应替身。
|
||||
const response = { ok: false, status: 500, headers: { get: /* contentTypeGetter 返回纯文本类型。 */ () => 'text/plain' }, text: vi.fn().mockRejectedValue(new Error('读取失败')) } as unknown as Response;
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response));
|
||||
await expect(postForm('/upload', new FormData())).rejects.toThrow('请求失败: 500');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:非 JSON 上传错误体读取失败时使用状态码兜底。 */);
|
||||
|
||||
test('上传认证失败也会触发登出事件', /* 当前回调验证上传请求的认证失效通知。 */ async () => {
|
||||
// events 是上传认证失效事件分发目标。
|
||||
@@ -273,7 +273,7 @@ describe('request helpers', () => {
|
||||
})));
|
||||
await expect(postForm('/upload', new FormData())).rejects.toThrow();
|
||||
expect(listener).toHaveBeenCalledOnce();
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:上传认证失败也会触发登出事件。 */);
|
||||
|
||||
test('请求开始前已取消的外部信号返回取消错误', /* 当前回调验证预取消信号分支。 */ async () => {
|
||||
// controller 是预先取消请求的外部控制器。
|
||||
@@ -285,5 +285,5 @@ describe('request helpers', () => {
|
||||
}));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await expect(get('/pre-cancelled', undefined, { signal: controller.signal })).rejects.toThrow('请求已取消');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调验证:请求开始前已取消的外部信号返回取消错误。 */);
|
||||
} /* 测试套件回调汇总共享 HTTP 客户端的成功、失败与取消契约。 */);
|
||||
@@ -31,8 +31,8 @@ const notifyAuthExpired = () => {
|
||||
window.dispatchEvent(new Event('auth:logout'));
|
||||
queueMicrotask(() => {
|
||||
authLogoutPending = false;
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
}; /* notifyAuthExpired 表示notifyAuthExpired。 */
|
||||
} /* 微任务结束后允许下一次未授权响应重新触发登出通知。 */);
|
||||
}; /* notifyAuthExpired 合并同一批 401 响应,避免重复触发会话清理。 */
|
||||
|
||||
const buildQueryString = (params?: QueryParams): string => {
|
||||
if (!params) return '';
|
||||
@@ -76,7 +76,7 @@ const request = async <T>(method: RequestMethod, url: string, options: RequestOp
|
||||
if (!res.ok) {
|
||||
if (res.status === 401 && !options.skipAuthLogout) notifyAuthExpired();
|
||||
// payload 是后端统一错误 DTO 或非 JSON 错误文本。
|
||||
const payload = isJson ? await res.json().catch(() => undefined /* 回调函数负责当前业务流程。 */) : await res.text().catch(() => undefined /* 回调函数负责当前业务流程。 */);
|
||||
const payload = isJson ? await res.json().catch(() => undefined /* 错误响应 JSON 无法解析时交由状态码兜底。 */) : await res.text().catch(() => undefined /* 错误响应文本无法读取时交由状态码兜底。 */);
|
||||
const message = errorMessageFromPayload(payload, res.status); // message 是统一错误 DTO 提取出的用户可见说明。
|
||||
throw new Error(message);
|
||||
}
|
||||
@@ -115,7 +115,7 @@ export const postForm = async <T>(url: string, body: FormData, options: RequestC
|
||||
|
||||
const contentType = res.headers.get('content-type') || ''; /* contentType 表示contentType。 */
|
||||
const isJson = contentType.includes('application/json'); /* isJson 表示isJson。 */
|
||||
const payload = isJson ? await res.json().catch(() => undefined /* 回调函数负责当前业务流程。 */) : await res.text().catch(() => undefined /* 回调函数负责当前业务流程。 */); /* payload 表示payload。 */
|
||||
const payload = isJson ? await res.json().catch(() => undefined /* 上传错误 JSON 无法解析时交由状态码兜底。 */) : await res.text().catch(() => undefined /* 上传错误文本无法读取时交由状态码兜底。 */); /* payload 是上传接口返回的错误载荷,仅用于构造异常。 */
|
||||
|
||||
if (!res.ok) {
|
||||
if (res.status === 401) notifyAuthExpired();
|
||||
@@ -133,13 +133,13 @@ const controlledSignal = (external: AbortSignal | undefined, timeoutMs: number)
|
||||
const abortFromExternal = () => controller.abort(external?.reason); /* abortFromExternal 表示abortFromExternal。 */
|
||||
if (external?.aborted) abortFromExternal();
|
||||
else external?.addEventListener('abort', abortFromExternal, { once: true });
|
||||
const timer = globalThis.setTimeout(() => controller.abort(new DOMException('timeout', 'TimeoutError')) /* 回调函数负责当前业务流程。 */, Math.max(1, timeoutMs)); /* timer 表示timer。 */
|
||||
const timer = globalThis.setTimeout(() => controller.abort(new DOMException('timeout', 'TimeoutError')) /* 到达请求时限后主动取消底层请求。 */, Math.max(1, timeoutMs)); /* timer 保存请求超时定时器,完成或取消时必须清理。 */
|
||||
return {
|
||||
signal: controller.signal,
|
||||
cleanup: () => {
|
||||
globalThis.clearTimeout(timer);
|
||||
external?.removeEventListener('abort', abortFromExternal);
|
||||
} /* 回调函数负责当前业务流程。 */,
|
||||
} /* 外部取消或请求结束时移除监听并清理超时定时器。 */,
|
||||
};
|
||||
}; /* controlledSignal 表示controlledSignal。 */
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ interface YdisksLogoProps {
|
||||
}
|
||||
|
||||
interface YdisksBrandIconProps {
|
||||
/** sizeClass 表示数量Class。 */ sizeClass?: string;
|
||||
/** sizeClass 指定品牌图标尺寸相关的 Tailwind 类名,而非业务数量。 */ sizeClass?: string;
|
||||
/** logoClassName 表示品牌图标的 CSS 类名。 */ logoClassName?: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -7,14 +7,14 @@ describe('normalizeSMTPSettings', () => {
|
||||
smtp_from_name: '',
|
||||
smtp_from_address: '[email protected]',
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言旧发件人字段迁移为 envelope 地址。 */);
|
||||
|
||||
test('migrates a legacy display name and falls back to the SMTP user address', () => {
|
||||
expect(normalizeSMTPSettings({ smtp_from: '闲鱼助手', smtp_user: '[email protected]' })).toMatchObject({
|
||||
smtp_from_name: '闲鱼助手',
|
||||
smtp_from_address: '[email protected]',
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言旧显示名和 SMTP 用户地址的回退规则。 */);
|
||||
|
||||
test('preserves explicit split sender fields', () => {
|
||||
expect(normalizeSMTPSettings({
|
||||
@@ -25,17 +25,17 @@ describe('normalizeSMTPSettings', () => {
|
||||
smtp_from_name: '新名称',
|
||||
smtp_from_address: '[email protected]',
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言显式拆分后的发件字段优先保留。 */);
|
||||
|
||||
test('normalizes persisted SMTP transport strings', () => {
|
||||
expect(normalizeSMTPSettings({ smtp_use_tls: 'false', smtp_use_ssl: 'true' })).toMatchObject({
|
||||
smtp_use_tls: false,
|
||||
smtp_use_ssl: true,
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言持久化 SMTP 字符串会归一化为布尔值。 */);
|
||||
|
||||
test('保留布尔值并对未知字符串使用默认值', () => {
|
||||
expect(normalizeSMTPSettings({ smtp_use_tls: true, smtp_use_ssl: false })).toMatchObject({ smtp_use_tls: true, smtp_use_ssl: false });
|
||||
expect(normalizeSMTPSettings({ smtp_use_tls: 'unknown', smtp_use_ssl: 'unknown' })).toMatchObject({ smtp_use_tls: true, smtp_use_ssl: false });
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言布尔值和未知字符串的默认策略。 */);
|
||||
} /* 测试套件回调汇总 SMTP 配置迁移契约。 */);
|
||||
@@ -15,4 +15,4 @@ test('development server proxies versioned API and health checks', () => {
|
||||
expect(proxy).not.toHaveProperty('/qr-login');
|
||||
expect(proxy).not.toHaveProperty('/items');
|
||||
expect(proxy).not.toHaveProperty('/cookies');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 测试回调断言开发代理只转发版本化 API 和健康检查。 */);
|
||||
Reference in new issue
Block a user