web/website/node/crysknife-parent.mjs

23 lines
2 KiB
JavaScript

import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
import {entityParent,setEntityParent} from './entity-relations.mjs';
import {CRYSKNIFE_COMPANY_ID} from './crysknife-company.mjs';
const REQUEST_ID='bd5cc574-f474-4df4-bc66-c659e5c49f32';
const SCOPE='protected:order-crysknife:emperor:v1';
// Fixed institutional relocation approved for this Order; not a general transfer endpoint.
export async function attachCrysknifeToEmperor(db,keys,{clock=Date.now}={}){
const verify=async tx=>{
const row=await tx.first("SELECT d.owner_account_id FROM site_company_institutions i JOIN site_company_deeds d ON d.company_id=i.company_id JOIN site_memorials m ON m.user_id=d.owner_account_id AND m.slug='patrick-stewart' JOIN corrino_companies c ON c.id=i.company_id AND c.status='active' WHERE i.company_id=? AND i.institution_key='order-crysknife'",[CRYSKNIFE_COMPANY_ID]);
if(!row)throw Error('Protected Order deed requires review');
const parent=await entityParent(tx,'company',CRYSKNIFE_COMPANY_ID);
if(parent&&(parent.parent_kind!=='politics'||parent.parent_id!=='emperor'))throw Error('Protected Order parent changed; review required');
};
const issued=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-parent-link',scopeId:SCOPE,authorize:verify});
const key=(await keys.list(STAFF_OFFICE_ACCOUNT_ID)).find(k=>k.id===issued.id);
if(key?.status==='used')return {state:'linked',replayed:true};
if(key?.status!=='available')throw Error('Protected Order parent instrument unavailable');
return keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-parent-link',code:key.code,targetId:CRYSKNIFE_COMPANY_ID,requestId:REQUEST_ID,apply:async(tx,{keyId,scopeId})=>{
if(scopeId!==SCOPE)throw Error('Protected Order instrument scope mismatch');
await verify(tx);
await setEntityParent(tx,{childKind:'company',childId:CRYSKNIFE_COMPANY_ID,parentKind:'politics',parentId:'emperor',origin:'staff',keyId,requestId:REQUEST_ID,actorId:STAFF_OFFICE_ACCOUNT_ID,now:clock()});
}});
}