开发者 2026-10-19:录单员只能看自己录的单,看不到其他人订单。 · 唯一口径 orderOwnerScope.ts:isOperatorScoped(非超管、非 admin、含 operator) + assertOperatorOwnOrder(403 order_scope_forbidden)+ assertOrderAccess(分公司边界 + operator 归属, 合并原先 orderWorkflowService / orderDeleteService 两份重复实现); · 三层收口:① 订单列表 SQL(stats/count/list 共用同一 where)② 详情/写入单点 assertOrderAccess(覆盖 Web 25 处 + 小程序 + MCP + 状态推进)③ /api/data 通用网关 (Web 详情/明细/导出走 supabase:orders/order_items 的 select/update/delete 注入可信表达式); · 补上原先没有 assert 的入口:散客确认、分享链接、主系统核货事实、批量动作、批量重新分配(SQL 层收窄)、 删单/恢复/彻底删除、回收站列表、小程序录单/管理端、MCP 订单详情与改单; · 历史 created_by 为空的单:operator 看不到;不做参与过就放行(参与制另立需求); · 未动状态链/分配/财务口径/表结构;未加索引与迁移。 验证:根与 server tsc 0 错;orderOperatorScope 31 条 + 相关 6 文件 67 条全过; 全量后端 556 文件通过、2 条失败为 mainSystemWriteback 既有失败(HEAD 同样失败); 本地真库 CTE + PREPARE/EXPLAIN 验证三视角可见数(operator 1/4、admin 4/4、finance 4/4)。
288 lines
14 KiB
TypeScript
288 lines
14 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_OWNER_SCOPE_TRUSTED_EXPR,
|
||
OPERATOR_ORDER_ITEM_OWNER_SCOPE_TRUSTED_EXPR,
|
||
} from '../src/services/orderOwnerScope';
|
||
import { compileTrustedExpr } from '../src/services/trustedExprFilters';
|
||
import { appendOperatorOwnOrderFilter } from '../src/services/orderManagementQueryService';
|
||
import 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 走父单 EXISTS 过滤', () => {
|
||
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 o') && 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']);
|
||
|
||
const compiledItems = compileTrustedExpr(OPERATOR_ORDER_ITEM_OWNER_SCOPE_TRUSTED_EXPR, 'u-operator', 1);
|
||
expect(compiledItems).not.toBeNull();
|
||
expect(compiledItems?.params).toEqual(['u-operator']);
|
||
});
|
||
});
|
||
|
||
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,');
|
||
});
|
||
});
|