fix(主系统对接): 绑定回读开发/测试默认启用 + 候选 token 回退(让快照权威优先真正生效)
真机 dev 验证"绑定快照权威优先"时发现:`MAIN_SYSTEM_BINDING_SYNC_URL` 从未配置
⇒ 回读通道根本没运行,上一提交的快照对账在 dev/生产都等于死代码;且换 token 只取
"最近一条 active 绑定",命中已解绑的残留绑定时直接 403,整轮回读永远跑不起来。
修复:
1) 启用方式:显式配置 URL ⇒ 用配置值;显式 `off` ⇒ 关闭;未配置 + 非生产 ⇒ 默认走主系统
已交付标准端点 `GET {BASE_URL}/api/supplier/integration-bindings`;未配置 + 生产 ⇒ 仍跳过
(生产启用需显式配置,避免部署默认值意外改写线上绑定)。
2) 换 token 改为逐个候选(镜像 active 绑定 → 分公司手工登记 → 台账)尝试,跳过残留 403。
3) 同步更新 config 注释/设计文档/README。
真机验证(dev,实际执行):
- sync 结果 checked=6 / applied=2 / unbound=3 / unboundMissing=3,
日志「主系统快照里已无此绑定,自动解绑:BR003/SUP10226949、BR003/SUP37831443、BR002/SUP35143228」;
- 之后按绑定拉取只覆盖真正绑定的 SUP37831443,不再拉 SUP35143228。
- 单测 20/20(新增"残留 token 失败继续用下一候选"用例);typecheck 通过;
后端全量 3 failed / 575 passed(18 failed / 4128 passed,红均为既有)。未部署。
This commit is contained in:
@@ -34,6 +34,17 @@
|
||||
导入路径也不把残缺 active 集合传给跟随层(让它自己重拉后整轮放弃);
|
||||
- `/main-system/preparations` 预览接口新增 `failed_supplier_codes`(可见但不阻断其它供应商)。
|
||||
|
||||
### 2.3 让「权威优先」真正跑起来(2026-10-22 补)
|
||||
|
||||
- 真机 dev 验证时发现 `MAIN_SYSTEM_BINDING_SYNC_URL` **未配置** ⇒ 回读通道从未运行,2.1 的快照对账等于死代码;
|
||||
- 现改为:显式配置 URL ⇒ 用配置值;显式配置 `off` ⇒ 关闭;**未配置 + 非生产环境 ⇒ 默认用主系统标准端点**
|
||||
`GET {BASE_URL}/api/supplier/integration-bindings`;**未配置 + 生产环境 ⇒ 仍跳过**(避免部署时因默认值
|
||||
意外改写线上绑定,生产启用前在 env 显式配置即可);
|
||||
- 换 token 改为**逐个候选供应商尝试**(镜像 active 绑定 → 分公司手工登记 → 台账),跳过"主系统已解绑"的残留行,
|
||||
否则残留绑定先被选中换来 403,会让整轮回读永远跑不起来;
|
||||
- dev 真跑结果:`checked=6 / applied=2 / unbound=3 / unboundMissing=3`,日志可见三条
|
||||
「主系统快照里已无此绑定,自动解绑:…」;随后拉取只覆盖真正绑定的 `SUP37831443`。
|
||||
|
||||
## 3. 兼容与回滚
|
||||
|
||||
- 无数据库迁移、无前端文案;解绑走既有 `unbindBinding`(唯一写入口,改绑留痕/删客户语义不变)。
|
||||
|
||||
@@ -51,7 +51,7 @@ AI 提示词清理已停用条目(7 条归档不删、清单过滤 archived、
|
||||
导航菜单按**主系统当前布局**收敛(顶层只留 数据看板/订单录入 + 业务流程/基础数据/财务结算/系统管理;老布局**每次加载自动归位**、幂等、不写一次性 SQL ⇒ 迁移换机都一样;缓存指纹加模板版本;含「财务管理→财务结算」这一处显示名收敛)见 [20261027-导航菜单按主系统模板收敛.md](./20261027-导航菜单按主系统模板收敛.md)。
|
||||
隐藏「市场价格监控」界面(本产品不需要:①菜单目录 ②基础数据规范条目 ③模块路由 ④落地路径兜底 四处同删;权限码/页面代码/i18n **有意保留**;后台每日行情刷新**未动**)见 [20261027-隐藏市场价格监控功能.md](./20261027-隐藏市场价格监控功能.md)。
|
||||
主系统对接**授权一致性防护**(dev 真机事故:订单被主系统另一个测试 client 推入、本地库存抵扣后出站 token 403,报告/回写全发不出去且无痕迹):① 入站按 `payload.client_id`/`X-Client-Id` 校验推送方与本地配置一致,不一致整条忽略 + 失败台账 + 首次通知;② 推送建单前先做「出站可用」预检(换 token 失败 ⇒ 不建单、503 可重试、台账 + 通知);③ token 401/403/404 统一落失败台账并通知,覆盖报告/回写/事实刷新;④ 导入成功即触发一次报告推送(15 分钟对账只作兜底)。无迁移,见 [20261022-主系统对接授权一致性防护.md](./20261022-主系统对接授权一致性防护.md)。
|
||||
绑定回读**全量快照权威优先 + 按供应商拉取容错**(真机事故:主系统没绑编码的供应商的货被拉进本地;一条 403 残留绑定使整分公司拉取中断):快照里不存在的 active 绑定自动解绑(空快照/backfill 行保护);单供应商失败跳过并回报,退货跟随遇 failures 整轮不做判定。无迁移,见 [20261022-绑定快照权威优先与拉取容错.md](./20261022-绑定快照权威优先与拉取容错.md)。
|
||||
绑定回读**全量快照权威优先 + 按供应商拉取容错**(真机事故:主系统没绑编码的供应商的货被拉进本地;一条 403 残留绑定使整分公司拉取中断):快照里不存在的 active 绑定自动解绑(空快照/backfill 行保护;开发/测试默认启用回读、生产需显式配置 URL);换 token 逐个候选回退;单供应商失败跳过并回报,退货跟随遇 failures 整轮不做判定。无迁移,见 [20261022-绑定快照权威优先与拉取容错.md](./20261022-绑定快照权威优先与拉取容错.md)。
|
||||
绑定关系**「绑定时间」只记首次绑定时间**(回读/推送刷新不再把 `bound_at` 刷成同步时间、避免"旧绑定看起来刚绑"的误导):UPSERT 冲突时原行 active 且分公司未变 ⇒ 保留原 `bound_at`,解绑再绑/改绑才用新时间;无迁移,历史已被刷掉的时间需另行批准回填,见 [20261022-绑定时间只记首次绑定.md](./20261022-绑定时间只记首次绑定.md)。
|
||||
库存入库支持**直接选择已有商品**并按「上次设置」预填(规格/单位/成本价/分类/保质期/存放区域/生产地区),**生产日期仍由操作员按批手填**见 [20261011-入库直接选择已有商品并按上次设置预填.md](./20261011-入库直接选择已有商品并按上次设置预填.md)。
|
||||
批量入库把**人工改过的规格**回写商品档案(方案 A:扩 `20261012` 的「档案回写」到批量路径)——根因是 `inventory` 无 `spec` 列、「上次入库的规格」唯一落点是商品档案,而批量入库对**已匹配的老商品**从不回写 ⇒ 下次选同一商品带不出规格;现按「只回写人工动过的字段(AI/预填值绝不覆盖)」在入库同事务写 `product_catalog.spec`(Web 回写 `spec`;小程序批量行有「生产地区」故连带回写 `origin`)见 [20261016-批量入库规格回写商品档案.md](./20261016-批量入库规格回写商品档案.md)。
|
||||
|
||||
@@ -247,7 +247,8 @@ export const config = {
|
||||
* 绑定关系**回读**端点(可选退路,2026-10-27 接入编码设计 §8 P0-2):
|
||||
* 主系统绑定/解绑时**首选**推 `binding.changed` 回调(复用 webhook 通道,无需配置);
|
||||
* 这条是备选:他们提供只读端点后把完整 URL 填这里,我们每轮对账回读一次全量绑定。
|
||||
* **空 = 不启用**(只靠回调 + 超管手工登记,绝不去猜对方路径)。
|
||||
* **off = 显式关闭**;**空 + 开发/测试 = 默认走主系统标准端点**(2026-10-22 起,
|
||||
* 让"快照权威优先"真正生效);**空 + 生产 = 不启用**(需显式配置,避免部署时意外解绑线上绑定)。
|
||||
*/
|
||||
bindingSyncUrl: (process.env.MAIN_SYSTEM_BINDING_SYNC_URL || '').trim(),
|
||||
/** 定时对账(兜底)开关:默认开;webhook 是实时通道,这个是防漏推 */
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { config } from '../config';
|
||||
import { pool } from '../db';
|
||||
import { MAIN_SYSTEM_FETCH_TIMEOUT_MS } from './mainSystem/config';
|
||||
import { MAIN_SYSTEM_DEFAULT_PATHS, MAIN_SYSTEM_FETCH_TIMEOUT_MS, mainSystemBaseUrl } from './mainSystem/config';
|
||||
import { getMainSystemToken } from './mainSystem/token';
|
||||
import { findBranchCodeByAccessCode, unbindBinding, upsertBinding } from './branchAccessCode';
|
||||
|
||||
@@ -187,52 +187,86 @@ export type BindingSyncOutcome = {
|
||||
* ② 分公司手工登记的 `main_supplier_code` → ③ 台账里最近出现过的 `main_supplier_code`。
|
||||
* 三者都没有(全新环境、尚未绑任何东西)⇒ 跳过:此时本来也没有绑定可对账。
|
||||
*
|
||||
* 未配置 `MAIN_SYSTEM_BINDING_SYNC_URL` ⇒ 直接跳过(不猜路径、不刷错误日志)。
|
||||
* 启用方式(2026-10-22 调整):
|
||||
* · 显式配置 `MAIN_SYSTEM_BINDING_SYNC_URL` ⇒ 用配置值;
|
||||
* · 显式配置 `off` ⇒ 关闭回读(只依赖回调/手工登记);
|
||||
* · 未配置 + 非生产环境 ⇒ 用主系统已交付的标准端点
|
||||
* `GET {BASE_URL}/api/supplier/integration-bindings`(开发/测试默认启用,让"权威优先"真正生效);
|
||||
* · 未配置 + 生产环境 ⇒ 不启用(部署时不得因默认值意外改写线上绑定;需要时在 env 里显式配置)。
|
||||
*/
|
||||
async function pickSupplierCodeForToken(): Promise<string | null> {
|
||||
async function listSupplierCodesForToken(): Promise<string[]> {
|
||||
const codes: string[] = [];
|
||||
const push = (value: unknown) => {
|
||||
const code = String(value || '').trim();
|
||||
if (code && !codes.includes(code)) codes.push(code);
|
||||
};
|
||||
// ① 我方镜像里的 active 绑定(可能有残留行,逐个试到能换到 token 为止)
|
||||
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`
|
||||
ORDER BY bound_at DESC`
|
||||
);
|
||||
const bound = String(fromBinding[0]?.code || '').trim();
|
||||
if (bound) return bound;
|
||||
|
||||
for (const row of fromBinding) push(row.code);
|
||||
// ② 分公司手工登记的 main_supplier_code
|
||||
const fromBranch = await poolQuery<{ code: string | null }>(
|
||||
`SELECT main_supplier_code AS code
|
||||
`SELECT DISTINCT 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`
|
||||
ORDER BY main_supplier_code`
|
||||
);
|
||||
const manual = String(fromBranch[0]?.code || '').trim();
|
||||
if (manual) return manual;
|
||||
|
||||
for (const row of fromBranch) push(row.code);
|
||||
// ③ 台账里最近出现过的 main_supplier_code
|
||||
const fromLedger = await poolQuery<{ code: string | null }>(
|
||||
`SELECT main_supplier_code AS code
|
||||
`SELECT DISTINCT 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`
|
||||
ORDER BY main_supplier_code`
|
||||
);
|
||||
return String(fromLedger[0]?.code || '').trim() || null;
|
||||
for (const row of fromLedger) push(row.code);
|
||||
return codes;
|
||||
}
|
||||
|
||||
function resolveBindingSyncUrl(): string {
|
||||
const configured = String(config.mainSystemIntegration.bindingSyncUrl || '').trim();
|
||||
if (configured.toLowerCase() === 'off') return '';
|
||||
if (configured) return configured;
|
||||
// 未显式配置:开发/测试环境默认走标准端点(主系统已交付);生产保持 opt-in,避免部署时意外解绑线上绑定
|
||||
if (String(process.env.NODE_ENV || '').toLowerCase() === 'production') return '';
|
||||
const base = mainSystemBaseUrl();
|
||||
return base ? `${base.replace(/\/+$/, '')}${MAIN_SYSTEM_DEFAULT_PATHS.integrationBindings}` : '';
|
||||
}
|
||||
|
||||
export async function syncMainSystemBindings(): Promise<BindingSyncOutcome> {
|
||||
const url = String(config.mainSystemIntegration.bindingSyncUrl || '').trim();
|
||||
const url = resolveBindingSyncUrl();
|
||||
if (!url) {
|
||||
return { checked: 0, applied: 0, unbound: 0, skipped: 0, reason: '未配置 MAIN_SYSTEM_BINDING_SYNC_URL(只依赖回调/手工登记)' };
|
||||
return {
|
||||
checked: 0,
|
||||
applied: 0,
|
||||
unbound: 0,
|
||||
skipped: 0,
|
||||
reason: '绑定回读未启用(MAIN_SYSTEM_BINDING_SYNC_URL=off 或生产环境未显式配置)',
|
||||
};
|
||||
}
|
||||
|
||||
const supplierCode = await pickSupplierCodeForToken();
|
||||
if (!supplierCode) {
|
||||
const candidates = await listSupplierCodesForToken();
|
||||
if (!candidates.length) {
|
||||
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 };
|
||||
/**
|
||||
* 逐个候选换 token:镜像里可能残留"主系统已解绑"的供应商(换 token 403),
|
||||
* 不能让它把整轮回读卡死(2026-10-22:残留绑定先被选中 ⇒ 403 ⇒ 快照对账永远跑不起来)。
|
||||
*/
|
||||
let tokenResult: Awaited<ReturnType<typeof getMainSystemToken>> | null = null;
|
||||
let lastReason = '';
|
||||
for (const candidate of candidates) {
|
||||
tokenResult = await getMainSystemToken(candidate);
|
||||
if (tokenResult.kind === 'ok') break;
|
||||
lastReason = tokenResult.reason;
|
||||
tokenResult = null;
|
||||
}
|
||||
if (!tokenResult || tokenResult.kind !== 'ok') {
|
||||
return { checked: 0, applied: 0, unbound: 0, skipped: 0, reason: lastReason || '换不到对接 token' };
|
||||
}
|
||||
|
||||
let payload: unknown;
|
||||
@@ -275,8 +309,9 @@ export async function syncMainSystemBindings(): Promise<BindingSyncOutcome> {
|
||||
|
||||
/**
|
||||
* 把**全量快照**落到绑定表(回读专用):
|
||||
* · 快照里 active 的行 ⇒ upsert;`status=0/unbound` 或 `subsystem_code` 为空且我方有 active 的 ⇒ 解绑。
|
||||
* ⚠️ 只解绑"快照里出现过、但已失效"的行 —— 快照**没提到**的绑定**不动**(避免对方分页/裁剪把绑定误删)。
|
||||
* · 快照里 active 的行 ⇒ upsert;`status=0/unbound` 或 `subsystem_code` 为空且我方有 active 的 ⇒ 解绑;
|
||||
* · 快照里**不存在**的我方 active 绑定 ⇒ 也解绑(2026-10-22「权威优先」,见本文件后续注释与设计文档);
|
||||
* · 空快照 ⇒ 不动(防端点抖动把绑定全部清空)。
|
||||
*/
|
||||
export async function applyBindingSnapshot(payload: unknown): Promise<BindingSyncOutcome> {
|
||||
const rows: Array<Record<string, unknown>> = Array.isArray((payload as any)?.data)
|
||||
|
||||
@@ -18,6 +18,12 @@ import { config } from '../../config';
|
||||
/** 各端点的**默认路径**(可被环境变量覆盖,见 endpoints.ts) */
|
||||
export const MAIN_SYSTEM_DEFAULT_PATHS = {
|
||||
oauth: '/api/supplier/oauth/token',
|
||||
/**
|
||||
* 绑定关系**只读回读**(主系统已交付;见 docs/design/20261027-分公司接入编码与主系统供应商绑定.md §8 P0-2)。
|
||||
* 按 token 所属 client 圈定作用域,`include_disabled=1` 取全量(含已关闭行)。
|
||||
* 2026-10-22 起开发/测试环境**默认启用**(生产仍要求显式配置 URL,避免部署时意外改写线上绑定)。
|
||||
*/
|
||||
integrationBindings: '/api/supplier/integration-bindings',
|
||||
preparations: '/api/supplier/preparations',
|
||||
preparationsStatus: '/api/supplier/preparations/status',
|
||||
priceQtyRequest: '/api/supplier/preparations/price-qty-request',
|
||||
|
||||
@@ -165,17 +165,73 @@ describe('落到绑定表(唯一写入口)', () => {
|
||||
});
|
||||
|
||||
describe('回读(退路通道)', () => {
|
||||
it('未配置 URL ⇒ 直接跳过(不猜路径、不发请求)', async () => {
|
||||
it('显式配置 off ⇒ 直接跳过(不猜路径、不发请求)', async () => {
|
||||
const { config } = await import('../src/config');
|
||||
const original = config.mainSystemIntegration.bindingSyncUrl;
|
||||
(config.mainSystemIntegration as { bindingSyncUrl: string }).bindingSyncUrl = '';
|
||||
(config.mainSystemIntegration as { bindingSyncUrl: string }).bindingSyncUrl = 'off';
|
||||
const r = await syncMainSystemBindings();
|
||||
expect(r.checked).toBe(0);
|
||||
expect(r.reason).toContain('MAIN_SYSTEM_BINDING_SYNC_URL');
|
||||
expect(r.reason).toContain('未启用');
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
(config.mainSystemIntegration as { bindingSyncUrl: string }).bindingSyncUrl = original;
|
||||
});
|
||||
|
||||
it('未配置 + 非生产环境 ⇒ 默认走标准端点 /api/supplier/integration-bindings', async () => {
|
||||
const { config } = await import('../src/config');
|
||||
const originalUrl = config.mainSystemIntegration.bindingSyncUrl;
|
||||
const originalBase = config.mainSystem.baseUrl;
|
||||
const originalNodeEnv = process.env.NODE_ENV;
|
||||
(config.mainSystemIntegration as { bindingSyncUrl: string }).bindingSyncUrl = '';
|
||||
(config.mainSystem as { baseUrl: string }).baseUrl = 'http://127.0.0.1:3001';
|
||||
process.env.NODE_ENV = 'development';
|
||||
fetchMock.mockResolvedValue({ ok: true, status: 200, json: async () => ({ data: [] }) } as never);
|
||||
const r = await syncMainSystemBindings();
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
const [url] = fetchMock.mock.calls[0] as [string];
|
||||
expect(url).toContain('/api/supplier/integration-bindings');
|
||||
expect(url).toContain('include_disabled=1');
|
||||
expect(r.checked).toBe(0);
|
||||
process.env.NODE_ENV = originalNodeEnv;
|
||||
(config.mainSystemIntegration as { bindingSyncUrl: string }).bindingSyncUrl = originalUrl;
|
||||
(config.mainSystem as { baseUrl: string }).baseUrl = originalBase;
|
||||
});
|
||||
|
||||
it('镜像里残留的已解绑供应商 token 失败时,继续用下一个候选换 token(不整轮卡死)', 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';
|
||||
poolQuery.mockImplementation(async (sql: unknown) => {
|
||||
if (String(sql).includes('SELECT main_supplier_code AS code') && String(sql).includes('FROM public.main_supplier_bindings')) {
|
||||
return { rows: [{ code: 'SUP_STALE' }, { code: 'SUP_GOOD' }], rowCount: 2 } as never;
|
||||
}
|
||||
if (String(sql).includes('FROM public.branches') || String(sql).includes('FROM public.main_system_order_import_items')) {
|
||||
return { rows: [], rowCount: 0 } as never;
|
||||
}
|
||||
return { rows: [], rowCount: 0 } as never;
|
||||
});
|
||||
tokenMock.mockImplementation(async (code: string) =>
|
||||
code === 'SUP_STALE'
|
||||
? { kind: 'unavailable', reason: 'forbidden: 残留绑定已解绑' }
|
||||
: { kind: 'ok', token: 'tok-ok', branchCode: 'BR002', expiresAt: Date.now() + 60000 }
|
||||
);
|
||||
fetchMock.mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({
|
||||
data: [{ branch_code: 'BR002', supplier_code: 'SUP_GOOD', subsystem_code: 'SC1', status: 1 }],
|
||||
}),
|
||||
} as never);
|
||||
findBranch.mockResolvedValue('BR002');
|
||||
upsert.mockResolvedValue({ branchCode: 'BR002', previousBranchCode: null });
|
||||
|
||||
const r = await syncMainSystemBindings();
|
||||
expect(tokenMock).toHaveBeenCalledWith('SUP_STALE');
|
||||
expect(tokenMock).toHaveBeenCalledWith('SUP_GOOD');
|
||||
expect(r.applied).toBe(1);
|
||||
(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;
|
||||
|
||||
Reference in New Issue
Block a user