diff --git a/server/src/services/inventoryBatchCostService.ts b/server/src/services/inventoryBatchCostService.ts index fd28fa9..5b69c58 100644 --- a/server/src/services/inventoryBatchCostService.ts +++ b/server/src/services/inventoryBatchCostService.ts @@ -167,25 +167,18 @@ export async function applyBatchCostChange(input: { newCost, ]); - // ② 口径甲:重算**未结算**订单的抵扣账本行 - for (const row of impact.rows) { - if (row.skipped === 'settled') continue; - await client.query( - `UPDATE cost_details - SET amount = $3::numeric, allocated_amount = $3::numeric - WHERE order_code = $1 AND sku_code = $2 AND cost_source = 'inventory_cover'`, - [row.order_code, row.sku_code, row.after_amount] - ); - } + // ②③ 同一事务里:重算**未结算**订单账本 + 写 adjust 流水(共享给其它改成本入口,口径一处) + await recalcCoverLedgerForBatchCostChange(client, { + batchNo, + skuCode, + beforeCost, + afterCost: newCost, + branchCode: input.branchCode, + operatorId: input.operatorId, + remark, + impact, + }); - // ③ 留痕:inventory_logs(与库存调整同表同口径)+ 审计 - await client.query( - `INSERT INTO inventory_logs ( - batch_no, sku_code, operation_type, quantity, before_qty, after_qty, - related_order_code, operator_id, remark - ) VALUES ($1, $2, 'adjust', 0::numeric, $3::numeric, $4::numeric, NULL, $5, $6)`, - [batchNo, skuCode, beforeCost, newCost, trim(input.operatorId) || null, remark] - ); await writeAuditLog({ operatorId: trim(input.operatorId) || null, operationType: 'inventory_batch_cost_adjust', @@ -299,3 +292,70 @@ async function buildImpact( skipped_count: rows.filter((r) => r.skipped === 'settled').length, }; } + +/** + * **共享重算**:批次成本变化后,重算「抵扣了这一批」的**未结算**订单账本 + 写 `adjust` 流水。 + * + * 为什么抽出来:能改 `inventory.cost_price` 的入口不止一个,而订单详情「抵扣成本价」 + * 是**直读账本**(`cost_details` 的 `inventory_cover` 金额 ÷ 抵扣量,见 `stockCoverBatchQueryService`)。 + * 2026-10-15 实测缺陷:**库存管理「修改」改成本**只写 `inventory.cost_price`,什么都不重算 + * ⇒ 订单里那个价永远是旧的(用户报障:批次 11.00,订单仍显示 10.00)。 + * + * 口径(沿用 2026-10-14 裁决,勿改):**只重算未结算订单**;已结算(客户结算单 + * `statement_status >= 20`)的账本**不回头改**,只计入 `skipped_count`。 + * + * 调用方负责写各自的审计(弹窗=`inventory_batch_cost_adjust`;库存管理修改=`inventory_batch_edit`)。 + */ +export async function recalcCoverLedgerForBatchCostChange( + client: PoolClient, + input: { + batchNo: string; + skuCode: string; + beforeCost: number; + afterCost: number; + branchCode?: string | null; + operatorId?: string | null; + remark?: string | null; + /** 调用方已算好的影响面(避免重复扫描);不传则本函数自己扫 */ + impact?: BatchCostImpact; + } +): Promise { + const impact = + input.impact || + (await buildImpact(client, { + batchNo: input.batchNo, + skuCode: input.skuCode, + beforeCost: input.beforeCost, + afterCost: input.afterCost, + branchCode: input.branchCode, + })); + + // ① 重算未结算订单的抵扣账本行(已结算跳过) + for (const row of impact.rows) { + if (row.skipped === 'settled') continue; + await client.query( + `UPDATE cost_details + SET amount = $3::numeric, allocated_amount = $3::numeric + WHERE order_code = $1 AND sku_code = $2 AND cost_source = 'inventory_cover'`, + [row.order_code, row.sku_code, row.after_amount] + ); + } + + // ② 留痕:与库存调整同表同口径(before/after 存的是成本价,quantity=0) + await client.query( + `INSERT INTO inventory_logs ( + batch_no, sku_code, operation_type, quantity, before_qty, after_qty, + related_order_code, operator_id, remark + ) VALUES ($1, $2, 'adjust', 0::numeric, $3::numeric, $4::numeric, NULL, $5, $6)`, + [ + input.batchNo, + input.skuCode, + input.beforeCost, + input.afterCost, + trim(input.operatorId) || null, + trim(input.remark) || null, + ] + ); + + return impact; +} diff --git a/server/src/services/inventoryBatchEditService.ts b/server/src/services/inventoryBatchEditService.ts index ecb3297..f9336b9 100644 --- a/server/src/services/inventoryBatchEditService.ts +++ b/server/src/services/inventoryBatchEditService.ts @@ -72,6 +72,11 @@ export interface UpdateInventoryBatchResult { batch_no: string; sku_code: string; changed: string[]; + /** + * 本次改了成本价时的重算结果:`affected` = 被重算的未结算订单数, + * `skipped_settled` = 因已结算而未回改的订单数(口径见 inventoryBatchCostService)。 + */ + cost_recalc?: { affected: number; skipped_settled: number } | null; } export async function updateInventoryBatchAttributes( @@ -162,6 +167,8 @@ export async function updateInventoryBatchAttributes( changed.push('expiry_date'); } } + /** 成本价变化时记下来:改完要在**同一事务**里重算订单抵扣账本(见下方) */ + let costChange: { before: number; after: number } | null = null; if (input.costPrice !== undefined) { const raw = input.costPrice; const next = raw == null || trimText(raw) === '' ? null : Number(raw); @@ -175,6 +182,7 @@ export async function updateInventoryBatchAttributes( batchParams.push(next); batchSets.push(`cost_price = $${batchParams.length}::numeric`); changed.push('cost_price'); + costChange = { before: Number(beforeBatch.cost_price) || 0, after: Number(next) || 0 }; } } if (batchSets.length) { @@ -185,6 +193,29 @@ export async function updateInventoryBatchAttributes( ); } + /** + * 改成本 ⇒ **同一事务**重算「抵扣了这一批」的未结算订单账本 + 写 `adjust` 流水。 + * + * 2026-10-15 缺陷:本入口原先只写 `inventory.cost_price`,而订单详情「抵扣成本价」是 + * **直读账本**(`cost_details.inventory_cover` ÷ 抵扣量)⇒ 改完成本订单里还是旧价 + * (开发者实测:批次 11.00、订单仍显示 10.00)。现与抵扣弹窗「改成本」走**同一个**重算函数, + * 口径=只重算未结算订单(已结算不回改)。 + */ + let costRecalc: { affected: number; skipped_settled: number } | null = null; + if (costChange) { + const { recalcCoverLedgerForBatchCostChange } = await import('./inventoryBatchCostService'); + const impact = await recalcCoverLedgerForBatchCostChange(client, { + batchNo: String(row.batch_no), + skuCode, + beforeCost: costChange.before, + afterCost: costChange.after, + branchCode, + operatorId: input.operatorId || null, + remark, + }); + costRecalc = { affected: impact.affected_count, skipped_settled: impact.skipped_count }; + } + // ── 商品级 ────────────────────────────────────────────── const productTouched = input.categoryCode !== undefined || @@ -284,6 +315,7 @@ export async function updateInventoryBatchAttributes( batch_no: String(row.batch_no), sku_code: skuCode, changed, + cost_recalc: costRecalc, }; // 审计(提交后写,失败不回滚主流程) @@ -294,7 +326,7 @@ export async function updateInventoryBatchAttributes( targetTable: 'inventory', targetId: result.id, oldValue: { ...beforeBatch }, - newValue: { ...input, changed }, + newValue: { ...input, changed, cost_recalc: costRecalc }, branchCode, actionCategory: 'inventory', }); diff --git a/server/tests/inventoryBatchCostRecalc.test.ts b/server/tests/inventoryBatchCostRecalc.test.ts new file mode 100644 index 0000000..2b3a74f --- /dev/null +++ b/server/tests/inventoryBatchCostRecalc.test.ts @@ -0,0 +1,75 @@ +/** + * 「改批次成本 ⇒ 重算订单抵扣账本」的入口一致性(2026-10-15 缺陷)。 + * + * 缺陷:**库存管理「修改」**改批次成本时只写 `inventory.cost_price`,什么都不重算; + * 而订单详情「抵扣成本价」是**直读账本**(`cost_details.inventory_cover` ÷ 抵扣量) + * ⇒ 改完成本订单里还是旧价(开发者实测:批次 11.00、订单仍显示 10.00;本地实测账本停在 10)。 + * + * 口径(2026-10-15 开发者裁决):**只修库存管理「修改」这一条入口**;重算沿用 2026-10-14 的口径 + * ——「只重算**未结算**订单;已结算(客户结算单 statement_status >= 20)不回头改」, + * 并要求统一留痕(备注必填 + `inventory_logs('adjust')` + 审计)。 + * + * 设计/口径出处:`inventoryBatchCostService` 文件头注释 + 本测试。 + */ +import { readFileSync } from 'fs'; +import { describe, expect, it } from 'vitest'; + +const costService = readFileSync( + new URL('../src/services/inventoryBatchCostService.ts', import.meta.url), + 'utf8' +); +const editService = readFileSync( + new URL('../src/services/inventoryBatchEditService.ts', import.meta.url), + 'utf8' +); + +describe('共享重算函数(口径一处)', () => { + it('存在导出的共享函数:重算未结算账本 + 写 adjust 流水', () => { + expect(costService).toContain( + 'export async function recalcCoverLedgerForBatchCostChange(' + ); + // 已结算跳过(2026-10-14 口径,勿改) + expect(costService).toMatch( + /for \(const row of impact\.rows\) \{\s*\n\s*if \(row\.skipped === 'settled'\) continue;/ + ); + // 只动抵扣账本行(inventory_cover) + expect(costService).toContain("AND cost_source = 'inventory_cover'"); + // 留痕:与库存调整同表同口径 + expect(costService).toMatch(/INSERT INTO inventory_logs \(/); + expect(costService).toContain("'adjust'"); + }); + + it('抵扣弹窗「改成本」也走同一个函数(不再各写一套)', () => { + expect(costService).toContain('await recalcCoverLedgerForBatchCostChange(client, {'); + }); +}); + +describe('库存管理「修改」这条入口', () => { + it('改成本时在同事务里调用共享重算', () => { + expect(editService).toContain("const { recalcCoverLedgerForBatchCostChange } = await import('./inventoryBatchCostService');"); + expect(editService).toContain('await recalcCoverLedgerForBatchCostChange(client, {'); + // 必须在 COMMIT 之前(同一事务):重算代码块出现在 'COMMIT' 之前 + const recalcAt = editService.indexOf('recalcCoverLedgerForBatchCostChange(client, {'); + const commitAt = editService.indexOf("await client.query('COMMIT')"); + expect(recalcAt).toBeGreaterThan(-1); + expect(commitAt).toBeGreaterThan(recalcAt); + }); + + it('只在成本价真的变了才重算(其它字段修改不触发)', () => { + expect(editService).toContain('costChange = { before: Number(beforeBatch.cost_price) || 0, after: Number(next) || 0 };'); + expect(editService).toContain('if (costChange) {'); + // 未变化时 costChange 保持 null(幂等:重复保存同价不写流水/不动账本) + expect(editService).toMatch(/if \(\(beforeBatch\.cost_price \?\? null\) !== \(next \?\? null\)\) \{/); + }); + + it('备注必填(统一留痕的一半)', () => { + expect(editService).toContain('请填写修改备注'); + expect(editService).toContain("code: 'invalid_request'"); + }); + + it('把重算结果回给调用方并写进审计(可追溯改了几个未结算单)', () => { + expect(editService).toContain('cost_recalc?: { affected: number; skipped_settled: number } | null;'); + expect(editService).toContain('cost_recalc: costRecalc,'); + expect(editService).toContain('newValue: { ...input, changed, cost_recalc: costRecalc },'); + }); +});