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; 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 { 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 ); } } }