2026-10-21 开发者看「分公司管理 → 绑定关系」时,两家供应商显示「绑定时间 19:19:17」, 误以为刚绑定;实际是每 15 分钟绑定回读的刷新时间(upsert 每次同步都写 bound_at=NOW()), 真实绑定时间早于该值,也误导了"主系统只绑 1 家、我们显示 2 家"的排查。 改法:UPSERT 冲突时按原行状态决定 bound_at—— - 原行 status='active' 且 branch_code 未变(同一绑定被回读/回调刷新)⇒ 保留原 bound_at; - 原行已 unbound(解绑后再绑)或 branch_code 变了(改绑)⇒ 用本次新时间。 无迁移、无接口变更、无前端文案改动;历史已被刷掉的时间无法还原(需另行批准的存量回填)。 验证:branchAccessCode/branchBindingSync/bindingAutoPullGuard 三文件 46 用例全过; typecheck 通过;后端全量 3 failed/574 passed(红均为既有)。见 docs/design/20261022-绑定时间只记首次绑定.md。未部署(生产发布需单独命令)。
283 lines
12 KiB
TypeScript
283 lines
12 KiB
TypeScript
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||
|
||
/**
|
||
* 分公司「接入编码」与绑定路由(2026-10-27 设计,验收项 V1–V8 的可机检部分)。
|
||
*
|
||
* 钉住四件事(这几条错了就是**串单/漏单**,比报错更难查):
|
||
* ① 编码形态固定(`SC` + 10 位、无易混字符);
|
||
* ② 入站路由的**判定顺序**:我方编码 → 精确 (主系统分公司+供应商) → 唯一绑定 → 通配 → 拒收;
|
||
* ③ 「该主系统分公司有行但已解绑」必须 `not_bound`(尊重显式解绑,不得回落成"唯一绑定");
|
||
* ④ 多绑定且不知分公司 ⇒ **ambiguous 拒收**(宁可漏一单,也不张冠李戴)。
|
||
*
|
||
* 设计:docs/design/20261027-分公司接入编码与主系统供应商绑定.md §3.3 / §9
|
||
*/
|
||
|
||
const query = vi.hoisted(() => vi.fn());
|
||
vi.mock('../src/db', () => ({
|
||
pool: { query: (...args: unknown[]) => query(...args), connect: vi.fn() },
|
||
getRawPoolQuery: () => query,
|
||
}));
|
||
|
||
const {
|
||
generateUniqueBranchAccessCode,
|
||
isBranchAccessCode,
|
||
resolveOurBranchByBinding,
|
||
upsertBinding,
|
||
resolveSupplierCodeForPrep,
|
||
} = await import('../src/services/branchAccessCode');
|
||
|
||
/** 让 pool.query 按 SQL 关键字返回预设结果(顺序敏感:先查分支编码,再查绑定行,再查台账) */
|
||
function mockQueries(handlers: Array<(sql: string, params: unknown[]) => unknown>) {
|
||
query.mockImplementation(async (sql: string, params: unknown[]) => {
|
||
for (const handler of handlers) {
|
||
const result = handler(String(sql), params ?? []);
|
||
if (result !== undefined) return result;
|
||
}
|
||
throw new Error(`未预期的 SQL:${String(sql).slice(0, 80)}`);
|
||
});
|
||
}
|
||
|
||
beforeEach(() => {
|
||
query.mockReset();
|
||
});
|
||
|
||
describe('接入编码形态(V1)', () => {
|
||
it('合法形态:SC + 10 位、字符集不含 0/O/1/I/L', () => {
|
||
expect(isBranchAccessCode('SC7K3Q9M2XTP')).toBe(true);
|
||
expect(isBranchAccessCode('sc7k3q9m2xtp')).toBe(true);
|
||
});
|
||
|
||
it('非法:长度不对、前缀不对、含易混字符、空值', () => {
|
||
expect(isBranchAccessCode('SC7K3Q9M2X')).toBe(false);
|
||
expect(isBranchAccessCode('SC7K3Q9M2XTPZ')).toBe(false);
|
||
expect(isBranchAccessCode('XX7K3Q9M2XT')).toBe(false);
|
||
expect(isBranchAccessCode('SC7K3Q9M2X0')).toBe(false);
|
||
expect(isBranchAccessCode('SC7K3Q9M2XO')).toBe(false);
|
||
expect(isBranchAccessCode('')).toBe(false);
|
||
expect(isBranchAccessCode(null)).toBe(false);
|
||
});
|
||
});
|
||
|
||
describe('编码生成:撞码只会重试,退役码不复用', () => {
|
||
it('查重同时覆盖 branches 与绑定历史(分公司删了码也不回收)', async () => {
|
||
const sqls: string[] = [];
|
||
let calls = 0;
|
||
query.mockImplementation(async (sql: string) => {
|
||
sqls.push(String(sql));
|
||
if (String(sql).includes('access_code = $1')) {
|
||
calls += 1;
|
||
// 第一次"撞码" ⇒ 必须重试;第二次放行
|
||
return calls === 1 ? { rowCount: 1, rows: [{ '?column?': 1 }] } : { rowCount: 0, rows: [] };
|
||
}
|
||
throw new Error(`未预期的 SQL:${String(sql).slice(0, 60)}`);
|
||
});
|
||
const code = await generateUniqueBranchAccessCode();
|
||
expect(isBranchAccessCode(code), `生成的编码应合法:${code}`).toBe(true);
|
||
expect(calls, '第一次撞码后必须重试一次').toBe(2);
|
||
expect(sqls[0]).toContain('public.branches');
|
||
expect(sqls[0], '必须同时查绑定历史,否则删掉分公司后编码会被回收').toContain('public.main_supplier_bindings');
|
||
});
|
||
|
||
it('连续撞码 20 次 ⇒ 抛错(不返回可疑编码)', async () => {
|
||
query.mockImplementation(async () => ({ rowCount: 1, rows: [{ '?column?': 1 }] }));
|
||
await expect(generateUniqueBranchAccessCode()).rejects.toThrow('连续 20 次撞唯一键');
|
||
});
|
||
});
|
||
|
||
describe('入站路由(V2–V6)', () => {
|
||
it('① 带了我们的 subsystem_code ⇒ 直接按我方编码定位(最稳)', async () => {
|
||
mockQueries([
|
||
(sql) => (sql.includes('FROM public.branches WHERE access_code') ? { rows: [{ branch_code: 'BR007' }] } : undefined),
|
||
]);
|
||
const r = await resolveOurBranchByBinding({ subsystemCode: 'SC7K3Q9M2XTP', supplierCode: 'SUP1' });
|
||
expect(r).toEqual({ ok: true, branchCode: 'BR007', binding: null, via: 'access_code' });
|
||
});
|
||
|
||
it('编码不认识 ⇒ unknown_access_code(单列一个原因:真机上 99% 是抄错一位)', async () => {
|
||
mockQueries([(sql) => (sql.includes('FROM public.branches WHERE access_code') ? { rows: [] } : undefined)]);
|
||
const r = await resolveOurBranchByBinding({ subsystemCode: 'SCZZZZZZZZZZ', supplierCode: 'SUP1' });
|
||
expect(r.ok).toBe(false);
|
||
if (!r.ok) expect(r.reason).toBe('unknown_access_code');
|
||
});
|
||
|
||
it('② 精确命中 (主系统分公司 + 供应商)', async () => {
|
||
mockQueries([
|
||
() => ({
|
||
rows: [
|
||
{ branch_code: 'BR007', main_branch_code: 'BR002', main_supplier_code: 'SUP1', status: 'active' },
|
||
{ branch_code: 'BR008', main_branch_code: 'BR003', main_supplier_code: 'SUP1', status: 'active' },
|
||
],
|
||
}),
|
||
]);
|
||
const r = await resolveOurBranchByBinding({ supplierCode: 'SUP1', mainBranchCode: 'BR003' });
|
||
expect(r.ok).toBe(true);
|
||
if (r.ok) {
|
||
expect(r.branchCode).toBe('BR008');
|
||
expect(r.via).toBe('exact');
|
||
}
|
||
});
|
||
|
||
it('③ 该主系统分公司有行、但已解绑 ⇒ not_bound(不得回落成"唯一绑定")', async () => {
|
||
mockQueries([
|
||
() => ({
|
||
rows: [
|
||
{ branch_code: 'BR007', main_branch_code: 'BR002', main_supplier_code: 'SUP1', status: 'unbound' },
|
||
{ branch_code: 'BR008', main_branch_code: 'BR003', main_supplier_code: 'SUP1', status: 'active' },
|
||
],
|
||
}),
|
||
]);
|
||
const r = await resolveOurBranchByBinding({ supplierCode: 'SUP1', mainBranchCode: 'BR002' });
|
||
expect(r.ok).toBe(false);
|
||
if (!r.ok) expect(r.reason).toBe('not_bound');
|
||
});
|
||
|
||
it('④ 分公司未知、该供应商只有一家我方分公司在绑 ⇒ 唯一命中', async () => {
|
||
mockQueries([
|
||
() => ({
|
||
rows: [{ branch_code: 'BR007', main_branch_code: 'BR002', main_supplier_code: 'SUP1', status: 'active' }],
|
||
}),
|
||
]);
|
||
const r = await resolveOurBranchByBinding({ supplierCode: 'SUP1' });
|
||
expect(r.ok).toBe(true);
|
||
if (r.ok) {
|
||
expect(r.branchCode).toBe('BR007');
|
||
expect(r.via).toBe('unique_supplier');
|
||
}
|
||
});
|
||
|
||
it('⑤ 分公司未知 + 多家在绑 ⇒ ambiguous **拒收**(不猜)', async () => {
|
||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
|
||
mockQueries([
|
||
() => ({
|
||
rows: [
|
||
{ branch_code: 'BR007', main_branch_code: 'BR002', main_supplier_code: 'SUP1', status: 'active' },
|
||
{ branch_code: 'BR008', main_branch_code: 'BR003', main_supplier_code: 'SUP1', status: 'active' },
|
||
],
|
||
}),
|
||
]);
|
||
const r = await resolveOurBranchByBinding({ supplierCode: 'SUP1' });
|
||
expect(r.ok).toBe(false);
|
||
if (!r.ok) expect(r.reason).toBe('ambiguous');
|
||
warn.mockRestore();
|
||
});
|
||
|
||
it('通配行(`*`)在精确行缺失时兜底;完全没绑 ⇒ not_bound;无供应商编码 ⇒ missing_supplier_code', async () => {
|
||
mockQueries([
|
||
() => ({
|
||
rows: [{ branch_code: 'BR007', main_branch_code: '*', main_supplier_code: 'SUP1', status: 'active' }],
|
||
}),
|
||
]);
|
||
const wild = await resolveOurBranchByBinding({ supplierCode: 'SUP1', mainBranchCode: 'BR009' });
|
||
expect(wild.ok).toBe(true);
|
||
if (wild.ok) expect(wild.via).toBe('wildcard');
|
||
|
||
query.mockReset();
|
||
mockQueries([() => ({ rows: [] })]);
|
||
const none = await resolveOurBranchByBinding({ supplierCode: 'SUP1', mainBranchCode: 'BR009' });
|
||
expect(none.ok).toBe(false);
|
||
if (!none.ok) expect(none.reason).toBe('not_bound');
|
||
|
||
query.mockReset();
|
||
mockQueries([]);
|
||
const missing = await resolveOurBranchByBinding({ supplierCode: '' });
|
||
expect(missing.ok).toBe(false);
|
||
if (!missing.ok) expect(missing.reason).toBe('missing_supplier_code');
|
||
});
|
||
});
|
||
|
||
describe('绑定登记:改绑要留痕(V7)', () => {
|
||
it('同一 (主系统分公司+供应商) 改绑到另一家 ⇒ 旧行转 unbound 并记 note', async () => {
|
||
const calls: Array<{ sql: string; params: unknown[] }> = [];
|
||
mockQueries([
|
||
(sql, params) => {
|
||
calls.push({ sql, params });
|
||
if (sql.includes('SELECT branch_code FROM public.main_supplier_bindings')) {
|
||
return { rows: [{ branch_code: 'BR007' }] };
|
||
}
|
||
if (sql.includes('UPDATE public.main_supplier_bindings')) return { rowCount: 1 };
|
||
if (sql.includes('INSERT INTO public.main_supplier_bindings')) return { rowCount: 1 };
|
||
return undefined;
|
||
},
|
||
]);
|
||
const result = await upsertBinding({
|
||
branchCode: 'BR008',
|
||
accessCode: 'sc7k3q9m2xtp',
|
||
mainBranchCode: 'br002',
|
||
mainSupplierCode: 'sup1',
|
||
source: 'main_push',
|
||
});
|
||
expect(result.previousBranchCode).toBe('BR007');
|
||
const unbind = calls.find((c) => c.sql.includes('UPDATE public.main_supplier_bindings') && c.sql.includes("status = 'unbound'"));
|
||
expect(unbind, '必须先把旧行转 unbound(留痕)').toBeTruthy();
|
||
const insert = calls.find((c) => c.sql.includes('INSERT INTO public.main_supplier_bindings'));
|
||
expect(insert?.params[1]).toBe('SC7K3Q9M2XTP');
|
||
expect(insert?.params[2]).toBe('BR002');
|
||
expect(insert?.params[3]).toBe('SUP1');
|
||
// 改绑后原行应保留(不删数据):只 UPDATE 状态,不 DELETE
|
||
expect(calls.some((c) => c.sql.includes('DELETE FROM public.main_supplier_bindings'))).toBe(false);
|
||
});
|
||
});
|
||
|
||
describe('绑定时间 = 首次绑定时间(回读刷新不得改写)', () => {
|
||
it('UPSERT 对"原行仍 active 且分公司未变"保留原 bound_at;解绑再绑/改绑才用新时间', async () => {
|
||
const calls: Array<{ sql: string; params: unknown[] }> = [];
|
||
mockQueries([
|
||
(sql, params) => {
|
||
calls.push({ sql, params });
|
||
if (sql.includes('SELECT branch_code FROM public.main_supplier_bindings')) return { rows: [] };
|
||
if (sql.includes('INSERT INTO public.main_supplier_bindings')) return { rowCount: 1 };
|
||
return undefined;
|
||
},
|
||
]);
|
||
await upsertBinding({
|
||
branchCode: 'BR002',
|
||
accessCode: 'SCQEM2X7B6P5',
|
||
mainBranchCode: 'BR003',
|
||
mainSupplierCode: 'SUP37831443',
|
||
source: 'main_pull',
|
||
});
|
||
const insert = calls.find((c) => c.sql.includes('INSERT INTO public.main_supplier_bindings'));
|
||
expect(insert, '必须走到 UPSERT').toBeTruthy();
|
||
const sql = String(insert!.sql);
|
||
// 关键:不再无条件 bound_at = NOW(),而是按"原行状态/分公司"决定
|
||
expect(sql).not.toMatch(/bound_at\s*=\s*NOW\(\)\s*,\s*unbound_at/);
|
||
expect(sql).toContain('bound_at = CASE');
|
||
expect(sql).toContain("WHEN public.main_supplier_bindings.status = 'active'");
|
||
expect(sql).toContain('public.main_supplier_bindings.branch_code = EXCLUDED.branch_code');
|
||
expect(sql, '已绑定的行回读刷新时必须沿用原 bound_at').toContain(
|
||
'THEN public.main_supplier_bindings.bound_at'
|
||
);
|
||
expect(sql, '解绑再绑/改绑时必须用本次新时间').toContain('ELSE EXCLUDED.bound_at');
|
||
});
|
||
});
|
||
|
||
describe('出站 supplier_code 解析(接入编码 ≠ 对方 supplier_code)', () => {
|
||
it('优先取行级台账的 main_supplier_code', async () => {
|
||
mockQueries([
|
||
(sql) =>
|
||
sql.includes('FROM public.main_system_order_import_items')
|
||
? { rows: [{ main_supplier_code: 'SUP_F' }] }
|
||
: undefined,
|
||
]);
|
||
expect(await resolveSupplierCodeForPrep({ branchCode: 'BR007', prepId: 'p1' })).toBe('SUP_F');
|
||
});
|
||
|
||
it('台账没有 ⇒ 退该分公司唯一生效绑定;多于一条或没有 ⇒ null(不猜)', async () => {
|
||
mockQueries([
|
||
(sql) => (sql.includes('FROM public.main_system_order_import_items') ? { rows: [] } : undefined),
|
||
(sql) =>
|
||
sql.includes('FROM public.main_supplier_bindings')
|
||
? { rows: [{ branch_code: 'BR007', access_code: 'SC7K3Q9M2XTP', main_branch_code: '*', main_supplier_code: 'SUP_ONLY', status: 'active', source: 'manual', bound_at: new Date(), unbound_at: null }] }
|
||
: undefined,
|
||
]);
|
||
expect(await resolveSupplierCodeForPrep({ branchCode: 'BR007', prepId: 'p1' })).toBe('SUP_ONLY');
|
||
|
||
query.mockReset();
|
||
mockQueries([
|
||
(sql) => (sql.includes('FROM public.main_system_order_import_items') ? { rows: [] } : undefined),
|
||
(sql) => (sql.includes('FROM public.main_supplier_bindings') ? { rows: [] } : undefined),
|
||
]);
|
||
expect(await resolveSupplierCodeForPrep({ branchCode: 'BR007', prepId: 'p1' })).toBeNull();
|
||
});
|
||
});
|