import { describe, expect, it } from 'vitest'; import { readFileSync } from 'node:fs'; import path from 'node:path'; import { catalogSkuBySpecJoin } from '../src/services/catalogSkuBySpec'; /** * 「没有 SKU 编码时按**品名**反查 SKU」必须**规格消歧 + 多义拒绝猜测**(2026-10-16)。 * * 背景(真库复现):商品主数据里同名不同规格是两行;原实现是普通 JOIN 只按品名匹配、不看规格, * 行上没有 SKU 时会把「客户要 1箱24瓶」的单扣到「1箱12瓶」那个 SKU 的库存(静默扣错)。 * 现状:口径收进 `catalogSkuBySpecJoin` 唯一实现,5 处调用点全部替换。 */ const readSrc = (rel: string) => readFileSync(path.join(__dirname, '../src/services', rel), 'utf8'); const fragment = readSrc('catalogSkuBySpec.ts'); describe('catalogSkuBySpecJoin:按品名兜底取 SKU 的唯一实现', () => { it('① 有规格时:先按 public.norm_spec 消歧(与抵扣选批次同一份归一实现)', () => { const sql = catalogSkuBySpecJoin({ nameExpr: 'pi.item_name', specExpr: 'oi.spec' }); expect(sql).toContain('public.norm_spec(c.spec) IS NOT DISTINCT FROM public.norm_spec(oi.spec)'); expect(sql).toContain('count(*) FILTER (WHERE'); expect(fragment).toContain('public.norm_spec'); // 不许引入第二份归一实现 expect(fragment).not.toMatch(/lower\(|TRIM\(c\.spec\)/); }); it('② 多义就拒绝猜测:唯一无歧义才回值,否则 NULL', () => { const withSpec = catalogSkuBySpecJoin({ nameExpr: 'pi.item_name', specExpr: 'oi.spec' }); expect(withSpec).toContain('WHEN count(*) = 1 THEN min(c.code)'); expect(withSpec).toContain('ELSE NULL'); // 没有规格可依据时(如 inspections 没有 spec 列)⇒ 只做"同名唯一才用" const noSpec = catalogSkuBySpecJoin({ nameExpr: 'i.item_name' }); expect(noSpec).not.toContain('norm_spec'); expect(noSpec).toContain('WHEN count(*) = 1 THEN min(c.code)'); expect(noSpec).toContain('ELSE NULL'); // 默认别名保持 catalog ⇒ 老消费者代码不用改 expect(noSpec).toContain(') catalog ON TRUE'); expect(catalogSkuBySpecJoin({ nameExpr: 'pi.item_name', alias: 'catalog_fb' })).toContain(') catalog_fb ON TRUE'); }); it('③ 五处调用点全部改用唯一实现,且旧"只按品名"的 JOIN 不许残留', () => { const outbound = readSrc('inventoryOutboundService.ts'); const picking = readSrc('pickingService.ts'); expect((outbound.match(/catalogSkuBySpecJoin\(/g) || []).length).toBe(3); expect((picking.match(/catalogSkuBySpecJoin\(/g) || []).length).toBe(2); for (const src of [outbound, picking]) { expect(src).toContain("from './catalogSkuBySpec'"); // 旧写法:普通 JOIN + 只按品名(同名多行会取错、还会让外层行翻倍) expect(src).not.toContain('LEFT JOIN product_catalog catalog ON catalog.item_type = \'product\'\n' + ' AND TRIM(catalog.name) = TRIM(pi.item_name)'); expect(src).not.toMatch(/LEFT JOIN product_catalog catalog ON catalog\.item_type = 'product'\s*\n\s*AND TRIM\(catalog\.name\) = TRIM\(/); } // 第五处(标签/区域)保留了"按码直配",并把兜底列并进 COALESCE expect(picking).toContain('catalog_fb.code'); expect(picking).toContain("AND catalog.code = COALESCE(NULLIF(TRIM(pi.sku_code), ''), NULLIF(TRIM(oi.sku_code), ''))"); }); });