From afa1feb36654526e631d90c130bd88bc710e1821 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sat, 5 Dec 2026 15:33:59 +0100 Subject: [PATCH] Pay approved Golden Path rewards through P&O --- website/node/pol-funded-rewards.mjs | 9 +++-- website/node/quest-treasury-payments.mjs | 16 ++++++--- website/tests/leto-quests.test.mjs | 45 ++++++++++++++++++++++++ 3 files changed, 63 insertions(+), 7 deletions(-) diff --git a/website/node/pol-funded-rewards.mjs b/website/node/pol-funded-rewards.mjs index b6578931..bb0079eb 100644 --- a/website/node/pol-funded-rewards.mjs +++ b/website/node/pol-funded-rewards.mjs @@ -1,9 +1,11 @@ import {validFaithReward} from './faith-blessings.mjs'; -import {createPOLQuestTreasuryPayments} from './quest-treasury-payments.mjs'; +import {createGoldenPathPayments,createPOLQuestTreasuryPayments} from './quest-treasury-payments.mjs'; +import {LETO_QUESTS} from '../control-panel/public/cp-v2/cp-v2-leto-quests.mjs'; import {currentMentorPolicy} from './pol-mentor-rewards.mjs'; import {createSystemCharacters} from './system-characters.mjs'; import {OFFICIAL_ACCOUNT} from './official-account.mjs'; const jobs='jarvis_pol_quest_reward_jobs'; +const goldenPathRewards=new Map(LETO_QUESTS.map(q=>[q.id,q.amountMinor])); export function createPOLFundedRewards(central,bank,keys,{clock=Date.now}={}){ 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||job.state!=='queued')return 'unchanged'; @@ -15,7 +17,10 @@ export function createPOLFundedRewards(central,bank,keys,{clock=Date.now}={}){ const blessed=!!r.faith;if(blessed&&(!Number.isSafeInteger(r.faithBaseAmountMinor)||r.faithBaseAmountMinor*2!==r.amountMinor||!await validFaithReward(tx,r.faith,{accountId:row.account_id,claimedAt:Number(row.claimed_at)}))||!blessed&&Object.hasOwn(r,'faithBaseAmountMinor'))throw Error('Verified faith reward required'); if(!await tx.first('SELECT id FROM organisation_keys WHERE id=? AND revoked_at IS NULL FOR UPDATE',[issuer.keyId]))throw Error('Current issuer key required'); const actor=await tx.first("SELECT username,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[OFFICIAL_ACCOUNT.id]),player=await tx.first("SELECT id FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%' AND role NOT IN ('official_account','system_account','memorial') FOR UPDATE",[row.account_id]);if(!player||actor?.username!==OFFICIAL_ACCOUNT.username||actor.role!=='official_account')throw Error('Current payment identities required'); - const payments=createPOLQuestTreasuryPayments(bank,{clock,blessed,authorize:async()=>{const current=await tx.first('SELECT used_at,revoked_at FROM organisation_keys WHERE id=? FOR UPDATE',[keyId]);return current?.used_at!=null&¤t.revoked_at===null;}}); + const goldenPath=goldenPathRewards.get(row.definition_id); + if(goldenPath!==undefined&&(central.letoQuestEnabled!==true||goldenPath!==r.baseAmountMinor))throw Error('The approved Golden Path payout is unavailable'); + const usePayments=goldenPath===undefined?createPOLQuestTreasuryPayments:createGoldenPathPayments; + const payments=usePayments(bank,{clock,blessed,authorize:async()=>{const current=await tx.first('SELECT used_at,revoked_at FROM organisation_keys WHERE id=? FOR UPDATE',[keyId]);return current?.used_at!=null&¤t.revoked_at===null;}}); await payments.pay({keyId,accountId:row.account_id,amountMinor:r.amountMinor,memo:'Reputation reward '+keyId});await tx.query("UPDATE "+jobs+" SET state='paid' WHERE key_id=?",[keyId]);return 'paid'; });} return Object.freeze({async drain(){const rows=await central.query("SELECT key_id FROM "+jobs+" WHERE state='queued' AND JSON_EXTRACT(payload_json,'$.schema')='pol-funded-reward-v1' ORDER BY created_at,key_id LIMIT 25"),results=[];for(const r of rows){try{results.push({keyId:r.key_id,state:await process(r.key_id)});}catch{results.push({keyId:r.key_id,state:'awaiting-funding-or-review'});}}return {attempted:rows.length,results};}}); diff --git a/website/node/quest-treasury-payments.mjs b/website/node/quest-treasury-payments.mjs index e18cc7f7..df3ce365 100644 --- a/website/node/quest-treasury-payments.mjs +++ b/website/node/quest-treasury-payments.mjs @@ -1,31 +1,36 @@ import {createHash} from 'node:crypto'; import {PostbankPayments} from './postbank-payments.mjs'; +import {postPayrollIssue} from './postbank-payroll-issuer.mjs'; import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs'; import {OFFICIAL_ACCOUNT} from './official-account.mjs'; export const QUEST_TREASURY='sys_web_treasury'; +const PO_ISSUER='sys_payroll_po'; const accounts='SELECT a.*,c.entity_id,e.kind,e.external_key,e.active AS entity_active,p.state AS 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'; // Private domain consumer, not a staff/browser transfer permission. Its caller // holds the actual consumed quest instruction lock until this bank commit. -function treasuryPayments(bank,{authorize,clock=Date.now,blessed=false},kind,research=false){ +function treasuryPayments(bank,{authorize,clock=Date.now,blessed=false},kind,research=false,payroll=false){ if(typeof authorize!=='function')throw TypeError('A current verified quest authorizer is required'); + const sourceKey=payroll?PO_ISSUER:QUEST_TREASURY; const payments=new PostbankPayments(bank,async()=>({}),{clock}); return Object.freeze({async pay({keyId,clanId,accountId,recipientId:researchRecipient,amountMinor,memo}){ const recipientId=research?researchRecipient:kind==='clan'?clanId:accountId; const validRecipient=research&&kind==='office'?/^[a-z0-9:_-]{1,64}$/.test(recipientId||''):/^[a-f0-9-]{36}$/i.test(recipientId||''); if(!/^[a-f0-9-]{36}$/i.test(keyId||'')||!validRecipient||!Number.isSafeInteger(amountMinor)||amountMinor<1||amountMinor>(research?(blessed?30000:15000):kind==='clan'?15000000:(blessed?2500000:1250000))||memo!==(research?'Research reward ':kind==='clan'?'Rebellion reward ':'Reputation reward ')+keyId)throw Error('Invalid bound quest reward'); - const fingerprint=createHash('sha256').update(JSON.stringify([QUEST_TREASURY,keyId,recipientId,amountMinor,memo])).digest('hex'); + const fingerprint=createHash('sha256').update(JSON.stringify([sourceKey,keyId,recipientId,amountMinor,memo])).digest('hex'); return bank.transaction(async tx=>{ const entity=await tx.first("SELECT id FROM pb_entities WHERE kind=? AND external_key=? FOR UPDATE",[kind,recipientId]);if(!entity)throw Error('Quest recipient bank entity unavailable'); await tx.first('SELECT id FROM pb_entities WHERE id=? FOR UPDATE',[entity.id]); - const rows=await tx.query(accounts+' WHERE a.system_key=? OR c.entity_id=? ORDER BY a.id FOR UPDATE',[QUEST_TREASURY,entity.id]),source=rows.find(r=>r.system_key===QUEST_TREASURY); + const rows=await tx.query(accounts+' WHERE a.system_key=? OR c.entity_id=? ORDER BY a.id FOR UPDATE',[sourceKey,entity.id]),source=rows.find(r=>r.system_key===sourceKey); if(!await authorize())throw Error('Verified quest authorization expired'); const prior=await tx.first('SELECT * FROM pb_orders WHERE id=? FOR UPDATE',[keyId]); if(prior){const target=rows.find(r=>String(r.id)===String(prior.target_id));if(prior.actor_id!==OFFICIAL_ACCOUNT.id||prior.fingerprint!==fingerprint||prior.mode!=='system'||prior.state!=='posted'||prior.memo!==memo||Number(prior.amount_minor)!==amountMinor||String(prior.source_id)!==String(source?.id)||target?.kind!==kind||target.external_key!==recipientId)throw Error('Quest payment reference conflict');return prior;} const target=rows.find(ordinaryPaymentAccount); - if(!source||source.state!=='active'||source.type_code!=='979'||!target||BigInt(source.balance_minor)-BigInt(source.reserved_minor)treasuryPayments(bank,options,'clan'); export const createPOLQuestTreasuryPayments=(bank,options={})=>treasuryPayments(bank,options,'person'); +export const createGoldenPathPayments=(bank,options={})=>treasuryPayments(bank,options,'person',false,true); export const createResearchTreasuryPayments=(bank,options={})=>{if(!['clan','company','office'].includes(options.kind))throw TypeError('Research organisation required.');return treasuryPayments(bank,options,options.kind,true);}; diff --git a/website/tests/leto-quests.test.mjs b/website/tests/leto-quests.test.mjs index 69cc7988..e9bfd4fc 100644 --- a/website/tests/leto-quests.test.mjs +++ b/website/tests/leto-quests.test.mjs @@ -122,3 +122,48 @@ test('all 13 chapters advance and claim in sequence from authenticated evidence' assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_pol_activity_events')).n,13); }finally{f.db.close();} }); + +test('Golden Path claims pay from P&O once, including after a lost acknowledgement',async()=>{ + const {randomUUID}=await import('node:crypto'); + const {systemCharacterFixture}=await import('./system-character-fixture.mjs'); + const {initializePOLProgression,ensureLetoQuestPolicy}=await import('../node/progression-pol.mjs'); + const {initializePOLActivityEvents,createPOLActivityEvents}=await import('../node/pol-activity-events.mjs'); + const {ensurePOLMentorPolicy}=await import('../node/pol-mentor-rewards.mjs'); + const {createPOLProgressionRuntime}=await import('../node/progression-pol-runtime.mjs'); + const {createPOLFundedRewards}=await import('../node/pol-funded-rewards.mjs'); + const {PostbankService}=await import('../node/postbank-service.mjs'); + const {BANK_VERSION}=await import('../node/postbank-catalogue.mjs'); + const {OFFICIAL_ACCOUNT}=await import('../node/official-account.mjs'); + const {BankFixture}=await import('./postbank-fixture.mjs'); + const fixture=await systemCharacterFixture(),bank=new BankFixture(); + try{ + const {db,keys,people}=fixture,player=people.Member,uuid=randomUUID(),clock=()=>2000; + await fixture.characters.provision(people.Owner,'stilgar'); + await initializePOLProgression(db);await ensureLetoQuestPolicy(db,keys,{clock});await ensurePOLMentorPolicy(db,keys,{clock}); + await initializePOLActivityEvents(db);Object.assign(db,{polActivityEventsEnabled:true,polMentorBonusEnabled:true,letoQuestEnabled:true}); + await db.query('UPDATE site_game_links SET minecraft_uuid=? WHERE user_id=?',[uuid,player.id]); + const producer={},evidence=createPOLActivityEvents(db,keys,{clock,authorizeProducer:async actor=>actor===producer}); + const chapter=LETO_QUESTS[0]; + await evidence.record(producer,{accountId:player.id,minecraftUuid:uuid,eventId:randomUUID(),seasonId:'S01',metric:chapter.metric,quantity:1,occurredAt:2000,reference:randomUUID()}); + const runtime=createPOLProgressionRuntime(db,keys,{clock});await runtime.collect(player); + const grant=await runtime.quests.start(player,{definitionId:chapter.id}); + await runtime.quests.claim(player,{definitionId:chapter.id,requestId:randomUUID(),revision:1}); + + const entity={id:randomUUID(),kind:'person',key:player.id,name:'Recipient',canView:true,canActivate:true,canPay:false}; + await new PostbankService(bank,async()=>({entities:[entity]})).activate(player,{entityId:entity.id,packageKey:'pb_start',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()}); + await bank.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,reserved_minor,state,created_at) VALUES('sys_web_treasury','979','Web Treasury',999999,0,'active',1),('sys_payroll_po','979','P&O',0,0,'active',1)"); + await db.query('INSERT INTO site_accounts(id,username,role) VALUES(?,?,?)',[OFFICIAL_ACCOUNT.id,OFFICIAL_ACCOUNT.username,'official_account']); + const worker=createPOLFundedRewards(db,bank,keys,{clock}); + db.letoQuestEnabled=false; + assert.equal((await worker.drain()).results[0].state,'awaiting-funding-or-review'); + assert.equal((await bank.first('SELECT COUNT(*) n FROM pb_entries')).n,0); + db.letoQuestEnabled=true; + assert.equal((await worker.drain()).results[0].state,'paid'); + const order=await bank.first('SELECT o.amount_minor,a.system_key FROM pb_orders o JOIN pb_accounts a ON a.id=o.source_id WHERE o.id=?',[grant.id]); + assert.deepEqual({...order},{amount_minor:16500,system_key:'sys_payroll_po'}); + assert.equal((await bank.first("SELECT balance_minor FROM pb_accounts WHERE system_key='sys_web_treasury'")).balance_minor,999999); + await db.query("UPDATE jarvis_pol_quest_reward_jobs SET state='queued' WHERE key_id=?",[grant.id]); + assert.equal((await worker.drain()).results[0].state,'paid'); + assert.deepEqual({...await bank.first('SELECT COUNT(*) n,SUM(amount_minor) net FROM pb_entries')},{n:2,net:0}); + }finally{fixture.db.close();bank.close();} +});