MC/website/node/rebellion-rewards.mjs
2026-11-27 23:43:05 +00:00

59 lines
6.3 KiB
JavaScript

import {PostbankPayments} from './postbank-payments.mjs';
import {createPostbankAuthority} from './postbank-authority.mjs';
import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs';
import {rebellionQuest} from './rebellion-quest-policy.mjs';
import {createQuestTreasuryPayments} from './quest-treasury-payments.mjs';
import {OFFICIAL_ACCOUNT} from './official-account.mjs';
const accountSQL='SELECT a.*,c.entity_id,e.kind,e.external_key,e.active AS entity_active,p.state AS 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 LEFT JOIN pb_packages p ON p.id=a.package_id';
const jobs='jarvis_pol_quest_reward_jobs';
const fail=message=>{throw Error(message);};
const first=async(db,sql,args)=>(await db.query(sql,args))[0]||null;
// No reward minting. A configured fund owner pays through the existing standard
// bank queue, with the quest key as the durable payment reference across crashes.
export function createRebellionRewards(central,bank,{sourceAccount,sourceOwnerId,useWebsiteTreasury=false,authority=createPostbankAuthority(central,{bank}),payments=null}={}){
const owner=async()=>await first(central,"SELECT id,username,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[sourceOwnerId]);
payments||=new PostbankPayments(bank,authority,{resolveUser:async id=>first(central,"SELECT id,username,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[id])});
async function process(keyId){return central.transaction(async tx=>{
const job=await tx.first(`SELECT * FROM ${jobs} WHERE key_id=? FOR UPDATE`,[keyId]);if(!job||!['awaiting_funding','submitted'].includes(job.state))return 'unchanged';
const reward=await tx.first('SELECT * FROM jarvis_rebellion_rewards WHERE quest_key_id=?',[keyId]);
const instruction=await tx.first("SELECT i.*,k.used_at,k.revoked_at,k.key_type,k.scope_id,k.account_id key_account FROM jarvis_generated_instructions i JOIN organisation_keys k ON k.id=i.key_id WHERE i.key_id=? AND i.action_id='politics.rebellion' FOR UPDATE",[keyId]);
if(!reward||!instruction||instruction.state!=='applied'||instruction.used_at==null||instruction.revoked_at!=null)fail('Verified completed rebellion key required');
const {declaration:d,receipt}=JSON.parse(instruction.manifest_json),base=rebellionQuest(reward.office_key).reward,multiplier=(d.rewardMultiplier||1)+(reward.bonus_marker==='inaugural'?5:0),policy={reputationXP:base.reputationXP*multiplier,amountMinor:base.amountMinor*multiplier};
if((reward.challenge_key_id||'00000000-0000-4000-8000-000000000000')!==(d.counterChallengeOf||'00000000-0000-4000-8000-000000000000')||!!receipt?.firstSuccessBonus!==(reward.bonus_marker==='inaugural'))fail('Rebellion bonus bindings changed');
if(!receipt||receipt.questKeyId!==keyId||d.attackerClanId!==reward.clan_id||d.officeKey!==reward.office_key||d.winnerId!==reward.winner_id||job.account_id!==reward.winner_id||job.season_id!==reward.season_id||d.seasonId!==reward.season_id||Number(reward.amount_minor)!==policy.amountMinor||Number(reward.xp)!==policy.reputationXP)fail('Rebellion reward bindings changed');
if(instruction.key_type!=='quest'||instruction.key_account!==reward.winner_id||instruction.account_id!==reward.winner_id||instruction.scope_id!==reward.season_id+':REBELLION_'+instruction.request_id)fail('Rebellion quest identity changed');
const reference='Rebellion reward '+keyId;
if(useWebsiteTreasury){
const treasury=createQuestTreasuryPayments(bank,{authorize:async()=>{
const actor=await tx.first("SELECT id,username,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[OFFICIAL_ACCOUNT.id]);
const key=await tx.first('SELECT used_at,revoked_at FROM organisation_keys WHERE id=? FOR UPDATE',[keyId]);
return actor?.username===OFFICIAL_ACCOUNT.username&&actor.role==='official_account'&&key?.used_at!=null&&key.revoked_at==null;
}});
await treasury.pay({keyId,clanId:reward.clan_id,amountMinor:policy.amountMinor,memo:reference});
await tx.query(`UPDATE ${jobs} SET state='paid' WHERE key_id=?`,[keyId]);receipt.rewardState='paid';
await tx.query('UPDATE jarvis_generated_instructions SET manifest_json=? WHERE key_id=?',[JSON.stringify({declaration:d,receipt}),keyId]);return 'paid';
}
let order=await bank.first('SELECT * FROM pb_orders WHERE id=?',[keyId]);
if(order){
const target=await bank.first(accountSQL+' WHERE a.id=?',[order.target_id]);
if(order.actor_id!==sourceOwnerId||String(order.source_id)!==String(sourceAccount)||order.memo!==reference||Number(order.amount_minor)!==policy.amountMinor||order.mode!=='standard'||target?.kind!=='clan'||target.external_key!==reward.clan_id)fail('Rebellion payment reference conflict');
}else{
const actor=await owner();if(!actor)fail('Quest funding owner unavailable');
const recipients=await bank.query(accountSQL+" WHERE e.kind='clan' AND e.external_key=? ORDER BY a.id",[reward.clan_id]);
const target=recipients.find(ordinaryPaymentAccount);if(!target)fail('Winning clan needs an active payment account');
await payments.transfer(actor,{requestId:keyId,sourceAccount:String(sourceAccount),targetNumber:target.account_number,amount:(policy.amountMinor/100).toFixed(2),reference,mode:'standard',confirmed:true},{revalidate:owner});
order=await bank.first('SELECT * FROM pb_orders WHERE id=?',[keyId]);
}
const state=order?.state==='posted'?'paid':order?.state==='queued'?'submitted':'payment_review';
await tx.query(`UPDATE ${jobs} SET state=? WHERE key_id=?`,[state,keyId]);
receipt.rewardState=state==='paid'?'paid':state==='submitted'?'bank-processing':'payment-review';
await tx.query('UPDATE jarvis_generated_instructions SET manifest_json=? WHERE key_id=?',[JSON.stringify({declaration:d,receipt}),keyId]);return state;
});}
return Object.freeze({async drain(){
if(!useWebsiteTreasury&&(!/^\d{1,12}$/.test(String(sourceAccount||''))||!/^[a-f0-9-]{36}$/i.test(sourceOwnerId||'')))return {state:'awaiting-funding-configuration',attempted:0};
const pending=await central.query(`SELECT key_id FROM ${jobs} WHERE state IN ('awaiting_funding','submitted') ORDER BY created_at,key_id LIMIT 25`),results=[];
for(const job of pending){try{results.push({keyId:job.key_id,state:await process(job.key_id)});}catch{results.push({keyId:job.key_id,state:'awaiting-funding-or-review'});}}
return {attempted:pending.length,results};
}});
}