import { pool } from '../db'; import { runWithTenantDataAccess } from './tenantSchemaService'; /** * 主系统改**备货行单位** → 通知我方(事件 `preparations.unit_changed`,2026-10-13)。 * * 为什么需要:主系统管理端改单位时,若**价格没变**就不发 `preparations.price_changed` * ⇒ 我方镜像里的单位一直是旧的(他们的 §10.4 / 本仓设计文 §11.4-3 登记的同源反向缺口)。 * 他们开发者已拍板:新增**专用事实事件**(`3608614d`,开关 `SUPPLIER_UNIT_CHANGED_PUSH_ENABLED`)。 * * ⚠️ **口径翻转(2026-10-13 晚,他们 §4.5.25 请求)**:原来是"收到即改我方镜像行", * 那等于"他们一改就把我们的数据改了",与"**自己只能改自己**"(改价那条早已是"事实 + 待审")冲突 * ⇒ 现在默认**登记待审**:写一条 `main_system_actual_qty_requests`(`field='unit'`,`node='unit_changed'`), * 审核页看得到、由我方的人决定跟不跟;**通过时才写** `order_items.unit`(见 `decideActualQtyRequest`)。 * `UNIT_CHANGED_AUTO_APPLY=1` 可整体回退旧行为(收到即改、不建待审)。 * * 纪律:不回推(他们只报事实);行对不上就 `ignored` + 原因,**不猜、不建行**。 */ export type UnitChangedOutcome = { status: 'applied' | 'ignored' | 'pending'; reason: string; /** 落地的我方订单行 id(幂等跳过/找不到行时为 null) */ rowId: string | null; /** 实际落地的单位(排障/日志用) */ unit?: string | null; /** 登记待审时:待审行 id(审核页据此操作) */ requestRowId?: string | null; }; function text(value: unknown): string | null { if (value === null || value === undefined) return null; const s = String(value).trim(); return s || null; } const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; /** 事件载荷 → 业务字段(两个字段名都认:`preparation_id`/`prep_id`、`final_unit`/`unit`) */ export function mapUnitChangedPayload(payload: any) { const prepId = text(payload?.preparation_id) ?? text(payload?.prep_id); const finalUnit = text(payload?.final_unit) ?? text(payload?.unit); return { prepId, beforeUnit: text(payload?.before_unit), finalUnit, unitAlias: text(payload?.unit), skuCode: text(payload?.sku_code), orderCode: text(payload?.order_code), source: text(payload?.source), operator: text(payload?.operator), operatorRole: text(payload?.operator_role), changedAt: text(payload?.changed_at), clientRequestId: text(payload?.client_request_id), /** 他们信封里的投递 id(事件唯一)—— 用作待审台账的 `request_id`(库里 NOT NULL + 唯一) */ requestId: text(payload?.request_id), reason: text(payload?.reason), }; } /** 单位比较:首尾空白与大小写不敏感(与他们 `isUnitActuallyChanged` 同口径) */ function sameUnit(a: string | null, b: string | null): boolean { return String(a ?? '').trim().toLowerCase() === String(b ?? '').trim().toLowerCase(); } /** * 单位变更是否**需要人工审核**(2026-10-13 口径翻转,主系统 §4.5.25 请求)。 * * 默认**要审**:他们改单位推 `preparations.unit_changed` 过来,我方**不再直接改镜像行**, * 而是登记一条待审(`main_system_actual_qty_requests`,`field='unit'`)⇒ 审核页看得到、由人决定跟不跟; * 通过时才写 `order_items.unit`。理由与改价同款:**自己只能改自己**。 * * `UNIT_CHANGED_AUTO_APPLY=1` 可**整体回退**到 2026-10-13 之前的行为(收到即改镜像、不建待审)。 */ export function isUnitChangedReviewRequired(): boolean { return String(process.env.UNIT_CHANGED_AUTO_APPLY ?? '').trim() !== '1'; } /** * 把一条单位变更**登记成待审**(`main_system_actual_qty_requests`,`field='unit'`)。 * * 纪律(与成本价事实 `recordPriceChangedFact` 同款): * · **同一行只留最新一条待审**:同 `(branch, prep)` 的旧 pending 单位行转 `superseded`; * · **幂等**:`request_id`(他们信封 id)或 `client_request_id`(`uc___`)重复投递 * ⇒ 命中唯一键 ⇒ `ignored`(重复投递),不新增第二行; * · 事实来源:他们那边**已经改了**(`changed_at` 落 `applied_at`),所以我们只决定"跟不跟"; * · `payload.local_only=true` ⇒ 审核通过时**不回传**给他们(他们只报事实,不需要回执)。 */ async function registerUnitChangedPending(params: { branchCode: string; mapped: ReturnType; ourOrderCode: string; }): Promise { const { branchCode, mapped, ourOrderCode } = params; const prepId = String(mapped.prepId); const requestId = mapped.requestId || `unit:${mapped.clientRequestId || `${prepId}:${mapped.beforeUnit}->${mapped.finalUnit}`}`; /** * **幂等前置必须在 supersede 之前**(2026-10-13 对抗式复核): * 主系统同一次投递的 2 次重试复用同一个 `request_id`(同一 body 循环重发)。 * 若先跑下面的 supersede UPDATE,重投会把它**自己刚登记的那条 pending** 打成 `superseded`, * 随后 INSERT 撞 `(branch_code, request_id)` 唯一键 ⇒ 接口回报"幂等跳过", * 但待审队列里已经**什么都没有了** ⇒ 单位变更永久丢失、审核页再也看不到。 * 先按唯一键查一次:已登记(含已决策)就直接 ignored,绝不改动既有行。 */ const existed = await pool.query( `SELECT 1 FROM public.main_system_actual_qty_requests WHERE branch_code = $1 AND request_id = $2 LIMIT 1`, [branchCode, requestId] ); if (existed.rowCount) { return { status: 'ignored', reason: '该单位变更已在待审台账里(重复投递,幂等跳过)', rowId: null, unit: mapped.finalUnit, }; } // 同一行只留最新:旧的待审单位行转 superseded(可追溯,审核页"已失效"档能看到) // ⚠️ 必须排除**本请求自己的 request_id**(2026-10-13 对抗式复核): // 上面的存在性前置查询本身是 check-then-act。两笔**并发**的同 request_id 投递里, // 后到的 T2 可能在 T1 提交**之后**才执行本条 UPDATE —— 若不过滤 request_id, // T2 会把 T1 刚落的那条 pending 打成 superseded,随后的 INSERT 再撞唯一键返回 ignored, // 净结果仍是"待审行凭空消失"(与修复前同一类数据丢失)。过滤后 T2 不动 T1 的行, // 插入失败即幂等跳过。顺序重投仍由上面的前置查询拦下,本条不会命中任何行。 await pool.query( `UPDATE public.main_system_actual_qty_requests SET status = 'superseded', updated_at = NOW(), decision_reason = COALESCE(decision_reason, '被更新的单位变更取代(只留最新一条待审)') WHERE branch_code = $1 AND prep_id = $2::uuid AND field = 'unit' AND status = 'pending' AND request_id <> $3`, [branchCode, prepId, requestId] ); try { const inserted = await pool.query<{ id: string }>( `INSERT INTO public.main_system_actual_qty_requests (branch_code, request_id, prep_id, order_code, our_order_code, sku_code, node, field, before_value, proposed_value, before_unit, unit, operator, reason, client_request_id, status, fact_registered, payload, applied_at) VALUES ($1,$2,$3::uuid,$4,$5,$6,'unit_changed','unit', NULL, NULL, $7, $8, $9, $10, $11, 'pending', true, $12::jsonb, $13::timestamptz) RETURNING id::text AS id`, [ branchCode, requestId, prepId, mapped.orderCode, ourOrderCode, mapped.skuCode, mapped.beforeUnit, mapped.finalUnit, mapped.operator, mapped.reason, mapped.clientRequestId, JSON.stringify({ event: 'preparations.unit_changed', source: 'main_system_unit_changed', source_label: mapped.source, operator_role: mapped.operatorRole, changed_at: mapped.changedAt, // 他们只报事实:审核结论**不回传**(`decideActualQtyRequest` 按 local_only 处理) local_only: true, }), mapped.changedAt, ] ); const id = inserted.rows[0]?.id ?? null; return { status: 'pending', reason: `已登记待审:单位 ${mapped.beforeUnit || '—'} → ${mapped.finalUnit}(由我方审核决定是否跟)`, rowId: null, unit: mapped.finalUnit, requestRowId: id, }; } catch (error: unknown) { // 唯一键冲突 = 同一事实重投(幂等) if (String((error as { code?: string })?.code) === '23505') { return { status: 'ignored', reason: '该单位变更已在待审台账里(重复投递,幂等跳过)', rowId: null, unit: mapped.finalUnit, }; } throw error; } } /** * 处理一条 `preparations.unit_changed`(幂等)。 * * · 默认(`isUnitChangedReviewRequired()`):**登记待审**,返回 `{status:'pending'}`; * · 回退开关打开时:直接改镜像行(旧行为,返回 `applied/ignored`)。 * * 业务失败不抛错:返回 `ignored` + 原因,调用方(webhook)照旧 200 收下 —— 重推解决不了前置问题。 */ export async function applyUnitChangedFact(params: { branchCode: string; payload: any; }): Promise { const branchCode = String(params.branchCode || '').trim(); if (!branchCode) return { status: 'ignored', reason: '缺少分公司', rowId: null }; const mapped = mapUnitChangedPayload(params.payload); if (!mapped.prepId) return { status: 'ignored', reason: '缺少 preparation_id', rowId: null }; if (!mapped.finalUnit) return { status: 'ignored', reason: '缺少 final_unit', rowId: null }; if (!UUID_RE.test(mapped.prepId)) { // 不拿非 uuid 去撞 `prep_id = $2::uuid`(那会抛 22P02 并打 500) return { status: 'ignored', reason: `preparation_id 不是 uuid:${mapped.prepId}`, rowId: null }; } // ① 定位我方订单行(行级对照台账是唯一权威,不按 sku/名称猜) const link = await pool.query<{ our_order_code: string | null; our_order_item_id: string | null }>( `SELECT our_order_code, our_order_item_id::text AS our_order_item_id FROM public.main_system_order_import_items WHERE branch_code = $1 AND prep_id = $2::uuid LIMIT 1`, [branchCode, mapped.prepId] ); const row = link.rows[0]; if (!row?.our_order_item_id || !row.our_order_code) { return { status: 'ignored', reason: '我方没有该备货行的对照行(未对照上/已删除)', rowId: null }; } /** * ② **登记待审**(默认口径):写一条 `field='unit'` 的待审行,由人决定跟不跟。 * 同 `(branch, prep)` 的旧 pending 单位行转 `superseded`(只留最新一条待审,与成本价事实同款纪律)。 * 幂等:他们同一 `request_id` / 同一 `client_request_id` 重投 ⇒ 命中唯一键 ⇒ `ignored`(重复投递)。 */ if (isUnitChangedReviewRequired()) { return registerUnitChangedPending({ branchCode, mapped, ourOrderCode: row.our_order_code }); } // ③ 回退路径:读我方当前单位(tenant 隔离:必须走 runWithTenantDataAccess) const current = await runWithTenantDataAccess(branchCode, (client) => client.query<{ unit: string | null }>( `SELECT unit FROM order_items WHERE order_code = $1 AND id = $2::uuid LIMIT 1`, [row.our_order_code, row.our_order_item_id] ) ); const currentRow = current.rows[0]; if (!currentRow) { return { status: 'ignored', reason: '我方订单行已不存在', rowId: null }; } if (sameUnit(currentRow.unit, mapped.finalUnit)) { return { status: 'ignored', reason: `我方单位已是 ${mapped.finalUnit}(幂等跳过)`, rowId: null, unit: mapped.finalUnit, }; } // ④ 只写 unit;价/量/状态/退货标记一律不动(`order_items` 无 updated_at 列) const updated = await runWithTenantDataAccess(branchCode, (client) => client.query<{ id: string }>( `UPDATE order_items SET unit = $3 WHERE order_code = $1 AND id = $2::uuid RETURNING id::text AS id`, [row.our_order_code, row.our_order_item_id, mapped.finalUnit] ) ); const rowId = updated.rows[0]?.id ?? null; // ④ 留痕(失败不阻断:日志属辅助面) try { const { writeAuditLog } = await import('./auditService'); await writeAuditLog({ operatorId: null, operatorRole: mapped.operatorRole || 'main_system', operationType: 'main_system_unit_changed_applied', targetTable: 'order_items', targetId: rowId ?? undefined, branchCode, actionCategory: 'order', ipAddress: null, oldValue: { unit: currentRow.unit ?? null }, newValue: { unit: mapped.finalUnit, before_unit: mapped.beforeUnit, prep_id: mapped.prepId, our_order_code: row.our_order_code, main_order_code: mapped.orderCode, sku_code: mapped.skuCode, source: mapped.source, operator: mapped.operator, changed_at: mapped.changedAt, client_request_id: mapped.clientRequestId, }, }); } catch (error: unknown) { console.error('[unit-changed] 写操作日志失败:', (error as Error)?.message || error); } return { status: 'applied', reason: `单位 ${currentRow.unit ?? '—'} → ${mapped.finalUnit}(主系统管理端改动,我方镜像)`, rowId, unit: mapped.finalUnit, }; }