web/website/node/progression-runtime.mjs

73 lines
8 KiB
JavaScript

import {verifyDeedAcquisition} from './deed-acquisition-proof.mjs';
import {createProgressionMilestoneNews} from './progression-milestone-news.mjs';
import {createQuestProgression} from './progression-quests.mjs';
import {createXPInstruments} from './progression-xp-instruments.mjs';
import {firstLoginState} from './first-login.mjs';
import {can} from './permissions.mjs';
const first=async(db,sql,args=[])=>{const rows=await db.query(sql,args);return rows[0]||null;};
export function createProgressionRuntime(central,bank,keys,{clock=Date.now,resolveCase=async()=>null,verifyAcquisition=input=>verifyDeedAcquisition(central,bank,input)}={}){
const observer=Object.freeze({internal:'progression-source-reader'});
const resolvePlayer=id=>first(central,"SELECT id,username,display_name,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[id]);
async function authorizePlayer(actor,store){
if(typeof actor.revalidate==='function'&&(await actor.revalidate())?.id!==actor.id)return false;
return !!await first(store,"SELECT id FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[actor.id]);
}
const quests=createQuestProgression(central,keys,{clock,authorizePlayer,resolvePlayer,
authorizeObservation:async actor=>actor===observer,
// A relation label alone cannot prove a settled transfer or its beneficiary.
// The existing deed settlement flow must supply its verified adapter.
verifyAcquisition:async(actor,input,tx)=>actor===observer&&await verifyAcquisition(input,tx)
});
const xp=createXPInstruments(central,keys,{clock,resolveCase,authorizeIssue:async(actor,type)=>{
const fresh=await resolvePlayer(actor.id);if(!fresh)return false;
return can(central,fresh,type==='xp-correction'?'web.progression.xp.correct':'web.progression.seasons.manage');
}});
async function collect(actor){
if(!await authorizePlayer(actor,central))throw Error('Current player identity required');
const now=clock(),seasons=await central.query("SELECT season_id,starts_at FROM jarvis_progression_seasons WHERE state='active' AND starts_at<=? AND ends_at>?",[now,now]);
if(seasons.length!==1)return {state:'season-not-configured',sources:[]};const season=seasons[0],sources=[];
const save=async(metric,value)=>{
const quantity=Number(value);if(!Number.isSafeInteger(quantity)||quantity<0)throw Error('Source counter is not safe');
await quests.observe(observer,{accountId:actor.id,seasonId:season.season_id,metric,value:quantity,eventId:'web:'+actor.id+':'+season.season_id+':'+metric+':'+quantity,source:'verified-website'});
};
const source=async(name,metrics,work)=>{try{await work();sources.push({name,metrics,state:'available'});}catch{sources.push({name,metrics,state:'unavailable'});}};
await source('profile',['onboarding','profile','faction'],async()=>{
const profile=await first(central,'SELECT a.display_name,p.bio,l.minecraft_uuid FROM site_accounts a LEFT JOIN site_profiles p ON p.user_id=a.id LEFT JOIN site_game_links l ON l.user_id=a.id WHERE a.id=?',[actor.id]);
if(profile?.minecraft_uuid&&!await firstLoginState(central,actor))await save('onboarding',1);
if(profile?.display_name?.trim()&&String(profile.bio||'').trim().length>=10)await save('profile',1);
const choice=await first(central,'SELECT c.faction FROM site_character_choices c JOIN site_game_links l ON l.user_id=c.user_id AND l.minecraft_uuid=c.minecraft_uuid WHERE c.user_id=?',[actor.id]);if(choice?.faction)await save('faction',1);
});
await source('forum',['forum-registration','forum-contributions'],async()=>{
const account=await first(central,'SELECT uid FROM drforum_dune_accounts WHERE website_id=?',[actor.id]);if(!account)return;await save('forum-registration',1);
// Count unique meaningful, moderated-visible messages, with at most the first
// eligible contribution per thread/day; copied text never adds extra progress.
const count=await first(central,"SELECT COUNT(DISTINCT SHA2(LOWER(TRIM(p.message)),256)) total FROM drforum_posts p JOIN drforum_threads t ON t.tid=p.tid WHERE p.uid=? AND p.visible=1 AND t.visible=1 AND p.dateline>=? AND LENGTH(TRIM(p.message))>=40 AND NOT EXISTS(SELECT 1 FROM drforum_posts earlier WHERE earlier.uid=p.uid AND earlier.tid=p.tid AND earlier.visible=1 AND LENGTH(TRIM(earlier.message))>=40 AND FLOOR(earlier.dateline/86400)=FLOOR(p.dateline/86400) AND earlier.pid<p.pid)",[account.uid,Math.floor(Number(season.starts_at)/1000)]);
await save('forum-contributions',count.total);
});
await source('atelier',['kit-design','kit-publication'],async()=>{
const design=await first(central,"SELECT COUNT(*) total FROM site_kit_blueprints WHERE owner_user_id=? AND active=1 AND commerce_kind='personal_sale' AND LENGTH(TRIM(name))>=3",[actor.id]);
const listing=await first(central,"SELECT COUNT(*) total FROM site_kit_listings l JOIN site_kit_blueprints b ON b.id=l.blueprint_id WHERE b.owner_user_id=? AND b.active=1 AND b.commerce_kind='personal_sale' AND l.active=1 AND l.published=1 AND l.price_cents>0 AND l.blueprint_version=b.version",[actor.id]);
await save('kit-design',Number(design.total)>0?1:0);await save('kit-publication',Number(listing.total)>0?1:0);
});
await source('elections',['civic-activity','civic-ballot-equivalent','civic-additional'],async()=>{
const ballots=await first(central,'SELECT COUNT(DISTINCT b.id) total FROM political_ballots b JOIN political_voters v ON v.round_id=b.round_id AND v.player_uuid=b.player_uuid JOIN political_ballot_allocations a ON a.ballot_id=b.id AND a.votes>0 WHERE v.user_id=? AND b.created_at>=?',[actor.id,Number(season.starts_at)]);
const total=Number(ballots.total);await save('civic-activity',total);await save('civic-ballot-equivalent',total);await save('civic-additional',Math.max(0,total-1));
});
if(bank)await source('bank',['bank-transfer','wage-received','earned-minor'],async()=>{
const transfers=await first(bank,"SELECT COUNT(*) total FROM pb_orders o JOIN pb_accounts a ON a.id=o.source_id JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id JOIN pb_accounts target ON target.id=o.target_id WHERE e.kind='person' AND e.external_key=? AND o.state='posted' AND o.mode IN ('standard','instant') AND o.posted_at>=? AND o.source_id<>o.target_id AND (target.client_number IS NULL OR target.client_number<>a.client_number)",[actor.id,Number(season.starts_at)]);await save('bank-transfer',transfers.total);
const wages=await first(bank,"SELECT COUNT(*) total,COALESCE(SUM(o.amount_minor),0) earned FROM pb_orders o 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 e.kind='person' AND e.external_key=? AND o.state='posted' AND o.mode='payroll' AND o.posted_at>=?",[actor.id,Number(season.starts_at)]);await save('wage-received',wages.total);await save('earned-minor',wages.earned);
});
if(bank)await source('deed-acquisitions',['acquired-clan','acquired-company'],async()=>{
const rows=await bank.query("SELECT quote_json FROM jarvis_deed_purchases WHERE actor_id=? AND state='posted' ORDER BY created_at,id",[actor.id]);
for(const row of rows){const q=JSON.parse(row.quote_json);if(!['clan','company'].includes(q.kind))continue;await quests.recordAcquisition(observer,{accountId:actor.id,kind:q.kind,entityId:q.entityId,origin:q.kind==='clan'?'bend-the-knee':'purchase'});}
});
return {state:'verified',sources};
}
async function recordPoliticalVisit(actor){
if(!await authorizePlayer(actor,central))throw Error('Current player identity required');const now=clock();
const seasons=await central.query("SELECT season_id FROM jarvis_progression_seasons WHERE state='active' AND starts_at<=? AND ends_at>?",[now,now]);
if(seasons.length!==1)return;
return quests.observe(observer,{accountId:actor.id,seasonId:seasons[0].season_id,metric:'political-interface',value:1,eventId:'political-interface:'+actor.id+':'+seasons[0].season_id,source:'verified-website-visit'});
}
return Object.freeze({quests,xp,collect,recordPoliticalVisit,announcements:createProgressionMilestoneNews(central,keys,{clock})});
}