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 既知红)。
This commit is contained in:
@@ -319,6 +319,13 @@ router.post('/main-system/webhook', async (req: Request, res: Response) => {
|
||||
String(rowsForBranch.find((raw: any) => raw?.branch_code)?.branch_code || '').trim() ||
|
||||
String(String(payload?.order_code || '').match(/_(BR[0-9A-Z]+)_/i)?.[1] || '').trim();
|
||||
const resolved = await resolveOurBranchByBinding({ subsystemCode, supplierCode, mainBranchCode });
|
||||
if (!resolved.ok && resolved.reason === 'unknown_access_code') {
|
||||
// 抄错一位就会走到这里:把编码原值打出来,便于与"分公司管理页里那一串"逐字比对
|
||||
console.warn(
|
||||
`[main-system-webhook] ${event}:接入编码不认识 subsystem_code=${subsystemCode} ` +
|
||||
`supplier=${supplierCode || '—'} ⇒ 已忽略(请核对编码是否抄全/大小写,或该分公司是否已被删除)`
|
||||
);
|
||||
}
|
||||
/** 命中的我方分公司(定不到时为 null);**所有分支都改用它**,不再拿 supplier_code 冒充 */
|
||||
const branchCode = resolved.ok ? resolved.branchCode : null;
|
||||
if (resolved.ok) {
|
||||
|
||||
@@ -273,7 +273,17 @@ export type BindingResolution =
|
||||
binding: { mainBranchCode: string; mainSupplierCode: string } | null;
|
||||
via: BindingVia;
|
||||
}
|
||||
| { ok: false; reason: 'missing_supplier_code' | 'not_bound' | 'ambiguous' };
|
||||
| {
|
||||
ok: false;
|
||||
/**
|
||||
* 失败原因(都会原样回给主系统的投递日志,所以要能直接指导排查):
|
||||
* · `unknown_access_code` —— 带了我们的编码但**查不到**(几乎总是抄错一位/大小写/漏字符);
|
||||
* · `not_bound` —— 编码/供应商没问题,但这家主系统分公司没绑我们(或已解绑);
|
||||
* · `ambiguous` —— 多个我方分公司都绑了这个供应商,而载荷没带主系统分公司 ⇒ 拒收;
|
||||
* · `missing_supplier_code` —— 载荷连供应商编码都没有。
|
||||
*/
|
||||
reason: 'missing_supplier_code' | 'not_bound' | 'ambiguous' | 'unknown_access_code';
|
||||
};
|
||||
|
||||
/**
|
||||
* 入站路由的**唯一判定点**(设计 §3.3):
|
||||
@@ -292,8 +302,12 @@ export async function resolveOurBranchByBinding(input: {
|
||||
if (subsystemCode) {
|
||||
const branchCode = await findBranchCodeByAccessCode(subsystemCode);
|
||||
if (branchCode) return { ok: true, branchCode, binding: null, via: 'access_code' };
|
||||
// 编码不认识:不回落去猜(可能是别的子系统实例的码)
|
||||
return { ok: false, reason: 'not_bound' };
|
||||
/**
|
||||
* 编码不认识:**不回落去猜**(可能是别的子系统实例的码)。
|
||||
* 单列一个 reason:真机上这一条 99% 是"编码抄错一位",运维看投递日志要能立刻分辨 ——
|
||||
* 与"这家没绑我们"(`not_bound`,语义正常)完全不是一回事。
|
||||
*/
|
||||
return { ok: false, reason: 'unknown_access_code' };
|
||||
}
|
||||
|
||||
const supplierCode = String(input.supplierCode || '').trim().toUpperCase();
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
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';
|
||||
|
||||
/**
|
||||
@@ -19,6 +21,12 @@ import { findBranchCodeByAccessCode, unbindBinding, upsertBinding } from './bran
|
||||
* 设计: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 = {
|
||||
@@ -158,32 +166,75 @@ export type BindingSyncOutcome = {
|
||||
/**
|
||||
* **回读**(退路通道):从对方只读端点拉全量「该 client 的授权行(含 subsystem_code)」。
|
||||
*
|
||||
* 鉴权:本系统的对接 client 凭据放在 `X-Client-Id` / `X-Client-Secret`(**不需要 supplier_code**,
|
||||
* 因为这个端点是按 client 维度给数据的;具体形态以对方实现为准,配 URL 即启用)。
|
||||
* 鉴权(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 clientId = String(config.mainSystemIntegration.clientId || '').trim();
|
||||
const clientSecret = String(config.mainSystemIntegration.clientSecret || '').trim();
|
||||
if (!clientId || !clientSecret) {
|
||||
return { checked: 0, applied: 0, unbound: 0, skipped: 0, reason: '未配置对接 client 凭据' };
|
||||
|
||||
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();
|
||||
// 与其他主系统调用同一超时口径(`mainSystem/http.ts` 用的就是它)
|
||||
const timer = setTimeout(() => controller.abort(), MAIN_SYSTEM_FETCH_TIMEOUT_MS);
|
||||
const response = await fetch(url, {
|
||||
// include_disabled=1:把已关闭行也带回来,否则"解绑"永远同步不到(对方默认只返回 status=1)
|
||||
const fullUrl = `${url}${url.includes('?') ? '&' : '?'}include_disabled=1`;
|
||||
const response = await fetch(fullUrl, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'X-Client-Id': clientId,
|
||||
'X-Client-Secret': clientSecret,
|
||||
Authorization: `Bearer ${tokenResult.token}`,
|
||||
},
|
||||
signal: controller.signal,
|
||||
}).finally(() => clearTimeout(timer));
|
||||
|
||||
Reference in New Issue
Block a user