MC/website/node/organisation-effective.mjs

28 lines
2.2 KiB
JavaScript

import {validStaffRole} from './organisation-model.mjs';
const nativeEditors=new Set(['web.forum.admin','web.luckperms.edit','cp.luckperms.edit','luckperms.editor','luckperms.applyedits','luckperms.trusteditor']);
const officialBank=new Set(['web.bank.staff.manage','cp.bank.staff.manage','web.bank.staff.deposit','cp.bank.staff.deposit']);
// Pure preview: never changes legacy ranks or grants native product permissions.
export function effectiveOrganisationAccess({assignments,policies,registry,principalKind=null,now=Date.now()}){
const nodes=new Set(),sources=[],missing=[],blocked=[];
for(const a of assignments){
if(a.status!=='active'||Number(a.starts_at)>now||a.ends_at!==null&&a.ends_at!==undefined&&Number(a.ends_at)<=now)continue;
if(!validStaffRole(a.scope_type,a.scope_key,a.role_key))continue;
const roles=a.scope_type==='branch'&&a.role_key==='branch_lead'?['officer','branch_lead']:[a.role_key];
for(const role of roles){
const p=policies.find(p=>p.scope_type===a.scope_type&&p.scope_key===a.scope_key&&p.role_key===role);
const source={scopeType:a.scope_type,scopeKey:a.scope_key,role,assignmentId:a.id};
if(!p){missing.push(source);continue;}
let requested;try{requested=JSON.parse(p.permissions_json);}catch{throw Error('Invalid stored organisation policy.');}
if(!Array.isArray(requested)||requested.some(n=>typeof n!=='string'))throw Error('Invalid stored organisation policy.');
const granted=[];
for(const n of requested){
const management=a.scope_type==='organisation'&&['owner_ceo','executive'].includes(role)||a.scope_type==='department'&&role==='department_head';
const payroll=['web.payroll.manage','cp.payroll.manage'].includes(n);
if(!Object.hasOwn(registry,n)||n.includes('*')||/(^|\.)op($|\.)/.test(n)||nativeEditors.has(n)||officialBank.has(n)&&!management||payroll&&!(['owner','executive','service'].includes(principalKind)&&a.scope_type==='organisation'&&['owner_ceo','executive'].includes(role))){blocked.push({...source,node:n});continue;}
nodes.add(n);granted.push(n);
}
sources.push({...source,version:Number(p.version),nodes:[...new Set(granted)].sort()});
}
}
return {nodes:[...nodes].sort(),sources,missingPolicies:missing,blocked,enforcement:'preparing',permissionsChanged:false};
}