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:
@@ -281,7 +281,7 @@ resolveOurBranchByBinding({ envelopeBranchCode, rowBranchCode, supplierCode, sub
|
||||
| 通道 | 形态 | 状态 |
|
||||
|---|---|---|
|
||||
| **回调**(首选) | webhook 新事件 `binding.changed`(兼容 `preparations.binding_changed` / `supplier.binding_changed` / `bindings.changed`),复用**既有 webhook URL 与验签**;支持单条与 `bindings:[...]` 批量 | ✅ 已实现(`branchBindingSync.ts` + webhook 分支) |
|
||||
| **回读**(退路) | `MAIN_SYSTEM_BINDING_SYNC_URL`(空=不启用,不猜路径)+ `X-Client-Id`/`X-Client-Secret`;每轮对账**在导入之前**跑 | ✅ 已实现(同上 + `scheduledJobs`) |
|
||||
| **回读**(退路) | `MAIN_SYSTEM_BINDING_SYNC_URL`(空=不启用,不猜路径)+ **`Authorization: Bearer <对接 token>`**(与主系统交付的 `GET /api/supplier/integration-bindings` 对齐)+ `?include_disabled=1`(否则解绑同步不到);每轮对账**在导入之前**跑 | ✅ 已实现(同上 + `scheduledJobs`);⚠️ 冷启动需一个已授权 supplier_code 才能换 token,否则跳过 |
|
||||
|
||||
四条纪律(都钉了测试):① 回调分支必须在**绑定路由闸门之前**(它本身在建绑定,查绑定表必然查不到);
|
||||
② 逐条独立(一条不认识不拖累其余);③ 编码不认识 ⇒ `ignored` + **零写入**;④ 快照回读只解绑"出现过但已失效"的行,
|
||||
|
||||
+42
-3
@@ -399,9 +399,13 @@ POST {我方}/api/supplier/preparations/actual-qty-decision
|
||||
· 解绑用 `"action": "unbind"`;`branch_code` 可省(省 = 通配 `*`,表示"该供应商所有分公司都归这个编码");
|
||||
· **批量**:`{ "event": "binding.changed", "bindings": [ {...}, {...} ] }`(全量重推用,逐条独立处理);
|
||||
· 我方回执:`{ok:true, applied, unbound, ignored, results:[...]}`;编码不认识 ⇒ `ignored` + reason(**不建任何数据**)。
|
||||
- **通道之二 · 回读(退路,我方已就绪)**:给一个只读端点,我们用 `MAIN_SYSTEM_BINDING_SYNC_URL` 配全 URL 启用
|
||||
(**空 = 不启用**,我们绝不猜你们路径),请求带 `X-Client-Id` / `X-Client-Secret`(**按 client 维度鉴权,
|
||||
不需要 supplier_code** —— 这一点和 oauth 换 token 不同,请按 client 放行)。
|
||||
- **通道之二 · 回读(退路,我方已就绪、已与你们的实现对齐)**:你们交付的是
|
||||
`GET /api/supplier/integration-bindings`(`Authorization: Bearer <对接 token>`,按 token 所属 client 圈作用域)。
|
||||
我们原先按草稿发的 `X-Client-Id`/`X-Client-Secret` **已改为 Bearer**(真库实测 200,返回本 client 的 3 行);
|
||||
我们额外带 `?include_disabled=1`,这样**解绑也能同步到**(默认只返回 `status=1`)。
|
||||
启用方式:`MAIN_SYSTEM_BINDING_SYNC_URL=http://<你们域名>/api/supplier/integration-bindings`;**空 = 不启用**。
|
||||
⚠️ 冷启动限制(我方):换 token 需要一个**已知的已授权 supplier_code**;全新环境尚未绑任何东西时跳过回读
|
||||
—— 此时本来也没有绑定可对账,等第一次绑定(push 或手工登记)后即可自动续上。
|
||||
返回 `{ "data": [ { "branch_code", "supplier_code", "subsystem_code", "status" } ] }`(`status=1/0` 或 `active/unbound`);
|
||||
⚠️ 只返回**该 client 的全部行**即可(我们自己按 `subsystem_code` 找分公司);分页/裁剪时**没提到的绑定我们不动**。
|
||||
- **顺带确认(已有代码证据,无需你们动手)**:行级 `branch_code` 你们**已经在回**了(第三批 `P1-11`,
|
||||
@@ -429,6 +433,20 @@ POST {我方}/api/supplier/preparations/actual-qty-decision
|
||||
的唯一键取 `(main_branch_code, main_supplier_code)`,与你们 `supplier_integration_client_suppliers` 的 PK 对齐;
|
||||
**登录改为我方本地账号**(不再回你们验密码 —— 与手机号彻底解耦)。
|
||||
|
||||
#### 2.11.4b 一条加固建议(你们侧,P1 但很值):绑定入口请**校验编码格式**
|
||||
|
||||
实测你们的 `bindIntegrationSupplier()` **不校验** `subsystem_code` 的形状(任何非空串都收)。
|
||||
后果很具体:**抄错一位**(漏字符 / 小写 / 多空格)会被当成有效绑定存下来,然后——
|
||||
你们的推送带着这个错码过来,我们**查不到 ⇒ 忽略**(`unknown_access_code`),用户看到的现象是
|
||||
「明明绑了,货就是不来」,而双方都不报错。
|
||||
|
||||
建议在绑定接口加一条正则(与我们生成端逐字一致):
|
||||
```
|
||||
^SC[23456789ABCDEFGHJKMNPQRSTUVWXYZ]{10}$ // 大写后校验;字母表去掉了易混的 0 O 1 I L
|
||||
```
|
||||
不做也能跑(我们已把"编码不认识"单独记 `warn` 并回 `unknown_access_code`,便于对日志),
|
||||
但校验一下能**在绑定的那一刻**就拦住错码。
|
||||
|
||||
#### 2.11.5 三个追问的答复(2026-10-27 追加,**请以此为准**)
|
||||
|
||||
**问 1:`P0-2②`(按 `subsystem_code` 过滤拉取)是不是主路?要不要做、什么优先级?**
|
||||
@@ -2280,6 +2298,27 @@ prep `931eda1a-3c19-4b49-ab24-664b54770fc4` / `SUP35143228` / `ORD_WEB_20261009_
|
||||
| 3 | 未绑编码的供应商 ⇒ 不发 webhook、也不放行 Token | ✅ 本地监听 **0 条投递**;换 Token **403**,文案「…尚未绑定子系统接入编码…」 |
|
||||
| 4 | 存量兼容(我方补测) | ✅ 已绑码供应商换 Token 仍 **200**;空码的存量行**未被收紧**(推送/授权照旧) |
|
||||
|
||||
#### 三·补、⚠️ 跨系统端到端已真跑(2026-10-12 晚,用你们的真接入编码)
|
||||
|
||||
我方绑定 → **你们的镜像表 `public.main_supplier_bindings` 真的跟着变**(提交 `0dad08f3` + 记录 `7c14bda0`):
|
||||
|
||||
| 动作 | 我方投递 | 你们库实测结果 |
|
||||
|---|---|---|
|
||||
| 绑定 `(BR002, SUP35143228)` → 码 `SCF69N8ZQEVQ`(你们的 BR002) | `binding.changed` **success / HTTP 200 / attempt 1** | 新增行:`{main_branch_code: BR002, main_supplier_code: SUP35143228, access_code: SCF69N8ZQEVQ, branch_code: BR002, status: active, source: main_push}` |
|
||||
| 改绑 → 码 `SCSTSHD6XVX4`(你们的 BR003) | 2 条(`unbind` 旧 + `bind` 新)均 success | 同 pair **只剩一行**、`access_code=SCSTSHD6XVX4`、`branch_code=BR003`、`status=active` |
|
||||
| 解绑 | 1 条 `unbind` success | 同 pair → `status=unbound`、`note=主系统解绑(main_push)` |
|
||||
|
||||
⇒ **P0-1 / P0-2①③ / P0-3 / P0-4 全链路真实打通,你们不用改任何代码**。跑完两侧我都还原了
|
||||
(我方绑定行回到 `status=1 / 编码为空`,你们镜像表回到测试前的空表)。
|
||||
|
||||
**ℹ️ 顺带发现你们一处小问题(不阻塞,供修)**:`branchAccessCode.upsertBinding()` 里,
|
||||
改绑时先 `UPDATE … SET status='unbound', note = COALESCE(note,'') || ' [改绑:旧 → 新]'`,
|
||||
紧接着 `INSERT … ON CONFLICT (main_branch_code, main_supplier_code) DO UPDATE SET … note = EXCLUDED.note`
|
||||
**把刚写的改绑留痕覆盖掉了** ⇒ 实测 `note` 只剩「主系统绑定同步(main_push)」,旧码不见了
|
||||
(你们文档 §2.11.4 写的是"旧行转 `unbound` 留痕 + 新行 `active`")。
|
||||
建议:`note = COALESCE(public.main_supplier_bindings.note,'') || ' [' || COALESCE(EXCLUDED.note,'') || ']'`,
|
||||
或把改绑历史另存一行/另开一张历史表(现表唯一键 `(main_branch_code, main_supplier_code)` 决定了一对一行)。
|
||||
|
||||
#### 四、边界遵守
|
||||
|
||||
- 我方**零反向写回**:编码只用于路由与授权,不改任何业务数据;
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -93,11 +93,11 @@ describe('入站路由(V2–V6)', () => {
|
||||
expect(r).toEqual({ ok: true, branchCode: 'BR007', binding: null, via: 'access_code' });
|
||||
});
|
||||
|
||||
it('编码不认识 ⇒ not_bound(不回落去猜:可能是别的子系统实例的码)', async () => {
|
||||
it('编码不认识 ⇒ unknown_access_code(单列一个原因:真机上 99% 是抄错一位)', async () => {
|
||||
mockQueries([(sql) => (sql.includes('FROM public.branches WHERE access_code') ? { rows: [] } : undefined)]);
|
||||
const r = await resolveOurBranchByBinding({ subsystemCode: 'SCZZZZZZZZZZ', supplierCode: 'SUP1' });
|
||||
expect(r.ok).toBe(false);
|
||||
if (!r.ok) expect(r.reason).toBe('not_bound');
|
||||
if (!r.ok) expect(r.reason).toBe('unknown_access_code');
|
||||
});
|
||||
|
||||
it('② 精确命中 (主系统分公司 + 供应商)', async () => {
|
||||
|
||||
@@ -21,6 +21,16 @@ vi.mock('../src/services/branchAccessCode', () => ({
|
||||
const fetchMock = vi.hoisted(() => vi.fn());
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const poolQuery = vi.hoisted(() => vi.fn());
|
||||
vi.mock('../src/db', () => ({
|
||||
pool: { query: (...args: unknown[]) => poolQuery(...args), connect: vi.fn() },
|
||||
getRawPoolQuery: () => poolQuery,
|
||||
}));
|
||||
const tokenMock = vi.hoisted(() => vi.fn());
|
||||
vi.mock('../src/services/mainSystem/token', () => ({
|
||||
getMainSystemToken: (...args: unknown[]) => tokenMock(...args),
|
||||
}));
|
||||
|
||||
const {
|
||||
isBindingChangedEvent,
|
||||
parseBindingChange,
|
||||
@@ -31,6 +41,10 @@ const {
|
||||
} = await import('../src/services/branchBindingSync');
|
||||
|
||||
beforeEach(() => {
|
||||
poolQuery.mockReset();
|
||||
poolQuery.mockResolvedValue({ rows: [{ code: 'SUP_BOUND' }], rowCount: 1 } as never);
|
||||
tokenMock.mockReset();
|
||||
tokenMock.mockResolvedValue({ kind: 'ok', token: 'tok-1', branchCode: 'BR002', expiresAt: Date.now() + 60000 });
|
||||
findBranch.mockReset();
|
||||
upsert.mockReset();
|
||||
unbind.mockReset();
|
||||
@@ -162,6 +176,47 @@ describe('回读(退路通道)', () => {
|
||||
(config.mainSystemIntegration as { bindingSyncUrl: string }).bindingSyncUrl = original;
|
||||
});
|
||||
|
||||
it('配了 URL ⇒ 用**对接 token**(Bearer)请求,并带 include_disabled=1(否则解绑同步不到)', async () => {
|
||||
const { config } = await import('../src/config');
|
||||
const original = config.mainSystemIntegration.bindingSyncUrl;
|
||||
(config.mainSystemIntegration as { bindingSyncUrl: string }).bindingSyncUrl =
|
||||
'http://127.0.0.1:3001/api/supplier/integration-bindings';
|
||||
fetchMock.mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({
|
||||
data: [{ branch_code: 'BR002', supplier_code: 'SUP1', subsystem_code: 'SC1', status: 1 }],
|
||||
}),
|
||||
});
|
||||
findBranch.mockResolvedValue('BR007');
|
||||
upsert.mockResolvedValue({ branchCode: 'BR007', previousBranchCode: null });
|
||||
|
||||
const r = await syncMainSystemBindings();
|
||||
expect(tokenMock).toHaveBeenCalledWith('SUP_BOUND');
|
||||
const [url, init] = fetchMock.mock.calls[0] as [string, { headers: Record<string, string> }];
|
||||
expect(url).toContain('include_disabled=1');
|
||||
expect(init.headers.Authorization).toBe('Bearer tok-1');
|
||||
// ⚠️ 初版发的是 X-Client-Id/_Secret,与他们的实现不匹配 —— 这条钉住不许回退
|
||||
expect(init.headers['X-Client-Secret']).toBeUndefined();
|
||||
expect(r.applied).toBe(1);
|
||||
(config.mainSystemIntegration as { bindingSyncUrl: string }).bindingSyncUrl = original;
|
||||
});
|
||||
|
||||
it('没有任何已知供应商 ⇒ 跳过(换不到 token),不发请求', async () => {
|
||||
const { config } = await import('../src/config');
|
||||
const original = config.mainSystemIntegration.bindingSyncUrl;
|
||||
(config.mainSystemIntegration as { bindingSyncUrl: string }).bindingSyncUrl = 'http://x/y';
|
||||
for (const table of ['bindings', 'branches', 'items']) {
|
||||
void table;
|
||||
}
|
||||
poolQuery.mockResolvedValue({ rows: [{ code: null }], rowCount: 1 } as never);
|
||||
const r = await syncMainSystemBindings();
|
||||
expect(r.checked).toBe(0);
|
||||
expect(r.reason).toContain('换不到对接 token');
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
(config.mainSystemIntegration as { bindingSyncUrl: string }).bindingSyncUrl = original;
|
||||
});
|
||||
|
||||
it('快照:active 行绑定、status=0 行解绑、缺 supplier_code 行跳过、空快照只记原因', async () => {
|
||||
findBranch.mockResolvedValue('BR007');
|
||||
upsert.mockResolvedValue({ branchCode: 'BR007', previousBranchCode: null });
|
||||
|
||||
Reference in New Issue
Block a user