Files
SupplierSystem/server/tests/t2ReviveMappingPurgeBoundary.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

332 lines
15 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';
import { loadEnv } from '../src/env';
import type { MainOrderGroup } from '../src/services/mainSystemOrderImport';
/**
* T2 红队攻破修复 · 独立增量复测(2026-10-19,tester;task-2 rev6)。
*
* 覆盖 3 个攻破点:
* a) 改派(reallocated)墓碑**不阻断**:E1 回来时解除墓碑、建行/追加、台账 imported;重复 E1 不重复行;
* item_removed / order 墓碑仍按硬删语义跳过。
* b) 旧行软退货 + 新行同 SKU/同量 ⇒ 映射候选必须只含新行(真实 SQL 过滤 + 真实 PG 排序),
* 之后 item_removed 只删新行,不误删旧退货行、不遗留。
* c) purgeReverseTombstones:null/undefined/NaN/负值/Infinity/字符串 一律抛错且不查库;0 允许。
*/
const H = vi.hoisted(() => ({
poolQuery: vi.fn(),
tenantCtx: vi.fn(),
markPrep: vi.fn(),
removeItem: vi.fn(),
recalc: vi.fn(),
notify: vi.fn(),
/** 内存墓碑表(reason 决定语义) */
tombstones: [] as Array<{ branch: string; kind: 'prep' | 'order'; key: string; reason: string | null }>,
/** 内存行级台账 */
ledger: new Map<string, { disposition: string; link: string | null }>(),
}));
function normalize(kind: string, key: unknown): string {
const text = String(key ?? '').trim();
return kind === 'prep' ? text.toLowerCase() : text;
}
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),
}));
// 墓碑表可控:reallocated 不阻断 + E1 回来时清除;其它 reason 继续阻断
vi.mock('../src/services/mainSystemReverseEvents', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/services/mainSystemReverseEvents')>();
const byKind = (branch: string, kind: string, keys: string[]) => {
const want = new Set(keys.map((key) => normalize(kind, key)));
return H.tombstones.filter((row) => row.branch === branch && row.kind === kind && want.has(row.key));
};
return {
...actual,
listReverseTombstoneKeys: async (input: { branchCode: string; kind: string; keys: string[] }) =>
new Set(byKind(input.branchCode, input.kind, input.keys || []).map((row) => row.key)),
listReallocatedReverseTombstones: async (input: { branchCode: string; keys: string[] }) =>
new Set(
byKind(input.branchCode, 'prep', input.keys || [])
.filter((row) => row.reason === 'reallocated')
.map((row) => row.key)
),
clearReverseTombstone: async (input: { branchCode: string; kind: string; businessKey: string }) => {
const key = normalize(input.kind, input.businessKey);
const before = H.tombstones.length;
H.tombstones = H.tombstones.filter(
(row) => !(row.branch === input.branchCode && row.kind === input.kind && row.key === key)
);
return before - H.tombstones.length;
},
};
});
const { filterTombstonedGroups, loadMappingCandidateOrderItems, needsAppendToOrder } = await import(
'../src/services/mainSystemOrderImport'
);
const {
mapOrderPrepRowsToOurItems,
recordImportedPrepItems,
} = await import('../src/services/mainSystemPrepLedger');
const { applyItemNoLongerOurs, purgeReverseTombstones } = await import(
'../src/services/mainSystemReverseEvents'
);
function group(orderCode: string, prepIds: string[], itemName = '肉片'): MainOrderGroup {
return {
orderCode,
deliveryDate: '2026-10-22',
taskDay: '2026-10-22',
rows: prepIds.map((id) => ({
id,
itemName,
prepareQty: 2,
isStockout: false,
})) as unknown as MainOrderGroup['rows'],
};
}
/** 最小 upsert 模拟:只实现 (branch_code, prep_id) 唯一键 + reallocated 复活语义 */
function installLedgerUpsert(): void {
H.poolQuery.mockImplementation(async (sql: string, params: unknown[] = []) => {
const text = String(sql);
if (/INSERT INTO public\.main_system_order_import_items/i.test(text)) {
const prepId = String(params[2]).trim().toLowerCase();
const incomingLink = (params[4] as string | null) ?? null;
const incomingDisposition = String(params[11]);
const existing = H.ledger.get(prepId);
if (!existing) {
H.ledger.set(prepId, { disposition: incomingDisposition, link: incomingLink });
} else {
const nextDisposition =
existing.disposition === 'reallocated' && incomingLink ? incomingDisposition : existing.disposition;
const nextLink =
existing.disposition === 'reallocated' ? incomingLink : existing.link ?? incomingLink;
H.ledger.set(prepId, { disposition: nextDisposition, link: nextLink });
}
return { rows: [], rowCount: 1 };
}
if (/FROM public\.main_system_order_import_items/i.test(text)) {
const prepId = String(params[1]).trim().toLowerCase();
const entry = H.ledger.get(prepId);
return entry
? { rows: [{ our_order_code: 'ORD_API_T2B', our_order_item_id: entry.link }], rowCount: 1 }
: { rows: [], rowCount: 0 };
}
return { rows: [], rowCount: 0 };
});
}
const PREP_1 = 'prep-revive-1';
const PREP_REMOVED = 'prep-removed-2';
const ITEM_OLD = '11111111-1111-4111-8111-1111111111aa';
const ITEM_NEW = '22222222-2222-4222-8222-2222222222bb';
beforeEach(() => {
H.poolQuery.mockReset();
H.tenantCtx.mockReset();
H.markPrep.mockReset();
H.removeItem.mockReset();
H.recalc.mockReset();
H.notify.mockReset();
H.tombstones = [];
H.ledger = new Map();
H.tenantCtx.mockImplementation(async (fn: () => Promise<unknown>) => fn());
H.markPrep.mockResolvedValue(undefined);
H.removeItem.mockResolvedValue('deleted');
H.recalc.mockResolvedValue(undefined);
H.notify.mockResolvedValue(undefined);
installLedgerUpsert();
});
/* ── a) 改派墓碑先于 E1 ────────────────────────────────────────────────── */
describe('T2 攻破 1:reallocated 墓碑不阻断,E1 回来即解除并 imported', () => {
it('E1 回来 ⇒ 行放行、墓碑删除、台账 reallocated→imported;重复 E1 仍 1 行', async () => {
H.tombstones = [{ branch: 'BR002', kind: 'prep', key: PREP_1, reason: 'reallocated' }];
// E1 到达前的状态:reallocated 墓碑存在,但该行**不阻断**
const filtered = await filterTombstonedGroups('BR002', [group('ORD_WEB_A', [PREP_1])]);
expect(filtered.skipped).toEqual([]);
expect(filtered.groups[0].rows.map((row) => row.id)).toEqual([PREP_1]);
expect(H.tombstones, 'E1 回来后改派墓碑必须被清除').toHaveLength(0);
// 台账侧:reallocated 允许重新追加;E1 写台账后复位 imported 且指向新行
expect(
needsAppendToOrder({ id: PREP_1, isStockout: false }, [
{ prep_id: PREP_1, our_order_item_id: ITEM_OLD, disposition: 'reallocated' },
])
).toBe(true);
H.ledger.set(PREP_1, { disposition: 'reallocated', link: ITEM_OLD });
await recordImportedPrepItems({
branchCode: 'BR002',
mainOrderCode: 'ORD_WEB_A',
supplierCode: 'INTERNAL',
ourOrderCode: 'ORD_API_T2B',
prepRows: [{ id: PREP_1, itemName: '肉片', prepareQty: 2 }],
ourItems: [{ id: ITEM_NEW, item_name: '肉片' }],
mapping: new Map([[PREP_1, ITEM_NEW]]),
});
expect(H.ledger.get(PREP_1)).toEqual({ disposition: 'imported', link: ITEM_NEW });
// 重复 E1(同 payload 再来一次)⇒ 同一 (branch, prep) 行,不重复
await recordImportedPrepItems({
branchCode: 'BR002',
mainOrderCode: 'ORD_WEB_A',
supplierCode: 'INTERNAL',
ourOrderCode: 'ORD_API_T2B',
prepRows: [{ id: PREP_1, itemName: '肉片', prepareQty: 2 }],
ourItems: [{ id: ITEM_NEW, item_name: '肉片' }],
mapping: new Map([[PREP_1, ITEM_NEW]]),
});
expect(H.ledger.size).toBe(1);
expect(H.ledger.get(PREP_1)).toEqual({ disposition: 'imported', link: ITEM_NEW });
});
it('item_removed 墓碑仍 skipped(硬删);order 墓碑整组跳过;无墓碑行为不变', async () => {
H.tombstones = [
{ branch: 'BR002', kind: 'prep', key: PREP_REMOVED, reason: 'item_removed' },
{ branch: 'BR002', kind: 'order', key: 'ORD_WEB_TOMB', reason: 'deleted' },
];
const removed = await filterTombstonedGroups('BR002', [group('ORD_WEB_OK', [PREP_REMOVED])]);
expect(removed.groups).toHaveLength(0);
expect(removed.skipped[0]).toMatchObject({ status: 'skipped_tombstoned', mainOrderCode: 'ORD_WEB_OK' });
const orderBlocked = await filterTombstonedGroups('BR002', [group('ORD_WEB_TOMB', ['keep-1'])]);
expect(orderBlocked.groups).toHaveLength(0);
expect(orderBlocked.skipped[0]).toMatchObject({ status: 'skipped_tombstoned', mainOrderCode: 'ORD_WEB_TOMB' });
const plain = await filterTombstonedGroups('BR002', [group('ORD_WEB_OK', ['keep-2'])]);
expect(plain.skipped).toEqual([]);
expect(plain.groups[0].rows.map((row) => row.id)).toEqual(['keep-2']);
});
});
/* ── b) 旧退货行 vs 新行的映射 ─────────────────────────────────────────── */
type PgClient = {
connect: () => Promise<void>;
end: () => Promise<void>;
query: (sql: string, params?: unknown[]) => Promise<{ rows: Array<Record<string, unknown>> }>;
};
describe('T2 攻破 2:映射候选排除已退货行(真实 SQL + 真实 PG)', () => {
it('软退货旧行排前也不会被选中;item_removed 只删新行、旧行保留', async (ctx) => {
let candidateSql = '';
await loadMappingCandidateOrderItems(
{ query: async (sql: string) => ((candidateSql = String(sql)), { rows: [] }) },
'ORD_X'
);
expect(candidateSql).toMatch(/COALESCE\(is_returned, false\) = false/);
expect(candidateSql).toMatch(/COALESCE\(is_extra_dish, false\) = false/);
expect(candidateSql).toContain('ORDER BY sort_order NULLS LAST, created_at, id');
loadEnv();
if (!process.env.DATABASE_URL) {
ctx.skip();
return;
}
const pg = (await import('pg')).default as unknown as {
Client: new (cfg: { connectionString: string }) => PgClient;
};
const client = new pg.Client({ connectionString: process.env.DATABASE_URL });
try {
await client.connect();
} catch {
ctx.skip();
return;
}
try {
await client.query('SET default_transaction_read_only = on');
const fixture = `(VALUES
('${ITEM_OLD}'::uuid, 'ORD_X'::text, '土豆'::text, 0, '2026-01-01 00:00:00+08'::timestamptz, true, false, 5::numeric),
('${ITEM_NEW}'::uuid, 'ORD_X'::text, '土豆'::text, 1, '2026-10-19 00:00:00+08'::timestamptz, false, false, 5::numeric)
) AS order_items(id, order_code, item_name, sort_order, created_at, is_returned, is_extra_dish, quantity)`;
const sql = candidateSql.replace('FROM order_items', `FROM ${fixture}`);
const rows = (await client.query(sql, ['ORD_X'])).rows;
expect(rows.map((row) => String(row.id))).toEqual([ITEM_NEW]);
// 真实映射:同 SKU/同量、仅有新行可选 ⇒ 指向新行
const PREP = 'prep-t2b-map';
const mapping = mapOrderPrepRowsToOurItems(
[{ orderCode: 'ORD_WEB_MAP', rows: [{ id: PREP, itemName: '土豆', prepareQty: 5 }] }],
rows.map((row) => ({ id: String(row.id), item_name: String(row.item_name || '') }))
);
expect(mapping.get(PREP)).toBe(ITEM_NEW);
// 之后 item_removed:台账指向新行 ⇒ 只删新行,旧退货行原样保留(不误删/不遗留)
const dbRows = [{ id: ITEM_OLD }, { id: ITEM_NEW }];
H.ledger.set(PREP, { disposition: 'imported', link: ITEM_NEW });
H.removeItem.mockImplementation(async (args: { itemId: string }) => {
const idx = dbRows.findIndex((row) => row.id === args.itemId);
if (idx >= 0) dbRows.splice(idx, 1);
return 'deleted';
});
const outcome = await applyItemNoLongerOurs({
branchCode: 'BR002',
prepId: PREP,
mainOrderCode: 'ORD_WEB_MAP',
reason: 'item_removed',
});
expect(outcome.status).toBe('removed');
expect(H.removeItem).toHaveBeenCalledTimes(1);
expect(H.removeItem.mock.calls[0][0]).toMatchObject({ itemId: ITEM_NEW });
expect(dbRows.map((row) => row.id), '旧退货行不得被误删,新行删除后无遗留').toEqual([ITEM_OLD]);
expect(H.markPrep.mock.calls[0][0]).toMatchObject({ prepId: PREP, disposition: 'removed' });
} finally {
await client.end();
}
});
});
/* ── c) purge 参数校验 ────────────────────────────────────────────────── */
describe('T2:purgeReverseTombstones 参数校验', () => {
it('null/undefined/NaN/负值/Infinity/字符串 ⇒ 抛错且不查库', async () => {
for (const bad of [null, undefined, Number.NaN, -1, -0.5, Number.POSITIVE_INFINITY, '30']) {
await expect(purgeReverseTombstones(bad as never), String(bad)).rejects.toThrow(/非负数字/);
}
expect(H.poolQuery).not.toHaveBeenCalled();
});
it('0 允许(只清 created_at < NOW() 的历史行),小数向下取整', async () => {
H.poolQuery.mockResolvedValue({ rows: [], rowCount: 2 });
expect(await purgeReverseTombstones(0)).toBe(2);
const call = H.poolQuery.mock.calls.at(-1)!;
expect(String(call[0])).toContain('created_at < NOW() - make_interval(days => $1::int)');
expect(call[1]).toEqual([0]);
H.poolQuery.mockClear();
H.poolQuery.mockResolvedValue({ rows: [], rowCount: 0 });
expect(await purgeReverseTombstones(3.9)).toBe(0);
expect(H.poolQuery.mock.calls.at(-1)![1]).toEqual([3]);
});
});