Files
SupplierSystem/server/src/services/mainSystemPriceQtyRequest.ts
T
Ubuntu 4fb4abb420
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
feat(跨系统): 单位载体走待审后的两处追赶(409 不算失败 / 驳回不再重发)
主系统 2026-10-13 单边把「我方送过去的单位载体」改成**走待审**(其提交 a0afc585):
单位变了 ⇒ 回 pending(他们的行先不变,审核通过后才写并推 price_qty_decided);
该行已有待审 ⇒ 回 409 pending_exists(原话「再等一轮即可,别重试轰炸」);
补单位(当前为空)仍免审。我方协议不用改,但有两处必须跟上:

1) 409 被我们误记成"提交失败":http.ts 把未分类 4xx 判 rejected ⇒ submitPriceQtyRequest
   落 failed ⇒ 设计文 §11.8 的定向补发每轮计 1 次尝试,5 轮(约 50 分钟)后判 abandoned。
   修法:api/priceQty.ts 把 409 映射为机器可读的 conflict='pending_exists' 并一路透传;
   补发遇到它时保持 waiting 且**把尝试次数退回**(不计重试预算),等那条待审落定后自然补发。

2) 单位载体被审核人驳回时,落定钩子会再发一次同一单位(可能被反复驳回)。
   修法:落定钩子把"刚落定的台账行"传给补发;若它是**单位载体**(kind='qty' 且
   proposed_qty === before_qty)且结论 rejected ⇒ 意图标 noop、不重发(尊重审核结论;
   操作员若仍要改,重新改一次单位即可 = 新的显式意图)。

不误伤(含反证用例):真失败仍按 5 次上限收敛;被驳回的是改量(proposed ≠ before)时单位照常补发。

测试:unitDeferredResend.test.ts 扩到 15 例(新增 ⑪/⑪b/⑫/⑫b/⑬);
服务端 tsc 0 错;全量 26 failed / 2653 passed 与基线持平(唯一差异仍是对方 WIP 的 pickingZoneOrder);
门禁 8 通过 / 1 既定红 / 1 未执行(与改前一致)。

文档:设计文 §11.10(新语义 + 两处追赶 + 补单位/他们的理由/已知边界);
对接清单 §4.5.24 七(我方回执:追赶明细 + 误发待审的处置结果 + 对其 六之补 的确认)。

另:误发待审那条(其请求驳回"成本价 6.5 → 10")——我方镜像价从未跟成 10;
代为驳回时其侧已查不到该 request_id(not_found),我方台账保持待审不变,
按既有 Q6 对账口径宽限期后自动关成 failed(已在回执里写清)。
2026-10-13 14:56:52 +08:00

2015 lines
85 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 { randomUUID } from 'crypto';
import { pool } from '../db';
import { runWithTenantDataAccess } from './tenantSchemaService';
import { runWithTenantDbContext } from './tenantDbContext';
import { listMainSystemRequests } from './mainSystem/api/preparations';
import {
MAIN_SYSTEM_AMEND_STATUS,
fetchMainSystemPriceAmendRows,
isPriceQtyRequestEnabled,
submitMainSystemPriceQtyRequest,
} from './mainSystem';
import type { OrderManageItemInput } from './orderManageItemsService';
import { resolveSupplierCodeForPrep } from './branchAccessCode';
import { listRequestsForBranch } from './mainSystemBranchApi';
/**
* 跨系统**改价 / 改量审核**(我方实现,2026-10-11)。
*
* 口径(开发者定稿,见 docs/design/20261011-跨系统改价改量审核.md):
* · 本系统操作员改「主系统来源订单」的销售价(= 主系统成本价)或数量 ⇒ **提交申请**,
* 主系统按统一规则判定:原值 0/空(补价/补量)、改低、减量 ⇒ `applied`(免审立即生效);
* 涨价、加量 ⇒ `pending`(等主系统管理员审核);
* · 审核结果经 webhook `preparations.price_qty_decided` 回传,**以主系统最终值为准**;
* 漏推由 `view=price_amend` 轮询兜底(两条路径共用同一 `decideRequest`,不会分叉);
* · 免审与审核两类都在本系统 `operation_logs` 留详细日志(原值/建议值/最终值/来源)。
*
* 台账:`public.main_system_price_qty_requests`(迁移 20261019)。
* 铁律:不改订单状态链、不改分配信号量、不改财务口径;价格落地仍走既有改明细链路。
*/
export type PriceQtyRequestStatus = 'pending' | 'applied' | 'approved' | 'rejected' | 'failed';
export type PriceQtyKind = 'price' | 'qty' | 'both';
export type PriceQtyRequestRow = {
id: string;
branch_code: string;
request_id: string | null;
client_request_id: string;
prep_id: string;
main_order_code: string | null;
our_order_code: string;
our_order_item_id: string | null;
kind: PriceQtyKind;
before_price: number | null;
before_qty: number | null;
proposed_price: number | null;
proposed_qty: number | null;
final_price: number | null;
final_qty: number | null;
unit: string | null;
/** 商品名(提交时落库;列表展示优先用本方订单行的实时值) */
item_name?: string | null;
/** 主系统 SKU 编码(排障用) */
main_sku_code?: string | null;
status: PriceQtyRequestStatus;
review_required: boolean;
reason: string | null;
decision_reason: string | null;
requested_by: string | null;
decided_by: string | null;
decided_at: string | null;
payload: unknown;
created_at: string;
updated_at: string;
};
/** 开关(默认关)。关 = 与改造前逐字节一致:入口停用、写路径不拦、回写照旧带价格。 */
export function isEnabled(): boolean {
return isPriceQtyRequestEnabled();
}
function num(value: unknown): number | null {
if (value === null || value === undefined || value === '') return null;
const n = Number(value);
return Number.isFinite(n) ? n : null;
}
function sameNumber(a: number | null, b: number | null, epsilon = 1e-6): boolean {
if (a === null || b === null) return a === b;
return Math.abs(a - b) < epsilon;
}
/* ── 写路径守卫(C2 的强制面:非申请入口不得改主系统行的价/量)────────────── */
export type PriceQtyChange =
| { itemId: string; itemName: string; field: 'price'; from: number; to: number }
| { itemId: string; itemName: string; field: 'quantity'; from: number; to: number }
/**
* **单位变更**(2026-10-13 追加,开发者确认要上报)。
* 单位不是数值,单独一支;上报时用「数量不变的改量载体」送(见 `submitPriceQtyRequest`)。
*/
| { itemId: string; itemName: string; field: 'unit'; fromUnit: string; toUnit: string };
/**
* 主系统来源订单的价/量变更必须走申请入口。
*
* 为什么要在服务层拦:改明细有 5 个入口(Web / 小程序 ×3 / MCP)+ 1 条绕过路径
* (采购联动改销售价),只在界面上做分流会被绕过。
*
* 开关关闭时**直接放行**(与改造前逐字节一致);已审核落地路径传 `approved: true` 放行。
*/
export function assertMainSystemPriceQtyReviewed(params: {
isMainSystemOrder: boolean;
changes: PriceQtyChange[];
/** 内部落地(申请生效/审核通过)时为 true */
approved?: boolean;
}): void {
if (params.approved) return;
if (!params.isMainSystemOrder || !params.changes.length) return;
if (!isEnabled()) return;
/**
* 2026-10-12 口径:**先改后通知** ⇒ 不再抛错拦人;由调用方在写库**之后**调用
* `notifyMainSystemPriceQtyChanges` 异步通知主系统(对方同意/驳回都不改我方值)。
*/
if (isPriceQtyLocalFirst()) return;
const detail = params.changes
.slice(0, 5)
.map((c) =>
c.field === 'unit'
? `${c.itemName}(单位 ${c.fromUnit || '—'} → ${c.toUnit})`
: `${c.itemName}(${c.field === 'price' ? '价格' : '数量'} ${c.from} → ${c.to})`
)
.join('、');
throw Object.assign(
new Error(
`主系统分配过来的商品改价/改量需要提交申请(${detail});` +
`免审项(补价/改低/减量)提交后立即生效,涨价/加量等主系统管理员审核`
),
{ status: 409, code: 'main_system_price_qty_requires_review', changes: params.changes }
);
}
/**
* **先改后通知**总口径(2026-10-12 开发者定稿):
*
* 实收数量/单位与销售价一律遵循「**自己只能改自己的**」——
* · 我方改**我方**字段(销售价 / 数量)⇒ **本地立即生效**(改了就是改了,含金额/毛利/看板/结算),
* **随后异步通知**主系统,由它决定是否让自己的值跟着变;它同意或驳回**都不影响我方已生效的值**;
* · 对方改**对方**字段 ⇒ 它先生效再发请求,我方决定是否同步自己的(见 `mainSystemActualQtyInbox`)。
*
* 因此本模块内两处旧行为被反转:
* 1. `assertMainSystemPriceQtyReviewed` 不再拦截改价/改量(改为**通知**,见 `notifyMainSystemPriceQtyChanges`);
* 2. `submitPriceQtyRequest` 的"免审⇒本地落地"与 `decidePriceQtyRequest` 的"按其结论覆盖我方值"都**关掉**
* —— 本地值由**发起改动的那个入口**写,主系统的结论只记台账 + 留痕(价格不一致时只记录、不提醒)。
*
* 置 `false` 可整体回退到 2026-10-11 的"先审后改"(仅用于线上异常回退,回退前请先确认没有在途 pending)。
*/
let priceQtyLocalFirst = true;
/** 当前是否"先改后通知"口径(默认 true;见上面的说明) */
export function isPriceQtyLocalFirst(): boolean {
return priceQtyLocalFirst;
}
/**
* 仅供测试:切换口径开关。
* 保留旧"先审后改"路径的实现与其既有测试(回退时仍可用),默认不被生产代码调用。
*/
export function __setPriceQtyLocalFirstForTests(value: boolean): void {
priceQtyLocalFirst = value;
}
/** 读我方订单行当前的价/量(用于"主系统结论 vs 我方实际值"的差异留痕) */
async function readOurOrderItemPriceQty(params: {
branchCode: string;
ourOrderCode: string;
ourOrderItemId: string;
}): Promise<{ price: number | null; quantity: number | null } | null> {
const rows = await runWithTenantDbContext(params.branchCode, () =>
pool.query<{ price: string | number | null; quantity: string | number | null }>(
`SELECT price, quantity FROM order_items WHERE order_code = $1 AND id = $2::uuid LIMIT 1`,
[params.ourOrderCode, params.ourOrderItemId]
)
);
const row = rows.rows[0];
if (!row) return null;
return { price: num(row.price), quantity: num(row.quantity) };
}
/**
* **通知**主系统:我方已经把价/量改了(先改后通知,2026-10-12 口径)。
*
* 与旧 `assertMainSystemPriceQtyReviewed` 的关系:那个是**拦截**;本函数是**事后通知**。
* 调用时机:调用方的**本地写入提交之后**(本函数异步执行,失败只记台账 + 日志,绝不回滚本地值)。
*
* 逐条变更发一条申请(价/量分开,主系统按 `field` 归行);每条独立成败,互不影响。
* 失败/未就绪时台账落 `failed`(带原因),由对账兜底或人工重发;**我方值保持已改后的值**。
*/
export function notifyMainSystemPriceQtyChanges(params: {
branchCode: string;
ourOrderCode: string;
changes: PriceQtyChange[];
actor: PriceQtyActor;
reason?: string | null;
}): void {
if (!isEnabled() || !isPriceQtyLocalFirst()) return;
const changes = Array.isArray(params.changes) ? params.changes : [];
if (!changes.length) return;
for (const change of changes) {
/**
* **单位变更**(2026-10-13):单位不是价/量,走"数量不变的改量载体"送 ——
* 主系统判 `no_change ⇒ 免审 applied` 时会把 `unit` 写进它的备货行(真机实测:
* 备货行 `unit: 斤 → 件 → 斤`,价/量分毫未动),因此**不需要主系统改代码**。
* 见 docs/design/20261011-跨系统改价改量审核.md 的「单位」一节。
*/
if (change.field === 'unit') {
void submitPriceQtyRequest({
branchCode: params.branchCode,
ourOrderCode: params.ourOrderCode,
ourOrderItemId: change.itemId,
proposedUnit: change.toUnit,
beforeUnit: change.fromUnit,
reason: params.reason
? `${params.reason}:改单位 ${change.fromUnit || '—'} → ${change.toUnit}`
: `订单明细改单位(先改后通知):${change.fromUnit || '—'} → ${change.toUnit}`,
actor: params.actor,
})
.then((outcome) => {
if (outcome.kind !== 'ok') {
const reason = (outcome as { reason?: string }).reason || outcome.kind;
console.error(
`[price-qty-notify] ${params.branchCode} ${params.ourOrderCode} ${change.itemName} 单位变更通知主系统失败(本地值已生效,不回滚):`,
reason
);
}
})
.catch((error: unknown) => {
console.error(
`[price-qty-notify] ${params.branchCode} ${params.ourOrderCode} ${change.itemName} 单位变更通知异常(本地值已生效,不回滚):`,
(error as Error)?.message || error
);
});
continue;
}
const isPrice = change.field === 'price';
void submitPriceQtyRequest({
branchCode: params.branchCode,
ourOrderCode: params.ourOrderCode,
ourOrderItemId: change.itemId,
proposedPrice: isPrice ? change.to : null,
proposedQty: isPrice ? null : change.to,
// **改动前**的值由调用方给出:此刻库里已是新值(COMMIT 之后才通知),回表必然读到新值
beforePrice: isPrice ? change.from : undefined,
beforeQty: isPrice ? undefined : change.from,
reason: params.reason || (isPrice ? '订单明细改销售价(先改后通知)' : '订单明细改数量(先改后通知)'),
actor: params.actor,
})
.then((outcome) => {
if (outcome.kind !== 'ok') {
const reason = (outcome as { reason?: string }).reason || outcome.kind;
console.error(
`[price-qty-notify] ${params.branchCode} ${params.ourOrderCode} ${change.itemName} 通知主系统失败(本地值已生效,不回滚):`,
reason
);
}
})
.catch((error: unknown) => {
console.error(
`[price-qty-notify] ${params.branchCode} ${params.ourOrderCode} ${change.itemName} 通知异常(本地值已生效,不回滚):`,
(error as Error)?.message || error
);
});
}
}
/* ── 行解析:本系统订单行 ↔ 主系统备货行 ───────────────────────────────────── */
export type MainSystemLineRef = {
isMainSystemOrder: boolean;
mainOrderCode: string | null;
prepId: string | null;
};
/**
* 解析某订单行是否来自主系统,并尽力拿到主系统备货行 id(提交申请需要它)。
* 依据:① 行级台账 `main_system_order_import_items.our_order_item_id`;
* ② `order_items.main_order_code`;③ 整单台账 `main_system_order_imports`。
*/
export async function resolveMainSystemOrderLine(params: {
branchCode: string;
ourOrderCode: string;
ourOrderItemId?: string | null;
}): Promise<MainSystemLineRef> {
const { branchCode, ourOrderCode, ourOrderItemId } = params;
const ledgerOrder = await pool.query<{ main_order_code: string }>(
`SELECT main_order_code FROM public.main_system_order_imports
WHERE branch_code = $1 AND our_order_code = $2
LIMIT 1`,
[branchCode, ourOrderCode]
);
let isMainSystemOrder = Boolean(ledgerOrder.rowCount);
let mainOrderCode: string | null = ledgerOrder.rows[0]?.main_order_code
? String(ledgerOrder.rows[0].main_order_code)
: null;
let prepId: string | null = null;
if (ourOrderItemId) {
const line = await pool.query<{ prep_id: string | null; main_order_code: string | null }>(
`SELECT prep_id, main_order_code
FROM public.main_system_order_import_items
WHERE branch_code = $1 AND our_order_item_id = $2::uuid
LIMIT 1`,
[branchCode, ourOrderItemId]
);
if (line.rowCount) {
isMainSystemOrder = true;
prepId = line.rows[0]?.prep_id ? String(line.rows[0].prep_id) : null;
mainOrderCode = line.rows[0]?.main_order_code
? String(line.rows[0].main_order_code)
: mainOrderCode;
}
}
if (!mainOrderCode || !prepId) {
const row = await runWithTenantDataAccess(branchCode, async (client) =>
client.query<{ main_order_code: string | null }>(
`SELECT main_order_code FROM order_items WHERE id = $1::uuid LIMIT 1`,
[ourOrderItemId || null]
)
);
const rowMainOrderCode = row.rows[0]?.main_order_code ? String(row.rows[0].main_order_code) : null;
if (rowMainOrderCode) {
isMainSystemOrder = true;
mainOrderCode = mainOrderCode || rowMainOrderCode;
if (!prepId) {
const byName = await pool.query<{ prep_id: string | null }>(
`SELECT i.prep_id
FROM public.main_system_order_import_items i
WHERE i.branch_code = $1 AND i.main_order_code = $2
AND (i.our_order_item_id = $3::uuid OR i.our_order_item_id IS NULL)
ORDER BY (i.our_order_item_id = $3::uuid) DESC NULLS LAST
LIMIT 1`,
[branchCode, rowMainOrderCode, ourOrderItemId || null]
);
prepId = byName.rows[0]?.prep_id ? String(byName.rows[0].prep_id) : null;
}
}
}
return { isMainSystemOrder, mainOrderCode, prepId };
}
/* ── 守卫范围判定:哪些**行**属于主系统分配行(C2 的地基)────────────────────── */
export type MainSystemLineCandidate = {
itemId: string;
itemName: string;
skuCode?: string | null;
/** 该行自己的 `order_items.main_order_code`(迁移 20261015 加的列,可能为 NULL) */
mainOrderCode?: string | null;
};
/**
* 判定"改动的是不是主系统分配过来的行"。
*
* ⚠️ 为什么不能只看整单台账(`main_system_order_imports`):主系统单是**按配送日合并**的一张单,
* 上面允许操作员加本系统自建行/加菜行;若按整单判,那些自建行将来改价也会被要求走主系统审核 ——
* 而它们在主系统根本没有对应备货行(提交申请必然失败),等于把正常业务堵死。
*
* 因此按**行**判定,三条任一成立即算主系统行:
* ① 行级台账 `main_system_order_import_items.our_order_item_id` 命中;
* ② `order_items.main_order_code` 非空(导入时逐行盖章);
* ③ 整单是主系统单,且该行与台账里**尚未回填对照**的某行同名同 SKU(此时顺手补回填 = 惰性自愈)。
*
* 返回:需要走审核的行(其余行放行,保持改造前行为)。
*/
export async function isMainSystemAllocatedLines(params: {
branchCode: string;
ourOrderCode: string;
candidates: MainSystemLineCandidate[];
/** 测试/调用方传入的既有客户端(同事务) */
query: (sql: string, values?: unknown[]) => Promise<{ rows: any[]; rowCount?: number | null }>;
}): Promise<{ guarded: Set<string>; orderIsMainSystem: boolean }> {
const guarded = new Set<string>();
const { branchCode, ourOrderCode, candidates } = params;
if (!candidates.length) return { guarded, orderIsMainSystem: false };
const ledgerOrder = await params.query(
`SELECT 1 FROM public.main_system_order_imports
WHERE branch_code = $1 AND our_order_code = $2 LIMIT 1`,
[branchCode, ourOrderCode]
);
const orderIsMainSystem = Boolean(ledgerOrder.rowCount || ledgerOrder.rows.length);
const rows = await params.query(
`SELECT prep_id, item_name, main_sku_code, our_order_item_id
FROM public.main_system_order_import_items
WHERE branch_code = $1 AND our_order_code = $2`,
[branchCode, ourOrderCode]
);
const mapped = new Set(
rows.rows.filter((r) => r.our_order_item_id).map((r) => String(r.our_order_item_id))
);
const unmapped = rows.rows.filter((r) => !r.our_order_item_id);
const normalize = (value: unknown) => String(value ?? '').trim().toLowerCase();
for (const candidate of candidates) {
if (mapped.has(candidate.itemId) || candidate.mainOrderCode) {
guarded.add(candidate.itemId);
continue;
}
if (!orderIsMainSystem) continue;
// ③ 同名同 SKU 的未回填台账行 ⇒ 视为主系统行,并把对照补上(惰性自愈,下次判定即走 ①)
const match = unmapped.find(
(row) =>
normalize(row.item_name) === normalize(candidate.itemName) &&
(!candidate.skuCode || !row.main_sku_code || normalize(row.main_sku_code) === normalize(candidate.skuCode))
);
if (match) {
guarded.add(candidate.itemId);
try {
await params.query(
`UPDATE public.main_system_order_import_items
SET our_order_item_id = $3::uuid, updated_at = NOW()
WHERE branch_code = $1 AND prep_id = $2 AND our_order_item_id IS NULL`,
[branchCode, String(match.prep_id), candidate.itemId]
);
} catch (error: unknown) {
// 回填失败不影响判定结论(下一次仍会走 ③)
console.warn(
'[main-system-price-qty] 行级对照自愈失败:',
(error as Error)?.message || error
);
}
}
}
return { guarded, orderIsMainSystem };
}
/* ── 台账读写 ─────────────────────────────────────────────────────────────── */
/** 落地失败自动重试上限(超过则标 failed 交人工,避免无限重试刷日志) */
const MAX_APPLY_ATTEMPTS = 5;
/** 幽灵 pending 判废阈值:落了台账但没拿到主系统申请号(提交中断)超过此时长即标 failed */
const STALE_PENDING_MS = 30 * 60 * 1000;
function isTerminalStatus(status: string): boolean {
return status === 'applied' || status === 'approved' || status === 'rejected';
}
/** 申请列表(界面用;按分公司过滤) */
export async function listPriceQtyRequests(params: {
branchCode: string;
status?: string | null;
ourOrderCode?: string | null;
limit?: number;
}): Promise<PriceQtyRequestRow[]> {
const args: unknown[] = [params.branchCode];
const where: string[] = ['branch_code = $1'];
if (params.status) {
args.push(params.status);
where.push(`status = $${args.length}`);
}
if (params.ourOrderCode) {
args.push(params.ourOrderCode);
where.push(`our_order_code = $${args.length}`);
}
args.push(Math.min(Math.max(Number(params.limit) || 100, 1), 500));
const result = await pool.query(
`SELECT * FROM public.main_system_price_qty_requests
WHERE ${where.join(' AND ')}
ORDER BY created_at DESC
LIMIT $${args.length}`,
args
);
const rows = result.rows as PriceQtyRequestRow[];
await attachItemNames(params.branchCode, rows);
return rows;
}
/**
* 给台账行补「商品名」:**优先用本方订单行的实时值**(改名/改规格后仍准),
* 取不到(订单行已删/退货清理)才退回提交时落库的 `item_name`,再不行前端退回 `prep_id`。
*
* 一次批量查本方租户的 `order_items`(单条 SQL、按 id 数组),不逐行查;查不到的名字不写回(避免固化旧名)。
*/
export async function attachItemNames(branchCode: string, rows: PriceQtyRequestRow[]): Promise<void> {
const ids = [...new Set(rows.map((row) => row.our_order_item_id).filter(Boolean))] as string[];
if (!ids.length) return;
try {
const live = await runWithTenantDataAccess(branchCode, async (client) =>
client.query<{ id: string; item_name: string | null }>(
`SELECT id::text AS id, item_name FROM order_items WHERE id = ANY($1::uuid[])`,
[ids]
)
);
const byId = new Map(live.rows.map((row) => [String(row.id), row.item_name ? String(row.item_name) : null]));
for (const row of rows) {
const name = row.our_order_item_id ? byId.get(String(row.our_order_item_id)) : null;
if (name) row.item_name = name;
}
} catch (error: unknown) {
// 名称只影响展示:查不到就用台账里落库的值,不阻断列表
console.warn('[main-system-price-qty] 解析商品名失败:', (error as Error)?.message || error);
}
}
/** 某备货行最近一次「已生效/已通过」的最终值(回写门禁 C5 用) */
export async function getApprovedFinalValues(params: {
branchCode: string;
prepId: string;
}): Promise<{ requestId: string | null; finalPrice: number | null; finalQty: number | null; status: string } | null> {
const result = await pool.query(
`SELECT request_id, final_price, final_qty, status
FROM public.main_system_price_qty_requests
WHERE branch_code = $1 AND prep_id = $2 AND status IN ('applied','approved')
ORDER BY COALESCE(decided_at, updated_at) DESC
LIMIT 1`,
[params.branchCode, params.prepId]
);
const row = result.rows[0];
if (!row) return null;
return {
requestId: row.request_id ? String(row.request_id) : null,
finalPrice: num(row.final_price),
finalQty: num(row.final_qty),
status: String(row.status),
};
}
/* ── 操作日志(C7)────────────────────────────────────────────────────────── */
export type PriceQtyActor = {
userId?: string | null;
roles?: string | null;
/** 身份留痕串:`SUP37831443:admin:<userId>` */
requestedBy?: string | null;
ipAddress?: string | null;
};
async function writePriceQtyAuditLog(params: {
branchCode: string;
actor: PriceQtyActor;
operationType: string;
row: Pick<
PriceQtyRequestRow,
'id' | 'our_order_code' | 'our_order_item_id' | 'main_order_code' | 'prep_id' | 'kind'
>;
oldValue: Record<string, unknown>;
newValue: Record<string, unknown>;
}): Promise<void> {
try {
const { writeAuditLog } = await import('./auditService');
await writeAuditLog({
operatorId: params.actor.userId ?? null,
operatorRole: params.actor.roles ?? null,
operationType: params.operationType,
targetTable: 'order_items',
targetId: params.row.our_order_item_id ?? undefined,
branchCode: params.branchCode,
actionCategory: 'order',
ipAddress: params.actor.ipAddress ?? null,
oldValue: params.oldValue,
newValue: {
...params.newValue,
request_row_id: params.row.id,
our_order_code: params.row.our_order_code,
main_order_code: params.row.main_order_code,
prep_id: params.row.prep_id,
kind: params.row.kind,
},
});
} catch (error: unknown) {
// 日志失败绝不阻断业务(与 main_system_stockout 同纪律)
console.error('[main-system-price-qty] 写操作日志失败:', (error as Error)?.message || error);
}
}
/* ── 落地:把最终值写进我方订单行 ─────────────────────────────────────────── */
type SnapshotItem = Record<string, unknown>;
function toManageItemInput(item: SnapshotItem): OrderManageItemInput {
return {
id: String(item.id),
item_name: (item.item_name as string | null) ?? null,
sku_code: (item.sku_code as string | null) ?? null,
quantity: item.quantity as number | null,
unit: (item.unit as string | null) ?? null,
price: item.price as number | null,
amount: item.amount as number | null,
// 必须原样回传:`unit_cost` 由它推导,漏传会把既有行的成本清成 0
cost_price: item.cost_price as number | null,
supplier_code: (item.supplier_code as string | null) ?? null,
processing_method: (item.processing_method as string | null) ?? null,
processing_owner: (item.processing_owner as string | null) ?? null,
category_code: (item.category_code as string | null) ?? null,
category_name: (item.category_name as string | null) ?? null,
remark: (item.remark as string | null) ?? null,
is_extra_dish: Boolean(item.is_extra_dish),
quality_report_id: (item.quality_report_id as string | null) ?? null,
} as OrderManageItemInput;
}
/**
* 按最终值落地到订单行(**走既有改明细链路**,与设计 §5 一致)。
*
* 幂等:重复回传同一 request 时,目标行已是该值 ⇒ 直接返回 `{ changed: false }`,不重复改账。
*/
export async function applyFinalPriceQtyToOurOrderItem(params: {
branchCode: string;
ourOrderCode: string;
ourOrderItemId: string;
finalPrice?: number | null;
finalQty?: number | null;
unit?: string | null;
actor: PriceQtyActor;
}): Promise<{ changed: boolean; reason: string }> {
const snapshot = await runWithTenantDataAccess(params.branchCode, async (client) => {
const itemsResult = await client.query<SnapshotItem>(
`SELECT id, item_name, sku_code, quantity, unit, price, amount,
unit_cost AS cost_price, supplier_code, processing_method, processing_owner,
category_code, category_name, sort_order, remark,
COALESCE(is_extra_dish, false) AS is_extra_dish,
quality_report_id
FROM order_items
WHERE order_code = $1
ORDER BY sort_order ASC NULLS LAST, id ASC`,
[params.ourOrderCode]
);
return itemsResult.rows;
});
if (!snapshot.length) return { changed: false, reason: '我方订单行不存在(可能已删除)' };
const inputs = snapshot.map(toManageItemInput);
const target = inputs.find((item) => String(item.id) === params.ourOrderItemId);
if (!target) return { changed: false, reason: '目标订单行不在该订单里(可能已被退货/删除)' };
const currentPrice = num(target.price);
const currentQty = num(target.quantity);
const nextPrice =
params.finalPrice === undefined || params.finalPrice === null ? currentPrice : Number(params.finalPrice);
const nextQty = params.finalQty === undefined || params.finalQty === null ? currentQty : Number(params.finalQty);
const priceChanged = !sameNumber(currentPrice, nextPrice);
const qtyChanged = !sameNumber(currentQty, nextQty);
if (!priceChanged && !qtyChanged) {
return { changed: false, reason: '订单行已是该值(幂等命中)' };
}
target.price = nextPrice;
target.quantity = nextQty;
if (params.unit) target.unit = params.unit;
// 懒加载:改明细服务体量大且与订单/分配模块互引(与导入路径同一处置)
const { syncOrderManageItems } = await import('./orderManageItemsService');
await runWithTenantDbContext(params.branchCode, () =>
syncOrderManageItems({
orderCode: params.ourOrderCode,
items: inputs,
operatorId: params.actor.userId ?? null,
operatorRoles: 'main_system_price_qty_apply',
// 主系统未定价 ⇒ 0 价是正常口径(与导入建单同一开关)
allowUnpriced: true,
// 审批结果必须落地:即使订单已进入履约(40+),系统落地路径也放行强制改单位
canForceEdit: true,
// 本路径 = 已审核/免审生效,跳过"必须走申请"守卫
mainSystemPriceQtyApproved: true,
})
);
return {
changed: true,
reason: `已落地:价格 ${currentPrice ?? '—'} → ${nextPrice ?? '—'},数量 ${currentQty ?? '—'} → ${nextQty ?? '—'}`,
};
}
/* ── 提交申请(C2)───────────────────────────────────────────────────────── */
export type SubmitPriceQtyOutcome =
| {
kind: 'ok';
row: PriceQtyRequestRow;
status: 'applied' | 'pending';
reviewRequired: boolean;
finalPrice: number | null;
finalQty: number | null;
/** 仍在审的字段(主系统响应 `pending` 分解对象):混合提交时前端据此提示"哪项待审" */
pendingFields: { price?: number; qty?: number };
message: string | null;
appliedLocally: boolean;
applyNote: string | null;
}
| { kind: 'disabled'; reason: string }
| { kind: 'not_main_system_order'; reason: string }
| { kind: 'no_change'; reason: string }
| { kind: 'invalid'; reason: string }
/** 主系统暂未提供该接口(联调前) */
| { kind: 'main_system_not_ready'; reason: string }
/** 提交未能确认(主系统不可用/响应不可识别)—— 未落地,可重试 */
| {
kind: 'failed';
reason: string;
retryable: boolean;
/**
* 机器可读的冲突码(2026-10-13):主系统把「子系统改我方单位」改成走待审后,
* 该行已有别的待审会回 `409 pending_exists` ⇒ 这是"等一轮",**不是**失败。
* 调用方(如 §11.8 的定向补发)据此不计重试次数、也不判放弃。
*/
conflict?: 'pending_exists';
};
/**
* 提交改价/改量申请。
*
* 流程:解析行 → 算 kind(价/量/两者)→ 落本地 `pending` 台账 → 调主系统 Q1 →
* 按响应把台账改成 `applied`(并立即落地)或保持 `pending`。
*/
export async function submitPriceQtyRequest(params: {
branchCode: string;
ourOrderCode: string;
ourOrderItemId: string;
proposedPrice?: number | null;
proposedQty?: number | null;
unit?: string | null;
/** **单位变更**(2026-10-13):新单位;与 `proposedPrice/Qty` 同为"要报的变更"三选一 */
proposedUnit?: string | null;
/** 单位变更前的值("先改后通知"下库里已是新值,故由调用方给旧值) */
beforeUnit?: string | null;
reason?: string | null;
actor: PriceQtyActor;
clientRequestId?: string;
/**
* **改动前**的值(可选,但"先改后通知"路径**必须**传)。
*
* 为什么必须:本函数默认从**当前**订单行读 before 值来判"值有没有变"。
* local-first 下调用方是**先写完库、COMMIT 之后**才通知的 —— 此刻库里已经是**新值**,
* 默认读法会得到 `before == proposed` ⇒ 判 `no_change` **根本不通知**,
* 台账 `before_*` 也会记成新值(发给主系统的 `before_value` 同样错)。
* 实测复现(2026-10-12 E2E):改价 8.30 → 9.10 后通知,主系统端完全收不到(我方值照常生效 ⇒ 静默漏发)。
*/
beforePrice?: number | null;
beforeQty?: number | null;
}): Promise<SubmitPriceQtyOutcome> {
if (!isEnabled()) {
return {
kind: 'disabled',
reason: '跨系统改价/改量审核未开启(MAIN_SYSTEM_PRICE_QTY_ENABLED=1 后可用)',
};
}
const current = await runWithTenantDataAccess(params.branchCode, async (client) =>
client.query<{
price: string | number | null;
quantity: string | number | null;
unit: string | null;
item_name: string | null;
sku_code: string | null;
}>(
`SELECT price, quantity, unit, item_name, sku_code
FROM order_items WHERE id = $1::uuid AND order_code = $2 LIMIT 1`,
[params.ourOrderItemId, params.ourOrderCode]
)
);
if (!current.rowCount) return { kind: 'invalid', reason: '订单行不存在' };
// ⚠️ before 的取值口径见 params 注释:local-first 下库里已是新值,必须用调用方给的旧值。
const beforePrice =
params.beforePrice !== undefined && params.beforePrice !== null
? num(params.beforePrice)
: num(current.rows[0].price);
const beforeQty =
params.beforeQty !== undefined && params.beforeQty !== null
? num(params.beforeQty)
: num(current.rows[0].quantity);
const itemName = current.rows[0].item_name ? String(current.rows[0].item_name) : '';
const proposedPrice = num(params.proposedPrice);
const proposedQty = num(params.proposedQty);
if (proposedPrice !== null && proposedPrice < 0) return { kind: 'invalid', reason: '价格不能为负' };
if (proposedQty !== null && proposedQty <= 0) return { kind: 'invalid', reason: '数量必须大于 0' };
/**
* **单位变更**(2026-10-13):单位不在主系统 `kind`(price/qty)里,所以用
* 「**数量不变的改量载体**」送达 —— 主系统看到 `proposed_qty === 它的当前值` ⇒ `no_change ⇒ 免审 applied`,
* 并在生效分支里把 `unit` 写进备货行(真机实测:备货行 `unit: 斤 → 件 → 斤`,价/量分毫未动)。
* ⇒ 不需要主系统改代码;待他们加 `kind='unit'` 后本载体可平滑替换。
*/
/**
* ⚠️ **before 必须取调用方给的旧值**(与 `beforePrice/beforeQty` 同一条教训):
* local-first 下调用方是**先写完库、COMMIT 之后**才通知的,此刻库里的 `unit` 已是**新值** ——
* 拿它当 before 比出来永远"没变" ⇒ 静默漏发(首版实现踩到:真库 E2E 里单位改了但一条申请都没有)。
*/
const currentUnit = String(current.rows[0].unit ?? '').trim();
const beforeUnit =
params.beforeUnit != null && String(params.beforeUnit).trim() !== ''
? String(params.beforeUnit).trim()
: currentUnit;
const proposedUnit = params.proposedUnit != null ? String(params.proposedUnit).trim() : '';
const unitChanged = Boolean(proposedUnit) && proposedUnit !== beforeUnit;
const priceChanged = proposedPrice !== null && !sameNumber(beforePrice, proposedPrice);
const qtyChanged = proposedQty !== null && !sameNumber(beforeQty, proposedQty);
/** 只改单位(价、量都没动)⇒ 走"数量不变的改量载体" */
const unitOnly = unitChanged && !priceChanged && !qtyChanged;
if (!priceChanged && !qtyChanged && !unitChanged) {
return { kind: 'no_change', reason: '价格与数量都没有变化' };
}
const kind: PriceQtyKind = priceChanged && qtyChanged ? 'both' : priceChanged ? 'price' : 'qty';
/** 送出去的数量:单位变更时用**当前数量**(不变)当载体;主系统据此判 no_change ⇒ 免审 applied ⇒ 只写 unit */
const carrierQty = unitOnly ? num(current.rows[0].quantity) : null;
const line = await resolveMainSystemOrderLine({
branchCode: params.branchCode,
ourOrderCode: params.ourOrderCode,
ourOrderItemId: params.ourOrderItemId,
});
if (!line.isMainSystemOrder || !line.prepId) {
return {
kind: 'not_main_system_order',
reason: line.isMainSystemOrder
? '找不到该行对应的主系统备货行(台账缺 prep_id),无法提交申请'
: '该订单不是主系统分配过来的,直接改明细即可',
};
}
/**
* ⚠️ 单位变更与"待审的改量申请"共用 `kind='qty'`:`uq_..._pending (branch_code, prep_id, kind)`
* 是部分唯一索引 ⇒ 直接提交会**把那条待审改量顶掉**。改量是业务实质变更(要主系统审),
* 不该被一次改单位挤掉 ⇒ 这种情况**本次不上报单位**,只记日志,等改量审完再说。
*
* 2026-10-13(开发者选 A):**「跳过」≠「排队」**(主系统回执 §10.2-3 指出)——
* 那条待审若最终被**驳回**,这次单位变更就永久丢了 ⇒ 跳过时**留一条"待补发意图"**,
* 等该行改量审核落定后**定向补发一次**(webhook/Q6 对账 + 15 分钟清扫)。
* 见 `mainSystemUnitDeferredResend.ts` 与设计文 §11.8。
*/
if (unitOnly) {
const pendingQty = await pool.query(
`SELECT 1 FROM public.main_system_price_qty_requests
WHERE branch_code = $1 AND prep_id = $2 AND kind = 'qty' AND status = 'pending'
LIMIT 1`,
[params.branchCode, line.prepId]
);
if (pendingQty.rowCount) {
// 留痕(失败不影响"跳过"这个业务结论):动态 import 以避开与本模块的循环依赖
try {
const { recordDeferredUnitResend } = await import('./mainSystemUnitDeferredResend');
await recordDeferredUnitResend({
branchCode: params.branchCode,
prepId: line.prepId,
mainOrderCode: line.mainOrderCode,
ourOrderCode: params.ourOrderCode,
ourOrderItemId: params.ourOrderItemId,
beforeUnit,
targetUnit: proposedUnit,
});
} catch (error: unknown) {
console.error(
'[price-qty-notify] 记录单位补发意图失败(跳过结论不变):',
(error as Error)?.message || error
);
}
return {
kind: 'no_change',
reason:
'该行有待审核的改量申请,单位变更本次未上报(避免顶掉待审改量);改量审完后再改单位即可',
};
}
}
const clientRequestId = String(params.clientRequestId || '').trim() || randomUUID();
const requestedBy =
params.actor.requestedBy || `${params.branchCode}:${params.actor.roles || ''}:${params.actor.userId || ''}`;
// ⚠️ 顺序要紧:`uq_..._pending (branch_code, prep_id, kind) WHERE status='pending'` 是**部分唯一索引**,
// 旧 pending 行必须先删掉,否则新申请 INSERT 直接撞唯一键("同类型 pending 覆盖"就是这个语义)。
// 历史留在 operation_logs(下面写日志时带 replaced_pending)。
const replaced = await pool.query(
`DELETE FROM public.main_system_price_qty_requests
WHERE branch_code = $1 AND prep_id = $2 AND kind = $3 AND status = 'pending'
RETURNING proposed_price, proposed_qty, created_at`,
[params.branchCode, line.prepId, kind]
);
let row: PriceQtyRequestRow;
try {
const inserted = await pool.query<PriceQtyRequestRow>(
`INSERT INTO public.main_system_price_qty_requests
(branch_code, client_request_id, prep_id, main_order_code, our_order_code, our_order_item_id,
kind, before_price, before_qty, proposed_price, proposed_qty, unit, status, review_required,
reason, requested_by, item_name, main_sku_code)
VALUES ($1,$2,$3,$4,$5,$6::uuid,$7,$8,$9,$10,$11,$12,'pending',false,$13,$14,$15,$16)
RETURNING *`,
[
params.branchCode,
clientRequestId,
line.prepId,
line.mainOrderCode,
params.ourOrderCode,
params.ourOrderItemId,
kind,
beforePrice,
beforeQty,
priceChanged ? proposedPrice : beforePrice,
qtyChanged ? proposedQty : beforeQty,
// 单位变更时 `unit` 记**新单位**(台账"改了什么"一眼可见:数量未变 + 单位变了)
unitChanged ? proposedUnit : params.unit ? String(params.unit) : null,
params.reason ? String(params.reason).slice(0, 500) : null,
requestedBy,
// 商品名/SKU 落库:列表直接可读(不必回表);列表展示仍会优先用本方订单行的实时值
itemName || null,
current.rows[0].sku_code ? String(current.rows[0].sku_code) : null,
]
);
row = inserted.rows[0];
} catch (error: any) {
// 同一个 client_request_id 重放(前端重试/双击):返回既有申请,不重复排队、不重复上报
if (String(error?.code) === '23505') {
const existing = await pool.query<PriceQtyRequestRow>(
`SELECT * FROM public.main_system_price_qty_requests
WHERE branch_code = $1 AND client_request_id = $2
LIMIT 1`,
[params.branchCode, clientRequestId]
);
const found = existing.rows[0];
if (found) {
if (found.status === 'pending' || found.status === 'applied' || found.status === 'approved') {
return {
kind: 'ok',
row: found,
status: found.status === 'pending' ? 'pending' : 'applied',
reviewRequired: Boolean(found.review_required),
finalPrice: found.final_price,
finalQty: found.final_qty,
message: '重复提交:返回既有申请',
pendingFields: {},
appliedLocally: false,
applyNote: '重复提交命中既有申请,未重复上报主系统',
};
}
return {
kind: 'failed',
reason: found.decision_reason || '同一请求此前提交失败,请重新提交',
retryable: found.status === 'failed',
};
}
}
throw error;
}
/**
* 2026-10-27:出站用的 `supplier_code` 从**行级台账**解析(接入编码 ≠ 对方 supplier_code;
* 一家分公司可能同时接主系统 A/B/C 三家的货 ⇒ 每行各归各的供应商)。
* 解析不到 ⇒ 走既有失败通道(台账记 failed、可重试),**不猜**。
*/
const supplierCode = await resolveSupplierCodeForPrep({ branchCode: params.branchCode, prepId: line.prepId });
const outcome = supplierCode
? await submitMainSystemPriceQtyRequest({
supplierCode,
prepId: line.prepId,
proposedPrice: priceChanged ? proposedPrice : null,
// 单位变更 ⇒ 带"数量不变"的载体(见上方 unitOnly 说明)
proposedQty: qtyChanged ? proposedQty : carrierQty,
unit: unitChanged ? proposedUnit : params.unit ? String(params.unit) : null,
reason: params.reason ? String(params.reason) : null,
requestedBy,
clientRequestId,
})
: ({
kind: 'unavailable' as const,
reason: '该订单行找不到对应的主系统供应商绑定(分公司接入编码可能未被绑定),无法提交申请',
});
if (outcome.kind === 'not_supported' || outcome.kind === 'unavailable' || outcome.kind === 'not_configured') {
const updated = await pool.query<PriceQtyRequestRow>(
`UPDATE public.main_system_price_qty_requests
SET status = 'failed', decision_reason = $2, payload = $3::jsonb, updated_at = NOW()
WHERE id = $1::uuid RETURNING *`,
[row.id, outcome.reason, JSON.stringify({ submit: { kind: outcome.kind } })]
);
row = updated.rows[0] || row;
await writePriceQtyAuditLog({
branchCode: params.branchCode,
actor: params.actor,
operationType: 'main_system_price_qty_submit_failed',
row,
oldValue: { price: beforePrice, quantity: beforeQty },
newValue: { proposed_price: proposedPrice, proposed_qty: proposedQty, error: outcome.reason },
});
if (outcome.kind === 'not_supported') {
return { kind: 'main_system_not_ready', reason: outcome.reason };
}
return { kind: 'failed', reason: outcome.reason, retryable: true };
}
if (outcome.kind === 'rejected') {
/**
* ⚠️ 409 `pending_exists` 与"真被拒"要分开(2026-10-13):对方把「子系统改我方单位」改成走待审后,
* 该行已有别的待审就回 409,语义是"等一轮",不是"这次变更不行"。
* 台账仍落 `failed`(本轮确实没提交成功),但把冲突码透传给调用方(补发路径据此不计尝试)。
*/
const conflict = outcome.conflict;
const updated = await pool.query<PriceQtyRequestRow>(
`UPDATE public.main_system_price_qty_requests
SET status = 'failed', decision_reason = $2, payload = $3::jsonb, updated_at = NOW()
WHERE id = $1::uuid RETURNING *`,
[
row.id,
outcome.reason,
JSON.stringify({ submit: { kind: 'rejected', ...(conflict ? { conflict } : {}) } }),
]
);
row = updated.rows[0] || row;
await writePriceQtyAuditLog({
branchCode: params.branchCode,
actor: params.actor,
operationType: 'main_system_price_qty_submit_failed',
row,
oldValue: { price: beforePrice, quantity: beforeQty },
newValue: {
proposed_price: proposedPrice,
proposed_qty: proposedQty,
error: outcome.reason,
...(conflict ? { conflict } : {}),
},
});
return { kind: 'failed', reason: outcome.reason, retryable: false, ...(conflict ? { conflict } : {}) };
}
// 主系统已受理。⚠️ 关键(2026-10-11 按主系统回执 §4.4 校正):
// 一次提交可以**同时含免审项与需审项**(例如 补价=免审 + 加量=需审):
// 此时 `status='pending'`,但免审那部分**主系统已经写值了**,并在响应 `applied` 里给出。
// ⇒ 本地必须**立刻跟着落已生效的那部分**,不能整体当 pending 挂着(否则"主系统变了、我方没变");
// ⇒ 未决字段的 final_* 必须留空,**不得用 proposed 兜底**(否则"还没通过就变了")。
// 老版本/异常形态兜底:响应没有分解决策对象,但整体判为 applied ⇒ 顶层 final_* 就是已生效值
const appliedSide =
outcome.applied && Object.keys(outcome.applied).length
? outcome.applied
: outcome.status === 'applied'
? { ...(outcome.finalPrice !== null ? { price: outcome.finalPrice } : {}), ...(outcome.finalQty !== null ? { qty: outcome.finalQty } : {}) }
: {};
const appliedPrice = appliedSide.price ?? null;
const appliedQty = appliedSide.qty ?? null;
const pendingFields = outcome.pending ?? {};
const finalPrice = appliedPrice ?? null;
const finalQty = appliedQty ?? null;
const hasAppliedPart = appliedPrice !== null || appliedQty !== null;
const hasPendingPart = pendingFields.price !== undefined || pendingFields.qty !== undefined;
const updated = await pool.query<PriceQtyRequestRow>(
`UPDATE public.main_system_price_qty_requests
SET request_id = $2,
status = $3::varchar,
review_required = $4,
final_price = $5,
final_qty = $6,
decision_reason = $7,
payload = $8::jsonb,
decided_at = CASE WHEN $3::varchar = 'applied' THEN NOW() ELSE decided_at END,
decided_by = CASE WHEN $3::varchar = 'applied' THEN 'main_system' ELSE decided_by END,
updated_at = NOW()
WHERE id = $1::uuid RETURNING *`,
[
row.id,
outcome.requestId,
outcome.status,
outcome.reviewRequired,
finalPrice,
finalQty,
outcome.message,
JSON.stringify({
submit: outcome.raw ?? null,
mode: isPriceQtyLocalFirst() ? 'notify_only' : 'review_gated',
replaced_pending: replaced.rowCount || 0,
// 已决/未决字段留痕:对账与排障时一眼看清哪一项已生效、哪一项在审
decided_kinds: [appliedPrice !== null ? 'price' : null, appliedQty !== null ? 'qty' : null].filter(Boolean),
pending_kinds: Object.keys(pendingFields),
}),
]
);
row = updated.rows[0] || row;
let appliedLocally = false;
let applyNote: string | null = null;
/**
* ⚠️ 2026-10-12 口径:**先改后通知** ⇒ 我方值由**发起改动的入口**写,
* 这里不再按主系统结论写我们的库(否则会出现"两个写入者 + 谁后写谁赢")。
* 主系统"免审已生效"仅作为**通知已送达**的凭据记录在台账上。
*/
if (hasAppliedPart && !isPriceQtyLocalFirst()) {
// ⚠️ 一致性红线:主系统**已经生效**,本地必须跟上;落地失败时**不能让台账停在终态**
// (否则对账不再重试 ⇒ "主系统变了、我方没变"永久存在)。失败就把台账退回 pending 等待重试,
// 并把原因写进 decision_reason + 操作日志,前端按 applied_locally=false 提示"本地待同步"。
let applied: { changed: boolean; reason: string };
try {
applied = await applyFinalPriceQtyToOurOrderItem({
branchCode: params.branchCode,
ourOrderCode: params.ourOrderCode,
ourOrderItemId: params.ourOrderItemId,
finalPrice,
finalQty,
unit: params.unit ? String(params.unit) : null,
actor: params.actor,
});
} catch (error: unknown) {
const message = (error as Error)?.message || String(error);
const reverted = await pool.query<PriceQtyRequestRow>(
`UPDATE public.main_system_price_qty_requests
SET status = 'pending',
decision_reason = $2,
payload = COALESCE(payload, '{}'::jsonb) || $3::jsonb,
updated_at = NOW()
WHERE id = $1::uuid RETURNING *`,
[
row.id,
`主系统已生效,但本地落地失败,将自动重试:${message}`,
JSON.stringify({ apply_attempts: 1, apply_last_error: message }),
]
);
row = reverted.rows[0] || row;
await writePriceQtyAuditLog({
branchCode: params.branchCode,
actor: params.actor,
operationType: 'main_system_price_qty_apply_failed',
row,
oldValue: { price: beforePrice, quantity: beforeQty },
newValue: {
final_price: finalPrice,
final_qty: finalQty,
source: 'main_system_apply',
error: message,
retryable: true,
},
});
return {
kind: 'ok',
row,
status: 'applied',
reviewRequired: false,
finalPrice,
finalQty,
message: outcome.message,
pendingFields,
appliedLocally: false,
applyNote: `主系统已生效,本地落地失败(将自动重试):${message}`,
};
}
appliedLocally = applied.changed;
applyNote = applied.reason;
await writePriceQtyAuditLog({
branchCode: params.branchCode,
actor: params.actor,
operationType: 'main_system_price_qty_auto_applied',
row,
oldValue: { price: beforePrice, quantity: beforeQty },
newValue: {
final_price: finalPrice,
final_qty: finalQty,
proposed_price: proposedPrice,
proposed_qty: proposedQty,
review_required: false,
source: 'main_system_apply',
apply_note: applied.reason,
},
});
}
// 需审部分也要留日志:纯需审走 else;**混合(部分免审 + 部分需审)两条都写**
if (!hasAppliedPart || hasPendingPart) {
await writePriceQtyAuditLog({
branchCode: params.branchCode,
actor: params.actor,
operationType: 'main_system_price_qty_requested',
row,
oldValue: { price: beforePrice, quantity: beforeQty },
newValue: {
proposed_price: proposedPrice,
proposed_qty: proposedQty,
request_id: outcome.requestId,
review_required: true,
pending_kinds: Object.keys(pendingFields),
replaced_pending: replaced.rowCount || 0,
},
});
}
return {
kind: 'ok',
row,
status: outcome.status,
reviewRequired: outcome.reviewRequired,
// 只回"已决"的字段(未决字段为 null):前端据此判断哪一项已生效、哪一项仍在审
finalPrice,
finalQty,
pendingFields,
message: outcome.message,
appliedLocally,
applyNote,
};
}
/* ── 决策落地(webhook 与轮询共用)────────────────────────────────────────── */
export type DecisionOutcome = {
status: 'done' | 'ignored' | 'suspended';
reason: string;
requestRowId: string | null;
duplicate: boolean;
};
/**
* 把主系统的决策写进台账并(通过时)落地。
*
* ⚠️ **按字段(kind)决策**(2026-10-11 按主系统回执 §4.4 校正):
* 主系统一次提交若同时含改价与改量,会**按 kind 各推一条事件**(两条的 `request_id` **不同**,
* 各自只带自己那一侧的 `final_value`)。因此:
* · 只用 `kind` 决定**哪个字段**被本次事件决定,**绝不**给未决字段兜底 proposed(否则"还没通过就变了");
* · 行是 `both` 时,只有两个字段都被决定后才置终态;只决定了一个 ⇒ 台账保持 `pending`(但已决字段立即落地);
* · 幂等按**字段**判:同字段重复回传 ⇒ duplicate,不重复落地、不重复写日志。
*/
export async function decidePriceQtyRequest(params: {
row: PriceQtyRequestRow;
decision: 'applied' | 'approved' | 'rejected';
/** 本次事件决定的字段(主系统载荷 `kind`;缺失则由 final_price/final_qty 推断) */
kind?: 'price' | 'qty' | null;
finalPrice: number | null;
finalQty: number | null;
unit: string | null;
reviewer: string | null;
decidedAt: string | null;
reason: string | null;
source: 'webhook' | 'poll';
payload: unknown;
}): Promise<DecisionOutcome> {
const { row } = params;
const targetStatus: PriceQtyRequestStatus =
params.decision === 'rejected' ? 'rejected' : params.decision === 'applied' ? 'applied' : 'approved';
// 本次事件决定哪个字段:优先用载荷 kind;没有 kind 就看带了哪个 final 值
const decidedKind: 'price' | 'qty' | null =
params.kind === 'price' || params.kind === 'qty'
? params.kind
: params.finalPrice !== null && params.finalQty === null
? 'price'
: params.finalQty !== null && params.finalPrice === null
? 'qty'
: row.kind === 'both'
? null
: row.kind;
// 该行共有哪些字段需要决策(提交时改了哪些)
const expectedKinds: Array<'price' | 'qty'> =
row.kind === 'both' ? ['price', 'qty'] : [row.kind === 'qty' ? 'qty' : 'price'];
const decidedKinds: string[] = Array.isArray((row.payload as { decided_kinds?: unknown } | null)?.decided_kinds)
? ([...((row.payload as { decided_kinds: string[] }).decided_kinds as string[])] as string[])
: [];
// 幂等(按字段):本字段已决策过且结论一致 ⇒ 重复投递
if (decidedKind && decidedKinds.includes(decidedKind)) {
return {
status: 'done',
reason: `字段 ${decidedKind} 已决策过(幂等跳过)`,
requestRowId: row.id,
duplicate: true,
};
}
// 整体已终态(含升级前落的老行、以及"全部字段已决"的行):
// 同结论 ⇒ 重复投递;不同结论 ⇒ 忽略(绝不二次改账)
if (isTerminalStatus(row.status)) {
if (row.status === targetStatus) {
return { status: 'done', reason: '重复回传(幂等跳过)', requestRowId: row.id, duplicate: true };
}
return {
status: 'ignored',
reason: `申请已是终态 ${row.status},忽略本次 ${params.decision}(避免二次改账)`,
requestRowId: row.id,
duplicate: false,
};
}
// 未决字段保持原值(null 表示"尚未决定",**不兜底 proposed**)
const nextDecided = decidedKind ? [...new Set([...decidedKinds, decidedKind])] : decidedKinds;
const finalPrice =
decidedKind === 'price' ? params.finalPrice : (row.final_price ?? null);
const finalQty = decidedKind === 'qty' ? params.finalQty : (row.final_qty ?? null);
const allDecided = expectedKinds.every((k) => nextDecided.includes(k));
const nextStatus: PriceQtyRequestStatus = allDecided ? targetStatus : 'pending';
await pool.query(
`UPDATE public.main_system_price_qty_requests
SET status = $2::varchar,
final_price = $3,
final_qty = $4,
unit = COALESCE($5, unit),
decision_reason = $6,
decided_by = $7,
decided_at = CASE WHEN $2::varchar = 'pending' THEN decided_at ELSE COALESCE($8::timestamptz, NOW()) END,
payload = COALESCE(payload, '{}'::jsonb) || $9::jsonb,
updated_at = NOW()
WHERE id = $1::uuid`,
[
row.id,
nextStatus,
finalPrice,
finalQty,
params.unit,
params.reason,
params.reviewer,
params.decidedAt,
JSON.stringify({
[params.source]: params.payload ?? null,
decided_kinds: nextDecided,
...(allDecided ? {} : { awaiting_kinds: expectedKinds.filter((k) => !nextDecided.includes(k)) }),
}),
]
);
// 用最新状态参与后续落地判断(避免用旧行决定"未决字段")
row.payload = { ...((row.payload as Record<string, unknown>) || {}), decided_kinds: nextDecided };
row.final_price = finalPrice;
row.final_qty = finalQty;
row.status = nextStatus;
const actor: PriceQtyActor = {
userId: null,
roles: params.reviewer || 'main_system',
requestedBy: params.reviewer,
};
if (targetStatus === 'rejected') {
await writePriceQtyAuditLog({
branchCode: row.branch_code,
actor,
operationType: 'main_system_price_qty_rejected',
row,
oldValue: { price: row.before_price, quantity: row.before_qty },
newValue: {
proposed_price: row.proposed_price,
proposed_qty: row.proposed_qty,
reviewer: params.reviewer,
reason: params.reason,
source: params.source,
},
});
return {
status: 'done',
reason: `主系统驳回:${params.reason || '未给原因'}`,
requestRowId: row.id,
duplicate: false,
};
}
if (!row.our_order_item_id) {
return {
status: 'suspended',
reason: '台账缺我方订单行 id,最终值无法落地(等人工处理)',
requestRowId: row.id,
duplicate: false,
};
}
/**
* ⚠️ 2026-10-12 口径:**自己只能改自己的** ⇒ 主系统对我方申请的结论(通过/改值后通过)
* **不再覆盖我方已生效的值**,只记台账 + 留痕;若它的最终值与我方当前值不同,
* 记一条 `divergence` 痕迹(开发者选择"允许不一致,只留痕不提醒")。
*/
if (isPriceQtyLocalFirst()) {
const current = await readOurOrderItemPriceQty({
branchCode: row.branch_code,
ourOrderCode: row.our_order_code,
ourOrderItemId: String(row.our_order_item_id),
}).catch(() => null);
const priceDiffers =
finalPrice !== null && current?.price !== null && Math.abs(Number(current?.price) - finalPrice) > 1e-9;
const qtyDiffers =
finalQty !== null && current?.quantity !== null && Math.abs(Number(current?.quantity) - finalQty) > 1e-9;
await pool.query(
`UPDATE public.main_system_price_qty_requests
SET payload = COALESCE(payload, '{}'::jsonb) || jsonb_build_object(
'local_first', jsonb_build_object(
'at', NOW(), 'decision', $2::text, 'final_price', $3::numeric, 'final_qty', $4::numeric,
'our_price', $5::numeric, 'our_quantity', $6::numeric,
'divergence', $7::boolean
)
),
updated_at = NOW()
WHERE id = $1::uuid`,
[
row.id,
String(targetStatus),
finalPrice,
finalQty,
current?.price ?? null,
current?.quantity ?? null,
Boolean(priceDiffers || qtyDiffers),
]
);
await writePriceQtyAuditLog({
branchCode: row.branch_code,
actor,
operationType: priceDiffers || qtyDiffers
? 'main_system_price_qty_decision_diverged'
: 'main_system_price_qty_decision_recorded',
row,
oldValue: { price: current?.price ?? null, quantity: current?.quantity ?? null },
newValue: {
decision: targetStatus,
final_price: finalPrice,
final_qty: finalQty,
divergence: Boolean(priceDiffers || qtyDiffers),
source: params.source,
},
});
return {
status: 'done',
reason:
priceDiffers || qtyDiffers
? `已记录主系统结论(${targetStatus});其最终值与我方当前值不同,按"自己只能改自己的"**不覆盖我方值**(留痕)`
: `已记录主系统结论(${targetStatus});与我方当前值一致`,
requestRowId: row.id,
duplicate: false,
};
}
let applied: { changed: boolean; reason: string };
try {
applied = await applyFinalPriceQtyToOurOrderItem({
branchCode: row.branch_code,
ourOrderCode: row.our_order_code,
ourOrderItemId: String(row.our_order_item_id),
finalPrice,
finalQty,
unit: params.unit,
actor,
});
} catch (error: unknown) {
// ⚠️ 一致性红线:主系统已经定了(通过/免审生效),本地落地失败**不得**让台账停在终态,
// 否则对账不再重试 ⇒ "主系统变了、我方没变"永久存在。
// 处置:台账退回 pending 等待下一轮重试(带次数),连续失败到上限才标 failed 交人工。
const message = (error as Error)?.message || String(error);
const attempts = Number((row.payload as { apply_attempts?: unknown } | null)?.apply_attempts || 0) + 1;
const giveUp = attempts >= MAX_APPLY_ATTEMPTS;
const reason = giveUp
? `本地落地连续失败 ${attempts} 次,停止自动重试,需人工处理:${message}`
: `主系统已定(${targetStatus}),本地落地失败,将自动重试(第 ${attempts} 次):${message}`;
await pool.query(
`UPDATE public.main_system_price_qty_requests
SET status = $2,
decision_reason = $3,
payload = COALESCE(payload, '{}'::jsonb) || $4::jsonb,
updated_at = NOW()
WHERE id = $1::uuid`,
[
row.id,
giveUp ? 'failed' : 'pending',
reason,
JSON.stringify({ apply_attempts: attempts, apply_last_error: message }),
]
);
await writePriceQtyAuditLog({
branchCode: row.branch_code,
actor,
operationType: 'main_system_price_qty_apply_failed',
row,
oldValue: { price: row.before_price, quantity: row.before_qty },
newValue: {
final_price: finalPrice,
final_qty: finalQty,
source: params.source,
attempts,
retryable: !giveUp,
error: message,
},
});
return {
status: 'suspended',
reason,
requestRowId: row.id,
duplicate: false,
};
}
await writePriceQtyAuditLog({
branchCode: row.branch_code,
actor,
operationType:
targetStatus === 'applied' ? 'main_system_price_qty_auto_applied' : 'main_system_price_qty_approved',
row,
oldValue: { price: row.before_price, quantity: row.before_qty },
newValue: {
proposed_price: row.proposed_price,
proposed_qty: row.proposed_qty,
final_price: finalPrice,
final_qty: finalQty,
decided_kind: decidedKind,
decided_kinds: nextDecided,
awaiting_kinds: allDecided ? [] : expectedKinds.filter((k) => !nextDecided.includes(k)),
reviewer: params.reviewer,
source: params.source,
apply_note: applied.reason,
},
});
const waiting = expectedKinds.filter((k) => !nextDecided.includes(k));
return {
status: 'done',
reason: `${applied.changed ? applied.reason : `无需落地(${applied.reason})`}${
waiting.length ? `;仍在等主系统决策:${waiting.join('、')}` : ''
}`,
requestRowId: row.id,
duplicate: false,
};
}
/* ── webhook 接收(C3)──────────────────────────────────────────────────── */
export type OurRequestReconcileOutcome = {
pulled: number;
checked: number;
closed: number;
refreshed: number;
kept: number;
truncated: boolean;
reason?: string;
};
/**
* 主系统申请行状态 → 我方决策事件的 `decision`。
*
* ⚠️ 决策事件处理器只认 `approved` / `rejected` / `applied`(`withdrawn`/`superseded` 会被忽略),
* 所以"对方作废/撤回"映射为 **rejected + 写明原因**(`payload.decided_event.status` 留存真实状态),
* 避免出现"对账把行标成已关、实际没落地"的假成功。
*/
const OUR_REQUEST_TERMINAL: Record<string, { decision: 'approved' | 'rejected'; label: string }> = {
approved: { decision: 'approved', label: 'approved' },
applied: { decision: 'approved', label: 'applied' },
rejected: { decision: 'rejected', label: 'rejected' },
superseded: { decision: 'rejected', label: 'superseded' },
withdrawn: { decision: 'rejected', label: 'withdrawn' },
};
/**
* **我方发起**的价/量申请:用 Q6 只读接口与主系统对账(2026-10-12,开发者要求补齐反方向)。
*
* 为什么需要:我方第二次提交同一 prep 行的改动会**原地刷新他们那条 pending**(唯一键 `(preparation_id, kind, field)`),
* 但他们**不会**为"请求被刷新"推事件;若 `price_qty_decided` 漏推,我方台账会一直挂着 `pending`。
*
* 判定(保守):
* · 对方侧该 `request_id` 已终态 ⇒ **复用** `handlePriceQtyDecidedEvent`(按 Q6 行合成载荷)落地结论,幂等;
* · 对方侧仍是 `pending` 但 `proposed_value` 变了 ⇒ 刷新我方待审行的申请值(只动我们自己的视图);
* · 对方侧查不到 ⇒ 且拉取未截断、且超过宽限期 ⇒ 置 `failed`(理由"主系统侧已无此申请"),交人工。
*/
export async function reconcileOurPriceQtyRequestsWithMainSystem(params: {
branchCode: string;
graceMinutes?: number;
limit?: number;
}): Promise<OurRequestReconcileOutcome> {
const branchCode = String(params.branchCode || '').trim();
const empty: OurRequestReconcileOutcome = {
pulled: 0,
checked: 0,
closed: 0,
refreshed: 0,
kept: 0,
truncated: false,
};
if (!branchCode) return { ...empty, reason: '缺少分公司' };
/**
* **无未决 ⇒ 不拉**(2026-10-13 优化,P2):本函数只对**本地 `pending` 行**做对账
* (见下方 `pendingRows`),一条都没有时拉回来也没有东西可对 —— 却要为每个已连接分公司
* 每 10 分钟发一次 GET(对方是单体系统,几千家分公司规模下这是最大的一笔纯浪费)。
* 先查本地(1 条轻查询,走 `(branch_code, status, updated_at DESC)` 索引),为 0 直接返回,**一个请求都不发**。
*/
const localPending = await pool.query<{ n: number }>(
`SELECT count(*)::int AS n FROM public.main_system_price_qty_requests
WHERE branch_code = $1 AND status = 'pending'`,
[branchCode]
);
if (!Number(localPending.rows[0]?.n || 0)) {
return { ...empty, reason: '本分公司没有待审的价/量申请,跳过拉取' };
}
const pulled = await listRequestsForBranch(branchCode, { limit: params.limit });
if (pulled.kind !== 'ok') return { ...empty, reason: pulled.reason };
type TheirRequestState = {
kind: string;
status: string;
proposed: number | null;
final: number | null;
decidedAt: string | null;
reviewer: string | null;
message: string | null;
orderCode: string | null;
skuCode: string | null;
};
const theirs = new Map<string, TheirRequestState>(
pulled.rows
// ⚠️ **只认同链**:`actual_qty` 链的 request_id 不得被当成我方价/量申请的对端
//(两条链的台账不同,按 id 硬套会把核货量写成价格)。kind 必须是 price / qty。
.filter((row) => row.requestId && (row.kind === 'price' || row.kind === 'qty'))
.map((row): [string, TheirRequestState] => [
row.requestId,
{
kind: row.kind,
status: row.status,
proposed: row.proposedValue,
final: row.finalValue,
decidedAt: row.decidedAt,
reviewer: row.reviewedBy,
message: row.message,
orderCode: row.orderCode,
skuCode: row.skuCode,
},
])
);
// ⚠️ 我方价/量申请台账在 **public**(`public.main_system_price_qty_requests`),
// 2026-10-12 核查发现首版误写成 `supplier_price_qty_requests`(本库无此表)⇒ 整段对账静默失效。
const pendingRows = await pool.query<{
id: string;
request_id: string | null;
kind: string;
proposed_price: string | number | null;
proposed_qty: string | number | null;
created_at: string;
}>(
`SELECT id::text AS id, request_id, kind, proposed_price, proposed_qty, created_at
FROM public.main_system_price_qty_requests
WHERE branch_code = $1 AND status = 'pending'
ORDER BY created_at`,
[branchCode]
);
const graceMs = Math.max(0, Number(params.graceMinutes ?? 30)) * 60 * 1000;
let closed = 0;
let refreshed = 0;
let kept = 0;
for (const row of pendingRows.rows) {
const requestId = row.request_id ? String(row.request_id) : '';
const theirRaw = requestId ? theirs.get(requestId) : undefined;
// 对方行的 kind 必须与我方台账行一致(防跨链串行)
const their = theirRaw && theirRaw.kind === row.kind ? theirRaw : undefined;
if (their && OUR_REQUEST_TERMINAL[their.status]) {
/**
* ⚠️ 只有 `kind ∈ {price, qty}` 才能安全复用决策事件处理器:
* 处理器用 `kind` 决定把 `final_value` 落到价还是量;`both` 行在对方侧是**按字段拆行**的,
* 单条对方行给不出两个值 ⇒ 硬套会把另一个字段写成同一个数(错账)。`both` 交人工。
*/
if (row.kind !== 'price' && row.kind !== 'qty') {
kept += 1;
continue;
}
const mapped = OUR_REQUEST_TERMINAL[their.status];
const terminalValue = their.final ?? their.proposed ?? null;
// 复用既有决策事件处理器:它负责落值/留痕/幂等,避免在这里另写一套
await handlePriceQtyDecidedEvent({
branchCode,
payload: {
request_id: requestId,
client_request_id: null,
kind: row.kind,
decision: mapped.decision,
final_value: terminalValue,
final_price: row.kind === 'price' ? terminalValue : null,
final_qty: row.kind === 'qty' ? terminalValue : null,
reviewer: their.reviewer ?? null,
reviewed_by: their.reviewer ?? null,
reason:
mapped.label === their.status
? their.message ?? `对账落地:主系统侧已是 ${their.status}`
: `对账落地:主系统侧已${mapped.label === 'withdrawn' ? '撤回' : '作废'}(${their.status})${
their.message ? `:${their.message}` : ''
}`,
decided_at: their.decidedAt,
source: 'reconcile',
},
});
closed += 1;
continue;
}
if (their && their.status === 'pending') {
// 同理由:`both` 行在对方侧按字段拆行,单条 pending 行不足以刷新两个值 ⇒ 不动
if (row.kind !== 'price' && row.kind !== 'qty') {
kept += 1;
continue;
}
const ours = Number(row.kind === 'price' ? row.proposed_price : row.proposed_qty);
const changed =
their.proposed !== null &&
Number.isFinite(ours) &&
Math.abs(ours - Number(their.proposed)) > 1e-9;
if (!changed) {
kept += 1;
continue;
}
await pool.query(
`UPDATE public.main_system_price_qty_requests
SET proposed_price = CASE WHEN kind = 'price' THEN $3::numeric ELSE proposed_price END,
proposed_qty = CASE WHEN kind = 'qty' THEN $3::numeric ELSE proposed_qty END,
payload = COALESCE(payload, '{}'::jsonb) || jsonb_build_object(
'reconcile_refresh', jsonb_build_object(
'at', NOW(), 'prev_value', $4::numeric, 'to_value', $3::numeric, 'kind', kind
)
),
updated_at = NOW()
WHERE branch_code = $1 AND id = $2::uuid AND status = 'pending'`,
[branchCode, row.id, their.proposed, ours]
);
refreshed += 1;
continue;
}
if (pulled.truncated) {
kept += 1;
continue;
}
const createdMs = new Date(String(row.created_at)).getTime();
if (Number.isFinite(createdMs) && Date.now() - createdMs < graceMs) {
kept += 1;
continue;
}
await pool.query(
`UPDATE public.main_system_price_qty_requests
SET status = 'failed', decision_reason = $3, decided_at = NOW(),
payload = COALESCE(payload, '{}'::jsonb) || jsonb_build_object(
'reconcile', jsonb_build_object('at', NOW(), 'reason', $3::text)
),
updated_at = NOW()
WHERE branch_code = $1 AND id = $2::uuid AND status = 'pending'`,
[branchCode, row.id, '对账关闭:主系统侧已无此申请(历史遗留或已被清理)']
);
closed += 1;
}
return {
pulled: pulled.rows.length,
checked: pendingRows.rowCount || 0,
closed,
refreshed,
kept,
truncated: pulled.truncated,
};
}
export const PRICE_QTY_DECIDED_EVENT = 'preparations.price_qty_decided';
export function isPriceQtyDecidedEvent(event: unknown): boolean {
return String(event || '') === PRICE_QTY_DECIDED_EVENT;
}
/**
* 处理 `preparations.price_qty_decided`。
*
* 定位分公司的顺序:① 信封里的 `supplier_code`(推荐,主系统既有信封就有);
* ② 按 `request_id` 反查我方台账(主系统若不便带 supplier_code 也能兜住)。
* 业务失败**不抛错**(与履约事件同纪律):事件本身无法重放,重试由对账负责。
*/
export async function handlePriceQtyDecidedEvent(params: {
branchCode: string | null;
payload: any;
}): Promise<DecisionOutcome> {
const payload = params.payload || {};
/** 业务载荷里的 request_id = 主系统**申请行** id(与信封顶层同名的投递 id 不是一回事) */
const requestId = payload?.request_id != null ? String(payload.request_id) : null;
const prepId =
payload?.prep_id != null
? String(payload.prep_id)
: payload?.preparation_id != null
? String(payload.preparation_id)
: null;
/** 提交时我们生成的幂等键,主系统会回显 —— 一次提交拆多条事件时靠它稳定归到同一行台账 */
const clientRequestId = payload?.client_request_id != null ? String(payload.client_request_id) : null;
const rawKind = String(payload?.kind || '').toLowerCase();
const kind = rawKind === 'price' || rawKind === 'qty' ? (rawKind as 'price' | 'qty') : null;
const rawDecision = String(payload?.decision || '').toLowerCase();
const decision =
rawDecision === 'approved' ? 'approved' : rawDecision === 'rejected' ? 'rejected' : rawDecision === 'applied' ? 'applied' : null;
if (!decision) {
return { status: 'ignored', reason: `无法识别的 decision:${rawDecision || '(空)'}`, requestRowId: null, duplicate: false };
}
let branchCode = params.branchCode ? String(params.branchCode).trim() : '';
let row: PriceQtyRequestRow | null = null;
// ① 我方幂等键优先:主系统按 kind 拆多条事件时,每条都回显同一个 client_request_id ⇒ 稳定命中同一行
if (clientRequestId) {
const found = await pool.query(
`SELECT * FROM public.main_system_price_qty_requests
WHERE client_request_id = $1${branchCode ? ' AND branch_code = $2' : ''}
ORDER BY created_at DESC LIMIT 1`,
branchCode ? [clientRequestId, branchCode] : [clientRequestId]
);
row = (found.rows[0] as PriceQtyRequestRow) || null;
if (row) branchCode = row.branch_code;
}
if (!row && branchCode && requestId) {
const found = await pool.query(
`SELECT * FROM public.main_system_price_qty_requests
WHERE branch_code = $1 AND request_id = $2
ORDER BY created_at DESC LIMIT 1`,
[branchCode, requestId]
);
row = (found.rows[0] as PriceQtyRequestRow) || null;
}
if (!row && requestId) {
const found = await pool.query(
`SELECT * FROM public.main_system_price_qty_requests WHERE request_id = $1 ORDER BY created_at DESC LIMIT 1`,
[requestId]
);
row = (found.rows[0] as PriceQtyRequestRow) || null;
if (row) branchCode = row.branch_code;
}
if (!row && branchCode && prepId) {
const found = await pool.query(
`SELECT * FROM public.main_system_price_qty_requests
WHERE branch_code = $1 AND prep_id = $2
ORDER BY created_at DESC LIMIT 1`,
[branchCode, prepId]
);
row = (found.rows[0] as PriceQtyRequestRow) || null;
}
if (!row) {
return {
status: 'ignored',
reason: `找不到对应申请(request_id=${requestId || '—'},prep_id=${prepId || '—'})`,
requestRowId: null,
duplicate: false,
};
}
// 单一真值来源:`kind` + `final_value`(主系统两条事件各自只带自己那一侧)
const finalValue = num(payload?.final_value);
const finalPrice = kind === 'price' ? (finalValue ?? num(payload?.final_price)) : num(payload?.final_price);
const finalQty = kind === 'qty' ? (finalValue ?? num(payload?.final_qty)) : num(payload?.final_qty);
const outcome = await decidePriceQtyRequest({
row,
decision,
kind,
finalPrice,
finalQty,
unit: payload?.unit != null ? String(payload.unit) : null,
reviewer: payload?.reviewer != null ? String(payload.reviewer) : null,
decidedAt: payload?.decided_at != null ? String(payload.decided_at) : null,
reason: payload?.reason != null ? String(payload.reason) : null,
// 对账复用同一处理器 ⇒ 让来源如实落在台账/审计里(webhook 漏推时是靠 reconcile 补的)
source: String(payload?.source || '') === 'reconcile' ? 'poll' : 'webhook',
payload,
});
/**
* **单位变更的定向补发触发点**(2026-10-13,设计文 §11.8):
* 该行的价/量审核刚落定 ⇒ 若此前有"被跳过的单位变更意图",此刻补发一次(幂等)。
*
* ⚠️ 触发点放在本处理器里,而不是 webhook 路由:**Q6 对账也调用本处理器**
*(`reconcileOurPriceQtyRequestsWithMainSystem`),两条路径因此自动共用同一个补发入口。
* 补发失败**绝不影响**决策结论(结论已落库)。
*/
try {
const { flushDeferredUnitResendForPrep } = await import('./mainSystemUnitDeferredResend');
await flushDeferredUnitResendForPrep({
branchCode: row.branch_code,
prepId: row.prep_id,
trigger: 'decided',
/**
* 刚落定的那条台账行:用于判定"**单位载体被驳回** ⇒ 不再自动补发"(设计文 §11.10)。
* 单位载体的特征 = `kind='qty'` 且 `proposed_qty === before_qty`(数量不变,只改单位)。
*/
justDecided: {
status: String(row.status),
kind: String(row.kind),
proposedQty: row.proposed_qty,
beforeQty: row.before_qty,
},
});
} catch (error: unknown) {
console.error(
'[price-qty-decided] 单位变更补发失败(决策结论不变):',
(error as Error)?.message || error
);
}
return outcome;
}
/* ── 轮询兜底(C4)───────────────────────────────────────────────────────── */
/** 主系统既有 amend 状态(数值)→ 我方决策 */
function mapAmendStatus(status: number | null): 'approved' | 'rejected' | null {
if (status === MAIN_SYSTEM_AMEND_STATUS.approved) return 'approved';
if (status === MAIN_SYSTEM_AMEND_STATUS.rejected) return 'rejected';
return null;
}
/**
* 对账兜底(**仅覆盖旧 amend 视图**,见下)。
*
* ⚠️ 2026-10-11 按主系统回执 §六·1 核实:新流程(第四批)**没有**并入 `GET /preparations?view=price_amend`
* (那是旧 amend 的视图,主系统为隔离纪律有意不混)⇒ 这条轮询对**新流程的行无效**,
* 新流程的漏推自愈目前只能靠 webhook + 我方台账人工核对。
* 已向主系统提一条**可选**兜底接口(`GET /api/supplier/preparations/price-qty-requests`,见对接清单 Q5),
* 交付后把本函数改为调它即可(决策逻辑仍复用 `decidePriceQtyRequest`,不会分叉)。
*
* 现在保留它的用途:`request_id` 为空的历史行(提交中断/老版本)若能在 amend 视图里对上状态,仍可补齐。
* 为避免每次对账都白发一次请求:**只有存在"无 request_id 的 pending 行"时才去拉**。
*/
export async function reconcileMainSystemPriceQtyRequests(params: {
branchCode: string;
deliveryDate?: string | null;
}): Promise<{ checked: number; closed: number; failed: number; skipped: number; reason?: string }> {
if (!isEnabled()) return { checked: 0, closed: 0, failed: 0, skipped: 0, reason: 'disabled' };
const pending = await pool.query<PriceQtyRequestRow>(
`SELECT * FROM public.main_system_price_qty_requests
WHERE branch_code = $1 AND status = 'pending'
ORDER BY created_at DESC
LIMIT 200`,
[params.branchCode]
);
if (!pending.rowCount) return { checked: 0, closed: 0, failed: 0, skipped: 0 };
// 新流程的行都带 request_id(主系统必回);只有"无 request_id"的历史行才值得去拉旧 amend 视图
const legacyRows = pending.rows.filter((row) => !row.request_id);
if (!legacyRows.length) return { checked: pending.rowCount || 0, closed: 0, failed: 0, skipped: 0 };
/**
* 2026-10-27:旧 amend 视图也按**绑定的 supplier_code** 拉(用第一条历史行的台账归属解析;
* 取不到 ⇒ 本轮跳过,不拿分公司编码去冒充)。
*/
const legacyPrepId = legacyRows.find((row) => row.prep_id)?.prep_id;
const supplierCode = legacyPrepId
? await resolveSupplierCodeForPrep({ branchCode: params.branchCode, prepId: String(legacyPrepId) })
: null;
if (!supplierCode) {
return {
checked: pending.rowCount || 0,
closed: 0,
failed: 0,
skipped: legacyRows.length,
reason: '找不到该分公司可用的主系统供应商绑定,跳过旧 amend 对账',
};
}
const rows = await fetchMainSystemPriceAmendRows({
supplierCode,
deliveryDate: params.deliveryDate ?? null,
});
if (rows.kind !== 'ok') {
return { checked: pending.rowCount || 0, closed: 0, failed: 0, skipped: 0, reason: rows.reason };
}
const byPrepId = new Map(rows.rows.map((row) => [row.prepId, row]));
let closed = 0;
let failed = 0;
let skipped = 0;
for (const row of pending.rows) {
// 幽灵 pending:台账已落但主系统申请号为空(提交过程中进程崩溃/被中断)⇒ 永远匹配不上,
// 30 分钟后标 failed 让操作员重新提交,避免它一直显示"待审核"。
if (!row.request_id && Date.parse(row.created_at) < Date.now() - STALE_PENDING_MS) {
await pool.query(
`UPDATE public.main_system_price_qty_requests
SET status = 'failed',
decision_reason = '申请未提交到主系统(无申请号),请重新提交',
updated_at = NOW()
WHERE id = $1::uuid`,
[row.id]
);
failed += 1;
continue;
}
const main = byPrepId.get(String(row.prep_id));
const decision = mapAmendStatus(main?.amendRequest?.status ?? null);
if (!main || !decision) {
skipped += 1;
continue;
}
const outcome = await decidePriceQtyRequest({
row,
decision,
finalPrice: decision === 'approved' ? (main.amendRequest?.proposedPrice ?? main.purchasePrice) : null,
finalQty: decision === 'approved' ? (main.amendRequest?.proposedQty ?? main.prepareQty) : null,
unit: main.amendRequest?.proposedUnit ?? main.unit ?? null,
reviewer: 'main_system',
decidedAt: null,
reason: main.amendRequest?.reviewRemark ?? null,
source: 'poll',
payload: { view: 'price_amend', prep_id: main.prepId, amend_request: main.amendRequest },
});
if (outcome.status === 'done') closed += 1;
else if (outcome.status === 'suspended') failed += 1;
else skipped += 1;
}
return { checked: pending.rowCount || 0, closed, failed, skipped };
}
/** 供界面/路由复用:把一行台账裁剪成前端 DTO(不暴露 payload 全文) */
export function toPriceQtyRequestDto(row: PriceQtyRequestRow) {
return {
id: row.id,
request_id: row.request_id,
prep_id: row.prep_id,
main_order_code: row.main_order_code,
our_order_code: row.our_order_code,
our_order_item_id: row.our_order_item_id,
kind: row.kind,
item_name: row.item_name ?? null,
main_sku_code: row.main_sku_code ?? null,
before_price: row.before_price,
before_qty: row.before_qty,
proposed_price: row.proposed_price,
proposed_qty: row.proposed_qty,
final_price: row.final_price,
final_qty: row.final_qty,
unit: row.unit,
status: row.status,
review_required: row.review_required,
reason: row.reason,
decision_reason: row.decision_reason,
requested_by: row.requested_by,
decided_by: row.decided_by,
decided_at: row.decided_at,
created_at: row.created_at,
updated_at: row.updated_at,
};
}