Files
SupplierSystem/server/src/services/selfPickupService.ts
T
Ubuntu a57a6c19ae feat(客户自提): 「是否取货」客户级开关 + 分拣完毕进「待取货」+ 管理员确认取货结案
开发者需求:「客户列表加一个按钮,是否取货(客户自己来拿货、不走配送)」;
二次澄清采纳方案乙:「还是待取货,旁边留一个按钮,客户取货后点完成就结案」;
逐条确认:权限给管理员 / 不生成配送单(和主系统发过来的类似)/ 取货在订单列表点按钮。

后端:
- 迁移 20261049:只加两列 customers.is_self_pickup / orders.self_pickup(NOT NULL DEFAULT false ⇒
  存量行为完全不变),逐 schema + tenant_template 幂等;不新建表、不动 tenant_business_tables()。
- 录单快照:建单 INSERT 里用子查询带出客户开关(改客户开关不影响已有单)。
  ⚠️ 子查询必须用独立参数 $13:否则 PG 报 `inconsistent types deduced for parameter $4`
  ($4 在 VALUES 推断 text、在 customers.customer_code=$4 推断 varchar;::text 转换救不了)——
  本地实测复现(PREPARE)+ 修复后验证。
- 不生成配送任务:ensureDeliveryTaskForOrder 第四道守卫(在 pool.connect() 之前)。
- 拦发车:tryAdvanceOrderToDelivering 对自提单抛 400 self_pickup_no_delivery;
  位置在 status>=60 / <50 两条早退之后(避免打断 orderStatusReconcileService 的周期性调用)。
- 配送管理列表不再显示自提单:nonSelfPickupOrderSql 加在 6 处查询。
- 回退器不再把自提单从 50 打回 30(demotePrematureInspectionStatus 的 UPDATE 加条件)。
- 确认取货接口 POST /workflow/orders/:orderCode/self-pickup-complete(仅管理员,
  requireAdminRole + 复用既有权限码):只允许自提单 + 只允许停在 50 + 已 90 幂等;
  走 completeOrderWithoutDriverDelivery(settleInventory:true) ⇒ 不新增状态边、不动状态链;
  全段在租户上下文内(orders 为 FORCE RLS);写审计。
- 客户开关走领域接口 POST /workflow/customers/:customerCode/self-pickup(仅管理员 + 审计),
  而不是前端通用网关直写 —— gatewayWriteBoundary 守卫禁止新增 /api/data 写入点(实测被拦下后改正)。

前端:
- 客户列表新增「是否取货」列 + 开关(仅管理员;走领域接口;在途锁)。
- 订单列表:50 的自提单显示「待取货」(与主系统免入库区分来源),管理员见「确认取货」按钮
  (在途锁、成功/失败提示、刷新)。
- 三语文案(开关列、按钮、提示)。

测试:server/tests/selfPickup.test.ts 8 例(迁移只加列、快照、两道守卫及其相对位置、列表派生、
接口管理员鉴权、服务状态机、状态链未改)。

回归:定向子集 23 文件/170 用例,8 个失败**全部为基线既有**;网关边界守卫 4/4 通过(修好新引入的
写入点数超标);两端 tsc 0 错误。全量后端 26 failed files,其中 weighInspectionMergeSimilar 的
2 例为 5s 测试超时(机器负载高、时快时慢,非本次改动)。
2026-10-16 13:50:19 +08:00

116 lines
5.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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<SelfPickupCompleteResult> {
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 };
}