MC/website/node/political-clan-grants.mjs
2026-11-27 23:43:05 +00:00

18 lines
2.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {boardReadStore} from './board-deed-source.mjs';
import {organisationRewardRoute} from './organisation-quest-payments.mjs';
import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs';
import {tradeWorld} from '../control-panel/public/world-trade-policy.mjs';
import {currentClanFaith} from './clan-faith.mjs';
const fail=(message,status=409)=>{throw Object.assign(Error(message),{status});};
export function createPoliticalClanGrants(base){
const db=typeof base?.query==='function'?boardReadStore(base,base):null;
async function eligible(tx,d,row){return !!row&&Number(row.active)===1&&(!d.grantWorld||tradeWorld(row.home_world)===d.grantWorld)&&(!d.grantFaith||(await currentClanFaith(tx,row.id)).faith===d.grantFaith);}
async function targets(tx,d){if(!db)fail('Clan grant records unavailable.',503);const rows=await tx.query('SELECT id,name,active,home_world FROM site_clans WHERE active=1 ORDER BY name,id LIMIT 1001');if(rows.length>1000)fail('Narrow the clan grant registry.',503);const results=[];for(const row of rows)if(await eligible(tx,d,row))results.push({id:row.id,name:row.name});return results;}
async function resolve(tx,bank,d,id){
const row=await tx.first('SELECT id,name,active,home_world FROM site_clans WHERE id=? AND active=1 FOR UPDATE',[id]);if(!await eligible(tx,d,row))fail('Choose a current eligible clan on this House’s world.',403);
const route=await organisationRewardRoute(tx,{kind:'clan',id}),entity=await bank.first('SELECT id FROM pb_entities WHERE kind=? AND external_key=? AND active=1 FOR UPDATE',[route.kind,route.id]);if(!entity)fail('Activate the clan’s payment account, or its legal owner’s personal account for a Basic clan.');
const rows=await bank.query('SELECT a.*,e.active entity_active,p.state package_state FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id JOIN pb_packages p ON p.id=a.package_id WHERE c.entity_id=? AND a.system_key IS NULL ORDER BY a.id',[entity.id]);
const account=rows.find(ordinaryPaymentAccount);if(!account)fail('The receiving clan has no active payment account.');return{account,clanId:id,clanName:row.name,basic:route.basic,recipientKind:route.kind,recipientKey:route.id};
}
return{targets:(tx,d)=>targets(boardReadStore(tx,db),d),resolve};
}