web/website/scripts/enable-bank-client-management.mjs
2026-11-21 20:22:37 +01:00

18 lines
2.4 KiB
JavaScript

import {randomUUID} from 'node:crypto';import {fileURLToPath} from 'node:url';import {resolve} from 'node:path';
import {openDatabase} from '../node/mysql.mjs';import {nativeSyncMutation} from '../node/native-sync-outbox.mjs';
const DEV='f7b88778-f0bc-41cc-9227-d8ef2f52264d',OWNER='f3ffda37-01e4-41ea-b89d-fbeda82e453e';
export async function enableClientManagement(db,{actorId,apply=false}={}){
if(![DEV,OWNER].includes(actorId))throw Error('Pinned deployment actor required.');
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 p.user_id=? AND a.password_hash NOT LIKE '!%' FOR SHARE",[actorId]);
if(actor?.principal_kind!==(actorId===DEV?'service':'owner'))throw Error('Current deployment authority required.');
const row=await tx.first("SELECT permissions_json,version FROM org_role_policies WHERE scope_type='branch' AND scope_key='sales_accounts' AND role_key='officer' FOR UPDATE");
if(!row)throw Error('Active sales policy required.');const before=JSON.parse(row.permissions_json),node='web.bank.staff.clients';
if(before.includes(node))return {applied:apply,changed:false};
const after=[...new Set([...before,node])].sort();if(!apply)return {applied:false,changed:true,policy:'sales_accounts/officer',add:[node]};
const now=Date.now();await tx.query("UPDATE org_role_policies SET permissions_json=?,version=version+1,updated_by=?,updated_at=? WHERE scope_type='branch' AND scope_key='sales_accounts' AND role_key='officer'",[JSON.stringify(after),actorId,now]);
await tx.query('INSERT INTO org_assignment_events(id,user_id,actor_id,action,scope_type,scope_key,reason,before_json,after_json,created_at) VALUES(?,?,?,?,?,?,?,?,?,?)',[randomUUID(),null,actorId,'bank-client-policy','branch','sales_accounts','Authorised bank officers manage customer products; official accounts remain bank management only',JSON.stringify({nodes:before,version:Number(row.version)}),JSON.stringify({nodes:after,version:Number(row.version)+1}),now]);
const sync=nativeSyncMutation(now);await tx.query(sync.sql,sync.values);return {applied:true,changed:true};
});
}
if(process.argv[1]&&fileURLToPath(import.meta.url)===resolve(process.argv[1])){const db=await openDatabase(process.env);try{console.log(JSON.stringify(await enableClientManagement(db,{actorId:process.argv.find(a=>a.startsWith('--actor='))?.slice(8),apply:process.argv.includes('--apply')})));}finally{await db.close();}}