import { pool } from '../db'; import { writeAuditLog } from './auditService'; import { completeOrderWithoutDriverDelivery } from './orderWorkflowFulfillmentService'; import { runWithTenantDbContext } from './tenantDbContext'; /** * 客户自提「确认取货」⇒ 结案(2026-10-15 开发者需求「是否取货」)。 * * 口径(与主系统免入库单同一套"无配送结案"机制): * · 自提客户的自提单:录单时把客户开关**快照**到 `orders.self_pickup`; * · 照常备货/验收/**分拣**(分拣完毕 = 出库 = 扣库存)⇒ 停在 **50「待取货」**; * · **管理员**在订单列表点「确认取货」⇒ 本函数 ⇒ **90 已完成**; * · 收口复用 `completeOrderWithoutDriverDelivery`(接受 30/50 → 90)⇒ **不新增状态边、不动状态链**; * · 结案照常:按实收冻结 `order_items.quantity` 并重算 `amount`、生成客户/供应商结算单、 * 结案前再跑一次出库引擎(逐 SKU 幂等,只补"分拣时软扣跳过"的缺口)。 * * 与相邻概念的区别: * · 主系统免入库「待取货」:由**主系统骑手上门取货**,靠对方 `preparations.picked_up` 事件收口; * · 散客录单:**无分拣**、全额库存抵扣、录单确认即完成; * · 本函数:**有分拣**、**我方管理员**确认取货后收口。 */ const ALLOWED_CLOSE_STATUSES = new Set([50]); export interface SelfPickupCompleteResult { order_code: string; order_status: number; already_completed: boolean; } function businessError(message: string, status: number, code: string): Error & { status: number; code: string } { return Object.assign(new Error(message), { status, code }); } export async function selfPickupComplete(input: { orderCode: string; branchCode?: string | null; operatorId?: string | null; operatorRole?: string | null; }): Promise { const orderCode = String(input.orderCode || '').trim(); if (!orderCode) throw businessError('缺少订单号', 400, 'invalid_request'); /** * ⚠️ 必须在**租户上下文内**读订单:`orders` 是 FORCE ROW LEVEL SECURITY。 * HTTP 路径有请求级 ALS 所以能读;但单测/脚本直接调会被 RLS 挡成 0 行 ⇒ 假 404(分析代理 2026-10-15 指出)。 * 故这里**要求显式 branchCode**并把整段逻辑都放进 `runWithTenantDbContext`。 */ const ctxBranchCode = String(input.branchCode || '').trim(); if (!ctxBranchCode) throw businessError('缺少分公司上下文', 400, 'branch_required'); const orderRow = await runWithTenantDbContext(ctxBranchCode, () => pool.query<{ order_status: number | null; self_pickup: boolean | null; branch_code: string | null; }>( `SELECT order_status, COALESCE(self_pickup, false) AS self_pickup, branch_code FROM orders WHERE order_code = $1 AND deleted_at IS NULL LIMIT 1`, [orderCode] )); if (!orderRow.rowCount) throw businessError('订单不存在', 404, 'not_found'); const row = orderRow.rows[0]; const status = Number(row.order_status) || 0; /** 幂等:已结案直接返回(前端重复点击/并发重试都不报错) */ if (status >= 90) { return { order_code: orderCode, order_status: status, already_completed: true }; } /** 只有自提单能走这条路:普通单/主系统单不得被这个按钮结案 */ if (row.self_pickup !== true) { throw businessError('该单不是客户自提单,不能用「确认取货」结案', 409, 'not_self_pickup'); } /** 必须停在 50「待取货」:分拣完毕(= 出库扣库)之后才是"客户可来拿货"的状态 */ if (!ALLOWED_CLOSE_STATUSES.has(status)) { throw businessError( `订单当前状态 ${status},自提确认取货需在待取货(50)之后(请先完成分拣)`, 409, 'invalid_state' ); } const branchCode = ctxBranchCode || String(row.branch_code || '').trim(); await runWithTenantDbContext(branchCode, () => completeOrderWithoutDriverDelivery(orderCode, undefined, { settleInventory: true }) ); const after = await runWithTenantDbContext(branchCode, () => pool.query<{ order_status: number | null }>( `SELECT order_status FROM orders WHERE order_code = $1 LIMIT 1`, [orderCode] ) ); const orderStatus = Number(after.rows[0]?.order_status) || status; // 审计(提交后写,失败不回滚主流程):谁在什么时候确认取货 try { await writeAuditLog({ operatorId: input.operatorId || null, operatorRole: input.operatorRole || null, operationType: 'self_pickup_complete', targetTable: 'orders', targetId: orderCode, oldValue: { order_status: status, self_pickup: true }, newValue: { order_status: orderStatus, self_pickup: true }, branchCode: branchCode || null, actionCategory: 'order', }); } catch (auditError) { console.error('[self-pickup] 取货确认审计写入失败', auditError); } return { order_code: orderCode, order_status: orderStatus, already_completed: orderStatus >= 90 }; }