- 报价单生效自动推销售价 → 配送成本价(台账+重试+rearm,映射优先) - 编辑生效单改价走内部审核(quote_sheet_change_requests) - 双向价格传递:A 提交配送商审核 / B 拉回并反查映射后写价、D3 回执 - SKU 映射:D4 字典推送、D5 完整拉取(截断不删)、只读本地副本 - 迁移登记 tenant_business_tables(三张租户表数组互相补齐,避免顺序敏感)
965 lines
37 KiB
TypeScript
965 lines
37 KiB
TypeScript
import { createHash, randomUUID } from 'node:crypto';
|
||
import { pool } from '../db';
|
||
import { runWithTenantDbContext } from './tenantDbContext';
|
||
import {
|
||
submitQuoteCostSync,
|
||
type QuoteCostSyncFailure,
|
||
type QuoteCostSyncItemPayload,
|
||
type QuoteCostSyncOutcome,
|
||
} from './mainSystem/api/quoteCostSync';
|
||
|
||
/**
|
||
* 报价单销售价 → 主系统报价单成本价:**推送端**(我方推、主系统收)。
|
||
*
|
||
* 设计:docs/design/20261018-报价单成本价同步推送.md(冻结契约 2026-10-18)
|
||
*
|
||
* 口径(做反就要返工):
|
||
* · 触发:报价单**审批生效之后**(`approval_status→30` 且 `status→1`),且必须**事务提交之后**;
|
||
* · 目标:该单绑定的客户里 `customer_code = MAIN_<主系统分公司码>` 的那个码 ⇒ **按分公司各推一次**;
|
||
* 非 `MAIN_` 形态(真实客户 / `__INDEPENDENT_INBOUND__` / `__RETAIL__` 哨兵)一律跳过,记 `not_usage_company`;
|
||
* · 内容:该单明细 `sku_code` / `unit` / `sale_price ?? price`,只推 `sale_price > 0` 的行;
|
||
* · 幂等:台账唯一键 `(quote_sheet_code, main_branch_code)` ⇒ 一张单 × 一个分公司只推一次;
|
||
* 重试**复用同一 `client_request_id`**(对方按请求号幂等);只有对方**明确回 409** 时才换新号;
|
||
* · 改价重推(R-2):重触发时若明细指纹变了 ⇒ 复用台账行 + 换新请求号 + attempts 归零 + 立即重推;
|
||
* 指纹没变 ⇒ 仍是 `duplicate` 零出站;
|
||
* · 出站:只走 `mainSystem/http.ts` + `mainSystem/api/quoteCostSync.ts`(不新造 HTTP 客户端、不拼 URL);
|
||
* · 开关:`MAIN_SYSTEM_QUOTE_COST_SYNC`(默认关)—— 关时**不查库、不出站**;
|
||
* · 事务纪律:**出网 HTTP 永远在数据库事务之外**;任何失败都不得冒泡到审批路径。
|
||
*/
|
||
|
||
/**
|
||
* 客户码 → 主系统分公司码(唯一形态;`__*__` 哨兵与真实客户都不匹配)。
|
||
* 前缀 `MAIN_` **大小写不敏感**:客户档案里的 `main_br002` / `Main_BR002` 与 `MAIN_BR002`
|
||
* 是同一个"使用公司占位客户",不能因为前缀大小写被当成"非使用公司"跳过(A2)。
|
||
*/
|
||
export const MAIN_BRANCH_CUSTOMER_RE = /^MAIN_([0-9A-Za-z_-]{1,32})$/i;
|
||
|
||
/** 对方 `items` 硬上限(超过整单跳过,不做截断/分批:部分成功会让对账说不清) */
|
||
export const QUOTE_COST_SYNC_MAX_ITEMS = 2000;
|
||
|
||
/** 台账 `attempts` 上限:到这就不再加自动重试(等人工) */
|
||
export const QUOTE_COST_SYNC_MAX_ATTEMPTS = 5;
|
||
|
||
/** 整单级跳过用的伪分公司码(不是真实 MAIN_ 码,不会与真实行冲突) */
|
||
const SHEET_LEVEL_BRANCH = '*';
|
||
|
||
function text(value: unknown): string {
|
||
return value === null || value === undefined ? '' : String(value).trim();
|
||
}
|
||
|
||
/**
|
||
* 总开关。默认关;`1` / `true` / `on`(大小写不敏感)为开。
|
||
*
|
||
* ⚠️ 与 `mainSystemReportPushService.isReportPushEnabled()` 同款:直接读 `process.env`,
|
||
* 不经 `config.mainSystemIntegration` —— 这样"关"就是逐字节回到改造前。
|
||
*/
|
||
export function isQuoteCostSyncEnabled(): boolean {
|
||
const raw = text(process.env.MAIN_SYSTEM_QUOTE_COST_SYNC).toLowerCase();
|
||
return raw === '1' || raw === 'true' || raw === 'on';
|
||
}
|
||
|
||
/**
|
||
* 客户码 → 主系统分公司码(`MAIN_BR002` ⇒ `BR002`);非该形态返回 null。
|
||
* 前缀大小写归一在 `MAIN_BRANCH_CUSTOMER_RE` 的 `i` 上,捕获组再 UPPER(对方分公司码是 `BRxxx`)。
|
||
*/
|
||
export function parseMainBranchCode(customerCode: unknown): string | null {
|
||
const code = text(customerCode);
|
||
const match = MAIN_BRANCH_CUSTOMER_RE.exec(code);
|
||
return match ? match[1].toUpperCase() : null;
|
||
}
|
||
|
||
/** 单位归一:trim 后 1~20 字符才带;否则带 null(对方按 `skus.unit` 比) */
|
||
export function normalizeQuoteCostSyncUnit(unit: unknown): string | null {
|
||
const value = text(unit);
|
||
return value && value.length <= 20 ? value : null;
|
||
}
|
||
|
||
/** 明细行售价:`sale_price ?? price`,只认有限且 > 0 的值;其余返回 null(记 `source_price_missing`) */
|
||
export function readQuoteCostSyncSalePrice(row: {
|
||
sale_price?: unknown;
|
||
price?: unknown;
|
||
}): number | null {
|
||
const raw = row?.sale_price ?? row?.price;
|
||
if (raw === null || raw === undefined || raw === '') return null;
|
||
const value = Number(raw);
|
||
if (!Number.isFinite(value) || value <= 0) return null;
|
||
// 落库是 DECIMAL(10,2) ⇒ 这里按 2 位小数归一,保证同一份输入得到同一份 payload
|
||
return Math.round(value * 100) / 100;
|
||
}
|
||
|
||
function isoOrNull(value: unknown): string | null {
|
||
if (value === null || value === undefined || value === '') return null;
|
||
const date = value instanceof Date ? value : new Date(String(value));
|
||
return Number.isFinite(date.getTime()) ? date.toISOString() : null;
|
||
}
|
||
|
||
export type QuoteCostSyncSkip = {
|
||
reason: string;
|
||
customer_code?: string;
|
||
sku_code?: string;
|
||
detail?: string;
|
||
};
|
||
|
||
export type QuoteCostSyncPlan = {
|
||
branchCode: string;
|
||
quoteSheetCode: string;
|
||
/** 报价单是否存在(不存在 ⇒ 整单跳过 `quote_sheet_not_found`) */
|
||
sheetExists: boolean;
|
||
/** 是否是"生效中"的单(`approval_status=30 && status=1 && 未过期`) */
|
||
isActive: boolean;
|
||
/** 仅溯源:`effective_at ?? approved_at` */
|
||
activatedAt: string | null;
|
||
/** 该单绑定的全部客户码(原样) */
|
||
customerCodes: string[];
|
||
/** `MAIN_<X>` 解析出的主系统分公司码(去重、升序) */
|
||
mainBranchCodes: string[];
|
||
supplierCode: string | null;
|
||
/** 要推的明细(已过滤 `sale_price > 0`) */
|
||
items: QuoteCostSyncItemPayload[];
|
||
/** 本地跳过明细(审计/排障用;对方回执里的 skipped 另存) */
|
||
skipped: QuoteCostSyncSkip[];
|
||
/** 过滤前的明细行数(超限判断与留痕) */
|
||
itemRowCount: number;
|
||
};
|
||
|
||
export type QuoteCostSyncPushRowResult = {
|
||
mainBranchCode: string;
|
||
/** duplicate = 台账已有行(一张单一个分公司只推一次,重试交给定时任务) */
|
||
status: 'sent' | 'failed' | 'forbidden' | 'skipped' | 'duplicate';
|
||
clientRequestId?: string;
|
||
error?: string;
|
||
replayed?: boolean;
|
||
};
|
||
|
||
export type QuoteCostSyncPushSummary = {
|
||
branchCode: string;
|
||
quoteSheetCode: string;
|
||
/** 本次**首次**落台账并出站的分公司数 */
|
||
attempted: number;
|
||
sent: number;
|
||
failed: number;
|
||
forbidden: number;
|
||
skipped: number;
|
||
/** 台账已有行而未出站的数(幂等命中) */
|
||
duplicates: number;
|
||
/** 明细变了 ⇒ 复用台账行换新请求号后**重推**的数(R-2) */
|
||
rearmed: number;
|
||
/** 一张单多个客户同名分公司时的明细条数(排障用) */
|
||
itemCount: number;
|
||
results: QuoteCostSyncPushRowResult[];
|
||
error?: string;
|
||
};
|
||
|
||
function emptySummary(branchCode = '', quoteSheetCode = ''): QuoteCostSyncPushSummary {
|
||
return {
|
||
branchCode,
|
||
quoteSheetCode,
|
||
attempted: 0,
|
||
sent: 0,
|
||
failed: 0,
|
||
forbidden: 0,
|
||
skipped: 0,
|
||
duplicates: 0,
|
||
rearmed: 0,
|
||
itemCount: 0,
|
||
results: [],
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 该分公司在主系统的**供应商编码**(换 token 用):
|
||
* ① `public.main_supplier_bindings`(active,权威在主系统侧,镜像在此)优先;
|
||
* ② 退到 `public.branches.main_supplier_code`(超管手工登记 / 历史回填)。
|
||
* 两者都空 ⇒ `null`(调用方记 failed,等人工补绑定)。
|
||
*/
|
||
export async function resolveMainSupplierCode(branchCode: string): Promise<string | null> {
|
||
const result = await pool.query<{ code: string | null }>(
|
||
`SELECT COALESCE(
|
||
(SELECT NULLIF(TRIM(main_supplier_code), '')
|
||
FROM public.main_supplier_bindings
|
||
WHERE branch_code = $1 AND status = 'active'
|
||
AND NULLIF(TRIM(main_supplier_code), '') IS NOT NULL
|
||
ORDER BY bound_at DESC
|
||
LIMIT 1),
|
||
(SELECT NULLIF(TRIM(main_supplier_code), '')
|
||
FROM public.branches
|
||
WHERE branch_code = $1),
|
||
NULL
|
||
) AS code`,
|
||
[branchCode]
|
||
);
|
||
return text(result.rows[0]?.code) || null;
|
||
}
|
||
|
||
/**
|
||
* 采集"该推什么":报价单(必须生效中)→ 绑定客户 → `MAIN_` 分公司 → 明细。
|
||
*
|
||
* ⚠️ 只读;必须在**租户上下文**内调用(报价单三张表在租户 schema 里)。
|
||
*/
|
||
export async function collectQuoteCostSyncPlan(input: {
|
||
branchCode: string;
|
||
quoteSheetCode: string;
|
||
}): Promise<QuoteCostSyncPlan> {
|
||
const branchCode = text(input.branchCode);
|
||
const quoteSheetCode = text(input.quoteSheetCode);
|
||
const plan: QuoteCostSyncPlan = {
|
||
branchCode,
|
||
quoteSheetCode,
|
||
sheetExists: false,
|
||
isActive: false,
|
||
activatedAt: null,
|
||
customerCodes: [],
|
||
mainBranchCodes: [],
|
||
supplierCode: null,
|
||
items: [],
|
||
skipped: [],
|
||
itemRowCount: 0,
|
||
};
|
||
if (!branchCode || !quoteSheetCode) return plan;
|
||
|
||
const sheetResult = await pool.query<{
|
||
quote_sheet_code: string;
|
||
branch_code: string | null;
|
||
status: number;
|
||
approval_status: number;
|
||
approved_at: Date | null;
|
||
effective_at: Date | null;
|
||
expires_at: Date | null;
|
||
}>(
|
||
`SELECT quote_sheet_code, branch_code, status, approval_status, approved_at, effective_at, expires_at
|
||
FROM customer_quote_sheets
|
||
WHERE quote_sheet_code = $1`,
|
||
[quoteSheetCode]
|
||
);
|
||
const sheet = sheetResult.rows[0];
|
||
if (!sheet) return plan;
|
||
plan.sheetExists = true;
|
||
plan.activatedAt = isoOrNull(sheet.effective_at ?? sheet.approved_at);
|
||
plan.isActive =
|
||
Number(sheet.approval_status) === 30 &&
|
||
Number(sheet.status) === 1 &&
|
||
(!sheet.expires_at || new Date(sheet.expires_at).getTime() > Date.now());
|
||
|
||
const [customersResult, itemsResult, supplierCode] = await Promise.all([
|
||
pool.query<{ customer_code: string }>(
|
||
`SELECT customer_code FROM customer_quote_sheet_customers
|
||
WHERE quote_sheet_code = $1
|
||
ORDER BY customer_code ASC`,
|
||
[quoteSheetCode]
|
||
),
|
||
pool.query<{ sku_code: string; unit: string | null; sale_price: string | null; price: string | null }>(
|
||
`SELECT sku_code, unit, sale_price, price
|
||
FROM customer_quote_sheet_items
|
||
WHERE quote_sheet_code = $1
|
||
ORDER BY sort_order ASC, sku_code ASC`,
|
||
[quoteSheetCode]
|
||
),
|
||
resolveMainSupplierCode(branchCode),
|
||
]);
|
||
plan.supplierCode = supplierCode;
|
||
|
||
const mainBranchCodes = new Set<string>();
|
||
for (const row of customersResult.rows) {
|
||
const customerCode = text(row.customer_code);
|
||
if (!customerCode) continue;
|
||
plan.customerCodes.push(customerCode);
|
||
const mainBranchCode = parseMainBranchCode(customerCode);
|
||
if (mainBranchCode) mainBranchCodes.add(mainBranchCode);
|
||
else plan.skipped.push({ reason: 'not_usage_company', customer_code: customerCode });
|
||
}
|
||
plan.mainBranchCodes = [...mainBranchCodes].sort();
|
||
|
||
for (const row of itemsResult.rows) {
|
||
const skuCode = text(row.sku_code);
|
||
if (!skuCode) continue;
|
||
plan.itemRowCount += 1;
|
||
const salePrice = readQuoteCostSyncSalePrice(row);
|
||
if (salePrice === null) {
|
||
plan.skipped.push({ reason: 'source_price_missing', sku_code: skuCode });
|
||
continue;
|
||
}
|
||
plan.items.push({
|
||
sku_code: skuCode,
|
||
unit: normalizeQuoteCostSyncUnit(row.unit),
|
||
sale_price: salePrice,
|
||
});
|
||
}
|
||
return plan;
|
||
}
|
||
|
||
/** 写一条台账(唯一键命中则忽略;返回是否真的插入) */
|
||
async function insertLedger(input: {
|
||
branchCode: string;
|
||
quoteSheetCode: string;
|
||
mainBranchCode: string;
|
||
clientRequestId: string;
|
||
status: 'pending' | 'failed' | 'skipped';
|
||
lastError?: string | null;
|
||
response?: unknown;
|
||
}): Promise<{ id: string; clientRequestId: string } | null> {
|
||
const result = await pool.query<{ id: string; client_request_id: string }>(
|
||
`INSERT INTO public.main_system_quote_cost_pushes
|
||
(branch_code, quote_sheet_code, main_branch_code, client_request_id, status, last_error, response)
|
||
VALUES ($1, $2, $3, $4::uuid, $5::varchar, $6::text, $7::jsonb)
|
||
ON CONFLICT (quote_sheet_code, main_branch_code) DO NOTHING
|
||
RETURNING id::text AS id, client_request_id::text AS client_request_id`,
|
||
[
|
||
input.branchCode,
|
||
input.quoteSheetCode,
|
||
input.mainBranchCode,
|
||
input.clientRequestId,
|
||
input.status,
|
||
input.lastError ?? null,
|
||
input.response === undefined || input.response === null ? null : JSON.stringify(input.response),
|
||
]
|
||
);
|
||
const row = result.rows[0];
|
||
if (!row) return null;
|
||
return { id: String(row.id), clientRequestId: String(row.client_request_id) };
|
||
}
|
||
|
||
/** 回写台账结果(attempts 每次出站都 +1,成功也计数) */
|
||
async function markLedger(
|
||
id: string,
|
||
patch: {
|
||
status: 'sent' | 'failed' | 'forbidden' | 'skipped';
|
||
lastError?: string | null;
|
||
response?: unknown;
|
||
}
|
||
): Promise<void> {
|
||
await pool.query(
|
||
`UPDATE public.main_system_quote_cost_pushes
|
||
SET status = $2::varchar,
|
||
attempts = attempts + 1,
|
||
last_error = $3::text,
|
||
response = $4::jsonb,
|
||
updated_at = NOW()
|
||
WHERE id = $1::uuid`,
|
||
[
|
||
id,
|
||
patch.status,
|
||
patch.lastError ?? null,
|
||
patch.response === undefined || patch.response === null ? null : JSON.stringify(patch.response),
|
||
]
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 明细指纹:只跟"会发出去的内容"有关(`sku_code` / `unit` / `sale_price`,按 sku+unit 排序后 sha256)。
|
||
*
|
||
* 用途(R-2):重触发时拿它跟台账里**最近一次推送的指纹**比对 —— 变了才换号重推,没变仍然零出站。
|
||
* 排序是为了让"只是明细顺序变了"不算改价(payload 语义与顺序无关)。
|
||
*/
|
||
export function quoteCostSyncItemsFingerprint(items: QuoteCostSyncItemPayload[]): string {
|
||
const canonical = (items || [])
|
||
.map((item) => [
|
||
String(item?.sku_code || ''),
|
||
item?.unit === null || item?.unit === undefined ? '' : String(item.unit),
|
||
(Number(item?.sale_price) || 0).toFixed(2),
|
||
])
|
||
.sort((a, b) => {
|
||
if (a[0] !== b[0]) return a[0] < b[0] ? -1 : 1;
|
||
if (a[1] !== b[1]) return a[1] < b[1] ? -1 : 1;
|
||
return a[2] < b[2] ? -1 : a[2] > b[2] ? 1 : 0;
|
||
});
|
||
return createHash('sha256').update(JSON.stringify(canonical)).digest('hex');
|
||
}
|
||
|
||
/** 本地跳过明细(截断,避免 2000 行零价把回执撑大;计数另给)+ 明细指纹 */
|
||
function localTrace(
|
||
plan: QuoteCostSyncPlan,
|
||
extra?: Record<string, unknown>
|
||
): Record<string, unknown> {
|
||
const counts: Record<string, number> = {};
|
||
for (const row of plan.skipped) counts[row.reason] = (counts[row.reason] || 0) + 1;
|
||
return {
|
||
skipped_counts: counts,
|
||
skipped: plan.skipped.slice(0, 50),
|
||
item_row_count: plan.itemRowCount,
|
||
pushed_item_count: plan.items.length,
|
||
items_fingerprint: quoteCostSyncItemsFingerprint(plan.items),
|
||
...(extra || {}),
|
||
};
|
||
}
|
||
|
||
/** 台账里"一张单 × 一个分公司"的当前快照(判重 / 改价重推都以它为准) */
|
||
type LedgerSnapshot = {
|
||
id: string;
|
||
status: string;
|
||
attempts: number;
|
||
clientRequestId: string;
|
||
response: unknown;
|
||
};
|
||
|
||
async function readLedgerRow(
|
||
quoteSheetCode: string,
|
||
mainBranchCode: string
|
||
): Promise<LedgerSnapshot | null> {
|
||
const result = await pool.query<{
|
||
id: string;
|
||
status: string;
|
||
attempts: number;
|
||
client_request_id: string;
|
||
response: unknown;
|
||
}>(
|
||
`SELECT id::text AS id,
|
||
status,
|
||
attempts,
|
||
client_request_id::text AS client_request_id,
|
||
response
|
||
FROM public.main_system_quote_cost_pushes
|
||
WHERE quote_sheet_code = $1 AND main_branch_code = $2`,
|
||
[quoteSheetCode, mainBranchCode]
|
||
);
|
||
const row = result.rows[0];
|
||
if (!row) return null;
|
||
return {
|
||
id: String(row.id),
|
||
status: String(row.status),
|
||
attempts: Number(row.attempts) || 0,
|
||
clientRequestId: String(row.client_request_id),
|
||
response: row.response,
|
||
};
|
||
}
|
||
|
||
/** 台账里**最近一次推送**的明细指纹(没有记录 ⇒ null:老行/未推送过,按"不确定"处理,不动它) */
|
||
export function readPushedFingerprint(response: unknown): string | null {
|
||
const local = (response as { local?: unknown } | null)?.local;
|
||
if (!local || typeof local !== 'object') return null;
|
||
const value = (local as Record<string, unknown>).items_fingerprint;
|
||
return typeof value === 'string' && value ? value : null;
|
||
}
|
||
|
||
/** 对方是否**明确回 409** 幂等冲突(只有这一条路径允许换请求号) */
|
||
function isPayloadConflict(outcome: QuoteCostSyncOutcome): outcome is QuoteCostSyncFailure {
|
||
return outcome.kind === 'rejected' && Number(outcome.status) === 409;
|
||
}
|
||
|
||
/**
|
||
* R-2 ①:对方明确回 409 ⇒ 该台账行**换新请求号**、`attempts=0`、`status='failed'`,下一轮重试用新号。
|
||
*
|
||
* 为什么只在这一条路径换号:换号会让对方"全新的请求",若在超时/5xx/网络故障时也换号,
|
||
* 就可能把"对方其实已受理的旧请求"再写一次(重复写成本价)。409 则相反:对方明确说这个号已用于**别的内容**,
|
||
* 不换号就永远推不出去。
|
||
*/
|
||
async function rotateLedgerRequestId(id: string, detail: string): Promise<string | null> {
|
||
const result = await pool.query<{ client_request_id: string }>(
|
||
`UPDATE public.main_system_quote_cost_pushes
|
||
SET client_request_id = $2::uuid,
|
||
attempts = 0,
|
||
status = 'failed',
|
||
last_error = 'payload_changed_rotate_id',
|
||
response = COALESCE(response, '{}'::jsonb)
|
||
|| jsonb_build_object('last_conflict_409', $3::text),
|
||
updated_at = NOW()
|
||
WHERE id = $1::uuid
|
||
RETURNING client_request_id::text AS client_request_id`,
|
||
[id, randomUUID(), detail]
|
||
);
|
||
const row = result.rows[0];
|
||
return row ? String(row.client_request_id) : null;
|
||
}
|
||
|
||
/**
|
||
* R-2 ②:明细变了 ⇒ 复用现有台账行、**换新请求号**、`attempts` 归零、重新入队(`status='pending'`),
|
||
* 并打上 `response.local.sheet_reason='rearmed_after_change'`。
|
||
*
|
||
* 为什么必须换号:旧号在对方那儿已经绑定了旧 payload,继续用同一号重放只会一直 409。
|
||
*/
|
||
async function rearmLedger(
|
||
id: string,
|
||
fingerprint: string
|
||
): Promise<{ id: string; clientRequestId: string } | null> {
|
||
const result = await pool.query<{ id: string; client_request_id: string }>(
|
||
`UPDATE public.main_system_quote_cost_pushes
|
||
SET client_request_id = $2::uuid,
|
||
attempts = 0,
|
||
status = 'pending',
|
||
last_error = 'rearmed_after_change',
|
||
response = COALESCE(response, '{}'::jsonb)
|
||
|| jsonb_build_object(
|
||
'local',
|
||
COALESCE(response->'local', '{}'::jsonb)
|
||
|| jsonb_build_object(
|
||
'sheet_reason', 'rearmed_after_change',
|
||
'items_fingerprint', $3::text
|
||
)
|
||
),
|
||
updated_at = NOW()
|
||
WHERE id = $1::uuid
|
||
RETURNING id::text AS id, client_request_id::text AS client_request_id`,
|
||
[id, randomUUID(), fingerprint]
|
||
);
|
||
const row = result.rows[0];
|
||
if (!row) return null;
|
||
return { id: String(row.id), clientRequestId: String(row.client_request_id) };
|
||
}
|
||
|
||
/** 出站结果 → 台账状态 */
|
||
function mapOutcome(outcome: QuoteCostSyncOutcome): {
|
||
status: 'sent' | 'failed' | 'forbidden';
|
||
lastError: string | null;
|
||
response?: unknown;
|
||
} {
|
||
if (outcome.kind === 'ok') {
|
||
return { status: 'sent', lastError: null, response: { data: outcome.data } };
|
||
}
|
||
const detail = `${outcome.code}: ${outcome.reason}`.trim();
|
||
if (outcome.kind === 'rejected' && Number(outcome.status) === 403) {
|
||
return { status: 'forbidden', lastError: detail };
|
||
}
|
||
return { status: 'failed', lastError: detail };
|
||
}
|
||
|
||
function countByStatus(summary: QuoteCostSyncPushSummary, row: QuoteCostSyncPushRowResult): void {
|
||
summary.results.push(row);
|
||
if (row.status === 'duplicate') summary.duplicates += 1;
|
||
else summary.attempted += 1;
|
||
if (row.status === 'sent') summary.sent += 1;
|
||
else if (row.status === 'failed') summary.failed += 1;
|
||
else if (row.status === 'forbidden') summary.forbidden += 1;
|
||
else if (row.status === 'skipped') summary.skipped += 1;
|
||
}
|
||
|
||
/**
|
||
* 单分公司:判重 → (必要时换号重推)→ 落 pending → 出站 → 回写。
|
||
*
|
||
* 判重口径(R-2 ②):
|
||
* · 台账无行 ⇒ 正常首推;
|
||
* · 台账有行且**明细指纹与最近一次推送一致** ⇒ `duplicate`(幂等,零出站);
|
||
* · 台账有行但**指纹变了**(改价后再触发)⇒ 复用该行 + 换新请求号 + attempts 归零 + 立即重推;
|
||
* · 台账有行但**没有指纹记录**(理论上只有升级前的行/从未推送过的行)⇒ 按 `duplicate` 保守处理,
|
||
* 交给定时重试(`failed && attempts<5` / 卡住的 `pending`)去收口。
|
||
*/
|
||
async function pushOneBranch(input: {
|
||
plan: QuoteCostSyncPlan;
|
||
mainBranchCode: string;
|
||
existing: LedgerSnapshot | null;
|
||
}): Promise<{ row: QuoteCostSyncPushRowResult; rearmed: boolean }> {
|
||
const { plan, mainBranchCode, existing } = input;
|
||
const fingerprint = quoteCostSyncItemsFingerprint(plan.items);
|
||
let ledger: { id: string; clientRequestId: string };
|
||
let rearmed = false;
|
||
|
||
if (existing) {
|
||
const previousFingerprint = readPushedFingerprint(existing.response);
|
||
if (!previousFingerprint || previousFingerprint === fingerprint) {
|
||
// 一张单 × 一个分公司只推一次(失败重试由 scheduledJobs 负责,不在这里推)
|
||
return { row: { mainBranchCode, status: 'duplicate' }, rearmed: false };
|
||
}
|
||
const rearmedRow = await rearmLedger(existing.id, fingerprint);
|
||
if (!rearmedRow) return { row: { mainBranchCode, status: 'duplicate' }, rearmed: false };
|
||
ledger = rearmedRow;
|
||
rearmed = true;
|
||
} else {
|
||
const clientRequestId = randomUUID();
|
||
const inserted = await insertLedger({
|
||
branchCode: plan.branchCode,
|
||
quoteSheetCode: plan.quoteSheetCode,
|
||
mainBranchCode,
|
||
clientRequestId,
|
||
status: 'pending',
|
||
response: { local: localTrace(plan) },
|
||
});
|
||
if (!inserted) {
|
||
// 并发下被别人抢先插入(唯一键命中)⇒ 按幂等命中处理
|
||
return { row: { mainBranchCode, status: 'duplicate' }, rearmed: false };
|
||
}
|
||
ledger = inserted;
|
||
}
|
||
|
||
const local = localTrace(plan, rearmed ? { sheet_reason: 'rearmed_after_change' } : undefined);
|
||
|
||
let outcome: QuoteCostSyncOutcome;
|
||
try {
|
||
outcome = await submitQuoteCostSync({
|
||
supplierCode: String(plan.supplierCode || ''),
|
||
body: {
|
||
client_request_id: ledger.clientRequestId,
|
||
supplier_quote_sheet_code: plan.quoteSheetCode,
|
||
main_branch_code: mainBranchCode,
|
||
...(plan.activatedAt ? { activated_at: plan.activatedAt } : {}),
|
||
items: plan.items,
|
||
},
|
||
});
|
||
} catch (error: any) {
|
||
// 出站层抛了未预期异常:也必须把 pending 收口成 failed(否则这行永远停在 pending、不会重试)
|
||
const message = `exception: ${String(error?.message || error)}`;
|
||
await markLedger(ledger.id, { status: 'failed', lastError: message, response: { local } });
|
||
return {
|
||
row: { mainBranchCode, status: 'failed', clientRequestId: ledger.clientRequestId, error: message },
|
||
rearmed,
|
||
};
|
||
}
|
||
|
||
if (isPayloadConflict(outcome)) {
|
||
// 对方明确说"这个请求号已用于别的内容" ⇒ 换号交给下一轮(换号后重放安全:全新请求)
|
||
await rotateLedgerRequestId(ledger.id, `${outcome.code}: ${outcome.reason}`.trim());
|
||
return {
|
||
row: {
|
||
mainBranchCode,
|
||
status: 'failed',
|
||
clientRequestId: ledger.clientRequestId,
|
||
error: 'payload_changed_rotate_id',
|
||
},
|
||
rearmed,
|
||
};
|
||
}
|
||
|
||
const mapped = mapOutcome(outcome);
|
||
const response =
|
||
mapped.response && typeof mapped.response === 'object'
|
||
? { ...(mapped.response as Record<string, unknown>), local }
|
||
: { local };
|
||
await markLedger(ledger.id, { ...mapped, response });
|
||
return {
|
||
row: {
|
||
mainBranchCode,
|
||
status: mapped.status,
|
||
clientRequestId: ledger.clientRequestId,
|
||
error: mapped.lastError ?? undefined,
|
||
replayed: outcome.kind === 'ok' ? outcome.data.replayed : undefined,
|
||
},
|
||
rearmed,
|
||
};
|
||
}
|
||
|
||
/** 整单级跳过:写一行 `main_branch_code = '*'` 的台账(唯一键保证只写一次) */
|
||
async function recordSheetSkip(plan: QuoteCostSyncPlan, reason: string, detail?: string): Promise<boolean> {
|
||
const inserted = await insertLedger({
|
||
branchCode: plan.branchCode,
|
||
quoteSheetCode: plan.quoteSheetCode,
|
||
mainBranchCode: SHEET_LEVEL_BRANCH,
|
||
clientRequestId: randomUUID(),
|
||
status: 'skipped',
|
||
lastError: detail ? `${reason}: ${detail}` : reason,
|
||
response: { local: { ...localTrace(plan), sheet_reason: reason } },
|
||
});
|
||
return Boolean(inserted);
|
||
}
|
||
|
||
/**
|
||
* 推送一张报价单(**事务提交之后**调用;内部自带租户上下文 + 全量吞异常)。
|
||
*
|
||
* `isolate + requestClient:false`:不复用调用方(请求)的数据库连接 ——
|
||
* 本函数是**旁路异步**的,请求结束后请求级连接会被归还,再借到它就是踩已释放连接。
|
||
*/
|
||
export async function pushQuoteCostSyncForSheet(input: {
|
||
branchCode?: string | null;
|
||
quoteSheetCode?: string | null;
|
||
}): Promise<QuoteCostSyncPushSummary> {
|
||
const branchCode = text(input?.branchCode);
|
||
const quoteSheetCode = text(input?.quoteSheetCode);
|
||
const summary = emptySummary(branchCode, quoteSheetCode);
|
||
if (!isQuoteCostSyncEnabled()) return summary;
|
||
if (!branchCode || !quoteSheetCode) return summary;
|
||
|
||
try {
|
||
return await runWithTenantDbContext(
|
||
branchCode,
|
||
async () => {
|
||
const plan = await collectQuoteCostSyncPlan({ branchCode, quoteSheetCode });
|
||
summary.itemCount = plan.items.length;
|
||
if (!plan.sheetExists) {
|
||
summary.skipped += 1;
|
||
summary.results.push({ mainBranchCode: SHEET_LEVEL_BRANCH, status: 'skipped', error: 'quote_sheet_not_found' });
|
||
return summary;
|
||
}
|
||
if (!plan.isActive) {
|
||
// 已驳回/已停用/已被新版取代/已过期:不推(成本价不该由一张失效单决定)
|
||
const inserted = await recordSheetSkip(plan, 'quote_sheet_not_active');
|
||
if (inserted) {
|
||
summary.skipped += 1;
|
||
summary.results.push({
|
||
mainBranchCode: SHEET_LEVEL_BRANCH,
|
||
status: 'skipped',
|
||
error: 'quote_sheet_not_active',
|
||
});
|
||
}
|
||
return summary;
|
||
}
|
||
if (!plan.mainBranchCodes.length) {
|
||
// 全单没有 MAIN_ 客户(真实客户/哨兵)⇒ 记 skipped,零出站
|
||
const inserted = await recordSheetSkip(plan, 'not_usage_company');
|
||
if (inserted) {
|
||
summary.skipped += 1;
|
||
summary.results.push({
|
||
mainBranchCode: SHEET_LEVEL_BRANCH,
|
||
status: 'skipped',
|
||
error: 'not_usage_company',
|
||
});
|
||
}
|
||
return summary;
|
||
}
|
||
if (!plan.items.length) {
|
||
const inserted = await recordSheetSkip(plan, 'no_pushable_items');
|
||
if (inserted) {
|
||
summary.skipped += 1;
|
||
summary.results.push({
|
||
mainBranchCode: SHEET_LEVEL_BRANCH,
|
||
status: 'skipped',
|
||
error: 'no_pushable_items',
|
||
});
|
||
}
|
||
return summary;
|
||
}
|
||
if (plan.items.length > QUOTE_COST_SYNC_MAX_ITEMS) {
|
||
// 对方硬限 2000:整单跳过,绝不截断成"部分同步"
|
||
const inserted = await recordSheetSkip(
|
||
plan,
|
||
'too_many_items',
|
||
`可推行 ${plan.items.length} > 对方上限 ${QUOTE_COST_SYNC_MAX_ITEMS}`
|
||
);
|
||
if (inserted) {
|
||
summary.skipped += 1;
|
||
summary.results.push({
|
||
mainBranchCode: SHEET_LEVEL_BRANCH,
|
||
status: 'skipped',
|
||
error: 'too_many_items',
|
||
});
|
||
}
|
||
return summary;
|
||
}
|
||
|
||
for (const mainBranchCode of plan.mainBranchCodes) {
|
||
if (!plan.supplierCode) {
|
||
// 没有供应商编码 ⇒ 换不到 token,落 failed 等人工补绑定(不在这里瞎猜编码)
|
||
const ledger = await insertLedger({
|
||
branchCode: plan.branchCode,
|
||
quoteSheetCode: plan.quoteSheetCode,
|
||
mainBranchCode,
|
||
clientRequestId: randomUUID(),
|
||
status: 'failed',
|
||
lastError: 'main_supplier_code_missing: 该分公司在主系统没有可用供应商编码',
|
||
response: { local: localTrace(plan) },
|
||
});
|
||
if (ledger) {
|
||
countByStatus(summary, {
|
||
mainBranchCode,
|
||
status: 'failed',
|
||
error: 'main_supplier_code_missing',
|
||
});
|
||
} else {
|
||
countByStatus(summary, { mainBranchCode, status: 'duplicate' });
|
||
}
|
||
continue;
|
||
}
|
||
try {
|
||
// 判重 / 改价重推都以台账里"该单 × 该分公司"那一行为准(R-2 ②)
|
||
const existing = await readLedgerRow(plan.quoteSheetCode, mainBranchCode);
|
||
const result = await pushOneBranch({ plan, mainBranchCode, existing });
|
||
if (result.rearmed) summary.rearmed += 1;
|
||
countByStatus(summary, result.row);
|
||
} catch (error: any) {
|
||
// 单分公司异常不得中断其它分公司
|
||
summary.failed += 1;
|
||
summary.attempted += 1;
|
||
summary.results.push({
|
||
mainBranchCode,
|
||
status: 'failed',
|
||
error: String(error?.message || error),
|
||
});
|
||
console.warn(
|
||
`[quote-cost-sync] 推送异常(${plan.quoteSheetCode} → ${mainBranchCode}):`,
|
||
error?.message || error
|
||
);
|
||
}
|
||
}
|
||
return summary;
|
||
},
|
||
{ isolate: true, requestClient: false }
|
||
);
|
||
} catch (error: any) {
|
||
// 绝不能冒泡:审批路径不因推送失败而失败
|
||
summary.error = String(error?.message || error);
|
||
console.warn('[quote-cost-sync] 推送整体失败(已吞,不影响审批):', error?.message || error);
|
||
return summary;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 触发点入口(旁路异步,绝不阻塞调用方):报价单审批生效(`COMMIT` 之后)调它。
|
||
* 关闭开关 / 空参数 ⇒ 立即返回(零出站、零查库)。
|
||
*/
|
||
export function triggerQuoteCostSync(input: {
|
||
branchCode?: string | null;
|
||
quoteSheetCode?: string | null;
|
||
}): void {
|
||
try {
|
||
if (!isQuoteCostSyncEnabled()) return;
|
||
const branchCode = text(input?.branchCode);
|
||
const quoteSheetCode = text(input?.quoteSheetCode);
|
||
if (!branchCode || !quoteSheetCode) return;
|
||
void pushQuoteCostSyncForSheet({ branchCode, quoteSheetCode }).catch((error: any) => {
|
||
console.warn('[quote-cost-sync] 触发推送失败(已吞,不影响主流程):', error?.message || error);
|
||
});
|
||
} catch (error: any) {
|
||
console.warn('[quote-cost-sync] 触发入口异常(已吞,不影响主流程):', error?.message || error);
|
||
}
|
||
}
|
||
|
||
export type QuoteCostSyncRetryRow = {
|
||
id: string;
|
||
branch_code: string;
|
||
quote_sheet_code: string;
|
||
main_branch_code: string;
|
||
client_request_id: string;
|
||
attempts: number;
|
||
/** 选中时的状态:failed(可重试失败)或 pending(卡住超过 10 分钟) */
|
||
status?: string;
|
||
};
|
||
|
||
export type QuoteCostSyncRetrySummary = {
|
||
/** 本轮选中的台账行数 */
|
||
rows: number;
|
||
attempted: number;
|
||
sent: number;
|
||
failed: number;
|
||
forbidden: number;
|
||
skipped: number;
|
||
/** 单行处理抛错(不影响其它行) */
|
||
errors: number;
|
||
};
|
||
|
||
/**
|
||
* 一条待重试行:重建 payload(可能已变)→ 用**原 `client_request_id`** 重放。
|
||
* 唯一例外:对方明确回 409(同号不同内容)⇒ 换新号、attempts 归零,下一轮用新号(R-2 ①)。
|
||
*/
|
||
async function retryOneRow(row: QuoteCostSyncRetryRow): Promise<
|
||
'sent' | 'failed' | 'forbidden' | 'skipped'
|
||
> {
|
||
return runWithTenantDbContext(
|
||
row.branch_code,
|
||
async () => {
|
||
const plan = await collectQuoteCostSyncPlan({
|
||
branchCode: row.branch_code,
|
||
quoteSheetCode: row.quote_sheet_code,
|
||
});
|
||
const finish = async (
|
||
status: 'sent' | 'failed' | 'forbidden' | 'skipped',
|
||
lastError: string | null,
|
||
response?: unknown
|
||
): Promise<'sent' | 'failed' | 'forbidden' | 'skipped'> => {
|
||
await markLedger(row.id, { status, lastError, response });
|
||
return status;
|
||
};
|
||
|
||
if (!plan.sheetExists) return finish('skipped', 'quote_sheet_not_found');
|
||
if (!plan.isActive) return finish('skipped', 'quote_sheet_not_active');
|
||
if (!plan.mainBranchCodes.includes(text(row.main_branch_code).toUpperCase())) {
|
||
// 客户绑定被撤掉(或改绑到别的分公司)⇒ 这条永远推不出去了
|
||
return finish('skipped', 'main_branch_customer_removed');
|
||
}
|
||
if (!plan.items.length) return finish('skipped', 'no_pushable_items');
|
||
if (plan.items.length > QUOTE_COST_SYNC_MAX_ITEMS) {
|
||
return finish('skipped', 'too_many_items');
|
||
}
|
||
if (!plan.supplierCode) {
|
||
return finish('failed', 'main_supplier_code_missing: 该分公司在主系统没有可用供应商编码');
|
||
}
|
||
|
||
const outcome = await submitQuoteCostSync({
|
||
supplierCode: plan.supplierCode,
|
||
body: {
|
||
client_request_id: row.client_request_id,
|
||
supplier_quote_sheet_code: row.quote_sheet_code,
|
||
main_branch_code: row.main_branch_code,
|
||
...(plan.activatedAt ? { activated_at: plan.activatedAt } : {}),
|
||
items: plan.items,
|
||
},
|
||
});
|
||
if (isPayloadConflict(outcome)) {
|
||
// 同号不同内容 ⇒ 换号(不消耗 attempts:归零后下一轮用新号重试)
|
||
await rotateLedgerRequestId(row.id, `${outcome.code}: ${outcome.reason}`.trim());
|
||
return 'failed';
|
||
}
|
||
const mapped = mapOutcome(outcome);
|
||
const response =
|
||
mapped.response && typeof mapped.response === 'object'
|
||
? { ...(mapped.response as Record<string, unknown>), local: localTrace(plan), retried: true }
|
||
: { local: localTrace(plan), retried: true };
|
||
return finish(mapped.status, mapped.lastError, response);
|
||
},
|
||
{ isolate: true, requestClient: false }
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 定时重试:**两类**待收口台账行,都**复用原 `client_request_id`** 重放。
|
||
*
|
||
* ① `status='failed' AND attempts < 5`(普通失败);
|
||
* ② `status='pending' AND updated_at < NOW() - INTERVAL '10 minutes'`(R-1:进程在
|
||
* "台账已落、结果未回写"之间被杀会留下永久 pending,唯一键还会挡住以后所有推送;
|
||
* 重放是安全的 —— 若对方其实已受理,会按请求号回放;没受理则正常执行)。
|
||
*
|
||
* - 开关关 ⇒ 立即返回(连台账都不查);
|
||
* - `forbidden` / `sent` / `skipped` 永不选中(绑定不成立的单重试也不会成立);
|
||
* - 单行失败只记日志(`errors`),不中断其它行(失败重试不得阻塞其它任务)。
|
||
*/
|
||
export async function retryQuoteCostSyncPushes(options?: {
|
||
limit?: number;
|
||
}): Promise<QuoteCostSyncRetrySummary> {
|
||
const summary: QuoteCostSyncRetrySummary = {
|
||
rows: 0,
|
||
attempted: 0,
|
||
sent: 0,
|
||
failed: 0,
|
||
forbidden: 0,
|
||
skipped: 0,
|
||
errors: 0,
|
||
};
|
||
if (!isQuoteCostSyncEnabled()) return summary;
|
||
|
||
const limit = Math.min(Math.max(Number(options?.limit) || 20, 1), 100);
|
||
const result = await pool.query<QuoteCostSyncRetryRow>(
|
||
`SELECT id::text AS id,
|
||
branch_code,
|
||
quote_sheet_code,
|
||
main_branch_code,
|
||
client_request_id::text AS client_request_id,
|
||
attempts,
|
||
status
|
||
FROM public.main_system_quote_cost_pushes
|
||
WHERE (status = 'failed' AND attempts < $1::int)
|
||
OR (status = 'pending' AND updated_at < NOW() - INTERVAL '10 minutes')
|
||
ORDER BY updated_at ASC
|
||
LIMIT $2::int`,
|
||
[QUOTE_COST_SYNC_MAX_ATTEMPTS, limit]
|
||
);
|
||
|
||
for (const row of result.rows) {
|
||
summary.rows += 1;
|
||
summary.attempted += 1;
|
||
try {
|
||
const status = await retryOneRow(row);
|
||
if (status === 'sent') summary.sent += 1;
|
||
else if (status === 'failed') summary.failed += 1;
|
||
else if (status === 'forbidden') summary.forbidden += 1;
|
||
else summary.skipped += 1;
|
||
} catch (error: any) {
|
||
summary.errors += 1;
|
||
console.warn(
|
||
`[quote-cost-sync] 重试异常(${row.quote_sheet_code} → ${row.main_branch_code}):`,
|
||
error?.message || error
|
||
);
|
||
// 异常也要消耗一次尝试次数,否则同一行会在每轮里无限重试(attempts 不涨 ⇒ 永远选中)
|
||
try {
|
||
await pool.query(
|
||
// pending 行重试时抛错 ⇒ 一并收口成 failed,让它回到 `attempts<5` 的闸门内
|
||
// (pending 的选中条件只看"卡住多久",不收口会被无限重试下去)
|
||
`UPDATE public.main_system_quote_cost_pushes
|
||
SET attempts = attempts + 1,
|
||
status = CASE WHEN status = 'pending' THEN 'failed' ELSE status END,
|
||
last_error = $2::text,
|
||
updated_at = NOW()
|
||
WHERE id = $1::uuid`,
|
||
[row.id, `retry_exception: ${String(error?.message || error)}`]
|
||
);
|
||
} catch {
|
||
/* 记账失败只能下轮再说,不得影响其它行 */
|
||
}
|
||
}
|
||
}
|
||
return summary;
|
||
}
|