Files
SupplierSystem/server/tests/stockCoverBatchQuery.test.ts
T
Ubuntu 65d56ee988 feat(抵扣批次): 列表「库存抵扣:…」点开看已抵扣批次明细(几号入库/生产日期/保质期/区域/抵扣多少)
开发者:「还有将已经被抵扣的批次展示出来呀 —— 几号入库的、生产日期、保质期、区域、
抵扣了多少都需要展示的」。展示面当轮确认:订单列表那行点开弹窗。

- 新增只读接口 GET /orders/:orderCode/stock-cover-batches(鉴权 + 委派,路由零 SQL),
  权限与 batch-reports/quality-report-files 同一套
- 批次来源①事实:picking_items.outbound_batches(抵扣写的 FIFO 计划 / 分拣选的批次)
  → source=plan;②无计划时按先进先出现算(ORDER BY created_at ASC, expiry_date ASC NULLS FIRST,
  与 stockCoverBatchPlanService.loadFifoBatches 逐字一致,有源码级守卫)→ source=fifo
- 字段:批次号 / 抵扣数量 / 入库日期 / 生产日期 / 保质期效期 / 区域;只列已抵扣且未退货的行;
  批次元数据从 inventory 现查(同一 batch_no 跨 SKU 重名 ⇒ 键带 sku_code)
- 前端:新弹窗 OrderStockCoverBatchesModal(加载/失败/空态齐、generation+订单号丢弃过期响应);
  列表那行有权限才可点且 stopPropagation(否则连带打开详情),无权限退回原文字
- 不新增界面文案:标题与字段标签全部复用既有词条(orders.list.inventoryOffset /
  inventory.inboundDate / inventory.col.prodDate / inventory.col.expiry / picking.batch.noZone 等),
  有契约测试逐键校验三语存在、且弹窗代码无硬编码中文
- 真库实测:纯抵扣单 ORD_API_20261013_BR003_0001 抄手皮×8 → STK202610118WEOS7
  (入库 2026-10-11 · 生产 2026-10-08 · 效期 2026-10-15 · 冷库A)source=fifo;
  有计划单 ORD_API_20261012_BR003_0002 三行 source=plan,批次/数量与库里逐字一致
- 设计文档:docs/design/20261013-订单抵扣批次明细.md
2026-10-13 10:11:38 +08:00

200 lines
8.4 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 { readFileSync } from 'fs';
import path from 'path';
/**
* 「这一单已经抵扣了哪些批次」(2026-10-13 开发者要求):
* 列表那行「库存抵扣:…」点开 ⇒ 几号入库 / 生产日期 / 保质期 / 区域 / 抵扣了多少。
*
* 这里钉住做反就要返工的四件事:
* ① **FIFO 口径不许漂**:无批次计划时的兜底顺序必须与 `stockCoverBatchPlanService.loadFifoBatches`
* **逐字一致**(`ORDER BY created_at ASC, expiry_date ASC NULLS FIRST`)——
* 漂了就会出现"界面说要扣这批、实际扣的是那批";
* ② **只读**:新模块不许出现 UPDATE / INSERT / DELETE(扣库、写计划、写流水都不许在这里干);
* ③ **事实优先**:库里已有批次事实(`picking_items.outbound_batches`)时按事实走(`source='plan'`),
* **绝不能**再用现算的 FIFO 覆盖它(库存后来变了,计划才是当初的凭证);
* ④ 路由只鉴权 + 委派(权限集合与 `batch-reports` 一致),不写 SQL。
*/
const query = vi.hoisted(() => vi.fn());
vi.mock('../src/db', () => ({
pool: { query: (...args: unknown[]) => query(...args) },
}));
import { listStockCoverBatches } from '../src/services/stockCoverBatchQueryService';
const serviceSrc = readFileSync(
path.join(__dirname, '../src/services/stockCoverBatchQueryService.ts'),
'utf8'
);
const planSrc = readFileSync(
path.join(__dirname, '../src/services/stockCoverBatchPlanService.ts'),
'utf8'
);
const routeSrc = readFileSync(
path.join(__dirname, '../src/modules/workflow/routes/orderRoutes.ts'),
'utf8'
);
const FIFO_ORDER_BY = 'ORDER BY created_at ASC, expiry_date ASC NULLS FIRST';
/** 取出 GET /orders/:orderCode/stock-cover-batches 这一个 handler 的源码片段 */
function coverBatchesRouteBlock(): string {
const start = routeSrc.indexOf("router.get('/orders/:orderCode/stock-cover-batches'");
expect(start, '路由必须存在').toBeGreaterThan(-1);
const end = routeSrc.indexOf('router.get(', start + 10);
return routeSrc.slice(start, end > start ? end : start + 2000);
}
type CoveredRow = {
id: string;
item_name: string | null;
sku_code: string | null;
unit: string | null;
cover_qty: number;
};
/** 把四条 SQL(已抵扣行 / 批次计划 / FIFO 候选 / 批次元数据)分别接上假数据 */
function wireQueries(input: {
covered: CoveredRow[];
plans?: Array<{ item_id: string; outbound_batches: unknown }>;
fifo?: Array<{ batch_no: string; available_qty: number }>;
meta?: Array<Record<string, unknown>>;
}) {
query.mockImplementation((sql: string) => {
const text = String(sql);
if (text.includes('FROM order_items') && text.includes('stock_cover_qty')) {
return Promise.resolve({ rows: input.covered, rowCount: input.covered.length });
}
if (text.includes('FROM picking_items pi')) {
return Promise.resolve({ rows: input.plans || [], rowCount: (input.plans || []).length });
}
if (text.includes('DISTINCT ON (sku_code, batch_no)')) {
return Promise.resolve({ rows: input.meta || [], rowCount: (input.meta || []).length });
}
if (text.includes('FROM inventory')) {
return Promise.resolve({ rows: input.fifo || [], rowCount: (input.fifo || []).length });
}
throw new Error(`未预期的 SQL: ${text.slice(0, 60)}`);
});
}
describe('库存抵扣批次明细(只读查询)', () => {
beforeEach(() => {
query.mockReset();
});
it('① FIFO 口径守卫:兜底顺序与抵扣侧 loadFifoBatches 逐字一致', () => {
expect(serviceSrc).toContain(FIFO_ORDER_BY);
expect(planSrc).toContain(FIFO_ORDER_BY);
// 同口径的另一半:只取有可用量的批次
expect(serviceSrc).toContain('available_qty > 0');
});
it('② 只读守卫:模块内不得有任何写语句', () => {
expect(serviceSrc).not.toMatch(/\b(UPDATE|INSERT\s+INTO|DELETE\s+FROM)\b/i);
});
it('③ 已有批次事实 ⇒ 按事实返回(source=plan),不再现算 FIFO', async () => {
wireQueries({
covered: [{ id: 'item-1', item_name: '抄手皮', sku_code: 'SKU62634064428', unit: '斤', cover_qty: 8 }],
plans: [{ item_id: 'item-1', outbound_batches: [{ batch_no: 'STK-A', qty: 5, source: 'fifo_cover' }, { batch_no: 'STK-B', qty: 3 }] }],
fifo: [{ batch_no: 'STK-Z', available_qty: 100 }],
});
const res = await listStockCoverBatches({ orderCode: 'ORD-1' });
expect(res.items).toHaveLength(1);
expect(res.items[0].source).toBe('plan');
expect(res.items[0].batches.map((b) => [b.batch_no, b.qty])).toEqual([
['STK-A', 5],
['STK-B', 3],
]);
// 事实优先:不许再去查 FIFO 候选(查了说明会用现算值覆盖凭证)
const fifoCalls = query.mock.calls.filter(
(call) => String(call[0]).includes('FROM inventory') && !String(call[0]).includes('DISTINCT ON')
);
expect(fifoCalls).toHaveLength(0);
});
it('④ 无批次事实 ⇒ 按先进先出算(source=fifo),数量封顶在已抵扣量', async () => {
wireQueries({
covered: [{ id: 'item-1', item_name: '苹果', sku_code: 'SKU-A', unit: '斤', cover_qty: 8 }],
plans: [],
fifo: [
{ batch_no: 'STK-早', available_qty: 5 },
{ batch_no: 'STK-晚', available_qty: 30 },
],
meta: [
{
sku_code: 'SKU-A',
batch_no: 'STK-早',
created_at: '2026-10-11T07:23:19.300Z',
production_date: '2026-10-08T16:00:00.000Z',
expiry_date: '2026-10-14T16:00:00.000Z',
storage_zone: '冷库A',
},
],
});
const res = await listStockCoverBatches({ orderCode: 'ORD-1' });
expect(res.items[0].source).toBe('fifo');
expect(res.items[0].batches.map((b) => [b.batch_no, b.qty])).toEqual([
['STK-早', 5],
['STK-晚', 3],
]);
// 元数据富化:入库日期 / 生产日期 / 效期 / 区域(本地日)
const first = res.items[0].batches[0];
expect(first.inbound_date).toBe('2026-10-11');
expect(first.production_date).toBe('2026-10-09');
expect(first.expiry_date).toBe('2026-10-15');
expect(first.storage_zone).toBe('冷库A');
// 查不到的批次照常返回批次号与数量,元数据为 null(不得整条丢掉)
const second = res.items[0].batches[1];
expect(second.batch_no).toBe('STK-晚');
expect(second.qty).toBe(3);
expect(second.inbound_date).toBeNull();
expect(second.storage_zone).toBeNull();
});
it('⑤ 库存已空且无计划 ⇒ 该行照常返回、批次为空(前端能说清"没有批次")', async () => {
wireQueries({
covered: [{ id: 'item-1', item_name: '水面', sku_code: 'SKU-B', unit: '斤', cover_qty: 13 }],
plans: [],
fifo: [],
meta: [],
});
const res = await listStockCoverBatches({ orderCode: 'ORD-1' });
expect(res.items).toHaveLength(1);
expect(res.items[0].batches).toEqual([]);
expect(res.items[0].cover_qty).toBe(13);
});
it('⑥ 未抵扣的订单 / 空单号 ⇒ 空结果,且不查库', async () => {
expect(await listStockCoverBatches({ orderCode: '' })).toEqual({ items: [] });
wireQueries({ covered: [] });
expect(await listStockCoverBatches({ orderCode: 'ORD-NONE' })).toEqual({ items: [] });
});
it('⑦ 已抵扣行的过滤口径写在 SQL 里(未退货 + 抵扣量 > 0)', () => {
expect(serviceSrc).toContain('COALESCE(stock_cover_qty, 0) > 0.000001');
expect(serviceSrc).toContain('COALESCE(is_returned, false) = false');
});
it('⑧ 路由:只鉴权 + 委派,权限集合与 batch-reports 一致,带分公司上下文', () => {
const block = coverBatchesRouteBlock();
expect(block).toContain('requireWorkflowPermission');
expect(block).toContain('assertOrderCodeAccess');
expect(block).toContain('stockCoverBatchQueryService');
expect(block).toContain('branchCode: ctx?.branchCode');
// 路由不写 SQL
expect(block).not.toMatch(/\b(SELECT|UPDATE|INSERT\s+INTO|DELETE\s+FROM)\b/i);
const permBlock = (marker: string) => {
const start = routeSrc.indexOf(marker);
return routeSrc.slice(start, start + 400);
};
const perms = (src: string) => (src.match(/'([a-z_]+)',/g) || []).join(',');
expect(perms(permBlock("router.get('/orders/:orderCode/stock-cover-batches'"))).toBe(
perms(permBlock("router.get('/orders/:orderCode/batch-reports'"))
);
});
});