forked from unimatrix/web
48 lines
6.4 KiB
JavaScript
48 lines
6.4 KiB
JavaScript
import {createHash} from 'node:crypto';
|
|
import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs';
|
|
import {postPayrollIssue} from './postbank-payroll-issuer.mjs';
|
|
import {OFFICIAL_ACCOUNT} from './official-account.mjs';
|
|
import {boardReadStore} from './board-deed-source.mjs';
|
|
import {readClanDeed} from './clan-deeds.mjs';
|
|
import {readCompanyDeed} from './company-deeds.mjs';
|
|
import {PUBLIC_OFFICES} from './public-government.mjs';
|
|
import {validUuid} from './game-link.mjs';
|
|
export const ORGANISATION_QUEST_TREASURY='sys_payroll_po';
|
|
export function organisationRewardRef(owner){
|
|
if(!owner||!['clan','company','politics','office'].includes(owner.kind))throw Error('Registered reward organisation required');
|
|
if(['clan','company'].includes(owner.kind)){if(!validUuid(owner.id))throw Error('Registered reward organisation required');return{kind:owner.kind,id:owner.id.toLowerCase()};}
|
|
if(!PUBLIC_OFFICES.some(o=>o.key===owner.id))throw Error('Registered political office required');return{kind:'office',id:owner.id};
|
|
}
|
|
// The caller retains this central deed lock until the bank commit finishes.
|
|
// Mother control and specialist roles never replace the legal Basic owner.
|
|
export async function organisationRewardRoute(raw,owner){
|
|
const ref=organisationRewardRef(owner),tx=boardReadStore(raw,raw);
|
|
if(ref.kind==='office')return{kind:'office',id:ref.id==='emperor'?'emperor':'leader:'+(({arrakis:'fremen'})[ref.id]||ref.id),basic:false};
|
|
if(ref.kind==='clan'){
|
|
await tx.first('SELECT id FROM site_clans WHERE id=? AND active=1 FOR UPDATE',[ref.id]);const deed=await readClanDeed(tx,ref.id);if(!deed.owner)throw Error('Current clan owner required');return deed.kind==='basic'?{kind:'person',id:deed.owner.id,basic:true}:{kind:'clan',id:ref.id,basic:false};
|
|
}
|
|
await tx.first('SELECT company_id FROM site_company_deeds WHERE company_id=? FOR UPDATE',[ref.id]);const deed=await readCompanyDeed(tx,ref.id);if(deed.company.status!=='active')throw Error('Active company required');return deed.company.charter_kind==='basic'?{kind:'person',id:deed.company.owner_account_id,basic:true}:{kind:'company',id:ref.id,basic:false};
|
|
}
|
|
const accounts='SELECT a.*,c.entity_id,e.kind,e.external_key,e.active entity_active,p.state package_state FROM pb_accounts a LEFT JOIN pb_clients c ON c.client_number=a.client_number LEFT JOIN pb_entities e ON e.id=c.entity_id LEFT JOIN pb_packages p ON p.id=a.package_id';
|
|
export function createOrganisationQuestPayments(bank,{authorize,resolveRoute,clock=Date.now}={}){
|
|
if(typeof authorize!=='function'||typeof resolveRoute!=='function')throw TypeError('Verified claim and current deed adapters required');
|
|
return{async pay({keyId,owner,amountMinor,purpose}){
|
|
const ref=organisationRewardRef(owner);if(!validUuid(keyId)||!Number.isSafeInteger(amountMinor)||amountMinor<1||amountMinor>250000||!['research','mission'].includes(purpose))throw Error('Invalid bound organisation reward');
|
|
const memo=(purpose==='research'?'Research reward ':'Organisation quest reward ')+keyId,fingerprint=createHash('sha256').update(JSON.stringify([ORGANISATION_QUEST_TREASURY,keyId,ref,amountMinor,memo])).digest('hex');
|
|
return bank.transaction(async tx=>{
|
|
if(!await authorize())throw Error('Consumed verified organisation claim required');
|
|
const prior=await tx.first('SELECT r.*,o.fingerprint,o.state order_state,o.actor_id,o.amount_minor,o.target_id paid_target,s.system_key source_key,e.kind paid_kind,e.external_key paid_key FROM pb_organisation_quest_rewards r JOIN pb_orders o ON o.id=r.order_id JOIN pb_accounts s ON s.id=o.source_id JOIN pb_accounts a ON a.id=o.target_id JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id WHERE r.key_id=? FOR UPDATE',[keyId]);
|
|
if(prior){if(prior.fingerprint!==fingerprint||prior.actor_id!==OFFICIAL_ACCOUNT.id||prior.order_state!=='posted'||prior.source_key!==ORGANISATION_QUEST_TREASURY||Number(prior.amount_minor)!==amountMinor||prior.organisation_kind!==ref.kind||prior.organisation_id!==ref.id||String(prior.target_id)!==String(prior.paid_target)||prior.recipient_kind!==prior.paid_kind||prior.recipient_key!==prior.paid_key)throw Error('Organisation reward reference conflict');return{orderId:prior.order_id,replayed:true,basic:!!Number(prior.basic_fallback),recipientKind:prior.recipient_kind};}
|
|
if(await tx.first('SELECT id FROM pb_orders WHERE id=? FOR UPDATE',[keyId]))throw Error('Organisation reward requires reconciliation');
|
|
const route=await resolveRoute(ref);if(!route||!['person','clan','company','office'].includes(route.kind)||route.basic!==true&&route.basic!==false||route.basic&&(route.kind!=='person'||!validUuid(route.id))||!route.basic&&(route.kind!==ref.kind||route.kind!=='office'&&route.id!==ref.id||route.kind==='office'&&route.id!==(ref.id==='emperor'?'emperor':'leader:'+(({arrakis:'fremen'})[ref.id]||ref.id))))throw Error('Current organisation reward route required');
|
|
const entity=await tx.first('SELECT id FROM pb_entities WHERE kind=? AND external_key=? AND active=1 FOR UPDATE',[route.kind,route.id]);if(!entity)throw Error('Organisation reward recipient has no active bank entity');
|
|
const rows=await tx.query(accounts+' WHERE a.system_key=? OR c.entity_id=? ORDER BY a.id FOR UPDATE',[ORGANISATION_QUEST_TREASURY,entity.id]),source=rows.find(a=>a.system_key===ORGANISATION_QUEST_TREASURY),target=rows.find(a=>a.entity_id===entity.id&&ordinaryPaymentAccount(a)&&BigInt(a.balance_minor)+BigInt(amountMinor)<=9223372036854775807n);
|
|
if(!source||source.state!=='active'||!target||String(source.id)===String(target.id))throw Error('P&O or organisation payment account unavailable');
|
|
if(!await authorize())throw Error('Organisation claim authority changed');
|
|
await tx.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'system','queued',?)",[keyId,OFFICIAL_ACCOUNT.id,source.id,target.id,fingerprint,String(amountMinor),memo,clock()]);
|
|
await postPayrollIssue(tx,{id:keyId,actor_id:OFFICIAL_ACCOUNT.id,amount_minor:String(amountMinor)},source,target,{now:clock()});
|
|
await tx.query('INSERT INTO pb_organisation_quest_rewards(key_id,order_id,target_id,organisation_kind,organisation_id,recipient_kind,recipient_key,basic_fallback,created_at) VALUES(?,?,?,?,?,?,?,?,?)',[keyId,keyId,target.id,ref.kind,ref.id,route.kind,route.id,route.basic?1:0,clock()]);
|
|
return{orderId:keyId,replayed:false,basic:route.basic,recipientKind:route.kind};
|
|
});
|
|
}};
|
|
}
|

Staff