Files
SupplierSystem/server/src/services/mainSystemBranchApi.ts
T
Ubuntu 44a660e18a
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
perf(跨系统): 出站闸门唯一化 + 无未决不拉(未绑编码 = 零沟通)
开发者要求:未绑接入编码的分公司全程不该与主系统沟通;后面可能几千家,
有的连主系统有的不连。核查发现 8-13 的收紧只闸住了"拉货"一条路:

- 申请列表 Q5/Q6(实收对账 / 我方价量对账 / 归档反查 / 按行分组)仍读"任何 active 绑定"
  ⇒ 迁移回填行、空接入编码行也解析出 supplier_code ⇒ 抱着注定 403 的编码换 Token + 发 GET
  (对方已收紧为「必须有接入编码才放行」,回执 §4.5.22)
- 定时对账 fan-out 名单用"有任何 active 绑定行"⇒ 这些分公司每轮白跑一遍
- 两条对账**先拉后判**:本地一条待审都没有也每 10 分钟发一次 GET

P1(判定点唯一):
- branchAccessCode:新增 listConnectableBindingsForBranch(四条规则压进一条 JOIN)+
  listConnectableBranchCodes(同谓词的分公司名单);listAutoPullableBindingsForBranch 保留旧名转发
- mainSystemBranchApi.listSupplierCodesForBranch → 同一判定点(出站正门)
- mainSystemOrderImport.listMainSupplierBranchCodes → listConnectableBranchCodes(fan-out 名单)

P2(无未决 ⇒ 不拉):
- reconcilePendingActualQtyRequests / reconcileOurPriceQtyRequestsWithMainSystem
  先查本地待审计数(轻查询),为 0 直接返回 —— 两者本来就只处理本地 pending 行,语义无变化

验证(真库冒烟,本地栈):
- 已绑编码的 BR002/BR003:仍进名单、仍解析出 1/2 条编码、拉取 ok(真 HTTP);
  真跑 fan-out branches=2 / failed=0
- 反证:临时清空 BR003 编码 ⇒ 名单 ["BR002"]、编码 []、拉取 not_bound(零 HTTP),BR002 不受影响;
  夹具已还原(残留 0)
- P2:0 条待审 ⇒ 跳过拉取;BR002 现库 1 条真实待审 ⇒ 不短路照旧拉;探针待审 ⇒ 立刻恢复真拉取
- 用例:mainSystemReconcileShortCircuit.test.ts(4 例,新)+ bindingAutoPullGuard P1/P2 段(14 例)
  + mainSystemBranchApi(11 例);服务端 tsc 0 错;全量 26 failed/377 passed 与基线持平
- 设计文 docs/design/20261013-主系统订单被本地拉取机制与绑定缺陷.md §9(收益估算:1000 家 43万→14万 GET/天)
2026-10-13 14:28:30 +08:00

190 lines
8.5 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 { pool } from '../db';
import { listConnectableBindingsForBranch } from './branchAccessCode';
import {
fetchMainSystemArchivedPreparations,
lookupMainSystemPreparationStates,
type MainOrderGroup,
type MainPreparationsOutcome,
type PrepLookupOutcome,
type PrepLookupResult,
} from './mainSystemPreparations';
// 申请列表(Q6)不在门面里 —— 与既有调用方(mainSystemPriceQtyRequest / mainSystemActualQtyInbox)同一来源
import {
listMainSystemRequests,
type MainSystemRequestListOutcome,
type MainSystemRequestRow,
} from './mainSystem/api/preparations';
/**
* 「**按分公司**」调用主系统只读接口(2026-10-10 补,接入编码落地的收尾)。
*
* 为什么必须有这一层:主系统那些接口的第一参数是 **`supplier_code`**(按"供货关系"鉴权),
* 而在旧的"`branch_code` == `supplier_code`"约定下,我方各处直接拿**分公司编码**当参数传 ——
* 编码解耦后这些调用**必然 403**(实测:`forbidden: …尚未绑定子系统接入编码`)。
* 而它们全是"兜底/跟随"路径(失败只记日志继续跑)⇒ **静默失效**,比报错更难查。
*
* 本模块把"分公司 → 该用哪些 supplier_code"收敛到一处:
* · 拉取(列表/归档/申请列表):遍历该分公司**全部生效绑定**的 supplier_code,合并结果;
* · 逐行查询(lookup):按**行级台账**里该 `prep_id` 的 `main_supplier_code` 把 items 分组,逐组调用。
* 写回路径(发车/缺货/改价改量/决策回执)用的是 `branchAccessCode.resolveSupplierCodeForPrep`,
* 与本模块同源同口径。
*
* ⚠️ 纪律:调用方**不要**再自己把 `branchCode` 传进 `supplierCode` 参数(有回归守卫钉住)。
*/
/**
* 该分公司**可出站**的主系统供应商编码(去重、稳定顺序)。
*
* ⚠️ 2026-10-13:改用 **`listConnectableBindingsForBranch`**(= 拉货侧同一判定点)——
* 以前读「任何 active 绑定」,于是**迁移回填行/空接入编码行**也会解析出编码 ⇒ 对账会抱着
* 注定 403 的编码去换 Token + 发 GET(对方已收紧为「必须有接入编码才放行」,回执 §4.5.22)。
* 现在未绑编码 ⇒ 返回 `[]` ⇒ 调用方走 `unavailable/not_bound` 分支,**一个请求都不发**。
*/
export async function listSupplierCodesForBranch(branchCode: string): Promise<string[]> {
const code = String(branchCode || '').trim();
if (!code) return [];
const bindings = await listConnectableBindingsForBranch(code);
return [...new Set(bindings.map((item) => item.mainSupplierCode).filter(Boolean))];
}
/** 把一批"行"按供应商编码分组;台账缺失时回退该分公司**唯一**绑定(多绑定时不猜,留给调用方跳过) */
export async function groupItemsBySupplierCode<T extends { id?: string | null }>(params: {
branchCode: string;
items: T[];
}): Promise<Map<string, T[]>> {
const groups = new Map<string, T[]>();
const code = String(params.branchCode || '').trim();
const items = params.items.filter((item) => String(item?.id || '').trim());
if (!code || !items.length) return groups;
const prepIds = [...new Set(items.map((item) => String(item.id).trim()))];
const ledger = await pool
.query<{ prep_id: string; main_supplier_code: string | null }>(
`SELECT prep_id::text AS prep_id, main_supplier_code
FROM public.main_system_order_import_items
WHERE branch_code = $1 AND prep_id::text = ANY($2::text[])`,
[code, prepIds]
)
.catch(() => ({ rows: [] as Array<{ prep_id: string; main_supplier_code: string | null }> }));
const byPrep = new Map<string, string>();
for (const row of ledger.rows) {
const supplier = String(row.main_supplier_code || '').trim();
if (supplier) byPrep.set(String(row.prep_id), supplier);
}
const supplierCodes = await listSupplierCodesForBranch(code);
const soleSupplier = supplierCodes.length === 1 ? supplierCodes[0] : null;
const unmapped: T[] = [];
for (const item of items) {
const supplier = byPrep.get(String(item.id).trim()) || soleSupplier;
if (!supplier) {
unmapped.push(item);
continue;
}
if (!groups.has(supplier)) groups.set(supplier, []);
groups.get(supplier)!.push(item);
}
if (unmapped.length) {
// 不猜:多绑定且台账缺失时不硬塞给某一家,直接跳过并留一行日志(下一次导入会补上台账)
console.warn(
`[main-system-branch-api] ${code}:${unmapped.length} 行的供应商归属未知(台账缺失且绑定不唯一)⇒ 本轮跳过这些行`
);
}
return groups;
}
/**
* 逐行问状态(`POST /preparations/lookup`)——按分公司的**多绑定**分组调用并合并。
* 部分供应商失败时**保留**已成功的结果(这些调用是兜底路径,能推进多少算多少),
* 全失败才返回失败;返回结构与被替换的单供应商版本完全一致。
*/
export async function lookupPreparationStatesForBranch(
branchCode: string,
items: Array<{ orderCode: string; skuCode: string; id?: string | null }>
): Promise<PrepLookupOutcome> {
if (!items.length) return { kind: 'ok', results: [] };
const groups = await groupItemsBySupplierCode({ branchCode, items });
if (!groups.size) {
return { kind: 'unavailable', reason: '该分公司没有可用的主系统供应商绑定(或这些行归属未知)' };
}
const results: PrepLookupResult[] = [];
const failures: string[] = [];
for (const [supplierCode, groupItems] of groups) {
const outcome = await lookupMainSystemPreparationStates(supplierCode, groupItems);
if (outcome.kind !== 'ok') {
failures.push(`${supplierCode}: ${outcome.reason}`);
continue;
}
results.push(...outcome.results);
}
if (!results.length && failures.length) {
return { kind: 'unavailable', reason: failures.join(';') };
}
if (failures.length) {
console.warn(`[main-system-branch-api] ${branchCode} 部分供应商 lookup 失败:${failures.join(';')}`);
}
return { kind: 'ok', results };
}
/** 归档视图(退货跟随的备用反查):遍历该分公司全部绑定并合并 */
export async function fetchArchivedPreparationsForBranch(
branchCode: string,
range: { date?: string; dateFrom?: string; dateTo?: string }
): Promise<MainPreparationsOutcome> {
const codes = await listSupplierCodesForBranch(branchCode);
if (!codes.length) {
return { kind: 'rejected', reason: '该分公司未绑定任何主系统供应商(接入编码未被绑定)' };
}
const orders: MainOrderGroup[] = [];
let rowCount = 0;
let truncated = false;
let mainBranchCode: string | null = null;
let anyOk = false;
const failures: string[] = [];
for (const code of codes) {
const outcome = await fetchMainSystemArchivedPreparations(code, range);
if (outcome.kind === 'not_configured') return outcome;
if (outcome.kind !== 'ok') {
failures.push(`${code}: ${outcome.reason}`);
continue;
}
anyOk = true;
orders.push(...outcome.orders);
rowCount += outcome.rowCount;
truncated = truncated || Boolean(outcome.truncated);
mainBranchCode = outcome.branchCode ?? mainBranchCode;
}
if (!anyOk) return { kind: 'unavailable', reason: failures.join(';') || '归档视图拉取失败' };
return { kind: 'ok', supplierCode: codes.join(','), branchCode: mainBranchCode, orders, rowCount, truncated };
}
/** 申请列表(Q6 漏推自愈):遍历该分公司全部绑定并合并 */
export async function listRequestsForBranch(
branchCode: string,
options?: { kind?: string | null; status?: string | null; limit?: number; updatedSince?: string | null }
): Promise<MainSystemRequestListOutcome> {
const codes = await listSupplierCodesForBranch(branchCode);
if (!codes.length) {
return { kind: 'unavailable', reason: '该分公司未绑定任何主系统供应商(接入编码未被绑定)' };
}
const rows: MainSystemRequestRow[] = [];
let truncated = false;
let anyOk = false;
const failures: string[] = [];
for (const code of codes) {
const outcome = await listMainSystemRequests(code, options);
if (outcome.kind === 'not_configured') return outcome;
if (outcome.kind !== 'ok') {
failures.push(`${code}: ${outcome.reason}`);
continue;
}
anyOk = true;
rows.push(...outcome.rows);
truncated = truncated || outcome.truncated;
}
if (!anyOk) return { kind: 'unavailable', reason: failures.join(';') || '申请列表拉取失败' };
return { kind: 'ok', rows, truncated };
}