Files
SupplierSystem/server/tests/t2FinalSuspendedPriority.test.ts
T
Ubuntu 5fa2bbfd55
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
fix(audit-20261019): T1-T9 审计修复、存储归属与审计日志列宽
- 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 超长修复
2026-10-19 16:16:51 +08:00

227 lines
9.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { beforeEach, describe, expect, it, vi } from 'vitest';
/**
* T2 rev22 实体最终复测 · B-A4(tester 独立边界,2026-10-19)。
*
* 场景:台账 `P_SU` 为 `suspended` 且已有**有效**对照 ROW_KEEP;同单另有活行 ROW_OTHER;
* payload 含 P_SU 与**缺行** P_MISS(同名)。要求:
* · suspended 属"保留指针"档 ⇒ repair 不得清/改它的 ROW_KEEP;
* · 缺行 P_MISS 只能从未占用候选里拿 **ROW_OTHER**;
* · 之后重复 item_removed:每次只针对自己那行(ROW_KEEP),返回 already_gone 时不得误删 ROW_OTHER。
*/
const H = vi.hoisted(() => ({
poolQuery: vi.fn(),
tenantCtx: vi.fn(),
markPrep: vi.fn(),
removeItem: vi.fn(),
recalc: vi.fn(),
notify: vi.fn(),
}));
vi.mock('../src/db', () => ({
pool: { query: (...args: unknown[]) => H.poolQuery(...args), connect: vi.fn() },
query: (...args: unknown[]) => H.poolQuery(...args),
getRawPoolQuery: () => H.poolQuery,
}));
vi.mock('../src/services/tenantDbContext', () => ({
runWithTenantDbContext: (_code: unknown, fn: () => Promise<unknown>) => H.tenantCtx(fn),
}));
vi.mock('../src/services/mainSystemPrepLedger', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/services/mainSystemPrepLedger')>();
return { ...actual, markPrepDisposition: (...args: unknown[]) => H.markPrep(...args) };
});
vi.mock('../src/services/orderManageItemsService', () => ({
removeOrderItemForMainSystemReturn: (...args: unknown[]) => H.removeItem(...args),
}));
vi.mock('../src/services/mainSystemStockout', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/services/mainSystemStockout')>();
return { ...actual, recalcOrderHeaderTotals: (...args: unknown[]) => H.recalc(...args) };
});
vi.mock('../src/services/notificationService', () => ({
notifyRoleUsers: (...args: unknown[]) => H.notify(...args),
}));
const { repairMissingPrepLedgerRows } = await import('../src/services/mainSystemReturnFollow');
const { applyItemNoLongerOurs } = await import('../src/services/mainSystemReverseEvents');
const P_SU = '55555555-5555-4555-8555-5555555555a1';
const P_MISS = '55555555-5555-4555-8555-5555555555b2';
const ROW_KEEP = '66666666-6666-4666-8666-66666666666a';
const ROW_OTHER = '77777777-7777-4777-8777-77777777777b';
const ORDER = 'ORD_API_BA4';
type LedgerEntry = { disposition: string; link: string | null };
const state = {
ledger: new Map<string, LedgerEntry>(),
items: [] as Array<{ id: string; returned: boolean }>,
upsertSql: '',
candidateSql: '',
upserts: [] as Array<{ prepId: string; link: string | null; disposition: string }>,
};
function installDb(): void {
H.poolQuery.mockImplementation(async (sql: string, params: unknown[] = []) => {
const text = String(sql);
if (/FROM public\.main_system_order_imports i/i.test(text)) {
return {
rows: [
{
main_order_code: 'ORD_WEB_BA4',
our_order_code: ORDER,
main_supplier_code: 'SUP1',
payload: [
{ id: P_SU, itemName: '肉片', prepareQty: 2, isStockout: false },
{ id: P_MISS, itemName: '肉片', prepareQty: 2, isStockout: false },
],
},
],
rowCount: 1,
};
}
// 清坏指针:只清"指向已退货/不存在"的;suspended 的有效 pointer 不动
if (/SET our_order_item_id = NULL/i.test(text)) {
let changed = 0;
for (const [prepId, entry] of state.ledger) {
const item = state.items.find((row) => row.id === entry.link);
if (entry.link && (!item || item.returned) && [P_SU, P_MISS].includes(prepId)) {
state.ledger.set(prepId, { ...entry, link: null });
changed += 1;
}
}
return { rows: [], rowCount: changed };
}
// fixed mapping:suspended 的有效对照参与"固定保留"
if (/JOIN order_items oi ON oi\.id = li\.our_order_item_id/i.test(text)) {
const rows = [...state.ledger.entries()]
.filter(([prepId, entry]) => entry.link && [P_SU, P_MISS].includes(prepId))
.map(([prepId, entry]) => ({ prep_id: prepId, our_order_item_id: entry.link }));
return { rows, rowCount: rows.length };
}
// item_removed 定位
if (/FROM public\.main_system_order_import_items/i.test(text) && /prep_id = \$2::uuid/i.test(text)) {
const entry = state.ledger.get(String(params[1]));
return entry?.link
? { rows: [{ our_order_code: ORDER, our_order_item_id: entry.link }], rowCount: 1 }
: { rows: [], rowCount: 0 };
}
// 候选(真实实现带 NOT EXISTS 排除已被占用的行;本 fake 按"未在台账里被指向"筛)
if (/FROM order_items/i.test(text)) {
state.candidateSql = text;
const claimed = new Set([...state.ledger.values()].map((entry) => entry.link).filter(Boolean));
const rows = state.items
.filter((row) => !row.returned && !claimed.has(row.id))
.map((row) => ({ id: row.id, item_name: '肉片' }));
return { rows, rowCount: rows.length };
}
// 台账 upsert(实现 rev22 的 B-A3/B-A4 CASE 语义)
if (/INSERT INTO public\.main_system_order_import_items/i.test(text)) {
state.upsertSql = text;
const prepId = String(params[2]);
const incomingLink = (params[4] as string | null) ?? null;
const incomingDisposition = String(params[11]);
state.upserts.push({ prepId, link: incomingLink, disposition: incomingDisposition });
const existing = state.ledger.get(prepId);
if (!existing) {
state.ledger.set(prepId, { disposition: incomingDisposition, link: incomingLink });
} else {
const hard = ['removed', 'returned', 'cancelled'].includes(String(existing.disposition || '').toLowerCase());
const nextLink = hard
? null
: existing.disposition === 'reallocated'
? incomingLink
: existing.link ?? incomingLink;
state.ledger.set(prepId, { disposition: existing.disposition, link: nextLink });
}
return { rows: [], rowCount: 1 };
}
return { rows: [], rowCount: 0 };
});
}
beforeEach(() => {
H.poolQuery.mockReset();
H.tenantCtx.mockReset();
H.markPrep.mockReset();
H.removeItem.mockReset();
H.recalc.mockReset();
H.notify.mockReset();
H.tenantCtx.mockImplementation(async (fn: () => Promise<unknown>) => fn());
H.markPrep.mockResolvedValue(undefined);
H.removeItem.mockResolvedValue('deleted');
H.recalc.mockResolvedValue(undefined);
H.notify.mockResolvedValue(undefined);
state.ledger = new Map([[P_SU, { disposition: 'suspended', link: ROW_KEEP }]]);
state.items = [
{ id: ROW_KEEP, returned: false },
{ id: ROW_OTHER, returned: false },
];
state.upsertSql = '';
state.candidateSql = '';
state.upserts = [];
installDb();
});
describe('T2 B-A4:suspended 保留原行,缺行拿另一行,重复 item_removed 只删自己行', () => {
it('repair:suspended(P_SU)→ROW_KEEP 不变;缺行 P_MISS→ROW_OTHER;upsert CASE 不把 suspended 强制 NULL', async () => {
await repairMissingPrepLedgerRows('BR002');
expect(state.ledger.get(P_SU)).toEqual({ disposition: 'suspended', link: ROW_KEEP });
expect(state.upsertSql).toMatch(/IN \('removed', 'returned', 'cancelled'\)/);
expect(state.upsertSql).toMatch(/THEN NULL/);
// 硬删档(removed/returned/cancelled)强制 NULL;suspended/completed 只在**无指针**时保持 NULL,
// 有指针时必须保留(RELATED-1,2026-10-19 复攻后实现新增该分支)
expect(state.upsertSql).toMatch(/IN \('removed', 'returned', 'cancelled'\)\s*\n?\s*THEN NULL/);
expect(state.upsertSql).toMatch(
/IN \('suspended', 'completed'\)[\s\S]{0,200}?our_order_item_id IS NULL[\s\S]{0,40}?THEN NULL/
);
// suspended 的保留语义由本测试第一段(ledger 仍为 ROW_KEEP)行为断言兜住
// 候选排除已被 suspended 占用的 ROW_KEEP ⇒ P_MISS 只能拿 ROW_OTHER
expect(state.candidateSql).toContain('NOT EXISTS');
expect(state.candidateSql).toContain('claimed.our_order_item_id = order_items.id');
// upsert 的 **EXCLUDED** 侧是 imported;DB 侧 disposition CASE 保持既有 suspended(上一断言已验)
expect(state.upserts.find((row) => row.prepId === P_SU)).toMatchObject({
link: ROW_KEEP,
disposition: 'imported',
});
expect(state.upserts.find((row) => row.prepId === P_MISS)).toMatchObject({
link: ROW_OTHER,
disposition: 'imported',
});
});
it('item_removed(P_SU) 删 ROW_KEEP;重复投递 already_gone 且绝不动 P_MISS 的 ROW_OTHER', async () => {
H.removeItem.mockImplementation(async (args: { itemId: string }) => {
const idx = state.items.findIndex((row) => row.id === args.itemId);
if (idx >= 0) {
state.items.splice(idx, 1);
return 'deleted';
}
return 'not_found';
});
const first = await applyItemNoLongerOurs({
branchCode: 'BR002',
prepId: P_SU,
mainOrderCode: 'ORD_WEB_BA4',
reason: 'item_removed',
});
const second = await applyItemNoLongerOurs({
branchCode: 'BR002',
prepId: P_SU,
mainOrderCode: 'ORD_WEB_BA4',
reason: 'item_removed',
});
expect(first.status).toBe('removed');
expect(second.status).toBe('already_gone');
expect(H.removeItem).toHaveBeenCalledTimes(2);
for (const call of H.removeItem.mock.calls) {
expect(call[0]).toMatchObject({ itemId: ROW_KEEP });
}
expect(state.items.map((row) => row.id), '缺行的 ROW_OTHER 不得被误删').toEqual([ROW_OTHER]);
expect(H.markPrep.mock.calls.every(([arg]) => (arg as { prepId: string }).prepId === P_SU)).toBe(true);
});
});