开发者 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)。
1425 lines
49 KiB
TypeScript
1425 lines
49 KiB
TypeScript
import { pool, getRawPoolQuery } from '../db';
|
||
import type { QuerySpec } from './queryExecutor';
|
||
import {
|
||
buildProductCatalogCategoryBranchExpr,
|
||
buildProductCatalogMixedBranchExpr,
|
||
buildProductCatalogProductBranchExpr,
|
||
buildLegacyCategoryBranchExpr,
|
||
} from './branchCategoryScope';
|
||
import { assertBranchAllowsOrders, assertBranchAllowsProductCatalog } from './platformBranch';
|
||
import { findAcrossActiveTenants, runInBranchSchema } from './tenantSchemaFallback';
|
||
import { PURCHASE_ORDER_OWNER_SCOPE_TRUSTED_EXPR } from './purchaseOwnerScope';
|
||
import {
|
||
OPERATOR_ORDER_ITEM_OWNER_SCOPE_TRUSTED_EXPR,
|
||
OPERATOR_ORDER_OWNER_SCOPE_TRUSTED_EXPR,
|
||
isOperatorScoped,
|
||
} from './orderOwnerScope';
|
||
|
||
const rawQuery = getRawPoolQuery();
|
||
export interface TenantContext {
|
||
userId: string;
|
||
roles: string[];
|
||
permissions: string[];
|
||
branchCode: string | null;
|
||
supplierCode: string | null;
|
||
purchaserCode: string | null;
|
||
isSuperAdmin: boolean;
|
||
isBranchAdmin: boolean;
|
||
isInternalStaff: boolean;
|
||
isSupplierAccount: boolean;
|
||
}
|
||
|
||
const SUPPLIER_OWNED_TABLES = new Set(['supplier_preparations']);
|
||
|
||
function isInternalStaffRole(roles: string[]) {
|
||
return roles.some((role) => ['super_admin', 'admin', 'operator'].includes(role));
|
||
}
|
||
|
||
const BRANCH_SCOPED_TABLES = new Set([
|
||
// profiles 留 public 平台表:不可进 tenant search_path/RLS,否则超管(branch 空)读不到自己
|
||
'customers',
|
||
'suppliers',
|
||
'orders',
|
||
'order_items',
|
||
'order_item_returns',
|
||
'picking_tasks',
|
||
'picking_items',
|
||
'customer_skus',
|
||
'customer_quote_versions',
|
||
'customer_quote_sheets',
|
||
'customer_quote_sheet_items',
|
||
'customer_quote_sheet_customers',
|
||
'purchase_orders',
|
||
'delivery_persons',
|
||
'delivery_schedules',
|
||
'after_sales',
|
||
'after_sale_returns',
|
||
'exception_tickets',
|
||
'customer_statements',
|
||
'supplier_statements',
|
||
'invoices',
|
||
'delivery_tasks',
|
||
'customer_delivery_assignments',
|
||
'inventory',
|
||
'supplier_preparations',
|
||
'inspections',
|
||
'inspection_returns',
|
||
'inspection_loss_confirmations',
|
||
'processing_tasks',
|
||
'picking_containers',
|
||
'picking_scan_logs',
|
||
'statement_lines',
|
||
'statement_disputes',
|
||
'supplier_rating_snapshots',
|
||
'categories',
|
||
'skus',
|
||
'smart_classification_rules',
|
||
'cost_details',
|
||
'cost_adjustments',
|
||
'market_prices',
|
||
'market_price_indices',
|
||
'market_compare_exclusions',
|
||
'fixed_costs',
|
||
'seasonal_recommendations',
|
||
'order_allocation_batches',
|
||
'picking_assign_rules',
|
||
'statement_payments',
|
||
'product_substitutions',
|
||
'delivery_signatures',
|
||
'warehouses',
|
||
'inspection_review_logs',
|
||
'user_preferences',
|
||
]);
|
||
|
||
/**
|
||
* 落在 tenant_*、但无 branch_code 列(或不按该列过滤)的表。
|
||
* /api/data 须切 search_path;过滤由 user_id / 关联表完成。
|
||
*/
|
||
const TENANT_PATH_TABLES = new Set([
|
||
'notifications',
|
||
'operation_logs',
|
||
'purchaser_users',
|
||
'supplier_users',
|
||
'delivery_person_users',
|
||
'allocation_tasks',
|
||
'bid_prices',
|
||
'inventory_logs',
|
||
'sign_records',
|
||
'order_item_fulfillments',
|
||
'processing_logs',
|
||
'warehouse_locations',
|
||
'delivery_person_locations',
|
||
'delivery_location_history',
|
||
]);
|
||
|
||
/** 无 branch_code 列,通过 suppliers 关联分公司 */
|
||
const SUPPLIER_LINKED_TABLES = new Set(['supplier_categories']);
|
||
|
||
/** 无 branch_code 列,通过 skus + suppliers 关联分公司 */
|
||
const SKU_SUPPLIER_LINKED_TABLES = new Set(['sku_suppliers']);
|
||
|
||
/** 无 branch_code 列,通过 customers 关联分公司 */
|
||
const CUSTOMER_LINKED_TABLES = new Set([
|
||
'customer_sku_aliases',
|
||
'customer_processing_aliases',
|
||
'customer_sku_remarks',
|
||
'customer_recipients',
|
||
'customer_alias_stats',
|
||
'alias_recognition_logs',
|
||
'voice_recognition_logs',
|
||
]);
|
||
|
||
/** 历史「平台共享目录表白名单」;现为空(SKU 等已按分公司隔离)。保留空集以免误用旧语义。 */
|
||
const SHARED_CATALOG_TABLES = new Set<string>();
|
||
|
||
/** 超级管理员平台管理:不受「操作分公司」过滤(用户/分公司/系统配置等) */
|
||
const SUPER_ADMIN_PLATFORM_TABLES = new Set([
|
||
'profiles',
|
||
'branches',
|
||
'system_configs',
|
||
'user_roles',
|
||
'permissions',
|
||
'role_permissions',
|
||
]);
|
||
|
||
const PLATFORM_ONLY_TABLES = new Set(['branches', 'permissions', 'role_permissions']);
|
||
|
||
const TENANT_CACHE_TTL_MS = Math.max(10_000, Number(process.env.TENANT_CACHE_TTL_MS || 60_000));
|
||
const tenantContextCache = new Map<string, { ctx: TenantContext; expiresAt: number }>();
|
||
|
||
export function invalidateTenantContextCache(userId?: string) {
|
||
if (userId) {
|
||
tenantContextCache.delete(userId);
|
||
return;
|
||
}
|
||
tenantContextCache.clear();
|
||
}
|
||
|
||
export async function loadTenantContext(userId?: string): Promise<TenantContext | null> {
|
||
if (!userId) return null;
|
||
|
||
const cached = tenantContextCache.get(userId);
|
||
if (cached && cached.expiresAt > Date.now()) {
|
||
return cached.ctx;
|
||
}
|
||
|
||
const ctx = await loadTenantContextUncached(userId);
|
||
if (ctx) {
|
||
tenantContextCache.set(userId, { ctx, expiresAt: Date.now() + TENANT_CACHE_TTL_MS });
|
||
}
|
||
return ctx;
|
||
}
|
||
|
||
async function loadTenantContextUncached(userId: string): Promise<TenantContext | null> {
|
||
// 平台表必须走 public + raw pool,避免 ALS search_path/RLS 干扰角色解析
|
||
const [rolesResult, profileResult, permissionsResult] = await Promise.all([
|
||
rawQuery(`SELECT role::text AS role FROM public.user_roles WHERE user_id = $1`, [userId]),
|
||
rawQuery(`SELECT branch_code FROM public.profiles WHERE id = $1`, [userId]),
|
||
rawQuery(
|
||
`SELECT DISTINCT p.permission_code
|
||
FROM public.user_roles ur
|
||
JOIN public.role_permissions rp ON rp.role::text = ur.role::text
|
||
JOIN public.permissions p ON p.id = rp.permission_id
|
||
WHERE ur.user_id = $1`,
|
||
[userId]
|
||
),
|
||
]);
|
||
|
||
const roles = rolesResult.rows.map((row) => row.role as string);
|
||
const permissions = permissionsResult.rows.map((row) => row.permission_code as string);
|
||
const isSuperAdmin = roles.includes('super_admin');
|
||
let branchCode = (profileResult.rows[0]?.branch_code as string | null) ?? null;
|
||
const isInternalStaff = isInternalStaffRole(roles);
|
||
const hasSupplierRole = roles.includes('supplier');
|
||
|
||
let supplierCode: string | null = null;
|
||
let purchaserCode: string | null = null;
|
||
if (!isInternalStaff) {
|
||
// 业务绑定表在 tenant_*:原来只能按 active schema 逐个扫、取「首个任意命中」。
|
||
// 规模改造 §4:`profiles.branch_code` 已知时先只查那一个租户(实测 104 租户 63.5 ms → 0.9 ms)。
|
||
// 但**只有该租户命中这个账号「声明身份」对应的绑定时才算数**(邮箱后缀 = 建号角色);
|
||
// 否则退回原来的「按 branch_code 顺序取首个任意命中」,结果与改造前完全一致
|
||
// (覆盖:老账号无 branch_code、调岗后旧绑定残留等)。
|
||
const { listActiveTenantBranches, resolvePreferredTenantBranch } = await import('./tenantSchemaFallback');
|
||
const { runWithTenantDbContext } = await import('./tenantDbContext');
|
||
const { declaredBindingKinds } = await import('../utils/accountBindingKinds');
|
||
const tenants = await listActiveTenantBranches();
|
||
const emailResult = await rawQuery(`SELECT email FROM auth.users WHERE id = $1`, [userId]);
|
||
const declared = declaredBindingKinds(String(emailResult.rows?.[0]?.email || ''));
|
||
// 只有当 `profiles.branch_code` 确实是「registry=active 的租户」时才拿它当优先租户。
|
||
// 否则绝不能查:`runWithTenantDbContext` 在 schema 解析为 null 时会以连接默认 search_path(public)执行,
|
||
// 而 supplier_users/purchaser_users/delivery_person_users 只在 tenant_*(迁移 20260775 已把 public 副本挪走),
|
||
// 结果是把「没有租户 = 找不到绑定」变成 42P01 抛错(每个请求 500,且 loadTenantContext 只缓存成功结果,不会自愈)。
|
||
// 触发面:registry 回滚成 pending、分公司建了但克隆失败/没克隆、脚本直接插 branches。
|
||
const preferredCandidate = resolvePreferredTenantBranch(branchCode);
|
||
const preferred =
|
||
preferredCandidate && tenants.some((t) => String(t.branch_code || '').trim() === preferredCandidate)
|
||
? preferredCandidate
|
||
: null;
|
||
|
||
const hitCache = new Map<
|
||
string,
|
||
{ supplierCode: string | null; purchaserCode: string | null; hasDelivery: boolean }
|
||
>();
|
||
const queryBindings = async (branchCodeToTry: string) => {
|
||
const cached = hitCache.get(branchCodeToTry);
|
||
if (cached) return cached;
|
||
const hit = await runWithTenantDbContext(branchCodeToTry, async () => {
|
||
const [supplierResult, purchaserResult, deliveryResult] = await Promise.all([
|
||
pool.query(
|
||
`SELECT supplier_code FROM supplier_users WHERE user_id = $1 AND status = 1 LIMIT 1`,
|
||
[userId]
|
||
),
|
||
pool.query(
|
||
`SELECT purchaser_code FROM purchaser_users WHERE user_id = $1 AND status = 1 LIMIT 1`,
|
||
[userId]
|
||
),
|
||
pool.query(
|
||
`SELECT person_code FROM delivery_person_users WHERE user_id = $1 LIMIT 1`,
|
||
[userId]
|
||
)
|
||
]);
|
||
return {
|
||
supplierCode: (supplierResult.rows[0]?.supplier_code as string) ?? null,
|
||
purchaserCode: (purchaserResult.rows[0]?.purchaser_code as string) ?? null,
|
||
hasDelivery: Boolean(deliveryResult.rowCount),
|
||
};
|
||
});
|
||
hitCache.set(branchCodeToTry, hit);
|
||
return hit;
|
||
};
|
||
const satisfiesDeclared = (hit: {
|
||
supplierCode: string | null;
|
||
purchaserCode: string | null;
|
||
hasDelivery: boolean;
|
||
}) =>
|
||
declared.length > 0
|
||
? declared.every((kind) =>
|
||
kind === 'purchaser' ? !!hit.purchaserCode : kind === 'supplier' ? !!hit.supplierCode : hit.hasDelivery
|
||
)
|
||
: Boolean(hit.supplierCode || hit.purchaserCode || hit.hasDelivery);
|
||
|
||
const applyHit = (
|
||
hit: { supplierCode: string | null; purchaserCode: string | null; hasDelivery: boolean },
|
||
branchCodeOfTenant: string
|
||
) => {
|
||
supplierCode = hit.supplierCode;
|
||
purchaserCode = hit.purchaserCode;
|
||
// 外部账号常无 profiles.branch_code:用绑定所在租户作为操作分公司
|
||
if (!branchCode) {
|
||
branchCode = branchCodeOfTenant;
|
||
}
|
||
};
|
||
|
||
let resolved = false;
|
||
if (preferred) {
|
||
const hit = await queryBindings(preferred);
|
||
if (satisfiesDeclared(hit)) {
|
||
applyHit(hit, preferred);
|
||
resolved = true;
|
||
} else if (hit.supplierCode || hit.purchaserCode || hit.hasDelivery) {
|
||
console.warn(
|
||
`[tenant-scope] 账号在 profiles.branch_code=${preferred} 内未命中声明绑定(${declared.join('/') || '任意'}),回退全租户扫描`
|
||
);
|
||
}
|
||
}
|
||
if (!resolved) {
|
||
// 原顺序(branch_code 升序)、原语义(首个任意命中):结果与改造前一致
|
||
for (const t of tenants) {
|
||
const hit = await queryBindings(t.branch_code);
|
||
if (hit.supplierCode || hit.purchaserCode || hit.hasDelivery) {
|
||
applyHit(hit, t.branch_code);
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
const isSupplierAccount = !isInternalStaff && (!!supplierCode || hasSupplierRole);
|
||
|
||
return {
|
||
userId,
|
||
roles,
|
||
permissions,
|
||
branchCode,
|
||
supplierCode,
|
||
purchaserCode,
|
||
isSuperAdmin,
|
||
isBranchAdmin: roles.includes('admin') && !isSuperAdmin,
|
||
isInternalStaff,
|
||
isSupplierAccount,
|
||
};
|
||
}
|
||
|
||
function applySupplierOwnedScope(spec: QuerySpec, ctx: TenantContext): QuerySpec {
|
||
if (!ctx.isSupplierAccount) return spec;
|
||
|
||
if (!ctx.supplierCode) {
|
||
throw new Error('账号未绑定供应商,请联系管理员');
|
||
}
|
||
|
||
spec.filters = spec.filters || [];
|
||
if (!hasFilter(spec, 'supplier_code', ctx.supplierCode)) {
|
||
spec.filters.push({ op: 'eq', column: 'supplier_code', value: ctx.supplierCode });
|
||
}
|
||
|
||
if (spec.action === 'insert') {
|
||
throw new Error('无权创建备货记录');
|
||
}
|
||
|
||
if (spec.action === 'update' && spec.updateData && typeof spec.updateData === 'object') {
|
||
delete (spec.updateData as Record<string, unknown>).supplier_code;
|
||
}
|
||
|
||
return spec;
|
||
}
|
||
|
||
function applySupplierPurchaseInsertScope(spec: QuerySpec, ctx: TenantContext): QuerySpec {
|
||
if (!ctx.isSupplierAccount || !ctx.supplierCode) return spec;
|
||
|
||
const rows = Array.isArray(spec.insertData) ? spec.insertData : [spec.insertData];
|
||
spec.insertData = rows.map((row) => {
|
||
if (!row || typeof row !== 'object') return row;
|
||
const record = row as Record<string, unknown>;
|
||
if (record.supplier_code && record.supplier_code !== ctx.supplierCode) {
|
||
throw new Error('无权为其他供应商创建采购单');
|
||
}
|
||
return { ...record, supplier_code: ctx.supplierCode };
|
||
});
|
||
|
||
return spec;
|
||
}
|
||
|
||
function applySupplierPurchaseScope(spec: QuerySpec, ctx: TenantContext): QuerySpec {
|
||
if (!ctx.isSupplierAccount || !ctx.supplierCode) return spec;
|
||
|
||
if (spec.action === 'select' || spec.action === 'update' || spec.action === 'delete') {
|
||
spec.filters = spec.filters || [];
|
||
if (!hasFilter(spec, 'supplier_code', ctx.supplierCode)) {
|
||
spec.filters.push({ op: 'eq', column: 'supplier_code', value: ctx.supplierCode });
|
||
}
|
||
}
|
||
|
||
if (spec.action === 'insert') {
|
||
spec = applySupplierPurchaseInsertScope(spec, ctx);
|
||
}
|
||
|
||
if (spec.action === 'update' && spec.updateData && typeof spec.updateData === 'object') {
|
||
delete (spec.updateData as Record<string, unknown>).supplier_code;
|
||
}
|
||
|
||
return spec;
|
||
}
|
||
|
||
function hasPurchaserPurchaseScopeExpr(spec: QuerySpec) {
|
||
return (spec.filters || []).some(
|
||
(filter) =>
|
||
filter.op === 'expr' &&
|
||
(filter.raw?.includes('t0.branch_code') || filter.raw?.includes('purchase_orders po'))
|
||
);
|
||
}
|
||
|
||
/** 采购员采购单:分公司 + 本人/待采自由池(见 purchaseOwnerScope) */
|
||
/**
|
||
* 录单员(operator)行级范围(2026-10-19):`/api/data` 读/改/删 `orders` / `order_items`
|
||
* 只落到自己录的单。
|
||
*
|
||
* 为什么必须在这里:Web 订单详情、明细、导出构建器走 `supabase.from('orders')` ⇒ 通用网关,
|
||
* **不经过**订单 workflow 路由,只锁 workflow 的那一层挡不住。
|
||
*
|
||
* `insert` 不加过滤(新建订单只有 `POST /orders/submit` 一条路径,`created_by` 由服务端写)——
|
||
* 已在设计文档「已知未覆盖」登记。
|
||
*/
|
||
function applyOperatorOwnOrdersScope(spec: QuerySpec, ctx: TenantContext): QuerySpec {
|
||
if (spec.action === 'insert') return spec;
|
||
const template =
|
||
spec.table === 'order_items'
|
||
? OPERATOR_ORDER_ITEM_OWNER_SCOPE_TRUSTED_EXPR
|
||
: OPERATOR_ORDER_OWNER_SCOPE_TRUSTED_EXPR;
|
||
spec.filters = spec.filters || [];
|
||
const alreadyScoped = spec.filters.some(
|
||
(filter) => filter.op === 'expr' && String(filter.raw || '').includes('created_by')
|
||
);
|
||
if (!alreadyScoped) {
|
||
spec.filters.push({ op: 'expr', raw: template, value: ctx.userId });
|
||
}
|
||
return spec;
|
||
}
|
||
|
||
function applyPurchaserOwnedPurchaseScope(spec: QuerySpec, ctx: TenantContext): QuerySpec {
|
||
if (!ctx.purchaserCode) return spec;
|
||
const branchCode = ctx.branchCode?.trim();
|
||
if (!branchCode) {
|
||
throw new Error('采购员未绑定分公司,请联系管理员');
|
||
}
|
||
|
||
spec.filters = spec.filters || [];
|
||
if (spec.action === 'select' || spec.action === 'update') {
|
||
if (!hasPurchaserPurchaseScopeExpr(spec)) {
|
||
spec.filters.push({
|
||
op: 'expr',
|
||
raw: `(t0.branch_code = $val OR (t0.branch_code IS NULL AND EXISTS (SELECT 1 FROM orders o WHERE o.order_code = t0.order_code AND o.branch_code = $val)))`,
|
||
value: branchCode,
|
||
});
|
||
}
|
||
const hasOwnerExpr = (spec.filters || []).some(
|
||
(filter) =>
|
||
filter.op === 'expr' && String(filter.raw || '').includes('t0.purchaser_code')
|
||
);
|
||
if (!hasOwnerExpr) {
|
||
spec.filters.push({
|
||
op: 'expr',
|
||
raw: PURCHASE_ORDER_OWNER_SCOPE_TRUSTED_EXPR,
|
||
value: ctx.purchaserCode,
|
||
});
|
||
}
|
||
}
|
||
|
||
if (spec.action === 'delete' || spec.action === 'insert') {
|
||
throw new Error('无权操作采购单');
|
||
}
|
||
|
||
if (spec.action === 'update' && spec.updateData && typeof spec.updateData === 'object') {
|
||
delete (spec.updateData as Record<string, unknown>).purchaser_code;
|
||
delete (spec.updateData as Record<string, unknown>).branch_code;
|
||
}
|
||
|
||
return spec;
|
||
}
|
||
|
||
function hasFilter(spec: QuerySpec, column: string, value: unknown) {
|
||
return (spec.filters || []).some((filter) => filter.column === column && filter.op === 'eq' && filter.value === value);
|
||
}
|
||
|
||
/** 读取当前登录用户自己的 profile / roles,不受操作分公司过滤 */
|
||
function isSelfAccountRead(spec: QuerySpec, ctx: TenantContext) {
|
||
if (spec.action !== 'select') return false;
|
||
if (spec.table === 'profiles' && hasFilter(spec, 'id', ctx.userId)) return true;
|
||
if (spec.table === 'user_roles' && hasFilter(spec, 'user_id', ctx.userId)) return true;
|
||
return false;
|
||
}
|
||
|
||
/**
|
||
* profiles 列表/写:按分公司隔离(表仍在 public,不走 tenant schema)。
|
||
* branchCode 为空且超管 → 全量;非超管必须有 branch。
|
||
*/
|
||
function applyProfilesBranchScope(
|
||
spec: QuerySpec,
|
||
ctx: TenantContext,
|
||
branchCode: string | null
|
||
): QuerySpec {
|
||
if (isSelfAccountRead(spec, ctx)) return spec;
|
||
|
||
if (!branchCode) {
|
||
if (!ctx.isSuperAdmin) {
|
||
throw new Error('未分配分公司,无法访问用户数据');
|
||
}
|
||
return spec;
|
||
}
|
||
|
||
if (spec.action === 'select' || spec.action === 'update' || spec.action === 'delete') {
|
||
spec.filters = spec.filters || [];
|
||
if (!hasFilter(spec, 'branch_code', branchCode)) {
|
||
spec.filters.push({ op: 'eq', column: 'branch_code', value: branchCode });
|
||
}
|
||
}
|
||
|
||
if (spec.action === 'insert' && spec.insertData) {
|
||
const rows = Array.isArray(spec.insertData) ? spec.insertData : [spec.insertData];
|
||
spec.insertData = rows.map((row) => {
|
||
if (!row || typeof row !== 'object') return row;
|
||
return { ...(row as Record<string, unknown>), branch_code: branchCode };
|
||
});
|
||
}
|
||
|
||
if (spec.action === 'update' && spec.updateData && typeof spec.updateData === 'object') {
|
||
if (!ctx.isSuperAdmin) {
|
||
delete (spec.updateData as Record<string, unknown>).branch_code;
|
||
}
|
||
}
|
||
|
||
return spec;
|
||
}
|
||
|
||
/** user_roles 列表:限定到指定分公司下的用户(自读除外) */
|
||
function applyUserRolesBranchScope(
|
||
spec: QuerySpec,
|
||
ctx: TenantContext,
|
||
branchCode: string | null
|
||
): QuerySpec {
|
||
if (isSelfAccountRead(spec, ctx)) return spec;
|
||
if (spec.action !== 'select') return spec;
|
||
if (hasFilter(spec, 'user_id', ctx.userId)) return spec;
|
||
|
||
if (!branchCode) {
|
||
if (!ctx.isSuperAdmin) {
|
||
throw new Error('未分配分公司,无法访问业务数据');
|
||
}
|
||
return spec;
|
||
}
|
||
|
||
spec.filters = spec.filters || [];
|
||
const hasBranchExpr = spec.filters.some(
|
||
(filter) => filter.op === 'expr' && filter.raw?.includes('profiles')
|
||
);
|
||
if (!hasBranchExpr) {
|
||
spec.filters.push({
|
||
op: 'expr',
|
||
raw: 't0.user_id IN (SELECT id FROM public.profiles WHERE branch_code = $val)',
|
||
value: branchCode,
|
||
});
|
||
}
|
||
return spec;
|
||
}
|
||
|
||
function hasIsNullFilter(spec: QuerySpec, column: string) {
|
||
return (spec.filters || []).some(
|
||
(filter) => filter.column === column && filter.op === 'is' && filter.value === null
|
||
);
|
||
}
|
||
|
||
function isNavMenuLayoutSpec(spec: QuerySpec) {
|
||
return hasFilter(spec, 'config_key', 'nav_menu_layout');
|
||
}
|
||
|
||
function isPrintTemplatesSpec(spec: QuerySpec) {
|
||
return hasFilter(spec, 'config_key', 'print_templates');
|
||
}
|
||
|
||
function isSkuAiImageSpec(spec: QuerySpec) {
|
||
return hasFilter(spec, 'config_key', 'sku_ai_image');
|
||
}
|
||
|
||
function insertIncludesSkuAiImage(spec: QuerySpec) {
|
||
if (spec.action !== 'insert' || spec.insertData == null) return false;
|
||
const rows = Array.isArray(spec.insertData) ? spec.insertData : [spec.insertData];
|
||
return rows.some((row) => {
|
||
if (!row || typeof row !== 'object') return false;
|
||
return (row as Record<string, unknown>).config_key === 'sku_ai_image';
|
||
});
|
||
}
|
||
|
||
function hasSkuAiImageNeqFilter(spec: QuerySpec) {
|
||
return (spec.filters || []).some(
|
||
(filter) => filter.column === 'config_key' && filter.op === 'neq' && filter.value === 'sku_ai_image'
|
||
);
|
||
}
|
||
|
||
/** 平台级配置(branch_code 为空),仅超级管理员可读写 */
|
||
function isPlatformSystemConfigSpec(spec: QuerySpec) {
|
||
if (spec.table !== 'system_configs') return false;
|
||
if (isNavMenuLayoutSpec(spec)) return false;
|
||
if (isPrintTemplatesSpec(spec)) return false;
|
||
if (isSkuAiImageSpec(spec)) return false;
|
||
if (spec.action === 'select' && hasIsNullFilter(spec, 'branch_code')) return true;
|
||
if (spec.action === 'insert') {
|
||
const rows = Array.isArray(spec.insertData) ? spec.insertData : [spec.insertData];
|
||
return rows.some((row) => {
|
||
if (!row || typeof row !== 'object') return false;
|
||
const record = row as Record<string, unknown>;
|
||
return record.config_key !== 'nav_menu_layout' &&
|
||
record.config_key !== 'print_templates' &&
|
||
record.config_key !== 'sku_ai_image' &&
|
||
(record.branch_code === null || record.branch_code === undefined);
|
||
});
|
||
}
|
||
if (spec.action === 'update' || spec.action === 'delete') {
|
||
return hasIsNullFilter(spec, 'branch_code');
|
||
}
|
||
return false;
|
||
}
|
||
|
||
function applyBranchAdminSystemConfigScope(spec: QuerySpec, ctx: TenantContext): QuerySpec {
|
||
if (!ctx.branchCode) {
|
||
throw new Error('未绑定分公司,无法访问系统配置');
|
||
}
|
||
|
||
if (spec.action === 'insert') {
|
||
const rows = Array.isArray(spec.insertData) ? spec.insertData : [spec.insertData];
|
||
spec.insertData = rows.map((row) => {
|
||
if (!row || typeof row !== 'object') return row;
|
||
const record = row as Record<string, unknown>;
|
||
if (record.config_key === 'nav_menu_layout') {
|
||
return { ...record, branch_code: ctx.branchCode };
|
||
}
|
||
if (record.config_key === 'print_templates') {
|
||
return { ...record, branch_code: ctx.branchCode };
|
||
}
|
||
if (record.config_key === 'sku_ai_image') {
|
||
return { ...record, branch_code: ctx.branchCode };
|
||
}
|
||
if (record.branch_code === null || record.branch_code === undefined) {
|
||
throw new Error('分公司管理员仅能修改本公司系统配置');
|
||
}
|
||
if (record.branch_code !== ctx.branchCode) {
|
||
throw new Error('无权为其他分公司写入系统配置');
|
||
}
|
||
return { ...record, branch_code: ctx.branchCode };
|
||
});
|
||
}
|
||
|
||
spec.filters = spec.filters || [];
|
||
if (spec.action === 'select' || spec.action === 'update' || spec.action === 'delete') {
|
||
const foreignBranch = (spec.filters || []).find(
|
||
(filter) => filter.column === 'branch_code' && filter.op === 'eq' && filter.value !== ctx.branchCode
|
||
);
|
||
if (foreignBranch) {
|
||
throw new Error('无权访问其他分公司的系统配置');
|
||
}
|
||
if (hasIsNullFilter(spec, 'branch_code')) {
|
||
throw new Error('分公司管理员无权修改平台级系统配置');
|
||
}
|
||
if (!hasFilter(spec, 'branch_code', ctx.branchCode)) {
|
||
spec.filters.push({ op: 'eq', column: 'branch_code', value: ctx.branchCode });
|
||
}
|
||
}
|
||
|
||
if (spec.action === 'update' && spec.updateData && typeof spec.updateData === 'object') {
|
||
delete (spec.updateData as Record<string, unknown>).branch_code;
|
||
delete (spec.updateData as Record<string, unknown>).config_key;
|
||
}
|
||
|
||
return spec;
|
||
}
|
||
|
||
function applySkuAiImageScope(spec: QuerySpec, ctx: TenantContext): QuerySpec | null {
|
||
if (spec.table !== 'system_configs') return null;
|
||
|
||
const isSkuAi = isSkuAiImageSpec(spec) || insertIncludesSkuAiImage(spec);
|
||
|
||
if (ctx.isSuperAdmin) {
|
||
if (isSkuAi && spec.action !== 'select') {
|
||
throw new Error('商品 AI 生图仅分公司管理员可配置');
|
||
}
|
||
if (isSkuAi) {
|
||
return spec;
|
||
}
|
||
if (spec.action === 'update' || spec.action === 'delete') {
|
||
spec.filters = spec.filters || [];
|
||
if (!hasSkuAiImageNeqFilter(spec)) {
|
||
spec.filters.push({ op: 'neq', column: 'config_key', value: 'sku_ai_image' });
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
if (!isSkuAi) return null;
|
||
|
||
if (spec.action === 'select' && hasIsNullFilter(spec, 'branch_code')) {
|
||
return spec;
|
||
}
|
||
|
||
if (!ctx.branchCode) {
|
||
throw new Error('未绑定分公司,无法访问商品 AI 生图配置');
|
||
}
|
||
|
||
if (spec.action === 'insert') {
|
||
const rows = Array.isArray(spec.insertData) ? spec.insertData : [spec.insertData];
|
||
spec.insertData = rows.map((row) => {
|
||
if (!row || typeof row !== 'object') return row;
|
||
const record = row as Record<string, unknown>;
|
||
if (record.config_key !== 'sku_ai_image') {
|
||
throw new Error('分公司管理员仅能修改本公司商品 AI 生图配置');
|
||
}
|
||
return { ...record, branch_code: ctx.branchCode };
|
||
});
|
||
}
|
||
|
||
spec.filters = spec.filters || [];
|
||
if (spec.action === 'select' || spec.action === 'update' || spec.action === 'delete') {
|
||
const foreignBranch = (spec.filters || []).find(
|
||
(filter) => filter.column === 'branch_code' && filter.op === 'eq' && filter.value !== ctx.branchCode
|
||
);
|
||
if (foreignBranch) {
|
||
throw new Error('无权访问其他分公司的商品 AI 生图配置');
|
||
}
|
||
if (hasIsNullFilter(spec, 'branch_code')) {
|
||
throw new Error('分公司管理员无权修改平台级商品 AI 生图配置');
|
||
}
|
||
if (!hasFilter(spec, 'branch_code', ctx.branchCode)) {
|
||
spec.filters.push({ op: 'eq', column: 'branch_code', value: ctx.branchCode });
|
||
}
|
||
}
|
||
|
||
if (spec.action === 'update' && spec.updateData && typeof spec.updateData === 'object') {
|
||
delete (spec.updateData as Record<string, unknown>).branch_code;
|
||
delete (spec.updateData as Record<string, unknown>).config_key;
|
||
}
|
||
|
||
return spec;
|
||
}
|
||
|
||
function applyPrintTemplatesScope(spec: QuerySpec, ctx: TenantContext): QuerySpec | null {
|
||
if (spec.table !== 'system_configs' || !isPrintTemplatesSpec(spec)) return null;
|
||
|
||
if (spec.action === 'select' && hasIsNullFilter(spec, 'branch_code')) {
|
||
return spec;
|
||
}
|
||
|
||
if (!ctx.isSuperAdmin) {
|
||
if (!ctx.branchCode) {
|
||
throw new Error('未绑定分公司,无法访问打印模板配置');
|
||
}
|
||
|
||
if (spec.action === 'insert') {
|
||
const rows = Array.isArray(spec.insertData) ? spec.insertData : [spec.insertData];
|
||
spec.insertData = rows.map((row) => {
|
||
if (!row || typeof row !== 'object') return row;
|
||
const record = row as Record<string, unknown>;
|
||
if (record.config_key !== 'print_templates') {
|
||
throw new Error('分公司管理员仅能修改本公司打印模板');
|
||
}
|
||
return { ...record, branch_code: ctx.branchCode };
|
||
});
|
||
}
|
||
|
||
spec.filters = spec.filters || [];
|
||
if (spec.action === 'select' || spec.action === 'update' || spec.action === 'delete') {
|
||
const foreignBranch = (spec.filters || []).find(
|
||
(filter) => filter.column === 'branch_code' && filter.op === 'eq' && filter.value !== ctx.branchCode
|
||
);
|
||
if (foreignBranch) {
|
||
throw new Error('无权访问其他分公司的打印模板配置');
|
||
}
|
||
if (hasIsNullFilter(spec, 'branch_code')) {
|
||
throw new Error('分公司管理员无权修改平台级打印模板');
|
||
}
|
||
if (!hasFilter(spec, 'branch_code', ctx.branchCode)) {
|
||
spec.filters.push({ op: 'eq', column: 'branch_code', value: ctx.branchCode });
|
||
}
|
||
}
|
||
|
||
if (spec.action === 'update' && spec.updateData && typeof spec.updateData === 'object') {
|
||
delete (spec.updateData as Record<string, unknown>).branch_code;
|
||
delete (spec.updateData as Record<string, unknown>).config_key;
|
||
}
|
||
}
|
||
|
||
return spec;
|
||
}
|
||
|
||
function applyNavMenuLayoutScope(spec: QuerySpec, ctx: TenantContext): QuerySpec | null {
|
||
if (spec.table !== 'system_configs' || !isNavMenuLayoutSpec(spec)) return null;
|
||
|
||
if (spec.action === 'select' && hasIsNullFilter(spec, 'branch_code')) {
|
||
return spec;
|
||
}
|
||
|
||
if (!ctx.isSuperAdmin) {
|
||
if (!ctx.branchCode) {
|
||
throw new Error('未绑定分公司,无法访问导航菜单配置');
|
||
}
|
||
|
||
if (spec.action === 'insert') {
|
||
const rows = Array.isArray(spec.insertData) ? spec.insertData : [spec.insertData];
|
||
spec.insertData = rows.map((row) => {
|
||
if (!row || typeof row !== 'object') return row;
|
||
const record = row as Record<string, unknown>;
|
||
if (record.config_key !== 'nav_menu_layout') {
|
||
throw new Error('分公司管理员仅能修改本公司导航菜单');
|
||
}
|
||
return { ...record, branch_code: ctx.branchCode };
|
||
});
|
||
}
|
||
|
||
spec.filters = spec.filters || [];
|
||
if (spec.action === 'select' || spec.action === 'update' || spec.action === 'delete') {
|
||
const foreignBranch = (spec.filters || []).find(
|
||
(filter) => filter.column === 'branch_code' && filter.op === 'eq' && filter.value !== ctx.branchCode
|
||
);
|
||
if (foreignBranch) {
|
||
throw new Error('无权访问其他分公司的导航菜单配置');
|
||
}
|
||
if (!hasFilter(spec, 'branch_code', ctx.branchCode)) {
|
||
spec.filters.push({ op: 'eq', column: 'branch_code', value: ctx.branchCode });
|
||
}
|
||
}
|
||
|
||
if (spec.action === 'update' && spec.updateData && typeof spec.updateData === 'object') {
|
||
delete (spec.updateData as Record<string, unknown>).branch_code;
|
||
delete (spec.updateData as Record<string, unknown>).config_key;
|
||
}
|
||
}
|
||
|
||
return spec;
|
||
}
|
||
|
||
function hasItemTypeFilter(spec: QuerySpec, itemType: string) {
|
||
return (spec.filters || []).some(
|
||
(filter) => filter.column === 'item_type' && filter.op === 'eq' && filter.value === itemType
|
||
);
|
||
}
|
||
|
||
export function readOperatingBranchCode(req: {
|
||
headers: Record<string, string | string[] | undefined>;
|
||
}): string | null {
|
||
const raw = req.headers['x-operating-branch'];
|
||
if (Array.isArray(raw)) return raw[0]?.trim() || null;
|
||
return raw?.trim() || null;
|
||
}
|
||
|
||
export function getEffectiveBranchCode(
|
||
ctx: TenantContext | null,
|
||
operatingBranchCode?: string | null
|
||
): string | null {
|
||
if (!ctx) return null;
|
||
if (!ctx.isSuperAdmin) return ctx.branchCode;
|
||
return operatingBranchCode?.trim() || null;
|
||
}
|
||
|
||
/** /api/data 在有效分公司下应走 DB RLS/tenant schema 的表(平台表除外) */
|
||
export function isBranchRlsTable(table: string): boolean {
|
||
if (SUPER_ADMIN_PLATFORM_TABLES.has(table) || PLATFORM_ONLY_TABLES.has(table)) {
|
||
return false;
|
||
}
|
||
return (
|
||
BRANCH_SCOPED_TABLES.has(table) ||
|
||
TENANT_PATH_TABLES.has(table) ||
|
||
table === 'product_catalog' ||
|
||
SUPPLIER_LINKED_TABLES.has(table) ||
|
||
SKU_SUPPLIER_LINKED_TABLES.has(table) ||
|
||
CUSTOMER_LINKED_TABLES.has(table)
|
||
);
|
||
}
|
||
|
||
function applyProductCatalogScope(spec: QuerySpec, branchCode: string | null, requireBranch: boolean): QuerySpec {
|
||
if (spec.action === 'insert' || spec.action === 'update' || spec.action === 'delete') {
|
||
assertBranchAllowsProductCatalog(branchCode);
|
||
}
|
||
|
||
if (spec.action === 'insert') {
|
||
const rows = Array.isArray(spec.insertData) ? spec.insertData : [spec.insertData];
|
||
spec.insertData = rows.map((row) => {
|
||
if (!row || typeof row !== 'object') return row;
|
||
const record = row as Record<string, unknown>;
|
||
if (record.item_type === 'category' || record.item_type === 'product') {
|
||
if (!branchCode) {
|
||
throw new Error('请选择当前操作分公司');
|
||
}
|
||
return { ...record, branch_code: branchCode };
|
||
}
|
||
return record;
|
||
});
|
||
return spec;
|
||
}
|
||
|
||
if (spec.action === 'update' && spec.updateData && typeof spec.updateData === 'object') {
|
||
delete (spec.updateData as Record<string, unknown>).branch_code;
|
||
}
|
||
|
||
if (spec.action !== 'select' && spec.action !== 'update' && spec.action !== 'delete') {
|
||
return spec;
|
||
}
|
||
|
||
spec.filters = spec.filters || [];
|
||
|
||
if (hasItemTypeFilter(spec, 'product')) {
|
||
if (!branchCode) {
|
||
throw new Error(requireBranch ? '请选择当前操作分公司' : '未分配分公司,无法访问商品');
|
||
}
|
||
if (!hasProductCatalogBranchExpr(spec)) {
|
||
spec.filters.push({
|
||
op: 'expr',
|
||
raw: buildProductCatalogProductBranchExpr('$val'),
|
||
value: branchCode,
|
||
});
|
||
}
|
||
return spec;
|
||
}
|
||
|
||
if (hasItemTypeFilter(spec, 'category')) {
|
||
if (!branchCode) {
|
||
throw new Error(requireBranch ? '请选择当前操作分公司' : '未分配分公司,无法访问分类');
|
||
}
|
||
if (!hasProductCatalogBranchExpr(spec)) {
|
||
spec.filters.push({
|
||
op: 'expr',
|
||
raw: buildProductCatalogCategoryBranchExpr('$val'),
|
||
value: branchCode,
|
||
});
|
||
}
|
||
return spec;
|
||
}
|
||
|
||
if (!branchCode) {
|
||
if (requireBranch) {
|
||
throw new Error('请选择当前操作分公司');
|
||
}
|
||
return spec;
|
||
}
|
||
|
||
if (!hasProductCatalogBranchExpr(spec)) {
|
||
spec.filters.push({
|
||
op: 'expr',
|
||
raw: buildProductCatalogMixedBranchExpr('$val'),
|
||
value: branchCode,
|
||
});
|
||
}
|
||
|
||
return spec;
|
||
}
|
||
|
||
function hasLegacyCategoryBranchExpr(spec: QuerySpec) {
|
||
return (spec.filters || []).some(
|
||
(filter) => filter.op === 'expr' && filter.raw?.includes('cat_fb')
|
||
);
|
||
}
|
||
|
||
function hasProductCatalogBranchExpr(spec: QuerySpec) {
|
||
return (spec.filters || []).some(
|
||
(filter) =>
|
||
filter.op === 'expr' &&
|
||
typeof filter.raw === 'string' &&
|
||
filter.raw.includes('branch_code')
|
||
);
|
||
}
|
||
|
||
function hasProductCatalogCategoryBranchExpr(spec: QuerySpec) {
|
||
return hasProductCatalogBranchExpr(spec);
|
||
}
|
||
|
||
function hasSupplierLinkedBranchExpr(spec: QuerySpec) {
|
||
return (spec.filters || []).some((filter) => filter.op === 'expr' && filter.raw?.includes('suppliers'));
|
||
}
|
||
|
||
function applySkuSupplierLinkedScope(spec: QuerySpec, branchCode: string): QuerySpec {
|
||
spec.filters = spec.filters || [];
|
||
const hasExpr = spec.filters.some(
|
||
(filter) => filter.op === 'expr' && filter.raw?.includes('FROM skus WHERE branch_code')
|
||
);
|
||
if (!hasExpr) {
|
||
spec.filters.push({
|
||
op: 'expr',
|
||
raw: `t0.sku_code IN (SELECT sku_code FROM skus WHERE branch_code = $val)
|
||
AND t0.supplier_code IN (SELECT supplier_code FROM suppliers WHERE branch_code = $val)`,
|
||
value: branchCode,
|
||
});
|
||
}
|
||
return spec;
|
||
}
|
||
|
||
function applyCustomerLinkedScope(spec: QuerySpec, branchCode: string): QuerySpec {
|
||
spec.filters = spec.filters || [];
|
||
const hasExpr = spec.filters.some(
|
||
(filter) => filter.op === 'expr' && filter.raw?.includes('FROM customers WHERE branch_code')
|
||
);
|
||
if (!hasExpr) {
|
||
spec.filters.push({
|
||
op: 'expr',
|
||
raw: 't0.customer_code IN (SELECT customer_code FROM customers WHERE branch_code = $val)',
|
||
value: branchCode,
|
||
});
|
||
}
|
||
return spec;
|
||
}
|
||
|
||
function applySupplierLinkedScope(spec: QuerySpec, branchCode: string): QuerySpec {
|
||
spec.filters = spec.filters || [];
|
||
if (!hasSupplierLinkedBranchExpr(spec)) {
|
||
spec.filters.push({
|
||
op: 'expr',
|
||
raw: 't0.supplier_code IN (SELECT supplier_code FROM suppliers WHERE branch_code = $val)',
|
||
value: branchCode,
|
||
});
|
||
}
|
||
return spec;
|
||
}
|
||
|
||
function applyBranchCodeScope(spec: QuerySpec, branchCode: string, ctx: TenantContext): QuerySpec {
|
||
if (
|
||
(spec.table === 'skus' || spec.table === 'categories') &&
|
||
(spec.action === 'insert' || spec.action === 'update' || spec.action === 'delete')
|
||
) {
|
||
assertBranchAllowsProductCatalog(branchCode);
|
||
}
|
||
|
||
spec.filters = spec.filters || [];
|
||
|
||
if (spec.action === 'select' || spec.action === 'update' || spec.action === 'delete') {
|
||
if (spec.table === 'categories' && spec.action === 'select') {
|
||
if (!hasLegacyCategoryBranchExpr(spec)) {
|
||
spec.filters.push({
|
||
op: 'expr',
|
||
raw: buildLegacyCategoryBranchExpr('$val'),
|
||
value: branchCode,
|
||
});
|
||
}
|
||
} else if (!hasFilter(spec, 'branch_code', branchCode)) {
|
||
spec.filters.push({ op: 'eq', column: 'branch_code', value: branchCode });
|
||
}
|
||
}
|
||
|
||
if (spec.action === 'insert') {
|
||
const rows = Array.isArray(spec.insertData) ? spec.insertData : [spec.insertData];
|
||
spec.insertData = rows.map((row) => {
|
||
if (!row || typeof row !== 'object') return row;
|
||
return { ...(row as Record<string, unknown>), branch_code: branchCode };
|
||
});
|
||
}
|
||
|
||
if (spec.action === 'update' && spec.updateData && typeof spec.updateData === 'object') {
|
||
delete (spec.updateData as Record<string, unknown>).branch_code;
|
||
}
|
||
|
||
if (SUPPLIER_OWNED_TABLES.has(spec.table)) {
|
||
spec = applySupplierOwnedScope(spec, ctx);
|
||
}
|
||
|
||
if (spec.table === 'purchase_orders') {
|
||
spec = applySupplierPurchaseScope(spec, ctx);
|
||
}
|
||
|
||
return spec;
|
||
}
|
||
|
||
/** 通知:强制仅能操作当前用户自己的行(防同租户越权) */
|
||
function applyNotificationsUserScope(spec: QuerySpec, ctx: TenantContext): QuerySpec {
|
||
const userId = String(ctx.userId || '').trim();
|
||
if (!userId) throw new Error('请先登录');
|
||
|
||
if (spec.action === 'select' || spec.action === 'update' || spec.action === 'delete') {
|
||
spec.filters = spec.filters || [];
|
||
// 去掉客户端伪造的其他 user_id 条件,再强制本人
|
||
spec.filters = spec.filters.filter((filter) => filter.column !== 'user_id');
|
||
spec.filters.push({ op: 'eq', column: 'user_id', value: userId });
|
||
}
|
||
|
||
if (spec.action === 'insert') {
|
||
const rows = Array.isArray(spec.insertData) ? spec.insertData : [spec.insertData];
|
||
spec.insertData = rows.map((row) => {
|
||
if (!row || typeof row !== 'object') return row;
|
||
return { ...(row as Record<string, unknown>), user_id: userId };
|
||
});
|
||
}
|
||
|
||
if (spec.action === 'update' && spec.updateData && typeof spec.updateData === 'object') {
|
||
delete (spec.updateData as Record<string, unknown>).user_id;
|
||
}
|
||
|
||
return spec;
|
||
}
|
||
|
||
export function applyTenantScope(
|
||
spec: QuerySpec,
|
||
ctx: TenantContext | null,
|
||
operatingBranchCode?: string | null
|
||
): QuerySpec {
|
||
if (spec.table === 'notifications') {
|
||
if (!ctx) throw new Error('请先登录');
|
||
spec = applyNotificationsUserScope(spec, ctx);
|
||
}
|
||
|
||
if (spec.table === 'orders' && (spec.action === 'select' || !spec.action)) {
|
||
const includeDeleted = Boolean(
|
||
spec.filters?.some(
|
||
(filter) =>
|
||
(filter.column === 'deleted_at' && filter.op !== 'is' && filter.value != null) ||
|
||
(filter.op === 'expr' && filter.raw?.includes('deleted_at IS NOT NULL'))
|
||
)
|
||
);
|
||
if (!includeDeleted) {
|
||
spec.filters = spec.filters || [];
|
||
const already = spec.filters.some(
|
||
(filter) =>
|
||
(filter.column === 'deleted_at' && (filter.op === 'is' || filter.op === 'eq') && (filter.value == null || filter.value === null)) ||
|
||
(filter.op === 'expr' && filter.raw?.includes('deleted_at IS NULL'))
|
||
);
|
||
if (!already) {
|
||
spec.filters.push({ op: 'is', column: 'deleted_at', value: null });
|
||
}
|
||
}
|
||
}
|
||
|
||
if ((BRANCH_SCOPED_TABLES.has(spec.table) || TENANT_PATH_TABLES.has(spec.table)) && !ctx) {
|
||
throw new Error('请先登录');
|
||
}
|
||
|
||
if (spec.table === 'product_catalog') {
|
||
const branchCode = getEffectiveBranchCode(ctx, operatingBranchCode);
|
||
const requireBranch = Boolean(ctx?.isSuperAdmin && !branchCode);
|
||
return applyProductCatalogScope(spec, branchCode, requireBranch);
|
||
}
|
||
|
||
if (SHARED_CATALOG_TABLES.has(spec.table)) {
|
||
return spec;
|
||
}
|
||
|
||
if (SUPPLIER_LINKED_TABLES.has(spec.table)) {
|
||
if (!ctx) throw new Error('请先登录');
|
||
const branchCode = getEffectiveBranchCode(ctx, operatingBranchCode);
|
||
if (!branchCode) {
|
||
if (ctx.isSuperAdmin) throw new Error('请选择当前操作分公司');
|
||
throw new Error('未分配分公司,无法访问业务数据');
|
||
}
|
||
return applySupplierLinkedScope(spec, branchCode);
|
||
}
|
||
|
||
if (SKU_SUPPLIER_LINKED_TABLES.has(spec.table)) {
|
||
if (!ctx) throw new Error('请先登录');
|
||
const branchCode = getEffectiveBranchCode(ctx, operatingBranchCode);
|
||
if (!branchCode) {
|
||
if (ctx.isSuperAdmin) throw new Error('请选择当前操作分公司');
|
||
throw new Error('未分配分公司,无法访问业务数据');
|
||
}
|
||
return applySkuSupplierLinkedScope(spec, branchCode);
|
||
}
|
||
|
||
if (CUSTOMER_LINKED_TABLES.has(spec.table)) {
|
||
if (!ctx) throw new Error('请先登录');
|
||
const branchCode = getEffectiveBranchCode(ctx, operatingBranchCode);
|
||
if (!branchCode) {
|
||
if (ctx.isSuperAdmin) throw new Error('请选择当前操作分公司');
|
||
throw new Error('未分配分公司,无法访问业务数据');
|
||
}
|
||
return applyCustomerLinkedScope(spec, branchCode);
|
||
}
|
||
|
||
if (!ctx) return spec;
|
||
|
||
if (ctx.purchaserCode && !ctx.isInternalStaff && spec.table === 'purchase_orders') {
|
||
return applyPurchaserOwnedPurchaseScope(spec, ctx);
|
||
}
|
||
|
||
// 录单员仅见自己录的单(admin/super_admin/其它角色一概不进这个分支)
|
||
if (isOperatorScoped(ctx) && (spec.table === 'orders' || spec.table === 'order_items')) {
|
||
spec = applyOperatorOwnOrdersScope(spec, ctx);
|
||
}
|
||
|
||
const effectiveBranch = getEffectiveBranchCode(ctx, operatingBranchCode);
|
||
|
||
if (TENANT_PATH_TABLES.has(spec.table)) {
|
||
const branchCode = effectiveBranch || (!ctx.isSuperAdmin ? ctx.branchCode : null);
|
||
if (!branchCode) {
|
||
throw new Error(ctx.isSuperAdmin ? '请选择当前操作分公司' : '未分配分公司,无法访问业务数据');
|
||
}
|
||
// 无 branch_code 列:仅依赖 tenant search_path,不加分公司过滤
|
||
return spec;
|
||
}
|
||
|
||
if (ctx.isSuperAdmin) {
|
||
if (isSelfAccountRead(spec, ctx)) {
|
||
return spec;
|
||
}
|
||
|
||
if (spec.table === 'profiles') {
|
||
return applyProfilesBranchScope(spec, ctx, effectiveBranch);
|
||
}
|
||
if (spec.table === 'user_roles') {
|
||
return applyUserRolesBranchScope(spec, ctx, effectiveBranch);
|
||
}
|
||
|
||
if (SUPER_ADMIN_PLATFORM_TABLES.has(spec.table)) {
|
||
if (spec.table === 'system_configs') {
|
||
const skuAiScoped = applySkuAiImageScope(spec, ctx);
|
||
if (skuAiScoped) return skuAiScoped;
|
||
const printScoped = applyPrintTemplatesScope(spec, ctx);
|
||
if (printScoped) return printScoped;
|
||
const navMenuScoped = applyNavMenuLayoutScope(spec, ctx);
|
||
if (navMenuScoped) return navMenuScoped;
|
||
}
|
||
return spec;
|
||
}
|
||
|
||
if (!effectiveBranch) {
|
||
if (PLATFORM_ONLY_TABLES.has(spec.table)) return spec;
|
||
if (BRANCH_SCOPED_TABLES.has(spec.table)) {
|
||
throw new Error('请选择当前操作分公司');
|
||
}
|
||
return spec;
|
||
}
|
||
|
||
if (PLATFORM_ONLY_TABLES.has(spec.table)) {
|
||
return spec;
|
||
}
|
||
|
||
if (!BRANCH_SCOPED_TABLES.has(spec.table)) {
|
||
return spec;
|
||
}
|
||
|
||
return applyBranchCodeScope(spec, effectiveBranch, ctx);
|
||
}
|
||
|
||
if (spec.table === 'profiles') {
|
||
return applyProfilesBranchScope(spec, ctx, ctx.branchCode);
|
||
}
|
||
|
||
// user_roles 无 branch_code 列:非超管读取时按 profiles.branch_code 限定本分公司
|
||
// (自读 user_id = 自己的场景不加过滤,避免无分公司账号读不到自身角色)
|
||
if (spec.table === 'user_roles') {
|
||
return applyUserRolesBranchScope(spec, ctx, ctx.branchCode);
|
||
}
|
||
|
||
if (PLATFORM_ONLY_TABLES.has(spec.table) && spec.table === 'branches') {
|
||
if (!ctx.branchCode) {
|
||
throw new Error('未分配分公司,无法访问');
|
||
}
|
||
if (spec.action === 'select' || spec.action === 'update' || spec.action === 'delete') {
|
||
spec.filters = spec.filters || [];
|
||
if (!hasFilter(spec, 'branch_code', ctx.branchCode)) {
|
||
spec.filters.push({ op: 'eq', column: 'branch_code', value: ctx.branchCode });
|
||
}
|
||
}
|
||
if (spec.action === 'insert' || spec.action === 'update' || spec.action === 'delete') {
|
||
throw new Error('仅超级管理员可管理分公司');
|
||
}
|
||
return spec;
|
||
}
|
||
|
||
if (PLATFORM_ONLY_TABLES.has(spec.table)) {
|
||
return spec;
|
||
}
|
||
|
||
if (!BRANCH_SCOPED_TABLES.has(spec.table)) {
|
||
if (spec.table === 'system_configs') {
|
||
const skuAiScoped = applySkuAiImageScope(spec, ctx);
|
||
if (skuAiScoped) return skuAiScoped;
|
||
const printScoped = applyPrintTemplatesScope(spec, ctx);
|
||
if (printScoped) return printScoped;
|
||
const navMenuScoped = applyNavMenuLayoutScope(spec, ctx);
|
||
if (navMenuScoped) return navMenuScoped;
|
||
|
||
if (!ctx.isSuperAdmin && isPlatformSystemConfigSpec(spec)) {
|
||
// 允许只读平台配置(如 auth_idle_timeout);禁止增删改
|
||
if (spec.action === 'select') {
|
||
return spec;
|
||
}
|
||
throw new Error('分公司管理员无权修改平台级系统配置');
|
||
}
|
||
|
||
if (!ctx.isSuperAdmin) {
|
||
return applyBranchAdminSystemConfigScope(spec, ctx);
|
||
}
|
||
}
|
||
return spec;
|
||
}
|
||
|
||
if (!ctx.branchCode) {
|
||
throw new Error('未分配分公司,无法访问业务数据');
|
||
}
|
||
|
||
return applyBranchCodeScope(spec, ctx.branchCode, ctx);
|
||
}
|
||
|
||
export function resolveBranchForUserCreation(
|
||
ctx: TenantContext,
|
||
requestedBranchCode?: string | null,
|
||
requestedRoles: string[] = []
|
||
): string | null {
|
||
if (requestedRoles.includes('super_admin')) {
|
||
if (!ctx.isSuperAdmin) {
|
||
throw Object.assign(new Error('无权创建超级管理员'), { code: 'forbidden' });
|
||
}
|
||
return null;
|
||
}
|
||
|
||
if (ctx.isSuperAdmin) {
|
||
const branchCode = requestedBranchCode || 'BR001';
|
||
if (!branchCode) {
|
||
throw Object.assign(new Error('请为分公司用户选择所属分公司'), { code: 'invalid_branch' });
|
||
}
|
||
return branchCode;
|
||
}
|
||
|
||
if (ctx.isBranchAdmin || ctx.roles.includes('admin')) {
|
||
if (!ctx.branchCode) {
|
||
throw Object.assign(new Error('当前管理员未绑定分公司'), { code: 'invalid_branch' });
|
||
}
|
||
if (requestedBranchCode && requestedBranchCode !== ctx.branchCode) {
|
||
throw Object.assign(new Error('只能在本分公司下创建用户'), { code: 'forbidden' });
|
||
}
|
||
if (requestedRoles.includes('super_admin')) {
|
||
throw Object.assign(new Error('无权创建超级管理员'), { code: 'forbidden' });
|
||
}
|
||
return ctx.branchCode;
|
||
}
|
||
|
||
throw Object.assign(new Error('权限不足'), { code: 'forbidden' });
|
||
}
|
||
|
||
/** 写入时补齐 branch_code(超级管理员下单继承客户分公司;明细继承订单) */
|
||
export async function enrichTenantInsert(
|
||
spec: QuerySpec,
|
||
ctx: TenantContext | null,
|
||
operatingBranchCode?: string | null
|
||
): Promise<QuerySpec> {
|
||
if (spec.action !== 'insert') return spec;
|
||
|
||
const fallbackBranch = getEffectiveBranchCode(ctx, operatingBranchCode);
|
||
|
||
const lookupBranchCode = async (sql: string, params: unknown[]): Promise<string | null> => {
|
||
if (fallbackBranch) {
|
||
const row = await runInBranchSchema(fallbackBranch, async () => {
|
||
const result = await pool.query(sql, params);
|
||
return result.rows[0] || null;
|
||
});
|
||
return row?.branch_code ? String(row.branch_code) : null;
|
||
}
|
||
const hit = await findAcrossActiveTenants(sql, params);
|
||
return hit?.row?.branch_code ? String(hit.row.branch_code) : null;
|
||
};
|
||
|
||
const rows = Array.isArray(spec.insertData) ? spec.insertData : [spec.insertData];
|
||
const normalized = rows.filter((row) => row && typeof row === 'object') as Record<string, unknown>[];
|
||
|
||
// 操作日志:服务端强制补齐操作人(前端直插常漏姓名)
|
||
if (spec.table === 'operation_logs' && ctx?.userId) {
|
||
let resolvedName: string | null | undefined;
|
||
for (const row of normalized) {
|
||
if (!row.operator_id) row.operator_id = ctx.userId;
|
||
if (!String(row.operator_role || '').trim() && ctx.roles.length) {
|
||
row.operator_role = ctx.roles.join(',');
|
||
}
|
||
if (!String(row.operator_name || '').trim()) {
|
||
if (resolvedName === undefined) {
|
||
const profile = await rawQuery(
|
||
`SELECT COALESCE(NULLIF(TRIM(full_name), ''), NULLIF(TRIM(username), '')) AS name
|
||
FROM public.profiles WHERE id = $1::uuid LIMIT 1`,
|
||
[ctx.userId]
|
||
);
|
||
resolvedName = profile.rows[0]?.name ? String(profile.rows[0].name) : null;
|
||
}
|
||
if (resolvedName) row.operator_name = resolvedName;
|
||
}
|
||
if (!row.branch_code && fallbackBranch) {
|
||
row.branch_code = fallbackBranch;
|
||
}
|
||
}
|
||
}
|
||
|
||
for (const row of normalized) {
|
||
if (row.branch_code) continue;
|
||
|
||
if (spec.table === 'orders' && row.customer_code) {
|
||
const branch =
|
||
(await lookupBranchCode(`SELECT branch_code FROM customers WHERE customer_code = $1`, [
|
||
row.customer_code,
|
||
])) || fallbackBranch;
|
||
if (branch) row.branch_code = branch;
|
||
continue;
|
||
}
|
||
|
||
if (spec.table === 'order_items' && row.order_code) {
|
||
const branch =
|
||
(await lookupBranchCode(`SELECT branch_code FROM orders WHERE order_code = $1`, [row.order_code])) ||
|
||
fallbackBranch;
|
||
if (branch) row.branch_code = branch;
|
||
continue;
|
||
}
|
||
|
||
if (spec.table === 'picking_tasks' && row.order_code) {
|
||
const branch =
|
||
(await lookupBranchCode(`SELECT branch_code FROM orders WHERE order_code = $1`, [row.order_code])) ||
|
||
fallbackBranch;
|
||
if (branch) row.branch_code = branch;
|
||
continue;
|
||
}
|
||
|
||
if (spec.table === 'purchase_orders' && row.order_code) {
|
||
const branch =
|
||
(await lookupBranchCode(`SELECT branch_code FROM orders WHERE order_code = $1`, [row.order_code])) ||
|
||
fallbackBranch;
|
||
if (branch) row.branch_code = branch;
|
||
continue;
|
||
}
|
||
|
||
if (spec.table === 'picking_items' && row.pick_code) {
|
||
const branch =
|
||
(await lookupBranchCode(`SELECT branch_code FROM picking_tasks WHERE pick_code = $1`, [
|
||
row.pick_code,
|
||
])) || fallbackBranch;
|
||
if (branch) row.branch_code = branch;
|
||
continue;
|
||
}
|
||
|
||
if (
|
||
(spec.table === 'inspection_returns' || spec.table === 'inspection_loss_confirmations') &&
|
||
row.inspection_id
|
||
) {
|
||
const branch =
|
||
(await lookupBranchCode(`SELECT branch_code FROM inspections WHERE id = $1`, [row.inspection_id])) ||
|
||
fallbackBranch;
|
||
if (branch) row.branch_code = branch;
|
||
continue;
|
||
}
|
||
|
||
if (fallbackBranch && BRANCH_SCOPED_TABLES.has(spec.table)) {
|
||
row.branch_code = fallbackBranch;
|
||
}
|
||
}
|
||
|
||
if (spec.table === 'orders') {
|
||
for (const row of normalized) {
|
||
const branchCode = (row.branch_code as string | null | undefined) || fallbackBranch;
|
||
assertBranchAllowsOrders(branchCode);
|
||
}
|
||
}
|
||
|
||
if (Array.isArray(spec.insertData)) {
|
||
spec.insertData = normalized;
|
||
} else if (normalized[0]) {
|
||
spec.insertData = normalized[0];
|
||
}
|
||
|
||
return spec;
|
||
}
|