fix(audit-20261019): T1-T9 审计修复、存储归属与审计日志列宽
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s

- T1 资金/库存/报价/自采 P1(BIZ-1/2/3/4/10/13/14)
- T2 主系统反向事件墓碑/改派/孤儿处理(BIZ-6/8/9)
- T3 选分公司 ticket、trust proxy、角色权限收口(SEC-2/3/4)
- T4 缺列/RLS/tenant 名单/FK/迁移执行器(DATA-1..8)
- T5 401 登出/分页/映射口径/blob/ZIP 中文名(FE-1..4/BIZ-15)
- T6 测试脚本目标守卫/config fail-fast/容器配置(OPS-2..8)
- T7 前后端测试与 lint 门禁清零
- T8 应付卡片按关联订单日(口径 A)
- T9 存储对象全链路归属校验、敏感列禁写、审计 target_id 超长修复
This commit is contained in:
Ubuntu
2026-10-19 16:16:51 +08:00
parent 601a207b1e
commit 5fa2bbfd55
252 changed files with 18656 additions and 721 deletions
@@ -75,7 +75,7 @@ const norm = (v: unknown) => String(v || '').trim().toLowerCase();
function parseQty(v: string): number {
const s = String(v || '').trim();
if (!s) return 0;
const cleaned = s.replace(/[^0-9.\-]/g, '').replace(/(?!^)-/g, '');
const cleaned = s.replace(/[^0-9.-]/g, '').replace(/(?!^)-/g, '');
const n = Number(cleaned);
return Number.isFinite(n) ? n : 0;
}
+10
View File
@@ -138,6 +138,16 @@ export function useNotificationStream(options: {
cache: 'no-store',
});
if (!res.ok || !res.body) {
/**
* FE-1:SSE 收到 401 = 认证失效 ⇒ **停止重连**并走统一登出
* (其它错误保持原有 2s→60s 指数退避,不改)。
*/
if (res.status === 401) {
stopped = true;
const { handleUnauthorized } = await import('../lib/localApiClient');
handleUnauthorized();
return;
}
throw new Error(`sse_http_${res.status}`);
}
@@ -0,0 +1,95 @@
// @vitest-environment jsdom
import { renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
/**
* FE-1(2026-10-19):通知流 SSE 收到 401 必须**停止重连**并触发统一登出;
* 其它错误(如 500)保持原有 2s→60s 指数退避重连(不得顺手改)。
*/
const SESSION_KEY = 'canteen.auth.session';
function setSession(): void {
localStorage.setItem(
SESSION_KEY,
JSON.stringify({ access_token: 't-1', user: { id: 'u1' } })
);
}
function installLocationStub(): { href: string } {
const loc = { href: '' };
try {
Object.defineProperty(window, 'location', { configurable: true, value: loc });
} catch {
(window as unknown as { location: { href: string } }).location = loc;
}
return loc;
}
function mockStreamResponse(status: number): void {
vi.stubGlobal(
'fetch',
vi.fn(async () => ({
ok: false,
status,
body: null,
}))
);
}
beforeEach(() => {
localStorage.clear();
vi.unstubAllGlobals();
});
afterEach(() => {
vi.unstubAllGlobals();
localStorage.clear();
});
describe('useNotificationStream:401 停止重连 + 登出', () => {
it('401 ⇒ 不安排下一次重试(无 2s 定时器)、session 被清并跳登录', async () => {
setSession();
const loc = installLocationStub();
mockStreamResponse(401);
const timeoutSpy = vi.spyOn(window, 'setTimeout');
const { unmount } = renderHook(() =>
useNotificationStream({
enabled: true,
onSnapshot: () => undefined,
})
);
await vi.waitFor(() => expect(globalThis.fetch).toHaveBeenCalledTimes(1));
// 401 的登出走动态 import(异步),等 session 被清/跳转发生
await vi.waitFor(() => expect(localStorage.getItem(SESSION_KEY)).toBeNull());
await vi.waitFor(() => expect(loc.href).toContain('/login'));
const retryDelays = timeoutSpy.mock.calls.map((call) => Number(call[1] || 0)).filter((ms) => ms >= 2000);
expect(retryDelays, '401 后不得安排 2s/指数退避重连').toEqual([]);
expect(loc.href).toContain('reason=expired');
unmount();
});
it('500 ⇒ 仍按原退避重连(2s 定时器存在,不登出)', async () => {
setSession();
installLocationStub();
mockStreamResponse(500);
const timeoutSpy = vi.spyOn(window, 'setTimeout');
const { unmount } = renderHook(() =>
useNotificationStream({
enabled: true,
onSnapshot: () => undefined,
})
);
await vi.waitFor(() => expect(globalThis.fetch).toHaveBeenCalledTimes(1));
await vi.waitFor(() => {
const retryDelays = timeoutSpy.mock.calls.map((call) => Number(call[1] || 0));
expect(retryDelays, '其它错误必须保持原有重连退避').toContain(2000);
});
expect(localStorage.getItem(SESSION_KEY)).toBeTruthy();
unmount();
});
});
import { useNotificationStream } from './useNotificationStream';
+6 -1
View File
@@ -128,7 +128,12 @@ function getAuthHeaders(): Record<string, string> {
let authRedirecting = false;
function handleUnauthorized() {
/**
* 401 统一登出(FE-1):清 session + 跳 `/login?reason=expired`;
* **无 session 不跳**(登录页输错密码等场景)。
* 导出给 `utils/workflowApi.ts` 共用,避免两套请求层行为漂移。
*/
export function handleUnauthorized() {
if (authRedirecting) return;
if (!getStoredSession()) return; // 无会话(如登录页输错密码)不触发自动登出
authRedirecting = true;
@@ -91,8 +91,9 @@ describe('商品映射(只读)面板', () => {
for (const forbidden of ['编辑', '绑定', '解绑', '保存']) {
expect(screen.queryByText(forbidden)).toBeNull();
}
// 进入时 refresh=1(先拉 D5 再展示)
// 进入时 refresh=1(先拉 D5 再展示),且显式取后端上限 500(FE-3:不静默截断)
expect((listApi.mock.calls[0][0] as any).refresh).toBe(true);
expect((listApi.mock.calls[0][0] as any).limit).toBe(500);
});
it('「只看未映射」⇒ 带 status=pending 重新请求', async () => {
@@ -100,10 +101,27 @@ describe('商品映射(只读)面板', () => {
await screen.findByText('草鱼');
fireEvent.click(screen.getByLabelText('只看未映射'));
await waitFor(() =>
expect(listApi.mock.calls.some(([arg]) => (arg as any).status === 'pending')).toBe(true)
expect(
listApi.mock.calls.some(
([arg]) => (arg as any).status === 'pending' && (arg as any).limit === 500
)
).toBe(true)
);
});
it('FE-3:summary 渲染服务端返回的**筛选口径**(不再假设全表)', async () => {
listApi.mockImplementation(async (options?: { status?: string; limit?: number }) => {
if (options?.status === 'pending') {
return { data: [ROWS[1]], summary: { total: 1, mapped: 0, unmapped: 1 }, pull: null };
}
return { data: ROWS, summary: { total: 2, mapped: 1, unmapped: 1 }, pull: null };
});
render(<QuoteSkuMappingsPanel />);
await screen.findByText('草鱼');
fireEvent.click(screen.getByLabelText('只看未映射'));
expect(await screen.findByText('共 1 个商品,已映射 0 / 未映射 1')).toBeTruthy();
});
it('关键字搜索 ⇒ 带 q 重新请求', async () => {
render(<QuoteSkuMappingsPanel />);
await screen.findByText('草鱼');
@@ -111,6 +129,23 @@ describe('商品映射(只读)面板', () => {
await waitFor(() => expect(listApi.mock.calls.some(([arg]) => (arg as any).q === '草鱼')).toBe(true));
});
it('搜索只查本地列表:连续击键防抖合并,且不得再带 refresh=1 触发全量 D5', async () => {
render(<QuoteSkuMappingsPanel />);
await screen.findByText('草鱼');
expect((listApi.mock.calls[0][0] as any).refresh).toBe(true);
const before = listApi.mock.calls.length;
const input = screen.getByLabelText('搜索 SKU/名称');
fireEvent.change(input, { target: { value: '草' } });
fireEvent.change(input, { target: { value: '草鱼' } });
await waitFor(() => expect(listApi.mock.calls.some(([arg]) => (arg as any).q === '草鱼')).toBe(true));
const after = listApi.mock.calls.slice(before);
// 两次击键只发一次请求(300ms 防抖),且不再触发 D5 全量同步
expect(after).toHaveLength(1);
expect(after.every(([arg]) => (arg as any).refresh !== true)).toBe(true);
});
it('开关关闭(503)⇒ 空态显示后端原文,不弹 toast', async () => {
listApi.mockRejectedValue(
Object.assign(new Error('报价单价格传递未开启(MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL)'), {
+22 -3
View File
@@ -1,4 +1,4 @@
import React, { useCallback, useEffect, useState } from 'react';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { RefreshCw, Search } from 'lucide-react';
import { notify } from '../../utils/notify';
import { useT } from '../../i18n';
@@ -30,20 +30,29 @@ export const QuoteSkuMappingsPanel: React.FC = () => {
const [unmappedOnly, setUnmappedOnly] = useState(false);
const [keyword, setKeyword] = useState('');
const [disabledReason, setDisabledReason] = useState<string | null>(null);
/** 只采信最后一次请求的响应:搜索/筛选连续触发时,旧响应不得覆盖新结果 */
const requestSeq = useRef(0);
/** 挂载时做一次完整 D5;之后关键字/筛选变化只查本地列表,不再触发外部全量同步 */
const mounted = useRef(false);
const load = useCallback(
async (options?: { refresh?: boolean }) => {
const seq = ++requestSeq.current;
setLoading(true);
try {
const result = await listSkuMappingsApi({
status: unmappedOnly ? 'pending' : undefined,
q: keyword.trim() || undefined,
// FE-3:显式取后端上限 500,避免默认 200 把「已映射在前」的未映射行截掉
limit: 500,
refresh: options?.refresh === true,
});
if (seq !== requestSeq.current) return;
setDisabledReason(null);
setRows(Array.isArray(result.data) ? result.data : []);
setSummary(result.summary || { total: 0, mapped: 0, unmapped: 0 });
} catch (error: any) {
if (seq !== requestSeq.current) return;
if (Number(error?.status) === 503 || error?.code === 'feature_disabled') {
setRows([]);
setDisabledReason(error?.message || t('quotes.skuMapping.loadFail'));
@@ -51,14 +60,24 @@ export const QuoteSkuMappingsPanel: React.FC = () => {
}
notify.error(error?.message || t('quotes.skuMapping.loadFail'));
} finally {
setLoading(false);
if (seq === requestSeq.current) setLoading(false);
}
},
[keyword, unmappedOnly, t]
);
useEffect(() => {
void load({ refresh: true });
if (!mounted.current) {
mounted.current = true;
// 进入页签时 refresh=1 拉一次 D5(契约 §5);搜索框击键不得重复触发全量外部同步。
void load({ refresh: true });
return;
}
// 搜索须防抖(.cursor/rules/frontend-ui-discipline.mdc);这里只查本地副本,不带 refresh。
const timer = setTimeout(() => {
void load();
}, 300);
return () => clearTimeout(timer);
}, [load]);
return (
-13
View File
@@ -2,25 +2,17 @@ import React, { useState, useEffect, useRef, useMemo } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import {
Truck,
Clock,
CheckCircle,
Route,
User,
Phone,
Package,
AlertCircle,
Search,
Eye,
Play,
PenTool,
Camera,
X,
ChevronRight,
ChevronDown,
List,
TrendingUp,
Timer,
CheckSquare,
FileText,
Download,
Share2,
@@ -424,7 +416,6 @@ export const DeliveryManagement: React.FC = () => {
}, [search]);
// dateRange 变化时重新加载,内部函数为稳定引用无需追踪
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(() => {
const load = async () => {
let bindings: CustomerBinding[] = [];
@@ -446,7 +437,6 @@ export const DeliveryManagement: React.FC = () => {
void fetchDeliveryData({ silent: true });
}, 15000);
return () => window.clearInterval(timer);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dateField, datePreset, dateRange?.start, dateRange?.end, canManageBindings, orderCodeSearch]);
useEffect(() => {
@@ -457,7 +447,6 @@ export const DeliveryManagement: React.FC = () => {
};
document.addEventListener('visibilitychange', onVisible);
return () => document.removeEventListener('visibilitychange', onVisible);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dateField, datePreset, dateRange?.start, dateRange?.end, canManageBindings, orderCodeSearch]);
useEffect(() => {
@@ -470,7 +459,6 @@ export const DeliveryManagement: React.FC = () => {
if (activeTab === 'routes' && canManageBindings) {
void fetchRouteDepartureSettings();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeTab, canManageBindings, scheduleFrom, scheduleTo, schedulePerson]);
const fetchRouteDepartureSettings = async () => {
@@ -744,7 +732,6 @@ export const DeliveryManagement: React.FC = () => {
};
// 已有客户绑定时进入页:自动按绑定测算一次(有额度用腾讯,否则预估仍展示)
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(() => {
if (!canManageBindings || didAutoRouteSyncRef.current) return;
if (customerBindings.length === 0) return;
@@ -94,7 +94,8 @@ describe('第三桶的两个真机缺陷(2026-10-14 测试中发现,已修
expect(panel).toContain("hiddenColumnId: 'purchase_cost' as const");
// 过滤后的列同时供表头与表体使用(4 处 map:2 表头 + 2 表体)
const filteredMapHits = panel.match(/\{columns\.map\(\(col\) => \{/g) || [];
expect(filteredMapHits.length, '表头2处 + 表体2处').toBe(4);
// 2026-10-15 列过滤收敛:表头/表体各 1 处 columns.map(共 2 处),隐藏列在统一过滤层实现
expect(filteredMapHits.length, '表头1处 + 表体1处').toBe(2);
// 空态/加载态的 colspan 必须跟过滤后的列数,否则表宽错位
expect(panel).not.toContain('colSpan={skuCostColumnCount}');
expect(panel.match(/colSpan=\{columns\.length\}/g)?.length).toBe(2);
@@ -679,7 +679,6 @@ export const InspectionManagement: React.FC = () => {
useEffect(() => {
void loadZoneChoices();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const zoneOptions = useMemo(
@@ -900,7 +899,6 @@ export const InspectionManagement: React.FC = () => {
useEffect(() => {
fetchInspections();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dateField, datePreset, dateRange?.start, dateRange?.end, activeTab, currentPage, pageSize, searchQuery, sourceFilter, gradeFilter, categoryFilter]);
const fetchInspections = async () => {
@@ -53,7 +53,7 @@ describe('Web 验收弹窗:存放区域候选刷新(bug 修复)', () => {
it('提成 loadZoneChoices 并在每次打开弹窗时重拉', () => {
expect(page).toContain('const loadZoneChoices = async () => {');
// 打开入库弹窗时重拉(否则刚建的区域要刷新页面才看得到)
expect(page).toMatch(/void loadZoneChoices\(\);\n };|void loadZoneChoices\(\);/);
expect(page).toMatch(/void loadZoneChoices\(\);\n {2}};|void loadZoneChoices\(\);/);
expect(page).toContain('每次打开都刷新区域候选');
});
});
+1 -1
View File
@@ -76,7 +76,7 @@ export function OrderTrashPanel({ open, onClose, onChanged }: OrderTrashPanelPro
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[110] p-4">
<div className="app-surface app-border app-foreground rounded-xl border w-full max-w-4xl max-h-[85vh] flex flex-col shadow-xl">
<div className="app-surface app-border app-foreground rounded-xl border w-full max-w-6xl max-h-[88vh] flex flex-col shadow-xl">
<div className="flex items-center justify-between gap-3 px-4 py-3 border-b app-border">
<div>
<h3 className="text-lg font-semibold flex items-center gap-2">
@@ -68,7 +68,8 @@ const SYNCED_ROW = {
payload: { apply: { status: 'applied', note: '我方销售价 5 → 4、金额 → 32' } },
} as const;
const listApi = vi.fn(async (params?: { status?: string; scope?: string }) => {
type ListParams = { status?: string; scope?: string; page?: number; pageSize?: number; limit?: number };
const defaultListImpl = async (params?: ListParams): Promise<any> => {
const status = params?.status;
const data =
status === 'approved'
@@ -80,16 +81,23 @@ const listApi = vi.fn(async (params?: { status?: string; scope?: string }) => {
: [PENDING_ROW, SYNCED_ROW];
return {
total: data.length,
page: 1,
page_size: 20,
page: params?.page || 1,
page_size: params?.pageSize || 20,
counts: { pending: 1, processed: 1 },
data,
};
});
};
const listApi = vi.fn(defaultListImpl);
const decideApi = vi.hoisted(() => vi.fn(async (..._args: unknown[]) => ({ status: 'done', reason: 'ok', duplicate: false })));
const notifyError = vi.hoisted(() => vi.fn());
vi.mock('../../utils/workflowApi', () => ({
listMainSystemActualQtyRequestsApi: (params?: { status?: string; scope?: string }) => listApi(params),
decideMainSystemActualQtyRequestApi: vi.fn(async () => ({ status: 'done', reason: 'ok', duplicate: false })),
listMainSystemActualQtyRequestsApi: (params?: ListParams) => listApi(params),
decideMainSystemActualQtyRequestApi: (...args: unknown[]) => decideApi(...args),
}));
vi.mock('../../utils/notify', () => ({
notify: { success: vi.fn(), error: (...args: unknown[]) => notifyError(...args), info: vi.fn(), warning: vi.fn() },
}));
// 用真实的 zh-CN 订单文案做 t(),并让 MenuLabel 直接渲染 fallback(免搭 Provider 栈)
@@ -147,6 +155,9 @@ import PriceQtyRequestsPage from './PriceQtyRequestsPage';
afterEach(() => {
cleanup();
listApi.mockClear();
listApi.mockImplementation(defaultListImpl);
decideApi.mockClear();
notifyError.mockClear();
});
const renderPage = () => render(<PriceQtyRequestsPage />);
@@ -209,6 +220,58 @@ describe('跨系统改价/改量待审页 · 版式(对齐主系统)', () =>
expect(await screen.findByText('我方销售价 5 → 4、金额 → 32')).toBeTruthy();
});
it('FE-2:目标行不在第 1 页(pending>100)⇒ 翻页找到后再审批,不再误判"已不存在"', async () => {
const page1Rows = Array.from({ length: 200 }, (_, index) => ({ ...PENDING_ROW, id: `other-${index}` }));
listApi.mockImplementation(async (params?: ListParams) => {
if (params?.pageSize === 200) {
if (params?.page === 1) {
return { total: 250, page: 1, page_size: 200, counts: { pending: 250, processed: 0 }, data: page1Rows };
}
return { total: 250, page: 2, page_size: 200, counts: { pending: 250, processed: 0 }, data: [PENDING_ROW] };
}
return defaultListImpl(params);
});
renderPage();
fireEvent.click(await screen.findByText('同步到本系统'));
await waitFor(() => expect(decideApi).toHaveBeenCalledWith('inbox-1', expect.objectContaining({ decision: 'approved' })));
const lookupCalls = listApi.mock.calls
.map(([params]) => params as ListParams)
.filter((params) => params?.pageSize === 200);
expect(lookupCalls.map((params) => params.page)).toEqual([1, 2]);
expect(notifyError).not.toHaveBeenCalled();
});
it('FE-2:翻完 total 仍未命中 ⇒ 提示"已不存在"且不调审批接口', async () => {
const page1Rows = Array.from({ length: 200 }, (_, index) => ({ ...PENDING_ROW, id: `other-${index}` }));
listApi.mockImplementation(async (params?: ListParams) => {
if (params?.pageSize === 200) {
if (params?.page === 1) {
return { total: 250, page: 1, page_size: 200, counts: { pending: 250, processed: 0 }, data: page1Rows };
}
return {
total: 250,
page: 2,
page_size: 200,
counts: { pending: 250, processed: 0 },
data: Array.from({ length: 50 }, (_, index) => ({ ...PENDING_ROW, id: `missing-${index}` })),
};
}
return defaultListImpl(params);
});
renderPage();
fireEvent.click(await screen.findByText('同步到本系统'));
await waitFor(() =>
expect(
notifyError.mock.calls.some((args) => String(args[0]).includes('该申请已被处理或撤回'))
).toBe(true)
);
expect(decideApi).not.toHaveBeenCalled();
const lookupCalls = listApi.mock.calls
.map(([params]) => params as ListParams)
.filter((params) => params?.pageSize === 200);
expect(lookupCalls.map((params) => params.page)).toEqual([1, 2]);
});
it('驳回要点弹窗(对齐主系统):填原因后才发决策', async () => {
renderPage();
fireEvent.click(await screen.findByText('驳回(不同步)'));
@@ -0,0 +1,226 @@
// @vitest-environment jsdom
import React from 'react';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
/**
* T5 独立边界复测 · FE-2 待审行翻页查找(2026-10-19,tester)。
*
* 修复:审批前按 id 精确定位待审行,从 `{limit:100}.find(id)` 改为 `page/pageSize=200` 翻页
* (最多 20 页 / 4000 条),避免 pending>100 时把真实存在的行误判成"已不存在"。
* 本文件与 dev 的 `PriceQtyRequestsPage.render.test.tsx` 独立,专测 5 个边界:
* total=0、目标在第 20 页、翻完不存在、page_size、请求数上限。
*/
const PENDING_ROW = {
id: 'inbox-t5',
request_id: 'ms-aqr-t5',
prep_id: 'prep-t5',
order_code: 'ORD_WEB_20261019_BR002_0001',
our_order_code: 'ORD_API_T5',
sku_code: 'SKU9',
node: 'picking_check',
field: 'qty',
before_value: 1,
proposed_value: 0.9,
before_unit: '袋',
unit: '袋',
operator: 'rider-001',
reason: '核货实测',
status: 'pending',
final_value: null,
reviewer: null,
decided_at: null,
decision_reason: null,
fact_registered: true,
request_version: 3,
created_at: '2026-10-19T09:30:00+08:00',
item_name: '思丰牌面粉',
payload: {},
} as const;
type ListParams = { status?: string; scope?: string; page?: number; pageSize?: number; limit?: number };
const listApi = vi.hoisted(() => vi.fn());
const decideApi = vi.hoisted(() => vi.fn());
const initialList = async (params?: ListParams): Promise<any> => {
const data = params?.status === 'pending' || !params?.status ? [PENDING_ROW] : [];
return {
total: data.length,
page: params?.page || 1,
page_size: params?.pageSize || 20,
counts: { pending: data.length, processed: 0 },
data,
};
};
vi.mock('../../utils/workflowApi', () => ({
listMainSystemActualQtyRequestsApi: (params?: ListParams) => listApi(params),
decideMainSystemActualQtyRequestApi: (...args: unknown[]) => decideApi(...args),
}));
vi.mock('../../utils/notify', () => {
const error = vi.fn();
return { notify: { success: vi.fn(), error, info: vi.fn(), warning: vi.fn() } };
});
vi.mock('../../i18n/I18nProvider', async () => {
const { orders: zh } = (await import('../../i18n/locales/zh-CN/orders')) as unknown as {
orders: Record<string, string>;
};
const { common } = (await import('../../i18n/locales/zh-CN/common')) as unknown as {
common: Record<string, string>;
};
const dict: Record<string, string> = {};
for (const [key, value] of Object.entries(zh)) dict[`orders.${key}`] = value;
for (const [key, value] of Object.entries(common)) dict[`common.${key}`] = value;
const t = (key: string, vars?: Record<string, unknown>) => {
const raw = dict[key] ?? key;
if (!vars) return raw;
return Object.entries(vars).reduce(
(acc, [name, value]) => acc.replace(new RegExp(`\\{${name}\\}`, 'g'), String(value)),
raw
);
};
return { useI18n: () => ({ locale: 'zh-CN', t }) };
});
vi.mock('../../components/MenuLabel', () => ({
MenuLabel: ({ fallback }: { fallback?: string }) => <span>{fallback}</span>,
}));
vi.mock('../../i18n', async () => {
const actual = await vi.importActual<typeof import('../../i18n')>('../../i18n');
const { orders: zh } = (await import('../../i18n/locales/zh-CN/orders')) as unknown as {
orders: Record<string, string>;
};
const { common } = (await import('../../i18n/locales/zh-CN/common')) as unknown as {
common: Record<string, string>;
};
const dict: Record<string, string> = {};
for (const [key, value] of Object.entries(zh)) dict[`orders.${key}`] = value;
for (const [key, value] of Object.entries(common)) dict[`common.${key}`] = value;
const t = (key: string, vars?: Record<string, unknown>) => {
const raw = dict[key] ?? key;
if (!vars) return raw;
return Object.entries(vars).reduce(
(acc, [name, value]) => acc.replace(new RegExp(`\\{${name}\\}`, 'g'), String(value)),
raw
);
};
return { ...actual, useTOrDefault: () => t };
});
import PriceQtyRequestsPage from './PriceQtyRequestsPage';
function notifyErrorSpy(): ReturnType<typeof vi.fn> {
return (globalThis as unknown as { __t5NotifyError?: ReturnType<typeof vi.fn> }).__t5NotifyError!;
}
function lookupCalls(): ListParams[] {
return listApi.mock.calls
.map(([params]) => (params || {}) as ListParams)
.filter((params) => params.pageSize === 200);
}
/** 第 page 页数据:前 19 页各 200 条(不含目标),第 20 页是否含目标由参数决定 */
function rowsPage(page: number, includeTarget: boolean): Array<Record<string, unknown>> {
const rows = Array.from({ length: 200 }, (_, index) => ({ ...PENDING_ROW, id: `other-${page}-${index}` }));
if (includeTarget) rows[0] = { ...PENDING_ROW };
return rows;
}
beforeEach(async () => {
listApi.mockReset();
decideApi.mockReset();
const notifyMod = await import('../../utils/notify');
const error = (notifyMod.notify.error as unknown as ReturnType<typeof vi.fn>);
error.mockReset();
(globalThis as unknown as { __t5NotifyError?: ReturnType<typeof vi.fn> }).__t5NotifyError = error;
listApi.mockImplementation(initialList);
decideApi.mockResolvedValue({ status: 'done', reason: 'ok', duplicate: false });
});
afterEach(() => {
cleanup();
});
async function clickApprove(): Promise<void> {
render(<PriceQtyRequestsPage />);
fireEvent.click(await screen.findByText('同步到本系统'));
}
describe('T5/FE-2:待审行翻页查找边界', () => {
it('total=0 ⇒ 只查 1 页、提示已不存在、不调审批', async () => {
listApi.mockImplementation(async (params?: ListParams) => {
if (params?.pageSize === 200) return { total: 0, page: 1, page_size: 200, counts: {}, data: [] };
return initialList(params);
});
await clickApprove();
await waitFor(() => expect(notifyErrorSpy()).toHaveBeenCalled());
expect(lookupCalls()).toHaveLength(1);
expect(lookupCalls()[0]).toMatchObject({ status: 'pending', page: 1, pageSize: 200 });
expect(decideApi).not.toHaveBeenCalled();
});
it('目标在第 20 页 ⇒ 恰好翻 20 页、命中后审批(不提前退出)', async () => {
listApi.mockImplementation(async (params?: ListParams) => {
if (params?.pageSize === 200) {
const page = Number(params.page) || 1;
return { total: 4000, page, page_size: 200, counts: {}, data: rowsPage(page, page === 20) };
}
return initialList(params);
});
await clickApprove();
await waitFor(() => expect(decideApi).toHaveBeenCalledTimes(1), { timeout: 4000 });
expect(lookupCalls().map((params) => params.page)).toEqual([
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
]);
expect(lookupCalls().every((params) => params.pageSize === 200)).toBe(true);
expect(notifyErrorSpy()).not.toHaveBeenCalled();
}, 15000);
it('翻完 total 仍未命中 ⇒ 最多 20 页、提示已不存在、不调审批', async () => {
listApi.mockImplementation(async (params?: ListParams) => {
if (params?.pageSize === 200) {
const page = Number(params.page) || 1;
return { total: 4000, page, page_size: 200, counts: {}, data: rowsPage(page, false) };
}
return initialList(params);
});
await clickApprove();
await waitFor(() => expect(notifyErrorSpy()).toHaveBeenCalled(), { timeout: 4000 });
const calls = lookupCalls();
expect(calls).toHaveLength(20); // 上限 20 页,不越界
expect(calls[calls.length - 1]).toMatchObject({ page: 20, pageSize: 200 });
expect(decideApi).not.toHaveBeenCalled();
}, 15000);
it('最后一页不足 page_size(total 小)⇒ 提前结束、只查 1 页', async () => {
listApi.mockImplementation(async (params?: ListParams) => {
if (params?.pageSize === 200) {
return { total: 50, page: 1, page_size: 200, counts: {}, data: rowsPage(1, false).slice(0, 50) };
}
return initialList(params);
});
await clickApprove();
await waitFor(() => expect(notifyErrorSpy()).toHaveBeenCalled());
expect(lookupCalls()).toHaveLength(1);
expect(decideApi).not.toHaveBeenCalled();
});
it('page_size 恒为 200(不受外部 limit 影响)、目标在第 2 页即停', async () => {
listApi.mockImplementation(async (params?: ListParams) => {
if (params?.pageSize === 200) {
const page = Number(params.page) || 1;
return { total: 400, page, page_size: 200, counts: {}, data: rowsPage(page, page === 2) };
}
return initialList(params);
});
await clickApprove();
await waitFor(() => expect(decideApi).toHaveBeenCalledTimes(1));
expect(lookupCalls().map((params) => params.page)).toEqual([1, 2]);
expect(lookupCalls().every((params) => params.pageSize === 200)).toBe(true);
}, 15000);
});
@@ -438,7 +438,6 @@ export const OrderManagement: React.FC = () => {
}, [urlDateFrom, urlDateTo, urlDateField]);
// mount-only: 组件挂载时加载一次基础配置数据(分类由 useCategoryRows 自动加载)
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(() => {
fetchCustomers();
fetchSuppliers();
@@ -507,7 +506,6 @@ export const OrderManagement: React.FC = () => {
void fetchOrders({ silent: true });
}, 15000);
return () => window.clearInterval(timer);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [currentPage, pageSize, sortField, sortOrder, statusFilter, statusGroup, dateRangePreset, dateFilter, dateField, customerFilter, searchQuery, operatingBranchCode, marginFilter, cycleCodeFilter, urlDateFrom, urlDateTo]);
useEffect(() => {
@@ -518,7 +516,6 @@ export const OrderManagement: React.FC = () => {
};
document.addEventListener('visibilitychange', onVisible);
return () => document.removeEventListener('visibilitychange', onVisible);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [currentPage, pageSize, sortField, sortOrder, statusFilter, statusGroup, dateRangePreset, dateFilter, dateField, customerFilter, searchQuery, operatingBranchCode, marginFilter, cycleCodeFilter, urlDateFrom, urlDateTo]);
const fetchSuppliers = async () => {
@@ -3253,7 +3250,6 @@ export const OrderManagement: React.FC = () => {
}
})
.catch(() => undefined);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const clearCustomDateRangeParams = () => {
+38 -6
View File
@@ -16,6 +16,10 @@ import { supabase } from '../../supabase/client';
import { notify } from '../../utils/notify';
import { guardCsvFormulaInjection } from '../../utils/excelImportExport';
import { confirmDialog } from '../../utils/confirmDialog';
import {
releaseOutboundPhotoPreviewUrls,
stageOutboundPhotoPreviewsIfMounted,
} from '../../utils/outboundPhotoPreview';
import { DecimalTextInput } from '../../components/ui/DecimalInput';
import { useTabChildSegment } from '../../hooks/useModuleTabRoute';
import {
@@ -422,6 +426,21 @@ function assigneeLabel(user: PickingAssignee, roleLabel: (code: string) => strin
const [saving, setSaving] = useState(false);
/** 分拣出库留证照片(可选,商品级):按拣货明细 id 存「对象路径 + 可显示 URL(服务端签名或本地预览)」 */
const [itemPhotos, setItemPhotos] = useState<Record<string, Array<{ path: string; previewUrl: string }>>>({});
/** 当前照片列表的 ref(供卸载/切单清理使用最新值;只释放 blob:,不碰签名 URL) */
const itemPhotosRef = useRef(itemPhotos);
/** B-9.1b:上传在途卸载的守卫(卸载后不得 setState,且要释放刚建的 blob) */
const mountedRef = useRef(true);
useEffect(() => {
itemPhotosRef.current = itemPhotos;
}, [itemPhotos]);
// 卸载时释放全部本地预览 blob(React state 只丢引用,不会 revokeObjectURL)
useEffect(() => () => releaseOutboundPhotoPreviewUrls(itemPhotosRef.current), []);
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
};
}, []);
const [photoUploadingItemId, setPhotoUploadingItemId] = useState<string | null>(null);
const itemPhotoInputRef = useRef<HTMLInputElement | null>(null);
// 当前拍照目标明细(同一个隐藏 file input 服务所有行)
@@ -432,7 +451,11 @@ function assigneeLabel(user: PickingAssignee, roleLabel: (code: string) => strin
const code = selectedTask?.pick_code || null;
const switched = seededPhotoPickRef.current !== code;
seededPhotoPickRef.current = code;
if (switched) itemPhotoTargetRef.current = null;
if (switched) {
// ③ 切单:上一单的本地预览 blob 全部释放(服务端签名 URL 由助手跳过)
releaseOutboundPhotoPreviewUrls(itemPhotosRef.current);
itemPhotoTargetRef.current = null;
}
setItemPhotos((prev) => {
if (!code) return {};
// 会话内新增的照片优先保留(不被回读覆盖);仅在缺失时按服务端已存照补齐(已完成单即可见)
@@ -1486,11 +1509,15 @@ function assigneeLabel(user: PickingAssignee, roleLabel: (code: string) => strin
if (!itemId || !files.length) return;
setPhotoUploadingItemId(itemId);
try {
const uploaded: Array<{ path: string; previewUrl: string }> = [];
for (const file of files) {
const path = await uploadPickingOutboundPhotoApi(file);
uploaded.push({ path, previewUrl: URL.createObjectURL(file) });
}
// FE-4:先全部上传成功再建预览 URL;任一文件失败 ⇒ 不会留下半截 blob URL。
// B-9.1b:返回后若组件已卸载 ⇒ helper 已释放刚建的 blob,这里直接 return(不 setState)。
const uploaded = await stageOutboundPhotoPreviewsIfMounted(
files,
(file) => uploadPickingOutboundPhotoApi(file),
(file) => URL.createObjectURL(file),
() => mountedRef.current
);
if (!uploaded) return;
setItemPhotos((prev) => ({ ...prev, [itemId]: [...(prev[itemId] || []), ...uploaded] }));
} catch (error) {
notify.error(error instanceof Error ? error.message : t('picking.outboundPhoto.fail'));
@@ -1500,6 +1527,9 @@ function assigneeLabel(user: PickingAssignee, roleLabel: (code: string) => strin
};
const removeItemPhoto = (itemId: string, path: string) => {
// ① 删图:先释放被删这一张的本地预览 blob(服务端签名 URL 不会被 revoke)
const removed = (itemPhotos[itemId] || []).filter((photo) => photo.path === path);
releaseOutboundPhotoPreviewUrls(removed);
setItemPhotos((prev) => ({
...prev,
[itemId]: (prev[itemId] || []).filter((photo) => photo.path !== path),
@@ -1545,6 +1575,8 @@ function assigneeLabel(user: PickingAssignee, roleLabel: (code: string) => strin
items: buildProgressItems(),
});
notify.success(t('picking.toast.completeOk'));
// ② 完成分拣:整单照片的本地预览 blob 全部释放,再清空 state
releaseOutboundPhotoPreviewUrls(itemPhotosRef.current);
setItemPhotos({});
const grouped = await fetchTasks();
await openTask({ ...selectedTask, pick_status: 30 }, grouped);
@@ -838,7 +838,6 @@ export const PurchaseManagement: React.FC<PurchaseManagementProps> = ({
.then((res) => setCategoryPurchaserBindings(res.data?.bindings || []))
.catch(() => setCategoryPurchaserBindings([]));
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [purchaserMode]);
useEffect(() => {
@@ -901,13 +900,11 @@ export const PurchaseManagement: React.FC<PurchaseManagementProps> = ({
}
}
fetchPurchases();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [listFilterKey, listPage, listPageSize]);
useEffect(() => {
if (purchaserMode || !isAssignView) return;
void fetchAssignCandidates();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [purchaserMode, isAssignView, dateField, dateRange?.start, dateRange?.end]);
useEffect(() => {
@@ -916,7 +913,6 @@ export const PurchaseManagement: React.FC<PurchaseManagementProps> = ({
fetchPurchases({ silent: true });
}, 15000);
return () => window.clearInterval(timer);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
purchaserMode,
dateField,
@@ -1069,7 +1065,6 @@ export const PurchaseManagement: React.FC<PurchaseManagementProps> = ({
useEffect(() => {
if (!purchaserMode && isAssignView) return;
void fetchPriceInvertRisks();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [purchaserMode, isAssignView, dateField, dateRange?.start, dateRange?.end]);
useEffect(() => {
@@ -85,8 +85,9 @@ describe('前端:规格列取值与位置', () => {
const iSpec = purchasePage.indexOf("{ id: 'spec', label: 'col.spec' }");
const iDesc = purchasePage.indexOf("{ id: 'product_desc', label: 'col.product_desc' }");
expect(iName).toBeGreaterThanOrEqual(0);
expect(iSpec).toBeGreaterThan(iName);
expect(iDesc).toBeGreaterThan(iSpec);
// 2026-10-15 列序调整:product_name → product_desc → spec(规格移到描述之后)
expect(iDesc).toBeGreaterThan(iName);
expect(iSpec).toBeGreaterThan(iDesc);
});
it('采购页:分组行与明细行都出 spec 单元格', () => {
@@ -44,7 +44,7 @@ describe('quality report upload channel', () => {
expect(service).toContain('async function resolveMatchUploadEntry');
expect(service).toContain("getObject('quality-reports', safe)");
expect(service).toContain('parseUploadPayload(entry)');
// 已有存储路径时不再重复保存
expect(service).toContain('parsed.storedPath || (await saveBase64Upload(');
// 已有存储路径时不再重复保存(T9 格式化后换行缩进不同,用\s* 容忍空白、语义不变)
expect(service).toMatch(/parsed\.storedPath\s*\|\|\s*\(await saveBase64Upload\(/);
});
});
@@ -543,7 +543,6 @@ export const DeliveryHtmlTemplateManagement: React.FC<DeliveryHtmlTemplateManage
editorLayout.additions.map((item) => `${item.id}:${item.text}:${item.xPercent ?? ''}:${item.yPercent ?? ''}:${item.x ?? ''}:${item.y ?? ''}`).join('|')].join('\u0000');
const editorSrcDoc = useMemo(
// editorLayoutRef 只用来在建文档那一刻取最新布局,故意不进依赖
// eslint-disable-next-line react-hooks/exhaustive-deps
() => (active ? buildDeliveryHtmlTemplatePreview({ ...active, layout: editorLayoutRef.current }) : ''),
[editorDocKey]
);
@@ -1,3 +1,4 @@
import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
import {
formatInventoryBatchCostAdjustDetail,
@@ -148,21 +149,21 @@ describe('操作日志 · 库存批次修改的前后值', () => {
describe('操作日志 · 接线与文案', () => {
it('两个 op 都接进详情分发,并且三语都有 op 标签', () => {
const page = require('node:fs').readFileSync(
const page = readFileSync(
new URL('./OperationLogs.tsx', import.meta.url),
'utf8'
) as string;
expect(page).toContain("if (op === 'inventory_batch_edit') {");
expect(page).toContain("if (op === 'inventory_batch_cost_adjust') {");
const zh = require('node:fs').readFileSync(
const zh = readFileSync(
new URL('../../i18n/locales/zh-CN/system.ts', import.meta.url),
'utf8'
) as string;
const en = require('node:fs').readFileSync(
const en = readFileSync(
new URL('../../i18n/locales/en/system.ts', import.meta.url),
'utf8'
) as string;
const id = require('node:fs').readFileSync(
const id = readFileSync(
new URL('../../i18n/locales/id/system.ts', import.meta.url),
'utf8'
) as string;
-1
View File
@@ -305,7 +305,6 @@ export const RoleManagement: React.FC = () => {
};
// mount-only: 组件挂载时加载一次角色权限数据
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(() => {
fetchData();
}, []);
@@ -95,18 +95,17 @@ describe('页面本地闸门(关闭=今天行为 / 开启=允许 0)', () =>
expect(server).toContain("else if (!Number.isFinite(finalPrice) || finalPrice <= 0) throw bizError('采购价必须大于 0');");
});
it('库存入库:开关开启时未填=0 放行;未开启时空白/0/负数仍拦', () => {
it('库存入库:面板不再读开关,空白成本价交服务端(null→0,由开关决定 0 是否合法)', () => {
const page = read('pages/inventory/StockInboundPanel.tsx');
expect(page).toContain('useAllowZeroCost');
// 2026-09-24 契约变更(开发者口径「用户没填直接点完成也算 0」):
// 开关开启时**空白不再拦**(`Number('')===0`,与完成自采/独立自采入库一致,按 0 提交);
// 开关关闭时保持原行为:空白 / 0 / 负数都拦。
expect(page).toContain('allowZeroCost\n ? !Number.isFinite(c) || c < 0');
expect(page).toContain(': !String(unitCost).trim() || !Number.isFinite(c) || c <= 0');
// 2026-10-15:面板去掉客户端 allowZeroCost 分支,空白直接提交 null;
// 服务端 `Number(null)=0`,0 是否合法由「允许成本价为 0」开关在服务端判定(单一裁决点)。
expect(page).not.toContain('useAllowZeroCost');
expect(page).toContain("unit_cost: line.unit_cost === '' ? null : Number(line.unit_cost),");
});
it('未新增业务页面文案(沿用既有提示 key)', () => {
expect(read('pages/inventory/StockInboundPanel.tsx')).toContain("t('inventory.stockIn.costGt0')");
// 客户端成本校验已移除(服务端裁决),面板文案仍全部来自既有 inventory.stockIn.* key
expect(read('pages/inventory/StockInboundPanel.tsx')).toContain("t('inventory.stockIn.");
expect(read('pages/purchase/PurchaseManagement.tsx')).toContain("t('purchase.notify.costMustGt0')");
expect(read('pages/purchase/supplierPreparation/SupplierPreparationPage.tsx')).toContain(
"t('preparations.toast.priceMustPositive')"
+1 -1
View File
@@ -590,7 +590,7 @@ describe('syncTemplateLayoutInDocument(编辑器就地更新布局,不重建
* 事故:用户在编辑器里挪了「每页合计 / 整单合计」,打印时位置错乱。
*/
describe('flow 定位语义(跟随内容)', () => {
const flowTemplate = (anchoring: 'flow' | 'page' | undefined, rows: number): DeliveryHtmlTemplate => ({
const flowTemplate = (anchoring: 'flow' | 'page' | undefined, _rows: number): DeliveryHtmlTemplate => ({
id: 'flow', name: 'flow',
html: '<table><tbody>{{#items}}<tr><td>{{item.item_name}}</td></tr>{{/items}}'
+ '<tr><td class="page-total" colspan="2">每页合计:{{group.total_amount}}</td></tr></tbody></table>',
@@ -0,0 +1,104 @@
// @vitest-environment jsdom
import React, { useEffect, useRef, useState } from 'react';
import { cleanup, render } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
/**
* B-9.1b(2026-10-19 T5 终局复攻):上传在途卸载。
*
* 旧行为:`await stage(...)` 返回时组件已卸载,仍会 `URL.createObjectURL`(1 个),
* setState 无效、blob 无人引用 ⇒ 永不 revoke(created=1 / revoked=0)。
* 修复:传入 `isMounted`,返回后若已卸载 ⇒ 释放刚建的 blob 并返回 null(created=1 / revoked=1)。
*/
import { stageOutboundPhotoPreviewsIfMounted } from './outboundPhotoPreview';
function Harness(props: {
upload: (file: File) => Promise<string>;
onStaged?: (count: number) => void;
}) {
const mountedRef = useRef(true);
const [count, setCount] = useState<number | null>(null);
// 回调走 ref:组件模拟"仅挂载时执行一次"的 effect,避免 exhaustive-deps 误报(行为不变)
const uploadRef = useRef(props.upload);
uploadRef.current = props.upload;
const onStagedRef = useRef(props.onStaged);
onStagedRef.current = props.onStaged;
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
};
}, []);
useEffect(() => {
void (async () => {
const staged = await stageOutboundPhotoPreviewsIfMounted(
[new File(['a'], 'a.jpg', { type: 'image/jpeg' })],
uploadRef.current,
(file) => URL.createObjectURL(file),
() => mountedRef.current
);
if (!staged) return; // 已卸载:helper 已释放,不得 setState
setCount(staged.length);
onStagedRef.current?.(staged.length);
})();
}, []);
return <div data-testid="count">{count ?? 'none'}</div>;
}
beforeEach(() => {
(URL as unknown as { createObjectURL: unknown }).createObjectURL = vi.fn(() => 'blob:mock-1');
(URL as unknown as { revokeObjectURL: unknown }).revokeObjectURL = vi.fn();
});
afterEach(() => {
cleanup();
vi.restoreAllMocks();
});
describe('B-9.1b:上传在途卸载 ⇒ 释放刚创建的 blob', () => {
it('真实渲染:卸载后才 resolve 上传 ⇒ createObjectURL 1 次、revokeObjectURL 1 次、不 setState', async () => {
let resolveUpload: (value: string) => void = () => undefined;
const upload = vi.fn(
() =>
new Promise<string>((resolve) => {
resolveUpload = resolve;
})
);
const onStaged = vi.fn();
const view = render(<Harness upload={upload} onStaged={onStaged} />);
await vi.waitFor(() => expect(upload).toHaveBeenCalledTimes(1));
view.unmount(); // 上传在途卸载
resolveUpload('server/a.jpg');
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
expect(URL.createObjectURL, '在途卸载后仍会创建一个 blob(这正是要释放的)').toHaveBeenCalledTimes(1);
expect(URL.revokeObjectURL, '必须把刚创建的 blob 释放掉').toHaveBeenCalledTimes(1);
expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:mock-1');
expect(onStaged, '卸载后不得 setState/回调').not.toHaveBeenCalled();
});
it('未卸载 ⇒ 正常 setState,不误释放', async () => {
const upload = vi.fn(async () => 'server/a.jpg');
const onStaged = vi.fn();
const view = render(<Harness upload={upload} onStaged={onStaged} />);
await vi.waitFor(() => expect(onStaged).toHaveBeenCalledWith(1));
expect(view.getByTestId('count').textContent).toBe('1');
expect(URL.createObjectURL).toHaveBeenCalledTimes(1);
expect(URL.revokeObjectURL).not.toHaveBeenCalled();
});
});
describe('B-9.1b:页面接线契约', () => {
it('PickingManagement 使用 mounted 守卫版本且传 mountedRef', async () => {
const { readFileSync } = await import('node:fs');
const path = await import('node:path');
const source = readFileSync(path.join(__dirname, '../pages/picking/PickingManagement.tsx'), 'utf8');
expect(source).toContain('stageOutboundPhotoPreviewsIfMounted');
expect(source).toContain('() => mountedRef.current');
});
});
@@ -0,0 +1,63 @@
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
/**
* FE-4(2026-10-19 T5 红队复攻):多文件上传**部分失败不得泄漏 blob URL**。
*
* 旧逻辑:每张成功就 createObjectURL,后续文件抛错 ⇒ uploaded 数组丢弃、前面建的 blob 不 revoke。
* 修复:先全部上传成功再建预览 URL;任一上传失败时一个 blob URL 都还没创建。
*/
import { stageOutboundPhotoPreviews } from './outboundPhotoPreview';
const files = [new File(['a'], 'a.jpg', { type: 'image/jpeg' }), new File(['b'], 'b.jpg', { type: 'image/jpeg' })];
beforeEach(() => {
let seq = 0;
vi.stubGlobal('URL', {
...URL,
createObjectURL: vi.fn(() => `blob:preview-${++seq}`),
revokeObjectURL: vi.fn(),
});
});
afterEach(() => {
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
describe('stageOutboundPhotoPreviews:部分失败无 blob 泄漏', () => {
it('第 2 个文件上传失败 ⇒ 不创建任何预览 URL(无可泄漏),错误原样抛出', async () => {
const upload = vi
.fn()
.mockResolvedValueOnce('server/a.jpg')
.mockRejectedValueOnce(new Error('upload failed'));
await expect(
stageOutboundPhotoPreviews(files, upload, (file) => URL.createObjectURL(file))
).rejects.toThrow('upload failed');
expect(upload).toHaveBeenCalledTimes(2);
expect(URL.createObjectURL, '失败时不得留下半截 blob').toHaveBeenCalledTimes(0);
expect(URL.revokeObjectURL).not.toHaveBeenCalled();
});
it('全部上传成功 ⇒ 才建预览 URL,且条数/顺序一致', async () => {
const upload = vi.fn(async (file: File) => `server/${file.name}`);
const staged = await stageOutboundPhotoPreviews(files, upload, (file) => URL.createObjectURL(file));
expect(staged.map((item) => item.path)).toEqual(['server/a.jpg', 'server/b.jpg']);
expect(staged.map((item) => item.previewUrl)).toEqual(['blob:preview-1', 'blob:preview-2']);
expect(URL.createObjectURL).toHaveBeenCalledTimes(2);
});
it('建预览 URL 中途抛错 ⇒ 释放已创建的 blob,再抛错', async () => {
const upload = vi.fn(async (file: File) => `server/${file.name}`);
let calls = 0;
(URL.createObjectURL as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => {
calls += 1;
if (calls === 2) throw new Error('oom');
return `blob:preview-${calls}`;
});
await expect(stageOutboundPhotoPreviews(files, upload, (file) => URL.createObjectURL(file))).rejects.toThrow('oom');
expect(URL.revokeObjectURL).toHaveBeenCalledTimes(1);
expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:preview-1');
});
});
+51
View File
@@ -31,3 +31,54 @@ export function releaseOutboundPhotoPreviewUrls(
}
}
}
/**
* FE-4(2026-10-19 T5 红队复攻):多文件上传的预览 URL 必须在**全部上传成功之后**才创建。
*
* 旧实现每传成功一个就 `createObjectURL`,随后一个文件抛错时 `uploaded` 数组被丢弃 ⇒
* 前面已创建的 blob URL 永远没人 revoke(多文件部分失败泄漏)。这里先传完再建 URL;
* 即使创建 URL 的中间环节抛错,也会释放已创建的 blob。
*/
export async function stageOutboundPhotoPreviews<T>(
files: File[],
upload: (file: File) => Promise<T>,
makePreviewUrl: (file: File) => string
): Promise<Array<{ path: T; previewUrl: string }>> {
const paths: T[] = [];
for (const file of files) {
paths.push(await upload(file)); // 任一失败即抛出:此时尚未创建任何 blob URL
}
const created: Array<{ path: T; previewUrl: string }> = [];
try {
for (let index = 0; index < paths.length; index += 1) {
created.push({ path: paths[index], previewUrl: makePreviewUrl(files[index]) });
}
return created;
} catch (error) {
releaseOutboundPhotoPreviewUrls(
created.map((item) => ({ path: String(item.path), previewUrl: item.previewUrl }))
);
throw error;
}
}
/**
* B-9.1b(2026-10-19 T5 终局复攻):上传在途时组件可能已卸载。
* 先按正常流程上传/建预览,返回后若已卸载 ⇒ 立刻释放刚创建的 blob 并返回 null,
* 调用方不得再 setState(否则 URL 无人引用、永不 revoke)。
*/
export async function stageOutboundPhotoPreviewsIfMounted<T>(
files: File[],
upload: (file: File) => Promise<T>,
makePreviewUrl: (file: File) => string,
isMounted: () => boolean
): Promise<Array<{ path: T; previewUrl: string }> | null> {
const staged = await stageOutboundPhotoPreviews(files, upload, makePreviewUrl);
if (!isMounted()) {
releaseOutboundPhotoPreviewUrls(
staged.map((item) => ({ path: String(item.path), previewUrl: item.previewUrl }))
);
return null;
}
return staged;
}
+3 -2
View File
@@ -5,8 +5,9 @@ import { describe, expect, it } from 'vitest';
* 未完成单只展示**待分拣**行(已确认的即时移出视野);已完成单仍为「待补录,全确认回退全部」。
* 设计见 docs/design/20261016-小程序分拣已确认行即时隐藏.md。
*/
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { visibleItemsForStatus } = require('../../miniprogram/utils/pickingAssembly');
import { createRequire } from 'node:module';
const requireForMiniprogram = createRequire(import.meta.url);
const { visibleItemsForStatus } = requireForMiniprogram('../../miniprogram/utils/pickingAssembly');
/** 已确认:有实拣量 + review_status ≥ 20(与 isItemPicked 同口径) */
const picked = (n = 1) => ({ picked_qty: n, review_status: 20, settlement_qty: n });
+1 -1
View File
@@ -383,7 +383,7 @@ export function buildPickingLabelRulerHtml(options?: {
const ruler = `<section class="pick-label">
<div class="rl-frame"></div>
${ticks.join('')}
<div class="rl-mid">${paper.widthMm} × ${paper.heightMm} mm 旋转 ${rotation}°</div>
<div class="rl-mid">${paper.widthMm} × ${paper.heightMm} mm\u3000旋转 ${rotation}°</div>
<div class="rl-mid2">↑ 顶边 / ← 左边(刻度单位 mm)</div>
</section>`;
const count = Math.min(Math.max(Number(options?.pages) || 2, 1), 5);
+3 -2
View File
@@ -7,8 +7,9 @@ import { describe, expect, it } from 'vitest';
* 这些用例守的是**回写边界**:识别值不能冒充人工值,换商品不能串档案。
*/
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { buildArchivePayload, hasUnsavedArchiveEdits } = require('../../miniprogram/utils/stockInboundArchive');
import { createRequire } from 'node:module';
const requireForMiniprogram = createRequire(import.meta.url);
const { buildArchivePayload, hasUnsavedArchiveEdits } = requireForMiniprogram('../../miniprogram/utils/stockInboundArchive');
describe('buildArchivePayload', () => {
it('无人工编辑 ⇒ null(不传 archive,服务端就不写档案)', () => {
+161
View File
@@ -0,0 +1,161 @@
// @vitest-environment jsdom
import { readFileSync } from 'node:fs';
import path from 'node:path';
import { renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
/**
* T5 独立边界复测 · FE-1(401 统一登出 / SSE 重连) + FE-4(blob 预览释放) —— 2026-10-19,tester。
* 与 dev 的 `workflowApi.unauthorized.test.ts` / `useNotificationStream.unauthorized.test.ts` 独立。
*/
const SESSION_KEY = 'canteen.auth.session';
function setSession(): void {
localStorage.setItem(SESSION_KEY, JSON.stringify({ access_token: 't-1', user: { id: 'u1' } }));
}
function installLocationStub(): { href: string } {
const loc = { href: '' };
try {
Object.defineProperty(window, 'location', { configurable: true, value: loc });
} catch {
(window as unknown as { location: { href: string } }).location = loc;
}
return loc;
}
function mockFetchStatus(status: number): void {
vi.stubGlobal(
'fetch',
vi.fn(async () => ({ ok: false, status, body: null, json: async () => ({ error: 'token_expired' }) }))
);
}
beforeEach(() => {
localStorage.clear();
vi.unstubAllGlobals();
vi.useRealTimers();
});
afterEach(() => {
vi.unstubAllGlobals();
vi.useRealTimers();
localStorage.clear();
});
describe('T5/FE-1:workflowApi 401 统一登出', () => {
it('有 session:第一次 401 清 session + 跳转;随后再 401(已无 session)不再重复跳', async () => {
setSession();
const loc = installLocationStub();
mockFetchStatus(401);
vi.resetModules();
const { submitInspectionComplianceApi } = await import('./workflowApi');
const first = await submitInspectionComplianceApi({}).catch((err) => err);
expect(first).toMatchObject({ status: 401, code: 'token_expired' });
expect(localStorage.getItem(SESSION_KEY)).toBeNull();
expect(loc.href).toContain('/login');
expect(loc.href).toContain('reason=expired');
const hrefAfterFirst = loc.href;
const second = await submitInspectionComplianceApi({}).catch((err) => err);
expect(second).toMatchObject({ status: 401 });
expect(loc.href, '无 session 后不得再跳(避免登录页自跳循环)').toBe(hrefAfterFirst);
});
it('无 session(登录页输错密码):只抛 401,不跳转、不清数据', async () => {
const loc = installLocationStub();
mockFetchStatus(401);
vi.resetModules();
const { submitInspectionComplianceApi } = await import('./workflowApi');
const error = await submitInspectionComplianceApi({}).catch((err) => err);
expect(error).toMatchObject({ status: 401 });
expect(loc.href).toBe('');
expect(localStorage.getItem(SESSION_KEY)).toBeNull();
});
});
describe('T5/FE-1:SSE 401 停止重连 / 500 保持退避', () => {
it('SSE 401 ⇒ 只请求 1 次,60s 内不再重连,并登出', async () => {
setSession();
const loc = installLocationStub();
mockFetchStatus(401);
vi.resetModules();
const { useNotificationStream } = await import('../hooks/useNotificationStream');
const { unmount } = renderHook(() => useNotificationStream({ enabled: true, onSnapshot: () => undefined }));
await vi.waitFor(() => expect(globalThis.fetch).toHaveBeenCalledTimes(1));
await vi.waitFor(() => expect(loc.href).toContain('/login'));
expect(localStorage.getItem(SESSION_KEY)).toBeNull();
await new Promise((resolve) => setTimeout(resolve, 50));
expect(globalThis.fetch, '401 后不得再重连').toHaveBeenCalledTimes(1);
unmount();
});
it('SSE 500 ⇒ 保持 2s 退避重连(第二次请求发生,且不登出)', async () => {
setSession();
installLocationStub();
mockFetchStatus(500);
vi.resetModules();
const { useNotificationStream } = await import('../hooks/useNotificationStream');
const { unmount } = renderHook(() => useNotificationStream({ enabled: true, onSnapshot: () => undefined }));
await vi.waitFor(() => expect(globalThis.fetch).toHaveBeenCalledTimes(1));
await vi.waitFor(() => expect(globalThis.fetch).toHaveBeenCalledTimes(2), { timeout: 5000 });
expect(localStorage.getItem(SESSION_KEY)).toBeTruthy();
unmount();
}, 15000);
});
describe('T5/FE-4:blob 预览 URL 成对释放', () => {
it('同一 blob URL 在「删图 → 卸载」生命周期里只 revoke 一次(状态已清空不重复)', async () => {
const revoked: string[] = [];
Object.defineProperty(URL, 'revokeObjectURL', {
configurable: true,
writable: true,
value: (url: string) => revoked.push(String(url)),
});
vi.resetModules();
const { releaseOutboundPhotoPreviewUrls } = await import('./outboundPhotoPreview');
const state: Record<string, Array<{ path: string; previewUrl: string }>> = {
item1: [{ path: 'p1', previewUrl: 'blob:http://localhost/same' }],
};
// ① 删图:释放被删那张,然后从 state 移除
releaseOutboundPhotoPreviewUrls(state.item1);
delete state.item1;
// ② 卸载:用 ref.current(已清空)再释放
releaseOutboundPhotoPreviewUrls(state);
expect(revoked).toEqual(['blob:http://localhost/same']);
});
it('切单只释放上一单的 blob;新单的 blob 在卸载时释放——各一次、均不碰签名 URL', async () => {
const revoked: string[] = [];
Object.defineProperty(URL, 'revokeObjectURL', {
configurable: true,
writable: true,
value: (url: string) => revoked.push(String(url)),
});
vi.resetModules();
const { releaseOutboundPhotoPreviewUrls } = await import('./outboundPhotoPreview');
const oldPhotos = { a: [{ path: 'p1', previewUrl: 'blob:old' }, { path: 'p2', previewUrl: 'https://cdn/x.jpg?sig=1' }] };
releaseOutboundPhotoPreviewUrls(oldPhotos); // 切单
const newPhotos = { a: [{ path: 'p9', previewUrl: 'blob:new' }] };
releaseOutboundPhotoPreviewUrls(newPhotos); // 卸载
expect(revoked).toEqual(['blob:old', 'blob:new']);
});
it('FE-3 前端接线:映射面板显式 limit=500 且搜索不带 refresh(源码契约)', () => {
const src = readFileSync(path.join(__dirname, '../pages/customers/QuoteSkuMappingsPanel.tsx'), 'utf8');
expect(src).toContain('limit: 500');
// 只有首次挂载带 refresh,后续搜索分支不带
const mountIdx = src.indexOf('void load({ refresh: true })');
const searchIdx = src.indexOf('void load();');
expect(mountIdx).toBeGreaterThan(-1);
expect(searchIdx).toBeGreaterThan(mountIdx);
});
});
+154
View File
@@ -0,0 +1,154 @@
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
/**
* T5 rev7 合并最终复测 · tester 独立边界(2026-10-19)。
* c1) 401 响应体为 JSON null ⇒ 仍清 session + 跳转、error.status=401(读 payload 不得崩溃)。
* c2) 多文件上传 a 成功 b 失败 ⇒ 不得泄漏 a 的 blob(或干脆尚未创建 blob)。
*/
const SESSION_KEY = 'canteen.auth.session';
function setSession(): void {
localStorage.setItem(SESSION_KEY, JSON.stringify({ access_token: 't-1', user: { id: 'u1' } }));
}
function installLocationStub(): { href: string } {
const loc = { href: '' };
try {
Object.defineProperty(window, 'location', { configurable: true, value: loc });
} catch {
(window as unknown as { location: { href: string } }).location = loc;
}
return loc;
}
beforeEach(() => {
localStorage.clear();
vi.unstubAllGlobals();
});
afterEach(() => {
vi.unstubAllGlobals();
localStorage.clear();
});
describe('T5/FE-1:401 body=null 不得崩溃,仍统一登出', () => {
it('有 session + body null ⇒ 清 session、跳 /login、error.status=401/code=unauthorized', async () => {
setSession();
const loc = installLocationStub();
vi.stubGlobal(
'fetch',
vi.fn(async () => ({ ok: false, status: 401, json: async () => null }))
);
vi.resetModules();
const { submitInspectionComplianceApi } = await import('./workflowApi');
const error = await submitInspectionComplianceApi({}).catch((err) => err);
expect(error).toMatchObject({ status: 401, code: 'unauthorized' });
expect(localStorage.getItem(SESSION_KEY)).toBeNull();
expect(loc.href).toContain('/login');
expect(loc.href).toContain('reason=expired');
});
it('无 session + body null ⇒ 不跳转(登录页场景)', async () => {
const loc = installLocationStub();
vi.stubGlobal(
'fetch',
vi.fn(async () => ({ ok: false, status: 401, json: async () => null }))
);
vi.resetModules();
const { submitInspectionComplianceApi } = await import('./workflowApi');
const error = await submitInspectionComplianceApi({}).catch((err) => err);
expect(error).toMatchObject({ status: 401 });
expect(loc.href).toBe('');
});
});
describe('T5/FE-4:多文件上传部分失败不得泄漏 blob', () => {
let created: string[];
let revoked: string[];
beforeEach(() => {
created = [];
revoked = [];
let seq = 0;
Object.defineProperty(URL, 'createObjectURL', {
configurable: true,
writable: true,
value: () => {
seq += 1;
const url = `blob:test/${seq}`;
created.push(url);
return url;
},
});
Object.defineProperty(URL, 'revokeObjectURL', {
configurable: true,
writable: true,
value: (url: string) => revoked.push(String(url)),
});
});
it('上传 a 成功、b 失败 ⇒ 整体拒绝且**未创建任何 blob**(无泄漏)', async () => {
vi.resetModules();
const { stageOutboundPhotoPreviews } = await import('./outboundPhotoPreview');
const files = [new File(['a'], 'a.jpg'), new File(['b'], 'b.jpg')];
let uploads = 0;
const error = await stageOutboundPhotoPreviews(
files,
async (file) => {
uploads += 1;
if (file.name === 'b.jpg') throw new Error('upload b failed');
return 'path-a';
},
(file) => URL.createObjectURL(file)
).catch((err) => err);
expect(String(error?.message)).toContain('upload b failed');
expect(uploads).toBe(2);
expect(created, '失败时不得留下半截 blob').toEqual([]);
expect(revoked).toEqual([]);
});
it('上传都成功但创建第 2 个预览 URL 抛错 ⇒ 已创建的 a blob 被 revoke,无泄漏', async () => {
vi.resetModules();
const { stageOutboundPhotoPreviews } = await import('./outboundPhotoPreview');
const files = [new File(['a'], 'a.jpg'), new File(['b'], 'b.jpg')];
let createdCalls = 0;
Object.defineProperty(URL, 'createObjectURL', {
configurable: true,
writable: true,
value: () => {
createdCalls += 1;
if (createdCalls === 2) throw new Error('create 2 failed');
const url = 'blob:test/a';
created.push(url);
return url;
},
});
const error = await stageOutboundPhotoPreviews(
files,
async (file) => `path-${file.name}`,
(file) => URL.createObjectURL(file)
).catch((err) => err);
expect(String(error?.message)).toContain('create 2 failed');
expect(revoked, 'a 的 blob 必须被释放').toEqual(['blob:test/a']);
});
it('全部成功 ⇒ 返回两条预览、不 revoke', async () => {
vi.resetModules();
const { stageOutboundPhotoPreviews } = await import('./outboundPhotoPreview');
const files = [new File(['a'], 'a.jpg'), new File(['b'], 'b.jpg')];
const staged = await stageOutboundPhotoPreviews(
files,
async (file) => `path-${file.name}`,
(file) => URL.createObjectURL(file)
);
expect(staged.map((row) => row.path)).toEqual(['path-a.jpg', 'path-b.jpg']);
expect(staged.every((row) => row.previewUrl.startsWith('blob:'))).toBe(true);
expect(revoked).toEqual([]);
});
});
+122
View File
@@ -0,0 +1,122 @@
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
/**
* T5 rev13 实体最终复测 · raw fetch 401(tester 独立边界,2026-10-19)。
*
* `uploadPickingOutboundPhotoApi` / `checkCustomerBudgetApi` 走**裸 fetch**(非 workflowFetch),
* 之前 401 只按普通失败处理:body=null 时 `payload.error` 可能崩溃,budget 还会返回
* `{allowed:false}`(页面误当成"客户不能下单"而不是登录失效)。rev13 统一走
* `throwIfUnauthorizedRaw`:清 session + 跳 `/login?reason=expired`、错误带 `status:401/code`。
*/
const SESSION_KEY = 'canteen.auth.session';
function setSession(): void {
localStorage.setItem(SESSION_KEY, JSON.stringify({ access_token: 't-1', user: { id: 'u1' } }));
}
function installLocationStub(): { href: string } {
const loc = { href: '' };
try {
Object.defineProperty(window, 'location', { configurable: true, value: loc });
} catch {
(window as unknown as { location: { href: string } }).location = loc;
}
return loc;
}
function mock401(body: 'null' | 'non-json' | 'envelope'): void {
const json =
body === 'null'
? async () => null
: body === 'non-json'
? async () => {
throw new SyntaxError('Unexpected token < in JSON');
}
: async () => ({ error: 'token_expired', error_description: '登录已过期' });
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 401, json })));
}
function mockStatus(status: number, jsonBody: unknown): void {
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status, json: async () => jsonBody })));
}
beforeEach(() => {
localStorage.clear();
vi.unstubAllGlobals();
vi.resetModules();
});
afterEach(() => {
vi.unstubAllGlobals();
localStorage.clear();
});
describe('T5/FE-1:uploadPickingOutboundPhotoApi 401(body null / 非 JSON)', () => {
it('body=null ⇒ 清 session、跳转、错误 status=401/code=unauthorized', async () => {
setSession();
const loc = installLocationStub();
mock401('null');
const { uploadPickingOutboundPhotoApi } = await import('./workflowApi');
const error = await uploadPickingOutboundPhotoApi(new File(['x'], 'a.jpg')).catch((err) => err);
expect(error).toMatchObject({ status: 401, code: 'unauthorized' });
expect(localStorage.getItem(SESSION_KEY)).toBeNull();
expect(loc.href).toContain('/login');
expect(loc.href).toContain('reason=expired');
});
it('非 JSON body ⇒ 同样按 401 登出,不因 JSON 解析失败崩溃', async () => {
setSession();
const loc = installLocationStub();
mock401('non-json');
const { uploadPickingOutboundPhotoApi } = await import('./workflowApi');
const error = await uploadPickingOutboundPhotoApi(new File(['x'], 'a.jpg')).catch((err) => err);
expect(error).toMatchObject({ status: 401, code: 'unauthorized' });
expect(localStorage.getItem(SESSION_KEY)).toBeNull();
expect(loc.href).toContain('reason=expired');
});
it('无 session ⇒ 401 不跳转(登录页场景),错误仍带 status=401', async () => {
const loc = installLocationStub();
mock401('null');
const { uploadPickingOutboundPhotoApi } = await import('./workflowApi');
const error = await uploadPickingOutboundPhotoApi(new File(['x'], 'a.jpg')).catch((err) => err);
expect(error).toMatchObject({ status: 401 });
expect(loc.href).toBe('');
});
});
describe('T5/FE-1:checkCustomerBudgetApi 401 不再返回 allowed:false', () => {
it('body=null ⇒ reject(不是 {allowed:false}),清 session + 跳转', async () => {
setSession();
const loc = installLocationStub();
mock401('null');
const { checkCustomerBudgetApi } = await import('./workflowApi');
const error = await checkCustomerBudgetApi('C001', 100).catch((err) => err);
expect(error).toMatchObject({ status: 401, code: 'unauthorized' });
expect((error as { allowed?: boolean }).allowed).toBeUndefined();
expect(localStorage.getItem(SESSION_KEY)).toBeNull();
expect(loc.href).toContain('/login');
});
it('envelope 带 error code ⇒ code 透传;非 401 仍返回 allowed:false(行为不回归)', async () => {
setSession();
installLocationStub();
mock401('envelope');
const { checkCustomerBudgetApi } = await import('./workflowApi');
const error = await checkCustomerBudgetApi('C001').catch((err) => err);
expect(error).toMatchObject({ status: 401, code: 'token_expired' });
vi.resetModules();
localStorage.setItem(SESSION_KEY, JSON.stringify({ access_token: 't-2', user: { id: 'u1' } }));
mockStatus(400, { error: 'budget_block', error_description: '超出预算' });
const mod = await import('./workflowApi');
const result = await mod.checkCustomerBudgetApi('C001', 50);
expect(result).toMatchObject({ allowed: false });
});
});
+122
View File
@@ -0,0 +1,122 @@
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
/**
* FE-1(2026-10-19):`workflowApi` 的 401 必须与 `localApiClient` 共用同一登出处理。
*
* 缺陷:workflow 请求层 401 只 throw 普通 Error,不清 session、不跳登录页、错误也没有
* status/code ⇒ 页面停在旧数据上,用户不知道要重新登录(与 localApiClient 行为不一致)。
* 修复:401 ⇒ `handleUnauthorized()`(清 session + 跳 `/login?reason=expired`;**无 session 不跳**),
* 抛出的错误带 `status:401` 与后端 `error` 字段 code。
*/
const SESSION_KEY = 'canteen.auth.session';
async function loadWorkflowApi() {
vi.resetModules();
return import('../utils/workflowApi');
}
function installLocationStub(): { href: string } {
const loc = { href: '' };
try {
Object.defineProperty(window, 'location', { configurable: true, value: loc });
} catch {
// 极端 jsdom 版本不可重定义时,退化为直接赋值观察
(window as unknown as { location: { href: string } }).location = loc;
}
return loc;
}
function mockUnauthorized(): void {
vi.stubGlobal(
'fetch',
vi.fn(async () => ({
ok: false,
status: 401,
json: async () => ({ error: 'token_expired', error_description: '登录已过期,请重新登录' }),
}))
);
}
beforeEach(() => {
localStorage.clear();
vi.unstubAllGlobals();
});
afterEach(() => {
vi.unstubAllGlobals();
localStorage.clear();
});
describe('B-10.1:raw fetch(文件上传)401 也走统一登出', () => {
it('uploadPickingOutboundPhotoApi 401 ⇒ 清 session、跳一次登录、错误带 status/code', async () => {
const { setStoredSession } = await import('../lib/localApiClient');
setStoredSession({ access_token: 't-upload', user: { id: 'u1' } } as never);
const loc = installLocationStub();
vi.stubGlobal(
'fetch',
vi.fn(async () => ({ ok: false, status: 401, json: async () => ({ error: 'token_expired' }) }))
);
const { uploadPickingOutboundPhotoApi } = await loadWorkflowApi();
const file = new File(['x'], 'a.jpg', { type: 'image/jpeg' });
const error = await uploadPickingOutboundPhotoApi(file).catch((err) => err);
expect(error).toMatchObject({ status: 401, code: 'token_expired' });
expect(localStorage.getItem(SESSION_KEY)).toBeNull();
expect(loc.href).toContain('/login');
expect(loc.href).toContain('reason=expired');
});
});
describe('workflowApi 401:与 localApiClient 共用登出处理', () => {
it('有 session ⇒ 清 session、跳 /login?reason=expired、错误带 status=401 与 code', async () => {
const { setStoredSession } = await import('../lib/localApiClient');
setStoredSession({ access_token: 't-1', user: { id: 'u1' } } as never);
expect(localStorage.getItem(SESSION_KEY)).toBeTruthy();
const loc = installLocationStub();
mockUnauthorized();
const { submitInspectionComplianceApi } = await loadWorkflowApi();
const error = await submitInspectionComplianceApi({}).catch((err) => err);
expect(error).toMatchObject({ status: 401, code: 'token_expired' });
expect(localStorage.getItem(SESSION_KEY), '401 后必须清掉本地 session').toBeNull();
expect(loc.href).toContain('/login');
expect(loc.href).toContain('reason=expired');
});
it('401 且 body 为 JSON null ⇒ 不崩、仍登出、错误带 status=401/code=unauthorized', async () => {
const { setStoredSession } = await import('../lib/localApiClient');
setStoredSession({ access_token: 't-null', user: { id: 'u1' } } as never);
const loc = installLocationStub();
vi.stubGlobal(
'fetch',
vi.fn(async () => ({ ok: false, status: 401, body: null, json: async () => null }))
);
const { submitInspectionComplianceApi } = await loadWorkflowApi();
const error = await submitInspectionComplianceApi({}).catch((err) => err);
expect(error, 'body=null 时不得因读 payload.error 抛 TypeError').toMatchObject({
status: 401,
code: 'unauthorized',
});
expect(localStorage.getItem(SESSION_KEY)).toBeNull();
expect(loc.href).toContain('/login');
expect(loc.href).toContain('reason=expired');
});
it('无 session(登录页本身 401)⇒ 不跳转、不清数据', async () => {
const loc = installLocationStub();
mockUnauthorized();
const { submitInspectionComplianceApi } = await loadWorkflowApi();
const error = await submitInspectionComplianceApi({}).catch((err) => err);
expect(error).toMatchObject({ status: 401 });
expect(loc.href, '无 session 时不得把登录页再跳走').toBe('');
expect(localStorage.getItem(SESSION_KEY)).toBeNull();
});
});
+7 -2
View File
@@ -73,7 +73,10 @@ export function buildZipStore(entries: Array<{ name: string; data: Uint8Array }>
]);
const central = concat([
new Uint8Array([0x50, 0x4b, 0x01, 0x02]),
u16(20),
// BIZ-15:central header `version made by` = Unix(3) + spec 3.0(0x031E),
// 配合 flags 0x0800(UTF-8 文件名)让 unzip 用 UTF-8 解中文名;
// 下面 `version needed` 仍保持 20(不改,避免破坏 zipStore.test.ts 的字节断言)。
u16(0x031e),
u16(20),
u16(0x0800),
u16(0),
@@ -87,7 +90,9 @@ export function buildZipStore(entries: Array<{ name: string; data: Uint8Array }>
u16(0),
u16(0),
u16(0),
u32(0),
// 外部属性:version made by 声明 Unix(3) 后,unzip 会按高 16 位当 Unix mode;
// 给 0100644(普通文件 rw-r--r--),否则解出的文件 mode=0000 会 EACCES 读不了。
u32(0x81a40000),
u32(offset),
file.nameBytes,
]);