Files
SupplierSystem/server/src/services/branchBindingSync.ts
T
Ubuntu e1efe3b2e9
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
fix(对接体检): 回读通道鉴权改为 Bearer(与主系统实现对齐)+ 编码不认识单列原因并 warn
背景:主系统第八批已交付(`22ef34a8` 绑定入口 + `0dad08f3` binding.changed 推送),本轮做对接体检。

体检发现的**我方**缺口(已修):
  1. 回读通道鉴权不匹配:他们交付的 `GET /api/supplier/integration-bindings` 走
     `Authorization: Bearer <对接 token>`(按 token 所属 client 圈作用域),
     而我方初版按草稿发 `X-Client-Id`/`X-Client-Secret` ⇒ 会 401。已改为用
     `getMainSystemToken()` 换 token 后 Bearer 调用;并补 `?include_disabled=1`
     (默认只返回 status=1 ⇒ 不加就永远同步不到"解绑")。
     supplier_code 取法:镜像 active 绑定 → 分公司手工登记 → 台账最近值;都没有则跳过(冷启动无绑定可对账)。
  2. 「编码不认识」与「这家没绑我们」原先都回 `not_bound`,真机上分不清。现在单列
     `unknown_access_code`(并 `console.warn` 打出编码原值)—— 抄错一位是这条路上最可能的人为错,
     必须能从对方的投递日志/我方日志一眼看出。

体检发现(记录进清单 §2.11.4b,给我方待办):
  · 他们的 `bindIntegrationSupplier()` **不校验编码格式**,错码会静默变成"没绑"⇒ 建议加正则
    `^SC[23456789ABCDEFGHJKMNPQRSTUVWXYZ]{10}$`(P1 加固,我们已用 warn + 独立 reason 兜住可观测性)。

体检结论(他们的实现与契约逐条对齐):
  · 信封带 `subsystem_code`(`supplierPrepWebhookService.ts:149`,空码行为 null);
  · `binding.changed` 推送:事件名/字段(同时给 subsystem_code 与 access_code)/改绑=unbind+bind/
    目标解析不看 status(解绑也要推)✅;
  · 迁移 `20261014_supplier_integration_subsystem_code.sql` 加列 + 部分索引,且**空码 = 存量行为不变**;
  · P0-4:自动授权**只对已绑编码的行补**(`supplierIntegrationClientService.ts:420-440`)✅;
  · 回读端点按 token 的 client 圈作用域(无跨客户端视图)✅。

验证:服务端 2333 用例 / 失败 30、失败文件 24 = 与基线逐字相同(无新增失败);
branchAccessCode 14 例 + branchBindingSync 16 例全绿;tsc 通过;门禁同基线(check-ai-cost 既知红)。
2026-10-10 17:47:39 +08:00

324 lines
13 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 { config } from '../config';
import { pool } from '../db';
import { MAIN_SYSTEM_FETCH_TIMEOUT_MS } from './mainSystem/config';
import { getMainSystemToken } from './mainSystem/token';
import { findBranchCodeByAccessCode, unbindBinding, upsertBinding } from './branchAccessCode';
/**
* 主系统 → 我方 的**绑定关系同步**(2026-10-27 接入编码设计 §8 P0-2 的接收端)。
*
* 为什么需要它:绑定的权威在主系统侧(他们在 `supplier_integration_client_suppliers` 的
* `(branch_code, supplier_code)` 行上填我们的接入编码)。我方要按绑定路由/拉单,
* 就必须**知道**这份绑定;只有两个来源可选:
* ① **回调**(首选):他们绑定/解绑时把变更推给我们 —— 复用**现有 webhook 通道与验签**,
* 事件名 `binding.changed`(兼容 `preparations.binding_changed`),无需新端点、新密钥;
* ② **回读**(退路):他们给一个只读端点,我们定时拉全量 —— 端点 URL 配 `MAIN_SYSTEM_BINDING_SYNC_URL`
* 才启用(不配就只靠 ① + 超管手工登记,绝不去猜路径)。
*
* 两条通道最终都落到 `branchAccessCode.upsertBinding / unbindBinding`(唯一写入口),
* 因此**改绑留痕、唯一键约束、通配行回退**这些语义只有一处实现。
*
* 设计:docs/design/20261027-分公司接入编码与主系统供应商绑定.md §3.2 / §8
*/
/** 小工具:本文件里的只读查询(SQL 留在 service,路由层有裸 SQL 棘轮) */
async function poolQuery<T>(sql: string): Promise<T[]> {
const result = await pool.query(sql);
return result.rows as T[];
}
export type BindingChangeAction = 'bind' | 'unbind';
export type ParsedBindingChange = {
/** 我方接入编码(= 绑定目标;兼容字段名 `subsystem_code`) */
accessCode: string;
/** 主系统分公司编码(可为空 ⇒ 通配 `*`;兼容字段名 `branch_code`) */
mainBranchCode: string | null;
/** 主系统供应商编码(兼容字段名 `supplier_code`) */
mainSupplierCode: string;
action: BindingChangeAction;
};
/** 值是"非空字符串"才算数(对方可能传 null / '' / 数字) */
function text(value: unknown): string {
if (value === null || value === undefined) return '';
return String(value).trim();
}
function normalizeAction(value: unknown): BindingChangeAction {
const raw = text(value).toLowerCase();
// 缺省按"绑定"处理:对方只推"我绑了谁"时不必多带一个字段
return raw === 'unbind' || raw === 'unbound' || raw === 'remove' || raw === 'detach' ? 'unbind' : 'bind';
}
/** 单条变更的解析(字段名做兼容,避免因为命名差异整批丢) */
export function parseBindingChange(raw: unknown): ParsedBindingChange | null {
if (!raw || typeof raw !== 'object') return null;
const item = raw as Record<string, unknown>;
const accessCode = text(item.subsystem_code) || text(item.access_code) || text(item.our_access_code);
const mainSupplierCode = text(item.main_supplier_code) || text(item.supplier_code);
if (!accessCode || !mainSupplierCode) return null;
const mainBranchCode =
text(item.main_branch_code) ||
text(item.branch_code) ||
text(item.main_system_branch_code) ||
null;
return {
accessCode,
mainBranchCode,
mainSupplierCode,
action: normalizeAction(item.action ?? item.change ?? item.operation),
};
}
/**
* 整包解析:支持**单条**(字段在顶层)与**批量**(`bindings: [...]` / `data: [...]`)。
* 批量用于"全量重推/回读"场景(一次把该 client 的全部授权行给我们)。
*/
export function parseBindingChangePayload(payload: unknown): ParsedBindingChange[] {
const body = (payload || {}) as Record<string, unknown>;
const single = parseBindingChange(body);
if (single) return [single];
const list = Array.isArray(body.bindings)
? body.bindings
: Array.isArray(body.data)
? body.data
: [];
return list.map(parseBindingChange).filter((item): item is ParsedBindingChange => Boolean(item));
}
export type ApplyBindingOutcome = {
status: 'applied' | 'unbound' | 'ignored';
branchCode: string | null;
accessCode: string;
mainBranchCode: string;
mainSupplierCode: string;
reason?: string;
/** 该 (主系统分公司 + 供应商) 之前指向的**另一家**我方分公司(有 ⇒ 这是一次改绑) */
previousBranchCode?: string | null;
};
/**
* 把**一条**变更落到绑定表(回调与回读共用;唯一写入口见 `branchAccessCode`)。
*
* 路由规则:**按接入编码定位我方分公司**(绑定的权威在主系统,分公司由编码决定,不看手机号)。
* 编码不认识 ⇒ `ignored`(不猜、不建分公司);解绑一条本就不存在的绑定 ⇒ `ignored`(幂等)。
*/
export async function applyBindingChange(
change: ParsedBindingChange,
source: 'main_push' | 'main_pull' | 'manual'
): Promise<ApplyBindingOutcome> {
const accessCode = text(change.accessCode).toUpperCase();
const mainSupplierCode = text(change.mainSupplierCode).toUpperCase();
const mainBranchCode = (text(change.mainBranchCode) || '*').toUpperCase();
const base = { branchCode: null as string | null, accessCode, mainBranchCode, mainSupplierCode };
if (!accessCode) return { ...base, status: 'ignored', reason: 'missing_access_code' };
if (!mainSupplierCode) return { ...base, status: 'ignored', reason: 'missing_supplier_code' };
const branchCode = await findBranchCodeByAccessCode(accessCode);
if (!branchCode) {
// 编码不认识:可能是别的子系统实例的码,也可能是分公司被删了 —— 只记日志,不建任何数据
return { ...base, status: 'ignored', reason: 'unknown_access_code' };
}
if (change.action === 'unbind') {
const done = await unbindBinding({
mainBranchCode,
mainSupplierCode,
note: `主系统解绑(${source})`,
});
return {
...base,
branchCode,
status: done ? 'unbound' : 'ignored',
reason: done ? undefined : 'no_active_binding',
};
}
const result = await upsertBinding({
branchCode,
accessCode,
mainBranchCode,
mainSupplierCode,
source,
note: `主系统绑定同步(${source})`,
});
return {
...base,
branchCode,
status: 'applied',
previousBranchCode: result.previousBranchCode,
};
}
export type BindingSyncOutcome = {
/** 对方返回的授权行数 */
checked: number;
/** 新建/刷新的绑定数(含改绑) */
applied: number;
/** 转 unbound 的绑定数 */
unbound: number;
skipped: number;
reason?: string;
};
/**
* **回读**(退路通道):从对方只读端点拉全量「该 client 的授权行(含 subsystem_code)」。
*
* 鉴权(2026-10-10 与主系统实现对齐 —— 他们交付的是 `GET /api/supplier/integration-bindings`):
* 用**对接 token**(`POST {oauth}` 换来的 `supplier_integration` scope token)走 `Authorization: Bearer`;
* 该端点按 **token 所属 client** 圈定作用域(不给跨客户端视图),所以拿我们任一已授权供应商换的
* token 即可。⚠️ 初版我们发的是 `X-Client-Id`/`X-Client-Secret` —— 与他们的实现不匹配,
* 已改为 Bearer(真库实测:Bearer 200 且返回本 client 的 3 行)。
*
* supplier_code 的取法(换 token 需要一个已授权供应商):① 我方镜像里的 active 绑定 →
* ② 分公司手工登记的 `main_supplier_code` → ③ 台账里最近出现过的 `main_supplier_code`。
* 三者都没有(全新环境、尚未绑任何东西)⇒ 跳过:此时本来也没有绑定可对账。
*
* 未配置 `MAIN_SYSTEM_BINDING_SYNC_URL` ⇒ 直接跳过(不猜路径、不刷错误日志)。
*/
async function pickSupplierCodeForToken(): Promise<string | null> {
const fromBinding = await poolQuery<{ code: string | null }>(
`SELECT main_supplier_code AS code
FROM public.main_supplier_bindings
WHERE status = 'active' AND NULLIF(TRIM(main_supplier_code), '') IS NOT NULL
ORDER BY bound_at DESC
LIMIT 1`
);
const bound = String(fromBinding[0]?.code || '').trim();
if (bound) return bound;
const fromBranch = await poolQuery<{ code: string | null }>(
`SELECT main_supplier_code AS code
FROM public.branches
WHERE NULLIF(TRIM(main_supplier_code), '') IS NOT NULL
ORDER BY updated_at DESC NULLS LAST
LIMIT 1`
);
const manual = String(fromBranch[0]?.code || '').trim();
if (manual) return manual;
const fromLedger = await poolQuery<{ code: string | null }>(
`SELECT main_supplier_code AS code
FROM public.main_system_order_import_items
WHERE NULLIF(TRIM(main_supplier_code), '') IS NOT NULL
ORDER BY updated_at DESC NULLS LAST
LIMIT 1`
);
return String(fromLedger[0]?.code || '').trim() || null;
}
export async function syncMainSystemBindings(): Promise<BindingSyncOutcome> {
const url = String(config.mainSystemIntegration.bindingSyncUrl || '').trim();
if (!url) {
return { checked: 0, applied: 0, unbound: 0, skipped: 0, reason: '未配置 MAIN_SYSTEM_BINDING_SYNC_URL(只依赖回调/手工登记)' };
}
const supplierCode = await pickSupplierCodeForToken();
if (!supplierCode) {
return { checked: 0, applied: 0, unbound: 0, skipped: 0, reason: '尚无已知的已授权供应商,换不到对接 token ⇒ 跳过回读' };
}
const tokenResult = await getMainSystemToken(supplierCode);
if (tokenResult.kind !== 'ok') {
return { checked: 0, applied: 0, unbound: 0, skipped: 0, reason: tokenResult.reason };
}
let payload: unknown;
try {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), MAIN_SYSTEM_FETCH_TIMEOUT_MS);
// include_disabled=1:把已关闭行也带回来,否则"解绑"永远同步不到(对方默认只返回 status=1)
const fullUrl = `${url}${url.includes('?') ? '&' : '?'}include_disabled=1`;
const response = await fetch(fullUrl, {
method: 'GET',
headers: {
Accept: 'application/json',
Authorization: `Bearer ${tokenResult.token}`,
},
signal: controller.signal,
}).finally(() => clearTimeout(timer));
if (!response.ok) {
return {
checked: 0,
applied: 0,
unbound: 0,
skipped: 0,
reason: `回读端点返回 HTTP ${response.status}`,
};
}
payload = await response.json();
} catch (error: unknown) {
// 对方还没实现该端点 / 网络抖动都走这里:只记原因,不抛(下一轮再试)
return {
checked: 0,
applied: 0,
unbound: 0,
skipped: 0,
reason: `回读失败:${(error as Error)?.message || error}`,
};
}
return applyBindingSnapshot(payload);
}
/**
* 把**全量快照**落到绑定表(回读专用):
* · 快照里 active 的行 ⇒ upsert;`status=0/unbound` 或 `subsystem_code` 为空且我方有 active 的 ⇒ 解绑。
* ⚠️ 只解绑"快照里出现过、但已失效"的行 —— 快照**没提到**的绑定**不动**(避免对方分页/裁剪把绑定误删)。
*/
export async function applyBindingSnapshot(payload: unknown): Promise<BindingSyncOutcome> {
const rows: Array<Record<string, unknown>> = Array.isArray((payload as any)?.data)
? ((payload as any).data as Array<Record<string, unknown>>)
: Array.isArray((payload as any)?.bindings)
? ((payload as any).bindings as Array<Record<string, unknown>>)
: [];
const outcome: BindingSyncOutcome = { checked: rows.length, applied: 0, unbound: 0, skipped: 0 };
if (!rows.length) {
outcome.reason = '快照为空(可能对方尚未实现该端点,或确实没有任何绑定)';
return outcome;
}
for (const raw of rows) {
const accessCode = text(raw.subsystem_code) || text(raw.access_code);
const mainSupplierCode = text(raw.main_supplier_code) || text(raw.supplier_code);
const mainBranchCode = text(raw.main_branch_code) || text(raw.branch_code) || '*';
const statusRaw = raw.status;
const active =
statusRaw === undefined || statusRaw === null || statusRaw === ''
? Boolean(accessCode)
: Number(statusRaw) === 1 || text(statusRaw).toLowerCase() === 'active';
if (!mainSupplierCode) {
outcome.skipped += 1;
continue;
}
const result = await applyBindingChange(
{
accessCode,
mainBranchCode,
mainSupplierCode,
action: active ? 'bind' : 'unbind',
},
'main_pull'
);
if (result.status === 'applied') outcome.applied += 1;
else if (result.status === 'unbound') outcome.unbound += 1;
else outcome.skipped += 1;
}
return outcome;
}
/**
* 事件名判定(容错:对方的 AI 可能挑 `binding.changed` / `preparations.binding_changed`
* / `supplier.binding_changed` 任一种写法)。
*/
export function isBindingChangedEvent(event: unknown): boolean {
const name = String(event || '').trim().toLowerCase();
return (
name === 'binding.changed' ||
name === 'preparations.binding_changed' ||
name === 'supplier.binding_changed' ||
name === 'bindings.changed'
);
}