'use strict'; const ROLE_CAPABILITIES = Object.freeze({ headquarters_admin: ['*'], regional_manager: ['read', 'manage_plans', 'execute_items', 'manage_findings', 'manage_tasks', 'manage_quality'], store_manager: ['read', 'manage_plans', 'execute_items', 'manage_findings', 'manage_tasks'], executor: ['read', 'manage_plans', 'execute_items', 'manage_findings'], auditor: ['read'] }); function hasCapability(binding, capability) { const capabilities = ROLE_CAPABILITIES[binding?.role] || []; return capabilities.includes('*') || capabilities.includes(capability); } function resolveTargetStore(store, accountKey, input = {}) { if (input.storeId) return String(input.storeId); if (input.roomId) return String(store.getGroup(accountKey, input.roomId)?.store_id || ''); if (input.itemId) return String(store.getPlanItemWithContext(accountKey, input.itemId)?.store_id || ''); if (input.findingId) { const finding = store.db.prepare('SELECT room_id FROM group_ops_findings WHERE id=? AND account_key=?').get(input.findingId, accountKey); return String(finding?.room_id ? store.getGroup(accountKey, finding.room_id)?.store_id || '' : ''); } if (input.taskId) return String(store.getTask(accountKey, input.taskId)?.room_id ? store.getGroup(accountKey, store.getTask(accountKey, input.taskId).room_id)?.store_id || '' : ''); return ''; } function authorizeGroupOps(store, accountKey, principal, capability, input = {}) { const bindings = store.listRoleBindings(accountKey); if (!bindings.length) return { allowed: true, mode: 'bootstrap', warning: '当前账号尚未配置角色绑定,沿用兼容模式。' }; const binding = store.getRoleBinding(accountKey, principal); if (!binding) return { allowed: false, reason: '当前身份未被授予社群运营角色' }; if (!hasCapability(binding, capability)) return { allowed: false, reason: `角色 ${binding.role} 没有 ${capability} 权限` }; if (binding.role === 'headquarters_admin' || capability === 'read' && binding.role === 'auditor') return { allowed: true, binding }; const targetStore = resolveTargetStore(store, accountKey, input); if (!targetStore) return { allowed: capability === 'read', binding, reason: capability === 'read' ? '' : '该操作缺少可校验的门店范围' }; if (!binding.storeScope.includes(targetStore)) return { allowed: false, reason: `无权操作门店 ${targetStore}` }; return { allowed: true, binding, targetStore }; } module.exports = { ROLE_CAPABILITIES, authorizeGroupOps };