- 根因:新「按分类提交」的提议 items 用的是我方 SKU,旧代码按配送 SKU 反查映射 ⇒ 名字/原价全空 - 现在兼容两种约定(我方 SKU 直接用 / 配送 SKU 才反查),并从本系统 skus + 映射镜像取双边名称 - 面板明细改为:我方商品 | 配送商品 | 单位 | 原价 → 新价
1418 lines
58 KiB
TypeScript
1418 lines
58 KiB
TypeScript
import { createHash, randomUUID } from 'node:crypto';
|
||
import { pool } from '../db';
|
||
import { runWithTenantDbContext } from './tenantDbContext';
|
||
import { getEffectiveBranchCode, type TenantContext } from './tenantScope';
|
||
import {
|
||
applyQuoteSheetUpdate,
|
||
loadQuoteSheetForUpdate,
|
||
type QuoteSheetItemInput,
|
||
} from './quoteSheetService';
|
||
import {
|
||
quoteCostSyncItemsFingerprint,
|
||
resolveMainSupplierCode,
|
||
} from './mainSystemQuoteCostSync';
|
||
import {
|
||
decideQuotePriceProposal,
|
||
listQuotePriceProposals,
|
||
submitQuotePriceProposal,
|
||
type QuotePriceProposalItemPayload,
|
||
type RemoteQuotePriceProposalRow,
|
||
} from './mainSystem/api/quotePriceProposals';
|
||
import { writeAuditLog } from './auditService';
|
||
import { getMappingByDeliverySku, getSheetMappingStats } from './skuMappingService';
|
||
|
||
/**
|
||
* 报价单**双向价格传递**(2026-10-18 冻结契约)。
|
||
*
|
||
* 两个方向(同一个数 V = 我方 `sale_price` = 配送商 `cost_price`):
|
||
* · **A `to_delivery`**:我方把整张单的价交配送商审 —— 走 D1 建对方 pending(**不写价**);
|
||
* 结果用 D2 轮询回写本地状态;
|
||
* · **B `from_delivery`**:配送商发起的成本价提议 —— 用 D2 拉回(本地建 pending),我方审:
|
||
* 通过 ⇒ 写本单 `sale_price`(复用 `applyQuoteSheetUpdate`,整单一次、缺 SKU 跳过并记录)
|
||
* ⇒ **D3 回执 `approved`(带 applied)由配送侧用配送 SKU 落地写价**(不再走旧成本同步推送);
|
||
* 驳回 ⇒ D3 回执 `rejected` + 理由,**不写价**。
|
||
*
|
||
* 纪律(前几轮踩过):
|
||
* · 出站 HTTP **永远在事务之外**;B 审批路径**不调** `triggerQuoteCostSync`(由配送侧按 D3 落地);
|
||
* · 台账 `main_system_quote_cost_pushes` 的唯一键/rearm 已存在 —— 本层**不重造推送、不直接写台账**;
|
||
* · 内部改价审核已删除(2026-10-18 用户裁定):改价一律走 `quote_price_proposals` 由对方审核;
|
||
* A 发起只检查"内部是否有在途 pending";
|
||
* · 开关 `MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL` 默认关 ⇒ 零出站、零写库(路由 503)。
|
||
*
|
||
* 设计:docs/design/20261018-报价单双向价格传递与审批.md
|
||
*/
|
||
|
||
export const MAX_PROPOSAL_ITEMS = 2000;
|
||
export const MAX_PROPOSAL_PRICE = 9_999_999.99;
|
||
|
||
/** 开关:默认关;`1` / `true` / `on`(大小写不敏感)才开 */
|
||
export function isQuotePriceProposalEnabled(): boolean {
|
||
const raw = String(process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL ?? '').trim().toLowerCase();
|
||
return raw === '1' || raw === 'true' || raw === 'on';
|
||
}
|
||
|
||
function httpError(status: number, code: string, message: string) {
|
||
return Object.assign(new Error(message), { status, code });
|
||
}
|
||
|
||
function toText(value: unknown): string {
|
||
return value === null || value === undefined ? '' : String(value).trim();
|
||
}
|
||
|
||
function roundPrice(value: unknown): number {
|
||
const num = Number(value);
|
||
if (!Number.isFinite(num)) return 0;
|
||
return Math.round(num * 100) / 100;
|
||
}
|
||
|
||
/** 我方明细行的价(`sale_price ?? price`),按 2 位小数归一 */
|
||
function readSheetPrice(row: Record<string, unknown>): number {
|
||
return roundPrice(row.sale_price ?? row.price);
|
||
}
|
||
|
||
/** 明细指纹(复用成本价同步同一算法,便于排障比对) */
|
||
function proposalPayloadHash(input: {
|
||
quoteSheetCode: string;
|
||
mainBranchCode: string;
|
||
note: string | null;
|
||
items: QuotePriceProposalItemPayload[];
|
||
}): string {
|
||
const items = [...input.items]
|
||
.map((item) => [item.sku_code, item.unit || '', Number(item.price).toFixed(2)])
|
||
.sort((a, b) => (a[0] === b[0] ? (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0) : a[0] < b[0] ? -1 : 1));
|
||
return createHash('sha256')
|
||
.update(
|
||
JSON.stringify({
|
||
sheet: input.quoteSheetCode,
|
||
branch: input.mainBranchCode,
|
||
note: input.note || '',
|
||
items,
|
||
})
|
||
)
|
||
.digest('hex');
|
||
}
|
||
|
||
function assertProposalItems(items: QuotePriceProposalItemPayload[]): void {
|
||
if (!Array.isArray(items) || !items.length) {
|
||
throw httpError(400, 'items_required', '没有可提交的商品行');
|
||
}
|
||
if (items.length > MAX_PROPOSAL_ITEMS) {
|
||
throw httpError(400, 'too_many_items', `商品行超过上限 ${MAX_PROPOSAL_ITEMS}`);
|
||
}
|
||
const seen = new Set<string>();
|
||
for (const item of items) {
|
||
const code = toText(item.sku_code);
|
||
if (!code) throw httpError(400, 'invalid_item', '商品行缺少 sku_code');
|
||
if (seen.has(code)) throw httpError(400, 'duplicate_sku', `同一商品重复出现:${code}`);
|
||
seen.add(code);
|
||
if (!(Number(item.price) > 0) || Number(item.price) > MAX_PROPOSAL_PRICE) {
|
||
throw httpError(400, 'invalid_price', `商品 ${code} 的价格不合法`);
|
||
}
|
||
}
|
||
}
|
||
|
||
/** 客户绑定的主系统分公司码(`MAIN_<X>`) */
|
||
export function parseMainBranchCodes(customerCodes: string[]): string[] {
|
||
const codes = new Set<string>();
|
||
for (const raw of customerCodes || []) {
|
||
const match = /^MAIN_([0-9A-Za-z_-]{1,32})$/i.exec(toText(raw));
|
||
if (match) codes.add(match[1].toUpperCase());
|
||
}
|
||
return [...codes].sort();
|
||
}
|
||
|
||
/* ── 本地台账读取 ───────────────────────────────────────────────────────── */
|
||
|
||
export type QuotePriceProposalDto = {
|
||
id: string;
|
||
branch_code: string;
|
||
quote_sheet_code: string;
|
||
main_branch_code: string;
|
||
direction: 'to_delivery' | 'from_delivery';
|
||
items: QuotePriceProposalItemPayload[];
|
||
payload_hash: string | null;
|
||
status: 'pending' | 'approved' | 'rejected' | 'cancelled' | 'superseded';
|
||
reject_reason: string | null;
|
||
client_request_id: string | null;
|
||
remote_proposal_id: string | null;
|
||
requested_by: string | null;
|
||
requested_by_name: string | null;
|
||
requested_at: string | null;
|
||
reviewed_by: string | null;
|
||
reviewed_by_name: string | null;
|
||
reviewed_at: string | null;
|
||
applied_at: string | null;
|
||
updated_at: string | null;
|
||
/** 列表附加:与当前报价单明细的「改前 → 改后」(仅 pending 的 B 方向) */
|
||
lines?: Array<{
|
||
sku_code: string;
|
||
sku_name: string | null;
|
||
unit: string | null;
|
||
before_sale_price: number | null;
|
||
after_sale_price: number | null;
|
||
/** unmapped = 该配送 SKU 在本地映射表里还没有 active 映射(审批时会 skip sku_unmapped) */
|
||
change: 'updated' | 'added' | 'unmapped';
|
||
/** 反查到的我方 SKU(未映射时为空) */
|
||
supplier_sku_code?: string | null;
|
||
/** 对应的配送侧 SKU / 商品名(供审批人对照;配送侧商品名可能与我方不同) */
|
||
delivery_sku_code?: string | null;
|
||
delivery_sku_name?: string | null;
|
||
}>;
|
||
/** 列表附加:该行最近一次 D2 回执里的 applied 摘要(若本轮拉到了) */
|
||
applied?: { updated: number; skipped: unknown } | null;
|
||
note?: string | null;
|
||
/** pending 行已等待天数(T7:pending 不自动过期,仅展示) */
|
||
waited_days?: number | null;
|
||
};
|
||
|
||
type LocalRow = Record<string, any>;
|
||
|
||
function waitedDays(requestedAt: unknown): number | null {
|
||
if (!requestedAt) return null;
|
||
const time = new Date(String(requestedAt)).getTime();
|
||
if (!Number.isFinite(time)) return null;
|
||
return Math.max(0, Math.floor((Date.now() - time) / 86400000));
|
||
}
|
||
|
||
function toDto(row: LocalRow): QuotePriceProposalDto {
|
||
return {
|
||
id: String(row.id),
|
||
branch_code: String(row.branch_code),
|
||
quote_sheet_code: String(row.quote_sheet_code),
|
||
main_branch_code: String(row.main_branch_code),
|
||
direction: row.direction,
|
||
items: Array.isArray(row.items) ? (row.items as QuotePriceProposalItemPayload[]) : [],
|
||
payload_hash: row.payload_hash ? String(row.payload_hash) : null,
|
||
status: row.status,
|
||
reject_reason: row.reject_reason ? String(row.reject_reason) : null,
|
||
client_request_id: row.client_request_id ? String(row.client_request_id) : null,
|
||
remote_proposal_id: row.remote_proposal_id ? String(row.remote_proposal_id) : null,
|
||
requested_by: row.requested_by ? String(row.requested_by) : null,
|
||
requested_by_name: row.requested_by_name ? String(row.requested_by_name) : null,
|
||
requested_at: row.requested_at ?? null,
|
||
reviewed_by: row.reviewed_by ? String(row.reviewed_by) : null,
|
||
reviewed_by_name: row.reviewed_by_name ? String(row.reviewed_by_name) : null,
|
||
reviewed_at: row.reviewed_at ?? null,
|
||
applied_at: row.applied_at ?? null,
|
||
updated_at: row.updated_at ?? null,
|
||
waited_days: row.status === 'pending' ? waitedDays(row.requested_at) : null,
|
||
};
|
||
}
|
||
|
||
/** 读本报价单的报价明细(价沿用 sale_price ?? price) */
|
||
async function loadSheetItemRows(quoteSheetCode: string): Promise<LocalRow[]> {
|
||
const result = await pool.query<LocalRow>(
|
||
`SELECT sku_code, sku_name, unit, sale_price, price, cost_price, markup_ratio
|
||
FROM customer_quote_sheet_items
|
||
WHERE quote_sheet_code = $1
|
||
ORDER BY sort_order ASC, sku_code ASC`,
|
||
[quoteSheetCode]
|
||
);
|
||
return result.rows;
|
||
}
|
||
|
||
async function findLocalByRemoteId(
|
||
remoteProposalId: string
|
||
): Promise<LocalRow | null> {
|
||
const result = await pool.query<LocalRow>(
|
||
`SELECT * FROM quote_price_proposals WHERE remote_proposal_id = $1 LIMIT 1`,
|
||
[remoteProposalId]
|
||
);
|
||
return result.rows[0] || null;
|
||
}
|
||
|
||
async function findPendingLocal(
|
||
branchCode: string,
|
||
quoteSheetCode: string,
|
||
direction: 'to_delivery' | 'from_delivery'
|
||
): Promise<LocalRow | null> {
|
||
const result = await pool.query<LocalRow>(
|
||
`SELECT * FROM quote_price_proposals
|
||
WHERE branch_code = $1 AND quote_sheet_code = $2 AND direction = $3 AND status = 'pending'
|
||
LIMIT 1`,
|
||
[branchCode, quoteSheetCode, direction]
|
||
);
|
||
return result.rows[0] || null;
|
||
}
|
||
|
||
function auditProposal(input: {
|
||
operatorId?: string | null;
|
||
operatorRole?: string | null;
|
||
action: 'submit' | 'approve' | 'reject' | 'sync';
|
||
branchCode: string;
|
||
proposalId: string;
|
||
quoteSheetCode: string;
|
||
direction: string;
|
||
status: string;
|
||
reason?: string | null;
|
||
}): void {
|
||
// best-effort:审计失败只记日志(与上一轮口径一致)
|
||
void writeAuditLog({
|
||
operatorId: input.operatorId || null,
|
||
operatorRole: input.operatorRole || null,
|
||
operationType: `quote_price_proposal_${input.action}`,
|
||
targetTable: 'quote_price_proposals',
|
||
targetId: input.proposalId,
|
||
oldValue: { proposal_id: input.proposalId, quote_sheet_code: input.quoteSheetCode, direction: input.direction },
|
||
newValue: {
|
||
proposal_id: input.proposalId,
|
||
quote_sheet_code: input.quoteSheetCode,
|
||
direction: input.direction,
|
||
action: input.action,
|
||
status: input.status,
|
||
reason: input.reason ?? null,
|
||
},
|
||
branchCode: input.branchCode,
|
||
actionCategory: 'quote_price_proposal',
|
||
}).catch((error: any) => {
|
||
console.warn('[quote-price-proposal] 审计写入失败(best-effort):', error?.message || error);
|
||
});
|
||
}
|
||
|
||
/* ── 方向 A:提交给配送商审 ─────────────────────────────────────────────── */
|
||
|
||
export type SubmitResult = {
|
||
applied: false;
|
||
proposal: QuotePriceProposalDto;
|
||
replayed: boolean;
|
||
/**
|
||
* 提交时本单的映射统计(契约 §5):「本单 N 个商品,已映射 X / 未映射 Y」。
|
||
* 未映射**不阻止**提交(配送侧写价时会 skip `sku_unmapped`),但用户要能看到。
|
||
*/
|
||
mapping: {
|
||
quote_sheet_code: string;
|
||
total: number;
|
||
mapped: number;
|
||
unmapped: number;
|
||
unmapped_skus: Array<{ sku_code: string; sku_name: string | null }>;
|
||
};
|
||
};
|
||
|
||
/**
|
||
* 方向 A 发起(整单一次):
|
||
* ① 报价单必须生效中;② **内部改价审核无在途 pending**;③ 本方向无在途 pending;
|
||
* ④ 从绑定客户解析**唯一**主系统分公司(`MAIN_<X>`);⑤ 调 D1(**事务外**)建对方 pending;
|
||
* ⑥ 本地建 `to_delivery` pending —— **不写价**(价只在对方通过后由对方自己写成本价)。
|
||
*/
|
||
export async function submitPriceProposal(input: {
|
||
quoteSheetCode: string;
|
||
note?: string | null;
|
||
ctx?: TenantContext | null;
|
||
operatingBranchCode?: string | null;
|
||
requestedBy?: string | null;
|
||
}): Promise<SubmitResult> {
|
||
if (!isQuotePriceProposalEnabled()) {
|
||
throw httpError(503, 'feature_disabled', '报价单价格传递未开启(MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL)');
|
||
}
|
||
const branchCode = getEffectiveBranchCode(input.ctx || null, input.operatingBranchCode);
|
||
if (!branchCode) throw httpError(400, 'branch_required', '请选择当前操作分公司');
|
||
|
||
const sheet = await loadQuoteSheetForUpdate(input.quoteSheetCode, input.ctx, input.operatingBranchCode);
|
||
const quoteSheetCode = String(sheet.quote_sheet_code);
|
||
|
||
const existingPending = await findPendingLocal(branchCode, quoteSheetCode, 'to_delivery');
|
||
|
||
const customerRows = await pool.query<{ customer_code: string }>(
|
||
`SELECT customer_code FROM customer_quote_sheet_customers WHERE quote_sheet_code = $1 ORDER BY customer_code ASC`,
|
||
[quoteSheetCode]
|
||
);
|
||
const mainBranchCodes = parseMainBranchCodes(customerRows.rows.map((row) => String(row.customer_code)));
|
||
if (!mainBranchCodes.length) {
|
||
throw httpError(400, 'not_usage_company', '该报价单没有绑定主系统分公司客户(MAIN_*),无需提交');
|
||
}
|
||
if (mainBranchCodes.length > 1) {
|
||
throw httpError(
|
||
400,
|
||
'ambiguous_main_branch',
|
||
`该报价单绑定了多个主系统分公司(${mainBranchCodes.join('、')}),请拆单后再提交`
|
||
);
|
||
}
|
||
const mainBranchCode = mainBranchCodes[0];
|
||
|
||
const supplierCode = await resolveMainSupplierCode(branchCode);
|
||
if (!supplierCode) {
|
||
throw httpError(409, 'main_supplier_code_missing', '该分公司在主系统没有可用供应商编码,无法提交');
|
||
}
|
||
|
||
const itemRows = await loadSheetItemRows(quoteSheetCode);
|
||
const items: QuotePriceProposalItemPayload[] = itemRows
|
||
.map((row) => ({
|
||
sku_code: toText(row.sku_code),
|
||
unit: toText(row.unit) || null,
|
||
price: readSheetPrice(row),
|
||
}))
|
||
.filter((item) => item.sku_code && item.price > 0);
|
||
assertProposalItems(items);
|
||
|
||
const note = toText(input.note) || null;
|
||
const payloadHash = proposalPayloadHash({ quoteSheetCode, mainBranchCode, note, items });
|
||
|
||
// T6:同方向重复提交 —— **同 payload 同 hash ⇒ 回放**(不重复出站),否则**覆盖旧 pending**(旧的置 superseded)
|
||
const mapping = await getSheetMappingStats(quoteSheetCode);
|
||
if (existingPending && String(existingPending.payload_hash || '') === payloadHash) {
|
||
return { applied: false, proposal: toDto(existingPending), replayed: true, mapping };
|
||
}
|
||
const clientRequestId = randomUUID();
|
||
|
||
// 出站 HTTP 必须在事务之外(这里没有任何打开的事务)
|
||
const submitted = await submitQuotePriceProposal({
|
||
supplierCode,
|
||
clientRequestId,
|
||
supplierQuoteSheetCode: quoteSheetCode,
|
||
mainBranchCode,
|
||
note,
|
||
items,
|
||
});
|
||
if (submitted.kind !== 'ok') {
|
||
throw httpError(
|
||
submitted.kind === 'rejected' ? submitted.status || 409 : 502,
|
||
submitted.code,
|
||
submitted.reason
|
||
);
|
||
}
|
||
|
||
// 旧 pending 必须置 `superseded`(T6)+ 插新行,同一事务;冲突(并发提交)时回读判断
|
||
const tx = await pool.connect();
|
||
let row: LocalRow;
|
||
try {
|
||
await tx.query('BEGIN');
|
||
await tx.query(
|
||
`UPDATE quote_price_proposals
|
||
SET status = 'superseded', updated_at = NOW()
|
||
WHERE branch_code = $1 AND quote_sheet_code = $2 AND direction = 'to_delivery' AND status = 'pending'`,
|
||
[branchCode, quoteSheetCode]
|
||
);
|
||
const inserted = await tx.query<LocalRow>(
|
||
`INSERT INTO quote_price_proposals
|
||
(branch_code, quote_sheet_code, main_branch_code, direction, items, payload_hash,
|
||
status, client_request_id, remote_proposal_id, requested_by, requested_at, updated_at)
|
||
VALUES ($1, $2, $3, 'to_delivery', $4::jsonb, $5, 'pending', $6::uuid, $7, $8::uuid, NOW(), NOW())
|
||
ON CONFLICT (branch_code, quote_sheet_code, direction) WHERE status = 'pending' DO NOTHING
|
||
RETURNING *`,
|
||
[
|
||
branchCode,
|
||
quoteSheetCode,
|
||
mainBranchCode,
|
||
JSON.stringify(items),
|
||
payloadHash,
|
||
clientRequestId,
|
||
submitted.data.proposal_id,
|
||
input.requestedBy ?? null,
|
||
]
|
||
);
|
||
await tx.query('COMMIT');
|
||
row = inserted.rows[0];
|
||
} catch (error) {
|
||
try {
|
||
await tx.query('ROLLBACK');
|
||
} catch {
|
||
/* ignore */
|
||
}
|
||
throw error;
|
||
} finally {
|
||
tx.release();
|
||
}
|
||
if (!row) {
|
||
// 并发:另一请求刚插了 pending ⇒ 同 hash 视为回放,不同 hash 明确冲突(不静默吞掉)
|
||
const pending = await findPendingLocal(branchCode, quoteSheetCode, 'to_delivery');
|
||
if (!pending) throw httpError(409, 'already_pending', '该报价单已有一条等待配送商审核的提议');
|
||
if (String(pending.payload_hash || '') !== payloadHash) {
|
||
throw httpError(409, 'concurrent_pending', '该报价单刚被另一请求提交了不同价格,请刷新后重试');
|
||
}
|
||
row = pending;
|
||
}
|
||
|
||
auditProposal({
|
||
operatorId: input.ctx?.userId || input.requestedBy || null,
|
||
operatorRole: input.ctx?.roles?.join(',') || null,
|
||
action: 'submit',
|
||
branchCode,
|
||
proposalId: String(row.id),
|
||
quoteSheetCode,
|
||
direction: 'to_delivery',
|
||
status: 'pending',
|
||
});
|
||
|
||
return { applied: false, proposal: toDto(row), replayed: submitted.data.replayed, mapping };
|
||
}
|
||
|
||
/* ── 同步(D2):A 结果回写 + B 提议拉回 + D3 回执重试 ──────────────────── */
|
||
|
||
export type SyncSummary = {
|
||
suppliers: number;
|
||
pulled: number;
|
||
synced: number;
|
||
receipts: number;
|
||
skipped: number;
|
||
errors: number;
|
||
};
|
||
|
||
const DELIVERY_DIRECTION_MAP: Record<string, 'to_delivery' | 'from_delivery'> = {
|
||
// 配送侧视角:from_supplier = 我方 A 提交的;to_supplier = 配送商发起的 B
|
||
from_supplier: 'to_delivery',
|
||
to_supplier: 'from_delivery',
|
||
};
|
||
|
||
function isTerminalProposalStatus(status: string): boolean {
|
||
// `superseded` 必须算终态:配送侧重复发起 B 时会先把旧 pending 置 superseded 再插新 pending
|
||
// (T6 覆盖语义)。若这里不认,旧本地 pending 永远收不了口,新 pending 还会撞本地 partial unique。
|
||
return (
|
||
status === 'approved' ||
|
||
status === 'rejected' ||
|
||
status === 'cancelled' ||
|
||
status === 'superseded'
|
||
);
|
||
}
|
||
|
||
async function deliverDecisionReceipt(input: {
|
||
supplierCode: string;
|
||
proposalId: string;
|
||
decision: 'approved' | 'rejected';
|
||
reason?: string | null;
|
||
/** approve 时把写价统计一并回执(配送侧只记录、不写价);A20 要求 `applied` 不能恒为 null */
|
||
applied?: { updated: number; skipped: unknown } | null;
|
||
}): Promise<boolean> {
|
||
const outcome = await decideQuotePriceProposal(input);
|
||
return outcome.kind === 'ok';
|
||
}
|
||
|
||
/**
|
||
* 回执补发时用的 `applied` 快照(T8:第一次回执失败后重发没有原统计):
|
||
* 与报价单**当前**明细比对 —— 价已等于提议价算 `updated`,行不存在算 `sku_not_in_sheet`。
|
||
* best-effort(重发场景),不写库。
|
||
*/
|
||
async function computeAppliedSnapshot(
|
||
quoteSheetCode: string,
|
||
items: Array<{ sku_code?: unknown; price?: unknown }>
|
||
): Promise<{ updated: number; skipped: Array<{ sku_code: string; reason: string }> }> {
|
||
const rows = await pool.query<{ sku_code: string; sale_price: string | null; price: string | null }>(
|
||
`SELECT sku_code, sale_price, price FROM customer_quote_sheet_items WHERE quote_sheet_code = $1`,
|
||
[quoteSheetCode]
|
||
);
|
||
const bySku = new Map(rows.rows.map((row) => [String(row.sku_code), row]));
|
||
let updated = 0;
|
||
const skipped: Array<{ sku_code: string; reason: string }> = [];
|
||
for (const item of items || []) {
|
||
const code = toText(item.sku_code);
|
||
const price = roundPrice(item.price);
|
||
if (!code) continue;
|
||
const row = bySku.get(code);
|
||
if (!row) {
|
||
skipped.push({ sku_code: code, reason: 'sku_not_in_sheet' });
|
||
continue;
|
||
}
|
||
if (Math.abs(readSheetPrice(row as unknown as Record<string, unknown>) - price) <= 1e-6) updated += 1;
|
||
else skipped.push({ sku_code: code, reason: 'price_not_applied' });
|
||
}
|
||
return { updated, skipped };
|
||
}
|
||
|
||
/**
|
||
* 把 D2 的一行落到本地台账(在**目标分公司的租户上下文**里执行):
|
||
* · A(`from_supplier`)已有本地行:远端终态 ⇒ 回写本地状态;本地终态但远端仍 pending ⇒ 重发 D3;
|
||
* · B(`to_supplier`):本地没有 ⇒ 建 `from_delivery` pending(**不写价**);已有 ⇒ 只补状态。
|
||
*/
|
||
async function applyRemoteRow(input: {
|
||
branchCode: string;
|
||
supplierCode: string;
|
||
remote: RemoteQuotePriceProposalRow;
|
||
}): Promise<'pulled' | 'synced' | 'receipt' | 'skipped'> {
|
||
const localDirection = DELIVERY_DIRECTION_MAP[input.remote.direction];
|
||
if (!localDirection) return 'skipped';
|
||
const remoteStatus = toText(input.remote.status) || 'pending';
|
||
|
||
/**
|
||
* A16/T6 交叉(verifier 阻断项):配送侧重复发起 B 时,会先把旧 pending 置 **`superseded`** 再插新 pending。
|
||
* 因此:
|
||
* · 远端 `superseded` 必须当**终态**(本地同 remote id 的 pending 收口成 superseded);
|
||
* · 新的远端 pending 落本地若撞 partial unique,**不能 DO NOTHING 静默跳过** —— 先把本地旧 pending
|
||
* 置 superseded,再插新行;否则新提议永远落不了本地,用户还会对旧 id 通过 → 把已撤回价写进报价单。
|
||
*/
|
||
return runWithTenantDbContext(
|
||
input.branchCode,
|
||
async () => {
|
||
const existingByRemote = await findLocalByRemoteId(input.remote.proposal_id);
|
||
|
||
if (existingByRemote) {
|
||
const localStatus = String(existingByRemote.status);
|
||
const isFromDelivery = String(existingByRemote.direction) === 'from_delivery';
|
||
|
||
// 远端已撤回/被替代 ⇒ 本地同 remote id 的 pending 直接收口(不写价、不推送)
|
||
if (remoteStatus === 'superseded') {
|
||
if (localStatus === 'pending') {
|
||
await pool.query(
|
||
`UPDATE quote_price_proposals
|
||
SET status = 'superseded',
|
||
reject_reason = 'remote_superseded',
|
||
remote_proposal_id = COALESCE(remote_proposal_id, $2),
|
||
updated_at = NOW()
|
||
WHERE id = $1::uuid AND status = 'pending'`,
|
||
[String(existingByRemote.id), input.remote.proposal_id]
|
||
);
|
||
return 'synced';
|
||
}
|
||
return 'skipped';
|
||
}
|
||
|
||
// 本地已终态但远端还没收到回执 ⇒ 重发 D3(幂等重试,只对 B 方向有意义)
|
||
if (isTerminalProposalStatus(localStatus) && remoteStatus === 'pending' && isFromDelivery) {
|
||
const applied =
|
||
localStatus === 'approved'
|
||
? await computeAppliedSnapshot(
|
||
String(existingByRemote.quote_sheet_code),
|
||
(Array.isArray(existingByRemote.items) ? existingByRemote.items : []) as any[]
|
||
)
|
||
: null;
|
||
const ok = await deliverDecisionReceipt({
|
||
supplierCode: input.supplierCode,
|
||
proposalId: input.remote.proposal_id,
|
||
decision: localStatus === 'approved' ? 'approved' : 'rejected',
|
||
reason: existingByRemote.reject_reason ? String(existingByRemote.reject_reason) : null,
|
||
applied,
|
||
});
|
||
return ok ? 'receipt' : 'skipped';
|
||
}
|
||
|
||
if (localStatus === 'pending' && isTerminalProposalStatus(remoteStatus)) {
|
||
await pool.query(
|
||
`UPDATE quote_price_proposals
|
||
SET status = $2::varchar,
|
||
reject_reason = COALESCE($3::text, reject_reason),
|
||
reviewed_at = COALESCE($4::timestamptz, reviewed_at),
|
||
applied_at = CASE WHEN $2::text = 'approved' THEN NOW() ELSE applied_at END,
|
||
updated_at = NOW()
|
||
WHERE id = $1::uuid`,
|
||
[
|
||
String(existingByRemote.id),
|
||
remoteStatus === 'cancelled' ? 'cancelled' : remoteStatus,
|
||
input.remote.reject_reason,
|
||
input.remote.reviewed_at,
|
||
]
|
||
);
|
||
return 'synced';
|
||
}
|
||
return 'skipped';
|
||
}
|
||
|
||
// 本地没有:只拉"待我方审"的 B 提议(A 的行由我们提交时自己建)
|
||
if (localDirection !== 'from_delivery') return 'skipped';
|
||
if (remoteStatus !== 'pending') return 'skipped';
|
||
|
||
/**
|
||
* T2:方向 B 的目标单在**我方**按 `MAIN_<main_branch_code>` 解析**唯一生效单**。
|
||
* 优先用对方带过来的单号(且校验仍生效),否则按 MAIN_ 解析;0/多张都不猜(跳过并告警,
|
||
* 审批时仍会以 409 `no_quote_sheet`/`ambiguous_sheet` 兜底)。
|
||
*/
|
||
let quoteSheetCode = toText(input.remote.supplier_quote_sheet_code);
|
||
if (quoteSheetCode) {
|
||
const alive = await pool.query(
|
||
`SELECT 1 FROM customer_quote_sheets
|
||
WHERE quote_sheet_code = $1 AND status = 1 AND approval_status = 30
|
||
AND (expires_at IS NULL OR expires_at > NOW())
|
||
LIMIT 1`,
|
||
[quoteSheetCode]
|
||
);
|
||
if (!alive.rows.length) quoteSheetCode = '';
|
||
}
|
||
if (!quoteSheetCode) {
|
||
const { candidates } = await resolveActiveSheetCodeForMainBranch(input.remote.branch_code);
|
||
if (candidates.length === 1) quoteSheetCode = candidates[0];
|
||
else {
|
||
console.warn(
|
||
`[quote-price-proposal] 方向 B 目标单无法唯一解析(main_branch=${input.remote.branch_code}, ` +
|
||
`候选 ${candidates.length} 张,proposal=${input.remote.proposal_id})⇒ 本轮跳过`
|
||
);
|
||
return 'skipped';
|
||
}
|
||
}
|
||
|
||
const items = (input.remote.items || [])
|
||
.map((item) => ({
|
||
sku_code: toText(item.sku_code),
|
||
unit: toText(item.unit) || null,
|
||
price: roundPrice(item.price),
|
||
}))
|
||
.filter((item) => item.sku_code && item.price > 0 && item.price <= MAX_PROPOSAL_PRICE)
|
||
.slice(0, MAX_PROPOSAL_ITEMS);
|
||
if (!items.length) return 'skipped';
|
||
|
||
const payloadHash = proposalPayloadHash({
|
||
quoteSheetCode,
|
||
mainBranchCode: input.remote.branch_code,
|
||
note: input.remote.note,
|
||
items,
|
||
});
|
||
|
||
const insertNew = () =>
|
||
pool.query(
|
||
`INSERT INTO quote_price_proposals
|
||
(branch_code, quote_sheet_code, main_branch_code, direction, items, payload_hash,
|
||
status, client_request_id, remote_proposal_id, requested_by, requested_at, updated_at)
|
||
VALUES ($1, $2, $3, 'from_delivery', $4::jsonb, $5, 'pending', $6::uuid, $7, NULL, NOW(), NOW())
|
||
ON CONFLICT (branch_code, quote_sheet_code, direction) WHERE status = 'pending' DO NOTHING
|
||
RETURNING id::text AS id`,
|
||
[
|
||
input.branchCode,
|
||
quoteSheetCode,
|
||
input.remote.branch_code,
|
||
JSON.stringify(items),
|
||
payloadHash,
|
||
randomUUID(),
|
||
input.remote.proposal_id,
|
||
]
|
||
);
|
||
|
||
/**
|
||
* 先直接插;撞唯一键时**显式接管**:旧的(不同 remote id)置 superseded 后再插。
|
||
* 极端并发(第二次仍撞到另一个 pending)时最多接管 4 次;仍失败 ⇒ **抛错失败关闭**
|
||
* (sync 侧记 errors 并重置该 supplier 的游标,下一轮重拉;绝不静默丢新提议)。
|
||
*/
|
||
const MAX_TAKEOVER_ATTEMPTS = 4;
|
||
for (let attempt = 0; attempt < MAX_TAKEOVER_ATTEMPTS; attempt += 1) {
|
||
const inserted = await insertNew();
|
||
if (inserted.rows[0]) return 'pulled';
|
||
|
||
const localPending = await findPendingLocal(input.branchCode, quoteSheetCode, 'from_delivery');
|
||
if (!localPending) continue; // 并发下对方刚好撤了:重试插入
|
||
if (String(localPending.remote_proposal_id || '') === input.remote.proposal_id) {
|
||
return 'skipped'; // 同一远端提议 ⇒ 幂等跳过(不清数据)
|
||
}
|
||
await pool.query(
|
||
`UPDATE quote_price_proposals
|
||
SET status = 'superseded',
|
||
reject_reason = $2,
|
||
updated_at = NOW()
|
||
WHERE id = $1::uuid AND status = 'pending'`,
|
||
[String(localPending.id), `replaced_by_remote:${input.remote.proposal_id}`]
|
||
);
|
||
}
|
||
throw new Error(
|
||
`quote_price_proposal_takeover_failed: ${input.remote.proposal_id} on ${input.branchCode}/${quoteSheetCode}`
|
||
);
|
||
},
|
||
{ isolate: true, requestClient: false }
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 定时/手动对账:按「有 active 绑定的供应商编码」逐个调 D2,把行落到**各自分公司**的租户表。
|
||
* 供应商编码 → 我方分公司:优先 `main_supplier_bindings` 的 `main_branch_code` 精确匹配,
|
||
* 否则仅在**唯一候选**分公司时回退(多候选不猜)。
|
||
*/
|
||
/** T10 游标记忆(按 supplier_code)。进程重启后退化为全量拉取,安全。 */
|
||
const syncCursors = new Map<string, string | null>();
|
||
|
||
export function resetQuotePriceProposalSyncCursor(supplierCode?: string): void {
|
||
if (supplierCode) syncCursors.delete(String(supplierCode));
|
||
else syncCursors.clear();
|
||
}
|
||
|
||
export async function syncQuotePriceProposals(options?: {
|
||
limit?: number;
|
||
/** 显式指定/覆盖游标(排障或手动全量:传 null) */
|
||
cursor?: string | null;
|
||
resetCursor?: boolean;
|
||
}): Promise<SyncSummary> {
|
||
const summary: SyncSummary = { suppliers: 0, pulled: 0, synced: 0, receipts: 0, skipped: 0, errors: 0 };
|
||
if (!isQuotePriceProposalEnabled()) return summary;
|
||
|
||
const bindings = await pool.query<{ branch_code: string; main_branch_code: string; main_supplier_code: string }>(
|
||
`SELECT branch_code, main_branch_code, main_supplier_code
|
||
FROM public.main_supplier_bindings
|
||
WHERE status = 'active' AND NULLIF(TRIM(main_supplier_code), '') IS NOT NULL`
|
||
);
|
||
const bySupplier = new Map<string, Array<{ branch_code: string; main_branch_code: string }>>();
|
||
for (const row of bindings.rows) {
|
||
const code = String(row.main_supplier_code).trim();
|
||
if (!bySupplier.has(code)) bySupplier.set(code, []);
|
||
bySupplier.get(code)!.push({
|
||
branch_code: String(row.branch_code),
|
||
main_branch_code: String(row.main_branch_code),
|
||
});
|
||
}
|
||
|
||
const limit = Math.min(Math.max(Number(options?.limit) || 100, 1), 200);
|
||
if (options?.resetCursor) syncCursors.clear();
|
||
for (const [supplierCode, branches] of bySupplier) {
|
||
summary.suppliers += 1;
|
||
const cursor =
|
||
options?.cursor !== undefined ? options.cursor : syncCursors.get(supplierCode) ?? null;
|
||
const listed = await listQuotePriceProposals({ supplierCode, limit, cursor });
|
||
if (listed.kind !== 'ok') {
|
||
summary.errors += 1;
|
||
continue;
|
||
}
|
||
// T10:带上服务端返回的复合游标 `(updated_at, id)`,下一轮增量拉取
|
||
syncCursors.set(supplierCode, listed.nextCursor);
|
||
for (const remote of listed.rows) {
|
||
const exact = branches.find((row) => row.main_branch_code === remote.branch_code);
|
||
const branchCode = exact
|
||
? exact.branch_code
|
||
: branches.length === 1
|
||
? branches[0].branch_code
|
||
: '';
|
||
if (!branchCode) {
|
||
summary.skipped += 1;
|
||
continue;
|
||
}
|
||
try {
|
||
const outcome = await applyRemoteRow({ branchCode, supplierCode, remote });
|
||
if (outcome === 'pulled') summary.pulled += 1;
|
||
else if (outcome === 'synced') summary.synced += 1;
|
||
else if (outcome === 'receipt') summary.receipts += 1;
|
||
else summary.skipped += 1;
|
||
} catch (error: any) {
|
||
summary.errors += 1;
|
||
// 接管失败/其它异常 ⇒ 重置该供应商游标,下一轮从头发(新提议不会被"游标已过"静默丢掉)
|
||
syncCursors.delete(supplierCode);
|
||
console.warn(
|
||
`[quote-price-proposal] 同步单行失败(${remote.proposal_id}),已重置游标待下轮重拉:`,
|
||
error?.message || error
|
||
);
|
||
}
|
||
}
|
||
}
|
||
return summary;
|
||
}
|
||
|
||
/* ── 列表 ───────────────────────────────────────────────────────────────── */
|
||
|
||
/** 本地提议列表(pending 的 B 方向附带与当前明细的「改前 → 改后」) */
|
||
export async function listPriceProposals(input: {
|
||
branchCode: string;
|
||
direction?: string | null;
|
||
status?: string | null;
|
||
limit?: number;
|
||
refresh?: boolean;
|
||
}): Promise<{ rows: QuotePriceProposalDto[]; sync: SyncSummary | null }> {
|
||
const branchCode = toText(input.branchCode);
|
||
if (!branchCode) return { rows: [], sync: null };
|
||
const sync = input.refresh && isQuotePriceProposalEnabled() ? await syncQuotePriceProposals() : null;
|
||
|
||
const direction = ['to_delivery', 'from_delivery'].includes(toText(input.direction))
|
||
? toText(input.direction)
|
||
: null;
|
||
const status = ['pending', 'approved', 'rejected', 'cancelled', 'superseded'].includes(toText(input.status))
|
||
? toText(input.status)
|
||
: null;
|
||
const limit = Math.min(Math.max(Number(input.limit) || 50, 1), 200);
|
||
const params: unknown[] = [branchCode];
|
||
let where = `WHERE p.branch_code = $1`;
|
||
if (direction) {
|
||
params.push(direction);
|
||
where += ` AND p.direction = $${params.length}`;
|
||
}
|
||
if (status) {
|
||
params.push(status);
|
||
where += ` AND p.status = $${params.length}`;
|
||
}
|
||
params.push(limit);
|
||
|
||
const result = await pool.query<LocalRow>(
|
||
// ⚠️ 展示名在 public.profiles(auth.users 没有 full_name/username)—— 上一轮踩过
|
||
`SELECT p.*,
|
||
COALESCE(NULLIF(TRIM(ru.full_name), ''), NULLIF(TRIM(ru.username), ''), '') AS requested_by_name,
|
||
COALESCE(NULLIF(TRIM(vu.full_name), ''), NULLIF(TRIM(vu.username), ''), '') AS reviewed_by_name
|
||
FROM quote_price_proposals p
|
||
LEFT JOIN public.profiles ru ON ru.id = p.requested_by
|
||
LEFT JOIN public.profiles vu ON vu.id = p.reviewed_by
|
||
${where}
|
||
ORDER BY p.requested_at DESC
|
||
LIMIT $${params.length}`,
|
||
params
|
||
);
|
||
const rows = result.rows.map((row) => toDto(row));
|
||
|
||
// pending 的 B 方向:附「改前 → 改后」(当前单明细 vs 提议价),供审批人直接看差
|
||
const pendingFromDelivery = rows.filter(
|
||
(row) => row.status === 'pending' && row.direction === 'from_delivery'
|
||
);
|
||
if (pendingFromDelivery.length) {
|
||
const codes = [...new Set(pendingFromDelivery.map((row) => row.quote_sheet_code))];
|
||
const items = await pool.query<LocalRow>(
|
||
`SELECT quote_sheet_code, sku_code, sku_name, unit, sale_price, price
|
||
FROM customer_quote_sheet_items WHERE quote_sheet_code = ANY($1)`,
|
||
[codes]
|
||
);
|
||
const bySheet = new Map<string, Map<string, LocalRow>>();
|
||
for (const row of items.rows) {
|
||
const sheet = String(row.quote_sheet_code);
|
||
if (!bySheet.has(sheet)) bySheet.set(sheet, new Map());
|
||
bySheet.get(sheet)!.set(String(row.sku_code), row);
|
||
}
|
||
// 提议 items 的 sku_code 有两种约定:
|
||
// ① 配送侧**手动**发起:给的是「配送 SKU」⇒ 需要反查映射得到我方 SKU;
|
||
// ② 配送侧「按分类提交成本价」:给的是**我方 SKU**(发送前已按映射换过)⇒ 直接用。
|
||
const itemCodes = [
|
||
...new Set(
|
||
pendingFromDelivery.flatMap((row) => row.items.map((item) => toText(item.sku_code))).filter(Boolean)
|
||
),
|
||
];
|
||
const localSkus = new Map<string, { sku_name: string | null; unit: string | null }>();
|
||
const deliveryToSupplier = new Map<string, string>();
|
||
const supplierToDelivery = new Map<
|
||
string,
|
||
{ delivery_sku_code: string; delivery_sku_name: string | null; supplier_sku_name: string | null }
|
||
>();
|
||
if (itemCodes.length) {
|
||
const localRows = await pool.query<{ sku_code: string; sku_name: string | null; unit: string | null }>(
|
||
`SELECT sku_code, sku_name, unit FROM skus WHERE sku_code = ANY($1)`,
|
||
[itemCodes]
|
||
);
|
||
for (const r of localRows.rows) {
|
||
localSkus.set(String(r.sku_code), {
|
||
sku_name: r.sku_name == null ? null : String(r.sku_name),
|
||
unit: r.unit == null ? null : String(r.unit),
|
||
});
|
||
}
|
||
const mappings = await pool.query<{
|
||
supplier_sku_code: string;
|
||
supplier_sku_name: string | null;
|
||
delivery_sku_code: string;
|
||
delivery_sku_name: string | null;
|
||
}>(
|
||
`SELECT supplier_sku_code, supplier_sku_name, delivery_sku_code, delivery_sku_name
|
||
FROM main_system_sku_mappings
|
||
WHERE status = 'active'
|
||
AND (delivery_sku_code = ANY($1) OR supplier_sku_code = ANY($1))`,
|
||
[itemCodes]
|
||
);
|
||
for (const m of mappings.rows) {
|
||
deliveryToSupplier.set(String(m.delivery_sku_code), String(m.supplier_sku_code));
|
||
supplierToDelivery.set(String(m.supplier_sku_code), {
|
||
delivery_sku_code: String(m.delivery_sku_code),
|
||
delivery_sku_name: m.delivery_sku_name == null ? null : String(m.delivery_sku_name),
|
||
supplier_sku_name: m.supplier_sku_name == null ? null : String(m.supplier_sku_name),
|
||
});
|
||
}
|
||
}
|
||
for (const row of pendingFromDelivery) {
|
||
const current = bySheet.get(row.quote_sheet_code) || new Map();
|
||
row.lines = row.items.map((item) => {
|
||
const code = toText(item.sku_code);
|
||
const isLocalSupplierSku = localSkus.has(code);
|
||
const supplierSku = isLocalSupplierSku ? code : deliveryToSupplier.get(code) || null;
|
||
const before = supplierSku ? current.get(supplierSku) : undefined;
|
||
const local = supplierSku ? localSkus.get(supplierSku) : undefined;
|
||
const mirrored = supplierSku ? supplierToDelivery.get(supplierSku) : undefined;
|
||
const supplierName = before?.sku_name
|
||
? String(before.sku_name)
|
||
: local?.sku_name ?? mirrored?.supplier_sku_name ?? null;
|
||
return {
|
||
sku_code: code,
|
||
supplier_sku_code: supplierSku,
|
||
sku_name: supplierName,
|
||
unit: item.unit || (before?.unit ? String(before.unit) : local?.unit ?? null),
|
||
before_sale_price: before ? readSheetPrice(before) : null,
|
||
after_sale_price: roundPrice(item.price),
|
||
change: !supplierSku ? ('unmapped' as const) : before ? ('updated' as const) : ('added' as const),
|
||
delivery_sku_code: mirrored?.delivery_sku_code ?? (isLocalSupplierSku ? null : code),
|
||
delivery_sku_name: mirrored?.delivery_sku_name ?? null,
|
||
};
|
||
});
|
||
}
|
||
}
|
||
return { rows, sync };
|
||
}
|
||
|
||
/* ── 方向 B:审批(按行写 sale_price → rearm 推对方 cost_price → D3 回执)────── */
|
||
|
||
/** 锁并校验本地提议(方向 B 专用):存在 / 本分公司 / 方向对 / 仍 pending */
|
||
async function loadLocalProposalForDecision(
|
||
client: import('pg').PoolClient,
|
||
input: { id: string; branchCode: string; expectedDirection: 'from_delivery' }
|
||
): Promise<LocalRow> {
|
||
const locked = await client.query<LocalRow>(
|
||
`SELECT * FROM quote_price_proposals WHERE id = $1::uuid FOR UPDATE`,
|
||
[input.id]
|
||
);
|
||
if (!locked.rows.length) throw httpError(404, 'proposal_not_found', '价格提议不存在');
|
||
const row = locked.rows[0];
|
||
if (String(row.branch_code) !== input.branchCode) {
|
||
throw httpError(403, 'branch_mismatch', '无权操作其它分公司的价格提议');
|
||
}
|
||
if (String(row.direction) !== input.expectedDirection) {
|
||
throw httpError(400, 'wrong_direction', '只有「配送商成本价确认」的提议可在此审批');
|
||
}
|
||
if (String(row.status) !== 'pending') {
|
||
throw httpError(409, 'already_decided', '该价格提议已处理');
|
||
}
|
||
return row;
|
||
}
|
||
|
||
/**
|
||
* A16(verifier 阻断项):审批前**向配送侧确认该提议仍是 pending**。
|
||
*
|
||
* 为什么必须查:配送侧重复发起 B 时会把旧 pending 置 `superseded` 再插新 pending;若本地同步还没跑到,
|
||
* 用户对**旧 id** 点通过就会把**已撤回的价**写进报价单并推给配送侧(D3 才 409,为时已晚)。
|
||
*
|
||
* verifier 第二轮指出**原实现 fail-open + 只看第一页**:D2 是 `ORDER BY updated_at ASC LIMIT 200`(最旧 200 行),
|
||
* 被 supersede 的旧行 `updated_at` 很新 ⇒ 不在第一页;旧实现"找不到就放行" ⇒ 仍会写已撤回价。
|
||
*
|
||
* 现在的口径(失败关闭):
|
||
* ① 先带 `proposal_id` 精确查(配送侧新增 `?proposal_id=`);
|
||
* ② 不支持精确查/没命中 ⇒ 用 `next_cursor` **翻页直到找到或耗尽**(上限 20 页);
|
||
* ③ **找不到 ⇒ 409 `remote_status_unverified`**(绝不放行);D2 不可用同样 409。
|
||
* 事务外调用(出网不得在事务里)。
|
||
*/
|
||
const REMOTE_STATUS_MAX_PAGES = 20;
|
||
|
||
async function assertRemoteProposalStillPending(input: {
|
||
supplierCode: string;
|
||
proposalId: string;
|
||
}): Promise<void> {
|
||
let cursor: string | null = null;
|
||
for (let page = 0; page < REMOTE_STATUS_MAX_PAGES; page += 1) {
|
||
const listed = await listQuotePriceProposals({
|
||
supplierCode: input.supplierCode,
|
||
proposalId: input.proposalId,
|
||
cursor,
|
||
limit: 200,
|
||
});
|
||
if (listed.kind !== 'ok') {
|
||
// 无法确认状态时**失败关闭**:宁可不批,也不把可能已撤回的价写下去
|
||
throw httpError(409, 'remote_status_unverified', '无法确认该提议在配送侧的最新状态,请稍后重试');
|
||
}
|
||
const remote = listed.rows.find((row) => row.proposal_id === input.proposalId);
|
||
if (remote) {
|
||
if (remote.status !== 'pending') {
|
||
const label =
|
||
remote.status === 'superseded'
|
||
? '已被新的提议替代'
|
||
: remote.status === 'approved'
|
||
? '已通过'
|
||
: remote.status === 'rejected'
|
||
? '已驳回'
|
||
: '已撤回';
|
||
throw httpError(409, 'proposal_not_pending', `该提议在配送侧${label},不能按旧价审批,请刷新列表`);
|
||
}
|
||
return;
|
||
}
|
||
if (!listed.nextCursor || listed.nextCursor === cursor) break; // 耗尽(或游标不前进)
|
||
cursor = listed.nextCursor;
|
||
}
|
||
// 翻页耗尽仍未找到 ⇒ **失败关闭**(旧实现这里会放行,是 verifier 抓到的阻断项)
|
||
throw httpError(
|
||
409,
|
||
'remote_status_unverified',
|
||
'无法在配送侧确认该提议的状态(已翻页查找),请刷新后重试'
|
||
);
|
||
}
|
||
|
||
|
||
/** 目标单不可用(编辑路径的普通 Error)⇒ 审批路径 409 `target_unavailable` */
|
||
function mapSheetUnavailable(error: any): Error | null {
|
||
const message = String(error?.message || '');
|
||
if (
|
||
message === '报价单不存在' ||
|
||
message === '仅执行中的报价单可修改' ||
|
||
message === '报价单已过期,无法修改'
|
||
) {
|
||
return httpError(409, 'target_unavailable', message);
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* T2:按 `MAIN_<main_branch_code>` 解析**唯一生效单**(`status=1 & approval_status=30 & 未过期`)。
|
||
*
|
||
* 0 张 ⇒ 调用方 409 `no_quote_sheet`;多张 ⇒ 409 `ambiguous_sheet`(**不做"全写"扇出**)。
|
||
* 真库 BR002 存在"同一客户多张生效单"的历史数据,所以这个闸门必须显式。
|
||
*/
|
||
export async function resolveActiveSheetCodeForMainBranch(
|
||
mainBranchCode: string
|
||
): Promise<{ candidates: string[] }> {
|
||
const customerCode = `MAIN_${toText(mainBranchCode).toUpperCase()}`;
|
||
const result = await pool.query<{ quote_sheet_code: string }>(
|
||
`SELECT qs.quote_sheet_code
|
||
FROM customer_quote_sheets qs
|
||
WHERE qs.status = 1
|
||
AND qs.approval_status = 30
|
||
AND (qs.expires_at IS NULL OR qs.expires_at > NOW())
|
||
AND EXISTS (
|
||
SELECT 1 FROM customer_quote_sheet_customers qc
|
||
WHERE qc.quote_sheet_code = qs.quote_sheet_code
|
||
AND UPPER(TRIM(qc.customer_code)) = UPPER($1)
|
||
)
|
||
ORDER BY qs.version_no DESC NULLS LAST, qs.updated_at DESC NULLS LAST, qs.created_at DESC NULLS LAST`,
|
||
[customerCode]
|
||
);
|
||
return { candidates: result.rows.map((row) => String(row.quote_sheet_code)) };
|
||
}
|
||
|
||
async function resolveUniqueTargetSheet(
|
||
mainBranchCode: string
|
||
): Promise<string> {
|
||
const { candidates } = await resolveActiveSheetCodeForMainBranch(mainBranchCode);
|
||
if (!candidates.length) {
|
||
throw httpError(409, 'no_quote_sheet', `没有找到 MAIN_${toText(mainBranchCode)} 对应且生效中的报价单`);
|
||
}
|
||
if (candidates.length > 1) {
|
||
throw httpError(
|
||
409,
|
||
'ambiguous_sheet',
|
||
`MAIN_${toText(mainBranchCode)} 对应多张生效报价单(${candidates.join('、')}),请先收敛后再审批`
|
||
);
|
||
}
|
||
return candidates[0];
|
||
}
|
||
|
||
/** 逐行审计:每个真正变更的 (报价单, SKU) 一条(best-effort,提交后写) */
|
||
function auditAppliedPriceRows(input: {
|
||
operatorId?: string | null;
|
||
operatorRole?: string | null;
|
||
branchCode: string;
|
||
quoteSheetCode: string;
|
||
proposalId: string;
|
||
rows: Array<{ itemId: string; skuCode: string; unit: string | null; oldPrice: number; newPrice: number }>;
|
||
}): void {
|
||
for (const row of input.rows) {
|
||
void writeAuditLog({
|
||
operatorId: input.operatorId || null,
|
||
operatorRole: input.operatorRole || null,
|
||
operationType: 'quote_price_proposal_apply',
|
||
targetTable: 'customer_quote_sheet_items',
|
||
targetId: row.itemId,
|
||
oldValue: {
|
||
quote_sheet_code: input.quoteSheetCode,
|
||
sku_code: row.skuCode,
|
||
unit: row.unit,
|
||
sale_price: row.oldPrice,
|
||
source: 'delivery_price_proposal',
|
||
proposal_id: input.proposalId,
|
||
},
|
||
newValue: {
|
||
quote_sheet_code: input.quoteSheetCode,
|
||
sku_code: row.skuCode,
|
||
unit: row.unit,
|
||
sale_price: row.newPrice,
|
||
source: 'delivery_price_proposal',
|
||
proposal_id: input.proposalId,
|
||
},
|
||
branchCode: input.branchCode,
|
||
actionCategory: 'quote_price_proposal',
|
||
}).catch((error: any) => {
|
||
console.warn('[quote-price-proposal] 行审计写入失败(best-effort):', error?.message || error);
|
||
});
|
||
}
|
||
}
|
||
|
||
export type ApproveResult = {
|
||
proposal: QuotePriceProposalDto;
|
||
applied: {
|
||
updated: number;
|
||
unchanged: number;
|
||
skipped: Array<{ sku_code: string; reason: string; detail?: string }>;
|
||
};
|
||
receiptSent: boolean;
|
||
};
|
||
|
||
/**
|
||
* 方向 B 通过(T3:**只按行 UPDATE**,绝不整表替换):
|
||
*
|
||
* 单事务内对 payload 里出现的 `sku_code` 逐行:
|
||
* `UPDATE customer_quote_sheet_items SET sale_price = $3, price = $3
|
||
* WHERE quote_sheet_code = $1 AND sku_code = $2`
|
||
* —— 只改已有行、**不 INSERT / 不 DELETE / 不改单结构 / 不动其它 SKU**;
|
||
* 缺行 ⇒ `sku_not_in_sheet`;单位不一致(双方都非空且不等)⇒ `unit_mismatch`;
|
||
* 金额不合法(≤0 或 >9,999,999.99)⇒ `invalid_price`;值未变 ⇒ 不写(计入 unchanged)。
|
||
* COMMIT 之后:每行审计(best-effort)→ D3 回执 `approved`(带 applied;配送侧据此用配送 SKU 写自己的 cost_price)。
|
||
*/
|
||
export async function approvePriceProposal(input: {
|
||
id: string;
|
||
ctx?: TenantContext | null;
|
||
operatingBranchCode?: string | null;
|
||
reviewedBy?: string | null;
|
||
}): Promise<ApproveResult> {
|
||
if (!isQuotePriceProposalEnabled()) {
|
||
throw httpError(503, 'feature_disabled', '报价单价格传递未开启(MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL)');
|
||
}
|
||
const branchCode = getEffectiveBranchCode(input.ctx || null, input.operatingBranchCode);
|
||
if (!branchCode) throw httpError(400, 'branch_required', '请选择当前操作分公司');
|
||
|
||
/**
|
||
* 事务外预检(出网不得在事务里):
|
||
* ① 本地行存在/本分公司/方向对/仍 pending;
|
||
* ② 远端仍是 pending(A16:防"旧 id 把已撤回价写下去")。事务内会再锁行复验一次。
|
||
*/
|
||
const preloaded = await pool.query<LocalRow>(
|
||
`SELECT * FROM quote_price_proposals WHERE id = $1::uuid`,
|
||
[input.id]
|
||
);
|
||
if (!preloaded.rows.length) throw httpError(404, 'proposal_not_found', '价格提议不存在');
|
||
const preRow = preloaded.rows[0];
|
||
if (String(preRow.branch_code) !== branchCode) {
|
||
throw httpError(403, 'branch_mismatch', '无权操作其它分公司的价格提议');
|
||
}
|
||
if (String(preRow.direction) !== 'from_delivery') {
|
||
throw httpError(400, 'wrong_direction', '只有「配送商成本价确认」的提议可在此审批');
|
||
}
|
||
if (String(preRow.status) !== 'pending') {
|
||
throw httpError(409, 'already_decided', '该价格提议已处理');
|
||
}
|
||
const preSupplierCode = await resolveMainSupplierCode(branchCode);
|
||
if (preRow.remote_proposal_id) {
|
||
if (!preSupplierCode) {
|
||
throw httpError(409, 'main_supplier_code_missing', '该分公司在主系统没有可用供应商编码,无法核对/回执提议');
|
||
}
|
||
await assertRemoteProposalStillPending({
|
||
supplierCode: preSupplierCode,
|
||
proposalId: String(preRow.remote_proposal_id),
|
||
});
|
||
}
|
||
|
||
const client = await pool.connect();
|
||
let committed = false;
|
||
let row: LocalRow;
|
||
let quoteSheetCode = '';
|
||
const changedRows: Array<{ itemId: string; skuCode: string; unit: string | null; oldPrice: number; newPrice: number }> = [];
|
||
const applied: ApproveResult['applied'] = { updated: 0, unchanged: 0, skipped: [] };
|
||
try {
|
||
await client.query('BEGIN');
|
||
row = await loadLocalProposalForDecision(client, {
|
||
id: input.id,
|
||
branchCode,
|
||
expectedDirection: 'from_delivery',
|
||
});
|
||
|
||
// T2:目标单按 MAIN_<主系统分公司> 唯一解析(0 ⇒ no_quote_sheet;多 ⇒ ambiguous_sheet)
|
||
quoteSheetCode = await resolveUniqueTargetSheet(String(row.main_branch_code));
|
||
try {
|
||
await loadQuoteSheetForUpdate(quoteSheetCode, input.ctx, input.operatingBranchCode);
|
||
} catch (error: any) {
|
||
throw mapSheetUnavailable(error) || error;
|
||
}
|
||
|
||
const current = await client.query<LocalRow>(
|
||
`SELECT id::text AS id, sku_code, unit, sale_price, price
|
||
FROM customer_quote_sheet_items
|
||
WHERE quote_sheet_code = $1`,
|
||
[quoteSheetCode]
|
||
);
|
||
const currentBySku = new Map(current.rows.map((item) => [String(item.sku_code), item]));
|
||
|
||
const proposalItems = Array.isArray(row.items) ? (row.items as QuotePriceProposalItemPayload[]) : [];
|
||
if (!proposalItems.length) throw httpError(400, 'items_required', '该提议没有可应用的商品行');
|
||
|
||
/**
|
||
* ⭐ 提议 items 里的 `sku_code` 是**配送 SKU**(契约 §5):必须先反查本地映射得到**我方 SKU**,
|
||
* 查不到 ⇒ skip `sku_unmapped`(**绝不按 sku_code 直接猜** —— 两个系统的 SKU 本来就不一致)。
|
||
*/
|
||
const resolvedSupplierSkus = new Set<string>();
|
||
for (const item of proposalItems) {
|
||
const deliverySku = toText(item.sku_code);
|
||
const price = roundPrice(item.price);
|
||
if (!deliverySku) {
|
||
applied.skipped.push({ sku_code: '', reason: 'invalid_item' });
|
||
continue;
|
||
}
|
||
if (!(price > 0) || price > MAX_PROPOSAL_PRICE) {
|
||
applied.skipped.push({ sku_code: deliverySku, reason: 'invalid_price' });
|
||
continue;
|
||
}
|
||
const mapping = await getMappingByDeliverySku(branchCode, deliverySku);
|
||
if (!mapping) {
|
||
applied.skipped.push({ sku_code: deliverySku, reason: 'sku_unmapped' });
|
||
continue;
|
||
}
|
||
const skuCode = mapping.supplier_sku_code;
|
||
if (resolvedSupplierSkus.has(skuCode)) {
|
||
// 多个配送 SKU 映射到同一我方 SKU:只按第一个处理,避免重复计数/重复审计
|
||
applied.skipped.push({ sku_code: deliverySku, reason: 'duplicate_supplier_sku', detail: skuCode });
|
||
continue;
|
||
}
|
||
const target = currentBySku.get(skuCode);
|
||
if (!target) {
|
||
applied.skipped.push({ sku_code: deliverySku, reason: 'sku_not_in_sheet', detail: skuCode });
|
||
continue;
|
||
}
|
||
// 单位闸门照旧:payload 单位(配送侧)与报价单行单位归一比较,不等就跳过并标注(契约决策 3)
|
||
const proposalUnit = toText(item.unit);
|
||
const rowUnit = toText(target.unit);
|
||
if (proposalUnit && rowUnit && proposalUnit.toLowerCase() !== rowUnit.toLowerCase()) {
|
||
applied.skipped.push({
|
||
sku_code: deliverySku,
|
||
reason: 'unit_mismatch',
|
||
detail: `${proposalUnit} vs ${rowUnit}`,
|
||
});
|
||
continue;
|
||
}
|
||
resolvedSupplierSkus.add(skuCode);
|
||
const oldPrice = roundPrice(target.sale_price ?? target.price);
|
||
if (Math.abs(oldPrice - price) <= 1e-6) {
|
||
applied.unchanged += 1;
|
||
continue;
|
||
}
|
||
// ⭐ T3 唯一写价语句:按 (quote_sheet_code, sku_code) 定点 UPDATE,只改 sale_price/price 两列
|
||
const updatedRow = await client.query<{ id: string }>(
|
||
`UPDATE customer_quote_sheet_items
|
||
SET sale_price = $3, price = $3
|
||
WHERE quote_sheet_code = $1 AND sku_code = $2
|
||
RETURNING id::text AS id`,
|
||
[quoteSheetCode, skuCode, price]
|
||
);
|
||
if (!updatedRow.rows.length) {
|
||
applied.skipped.push({ sku_code: deliverySku, reason: 'sku_not_in_sheet', detail: skuCode });
|
||
continue;
|
||
}
|
||
applied.updated += 1;
|
||
changedRows.push({
|
||
itemId: String(updatedRow.rows[0].id),
|
||
skuCode,
|
||
unit: rowUnit || null,
|
||
oldPrice,
|
||
newPrice: price,
|
||
});
|
||
}
|
||
|
||
const updatedRow = await client.query<LocalRow>(
|
||
`UPDATE quote_price_proposals
|
||
SET status = 'approved', quote_sheet_code = $2, reviewed_by = $3::uuid,
|
||
reviewed_at = NOW(), applied_at = NOW(), reject_reason = NULL, updated_at = NOW()
|
||
WHERE id = $1::uuid AND status = 'pending'
|
||
RETURNING *`,
|
||
[row.id, quoteSheetCode, input.reviewedBy ?? null]
|
||
);
|
||
if (!updatedRow.rows.length) throw httpError(409, 'already_decided', '该价格提议已处理');
|
||
row = updatedRow.rows[0];
|
||
await client.query('COMMIT');
|
||
committed = true;
|
||
} catch (error) {
|
||
if (!committed) {
|
||
try {
|
||
await client.query('ROLLBACK');
|
||
} catch {
|
||
/* ignore */
|
||
}
|
||
}
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
|
||
// 提交之后:① 每行审计(best-effort)② 既有 rearm 推对方 cost_price(本层不重造推送、不写台账)
|
||
auditAppliedPriceRows({
|
||
operatorId: input.ctx?.userId || input.reviewedBy || null,
|
||
operatorRole: input.ctx?.roles?.join(',') || null,
|
||
branchCode,
|
||
quoteSheetCode,
|
||
proposalId: String(row.id),
|
||
rows: changedRows,
|
||
});
|
||
/**
|
||
* ⛔ **B 审批不再走旧的成本同步推送**(2026-10-18 verifier 阻断项修正):
|
||
* 旧通道按 `sku_code` 直猜、还跳过共享单;两个系统 SKU 本就不一致 ⇒ 推过去配送 `cost_price` 静默不变。
|
||
* 现在由**配送侧在 D3 `decision='approved'` 时**用提议里的**配送 SKU** 落地写价(共享单同样按映射写)。
|
||
* `triggerQuoteCostSync` 只保留在**报价单生效自动推**那条链路(`quoteSheetService`),本函数不再调用。
|
||
*/
|
||
auditProposal({
|
||
operatorId: input.ctx?.userId || input.reviewedBy || null,
|
||
operatorRole: input.ctx?.roles?.join(',') || null,
|
||
action: 'approve',
|
||
branchCode,
|
||
proposalId: String(row.id),
|
||
quoteSheetCode,
|
||
direction: 'from_delivery',
|
||
status: 'approved',
|
||
});
|
||
|
||
// D3 回执(事务外;失败只记 warning,下次 D2 轮询按「本地终态 + 远端 pending」自动重发 —— T8)
|
||
let receiptSent = false;
|
||
const supplierCode = await resolveMainSupplierCode(branchCode);
|
||
if (supplierCode && row.remote_proposal_id) {
|
||
receiptSent = await deliverDecisionReceipt({
|
||
supplierCode,
|
||
proposalId: String(row.remote_proposal_id),
|
||
decision: 'approved',
|
||
// A20:回执必须带写价统计(配送侧只记录、不写价),否则对方 proposal 的 applied 恒为 null
|
||
applied: { updated: applied.updated, skipped: applied.skipped },
|
||
});
|
||
if (!receiptSent) {
|
||
console.warn(`[quote-price-proposal] D3 回执失败(approved ${row.remote_proposal_id}),等待下轮自动重发`);
|
||
}
|
||
}
|
||
return { proposal: toDto(row), applied, receiptSent };
|
||
}
|
||
|
||
export type RejectResult = { proposal: QuotePriceProposalDto; receiptSent: boolean };
|
||
|
||
/** 方向 B 驳回:只记状态 + 理由,**不写价、不推送**,D3 回执 `rejected`。 */
|
||
export async function rejectPriceProposal(input: {
|
||
id: string;
|
||
reason: string;
|
||
ctx?: TenantContext | null;
|
||
operatingBranchCode?: string | null;
|
||
reviewedBy?: string | null;
|
||
}): Promise<RejectResult> {
|
||
if (!isQuotePriceProposalEnabled()) {
|
||
throw httpError(503, 'feature_disabled', '报价单价格传递未开启(MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL)');
|
||
}
|
||
const branchCode = getEffectiveBranchCode(input.ctx || null, input.operatingBranchCode);
|
||
if (!branchCode) throw httpError(400, 'branch_required', '请选择当前操作分公司');
|
||
const reason = toText(input.reason);
|
||
if (!reason) throw httpError(400, 'reject_reason_required', '请填写驳回理由');
|
||
|
||
const client = await pool.connect();
|
||
let row: LocalRow;
|
||
try {
|
||
await client.query('BEGIN');
|
||
row = await loadLocalProposalForDecision(client, {
|
||
id: input.id,
|
||
branchCode,
|
||
expectedDirection: 'from_delivery',
|
||
});
|
||
const updatedRow = await client.query<LocalRow>(
|
||
`UPDATE quote_price_proposals
|
||
SET status = 'rejected', reject_reason = $2, reviewed_by = $3::uuid,
|
||
reviewed_at = NOW(), updated_at = NOW()
|
||
WHERE id = $1::uuid AND status = 'pending'
|
||
RETURNING *`,
|
||
[row.id, reason, input.reviewedBy ?? null]
|
||
);
|
||
if (!updatedRow.rows.length) throw httpError(409, 'already_decided', '该价格提议已处理');
|
||
row = updatedRow.rows[0];
|
||
await client.query('COMMIT');
|
||
} catch (error) {
|
||
try {
|
||
await client.query('ROLLBACK');
|
||
} catch {
|
||
/* ignore */
|
||
}
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
|
||
auditProposal({
|
||
operatorId: input.ctx?.userId || input.reviewedBy || null,
|
||
operatorRole: input.ctx?.roles?.join(',') || null,
|
||
action: 'reject',
|
||
branchCode,
|
||
proposalId: String(row.id),
|
||
quoteSheetCode: String(row.quote_sheet_code),
|
||
direction: 'from_delivery',
|
||
status: 'rejected',
|
||
reason,
|
||
});
|
||
|
||
let receiptSent = false;
|
||
const supplierCode = await resolveMainSupplierCode(branchCode);
|
||
if (supplierCode && row.remote_proposal_id) {
|
||
receiptSent = await deliverDecisionReceipt({
|
||
supplierCode,
|
||
proposalId: String(row.remote_proposal_id),
|
||
decision: 'rejected',
|
||
reason,
|
||
});
|
||
if (!receiptSent) {
|
||
console.warn(`[quote-price-proposal] D3 回执失败(rejected ${row.remote_proposal_id}),等待下轮自动重发`);
|
||
}
|
||
}
|
||
return { proposal: toDto(row), receiptSent };
|
||
}
|
||
|
||
export const __testables = {
|
||
proposalPayloadHash,
|
||
quoteCostSyncItemsFingerprint,
|
||
};
|