- 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 超长修复
851 lines
38 KiB
TypeScript
851 lines
38 KiB
TypeScript
import { readFileSync } from 'node:fs';
|
||
import path from 'node:path';
|
||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||
|
||
/**
|
||
* T2 红队攻破 B(2026-10-19):台账补齐路径不得把 reallocated 复活到**已退货旧行**。
|
||
*
|
||
* 事故:`mainSystemReturnFollow.repairMissingPrepLedgerRows` 读 `order_items` 时
|
||
* 不过滤 `is_returned`/`is_extra_dish`、也不传 mapping ⇒ 同名旧退货行排前被选中,
|
||
* `recordImportedPrepItems` 的 reallocated 分支复位 imported 并指向旧退货行;
|
||
* 之后删行发现 already_returned ⇒ 新行永久留下、台账却 removed。
|
||
* `mainSystemWriteback` 的惰性对照同类(观察项),一并加过滤。
|
||
*
|
||
* 本文件跑**真实** `repairMissingPrepLedgerRows` + 真实 `recordImportedPrepItems`(仅 db 为
|
||
* 可控 fake),断言:① 候选查询带过滤;② 有未退货新行 ⇒ 对照指向新行且 disposition=imported;
|
||
* ③ 无可用新行 ⇒ 不复活(link=NULL、disposition 不写 imported)。
|
||
*/
|
||
|
||
const H = vi.hoisted(() => ({ poolQuery: vi.fn(), tenantCtx: 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),
|
||
}));
|
||
|
||
import { repairMissingPrepLedgerRows } from '../src/services/mainSystemReturnFollow';
|
||
import { loadMappingCandidateOrderItems } from '../src/services/mainSystemOrderImport';
|
||
import { mapOrderPrepRowsToOurItems as mapPrepRowsToOurItemsForTest } from '../src/services/mainSystemPrepLedger';
|
||
|
||
const NEW_ID = '22222222-2222-4222-8222-222222222222';
|
||
const OLD_RETURNED_ID = '11111111-1111-4111-8111-111111111111';
|
||
const PREP = '33333333-3333-4333-8333-333333333333';
|
||
|
||
function payload(): Array<Record<string, unknown>> {
|
||
return [{ id: PREP, itemName: '肉片', prepareQty: 2, isStockout: false }];
|
||
}
|
||
|
||
type Captured = { itemSql: string; itemParams: unknown[]; upsertParams: unknown[] | null; cleared: number };
|
||
|
||
function installPool(candidateRows: Array<{ id: string; item_name: string }>): Captured {
|
||
const captured: Captured = { itemSql: '', itemParams: [], upsertParams: null, cleared: 0 };
|
||
H.poolQuery.mockImplementation(async (sql: string, params: unknown[] = []) => {
|
||
const text = String(sql);
|
||
if (/UPDATE public\.main_system_order_import_items li/i.test(text)) {
|
||
captured.cleared += 1;
|
||
return { rows: [], rowCount: 1 };
|
||
}
|
||
if (/FROM public\.main_system_order_imports i/i.test(text)) {
|
||
return {
|
||
rows: [
|
||
{
|
||
main_order_code: 'ORD_WEB_A',
|
||
main_supplier_code: 'SUP1',
|
||
our_order_code: 'ORD_API_1',
|
||
payload: payload(),
|
||
},
|
||
],
|
||
rowCount: 1,
|
||
};
|
||
}
|
||
if (/^\s*SELECT[\s\S]*FROM order_items/i.test(text)) {
|
||
captured.itemSql = text;
|
||
captured.itemParams = params;
|
||
return { rows: candidateRows, rowCount: candidateRows.length };
|
||
}
|
||
if (/INSERT INTO public\.main_system_order_import_items/i.test(text)) {
|
||
captured.upsertParams = params;
|
||
return { rows: [], rowCount: 1 };
|
||
}
|
||
return { rows: [], rowCount: 0 };
|
||
});
|
||
return captured;
|
||
}
|
||
|
||
type PayloadPrepRow = { id: string; itemName: string; prepareQty: number };
|
||
|
||
function installPoolWithPayload(
|
||
payloadRows: PayloadPrepRow[],
|
||
opts: {
|
||
linked: Array<{ prep_id: string; our_order_item_id: string }>;
|
||
candidates: Array<{ id: string; item_name: string }>;
|
||
ledgerStates?: Array<{ prep_id: string; disposition: string }>;
|
||
}
|
||
): {
|
||
itemParams: unknown[];
|
||
mapping: Map<string, string>;
|
||
upsertMapping: unknown[];
|
||
} {
|
||
const captured = {
|
||
itemParams: [] as unknown[],
|
||
mapping: new Map<string, string>(),
|
||
upsertMapping: [] as unknown[],
|
||
cleared: 0,
|
||
};
|
||
H.poolQuery.mockImplementation(async (sql: string, params: unknown[] = []) => {
|
||
const text = String(sql);
|
||
if (/UPDATE public\.main_system_order_import_items li/i.test(text)) {
|
||
captured.cleared += 1;
|
||
return { rows: [], rowCount: 1 };
|
||
}
|
||
if (/SELECT li\.prep_id::text AS prep_id, li\.disposition/i.test(text)) {
|
||
return { rows: opts.ledgerStates || [], rowCount: (opts.ledgerStates || []).length };
|
||
}
|
||
if (/FROM public\.main_system_order_imports i/i.test(text)) {
|
||
return {
|
||
rows: [
|
||
{
|
||
main_order_code: 'ORD_WEB_A',
|
||
main_supplier_code: 'SUP1',
|
||
our_order_code: 'ORD_API_1',
|
||
payload: payloadRows,
|
||
},
|
||
],
|
||
rowCount: 1,
|
||
};
|
||
}
|
||
if (/FROM public\.main_system_order_import_items li/i.test(text)) {
|
||
return { rows: opts.linked, rowCount: opts.linked.length };
|
||
}
|
||
if (/^\s*SELECT[\s\S]*FROM order_items/i.test(text)) {
|
||
captured.itemParams = params;
|
||
return { rows: opts.candidates, rowCount: opts.candidates.length };
|
||
}
|
||
if (/INSERT INTO public\.main_system_order_import_items/i.test(text)) {
|
||
const prepId = String(params[2]);
|
||
const link = params[4] == null ? null : String(params[4]);
|
||
if (link) captured.mapping.set(prepId, link);
|
||
captured.upsertMapping.push(prepId);
|
||
return { rows: [], rowCount: 1 };
|
||
}
|
||
return { rows: [], rowCount: 0 };
|
||
});
|
||
return captured;
|
||
}
|
||
|
||
beforeEach(() => {
|
||
H.poolQuery.mockReset();
|
||
H.tenantCtx.mockReset();
|
||
H.tenantCtx.mockImplementation(async (fn: () => Promise<unknown>) => fn());
|
||
});
|
||
|
||
describe('攻破 B:repairMissingPrepLedgerRows 只认未退货/非加菜的新行', () => {
|
||
it('旧退货行 + 新行 ⇒ 候选 SQL 过滤退货/加菜,对照指向新行且 imported', async () => {
|
||
const captured = installPool([{ id: NEW_ID, item_name: '肉片' }]);
|
||
|
||
const written = await repairMissingPrepLedgerRows('BR002');
|
||
expect(written).toBe(1);
|
||
|
||
// ① 候选查询必须排除已退货/加菜行(否则同名旧退货行 sort_order 更靠前会被选中)
|
||
expect(captured.itemSql).toMatch(/COALESCE\(is_returned, false\) = false/);
|
||
expect(captured.itemSql).toMatch(/COALESCE\(is_extra_dish, false\) = false/);
|
||
// ①b B1:还必须排除已被本分公司其它备货行占用的订单行(一对一),参数带 branch + 本单 prep 集合
|
||
expect(captured.itemSql).toContain('NOT EXISTS');
|
||
expect(captured.itemSql).toContain('claimed.our_order_item_id = order_items.id');
|
||
expect(captured.itemSql).toContain('NOT (claimed.prep_id = ANY($3::uuid[]))');
|
||
expect(captured.itemParams[1]).toBe('BR002');
|
||
expect(captured.itemParams[2]).toEqual([]); // R4:排除所有已占用行,已 linked 的本单 preps 用固定对照保留
|
||
|
||
// ② 台账 upsert:对照=新行,disposition=imported(reallocated 复活到新行)
|
||
expect(captured.upsertParams).toBeTruthy();
|
||
expect(captured.upsertParams![4]).toBe(NEW_ID);
|
||
expect(captured.upsertParams![4]).not.toBe(OLD_RETURNED_ID);
|
||
expect(captured.upsertParams![11]).toBe('imported');
|
||
});
|
||
|
||
it('只有退货行(候选为空)⇒ 不复活:对照=NULL、disposition 不写 imported', async () => {
|
||
const captured = installPool([]);
|
||
|
||
await repairMissingPrepLedgerRows('BR002');
|
||
|
||
expect(captured.itemSql).toMatch(/COALESCE\(is_returned, false\) = false/);
|
||
expect(captured.upsertParams).toBeTruthy();
|
||
expect(captured.upsertParams![4]).toBeNull();
|
||
expect(captured.upsertParams![11]).not.toBe('imported');
|
||
});
|
||
});
|
||
|
||
describe('攻破 B(观察项):writeback 惰性对照同样过滤退货/加菜行', () => {
|
||
it('mainSystemWriteback 的 order_items 候选查询含 is_returned/is_extra_dish 过滤', () => {
|
||
const source = readFileSync(path.join(__dirname, '../src/services/mainSystemWriteback.ts'), 'utf8');
|
||
const query = source.slice(source.indexOf('FROM order_items'), source.indexOf('FROM order_items') + 400);
|
||
expect(query).toMatch(/COALESCE\(is_returned, false\) = false/);
|
||
expect(query).toMatch(/COALESCE\(is_extra_dish, false\) = false/);
|
||
});
|
||
});
|
||
|
||
describe('R4:同一 payload 内 P1 已占 R2、P2 缺行 ⇒ P1 保留 R2,P2 不得再认领 R2', () => {
|
||
it('运行时:linked 的 P1 固定保留,P2 只能从未占用候选里配(候选不足则 pending)', async () => {
|
||
const P1 = 'aaaaaaaa-0001-4000-8000-000000000001';
|
||
const P2 = 'aaaaaaaa-0002-4000-8000-000000000002';
|
||
const R2 = '11111111-0002-4000-8000-000000000002';
|
||
const R3 = '11111111-0003-4000-8000-000000000003';
|
||
const captured = installPoolWithPayload(
|
||
[
|
||
{ id: P1, itemName: '肉片', prepareQty: 1 },
|
||
{ id: P2, itemName: '牛肉', prepareQty: 1 },
|
||
],
|
||
{ linked: [{ prep_id: P1, our_order_item_id: R2 }], candidates: [{ id: R3, item_name: '牛肉' }] }
|
||
);
|
||
|
||
await repairMissingPrepLedgerRows('BR002');
|
||
|
||
// 候选查询必须排除全部已占用行(params[2] 为空数组)
|
||
expect(captured.itemParams[2]).toEqual([]);
|
||
// 新 payload 只有缺行 P2(P1 已在 link 查询里固定,不再参与映射)
|
||
expect(captured.mapping.get(P2)).toBe(R3);
|
||
expect(captured.mapping.get(P1)).toBe(R2);
|
||
});
|
||
});
|
||
|
||
describe('R-A:运行时 —— repair 先清坏对照再一对一映射', () => {
|
||
it('P3A 的旧对照无效(未 fixed)时清 NULL,P3A→NEW、P3B→NEXT,活行不被浪费', async () => {
|
||
const P3A = 'ffffffff-0001-4000-8000-000000000001';
|
||
const P3B = 'ffffffff-0002-4000-8000-000000000002';
|
||
const NEW = '11111111-0002-4000-8000-000000000002';
|
||
const NEXT = '11111111-0003-4000-8000-000000000003';
|
||
const captured = installPoolWithPayload(
|
||
[
|
||
{ id: P3A, itemName: '肉片', prepareQty: 1 },
|
||
{ id: P3B, itemName: '肉片', prepareQty: 1 },
|
||
],
|
||
{
|
||
linked: [], // 旧对照指向已退货行 ⇒ link 查询不返回(视为缺对照)
|
||
candidates: [
|
||
{ id: NEW, item_name: '肉片' },
|
||
{ id: NEXT, item_name: '肉片' },
|
||
],
|
||
}
|
||
);
|
||
|
||
await repairMissingPrepLedgerRows('BR002');
|
||
|
||
expect(captured.cleared, '必须先清掉坏对照(SET our_order_item_id=NULL)').toBeGreaterThanOrEqual(1);
|
||
expect(captured.mapping.get(P3A)).toBe(NEW);
|
||
expect(captured.mapping.get(P3B)).toBe(NEXT);
|
||
});
|
||
});
|
||
|
||
/* ── B1 真实 SQL 测试:A 单 2 行 + B 单 1 行已占 ROW2(无库时跳过) ───────────── */
|
||
|
||
type PgClient = {
|
||
connect: () => Promise<void>;
|
||
end: () => Promise<void>;
|
||
query: (sql: string, params?: unknown[]) => Promise<{ rows: Array<Record<string, unknown>> }>;
|
||
};
|
||
|
||
async function loadPgClient(): Promise<PgClient | null> {
|
||
const { loadEnv } = await import('../src/env');
|
||
loadEnv();
|
||
if (!process.env.DATABASE_URL) return null;
|
||
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 {
|
||
return null;
|
||
}
|
||
return client;
|
||
}
|
||
|
||
describe('B1:真实 PG —— 候选排除其它备货行已占用的订单行', () => {
|
||
it('A1→ROW1、B1→ROW2 已占位;A2 补齐时候选不含 ROW2(映射到 ROW3)', async (ctx) => {
|
||
const PREP_A1 = 'aaaaaaaa-0001-4000-8000-000000000001';
|
||
const PREP_A2 = 'aaaaaaaa-0002-4000-8000-000000000002';
|
||
const PREP_B1 = 'bbbbbbbb-0001-4000-8000-000000000001';
|
||
const ROW1 = '11111111-0001-4000-8000-000000000001';
|
||
const ROW2 = '11111111-0002-4000-8000-000000000002';
|
||
const ROW3 = '11111111-0003-4000-8000-000000000003';
|
||
|
||
// 捕获真实候选 SQL
|
||
let candidateSql = '';
|
||
let candidateParams: unknown[] = [];
|
||
await loadMappingCandidateOrderItems(
|
||
{
|
||
query: async (sql: string, params?: unknown[]) => {
|
||
candidateSql = String(sql);
|
||
candidateParams = params || [];
|
||
return { rows: [] };
|
||
},
|
||
},
|
||
'ORD_X',
|
||
{ branchCode: '__T2B1__', excludePrepIds: [PREP_A1, PREP_A2] }
|
||
);
|
||
|
||
const client = await loadPgClient();
|
||
if (!client) {
|
||
ctx.skip();
|
||
return;
|
||
}
|
||
try {
|
||
const schemaRes = await client.query(
|
||
`SELECT table_schema FROM information_schema.tables
|
||
WHERE table_name = 'order_items' AND table_schema LIKE 'tenant\_%' ESCAPE '\'
|
||
ORDER BY table_schema LIMIT 1`
|
||
);
|
||
const schema = String(schemaRes.rows[0]?.table_schema || '');
|
||
if (!/^tenant_[A-Za-z0-9_]+$/.test(schema)) {
|
||
ctx.skip();
|
||
return;
|
||
}
|
||
await client.query(`SET search_path TO ${schema}`);
|
||
await client.query('BEGIN');
|
||
// 两条已有对照(A1→ROW1、B1→ROW2)
|
||
await client.query(
|
||
`INSERT INTO public.main_system_order_import_items
|
||
(branch_code, main_order_code, prep_id, our_order_code, our_order_item_id, disposition)
|
||
VALUES ('__T2B1__','M_A',$1::uuid,'ORD_X',$2::uuid,'imported'),
|
||
('__T2B1__','M_B',$3::uuid,'ORD_X',$4::uuid,'imported')`,
|
||
[PREP_A1, ROW1, PREP_B1, ROW2]
|
||
);
|
||
const fixture = `(VALUES
|
||
('${ROW1}'::uuid, 'ORD_X'::text, '肉片'::text, 0, '2026-01-01'::timestamptz, false, false),
|
||
('${ROW2}'::uuid, 'ORD_X'::text, '鱼片'::text, 1, '2026-01-01'::timestamptz, false, false),
|
||
('${ROW3}'::uuid, 'ORD_X'::text, '牛肉'::text, 2, '2026-01-01'::timestamptz, false, false)
|
||
) AS order_items(id, order_code, item_name, sort_order, created_at, is_returned, is_extra_dish)`;
|
||
const rows = (
|
||
await client.query(candidateSql.replace('FROM order_items', `FROM ${fixture}`), candidateParams)
|
||
).rows;
|
||
const ids = rows.map((row) => String(row.id));
|
||
// ROW2 被 B1 占用 ⇒ 必须排除;ROW1 属于本单(A1 在 exclude 集合)⇒ 保留
|
||
expect(ids).toEqual([ROW1, ROW3]);
|
||
|
||
const mapping = mapPrepRowsToOurItemsForTest(
|
||
[{ orderCode: 'M_A', rows: [{ id: PREP_A1, itemName: '肉片' }, { id: PREP_A2, itemName: '牛肉' }] }],
|
||
rows.map((row) => ({ id: String(row.id), item_name: String(row.item_name || '') }))
|
||
);
|
||
expect(mapping.get(PREP_A2)).toBe(ROW3);
|
||
} finally {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
await client.end();
|
||
}
|
||
});
|
||
});
|
||
|
||
/* ── R4 真实 SQL:同一 payload P1 已 linked R2、P2 缺行(无库时跳过) ───────────── */
|
||
|
||
describe('R4:真实 PG —— 同单重复认领', () => {
|
||
it('P1→R2 固定保留;P2 候选排除 R2 只能选 R3;无 R3 时 P2 不配(保持 pending)', async (ctx) => {
|
||
const P1 = 'eeeeeeee-0001-4000-8000-000000000001';
|
||
const P2 = 'eeeeeeee-0002-4000-8000-000000000002';
|
||
const R1 = '11111111-0001-4000-8000-000000000001';
|
||
const R2 = '11111111-0002-4000-8000-000000000002';
|
||
const R3 = '11111111-0003-4000-8000-000000000003';
|
||
|
||
const candidateSql = `SELECT id::text AS id, item_name
|
||
FROM order_items
|
||
WHERE order_code = $1
|
||
AND COALESCE(is_returned, false) = false
|
||
AND COALESCE(is_extra_dish, false) = false
|
||
AND NOT EXISTS (
|
||
SELECT 1 FROM public.main_system_order_import_items claimed
|
||
WHERE claimed.branch_code = $2
|
||
AND claimed.our_order_item_id = order_items.id
|
||
AND NOT (claimed.prep_id = ANY($3::uuid[]))
|
||
)
|
||
ORDER BY sort_order NULLS LAST, created_at, id`;
|
||
const fixedSql = `SELECT li.prep_id::text AS prep_id, li.our_order_item_id::text AS our_order_item_id
|
||
FROM public.main_system_order_import_items li
|
||
JOIN order_items oi ON oi.id = li.our_order_item_id AND oi.order_code = $2
|
||
WHERE li.branch_code = $1 AND li.our_order_code = $2
|
||
AND li.our_order_item_id IS NOT NULL
|
||
AND li.prep_id = ANY($3::uuid[])
|
||
AND li.disposition <> 'reallocated'
|
||
AND COALESCE(oi.is_returned, false) = false
|
||
AND COALESCE(oi.is_extra_dish, false) = false`;
|
||
|
||
const client = await loadPgClient();
|
||
if (!client) {
|
||
ctx.skip();
|
||
return;
|
||
}
|
||
try {
|
||
const schemaRes = await client.query(
|
||
`SELECT table_schema FROM information_schema.tables
|
||
WHERE table_name = 'order_items' AND table_schema LIKE 'tenant\\_%' ESCAPE '\\'
|
||
ORDER BY table_schema LIMIT 1`
|
||
);
|
||
const schema = String(schemaRes.rows[0]?.table_schema || '');
|
||
if (!/^tenant_[A-Za-z0-9_]+$/.test(schema)) {
|
||
ctx.skip();
|
||
return;
|
||
}
|
||
await client.query(`SET search_path TO ${schema}`);
|
||
await client.query('BEGIN');
|
||
await client.query(
|
||
`INSERT INTO public.main_system_order_import_items
|
||
(branch_code, main_order_code, prep_id, our_order_code, our_order_item_id, disposition)
|
||
VALUES ('__T2R4__','M_A',$1::uuid,'ORD_X',$2::uuid,'imported')`,
|
||
[P1, R2]
|
||
);
|
||
|
||
const fixture = (withR3: boolean, alias: 'order_items' | 'oi') => `(VALUES
|
||
('${R1}'::uuid, 'ORD_X'::text, '肉片'::text, 0, '2026-01-01'::timestamptz, false, false),
|
||
('${R2}'::uuid, 'ORD_X'::text, '肉片'::text, 1, '2026-01-01'::timestamptz, false, false)${withR3 ? `,
|
||
('${R3}'::uuid, 'ORD_X'::text, '牛肉'::text, 2, '2026-01-01'::timestamptz, false, false)` : ''}
|
||
) AS ${alias}(id, order_code, item_name, sort_order, created_at, is_returned, is_extra_dish)`;
|
||
|
||
const runAll = async (withR3: boolean) => {
|
||
const fx = fixture(withR3, 'order_items');
|
||
const candidates = (
|
||
await client.query(candidateSql.replace('FROM order_items', `FROM ${fx}`), ['ORD_X', '__T2R4__', []])
|
||
).rows.map((row) => ({ id: String(row.id), item_name: String(row.item_name || '') }));
|
||
const fixedRows = (
|
||
await client.query(
|
||
fixedSql.replace('JOIN order_items oi ON', `JOIN ${fixture(withR3, 'oi')} ON`),
|
||
['__T2R4__', 'ORD_X', [P1, P2]]
|
||
)
|
||
).rows;
|
||
const fixed = new Map(fixedRows.map((row) => [String(row.prep_id), String(row.our_order_item_id)]));
|
||
const computed = mapPrepRowsToOurItemsForTest(
|
||
[{ orderCode: 'M_A', rows: [{ id: P2, itemName: '牛肉' }] }],
|
||
candidates
|
||
);
|
||
return { candidates: candidates.map((row) => row.id), mapping: new Map([...fixed, ...computed]) };
|
||
};
|
||
|
||
const withR3 = await runAll(true);
|
||
expect(withR3.candidates, 'R2 被 P1 占用必须排除').toEqual([R1, R3]);
|
||
expect(withR3.mapping.get(P1), 'P1 保留原 R2').toBe(R2);
|
||
expect(withR3.mapping.get(P2), 'P2 只能选未占用的 R3').toBe(R3);
|
||
|
||
const withoutR3 = await runAll(false);
|
||
expect(withoutR3.candidates).toEqual([R1]);
|
||
expect(withoutR3.mapping.get(P2), '候选不足时不得硬塞(P2 不配 ⇒ pending)').toBeUndefined();
|
||
} finally {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
await client.end();
|
||
}
|
||
});
|
||
});
|
||
|
||
describe('B-A3:repair 不得把 removed 台账重新挂到活行', () => {
|
||
it('运行时:removed 不参与映射(保持 NULL),缺行 P_M 拿走活行 LIVE', async () => {
|
||
const P_R = 'dddddddd-0001-4000-8000-000000000001';
|
||
const P_M = 'dddddddd-0002-4000-8000-000000000002';
|
||
const LIVE = '11111111-0009-4000-8000-000000000009';
|
||
const captured = installPoolWithPayload(
|
||
[
|
||
{ id: P_R, itemName: '肉片', prepareQty: 1 },
|
||
{ id: P_M, itemName: '肉片', prepareQty: 1 },
|
||
],
|
||
{
|
||
linked: [],
|
||
ledgerStates: [{ prep_id: P_R, disposition: 'removed' }],
|
||
candidates: [{ id: LIVE, item_name: '肉片' }],
|
||
}
|
||
);
|
||
|
||
await repairMissingPrepLedgerRows('BR002');
|
||
|
||
expect(captured.mapping.has(P_R), 'removed 不得被重新映射').toBe(false);
|
||
expect(captured.mapping.get(P_M)).toBe(LIVE);
|
||
expect(captured.cleared, '硬终态也必须清空指针').toBeGreaterThanOrEqual(1);
|
||
});
|
||
|
||
it('recordImportedPrepItems 的 upsert 对硬终态强制指针 NULL', async () => {
|
||
const sqls: string[] = [];
|
||
H.poolQuery.mockImplementation(async (sql: string) => {
|
||
sqls.push(String(sql));
|
||
return { rows: [], rowCount: 1 };
|
||
});
|
||
const { recordImportedPrepItems } = await import('../src/services/mainSystemPrepLedger');
|
||
await recordImportedPrepItems({
|
||
branchCode: 'BR002',
|
||
mainOrderCode: 'M_A',
|
||
supplierCode: null,
|
||
ourOrderCode: 'ORD_X',
|
||
prepRows: [{ id: 'dddddddd-0001-4000-8000-000000000001', itemName: '肉片' }],
|
||
ourItems: [{ id: '11111111-0009-4000-8000-000000000009', item_name: '肉片' }],
|
||
mapping: new Map([['dddddddd-0001-4000-8000-000000000001', '11111111-0009-4000-8000-000000000009']]),
|
||
});
|
||
expect(sqls[0]).toContain("IN ('removed', 'returned', 'cancelled')");
|
||
expect(sqls[0]).toContain('THEN NULL');
|
||
// B-A4/RELATED-1:suspended/completed 的 NULL 只在"本来就没指针"时成立(保留已有有效指针)
|
||
expect(sqls[0]).toMatch(/IN \('suspended', 'completed'\)[\s\S]{0,240}our_order_item_id IS NULL[\s\S]{0,40}THEN NULL/);
|
||
});
|
||
});
|
||
|
||
/* ── R-A 真实 SQL:历史 imported→已退货行 ⇒ 先清 NULL 再重映射 ───────────── */
|
||
|
||
describe('R-A:真实 PG —— 坏对照清 NULL 后活行被真正占用', () => {
|
||
it('P3A imported→OLD(已退货);清坏指针后 P3A→NEW、P3B→NEXT(不再浪费 NEW)', async (ctx) => {
|
||
const P3A = 'ffffffff-0001-4000-8000-000000000001';
|
||
const P3B = 'ffffffff-0002-4000-8000-000000000002';
|
||
const OLD = '11111111-0001-4000-8000-000000000001';
|
||
const NEW = '11111111-0002-4000-8000-000000000002';
|
||
const NEXT = '11111111-0003-4000-8000-000000000003';
|
||
const clearSql = `UPDATE public.main_system_order_import_items li
|
||
SET our_order_item_id = NULL, updated_at = NOW()
|
||
WHERE li.branch_code = $1
|
||
AND li.our_order_code = $3
|
||
AND li.prep_id = ANY($2::uuid[])
|
||
AND li.our_order_item_id IS NOT NULL
|
||
AND NOT EXISTS (
|
||
SELECT 1 FROM order_items oi
|
||
WHERE oi.id = li.our_order_item_id
|
||
AND oi.order_code = $3
|
||
AND COALESCE(oi.is_returned, false) = false
|
||
AND COALESCE(oi.is_extra_dish, false) = false
|
||
)`;
|
||
const candidateSql = `SELECT id::text AS id, item_name
|
||
FROM order_items
|
||
WHERE order_code = $1
|
||
AND COALESCE(is_returned, false) = false
|
||
AND COALESCE(is_extra_dish, false) = false
|
||
AND NOT EXISTS (
|
||
SELECT 1 FROM public.main_system_order_import_items claimed
|
||
WHERE claimed.branch_code = $2
|
||
AND claimed.our_order_item_id = order_items.id
|
||
AND NOT (claimed.prep_id = ANY($3::uuid[]))
|
||
)
|
||
ORDER BY sort_order NULLS LAST, created_at, id`;
|
||
const fixture = `(VALUES
|
||
('${OLD}'::uuid, 'ORD_X'::text, '肉片'::text, 0, '2026-01-01'::timestamptz, true, false),
|
||
('${NEW}'::uuid, 'ORD_X'::text, '肉片'::text, 1, '2026-10-19'::timestamptz, false, false),
|
||
('${NEXT}'::uuid, 'ORD_X'::text, '肉片'::text, 2, '2026-10-19'::timestamptz, false, false)
|
||
) AS order_items(id, order_code, item_name, sort_order, created_at, is_returned, is_extra_dish)`;
|
||
|
||
const client = await loadPgClient();
|
||
if (!client) {
|
||
ctx.skip();
|
||
return;
|
||
}
|
||
try {
|
||
const schemaRes = await client.query(
|
||
`SELECT table_schema FROM information_schema.tables
|
||
WHERE table_name = 'order_items' AND table_schema LIKE 'tenant\\_%' ESCAPE '\\'
|
||
ORDER BY table_schema LIMIT 1`
|
||
);
|
||
const schema = String(schemaRes.rows[0]?.table_schema || '');
|
||
if (!/^tenant_[A-Za-z0-9_]+$/.test(schema)) {
|
||
ctx.skip();
|
||
return;
|
||
}
|
||
await client.query(`SET search_path TO ${schema}`);
|
||
await client.query('BEGIN');
|
||
await client.query(
|
||
`INSERT INTO public.main_system_order_import_items
|
||
(branch_code, main_order_code, prep_id, our_order_code, our_order_item_id, disposition, item_name)
|
||
VALUES ('__T2RA__','M_A',$1::uuid,'ORD_X',$2::uuid,'imported','肉片')`,
|
||
[P3A, OLD]
|
||
);
|
||
|
||
// 修复前:不清坏指针 ⇒ COALESCE 会保留 OLD(活行 NEW 被算给 P3A 却写不回)
|
||
const before = (
|
||
await client.query(`SELECT our_order_item_id::text AS link FROM public.main_system_order_import_items WHERE branch_code='__T2RA__'`)
|
||
).rows[0].link;
|
||
// 新逻辑:清掉指向已退货行的坏对照
|
||
const clearFixture = fixture.replace('AS order_items(', 'AS oi(');
|
||
await client.query(clearSql.replace('FROM order_items oi', `FROM ${clearFixture}`), [
|
||
'__T2RA__',
|
||
[P3A, P3B],
|
||
'ORD_X',
|
||
]);
|
||
const afterClear = (
|
||
await client.query(`SELECT our_order_item_id::text AS link FROM public.main_system_order_import_items WHERE branch_code='__T2RA__'`)
|
||
).rows[0].link;
|
||
|
||
const candidates = (
|
||
await client.query(candidateSql.replace('FROM order_items', `FROM ${fixture}`), ['ORD_X', '__T2RA__', []])
|
||
).rows.map((row) => ({ id: String(row.id), item_name: String(row.item_name || '') }));
|
||
const mapping = mapPrepRowsToOurItemsForTest(
|
||
[
|
||
{
|
||
orderCode: 'M_A',
|
||
rows: [
|
||
{ id: P3A, itemName: '肉片' },
|
||
{ id: P3B, itemName: '肉片' },
|
||
],
|
||
},
|
||
],
|
||
candidates
|
||
);
|
||
|
||
expect(before, '修复前历史坏指针仍是 OLD').toBe(OLD);
|
||
expect(afterClear, '坏对照必须被清 NULL,否则 COALESCE 永远保留旧值').toBeNull();
|
||
expect(candidates.map((row) => row.id)).toEqual([NEW, NEXT]);
|
||
expect(mapping.get(P3A)).toBe(NEW);
|
||
expect(mapping.get(P3B)).toBe(NEXT);
|
||
} finally {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
await client.end();
|
||
}
|
||
});
|
||
});
|
||
|
||
|
||
describe('B-A4:suspended 的既有有效指针必须保留(不得被 repair 清空)', () => {
|
||
it('运行时:suspended 不参与映射但保留原 link,缺行 P_new 只拿未占用的 R_X', async () => {
|
||
const P_susp = 'cccccccc-0001-4000-8000-000000000001';
|
||
const P_new = 'cccccccc-0002-4000-8000-000000000002';
|
||
const R_S = '11111111-0001-4000-8000-000000000001';
|
||
const R_X = '11111111-0002-4000-8000-000000000002';
|
||
const captured = installPoolWithPayload(
|
||
[
|
||
{ id: P_susp, itemName: '肉片', prepareQty: 1 },
|
||
{ id: P_new, itemName: '肉片', prepareQty: 1 },
|
||
],
|
||
{
|
||
linked: [{ prep_id: P_susp, our_order_item_id: R_S }],
|
||
ledgerStates: [{ prep_id: P_susp, disposition: 'suspended' }],
|
||
candidates: [{ id: R_X, item_name: '肉片' }],
|
||
}
|
||
);
|
||
|
||
await repairMissingPrepLedgerRows('BR002');
|
||
|
||
// GAP-1:保留档整行跳过(不重算映射、也不 upsert),原 link 由 DB 保持
|
||
expect(captured.mapping.has(P_susp), 'suspended 不参与映射/写回').toBe(false);
|
||
expect(captured.mapping.get(P_new)).toBe(R_X);
|
||
});
|
||
});
|
||
|
||
/* ── B-A3 真实 SQL:removed 指针被强制清空、不参与映射(无库时跳过) ───────────── */
|
||
|
||
describe('B-A3:真实 PG —— removed 保持 NULL,缺行拿活行', () => {
|
||
it('removed(ptr=OLD) + pending 缺行 ⇒ removed=NULL/不映射;P_M→LIVE;重复 item_removed 无指针可删', async (ctx) => {
|
||
const P_R = 'dddddddd-0001-4000-8000-000000000001';
|
||
const P_M = 'dddddddd-0002-4000-8000-000000000002';
|
||
const OLD = '11111111-0001-4000-8000-000000000001';
|
||
const LIVE = '11111111-0002-4000-8000-000000000002';
|
||
const NEXT = '11111111-0003-4000-8000-000000000003';
|
||
|
||
const nonRevivableSql = `UPDATE public.main_system_order_import_items li
|
||
SET our_order_item_id = NULL, updated_at = NOW()
|
||
WHERE li.branch_code = $1
|
||
AND li.our_order_code = $3
|
||
AND li.prep_id = ANY($2::uuid[])
|
||
AND li.our_order_item_id IS NOT NULL
|
||
AND LOWER(TRIM(COALESCE(li.disposition, ''))) NOT IN ('imported', 'pending', 'reallocated', 'skipped_stockout')`;
|
||
const revivableSql = `UPDATE public.main_system_order_import_items li
|
||
SET our_order_item_id = NULL, updated_at = NOW()
|
||
WHERE li.branch_code = $1
|
||
AND li.our_order_code = $3
|
||
AND li.prep_id = ANY($2::uuid[])
|
||
AND li.our_order_item_id IS NOT NULL
|
||
AND LOWER(TRIM(COALESCE(li.disposition, ''))) IN ('imported', 'pending', 'reallocated', 'skipped_stockout')
|
||
AND NOT EXISTS (
|
||
SELECT 1 FROM order_items oi
|
||
WHERE oi.id = li.our_order_item_id
|
||
AND oi.order_code = $3
|
||
AND COALESCE(oi.is_returned, false) = false
|
||
AND COALESCE(oi.is_extra_dish, false) = false
|
||
)`;
|
||
const candidateSql = `SELECT id::text AS id, item_name
|
||
FROM order_items
|
||
WHERE order_code = $1
|
||
AND COALESCE(is_returned, false) = false
|
||
AND COALESCE(is_extra_dish, false) = false
|
||
AND NOT EXISTS (
|
||
SELECT 1 FROM public.main_system_order_import_items claimed
|
||
WHERE claimed.branch_code = $2
|
||
AND claimed.our_order_item_id = order_items.id
|
||
AND NOT (claimed.prep_id = ANY($3::uuid[]))
|
||
)
|
||
ORDER BY sort_order NULLS LAST, created_at, id`;
|
||
const fixture = `(VALUES
|
||
('${OLD}'::uuid, 'ORD_X'::text, '肉片'::text, 0, '2026-01-01'::timestamptz, true, false),
|
||
('${LIVE}'::uuid, 'ORD_X'::text, '肉片'::text, 1, '2026-10-19'::timestamptz, false, false),
|
||
('${NEXT}'::uuid, 'ORD_X'::text, '肉片'::text, 2, '2026-10-19'::timestamptz, false, false)
|
||
) AS order_items(id, order_code, item_name, sort_order, created_at, is_returned, is_extra_dish)`;
|
||
|
||
const client = await loadPgClient();
|
||
if (!client) {
|
||
ctx.skip();
|
||
return;
|
||
}
|
||
try {
|
||
const schemaRes = await client.query(
|
||
`SELECT table_schema FROM information_schema.tables
|
||
WHERE table_name = 'order_items' AND table_schema LIKE 'tenant\_%' ESCAPE '\'
|
||
ORDER BY table_schema LIMIT 1`
|
||
);
|
||
const schema = String(schemaRes.rows[0]?.table_schema || '');
|
||
if (!/^tenant_[A-Za-z0-9_]+$/.test(schema)) {
|
||
ctx.skip();
|
||
return;
|
||
}
|
||
await client.query(`SET search_path TO ${schema}`);
|
||
await client.query('BEGIN');
|
||
await client.query(
|
||
`INSERT INTO public.main_system_order_import_items
|
||
(branch_code, main_order_code, prep_id, our_order_code, our_order_item_id, disposition)
|
||
VALUES ('__T2BA3__','M_R',$1::uuid,'ORD_X',$2::uuid,'removed'),
|
||
('__T2BA3__','M_M',$3::uuid,'ORD_X',NULL,'pending')`,
|
||
[P_R, OLD, P_M]
|
||
);
|
||
|
||
const fixtureOi = fixture.replace('AS order_items(', 'AS oi(');
|
||
await client.query(nonRevivableSql.replace('FROM order_items oi', `FROM ${fixtureOi}`), [
|
||
'__T2BA3__',
|
||
[P_R, P_M],
|
||
'ORD_X',
|
||
]);
|
||
await client.query(revivableSql.replace('FROM order_items oi', `FROM ${fixtureOi}`), [
|
||
'__T2BA3__',
|
||
[P_R, P_M],
|
||
'ORD_X',
|
||
]);
|
||
const links = (
|
||
await client.query(
|
||
`SELECT prep_id::text AS prep_id, our_order_item_id::text AS link, disposition
|
||
FROM public.main_system_order_import_items WHERE branch_code='__T2BA3__' ORDER BY prep_id`
|
||
)
|
||
).rows;
|
||
const byPrep = new Map(links.map((row) => [String(row.prep_id), row]));
|
||
|
||
const stateRows = (
|
||
await client.query(
|
||
`SELECT prep_id::text AS prep_id, disposition FROM public.main_system_order_import_items
|
||
WHERE branch_code='__T2BA3__' AND our_order_code='ORD_X' AND prep_id = ANY($1::uuid[])`,
|
||
[[P_R, P_M]]
|
||
)
|
||
).rows;
|
||
const revivable = new Set(['imported', 'pending', 'reallocated', 'skipped_stockout']);
|
||
const mappingRows = stateRows.filter((row) => revivable.has(String(row.disposition).toLowerCase()));
|
||
const candidates = (
|
||
await client.query(candidateSql.replace('FROM order_items', `FROM ${fixture}`), ['ORD_X', '__T2BA3__', []])
|
||
).rows.map((row) => ({ id: String(row.id), item_name: String(row.item_name || '') }));
|
||
const mapping = mapPrepRowsToOurItemsForTest(
|
||
[{ orderCode: 'M_M', rows: mappingRows.map((row) => ({ id: String(row.prep_id), itemName: '肉片' })) }],
|
||
candidates
|
||
);
|
||
|
||
expect(byPrep.get(P_R)).toMatchObject({ link: null, disposition: 'removed' });
|
||
expect(byPrep.get(P_M).link).toBeNull();
|
||
expect(mappingRows.map((row) => String(row.prep_id))).toEqual([P_M]);
|
||
expect(mapping.get(P_R), 'removed 不参与映射').toBeUndefined();
|
||
expect(mapping.get(P_M)).toBe(LIVE);
|
||
// 重复 item_removed:P_R 无指针 ⇒ 不会命中/删除活行(applyItemNoLongerOurs 走 already_gone)
|
||
expect(byPrep.get(P_R).link).toBeNull();
|
||
} finally {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
await client.end();
|
||
}
|
||
});
|
||
});
|
||
|
||
/* ── B-A4 真实 SQL:suspended 有效指针保留,follow 不删错行(无库时跳过) ───────────── */
|
||
|
||
describe('B-A4:真实 PG —— suspended 保留 R_S,缺行拿 R_X', () => {
|
||
it('repair 后 suspended 仍指 R_S;同单同名缺行 P_new 只配 R_X;follow 删 R_S 不误删 R_X', async (ctx) => {
|
||
const P_susp = 'cccccccc-0001-4000-8000-000000000001';
|
||
const P_new = 'cccccccc-0002-4000-8000-000000000002';
|
||
const R_S = '11111111-0001-4000-8000-000000000001';
|
||
const R_X = '11111111-0002-4000-8000-000000000002';
|
||
const R_Y = '11111111-0003-4000-8000-000000000003';
|
||
|
||
const invalidLinkSql = `NOT EXISTS (
|
||
SELECT 1 FROM order_items oi
|
||
WHERE oi.id = li.our_order_item_id
|
||
AND oi.order_code = $3
|
||
AND COALESCE(oi.is_returned, false) = false
|
||
AND COALESCE(oi.is_extra_dish, false) = false
|
||
)`;
|
||
const clear = (condition: string) => `UPDATE public.main_system_order_import_items li
|
||
SET our_order_item_id = NULL, updated_at = NOW()
|
||
WHERE li.branch_code = $1 AND li.our_order_code = $3
|
||
AND li.prep_id = ANY($2::uuid[]) AND li.our_order_item_id IS NOT NULL
|
||
AND ${condition}`;
|
||
const candidateSql = `SELECT id::text AS id, item_name
|
||
FROM order_items
|
||
WHERE order_code = $1
|
||
AND COALESCE(is_returned, false) = false
|
||
AND COALESCE(is_extra_dish, false) = false
|
||
AND NOT EXISTS (
|
||
SELECT 1 FROM public.main_system_order_import_items claimed
|
||
WHERE claimed.branch_code = $2
|
||
AND claimed.our_order_item_id = order_items.id
|
||
AND NOT (claimed.prep_id = ANY($3::uuid[]))
|
||
)
|
||
ORDER BY sort_order NULLS LAST, created_at, id`;
|
||
const fixture = (alias: 'order_items' | 'oi') => `(VALUES
|
||
('${R_S}'::uuid, 'ORD_X'::text, '肉片'::text, 0, '2026-01-01'::timestamptz, false, false),
|
||
('${R_X}'::uuid, 'ORD_X'::text, '肉片'::text, 1, '2026-10-19'::timestamptz, false, false),
|
||
('${R_Y}'::uuid, 'ORD_X'::text, '肉片'::text, 2, '2026-10-19'::timestamptz, false, false)
|
||
) AS ${alias}(id, order_code, item_name, sort_order, created_at, is_returned, is_extra_dish)`;
|
||
|
||
const client = await loadPgClient();
|
||
if (!client) {
|
||
ctx.skip();
|
||
return;
|
||
}
|
||
try {
|
||
const schemaRes = await client.query(
|
||
`SELECT table_schema FROM information_schema.tables
|
||
WHERE table_name = 'order_items' AND table_schema LIKE 'tenant\\_%' ESCAPE '\\'
|
||
ORDER BY table_schema LIMIT 1`
|
||
);
|
||
const schema = String(schemaRes.rows[0]?.table_schema || '');
|
||
if (!/^tenant_[A-Za-z0-9_]+$/.test(schema)) {
|
||
ctx.skip();
|
||
return;
|
||
}
|
||
await client.query(`SET search_path TO ${schema}`);
|
||
await client.query('BEGIN');
|
||
await client.query(
|
||
`INSERT INTO public.main_system_order_import_items
|
||
(branch_code, main_order_code, prep_id, our_order_code, our_order_item_id, disposition)
|
||
VALUES ('__T2BA4__','M_S',$1::uuid,'ORD_X',$2::uuid,'suspended'),
|
||
('__T2BA4__','M_N',$3::uuid,'ORD_X',NULL,'pending')`,
|
||
[P_susp, R_S, P_new]
|
||
);
|
||
|
||
await client.query(clear(`LOWER(TRIM(COALESCE(li.disposition, ''))) IN ('removed', 'returned', 'cancelled')`).replace('FROM order_items oi', `FROM ${fixture('oi')}`), ['__T2BA4__', [P_susp, P_new], 'ORD_X']);
|
||
await client.query(clear(`LOWER(TRIM(COALESCE(li.disposition, ''))) IN ('suspended', 'completed') AND ${invalidLinkSql}`).replace('FROM order_items oi', `FROM ${fixture('oi')}`), ['__T2BA4__', [P_susp, P_new], 'ORD_X']);
|
||
await client.query(clear(`LOWER(TRIM(COALESCE(li.disposition, ''))) IN ('imported', 'pending', 'reallocated', 'skipped_stockout') AND ${invalidLinkSql}`).replace('FROM order_items oi', `FROM ${fixture('oi')}`), ['__T2BA4__', [P_susp, P_new], 'ORD_X']);
|
||
|
||
const links = (
|
||
await client.query(
|
||
`SELECT prep_id::text AS prep_id, our_order_item_id::text AS link, disposition
|
||
FROM public.main_system_order_import_items WHERE branch_code='__T2BA4__'`
|
||
)
|
||
).rows;
|
||
const byPrep = new Map(links.map((row) => [String(row.prep_id), row]));
|
||
expect(byPrep.get(P_susp)).toMatchObject({ link: R_S, disposition: 'suspended' });
|
||
|
||
const stateRows = (
|
||
await client.query(
|
||
`SELECT prep_id::text AS prep_id, disposition FROM public.main_system_order_import_items
|
||
WHERE branch_code='__T2BA4__' AND prep_id = ANY($1::uuid[])`,
|
||
[[P_susp, P_new]]
|
||
)
|
||
).rows;
|
||
const revivable = new Set(['imported', 'pending', 'reallocated', 'skipped_stockout']);
|
||
const mappingRows = stateRows.filter((row) => revivable.has(String(row.disposition).toLowerCase()));
|
||
const candidates = (
|
||
await client.query(candidateSql.replace('FROM order_items', `FROM ${fixture('order_items')}`), ['ORD_X', '__T2BA4__', []])
|
||
).rows.map((row) => ({ id: String(row.id), item_name: String(row.item_name || '') }));
|
||
const mapping = mapPrepRowsToOurItemsForTest(
|
||
[{ orderCode: 'M_N', rows: mappingRows.map((row) => ({ id: String(row.prep_id), itemName: '肉片' })) }],
|
||
candidates
|
||
);
|
||
expect(candidates.map((row) => row.id), 'R_S 仍被 suspended 占用,不得回池').toEqual([R_X, R_Y]);
|
||
expect(mapping.get(P_new)).toBe(R_X);
|
||
// follow 只处理 suspended 自己的指针(R_S);R_X 已属于 P_new,不会被误删
|
||
expect(byPrep.get(P_susp).link).toBe(R_S);
|
||
} finally {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
await client.end();
|
||
}
|
||
});
|
||
});
|