开发者 2026-10-27 口径:
「每一家分公司一个唯一的接入编码;主系统在供应商列表里给某个供应商绑定这个编码,
货按编码流转;主系统的 A/B/C 分公司都可以绑定同一个 F 供应商的编码;
我们这边的编码没有被绑定就接收不到 —— 因为我们的供应商也可能只用子系统、不走主系统。」
并明确:**与手机号无关**;登录**完全用我方本地账号**。
改前的问题(三处耦合,代码证据见设计文档 §1):
· 我方 branch_code 被当成主系统的 supplier_code(mainSystemIntegration.ts / token.ts);
· 入站拿 payload.supplier_code 直接当分公司编码 ⇒ 编码权在对方、无法一码多绑、
「未被绑定就收不到」无处落地;
· 登录靠手机号 + 回主系统验密码比对绑定。
落地(设计:docs/design/20261027-分公司接入编码与主系统供应商绑定.md):
· 迁移 20261030:branches.access_code(SC+10 位、唯一、非平台分公司回填)
· 迁移 20261031:main_supplier_bindings 镜像表,唯一键 (main_branch_code, main_supplier_code)
⇒ 同一编码可被主系统 A/B/C 三行绑定;另含台账证据回填 + 通配兜底
· 迁移 20261032:日级占坑键加 main_branch_code(否则 A、B 同一天会并成一张单,
而两者送达仓地址不同 ⇒ 派车/送达会错;开发者 2026-10-27 裁决「加」)
· 新增 branchAccessCode.ts(编码生成/绑定 upsert/入站解析/出站 supplier_code 解析)
与 mainSystemBranchPull.ts(按全部生效绑定逐个拉取;未绑定 = not_bound,非故障)
· 入站全部事件改按绑定路由:我方编码 → 精确 → 唯一 → 通配 → 否则 200 忽略
(多绑定又不知分公司 ⇒ ambiguous 拒收,不猜)
· 出站(拉单/导入/发车回写/报缺货/提交改价改量/决策回执)改用台账里的 supplier_code
· 登录:Web 与小程序都删除「回主系统验密码 + 绑定比对」⇒ 本地账号本地密码
· 建分公司总是发接入编码 + 本地初始密码(首登改密);main_supplier_code 降级为
手工通配绑定登记;新增只读 GET /auth/admin/branches/:code/bindings
· 界面:分公司管理「接入编码」列 + 复制 + 「已绑定的主系统供应商」弹层(含空态),三语
验证(真库 + 单测 + 回归):
· 真库实测:建分公司返回 access_code/初始密码;本地密码登录成功(不调主系统);
未绑定推送 ⇒ {ok:true,ignored:true,reason:'not_bound'} 且台账 0→0;
带编码推送落到对应分公司;未绑定拉单/建单 ⇒ 400「未绑定主系统供应商,无法拉取」
· 服务端 2312 用例 / 失败 30、失败文件 24 个 = **与基线逐字相同**(无新增失败)
· 前端 707 用例全绿;双端 tsc 通过;设计门禁同基线(check-ai-cost 既知红)
给主系统(清单 §2.11,5 项 P0 待回执):supplier_integration_client_suppliers 加
subsystem_code 列 + 绑定入口;webhook 信封带该字段、GET /preparations 支持按它过滤;
改绑/解绑通知;授权判定统一到该列(绑定即授权)。他们落地后我方无需改码即可生效。
320 lines
13 KiB
TypeScript
320 lines
13 KiB
TypeScript
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||
|
||
/**
|
||
* 发车回写(2026-10-08,设计文档 20261008 §3.5)的三条硬规则回归:
|
||
* ① 我价 ≤ 0 → **跳过回写**(挂 skipped_zero_price),不因一行卡住整单;
|
||
* ② 实供量 > 主系统备货量 → 必须带 `confirm_over_qty`;
|
||
* ③ 主系统 4xx(明确拒绝)记 rejected 不重试;5xx/超时记 suspended 待重试;
|
||
* ④ 未找到对应订单行的行不猜,记 suspended。
|
||
*/
|
||
|
||
const query = vi.hoisted(() => vi.fn());
|
||
const writebackHttp = vi.hoisted(() => vi.fn());
|
||
const listPending = vi.hoisted(() => vi.fn());
|
||
const markWriteback = vi.hoisted(() => vi.fn());
|
||
const withTenant = vi.hoisted(() => vi.fn());
|
||
const setOurOrderItemId = vi.hoisted(() => vi.fn());
|
||
const priceQtyEnabled = vi.hoisted(() => ({ value: false }));
|
||
const approvedFinal = vi.hoisted(() => vi.fn());
|
||
|
||
vi.mock('../src/db', () => ({
|
||
pool: { query: (...a: unknown[]) => query(...a), connect: vi.fn() },
|
||
getRawPoolQuery: () => query,
|
||
}));
|
||
vi.mock('../src/config', () => ({
|
||
config: {
|
||
mainSystemIntegration: {
|
||
writebackEnabled: true,
|
||
returnFollowEnabled: true,
|
||
clientId: 'x',
|
||
clientSecret: 'y',
|
||
preparationsPath: '/api/supplier/preparations',
|
||
statusPath: '/api/supplier/preparations/status',
|
||
oauthPath: '/api/supplier/oauth/token',
|
||
},
|
||
mainSystem: { baseUrl: 'http://stub', timeoutMs: 1000 },
|
||
},
|
||
}));
|
||
vi.mock('../src/services/mainSystemPreparations', () => ({
|
||
writebackMainSystemPreparationStatus: (...a: unknown[]) => writebackHttp(...a),
|
||
fetchMainSystemPreparations: vi.fn(),
|
||
fetchMainSystemArchivedPreparations: vi.fn(),
|
||
}));
|
||
vi.mock('../src/services/mainSystemPrepLedger', async (importOriginal) => {
|
||
const actual = await importOriginal<typeof import('../src/services/mainSystemPrepLedger')>();
|
||
return {
|
||
...actual,
|
||
listRowsPendingWriteback: (...a: unknown[]) => listPending(...a),
|
||
markWriteback: (...a: unknown[]) => markWriteback(...a),
|
||
setOurOrderItemId: (...a: unknown[]) => setOurOrderItemId(...a),
|
||
};
|
||
});
|
||
// 2026-10-27:出站 supplier_code 改由行级台账解析 ⇒ 本文件固定为 branchCode(等价改造前行为),
|
||
// 解析逻辑本身在 tests/branchAccessCode.test.ts 单独钉。
|
||
vi.mock('../src/services/branchAccessCode', () => ({
|
||
resolveSupplierCodeForPrep: async (params: { branchCode: string }) => params.branchCode,
|
||
}));
|
||
vi.mock('../src/services/mainSystemPriceQtyRequest', () => ({
|
||
isEnabled: () => priceQtyEnabled.value,
|
||
getApprovedFinalValues: (...a: unknown[]) => approvedFinal(...a),
|
||
}));
|
||
vi.mock('../src/services/tenantDbContext', () => ({
|
||
runWithTenantDbContext: (...a: unknown[]) => withTenant(...a),
|
||
getTenantDbStore: () => undefined,
|
||
}));
|
||
|
||
import { writebackDeliveredOrderToMainSystem } from '../src/services/mainSystemWriteback';
|
||
|
||
const ROW = {
|
||
id: 'l1',
|
||
branch_code: 'SUP1',
|
||
main_order_code: 'MO1',
|
||
prep_id: 'p1',
|
||
our_order_code: 'ORD_API_1',
|
||
our_order_item_id: 'i1',
|
||
main_supplier_code: 'SUP1',
|
||
main_sku_code: 'SKU1',
|
||
item_name: '土豆',
|
||
last_prepare_qty: 10,
|
||
last_prepare_status: 10,
|
||
last_return_code: null,
|
||
disposition: 'imported' as const,
|
||
disposition_reason: null,
|
||
writeback_status: 'none',
|
||
payload: null,
|
||
};
|
||
|
||
function mockItem(overrides: Record<string, unknown> = {}) {
|
||
const item = {
|
||
id: 'i1',
|
||
sku_code: 'SKU_LOCAL',
|
||
item_name: '土豆',
|
||
quantity: 10,
|
||
unit: '斤',
|
||
price: 3.5,
|
||
...overrides,
|
||
};
|
||
withTenant.mockImplementation(async (_b: string, fn: (c: unknown) => Promise<unknown>) =>
|
||
fn({ query: async () => ({ rowCount: 1, rows: [item] }) })
|
||
);
|
||
// 兼容直接 pool.query 读订单行的写法
|
||
query.mockImplementation(async () => ({ rowCount: 1, rows: [item] }));
|
||
}
|
||
|
||
describe('writebackDeliveredOrderToMainSystem', () => {
|
||
beforeEach(() => {
|
||
query.mockReset();
|
||
writebackHttp.mockReset();
|
||
listPending.mockReset();
|
||
markWriteback.mockReset();
|
||
withTenant.mockReset();
|
||
listPending.mockResolvedValue([ROW]);
|
||
markWriteback.mockResolvedValue(undefined);
|
||
setOurOrderItemId.mockReset();
|
||
setOurOrderItemId.mockResolvedValue(undefined);
|
||
writebackHttp.mockResolvedValue({ kind: 'ok', updated: 1, skipped: [], needsCustomerPrice: false });
|
||
priceQtyEnabled.value = false;
|
||
approvedFinal.mockReset();
|
||
approvedFinal.mockResolvedValue(null);
|
||
mockItem();
|
||
});
|
||
|
||
it('正常回写:数量/单价/单位按我方口径,带 prep_id', async () => {
|
||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||
expect(out.done).toBe(1);
|
||
expect(writebackHttp).toHaveBeenCalledTimes(1);
|
||
const arg = writebackHttp.mock.calls[0][0] as Record<string, unknown>;
|
||
expect(arg).toMatchObject({
|
||
supplierCode: 'SUP1',
|
||
preparationId: 'p1',
|
||
status: 30,
|
||
prepareQty: 10,
|
||
purchasePrice: 3.5,
|
||
unit: '斤',
|
||
});
|
||
expect(arg.confirmOverQty).toBe(false);
|
||
expect(markWriteback).toHaveBeenCalledWith(expect.objectContaining({ status: 'done' }));
|
||
});
|
||
|
||
it('我价 0 → 跳过回写、不发 HTTP、挂 skipped_zero_price', async () => {
|
||
mockItem({ price: 0 });
|
||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||
expect(writebackHttp).not.toHaveBeenCalled();
|
||
expect(out.skippedZeroPrice).toBe(1);
|
||
expect(out.done).toBe(0);
|
||
expect(markWriteback).toHaveBeenCalledWith(expect.objectContaining({ status: 'skipped_zero_price' }));
|
||
});
|
||
|
||
it('实供量 > 主系统备货量 → 带 confirm_over_qty', async () => {
|
||
mockItem({ quantity: 12 });
|
||
await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||
expect((writebackHttp.mock.calls[0][0] as Record<string, unknown>).confirmOverQty).toBe(true);
|
||
});
|
||
|
||
it('C5:改价审核开关关闭(默认)⇒ 回写照旧携带价格', async () => {
|
||
priceQtyEnabled.value = false;
|
||
await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||
const arg = writebackHttp.mock.calls[0][0] as Record<string, unknown>;
|
||
expect(arg.purchasePrice).toBe(3.5);
|
||
expect(approvedFinal).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('C5:开关打开 + 价格未经审核 ⇒ **不回写价格**(堵住静默通道)', async () => {
|
||
priceQtyEnabled.value = true;
|
||
approvedFinal.mockResolvedValue(null);
|
||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||
const arg = writebackHttp.mock.calls[0][0] as Record<string, unknown>;
|
||
expect(arg.purchasePrice).toBeUndefined();
|
||
// 数量仍按实供量回写(备货完成这件事不受影响)
|
||
expect(arg.prepareQty).toBe(10);
|
||
expect(out.done).toBe(1);
|
||
expect(markWriteback).toHaveBeenCalledWith(
|
||
expect.objectContaining({ status: 'done', reason: expect.stringContaining('未经改价审核流程确认') })
|
||
);
|
||
});
|
||
|
||
it('C5:开关打开 + 已有审核通过的同一价格 ⇒ 照常回写价格', async () => {
|
||
priceQtyEnabled.value = true;
|
||
approvedFinal.mockResolvedValue({ requestId: 'MS-REQ-1', finalPrice: 3.5, finalQty: 10, status: 'approved' });
|
||
await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||
const arg = writebackHttp.mock.calls[0][0] as Record<string, unknown>;
|
||
expect(arg.purchasePrice).toBe(3.5);
|
||
});
|
||
|
||
it('C5:开关打开 + 已审核价与本地价不一致 ⇒ 不回写价格(主系统以自己为准)', async () => {
|
||
priceQtyEnabled.value = true;
|
||
approvedFinal.mockResolvedValue({ requestId: 'MS-REQ-1', finalPrice: 4.2, finalQty: 10, status: 'approved' });
|
||
await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||
const arg = writebackHttp.mock.calls[0][0] as Record<string, unknown>;
|
||
expect(arg.purchasePrice).toBeUndefined();
|
||
});
|
||
|
||
it('主系统 4xx 明确拒绝 → rejected(不再重试)', async () => {
|
||
writebackHttp.mockResolvedValue({ kind: 'rejected', reason: '价格须大于 0' });
|
||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||
expect(out.rejected).toBe(1);
|
||
expect(markWriteback).toHaveBeenCalledWith(expect.objectContaining({ status: 'rejected' }));
|
||
});
|
||
|
||
it('主系统 5xx/超时 → suspended(下轮重试)', async () => {
|
||
writebackHttp.mockResolvedValue({ kind: 'unavailable', reason: 'HTTP 502' });
|
||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||
expect(out.unavailable).toBe(1);
|
||
expect(markWriteback).toHaveBeenCalledWith(expect.objectContaining({ status: 'suspended' }));
|
||
});
|
||
|
||
it('缺对照但能按商品名对上 → 惰性对照后照常回写(历史行自愈)', async () => {
|
||
listPending.mockResolvedValue([{ ...ROW, our_order_item_id: null }]);
|
||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||
// 惰性对照在租户上下文里按「同单 + 同商品名」找回订单行,并回写台账
|
||
expect(setOurOrderItemId).toHaveBeenCalledWith(
|
||
expect.objectContaining({ branchCode: 'SUP1', prepId: 'p1', ourOrderItemId: 'i1' })
|
||
);
|
||
expect(writebackHttp).toHaveBeenCalledTimes(1);
|
||
expect(out.done).toBe(1);
|
||
});
|
||
|
||
it('缺对照且名字也对不上 → 挂 suspended,不发 HTTP(不猜)', async () => {
|
||
listPending.mockResolvedValue([{ ...ROW, our_order_item_id: null, item_name: '对不上的品' }]);
|
||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||
expect(writebackHttp).not.toHaveBeenCalled();
|
||
expect(markWriteback).toHaveBeenCalledWith(expect.objectContaining({ status: 'suspended' }));
|
||
expect(out.attempted).toBe(0);
|
||
});
|
||
|
||
it('无待回写行时不发任何 HTTP', async () => {
|
||
listPending.mockResolvedValue([]);
|
||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||
expect(writebackHttp).not.toHaveBeenCalled();
|
||
expect(out.attempted).toBe(0);
|
||
});
|
||
});
|
||
|
||
describe('A3:按主系统回传的 updated / skipped 记账(2026-10-09 增量)', () => {
|
||
beforeEach(() => {
|
||
query.mockReset();
|
||
writebackHttp.mockReset();
|
||
listPending.mockReset();
|
||
markWriteback.mockReset();
|
||
withTenant.mockReset();
|
||
listPending.mockResolvedValue([ROW]);
|
||
markWriteback.mockResolvedValue(undefined);
|
||
mockItem();
|
||
});
|
||
|
||
it('updated=0 且 reason=already_completed → 记 done(幂等命中,等价成功)', async () => {
|
||
writebackHttp.mockResolvedValue({
|
||
kind: 'ok',
|
||
updated: 0,
|
||
skipped: [{ id: 'p1', skuCode: null, reason: 'already_completed', message: '该行已备货完成' }],
|
||
needsCustomerPrice: false,
|
||
});
|
||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||
expect(out.alreadyDone).toBe(1);
|
||
expect(out.done).toBe(0);
|
||
expect(markWriteback).toHaveBeenCalledWith(expect.objectContaining({ status: 'done' }));
|
||
});
|
||
|
||
it('updated=0 且 reason=transferred_to_purchase → 记 rejected(重试无用,不再重试)', async () => {
|
||
writebackHttp.mockResolvedValue({
|
||
kind: 'ok',
|
||
updated: 0,
|
||
skipped: [{ id: 'p1', skuCode: null, reason: 'transferred_to_purchase', message: '已流转自采' }],
|
||
needsCustomerPrice: false,
|
||
});
|
||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||
expect(out.rejected).toBe(1);
|
||
expect(markWriteback).toHaveBeenCalledWith(expect.objectContaining({ status: 'rejected' }));
|
||
});
|
||
|
||
it('updated=0 且 reason=row_not_updated → 记 suspended(下轮兜底重试)', async () => {
|
||
writebackHttp.mockResolvedValue({
|
||
kind: 'ok',
|
||
updated: 0,
|
||
skipped: [{ id: 'p1', skuCode: null, reason: 'row_not_updated', message: '并发修改' }],
|
||
needsCustomerPrice: false,
|
||
});
|
||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||
expect(out.unavailable).toBe(1);
|
||
expect(markWriteback).toHaveBeenCalledWith(expect.objectContaining({ status: 'suspended' }));
|
||
});
|
||
|
||
it('updated=0 且没有任何 skipped 记录 → 绝不记 done(挂 suspended 交下轮)', async () => {
|
||
writebackHttp.mockResolvedValue({ kind: 'ok', updated: 0, skipped: [], needsCustomerPrice: false });
|
||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||
expect(out.done).toBe(0);
|
||
expect(out.unavailable).toBe(1);
|
||
});
|
||
});
|
||
|
||
describe('A3b:409 的两种含义(真实主系统实测得出)', () => {
|
||
beforeEach(() => {
|
||
query.mockReset();
|
||
writebackHttp.mockReset();
|
||
listPending.mockReset();
|
||
markWriteback.mockReset();
|
||
withTenant.mockReset();
|
||
listPending.mockResolvedValue([ROW]);
|
||
markWriteback.mockResolvedValue(undefined);
|
||
mockItem();
|
||
});
|
||
|
||
it('409「备货已确认锁定」→ already_done(结果已达成,记 done)', async () => {
|
||
writebackHttp.mockResolvedValue({
|
||
kind: 'already_done',
|
||
reason: 'conflict 备货已确认锁定,不可修改(缺货标记除外)',
|
||
});
|
||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||
expect(out.alreadyDone).toBe(1);
|
||
expect(out.rejected).toBe(0);
|
||
expect(markWriteback).toHaveBeenCalledWith(expect.objectContaining({ status: 'done' }));
|
||
});
|
||
|
||
it('409「已流转自采」→ rejected(真的没写进去)', async () => {
|
||
writebackHttp.mockResolvedValue({ kind: 'rejected', reason: 'conflict 该备货已流转自采,不可修改' });
|
||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||
expect(out.rejected).toBe(1);
|
||
expect(out.alreadyDone).toBe(0);
|
||
});
|
||
});
|