- 分公司类型模板:超管配置隐藏路由/菜单 + 中文文案覆盖,仅对挂类型的分公司生效(后端 service/routes、前端 Provider/守卫/配置页) - 超管模板 iframe 真还原预览:28 个业务页注册、白名单点选编辑、空/示例数据 fixture、白名单漂移检测工具 - 商品/SKU 下拉远程搜索:服务端关键词搜索 + 前端 useRemoteOptionSearch/SearchableSelect 接入(订单/采购/商品等页) - 主系统联调:子系统主动解绑主系统授权(幂等重试/本地兜底)、追加修改 price_amend 视图代理与 amend-price 转发 - 修复:仓内加工重复建单幂等(已完成需求单 guard、order 任务一商品一单 guard) - 修复:出入库记录只取前 100 条 → 服务端分页 + 真实总数 - 其它:库存/订单若干修复、分公司管理响应式布局、i18n 文案、设计文档与回归测试
794 lines
32 KiB
TypeScript
794 lines
32 KiB
TypeScript
/**
|
||
* 分公司类型模板配置服务 · 边界/回归补充(tester,独立于 dev 的 branchUiConfigService.test.ts)。
|
||
*
|
||
* 只补 dev 单测未覆盖的「边」:
|
||
* - 隐藏合并边界:重开 ∩ 额外隐藏、类型删项后的陈旧重开、无效重开;
|
||
* - No-Op 读侧容错边界:版本/类型/状态/所属分公司不一致等损坏形态;
|
||
* - 校验边界:hidden 非数组 / 非字符串 / 去重、i18n key 长度与形状、401 字文案、名称 trim;
|
||
* - revision 409:删除类型、保存类型;**损坏行修复**时 expected_revision 不得误报 409;
|
||
* - 分公司覆盖部分更新:只传 reopened / text 时不丢其它字段;不存在公司 400;类型停用后重开 400;
|
||
* - 删除类型只动自身:其它类型模板 / 归属保留。
|
||
*
|
||
* 不连库:与 dev 单测同一套内存 system_configs/branches 假库(SQL 按语句特征分派)。
|
||
*/
|
||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||
|
||
interface StoredRow {
|
||
config_key: string;
|
||
branch_code: string | null;
|
||
config_value: unknown;
|
||
config_group: string | null;
|
||
description: string | null;
|
||
updated_at: string;
|
||
updated_by: string | null;
|
||
}
|
||
|
||
interface StoredBranch {
|
||
branch_code: string;
|
||
branch_name: string | null;
|
||
status: number;
|
||
}
|
||
|
||
const store = vi.hoisted(() => {
|
||
const rows = new Map<string, StoredRow>();
|
||
const branches = new Map<string, StoredBranch>();
|
||
const rowKey = (configKey: string, branchCode: string | null) => `${configKey}||${branchCode ?? ''}`;
|
||
|
||
const query = vi.fn(async (sql: string, params: unknown[] = []) => {
|
||
const normalized = String(sql).replace(/\s+/g, ' ').trim();
|
||
|
||
if (normalized.startsWith('SELECT config_value, updated_at, updated_by FROM public.system_configs')) {
|
||
const configKey = String(params[0]);
|
||
const isBranchScoped = normalized.includes('branch_code = $2');
|
||
const branchCode = isBranchScoped ? String(params[1]) : null;
|
||
const row = rows.get(rowKey(configKey, branchCode));
|
||
return {
|
||
rows: row
|
||
? [{ config_value: row.config_value, updated_at: row.updated_at, updated_by: row.updated_by }]
|
||
: [],
|
||
rowCount: row ? 1 : 0,
|
||
};
|
||
}
|
||
|
||
if (
|
||
normalized.startsWith(
|
||
'SELECT config_key, config_value, updated_at, updated_by FROM public.system_configs'
|
||
)
|
||
) {
|
||
const prefix = String(params[0]).replace(/%$/, '');
|
||
const matched = [...rows.values()]
|
||
.filter((row) => row.branch_code === null && row.config_key.startsWith(prefix))
|
||
.sort((a, b) => a.config_key.localeCompare(b.config_key));
|
||
return {
|
||
rows: matched.map((row) => ({
|
||
config_key: row.config_key,
|
||
config_value: row.config_value,
|
||
updated_at: row.updated_at,
|
||
updated_by: row.updated_by,
|
||
})),
|
||
rowCount: matched.length,
|
||
};
|
||
}
|
||
|
||
if (
|
||
normalized.startsWith(
|
||
'SELECT config_key, branch_code, config_value, updated_at, updated_by FROM public.system_configs'
|
||
)
|
||
) {
|
||
const configKey = String(params[0]);
|
||
const matched = [...rows.values()]
|
||
.filter((row) => row.config_key === configKey)
|
||
.sort((a, b) => String(a.branch_code).localeCompare(String(b.branch_code)));
|
||
return {
|
||
rows: matched.map((row) => ({
|
||
config_key: row.config_key,
|
||
branch_code: row.branch_code,
|
||
config_value: row.config_value,
|
||
updated_at: row.updated_at,
|
||
updated_by: row.updated_by,
|
||
})),
|
||
rowCount: matched.length,
|
||
};
|
||
}
|
||
|
||
if (normalized.startsWith('SELECT branch_code, branch_name, status FROM public.branches')) {
|
||
if (normalized.includes('WHERE branch_code = $1')) {
|
||
const branch = branches.get(String(params[0]));
|
||
return { rows: branch ? [{ ...branch }] : [], rowCount: branch ? 1 : 0 };
|
||
}
|
||
const all = [...branches.values()].sort((a, b) => a.branch_code.localeCompare(b.branch_code));
|
||
return { rows: all.map((branch) => ({ ...branch })), rowCount: all.length };
|
||
}
|
||
|
||
if (normalized.startsWith('SELECT branch_code FROM public.branches WHERE branch_code = ANY')) {
|
||
const codes = (params[0] as string[]) || [];
|
||
const matched = codes.filter((code) => branches.has(code));
|
||
return { rows: matched.map((code) => ({ branch_code: code })), rowCount: matched.length };
|
||
}
|
||
|
||
if (normalized.startsWith('INSERT INTO public.system_configs')) {
|
||
// task-9 F3 起写库有两种形态,这里都要支持:
|
||
// a) CAS upsert(7 参数,`DO UPDATE ... WHERE COALESCE(...->>'revision','0')::int = $7 RETURNING id`)
|
||
// ⇒ 行不存在:插入成功 rowCount=1;行存在:仅当现有 revision === params[6] 才覆盖,
|
||
// 否则返回 { rows: [], rowCount: 0 }(service 据此转 409 并回填当前 revision)
|
||
// b) 损坏行修复路径:旧的无条件 upsert(6 参数,DO UPDATE 无 WHERE)
|
||
// ⇒ 无条件覆盖写 rowCount=1(这正是"修复"语义)
|
||
// 另兼容 `ON CONFLICT DO NOTHING` 形态(冲突时 rowCount=0)。
|
||
const isCas =
|
||
/WHERE\s+COALESCE\(.*revision.*\)::int\s*=\s*\$7/i.test(normalized) ||
|
||
/RETURNING\s+id/i.test(normalized);
|
||
const isDoNothing = /ON CONFLICT/i.test(normalized) && /DO NOTHING/i.test(normalized);
|
||
const [configKey, json, configGroup, description, branchCode, updatedBy] = params as [
|
||
string,
|
||
string,
|
||
string,
|
||
string,
|
||
string | null,
|
||
string | null,
|
||
];
|
||
const value = JSON.parse(json);
|
||
const key = rowKey(configKey, branchCode ?? null);
|
||
const existing = rows.get(key);
|
||
if (isCas && existing) {
|
||
const expectedRevision = Number(params[6]);
|
||
const currentRevision = Number(
|
||
(existing.config_value as { revision?: unknown } | null)?.revision ?? 0
|
||
);
|
||
if (
|
||
!Number.isFinite(expectedRevision) ||
|
||
!Number.isFinite(currentRevision) ||
|
||
currentRevision !== expectedRevision
|
||
) {
|
||
return { rows: [], rowCount: 0 };
|
||
}
|
||
}
|
||
if (isDoNothing && existing) return { rows: [], rowCount: 0 };
|
||
const row: StoredRow = {
|
||
config_key: configKey,
|
||
branch_code: branchCode ?? null,
|
||
config_value: value,
|
||
config_group: configGroup ?? null,
|
||
description: description ?? null,
|
||
updated_at: new Date().toISOString(),
|
||
updated_by: updatedBy ?? null,
|
||
};
|
||
rows.set(key, row);
|
||
if (isCas) return { rows: [{ id: `row-${key}` }], rowCount: 1 };
|
||
return { rows: [{ ...row }], rowCount: 1 };
|
||
}
|
||
|
||
if (normalized.startsWith('DELETE FROM public.system_configs')) {
|
||
const configKey = String(params[0]);
|
||
const branchCode = normalized.includes('branch_code = $2') ? String(params[1]) : null;
|
||
const existed = rows.delete(rowKey(configKey, branchCode));
|
||
return { rows: [], rowCount: existed ? 1 : 0 };
|
||
}
|
||
|
||
throw new Error(`未预期的 SQL:${normalized.slice(0, 120)}`);
|
||
});
|
||
|
||
return { rows, branches, query, rowKey };
|
||
});
|
||
|
||
vi.mock('../src/db', () => ({
|
||
pool: { query: (...args: unknown[]) => store.query(...args) },
|
||
query: (...args: unknown[]) => store.query(...args),
|
||
getRawPoolQuery: () => (...args: unknown[]) => store.query(...args),
|
||
}));
|
||
|
||
import {
|
||
BRANCH_UI_BRANCH_KEY,
|
||
BRANCH_UI_TYPES_KEY,
|
||
MAX_CONFIG_REVISION,
|
||
branchUiTemplateKey,
|
||
deleteBranchUiType,
|
||
invalidateBranchUiConfigCache,
|
||
reopenBranchUiMenus,
|
||
resolveEffectiveBranchUi,
|
||
saveBranchUiBranchOverride,
|
||
saveBranchUiTemplate,
|
||
saveBranchUiTypes,
|
||
} from '../src/services/branchUiConfigService';
|
||
|
||
const TYPES_ROW_KEY = BRANCH_UI_TYPES_KEY;
|
||
const BRANCH = 'SUP0001';
|
||
const OTHER_BRANCH = 'SUP0002';
|
||
|
||
function setBranch(branchCode: string, status = 1) {
|
||
store.branches.set(branchCode, { branch_code: branchCode, branch_name: branchCode, status });
|
||
}
|
||
|
||
function setConfigRow(configKey: string, branchCode: string | null, value: unknown) {
|
||
store.rows.set(store.rowKey(configKey, branchCode), {
|
||
config_key: configKey,
|
||
branch_code: branchCode,
|
||
config_value: value,
|
||
config_group: 'branch_ui',
|
||
description: null,
|
||
updated_at: '2026-11-01T00:00:00.000Z',
|
||
updated_by: null,
|
||
});
|
||
}
|
||
|
||
function readConfigRow(configKey: string, branchCode: string | null = null): StoredRow | undefined {
|
||
return store.rows.get(store.rowKey(configKey, branchCode));
|
||
}
|
||
|
||
function seedTypes(overrides: {
|
||
revision?: number;
|
||
types?: unknown[];
|
||
assignments?: Record<string, string>;
|
||
} = {}) {
|
||
setConfigRow(TYPES_ROW_KEY, null, {
|
||
version: 1,
|
||
revision: overrides.revision ?? 1,
|
||
types: overrides.types ?? [
|
||
{ code: 'retail', name: '零售型', sort: 1, status: 1 },
|
||
{ code: 'wholesale', name: '批发型', sort: 2, status: 1 },
|
||
],
|
||
assignments: overrides.assignments ?? { [BRANCH]: 'retail', [OTHER_BRANCH]: 'retail' },
|
||
updated_at: '2026-11-01T00:00:00.000Z',
|
||
updated_by: null,
|
||
});
|
||
}
|
||
|
||
function seedTemplate(
|
||
typeCode: string,
|
||
overrides: { revision?: number; hidden?: string[]; text?: Record<string, string>; raw?: unknown } = {}
|
||
) {
|
||
if (overrides.raw !== undefined) {
|
||
setConfigRow(branchUiTemplateKey(typeCode), null, overrides.raw);
|
||
return;
|
||
}
|
||
setConfigRow(branchUiTemplateKey(typeCode), null, {
|
||
version: 1,
|
||
revision: overrides.revision ?? 1,
|
||
type_code: typeCode,
|
||
hidden_menu_keys: overrides.hidden ?? [],
|
||
text_overrides: overrides.text ?? {},
|
||
updated_at: '2026-11-01T01:00:00.000Z',
|
||
updated_by: null,
|
||
});
|
||
}
|
||
|
||
function seedBranchOverride(
|
||
branchCode: string,
|
||
overrides: {
|
||
revision?: number;
|
||
reopened?: string[];
|
||
hidden?: string[];
|
||
text?: Record<string, string>;
|
||
raw?: unknown;
|
||
} = {}
|
||
) {
|
||
if (overrides.raw !== undefined) {
|
||
setConfigRow(BRANCH_UI_BRANCH_KEY, branchCode, overrides.raw);
|
||
return;
|
||
}
|
||
setConfigRow(BRANCH_UI_BRANCH_KEY, branchCode, {
|
||
version: 1,
|
||
revision: overrides.revision ?? 1,
|
||
branch_code: branchCode,
|
||
reopened_menu_keys: overrides.reopened ?? [],
|
||
hidden_menu_keys: overrides.hidden ?? [],
|
||
text_overrides: overrides.text ?? {},
|
||
updated_at: '2026-11-01T02:00:00.000Z',
|
||
updated_by: null,
|
||
});
|
||
}
|
||
|
||
/** 一次性铺「类型 hidden + 分公司额外 hidden/reopened」场景 */
|
||
function seedScenario(input: {
|
||
typeHidden?: string[];
|
||
branchHidden?: string[];
|
||
reopened?: string[];
|
||
}) {
|
||
seedTypes();
|
||
setBranch(BRANCH);
|
||
setBranch(OTHER_BRANCH);
|
||
seedTemplate('retail', { hidden: input.typeHidden ?? [] });
|
||
if ((input.branchHidden ?? []).length || (input.reopened ?? []).length) {
|
||
seedBranchOverride(BRANCH, { hidden: input.branchHidden, reopened: input.reopened });
|
||
}
|
||
}
|
||
|
||
beforeEach(() => {
|
||
store.rows.clear();
|
||
store.branches.clear();
|
||
store.query.mockClear();
|
||
invalidateBranchUiConfigCache();
|
||
});
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// 隐藏合并边界 §7.2
|
||
// ---------------------------------------------------------------------------
|
||
|
||
describe('隐藏合并边界(§7.2:effectiveHidden = (typeHidden ∪ branchExtraHide) − branchReopened)', () => {
|
||
it('类型隐藏 + 额外隐藏:并集、去重、类型项在前', async () => {
|
||
seedScenario({
|
||
typeHidden: ['inventory', 'finance-overview'],
|
||
branchHidden: ['finance-overview', 'orders-list'],
|
||
});
|
||
const result = await resolveEffectiveBranchUi(BRANCH);
|
||
expect(result.applied).toBe(true);
|
||
expect(result.hidden_menu_keys).toEqual(['inventory', 'finance-overview', 'orders-list']);
|
||
});
|
||
|
||
it('同一 key 同时在类型隐藏 / 额外隐藏 / 重开 ⇒ 重开胜出(重开 ∩ 额外隐藏)', async () => {
|
||
seedScenario({
|
||
typeHidden: ['inventory'],
|
||
branchHidden: ['inventory'],
|
||
reopened: ['inventory'],
|
||
});
|
||
const result = await resolveEffectiveBranchUi(BRANCH);
|
||
expect(result.hidden_menu_keys).toEqual([]);
|
||
expect(result.reopened_menu_keys).toEqual(['inventory']);
|
||
expect(result.type_hidden_menu_keys).toEqual(['inventory']);
|
||
});
|
||
|
||
it('陈旧重开(类型模板已删掉该项):按 §7.2 公式不再隐藏,且不计入有效重开', async () => {
|
||
// 场景:类型原来隐藏 inventory,分公司重开过;后来类型模板去掉 inventory(全局放开)。
|
||
// 设计 §7.2 第 227 行:重开只对类型隐藏集内 key 生效 ⇒ 陈旧项自然失效。
|
||
seedScenario({ typeHidden: [], branchHidden: [], reopened: ['inventory'] });
|
||
const result = await resolveEffectiveBranchUi(BRANCH);
|
||
expect(result.hidden_menu_keys).toEqual([]);
|
||
expect(result.reopened_menu_keys).toEqual([]); // 有效重开只回传类型隐藏集内的项
|
||
});
|
||
|
||
it('陈旧重开不会误伤「不在类型隐藏集」的其它额外隐藏项', async () => {
|
||
seedScenario({
|
||
typeHidden: [],
|
||
branchHidden: ['finance-overview'],
|
||
reopened: ['inventory'],
|
||
});
|
||
const result = await resolveEffectiveBranchUi(BRANCH);
|
||
expect(result.hidden_menu_keys).toEqual(['finance-overview']);
|
||
expect(result.reopened_menu_keys).toEqual([]);
|
||
});
|
||
|
||
it('陈旧重开与分公司额外隐藏同名 ⇒ 额外隐藏必须保留(§7.2 第 227 行,独立复测 dev 修复)', async () => {
|
||
// 线上路径:类型模板原隐藏 orders-list 且分公司重开过;后来类型模板删掉 orders-list,
|
||
// 分公司另外又把 orders-list 额外隐藏 ⇒ 陈旧 reopened 不得把额外隐藏解开。
|
||
seedScenario({
|
||
typeHidden: ['inventory'],
|
||
branchHidden: ['orders-list'],
|
||
reopened: ['orders-list'],
|
||
});
|
||
const result = await resolveEffectiveBranchUi(BRANCH);
|
||
expect(result.hidden_menu_keys).toEqual(['inventory', 'orders-list']);
|
||
expect(result.reopened_menu_keys).toEqual([]);
|
||
expect(result.type_hidden_menu_keys).toEqual(['inventory']);
|
||
});
|
||
|
||
it('无效重开 key 混入:有效项仍生效、有效重开列表保持入参顺序', async () => {
|
||
seedScenario({
|
||
typeHidden: ['inventory', 'orders-list'],
|
||
branchHidden: [],
|
||
reopened: ['orders-list', 'not-in-type-hidden', 'inventory'],
|
||
});
|
||
const result = await resolveEffectiveBranchUi(BRANCH);
|
||
expect(result.hidden_menu_keys).toEqual([]);
|
||
expect(result.reopened_menu_keys).toEqual(['orders-list', 'inventory']);
|
||
});
|
||
|
||
it('同类型另一家分公司不受本公司重开影响', async () => {
|
||
seedScenario({ typeHidden: ['inventory'], branchHidden: [], reopened: ['inventory'] });
|
||
const own = await resolveEffectiveBranchUi(BRANCH);
|
||
const other = await resolveEffectiveBranchUi(OTHER_BRANCH);
|
||
expect(own.hidden_menu_keys).toEqual([]); // BRANCH 显式重开 inventory
|
||
expect(other.hidden_menu_keys).toEqual(['inventory']); // 同类型另一家没重开 ⇒ 仍隐藏
|
||
});
|
||
});
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// No-Op 读侧容错边界 §7.1 / §7.4
|
||
// ---------------------------------------------------------------------------
|
||
|
||
describe('No-Op 读侧容错边界(损坏形态 ⇒ applied:false,不 500)', () => {
|
||
it('类型行 revision 非整数 ⇒ 损坏', async () => {
|
||
setBranch(BRANCH);
|
||
seedTypes();
|
||
const row = readConfigRow(TYPES_ROW_KEY)!;
|
||
row.config_value = { ...(row.config_value as object), revision: '1' };
|
||
const result = await resolveEffectiveBranchUi(BRANCH);
|
||
expect(result.applied).toBe(false);
|
||
});
|
||
|
||
it('类型行 version 不是 1 ⇒ 损坏', async () => {
|
||
setBranch(BRANCH);
|
||
seedTypes();
|
||
const row = readConfigRow(TYPES_ROW_KEY)!;
|
||
row.config_value = { ...(row.config_value as object), version: 2 };
|
||
expect((await resolveEffectiveBranchUi(BRANCH)).applied).toBe(false);
|
||
});
|
||
|
||
it('类型 status 是字符串 "1" ⇒ 损坏(不当作启用)', async () => {
|
||
setBranch(BRANCH);
|
||
seedTypes({ types: [{ code: 'retail', name: '零售型', sort: 1, status: '1' }] });
|
||
expect((await resolveEffectiveBranchUi(BRANCH)).applied).toBe(false);
|
||
});
|
||
|
||
it('模板行 type_code 与 config_key 不一致 ⇒ 损坏(防串行)', async () => {
|
||
setBranch(BRANCH);
|
||
seedTypes();
|
||
seedTemplate('retail', { raw: { version: 1, revision: 1, type_code: 'wholesale', hidden_menu_keys: [], text_overrides: {} } });
|
||
expect((await resolveEffectiveBranchUi(BRANCH)).applied).toBe(false);
|
||
});
|
||
|
||
it('分公司行 branch_code 与所在行不一致 ⇒ 损坏', async () => {
|
||
setBranch(BRANCH);
|
||
seedTypes();
|
||
seedTemplate('retail', { hidden: ['inventory'] });
|
||
seedBranchOverride(BRANCH, {
|
||
raw: { version: 1, revision: 1, branch_code: OTHER_BRANCH, reopened_menu_keys: [], hidden_menu_keys: [], text_overrides: {} },
|
||
});
|
||
expect((await resolveEffectiveBranchUi(BRANCH)).applied).toBe(false);
|
||
});
|
||
|
||
it('原始值为 JSON 字符串/数组(非对象)⇒ 损坏', async () => {
|
||
setBranch(BRANCH);
|
||
seedTypes();
|
||
seedTemplate('retail', { raw: '[1,2,3]' });
|
||
expect((await resolveEffectiveBranchUi(BRANCH)).applied).toBe(false);
|
||
});
|
||
|
||
it('applied:true 但零隐藏/零文字 ⇒ 空数组 + 空对象(不是损坏)', async () => {
|
||
seedScenario({ typeHidden: [], branchHidden: [], reopened: [] });
|
||
const result = await resolveEffectiveBranchUi(BRANCH);
|
||
expect(result.applied).toBe(true);
|
||
expect(result.hidden_menu_keys).toEqual([]);
|
||
expect(result.text_overrides).toEqual({});
|
||
expect(result.type?.code).toBe('retail');
|
||
});
|
||
|
||
it('分公司 status 为非 1 值(含字符串 "0")⇒ 按停用处理 applied:false', async () => {
|
||
setBranch(BRANCH);
|
||
seedTypes();
|
||
seedTemplate('retail', { hidden: ['inventory'] });
|
||
store.branches.set(BRANCH, { branch_code: BRANCH, branch_name: BRANCH, status: '0' as unknown as number });
|
||
expect((await resolveEffectiveBranchUi(BRANCH)).applied).toBe(false);
|
||
});
|
||
});
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// 校验边界 §8.3
|
||
// ---------------------------------------------------------------------------
|
||
|
||
describe('校验边界(§8.3)', () => {
|
||
it('hidden_menu_keys 非数组 ⇒ 400;元素非字符串 ⇒ 400', async () => {
|
||
seedScenario({ typeHidden: [] });
|
||
await expect(
|
||
saveBranchUiTemplate('retail', { hiddenMenuKeys: 'inventory' })
|
||
).rejects.toMatchObject({ status: 400 });
|
||
await expect(
|
||
saveBranchUiTemplate('retail', { hiddenMenuKeys: ['inventory', 1] })
|
||
).rejects.toMatchObject({ status: 400 });
|
||
});
|
||
|
||
it('hidden_menu_keys 重复项去重后保存', async () => {
|
||
seedScenario({ typeHidden: [] });
|
||
await saveBranchUiTemplate('retail', { hiddenMenuKeys: ['inventory', 'inventory', 'orders-list'] });
|
||
const doc = readConfigRow(branchUiTemplateKey('retail'))!.config_value as { hidden_menu_keys: string[] };
|
||
expect(doc.hidden_menu_keys).toEqual(['inventory', 'orders-list']);
|
||
});
|
||
|
||
it('i18n key 超过 200 字 ⇒ 400 invalid_i18n_key', async () => {
|
||
seedScenario({ typeHidden: [] });
|
||
const longKey = `a.${'b'.repeat(200)}`;
|
||
await expect(
|
||
saveBranchUiTemplate('retail', { textOverrides: { [longKey]: 'x' } })
|
||
).rejects.toMatchObject({ status: 400, code: 'invalid_i18n_key' });
|
||
});
|
||
|
||
it('i18n key 以数字开头 / 含空格 ⇒ 400 invalid_i18n_key', async () => {
|
||
seedScenario({ typeHidden: [] });
|
||
for (const key of ['1orders.title', 'orders title', '']) {
|
||
await expect(
|
||
saveBranchUiTemplate('retail', { textOverrides: { [key]: 'x' } })
|
||
).rejects.toMatchObject({ status: 400, code: 'invalid_i18n_key' });
|
||
}
|
||
});
|
||
|
||
it('text_overrides 值非字符串 ⇒ 400;全空白值 = 删除覆盖(存库无该 key)', async () => {
|
||
seedScenario({ typeHidden: [] });
|
||
await expect(
|
||
saveBranchUiTemplate('retail', { textOverrides: { 'orders.title': 123 } })
|
||
).rejects.toMatchObject({ status: 400 });
|
||
await saveBranchUiTemplate('retail', {
|
||
textOverrides: { 'orders.title': ' ', 'orders.subtitle': '有值' },
|
||
});
|
||
const doc = readConfigRow(branchUiTemplateKey('retail'))!.config_value as {
|
||
text_overrides: Record<string, string>;
|
||
};
|
||
expect(doc.text_overrides).toEqual({ 'orders.subtitle': '有值' });
|
||
});
|
||
|
||
it('文案 400 字可保存;401 字 ⇒ 400 text_too_long', async () => {
|
||
seedScenario({ typeHidden: [] });
|
||
await saveBranchUiTemplate('retail', { textOverrides: { 'orders.title': 'x'.repeat(400) } });
|
||
await expect(
|
||
saveBranchUiTemplate('retail', { textOverrides: { 'orders.title': 'x'.repeat(401) } })
|
||
).rejects.toMatchObject({ status: 400, code: 'text_too_long' });
|
||
});
|
||
|
||
it('类型名称 41 字 ⇒ 400;名称首尾空格 trim 后保存、编码重复 ⇒ 400', async () => {
|
||
seedScenario({ typeHidden: [] });
|
||
await expect(
|
||
saveBranchUiTypes({
|
||
types: [{ code: 'retail', name: 'x'.repeat(41), sort: 1, status: 1 }],
|
||
assignments: {},
|
||
})
|
||
).rejects.toMatchObject({ status: 400 });
|
||
await saveBranchUiTypes({
|
||
types: [{ code: 'retail', name: ' 零售型 ', sort: 1, status: 1 }],
|
||
assignments: {},
|
||
});
|
||
const doc = readConfigRow(TYPES_ROW_KEY)!.config_value as { types: Array<{ name: string }> };
|
||
expect(doc.types[0].name).toBe('零售型');
|
||
await expect(
|
||
saveBranchUiTypes({
|
||
types: [
|
||
{ code: 'retail', name: 'A', sort: 1, status: 1 },
|
||
{ code: 'retail', name: 'B', sort: 2, status: 1 },
|
||
],
|
||
assignments: {},
|
||
})
|
||
).rejects.toMatchObject({ status: 400, code: 'duplicate_type_code' });
|
||
});
|
||
|
||
it('归属指向不存在的类型 ⇒ 400 type_not_found', async () => {
|
||
seedTypes();
|
||
await expect(
|
||
saveBranchUiTypes({
|
||
types: [{ code: 'retail', name: '零售型', sort: 1, status: 1 }],
|
||
assignments: { [BRANCH]: 'ghost' },
|
||
})
|
||
).rejects.toMatchObject({ status: 400, code: 'type_not_found' });
|
||
});
|
||
});
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// revision 409 补充 + 损坏行修复 §8.4
|
||
// ---------------------------------------------------------------------------
|
||
|
||
describe('revision 乐观锁补充(§8.4)', () => {
|
||
it('保存类型:expected_revision 不符 ⇒ 409 且带当前 revision', async () => {
|
||
seedTypes({ revision: 3 });
|
||
const error = await saveBranchUiTypes({
|
||
expectedRevision: 2,
|
||
types: [],
|
||
assignments: {},
|
||
}).catch((e) => e);
|
||
expect(error).toMatchObject({ status: 409, code: 'revision_conflict', revision: 3 });
|
||
});
|
||
|
||
it('删除类型:expected_revision 不符 ⇒ 409 且不删模板行', async () => {
|
||
seedTypes({ revision: 3 });
|
||
seedTemplate('retail', { hidden: ['inventory'] });
|
||
const error = await deleteBranchUiType('retail', { expectedRevision: 2 }).catch((e) => e);
|
||
expect(error).toMatchObject({ status: 409, code: 'revision_conflict', revision: 3 });
|
||
expect(readConfigRow(branchUiTemplateKey('retail'))).toBeDefined();
|
||
});
|
||
|
||
it('损坏行修复:类型行结构异常时,expected_revision 给任何值都不得误报 409', async () => {
|
||
setConfigRow(TYPES_ROW_KEY, null, { version: 1, revision: 'bad', types: [] });
|
||
const result = await saveBranchUiTypes({
|
||
expectedRevision: 99,
|
||
types: [{ code: 'retail', name: '零售型', sort: 1, status: 1 }],
|
||
assignments: {},
|
||
});
|
||
expect(result.revision).toBe(1); // 覆盖修复后重新从 1 开始
|
||
});
|
||
|
||
it('损坏行修复:类型模板行结构异常时允许覆盖修复,且照常校验入参', async () => {
|
||
seedScenario({ typeHidden: [] });
|
||
setConfigRow(branchUiTemplateKey('retail'), null, { version: 1, revision: 'bad' });
|
||
const ok = await saveBranchUiTemplate('retail', {
|
||
expectedRevision: 99,
|
||
hiddenMenuKeys: ['inventory'],
|
||
});
|
||
expect(ok.revision).toBe(1);
|
||
await expect(
|
||
saveBranchUiTemplate('retail', { expectedRevision: 1, hiddenMenuKeys: ['ghost-key'] })
|
||
).rejects.toMatchObject({ status: 400, code: 'invalid_menu_key' });
|
||
});
|
||
|
||
it('损坏行修复:分公司覆盖行结构异常时允许覆盖修复,保留入参字段', async () => {
|
||
seedScenario({ typeHidden: [] });
|
||
setConfigRow(BRANCH_UI_BRANCH_KEY, BRANCH, { version: 1, revision: 'bad' });
|
||
const result = await saveBranchUiBranchOverride(BRANCH, {
|
||
expectedRevision: 99,
|
||
textOverrides: { 'orders.title': '分公司微调' },
|
||
});
|
||
expect(result.revision).toBe(1);
|
||
const doc = readConfigRow(BRANCH_UI_BRANCH_KEY, BRANCH)!.config_value as {
|
||
text_overrides: Record<string, string>;
|
||
};
|
||
expect(doc.text_overrides).toEqual({ 'orders.title': '分公司微调' });
|
||
});
|
||
});
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// 分公司覆盖写边界 §8.2
|
||
// ---------------------------------------------------------------------------
|
||
|
||
describe('分公司覆盖写边界(§8.2)', () => {
|
||
it('只传 reopened_menu_keys 时保留已有额外隐藏与文字(部分更新不丢字段)', async () => {
|
||
seedScenario({
|
||
typeHidden: ['inventory', 'orders-list'],
|
||
branchHidden: ['finance-overview'],
|
||
reopened: [],
|
||
});
|
||
seedBranchOverride(BRANCH, {
|
||
revision: 2,
|
||
hidden: ['finance-overview'],
|
||
reopened: [],
|
||
text: { 'orders.title': '保留我' },
|
||
});
|
||
invalidateBranchUiConfigCache();
|
||
await reopenBranchUiMenus(BRANCH, { reopenedMenuKeys: ['inventory'] });
|
||
const doc = readConfigRow(BRANCH_UI_BRANCH_KEY, BRANCH)!.config_value as {
|
||
hidden_menu_keys: string[];
|
||
text_overrides: Record<string, string>;
|
||
reopened_menu_keys: string[];
|
||
revision: number;
|
||
};
|
||
expect(doc.hidden_menu_keys).toEqual(['finance-overview']);
|
||
expect(doc.text_overrides).toEqual({ 'orders.title': '保留我' });
|
||
expect(doc.reopened_menu_keys).toEqual(['inventory']);
|
||
expect(doc.revision).toBe(3);
|
||
});
|
||
|
||
it('重开入参重复 key 去重;非数组 ⇒ 400', async () => {
|
||
seedScenario({ typeHidden: ['inventory', 'orders-list'] });
|
||
const result = await reopenBranchUiMenus(BRANCH, {
|
||
reopenedMenuKeys: ['inventory', 'inventory'],
|
||
});
|
||
expect(result.reopened_menu_keys).toEqual(['inventory']);
|
||
await expect(
|
||
reopenBranchUiMenus(BRANCH, { reopenedMenuKeys: 'inventory' })
|
||
).rejects.toMatchObject({ status: 400 });
|
||
});
|
||
|
||
it('对不存在的分公司保存覆盖 ⇒ 400 branch_not_found', async () => {
|
||
seedTypes();
|
||
await expect(
|
||
saveBranchUiBranchOverride('SUP9999', { textOverrides: { 'orders.title': 'x' } })
|
||
).rejects.toMatchObject({ status: 400, code: 'branch_not_found' });
|
||
});
|
||
|
||
it('类型停用后分公司重开 ⇒ 400 branch_ui_not_applied;超管覆盖写重开同样被拒', async () => {
|
||
seedTypes({
|
||
types: [{ code: 'retail', name: '零售型', sort: 1, status: 0 }],
|
||
assignments: { [BRANCH]: 'retail' },
|
||
});
|
||
setBranch(BRANCH);
|
||
seedTemplate('retail', { hidden: ['inventory'] });
|
||
await expect(
|
||
reopenBranchUiMenus(BRANCH, { reopenedMenuKeys: ['inventory'] })
|
||
).rejects.toMatchObject({ status: 400, code: 'branch_ui_not_applied' });
|
||
await expect(
|
||
saveBranchUiBranchOverride(BRANCH, { reopenedMenuKeys: ['inventory'] })
|
||
).rejects.toMatchObject({ status: 400, code: 'branch_ui_not_applied' });
|
||
});
|
||
|
||
it('超管覆盖只传 text_overrides 时保留已有重开与额外隐藏', async () => {
|
||
seedScenario({ typeHidden: ['inventory'] });
|
||
seedBranchOverride(BRANCH, { revision: 2, reopened: ['inventory'], hidden: ['finance-overview'], text: {} });
|
||
invalidateBranchUiConfigCache();
|
||
await saveBranchUiBranchOverride(BRANCH, { textOverrides: { 'orders.title': '新文案' } });
|
||
const doc = readConfigRow(BRANCH_UI_BRANCH_KEY, BRANCH)!.config_value as {
|
||
reopened_menu_keys: string[];
|
||
hidden_menu_keys: string[];
|
||
text_overrides: Record<string, string>;
|
||
};
|
||
expect(doc.reopened_menu_keys).toEqual(['inventory']);
|
||
expect(doc.hidden_menu_keys).toEqual(['finance-overview']);
|
||
expect(doc.text_overrides).toEqual({ 'orders.title': '新文案' });
|
||
});
|
||
});
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// 删除类型边界 §8.2
|
||
// ---------------------------------------------------------------------------
|
||
|
||
describe('删除类型边界(§8.2)', () => {
|
||
it('删除类型只删自身模板行,其它类型模板与归属保留', async () => {
|
||
seedTypes({
|
||
types: [
|
||
{ code: 'retail', name: '零售型', sort: 1, status: 1 },
|
||
{ code: 'wholesale', name: '批发型', sort: 2, status: 1 },
|
||
],
|
||
assignments: { [BRANCH]: 'retail', [OTHER_BRANCH]: 'wholesale' },
|
||
});
|
||
setBranch(BRANCH);
|
||
setBranch(OTHER_BRANCH);
|
||
seedTemplate('retail', { hidden: ['inventory'] });
|
||
seedTemplate('wholesale', { hidden: ['finance-overview'] });
|
||
const result = await deleteBranchUiType('retail', { expectedRevision: 1 });
|
||
expect(result).toMatchObject({ revision: 2, removed_assignments: 1, template_deleted: true });
|
||
expect(readConfigRow(branchUiTemplateKey('retail'))).toBeUndefined();
|
||
expect(readConfigRow(branchUiTemplateKey('wholesale'))).toBeDefined();
|
||
const typesDoc = readConfigRow(TYPES_ROW_KEY)!.config_value as {
|
||
types: Array<{ code: string }>;
|
||
assignments: Record<string, string>;
|
||
};
|
||
expect(typesDoc.types.map((item) => item.code)).toEqual(['wholesale']);
|
||
expect(typesDoc.assignments).toEqual({ [OTHER_BRANCH]: 'wholesale' });
|
||
// 被删类型的分公司回原状;另一家仍套用 wholesale 模板
|
||
expect((await resolveEffectiveBranchUi(BRANCH)).applied).toBe(false);
|
||
expect((await resolveEffectiveBranchUi(OTHER_BRANCH)).hidden_menu_keys).toEqual(['finance-overview']);
|
||
});
|
||
});
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// R2(task-11)F12 / P3:超大 revision 与脏 config_group/description 纠正
|
||
// ---------------------------------------------------------------------------
|
||
|
||
describe('R2-F12:超大 revision(越界)与 P3 脏列纠正', () => {
|
||
it('存储行 revision 超出 int4 上限 ⇒ 按损坏修复(revision 重置 1,不 500/不 409)', async () => {
|
||
setBranch(BRANCH);
|
||
seedTypes({ revision: MAX_CONFIG_REVISION }); // 先把合法行铺好再改成越界值
|
||
const corruptedRow = readConfigRow(TYPES_ROW_KEY)!;
|
||
corruptedRow.config_value = { ...(corruptedRow.config_value as object), revision: MAX_CONFIG_REVISION + 1 };
|
||
corruptedRow.config_group = 'zz_hacked';
|
||
corruptedRow.description = 'zz dirty description';
|
||
|
||
const result = await saveBranchUiTypes({
|
||
expectedRevision: 0, // 损坏行修复路径应跳过 expected 校验
|
||
types: [{ code: 'retail', name: '零售型', sort: 1, status: 1 }],
|
||
assignments: {},
|
||
});
|
||
expect(result.revision).toBe(1);
|
||
const repaired = readConfigRow(TYPES_ROW_KEY)!;
|
||
const doc = repaired.config_value as { revision: number };
|
||
expect(doc.revision).toBe(1);
|
||
// P3:修复路径的 upsert 也补 config_group/description = EXCLUDED.*,脏列被纠正
|
||
expect(repaired.config_group).toBe('branch_ui');
|
||
expect(repaired.description).not.toContain('zz dirty');
|
||
});
|
||
|
||
it('存储行 revision 恰好等于上限 ⇒ 合法(applied:true,不当损坏)', async () => {
|
||
seedScenario({ typeHidden: ['inventory'] });
|
||
const row = readConfigRow(TYPES_ROW_KEY)!;
|
||
row.config_value = { ...(row.config_value as object), revision: MAX_CONFIG_REVISION };
|
||
invalidateBranchUiConfigCache();
|
||
const result = await resolveEffectiveBranchUi(BRANCH);
|
||
expect(result.applied).toBe(true);
|
||
expect(result.revisions?.types).toBe(MAX_CONFIG_REVISION);
|
||
});
|
||
|
||
it('请求 expected_revision 超出上限 ⇒ 400 invalid_input(types / templates / reopen 三处)', async () => {
|
||
seedScenario({ typeHidden: ['inventory'] });
|
||
const tooBig = MAX_CONFIG_REVISION + 1;
|
||
const tooBigExpected = { status: 400, code: 'invalid_input' };
|
||
await expect(
|
||
saveBranchUiTypes({ expectedRevision: tooBig, types: [], assignments: {} })
|
||
).rejects.toMatchObject(tooBigExpected);
|
||
await expect(
|
||
saveBranchUiTemplate('retail', { expectedRevision: tooBig, hiddenMenuKeys: [] })
|
||
).rejects.toMatchObject(tooBigExpected);
|
||
await expect(
|
||
reopenBranchUiMenus(BRANCH, { reopenedMenuKeys: [], expectedRevision: tooBig })
|
||
).rejects.toMatchObject(tooBigExpected);
|
||
});
|
||
|
||
it('P3:合法行的 CAS 写入也把脏 config_group/description 纠正为平台分组/描述', async () => {
|
||
seedScenario({ typeHidden: [] });
|
||
const row = readConfigRow(TYPES_ROW_KEY)!;
|
||
row.config_group = 'zz_hacked';
|
||
row.description = 'zz dirty description';
|
||
invalidateBranchUiConfigCache();
|
||
|
||
const result = await saveBranchUiTypes({
|
||
expectedRevision: 1,
|
||
types: [{ code: 'retail', name: '零售型', sort: 1, status: 1 }],
|
||
assignments: {},
|
||
});
|
||
expect(result.revision).toBe(2);
|
||
const updated = readConfigRow(TYPES_ROW_KEY)!;
|
||
expect(updated.config_group).toBe('branch_ui');
|
||
expect(updated.description).not.toContain('zz dirty');
|
||
});
|
||
});
|