import { readFileSync } from 'node:fs'; import { describe, expect, it } from 'vitest'; /** * 订单商品成本的「分类」以订单行分类为基准(开发者 2026-09-22 批准)。 * * 旧实现取 `skus.category_code`(商品主数据),而主数据会被录单手动选分类回写, * 导致同一商品在本页与订单详情显示不一致,且按品类筛选查不到。 * 见 docs/design/20260922-sku-cost-category-from-order-line.md */ const src = readFileSync( new URL('../src/services/marginQueryService.ts', import.meta.url), 'utf8' ); const sliceFn = (name: string) => { const start = src.indexOf(`export async function ${name}(`); expect(start, `未找到 ${name}`).toBeGreaterThan(-1); const next = src.indexOf('\nexport ', start + 10); return src.slice(start, next === -1 ? undefined : next); }; describe('sku cost category follows order line', () => { const paged = sliceFn('getSkuDirectCostsPaged'); const lines = sliceFn('getSkuDirectCostLinesPaged'); it('列表:订单行分类进入聚合,代表分类 = 数量占比最大', () => { expect(paged).toContain('oi.category_code AS line_category_code'); expect(paged).toContain('cat_qty AS ('); expect(paged).toContain( 'SELECT DISTINCT ON (sku_code, is_extra_dish, cost_bucket, is_warehouse_processing)' ); expect(paged).toContain('cat_qty DESC, line_category_code'); expect(paged).toContain('line_category_code AS rep_category_code'); }); it('列表:分类名与分类筛选都走 rep_cat(订单行口径),不再用 skus.category_code', () => { expect(paged).toContain('LEFT JOIN rep_cat rc'); expect(paged).toContain('WHERE c.category_code = rc.rep_category_code'); expect(paged).toContain('AND rc.rep_category_code = ANY('); expect(paged).not.toContain('WHERE c.category_code = s.category_code'); expect(paged).not.toContain('AND s.category_code = ANY('); }); it('列表:表头两个桶的合计仍不套来源过滤(前端两张表头共用一个 state)', () => { const lt = paged.slice(paged.indexOf('ledger_totals AS (')); const body = lt.slice(0, lt.indexOf('ranked AS (')); expect(body).toContain("WHEN t.cost_bucket = 'self'"); expect(body).toContain("WHEN t.cost_bucket = 'supplier'"); // 不得引入 sourceFilter 条件,否则其中一张表头会变 0 expect(body).not.toContain('sourceFilter'); expect(body).toContain('WHERE NOT sc.is_warehouse_processing'); }); it('导出明细:一行一订单,分类与筛选都用该行 order_items.category_code', () => { expect(lines).toContain('WHERE c.category_code = oi.category_code'); expect(lines).toContain('AND oi.category_code = ANY('); expect(lines).not.toContain('WHERE c.category_code = s.category_code'); expect(lines).not.toContain('AND s.category_code = ANY('); }); });