- 分公司类型模板:超管配置隐藏路由/菜单 + 中文文案覆盖,仅对挂类型的分公司生效(后端 service/routes、前端 Provider/守卫/配置页) - 超管模板 iframe 真还原预览:28 个业务页注册、白名单点选编辑、空/示例数据 fixture、白名单漂移检测工具 - 商品/SKU 下拉远程搜索:服务端关键词搜索 + 前端 useRemoteOptionSearch/SearchableSelect 接入(订单/采购/商品等页) - 主系统联调:子系统主动解绑主系统授权(幂等重试/本地兜底)、追加修改 price_amend 视图代理与 amend-price 转发 - 修复:仓内加工重复建单幂等(已完成需求单 guard、order 任务一商品一单 guard) - 修复:出入库记录只取前 100 条 → 服务端分页 + 真实总数 - 其它:库存/订单若干修复、分公司管理响应式布局、i18n 文案、设计文档与回归测试
439 lines
18 KiB
TypeScript
439 lines
18 KiB
TypeScript
/**
|
||
* 分公司类型模板路由层测试(设计 v2 §8.2 / §8.5 / INV-3)。
|
||
*
|
||
* 只 mock 认证、ctx 与 service/audit —— `requireSuperAdminRole` / `requireAdminRole` 用**真实实现**,
|
||
* 因此 403 是被测代码(context.ts 守卫 + 路由挂载)的真实行为,不是测试自己模拟出来的。
|
||
* 覆盖:effective 的 branch_code 作用域(非超管忽略参数 / 超管预览 / 不读 x-operating-branch)、
|
||
* 4 类写接口仅超管、分公司重开仅 admin 且强制 ctx.branchCode、409 映射、审计 branchCode 不为空。
|
||
*/
|
||
import express from 'express';
|
||
import request from 'supertest';
|
||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||
import type { TenantContext } from '../src/services/tenantScope';
|
||
|
||
const mocks = vi.hoisted(() => ({
|
||
getWorkflowCtx: vi.fn(),
|
||
resolveEffectiveBranchUi: vi.fn(),
|
||
getBranchUiAdminConfig: vi.fn(),
|
||
saveBranchUiTypes: vi.fn(),
|
||
saveBranchUiTemplate: vi.fn(),
|
||
saveBranchUiBranchOverride: vi.fn(),
|
||
deleteBranchUiType: vi.fn(),
|
||
reopenBranchUiMenus: vi.fn(),
|
||
writeAuditLog: vi.fn(),
|
||
}));
|
||
|
||
vi.mock('../src/middleware/auth', () => ({
|
||
authMiddleware: (req: any, res: any, next: any) => {
|
||
if (!req.headers['x-test-user-id']) return res.status(401).json({ error: 'invalid_token' });
|
||
req.userId = String(req.headers['x-test-user-id']);
|
||
req.tokenScope = 'web';
|
||
next();
|
||
},
|
||
}));
|
||
|
||
vi.mock('../src/modules/workflow/context', async (importOriginal) => {
|
||
const actual = await importOriginal<typeof import('../src/modules/workflow/context')>();
|
||
return {
|
||
...actual,
|
||
getWorkflowCtx: (...args: unknown[]) => mocks.getWorkflowCtx(...args),
|
||
};
|
||
});
|
||
|
||
vi.mock('../src/services/auditService', () => ({
|
||
writeAuditLog: (...args: unknown[]) => mocks.writeAuditLog(...args),
|
||
}));
|
||
|
||
vi.mock('../src/services/branchUiConfigService', () => ({
|
||
BRANCH_UI_TYPES_KEY: 'branch_ui_types',
|
||
BRANCH_UI_BRANCH_KEY: 'branch_ui_branch',
|
||
BRANCH_UI_TEMPLATE_KEY_PREFIX: 'branch_ui_template.',
|
||
emptyBranchUiEffective: (branchCode: string | null) => ({
|
||
applied: false,
|
||
revision: null,
|
||
branch_code: branchCode,
|
||
hidden_menu_keys: [],
|
||
type_hidden_menu_keys: [],
|
||
reopened_menu_keys: [],
|
||
text_overrides: {},
|
||
updated_at: null,
|
||
revisions: null,
|
||
}),
|
||
resolveEffectiveBranchUi: (...args: unknown[]) => mocks.resolveEffectiveBranchUi(...args),
|
||
getBranchUiAdminConfig: (...args: unknown[]) => mocks.getBranchUiAdminConfig(...args),
|
||
saveBranchUiTypes: (...args: unknown[]) => mocks.saveBranchUiTypes(...args),
|
||
saveBranchUiTemplate: (...args: unknown[]) => mocks.saveBranchUiTemplate(...args),
|
||
saveBranchUiBranchOverride: (...args: unknown[]) => mocks.saveBranchUiBranchOverride(...args),
|
||
deleteBranchUiType: (...args: unknown[]) => mocks.deleteBranchUiType(...args),
|
||
reopenBranchUiMenus: (...args: unknown[]) => mocks.reopenBranchUiMenus(...args),
|
||
}));
|
||
|
||
import { mountBranchUiWorkflowRoutes } from '../src/modules/workflow/routes/branchUiRoutes';
|
||
|
||
function ctx(overrides: Partial<TenantContext> = {}): TenantContext {
|
||
return {
|
||
userId: 'U1',
|
||
roles: ['admin'],
|
||
permissions: [],
|
||
branchCode: 'SUP0001',
|
||
supplierCode: null,
|
||
purchaserCode: null,
|
||
isSuperAdmin: false,
|
||
isBranchAdmin: true,
|
||
isInternalStaff: true,
|
||
isSupplierAccount: false,
|
||
...overrides,
|
||
};
|
||
}
|
||
|
||
const SUPER_CTX = ctx({ userId: 'U-SUPER', roles: ['super_admin'], branchCode: null, isSuperAdmin: true, isBranchAdmin: false });
|
||
|
||
function buildApp() {
|
||
const app = express();
|
||
app.use(express.json());
|
||
const router = express.Router();
|
||
mountBranchUiWorkflowRoutes(router);
|
||
app.use('/api/workflow', router);
|
||
return app;
|
||
}
|
||
|
||
const app = buildApp();
|
||
|
||
function withUser(method: 'get' | 'put' | 'delete', url: string) {
|
||
const req = request(app)[method](url).set('x-test-user-id', 'U1');
|
||
return req;
|
||
}
|
||
|
||
beforeEach(() => {
|
||
vi.clearAllMocks();
|
||
mocks.getWorkflowCtx.mockResolvedValue(ctx());
|
||
mocks.resolveEffectiveBranchUi.mockResolvedValue({
|
||
applied: true,
|
||
revision: 'types:1,tpl:2,branch:3',
|
||
branch_code: 'SUP0001',
|
||
type: { code: 'retail', name: '零售型' },
|
||
hidden_menu_keys: ['products-units'],
|
||
type_hidden_menu_keys: ['products-units'],
|
||
reopened_menu_keys: [],
|
||
text_overrides: {},
|
||
updated_at: '2026-11-01T00:00:00.000Z',
|
||
revisions: { types: 1, template: 2, branch: 3 },
|
||
});
|
||
mocks.getBranchUiAdminConfig.mockResolvedValue({
|
||
types: { revision: 1, updated_at: null, updated_by: null, corrupted: false, types: [], assignments: {} },
|
||
templates: [],
|
||
branch_overrides: [],
|
||
branches: [],
|
||
menu_keys: [],
|
||
revision: 'types:1,tpl:0,branch:0',
|
||
});
|
||
mocks.saveBranchUiTypes.mockResolvedValue({ revision: 2 });
|
||
mocks.saveBranchUiTemplate.mockResolvedValue({
|
||
revision: 3,
|
||
type_code: 'retail',
|
||
hidden_count: 1,
|
||
text_override_count: 2,
|
||
});
|
||
mocks.saveBranchUiBranchOverride.mockResolvedValue({
|
||
revision: 4,
|
||
branch_code: 'SUP0001',
|
||
reopened_count: 1,
|
||
hidden_count: 0,
|
||
text_override_count: 1,
|
||
});
|
||
mocks.deleteBranchUiType.mockResolvedValue({
|
||
revision: 5,
|
||
type_code: 'retail',
|
||
removed_assignments: 2,
|
||
template_deleted: true,
|
||
removed_branch_overrides: 1,
|
||
});
|
||
mocks.reopenBranchUiMenus.mockResolvedValue({ revision: 3, reopened_menu_keys: ['products-units'] });
|
||
mocks.writeAuditLog.mockResolvedValue(undefined);
|
||
});
|
||
|
||
afterEach(() => {
|
||
vi.restoreAllMocks();
|
||
});
|
||
|
||
describe('GET /effective 的作用域(AC-32 / INV-3)', () => {
|
||
it('未登录 ⇒ 401', async () => {
|
||
const res = await request(app).get('/api/workflow/platform/branch-ui/effective');
|
||
expect(res.status).toBe(401);
|
||
});
|
||
|
||
it('非超管带 ?branch_code=别家 ⇒ 忽略,读自己分公司', async () => {
|
||
const res = await withUser('get', '/api/workflow/platform/branch-ui/effective?branch_code=SUP9999');
|
||
expect(res.status).toBe(200);
|
||
expect(mocks.resolveEffectiveBranchUi).toHaveBeenCalledTimes(1);
|
||
expect(mocks.resolveEffectiveBranchUi).toHaveBeenCalledWith('SUP0001');
|
||
expect(res.body.data.branch_code).toBe('SUP0001');
|
||
});
|
||
|
||
it('非超管带 x-operating-branch 头不改变结果', async () => {
|
||
await request(app)
|
||
.get('/api/workflow/platform/branch-ui/effective')
|
||
.set('x-test-user-id', 'U1')
|
||
.set('x-operating-branch', 'SUP9999');
|
||
expect(mocks.resolveEffectiveBranchUi).toHaveBeenCalledWith('SUP0001');
|
||
});
|
||
|
||
it('超管不带参数 ⇒ applied:false(看原状),不查配置', async () => {
|
||
mocks.getWorkflowCtx.mockResolvedValue(SUPER_CTX);
|
||
const res = await withUser('get', '/api/workflow/platform/branch-ui/effective');
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.data.applied).toBe(false);
|
||
expect(mocks.resolveEffectiveBranchUi).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('超管带 ?branch_code= ⇒ 预览该分公司', async () => {
|
||
mocks.getWorkflowCtx.mockResolvedValue(SUPER_CTX);
|
||
const res = await withUser('get', '/api/workflow/platform/branch-ui/effective?branch_code=SUP0002');
|
||
expect(res.status).toBe(200);
|
||
expect(mocks.resolveEffectiveBranchUi).toHaveBeenCalledWith('SUP0002');
|
||
});
|
||
|
||
it('未绑定分公司的非超管 ⇒ applied:false', async () => {
|
||
mocks.getWorkflowCtx.mockResolvedValue(ctx({ branchCode: null }));
|
||
const res = await withUser('get', '/api/workflow/platform/branch-ui/effective');
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.data.applied).toBe(false);
|
||
expect(mocks.resolveEffectiveBranchUi).not.toHaveBeenCalled();
|
||
});
|
||
});
|
||
|
||
describe('超管写接口:权限 + 409 + 审计(§8.2 / §8.5)', () => {
|
||
it('admin-config 非超管 403,超管 200', async () => {
|
||
const forbidden = await withUser('get', '/api/workflow/platform/branch-ui/admin-config');
|
||
expect(forbidden.status).toBe(403);
|
||
expect(mocks.getBranchUiAdminConfig).not.toHaveBeenCalled();
|
||
|
||
mocks.getWorkflowCtx.mockResolvedValue(SUPER_CTX);
|
||
const ok = await withUser('get', '/api/workflow/platform/branch-ui/admin-config');
|
||
expect(ok.status).toBe(200);
|
||
expect(ok.body.data.types.revision).toBe(1);
|
||
});
|
||
|
||
it('PUT /types 非超管 403;超管 200 且审计 branchCode=平台分公司', async () => {
|
||
const forbidden = await withUser('put', '/api/workflow/platform/branch-ui/types').send({
|
||
types: [],
|
||
assignments: {},
|
||
});
|
||
expect(forbidden.status).toBe(403);
|
||
expect(mocks.saveBranchUiTypes).not.toHaveBeenCalled();
|
||
|
||
mocks.getWorkflowCtx.mockResolvedValue(SUPER_CTX);
|
||
const ok = await withUser('put', '/api/workflow/platform/branch-ui/types').send({
|
||
expected_revision: 1,
|
||
types: [{ code: 'retail', name: '零售型', status: 1 }],
|
||
assignments: { SUP0001: 'retail' },
|
||
});
|
||
expect(ok.status).toBe(200);
|
||
expect(ok.body.data).toEqual({ revision: 2 });
|
||
expect(mocks.saveBranchUiTypes).toHaveBeenCalledWith(
|
||
expect.objectContaining({ expectedRevision: 1, types: expect.any(Array), operatorId: 'U-SUPER' })
|
||
);
|
||
expect(mocks.writeAuditLog).toHaveBeenCalledTimes(1);
|
||
const audit = mocks.writeAuditLog.mock.calls[0][0];
|
||
expect(audit).toMatchObject({
|
||
operationType: 'branch_ui_template_update',
|
||
actionCategory: 'platform',
|
||
targetTable: 'system_configs',
|
||
branchCode: 'BR001',
|
||
targetId: 'branch_ui_types',
|
||
});
|
||
expect(audit.newValue).toMatchObject({ target: 'branch_ui_types', revision: 2 });
|
||
expect(audit.newValue.branch_code).toBe('BR001');
|
||
});
|
||
|
||
it('PUT /templates/:typeCode 超管 200,审计 branchCode=平台分公司', async () => {
|
||
mocks.getWorkflowCtx.mockResolvedValue(SUPER_CTX);
|
||
const res = await withUser('put', '/api/workflow/platform/branch-ui/templates/retail').send({
|
||
hidden_menu_keys: ['products-units'],
|
||
text_overrides: { 'orders.title': '配送单' },
|
||
});
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.data).toMatchObject({ revision: 3, type_code: 'retail', hidden_count: 1, text_override_count: 2 });
|
||
const audit = mocks.writeAuditLog.mock.calls[0][0];
|
||
expect(audit.branchCode).toBe('BR001');
|
||
expect(audit.targetId).toBe('branch_ui_template.retail');
|
||
expect(audit.newValue).toMatchObject({ target: 'branch_ui_template.retail', hidden_count: 1, revision: 3 });
|
||
});
|
||
|
||
it('PUT /branches/:branchCode 超管 200,审计 branchCode=目标分公司', async () => {
|
||
mocks.getWorkflowCtx.mockResolvedValue(SUPER_CTX);
|
||
const res = await withUser('put', '/api/workflow/platform/branch-ui/branches/SUP0001').send({
|
||
reopened_menu_keys: ['products-units'],
|
||
});
|
||
expect(res.status).toBe(200);
|
||
expect(mocks.saveBranchUiBranchOverride).toHaveBeenCalledWith(
|
||
'SUP0001',
|
||
expect.objectContaining({ reopenedMenuKeys: ['products-units'] })
|
||
);
|
||
const audit = mocks.writeAuditLog.mock.calls[0][0];
|
||
expect(audit.branchCode).toBe('SUP0001');
|
||
expect(audit.newValue).toMatchObject({ branch_code: 'SUP0001', reopened_count: 1, revision: 4 });
|
||
});
|
||
|
||
it('DELETE /types/:typeCode 非超管 403;超管 200', async () => {
|
||
const forbidden = await withUser('delete', '/api/workflow/platform/branch-ui/types/retail');
|
||
expect(forbidden.status).toBe(403);
|
||
expect(mocks.deleteBranchUiType).not.toHaveBeenCalled();
|
||
|
||
mocks.getWorkflowCtx.mockResolvedValue(SUPER_CTX);
|
||
const ok = await withUser('delete', '/api/workflow/platform/branch-ui/types/retail?expected_revision=2');
|
||
expect(ok.status).toBe(200);
|
||
expect(ok.body.data).toMatchObject({ revision: 5, removed_assignments: 2 });
|
||
expect(mocks.writeAuditLog.mock.calls[0][0].branchCode).toBe('BR001');
|
||
});
|
||
|
||
it('409 revision_conflict ⇒ HTTP 409 + 当前 revision', async () => {
|
||
mocks.getWorkflowCtx.mockResolvedValue(SUPER_CTX);
|
||
mocks.saveBranchUiTemplate.mockRejectedValueOnce(
|
||
Object.assign(new Error('配置已被其他管理员修改,请刷新后重试'), {
|
||
status: 409,
|
||
code: 'revision_conflict',
|
||
revision: 7,
|
||
})
|
||
);
|
||
const res = await withUser('put', '/api/workflow/platform/branch-ui/templates/retail').send({
|
||
expected_revision: 2,
|
||
hidden_menu_keys: [],
|
||
});
|
||
expect(res.status).toBe(409);
|
||
expect(res.body).toMatchObject({ error: 'revision_conflict', revision: 7 });
|
||
expect(mocks.writeAuditLog).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('审计失败不回滚、不影响响应(与既有配置类审计同口径)', async () => {
|
||
mocks.getWorkflowCtx.mockResolvedValue(SUPER_CTX);
|
||
mocks.writeAuditLog.mockRejectedValueOnce(new Error('audit down'));
|
||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||
const res = await withUser('put', '/api/workflow/platform/branch-ui/types').send({ types: [], assignments: {} });
|
||
expect(res.status).toBe(200);
|
||
expect(warn).toHaveBeenCalled();
|
||
warn.mockRestore();
|
||
});
|
||
});
|
||
|
||
describe('PUT /reopen 分公司管理员(§9.6 / D6)', () => {
|
||
it('分公司 admin ⇒ 强制 ctx.branchCode,请求体伪造 branch_code 无效', async () => {
|
||
const res = await withUser('put', '/api/workflow/platform/branch-ui/reopen').send({
|
||
branch_code: 'SUP9999',
|
||
reopened_menu_keys: ['products-units'],
|
||
});
|
||
expect(res.status).toBe(200);
|
||
expect(mocks.reopenBranchUiMenus).toHaveBeenCalledWith(
|
||
'SUP0001',
|
||
expect.objectContaining({ reopenedMenuKeys: ['products-units'] })
|
||
);
|
||
const audit = mocks.writeAuditLog.mock.calls[0][0];
|
||
expect(audit.branchCode).toBe('SUP0001');
|
||
expect(audit.newValue).toMatchObject({ branch_code: 'SUP0001', reopened_count: 1 });
|
||
});
|
||
|
||
it('非 admin(如 operator)⇒ 403,service 不被调用', async () => {
|
||
mocks.getWorkflowCtx.mockResolvedValue(ctx({ roles: ['operator'], isBranchAdmin: false }));
|
||
const res = await withUser('put', '/api/workflow/platform/branch-ui/reopen').send({
|
||
reopened_menu_keys: [],
|
||
});
|
||
expect(res.status).toBe(403);
|
||
expect(mocks.reopenBranchUiMenus).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('超管 ⇒ 403(超管走「分公司微调」接口),service 不被调用', async () => {
|
||
mocks.getWorkflowCtx.mockResolvedValue(SUPER_CTX);
|
||
const res = await withUser('put', '/api/workflow/platform/branch-ui/reopen').send({
|
||
reopened_menu_keys: [],
|
||
});
|
||
expect(res.status).toBe(403);
|
||
expect(mocks.reopenBranchUiMenus).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('未绑定分公司的 admin ⇒ 400', async () => {
|
||
mocks.getWorkflowCtx.mockResolvedValue(ctx({ branchCode: null }));
|
||
const res = await withUser('put', '/api/workflow/platform/branch-ui/reopen').send({
|
||
reopened_menu_keys: [],
|
||
});
|
||
expect(res.status).toBe(400);
|
||
expect(res.body.error).toBe('branch_required');
|
||
});
|
||
});
|
||
|
||
|
||
describe('F8:畸形 branch_code 在路由层 400(不落库、不回显 PG 错误)', () => {
|
||
it('超管 effective?branch_code=<NUL> ⇒ 400 invalid_branch_code,且不查库', async () => {
|
||
mocks.getWorkflowCtx.mockResolvedValue(SUPER_CTX);
|
||
const res = await withUser(
|
||
'get',
|
||
`/api/workflow/platform/branch-ui/effective?branch_code=${encodeURIComponent('\u0000')}`
|
||
);
|
||
expect(res.status).toBe(400);
|
||
expect(res.body.error).toBe('invalid_branch_code');
|
||
expect(mocks.resolveEffectiveBranchUi).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('超管 effective?branch_code=<带空格/控制字符> ⇒ 400;合法编码仍 200', async () => {
|
||
mocks.getWorkflowCtx.mockResolvedValue(SUPER_CTX);
|
||
const bad = await withUser(
|
||
'get',
|
||
`/api/workflow/platform/branch-ui/effective?branch_code=${encodeURIComponent('SUP 0001')}`
|
||
);
|
||
expect(bad.status).toBe(400);
|
||
const ok = await withUser('get', '/api/workflow/platform/branch-ui/effective?branch_code=SUP0001');
|
||
expect(ok.status).toBe(200);
|
||
expect(mocks.resolveEffectiveBranchUi).toHaveBeenCalledWith('SUP0001');
|
||
});
|
||
|
||
it('非超管带畸形 branch_code 参数 ⇒ 忽略(仍读自己分公司,不 400)', async () => {
|
||
const res = await withUser(
|
||
'get',
|
||
`/api/workflow/platform/branch-ui/effective?branch_code=${encodeURIComponent('\u0000')}`
|
||
);
|
||
expect(res.status).toBe(200);
|
||
expect(mocks.resolveEffectiveBranchUi).toHaveBeenCalledWith('SUP0001');
|
||
});
|
||
|
||
it('超管 PUT branches/:branchCode 畸形 ⇒ 400 且 service 不被调用', async () => {
|
||
mocks.getWorkflowCtx.mockResolvedValue(SUPER_CTX);
|
||
const nul = await withUser(
|
||
'put',
|
||
`/api/workflow/platform/branch-ui/branches/${encodeURIComponent('\u0000')}`
|
||
).send({ reopened_menu_keys: [] });
|
||
expect(nul.status).toBe(400);
|
||
expect(nul.body.error).toBe('invalid_branch_code');
|
||
const spaced = await withUser('put', '/api/workflow/platform/branch-ui/branches/SUP%200001').send({});
|
||
expect(spaced.status).toBe(400);
|
||
expect(mocks.saveBranchUiBranchOverride).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('DELETE types 响应包含 F6 清理的覆盖行数', async () => {
|
||
mocks.getWorkflowCtx.mockResolvedValue(SUPER_CTX);
|
||
const res = await withUser('delete', '/api/workflow/platform/branch-ui/types/retail');
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.data).toMatchObject({ removed_assignments: 2, removed_branch_overrides: 1 });
|
||
});
|
||
});
|
||
|
||
|
||
describe('F13:branch_code 大小写归一到大写', () => {
|
||
it('超管 effective?branch_code=br002 ⇒ 以 BR002 查询(不再静默查不到)', async () => {
|
||
mocks.getWorkflowCtx.mockResolvedValue(SUPER_CTX);
|
||
const res = await withUser('get', '/api/workflow/platform/branch-ui/effective?branch_code=br002');
|
||
expect(res.status).toBe(200);
|
||
expect(mocks.resolveEffectiveBranchUi).toHaveBeenCalledWith('BR002');
|
||
});
|
||
|
||
it('PUT branches/br002 ⇒ 以 BR002 调用领域保存', async () => {
|
||
mocks.getWorkflowCtx.mockResolvedValue(SUPER_CTX);
|
||
const res = await withUser('put', '/api/workflow/platform/branch-ui/branches/br002').send({
|
||
reopened_menu_keys: [],
|
||
});
|
||
expect(res.status).toBe(200);
|
||
expect(mocks.saveBranchUiBranchOverride).toHaveBeenCalledWith(
|
||
'BR002',
|
||
expect.objectContaining({ expectedRevision: undefined })
|
||
);
|
||
});
|
||
});
|