import { pool } from '../db'; import type { PoolClient } from 'pg'; import { allocateOrderItems, DEFAULT_ALLOCATION_RULES, INTERNAL_PURCHASER_CODE, resolveItemAllocation, type AllocationItemInput, type AllocationRules, type SkuSupplierPrice, type SupplierCategoryBinding, type SupplierInfo, } from './allocationRules'; import { assertNoZeroPriceItems } from './orderZeroPriceGuard'; import { fetchCategoryRows, findCategoryRowByCode, getCategoryDisplayLabel, type CategoryRow, } from './categoryCatalogService'; import { listMarketBlockedSkuCodes } from './marketAllocationGuard'; import { syncSkuCostFromPreparation } from './preparationCostService'; import { ensureInspectionsForOrder } from './preparationFulfillmentService'; import { notifyPreparationsAllocated } from './supplierPrepWebhookService'; import { deletePendingInspectionsForPurchaseCode, hasSuccessfulInboundInspection, } from './inspectionRejectFulfillmentService'; import { findSkuByFuzzyName } from './skuFuzzyMatchService'; import { resolveLastSupplyCostPrice } from './purchasePriceMemoryService'; import { withAllocationSlot } from './allocationConcurrency'; import { stampWarehouseProcessingAsSelfPurchase } from './processingDemandSheetService'; import { loadDirectDeliverySkuSet, loadDirectDeliverySkuSetForOrder, skuDirectDeliveryAppliesSql, stampDirectDeliveryAsSelfPurchase } from './skuDirectDelivery'; import { requiresWarehouseProcessing } from './processingMethodUtils'; import { assertOrderItemsFulfilled, clearMismatchedPreparationFulfillments, isOrderItemFulfillmentValid, linkOrderItemToInventoryCover, linkOrderItemToPreparation, linkOrderItemToPurchase, listUncoveredOrderItems, recalcPreparationQty, dropStalePendingPreparationsForSku, } from './orderItemFulfillmentService'; import { isSmartAllocationEnabled } from './smartAllocationConfigService'; import { isDirectToDeliveryEnabled } from './directToDeliveryConfigService'; import { applyDirectToDeliveryAfterAllocation, ensureDirectDeliveryCoverRows } from './directToDeliveryService'; import { getAllocationRulesConfig } from './allocationRulesConfigService'; import { applyStockCoverForOrder, applyStockCoverForOrderItem, procureQtyFromNeed, } from './inventoryStockCoverService'; import { resolveMappedPurchaserForCategory, resolvePurchaserForNewPurchaseOrder, } from './purchaserAssignmentService'; import { getCategoryPurchaserMap } from './purchaseCategoryPurchaserMapService'; import { getPurchaseAssignDefaultConfig } from './purchaseAssignDefaultConfigService'; import { detachOrKeepTransferredPurchase, detachTransferredPurchasesForOrderItem, STOCKOUT_SOURCE_TYPES, } from './preparationStockoutService'; import { orderItemHasInspectionInbound } from './orderItemReturnService'; export interface ReprocessOrderResult { orderCode: string; itemsProcessed: number; purchaseOrdersCreated: number; preparationsCreated: number; skipped: number; orderStatusUpdated?: number; errors: string[]; /** 当前是否走智能分配 */ smartAllocationEnabled?: boolean; /** 按每单自动竞价:已暂缓分配 */ deferredForBid?: boolean; /** 外层事务提交后需自动发标(嵌套事务场景) */ needsAutoBidStart?: boolean; /** 暂缓分配时的提示文案 */ bidGateMessage?: string; /** 因竞价暂缓、尚未分配的 SKU(供嵌套事务提交后做范围外分配) */ deferredBidSkuCodes?: string[]; } /** 关智能分配时的调用意图 */ export type ReprocessAllocationOptions = { /** * 放行零价明细。默认 false(硬拦)。 * 只有两条路径会传 true,都来自主系统分配过来的备货任务(主系统的成本价=我们的销售价, * 那边没定价时就是 0;用户 2026-10-08 明确允许这类订单零价): * 1) 导入建单,`customerOrderSubmitService` 透传; * 2) 同一主订单后来追加分配的行,`syncOrderManageItems({ allowUnpriced: true })`。 * 其它入口(Web 改明细、小程序改单、手动分配)一律保持硬拦。 */ allowUnpriced?: boolean; /** * 关模式下:true=确认分配(空供应商转自采,要求全覆盖); * false/缺省=仅落已有供应商备货,未指定行保持待分配、不升 30、不报履约不全。 */ confirmManualAllocation?: boolean; /** * 跳过按每单自动竞价闸门(中标后强制重分配、自动发标失败回退分配时使用)。 */ skipPerOrderAutoBidGate?: boolean; /** 自动发标时的操作人(仅 ownsTransaction 路径在闸门内发标时使用) */ bidCreatedBy?: string | null; /** * 手动分配页保存:即使智能分配开启,也按明细已有 supplier_code 落履约,不跑规则引擎改写。 */ preferItemSuppliers?: boolean; /** * 暂缓竞价的 SKU:本轮不跑规则分配、不强制转自采(留给中标后再分)。 * 用于「范围内走竞价、范围外立刻分配」。 */ excludeSkuCodes?: string[]; /** * 可修改时限内新增的明细 id(非加菜):即使 preferItemSuppliers(手动语义)也按分配规则 * 自动定供应商或转自采,不留待分配。 */ autoAllocateItemIds?: string[]; /** * 订单列表手选自采:仅对这些明细 id 建自采单。软落仍保持 selfPurchaseUnassigned=false。 */ forceSelfPurchaseItemIds?: string[]; /** * 重分配时禁止再次被多采抵扣的明细 id。 * * 无调用方(原「还原库存抵扣」能力已于 2026-09-16 下线,见 * docs/todo/20260915-模块流转总图与设计对照.md §4.3 第 3 项)。 * 保留为可选参数以免改动 reprocessOrderAllocation 签名;如确认不再需要可整体删除。 */ skipStockCoverItemIds?: string[]; /** * 待配送(50) 新加明细:只对这些 id 分配,禁止整单重跑以免打乱已拣货。 */ onlyItemIds?: string[]; /** * 订单管理手选改过供应商/自采的明细。传入时(含空数组)手选圈只对这些 id 作废未入库自采。 * 不传则保持原行为:真实供应商行都尝试 cancel。 */ supplierSwitchItemIds?: string[]; }; export interface OrderItemRow { id: string; order_code: string; sku_code: string | null; item_name: string | null; quantity: number | string; unit: string | null; price: number | string | null; amount: number | string | null; supplier_code?: string | null; category_code?: string | null; category_name?: string | null; sku_name?: string | null; processing_method?: string | null; processing_owner?: string | null; is_extra_dish?: boolean | null; stock_cover_qty?: number | null; direct_delivery?: boolean | null; } function isUnassignedSupplier(supplierCode?: string | null): boolean { return !supplierCode || supplierCode === INTERNAL_PURCHASER_CODE; } /** 改自采后清掉旧供应商未入库备货(含完成)与待验,避免 ensure 被跳过留下孤儿 */ async function dropStalePrepsAfterSelfPurchaseAssign( db: Pick, orderCode: string, skuCode?: string | null ): Promise { await dropStalePendingPreparationsForSku(db, { orderCode, skuCode, keepSupplierCode: INTERNAL_PURCHASER_CODE, }); } function hasSkuCode(skuCode?: string | null): boolean { return Boolean(String(skuCode || '').trim()); } async function hasOpenPendingPurchase( orderCode: string, orderItemId: string, db: DbClient ): Promise { const result = await db.query( `SELECT 1 FROM purchase_orders po WHERE po.order_code = $1 AND po.purchase_status IN (10, 32) AND ( po.source_id = $2 OR ( COALESCE(po.source_type, '') = ANY($3::text[]) AND EXISTS ( SELECT 1 FROM order_item_fulfillments f WHERE f.order_item_id = $2::uuid AND f.purchase_code = po.purchase_code ) ) ) LIMIT 1`, [orderCode, orderItemId, [...STOCKOUT_SOURCE_TYPES]] ); return Boolean(result.rowCount); } function isKeptSelfPurchasePurchaseStatus(status: unknown): boolean { const n = Number(status) || 0; return n === 20 || n === 30; } function isOpenPendingPurchaseStatus(status: unknown): boolean { const n = Number(status) || 0; return n === 10 || n === 32; } export function partitionLinkedPurchasesForSupplierAssign( rows: Array<{ purchase_code?: string | null; purchase_status?: unknown }>, options?: { itemInbound?: boolean } ): { keep: boolean; detachCodes: string[] } { const itemInbound = Boolean(options?.itemInbound); const detachCodes: string[] = []; let keep = false; for (const row of rows) { const code = String(row.purchase_code || '').trim(); if (isKeptSelfPurchasePurchaseStatus(row.purchase_status)) { if (itemInbound) { keep = true; continue; } if (code) detachCodes.push(code); continue; } if (!code) continue; if (isOpenPendingPurchaseStatus(row.purchase_status)) { detachCodes.push(code); } } return { keep, detachCodes: [...new Set(detachCodes)] }; } export function shouldVoidPurchaseAfterItemUnlink(remainingFulfillmentCount: number): boolean { return remainingFulfillmentCount <= 0; } /** 手选改派名单内的行即使已有自采履约也要进 pending,否则 pending 为空会跳过作废圈。 */ export function keepFulfilledItemPendingForSupplierSwitch( fulfillmentValid: boolean, itemId: string, supplierSwitchItemIds?: string[] ): boolean { if (!fulfillmentValid) return true; const id = String(itemId || '').trim(); if (!id || !supplierSwitchItemIds?.length) return false; return supplierSwitchItemIds.map((row) => String(row || '').trim()).includes(id); } export async function planOpenPendingPurchasesForItem( orderCode: string, orderItemId: string, db: DbClient ): Promise<{ kept: boolean; detachCodes: string[] }> { const itemId = String(orderItemId || '').trim(); const code = String(orderCode || '').trim(); if (!itemId || !code) return { kept: false, detachCodes: [] }; const found = await db.query( `SELECT DISTINCT po.purchase_code, po.purchase_status FROM purchase_orders po WHERE po.order_code = $1 AND po.purchase_status <> 40 AND ( po.source_id = $2 OR EXISTS ( SELECT 1 FROM order_item_fulfillments f WHERE f.order_item_id = $2::uuid AND f.purchase_code = po.purchase_code ) )`, [code, itemId] ); if (!found.rowCount) { return { kept: false, detachCodes: [] }; } const skuRow = await db.query(`SELECT sku_code FROM order_items WHERE id = $1::uuid LIMIT 1`, [ itemId, ]); const inbound = await orderItemHasInspectionInbound(db, code, { id: itemId, sku_code: skuRow.rows[0]?.sku_code, }); const partitioned = partitionLinkedPurchasesForSupplierAssign( found.rows as Array<{ purchase_code?: string | null; purchase_status?: unknown }>, { itemInbound: inbound } ); return { kept: partitioned.keep, detachCodes: partitioned.detachCodes }; } /** 履约已原子换到备货/库存后,收尾原自采单;禁止在换链前把 purchase_code 单独清空。 */ export async function finalizeOpenPendingPurchasesForItem( orderItemId: string, detachCodes: string[], db: DbClient, remark = '改派供应商,取消原自采单' ): Promise<{ voided: number; recalc: number }> { const itemId = String(orderItemId || '').trim(); const codes = [...new Set(detachCodes.map((code) => String(code || '').trim()).filter(Boolean))]; if (!itemId || !codes.length) return { voided: 0, recalc: 0 }; const note = String(remark || '').trim() || '改派供应商,取消原自采单'; let voided = 0; let recalc = 0; for (const purchaseCode of codes) { const links = await db.query( `SELECT COUNT(*)::int AS cnt FROM order_item_fulfillments WHERE purchase_code = $1`, [purchaseCode] ); const remaining = Number(links.rows[0]?.cnt) || 0; if (shouldVoidPurchaseAfterItemUnlink(remaining)) { const updated = await db.query( `UPDATE purchase_orders SET purchase_status = 40, remark = CASE WHEN remark IS NULL OR TRIM(remark) = '' THEN $2 ELSE remark || ';' || $2 END WHERE purchase_code = $1 AND purchase_status IN (10, 20, 30, 32)`, [purchaseCode, note] ); if (updated.rowCount) { voided += 1; await deletePendingInspectionsForPurchaseCode(db, purchaseCode); } } else { await syncPurchaseQtyFromFulfillments(purchaseCode, db as PoolClient); recalc += 1; } } return { voided, recalc }; } async function filterPendingAllocationItems( orderCode: string, items: OrderItemRow[], allocationCtx: { rules: AllocationRules; supplierCategories: SupplierCategoryBinding[]; suppliers: SupplierInfo[]; skuSuppliers: SkuSupplierPrice[]; categoryRows: CategoryRow[]; categoryPurchaserBindings?: Array<{ category_code: string }>; }, db: DbClient = pool ): Promise { const pending: OrderItemRow[] = []; for (const item of items) { // 采购员手动选择了自采(INTERNAL)→ 不参与智能分配,由 forceCoverUnfulfilledOrderItems 生成采购单 if (item.supplier_code === INTERNAL_PURCHASER_CODE) continue; const fulfilled = await isOrderItemFulfillmentValid(db, String(item.id)); if (!fulfilled) { pending.push(item); continue; } // 已有未完成自采,但规则现已指向供应商 → 纳入重分配以改挂备货 const hasOpenPo = await hasOpenPendingPurchase(orderCode, String(item.id), db); if (!hasOpenPo) continue; const resolved = resolveItemAllocation({ orderCode, item: toAllocationInput(item), rules: allocationCtx.rules, supplierCategories: allocationCtx.supplierCategories, suppliers: allocationCtx.suppliers, skuSuppliers: allocationCtx.skuSuppliers, categoryRows: allocationCtx.categoryRows, categoryPurchaserBindings: allocationCtx.categoryPurchaserBindings, }); if (resolved?.target === 'supplier') { pending.push(item); } } return pending; } type DbClient = Pick; function dbClient(client?: PoolClient): DbClient { return client || pool; } async function recalcPurchaseQty(db: DbClient, purchaseCode: string): Promise { const result = await db.query( `SELECT COALESCE(SUM(GREATEST(0, oi.quantity - COALESCE(oi.stock_cover_qty, 0))), 0)::float AS qty FROM order_item_fulfillments f JOIN order_items oi ON oi.id = f.order_item_id WHERE f.purchase_code = $1`, [purchaseCode] ); return Number(result.rows[0]?.qty) || 0; } /** 按履约挂链重算并写回自采单数量(合单改量/删明细后调用) */ export async function syncPurchaseQtyFromFulfillments( purchaseCode: string, client?: PoolClient ): Promise { const db = dbClient(client); const qty = await recalcPurchaseQty(db, purchaseCode); await db.query( `UPDATE purchase_orders SET purchase_qty = $2 WHERE purchase_code = $1 AND purchase_status < 40`, [purchaseCode, qty] ); return qty; } /** * 改单后同步本单所有在途自采单的数量(计划量=Σ(需求−库存抵扣),按履约挂链): * - 待采/质检退回(10/32):只动计划量; * - 仓内加工成品占位单(self_processed 且 20,系统自动完成、无人采购):计划量与实采量一起对齐; * - 需求归零(如改量后库存全覆盖):取消仍在待采的自采单,仓内加工挂接单除外(由需求单链路管理)。 */ export async function syncOpenPurchaseQtyForOrder( client: PoolClient, orderCode: string ): Promise { const code = String(orderCode || '').trim(); if (!code) return; const linkedQtySql = ` SELECT f.purchase_code, SUM(GREATEST(0, oi.quantity - COALESCE(oi.stock_cover_qty, 0)))::numeric AS qty FROM order_item_fulfillments f JOIN order_items oi ON oi.id = f.order_item_id WHERE oi.order_code = $1 AND f.purchase_code IS NOT NULL GROUP BY f.purchase_code`; await client.query( `UPDATE purchase_orders po SET purchase_qty = sub.qty FROM (${linkedQtySql}) sub WHERE po.purchase_code = sub.purchase_code AND po.purchase_status IN (10, 32) AND po.purchase_qty IS DISTINCT FROM sub.qty`, [code] ); await client.query( // 方案 C(docs/design/20260920-self-purchase-actual-qty-single-writer.md): // 加工成品行不再预填 actual_qty —— 预填值若与验收实收不一致,会让 // inspectionComplianceService 的守卫早退,单据永久停在 20。实收只由验收写。 `UPDATE purchase_orders po SET purchase_qty = sub.qty FROM (${linkedQtySql}) sub WHERE po.purchase_code = sub.purchase_code AND po.purchase_status = 20 AND COALESCE(po.self_processed, false) = true AND po.purchase_qty IS DISTINCT FROM sub.qty`, [code] ); // 需求归零的待采自采单自动取消;仓内加工需求挂接单不动(需求单作废/跳过走自己的链路) await client.query( `UPDATE purchase_orders po SET purchase_status = 40, remark = CASE WHEN po.remark IS NULL OR TRIM(po.remark) = '' THEN '需求归零,自动取消' ELSE po.remark || ';需求归零,自动取消' END WHERE po.order_code = $1 AND po.purchase_status IN (10, 32) AND COALESCE(po.self_processed, false) = false AND EXISTS ( SELECT 1 FROM order_item_fulfillments f WHERE f.purchase_code = po.purchase_code ) AND NOT EXISTS ( SELECT 1 FROM order_item_fulfillments f JOIN order_items oi ON oi.id = f.order_item_id WHERE f.purchase_code = po.purchase_code AND GREATEST(0, oi.quantity - COALESCE(oi.stock_cover_qty, 0)) > 1e-9 ) AND NOT EXISTS ( SELECT 1 FROM processing_demand_items di JOIN processing_tasks pt ON pt.id = di.task_id AND pt.source_type = 'demand' AND pt.process_status < 50 JOIN order_item_fulfillments f ON f.order_item_id = di.order_item_id WHERE f.purchase_code = po.purchase_code )`, [code] ); } /** 分配前抵扣库存;全覆盖则只写库存履约并返回 true(跳过建备货/自采) */ async function tryFulfillFromInventory( db: DbClient, params: { orderCode: string; item: OrderItemRow; branchCode?: string | null; } ): Promise<{ coveredFully: boolean; coverQty: number; procureQty: number }> { const skuCode = String(params.item.sku_code || '').trim(); if ( params.item.direct_delivery === true || (skuCode && (await loadDirectDeliverySkuSetForOrder(params.orderCode, [skuCode], db)).has(skuCode)) ) { const qty = Number(params.item.quantity) || 0; return { coveredFully: false, coverQty: 0, procureQty: qty }; } const coverQty = await applyStockCoverForOrderItem(db, { orderItemId: String(params.item.id), orderCode: params.orderCode, skuCode: params.item.sku_code, quantity: Number(params.item.quantity) || 0, branchCode: params.branchCode, }); const procureQty = procureQtyFromNeed(Number(params.item.quantity) || 0, coverQty); if (procureQty <= 1e-9 && coverQty > 1e-9) { await linkOrderItemToInventoryCover(db, { orderItemId: String(params.item.id), orderCode: params.orderCode, inventoryCoverQty: coverQty, }); return { coveredFully: true, coverQty, procureQty: 0 }; } return { coveredFully: false, coverQty, procureQty }; } /** 履约完成 = 有备货 或 有未关闭自采单(仅有供应商不算完成) */ async function isOrderItemFulfilled( orderCode: string, item: { id: string; sku_code?: string | null; item_name?: string | null; supplier_code?: string | null }, db: DbClient ): Promise { void orderCode; return isOrderItemFulfillmentValid(db, String(item.id)); } async function backfillPreparationsForAssignedItems( orderCode: string, items: OrderItemRow[], branchCode: string | null | undefined, customerCode: string | null | undefined, result: ReprocessOrderResult, client: PoolClient ): Promise { for (const item of items) { if (isUnassignedSupplier(item.supplier_code) || !hasSkuCode(item.sku_code)) continue; const supplierCode = String(item.supplier_code); const prep = await ensureSupplierPreparation( { orderCode, item, supplierCode, branchCode, customerCode, }, client ); if (prep.created) { result.preparationsCreated += 1; result.itemsProcessed += 1; if (prep.skuCostSync) { // queued by caller when needed — sync immediately for early-return path } } } } /** * 强制覆盖:订单每一行必须进入自采或供应商备货,禁止遗漏。 * 有真实供应商 → 建/更新备货;否则 → 自采(可通过 selfPurchaseUnassigned 关闭)。 */ async function forceCoverUnfulfilledOrderItems( orderCode: string, items: OrderItemRow[], primaryPurchaser: { purchaser_code: string; purchaser_name: string } | null, branchCode: string | null | undefined, customerCode: string | null | undefined, result: ReprocessOrderResult, client: PoolClient, skuSyncQueue: Array<{ skuCode: string; costPrice: number }>, options: { selfPurchaseUnassigned?: boolean; reportUncoveredErrors?: boolean; /** 这些 SKU 故意暂缓履约(竞价中),不强制自采、不记入 uncovered */ skipSkuCodes?: Set | string[]; /** 仅这些明细允许在软落下建自采(订单列表显式选「自采」) */ forceSelfPurchaseItemIds?: Set | string[]; } = {} ): Promise { // 极简流转:先把「配送直供」来源补齐,再做覆盖检查 —— 该模式不建备货/采购, // 否则这里会把每条明细都判成「未能进入自采或备货」(2026-10-07 实测)。 // 开关未开时本调用什么都不做;幂等。见 docs/design/20261007-direct-to-delivery-mode.md await ensureDirectDeliveryCoverRows(client, orderCode, branchCode); const selfPurchaseUnassigned = options.selfPurchaseUnassigned !== false; const reportUncoveredErrors = options.reportUncoveredErrors !== false; const skipSkuCodes = new Set( [...(options.skipSkuCodes || [])].map((c) => String(c || '').trim()).filter(Boolean) ); const forceSelfPurchaseItemIds = new Set( [...(options.forceSelfPurchaseItemIds || [])].map((id) => String(id || '').trim()).filter(Boolean) ); const uncoveredLabels: string[] = []; const directSkuSet = await loadDirectDeliverySkuSet( items.map((item) => item.sku_code), customerCode, client ); const orderStatusResult = await client.query( `SELECT order_status FROM orders WHERE order_code = $1 LIMIT 1`, [orderCode] ); const orderStatus = Number(orderStatusResult.rows[0]?.order_status) || 0; /** 已完结订单不再强制新建自采/备货,避免假「待验收」 */ const orderClosed = orderStatus >= 90; for (const item of items) { const sku = String(item.sku_code || '').trim(); const forceSelfPurchase = forceSelfPurchaseItemIds.has(String(item.id || '').trim()); if (sku && skipSkuCodes.has(sku) && !forceSelfPurchase) continue; const label = String(item.item_name || item.sku_name || item.sku_code || item.id).trim(); if (sku && item.supplier_code === INTERNAL_PURCHASER_CODE) { await dropStalePrepsAfterSelfPurchaseAssign(client, orderCode, sku); } if (await isOrderItemFulfilled(orderCode, item, client)) continue; if ( orderClosed || (orderStatus >= 50 && hasSkuCode(item.sku_code) && (await hasSuccessfulInboundInspection( { orderCode, skuCode: item.sku_code, supplierCode: isUnassignedSupplier(item.supplier_code) ? null : String(item.supplier_code), }, client ))) ) { continue; } if (sku && directSkuSet.has(sku)) { if (item.supplier_code !== INTERNAL_PURCHASER_CODE) { await client.query(`UPDATE order_items SET supplier_code = $2 WHERE id = $1::uuid`, [ item.id, INTERNAL_PURCHASER_CODE, ]); item.supplier_code = INTERNAL_PURCHASER_CODE; } } else if (!isUnassignedSupplier(item.supplier_code) && hasSkuCode(item.sku_code)) { const supplierCode = String(item.supplier_code); const prep = await ensureSupplierPreparation( { orderCode, item, supplierCode, branchCode, customerCode, }, client ); if (prep.created) { result.preparationsCreated += 1; result.itemsProcessed += 1; if (prep.skuCostSync) skuSyncQueue.push(prep.skuCostSync); } } if (await isOrderItemFulfilled(orderCode, item, client)) continue; if (!selfPurchaseUnassigned && !forceSelfPurchase) { uncoveredLabels.push(label || '未命名商品'); continue; } const created = await createPurchaseOrderForItem( { orderCode, item: { ...item, sku_name: item.sku_name || item.item_name }, remark: '强制覆盖:订单明细必须进自采或备货,禁止遗漏', purchaser: primaryPurchaser, branchCode, customerCode, }, client ); if (created) { result.purchaseOrdersCreated += 1; result.itemsProcessed += 1; } if (!(await isOrderItemFulfilled(orderCode, item, client))) { uncoveredLabels.push(label || '未命名商品'); } } if (reportUncoveredErrors && uncoveredLabels.length) { if (!primaryPurchaser && selfPurchaseUnassigned) { const cfg = await getPurchaseAssignDefaultConfig(branchCode); if (cfg.mode && cfg.mode !== 'to_purchaser') { result.errors.push( `以下订单商品未能进入自采或备货:${uncoveredLabels.slice(0, 8).join('、')}${ uncoveredLabels.length > 8 ? '…' : '' }` ); } else { result.errors.push( `未配置采购员,无法将遗漏商品转自采:${uncoveredLabels.slice(0, 8).join('、')}${ uncoveredLabels.length > 8 ? '…' : '' }` ); } } else if (selfPurchaseUnassigned) { result.errors.push( `以下订单商品未能进入自采或备货:${uncoveredLabels.slice(0, 8).join('、')}${ uncoveredLabels.length > 8 ? '…' : '' }` ); } } return uncoveredLabels; } async function fetchPrimaryPurchaserForBranch(branchCode?: string | null) { if (branchCode) { const branch = await pool.query( `SELECT pu.purchaser_code, pu.purchaser_name FROM purchaser_users pu JOIN profiles p ON p.id = pu.user_id WHERE p.branch_code = $1 AND pu.status = 1 ORDER BY pu.is_primary DESC NULLS LAST, pu.created_at ASC LIMIT 1`, [branchCode] ); if (branch.rows[0]?.purchaser_code) return branch.rows[0]; } const primary = await pool.query( `SELECT purchaser_code, purchaser_name FROM purchaser_users WHERE is_primary = true AND status = 1 LIMIT 1` ); if (primary.rows[0]?.purchaser_code) return primary.rows[0]; const fallback = await pool.query( `SELECT purchaser_code, purchaser_name FROM purchaser_users WHERE status = 1 ORDER BY created_at ASC LIMIT 1` ); return fallback.rows[0] || null; } async function loadAllocationContext(branchCode?: string | null) { const [suppliers, supplierCategories, skuSuppliers, categoryRows, rules, categoryPurchaserMap] = await Promise.all([ pool.query( `SELECT supplier_code, company_name, rating, status FROM suppliers WHERE status IN (10, 20, 30, 40)` ), pool.query(`SELECT supplier_code, category_code, is_primary FROM supplier_categories`), pool.query( `SELECT sku_code, supplier_code, supply_price, is_preferred, in_stock, status, quality_rating FROM sku_suppliers WHERE status = 1` ), fetchCategoryRows(branchCode), getAllocationRulesConfig(branchCode), getCategoryPurchaserMap(branchCode), ]); return { rules, suppliers: suppliers.rows as SupplierInfo[], supplierCategories: supplierCategories.rows as SupplierCategoryBinding[], skuSuppliers: skuSuppliers.rows as SkuSupplierPrice[], categoryRows, categoryPurchaserBindings: categoryPurchaserMap.bindings || [], }; } async function enrichOrderItemsWithFuzzySku( items: OrderItemRow[], branchCode: string | null | undefined, client: PoolClient ): Promise { const enriched: OrderItemRow[] = []; for (const item of items) { if (hasSkuCode(item.sku_code)) { enriched.push(item); continue; } const itemName = String(item.item_name || item.sku_name || '').trim(); if (!itemName) { enriched.push(item); continue; } const match = await findSkuByFuzzyName(itemName, branchCode, item.category_code || undefined); if (!match) { enriched.push(item); continue; } await client.query(`UPDATE order_items SET sku_code = $2 WHERE id = $1`, [item.id, match.skuCode]); enriched.push({ ...item, sku_code: match.skuCode, sku_name: match.skuName, category_code: item.category_code || match.categoryCode || item.category_code, }); } return enriched; } async function enrichOrderItemsWithCategory( rawItems: OrderItemRow[], customerCode?: string, categoryRows?: CategoryRow[], branchCode?: string | null ): Promise { const flatCategories = categoryRows || (await fetchCategoryRows(branchCode)); let customerSkuRows: Array<{ sku_code: string; customer_sku_name: string | null; category_code: string | null }> = []; if (customerCode) { const customerSkus = await pool.query( `SELECT sku_code, customer_sku_name, category_code FROM customer_skus WHERE customer_code = $1`, [customerCode] ); customerSkuRows = customerSkus.rows; } const smartRules = await pool.query( `SELECT keyword, category_code, match_type, priority FROM smart_classification_rules WHERE is_active = true` ); return rawItems.map((item) => { let categoryCode = item.category_code || undefined; const itemName = String(item.item_name || item.sku_name || '').trim(); if (!categoryCode && item.sku_code) { // filled via join in caller when possible } if (!categoryCode && customerSkuRows.length) { const normalizedItemName = itemName.toLowerCase(); const bySku = customerSkuRows.find((row) => row.sku_code === item.sku_code && row.category_code); const byName = customerSkuRows.find((row) => { if (!row.category_code || !row.customer_sku_name) return false; const mappingName = row.customer_sku_name.trim().toLowerCase(); return ( mappingName === normalizedItemName || normalizedItemName.includes(mappingName) || mappingName.includes(normalizedItemName) ); }); categoryCode = bySku?.category_code || byName?.category_code || undefined; } if (!categoryCode && itemName) { for (const rule of smartRules.rows) { const keyword = String(rule.keyword || '').trim(); if (!keyword) continue; if (itemName.includes(keyword)) { categoryCode = String(rule.category_code); break; } } } const matchedRow = categoryCode ? findCategoryRowByCode(flatCategories, categoryCode) : undefined; const normalizedCode = matchedRow?.category_code || categoryCode || null; const lookedUp = normalizedCode ? getCategoryDisplayLabel(flatCategories, normalizedCode) : ''; const lookedUpIsCode = !lookedUp || lookedUp.toUpperCase() === String(normalizedCode || '').toUpperCase() || lookedUp.toUpperCase() === String(categoryCode || '').toUpperCase(); const existingName = String(item.category_name || '').trim(); const existingIsCode = !existingName || existingName.toUpperCase() === String(categoryCode || '').toUpperCase() || existingName.toUpperCase() === String(normalizedCode || '').toUpperCase(); return { ...item, sku_name: item.item_name || item.sku_name, category_code: normalizedCode, category_name: (!existingIsCode ? existingName : null) || (!lookedUpIsCode ? lookedUp : null) || null, }; }); } type CostPriceContext = { customerCode?: string | null; branchCode?: string | null; orderCode?: string | null; client?: PoolClient; }; /** 客户生效报价单成本价(与财务 activeCustomerSkuQuoteCte 口径一致) */ async function resolveQuoteSheetCostPrice( skuCode: string, ctx: CostPriceContext, db: DbClient ): Promise { const sku = String(skuCode || '').trim(); if (!sku) return null; let customerCode = String(ctx.customerCode || '').trim(); let branchCode = String(ctx.branchCode || '').trim() || null; if (!customerCode && ctx.orderCode) { const order = await db.query( `SELECT customer_code, branch_code FROM orders WHERE order_code = $1 LIMIT 1`, [ctx.orderCode] ); customerCode = String(order.rows[0]?.customer_code || '').trim(); if (!branchCode) branchCode = String(order.rows[0]?.branch_code || '').trim() || null; } if (!customerCode) return null; const result = await db.query( `SELECT COALESCE(i.cost_price, 0)::float AS cost_price FROM customer_quote_sheet_items i INNER JOIN customer_quote_sheets qs ON qs.quote_sheet_code = i.quote_sheet_code INNER JOIN customer_quote_sheet_customers qsc ON qsc.quote_sheet_code = qs.quote_sheet_code WHERE qsc.customer_code = $1 AND i.sku_code = $2 AND qs.approval_status = 30 AND qs.status = 1 AND (qs.expires_at IS NULL OR qs.expires_at > NOW()) AND ($3::text IS NULL OR qs.branch_code IS NOT DISTINCT FROM $3) ORDER BY qs.updated_at DESC NULLS LAST, qs.created_at DESC LIMIT 1`, [customerCode, sku, branchCode] ); const price = Number(result.rows[0]?.cost_price); if (Number.isFinite(price) && price > 0) return price; return null; } /** 备货写入价:中标/传入 supplyPrice 优先,否则用解析到的历史成本价 */ export function resolvePreparationInsertPrice( supplyPrice: number | undefined | null, resolvedCost: number ): number { const supply = Number(supplyPrice); if (Number.isFinite(supply) && supply > 0) return supply; const cost = Number(resolvedCost); return Number.isFinite(cost) && cost > 0 ? cost : 0; } /** * 采购/供货单价:报价单成本价 → 上次自采/供货成交价 → 供货目录 → 0 * 禁止使用订单销售价;商品档案已无成本价。 */ async function resolveSupplierCostPrice( item: OrderItemRow, supplierCode: string, ctx: CostPriceContext = {} ): Promise { const db = dbClient(ctx.client); const sku = String(item.sku_code || '').trim(); const realSupplier = String(supplierCode || '').trim() && String(supplierCode).trim() !== INTERNAL_PURCHASER_CODE && String(supplierCode).trim() !== 'UNASSIGNED' ? String(supplierCode).trim() : ''; if (sku) { const quoteCost = await resolveQuoteSheetCostPrice( sku, { ...ctx, orderCode: ctx.orderCode || item.order_code || null, }, db ); if (quoteCost != null && quoteCost > 0) return quoteCost; const remembered = await resolveLastSupplyCostPrice({ skuCode: sku, supplierCode: realSupplier || null, branchCode: ctx.branchCode || null, client: ctx.client || null, }); if (remembered.price != null && remembered.price > 0) return remembered.price; } return 0; } async function createPurchaseOrderForItem( params: { orderCode: string; item: OrderItemRow; remark?: string; /** @deprecated 建单采购员改由 resolvePurchaserForNewPurchaseOrder 决定;保留参数兼容调用方 */ purchaser?: { purchaser_code: string | null; purchaser_name: string | null } | null; /** 采购员加单:锁定传入 purchaser,不吃分类绑定 */ lockPurchaser?: boolean; branchCode?: string | null; customerCode?: string | null; }, client?: PoolClient ): Promise { // 极简流转(分配完成后直接待配送):**不建采购单** —— 这类订单的履约来源是 // order_item_fulfillments.direct_delivery_cover(配送直供),见 // docs/design/20261007-direct-to-delivery-mode.md if (await isDirectToDeliveryEnabled(params.branchCode)) return false; const db = dbClient(client); const orderStatusResult = await db.query( `SELECT order_status FROM orders WHERE order_code = $1 LIMIT 1`, [params.orderCode] ); if (Number(orderStatusResult.rows[0]?.order_status) >= 90) { return false; } // 仅当本行已有自采/备货履约时跳过;禁止用「同 SKU 兄弟行已入库」误杀其它明细 if ( await isOrderItemFulfilled( params.orderCode, { id: String(params.item.id), sku_code: params.item.sku_code, item_name: params.item.item_name || params.item.sku_name, supplier_code: params.item.supplier_code, }, db ) ) { return false; } const stock = await tryFulfillFromInventory(db, { orderCode: params.orderCode, item: params.item, branchCode: params.branchCode, }); if (stock.coveredFully) { return false; } const procureQty = stock.procureQty; const coverQty = stock.coverQty; const existing = await db.query( `SELECT purchase_code, purchase_status FROM purchase_orders WHERE order_code = $1 AND source_id = $2 AND purchase_status < 80 LIMIT 1`, [params.orderCode, params.item.id] ); if (existing.rows.length) { const purchaseCode = String(existing.rows[0].purchase_code); const purchaseStatus = Number(existing.rows[0].purchase_status) || 0; if (purchaseStatus === 40) { await db.query( `UPDATE purchase_orders SET purchase_status = 10, supplier_code = NULL, actual_qty = NULL, actual_price = NULL, audit_status = 10, audit_remark = NULL, submitted_at = NULL, reviewed_at = NULL, remark = CASE WHEN remark IS NULL OR TRIM(remark) = '' THEN '改回自采,恢复待采' ELSE remark || ';改回自采,恢复待采' END WHERE purchase_code = $1 AND purchase_status = 40`, [purchaseCode] ); } await linkOrderItemToPurchase(db, { orderItemId: String(params.item.id), orderCode: params.orderCode, purchaseCode, inventoryCoverQty: coverQty, }); await dropStalePrepsAfterSelfPurchaseAssign(db, params.orderCode, params.item.sku_code); const mergedQty = await recalcPurchaseQty(db, purchaseCode); await db.query( `UPDATE purchase_orders SET sku_code = $2, purchase_qty = $3 WHERE purchase_code = $1 AND purchase_status < 40`, [purchaseCode, params.item.sku_code || null, mergedQty] ); return false; } let purchaserCode: string | null; let purchaserName: string | null; if (params.lockPurchaser && params.purchaser) { purchaserCode = params.purchaser.purchaser_code || null; purchaserName = params.purchaser.purchaser_name || null; } else { const mapped = await resolveMappedPurchaserForCategory({ branchCode: params.branchCode, categoryCode: params.item.category_code, client: client || null, }); if (mapped) { purchaserCode = mapped.purchaser_code; purchaserName = mapped.purchaser_name; } else if (params.purchaser) { purchaserCode = params.purchaser.purchaser_code || null; purchaserName = params.purchaser.purchaser_name || null; } else { const resolved = await resolvePurchaserForNewPurchaseOrder({ orderCode: params.orderCode, branchCode: params.branchCode, skuCode: params.item.sku_code, itemName: params.item.item_name || params.item.sku_name, categoryCode: params.item.category_code, client: client || null, }); if (resolved.kind === 'unavailable') { return false; } purchaserCode = resolved.kind === 'free_pool' ? null : resolved.purchaser_code; purchaserName = resolved.kind === 'free_pool' ? null : resolved.purchaser_name; } } // 自采不再同日合单:每条订单明细各自建采购单;列表层按商品合计展示/批量完成 const purchaseCode = `PUR${Date.now()}${String(params.item.id).slice(-4)}${Math.floor(Math.random() * 1000)}`; const sourceType = !hasSkuCode(params.item.sku_code) ? 'order_no_sku' : params.item.category_code ? 'order_no_supplier' : 'order_no_category'; // 分配原因 / 库存抵扣量不进采购备注(采购员在 purchaser_name,抵扣在履约预留) // 采购单存成本价:报价单成本 → 上次自采价 → 0(禁止订单销售价) // 仓内加工成品只提示采购员采原料,成本固定 0 const purchasePrice = requiresWarehouseProcessing( params.item.processing_method, params.item.processing_owner ) ? 0 : await resolveSupplierCostPrice(params.item, 'UNASSIGNED', { customerCode: params.customerCode, branchCode: params.branchCode, orderCode: params.orderCode, client, }); await db.query( `INSERT INTO purchase_orders ( purchase_code, order_code, sku_code, supplier_code, purchaser_code, purchaser_name, purchase_qty, purchase_price, purchase_status, is_temporary_supplier, source_type, source_id, remark, branch_code ) VALUES ($1, $2, $3, NULL, $4, $5, $6, $7, 10, false, $8, $9, $10, $11)`, [ purchaseCode, params.orderCode, params.item.sku_code || null, purchaserCode, purchaserName, procureQty, purchasePrice, sourceType, params.item.id, null, params.branchCode || null, ] ); await linkOrderItemToPurchase(db, { orderItemId: String(params.item.id), orderCode: params.orderCode, purchaseCode, inventoryCoverQty: coverQty, }); await dropStalePrepsAfterSelfPurchaseAssign(db, params.orderCode, params.item.sku_code); return true; } /** 配送后加菜的自采履约凭证:不走库存/验收流程,但必须保留一条已完成采购记录。 */ export async function ensureCompletedExtraDishPurchase( params: { orderCode: string; itemId: string; skuCode?: string | null; itemName?: string | null; quantity: number; unitCost?: number; branchCode?: string | null }, client?: PoolClient ): Promise { const db = dbClient(client); const qty = Math.max(0, Number(params.quantity) || 0); if (!params.orderCode || !params.itemId || !(qty > 0)) return false; const existing = await db.query( `SELECT purchase_code FROM purchase_orders WHERE order_code = $1 AND source_id = $2 LIMIT 1`, [params.orderCode, params.itemId] ); if (existing.rows.length) { await linkOrderItemToPurchase(db, { orderItemId: params.itemId, orderCode: params.orderCode, purchaseCode: String(existing.rows[0].purchase_code), inventoryCoverQty: 0 }); return false; } const purchaseCode = `PURX${Date.now()}${String(params.itemId).slice(-6)}${Math.floor(Math.random() * 1000)}`; await db.query( `INSERT INTO purchase_orders (purchase_code, order_code, sku_code, supplier_code, purchase_qty, purchase_price, purchase_status, is_temporary_supplier, source_type, source_id, remark, branch_code) VALUES ($1, $2, $3, NULL, $4, $5, 30, false, 'extra_dish', $6, '配送后加菜自采(已完成)', $7)`, [purchaseCode, params.orderCode, params.skuCode || null, qty, Math.max(0, Number(params.unitCost) || 0), params.itemId, params.branchCode || null] ); await linkOrderItemToPurchase(db, { orderItemId: params.itemId, orderCode: params.orderCode, purchaseCode, inventoryCoverQty: 0 }); return true; } /** 已入库后将供应商来源更正为自采:仅建履约与财务来源,不重复影响库存数量。 */ export async function ensureCompletedInboundCorrectionPurchase( params: { orderCode: string; itemId: string; skuCode?: string | null; quantity: number; unitCost?: number; branchCode?: string | null }, client?: PoolClient ): Promise { const db = dbClient(client); const qty = Math.max(0, Number(params.quantity) || 0); if (!params.orderCode || !params.itemId || !(qty > 0)) throw new Error('入库来源更正缺少订单商品或数量'); const existing = await db.query( `SELECT purchase_code FROM purchase_orders WHERE order_code = $1 AND source_id = $2 AND source_type = 'inbound_source_correction' AND purchase_status <> 40 LIMIT 1`, [params.orderCode, params.itemId] ); const purchaseCode = existing.rows[0]?.purchase_code ? String(existing.rows[0].purchase_code) : `PURC${Date.now()}${String(params.itemId).slice(-6)}${Math.floor(Math.random() * 1000)}`; if (!existing.rows.length) { await db.query( `INSERT INTO purchase_orders ( purchase_code, order_code, sku_code, supplier_code, purchase_qty, purchase_price, actual_qty, actual_price, purchase_status, is_temporary_supplier, source_type, source_id, remark, branch_code ) VALUES ($1, $2, $3, NULL, $4, $5, $4, $5, 30, false, 'inbound_source_correction', $6, '已入库来源更正:供应商转自采(库存不重复入库)', $7)`, [purchaseCode, params.orderCode, params.skuCode || null, qty, Math.max(0, Number(params.unitCost) || 0), params.itemId, params.branchCode || null] ); } await linkOrderItemToPurchase(db, { orderItemId: params.itemId, orderCode: params.orderCode, purchaseCode, inventoryCoverQty: 0 }); return purchaseCode; } interface PreparationResult { created: boolean; skuCostSync?: { skuCode: string; costPrice: number }; } async function ensureSupplierPreparation( params: { orderCode: string; item: OrderItemRow; supplierCode: string; supplyPrice?: number; branchCode?: string | null; customerCode?: string | null; }, client?: PoolClient ): Promise { // 极简流转:**不建备货单**(同上,来源走「配送直供」) if (await isDirectToDeliveryEnabled(params.branchCode)) { return { created: false }; } const db = dbClient(client); if (requiresWarehouseProcessing(params.item.processing_method, params.item.processing_owner)) { return { created: false }; } const skuCode = String(params.item.sku_code || '').trim(); if (skuCode && (await loadDirectDeliverySkuSetForOrder(params.orderCode, [skuCode], db)).has(skuCode)) { return { created: false }; } const stock = await tryFulfillFromInventory(db, { orderCode: params.orderCode, item: params.item, branchCode: params.branchCode, }); await dropStalePendingPreparationsForSku(db, { orderCode: params.orderCode, skuCode: params.item.sku_code, keepSupplierCode: params.supplierCode, }); if (stock.coveredFully) { return { created: false }; } const coverQty = stock.coverQty; const costCtx: CostPriceContext = { customerCode: params.customerCode, branchCode: params.branchCode, orderCode: params.orderCode, client, }; const processingMethod = String(params.item.processing_method || '').trim(); const supplierProcessingMethod = String(params.item.processing_owner || '').trim().toLowerCase() === 'supplier' && processingMethod && processingMethod !== '原材料' ? processingMethod : null; const existing = await db.query( `SELECT id, is_stockout, transferred_to_purchase, purchase_price, purchase_code FROM supplier_preparations WHERE order_code = $1 AND sku_code = $2 AND supplier_code = $3 LIMIT 1`, [params.orderCode, params.item.sku_code, params.supplierCode] ); const orderUnit = String(params.item.unit || '').trim() || null; const supplySeed = Number(params.supplyPrice); const supplySeedPrice = Number.isFinite(supplySeed) && supplySeed > 0 ? supplySeed : 0; // B5:先锁行再聚合(PG 禁止 SUM + FOR UPDATE 同句);reprocess 入口已锁时此处为 no-op 等待 await db.query( `SELECT id FROM order_items oi WHERE oi.order_code = $1 AND oi.sku_code = $2 AND oi.supplier_code = $3 FOR UPDATE OF oi`, [params.orderCode, params.item.sku_code, params.supplierCode] ); const qtyResult = await db.query( `SELECT COALESCE(SUM(GREATEST(0, oi.quantity - COALESCE(oi.stock_cover_qty, 0))), 0)::float AS qty FROM order_items oi WHERE oi.order_code = $1 AND oi.sku_code = $2 AND oi.supplier_code = $3`, [params.orderCode, params.item.sku_code, params.supplierCode] ); // B5: 同事务内已锁明细;若仍有未写 cover 的兄弟行,末尾 reconcileOrderPreparationArtifacts 权威对齐 const totalQty = Number(qtyResult.rows[0]?.qty) || procureQtyFromNeed(Number(params.item.quantity) || 0, coverQty) || 0; const foreign = await detachTransferredPurchasesForOrderItem(db, { orderItemId: String(params.item.id), keepSupplierCode: params.supplierCode, remark: '改派供应商,取消原无货流转自采', }); if (foreign.action === 'keep_purchase') { await linkOrderItemToPurchase(db, { orderItemId: String(params.item.id), orderCode: params.orderCode, purchaseCode: foreign.purchaseCode, inventoryCoverQty: coverQty, }); return { created: false }; } if (existing.rows.length) { const existingRow = existing.rows[0]; const preparationId = String(existingRow.id); const existingPrice = Number(existingRow.purchase_price); const shouldBackfillPrice = supplySeedPrice > 0 && !(Number.isFinite(existingPrice) && existingPrice > 0); const wasTransferred = Boolean(existingRow.transferred_to_purchase) || Boolean(existingRow.is_stockout) || Boolean(existingRow.purchase_code); if (wasTransferred) { const outcome = await detachOrKeepTransferredPurchase(db, { prepId: preparationId, purchaseCode: existingRow.purchase_code, remark: '分配重新匹配供应商,取消原无货流转自采', }); if (outcome.action === 'keep_purchase') { await linkOrderItemToPurchase(db, { orderItemId: String(params.item.id), orderCode: params.orderCode, purchaseCode: outcome.purchaseCode, inventoryCoverQty: coverQty, }); if (params.item.sku_code) { await db.query( `UPDATE allocation_tasks SET allocated_qty = $4 WHERE order_code = $1 AND sku_code = $2 AND supplier_code = $3`, [params.orderCode, params.item.sku_code, params.supplierCode, totalQty] ); } return { created: false }; } } await db.query( `UPDATE supplier_preparations SET prepare_qty = $2, processing_method = COALESCE($3::varchar, processing_method), processing_owner = CASE WHEN $3::varchar IS NOT NULL THEN 'supplier' ELSE processing_owner END, unit = COALESCE($4::varchar, unit), purchase_price = CASE WHEN $5::boolean THEN $6::float ELSE purchase_price END, is_stockout = false, transferred_to_purchase = false, stockout_reason = NULL, purchase_code = NULL, prepare_status = CASE WHEN prepare_status = 40 THEN 10 ELSE prepare_status END WHERE id = $1`, [ preparationId, totalQty, supplierProcessingMethod, orderUnit, shouldBackfillPrice, supplySeedPrice, ] ); await linkOrderItemToPreparation(db, { orderItemId: String(params.item.id), orderCode: params.orderCode, preparationId, inventoryCoverQty: coverQty, }); await dropStalePendingPreparationsForSku(db, { orderCode: params.orderCode, skuCode: params.item.sku_code, keepSupplierCode: params.supplierCode, }); if (params.item.sku_code) { await db.query( `UPDATE allocation_tasks SET allocated_qty = $4 WHERE order_code = $1 AND sku_code = $2 AND supplier_code = $3`, [params.orderCode, params.item.sku_code, params.supplierCode, totalQty] ); } return { created: false }; } // 备货不再同日合单:每条订单明细各自建备货;列表层可按商品合计展示 // 竞价中标价(supplyPrice)优先,避免备货页单价空白 const resolvedCost = await resolveSupplierCostPrice(params.item, params.supplierCode, costCtx); const costPrice = resolvePreparationInsertPrice(params.supplyPrice, resolvedCost); const insertedPreparation = await db.query( `INSERT INTO supplier_preparations ( order_code, supplier_code, sku_code, item_name, prepare_qty, purchase_price, prepare_status, branch_code, unit, processing_method, processing_owner ) VALUES ($1, $2, $3, $4, $5, $6, 10, $7, $8::varchar, $9::varchar, CASE WHEN $9::varchar IS NULL THEN NULL ELSE 'supplier' END)`, [ params.orderCode, params.supplierCode, params.item.sku_code, params.item.item_name || params.item.sku_name || params.item.sku_code, totalQty, costPrice, params.branchCode || null, orderUnit, supplierProcessingMethod, ] ); const preparationResult = insertedPreparation.rows[0]?.id ? insertedPreparation : await db.query( `SELECT id FROM supplier_preparations WHERE order_code = $1 AND sku_code = $2 AND supplier_code = $3 LIMIT 1`, [params.orderCode, params.item.sku_code, params.supplierCode] ); const preparationId = String(preparationResult.rows[0]?.id || ''); if (!preparationId) throw new Error('供应商备货创建后未找到记录'); await linkOrderItemToPreparation(db, { orderItemId: String(params.item.id), orderCode: params.orderCode, preparationId, inventoryCoverQty: coverQty, }); await dropStalePendingPreparationsForSku(db, { orderCode: params.orderCode, skuCode: params.item.sku_code, keepSupplierCode: params.supplierCode, }); const taskCode = `AT${Date.now()}${String(params.item.sku_code || params.item.id).slice(-4)}`; if (params.item.sku_code) { await db.query('SAVEPOINT sp_allocation_task'); try { await db.query( `INSERT INTO allocation_tasks ( task_code, order_code, sku_code, supplier_code, allocated_price, allocated_qty, task_status ) VALUES ($1, $2, $3, $4, $5, $6, 20)`, [ taskCode, params.orderCode, params.item.sku_code, params.supplierCode, costPrice, totalQty, ] ); await db.query('RELEASE SAVEPOINT sp_allocation_task'); } catch { await db.query('ROLLBACK TO SAVEPOINT sp_allocation_task'); } } const skuCostSync = params.item.sku_code && costPrice > 0 ? { skuCode: String(params.item.sku_code), costPrice } : undefined; return { created: true, skuCostSync }; } async function ensureSupplierPreparationReplacingPurchases( params: Parameters[0], client: PoolClient, remark: string ): Promise<{ kept: boolean; preparation: PreparationResult }> { const itemId = String(params.item.id || '').trim(); const release = await planOpenPendingPurchasesForItem(params.orderCode, itemId, client); if (release.kept) { return { kept: true, preparation: { created: false } }; } const preparation = await ensureSupplierPreparation(params, client); if (release.detachCodes.length) { const replacement = await client.query( `SELECT 1 FROM order_item_fulfillments WHERE order_item_id = $1::uuid AND ( supplier_preparation_id IS NOT NULL OR (purchase_code IS NULL AND inventory_cover_qty > 0) ) LIMIT 1`, [itemId] ); if (!replacement.rowCount) { throw new Error('供应商备货未成功替换原自采履约,已保留原自采单'); } await finalizeOpenPendingPurchasesForItem( itemId, release.detachCodes, client, remark ); } return { kept: false, preparation }; } function toAllocationInput(item: OrderItemRow): AllocationItemInput { return { id: item.id, sku_code: String(item.sku_code || ''), sku_name: String(item.sku_name || item.item_name || item.sku_code || '未命名商品'), category_code: item.category_code || undefined, category_name: item.category_name || undefined, quantity: Number(item.quantity) || 0, price: Number(item.price) || 0, unit: String(item.unit || '斤'), direct_delivery: item.direct_delivery === true, }; } async function runAllocationAfterCommitSideEffects(input: { orderCode: string; orderBranchCode: string | null; result: ReprocessOrderResult; skuSyncQueue: Array<{ skuCode: string; costPrice: number }>; }) { const { orderCode, orderBranchCode, result, skuSyncQueue } = input; for (const sync of skuSyncQueue) { await syncSkuCostFromPreparation(sync.skuCode, sync.costPrice, undefined, orderBranchCode).catch((err) => { console.error(`[allocation] syncSkuCost failed order=${orderCode} sku=${sync.skuCode}:`, err); }); } // 极简流转(按分公司开关,**默认关闭**):该分公司只用配送功能 —— 分配完成即置待配送, // 不建验收单、不建分拣待办(核货行照补,见 directToDeliveryService)。 // 开关关闭时这一支完全不走,行为与之前逐字一致。 // 见 docs/design/20261007-direct-to-delivery-mode.md const directToDeliveryEnabled = await isDirectToDeliveryEnabled(orderBranchCode).catch(() => false); if (directToDeliveryEnabled) { await applyDirectToDeliveryAfterAllocation(orderCode, orderBranchCode).catch((err) => { console.error(`[allocation] 极简流转失败 order=${orderCode}:`, err); }); } else if (result.preparationsCreated > 0 || result.orderStatusUpdated === 30) { await ensureInspectionsForOrder(orderCode, orderBranchCode).catch((err) => { console.error(`[allocation] ensureInspections failed order=${orderCode}:`, err); }); } if (orderBranchCode) { await notifyPreparationsAllocated({ orderCode, branchCode: orderBranchCode }).catch((err) => { console.error(`[allocation] prep webhook failed order=${orderCode}:`, err); }); } } export async function reprocessOrderAllocation( orderCode: string, customerCode?: string | null, branchCode?: string | null, externalClient?: PoolClient, options: ReprocessAllocationOptions = {} ): Promise { // 外层已持有事务连接时由调用方用 withAllocationSlot 包住整段事务,避免「占连接再排队」打满池 if (externalClient) { return reprocessOrderAllocationUnlocked(orderCode, customerCode, branchCode, externalClient, options); } return withAllocationSlot(() => reprocessOrderAllocationUnlocked(orderCode, customerCode, branchCode, undefined, options) ); } async function reprocessOrderAllocationUnlocked( orderCode: string, customerCode?: string | null, branchCode?: string | null, externalClient?: PoolClient, options: ReprocessAllocationOptions = {} ): Promise { const result: ReprocessOrderResult = { orderCode, itemsProcessed: 0, purchaseOrdersCreated: 0, preparationsCreated: 0, skipped: 0, errors: [], }; const ownsTransaction = !externalClient; const client = externalClient || (await pool.connect()); const skuSyncQueue: Array<{ skuCode: string; costPrice: number }> = []; let orderBranchCode: string | null = branchCode || null; try { if (ownsTransaction) await client.query('BEGIN'); // 行锁串行化同一订单的并发分配(提交、工作流推进、批量重跑), // 幂等检查与写入在同一事务内,避免重复生成采购单/备货单。 const orderResult = await client.query( `SELECT order_code, order_status, customer_code, branch_code FROM orders WHERE order_code = $1 FOR UPDATE`, [orderCode] ); const order = orderResult.rows[0]; orderBranchCode = branchCode || order?.branch_code || null; if (!order) { if (!ownsTransaction) throw new Error(`订单 ${orderCode} 不存在`); await client.query('ROLLBACK'); result.errors.push(`订单 ${orderCode} 不存在`); return result; } const effectiveBranch = branchCode || order.branch_code || null; const effectiveCustomer = customerCode || order.customer_code || null; // 按每单自动竞价闸门须在零价硬拦之前:否则「管理员放行零价 + auto 发标」会整单回滚 let needingBidSkus: string[] = []; try { const { resolvePerOrderAutoBidGate, runPerOrderAutoBidAfterDefer, listOrderSkusNeedingBidProcure, resolvePerOrderBidSkipGateAllocOptions, } = await import('./bidRoundService'); // 先落库存抵扣:范围内无净需求则不 defer,直接本事务分配 let skipBecauseNoProcure = false; if (options.skipPerOrderAutoBidGate !== true) { await applyStockCoverForOrder( orderCode, effectiveBranch, client, options.skipStockCoverItemIds ); needingBidSkus = await listOrderSkusNeedingBidProcure({ orderCode, branchCode: effectiveBranch, client, }); skipBecauseNoProcure = needingBidSkus.length === 0; } const gate = await resolvePerOrderAutoBidGate({ orderCode, branchCode: effectiveBranch, orderStatus: Number(order.order_status), skip: options.skipPerOrderAutoBidGate === true || skipBecauseNoProcure, }); if (gate.defer) { // 管理员显式确认分配:给出明确错误,避免 silent defer 后落到「尚未完成分配」 if (options.confirmManualAllocation === true) { throw Object.assign(new Error(gate.message || '竞价尚未结束,请先确认中标后再分配'), { status: 409, code: 'bid_round_pending', }); } result.deferredForBid = true; result.needsAutoBidStart = gate.needsAutoStart; result.bidGateMessage = gate.message; result.deferredBidSkuCodes = needingBidSkus; result.smartAllocationEnabled = await isSmartAllocationEnabled(effectiveBranch); const allocateOutsideBidScope = () => reprocessOrderAllocation(orderCode, effectiveCustomer, effectiveBranch, undefined, { ...options, skipPerOrderAutoBidGate: true, excludeSkuCodes: needingBidSkus, }); if (ownsTransaction) { await client.query('ROLLBACK'); if (gate.needsAutoStart) { const started = await runPerOrderAutoBidAfterDefer({ orderCode, branchCode: effectiveBranch, createdBy: options.bidCreatedBy ?? null, }); if (!started.ok) { const skipOpts = await resolvePerOrderBidSkipGateAllocOptions({ orderCode, excludeSkuCodes: needingBidSkus, started, }); return reprocessOrderAllocation( orderCode, effectiveCustomer, effectiveBranch, undefined, { ...options, ...skipOpts } ); } } // 竞价进行中:立刻分配范围外商品(如蔬菜),范围内留给中标 if (needingBidSkus.length > 0) { const partial = await allocateOutsideBidScope(); partial.deferredForBid = true; partial.needsAutoBidStart = false; partial.bidGateMessage = gate.message; partial.deferredBidSkuCodes = needingBidSkus; return partial; } return result; } // 嵌套事务:标记后由外层提交再发标,并由外层用 deferredBidSkuCodes 做范围外分配 return result; } } catch (error: unknown) { if ( error && typeof error === 'object' && (error as { code?: string }).code === 'bid_round_pending' ) { throw error; } // 闸门读取失败不阻断分配 } await assertNoZeroPriceItems(orderCode, client, options.allowUnpriced === true, '分配'); const smartEnabled = await isSmartAllocationEnabled(effectiveBranch); result.smartAllocationEnabled = smartEnabled; const confirmManual = options.confirmManualAllocation === true; /** 手动页保存 / 关智能:按明细已有供应商落履约,不跑规则引擎 */ const useItemSuppliers = !smartEnabled || options.preferItemSuppliers === true; /** 关智能且未确认:不跑规则引擎;裸行仍由 finalizeCoverage 强制自采 + 断言 */ // B5: 锁住本单全部明细,避免并发分配下兄弟行 cover/备货量短暂分叉 const itemsResult = await client.query( `SELECT oi.*, s.sku_name AS joined_sku_name, s.category_code AS joined_category_code, s.unit AS joined_unit, ${skuDirectDeliveryAppliesSql('oi.sku_code', 'oi.order_code')} AS joined_direct_delivery FROM order_items oi LEFT JOIN skus s ON s.sku_code = oi.sku_code WHERE oi.order_code = $1 ORDER BY oi.sort_order ASC NULLS LAST, oi.id ASC FOR UPDATE OF oi`, [orderCode] ); await stampWarehouseProcessingAsSelfPurchase(orderCode, client); await stampDirectDeliveryAsSelfPurchase(orderCode, client); const stampedResult = await client.query( `SELECT oi.*, s.sku_name AS joined_sku_name, s.category_code AS joined_category_code, s.unit AS joined_unit, ${skuDirectDeliveryAppliesSql('oi.sku_code', 'oi.order_code')} AS joined_direct_delivery FROM order_items oi LEFT JOIN skus s ON s.sku_code = oi.sku_code WHERE oi.order_code = $1 ORDER BY oi.sort_order ASC NULLS LAST, oi.id ASC`, [orderCode] ); const rawItems = stampedResult.rows.map((row) => ({ ...row, sku_name: row.joined_sku_name || row.item_name, category_code: row.category_code || row.joined_category_code || null, unit: row.unit || row.joined_unit || '斤', direct_delivery: row.joined_direct_delivery === true || row.joined_direct_delivery === 't', })) as OrderItemRow[]; if (!rawItems.length) { if (!ownsTransaction) throw new Error('订单没有明细'); await client.query('ROLLBACK'); result.errors.push('订单没有明细'); return result; } const ctx = await loadAllocationContext(effectiveBranch); const enriched = await enrichOrderItemsWithCategory( rawItems, effectiveCustomer || undefined, ctx.categoryRows, effectiveBranch ); const withSku = await enrichOrderItemsWithFuzzySku(enriched, effectiveBranch, client); const primaryPurchaser = await fetchPrimaryPurchaserForBranch(effectiveBranch); let designatedBySku = new Map(); try { const { stampDesignatedSuppliersOnOrderItems } = await import('./bidRoundService'); designatedBySku = await stampDesignatedSuppliersOnOrderItems({ orderCode, branchCode: effectiveBranch, items: withSku, client, }); } catch { // 指定直供盖章失败不阻断分配 } const directSkuSet = await loadDirectDeliverySkuSet( withSku.map((item) => item.sku_code), effectiveCustomer, client ); for (const sku of directSkuSet) designatedBySku.delete(sku); const excludeSkuSet = new Set( (options.excludeSkuCodes || []).map((c) => String(c || '').trim()).filter(Boolean) ); const onlyItemIdSet = new Set( (options.onlyItemIds || []).map((s) => String(s || '').trim()).filter(Boolean) ); const restrictToNewItems = onlyItemIdSet.size > 0; const inOnlyItemScope = (id: unknown) => !restrictToNewItems || onlyItemIdSet.has(String(id || '').trim()); const pendingItemsRaw = !useItemSuppliers ? await filterPendingAllocationItems( orderCode, withSku, { rules: ctx.rules, supplierCategories: ctx.supplierCategories, suppliers: ctx.suppliers, skuSuppliers: ctx.skuSuppliers, categoryRows: ctx.categoryRows, categoryPurchaserBindings: ctx.categoryPurchaserBindings, }, client ) : ( await Promise.all( withSku.map(async (item) => { const fulfilled = await isOrderItemFulfillmentValid(client, String(item.id)); return keepFulfilledItemPendingForSupplierSwitch( fulfilled, String(item.id), options.supplierSwitchItemIds ) ? item : null; }) ) ).filter(Boolean) as OrderItemRow[]; // 竞价暂缓 SKU:本轮不进规则引擎 const pendingItemsUnscoped = excludeSkuSet.size ? pendingItemsRaw.filter((item) => !excludeSkuSet.has(String(item.sku_code || '').trim())) : pendingItemsRaw; const pendingItems = restrictToNewItems ? pendingItemsUnscoped.filter((item) => onlyItemIdSet.has(String(item.id))) : pendingItemsUnscoped; const finalizeCoverage = async () => { if (restrictToNewItems) { const subset = withSku.filter((item) => onlyItemIdSet.has(String(item.id))); await backfillPreparationsForAssignedItems( orderCode, subset, effectiveBranch, effectiveCustomer, result, client ); const coverageRows = ( ( await client.query( `SELECT id, sku_code, item_name, quantity, unit, price, category_code, category_name, supplier_code, processing_method, processing_owner FROM order_items WHERE order_code = $1 AND id = ANY($2::uuid[]) ORDER BY sort_order ASC NULLS LAST, id ASC`, [orderCode, [...onlyItemIdSet]] ) ).rows as OrderItemRow[] ); await forceCoverUnfulfilledOrderItems( orderCode, coverageRows, primaryPurchaser, effectiveBranch, effectiveCustomer, result, client, skuSyncQueue, { selfPurchaseUnassigned: true, reportUncoveredErrors: true, skipSkuCodes: excludeSkuSet, forceSelfPurchaseItemIds: options.forceSelfPurchaseItemIds, } ); await recalcPreparationQty(client, orderCode); return; } // 先清「明细供应商已改/清空」导致的失效备货履约,再覆盖或软落 await clearMismatchedPreparationFulfillments(client, orderCode); await backfillPreparationsForAssignedItems( orderCode, withSku, effectiveBranch, effectiveCustomer, result, client ); const coverageRows = ( await client.query( `SELECT id, sku_code, item_name, quantity, unit, price, category_code, category_name, supplier_code, processing_method, processing_owner FROM order_items WHERE order_code = $1 ORDER BY sort_order ASC NULLS LAST, id ASC`, [orderCode] ) ).rows as OrderItemRow[]; // 关智能/手选保存且非「确认分配」:仅落已有供应商备货,未指定行保持待分配(软落) const softManualSave = useItemSuppliers && !confirmManual; const uncovered = await forceCoverUnfulfilledOrderItems( orderCode, coverageRows, primaryPurchaser, effectiveBranch, effectiveCustomer, result, client, skuSyncQueue, softManualSave ? { selfPurchaseUnassigned: false, reportUncoveredErrors: false, skipSkuCodes: excludeSkuSet, forceSelfPurchaseItemIds: options.forceSelfPurchaseItemIds, } : { selfPurchaseUnassigned: true, reportUncoveredErrors: true, skipSkuCodes: excludeSkuSet, forceSelfPurchaseItemIds: options.forceSelfPurchaseItemIds, } ); const waitingBidUncovered = excludeSkuSet.size > 0 ? (await listUncoveredOrderItems(client, orderCode)).filter((row) => excludeSkuSet.has(String(row.sku_code || '').trim()) ) : []; const allFulfilled = uncovered.length === 0 && waitingBidUncovered.length === 0; const currentStatus = Number(order.order_status); if (!softManualSave) { if (excludeSkuSet.size === 0) { await assertOrderItemsFulfilled(client, orderCode, { includeHistoryRepair: currentStatus >= 90, }); } else { const leftover = (await listUncoveredOrderItems(client, orderCode)).filter( (row) => !excludeSkuSet.has(String(row.sku_code || '').trim()) ); if (leftover.length) { const labels = leftover .slice(0, 8) .map((row) => row.item_name || row.sku_code || row.id) .join('、'); throw Object.assign( new Error( `订单仍有 ${leftover.length} 条商品未进入供应商备货、自采或库存覆盖:${labels}${ leftover.length > 8 ? '…' : '' }` ), { status: 409, code: 'order_item_fulfillment_incomplete', uncovered: leftover } ); } } } await recalcPreparationQty(client, orderCode); // 手动保存允许保留未分配行(allFulfilled=false);但一旦全部已有备货/自采/库存履约, // 必须推进到待备货,不能因 softManualSave 永久停留在待分配。 if (allFulfilled && currentStatus < 30) { await client.query(`UPDATE orders SET order_status = 30 WHERE order_code = $1`, [orderCode]); result.orderStatusUpdated = 30; } }; // pending 为空会跳过下面手选作废圈。改派名单内的已履约行已由 // keepFulfilledItemPendingForSupplierSwitch 留在 pendingItems。 if (!pendingItems.length) { await finalizeCoverage(); if (ownsTransaction) await client.query('COMMIT'); result.skipped = Math.max(0, withSku.length - result.itemsProcessed); if (ownsTransaction) { await runAllocationAfterCommitSideEffects({ orderCode, orderBranchCode, result, skuSyncQueue }); } return result; } // —— 关智能 / 手选供应商:不跑规则引擎,仅按已有 supplier_code 落备货/(确认时)自采 —— if (useItemSuppliers) { // 可修改时限内新增且未指定供应商的明细:按分配规则定供应商,未匹配转自采 const autoAllocateSet = new Set( (options.autoAllocateItemIds || []).map((s) => String(s || '').trim()).filter(Boolean) ); for (const item of withSku) { if (!inOnlyItemScope(item.id)) continue; if (excludeSkuSet.has(String(item.sku_code || '').trim())) continue; if (item.direct_delivery === true || directSkuSet.has(String(item.sku_code || '').trim())) continue; if (!item.sku_code) continue; if (isUnassignedSupplier(item.supplier_code)) { if (item.supplier_code === INTERNAL_PURCHASER_CODE) { await dropStalePrepsAfterSelfPurchaseAssign(client, orderCode, item.sku_code); } continue; } const supplierCode = String(item.supplier_code); const switchIds = options.supplierSwitchItemIds; const shouldCancelOpenPurchases = !switchIds || switchIds.map((id) => String(id || '').trim()).includes(String(item.id)); const switched = shouldCancelOpenPurchases ? await ensureSupplierPreparationReplacingPurchases( { orderCode, item, supplierCode, branchCode: effectiveBranch, customerCode: effectiveCustomer, }, client, '改派供应商,取消原自采单' ) : { kept: false, preparation: await ensureSupplierPreparation( { orderCode, item, supplierCode, branchCode: effectiveBranch, customerCode: effectiveCustomer, }, client ), }; if (switched.kept) continue; const prep = switched.preparation; if (prep.created) { result.preparationsCreated += 1; result.itemsProcessed += 1; if (prep.skuCostSync) skuSyncQueue.push(prep.skuCostSync); } } for (const item of withSku) { if (!autoAllocateSet.has(String(item.id))) continue; if (excludeSkuSet.has(String(item.sku_code || '').trim())) continue; if (!isUnassignedSupplier(item.supplier_code)) continue; if (await isOrderItemFulfillmentValid(client, String(item.id))) continue; const resolved = resolveItemAllocation({ orderCode, item: toAllocationInput(item), rules: ctx.rules, supplierCategories: ctx.supplierCategories, suppliers: ctx.suppliers, skuSuppliers: ctx.skuSuppliers, categoryRows: ctx.categoryRows, categoryPurchaserBindings: ctx.categoryPurchaserBindings, }); if ( resolved?.target === 'supplier' && resolved.supplier_code && !isUnassignedSupplier(resolved.supplier_code) && hasSkuCode(item.sku_code) ) { await client.query( `UPDATE order_items SET supplier_code = $2 WHERE id = $1::uuid`, [item.id, resolved.supplier_code] ); item.supplier_code = resolved.supplier_code; const prep = await ensureSupplierPreparation( { orderCode, item, supplierCode: resolved.supplier_code, supplyPrice: resolved.supply_price > 0 ? resolved.supply_price : undefined, branchCode: effectiveBranch, customerCode: effectiveCustomer, }, client ); if (prep.created) { result.preparationsCreated += 1; result.itemsProcessed += 1; if (prep.skuCostSync) skuSyncQueue.push(prep.skuCostSync); } } else { const created = await createPurchaseOrderForItem( { orderCode, item: { ...item, sku_name: item.sku_name || item.item_name }, remark: '可修改时限内新增商品自动分配:未匹配供应商,转自采', purchaser: primaryPurchaser, branchCode: effectiveBranch, customerCode: effectiveCustomer, }, client ); if (created) { result.purchaseOrdersCreated += 1; result.itemsProcessed += 1; } } } if (confirmManual) { const leftover = await client.query( `SELECT oi.id, oi.order_code, oi.sku_code, oi.item_name, oi.quantity, oi.unit, oi.price, oi.category_code, oi.category_name, oi.supplier_code, oi.processing_method, oi.processing_owner FROM order_items oi WHERE oi.order_code = $1 AND (oi.supplier_code IS NULL OR TRIM(oi.supplier_code) = '' OR oi.supplier_code IN ('UNASSIGNED', 'INTERNAL')) AND NOT EXISTS ( SELECT 1 FROM purchase_orders po WHERE po.order_code = oi.order_code AND po.source_id = oi.id::text AND po.purchase_status < 80 )`, [orderCode] ); for (const row of leftover.rows as OrderItemRow[]) { if (!inOnlyItemScope(row.id)) continue; if (excludeSkuSet.has(String(row.sku_code || '').trim())) continue; const created = await createPurchaseOrderForItem( { orderCode, item: { ...row, sku_name: row.item_name }, remark: '手动分配:未指定供应商,转自采', purchaser: primaryPurchaser, branchCode: effectiveBranch, customerCode: effectiveCustomer, }, client ); if (created) { result.purchaseOrdersCreated += 1; result.itemsProcessed += 1; } } } await finalizeCoverage(); if (ownsTransaction) await client.query('COMMIT'); result.skipped = Math.max(0, withSku.length - result.itemsProcessed); if (ownsTransaction) { await runAllocationAfterCommitSideEffects({ orderCode, orderBranchCode, result, skuSyncQueue }); } return result; } const blockedSkuCodes = await listMarketBlockedSkuCodes( null, pendingItems.map((item) => item.sku_code).filter(Boolean) as string[], effectiveBranch ); // 已有未完成自采、待改挂供应商的明细:不因市场红灯跳过,否则会永久卡在自采 const effectiveBlocked = new Set(); for (const sku of blockedSkuCodes) { const owners = pendingItems.filter((item) => String(item.sku_code || '') === sku); let keepBlocked = false; for (const item of owners) { const hasOpenPo = await hasOpenPendingPurchase(orderCode, String(item.id), client); if (!hasOpenPo) { keepBlocked = true; break; } } if (keepBlocked || owners.length === 0) effectiveBlocked.add(sku); } const { results, skipped, marketBlocked } = allocateOrderItems({ orderCode, items: pendingItems.map((item) => toAllocationInput(item)), rules: ctx.rules, supplierCategories: ctx.supplierCategories, suppliers: ctx.suppliers, skuSuppliers: ctx.skuSuppliers, categoryRows: ctx.categoryRows, categoryPurchaserBindings: ctx.categoryPurchaserBindings, blockedSkuCodes: effectiveBlocked, }); result.skipped = skipped.length + marketBlocked.length; // 竞价中标强制供应商(管理员事后改派不在此覆盖;再次智能分配会重新强制) try { const { loadActiveBidAwardsForOrder } = await import('./bidAwardService'); const { getBidSettings } = await import('./bidConfigService'); const bidSettings = await getBidSettings(effectiveBranch); if (bidSettings.enabled) { const awards = await loadActiveBidAwardsForOrder(orderCode, client); const fullCoverSkus = new Set(); if (awards.size) { const coverRows = await client.query( `SELECT sku_code FROM order_items WHERE order_code = $1 AND NULLIF(TRIM(sku_code), '') IS NOT NULL GROUP BY sku_code HAVING BOOL_AND( COALESCE(stock_cover_qty, 0) >= COALESCE(quantity, 0) - 1e-9 )`, [orderCode] ); for (const row of coverRows.rows) { const sku = String(row.sku_code || '').trim(); if (sku) fullCoverSkus.add(sku); } } for (const allocation of results) { const sku = String(allocation.sku_code || '').trim(); const award = sku ? awards.get(sku) : undefined; if (!award) continue; if (sku && directSkuSet.has(sku)) continue; // 本单该 SKU 已全额库存覆盖:不强制中标商(含周期中标) if (sku && fullCoverSkus.has(sku)) continue; // 有中标则强制走供应商备货(覆盖原先「无分类→自采」等结果) allocation.target = 'supplier'; allocation.supplier_code = award.supplier_code; allocation.supplier_name = award.supplier_name; allocation.supply_price = award.unit_price > 0 ? award.unit_price : allocation.supply_price; allocation.total_cost = (allocation.supply_price || 0) * allocation.quantity + (allocation.transport_cost || 0); allocation.reason = `竞价中标供应商 ${award.supplier_name}(管理员可改派)`; allocation.allocation_source = 'bid_award'; allocation.confidence = 98; } } } catch { // 竞价挂钩失败不阻断分配 } // B3: 无采购员且无默认分配配置时不再整单回滚;供应商明细照常分配,自采行记入待人工 const assignDefault = await getPurchaseAssignDefaultConfig(effectiveBranch); const canSelfPurchaseWithoutPrimary = Boolean(primaryPurchaser) || Boolean(assignDefault.mode); // free_pool / by_sku / by_category / to_purchaser const purchaserNeededWithoutBuyer = results.some((row) => row.target === 'purchaser') && !canSelfPurchaseWithoutPrimary; if (purchaserNeededWithoutBuyer) { const names = results .filter((row) => row.target === 'purchaser') .map((row) => { const it = pendingItems.find((p) => p.id === row.item_id); return String(it?.item_name || it?.sku_name || it?.sku_code || '未命名'); }) .slice(0, 8); result.errors.push( `未配置主采购员,以下明细待人工处理:${names.join('、')}${names.length >= 8 ? '…' : ''}` ); } for (const allocation of results) { const sourceItem = pendingItems.find((row) => row.id === allocation.item_id); if (!sourceItem) continue; // 安全网:采购员手动选择了自采(INTERNAL)的明细,不覆盖为供应商 if (sourceItem.supplier_code === INTERNAL_PURCHASER_CODE) continue; const designatedSupplier = designatedBySku.get(String(sourceItem.sku_code || '').trim()); if (designatedSupplier) { const switched = await ensureSupplierPreparationReplacingPurchases( { orderCode, item: sourceItem, supplierCode: designatedSupplier, branchCode: effectiveBranch, customerCode: effectiveCustomer, }, client, '分类/SKU 匹配供应商,取消原自采单' ); if (!switched.kept) { const prep = switched.preparation; if (prep.created) { result.preparationsCreated += 1; if (prep.skuCostSync) skuSyncQueue.push(prep.skuCostSync); } } result.itemsProcessed += 1; continue; } const supplierCodeForItem = allocation.target === 'purchaser' ? null : allocation.supplier_code; await client.query( `UPDATE order_items SET supplier_code = $1, category_code = $2, category_name = $3 WHERE id = $4 AND order_code = $5`, [ supplierCodeForItem, sourceItem.category_code || allocation.category_code || null, sourceItem.category_name || allocation.category_name || null, allocation.item_id, orderCode, ] ); sourceItem.supplier_code = supplierCodeForItem; sourceItem.category_code = sourceItem.category_code || allocation.category_code || null; if (allocation.target === 'purchaser') { const created = await createPurchaseOrderForItem( { orderCode, item: sourceItem, remark: allocation.reason, purchaser: primaryPurchaser, branchCode: effectiveBranch, customerCode: effectiveCustomer, }, client ); if (created) result.purchaseOrdersCreated += 1; // 无法解析采购员:明细已清 supplier,不建自采单,由后续状态/人工处理 } else if (allocation.sku_code) { const switched = await ensureSupplierPreparationReplacingPurchases( { orderCode, item: sourceItem, supplierCode: allocation.supplier_code, supplyPrice: allocation.allocation_source === 'bid_award' ? Number(allocation.supply_price) || undefined : undefined, branchCode: effectiveBranch, customerCode: effectiveCustomer, }, client, '分类/SKU 匹配供应商,取消原自采单' ); if (!switched.kept) { const prep = switched.preparation; if (prep.created) { result.preparationsCreated += 1; if (prep.skuCostSync) skuSyncQueue.push(prep.skuCostSync); } } } result.itemsProcessed += 1; } for (const item of withSku) { if (!inOnlyItemScope(item.id)) continue; if (isUnassignedSupplier(item.supplier_code) || !item.sku_code) continue; const supplierCode = String(item.supplier_code); const prep = await ensureSupplierPreparation( { orderCode, item, supplierCode, branchCode: effectiveBranch, customerCode: effectiveCustomer, }, client ); if (prep.created) { result.preparationsCreated += 1; if (prep.skuCostSync) skuSyncQueue.push(prep.skuCostSync); } } // 兜底:仍无供应商且无采购单的明细 → 生成自采采购单 { const leftover = await client.query( `SELECT oi.id, oi.order_code, oi.sku_code, oi.item_name, oi.quantity, oi.unit, oi.price, oi.category_code, oi.category_name, oi.supplier_code, oi.processing_method, oi.processing_owner FROM order_items oi WHERE oi.order_code = $1 AND (oi.supplier_code IS NULL OR TRIM(oi.supplier_code) = '' OR oi.supplier_code IN ('UNASSIGNED', 'INTERNAL')) AND NOT EXISTS ( SELECT 1 FROM purchase_orders po WHERE po.order_code = oi.order_code AND po.source_id = oi.id::text AND po.purchase_status < 80 )`, [orderCode] ); for (const row of leftover.rows as OrderItemRow[]) { if (!inOnlyItemScope(row.id)) continue; // 竞价范围内的 SKU 暂缓履约(留给中标后按中标供应商分配)。 // 漏掉这一句会让「供应商为空 + 无采购单」的行(正是竞价中行的特征) // 立刻生成空供应商自采单,既与竞价冲突,订单列表/自采列表也会显示成「自采」。 if (excludeSkuSet.has(String(row.sku_code || '').trim())) continue; const created = await createPurchaseOrderForItem( { orderCode, item: { ...row, sku_name: row.item_name, }, remark: '分配兜底:未匹配供应商,转自采', purchaser: primaryPurchaser, branchCode: effectiveBranch, customerCode: effectiveCustomer, }, client ); if (created) { result.purchaseOrdersCreated += 1; result.itemsProcessed += 1; } } } if (restrictToNewItems) { const coverageRows = ( await client.query( `SELECT id, sku_code, item_name, quantity, unit, price, category_code, category_name, supplier_code, processing_method, processing_owner FROM order_items WHERE order_code = $1 AND id = ANY($2::uuid[]) ORDER BY sort_order ASC NULLS LAST, id ASC`, [orderCode, [...onlyItemIdSet]] ) ).rows as OrderItemRow[]; await forceCoverUnfulfilledOrderItems( orderCode, coverageRows, primaryPurchaser, effectiveBranch, effectiveCustomer, result, client, skuSyncQueue, // 同上:竞价中的 SKU 不在此强制转自采 { skipSkuCodes: excludeSkuSet } ); await recalcPreparationQty(client, orderCode); } else { // 强制:订单列表每一行必须进入自采或备货,禁止遗漏(含市场阻断/规则跳过) await clearMismatchedPreparationFulfillments(client, orderCode); const coverageRows = ( await client.query( `SELECT id, sku_code, item_name, quantity, unit, price, category_code, category_name, supplier_code, processing_method, processing_owner FROM order_items WHERE order_code = $1 ORDER BY sort_order ASC NULLS LAST, id ASC`, [orderCode] ) ).rows as OrderItemRow[]; const uncovered = await forceCoverUnfulfilledOrderItems( orderCode, coverageRows, primaryPurchaser, effectiveBranch, effectiveCustomer, result, client, skuSyncQueue, // 竞价范围内的 SKU 暂缓履约(留给中标后按中标供应商分配),不得在此强制转自采 { skipSkuCodes: excludeSkuSet } ); // 竞价中的行不要求此时已覆盖,否则会把「等待中标」误判为「订单未全覆盖」 const waitingBidUncovered = excludeSkuSet.size > 0 ? (await listUncoveredOrderItems(client, orderCode)).filter((row) => excludeSkuSet.has(String(row.sku_code || '').trim()) ) : []; const allFilledOutsideBid = uncovered.length === 0 && waitingBidUncovered.length === 0; const allFulfilled = uncovered.length === 0; const currentStatus = Number(order.order_status); // 无采购员且无默认分配导致无法转自采:记入 errors,嵌套事务中不抛断,由上层按软警告处理 if (!allFilledOutsideBid && canSelfPurchaseWithoutPrimary) { await assertOrderItemsFulfilled(client, orderCode, { includeHistoryRepair: currentStatus >= 90, }); } else if (allFulfilled && waitingBidUncovered.length === 0) { await assertOrderItemsFulfilled(client, orderCode, { includeHistoryRepair: currentStatus >= 90, }); } // 改 SKU / 重分配后重算仍共用的备货数量;孤儿备货由触发器 trg_cleanup_orphan_fulfillments 自动清理 await recalcPreparationQty(client, orderCode); if (allFulfilled && currentStatus < 30) { await client.query(`UPDATE orders SET order_status = 30 WHERE order_code = $1`, [orderCode]); result.orderStatusUpdated = 30; } } if (ownsTransaction) await client.query('COMMIT'); } catch (error: unknown) { if (!ownsTransaction) throw error; await client.query('ROLLBACK').catch(() => undefined); result.errors.push(error instanceof Error ? error.message : '订单分配失败,已回滚'); result.itemsProcessed = 0; result.purchaseOrdersCreated = 0; result.preparationsCreated = 0; result.orderStatusUpdated = undefined; return result; } finally { if (ownsTransaction) client.release(); } if (ownsTransaction) { await runAllocationAfterCommitSideEffects({ orderCode, orderBranchCode, result, skuSyncQueue }); } return result; } /** * 采购员加单直接分配:按明细已有的 supplier_code 直接落库, * 不经过智能分配引擎,不修改 supplier_code,完全尊重采购员的选择。 * * - supplier_code 为空或 INTERNAL → 生成自采采购单 * - supplier_code 为真实供应商 → 生成供应商备货 */ /** * 手动补一次「库存抵扣」(2026-10-10 开发者要求)。 * * 场景:主系统分配过来的订单,**分配那一刻库存还没上新**(忘记录入库)⇒ 库存抵扣 = 0、缺口全转采购; * 事后补录库存却没有任何入口重跑。本函数就是那个入口。 * * 为什么放在 service 而不是路由里:① 路由层不得内嵌 SQL(`routeLayerBoundary.test.ts` 棘轮); * ② 必须复用既有分配路线 `reprocessOrderAllocation`(行锁 + 事务 + 幂等,并按新抵扣**重规划采购/备货** * —— 只调 `applyStockCoverForOrder` 会留下"既抵扣又采购"的双记)。 * 安全:已入库/已拣货的行由 `loadLockedStockCoverIfInboundOrPicking` 守住,重复点不会翻倍或清零。 */ export async function applyInventoryOffsetForMainSystemOrder(input: { orderCode: string; customerCode?: string | null; branchCode: string; /** 调用方已取到的订单状态(避免重复查询) */ orderStatus: number; }): Promise< | { kind: 'ok'; coveredBefore: number; coveredAfter: number; coveredDelta: number; message: string; allocation: ReprocessOrderResult; } | { kind: 'not_main_system_order' } | { kind: 'too_late'; status: number } | { kind: 'invalid'; reason: string } > { const orderCode = String(input.orderCode || '').trim(); const branchCode = String(input.branchCode || '').trim(); if (!orderCode || !branchCode) return { kind: 'invalid', reason: '缺少订单号或分公司' }; // 只给**主系统分配过来的单**用:自建单在录单/分配时就走过了这条路线,不需要这个补丁入口 const ledger = await pool.query( `SELECT 1 FROM public.main_system_order_imports WHERE branch_code = $1 AND our_order_code = $2 LIMIT 1`, [branchCode, orderCode] ); if (!ledger.rowCount) return { kind: 'not_main_system_order' }; const status = Number(input.orderStatus) || 0; // 发车/配送中(>=50)已在扣库与出库,重跑抵扣会与在途库存打架 if (status >= 50) return { kind: 'too_late', status }; const sumCover = async (): Promise => { const res = await pool.query<{ n: number }>( `SELECT COALESCE(SUM(stock_cover_qty), 0)::float AS n FROM order_items WHERE order_code = $1`, [orderCode] ); return Number(res.rows[0]?.n) || 0; }; const before = await sumCover(); const allocation = await reprocessOrderAllocation(orderCode, input.customerCode ?? null, branchCode); const after = await sumCover(); const coveredDelta = Math.round((after - before) * 1000) / 1000; return { kind: 'ok', coveredBefore: before, coveredAfter: after, coveredDelta, message: coveredDelta > 0 ? `库存抵扣完成:本次新增抵扣 ${coveredDelta}` : '库存抵扣完成:当前库存没有可新抵扣的量(缺口仍需采购)', allocation, }; } export async function purchaserDirectAllocation( params: { orderCode: string; branchCode: string | null | undefined; customerCode: string | null | undefined; purchaserCode: string; itemIds: string[]; }, client: PoolClient ): Promise<{ purchaseOrdersCreated: number; preparationsCreated: number; errors: string[]; }> { const result = { purchaseOrdersCreated: 0, preparationsCreated: 0, errors: [] as string[] }; const itemIds = [...new Set(params.itemIds.map((id) => String(id || '').trim()).filter(Boolean))]; if (!itemIds.length) return result; const purchaserResult = await client.query( `SELECT purchaser_code, purchaser_name FROM purchaser_users WHERE purchaser_code = $1 AND status = 1 LIMIT 1`, [params.purchaserCode] ); const directPurchaser = purchaserResult.rows[0] || { purchaser_code: params.purchaserCode, purchaser_name: params.purchaserCode, }; // 只加载本次小程序加单实际新建的行,不回扫或重分配历史订单行。 const itemsResult = await client.query( `SELECT oi.*, s.sku_name AS joined_sku_name FROM order_items oi LEFT JOIN skus s ON s.sku_code = oi.sku_code WHERE oi.order_code = $1 AND oi.id = ANY($2::uuid[]) ORDER BY oi.sort_order ASC NULLS LAST, oi.id ASC`, [params.orderCode, itemIds] ); for (const row of itemsResult.rows) { const item: OrderItemRow = { ...row, sku_name: row.joined_sku_name || row.item_name, }; // 跳过已履约的明细 if (await isOrderItemFulfillmentValid(client, String(item.id))) continue; try { const forceSelfPurchase = requiresWarehouseProcessing(item.processing_method, item.processing_owner) || (hasSkuCode(item.sku_code) && (await loadDirectDeliverySkuSetForOrder(params.orderCode, [item.sku_code], client)).has(String(item.sku_code))); if (forceSelfPurchase || isUnassignedSupplier(item.supplier_code) || !hasSkuCode(item.sku_code)) { if (forceSelfPurchase) { await client.query(`UPDATE order_items SET supplier_code = $2 WHERE id = $1::uuid`, [ item.id, INTERNAL_PURCHASER_CODE, ]); item.supplier_code = INTERNAL_PURCHASER_CODE; } // 自采:直接生成采购单 const created = await createPurchaseOrderForItem( { orderCode: params.orderCode, item: { ...item, sku_name: item.sku_name || item.item_name }, remark: '采购员加单:自采', purchaser: directPurchaser, lockPurchaser: true, branchCode: params.branchCode, customerCode: params.customerCode, }, client ); if (created) result.purchaseOrdersCreated += 1; } else { // 指定供应商:直接生成备货 const supplierCode = String(item.supplier_code); const prep = await ensureSupplierPreparation( { orderCode: params.orderCode, item, supplierCode, branchCode: params.branchCode, customerCode: params.customerCode, }, client ); if (prep.created) result.preparationsCreated += 1; } } catch (err: any) { result.errors.push( `${String(item.item_name || item.sku_code || '商品')}: ${err?.message || '分配失败'}` ); } } return result; }