Files
SupplierSystem/server/src/services/inventoryOutboundService.ts
T
Ubuntu 42c5cb8332 fix(库存审计面): P0 三条收口 —— 网关禁写库存台账 / 审计表补 RLS / 出库幂等改逐 SKU
8 维度多 agent 审计(含真库核查 + 对抗复核)结论:进销存主链路可用,库存管理体系 4 条高危缺口。
本次落地 P0 三条(开发者批准「可以」):

P0-1 通用数据网关禁写 `inventory` / `inventory_logs`(accessPolicy.DENY_WRITE_TABLES):
  裸写会绕过「备注必填 + 双日志 + FIFO/预留保护」;读取不受影响(两表仍在 ALLOWED_TABLES,
  前端对它们只有 SELECT,已 grep 核对)。台账写入必须走验收/独立入库/自采入库/调整/出库受控路由。

P0-2 审计面补 RLS(迁移 20261014_tenant_inventory_audit_rls.sql):
  apply_tenant_core_rls 的 core_tables 11 → 14 张,新增 inventory_reservations / picking_items /
  picking_tasks(三张都有 branch_code、真库 0 行 NULL),并幂等重放到全部 tenant_*;
  tenantRlsGuard.CORE_TABLES 同步扩到 14 张(名单漏一张 ⇒ 缺 RLS 也会报 ok,这正是本次缺口成因)。
  实测:tenant_br003 有 RLS 的表 11 → 14;正确分支可读 12 行分拣行,错误分支读到 0 行。
  ⚠️ inventory_logs 无 branch_code 列(40 行 + 17 处服务端写入点 + prod-* 脚本),
  需「加列+回填+逐写入点补列+收紧策略」整体做,列下一轮 P0-2b。

P0-3 出库幂等:整单 → **逐 SKU**(inventoryOutboundService + 分拣漏斗):
  · 删掉整单守卫 orderHasOutboundOnClient,改 loadOutboundStateOnClient(DISTINCT sku_code)
    + orderHasPendingOutboundOnClient(逐 SKU 是否仍有"有实物动作却没流水"的行);
  · 计划按已扣 SKU 过滤;全扣过才 already_outbound;流水缺 sku_code 的老数据退回整单语义;
  · 结案兜底只有真扣成功才置 deducted(原先无条件 true ⇒ 全行软扣失败也报"补扣成功");
  · softSkipped 被消费:结案口径上抛 + 分拣漏斗逐行告警(原来算了没人读);
  · listOrdersMissingOutboundSettlement 判据改逐 SKU ⇒ 部分扣过的单也会被 10 分钟任务重扫。
  真库验证:listOrdersMissingOutboundSettlement()=[](无待补扣);已全扣的单再跑返回
  already_outbound 且出库流水 4 条/63.00 不变(不重复扣)。

测试:新增 inventoryAuditHardening.test.ts(9 例:P0-1/P0-2 名单与迁移一致、P0-3 逐 SKU + softSkipped);
更新 pickingCompleteDeductsInventory / pickupSettleInventoryOnClose 两处断言到新代码形状。
回归:server 25 failed / 396 passed(失败文件集与基线逐一比对一致,无新增失败);root tsc 0;
门禁 8 通过 / 1 已知红 / 1 未执行。

待批准(P1):90 状态历史缺口单 1 张(4 行/29 斤)的收口或兜底上延;成本口径三处对齐(财务冻结);
整单抵扣入口补直送/免入库闸门;效期闸门 + 验收写 expiry_date;盘点单据化。
2026-10-14 10:43:26 +08:00

1457 lines
55 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 { PoolClient } from 'pg';
import { pool } from '../db';
import {
consumeReservationsForOrder,
getClaimableStockQty,
listPurchaseMergePeerOrderCodes,
} from './inventoryStockCoverService';
import { notifyInventoryShortage } from './inventoryShortageNotificationService';
import { isPassThroughSku } from './stockModeService';
import { skuDirectDeliveryAppliesSql } from './skuDirectDelivery';
import { writeAuditLog } from './auditService';
export interface InventoryDeductBatch {
batchNo: string;
deductedQty: number;
costPrice: number;
}
/**
* 本单**已有出库流水**的 SKU 集合(出库事实只认 `inventory_logs`)。
*
* 为什么要逐 SKU(2026-10-14 多 agent 审计 P0-3):出库幂等原先按**整单**判
* (只要有一行扣成,整单就短路)。而分拣完毕(45→50)是**软扣**:
* 某 SKU 库存不足时该行被 `continue` 跳过、订单照样推进到 50,之后发车/结案/10 分钟兜底
* 全被整单守卫挡住 ⇒ **那个 SKU 永远漏扣**(库存长期虚高、账面与实物不符)。
* 现在改成"**哪个 SKU 没扣过就补哪个**":已扣的跳过,未扣的继续扣。
*/
async function loadOutboundStateOnClient(
client: PoolClient,
orderCode: string
): Promise<{ skus: Set<string>; hasAny: boolean }> {
const result = await client.query(
`SELECT DISTINCT sku_code FROM inventory_logs
WHERE related_order_code = $1
AND operation_type IN ('picking_out', 'delivery_loading_out')`,
[orderCode]
);
const skus = new Set(
result.rows.map((row) => trimSku((row as { sku_code?: unknown }).sku_code)).filter(Boolean)
);
return { skus, hasAny: (result.rowCount || 0) > 0 };
}
/**
* 本单是否还有「有实物动作、却没有出库流水」的行(逐 SKU 判据)。
* 与 `listOrdersMissingOutboundSettlement` 的取数判据同口径:用于结案兜底与定时补扣。
*/
async function orderHasPendingOutboundOnClient(
client: PoolClient,
orderCode: string
): Promise<boolean> {
const result = await client.query(
`SELECT 1
FROM picking_items pi
WHERE pi.order_code = $1
AND (COALESCE(pi.picked_qty, 0) > 0 OR COALESCE(pi.loaded_qty, 0) > 0)
AND NOT EXISTS (
SELECT 1 FROM inventory_logs il
WHERE il.related_order_code = $1
AND il.sku_code = pi.sku_code
AND il.operation_type IN ('picking_out', 'delivery_loading_out')
)
LIMIT 1`,
[orderCode]
);
return (result.rowCount || 0) > 0;
}
function trimSku(value: unknown): string {
return String(value || '').trim();
}
/** 验收流水备注:订单过手未写 inventory(含 inboundGapRepair 修复变体) */
export const PASS_THROUGH_LEDGER_SKIP_REMARK = '过手履约跳过库存台账';
/** 仓内加工成品验收不入可领库存,见 20260901-warehouse-finished-no-pickable-stock */
export const WAREHOUSE_FINISHED_LEDGER_SKIP_REMARK = '仓内加工成品不入可领库存';
/**
* 本单该 SKU 验收时故意不入可用库存。结案/发车扣库看履约事实,不看当前 stock_mode。
* 见 docs/design/20260828-complete-skip-passthrough-ledger.md、
* 20260901-warehouse-finished-no-pickable-stock.md
*/
export async function orderSkuSkippedPassThroughLedger(
client: PoolClient,
orderCode: string,
skuCode: string
): Promise<boolean> {
const code = trimSku(orderCode);
const sku = trimSku(skuCode);
if (!code || !sku) return false;
const result = await client.query(
`SELECT 1 FROM inventory_logs
WHERE related_order_code = $1
AND sku_code IS NOT DISTINCT FROM $2
AND operation_type = 'inspection_in'
AND (
remark ILIKE '%' || $3 || '%'
OR remark ILIKE '%' || $4 || '%'
)
LIMIT 1`,
[code, sku, PASS_THROUGH_LEDGER_SKIP_REMARK, WAREHOUSE_FINISHED_LEDGER_SKIP_REMARK]
);
return (result.rowCount || 0) > 0;
}
function businessError(message: string, status = 400): Error {
return Object.assign(new Error(message), { status, code: 'inventory_outbound' });
}
/**
* 从拣货行读「手选批次计划」⇒ 交给 `fifoDeductInventory` 优先扣。
*
* 计划来源三种,**同一个字段**:分拣员现场选的 / 抵扣时写的 FIFO 计划 / 我方在订单侧指定的
* (`source='manual_cover'`,见 `orderItemCoverBatchesService`)。
* ⚠️ **发车扣库与结案补扣必须同口径**(都用本函数)—— 只在一处传计划,另一处纯 FIFO,
* 就会出现"界面上写着扣这批、实际扣的是那批"(2026-10-13 方案甲一并收口)。
*/
async function loadPickItemBatchPlans(
client: PoolClient,
pickItemIds: Array<string | null | undefined>
): Promise<Map<string, Array<{ batchNo: string; qty: number }>>> {
const map = new Map<string, Array<{ batchNo: string; qty: number }>>();
const ids = pickItemIds.map((id) => String(id || '').trim()).filter(Boolean);
if (!ids.length) return map;
const planRes = await client.query(
`SELECT id, outbound_batches FROM picking_items WHERE id = ANY($1::uuid[])`,
[ids]
);
for (const pr of planRes.rows as Array<{ id?: unknown; outbound_batches?: unknown }>) {
const raw = pr.outbound_batches;
if (!Array.isArray(raw)) continue;
const plan: Array<{ batchNo: string; qty: number }> = [];
for (const x of raw as Array<{ batch_no?: unknown; batchNo?: unknown; qty?: unknown }>) {
const bn = String(x?.batch_no ?? x?.batchNo ?? '').trim();
const q = Number(x?.qty);
if (!bn || !Number.isFinite(q) || q <= 0) continue;
plan.push({ batchNo: bn, qty: q });
}
if (plan.length) map.set(String(pr.id), plan);
}
return map;
}
export async function fifoDeductInventory(
client: PoolClient,
input: {
skuCode: string;
qty: number;
branchCode?: string | null;
orderCode?: string | null;
pickCode: string;
pickItemId?: string | null;
operatorId?: string | null;
itemName?: string | null;
/** 默认分拣出库;配送核货发车用 delivery_loading_out;独立加工用 processing_out */
operationType?: 'picking_out' | 'delivery_loading_out' | 'processing_out';
remark?: string | null;
/** 默认 true:扣库不得超过「毛可用−他单预留」 */
respectOtherReservations?: boolean;
/** 手选批次计划(可选):按顺序/数量优先扣;**不传 = 纯 FIFO(逐字不变)** */
batchPlan?: Array<{ batchNo: string; qty: number }> | null;
},
onBatchDeducted?: (
batch: { batchNo: string; costPrice: number; supplierCode?: string | null; inboundAt?: string | null },
deductedQty: number,
costPrice: number
) => void
) {
let remaining = input.qty;
const operationType = input.operationType || 'picking_out';
const remark =
input.remark ||
(operationType === 'delivery_loading_out'
? `配送核货出库 ${input.pickCode}`
: `分拣出库 ${input.pickCode}`);
if (input.respectOtherReservations !== false && remaining > 0) {
let claimable = await getClaimableStockQty(
client,
input.skuCode,
input.branchCode,
input.orderCode || undefined
);
if (claimable + 1e-9 < remaining && input.branchCode) {
claimable = await getClaimableStockQty(client, input.skuCode, null, input.orderCode || undefined);
}
if (claimable + 1e-9 < remaining) {
const label = input.itemName ? `${input.itemName}(${input.skuCode})` : input.skuCode;
let hint = '';
if (input.orderCode) {
const peers = await listPurchaseMergePeerOrderCodes(client, {
orderCode: input.orderCode,
skuCode: input.skuCode,
});
if (peers.length) {
hint = `(与订单 ${peers.slice(0, 5).join('、')}${peers.length > 5 ? ' 等' : ''} 合单共用库存)`;
}
}
const short = Math.round((remaining - claimable) * 100) / 100;
const stage =
operationType === 'delivery_loading_out' ? 'depart' : 'picking';
await notifyInventoryShortage({
orderCode: input.orderCode,
branchCode: input.branchCode,
skuCode: input.skuCode,
itemName: input.itemName,
requiredQty: remaining,
availableQty: claimable,
shortQty: short,
hint: hint || null,
stage,
});
throw businessError(
`${label} 库存不足,缺少 ${short}(扣除他单预留后可用 ${claimable})${hint}`
);
}
}
const loadBatches = async (branchCode?: string | null, byBatchOnly = false) => {
if (byBatchOnly && input.pickItemId) {
const params: unknown[] = [input.pickItemId];
let branchFilter = '';
if (branchCode) {
params.push(branchCode);
branchFilter = `AND inv.branch_code = $${params.length}`;
}
return client.query(
`SELECT inv.id, inv.batch_no, inv.available_qty, inv.cost_price, inv.supplier_code, inv.created_at
FROM picking_items pi
JOIN inspections insp
ON insp.order_code = pi.order_code
AND TRIM(COALESCE(insp.item_name, '')) = TRIM(COALESCE(pi.item_name, ''))
AND insp.inbound_batch_no IS NOT NULL
JOIN inventory inv ON inv.batch_no = insp.inbound_batch_no
WHERE pi.id = $1
AND inv.available_qty > 0 ${branchFilter}
ORDER BY inv.created_at ASC, inv.expiry_date ASC NULLS FIRST
FOR UPDATE OF inv`,
params
);
}
const params: unknown[] = [input.skuCode];
let branchFilter = '';
if (branchCode) {
params.push(branchCode);
branchFilter = `AND branch_code = $${params.length}`;
}
// SELECT 里带上 supplier_code,供加工领料追溯来源
return client.query(
`SELECT id, batch_no, available_qty, cost_price, supplier_code, created_at FROM inventory
WHERE sku_code = $1 AND available_qty > 0 ${branchFilter}
ORDER BY created_at ASC, expiry_date ASC NULLS FIRST
FOR UPDATE`,
params
);
};
let batches = await loadBatches(input.branchCode);
// 加工领料(processing_out)禁止跨分公司兜底扣减:只能耗本分公司库存
if (!batches.rows.length && input.branchCode && operationType !== 'processing_out') {
batches = await loadBatches(null);
}
if (!batches.rows.length && input.pickItemId) {
batches = await loadBatches(input.branchCode, true);
if (!batches.rows.length && input.branchCode) {
batches = await loadBatches(null, true);
}
}
// 手选批次计划(可选):先按计划顺序/数量扣,其余批次按 FIFO 兜底。
// 不传 batchPlan ⇒ map 为空、orderedRows === batches.rows ⇒ 与改前逐字一致。
const planQtyByBatch = new Map<string, number>();
const planOrderByBatch = new Map<string, number>();
for (const p of input.batchPlan || []) {
const bn = String(p?.batchNo || '').trim();
const q = Number(p?.qty);
if (!bn || !Number.isFinite(q) || q <= 0) continue;
planQtyByBatch.set(bn, q);
if (!planOrderByBatch.has(bn)) planOrderByBatch.set(bn, planOrderByBatch.size);
}
let orderedRows: any[] = batches.rows;
if (planQtyByBatch.size) {
const planned: any[] = [];
const rest: any[] = [];
for (const row of batches.rows) {
if (planOrderByBatch.has(String(row.batch_no))) planned.push(row);
else rest.push(row);
}
planned.sort(
(a, b) =>
(planOrderByBatch.get(String(a.batch_no)) || 0) -
(planOrderByBatch.get(String(b.batch_no)) || 0)
);
orderedRows = [...planned, ...rest];
}
for (const batch of orderedRows) {
if (remaining <= 0) break;
const beforeQty = Number(batch.available_qty) || 0;
// 手选批次:本批扣减不超过「该批可用」与「计划指定量」的较小者
const planCap = planQtyByBatch.get(String(batch.batch_no));
const deductQty = Math.min(planCap != null ? Math.min(beforeQty, planCap) : beforeQty, remaining);
if (deductQty <= 0) continue;
const afterQty = Math.round((beforeQty - deductQty) * 100) / 100;
remaining = Math.round((remaining - deductQty) * 100) / 100;
const batchCostPrice = Number(batch.cost_price) || 0;
const updated = await client.query(
`UPDATE inventory SET available_qty = $1 WHERE id = $2 AND available_qty >= $3`,
[afterQty, batch.id, deductQty]
);
if ((updated.rowCount || 0) === 0) throw businessError('库存并发冲突,请重试');
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, $3, $4, $5, $6, $7, $8, $9)`,
[
batch.batch_no,
input.skuCode,
operationType,
deductQty,
beforeQty,
afterQty,
input.orderCode,
input.operatorId || null,
remark,
]
);
if (onBatchDeducted) {
onBatchDeducted(
{
batchNo: String(batch.batch_no),
costPrice: batchCostPrice,
supplierCode: batch.supplier_code != null ? String(batch.supplier_code) : null,
inboundAt: batch.created_at ? new Date(batch.created_at).toISOString() : null,
},
deductQty,
batchCostPrice
);
}
}
if (remaining > 0) {
const label = input.itemName ? `${input.itemName}(${input.skuCode})` : input.skuCode;
const stage =
operationType === 'delivery_loading_out' ? 'depart' : 'picking';
if (operationType !== 'processing_out') {
await notifyInventoryShortage({
orderCode: input.orderCode,
branchCode: input.branchCode,
skuCode: input.skuCode,
itemName: input.itemName,
requiredQty: input.qty,
shortQty: remaining,
stage,
});
}
throw businessError(`${label} 库存不足,缺少 ${remaining}`);
}
}
/** 订单是否已通过分拣或配送核货扣过库存 */
export async function orderHasInventoryOutbound(orderCode: string): Promise<boolean> {
const result = await pool.query(
`SELECT 1 FROM inventory_logs
WHERE related_order_code = $1
AND operation_type IN ('picking_out', 'delivery_loading_out')
LIMIT 1`,
[orderCode]
);
return (result.rowCount || 0) > 0;
}
/**
* 无分拣出库时:司机核货完成并开始配送,按核货明细 FIFO 扣减可用库存。
* 已有 picking_out / delivery_loading_out 则跳过(幂等)。
* softInventory:库存不足不抛错(发车仍可继续),逐行尽量扣、失败行跳过。
*/
export async function deductInventoryForOrderDeparture(
orderCode: string,
options?: {
operatorId?: string | null;
taskCode?: string | null;
client?: PoolClient;
/** 设计:20260807-depart-no-inventory-gate — 发车不因库存硬拦 */
softInventory?: boolean;
/**
* 出库流水的类型:`picking_out` = **分拣出库**(分拣完毕 45→50、10 分钟兜底补写),
* `delivery_loading_out` = **配送核货出库**(发车 50→60、结案 60→90)。
*
* ⚠️ 两条链路必须分开记(2026-10-13 开发者批准):分拣出库与配送核货出库是**不同履约环节**,
* 备注也据此区分(`分拣出库 <pickCode>` / `配送核货出库 <pickCode>`),排障时看备注即可定位。
* 幂等守卫两种类型都认(`orderHasOutboundOnClient`)⇒ 分拣/发车/结案三条路互不重复扣。
*
* 历史说明:原先还有 `restoreInventoryForOrderDeparture`(发车失败回补),它**只回补
* `delivery_loading_out`**、不回补 `picking_out` —— 正因如此分拣口径当初才改用 `picking_out`。
* 该函数在生产代码里**没有任何调用方**,已按开发者指示作为死代码删除(2026-10-13);
* `delivery_loading_restore` 这一历史流水类型的展示文案保留,老数据仍可读。
*/
operationType?: 'picking_out' | 'delivery_loading_out';
}
): Promise<{
deducted: boolean;
skipped: boolean;
reason?: string;
softSkipped?: Array<{ sku: string; itemName: string | null; qty: number; message: string }>;
}> {
const code = String(orderCode || '').trim();
if (!code) return { deducted: false, skipped: true, reason: 'missing_order' };
const softInventory = options?.softInventory === true;
const external = options?.client;
const ownsTxn = !external;
const client = external || (await pool.connect());
try {
if (ownsTxn) await client.query('BEGIN');
/**
* ⚠️ **必须先锁订单行(`FOR UPDATE`)再查幂等流水**(2026-10-13 对抗式复核)。
*
* 分拣完成(45→50)没有外层 `withOrderLock`:两条"确认分拣完成"路径(或与 15 分钟对账)
* 会各自开事务。若先查 `inventory_logs`,两边都在各自快照里判"尚无出库" ⇒ 各自扣一遍;
* 原来的 `orders ... FOR SHARE` 只是共享锁、互不阻塞,挡不住。
* 改成对 `orders` 行取独占锁:后到者阻塞到先到者提交,再查流水就能看见并短路。
* 与 50→60 / 结案路径一致(它们外层已持 `withOrderLock`,同事务内重入独占锁无冲突)。
*/
const orderResult = await client.query(
`SELECT order_code, branch_code FROM orders WHERE order_code = $1 FOR UPDATE`,
[code]
);
const order = orderResult.rows[0];
if (!order) {
throw businessError('订单不存在', 404);
}
const branchCode = order.branch_code ? String(order.branch_code) : null;
/**
* **逐 SKU 幂等**(2026-10-14 审计 P0-3):先取"本单已扣过的 SKU",
* 后面只扣**还没扣过**的行。整单守卫已废弃 —— 它会把"分拣时库存不足被软扣跳过"的 SKU 永久漏掉。
* 仍持 `orders ... FOR UPDATE` 独占锁:并发两路(分拣完成 / 15 分钟对账)串行进入,后到者能看见先到者的流水。
*/
const outboundSkus = await loadOutboundStateOnClient(client, code);
/**
* 快路径(保留旧契约 + 省一次计划查询):**已有出库流水、且已经没有任何"有实物动作却没流水"的行**
* ⇒ 本单无事可做,直接 `already_outbound`。
* 注意判据是"逐 SKU 是否还有缺",不是"整单有没有流水"——后者会把分拣软扣跳过的 SKU 永久漏掉(P0-3)。
*
* ⚠️ 老数据里出库流水可能没有 `sku_code`(`hasAny` 为真但 SKU 集合为空)⇒ 无法逐 SKU 归因,
* 此时**退回旧的整单语义**(宁可少扣一次,也不能凭"归因不了"再扣一遍)。
*/
if (
outboundSkus.hasAny &&
(outboundSkus.skus.size === 0 || !(await orderHasPendingOutboundOnClient(client, code)))
) {
if (ownsTxn) await client.query('COMMIT');
return { deducted: false, skipped: true, reason: 'already_outbound' };
}
const outboundSkuSet = outboundSkus.skus;
const itemsResult = await client.query(
`SELECT pi.id, pi.order_item_id, pi.pick_code, pi.item_name, pi.sku_code, pi.unit,
pi.loaded_qty, pi.picked_qty, pi.required_qty,
oi.sku_code AS order_sku,
catalog.code AS catalog_sku,
pt.branch_code AS pick_branch,
COALESCE(skip_sup.skip_inbound, false) AS skip_inbound,
-- 极简流转(配送直供):该模式不采购、不入库,库存天然为 0,扣库必须跳过,
-- 否则完成配送时(ensureOrderInventorySettledOnComplete 走硬扣库)会抛
-- 「库存不足,缺少 N」并弹红字(2026-10-07 用户实测)。见
-- docs/design/20261007-direct-to-delivery-mode.md
COALESCE(ff.direct_delivery_cover, false) AS direct_delivery_cover,
-- 加菜:配送员/采购员在外面买的,**从未入库** ⇒ 无可扣之库(2026-10-07 用户确认)
COALESCE(oi.is_extra_dish, false) AS is_extra_dish,
${skuDirectDeliveryAppliesSql(
"COALESCE(NULLIF(TRIM(pi.sku_code), ''), NULLIF(TRIM(oi.sku_code), ''))",
'COALESCE(NULLIF(TRIM(oi.order_code), \'\'), NULLIF(TRIM(pi.order_code), \'\'), pt.order_code)'
)} AS sku_direct_delivery
FROM picking_items pi
JOIN picking_tasks pt ON pt.pick_code = pi.pick_code
LEFT JOIN order_items oi ON oi.id = pi.order_item_id
LEFT JOIN suppliers skip_sup ON skip_sup.supplier_code = oi.supplier_code
LEFT JOIN order_item_fulfillments ff ON ff.order_item_id = pi.order_item_id
LEFT JOIN skus sku_dd ON sku_dd.sku_code = COALESCE(NULLIF(TRIM(pi.sku_code), ''), NULLIF(TRIM(oi.sku_code), ''))
LEFT JOIN product_catalog catalog ON catalog.item_type = 'product'
AND TRIM(catalog.name) = TRIM(pi.item_name)
WHERE pi.order_code = $1
OR pt.order_code = $1
ORDER BY pi.sort_order NULLS LAST, pi.created_at ASC`,
[code]
);
if (!itemsResult.rows.length) {
if (ownsTxn) await client.query('COMMIT');
return { deducted: false, skipped: true, reason: 'no_loading_items' };
}
// 合单/补录会产生「旧任务 0 拣 + 新任务已拣」多行;按明细去重且不以 required 兜底,
// 否则发车会把幽灵行应拣量再扣一遍(设计:20260807-depart-dedupe-zero-pick-lines)。
type DepartLine = {
id: string;
pick_code: string;
item_name: string | null;
sku: string;
pick_branch: string | null;
qty: number;
needSkuBackfill: boolean;
};
const bestByItem = new Map<string, DepartLine>();
for (const row of itemsResult.rows) {
const skipInbound =
row.skip_inbound === true || row.skip_inbound === 't' || row.skip_inbound === 'true';
const skuDirect =
row.sku_direct_delivery === true ||
row.sku_direct_delivery === 't' ||
row.sku_direct_delivery === 'true';
// 配送直供(极简流转):与免入库/直送同款处理 —— 这些货从未入库,无可扣之库
const directDeliveryCover =
row.direct_delivery_cover === true ||
row.direct_delivery_cover === 't' ||
row.direct_delivery_cover === 'true';
// 加菜同上:不入库 ⇒ 无可扣之库(结案补扣计划里同样排除,见 planDeductLinesForOrder)
const extraDish =
row.is_extra_dish === true || row.is_extra_dish === 't' || row.is_extra_dish === 'true';
if (skipInbound || skuDirect || directDeliveryCover || extraDish) continue;
const sku =
trimSku(row.sku_code) || trimSku(row.order_sku) || trimSku(row.catalog_sku);
if (!sku) continue;
const loaded = Number(row.loaded_qty) || 0;
const picked = Number(row.picked_qty) || 0;
// 配送核货确认会写 loaded;无装无拣的幽灵行不扣
const qty = loaded > 0 ? loaded : picked > 0 ? picked : 0;
if (qty <= 0) continue;
const itemKey = trimSku(row.order_item_id) || String(row.id);
const prev = bestByItem.get(itemKey);
if (prev && prev.qty >= qty) continue;
bestByItem.set(itemKey, {
id: String(row.id),
pick_code: String(row.pick_code || ''),
item_name: row.item_name,
sku,
pick_branch: row.pick_branch ? String(row.pick_branch) : null,
qty,
needSkuBackfill: !trimSku(row.sku_code),
});
}
const allLines = [...bestByItem.values()];
if (!allLines.length) {
// 有明细但无实装/实拣:软模式下不拦发车(品类闸门在装车完成)
await consumeReservationsForOrder(client, code);
if (ownsTxn) await client.query('COMMIT');
return {
deducted: false,
skipped: true,
reason: softInventory ? 'no_settlement_qty' : 'no_loading_items',
};
}
/** 逐 SKU 幂等:已扣过的行跳过,只扣"还没扣过"的(P0-3) */
const deductLines = allLines.filter((line) => !outboundSkuSet.has(line.sku));
if (!deductLines.length) {
await consumeReservationsForOrder(client, code);
if (ownsTxn) await client.query('COMMIT');
return { deducted: false, skipped: true, reason: 'already_outbound' };
}
const pickCode =
deductLines[0].pick_code ||
String(options?.taskCode || '') ||
`DL-${code}`;
// 分拣「完成」时手选的出库批次计划(picking_items.outbound_batches)⇒ 发车优先按它扣;无则纯 FIFO。
const planById = await loadPickItemBatchPlans(
client,
deductLines.map((r) => String(r.id))
);
const softSkipped: Array<{
sku: string;
itemName: string | null;
qty: number;
message: string;
}> = [];
let deductedAny = false;
/** 出库留痕:逐批次(品名/批次/入库日/数量) */
const departDetail: Array<{
sku_code: string | null;
sku_name: string | null;
batch_no: string;
inbound_at: string | null;
qty: number;
}> = [];
for (const row of deductLines) {
if (row.needSkuBackfill) {
await client.query(`UPDATE picking_items SET sku_code = $2 WHERE id = $1`, [
row.id,
row.sku,
]);
}
const passThrough = await isPassThroughSku(
{ skuCode: row.sku, branchCode: row.pick_branch || branchCode },
client
);
if (
passThrough ||
(await orderSkuSkippedPassThroughLedger(client, code, row.sku))
) {
continue;
}
try {
await fifoDeductInventory(client, {
skuCode: row.sku,
qty: row.qty,
branchCode: row.pick_branch || branchCode,
orderCode: code,
pickCode,
pickItemId: row.id,
operatorId: options?.operatorId || null,
itemName: row.item_name,
operationType: options?.operationType || 'delivery_loading_out',
remark:
(options?.operationType || 'delivery_loading_out') === 'picking_out'
? `分拣出库 ${pickCode}`
: `配送核货出库 ${options?.taskCode || pickCode}`,
batchPlan: planById.get(String(row.id)) || undefined,
},
(batch, deductedQty) => {
departDetail.push({
sku_code: row.sku || null,
sku_name: row.item_name ? String(row.item_name) : null,
batch_no: batch.batchNo,
inbound_at: batch.inboundAt ?? null,
qty: deductedQty,
});
});
deductedAny = true;
} catch (error: any) {
if (softInventory && (error?.code === 'inventory_outbound' || error?.status === 400)) {
softSkipped.push({
sku: row.sku,
itemName: row.item_name,
qty: row.qty,
message: String(error?.message || '库存不足'),
});
continue;
}
throw error;
}
}
await consumeReservationsForOrder(client, code);
if (ownsTxn) await client.query('COMMIT');
// 出库留痕到系统操作日志(操作人 + 分拣员 + 逐批次:品名/批次/入库日/数量)
if (departDetail.length) {
// 「留痕」不承担正确性:用 SAVEPOINT 隔离,任何失败只回滚这一段,绝不 abort 扣库事务
const outboundAuditSavepoint = 'sp_outbound_audit';
await client.query(`SAVEPOINT ${outboundAuditSavepoint}`).catch(() => undefined);
try {
const pickCodes = Array.from(
new Set(deductLines.map((r) => String(r.pick_code || '')).filter(Boolean))
);
let pickerIds: string[] = [];
let pickerNames: string[] = [];
if (pickCodes.length) {
const pr = await pool.query(
/**
* ⚠️ 列名必须是 `full_name`(2026-10-13 真库事故):
* 原写成 `p.name`,而 `public.profiles` 上**没有 name 列**(只有 username/full_name)
* ⇒ 这条"留痕用"的查询报 `column p.name does not exist` ⇒ **把整个出库扣库事务 abort**
* (语句失败后事务进 aborted 态,后面的扣库语句全被拒),而错误又被下面的 catch 吞掉,
* 只留一行 `[depart] writeAuditLog(outbound) failed:` ⇒ 表现为"库存从来没扣过"。
* 真库实证:BR003 `inventory_logs` 里 `delivery_loading_out` / `picking_out` **0 条**。
* 另见下方 SAVEPOINT:留痕再出问题也不许拖垮扣库。
*/
`SELECT DISTINCT pt.uid, p.full_name AS name
FROM (
SELECT COALESCE(reviewer_id, pick_completed_by) AS uid
FROM picking_tasks WHERE pick_code = ANY($1::text[])
) pt
LEFT JOIN public.profiles p ON p.id = pt.uid
WHERE pt.uid IS NOT NULL`,
[pickCodes]
);
pickerIds = pr.rows.map((r) => String(r.uid)).filter((v) => v && v !== 'null');
pickerNames = Array.from(
new Set(
pr.rows
.map((r) => (r.name != null ? String(r.name).trim() : ''))
.filter(Boolean)
)
);
}
await writeAuditLog({
operatorId: options?.operatorId || null,
operationType: 'picking_outbound',
targetTable: 'orders',
targetId: code,
oldValue: null,
newValue: {
order_code: code,
pick_codes: pickCodes,
picker_ids: pickerIds,
picker_names: pickerNames,
batches: departDetail,
},
branchCode: branchCode || null,
actionCategory: 'inventory',
});
await client.query(`RELEASE SAVEPOINT ${outboundAuditSavepoint}`).catch(() => undefined);
} catch (auditError) {
console.error('[depart] writeAuditLog(outbound) failed:', auditError);
// 回滚到 SAVEPOINT:把事务从 aborted 态救回来,扣库结果不受留痕影响
await client.query(`ROLLBACK TO SAVEPOINT ${outboundAuditSavepoint}`).catch(() => undefined);
}
}
if (softSkipped.length && !deductedAny) {
return {
deducted: false,
skipped: true,
reason: 'soft_inventory_skip',
softSkipped,
};
}
return {
deducted: deductedAny,
skipped: !deductedAny,
reason: softSkipped.length ? 'partial_soft_skip' : undefined,
softSkipped: softSkipped.length ? softSkipped : undefined,
};
} catch (error) {
if (ownsTxn) await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
if (ownsTxn) client.release();
}
}
export type MissingOutboundOrder = {
order_code: string;
branch_code: string | null;
order_status: number;
delivery_date: string | null;
};
export type BackfillDeductLine = {
sku_code: string;
item_name: string | null;
qty: number;
source: 'loading' | 'inspection';
available_qty: number;
};
export type BackfillOrderResult = {
order_code: string;
branch_code: string | null;
status: 'deducted' | 'skipped' | 'failed' | 'planned';
reason?: string;
lines?: BackfillDeductLine[];
error?: string;
};
/** 已发车但缺少出库流水的订单 */
export async function listOrdersMissingDeliveryOutbound(input?: {
branchCode?: string | null;
orderCode?: string | null;
since?: string | null;
limit?: number;
}): Promise<MissingOutboundOrder[]> {
const limit = Math.max(1, Math.min(5000, Number(input?.limit) || 500));
const params: unknown[] = [];
const filters: string[] = [
`o.order_status >= 60`,
`EXISTS (
SELECT 1 FROM delivery_tasks dt
WHERE dt.order_code = o.order_code AND COALESCE(dt.task_status, 0) >= 20
)`,
`EXISTS (
SELECT 1 FROM inventory_logs il
WHERE il.related_order_code = o.order_code AND il.operation_type = 'inspection_in'
)`,
`NOT EXISTS (
SELECT 1 FROM inventory_logs il
WHERE il.related_order_code = o.order_code
AND il.operation_type IN ('picking_out', 'delivery_loading_out')
)`,
];
if (input?.orderCode) {
params.push(String(input.orderCode).trim());
filters.push(`o.order_code = $${params.length}`);
}
if (input?.branchCode) {
params.push(String(input.branchCode).trim());
filters.push(`o.branch_code = $${params.length}`);
}
if (input?.since) {
params.push(String(input.since).trim());
filters.push(`o.delivery_date >= $${params.length}::date`);
}
params.push(limit);
const result = await pool.query(
`SELECT o.order_code, o.branch_code, o.order_status,
o.delivery_date::text AS delivery_date
FROM orders o
WHERE ${filters.join('\n AND ')}
ORDER BY o.delivery_date DESC NULLS LAST, o.order_code
LIMIT $${params.length}`,
params
);
return result.rows.map((row) => ({
order_code: String(row.order_code),
branch_code: row.branch_code ? String(row.branch_code) : null,
order_status: Number(row.order_status) || 0,
delivery_date: row.delivery_date ? String(row.delivery_date) : null,
}));
}
async function sumAvailableQty(
client: PoolClient,
skuCode: string,
branchCode?: string | null
): Promise<number> {
const params: unknown[] = [skuCode];
let branchFilter = '';
if (branchCode) {
params.push(branchCode);
branchFilter = `AND branch_code = $${params.length}`;
}
const result = await client.query(
`SELECT COALESCE(SUM(available_qty), 0)::float AS total
FROM inventory
WHERE sku_code = $1 AND available_qty > 0 ${branchFilter}`,
params
);
return Number(result.rows[0]?.total) || 0;
}
async function planDeductLinesForOrder(
client: PoolClient,
orderCode: string,
branchCode: string | null
): Promise<{
lines: Array<BackfillDeductLine & { pick_item_id?: string | null; pick_code?: string | null }>;
source: 'loading' | 'inspection' | 'none';
}> {
const loading = await client.query(
`SELECT pi.id, pi.order_item_id, pi.pick_code, pi.item_name, pi.sku_code,
pi.loaded_qty, pi.picked_qty, pi.required_qty,
oi.sku_code AS order_sku, catalog.code AS catalog_sku,
COALESCE(skip_sup.skip_inbound, false) AS skip_inbound,
${skuDirectDeliveryAppliesSql(
"COALESCE(NULLIF(TRIM(pi.sku_code), ''), NULLIF(TRIM(oi.sku_code), ''))",
"COALESCE(NULLIF(TRIM(oi.order_code), ''), NULLIF(TRIM(pi.order_code), ''), pt.order_code)"
)} AS sku_direct_delivery,
COALESCE(ff.direct_delivery_cover, false) AS direct_delivery_cover,
COALESCE(oi.is_extra_dish, false) AS is_extra_dish
FROM picking_items pi
JOIN picking_tasks pt ON pt.pick_code = pi.pick_code
LEFT JOIN order_items oi ON oi.id = pi.order_item_id
LEFT JOIN suppliers skip_sup ON skip_sup.supplier_code = oi.supplier_code
LEFT JOIN order_item_fulfillments ff ON ff.order_item_id = pi.order_item_id
LEFT JOIN skus sku_dd ON sku_dd.sku_code = COALESCE(NULLIF(TRIM(pi.sku_code), ''), NULLIF(TRIM(oi.sku_code), ''))
LEFT JOIN product_catalog catalog ON catalog.item_type = 'product'
AND TRIM(catalog.name) = TRIM(pi.item_name)
WHERE pi.order_code = $1 OR pt.order_code = $1
ORDER BY pi.sort_order NULLS LAST, pi.created_at ASC`,
[orderCode]
);
const lines: Array<BackfillDeductLine & { pick_item_id?: string | null; pick_code?: string | null }> =
[];
if (loading.rows.length) {
const bestByItem = new Map<
string,
{
sku: string;
item_name: string | null;
qty: number;
pick_item_id: string | null;
pick_code: string | null;
}
>();
for (const row of loading.rows) {
// 直送免入库行没有库存批次,不进入扣库计划(与发车扣库口径一致);
// 「配送直供」(极简流转)同理:不采购不入库,库存天然为 0,否则结案前会抛
// 「结案前扣库失败:… 需 N,可用 0」(2026-10-07 用户实测)。
if (
row.skip_inbound === true ||
row.skip_inbound === 't' ||
row.skip_inbound === 'true' ||
row.sku_direct_delivery === true ||
row.sku_direct_delivery === 't' ||
row.sku_direct_delivery === 'true' ||
row.direct_delivery_cover === true ||
row.direct_delivery_cover === 't' ||
row.direct_delivery_cover === 'true' ||
// 加菜:从未入库 ⇒ 无可扣之库(与发车扣库口径一致)
row.is_extra_dish === true ||
row.is_extra_dish === 't' ||
row.is_extra_dish === 'true'
) {
continue;
}
const sku =
trimSku(row.sku_code) || trimSku(row.order_sku) || trimSku(row.catalog_sku);
if (!sku) continue;
const loaded = Number(row.loaded_qty) || 0;
const picked = Number(row.picked_qty) || 0;
const qty = loaded > 0 ? loaded : picked > 0 ? picked : 0;
if (qty <= 0) continue;
const itemKey = trimSku(row.order_item_id) || String(row.id);
const prev = bestByItem.get(itemKey);
if (prev && prev.qty >= qty) continue;
bestByItem.set(itemKey, {
sku,
item_name: row.item_name ? String(row.item_name) : null,
qty,
pick_item_id: row.id ? String(row.id) : null,
pick_code: row.pick_code ? String(row.pick_code) : null,
});
}
for (const row of bestByItem.values()) {
if (await isPassThroughSku({ skuCode: row.sku, branchCode }, client)) continue;
if (await orderSkuSkippedPassThroughLedger(client, orderCode, row.sku)) continue;
lines.push({
sku_code: row.sku,
item_name: row.item_name,
qty: row.qty,
source: 'loading',
available_qty: await sumAvailableQty(client, row.sku, branchCode),
pick_item_id: row.pick_item_id,
pick_code: row.pick_code,
});
}
if (lines.length) return { lines, source: 'loading' };
}
const inspections = await client.query(
`SELECT i.item_name, i.sku_code, i.actual_qty,
catalog.code AS catalog_sku
FROM inspections i
LEFT JOIN product_catalog catalog ON catalog.item_type = 'product'
AND TRIM(catalog.name) = TRIM(i.item_name)
WHERE i.order_code = $1
AND i.inbound_batch_no IS NOT NULL
AND COALESCE(i.actual_qty, 0) > 0`,
[orderCode]
);
for (const row of inspections.rows) {
const sku = trimSku(row.sku_code) || trimSku(row.catalog_sku);
if (!sku) continue;
const qty = Number(row.actual_qty) || 0;
if (qty <= 0) continue;
if (await isPassThroughSku({ skuCode: sku, branchCode }, client)) continue;
if (await orderSkuSkippedPassThroughLedger(client, orderCode, sku)) continue;
lines.push({
sku_code: sku,
item_name: row.item_name ? String(row.item_name) : null,
qty,
source: 'inspection',
available_qty: await sumAvailableQty(client, sku, branchCode),
});
}
return { lines, source: lines.length ? 'inspection' : 'none' };
}
/**
* 运维回冲:为单笔已发车缺出库流水的订单补扣库存。
* dryRun=true 时只返回拟扣明细,不写库。
*/
export async function backfillDeliveryLoadingOutboundForOrder(
orderCode: string,
options?: {
dryRun?: boolean;
operatorId?: string | null;
remark?: string | null;
}
): Promise<BackfillOrderResult> {
const code = String(orderCode || '').trim();
if (!code) {
return { order_code: '', branch_code: null, status: 'skipped', reason: 'missing_order' };
}
if (await orderHasInventoryOutbound(code)) {
return { order_code: code, branch_code: null, status: 'skipped', reason: 'already_outbound' };
}
const client = await pool.connect();
try {
await client.query('BEGIN');
const orderResult = await client.query(
`SELECT order_code, branch_code FROM orders WHERE order_code = $1 FOR SHARE`,
[code]
);
const order = orderResult.rows[0];
if (!order) {
await client.query('ROLLBACK');
return { order_code: code, branch_code: null, status: 'failed', error: '订单不存在' };
}
const branchCode = order.branch_code ? String(order.branch_code) : null;
const again = await client.query(
`SELECT 1 FROM inventory_logs
WHERE related_order_code = $1
AND operation_type IN ('picking_out', 'delivery_loading_out')
LIMIT 1
FOR SHARE`,
[code]
);
if (again.rowCount) {
await client.query('COMMIT');
return { order_code: code, branch_code: branchCode, status: 'skipped', reason: 'already_outbound' };
}
const plan = await planDeductLinesForOrder(client, code, branchCode);
if (!plan.lines.length) {
await client.query('COMMIT');
return {
order_code: code,
branch_code: branchCode,
status: 'skipped',
reason: 'no_deduct_lines',
lines: [],
};
}
const short = plan.lines.filter((line) => line.available_qty + 1e-6 < line.qty);
if (short.length) {
const parts: string[] = [];
for (const line of short) {
let msg = `${line.item_name || line.sku_code} 需 ${line.qty},可用 ${line.available_qty}`;
const peers = await listPurchaseMergePeerOrderCodes(client, {
orderCode: code,
skuCode: String(line.sku_code || ''),
});
if (peers.length) {
msg += `(与订单 ${peers.slice(0, 5).join('、')}${peers.length > 5 ? ' 等' : ''} 合单共用库存)`;
}
parts.push(msg);
}
await client.query('ROLLBACK');
return {
order_code: code,
branch_code: branchCode,
status: 'failed',
reason: 'insufficient_stock',
lines: plan.lines,
error: parts.join(';'),
};
}
if (options?.dryRun) {
await client.query('ROLLBACK');
return {
order_code: code,
branch_code: branchCode,
status: 'planned',
reason: plan.source,
lines: plan.lines,
};
}
const remark = options?.remark || `配送核货出库回冲 ${code}`;
const pickCode = plan.lines[0]?.pick_code || `BF-${code}`;
for (const line of plan.lines) {
await fifoDeductInventory(client, {
skuCode: line.sku_code,
qty: line.qty,
branchCode,
orderCode: code,
pickCode,
pickItemId: line.pick_item_id || null,
operatorId: options?.operatorId || null,
itemName: line.item_name,
operationType: 'delivery_loading_out',
remark,
});
}
await consumeReservationsForOrder(client, code);
await client.query('COMMIT');
return {
order_code: code,
branch_code: branchCode,
status: 'deducted',
reason: plan.source,
lines: plan.lines,
};
} catch (error: any) {
await client.query('ROLLBACK').catch(() => undefined);
return {
order_code: code,
branch_code: null,
status: 'failed',
error: error?.message || String(error),
};
} finally {
client.release();
}
}
/**
* 运维清理:订单已 ≥60 仍 status=10 的预留 → 按预留量 FIFO 扣库并消费预留。
* 不要求整单装车明细都能扣(避免历史单部分 0 库存堵死老姜等有货行)。
*/
export async function cleanupStaleReservationsForCompletedOrders(options?: {
branchCode?: string | null;
operatorId?: string | null;
dryRun?: boolean;
}): Promise<
Array<{
order_code: string;
sku_code: string;
item_name: string | null;
reserved_qty: number;
deducted_qty: number;
status: 'planned' | 'deducted' | 'consumed_only' | 'skipped' | 'failed';
error?: string;
}>
> {
const branch = String(options?.branchCode || '').trim() || null;
const listClient = await pool.connect();
let rows: Array<Record<string, unknown>> = [];
try {
const listed = await listClient.query(
`SELECT r.id, r.order_code, r.order_item_id, r.sku_code, r.qty::float AS qty, r.branch_code,
oi.item_name
FROM inventory_reservations r
JOIN orders o ON o.order_code = r.order_code
LEFT JOIN order_items oi ON oi.id = r.order_item_id
WHERE r.status = 10
AND o.order_status >= 60
AND ($1::text IS NULL OR r.branch_code IS NULL OR r.branch_code = $1 OR o.branch_code = $1)
ORDER BY o.delivery_date NULLS LAST, r.order_code, r.sku_code`,
[branch]
);
rows = listed.rows;
} finally {
listClient.release();
}
const out: Array<{
order_code: string;
sku_code: string;
item_name: string | null;
reserved_qty: number;
deducted_qty: number;
status: 'planned' | 'deducted' | 'consumed_only' | 'skipped' | 'failed';
error?: string;
}> = [];
for (const row of rows) {
const orderCode = String(row.order_code || '');
const skuCode = String(row.sku_code || '').trim();
const reservedQty = Number(row.qty) || 0;
const itemName = row.item_name ? String(row.item_name) : null;
const lineBranch = row.branch_code ? String(row.branch_code) : branch;
const reservId = String(row.id || '');
if (!skuCode || reservedQty <= 1e-9 || !reservId) {
out.push({
order_code: orderCode,
sku_code: skuCode,
item_name: itemName,
reserved_qty: reservedQty,
deducted_qty: 0,
status: 'skipped',
});
continue;
}
const probe = await pool.connect();
try {
const avail = await sumAvailableQty(probe, skuCode, lineBranch);
const deductQty = Math.min(reservedQty, avail);
if (options?.dryRun) {
out.push({
order_code: orderCode,
sku_code: skuCode,
item_name: itemName,
reserved_qty: reservedQty,
deducted_qty: deductQty,
status: 'planned',
});
continue;
}
} finally {
probe.release();
}
const client = await pool.connect();
try {
await client.query('BEGIN');
const locked = await client.query(
`SELECT id, qty::float AS qty FROM inventory_reservations
WHERE id = $1::uuid AND status = 10 FOR UPDATE`,
[reservId]
);
if (!locked.rowCount) {
await client.query('ROLLBACK');
out.push({
order_code: orderCode,
sku_code: skuCode,
item_name: itemName,
reserved_qty: reservedQty,
deducted_qty: 0,
status: 'skipped',
});
continue;
}
const avail = await sumAvailableQty(client, skuCode, lineBranch);
const deductQty = Math.min(Number(locked.rows[0].qty) || reservedQty, avail);
if (deductQty > 1e-9) {
await fifoDeductInventory(client, {
skuCode,
qty: deductQty,
branchCode: lineBranch,
orderCode,
pickCode: `CL-${orderCode}`,
pickItemId: row.order_item_id ? String(row.order_item_id) : null,
operatorId: options?.operatorId || null,
itemName,
operationType: 'delivery_loading_out',
remark: `幽灵预留清理出库 ${orderCode}`,
respectOtherReservations: true,
});
}
await client.query(
`UPDATE inventory_reservations
SET status = 20, updated_at = NOW()
WHERE id = $1::uuid AND status = 10`,
[reservId]
);
await client.query('COMMIT');
out.push({
order_code: orderCode,
sku_code: skuCode,
item_name: itemName,
reserved_qty: reservedQty,
deducted_qty: deductQty,
status: deductQty > 1e-9 ? 'deducted' : 'consumed_only',
});
} catch (error: any) {
await client.query('ROLLBACK').catch(() => undefined);
out.push({
order_code: orderCode,
sku_code: skuCode,
item_name: itemName,
reserved_qty: reservedQty,
deducted_qty: 0,
status: 'failed',
error: error?.message || String(error),
});
} finally {
client.release();
}
}
return out;
}
/**
* 订单结案前:幂等补出库(装车优先,否则验收实收)并消费预留。
* 真缺货时抛错,禁止带着幽灵预留完结。
*/
/**
* 兜底取数:**状态 50–89、有拣货实拣/核货量、却没有任何出库流水的单**(2026-10-13 开发者要求)。
*
* 用在调度器的「出库扣库兜底」(`scheduledJobs.runOutboundSettleBackfill`):
* 扣库时点前移到「分拣完成」之前就已经越过该时点的存量单,靠它被捞出来补扣。
* ⚠️ 只到 89:**已结案(90)的单不动** —— 历史结案白名单是有意跳过 FIFO 扣库的。
*/
export async function listOrdersMissingOutboundSettlement(limit = 30): Promise<string[]> {
const cap = Math.min(Math.max(Number(limit) || 30, 1), 200);
const result = await pool.query<{ order_code: string }>(
`SELECT o.order_code
FROM orders o
WHERE o.deleted_at IS NULL
AND o.order_status BETWEEN 50 AND 89
AND COALESCE(o.created_at, NOW()) > NOW() - INTERVAL '45 days'
AND EXISTS (
SELECT 1 FROM picking_items pi
WHERE pi.order_code = o.order_code
AND (COALESCE(pi.picked_qty, 0) > 0 OR COALESCE(pi.loaded_qty, 0) > 0)
-- **逐 SKU** 判据(2026-10-14 审计 P0-3):只要还有一个 SKU 没出库流水就捞它。
-- 原先按"整单有没有流水"判 ⇒ 分拣时被软扣跳过的 SKU 永远进不了兜底扫描。
AND NOT EXISTS (
SELECT 1 FROM inventory_logs il
WHERE il.related_order_code = o.order_code
AND il.sku_code = pi.sku_code
AND il.operation_type IN ('picking_out', 'delivery_loading_out')
)
)
ORDER BY o.updated_at DESC NULLS LAST
LIMIT $1`,
[cap]
);
return result.rows.map((row) => String(row.order_code || '')).filter(Boolean);
}
export async function ensureOrderInventorySettledOnComplete(
orderCode: string,
options?: {
operatorId?: string | null;
client?: PoolClient;
softInventory?: boolean;
/** 默认 `delivery_loading_out`(发车/结案口径);分拣完毕即出库传 `picking_out`(见上) */
operationType?: 'picking_out' | 'delivery_loading_out';
}
): Promise<{
deducted: boolean;
consumed_reservations: boolean;
reason?: string;
/** 软扣下因库存不足**没扣成**的行(P0-3:原先是"算了不报",调用方看不到缺口) */
softSkipped?: Array<{ sku: string; itemName: string | null; qty: number; message: string }>;
}> {
const code = String(orderCode || '').trim();
if (!code) return { deducted: false, consumed_reservations: false, reason: 'missing_order' };
const external = options?.client;
const ownsTxn = !external;
const client = external || (await pool.connect());
try {
if (ownsTxn) await client.query('BEGIN');
let deducted = false;
let reason: string | undefined;
let softSkipped: Array<{ sku: string; itemName: string | null; qty: number; message: string }> = [];
/**
* **逐 SKU 幂等**(2026-10-14 审计 P0-3):不再用"整单有没有出库流水"一票否决 ——
* 由 `deductInventoryForOrderDeparture` 内部按 SKU 跳过已扣的、补扣没扣的。
* 整单守卫的后果是「分拣软扣跳过的 SKU 在发车/结案/兜底三处全被挡住 ⇒ 永久漏扣」。
*/
const depart = await deductInventoryForOrderDeparture(code, {
client,
operatorId: options?.operatorId || null,
softInventory: options?.softInventory === true,
operationType: options?.operationType || 'delivery_loading_out',
});
deducted = depart.deducted;
softSkipped = depart.softSkipped || [];
reason = depart.deducted
? options?.operationType || 'delivery_loading_out'
: depart.reason;
if (softSkipped.length) {
reason = `partial_soft_skip:${depart.reason || reason || ''}`;
}
// 兜底:仍存在「有实物动作、却没有出库流水」的行(逐 SKU 判据)才进第二段(结案前硬扣口径)
if (await orderHasPendingOutboundOnClient(client, code)) {
const orderResult = await client.query(
`SELECT branch_code FROM orders WHERE order_code = $1 FOR SHARE`,
[code]
);
const branchCode = orderResult.rows[0]?.branch_code
? String(orderResult.rows[0].branch_code)
: null;
const plan = await planDeductLinesForOrder(client, code, branchCode);
const outboundState = await loadOutboundStateOnClient(client, code);
const pendingPlanLines = plan.lines.filter(
(line) => !outboundState.skus.has(String(line.sku_code))
);
if (pendingPlanLines.length) {
const soft = options?.softInventory === true;
const short = pendingPlanLines.filter((line) => line.available_qty + 1e-6 < line.qty);
if (short.length && !soft) {
const msg = short
.map(
(line) =>
`${line.item_name || line.sku_code} 需 ${line.qty},可用 ${line.available_qty}`
)
.join(';');
throw businessError(`结案前扣库失败:${msg}`, 400);
}
const pickCode = plan.lines[0]?.pick_code || `CF-${code}`;
// 结案补扣同样按「手选批次计划」扣(此前漏了 ⇒ 与界面/报告口径不一致)
const settlePlanById = await loadPickItemBatchPlans(
client,
pendingPlanLines.map((line) => line.pick_item_id)
);
let settledAny = false;
for (const line of pendingPlanLines) {
try {
await fifoDeductInventory(client, {
skuCode: line.sku_code,
qty: line.qty,
branchCode,
orderCode: code,
pickCode,
pickItemId: line.pick_item_id || null,
operatorId: options?.operatorId || null,
itemName: line.item_name,
operationType: options?.operationType || 'delivery_loading_out',
remark: `订单结案补扣出库 ${code}`,
batchPlan: settlePlanById.get(String(line.pick_item_id || '')) || undefined,
});
settledAny = true;
} catch (error: any) {
// 软扣(骑手上门取货收口):库存不足只记缺口、不阻断收口(与发车软扣一致)
if (soft && (error?.code === 'inventory_outbound' || error?.status === 400)) {
softSkipped.push({
sku: line.sku_code,
itemName: line.item_name ?? null,
qty: line.qty,
message: String(error?.message || '库存不足'),
});
continue;
}
throw error;
}
}
// ⚠️ 只有**真的扣成功**才算 deducted(P0-3:原先无条件置 true ⇒ 全行软扣失败也报"补扣成功")
if (settledAny) deducted = true;
reason = `complete_${plan.source}`;
}
}
await consumeReservationsForOrder(client, code);
// 仍有活跃预留则异常(consume 后不应存在)
const left = await client.query(
`SELECT COUNT(*)::int AS cnt FROM inventory_reservations
WHERE order_code = $1 AND status = 10`,
[code]
);
if (Number(left.rows[0]?.cnt || 0) > 0) {
throw businessError('结案后仍有未消费库存预留,请联系管理员', 500);
}
if (ownsTxn) await client.query('COMMIT');
return {
deducted,
consumed_reservations: true,
reason,
softSkipped: softSkipped.length ? softSkipped : undefined,
};
} catch (error) {
if (ownsTxn) await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
if (ownsTxn) client.release();
}
}