/** * 仓内加工领料:**本单自己的**预留消费(2026-10-14 开发者批准)。 * * 为什么单独成文件:这两个函数只服务"加工领料"这一条链路,放在 * `inventoryStockCoverService.ts` 会把那个文件越撑越大 —— 而该文件里 * `applyStockCoverForOrderItem` 的"守卫在无效入参清零之前"是被**固定窗口源码契约测试** * 钉住的(`stockCoverGuard.test.ts` / `independentInbound.test.ts`), * 函数头继续变长会把窗口撑破、让那两个测试假失败(本文件抽离前实测已发生)。 * * 口径见 [`20261014-加工领料可用本单预留.md`](../../docs/design/20261014-加工领料可用本单预留.md)。 */ import type { PoolClient } from 'pg'; /** 只需要 query 能力,便于单测注入假 db */ type Db = Pick; /** * 仓内加工领料:把**本单自己的**活跃预留按实际领用量消费掉(2026-10-14 开发者批准)。 * * ## 为什么要它 * 「需求单领料」的成品就是本单已被预留的那批货(实测 `ORD_API_20261014_BR002_0002`: * 二刀肉 5 斤预留持有者 = 该单自身「去皮·仓内加工」行,而需求单要加工的也正是它)。 * 旧口径领料一律扣「毛可用 − **全部**在用预留」⇒ 本单自己的预留把自己挡住(5−5=0), * 需求单永远领不到料 —— 这是 [`20260922-processing-pick-respect-reservations.md`] 里 * 已知并被接受的代价,但对"本单成品"这一形态是死锁。 * * ## 为什么不能只放开校验 * 领料会 `fifoDeductInventory` 扣库,但**预留不会被扣**。若只放开校验、不消费预留: * 库存已扣为 0、预留仍 `status=10` ⇒ ① 发车仍需这 5 斤 ⇒ 扣不到 ⇒ **短送**; * ② 加工成品又产出了 5 斤 ⇒ **同一批货算两次**(与本项目 `consumed_only` 同源的 P0 形态)。 * ⇒ 放行必须**成对**:这里把预留同步消费掉。 * * ## 口径 * · 只动**入参订单号自己**的 `status=10` 预留(他单预留一律不碰); * · `newQty <= 0` ⇒ 置 `status=20`(已消费);否则把 `qty` 降为剩余(`upsert` 的 HAVING 判据即以此为准); * · `planned` 传**领料前**的预留量(调用方在同事务内先取好),以便精确算"本次只领了一部分"。 * 见 [`20261014-加工领料可用本单预留.md`](../../docs/design/20261014-加工领料可用本单预留.md)。 */ export async function claimOwnOrderReservationForProcessingPick( db: Db, input: { orderCodes: string[]; skuCode: string; branchCode?: string | null; qty: number; /** 领料前该 (订单, SKU) 的活跃预留量(调用方在同事务内先查) */ planned: number; /** 同一 SKU 已消费过的量(一次领料内累计,调用方维护) */ alreadyClaimed?: number; } ): Promise { const sku = String(input.skuCode || '').trim(); const codes = Array.from( new Set((input.orderCodes || []).map((c) => String(c || '').trim()).filter(Boolean)) ); const picked = Math.max(0, Number(input.qty) || 0); const planned = Math.max(0, Number(input.planned) || 0); if (!sku || !codes.length || picked <= 1e-9 || planned <= 1e-9) return 0; const already = Math.max(0, Number(input.alreadyClaimed) || 0); const rows = await db.query( `SELECT id, order_item_id, qty::float AS qty FROM inventory_reservations WHERE sku_code = $1 AND order_code = ANY($2::text[]) AND status = 10 AND ($3::text IS NULL OR branch_code IS NULL OR branch_code = $3) ORDER BY created_at ASC FOR UPDATE`, [sku, codes, String(input.branchCode || '').trim() || null] ); const total = rows.rows.reduce((sum, r) => sum + (Number(r.qty) || 0), 0); if (total <= 1e-9) return 0; // 同上:本次能把预留降到多少(按累计口径,避免多行预留被重复算满) const targetAfter = Math.max(0, planned - already - picked); let release = Math.round((total - targetAfter) * 1000) / 1000; if (release <= 1e-9) return 0; let claimed = 0; for (const row of rows.rows) { if (release <= 1e-9) break; const qty = Math.max(0, Number(row.qty) || 0); if (qty <= 1e-9) continue; const take = Math.min(qty, release); const rest = Math.round((qty - take) * 1000) / 1000; if (rest > 1e-9) { // CHECK 约束 qty > 0 ⇒ 只降不删 await db.query(`UPDATE inventory_reservations SET qty = $2, updated_at = NOW() WHERE id = $1::uuid`, [ String(row.id), rest, ]); } else { // 整条消费(status 20 = 已消费,与 consumeReservationsForOrder 同一语义) await db.query( `UPDATE inventory_reservations SET status = 20, updated_at = NOW() WHERE id = $1::uuid`, [String(row.id)] ); } release -= take; claimed += take; } return Math.round(claimed * 1000) / 1000; } /** 某 (订单集合, SKU) 的活跃预留合计(领料前取 `planned` 用) */ export async function sumActiveReservationsForOrders( db: Db, input: { orderCodes: string[]; skuCode: string; branchCode?: string | null } ): Promise { const sku = String(input.skuCode || '').trim(); const codes = Array.from( new Set((input.orderCodes || []).map((c) => String(c || '').trim()).filter(Boolean)) ); if (!sku || !codes.length) return 0; const r = await db.query( `SELECT COALESCE(SUM(qty), 0)::float AS total FROM inventory_reservations WHERE sku_code = $1 AND order_code = ANY($2::text[]) AND status = 10 AND ($3::text IS NULL OR branch_code IS NULL OR branch_code = $3)`, [sku, codes, String(input.branchCode || '').trim() || null] ); return Math.round((Number(r.rows[0]?.total) || 0) * 1000) / 1000; } /** * 领料可扣量切分:**他单预留 = 全部在用预留 − 本单自己的在用预留**(一次成型)。 * * 旧写法对每个本单订单号各调一次 `sumOtherOrderReservations` 再相加,而该函数每次只排除 * **一个** order_code ⇒ 同一需求单含 A、B 两张订单时,他单预留被算 N 倍(见 * `processingPickOwnReservationMultiOrder.test.ts` ①)。本函数只读、不产生写语句; * `orderCodes` 为空(自采/独立加工)时他单 = 全部在用预留,且省掉 own 查询。 */ export async function resolveProcessingPickReservationSplit( db: Db, input: { orderCodes: string[]; skuCode: string; branchCode?: string | null } ): Promise<{ totalReserved: number; ownReserved: number; otherReserved: number }> { const sku = String(input.skuCode || '').trim(); const codes = Array.from( new Set((input.orderCodes || []).map((c) => String(c || '').trim()).filter(Boolean)) ); const branch = String(input.branchCode || '').trim() || null; if (!sku) return { totalReserved: 0, ownReserved: 0, otherReserved: 0 }; const totalRow = await db.query( `SELECT COALESCE(SUM(qty), 0)::float AS total FROM inventory_reservations WHERE sku_code = $1 AND status = 10 AND ($2::text IS NULL OR branch_code IS NULL OR branch_code = $2)`, [sku, branch] ); const totalReserved = Math.round((Number(totalRow.rows[0]?.total) || 0) * 1000) / 1000; const ownReserved = codes.length ? await sumActiveReservationsForOrders(db, { orderCodes: codes, skuCode: sku, branchCode: branch }) : 0; const otherReserved = Math.max( 0, Math.round((totalReserved - ownReserved) * 1000) / 1000 ); return { totalReserved, ownReserved, otherReserved }; }