feat(main-system): 消费 preparations.quantity_changed 同步订单计划数量
- webhook 消费:event_id+prep_id 幂等、revision 防乱序,业务失败 200 靠对账兜底 - 未出库:订单数量/金额/分拣 required_qty/库存抵扣差额/已分配备货/自采/结算同步 - 已出库/备货完成竞态/共享行缺订单行 id:不覆盖,落冲突台账 + 站内通知 - 定时对账兜底:mainSystemReturnFollow + 事件消费者 quantity_sync - 迁移两张台账表;新增 13 条单测
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
-- 主系统「计划数量变化」事件应用台账(2026-10-28)
|
||||
-- 用途:event_id+prep_id 幂等 / revision 防乱序 / 定时对账复用同一张表。
|
||||
BEGIN;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.main_system_quantity_event_applies (
|
||||
event_id UUID NOT NULL,
|
||||
prep_id UUID NOT NULL,
|
||||
branch_code VARCHAR(20) NOT NULL,
|
||||
main_order_code VARCHAR(64),
|
||||
our_order_code VARCHAR(64),
|
||||
revision INTEGER NOT NULL DEFAULT 0,
|
||||
sku_code VARCHAR(64),
|
||||
old_quantity NUMERIC(14,3),
|
||||
new_quantity NUMERIC(14,3),
|
||||
status VARCHAR(32) NOT NULL,
|
||||
detail JSONB,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
PRIMARY KEY (event_id, prep_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_quantity_event_applies_prep_revision
|
||||
ON public.main_system_quantity_event_applies (branch_code, prep_id, revision DESC);
|
||||
|
||||
COMMENT ON TABLE public.main_system_quantity_event_applies IS
|
||||
'主系统 preparations.quantity_changed 应用台账(event_id+prep_id 幂等 / revision 防乱序)';
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1,33 @@
|
||||
-- 主系统「计划数量变化」冲突/差异台账(2026-10-28)
|
||||
-- 已出库/已发车/备货完成竞态/已拣超量等场景不静默覆盖,落表交人工。
|
||||
BEGIN;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.main_system_quantity_conflicts (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
branch_code VARCHAR(20) NOT NULL,
|
||||
main_order_code VARCHAR(64),
|
||||
our_order_code VARCHAR(64),
|
||||
prep_id UUID,
|
||||
main_order_item_id UUID,
|
||||
our_order_item_id UUID,
|
||||
sku_code VARCHAR(64),
|
||||
item_name VARCHAR(255),
|
||||
old_quantity NUMERIC(14,3),
|
||||
new_quantity NUMERIC(14,3),
|
||||
target_quantity NUMERIC(14,3),
|
||||
reason VARCHAR(64) NOT NULL,
|
||||
detail JSONB,
|
||||
event_id UUID,
|
||||
revision INTEGER,
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'open',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
resolved_at TIMESTAMPTZ
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_quantity_conflicts_open
|
||||
ON public.main_system_quantity_conflicts (branch_code, status, created_at DESC);
|
||||
|
||||
COMMENT ON TABLE public.main_system_quantity_conflicts IS
|
||||
'主系统数量变化冲突/差异(已出库拒绝覆盖 / 备货完成竞态 / 已拣超量等),交人工处理';
|
||||
|
||||
COMMIT;
|
||||
@@ -264,6 +264,16 @@ function mapWebhookRow(raw: any): MainPreparationRow {
|
||||
isInbounded: raw?.is_inbounded === true,
|
||||
inboundAt: isoOrNull(raw?.inbound_at),
|
||||
orderDepartedAt: isoOrNull(raw?.order_departed_at),
|
||||
// 2026-10-28:数量变化只读兜底字段(主系统只读接口新增)
|
||||
updatedAt: isoOrNull(raw?.updated_at),
|
||||
mainOrderItemId:
|
||||
raw?.main_order_item_id != null && String(raw.main_order_item_id).trim()
|
||||
? String(raw.main_order_item_id).trim()
|
||||
: null,
|
||||
quantityRevision:
|
||||
raw?.quantity_revision === null || raw?.quantity_revision === undefined
|
||||
? null
|
||||
: Number(raw.quantity_revision) || 0,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -664,6 +674,30 @@ router.post('/main-system/webhook', async (req: Request, res: Response) => {
|
||||
return res.json({ ok: true, results });
|
||||
}
|
||||
|
||||
/* ── 主系统改计划数量(2026-10-28):`preparations.quantity_changed` ─────────────
|
||||
* 我方动作(见 services/mainSystemQuantityChange.ts):
|
||||
* · 未出库 ⇒ 更新订单数量/金额、分拣计划、库存抵扣差额、已分配备货/自采、结算;
|
||||
* · 已出库/备货完成竞态 ⇒ 不覆盖,落冲突台账 + 站内通知交人工;
|
||||
* · 按 event_id+prep_id 幂等、revision 防乱序;业务失败一律 200(重推解决不了,靠 15 分钟对账)。
|
||||
*/
|
||||
if (event === 'preparations.quantity_changed') {
|
||||
try {
|
||||
const { applyQuantityChangedPayload } = await import('../services/mainSystemQuantityChange');
|
||||
const handled = await applyQuantityChangedPayload({ branchCode, payload });
|
||||
const applied = handled.results.filter((r) => r.status === 'applied').length;
|
||||
const conflicts = handled.results.filter((r) => r.status === 'conflict').length;
|
||||
console.log(
|
||||
`[main-system-webhook] ${branchCode} ${event} revision=${handled.revision}:` +
|
||||
`应用 ${applied} / 冲突 ${conflicts} / 共 ${handled.results.length} 行`
|
||||
);
|
||||
return res.json({ ok: true, revision: handled.revision, results: handled.results });
|
||||
} catch (error) {
|
||||
// 事件已持久化;重推解决不了内部错误 ⇒ 200 + 记日志(对账兜底)
|
||||
console.error(`[main-system-webhook] ${branchCode} ${event} 处理失败(交对账):`, (error as Error)?.message || error);
|
||||
return res.json({ ok: true, failed: true });
|
||||
}
|
||||
}
|
||||
|
||||
if (isFulfillmentEvent(event)) {
|
||||
if (!isFulfillmentEventsEnabled()) {
|
||||
// 开关关闭 ⇒ 与改造前逐字节一致:200 收下但忽略
|
||||
|
||||
@@ -69,6 +69,12 @@ export type MainPreparationRow = {
|
||||
branchAddress: string | null;
|
||||
/** 主系统 2026-10-09 增量:该供应商是否免入库(**供应商级**事实) */
|
||||
skipInbound: boolean;
|
||||
/** 备货行最近更新时间(2026-10-28,供应商数量变化对账用;主系统只读接口新增) */
|
||||
updatedAt: string | null;
|
||||
/** 该备货行对应的主系统订单行 id(共享备货行时用于精确定位;确定一行) */
|
||||
mainOrderItemId: string | null;
|
||||
/** 主系统当前订单编辑 revision(数量事件幂等/对账用;缺省 null) */
|
||||
quantityRevision: number | null;
|
||||
/** 主系统 2026-10-09 增量:该行是否商品直送(**行级**事实);与 skipInbound 分别独立,禁止合并判定 */
|
||||
isDirectDelivery: boolean;
|
||||
// ── 主系统 2026-10-10 R3 履约事实(只读派生值,**不参与任何我方判定门槛**)──────────
|
||||
@@ -176,6 +182,15 @@ export function mapMainPreparationRow(raw: any): MainPreparationRow {
|
||||
isInbounded: raw?.is_inbounded === true,
|
||||
inboundAt: isoOrNull(raw?.inbound_at),
|
||||
orderDepartedAt: isoOrNull(raw?.order_departed_at),
|
||||
// 2026-10-28:数量变化只读兜底字段(主系统只读接口新增)
|
||||
updatedAt: isoOrNull(raw?.updated_at),
|
||||
mainOrderItemId: raw?.main_order_item_id != null && String(raw.main_order_item_id).trim()
|
||||
? String(raw.main_order_item_id).trim()
|
||||
: null,
|
||||
quantityRevision:
|
||||
raw?.quantity_revision === null || raw?.quantity_revision === undefined
|
||||
? null
|
||||
: Number(raw.quantity_revision) || 0,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -331,6 +331,7 @@ export function classifyEvent(event: Pick<MainSystemEvent, 'event' | 'orderCode'
|
||||
const name = trim(event.event).toLowerCase();
|
||||
if (name === 'binding.changed' || name.startsWith('binding.')) return 'binding_sync';
|
||||
if (name === 'preparations.allocated' || name === 'allocated') return 'targeted_pull';
|
||||
if (name === 'preparations.quantity_changed') return 'quantity_sync';
|
||||
if (
|
||||
name === 'preparations.returned' ||
|
||||
name === 'returned' ||
|
||||
@@ -364,6 +365,40 @@ async function dispatchEvent(input: {
|
||||
const orderCode = trim(event.orderCode);
|
||||
if (!orderCode) return 'ignored';
|
||||
|
||||
if (action === 'quantity_sync') {
|
||||
// 先定向拉这一单(导入幂等),再按只读接口最新 prepare_qty 做数量对账(事件丢失的兜底路径)
|
||||
const { importMainSystemOrders } = await import('./mainSystemOrderImport');
|
||||
const imported = await importMainSystemOrders({
|
||||
branchCode,
|
||||
userId: null,
|
||||
onlyMainOrderCodes: [orderCode],
|
||||
});
|
||||
if (imported.kind !== 'ok') {
|
||||
console.warn(
|
||||
`[main-system-events] ${branchCode} 数量事件定向导入 ${orderCode} 未成功(kind=${imported.kind}),交下轮对账`
|
||||
);
|
||||
return 'ignored';
|
||||
}
|
||||
const supplierCode = trim(event.supplierCode);
|
||||
if (supplierCode) {
|
||||
try {
|
||||
const { reconcileQuantityChangedForOrder } = await import('./mainSystemQuantityChange');
|
||||
const outcome = await runWithTenantDbContext(branchCode, () =>
|
||||
reconcileQuantityChangedForOrder({ branchCode, supplierCode, mainOrderCode: orderCode })
|
||||
);
|
||||
console.log(
|
||||
`[main-system-events] ${branchCode} 数量对账 ${orderCode}:${outcome.status} 应用 ${outcome.applied} / 跳过 ${outcome.skipped} / active ${outcome.rows}`
|
||||
);
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`[main-system-events] ${branchCode} 数量对账 ${orderCode} 失败(交下轮):`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
}
|
||||
}
|
||||
return 'applied';
|
||||
}
|
||||
|
||||
if (action === 'targeted_pull') {
|
||||
// 只拉这一单(主系统 ②:view=active&order_code=…),再走既有导入(幂等:同一单重复导入不会重复建行)
|
||||
const { importMainSystemOrders } = await import('./mainSystemOrderImport');
|
||||
|
||||
@@ -0,0 +1,756 @@
|
||||
import { randomUUID } from 'crypto';
|
||||
import { pool } from '../db';
|
||||
import { runWithTenantDataAccess } from './tenantSchemaService';
|
||||
import { loadCoverBatchLockState } from './orderItemCoverBatchesService';
|
||||
import { applyStockCoverForOrder } from './inventoryStockCoverService';
|
||||
import { recalcPreparationQty } from './orderItemFulfillmentService';
|
||||
import { syncOpenPurchaseQtyForOrder } from './orderAllocationService';
|
||||
import { syncStatementsForOrderSafe } from './financeReconciliationService';
|
||||
import { recalcOrderHeaderTotals } from './mainSystemStockout';
|
||||
import { updatePrepSnapshot } from './mainSystemPrepLedger';
|
||||
import { recordMainSystemImportFailure } from './mainSystemImportFailureService';
|
||||
import { notifyRoleUsers } from './notificationService';
|
||||
import { writeAuditLog } from './auditService';
|
||||
import { fetchActivePreparationsForOrder } from './mainSystemPreparations';
|
||||
import type { MainPreparationRow } from './mainSystem/api/preparations';
|
||||
|
||||
/**
|
||||
* 主系统「订单计划数量变化」消费(`preparations.quantity_changed`,2026-10-28)
|
||||
*
|
||||
* 背景:主系统改计划数量后只更新自己的 `prepare_qty`,供应商已有行命中 needsAppendToOrder=false
|
||||
* 不更新本地数量 ⇒ 主系统 30 / 供应商 25 长期不一致(分拣/采购/结算跟着旧值)。
|
||||
*
|
||||
* 本模块(供应商侧):
|
||||
* · webhook 事件消费:`applyQuantityChangedPayload`(按 event_id+prep_id 幂等 / revision 防乱序);
|
||||
* · 定时对账兜底:`reconcileQuantityChangedForOrder` 按只读接口 `prepare_qty` vs 台账快照发现漏发;
|
||||
* · 未出库:更新本地订单行数量/金额、分拣计划 required_qty、库存抵扣(差额)、
|
||||
* 已分配备货/自采数量、客户/供应商结算;缺口按 2026-10-13 既有裁决**留在未分配**交人工;
|
||||
* · 已出库/已发车/已拣超量/备货完成竞态:**不静默覆盖**,写 `main_system_quantity_conflicts` +
|
||||
* 复用 `main_system_import_failures` 告警(站内通知),可人工处理;
|
||||
* · 不新造传输通道:事件来自既有 webhook/签名/重试/kill switch;失败一律 200(重推解决不了,靠对账)。
|
||||
*/
|
||||
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
export type QuantityChangedRow = {
|
||||
prep_id?: string | null;
|
||||
main_order_item_id?: string | null;
|
||||
sku_code?: string | null;
|
||||
item_name?: string | null;
|
||||
unit?: string | null;
|
||||
old_quantity?: number | string | null;
|
||||
new_quantity?: number | string | null;
|
||||
prepare_status?: number | string | null;
|
||||
shared_prep?: boolean;
|
||||
prep_old_qty?: number | string | null;
|
||||
prep_new_qty?: number | string | null;
|
||||
order_code?: string | null;
|
||||
};
|
||||
|
||||
export type QuantityChangedStatus =
|
||||
| 'applied'
|
||||
| 'duplicate'
|
||||
| 'stale_revision'
|
||||
| 'ignored_unknown_prep'
|
||||
| 'ignored_ledger_terminal'
|
||||
| 'ignored_missing_item'
|
||||
| 'conflict'
|
||||
| 'failed'
|
||||
| 'invalid_payload';
|
||||
|
||||
export type QuantityChangedResult = {
|
||||
prepId: string;
|
||||
status: QuantityChangedStatus;
|
||||
reason?: string | null;
|
||||
ourOrderCode?: string | null;
|
||||
oldQuantity?: number | null;
|
||||
newQuantity?: number | null;
|
||||
note?: string | null;
|
||||
};
|
||||
|
||||
type LedgerRow = {
|
||||
prep_id: string;
|
||||
our_order_code: string | null;
|
||||
our_order_item_id: string | null;
|
||||
last_prepare_qty: string | number | null;
|
||||
last_prepare_status: number | null;
|
||||
disposition: string | null;
|
||||
payload: Record<string, unknown> | null;
|
||||
};
|
||||
|
||||
function trimText(value: unknown): string {
|
||||
return String(value ?? '').trim();
|
||||
}
|
||||
|
||||
function round3(value: unknown): number {
|
||||
const n = Number(value);
|
||||
return Number.isFinite(n) ? Math.round(n * 1000) / 1000 : 0;
|
||||
}
|
||||
|
||||
function round2(value: unknown): number {
|
||||
const n = Number(value);
|
||||
return Number.isFinite(n) ? Math.round(n * 100) / 100 : 0;
|
||||
}
|
||||
|
||||
class QuantityConflictError extends Error {
|
||||
reason: string;
|
||||
detail: Record<string, unknown>;
|
||||
constructor(reason: string, detail: Record<string, unknown> = {}) {
|
||||
super(reason);
|
||||
this.reason = reason;
|
||||
this.detail = detail;
|
||||
}
|
||||
}
|
||||
|
||||
async function setApplyStatus(input: {
|
||||
eventId: string;
|
||||
prepId: string;
|
||||
status: string;
|
||||
detail?: Record<string, unknown>;
|
||||
}): Promise<void> {
|
||||
try {
|
||||
await pool.query(
|
||||
`UPDATE public.main_system_quantity_event_applies
|
||||
SET status = $3, detail = $4::jsonb
|
||||
WHERE event_id = $1::uuid AND prep_id = $2::uuid`,
|
||||
[input.eventId, input.prepId, input.status, JSON.stringify(input.detail || {})]
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
'[main-system-quantity] 更新事件台账失败(不影响主流程):',
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** 冲突/差异留痕 + 可见告警(站内通知,1 小时内同类去重) */
|
||||
async function recordQuantityConflict(input: {
|
||||
branchCode: string;
|
||||
mainOrderCode: string | null;
|
||||
ourOrderCode: string | null;
|
||||
prepId: string | null;
|
||||
mainOrderItemId: string | null;
|
||||
ourOrderItemId: string | null;
|
||||
skuCode: string | null;
|
||||
itemName: string | null;
|
||||
oldQuantity: number | null;
|
||||
newQuantity: number | null;
|
||||
targetQuantity: number | null;
|
||||
reason: string;
|
||||
detail?: Record<string, unknown>;
|
||||
eventId: string | null;
|
||||
revision: number | null;
|
||||
severity?: 'conflict' | 'difference';
|
||||
}): Promise<void> {
|
||||
const severity = input.severity || 'conflict';
|
||||
try {
|
||||
await pool.query(
|
||||
`INSERT INTO public.main_system_quantity_conflicts
|
||||
(branch_code, main_order_code, our_order_code, prep_id, main_order_item_id, our_order_item_id,
|
||||
sku_code, item_name, old_quantity, new_quantity, target_quantity, reason, detail,
|
||||
event_id, revision, status)
|
||||
VALUES ($1,$2,$3,$4,$5::uuid,NULLIF($6,'')::uuid,$7,$8,$9,$10,$11,$12,$13::jsonb,$14::uuid,$15,$16)`,
|
||||
[
|
||||
input.branchCode,
|
||||
input.mainOrderCode,
|
||||
input.ourOrderCode,
|
||||
input.prepId && UUID_RE.test(input.prepId) ? input.prepId : null,
|
||||
input.mainOrderItemId && UUID_RE.test(input.mainOrderItemId) ? input.mainOrderItemId : null,
|
||||
input.ourOrderItemId || '',
|
||||
input.skuCode,
|
||||
input.itemName,
|
||||
input.oldQuantity,
|
||||
input.newQuantity,
|
||||
input.targetQuantity,
|
||||
input.reason,
|
||||
JSON.stringify(input.detail || {}),
|
||||
input.eventId && UUID_RE.test(input.eventId) ? input.eventId : null,
|
||||
input.revision,
|
||||
severity === 'difference' ? 'difference' : 'open',
|
||||
]
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
'[main-system-quantity] 写冲突台账失败(不影响主流程):',
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
}
|
||||
// 复用既有导入失败台账 + 站内通知(供应商系统已有的可见通道)
|
||||
try {
|
||||
const orderInfo = input.ourOrderCode
|
||||
? await pool
|
||||
.query(`SELECT delivery_date FROM orders WHERE order_code = $1 LIMIT 1`, [input.ourOrderCode])
|
||||
.catch(() => ({ rows: [] as Array<Record<string, any>> }))
|
||||
: { rows: [] as Array<Record<string, any>> };
|
||||
const deliveryDate =
|
||||
orderInfo.rows?.[0]?.delivery_date != null
|
||||
? new Date(orderInfo.rows[0].delivery_date).toISOString().slice(0, 10)
|
||||
: new Date().toISOString().slice(0, 10);
|
||||
const mainBranchCode = trimText(input.detail?.main_branch_code) || input.branchCode;
|
||||
await recordMainSystemImportFailure({
|
||||
branchCode: input.branchCode,
|
||||
deliveryDate,
|
||||
mainBranchCode,
|
||||
mainOrderCode: input.mainOrderCode,
|
||||
ourOrderCode: input.ourOrderCode,
|
||||
message: `主系统数量变化${severity === 'difference' ? '差异' : '冲突'}:${input.itemName || input.skuCode || (input.prepId || '')}(${input.reason})`,
|
||||
errorCode: `quantity_${severity}_${input.reason}`,
|
||||
});
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
try {
|
||||
await notifyRoleUsers({
|
||||
roles: ['admin', 'operator'],
|
||||
notifyType: 'main_system_quantity_conflict',
|
||||
title:
|
||||
severity === 'difference'
|
||||
? '主系统改量存在差异,请核对'
|
||||
: '主系统改量冲突,需人工处理',
|
||||
content:
|
||||
`订单 ${input.ourOrderCode || '-'} 商品 ${input.itemName || input.skuCode || input.prepId || '-'}:` +
|
||||
`主系统计划 ${input.oldQuantity ?? '-'} → ${input.newQuantity ?? '-'},原因 ${input.reason}。` +
|
||||
(severity === 'difference' ? '已同步订单数量并留差异。' : '已保留本地历史数量,未直接覆盖。'),
|
||||
relatedOrderCode: input.ourOrderCode,
|
||||
branchCode: input.branchCode,
|
||||
dedupWithinHours: 1,
|
||||
}).catch(() => undefined);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
async function loadLedgerRow(branchCode: string, prepId: string): Promise<LedgerRow | null> {
|
||||
const result = await pool.query(
|
||||
`SELECT prep_id::text AS prep_id, our_order_code, our_order_item_id::text AS our_order_item_id,
|
||||
last_prepare_qty, last_prepare_status, disposition, payload
|
||||
FROM public.main_system_order_import_items
|
||||
WHERE branch_code = $1 AND prep_id = $2::uuid
|
||||
LIMIT 1`,
|
||||
[branchCode, prepId]
|
||||
);
|
||||
return (result.rows?.[0] as LedgerRow) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用一条数量变化(webhook / 对账共用)。
|
||||
* 事务外先做幂等/revision;业务写入全部在 `runWithTenantDataAccess` 单事务内。
|
||||
*/
|
||||
export async function applyOneQuantityChange(input: {
|
||||
branchCode: string;
|
||||
eventId: string;
|
||||
revision: number;
|
||||
row: QuantityChangedRow;
|
||||
source: 'webhook' | 'reconcile';
|
||||
}): Promise<QuantityChangedResult> {
|
||||
const branchCode = trimText(input.branchCode);
|
||||
const eventId = trimText(input.eventId) || randomUUID();
|
||||
const revision = Number(input.revision) || 0;
|
||||
const prepId = trimText(input.row?.prep_id);
|
||||
if (!branchCode || !UUID_RE.test(prepId)) {
|
||||
return { prepId, status: 'invalid_payload', reason: 'missing_or_invalid_prep_id' };
|
||||
}
|
||||
|
||||
// ① 幂等:同 event_id+prep_id 只处理一次
|
||||
try {
|
||||
const inserted = await pool.query(
|
||||
`INSERT INTO public.main_system_quantity_event_applies
|
||||
(event_id, prep_id, branch_code, revision, sku_code, old_quantity, new_quantity, status)
|
||||
VALUES ($1::uuid,$2::uuid,$3,$4,$5,$6,$7,'processing')
|
||||
ON CONFLICT (event_id, prep_id) DO NOTHING
|
||||
RETURNING event_id`,
|
||||
[
|
||||
eventId,
|
||||
prepId,
|
||||
branchCode,
|
||||
revision,
|
||||
trimText(input.row.sku_code) || null,
|
||||
round3(input.row.old_quantity),
|
||||
round3(input.row.new_quantity),
|
||||
]
|
||||
);
|
||||
if (!inserted.rowCount) {
|
||||
return { prepId, status: 'duplicate' };
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
'[main-system-quantity] 事件台账写入失败(按失败处理,交对账):',
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
return { prepId, status: 'failed', reason: 'apply_ledger_write_failed' };
|
||||
}
|
||||
|
||||
// ② revision 防乱序:旧 revision 直接跳过
|
||||
if (revision > 0) {
|
||||
try {
|
||||
const prev = await pool.query(
|
||||
`SELECT COALESCE(MAX(revision), 0)::int AS max_revision
|
||||
FROM public.main_system_quantity_event_applies
|
||||
WHERE branch_code = $1 AND prep_id = $2::uuid
|
||||
AND status IN ('applied', 'conflict', 'skipped_stale')
|
||||
AND NOT (event_id = $3::uuid)`,
|
||||
[branchCode, prepId, eventId]
|
||||
);
|
||||
const maxRevision = Number(prev.rows?.[0]?.max_revision) || 0;
|
||||
if (maxRevision > 0 && revision <= maxRevision) {
|
||||
await setApplyStatus({ eventId, prepId, status: 'skipped_stale', detail: { maxRevision } });
|
||||
return { prepId, status: 'stale_revision', reason: `revision<=${maxRevision}` };
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[main-system-quantity] revision 校验失败(继续按事件处理):', error);
|
||||
}
|
||||
}
|
||||
|
||||
// ③ 台账定位
|
||||
const ledger = await loadLedgerRow(branchCode, prepId);
|
||||
if (!ledger) {
|
||||
await setApplyStatus({ eventId, prepId, status: 'ignored_unknown_prep' });
|
||||
try {
|
||||
await recordMainSystemImportFailure({
|
||||
branchCode,
|
||||
deliveryDate: new Date().toISOString().slice(0, 10),
|
||||
mainBranchCode: branchCode,
|
||||
mainOrderCode: input.row.order_code ? String(input.row.order_code) : null,
|
||||
ourOrderCode: null,
|
||||
message: `主系统数量变化事件找不到备货台账 prep=${prepId}(等导入/对账)`,
|
||||
errorCode: 'quantity_unknown_prep',
|
||||
});
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return { prepId, status: 'ignored_unknown_prep' };
|
||||
}
|
||||
if (['removed', 'returned', 'cancelled'].includes(String(ledger.disposition || ''))) {
|
||||
await setApplyStatus({ eventId, prepId, status: 'ignored_ledger_terminal', detail: { disposition: ledger.disposition } });
|
||||
return { prepId, status: 'ignored_ledger_terminal', ourOrderCode: ledger.our_order_code };
|
||||
}
|
||||
const ourOrderCode = trimText(ledger.our_order_code);
|
||||
const ourOrderItemId = trimText(ledger.our_order_item_id);
|
||||
if (!ourOrderCode || !UUID_RE.test(ourOrderItemId)) {
|
||||
await setApplyStatus({ eventId, prepId, status: 'ignored_missing_item' });
|
||||
return { prepId, status: 'ignored_missing_item', ourOrderCode };
|
||||
}
|
||||
|
||||
// ④ 目标数量:
|
||||
// · 非共享备货行:优先主系统备货聚合量(本地订单行按 prep 建,数量=聚合量);
|
||||
// · **共享备货行**:必须用订单行新量(聚合量会包含其它订单行),且必须带 main_order_item_id
|
||||
// —— 缺了就无法定位是哪一行,明确拒绝(不静默按聚合量覆盖)。
|
||||
const oldQuantity = round3(ledger.last_prepare_qty);
|
||||
const sharedPrep = input.row.shared_prep === true;
|
||||
const mainOrderItemId = trimText(input.row.main_order_item_id);
|
||||
if (sharedPrep && !UUID_RE.test(mainOrderItemId)) {
|
||||
await setApplyStatus({ eventId, prepId, status: 'conflict', detail: { reason: 'shared_prep_missing_main_item' } });
|
||||
await recordQuantityConflict({
|
||||
branchCode,
|
||||
mainOrderCode: ledger.payload?.main_order_code ? String(ledger.payload.main_order_code) : null,
|
||||
ourOrderCode: ourOrderCode || null,
|
||||
prepId,
|
||||
mainOrderItemId: mainOrderItemId || null,
|
||||
ourOrderItemId: ourOrderItemId || null,
|
||||
skuCode: trimText(input.row.sku_code) || null,
|
||||
itemName: trimText(input.row.item_name) || null,
|
||||
oldQuantity,
|
||||
newQuantity: round3(input.row.new_quantity),
|
||||
targetQuantity: null,
|
||||
reason: 'shared_prep_missing_main_item',
|
||||
detail: { shared_prep: true },
|
||||
eventId,
|
||||
revision,
|
||||
severity: 'conflict',
|
||||
});
|
||||
return { prepId, status: 'conflict', reason: 'shared_prep_missing_main_item', ourOrderCode };
|
||||
}
|
||||
const targetQuantity = round3(
|
||||
sharedPrep
|
||||
? input.row.new_quantity
|
||||
: input.row.prep_new_qty !== null && input.row.prep_new_qty !== undefined && Number(input.row.prep_new_qty) > 0
|
||||
? input.row.prep_new_qty
|
||||
: input.row.new_quantity
|
||||
);
|
||||
|
||||
try {
|
||||
const outcome = await runWithTenantDataAccess(branchCode, async (client) => {
|
||||
const orderResult = await client.query(
|
||||
`SELECT order_code, order_status, delivery_date, branch_code
|
||||
FROM orders WHERE order_code = $1 FOR UPDATE`,
|
||||
[ourOrderCode]
|
||||
);
|
||||
if (!orderResult.rowCount) throw new QuantityConflictError('order_not_found');
|
||||
const order = orderResult.rows[0] as Record<string, any>;
|
||||
const orderStatus = Number(order.order_status) || 0;
|
||||
|
||||
const itemResult = await client.query(
|
||||
`SELECT id::text AS id, quantity::float AS quantity, ordered_quantity::float AS ordered_quantity,
|
||||
price::float AS price, amount::float AS amount, sku_code, item_name, unit,
|
||||
COALESCE(stock_cover_qty, 0)::float AS stock_cover_qty
|
||||
FROM order_items
|
||||
WHERE id = $1::uuid AND order_code = $2`,
|
||||
[ourOrderItemId, ourOrderCode]
|
||||
);
|
||||
if (!itemResult.rowCount) throw new QuantityConflictError('item_missing');
|
||||
const item = itemResult.rows[0] as Record<string, any>;
|
||||
|
||||
// 已出库/已发车 ⇒ 不覆盖历史数量,转差异
|
||||
const lock = await loadCoverBatchLockState(client as any, {
|
||||
orderCode: ourOrderCode,
|
||||
itemId: ourOrderItemId,
|
||||
skuCode: item.sku_code != null ? String(item.sku_code) : trimText(input.row.sku_code) || null,
|
||||
orderStatus,
|
||||
});
|
||||
if (lock.locked) throw new QuantityConflictError(lock.reason || 'outbound_locked');
|
||||
|
||||
// 备货完成竞态(事件早于完成、到达时已完成)⇒ 不静默覆盖
|
||||
if (Number(ledger.last_prepare_status || 0) >= 30) {
|
||||
throw new QuantityConflictError('prep_completed_race');
|
||||
}
|
||||
if (!(targetQuantity > 0)) throw new QuantityConflictError('invalid_quantity');
|
||||
|
||||
const beforeQty = Number(item.quantity) || 0;
|
||||
const beforeCover = Number(item.stock_cover_qty) || 0;
|
||||
const price = Number(item.price) || 0;
|
||||
const nextAmount = round2(targetQuantity * price);
|
||||
|
||||
const pickResult = await client.query(
|
||||
`SELECT COUNT(*)::int AS rows, COALESCE(MAX(picked_qty), 0)::float AS picked_qty
|
||||
FROM picking_items WHERE order_item_id = $1::uuid`,
|
||||
[ourOrderItemId]
|
||||
);
|
||||
const pickingRows = Number(pickResult.rows?.[0]?.rows) || 0;
|
||||
const pickedQty = Number(pickResult.rows?.[0]?.picked_qty) || 0;
|
||||
|
||||
await client.query(
|
||||
`UPDATE order_items
|
||||
SET quantity = $2, ordered_quantity = $2, amount = $3
|
||||
WHERE id = $1::uuid`,
|
||||
[ourOrderItemId, targetQuantity, nextAmount]
|
||||
);
|
||||
// 分拣计划跟随;已出库行不动(前面已拦),已拣数量不被覆盖
|
||||
await client.query(
|
||||
`UPDATE picking_items
|
||||
SET required_qty = $2
|
||||
WHERE order_item_id = $1::uuid
|
||||
AND outbound_at IS NULL`,
|
||||
[ourOrderItemId, targetQuantity]
|
||||
);
|
||||
|
||||
// 库存抵扣按差额重算(已拣/已入库行由既有守卫保持原值 → 下面记录差异)
|
||||
await applyStockCoverForOrder(ourOrderCode, String(order.branch_code || branchCode), client);
|
||||
|
||||
// 已分配备货/未完成自采数量跟随(缺口保持未分配,交人工;不跑分配规则)
|
||||
await recalcPreparationQty(client, ourOrderCode);
|
||||
await syncOpenPurchaseQtyForOrder(client, ourOrderCode);
|
||||
|
||||
// 金额/结算投影同步(客户 + 供应商;内部失败已 catch)
|
||||
await syncStatementsForOrderSafe(ourOrderCode, client);
|
||||
|
||||
const afterItem = await client.query(
|
||||
`SELECT COALESCE(stock_cover_qty, 0)::float AS cover FROM order_items WHERE id = $1::uuid`,
|
||||
[ourOrderItemId]
|
||||
);
|
||||
|
||||
return {
|
||||
beforeQty,
|
||||
beforeCover,
|
||||
afterCover: Number(afterItem.rows?.[0]?.cover) || 0,
|
||||
targetQuantity,
|
||||
pickingRows,
|
||||
pickedQty,
|
||||
orderStatus,
|
||||
};
|
||||
});
|
||||
|
||||
await setApplyStatus({
|
||||
eventId,
|
||||
prepId,
|
||||
status: 'applied',
|
||||
detail: {
|
||||
our_order_code: ourOrderCode,
|
||||
our_order_item_id: ourOrderItemId,
|
||||
before_quantity: outcome.beforeQty,
|
||||
target_quantity: outcome.targetQuantity,
|
||||
cover_before: outcome.beforeCover,
|
||||
cover_after: outcome.afterCover,
|
||||
picked_qty: outcome.pickedQty,
|
||||
source: input.source,
|
||||
},
|
||||
});
|
||||
|
||||
// 对账兜底要用的台账快照:主系统 prepare_qty/status 最新值
|
||||
try {
|
||||
await updatePrepSnapshot({
|
||||
branchCode,
|
||||
prepId,
|
||||
prepareQty:
|
||||
input.row.prep_new_qty !== null && input.row.prep_new_qty !== undefined
|
||||
? Number(input.row.prep_new_qty)
|
||||
: Number(input.row.new_quantity),
|
||||
prepareStatus:
|
||||
input.row.prepare_status === null || input.row.prepare_status === undefined
|
||||
? ledger.last_prepare_status
|
||||
: Number(input.row.prepare_status),
|
||||
returnCode: null,
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn('[main-system-quantity] 更新台账快照失败(不影响本地落值):', (error as Error)?.message || error);
|
||||
}
|
||||
|
||||
// 订单头合计重算(事件路径既有教训:只改行不改头,列表金额旧)
|
||||
try {
|
||||
await recalcOrderHeaderTotals({ branchCode, orderCode: ourOrderCode });
|
||||
} catch (error) {
|
||||
console.error('[main-system-quantity] 订单头重算失败(不影响数量结果):', (error as Error)?.message || error);
|
||||
}
|
||||
|
||||
try {
|
||||
await writeAuditLog({
|
||||
operatorRole: 'main_system_event',
|
||||
operationType: 'main_system_quantity_changed',
|
||||
targetTable: 'order_items',
|
||||
targetId: ourOrderItemId,
|
||||
oldValue: {
|
||||
order_code: ourOrderCode,
|
||||
prep_id: prepId,
|
||||
quantity: outcome.beforeQty,
|
||||
stock_cover_qty: outcome.beforeCover,
|
||||
},
|
||||
newValue: {
|
||||
quantity: outcome.targetQuantity,
|
||||
stock_cover_qty: outcome.afterCover,
|
||||
event_id: eventId,
|
||||
revision,
|
||||
source: input.source,
|
||||
},
|
||||
branchCode,
|
||||
actionCategory: 'order',
|
||||
});
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
|
||||
// 差异:已拣数量 > 新数量(不覆盖已拣历史,交人工)
|
||||
if (outcome.pickedQty > outcome.targetQuantity + 1e-9) {
|
||||
await recordQuantityConflict({
|
||||
branchCode,
|
||||
mainOrderCode: ledger.payload?.main_order_code ? String(ledger.payload.main_order_code) : null,
|
||||
ourOrderCode,
|
||||
prepId,
|
||||
mainOrderItemId: trimText(input.row.main_order_item_id) || null,
|
||||
ourOrderItemId,
|
||||
skuCode: trimText(input.row.sku_code) || null,
|
||||
itemName: trimText(input.row.item_name) || null,
|
||||
oldQuantity: outcome.beforeQty,
|
||||
newQuantity: outcome.targetQuantity,
|
||||
targetQuantity: outcome.targetQuantity,
|
||||
reason: 'picked_qty_exceeds_new',
|
||||
detail: { picked_qty: outcome.pickedQty, stock_cover_before: outcome.beforeCover, stock_cover_after: outcome.afterCover },
|
||||
eventId,
|
||||
revision,
|
||||
severity: 'difference',
|
||||
});
|
||||
} else if (
|
||||
input.row.shared_prep !== true &&
|
||||
// 仅当「原本有抵扣量、却因已拣/已入库守卫没能按新量调整」才算差异;
|
||||
// 本就没有可抵扣库存(cover=0)时数量变化不构成差异,避免噪声告警。
|
||||
outcome.beforeCover > 1e-9 &&
|
||||
Math.abs(outcome.afterCover - outcome.beforeCover) < 1e-9 &&
|
||||
Math.abs(outcome.targetQuantity - outcome.beforeQty) > 1e-9 &&
|
||||
outcome.pickingRows > 0
|
||||
) {
|
||||
// 已拣进行中:抵扣按既有守卫保持原值 ⇒ 留差异
|
||||
await recordQuantityConflict({
|
||||
branchCode,
|
||||
mainOrderCode: ledger.payload?.main_order_code ? String(ledger.payload.main_order_code) : null,
|
||||
ourOrderCode,
|
||||
prepId,
|
||||
mainOrderItemId: trimText(input.row.main_order_item_id) || null,
|
||||
ourOrderItemId,
|
||||
skuCode: trimText(input.row.sku_code) || null,
|
||||
itemName: trimText(input.row.item_name) || null,
|
||||
oldQuantity: outcome.beforeQty,
|
||||
newQuantity: outcome.targetQuantity,
|
||||
targetQuantity: outcome.targetQuantity,
|
||||
reason: 'cover_locked_picking',
|
||||
detail: { stock_cover_before: outcome.beforeCover, stock_cover_after: outcome.afterCover, picking_rows: outcome.pickingRows },
|
||||
eventId,
|
||||
revision,
|
||||
severity: 'difference',
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
prepId,
|
||||
status: 'applied',
|
||||
ourOrderCode,
|
||||
oldQuantity,
|
||||
newQuantity: targetQuantity,
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof QuantityConflictError) {
|
||||
await setApplyStatus({ eventId, prepId, status: 'conflict', detail: { reason: error.reason, ...error.detail } });
|
||||
await recordQuantityConflict({
|
||||
branchCode,
|
||||
mainOrderCode: ledger.payload?.main_order_code ? String(ledger.payload.main_order_code) : null,
|
||||
ourOrderCode: ourOrderCode || null,
|
||||
prepId,
|
||||
mainOrderItemId: trimText(input.row.main_order_item_id) || null,
|
||||
ourOrderItemId: ourOrderItemId || null,
|
||||
skuCode: trimText(input.row.sku_code) || null,
|
||||
itemName: trimText(input.row.item_name) || null,
|
||||
oldQuantity,
|
||||
newQuantity: targetQuantity,
|
||||
targetQuantity,
|
||||
reason: error.reason,
|
||||
detail: error.detail,
|
||||
eventId,
|
||||
revision,
|
||||
severity: 'conflict',
|
||||
});
|
||||
// 冲突已留痕交人工;同步台账快照避免 15 分钟对账反复告警(人工处理后如需重放可手动重推事件)
|
||||
try {
|
||||
await updatePrepSnapshot({
|
||||
branchCode,
|
||||
prepId,
|
||||
prepareQty:
|
||||
input.row.prep_new_qty !== null && input.row.prep_new_qty !== undefined
|
||||
? Number(input.row.prep_new_qty)
|
||||
: Number(input.row.new_quantity),
|
||||
prepareStatus:
|
||||
input.row.prepare_status === null || input.row.prepare_status === undefined
|
||||
? ledger.last_prepare_status
|
||||
: Number(input.row.prepare_status),
|
||||
returnCode: null,
|
||||
});
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return { prepId, status: 'conflict', reason: error.reason, ourOrderCode };
|
||||
}
|
||||
await setApplyStatus({
|
||||
eventId,
|
||||
prepId,
|
||||
status: 'failed',
|
||||
detail: { message: (error as Error)?.message || String(error) },
|
||||
});
|
||||
try {
|
||||
await recordMainSystemImportFailure({
|
||||
branchCode,
|
||||
deliveryDate: new Date().toISOString().slice(0, 10),
|
||||
mainBranchCode: branchCode,
|
||||
mainOrderCode: ledger.payload?.main_order_code ? String(ledger.payload.main_order_code) : null,
|
||||
ourOrderCode: ourOrderCode || null,
|
||||
message: `主系统数量变化落值失败:${(error as Error)?.message || error}`,
|
||||
errorCode: 'quantity_apply_failed',
|
||||
});
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
console.error(
|
||||
`[main-system-quantity] ${branchCode} ${ourOrderCode || ''} prep=${prepId} 数量变化落值失败:`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
return { prepId, status: 'failed', reason: (error as Error)?.message || 'apply_failed', ourOrderCode };
|
||||
}
|
||||
}
|
||||
|
||||
/** webhook 入口:`data[]` 或 `items[]` 都接受;一条订单事件可带多行 */
|
||||
export async function applyQuantityChangedPayload(input: {
|
||||
branchCode: string;
|
||||
payload: Record<string, any> | null | undefined;
|
||||
}): Promise<{ results: QuantityChangedResult[]; revision: number }> {
|
||||
const branchCode = trimText(input.branchCode);
|
||||
const payload = (input.payload || {}) as Record<string, any>;
|
||||
const rows: QuantityChangedRow[] = Array.isArray(payload.data)
|
||||
? (payload.data as QuantityChangedRow[])
|
||||
: Array.isArray(payload.items)
|
||||
? (payload.items as QuantityChangedRow[])
|
||||
: payload.prep_id
|
||||
? [payload as QuantityChangedRow]
|
||||
: [];
|
||||
const revision = Number(payload.revision) || 0;
|
||||
const eventId = trimText(payload.event_id) || trimText(payload.request_id) || randomUUID();
|
||||
const results: QuantityChangedResult[] = [];
|
||||
for (const row of rows) {
|
||||
try {
|
||||
const result = await applyOneQuantityChange({ branchCode, eventId, revision, row, source: 'webhook' });
|
||||
results.push(result);
|
||||
} catch (error) {
|
||||
results.push({
|
||||
prepId: trimText(row?.prep_id),
|
||||
status: 'failed',
|
||||
reason: (error as Error)?.message || 'unexpected',
|
||||
});
|
||||
}
|
||||
}
|
||||
return { results, revision };
|
||||
}
|
||||
|
||||
/**
|
||||
* 定时对账兜底:按主系统只读接口最新 `prepare_qty` 与本地台账快照比较,
|
||||
* 发现「事件丢失/延迟」的数量变化后走同一应用逻辑(event_id 合成、revision 用只读字段)。
|
||||
*/
|
||||
export async function reconcileQuantityChangedForOrder(input: {
|
||||
branchCode: string;
|
||||
supplierCode: string;
|
||||
mainOrderCode: string;
|
||||
}): Promise<{ status: string; applied: number; skipped: number; rows: number }> {
|
||||
const branchCode = trimText(input.branchCode);
|
||||
const supplierCode = trimText(input.supplierCode);
|
||||
const mainOrderCode = trimText(input.mainOrderCode);
|
||||
if (!branchCode || !supplierCode || !mainOrderCode) return { status: 'invalid', applied: 0, skipped: 0, rows: 0 };
|
||||
const outcome = await fetchActivePreparationsForOrder({ supplierCode, orderCode: mainOrderCode });
|
||||
if (outcome.kind !== 'ok') {
|
||||
return { status: outcome.kind, applied: 0, skipped: 0, rows: 0 };
|
||||
}
|
||||
const activeRows: MainPreparationRow[] = (outcome.orders || []).flatMap((group) => group.rows || []);
|
||||
if (!activeRows.length) return { status: 'ok', applied: 0, skipped: 0, rows: 0 };
|
||||
|
||||
const ledgerResult = await pool.query(
|
||||
`SELECT prep_id::text AS prep_id, last_prepare_qty, last_prepare_status
|
||||
FROM public.main_system_order_import_items
|
||||
WHERE branch_code = $1 AND main_order_code = $2`,
|
||||
[branchCode, mainOrderCode]
|
||||
);
|
||||
const ledgerByPrep = new Map<string, { last_prepare_qty: string | number | null; last_prepare_status: number | null }>();
|
||||
for (const row of ledgerResult.rows || []) {
|
||||
ledgerByPrep.set(trimText(row.prep_id), {
|
||||
last_prepare_qty: row.last_prepare_qty,
|
||||
last_prepare_status: row.last_prepare_status,
|
||||
});
|
||||
}
|
||||
|
||||
let applied = 0;
|
||||
let skipped = 0;
|
||||
for (const row of activeRows) {
|
||||
const prepId = trimText(row.id);
|
||||
const ledger = ledgerByPrep.get(prepId);
|
||||
if (!ledger) continue;
|
||||
const oldQty = round3(ledger.last_prepare_qty);
|
||||
const newQty = round3(row.prepareQty);
|
||||
if (!(newQty > 0) || Math.abs(newQty - oldQty) < 1e-6) continue;
|
||||
const result = await applyOneQuantityChange({
|
||||
branchCode,
|
||||
eventId: randomUUID(),
|
||||
revision: Number(row.quantityRevision) || 0,
|
||||
source: 'reconcile',
|
||||
row: {
|
||||
prep_id: prepId,
|
||||
main_order_item_id: row.mainOrderItemId || null,
|
||||
sku_code: row.skuCode,
|
||||
item_name: row.itemName,
|
||||
unit: row.unit,
|
||||
old_quantity: oldQty,
|
||||
new_quantity: newQty,
|
||||
prepare_status: row.prepareStatus,
|
||||
prep_old_qty: oldQty,
|
||||
prep_new_qty: row.prepareQty,
|
||||
order_code: mainOrderCode,
|
||||
},
|
||||
});
|
||||
if (result.status === 'applied') applied += 1;
|
||||
else {
|
||||
skipped += 1;
|
||||
if (result.status === 'conflict' || result.status === 'failed') break;
|
||||
}
|
||||
}
|
||||
return { status: 'ok', applied, skipped, rows: activeRows.length };
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { randomUUID } from 'crypto';
|
||||
import { config } from '../config';
|
||||
import { pool } from '../db';
|
||||
import {
|
||||
@@ -463,6 +464,47 @@ async function followMainSystemPrepChangesLocked(
|
||||
);
|
||||
}
|
||||
if (qtyChanged || statusChanged || returnAppeared) {
|
||||
/**
|
||||
* 2026-10-28:数量变化不再只更新台账快照 —— 走统一应用逻辑:
|
||||
* 未出库 ⇒ 本地订单数量/金额、分拣计划、库存抵扣差额、已分配备货/自采、结算跟随;
|
||||
* 已出库/备货完成竞态 ⇒ 不覆盖,落冲突台账 + 站内通知。
|
||||
* 事件可能延迟/丢失,因此这条 15 分钟对账必须也能补。
|
||||
*/
|
||||
if (qtyChanged && existing.our_order_item_id && Number(row.prepareQty) > 0) {
|
||||
try {
|
||||
const { applyOneQuantityChange } = await import('./mainSystemQuantityChange');
|
||||
const applied = await applyOneQuantityChange({
|
||||
branchCode,
|
||||
eventId: randomUUID(),
|
||||
revision: Number(row.quantityRevision) || 0,
|
||||
source: 'reconcile',
|
||||
row: {
|
||||
prep_id: String(row.id),
|
||||
main_order_item_id: row.mainOrderItemId || null,
|
||||
sku_code: row.skuCode,
|
||||
item_name: row.itemName,
|
||||
unit: row.unit,
|
||||
old_quantity: Number(existing.last_prepare_qty) || 0,
|
||||
new_quantity: Number(row.prepareQty) || 0,
|
||||
prepare_status: row.prepareStatus,
|
||||
prep_old_qty: Number(existing.last_prepare_qty) || 0,
|
||||
prep_new_qty: Number(row.prepareQty) || 0,
|
||||
order_code: String(existing.main_order_code || ''),
|
||||
},
|
||||
});
|
||||
if (applied.status !== 'applied') {
|
||||
console.warn(
|
||||
`[main-system-return] ${branchCode} 备货行 ${row.id}(${row.itemName})数量对账未落值:${applied.status}` +
|
||||
`${applied.reason ? ` — ${applied.reason}` : ''}`
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`[main-system-return] ${branchCode} 备货行 ${row.id} 数量对账落值失败(不影响退货判定):`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
}
|
||||
}
|
||||
await updatePrepSnapshot({
|
||||
branchCode,
|
||||
prepId: String(row.id),
|
||||
|
||||
@@ -0,0 +1,529 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
/**
|
||||
* 供应商侧:主系统 `preparations.quantity_changed` 消费(2026-10-28)
|
||||
*
|
||||
* 验收要点:
|
||||
* · 未出库:更新本地订单数量/金额、分拣计划 required_qty、库存抵扣(差额)、
|
||||
* 已分配备货/自采数量、客户/供应商结算;
|
||||
* · 已出库/发车/备货完成竞态:不静默覆盖,落冲突台账 + 站内通知;
|
||||
* · event_id+prep_id 幂等、revision 防乱序;事件丢失由定时对账补(reconcile)。
|
||||
*/
|
||||
|
||||
const poolQuery = vi.hoisted(() => vi.fn());
|
||||
vi.mock('../src/db', () => ({
|
||||
pool: { query: (...args: unknown[]) => poolQuery(...args), connect: vi.fn() },
|
||||
query: (...args: unknown[]) => poolQuery(...args),
|
||||
getRawPoolQuery: () => poolQuery,
|
||||
getRawPoolConnect: () => vi.fn(),
|
||||
acquireTenantSessionClient: vi.fn(),
|
||||
releaseTenantSessionClient: vi.fn(),
|
||||
attachSerializedQuery: (c: unknown) => c,
|
||||
isRlsRoleAvailable: async () => false,
|
||||
warmRlsRoleCache: async () => undefined,
|
||||
allowRlsFailOpen: () => true,
|
||||
runWithBranchRls: async (_code: string, fn: () => Promise<unknown>) => fn(),
|
||||
applyBranchRlsToClient: async () => true,
|
||||
}));
|
||||
|
||||
const tenantRun = vi.hoisted(() => vi.fn());
|
||||
vi.mock('../src/services/tenantSchemaService', () => ({
|
||||
runWithTenantDataAccess: (code: string, fn: (client: unknown) => Promise<unknown>) =>
|
||||
tenantRun(code, fn),
|
||||
}));
|
||||
|
||||
const lockState = vi.hoisted(() => vi.fn());
|
||||
vi.mock('../src/services/orderItemCoverBatchesService', () => ({
|
||||
loadCoverBatchLockState: (...args: unknown[]) => lockState(...args),
|
||||
}));
|
||||
|
||||
const applyCover = vi.hoisted(() => vi.fn());
|
||||
vi.mock('../src/services/inventoryStockCoverService', () => ({
|
||||
applyStockCoverForOrder: (...args: unknown[]) => applyCover(...args),
|
||||
}));
|
||||
|
||||
const recalcPrep = vi.hoisted(() => vi.fn());
|
||||
vi.mock('../src/services/orderItemFulfillmentService', () => ({
|
||||
recalcPreparationQty: (...args: unknown[]) => recalcPrep(...args),
|
||||
}));
|
||||
|
||||
const syncOpenPurchase = vi.hoisted(() => vi.fn());
|
||||
vi.mock('../src/services/orderAllocationService', () => ({
|
||||
syncOpenPurchaseQtyForOrder: (...args: unknown[]) => syncOpenPurchase(...args),
|
||||
}));
|
||||
|
||||
const syncStatements = vi.hoisted(() => vi.fn());
|
||||
vi.mock('../src/services/financeReconciliationService', () => ({
|
||||
syncStatementsForOrderSafe: (...args: unknown[]) => syncStatements(...args),
|
||||
}));
|
||||
|
||||
const recalcHeader = vi.hoisted(() => vi.fn());
|
||||
vi.mock('../src/services/mainSystemStockout', () => ({
|
||||
recalcOrderHeaderTotals: (...args: unknown[]) => recalcHeader(...args),
|
||||
}));
|
||||
|
||||
const updateSnapshot = vi.hoisted(() => vi.fn());
|
||||
vi.mock('../src/services/mainSystemPrepLedger', () => ({
|
||||
updatePrepSnapshot: (...args: unknown[]) => updateSnapshot(...args),
|
||||
}));
|
||||
|
||||
const recordFailure = vi.hoisted(() => vi.fn());
|
||||
vi.mock('../src/services/mainSystemImportFailureService', () => ({
|
||||
recordMainSystemImportFailure: (...args: unknown[]) => recordFailure(...args),
|
||||
}));
|
||||
|
||||
const notifyRoleUsers = vi.hoisted(() => vi.fn());
|
||||
vi.mock('../src/services/notificationService', () => ({
|
||||
notifyRoleUsers: (...args: unknown[]) => notifyRoleUsers(...args),
|
||||
}));
|
||||
|
||||
const auditLog = vi.hoisted(() => vi.fn());
|
||||
vi.mock('../src/services/auditService', () => ({
|
||||
writeAuditLog: (...args: unknown[]) => auditLog(...args),
|
||||
}));
|
||||
|
||||
const fetchActive = vi.hoisted(() => vi.fn());
|
||||
vi.mock('../src/services/mainSystemPreparations', () => ({
|
||||
fetchActivePreparationsForOrder: (...args: unknown[]) => fetchActive(...args),
|
||||
}));
|
||||
|
||||
const {
|
||||
applyOneQuantityChange,
|
||||
applyQuantityChangedPayload,
|
||||
reconcileQuantityChangedForOrder,
|
||||
} = await import('../src/services/mainSystemQuantityChange');
|
||||
const { classifyEvent } = await import('../src/services/mainSystemEventConsumer');
|
||||
|
||||
const read = (rel: string) => readFileSync(path.join(__dirname, '..', rel), 'utf8');
|
||||
|
||||
const PREP_ID = '036d60e9-1e31-434e-86f4-e0870909d652';
|
||||
const ITEM_ID = 'd494daef-2282-420d-80cf-da3b71681586';
|
||||
const OUR_ORDER = 'ORD_API_20261028_BR002_0001';
|
||||
const MAIN_ORDER = 'ORD_WEB_20261028_BR002_0001';
|
||||
|
||||
type ClientResult = { rows: Array<Record<string, any>>; rowCount: number };
|
||||
|
||||
function makeFakeClient(handler: (text: string, params?: unknown[]) => ClientResult) {
|
||||
const calls: Array<{ text: string; params?: unknown[] }> = [];
|
||||
const client = {
|
||||
query: vi.fn(async (text: string, params?: unknown[]) => {
|
||||
calls.push({ text, params });
|
||||
return handler(text, params);
|
||||
}),
|
||||
};
|
||||
return { client, calls };
|
||||
}
|
||||
|
||||
function ledgerRow(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
prep_id: PREP_ID,
|
||||
our_order_code: OUR_ORDER,
|
||||
our_order_item_id: ITEM_ID,
|
||||
last_prepare_qty: '25',
|
||||
last_prepare_status: 10,
|
||||
disposition: 'imported',
|
||||
payload: { main_order_code: MAIN_ORDER },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
poolQuery.mockReset();
|
||||
tenantRun.mockReset();
|
||||
lockState.mockReset();
|
||||
lockState.mockResolvedValue({ locked: false, reason: null });
|
||||
applyCover.mockReset();
|
||||
applyCover.mockResolvedValue({ itemCount: 1, coveredQty: 30 });
|
||||
recalcPrep.mockReset();
|
||||
recalcPrep.mockResolvedValue({ qtyUpdated: 1, completedOrphans: 0 });
|
||||
syncOpenPurchase.mockReset();
|
||||
syncOpenPurchase.mockResolvedValue(undefined);
|
||||
syncStatements.mockReset();
|
||||
syncStatements.mockResolvedValue(undefined);
|
||||
recalcHeader.mockReset();
|
||||
recalcHeader.mockResolvedValue(undefined);
|
||||
updateSnapshot.mockReset();
|
||||
updateSnapshot.mockResolvedValue(undefined);
|
||||
recordFailure.mockReset();
|
||||
recordFailure.mockResolvedValue({ attempts: 1, isFirst: true });
|
||||
notifyRoleUsers.mockReset();
|
||||
notifyRoleUsers.mockResolvedValue(true);
|
||||
auditLog.mockReset();
|
||||
auditLog.mockResolvedValue(undefined);
|
||||
fetchActive.mockReset();
|
||||
});
|
||||
|
||||
describe('未出库应用(applied)', () => {
|
||||
it('25→30:更新订单数量/金额、分拣 required_qty、抵扣/备货/自采/结算同步', async () => {
|
||||
const { client, calls } = makeFakeClient((text) => {
|
||||
if (text.includes('FROM orders') && text.includes('FOR UPDATE')) {
|
||||
return { rows: [{ order_code: OUR_ORDER, order_status: 30, delivery_date: '2026-10-28', branch_code: 'BR002' }], rowCount: 1 };
|
||||
}
|
||||
if (text.includes('FROM order_items') && text.includes('WHERE id = $1::uuid AND order_code = $2')) {
|
||||
return {
|
||||
rows: [{ id: ITEM_ID, quantity: 25, ordered_quantity: 25, price: 12, amount: 300, sku_code: 'SKU78659582524', item_name: '二刀肉', unit: '斤', stock_cover_qty: 0 }],
|
||||
rowCount: 1,
|
||||
};
|
||||
}
|
||||
if (text.includes('FROM picking_items') && text.includes('MAX(picked_qty)')) {
|
||||
return { rows: [{ rows: 1, picked_qty: 0 }], rowCount: 1 };
|
||||
}
|
||||
if (text.includes('UPDATE order_items')) return { rows: [], rowCount: 1 };
|
||||
if (text.includes('UPDATE picking_items')) return { rows: [], rowCount: 1 };
|
||||
if (text.includes('SELECT COALESCE(stock_cover_qty')) return { rows: [{ cover: 30 }], rowCount: 1 };
|
||||
return { rows: [], rowCount: 0 };
|
||||
});
|
||||
tenantRun.mockImplementation(async (_code: string, fn: (c: unknown) => Promise<unknown>) => fn(client));
|
||||
poolQuery.mockImplementation(async (text: string) => {
|
||||
if (text.includes('INSERT INTO public.main_system_quantity_event_applies')) {
|
||||
return { rows: [{ event_id: 'evt-1' }], rowCount: 1 };
|
||||
}
|
||||
if (text.includes('MAX(revision)')) return { rows: [{ max_revision: 0 }], rowCount: 1 };
|
||||
if (text.includes('FROM public.main_system_order_import_items')) return { rows: [ledgerRow()], rowCount: 1 };
|
||||
return { rows: [], rowCount: 0 };
|
||||
});
|
||||
|
||||
const result = await applyOneQuantityChange({
|
||||
branchCode: 'BR002',
|
||||
eventId: '11111111-1111-4111-8111-111111111111',
|
||||
revision: 4,
|
||||
source: 'webhook',
|
||||
row: {
|
||||
prep_id: PREP_ID,
|
||||
main_order_item_id: ITEM_ID,
|
||||
sku_code: 'SKU78659582524',
|
||||
item_name: '二刀肉',
|
||||
unit: '斤',
|
||||
old_quantity: 25,
|
||||
new_quantity: 30,
|
||||
prep_old_qty: 25,
|
||||
prep_new_qty: 30,
|
||||
prepare_status: 10,
|
||||
order_code: MAIN_ORDER,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.status).toBe('applied');
|
||||
const orderUpdate = calls.find((c) => c.text.includes('UPDATE order_items'));
|
||||
expect(orderUpdate?.params).toEqual([ITEM_ID, 30, 360]);
|
||||
const pickingUpdate = calls.find((c) => c.text.includes('UPDATE picking_items'));
|
||||
expect(pickingUpdate?.params).toEqual([ITEM_ID, 30]);
|
||||
expect(applyCover).toHaveBeenCalledTimes(1);
|
||||
expect(recalcPrep).toHaveBeenCalledTimes(1);
|
||||
expect(syncOpenPurchase).toHaveBeenCalledTimes(1);
|
||||
expect(syncStatements).toHaveBeenCalledTimes(1);
|
||||
expect(updateSnapshot).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ branchCode: 'BR002', prepId: PREP_ID, prepareQty: 30 })
|
||||
);
|
||||
expect(recalcHeader).toHaveBeenCalledTimes(1);
|
||||
// 事件台账 applied
|
||||
const applyStatusCall = poolQuery.mock.calls.find(
|
||||
(c) => String(c[0]).includes('UPDATE public.main_system_quantity_event_applies')
|
||||
);
|
||||
expect(applyStatusCall?.[1]?.[2]).toBe('applied');
|
||||
});
|
||||
|
||||
it('重复事件(event_id+prep_id 已存在)⇒ duplicate,不写业务', async () => {
|
||||
poolQuery.mockImplementation(async (text: string) => {
|
||||
if (text.includes('INSERT INTO public.main_system_quantity_event_applies')) {
|
||||
return { rows: [], rowCount: 0 };
|
||||
}
|
||||
return { rows: [], rowCount: 0 };
|
||||
});
|
||||
const result = await applyOneQuantityChange({
|
||||
branchCode: 'BR002',
|
||||
eventId: '11111111-1111-4111-8111-111111111111',
|
||||
revision: 4,
|
||||
source: 'webhook',
|
||||
row: { prep_id: PREP_ID, new_quantity: 30, old_quantity: 25 },
|
||||
});
|
||||
expect(result.status).toBe('duplicate');
|
||||
expect(tenantRun).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('旧 revision ⇒ stale_revision,不写业务', async () => {
|
||||
poolQuery.mockImplementation(async (text: string) => {
|
||||
if (text.includes('INSERT INTO public.main_system_quantity_event_applies')) return { rows: [{ event_id: 'e' }], rowCount: 1 };
|
||||
if (text.includes('MAX(revision)')) return { rows: [{ max_revision: 9 }], rowCount: 1 };
|
||||
if (text.includes('FROM public.main_system_order_import_items')) return { rows: [ledgerRow()], rowCount: 1 };
|
||||
return { rows: [], rowCount: 0 };
|
||||
});
|
||||
const result = await applyOneQuantityChange({
|
||||
branchCode: 'BR002',
|
||||
eventId: '22222222-2222-4222-8222-222222222222',
|
||||
revision: 8,
|
||||
source: 'webhook',
|
||||
row: { prep_id: PREP_ID, new_quantity: 30, old_quantity: 25 },
|
||||
});
|
||||
expect(result.status).toBe('stale_revision');
|
||||
expect(tenantRun).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('共享备货行缺 main_order_item_id ⇒ 明确拒绝(shared_prep_missing_main_item),不按聚合量覆盖', async () => {
|
||||
poolQuery.mockImplementation(async (text: string) => {
|
||||
if (text.includes('INSERT INTO public.main_system_quantity_event_applies')) return { rows: [{ event_id: 'e' }], rowCount: 1 };
|
||||
if (text.includes('MAX(revision)')) return { rows: [{ max_revision: 0 }], rowCount: 1 };
|
||||
if (text.includes('FROM public.main_system_order_import_items')) return { rows: [ledgerRow()], rowCount: 1 };
|
||||
if (text.includes('FROM orders WHERE order_code = $1 LIMIT 1')) return { rows: [{ delivery_date: '2026-10-28' }], rowCount: 1 };
|
||||
return { rows: [], rowCount: 0 };
|
||||
});
|
||||
const result = await applyOneQuantityChange({
|
||||
branchCode: 'BR002',
|
||||
eventId: '66666666-6666-4666-8666-666666666666',
|
||||
revision: 2,
|
||||
source: 'webhook',
|
||||
row: { prep_id: PREP_ID, shared_prep: true, old_quantity: 10, new_quantity: 12, prep_new_qty: 30 },
|
||||
});
|
||||
expect(result.status).toBe('conflict');
|
||||
expect(result.reason).toBe('shared_prep_missing_main_item');
|
||||
expect(tenantRun).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('共享备货行用订单行新量(不是聚合量)作为目标数量', async () => {
|
||||
const { client, calls } = makeFakeClient((text) => {
|
||||
if (text.includes('FROM orders') && text.includes('FOR UPDATE')) {
|
||||
return { rows: [{ order_code: OUR_ORDER, order_status: 30, delivery_date: '2026-10-28', branch_code: 'BR002' }], rowCount: 1 };
|
||||
}
|
||||
if (text.includes('FROM order_items') && text.includes('WHERE id = $1::uuid AND order_code = $2')) {
|
||||
return { rows: [{ id: ITEM_ID, quantity: 10, price: 5, sku_code: 'SKU1', item_name: '共享菜', unit: '斤', stock_cover_qty: 0 }], rowCount: 1 };
|
||||
}
|
||||
if (text.includes('FROM picking_items') && text.includes('MAX(picked_qty)')) return { rows: [{ rows: 0, picked_qty: 0 }], rowCount: 1 };
|
||||
if (text.includes('UPDATE ')) return { rows: [], rowCount: 1 };
|
||||
if (text.includes('SELECT COALESCE(stock_cover_qty')) return { rows: [{ cover: 0 }], rowCount: 1 };
|
||||
return { rows: [], rowCount: 0 };
|
||||
});
|
||||
tenantRun.mockImplementation(async (_code: string, fn: (c: unknown) => Promise<unknown>) => fn(client));
|
||||
poolQuery.mockImplementation(async (text: string) => {
|
||||
if (text.includes('INSERT INTO public.main_system_quantity_event_applies')) return { rows: [{ event_id: 'e' }], rowCount: 1 };
|
||||
if (text.includes('MAX(revision)')) return { rows: [{ max_revision: 0 }], rowCount: 1 };
|
||||
if (text.includes('FROM public.main_system_order_import_items')) return { rows: [ledgerRow()], rowCount: 1 };
|
||||
return { rows: [], rowCount: 0 };
|
||||
});
|
||||
const result = await applyOneQuantityChange({
|
||||
branchCode: 'BR002',
|
||||
eventId: '77777777-7777-4777-8777-777777777777',
|
||||
revision: 3,
|
||||
source: 'webhook',
|
||||
row: {
|
||||
prep_id: PREP_ID,
|
||||
main_order_item_id: ITEM_ID,
|
||||
shared_prep: true,
|
||||
old_quantity: 10,
|
||||
new_quantity: 12,
|
||||
prep_old_qty: 28,
|
||||
prep_new_qty: 30,
|
||||
},
|
||||
});
|
||||
expect(result.status).toBe('applied');
|
||||
const orderUpdate = calls.find((c) => c.text.includes('UPDATE order_items'));
|
||||
expect(orderUpdate?.params).toEqual([ITEM_ID, 12, 60]);
|
||||
});
|
||||
|
||||
it('未知 prep ⇒ ignored_unknown_prep(落失败台账,等导入/对账)', async () => {
|
||||
poolQuery.mockImplementation(async (text: string) => {
|
||||
if (text.includes('INSERT INTO public.main_system_quantity_event_applies')) return { rows: [{ event_id: 'e' }], rowCount: 1 };
|
||||
if (text.includes('MAX(revision)')) return { rows: [{ max_revision: 0 }], rowCount: 1 };
|
||||
return { rows: [], rowCount: 0 };
|
||||
});
|
||||
const result = await applyOneQuantityChange({
|
||||
branchCode: 'BR002',
|
||||
eventId: '33333333-3333-4333-8333-333333333333',
|
||||
revision: 1,
|
||||
source: 'webhook',
|
||||
row: { prep_id: PREP_ID, new_quantity: 30, old_quantity: 25 },
|
||||
});
|
||||
expect(result.status).toBe('ignored_unknown_prep');
|
||||
expect(recordFailure).toHaveBeenCalled();
|
||||
expect(tenantRun).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('已出库 / 备货完成竞态 ⇒ 冲突不覆盖', () => {
|
||||
it('order_departed:不写订单数量,落冲突台账 + 通知', async () => {
|
||||
lockState.mockResolvedValue({ locked: true, reason: 'order_departed' });
|
||||
const { client, calls } = makeFakeClient((text) => {
|
||||
if (text.includes('FROM orders') && text.includes('FOR UPDATE')) {
|
||||
return { rows: [{ order_code: OUR_ORDER, order_status: 50, delivery_date: '2026-10-28', branch_code: 'BR002' }], rowCount: 1 };
|
||||
}
|
||||
if (text.includes('FROM order_items')) {
|
||||
return { rows: [{ id: ITEM_ID, quantity: 25, price: 12, sku_code: 'SKU1', item_name: '二刀肉', unit: '斤', stock_cover_qty: 0 }], rowCount: 1 };
|
||||
}
|
||||
return { rows: [], rowCount: 0 };
|
||||
});
|
||||
tenantRun.mockImplementation(async (_code: string, fn: (c: unknown) => Promise<unknown>) => fn(client));
|
||||
poolQuery.mockImplementation(async (text: string) => {
|
||||
if (text.includes('INSERT INTO public.main_system_quantity_event_applies')) return { rows: [{ event_id: 'e' }], rowCount: 1 };
|
||||
if (text.includes('MAX(revision)')) return { rows: [{ max_revision: 0 }], rowCount: 1 };
|
||||
if (text.includes('FROM public.main_system_order_import_items')) return { rows: [ledgerRow()], rowCount: 1 };
|
||||
if (text.includes('FROM orders WHERE order_code = $1 LIMIT 1')) return { rows: [{ delivery_date: '2026-10-28' }], rowCount: 1 };
|
||||
return { rows: [], rowCount: 0 };
|
||||
});
|
||||
|
||||
const result = await applyOneQuantityChange({
|
||||
branchCode: 'BR002',
|
||||
eventId: '44444444-4444-4444-8444-444444444444',
|
||||
revision: 3,
|
||||
source: 'webhook',
|
||||
row: { prep_id: PREP_ID, main_order_item_id: ITEM_ID, new_quantity: 30, old_quantity: 25, sku_code: 'SKU1', item_name: '二刀肉' },
|
||||
});
|
||||
expect(result.status).toBe('conflict');
|
||||
expect(result.reason).toBe('order_departed');
|
||||
expect(calls.some((c) => c.text.includes('UPDATE order_items'))).toBe(false);
|
||||
const conflictInsert = poolQuery.mock.calls.find((c) =>
|
||||
String(c[0]).includes('INSERT INTO public.main_system_quantity_conflicts')
|
||||
);
|
||||
expect(conflictInsert).toBeTruthy();
|
||||
expect(notifyRoleUsers).toHaveBeenCalled();
|
||||
// 冲突也同步台账快照,避免对账每轮重复告警
|
||||
expect(updateSnapshot).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('prep_completed_race:备货已完成 ⇒ 冲突', async () => {
|
||||
lockState.mockResolvedValue({ locked: false, reason: null });
|
||||
const { client } = makeFakeClient((text) => {
|
||||
if (text.includes('FROM orders') && text.includes('FOR UPDATE')) {
|
||||
return { rows: [{ order_code: OUR_ORDER, order_status: 30, delivery_date: '2026-10-28', branch_code: 'BR002' }], rowCount: 1 };
|
||||
}
|
||||
if (text.includes('FROM order_items')) {
|
||||
return { rows: [{ id: ITEM_ID, quantity: 25, price: 12, sku_code: 'SKU1', item_name: '二刀肉', unit: '斤', stock_cover_qty: 0 }], rowCount: 1 };
|
||||
}
|
||||
return { rows: [], rowCount: 0 };
|
||||
});
|
||||
tenantRun.mockImplementation(async (_code: string, fn: (c: unknown) => Promise<unknown>) => fn(client));
|
||||
poolQuery.mockImplementation(async (text: string) => {
|
||||
if (text.includes('INSERT INTO public.main_system_quantity_event_applies')) return { rows: [{ event_id: 'e' }], rowCount: 1 };
|
||||
if (text.includes('MAX(revision)')) return { rows: [{ max_revision: 0 }], rowCount: 1 };
|
||||
if (text.includes('FROM public.main_system_order_import_items')) {
|
||||
return { rows: [ledgerRow({ last_prepare_status: 30 })], rowCount: 1 };
|
||||
}
|
||||
if (text.includes('FROM orders WHERE order_code = $1 LIMIT 1')) return { rows: [{ delivery_date: '2026-10-28' }], rowCount: 1 };
|
||||
return { rows: [], rowCount: 0 };
|
||||
});
|
||||
const result = await applyOneQuantityChange({
|
||||
branchCode: 'BR002',
|
||||
eventId: '55555555-5555-4555-8555-555555555555',
|
||||
revision: 2,
|
||||
source: 'webhook',
|
||||
row: { prep_id: PREP_ID, main_order_item_id: ITEM_ID, new_quantity: 30, old_quantity: 25 },
|
||||
});
|
||||
expect(result.status).toBe('conflict');
|
||||
expect(result.reason).toBe('prep_completed_race');
|
||||
});
|
||||
});
|
||||
|
||||
describe('webhook payload 解析 / 消费端接线', () => {
|
||||
it('data[] 与 items[] 都接受;revision 从信封取', async () => {
|
||||
poolQuery.mockImplementation(async (text: string) => {
|
||||
if (text.includes('INSERT INTO public.main_system_quantity_event_applies')) return { rows: [], rowCount: 0 };
|
||||
return { rows: [], rowCount: 0 };
|
||||
});
|
||||
const dataPayload = await applyQuantityChangedPayload({
|
||||
branchCode: 'BR002',
|
||||
payload: { revision: 7, request_id: 'req-1', data: [{ prep_id: PREP_ID }] },
|
||||
});
|
||||
expect(dataPayload.revision).toBe(7);
|
||||
expect(dataPayload.results).toHaveLength(1);
|
||||
expect(dataPayload.results[0].status).toBe('duplicate');
|
||||
|
||||
const itemsPayload = await applyQuantityChangedPayload({
|
||||
branchCode: 'BR002',
|
||||
payload: { revision: 8, event_id: 'req-2', items: [{ prep_id: PREP_ID }, { prep_id: PREP_ID }] },
|
||||
});
|
||||
expect(itemsPayload.revision).toBe(8);
|
||||
expect(itemsPayload.results).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('事件消费者把 quantity_changed 分类为 quantity_sync', () => {
|
||||
expect(classifyEvent({ event: 'preparations.quantity_changed', orderCode: MAIN_ORDER })).toBe('quantity_sync');
|
||||
const consumer = read('src/services/mainSystemEventConsumer.ts');
|
||||
expect(consumer).toContain("name === 'preparations.quantity_changed'");
|
||||
expect(consumer).toContain('reconcileQuantityChangedForOrder');
|
||||
});
|
||||
|
||||
it('webhook 路由处理 quantity_changed(在 E1 兜底之前);对账接入 mainSystemReturnFollow', () => {
|
||||
const route = read('src/routes/mainSystemIntegration.ts');
|
||||
expect(route).toContain("event === 'preparations.quantity_changed'");
|
||||
expect(route).toContain('applyQuantityChangedPayload');
|
||||
const routeIdx = route.indexOf("event === 'preparations.quantity_changed'");
|
||||
const fallbackIdx = route.indexOf("if (event !== 'preparations.allocated')");
|
||||
expect(routeIdx).toBeGreaterThan(-1);
|
||||
expect(fallbackIdx).toBeGreaterThan(routeIdx);
|
||||
const follow = read('src/services/mainSystemReturnFollow.ts');
|
||||
expect(follow).toContain('applyOneQuantityChange');
|
||||
});
|
||||
});
|
||||
|
||||
describe('定时对账兜底(reconcileQuantityChangedForOrder)', () => {
|
||||
it('active 行 prepare_qty 与台账快照不同 ⇒ 走同一应用逻辑', async () => {
|
||||
fetchActive.mockResolvedValue({
|
||||
kind: 'ok',
|
||||
supplierCode: 'SUP76694428',
|
||||
branchCode: 'BR002',
|
||||
rowCount: 1,
|
||||
orders: [
|
||||
{
|
||||
orderCode: MAIN_ORDER,
|
||||
deliveryDate: '2026-10-28',
|
||||
taskDay: '2026-10-28',
|
||||
rows: [
|
||||
{
|
||||
id: PREP_ID,
|
||||
orderCode: MAIN_ORDER,
|
||||
skuCode: 'SKU78659582524',
|
||||
itemName: '二刀肉',
|
||||
prepareQty: 30,
|
||||
unit: '斤',
|
||||
prepareStatus: 10,
|
||||
mainOrderItemId: ITEM_ID,
|
||||
quantityRevision: 6,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
const { client } = makeFakeClient((text) => {
|
||||
if (text.includes('FROM orders') && text.includes('FOR UPDATE')) {
|
||||
return { rows: [{ order_code: OUR_ORDER, order_status: 30, delivery_date: '2026-10-28', branch_code: 'BR002' }], rowCount: 1 };
|
||||
}
|
||||
if (text.includes('FROM order_items') && text.includes('WHERE id = $1::uuid AND order_code = $2')) {
|
||||
return { rows: [{ id: ITEM_ID, quantity: 25, price: 12, sku_code: 'SKU78659582524', item_name: '二刀肉', unit: '斤', stock_cover_qty: 0 }], rowCount: 1 };
|
||||
}
|
||||
if (text.includes('FROM picking_items') && text.includes('MAX(picked_qty)')) return { rows: [{ rows: 0, picked_qty: 0 }], rowCount: 1 };
|
||||
if (text.includes('UPDATE ')) return { rows: [], rowCount: 1 };
|
||||
if (text.includes('SELECT COALESCE(stock_cover_qty')) return { rows: [{ cover: 30 }], rowCount: 1 };
|
||||
return { rows: [], rowCount: 0 };
|
||||
});
|
||||
tenantRun.mockImplementation(async (_code: string, fn: (c: unknown) => Promise<unknown>) => fn(client));
|
||||
poolQuery.mockImplementation(async (text: string) => {
|
||||
if (text.includes('FROM public.main_system_order_import_items') && text.includes('main_order_code')) {
|
||||
return { rows: [{ prep_id: PREP_ID, last_prepare_qty: '25', last_prepare_status: 10 }], rowCount: 1 };
|
||||
}
|
||||
if (text.includes('INSERT INTO public.main_system_quantity_event_applies')) return { rows: [{ event_id: 'e' }], rowCount: 1 };
|
||||
if (text.includes('MAX(revision)')) return { rows: [{ max_revision: 0 }], rowCount: 1 };
|
||||
if (text.includes('FROM public.main_system_order_import_items')) return { rows: [ledgerRow()], rowCount: 1 };
|
||||
return { rows: [], rowCount: 0 };
|
||||
});
|
||||
|
||||
const outcome = await reconcileQuantityChangedForOrder({
|
||||
branchCode: 'BR002',
|
||||
supplierCode: 'SUP76694428',
|
||||
mainOrderCode: MAIN_ORDER,
|
||||
});
|
||||
expect(outcome.status).toBe('ok');
|
||||
expect(outcome.applied).toBe(1);
|
||||
expect(updateSnapshot).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('主系统接口不可用 ⇒ 不判定(下轮重试)', async () => {
|
||||
fetchActive.mockResolvedValue({ kind: 'unavailable', reason: 'timeout' });
|
||||
const outcome = await reconcileQuantityChangedForOrder({
|
||||
branchCode: 'BR002',
|
||||
supplierCode: 'SUP76694428',
|
||||
mainOrderCode: MAIN_ORDER,
|
||||
});
|
||||
expect(outcome.status).toBe('unavailable');
|
||||
expect(outcome.applied).toBe(0);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user