Files
SupplierSystem/server/tests/reportPushTenantContextIsolation.test.ts
T
Ubuntu ad36182a9e
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
fix(报告推送/订单UI): 修复"立即推送"租户上下文竞态;移除全天下单控件;抵扣批次显示商品名
1) 批次报告"立即推送"偶发丢失(租户上下文收尾竞态报 42P01 被吞,只能等 15 分钟对账):
   - 连接归还前先排空请求级查询队列,再复位 search_path;
   - triggerReportPush 改独立租户上下文(isolate)运行,失败日志带分公司;
   - webhook 绑定后即时拉取改用新增的 runDetachedTenantTask(独立连接 + 结构化错误日志)。
2) 订单管理工具栏移除「全天下单」控件及配套状态/接口调用(后端下单时段配置未改)。
3) 「选择抵扣的库存商品」弹窗:实际抵扣批次前置库存商品名(SKU),名字取自候选列表。

测试:releaseTenantSessionClient.ordering / reportPushTenantContextIsolation /
tenantContextDetachedTask.integration 共 8 用例通过;OrderItemCoverSkuModal +
orderManagement 共 138 用例通过;npm run typecheck 通过。
2026-10-21 19:21:20 +08:00

95 lines
4.3 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 path from 'node:path';
import { beforeEach, describe, expect, it, vi } from 'vitest';
/**
* 2026-10-21 报告推送稳定性修复:**旁路异步必须使用隔离租户上下文**。
*
* 1) `pushBranchReports` 必须用 `runWithTenantDbContext(..., { isolate: true })`:
* 旁路任务不得继承请求级 ALS 租户上下文,否则请求收尾复位 search_path 时会让它跑到 public 上(42P01)。
* 2) `triggerReportPush` 的失败日志必须带分公司(原来「已吞」且无上下文,线上排障看不到)。
* 3) webhook 绑定后的即时拉单必须改走 `runDetachedTenantTask`(同类根因的第二个现场)。
*/
const H = vi.hoisted(() => ({
tenantCalls: [] as Array<{ code: string; opts: unknown }>,
failNextTenantRun: false,
}));
vi.mock('../src/services/tenantDbContext', () => ({
runWithTenantDbContext: async (code: string, fn: () => Promise<unknown>, opts?: unknown) => {
H.tenantCalls.push({ code, opts });
if (H.failNextTenantRun) {
H.failNextTenantRun = false;
throw new Error('simulated tenant context failure');
}
return fn();
},
}));
vi.mock('../src/db', () => ({
pool: {
query: async () => ({ rows: [], rowCount: 0 }),
connect: async () => ({ query: async () => ({ rows: [], rowCount: 0 }), release: () => undefined }),
},
query: async () => ({ rows: [], rowCount: 0 }),
getRawPoolQuery: () => async () => ({ rows: [], rowCount: 0 }),
getRawPoolConnect: async () => ({ query: async () => ({ rows: [], rowCount: 0 }), release: () => undefined }),
isRlsRoleAvailable: async () => true,
allowRlsFailOpen: () => true,
runWithBranchRls: async (_branch: string, fn: (client: unknown) => Promise<unknown>) => fn({}),
}));
vi.mock('../src/services/storageProvider', () => ({
getStorageProvider: () => ({ getObject: async () => null }),
}));
vi.mock('../src/services/mainSystem/api/qualityReports', () => ({
registerBatchReportOnPreparation: async () => ({ kind: 'not_configured', reason: 'test' }),
uploadBatchReportFile: async () => ({ kind: 'not_configured', reason: 'test' }),
isUploadableReportFileName: () => true,
voidSupplierBatchReport: async () => ({ kind: 'not_configured' }),
}));
const SERVICE = path.resolve(__dirname, '../src/services/mainSystemReportPushService.ts');
const INTEGRATION_ROUTE = path.resolve(__dirname, '../src/routes/mainSystemIntegration.ts');
describe('报告推送旁路异步的租户上下文隔离', () => {
beforeEach(() => {
H.tenantCalls = [];
H.failNextTenantRun = false;
process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true';
});
it('pushBranchReports 以 isolate:true 自取租户连接(不复用请求上下文)', async () => {
const { pushBranchReports } = await import('../src/services/mainSystemReportPushService');
const stat = await pushBranchReports({ branchCode: 'BR002' });
expect(H.tenantCalls).toHaveLength(1);
expect(H.tenantCalls[0]).toEqual({ code: 'BR002', opts: { isolate: true } });
expect(stat.candidates).toBe(0);
});
it('triggerReportPush 失败日志带分公司上下文(不再静默无上下文)', async () => {
const { triggerReportPush } = await import('../src/services/mainSystemReportPushService');
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
H.failNextTenantRun = true;
triggerReportPush('BR002');
// 等旁路 promise 的 catch 执行
await new Promise((resolve) => setTimeout(resolve, 20));
const messages = errorSpy.mock.calls.map((args) => args.map(String).join(' '));
expect(messages.some((m) => m.includes('[report-push]') && m.includes('BR002'))).toBe(true);
errorSpy.mockRestore();
});
it('源码合同:webhook 绑定后拉单改走 runDetachedTenantTask,不再裸 void importMainSystemOrders', () => {
const source = readFileSync(INTEGRATION_ROUTE, 'utf8');
expect(source).toContain("runDetachedTenantTask(branch, 'webhook-import'");
expect(source).not.toContain('void importMainSystemOrders({ branchCode: branch, userId: null })');
});
it('源码合同:pushBranchReports 的 isolate 标记仍在(防以后被顺手删掉)', () => {
const source = readFileSync(SERVICE, 'utf8');
expect(source).toContain('{ isolate: true }');
});
});