MC/website/scripts/bootstrap-organisation-appointments.mjs

36 lines
4.1 KiB
JavaScript

import {randomUUID} from 'node:crypto';
import {fileURLToPath} from 'node:url';import {resolve} from 'node:path';
import {openDatabase} from '../node/mysql.mjs';
import {initializeOrganisation,validStaffRole} from '../node/organisation-model.mjs';
import {MIGRATION_APPOINTMENTS} from '../node/organisation-appointments.mjs';
const OWNER_ID='f3ffda37-01e4-41ea-b89d-fbeda82e453e';
export async function bootstrapAppointments(db,{actorId,apply=false,clock=Date.now}={}){
const names=[...new Set(MIGRATION_APPOINTMENTS.map(p=>p.username))];
const {results:accounts}=await db.prepare(`SELECT a.id,a.username,p.game_link_exempt FROM site_accounts a LEFT JOIN site_account_policies p ON p.user_id=a.id WHERE a.username IN (${names.map(()=>'?')}) AND a.password_hash NOT LIKE '!%'`).bind(...names).all();
if(accounts.length!==names.length||accounts.some(a=>a.game_link_exempt)||accounts.find(a=>a.username==='unimatrix999')?.id!==OWNER_ID)throw Error('Approved migration identities do not match the existing active accounts.');
const plan=MIGRATION_APPOINTMENTS.map(p=>({...p,userId:accounts.find(a=>a.username===p.username).id})).sort((a,b)=>(a.scopeType+':'+a.scopeKey+':'+a.role+':'+a.userId).localeCompare(b.scopeType+':'+b.scopeKey+':'+b.role+':'+b.userId));
if(plan.some(p=>!validStaffRole(p.scopeType,p.scopeKey,p.role)))throw Error('Invalid approved migration function.');
if(!apply)return {applied:false,accounts:accounts.length,assignments:plan,permissionsChanged:false};
return db.transaction(async tx=>{
const actor=await tx.first("SELECT p.principal_kind FROM org_control_principals p JOIN site_accounts a ON a.id=p.user_id WHERE a.id=? AND a.password_hash NOT LIKE '!%' FOR SHARE",[actorId]);
if(!actor||!['owner','executive','service'].includes(actor.principal_kind))throw Error('Existing control actor required.');
let created=0,retained=0;
for(const p of plan){
await tx.query('INSERT IGNORE INTO org_scope_versions(scope_type,scope_key,version) VALUES(?,?,1)',[p.scopeType,p.scopeKey]);
await tx.first('SELECT version FROM org_scope_versions WHERE scope_type=? AND scope_key=? FOR UPDATE',[p.scopeType,p.scopeKey]);
const identity=await tx.first("SELECT a.id,p.game_link_exempt FROM site_accounts a LEFT JOIN site_account_policies p ON p.user_id=a.id WHERE a.id=? AND a.username=? AND a.password_hash NOT LIKE '!%' FOR SHARE",[p.userId,p.username]);
if(!identity||identity.game_link_exempt)throw Error('Migration identity changed.');
const now=clock(),current=await tx.query("SELECT user_id,role_key FROM org_assignments WHERE scope_type=? AND scope_key=? AND status='active' AND starts_at<=? AND (ends_at IS NULL OR ends_at>?) FOR UPDATE",[p.scopeType,p.scopeKey,now,now]);
if(current.some(a=>a.user_id===p.userId&&a.role_key===p.role)){retained++;continue;}
if(['branch_lead','department_head','owner_ceo'].includes(p.role)&&current.some(a=>a.role_key===p.role))throw Error('A migration leadership position already has another holder.');
const id=randomUUID();
await tx.query('INSERT INTO org_assignments(id,user_id,scope_type,scope_key,role_key,source_kind,source_ref,status,starts_at,created_by,created_at,version) VALUES(?,?,?,?,?,?,?,?,?,?,?,1)',[id,p.userId,p.scopeType,p.scopeKey,p.role,'manual','great-migration-owner-approved','active',now,actorId,now]);
await tx.query('UPDATE org_scope_versions SET version=version+1 WHERE scope_type=? AND scope_key=?',[p.scopeType,p.scopeKey]);
await tx.query('INSERT INTO org_assignment_events(id,user_id,assignment_id,actor_id,action,scope_type,scope_key,reason,after_json,created_at) VALUES(?,?,?,?,?,?,?,?,?,?)',[randomUUID(),p.userId,id,actorId,'appointment-baseline',p.scopeType,p.scopeKey,'Owner-approved Great Migration appointment',JSON.stringify({...p,permissionsChanged:false}),now]);created++;
}
return {applied:true,created,retained,permissionsChanged:false};
});
}
if(process.argv[1]&&fileURLToPath(import.meta.url)===resolve(process.argv[1])){
const db=await openDatabase(process.env);try{await initializeOrganisation(db);console.log(JSON.stringify(await bootstrapAppointments(db,{actorId:process.argv.find(a=>a.startsWith('--actor='))?.slice(8),apply:process.argv.includes('--apply')})));}finally{await db.close();}
}