真机:录单员列表有单、详情「暂无明细」。根因是子表谓词写成 EXISTS(... o.order_code = t0.order_code ...),而网关给 order_items 的别名是 t5 ⇒ PG 报 missing FROM-clause entry for table "t0" ⇒ 前端 fetchOrderItems 吞错返回 []。 · orderOwnerScope 新增别名无关的父单谓词: order_code IN (SELECT order_code FROM orders WHERE created_by::text = $val); · order_items / order_item_fulfillments / picking_items 三张子表统一走父单归属(不按自身字段过滤); orders 本身仍按 created_by; · 新增真库回归单测(事务造数 + ROLLBACK):自己单 头+明细+履约+分拣可见、他人单全 0、admin 不过滤; · 设计文补 7.1 真机回归与修正。 验证:根/server tsc 0 错;orderOperatorScope* 37 条 + 相关子集 75 条全过; 全量后端 557 文件通过,1 文件(mainSystemWriteback 2 条)为 HEAD 既有失败。 设计门禁 6 通过/3 红(check-migrations、check-ai-cost、check-env-coverage,均为既有基线)。
389 lines
18 KiB
TypeScript
389 lines
18 KiB
TypeScript
/**
|
||
* 录单员(operator)订单可见范围(2026-10-19 开发者需求)。
|
||
*
|
||
* 设计要求:`docs/design/20261019-录单员仅见自己录的订单.md`
|
||
*
|
||
* 覆盖三层收口:
|
||
* ① 列表 SQL(`appendOperatorOwnOrderFilter`)
|
||
* ② 详情/写入单点 assert(`assertOrderAccess` / `assertOperatorOwnOrder`)
|
||
* ③ `/api/data` 通用网关行级过滤(`applyTenantScope` + 可信表达式)
|
||
* 以及「每个入口都真的接上了」的接线钉住(源码断言,与仓库既有测试风格一致)。
|
||
*/
|
||
import { describe, expect, it } from 'vitest';
|
||
import { readFileSync } from 'node:fs';
|
||
import type { TenantContext } from '../src/services/tenantScope';
|
||
import { applyTenantScope } from '../src/services/tenantScope';
|
||
import {
|
||
ORDER_SCOPE_FORBIDDEN,
|
||
assertOperatorOwnOrder,
|
||
assertOrderAccess,
|
||
isOperatorScoped,
|
||
OPERATOR_ORDER_CHILD_SCOPE_TRUSTED_EXPR,
|
||
OPERATOR_ORDER_ITEM_OWNER_SCOPE_TRUSTED_EXPR,
|
||
OPERATOR_ORDER_OWNER_SCOPE_TRUSTED_EXPR,
|
||
} from '../src/services/orderOwnerScope';
|
||
import { compileTrustedExpr } from '../src/services/trustedExprFilters';
|
||
import { appendOperatorOwnOrderFilter } from '../src/services/orderManagementQueryService';
|
||
import { executeQuery, type QuerySpec } from '../src/services/queryExecutor';
|
||
|
||
const read = (rel: string) => readFileSync(new URL(`../src/${rel}`, import.meta.url), 'utf8');
|
||
|
||
function ctx(partial: Partial<TenantContext> & Pick<TenantContext, 'userId'>): TenantContext {
|
||
return {
|
||
userId: partial.userId,
|
||
roles: partial.roles || [],
|
||
permissions: partial.permissions || [],
|
||
branchCode: partial.branchCode === undefined ? 'BR002' : partial.branchCode,
|
||
supplierCode: null,
|
||
purchaserCode: null,
|
||
isSuperAdmin: partial.isSuperAdmin ?? false,
|
||
isBranchAdmin: partial.isBranchAdmin ?? false,
|
||
isInternalStaff: partial.isInternalStaff ?? false,
|
||
isSupplierAccount: partial.isSupplierAccount ?? false,
|
||
};
|
||
}
|
||
|
||
const operator = ctx({ userId: 'u-operator', roles: ['operator'] });
|
||
const admin = ctx({ userId: 'u-admin', roles: ['admin'] });
|
||
const superAdmin = ctx({ userId: 'u-super', roles: ['super_admin'], isSuperAdmin: true, branchCode: null });
|
||
const OWN = { order_code: 'ORD_1', branch_code: 'BR002', created_by: 'u-operator' };
|
||
const OTHERS = { order_code: 'ORD_2', branch_code: 'BR002', created_by: 'u-other' };
|
||
const NO_OWNER = { order_code: 'ORD_3', branch_code: 'BR002', created_by: null };
|
||
|
||
describe('isOperatorScoped:只有 operator(且不含 admin/super_admin)才收窄', () => {
|
||
it('operator 收窄', () => {
|
||
expect(isOperatorScoped(operator)).toBe(true);
|
||
expect(isOperatorScoped(ctx({ userId: 'u', roles: ['operator', 'finance'] }))).toBe(true);
|
||
});
|
||
|
||
it('admin / super_admin / operator+admin 一律不收窄', () => {
|
||
expect(isOperatorScoped(admin)).toBe(false);
|
||
expect(isOperatorScoped(superAdmin)).toBe(false);
|
||
expect(isOperatorScoped(ctx({ userId: 'u', roles: ['operator', 'admin'] }))).toBe(false);
|
||
});
|
||
|
||
it('其它角色不收窄(行为不变)', () => {
|
||
for (const role of ['finance', 'warehouse', 'picker', 'delivery', 'purchaser', 'supplier']) {
|
||
expect(isOperatorScoped(ctx({ userId: 'u', roles: [role] }))).toBe(false);
|
||
}
|
||
expect(isOperatorScoped(ctx({ userId: 'u', roles: [] }))).toBe(false);
|
||
});
|
||
});
|
||
|
||
describe('assertOperatorOwnOrder:operator 只看本人单', () => {
|
||
it('本人单放行', () => {
|
||
expect(() => assertOperatorOwnOrder(operator, OWN)).not.toThrow();
|
||
});
|
||
|
||
it('他人单 403 order_scope_forbidden', () => {
|
||
try {
|
||
assertOperatorOwnOrder(operator, OTHERS);
|
||
throw new Error('应当抛错');
|
||
} catch (error: any) {
|
||
expect(error.status).toBe(403);
|
||
expect(error.code).toBe(ORDER_SCOPE_FORBIDDEN);
|
||
expect(error.code).toBe('order_scope_forbidden');
|
||
}
|
||
});
|
||
|
||
it('created_by 为空的历史单 operator 看不到', () => {
|
||
expect(() => assertOperatorOwnOrder(operator, NO_OWNER)).toThrow(/录单员/);
|
||
});
|
||
|
||
it('admin / super_admin 完全不受影响', () => {
|
||
expect(() => assertOperatorOwnOrder(admin, OTHERS)).not.toThrow();
|
||
expect(() => assertOperatorOwnOrder(admin, NO_OWNER)).not.toThrow();
|
||
expect(() => assertOperatorOwnOrder(superAdmin, OTHERS)).not.toThrow();
|
||
});
|
||
});
|
||
|
||
describe('assertOrderAccess:分公司边界保留,operator 归属叠加', () => {
|
||
it('operator 本人单 + 同分公司放行', () => {
|
||
expect(() => assertOrderAccess(operator, OWN)).not.toThrow();
|
||
});
|
||
|
||
it('operator 他人单拒绝', () => {
|
||
expect(() => assertOrderAccess(operator, OTHERS)).toThrow(/录单员/);
|
||
});
|
||
|
||
it('分公司越权仍拒绝(既有口径不变)', () => {
|
||
expect(() =>
|
||
assertOrderAccess(operator, { ...OWN, branch_code: 'BR999' })
|
||
).toThrow(/分公司/);
|
||
});
|
||
|
||
it('超管跨分公司放行(既有口径不变)', () => {
|
||
expect(() => assertOrderAccess(superAdmin, { ...OTHERS, branch_code: 'BR999' })).not.toThrow();
|
||
});
|
||
|
||
it('未绑定分公司仍拒绝(既有口径不变)', () => {
|
||
expect(() => assertOrderAccess(ctx({ userId: 'u', roles: ['finance'], branchCode: null }), OWN)).toThrow(
|
||
/未绑定分公司/
|
||
);
|
||
});
|
||
});
|
||
|
||
describe('列表 SQL:operator 追加 created_by,admin/超管不追加', () => {
|
||
it('operator 追加 `o.created_by = $n` 且参数是当前用户', () => {
|
||
const where: string[] = [];
|
||
const params: unknown[] = [];
|
||
appendOperatorOwnOrderFilter(where, params, isOperatorScoped(operator), operator.userId);
|
||
expect(where).toEqual(['o.created_by = $1']);
|
||
expect(params).toEqual(['u-operator']);
|
||
});
|
||
|
||
it('admin / super_admin / 其它角色不追加(SQL 里没有 created_by)', () => {
|
||
for (const principal of [admin, superAdmin, ctx({ userId: 'u', roles: ['finance'] })]) {
|
||
const where: string[] = [];
|
||
const params: unknown[] = [];
|
||
appendOperatorOwnOrderFilter(where, params, isOperatorScoped(principal), principal.userId);
|
||
expect(where.join(' ')).not.toContain('created_by');
|
||
expect(params).toEqual([]);
|
||
}
|
||
});
|
||
|
||
it('已有 where 时不覆盖、占位序号接续', () => {
|
||
const where: string[] = ['o.branch_code = $1'];
|
||
const params: unknown[] = ['BR002'];
|
||
appendOperatorOwnOrderFilter(where, params, true, 'u-operator');
|
||
expect(where).toEqual(['o.branch_code = $1', 'o.created_by = $2']);
|
||
expect(params).toEqual(['BR002', 'u-operator']);
|
||
});
|
||
|
||
it('operator 但拿不到 userId 时拒绝而不是静默放开', () => {
|
||
expect(() => appendOperatorOwnOrderFilter([], [], true, null)).toThrow(/登录/);
|
||
});
|
||
});
|
||
|
||
describe('列表服务接线:过滤加在 baseWhere(stats/count/list 同一份)', () => {
|
||
const src = read('services/orderManagementQueryService.ts');
|
||
|
||
it('在 appendDateFilter 之前把 created_by 追加进 baseWhere', () => {
|
||
expect(src).toContain('appendOperatorOwnOrderFilter(baseWhere, params, isOperatorScoped(ctx), ctx.userId);');
|
||
const ownerIdx = src.indexOf('appendOperatorOwnOrderFilter(baseWhere');
|
||
const dateIdx = src.indexOf('appendDateFilter(baseWhere, params, range, dateField);');
|
||
expect(ownerIdx).toBeGreaterThan(0);
|
||
expect(dateIdx).toBeGreaterThan(ownerIdx);
|
||
});
|
||
|
||
it('三条 SQL 都吃同一个 baseWhere', () => {
|
||
expect(src).toContain('WHERE ${baseWhereSql}`'); // stats
|
||
expect(src).toContain('const where = [...baseWhere];');
|
||
expect(src).toContain('WHERE ${whereSql}');
|
||
});
|
||
});
|
||
|
||
describe('详情/写入单点:assertOrderAccess 复用同一实现(不再两份)', () => {
|
||
it('orderWorkflowService 的 loadOrderRow 带 created_by 并复用 orderOwnerScope', () => {
|
||
const src = read('services/orderWorkflowService.ts');
|
||
expect(src).toContain("import { assertOrderAccess } from './orderOwnerScope';");
|
||
expect(src).toContain('delivery_date, created_by FROM orders');
|
||
expect(src).not.toContain("throw Object.assign(new Error('无权操作其他分公司的订单'), { status: 403 });");
|
||
});
|
||
|
||
it('orderDeleteService 删单/恢复/彻底删除都走统一 assert,SELECT 带 created_by', () => {
|
||
const src = read('services/orderDeleteService.ts');
|
||
expect(src).toContain("import { assertOrderAccess, isOperatorScoped } from './orderOwnerScope';");
|
||
expect(src).not.toContain('function assertOrderAccess(');
|
||
// 移入垃圾桶 + 彻底删除 两处 SELECT;恢复那处是 deleted_by_name 变体
|
||
expect((src.match(/o\.deleted_at, o\.created_by/g) || []).length).toBe(2);
|
||
expect(src).toContain('o.deleted_by_name, o.created_by');
|
||
expect((src.match(/assertOrderAccess\(ctx, order\)/g) || []).length).toBe(3);
|
||
});
|
||
|
||
it('回收站列表对 operator 追加 created_by', () => {
|
||
const src = read('services/orderDeleteService.ts');
|
||
expect(src).toContain('if (isOperatorScoped(ctx)) {');
|
||
expect(src).toContain('branchSql += ` AND o.created_by = $${params.length}`;');
|
||
});
|
||
});
|
||
|
||
describe('/api/data 通用网关:orders / order_items 行级过滤', () => {
|
||
it('operator 查 orders 追加 created_by 可信表达式,参数为当前用户', () => {
|
||
const spec: QuerySpec = { table: 'orders', action: 'select', select: '*' };
|
||
const scoped = applyTenantScope(spec, operator);
|
||
const expr = (scoped.filters || []).filter((filter) => filter.op === 'expr');
|
||
expect(expr.length).toBe(1);
|
||
expect(String(expr[0].raw)).toContain('created_by');
|
||
expect(expr[0].value).toBe('u-operator');
|
||
// 分公司过滤仍在(同一 where 里两个条件都要有)
|
||
expect((scoped.filters || []).some((f) => f.column === 'branch_code')).toBe(true);
|
||
});
|
||
|
||
it('operator 查 order_items 走父单归属过滤(不带外层别名)', () => {
|
||
const spec: QuerySpec = { table: 'order_items', action: 'select', select: '*' };
|
||
const scoped = applyTenantScope(spec, operator);
|
||
const raws = (scoped.filters || []).filter((f) => f.op === 'expr').map((f) => String(f.raw));
|
||
expect(raws.some((raw) => raw.includes('FROM orders') && raw.includes('created_by'))).toBe(true);
|
||
});
|
||
|
||
it('operator 改 orders 同样被限定(不能改他人单)', () => {
|
||
const spec: QuerySpec = { table: 'orders', action: 'update', updateData: { remark: 'x' } };
|
||
const scoped = applyTenantScope(spec, operator);
|
||
expect((scoped.filters || []).some((f) => f.op === 'expr' && String(f.raw).includes('created_by'))).toBe(
|
||
true
|
||
);
|
||
});
|
||
|
||
it('admin / super_admin / 其它角色不加任何 created_by 过滤', () => {
|
||
for (const principal of [admin, ctx({ userId: 'u', roles: ['finance'] })]) {
|
||
const scoped = applyTenantScope({ table: 'orders', action: 'select', select: '*' }, principal);
|
||
expect((scoped.filters || []).some((f) => String(f.raw || '').includes('created_by'))).toBe(false);
|
||
}
|
||
});
|
||
|
||
it('可信表达式在白名单内且能编译成参数占位', () => {
|
||
const compiled = compileTrustedExpr(OPERATOR_ORDER_OWNER_SCOPE_TRUSTED_EXPR, 'u-operator', 3);
|
||
expect(compiled).not.toBeNull();
|
||
expect(compiled?.sql).toBe('t0.created_by::text = $3');
|
||
expect(compiled?.params).toEqual(['u-operator']);
|
||
|
||
expect(OPERATOR_ORDER_ITEM_OWNER_SCOPE_TRUSTED_EXPR).toBe(OPERATOR_ORDER_CHILD_SCOPE_TRUSTED_EXPR);
|
||
const compiledItems = compileTrustedExpr(OPERATOR_ORDER_CHILD_SCOPE_TRUSTED_EXPR, 'u-operator', 1);
|
||
expect(compiledItems).not.toBeNull();
|
||
expect(compiledItems?.params).toEqual(['u-operator']);
|
||
expect(compiledItems?.sql).toBe(
|
||
'order_code IN (SELECT order_code FROM orders WHERE created_by::text = $1)'
|
||
);
|
||
});
|
||
});
|
||
|
||
/**
|
||
* 2026-10-20 回归:`/api/data` 的 `order_items` 外层别名是 **t5**(见 queryExecutor.TABLE_ALIASES),
|
||
* 旧表达式写死 `EXISTS (... o.order_code = t0.order_code ...)` ⇒ 真实 PG 报
|
||
* `missing FROM-clause entry for table "t0"`,前端把错误吞成空数组 ⇒ 订单详情「暂无明细」。
|
||
*
|
||
* 这里不测"字符串长得像",而是**真的跑一遍 executeQuery 的 SQL 生成**(假 db 只收 SQL),
|
||
* 钉住「子表表达式不引用任何外层别名」这个不变量。
|
||
*/
|
||
describe('/api/data 子表范围:按所属订单归属,不引用外层别名(2026-10-20 回归)', () => {
|
||
function collectSql(spec: QuerySpec): Promise<string[]> {
|
||
const captured: string[] = [];
|
||
const fakeDb = {
|
||
query: async (sql: string) => {
|
||
captured.push(sql);
|
||
return { rows: [], rowCount: 0 };
|
||
},
|
||
};
|
||
return executeQuery(spec, fakeDb as never).then(() => captured);
|
||
}
|
||
|
||
it('order_items 表达式不含任何 `t0.` 引用', () => {
|
||
const scoped = applyTenantScope({ table: 'order_items', action: 'select', select: '*' }, operator);
|
||
const exprs = (scoped.filters || []).filter((filter) => filter.op === 'expr');
|
||
expect(exprs.length).toBe(1);
|
||
const raw = String(exprs[0].raw);
|
||
expect(raw).not.toMatch(/\bt0\./);
|
||
expect(raw).toContain('order_code IN (SELECT order_code FROM orders');
|
||
expect(raw).toContain('created_by');
|
||
expect(exprs[0].value).toBe('u-operator');
|
||
});
|
||
|
||
it('前端明细原样查询(order_code + is_returned or)生成的 SQL:别名 t5,且无 t0', async () => {
|
||
const scoped = applyTenantScope(
|
||
{
|
||
table: 'order_items',
|
||
action: 'select',
|
||
select: '*',
|
||
filters: [
|
||
{ op: 'eq', column: 'order_code', value: 'ORD_WEB_20261020_BR002_0001' },
|
||
{ op: 'or', raw: 'is_returned.is.null,is_returned.eq.false' },
|
||
],
|
||
},
|
||
operator
|
||
);
|
||
const [sql] = await collectSql(scoped);
|
||
expect(sql).toContain('FROM order_items AS t5');
|
||
// 旧 bug 的准确形态:外层别名 t5,却引用 t0
|
||
expect(sql).not.toMatch(/\bt0\./);
|
||
expect(sql).not.toContain('t0.order_code');
|
||
// 父单归属谓词在
|
||
expect(sql).toContain('order_code IN (SELECT order_code FROM orders WHERE created_by::text = $3)');
|
||
// 子表自身的 branch 过滤仍在
|
||
expect(sql).toContain('t5.branch_code');
|
||
});
|
||
|
||
it('子表清单:order_items / order_item_fulfillments / picking_items 都按父单归属', () => {
|
||
for (const table of ['order_items', 'order_item_fulfillments', 'picking_items']) {
|
||
const scoped = applyTenantScope({ table, action: 'select', select: '*' }, operator);
|
||
const raws = (scoped.filters || [])
|
||
.filter((filter) => filter.op === 'expr')
|
||
.map((filter) => String(filter.raw));
|
||
expect(raws, table).toContain(OPERATOR_ORDER_CHILD_SCOPE_TRUSTED_EXPR);
|
||
expect(raws.join(' ')).not.toMatch(/\bt0\./);
|
||
}
|
||
// orders 本身仍按 created_by(需求口径,不改)
|
||
const orderScope = applyTenantScope({ table: 'orders', action: 'select', select: '*' }, operator);
|
||
const orderRaw = String(
|
||
(orderScope.filters || []).find((filter) => filter.op === 'expr')?.raw || ''
|
||
);
|
||
expect(orderRaw).toBe(OPERATOR_ORDER_OWNER_SCOPE_TRUSTED_EXPR);
|
||
});
|
||
|
||
it('admin / 其它角色对子表不加任何过滤', () => {
|
||
// 注:super_admin 未选分公司时子表会走「请选择当前操作分公司」分支(既有行为),不在此列
|
||
for (const principal of [admin, ctx({ userId: 'u', roles: ['warehouse'] })]) {
|
||
for (const table of ['order_items', 'order_item_fulfillments', 'picking_items']) {
|
||
const scoped = applyTenantScope({ table, action: 'select', select: '*' }, principal);
|
||
expect(
|
||
(scoped.filters || []).some((filter) => filter.op === 'expr' && String(filter.raw).includes('orders'))
|
||
).toBe(false);
|
||
}
|
||
}
|
||
});
|
||
|
||
it('operator 改/删子表同样被父单限定(不能改他人单的明细)', () => {
|
||
for (const action of ['update', 'delete'] as const) {
|
||
const scoped = applyTenantScope(
|
||
{ table: 'order_items', action, updateData: action === 'update' ? { remark: 'x' } : undefined },
|
||
operator
|
||
);
|
||
const raws = (scoped.filters || []).map((filter) => String(filter.raw || ''));
|
||
expect(raws.join(' ')).toContain('order_code IN (SELECT order_code FROM orders');
|
||
}
|
||
});
|
||
});
|
||
|
||
describe('入口接线钉住(每处都真的调了 assert)', () => {
|
||
it('Web 订单路由:分享链接 / 核货事实 / 散客确认 / 批量动作 都补了 assert', () => {
|
||
const route = read('modules/workflow/routes/orderRoutes.ts');
|
||
expect(route).toContain('const data = await createOrReuseOrderShareLink({');
|
||
expect(route).toContain('const data = await getOrderShareLinkStatus({');
|
||
expect(route).toContain('const data = await revokeOrderShareLink({');
|
||
expect(route).toContain('await assertOrderCodeAccess(orderCode, ctx!);\n const items = await listOrderActualFacts');
|
||
expect(route).toContain('await assertOrderCodeAccess(orderCode, ctx!);\n const outcome = await refreshOrderActualFacts');
|
||
expect(route).toContain("await assertOrderCodeAccess(String(req.params.orderCode || ''), ctx!);\n const data = await confirmRetailOrderComplete");
|
||
// 批量动作逐单 assert
|
||
expect(route).toContain('for (const code of orderCodes) {\n await assertOrderCodeAccess(');
|
||
// 批量重新分配在 SQL 层收窄
|
||
expect(route).toContain('isOperatorScoped(ctx!) ? ` AND created_by = $3`');
|
||
});
|
||
|
||
it('小程序录单详情/改明细:operator 归属校验', () => {
|
||
const route = read('routes/mobile/mobileOrderRoutes.ts');
|
||
expect((route.match(/assertOperatorOwnOrder\(scope, order\)/g) || []).length).toBe(2);
|
||
expect(route).toContain('o.customer_code, o.branch_code, o.created_at, o.created_by,');
|
||
expect(route).toContain('customer_code, branch_code, created_by FROM orders');
|
||
});
|
||
|
||
it('小程序管理端:详情/改单/推进/散客确认 都经过统一收口', () => {
|
||
const route = read('routes/mobile/mobileAdminRoutes.ts');
|
||
expect((route.match(/assertOrderCodeAccess\(/g) || []).length).toBeGreaterThanOrEqual(4);
|
||
expect(route).toContain('await assertOrderCodeAccess(orderCode, ctx);\n const data = await confirmRetailOrderComplete');
|
||
});
|
||
|
||
it('MCP:取单助手先过 assert(list/get/prepare 三个工具同一入口)', () => {
|
||
const src = read('mcp/tools/orders.ts');
|
||
expect(src).toContain('await assertOrderCodeAccess(code, ctx);');
|
||
const assertIdx = src.indexOf('await assertOrderCodeAccess(code, ctx);');
|
||
const queryIdx = src.indexOf('SELECT o.order_code, o.customer_code, o.branch_code', assertIdx);
|
||
expect(queryIdx).toBeGreaterThan(assertIdx);
|
||
});
|
||
|
||
it('orderEntryScope 带上 userId/roles(供归属判定使用)', () => {
|
||
const src = read('services/orderEntryScopeService.ts');
|
||
expect(src).toContain('userId: ctx.userId,');
|
||
expect(src).toContain('roles: ctx.roles,');
|
||
});
|
||
});
|