Files
SupplierSystem/server/tests/stockCoverBatchQuery.test.ts
T
Ubuntu 7e9606745b feat(库存抵扣): 弹窗展示被抵扣批次的成本价
开发者当轮要求:「库存抵扣的这块 将抵扣的库存的成本价展示出来」。

口径依据:抵扣部分按**被抵扣批次成本价**计入订单成本
(docs/design/20261014-抵扣成本口径(成本随货走+去重).md)⇒ 运营在弹窗里要能看到
"抵的是多少钱的货",否则无法核对成本与选批。

改动:
- 服务端 `stockCoverBatchQueryService.listStockCoverBatches`:批次元数据 SELECT 增取
  `inventory.cost_price`,并映射进 `batches[]` 与 `candidates[]`(未设成本价 ⇒ **null**,
  不当 0 —— 0 会让这行看着"不要钱")。该模块仍是**只读**(②守卫:无 UPDATE/INSERT/DELETE)。
- 前端 `workflowApi.ts`:两个类型各加 `cost_price?: number | null`。
- `OrderStockCoverBatchesModal`:三处都展示 —— 展示行(区域·入库·生产日期·效期·**成本价**)、
  候选批次行、编辑中的批次行;格式与库存页一致(两位小数),未设成本价显示
  `inventory.col.costMissing`(未设置/Not set/Belum diisi)。

**未新增任何文案**:复用既有 `inventory.col.cost`(成本价)与 `inventory.col.costMissing`,
三语词条均已存在(弹窗契约测试 ② 会逐条校验)。

验证:
- 真库端到端(`ORD_API_20261014_BR002_0002` / BR002)实跑 listStockCoverBatches:
  健裕泡酸菜2kg IN20261014NAMMFS ×10 成本价 6;草鱼加工 ×5 成本价 6;圣女果 ×12 成本价 2;
  二刀肉那批成本价 **null**(正好命中「未设置」分支)。
- 服务端全量:25 failed / 401 passed(426 文件),失败文件集与基线**逐项相同**(comm 无差异);
  新增 tests/stockCoverBatchQuery.test.ts ⑬(批次与候选都带成本价 + 未设成本价 ⇒ null + SQL 含
  `available_qty, cost_price`)。
- 前端契约测试:`OrderStockCoverBatchesModal.contract.test.ts` 9 例全绿(新增 ⑨)。
- `tsc --noEmit`(web + server)均 0;webpack dev 重编译成功、无 ERROR,
  且**在实际下发的 chunk**(`src_pages_orders_orderManagement_index_tsx.bundle.js`)里核到
  `inventory.col.cost` / `costText` / `cost_price`。
- 前端全量 2 failed / 159 passed:两项均与本改动无关且**在 HEAD 就是红的**
  (`StockInboundPanel.tsx` 里本就没有 `useAllowZeroCost`;另一项是并发未跟踪的
  `PickingManagement.outboundPhotoPreview.test.ts`)。两者都不引用本次改动的任何文件。
- 门禁:run-all.sh --verify 8 通过 / 1 已知红(check-ai-cost) / 1 未执行,与基线一致。

提交范围说明:`src/utils/workflowApi.ts` 用选择性暂存(HEAD + 仅本次 hunk),
**未夹带**并发会话在该文件里的未提交改动(其 `listStandaloneProcessingSkuOptionsApi` 的
`demandTaskId` 改动仍留在工作区)。
2026-10-14 14:20:11 +08:00

387 lines
15 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);
});
/**
* 开发者 2026-10-14:「将抵扣的库存的成本价展示出来」。
* 成本口径见 docs/design/20261014-抵扣成本口径(成本随货走+去重).md —— 抵扣部分按
* **被抵扣批次成本价**计入订单成本,所以弹窗必须能看到"抵的是多少钱的货"。
*/
it('⑬ 批次与候选都带成本价;批次未设成本价 ⇒ null(不当 0 展示)', async () => {
wireQueries({
covered: [
{ id: 'item-1', item_name: '抄手皮', sku_code: 'SKU-A', unit: '斤', cover_qty: 8, order_status: 30 },
],
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',
cost_price: '6.00',
},
{
sku_code: 'SKU-A',
batch_no: 'STK-无价',
created_at: '2026-10-12T07:23:19.300Z',
production_date: null,
expiry_date: null,
storage_zone: '冷库A',
available_qty: '9.00',
cost_price: null,
},
],
});
const res = await listStockCoverBatches({ orderCode: 'ORD-1' });
expect(res.items[0].batches[0].cost_price).toBe(6);
expect(res.items[0].candidates.map((c) => [c.batch_no, c.cost_price])).toEqual([
['STK-早', 6],
['STK-无价', null],
]);
// 取数 SQL 必须把 cost_price 一并取回(否则界面永远是 null)
expect(serviceSrc).toMatch(/available_qty, cost_price/);
});
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'"))
);
});
});