开发者:「这个调整出库后就只能是看了不能改;这边如果改了抵扣的批次后,那么分拣时 分拣的批次需要对应得上(当然分拣时分拣员也能改)」。方案甲(开发者选定)。 口径(写死并测): - 唯一落点仍是 picking_items.outbound_batches(分拣界面默认值 / 分拣出库扣库 / 发车核货扣库 / 批次报告推送 四个消费方零改动即对上) - 还没拣货行(开了分拣的分公司抵扣时行不存在)⇒ 先落 order_items.cover_batches (迁移 20261041,只加列不建表),在 4 个建行入口带进新行: pickingService.insertPickingItems / skipInboundLoadingService / deliveryLoadingService(两处) - 优先级:我方指定 > 抵扣 FIFO 计划 > 先进先出现算;分拣员完成分拣即覆盖行值 - 出库后只读(409 cover_batches_locked):出库流水 / 拣货行 outbound_at / 订单 ≥50 - 保存校验:批次须属该 SKU 且在本分公司、单批 ≤ 当前可用、合计 ≤ 该行已抵扣量 - 清理联动:释放/退货/删单/换货六个入口汇到 inventoryStockCoverService.clearAutoCoverBatchPlan 一处(连同 FIFO 计划一起清);改绑 SKU 即时清;15 分钟兜底清扫(含"指定批次已不存在") - 读侧防御:指定批次在当前 SKU 下不存在 ⇒ 该条目不当真,退回计划/FIFO - 顺带修既有不一致:结案补扣出库此前不按批次计划扣(纯 FIFO),现与发车扣库共用 loadPickItemBatchPlans 真库实测(BR003,夹具跑完清理残留 0): - PUT 200 → order_items.cover_batches 落库、GET source=manual - 已有空拣货行 ⇒ applied_to_picking_rows=1,该行 outbound_batches 即我方指定 - 直调 materialize:applied=1、再跑 0(幂等)、无指定的行 untouched=0 - 撤销:cleared=true、cover_batches=null、行内我方条目摘掉 - 状态 50 单:GET 三行 read_only=true/order_departed、PUT 409 cover_batches_locked - 合计超抵扣量 ⇒ 400 batch_total_exceeds_cover 测试:server/tests/orderItemCoverBatches.test.ts(14 例)、stockCoverBatchQuery.test.ts(12 例)、 OrderStockCoverBatchesModal.contract.test.ts(8 例);前端 order 相关 29 文件 193 例全绿; 前端新增文案 2 条(已获批准):orders.coverBatch.manual / orders.coverBatch.fallbackHint
161 lines
6.5 KiB
TypeScript
161 lines
6.5 KiB
TypeScript
import type { PoolClient } from 'pg';
|
||
import { isOrderIndependentInbound } from './independentInbound';
|
||
import { pool } from '../db';
|
||
import { ensureDeliveryTaskForOrder } from './orderWorkflowFulfillmentService';
|
||
import { supplierSkipInboundExistsSql } from './supplierSkipInbound';
|
||
import { skuDirectDeliveryAppliesSql } from './skuDirectDelivery';
|
||
|
||
type Db = Pick<PoolClient, 'query'>;
|
||
|
||
function newPickCode() {
|
||
return `PK${Date.now()}${Math.random().toString(36).slice(2, 6).toUpperCase()}`;
|
||
}
|
||
|
||
/**
|
||
* 供应商不入仓:备货完成后补配送核货行(司机去供应商处拿)。
|
||
* 仅当商品直送对该单客户生效(开关+名单)才不建核货行;SKU 开了但客户未命中仍建。
|
||
*
|
||
* `options.includeAllItems`(2026-10-07 新增,极简流转用):不再要求「供应商免入库」,
|
||
* 给**每一条**未退货明细补核货行(备货单已完成即可)。极简流转下这个分公司的单整单不走验收,
|
||
* 但发车(50→60)必须有核货/分拣明细(否则报 `no_loading_items`),司机的核货拍照也挂在核货行上。
|
||
* 见 docs/design/20261007-direct-to-delivery-mode.md
|
||
*/
|
||
export async function ensureSkipInboundLoadingLines(
|
||
orderCode: string,
|
||
client?: PoolClient,
|
||
options?: { includeAllItems?: boolean }
|
||
): Promise<void> {
|
||
const code = String(orderCode || '').trim();
|
||
if (!code) return;
|
||
const db: Db = client || pool;
|
||
/**
|
||
* 「独立进货」单(哨兵客户,2026-10-12):**不补核货/拣货行**。
|
||
* 它的货是"进自己的库",不是发给客户的;补出来的核货行会落进分拣面(
|
||
* `ensureSkipInboundLoadingLines` 建的 picking_items 与拣货任务),与
|
||
* 「进货单不进分拣/配送」的口径冲突。见 docs/design/20261012-独立进货(自用哨兵客户).md §4
|
||
*/
|
||
if (await isOrderIndependentInbound(code, db)) return;
|
||
const includeAllItems = options?.includeAllItems === true;
|
||
// 免入库限定条件:极简流转下换成恒真,其余(退货行、加菜行)判定不变。
|
||
// 同样地,「备货单已完成」这条 EXISTS 也只在**非**极简流转时要求:
|
||
// 极简流转下司机直接去供应商处拿货,不依赖备货记录;全量「库存抵扣」的明细本来就没有备货单,
|
||
// 若仍要求它,那张单会一行核货行都补不出来 ⇒ 发车被 `no_loading_items` 拦死(2026-10-07 核查发现)。
|
||
const skipInboundCondition = includeAllItems ? 'TRUE' : supplierSkipInboundExistsSql('oi.supplier_code');
|
||
const preparationReadyCondition = includeAllItems
|
||
? 'TRUE'
|
||
: `EXISTS (
|
||
SELECT 1 FROM supplier_preparations sp
|
||
WHERE sp.order_code = oi.order_code
|
||
AND COALESCE(sp.supplier_code, '') = COALESCE(oi.supplier_code, '')
|
||
AND COALESCE(sp.prepare_status, 0) >= 30
|
||
AND COALESCE(sp.is_stockout, false) = false
|
||
AND (
|
||
(NULLIF(TRIM(oi.sku_code), '') IS NOT NULL AND sp.sku_code IS NOT DISTINCT FROM oi.sku_code)
|
||
OR TRIM(COALESCE(sp.item_name, '')) = TRIM(COALESCE(oi.item_name, ''))
|
||
)
|
||
)`;
|
||
|
||
const items = await db.query(
|
||
`SELECT oi.id, oi.order_code, oi.sku_code, oi.item_name, oi.quantity, oi.unit, oi.branch_code
|
||
FROM order_items oi
|
||
WHERE oi.order_code = $1
|
||
AND COALESCE(oi.is_returned, false) = false
|
||
AND COALESCE(oi.is_extra_dish, false) = false
|
||
AND ${skipInboundCondition}
|
||
AND NOT ${skuDirectDeliveryAppliesSql('oi.sku_code', 'oi.order_code')}
|
||
AND ${preparationReadyCondition}`,
|
||
[code]
|
||
);
|
||
if (!items.rows.length) return;
|
||
|
||
const orderResult = await db.query(`SELECT branch_code FROM orders WHERE order_code = $1`, [code]);
|
||
const branchCode = orderResult.rows[0]?.branch_code ? String(orderResult.rows[0].branch_code) : null;
|
||
await ensureDeliveryTaskForOrder(code, branchCode, client);
|
||
|
||
const missing = [];
|
||
for (const item of items.rows) {
|
||
const exists = await db.query(
|
||
`SELECT 1 FROM picking_items WHERE order_item_id = $1::uuid LIMIT 1`,
|
||
[item.id]
|
||
);
|
||
if (!(exists.rowCount || 0)) missing.push(item);
|
||
}
|
||
if (!missing.length) return;
|
||
|
||
const existingPick = await db.query(
|
||
`SELECT pt.pick_code
|
||
FROM picking_tasks pt
|
||
WHERE pt.order_code = $1
|
||
AND COALESCE(pt.pick_status, 10) >= 30
|
||
AND NOT EXISTS (
|
||
SELECT 1
|
||
FROM picking_items pi
|
||
JOIN order_items oi ON oi.id = pi.order_item_id
|
||
WHERE pi.pick_code = pt.pick_code
|
||
AND NOT ${skipInboundCondition}
|
||
)
|
||
ORDER BY pt.created_at DESC
|
||
LIMIT 1`,
|
||
[code]
|
||
);
|
||
|
||
let pickCode = existingPick.rows[0]?.pick_code ? String(existingPick.rows[0].pick_code) : '';
|
||
if (!pickCode) {
|
||
pickCode = newPickCode();
|
||
await db.query(
|
||
`INSERT INTO picking_tasks (pick_code, order_code, warehouse_code, pick_status, branch_code, pick_completed_at)
|
||
VALUES ($1, $2, NULL, 40, $3, NOW())`,
|
||
[pickCode, code, branchCode]
|
||
);
|
||
}
|
||
|
||
let sortIdx = 0;
|
||
const maxSort = await db.query(
|
||
`SELECT COALESCE(MAX(sort_order), 0)::int AS n FROM picking_items WHERE pick_code = $1`,
|
||
[pickCode]
|
||
);
|
||
sortIdx = Number(maxSort.rows[0]?.n) || 0;
|
||
|
||
const insertedIds: string[] = [];
|
||
for (const item of missing) {
|
||
sortIdx += 1;
|
||
const inserted = await db.query(
|
||
`INSERT INTO picking_items (
|
||
pick_code, order_item_id, order_code, sku_code, item_name, required_qty, picked_qty,
|
||
loaded_qty, unit, review_status, branch_code, sort_order
|
||
) VALUES ($1, $2, $3, $4, $5, $6, $6, 0, $7, 30, $8, $9)
|
||
RETURNING id::text AS id`,
|
||
[
|
||
pickCode,
|
||
item.id,
|
||
item.order_code,
|
||
item.sku_code,
|
||
item.item_name || item.sku_code,
|
||
Number(item.quantity) || 0,
|
||
item.unit,
|
||
item.branch_code || branchCode,
|
||
sortIdx,
|
||
]
|
||
);
|
||
const insertedId = (inserted.rows as Array<{ id?: string }>)[0]?.id;
|
||
if (insertedId) insertedIds.push(String(insertedId));
|
||
}
|
||
/**
|
||
* 「我方指定的抵扣批次」随建行带进新行(2026-10-13 方案甲)。
|
||
* 免入库核货行是抵扣单最常见的一类行,必须与分拣建单同口径带入。
|
||
*/
|
||
if (insertedIds.length) {
|
||
try {
|
||
const { materializeCoverBatchesForPickingRows } = await import(
|
||
'./orderItemCoverBatchesService'
|
||
);
|
||
await materializeCoverBatchesForPickingRows(db, { pickItemIds: insertedIds });
|
||
} catch (error: unknown) {
|
||
console.error(
|
||
'[skip-inbound] 带入我方指定抵扣批次失败(不影响建行):',
|
||
(error as Error)?.message || error
|
||
);
|
||
}
|
||
}
|
||
}
|