Files
SupplierSystem/server/tests/mainSupplierBindingLocalOverride.test.ts
T
Ubuntu de14fb01f0
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
feat: 供应商系统 2026-11 阶段成果(分公司模板/真还原预览、商品远程搜索、主系统联调、加工幂等修复)
- 分公司类型模板:超管配置隐藏路由/菜单 + 中文文案覆盖,仅对挂类型的分公司生效(后端 service/routes、前端 Provider/守卫/配置页)
- 超管模板 iframe 真还原预览:28 个业务页注册、白名单点选编辑、空/示例数据 fixture、白名单漂移检测工具
- 商品/SKU 下拉远程搜索:服务端关键词搜索 + 前端 useRemoteOptionSearch/SearchableSelect 接入(订单/采购/商品等页)
- 主系统联调:子系统主动解绑主系统授权(幂等重试/本地兜底)、追加修改 price_amend 视图代理与 amend-price 转发
- 修复:仓内加工重复建单幂等(已完成需求单 guard、order 任务一商品一单 guard)
- 修复:出入库记录只取前 100 条 → 服务端分页 + 真实总数
- 其它:库存/订单若干修复、分公司管理响应式布局、i18n 文案、设计文档与回归测试
2026-11-07 20:10:48 +08:00

635 lines
26 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 { readFileSync } from 'node:fs';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
/**
* 主系统供应商绑定「超管本地解绑 + 防回潮 + 入站拒收」—— 真实 PG 集成测试(2026-11-06 方案A)。
*
* 为什么值得单独钉:绑定的**权威在主系统侧**(`supplier_integration_client_suppliers`),
* 我方 `public.main_supplier_bindings` 只是镜像,而镜像会被**回调 + 定时全量回读**反复刷新。
* 于是"超管在本地解绑"如果没有防回潮标记,下一轮同步就会把它刷回 active —— 本地解绑等于没解。
*
* 本文件覆盖:
* ① 本地解绑立即停用(`listConnectableBindingsForBranch` 不含该行)+ 入站按 `locally_unbound` 拒收;
* ② 主系统 bind 同步**不复活**已本地解绑的行(`skipped / local_unbound_override`);
* ③ 主系统 unbind 事件清本地覆盖;恢复同步后主系统 bind 可再次生效;
* ④ 权限接线(仅 super_admin)与「无 active 行 ⇒ 404」。
*
* 数据隔离:每条用例用**独立的临时分公司 + 临时 main_supplier_code**,`afterAll` 全部删除;
* 客户同步(建/删客户)与审计写入用 mock 截获(会落到租户 schema,测试环境不必真写),
* 断言它们的**入参与载荷**,绑定表本身走真实 SQL。
*/
const customerMock = vi.hoisted(() => ({ ensure: vi.fn(), remove: vi.fn() }));
vi.mock('../src/services/mainSystemCustomerBindingService', () => ({
ensureCustomerForBinding: (...args: unknown[]) => customerMock.ensure(...args),
removeCustomerForBinding: (...args: unknown[]) => customerMock.remove(...args),
mainBranchCustomerCode: (code: string | null | undefined) => {
const text = String(code || '').trim().toUpperCase();
return !text || text === '*' ? null : `MAIN_${text}`;
},
}));
const auditMock = vi.hoisted(() => ({ write: vi.fn(), profile: vi.fn() }));
vi.mock('../src/services/auditService', async (importOriginal) => {
const actual = await importOriginal<Record<string, unknown>>();
return {
...actual,
writeAuditLog: (...args: unknown[]) => auditMock.write(...args),
resolveOperatorProfile: (...args: unknown[]) => auditMock.profile(...args),
};
});
const { pool } = await import('../src/db');
const {
clearManualUnbind,
listBindingsForBranch,
listConnectableBindingsForBranch,
manualUnbindBinding,
resolveOurBranchByBinding,
unbindBinding,
upsertBinding,
} = await import('../src/services/branchAccessCode');
const { applyBindingChange } = await import('../src/services/branchBindingSync');
const OPERATOR_ID = '11111111-1111-4111-8111-111111111111';
/** 每次运行独立后缀:不碰真实绑定,也不与其它并发测试撞唯一键 */
const STAMP = `${Date.now()}${process.pid}`;
const SUFFIX = STAMP.slice(-9);
type Fixture = {
branchCode: string;
accessCode: string;
mainBranchCode: string;
supplierCode: string;
};
function makeFixture(tag: string, supplierTag = tag): Fixture {
return {
branchCode: `T_LOCAL_${tag}_${SUFFIX}`,
accessCode: `SCTLOCAL${tag}${SUFFIX}`.toUpperCase(),
mainBranchCode: `BRTL${tag}${SUFFIX}`.toUpperCase(),
supplierCode: `SUPL${supplierTag}${SUFFIX}`.toUpperCase(),
};
}
const FX_A = makeFixture('A');
const FX_B = makeFixture('B');
const FX_C = makeFixture('C');
const FX_C2 = makeFixture('D');
/** ①b 专用:同主系统分公司多供应商共享客户(不与其它用例复用行/覆盖状态) */
const FX_SHARED = makeFixture('S');
/** ③b 专用(2026-11-06 双向解绑联调):主系统解绑 webhook 先到 ⇒ 行已 unbound 再本地解绑 */
const FX_E = makeFixture('E');
const ALL = [FX_A, FX_B, FX_C, FX_C2, FX_SHARED, FX_E];
async function insertBranch(fx: Fixture) {
await pool.query(
`INSERT INTO public.branches (branch_code, branch_name, access_code, status)
VALUES ($1, $2, $3, 1)
ON CONFLICT (branch_code) DO UPDATE
SET access_code = EXCLUDED.access_code, branch_name = EXCLUDED.branch_name`,
[fx.branchCode, `测试临时分公司-${fx.branchCode}`, fx.accessCode]
);
}
async function cleanup() {
for (const fx of ALL) {
await pool.query('DELETE FROM public.main_supplier_bindings WHERE branch_code = $1', [fx.branchCode]);
await pool.query(
'DELETE FROM public.main_supplier_bindings WHERE main_branch_code = $1 AND main_supplier_code = $2',
[fx.mainBranchCode, fx.supplierCode]
);
await pool.query('DELETE FROM public.branches WHERE branch_code = $1', [fx.branchCode]);
}
}
type Row = {
status: string;
access_code: string;
main_branch_code: string;
main_supplier_code: string;
branch_code: string;
note: string | null;
bound_at: string;
unbound_at: string | null;
local_override_state: string | null;
local_override_reason: string | null;
local_override_by: string | null;
local_override_by_name: string | null;
local_override_at: string | null;
};
async function readRow(fx: Fixture): Promise<Row | null> {
const result = await pool.query<Row>(
`SELECT status, access_code, main_branch_code, main_supplier_code, branch_code, note,
bound_at, unbound_at, local_override_state, local_override_reason,
local_override_by, local_override_by_name, local_override_at
FROM public.main_supplier_bindings
WHERE main_branch_code = $1 AND main_supplier_code = $2`,
[fx.mainBranchCode, fx.supplierCode]
);
return result.rows[0] ?? null;
}
/** 先造一条 active 绑定(走真实 upsertBinding;客户同步已 mock) */
async function bindActive(fx: Fixture) {
const result = await upsertBinding({
branchCode: fx.branchCode,
accessCode: fx.accessCode,
mainBranchCode: fx.mainBranchCode,
mainSupplierCode: fx.supplierCode,
mainBranchName: '测试主系统分公司',
source: 'main_push',
note: '测试夹具',
});
expect(result.skippedByLocalOverride).toBeFalsy();
}
beforeAll(async () => {
await cleanup();
for (const fx of [FX_A, FX_B, FX_C, FX_C2, FX_SHARED, FX_E]) await insertBranch(fx);
});
afterAll(async () => {
await cleanup();
});
beforeEach(() => {
customerMock.ensure.mockReset().mockResolvedValue({ ok: true, action: 'created_or_kept' });
customerMock.remove.mockReset().mockResolvedValue({ ok: true, action: 'deleted' });
auditMock.write.mockReset().mockResolvedValue(undefined);
auditMock.profile.mockReset().mockResolvedValue({ name: '超管甲', roles: 'super_admin' });
});
describe('① 超管本地解绑:立即停用 + 入站拒收 + 审计', () => {
it('解绑后不可沟通、入站 locally_unbound、客户按解绑口径处理、审计留痕', async () => {
await bindActive(FX_A);
expect((await listConnectableBindingsForBranch(FX_A.branchCode)).map((b) => b.mainSupplierCode)).toEqual([
FX_A.supplierCode,
]);
// 解绑前:带编码 + 供应商 ⇒ 正常路由到该分公司
await expect(
resolveOurBranchByBinding({ subsystemCode: FX_A.accessCode, supplierCode: FX_A.supplierCode })
).resolves.toMatchObject({ ok: true, branchCode: FX_A.branchCode, via: 'access_code' });
const before = await readRow(FX_A);
expect(before?.bound_at).toBeTruthy();
// 作用域:URL 里的分公司与行归属不一致 ⇒ 404(防拿错 URL 解掉别家分公司的绑定)
await expect(
manualUnbindBinding({
mainBranchCode: FX_A.mainBranchCode,
mainSupplierCode: FX_A.supplierCode,
branchCode: 'T_LOCAL_OTHER',
operatorId: OPERATOR_ID,
})
).rejects.toMatchObject({ status: 404, code: 'not_found' });
expect((await readRow(FX_A))?.status).toBe('active');
const binding = await manualUnbindBinding({
mainBranchCode: FX_A.mainBranchCode,
mainSupplierCode: FX_A.supplierCode,
branchCode: FX_A.branchCode,
reason: '测试:超管本地解绑',
operatorId: OPERATOR_ID,
});
expect(binding).toMatchObject({
branchCode: FX_A.branchCode,
mainBranchCode: FX_A.mainBranchCode,
mainSupplierCode: FX_A.supplierCode,
status: 'unbound',
localOverrideState: 'manual_unbound',
localOverrideReason: '测试:超管本地解绑',
localOverrideByName: '超管甲',
});
expect(binding.unboundAt).toBeTruthy();
expect(binding.localOverrideAt).toBeTruthy();
// 出站判定点:不再可沟通
expect(await listConnectableBindingsForBranch(FX_A.branchCode)).toEqual([]);
// 入站判定点:拒收(reason 必须能让人看出是"本地解绑",不是"本来就没绑")
await expect(
resolveOurBranchByBinding({ subsystemCode: FX_A.accessCode, supplierCode: FX_A.supplierCode })
).resolves.toEqual({ ok: false, reason: 'locally_unbound' });
const row = await readRow(FX_A);
expect(row).toMatchObject({
status: 'unbound',
local_override_state: 'manual_unbound',
local_override_reason: '测试:超管本地解绑',
local_override_by: OPERATOR_ID,
local_override_by_name: '超管甲',
});
expect(row?.note).toContain('[超管本地解绑]');
expect(row?.note).toContain('测试:超管本地解绑');
// 解绑即处理客户:与 unbindBinding 同口径(传我方分公司 + 主系统分公司)
expect(customerMock.remove).toHaveBeenCalledWith({
branchCode: FX_A.branchCode,
mainBranchCode: FX_A.mainBranchCode,
});
// 审计:operationType / targetTable / 关键字段 / 分类 / 分公司
const auditCall = auditMock.write.mock.calls.find(
([input]) => (input as { operationType?: string })?.operationType === 'main_supplier_binding_unbind'
);
expect(auditCall, '缺少 main_supplier_binding_unbind 审计').toBeTruthy();
const auditInput = auditCall![0] as Record<string, unknown>;
expect(auditInput.operatorId).toBe(OPERATOR_ID);
expect(auditInput.targetTable).toBe('main_supplier_bindings');
expect(auditInput.actionCategory).toBe('system');
expect(auditInput.branchCode).toBe(FX_A.branchCode);
expect(auditInput.oldValue).toMatchObject({
status: 'active',
branch_code: FX_A.branchCode,
access_code: FX_A.accessCode,
main_branch_code: FX_A.mainBranchCode,
main_supplier_code: FX_A.supplierCode,
});
expect(auditInput.newValue).toMatchObject({
status: 'unbound',
reason: '测试:超管本地解绑',
local_override_state: 'manual_unbound',
});
// 界面展示面:listBindingsForBranch 自动带上覆盖字段
const forUi = await listBindingsForBranch(FX_A.branchCode);
expect(forUi.find((b) => b.mainSupplierCode === FX_A.supplierCode)).toMatchObject({
status: 'unbound',
localOverrideState: 'manual_unbound',
});
});
it('无 active 行再解绑 ⇒ 404 not_found;载荷没带 supplier_code ⇒ 该分公司无 active 绑定则 not_bound', async () => {
await expect(
manualUnbindBinding({
mainBranchCode: FX_A.mainBranchCode,
mainSupplierCode: FX_A.supplierCode,
operatorId: OPERATOR_ID,
})
).rejects.toMatchObject({ status: 404, code: 'not_found' });
// 没传 supplier_code:要求该分公司至少 1 条可沟通 active 绑定 —— 全被解绑后应拒收
await expect(resolveOurBranchByBinding({ subsystemCode: FX_A.accessCode })).resolves.toEqual({
ok: false,
reason: 'not_bound',
});
});
});
describe('①b 同一主系统分公司多供应商共享客户:解绑其中一条不能动客户', () => {
it('还有其它 active 绑定时不删/停用客户;最后一条解绑时才处理客户', async () => {
const first = FX_SHARED;
const shared = { ...FX_SHARED, supplierCode: `SUPSHARED${SUFFIX}` };
await bindActive(first);
await bindActive(shared);
customerMock.remove.mockClear();
// 解绑一条:同主系统分公司仍有 shared active ⇒ 客户不能动
await manualUnbindBinding({
mainBranchCode: first.mainBranchCode,
mainSupplierCode: first.supplierCode,
operatorId: OPERATOR_ID,
});
expect(customerMock.remove).not.toHaveBeenCalled();
// 解绑最后一条 ⇒ 此时才按解绑口径处理客户
await manualUnbindBinding({
mainBranchCode: shared.mainBranchCode,
mainSupplierCode: shared.supplierCode,
operatorId: OPERATOR_ID,
});
expect(customerMock.remove).toHaveBeenCalledTimes(1);
expect(customerMock.remove).toHaveBeenCalledWith({
branchCode: first.branchCode,
mainBranchCode: first.mainBranchCode,
});
});
});
describe('①c 主系统已同步解绑成功时:本地只转 unbound、不打覆盖(界面不再残留「本地已停用」)', () => {
it('keepOverride=false:行转 unbound 且 local_override_state=null;listBindingsForBranch 不再展示', async () => {
const fx = { ...FX_SHARED, supplierCode: `SUPKEEP${SUFFIX}` };
await bindActive(fx);
const binding = await manualUnbindBinding({
mainBranchCode: fx.mainBranchCode,
mainSupplierCode: fx.supplierCode,
operatorId: OPERATOR_ID,
keepOverride: false,
});
expect(binding.status).toBe('unbound');
expect(binding.localOverrideState).toBeNull();
const shown = await listBindingsForBranch(fx.branchCode);
expect(shown.some((b) => b.mainSupplierCode === fx.supplierCode)).toBe(false);
});
it('allowAlreadyUnbound + keepOverride=false:webhook 已先刷 unbound 时只补 unbound_at 语义、不打覆盖', async () => {
const fx = { ...FX_SHARED, supplierCode: `SUPKEEP2${SUFFIX}` };
await bindActive(fx);
// 模拟主系统解绑 webhook 先到(走主系统通道:清覆盖并转 unbound)
const { applyBindingChange } = await import('../src/services/branchBindingSync');
await applyBindingChange(
{
action: 'unbind',
accessCode: fx.accessCode,
mainBranchCode: fx.mainBranchCode,
mainSupplierCode: fx.supplierCode,
} as never,
'main_push'
);
const binding = await manualUnbindBinding({
mainBranchCode: fx.mainBranchCode,
mainSupplierCode: fx.supplierCode,
operatorId: OPERATOR_ID,
allowAlreadyUnbound: true,
keepOverride: false,
});
expect(binding.status).toBe('unbound');
expect(binding.localOverrideState).toBeNull();
const shown = await listBindingsForBranch(fx.branchCode);
expect(shown.some((b) => b.mainSupplierCode === fx.supplierCode)).toBe(false);
});
});
describe('② 防回潮:主系统 bind 同步不复活已本地解绑的行', () => {
it('applyBindingChange(bind, main_push) ⇒ skipped/local_unbound_override,行仍 unbound', async () => {
await bindActive(FX_B);
await manualUnbindBinding({
mainBranchCode: FX_B.mainBranchCode,
mainSupplierCode: FX_B.supplierCode,
reason: '测试:防回潮',
operatorId: OPERATOR_ID,
});
const afterUnbind = await readRow(FX_B);
customerMock.ensure.mockClear();
customerMock.remove.mockClear();
const outcome = await applyBindingChange(
{
accessCode: FX_B.accessCode,
mainBranchCode: FX_B.mainBranchCode,
mainSupplierCode: FX_B.supplierCode,
mainBranchName: '主系统推回来的分公司名',
action: 'bind',
},
'main_push'
);
expect(outcome).toMatchObject({
status: 'skipped',
reason: 'local_unbound_override',
branchCode: FX_B.branchCode,
mainSupplierCode: FX_B.supplierCode,
});
const row = await readRow(FX_B);
expect(row).toMatchObject({
status: 'unbound',
local_override_state: 'manual_unbound',
local_override_reason: '测试:防回潮',
});
// 不复活:绑定时间/解绑时间都不该被同步改写(pg 返回 Date,比较 ISO 串而不是对象引用)
expect(new Date(row!.bound_at).toISOString()).toBe(new Date(afterUnbind!.bound_at).toISOString());
expect(new Date(row!.unbound_at!).toISOString()).toBe(new Date(afterUnbind!.unbound_at!).toISOString());
// 只补记同步事实(access_code / 主系统分公司名),并留一条"同步已跳过"痕迹
expect(row?.access_code).toBe(FX_B.accessCode);
expect(row?.note).toContain('[同步已跳过:本地超管解绑生效]');
// 不建客户(本地解绑时已按解绑口径处理过)
expect(customerMock.ensure).not.toHaveBeenCalled();
// 出站仍然不可沟通
expect(await listConnectableBindingsForBranch(FX_B.branchCode)).toEqual([]);
});
it('回读快照里的 active 行同样被挡(main_pull),skipped 计入 skipped 而不是 applied', async () => {
const outcome = await applyBindingChange(
{
accessCode: FX_B.accessCode,
mainBranchCode: FX_B.mainBranchCode,
mainSupplierCode: FX_B.supplierCode,
mainBranchName: '回读分公司名',
action: 'bind',
},
'main_pull'
);
expect(outcome.status).toBe('skipped');
expect(outcome.reason).toBe('local_unbound_override');
expect((await readRow(FX_B))?.status).toBe('unbound');
});
});
describe('③ 主系统 unbind 清覆盖;恢复同步后主系统 bind 可再次生效', () => {
it('主系统 unbind 事件(行已被本地解绑、无 active)也会清掉本地覆盖', async () => {
await bindActive(FX_C);
await manualUnbindBinding({
mainBranchCode: FX_C.mainBranchCode,
mainSupplierCode: FX_C.supplierCode,
reason: '测试:主系统随后也解绑',
operatorId: OPERATOR_ID,
});
expect((await readRow(FX_C))?.local_override_state).toBe('manual_unbound');
const outcome = await applyBindingChange(
{
accessCode: FX_C.accessCode,
mainBranchCode: FX_C.mainBranchCode,
mainSupplierCode: FX_C.supplierCode,
action: 'unbind',
},
'main_push'
);
// 没有 active 行可解 ⇒ ignored,但覆盖必须被清(否则主系统以后重新授权会被永久挡住)
expect(outcome.status).toBe('ignored');
const row = await readRow(FX_C);
expect(row?.local_override_state).toBeNull();
expect(row?.status).toBe('unbound');
// 主系统重新授权 ⇒ 这次应真的生效
const rebound = await applyBindingChange(
{
accessCode: FX_C.accessCode,
mainBranchCode: FX_C.mainBranchCode,
mainSupplierCode: FX_C.supplierCode,
mainBranchName: '重新授权',
action: 'bind',
},
'main_push'
);
expect(rebound.status).toBe('applied');
expect((await readRow(FX_C))?.status).toBe('active');
expect(await listConnectableBindingsForBranch(FX_C.branchCode)).toHaveLength(1);
});
it('恢复同步(restore)清空标记但不立刻绑定;随后主系统 bind 生效;重复恢复 ⇒ 404', async () => {
await bindActive(FX_C2);
await manualUnbindBinding({
mainBranchCode: FX_C2.mainBranchCode,
mainSupplierCode: FX_C2.supplierCode,
reason: '测试:恢复同步',
operatorId: OPERATOR_ID,
});
auditMock.write.mockClear();
await clearManualUnbind({
mainBranchCode: FX_C2.mainBranchCode,
mainSupplierCode: FX_C2.supplierCode,
operatorId: OPERATOR_ID,
});
const restored = await readRow(FX_C2);
expect(restored).toMatchObject({
status: 'unbound',
local_override_state: null,
local_override_reason: null,
local_override_by: null,
local_override_by_name: null,
local_override_at: null,
});
expect(restored?.note).toContain('[已恢复同步:本地解绑标记清除]');
const restoreAudit = auditMock.write.mock.calls.find(
([input]) => (input as { operationType?: string })?.operationType === 'main_supplier_binding_restore_sync'
);
expect(restoreAudit, '缺少 main_supplier_binding_restore_sync 审计').toBeTruthy();
// 恢复 ≠ 立刻绑定:主系统还没推,就仍是未绑
expect(await listConnectableBindingsForBranch(FX_C2.branchCode)).toEqual([]);
// 主系统下一次 bind ⇒ 正常生效
const outcome = await applyBindingChange(
{
accessCode: FX_C2.accessCode,
mainBranchCode: FX_C2.mainBranchCode,
mainSupplierCode: FX_C2.supplierCode,
action: 'bind',
},
'main_pull'
);
expect(outcome.status).toBe('applied');
expect((await readRow(FX_C2))?.status).toBe('active');
// 已无标记时再恢复 ⇒ 404(界面要能区分"没解绑过"和"恢复成功")
await expect(
clearManualUnbind({
mainBranchCode: FX_C2.mainBranchCode,
mainSupplierCode: FX_C2.supplierCode,
operatorId: OPERATOR_ID,
})
).rejects.toMatchObject({ status: 404, code: 'not_found' });
});
});
describe('④ 路由接线:本地解绑/恢复只给 super_admin(源码契约)', () => {
const authSrc = readFileSync(new URL('../src/routes/auth.ts', import.meta.url), 'utf8');
it('两个写路由都先 requireSuperAdmin,再调服务(路由层不写裸 SQL)', () => {
for (const [path, serviceCall] of [
["'/admin/branches/:branchCode/bindings/unbind'", 'manualUnbindBinding('],
["'/admin/branches/:branchCode/bindings/restore'", 'clearManualUnbind('],
] as const) {
const idx = authSrc.indexOf(path);
expect(idx, `缺少路由 ${path}`).toBeGreaterThan(-1);
/**
* 2026-11-06:解绑路由在「鉴权」与「本地 service」之间多了**主系统解绑调用**(双向解绑),
* 固定字符窗口(原 1200)已经装不下。改判**顺序**:鉴权位置必须早于 service 调用位置 ——
* 这正是这条守卫要保证的不变量,与中间隔多少行无关。
*/
const guardIdx = authSrc.indexOf('requireSuperAdmin(req, res)', idx);
const serviceIdx = authSrc.indexOf(serviceCall, idx);
expect(guardIdx, `${path} 未校验超管`).toBeGreaterThan(idx);
expect(serviceIdx, `${path} 未调用服务`).toBeGreaterThan(idx);
expect(guardIdx, `${path} 鉴权必须在调服务之前`).toBeLessThan(serviceIdx);
expect(authSrc.slice(idx, serviceIdx), `${path} 缺 main_supplier_code 校验`).toContain(
'缺少 main_supplier_code'
);
}
});
it('requireSuperAdmin 只认 super_admin,否则 403', () => {
const idx = authSrc.indexOf('async function requireSuperAdmin');
expect(idx).toBeGreaterThan(-1);
const helper = authSrc.slice(idx, idx + 700);
expect(helper).toContain('isSuperAdminAccount(req.userId)');
expect(helper).toContain('res.status(403)');
// admin(分公司管理员)不在放行集合里
expect(helper).not.toContain("role IN ('super_admin', 'admin')");
});
});
/**
* ③b **双向解绑的真实竞态**(2026-11-06 联调发现)。
*
* 主系统 `unbind` 的成功路径里 `await notifyBindingChanged(...)` 是**同步**的:
* 它的响应还没回到我们,`binding.changed(action=unbind)` 已经打到 webhook、把本地行刷成 `unbound`。
* 于是路由接着调 `manualUnbindBinding` 时行**已经不是 active** ——
* 若不给幂等口径,接口会对一次真实成功的双向解绑回 404。
*
* 这里用真库复现这条时序:先走 `unbindBinding`(= webhook 通道写入口),再走两种口径的本地解绑。
*/
describe('③b 主系统解绑 webhook 先到(行已 unbound)后再本地解绑', () => {
it('allowAlreadyUnbound 补写覆盖且保留首个 unbound_at;不带该参数仍是 404', async () => {
await bindActive(FX_E);
expect((await readRow(FX_E))?.status).toBe('active');
// 模拟绑主系统解绑推送:applyBindingChange 内部就是 unbindBinding(同一写入口)
await expect(
unbindBinding({ mainBranchCode: FX_E.mainBranchCode, mainSupplierCode: FX_E.supplierCode })
).resolves.toBe(true);
const afterWebhook = await readRow(FX_E);
expect(afterWebhook?.status).toBe('unbound');
expect(afterWebhook?.local_override_state).toBeNull();
// 默认口径(既有语义):行已非 active ⇒ 404
await expect(
manualUnbindBinding({
mainBranchCode: FX_E.mainBranchCode,
mainSupplierCode: FX_E.supplierCode,
branchCode: FX_E.branchCode,
operatorId: OPERATOR_ID,
})
).rejects.toMatchObject({ status: 404, code: 'not_found' });
// 路由口径(幂等):补写 manual_unbound 覆盖,不报错、不重写首次解绑时间
const binding = await manualUnbindBinding({
mainBranchCode: FX_E.mainBranchCode,
mainSupplierCode: FX_E.supplierCode,
branchCode: FX_E.branchCode,
reason: '双向解绑联调',
operatorId: OPERATOR_ID,
allowAlreadyUnbound: true,
});
expect(binding).toMatchObject({
branchCode: FX_E.branchCode,
mainBranchCode: FX_E.mainBranchCode,
mainSupplierCode: FX_E.supplierCode,
status: 'unbound',
localOverrideState: 'manual_unbound',
localOverrideReason: '双向解绑联调',
});
const afterPatch = await readRow(FX_E);
expect(afterPatch?.local_override_state).toBe('manual_unbound');
expect(String(afterPatch?.unbound_at)).toBe(String(afterWebhook?.unbound_at));
// 审计要如实写出「解绑前已经是 unbound」(否则事后看日志会以为是本地先动的手)
expect(auditMock.write).toHaveBeenCalledWith(
expect.objectContaining({
operationType: 'main_supplier_binding_unbind',
oldValue: expect.objectContaining({ status: 'unbound' }),
newValue: expect.objectContaining({ already_unbound_before: true }),
})
);
});
it('行根本不存在 ⇒ 即使 allowAlreadyUnbound 也 404(不静默成功)', async () => {
await expect(
manualUnbindBinding({
mainBranchCode: FX_E.mainBranchCode,
mainSupplierCode: `SUPLMISSING${SUFFIX}`,
branchCode: FX_E.branchCode,
operatorId: OPERATOR_ID,
allowAlreadyUnbound: true,
})
).rejects.toMatchObject({ status: 404, code: 'not_found' });
});
});