MC/website/node/staff-bureau-read-api.mjs
2026-11-27 23:43:05 +00:00

17 lines
2.1 KiB
JavaScript

import {identity} from './auth.mjs';
import {can} from './permissions.mjs';
import {STAFF_DEPARTMENTS,STAFF_LEVELS,shadowStaffAccess} from './staff-bureau-policy.mjs';
import {STAFF_SUBTEAMS} from './staff-bureau-subteams.mjs';
const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'no-store'}});
// Read-only shadow API. Does not assign positions, grant permissions or modify live RBAC.
export function createStaffBureauReadApi(db,{authenticate=identity,authorize=can}={}){
async function position(accountId){return db.prepare('SELECT account_id,department_key,staff_level,status,appointed_at,version FROM staff_positions WHERE account_id=?').bind(accountId).first();}
function projection(row){if(!row)return null;const position={accountId:row.account_id,department:row.department_key,level:row.staff_level,status:row.status};return {...position,appointedAt:row.appointed_at,version:row.version,shadow:shadowStaffAccess(position)};}
return async function staffBureauRead(request){if(request.method!=='GET')return reply({message:'Method not allowed'},405);const user=await authenticate(request,db);if(!user)return reply({message:'Sign in first'},401);const path=new URL(request.url).pathname;
if(path==='/api/v1/staff/me'){return reply({position:projection(await position(user.id)),mode:'shadow',active:false});}
if(!await authorize(db,user,'web.accounts.view'))return reply({message:'Permission required: web.accounts.view'},403);
if(path==='/api/v1/staff/departments')return reply({departments:Object.entries(STAFF_DEPARTMENTS).map(([key,label])=>({key,label,subteams:STAFF_SUBTEAMS[key]||[]})),levels:STAFF_LEVELS,mode:'shadow'});
if(path==='/api/v1/staff/directory'){const {results}=await db.prepare('SELECT p.account_id,p.department_key,p.staff_level,p.status,p.appointed_at,p.version,a.username,a.display_name FROM staff_positions p JOIN site_accounts a ON a.id=p.account_id ORDER BY p.department_key,p.staff_level DESC,a.username LIMIT 250').all();return reply({staff:results.map(row=>({...projection(row),username:row.username,displayName:row.display_name})),mode:'shadow'});}
return reply({message:'Not found'},404);
};
}