import type { PoolClient } from 'pg'; import { pool } from '../db'; import { assertPurchaseOrderInBranch } from './purchaserBranchScope'; import { PURCHASE_STATUS_QUALITY_REJECTED } from './purchaseInboundService'; import { ensurePurchaseInspectionForCompletedPurchase } from './inspectionComplianceService'; import { tryAdvanceOrderToInspection } from './preparationFulfillmentService'; import { ensureSkuFromPurchaseCompletion } from './skuProvisioningService'; import { syncOrderItemsFromSupplyCompletion } from './orderItemSupplyUnitSync'; import { assertPositiveSupplyCostPrice, assertSupplyCostPrice, clearPlanPriceForZeroCost, } from './supplyCostPrice'; import { isZeroSupplyCostAllowed } from './zeroSupplyCostConfigService'; import { syncSkuCostFromPreparation } from './preparationCostService'; import { assertOrderActiveForFulfillment } from './orderTrashScope'; import { isSkuDirectDeliveryForPurchase } from './skuDirectDelivery'; import { assertSkuDirectDeliveryPhotosIfRequired } from './purchaseDirectDeliveryPhotoService'; import { applyQuoteMarkupSalePriceAtSupplyCompletion } from './quoteMarkupSalePriceService'; export interface UpdatePurchaseOrderStatusInput { purchaseCode: string; branchCode: string; status: number; actualQty?: number | null; actualPrice?: number | null; remark?: string | null; itemName?: string | null; categoryCode?: string | null; categoryName?: string | null; unit?: string | null; /** 自由池完成时写入归属;已挂他人则拒绝(见 free-pool 设计) */ claimPurchaser?: { purchaser_code: string; purchaser_name: string } | null; } export interface UpdatePurchaseOrderStatusResult { success: true; sku_code: string | null; sku_created: boolean; needs_customer_price: boolean; needs_customer_price_item_ids: string[]; } export async function updatePurchaseOrderStatus( input: UpdatePurchaseOrderStatusInput, existingClient?: PoolClient ): Promise { const client = existingClient || (await pool.connect()); const ownsClient = !existingClient; try { if (ownsClient) await client.query('BEGIN'); const purchaseCode = String(input.purchaseCode || '').trim(); const status = Number(input.status); let actualQty = input.actualQty === undefined ? null : Number(input.actualQty); let actualPrice = input.actualPrice === undefined ? null : Number(input.actualPrice); const remark = input.remark === undefined ? null : String(input.remark).trim(); const itemName = input.itemName === undefined ? null : String(input.itemName).trim(); const categoryCode = input.categoryCode === undefined ? null : String(input.categoryCode).trim(); const categoryName = input.categoryName === undefined ? null : String(input.categoryName).trim(); const unit = input.unit === undefined ? null : String(input.unit).trim(); if (!purchaseCode || ![20, 30, 40].includes(status)) { throw Object.assign(new Error('采购状态参数无效'), { status: 400, code: 'invalid_request' }); } const currentRow = await assertPurchaseOrderInBranch(client, purchaseCode, input.branchCode); if (status === 40) { const { purchaseLinkedToWarehouseDemand } = await import('./processingDemandSheetService'); if (await purchaseLinkedToWarehouseDemand(purchaseCode, client)) { throw Object.assign(new Error('仓内加工成品自采不可作废,请点「跳过」'), { status: 409, code: 'warehouse_demand_no_cancel', }); } } if ([20, 30].includes(status)) { const { assertWarehouseDemandPurchaseNotFinishedAsProduct } = await import( './processingDemandSheetService' ); await assertWarehouseDemandPurchaseNotFinishedAsProduct( purchaseCode, actualPrice, client ); } const orderLink = await client.query( `SELECT order_code, purchaser_code, purchaser_name FROM purchase_orders WHERE purchase_code = $1 LIMIT 1`, [purchaseCode] ); await assertOrderActiveForFulfillment(orderLink.rows[0]?.order_code, client); const currentStatus = Number(currentRow.purchase_status) || 0; const needsProductSetup = status === 20 && !String(currentRow.sku_code || '').trim(); const claim = input.claimPurchaser; const claimCode = String(claim?.purchaser_code || '').trim(); const claimName = String(claim?.purchaser_name || claimCode || '').trim(); if (claimCode && [20, 30, 40].includes(status)) { const existingPurchaser = String(orderLink.rows[0]?.purchaser_code || '').trim(); if (existingPurchaser && existingPurchaser !== claimCode) { throw Object.assign(new Error('该采购任务已分配给其他采购员'), { status: 403, code: 'purchaser_mismatch', }); } if (!existingPurchaser) { await client.query( `UPDATE purchase_orders SET purchaser_code = $2, purchaser_name = $3 WHERE purchase_code = $1 AND (purchaser_code IS NULL OR TRIM(purchaser_code) = '')`, [purchaseCode, claimCode, claimName || claimCode] ); } } if (needsProductSetup) { if (!itemName) { throw Object.assign(new Error('未匹配商品库,请填写商品名称'), { status: 400, code: 'invalid_request' }); } if (!categoryCode) { throw Object.assign(new Error('未匹配商品库,请选择商品分类'), { status: 400, code: 'invalid_request' }); } } /** 直送行不进验收待办,保留「完成自采时按计划量落实收」这一豁免 */ let autoActualForDelivery = false; if (status === 20) { const skuCode = String(currentRow.sku_code || '').trim(); if (skuCode && (await isSkuDirectDeliveryForPurchase(purchaseCode, client))) { if (actualQty == null || !Number.isFinite(actualQty) || actualQty <= 0) { const qtyRow = await client.query( `SELECT purchase_qty FROM purchase_orders WHERE purchase_code = $1 LIMIT 1`, [purchaseCode] ); actualQty = Number(qtyRow.rows[0]?.purchase_qty) || 0; } autoActualForDelivery = actualQty != null && Number.isFinite(actualQty) && Number(actualQty) > 0; } } // 方案 C(docs/design/20260920-self-purchase-actual-qty-single-writer.md): // 仅「完成自采(status 20)」这条路径忽略客户端预填的实收量——预填会让 // inspectionComplianceService 的「实收量归谁写」守卫早退,单据永久停在 20。 // status 30/40 是状态机其它边(含作废 40),必须保持改动前的 COALESCE 语义, // 否则会把已有实收与金额误清成 NULL。 const preserveStoredActual = status !== 20 || autoActualForDelivery; if (status === 20 && !autoActualForDelivery) actualQty = null; if (status === 20) { const priceRow = await client.query( `SELECT actual_price, purchase_price, self_processed, branch_code FROM purchase_orders WHERE purchase_code = $1 LIMIT 1`, [purchaseCode] ); const existing = priceRow.rows[0] || {}; const selfProcessed = Boolean(existing.self_processed); const { purchaseLinkedToWarehouseDemand } = await import('./processingDemandSheetService'); const warehouseDemand = await purchaseLinkedToWarehouseDemand(purchaseCode, client); // 仓内加工/挂加工需求单:成本必须为 0(既有反向规则,开关不改); // 其余单据:默认必须 >0,「允许成本价为 0」开关开启后可按 0 保存(负数/NaN 仍拒)。 const allowZeroCost = selfProcessed || warehouseDemand; const effectivePrice = actualPrice !== null && Number.isFinite(actualPrice) ? actualPrice : Number(existing.actual_price ?? existing.purchase_price) || 0; if (allowZeroCost) { if (!Number.isFinite(effectivePrice) || effectivePrice < 0) { throw Object.assign(new Error('实采单价无效'), { status: 400, code: 'invalid_request' }); } if (actualPrice === null || actualPrice <= 0) actualPrice = 0; } else { const zeroCostAllowedForBranch = await isZeroSupplyCostAllowed( String(existing.branch_code || '').trim() || null ); // 开关开启:「未填」与「填 0」等价,都按 0 落库(负数/NaN 仍拒)。 // 未填**不再沿用登记价** —— 否则用户没填价直接点完成,系统却按下单价算成本。 if (zeroCostAllowedForBranch && (actualPrice === null || Number(actualPrice) === 0)) { if (actualPrice === null) actualPrice = 0; assertSupplyCostPrice(actualPrice, '实采单价', { allowZero: true }); } else { assertPositiveSupplyCostPrice(effectivePrice, '实采单价'); } } } const zeroPurchaseCost = status === 20 && actualPrice !== null && Number(actualPrice) === 0; if (currentStatus === PURCHASE_STATUS_QUALITY_REJECTED && status === 20) { await client.query( `UPDATE purchase_orders SET purchase_status = 20, inbound_quality_grade = NULL, inbound_quality_score = NULL, inbound_photo = NULL, -- 方案 C:重新采购时清掉上一批实收与金额,交由新一轮验收写入 actual_qty = CASE WHEN $4::boolean THEN COALESCE($2, actual_qty) ELSE NULL END, actual_price = COALESCE($3, actual_price), total_amount = CASE WHEN NOT $4::boolean THEN NULL WHEN COALESCE($2, actual_qty) IS NOT NULL AND COALESCE($3, actual_price) IS NOT NULL THEN ROUND(COALESCE($2, actual_qty) * COALESCE($3, actual_price), 2) ELSE total_amount END, remark = COALESCE(remark, '') || ';质检不合格后重新采购' WHERE purchase_code = $1`, [purchaseCode, actualQty, actualPrice, preserveStoredActual] ); } else { await client.query( `UPDATE purchase_orders SET purchase_status = $1, actual_qty = CASE WHEN $6::boolean THEN COALESCE($2, actual_qty) ELSE NULL END, actual_price = COALESCE($3, actual_price), total_amount = CASE WHEN NOT $6::boolean THEN NULL WHEN COALESCE($2, actual_qty) IS NOT NULL AND COALESCE($3, actual_price) IS NOT NULL THEN ROUND(COALESCE($2, actual_qty) * COALESCE($3, actual_price), 2) ELSE total_amount END, remark = COALESCE($5::text, remark) WHERE purchase_code = $4`, [status, actualQty, actualPrice, purchaseCode, remark, preserveStoredActual] ); } // 实采价为 0:把「下单采购价」与金额一并清零,避免各处读取点 // (`COALESCE(NULLIF(actual_price,0), purchase_price)`:金额重算 / 倒挂判定 / 列表展示) // 把真实的 0 成本静默回退成下单价。适用两种情形: // ① 仓内加工行(既有反向规则:成本必须为 0,开关不改); // ② 「允许成本价为 0」开关开启的普通自采行(显式 0 或未填按 0 处理)。 if (zeroPurchaseCost) { const flagRow = await client.query( `SELECT COALESCE(self_processed, false) AS self_processed, branch_code FROM purchase_orders WHERE purchase_code = $1`, [purchaseCode] ); const { purchaseLinkedToWarehouseDemand } = await import('./processingDemandSheetService'); const linked = await purchaseLinkedToWarehouseDemand(purchaseCode, client); const branchAllowsZero = await isZeroSupplyCostAllowed( String(flagRow.rows[0]?.branch_code || '').trim() || null ); if (Boolean(flagRow.rows[0]?.self_processed) || linked || branchAllowsZero) { await clearPlanPriceForZeroCost(client, purchaseCode); } } let skuProvision: { skuCode: string; barcode: string; created: boolean } | null = null; if (status === 20 && needsProductSetup && itemName && categoryCode) { skuProvision = await ensureSkuFromPurchaseCompletion(client, { purchaseCode, itemName, categoryCode, categoryName, unit, costPrice: actualPrice, branchCode: input.branchCode, }); if (!skuProvision?.skuCode) { throw Object.assign(new Error('保存商品信息失败,请检查名称和分类'), { status: 400, code: 'invalid_request', }); } } let needsCustomerPrice = false; const needsCustomerPriceItemIds: string[] = []; // 采购进入完成态(20 待仓验 / 30 / 40)后都应尝试推进订单离开「待备货」 if ([20, 30, 40].includes(status)) { if (status === 20) { const poRow = await client.query( `SELECT po.order_code, po.sku_code, po.actual_qty, po.purchase_qty, po.actual_price, po.purchase_price, po.supplier_code, po.branch_code, o.customer_code FROM purchase_orders po LEFT JOIN orders o ON o.order_code = po.order_code WHERE po.purchase_code = $1 LIMIT 1`, [purchaseCode] ); const po = poRow.rows[0]; if (po) { const syncResult = await syncOrderItemsFromSupplyCompletion(client, { orderCode: po.order_code ? String(po.order_code) : null, skuCode: po.sku_code ? String(po.sku_code) : null, settlementQty: Number(po.actual_qty) || 0, settlementUnit: unit || null, link: { type: 'purchase', purchaseCode }, supplierCode: po.supplier_code ? String(po.supplier_code) : null, // 直送采购没有后续配送员核货,实际采购量即客户实配量; // 其他采购继续按原有 quantity 口径,避免影响普通订单。 alignSettlementQty: await isSkuDirectDeliveryForPurchase(purchaseCode, client), }); needsCustomerPrice = syncResult.needsCustomerPrice; needsCustomerPriceItemIds.push(...syncResult.itemIds); const costPrice = Number(po.actual_price) > 0 ? Number(po.actual_price) : Number(po.purchase_price) || 0; const skuCode = String(po.sku_code || skuProvision?.skuCode || '').trim(); if (skuCode && costPrice > 0) { const saleResult = po.order_code ? await client.query( `SELECT COALESCE(price, 0)::float AS sale_price FROM order_items WHERE order_code = $1 AND sku_code = $2 ORDER BY id ASC LIMIT 1`, [po.order_code, skuCode] ) : { rows: [] as Array<{ sale_price: number }> }; await syncSkuCostFromPreparation( skuCode, costPrice, client, po.branch_code || input.branchCode || null, { syncQuoteSheet: true, onlyIfQuoteCostZero: false, salePrice: Number(saleResult.rows[0]?.sale_price) || null, onlyIfQuoteSalePriceZero: false, customerCode: String(po.customer_code || '').trim() || null, } ); if (po.order_code) { const { setOrderItemUnitCostByOrderSku } = await import('./orderItemUnitCostService'); await setOrderItemUnitCostByOrderSku( client, String(po.order_code), skuCode, costPrice ); if (await isSkuDirectDeliveryForPurchase(purchaseCode, client)) { const { upsertSkuDirectDeliverySelfPurchaseCost } = await import( './orderCostPostingService' ); const settleQty = Number(po.actual_qty) > 0 ? Number(po.actual_qty) : Number(po.purchase_qty) || 0; await upsertSkuDirectDeliverySelfPurchaseCost(client, { orderCode: String(po.order_code), skuCode, qty: settleQty, unitPrice: costPrice, branchCode: po.branch_code || input.branchCode || null, purchaseCode, }); } } const completedActualCost = Number(po.actual_price); if ( po.order_code && currentStatus !== 20 && Number.isFinite(completedActualCost) && completedActualCost > 0 ) { await applyQuoteMarkupSalePriceAtSupplyCompletion(client, { link: { type: 'purchase', purchaseCode }, finalCost: completedActualCost, branchCode: po.branch_code || input.branchCode || null, orderCode: String(po.order_code), skuCode, supplierCode: po.supplier_code ? String(po.supplier_code) : null, }); } } } await assertSkuDirectDeliveryPhotosIfRequired(purchaseCode, client); await ensurePurchaseInspectionForCompletedPurchase(client, purchaseCode); } const orderCodeResult = await client.query( `SELECT order_code FROM purchase_orders WHERE purchase_code = $1 LIMIT 1`, [purchaseCode] ); const orderCode = orderCodeResult.rows[0]?.order_code; if (orderCode) { await tryAdvanceOrderToInspection(String(orderCode), client); } } if (ownsClient) await client.query('COMMIT'); return { success: true, sku_code: skuProvision?.skuCode || null, sku_created: skuProvision?.created ?? false, needs_customer_price: needsCustomerPrice, needs_customer_price_item_ids: needsCustomerPriceItemIds, }; } catch (error) { if (ownsClient) await client.query('ROLLBACK').catch(() => undefined); throw error; } finally { if (ownsClient) client.release(); } }