1536 lines
59 KiB
TypeScript
1536 lines
59 KiB
TypeScript
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';
|
||
import { resolveCompleteReceivedSettlementQty } from './orderItemSupplyUnitSync';
|
||
// 批次选择排序:规格匹配优先 → 先入库先出(全系统唯一一份,禁止别处再写)
|
||
import { batchSelectionOrderBy } from './inventoryBatchSelection';
|
||
import { catalogSkuBySpecJoin } from './catalogSkuBySpec';
|
||
|
||
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' | 'retail_out';
|
||
remark?: string | null;
|
||
/** 默认 true:扣库不得超过「毛可用−他单预留」 */
|
||
respectOtherReservations?: boolean;
|
||
/** 手选批次计划(可选):按顺序/数量优先扣;**不传 = 纯 FIFO(逐字不变)** */
|
||
batchPlan?: Array<{ batchNo: string; qty: number }> | null;
|
||
/**
|
||
* 加工领料专用(可选):一次豁免**全部**本单订单号的预留(SQL 数组)。
|
||
* 不传 ⇒ 旧口径逐字不变(只豁免 `orderCode` 一个)。
|
||
*/
|
||
reservationExemptOrderCodes?: string[] | 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,
|
||
input.reservationExemptOrderCodes
|
||
);
|
||
if (claimable + 1e-9 < remaining && input.branchCode) {
|
||
claimable = await getClaimableStockQty(
|
||
client,
|
||
input.skuCode,
|
||
null,
|
||
input.orderCode || undefined,
|
||
input.reservationExemptOrderCodes
|
||
);
|
||
}
|
||
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,
|
||
inv.spec
|
||
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
|
||
-- 订单行规格(2026-10-16 方案丙):客户要的是哪个规格;为空 ⇒ 排序退化为纯 FIFO
|
||
LEFT JOIN order_items oi ON oi.id = pi.order_item_id
|
||
WHERE pi.id = $1
|
||
AND inv.available_qty > 0 ${branchFilter}
|
||
ORDER BY ${batchSelectionOrderBy({ alias: 'inv', orderSpecSql: 'oi.spec' })}
|
||
FOR UPDATE OF inv`,
|
||
params
|
||
);
|
||
}
|
||
const params: unknown[] = [input.skuCode];
|
||
let branchFilter = '';
|
||
if (branchCode) {
|
||
params.push(branchCode);
|
||
branchFilter = `AND branch_code = $${params.length}`;
|
||
}
|
||
/**
|
||
* 订单行规格(2026-10-16 方案丙):客户要的是哪个规格。
|
||
*
|
||
* ⚠️ **给了 `pickItemId` 就必须取"该行自己"的规格**(对抗实测修正):同一张单里同一个 SKU
|
||
* 允许有两行、规格不同(行1 `1箱12瓶` / 行2 `1箱24瓶`),只看「订单 + SKU」会**任取一行**
|
||
* (原实现 `LIMIT 1` 且无 ORDER BY)⇒ 给行2 实扣会拿到行1 的规格、扣错批次。
|
||
* 行级取不到(该行没写规格 / 拣货行不存在)再退回「订单 + SKU」,且加 ORDER BY 保证确定性。
|
||
* 订单没写规格 / 找不到 ⇒ 表达式为 NULL ⇒ 排序**退化为纯 FIFO**(与改前逐字一致)。
|
||
*/
|
||
params.push(input.orderCode || null);
|
||
const orderCodeParam = `$${params.length}`;
|
||
let pickItemParam = '';
|
||
if (input.pickItemId) {
|
||
params.push(input.pickItemId);
|
||
pickItemParam = `$${params.length}`;
|
||
}
|
||
const byOrderSkuSpec =
|
||
`(SELECT NULLIF(TRIM(oi.spec), '') FROM order_items oi ` +
|
||
`WHERE oi.order_code = ${orderCodeParam} AND oi.sku_code = $1 AND NULLIF(TRIM(oi.spec), '') IS NOT NULL ` +
|
||
`ORDER BY oi.sort_order ASC NULLS LAST, oi.id ASC LIMIT 1)`;
|
||
const orderSpecExpr = pickItemParam
|
||
? `COALESCE((SELECT NULLIF(TRIM(oi.spec), '') FROM picking_items pi2 ` +
|
||
`JOIN order_items oi ON oi.id = pi2.order_item_id WHERE pi2.id = ${pickItemParam}), ${byOrderSkuSpec})`
|
||
: byOrderSkuSpec;
|
||
// SELECT 里带上 supplier_code,供加工领料追溯来源
|
||
return client.query(
|
||
`SELECT id, batch_no, available_qty, cost_price, supplier_code, created_at, spec FROM inventory
|
||
WHERE sku_code = $1 AND available_qty > 0 ${branchFilter}
|
||
ORDER BY ${batchSelectionOrderBy({ orderSpecSql: orderSpecExpr })}
|
||
FOR UPDATE`,
|
||
params
|
||
);
|
||
};
|
||
|
||
/**
|
||
* ⚠️ **库存枚举只有一条口径:「订单 + SKU」**(能看到该 SKU 的**全部**批次)。
|
||
*
|
||
* 2026-10-16 第二轮对抗实测(B1)的教训:曾把"行级"SQL 提到最前面,本意是用它拿"该行自己的规格",
|
||
* 但那条 SQL 只 `JOIN inspections`(**只看得见本单本行验收报告关联到的那几批**)⇒ 子集**非空但量不够**时,
|
||
* 因为兜底守卫是"结果为空才退",就再也不会退回全 SKU 批次 ⇒ **库存明明充足却报"库存不足,缺少 N"**:
|
||
* 分拣出库(`picking_out`)直接失败;发车/结案走 `softInventory` 时错误被吞 ⇒ **货发走、库存不扣**(账实不符)。
|
||
* ⇒ **规格来源与库存来源必须分开**:库存枚举保持「订单 + SKU」,
|
||
* 规格用 `orderSpecExpr` 的 `COALESCE(按本行取, 按订单+SKU 取)`(上面已实现)。
|
||
* 行级 SQL 只保留为**最后兜底**(该 SKU 在 `inventory` 里没有可用行时的既有语义,**与改前逐字一致**)。
|
||
*/
|
||
const canCrossBranch = operationType !== 'processing_out';
|
||
let batches = await loadBatches(input.branchCode);
|
||
if (!batches.rows.length && input.branchCode && canCrossBranch) {
|
||
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' | 'retail_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, pi.picked_weight,
|
||
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), ''))
|
||
${catalogSkuBySpecJoin({ nameExpr: 'pi.item_name', specExpr: 'oi.spec' })}
|
||
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;
|
||
|
||
// 数量与「计划量对齐 / 界面实收」同一口径(重量 → 真人改过的实配 → 实拣数量 → 镜像实配):
|
||
// 斤类原来完全不看重量 ⇒ 出现「扣库按数量、计划量按重量」的错位,2026-10-15 统一。
|
||
const qty =
|
||
resolveCompleteReceivedSettlementQty(
|
||
row.picked_weight,
|
||
row.loaded_qty,
|
||
row.unit,
|
||
row.picked_qty,
|
||
row.required_qty
|
||
) || 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, pi.unit, pi.picked_weight,
|
||
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), ''))
|
||
${catalogSkuBySpecJoin({ nameExpr: 'pi.item_name', specExpr: 'oi.spec' })}
|
||
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 qty =
|
||
resolveCompleteReceivedSettlementQty(
|
||
row.picked_weight,
|
||
row.loaded_qty,
|
||
row.unit,
|
||
row.picked_qty,
|
||
row.required_qty
|
||
) || 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
|
||
${catalogSkuBySpecJoin({ nameExpr: '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');
|
||
/**
|
||
* **事件驱动报告推送**(2026-10-24 核查项 1):发车核货出库(`delivery_loading_out`)是报告候选源②,
|
||
* 这一刻才知道实际消耗的批次 ⇒ 入队这一单,别等每日全量兜底。失败不影响出库。
|
||
*/
|
||
try {
|
||
const { enqueueReportPush } = await import('./reportPushQueueService');
|
||
if (branchCode) {
|
||
await enqueueReportPush({
|
||
branchCode: String(branchCode),
|
||
kind: 'register' as const,
|
||
ourOrderCode: code,
|
||
reason: '发车核货出库(delivery_loading_out)',
|
||
});
|
||
}
|
||
} catch (queueError) {
|
||
console.warn('[outbound] 报告推送入队失败(忽略):', (queueError as Error)?.message || queueError);
|
||
}
|
||
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' | 'retail_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();
|
||
}
|
||
}
|