Files
SupplierSystem/server/tests/stockCoverBatchQuery.test.ts
T
Ubuntu 5d33d7010f feat(抵扣批次): 订单侧可指定抵扣批次(方案甲)—— 出库只读、分拣对应得上
开发者:「这个调整出库后就只能是看了不能改;这边如果改了抵扣的批次后,那么分拣时
分拣的批次需要对应得上(当然分拣时分拣员也能改)」。方案甲(开发者选定)。

口径(写死并测):
- 唯一落点仍是 picking_items.outbound_batches(分拣界面默认值 / 分拣出库扣库 /
  发车核货扣库 / 批次报告推送 四个消费方零改动即对上)
- 还没拣货行(开了分拣的分公司抵扣时行不存在)⇒ 先落 order_items.cover_batches
  (迁移 20261041,只加列不建表),在 4 个建行入口带进新行:
  pickingService.insertPickingItems / skipInboundLoadingService / deliveryLoadingService(两处)
- 优先级:我方指定 > 抵扣 FIFO 计划 > 先进先出现算;分拣员完成分拣即覆盖行值
- 出库后只读(409 cover_batches_locked):出库流水 / 拣货行 outbound_at / 订单 ≥50
- 保存校验:批次须属该 SKU 且在本分公司、单批 ≤ 当前可用、合计 ≤ 该行已抵扣量
- 清理联动:释放/退货/删单/换货六个入口汇到 inventoryStockCoverService.clearAutoCoverBatchPlan
  一处(连同 FIFO 计划一起清);改绑 SKU 即时清;15 分钟兜底清扫(含"指定批次已不存在")
- 读侧防御:指定批次在当前 SKU 下不存在 ⇒ 该条目不当真,退回计划/FIFO
- 顺带修既有不一致:结案补扣出库此前不按批次计划扣(纯 FIFO),现与发车扣库共用
  loadPickItemBatchPlans

真库实测(BR003,夹具跑完清理残留 0):
- PUT 200 → order_items.cover_batches 落库、GET source=manual
- 已有空拣货行 ⇒ applied_to_picking_rows=1,该行 outbound_batches 即我方指定
- 直调 materialize:applied=1、再跑 0(幂等)、无指定的行 untouched=0
- 撤销:cleared=true、cover_batches=null、行内我方条目摘掉
- 状态 50 单:GET 三行 read_only=true/order_departed、PUT 409 cover_batches_locked
- 合计超抵扣量 ⇒ 400 batch_total_exceeds_cover

测试:server/tests/orderItemCoverBatches.test.ts(14 例)、stockCoverBatchQuery.test.ts(12 例)、
OrderStockCoverBatchesModal.contract.test.ts(8 例);前端 order 相关 29 文件 193 例全绿;
前端新增文案 2 条(已获批准):orders.coverBatch.manual / orders.coverBatch.fallbackHint
2026-10-13 10:53:52 +08:00

339 lines
14 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;
/** 我方指定的抵扣批次(方案甲新增列) */
cover_batches?: unknown;
order_status?: 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>>;
/** 出库锁定判据(默认未出库) */
lock?: { has_outbound?: boolean; pick_outbound?: boolean };
}) {
query.mockImplementation((sql: string) => {
const text = String(sql);
if (text.includes('FROM inventory_logs il')) {
return Promise.resolve({
rows: [
{
has_outbound: Boolean(input.lock?.has_outbound),
pick_outbound: Boolean(input.lock?.pick_outbound),
},
],
rowCount: 1,
});
}
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 的 STK-Z(FIFO 只作为编辑候选一起返回)
expect(res.items[0].batches.map((b) => b.batch_no)).not.toContain('STK-Z');
expect(res.items[0].candidates.map((c) => c.batch_no)).toEqual(['STK-Z']);
});
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(oi.stock_cover_qty, 0) > 0.000001');
expect(serviceSrc).toContain('COALESCE(oi.is_returned, false) = false');
});
/**
* 方案甲(开发者 2026-10-13):「这边如果改了抵扣的批次后,那么分拣时分拣的批次需要对应得上」。
* 优先级写死:我方指定 > 抵扣计划/分拣选定 > 先进先出现算。
*/
it('⑨ 我方指定优先:有 cover_batches ⇒ source=manual(压过库里的计划)', async () => {
wireQueries({
covered: [
{
id: 'item-1',
item_name: '抄手皮',
sku_code: 'SKU-A',
unit: '斤',
cover_qty: 8,
cover_batches: [{ batch_no: 'STK-我方', qty: 8, source: 'manual_cover' }],
order_status: 30,
} as CoveredRow,
],
plans: [{ item_id: 'item-1', outbound_batches: [{ batch_no: 'STK-计划', qty: 8 }] }],
fifo: [{ batch_no: 'STK-FIFO', available_qty: 100 }],
meta: [
{
sku_code: 'SKU-A',
batch_no: 'STK-我方',
created_at: '2026-10-11T07:23:19.300Z',
production_date: null,
expiry_date: null,
storage_zone: '冷库A',
available_qty: '8.00',
},
],
});
const res = await listStockCoverBatches({ orderCode: 'ORD-1' });
expect(res.items[0].source).toBe('manual');
expect(res.items[0].batches.map((b) => [b.batch_no, b.qty])).toEqual([['STK-我方', 8]]);
expect(res.items[0].read_only).toBe(false);
});
it('⑫ 我方指定里的批次在当前 SKU 下已不存在(换过商品/批次被删)⇒ 不当真,退回计划/FIFO', async () => {
wireQueries({
covered: [
{
id: 'item-1',
item_name: '抄手皮',
sku_code: 'SKU-A',
unit: '斤',
cover_qty: 8,
cover_batches: [{ batch_no: 'STK-旧商品批次', qty: 8, source: 'manual_cover' }],
order_status: 30,
} as CoveredRow,
],
plans: [{ item_id: 'item-1', outbound_batches: [{ batch_no: 'STK-计划', qty: 8 }] }],
fifo: [{ batch_no: 'STK-计划', available_qty: 8 }],
meta: [
{
sku_code: 'SKU-A',
batch_no: 'STK-计划',
created_at: '2026-10-11T07:23:19.300Z',
production_date: null,
expiry_date: null,
storage_zone: '冷库A',
available_qty: '8.00',
},
],
});
const res = await listStockCoverBatches({ orderCode: 'ORD-1' });
expect(res.items[0].source).toBe('plan');
expect(res.items[0].batches.map((b) => b.batch_no)).toEqual(['STK-计划']);
});
it('⑩ 已出库 ⇒ read_only 且以拣货行事实为准(我方指定不再顶掉已经扣掉的事实)', async () => {
wireQueries({
covered: [
{
id: 'item-1',
item_name: '抄手皮',
sku_code: 'SKU-A',
unit: '斤',
cover_qty: 8,
cover_batches: [{ batch_no: 'STK-我方', qty: 8, source: 'manual_cover' }],
order_status: 50,
} as CoveredRow,
],
plans: [{ item_id: 'item-1', outbound_batches: [{ batch_no: 'STK-实际', qty: 8 }] }],
fifo: [{ batch_no: 'STK-FIFO', available_qty: 100 }],
lock: { has_outbound: true },
});
const res = await listStockCoverBatches({ orderCode: 'ORD-1' });
expect(res.items[0].read_only).toBe(true);
expect(res.items[0].read_only_reason).toBe('order_departed');
expect(res.items[0].source).toBe('plan');
expect(res.items[0].batches.map((b) => b.batch_no)).toEqual(['STK-实际']);
// 已出库不给编辑候选
expect(res.items[0].candidates).toEqual([]);
});
it('⑪ 候选批次与 FIFO 同序、带元数据(编辑界面用)', async () => {
wireQueries({
covered: [
{ id: 'item-1', item_name: '苹果', sku_code: 'SKU-A', unit: '斤', cover_qty: 3 } as CoveredRow,
],
plans: [],
fifo: [
{ batch_no: 'STK-早', available_qty: 5 },
{ batch_no: 'STK-晚', available_qty: 9 },
],
meta: [
{
sku_code: 'SKU-A',
batch_no: 'STK-早',
created_at: '2026-10-11T07:23:19.300Z',
production_date: null,
expiry_date: null,
storage_zone: '冷库A',
available_qty: '5.00',
},
],
});
const res = await listStockCoverBatches({ orderCode: 'ORD-1' });
expect(res.items[0].candidates.map((c) => c.batch_no)).toEqual(['STK-早', 'STK-晚']);
expect(res.items[0].candidates[0].storage_zone).toBe('冷库A');
expect(res.items[0].candidates[0].inbound_date).toBe('2026-10-11');
// 展示行也带「当前可用量」(库存后来变了要看得见)
expect(res.items[0].batches[0].available_qty).toBe(5);
});
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'"))
);
});
});