diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs index 8a307e55..1afa9a49 100644 --- a/website/control-panel/server.mjs +++ b/website/control-panel/server.mjs @@ -78,7 +78,7 @@ import {openOrganisationKeyService,grantCurrentAccountKeys,ensureOriginalKeys} f import {CHARACTER_PREFERENCE_SCHEMA} from '../node/character-preferences.mjs'; import {CHARACTER_SCHEMA,createCharacterChoice} from './character-choice.mjs'; import {HOUSE_SELECTION_SCHEMA,createHouseSelectionAPI} from '../node/house-selection.mjs'; -import {createGameBriefing} from '../node/game-briefing.mjs'; +import {createGameBriefing,readGameMemberships} from '../node/game-briefing.mjs'; import {createClanKeyReceipts} from './clan-key-receipts.mjs'; import {clanDeedAuthority} from '../node/clan-deeds.mjs'; import {createClanDeedRoute} from './clan-deed-route.mjs'; @@ -224,7 +224,7 @@ export function createPanel(db,settings={},dependencies={}){ const progressionRuntime=dependencies.progressionRuntime||(dependencies.organisationKeys?createProgressionRuntime(db,dependencies.bankDatabase||null,dependencies.organisationKeys):null); const progression=createProgressionAPI(db,{...progressionRuntime,origin}); const polRuntime=dependencies.polProgressionRuntime||(dependencies.organisationKeys?createPOLProgressionRuntime(db,dependencies.organisationKeys):null); - const gameHouseSelection=createHouseSelectionAPI(db,dependencies.organisationKeys,settings,{readBriefing:createGameBriefing({personal:progressionRuntime,pol:polRuntime,bank:dependencies.bankDatabase||null,authority:createPostbankAuthority(db,{bank:dependencies.bankDatabase||null})})}); + const gameHouseSelection=createHouseSelectionAPI(db,dependencies.organisationKeys,settings,{readBriefing:createGameBriefing({personal:progressionRuntime,pol:polRuntime,bank:dependencies.bankDatabase||null,authority:createPostbankAuthority(db,{bank:dependencies.bankDatabase||null}),organisations:actor=>readGameMemberships(db,actor)})}); const polProgression=createProgressionAPI(polProgressionStore(db),{...polRuntime,authenticate:r=>identity(r,db),origin,basePath:'/api/progression/pol'}); const serverProjects=dependencies.serverProjects||(dependencies.organisationKeys?createServerProjectRuntime(db,dependencies.bankDatabase||null,dependencies.organisationKeys):null); const projectsAPI=createServerProjectAPI(db,serverProjects,{origin}); diff --git a/website/node/game-briefing.mjs b/website/node/game-briefing.mjs index e5875c29..0792c93b 100644 --- a/website/node/game-briefing.mjs +++ b/website/node/game-briefing.mjs @@ -3,12 +3,17 @@ import {canViewAccount} from './postbank-authorisations.mjs'; import {money} from './postbank-catalogue.mjs'; // Existing quest/key readers and bank authority only. Never collect facts, claim // a reward, sync bank identities, create accounts or change balances on a HUD read. -export function createGameBriefing({personal,pol,bank=null,authority,clock=Date.now}={}){ +export async function readGameMemberships(db,actor){ + const clans=await db.query('SELECT DISTINCT c.name FROM site_clans c JOIN site_clan_members m ON m.clan_id=c.id WHERE m.user_id=? AND c.active=1 ORDER BY c.name LIMIT 20',[actor.id]); + const companies=await db.query("SELECT DISTINCT c.name FROM corrino_companies c LEFT JOIN site_company_members m ON m.company_id=c.id WHERE c.status='active' AND (m.user_id=? OR c.ceo_account_id=?) ORDER BY c.name LIMIT 20",[actor.id,actor.id]); + return {clans:clans.map(row=>row.name),companies:companies.map(row=>row.name)}; +} +export function createGameBriefing({personal,pol,bank=null,authority,organisations=null,clock=Date.now}={}){ const cache=new Map(); const summary=data=>{const report=xpReport(data);return report?{level:report.level,xp:report.xp,nextXP:report.nextXP,cap:report.cap,quest:report.quest?.title||null}:null;}; return async actor=>{ const now=clock(),prior=cache.get(actor.id);if(prior&&prior.until>now)return prior.value; - const [p,r,a]=await Promise.allSettled([personal?.quests.list(actor),pol?.quests.list(actor),authority?.(actor)]); + const [p,r,a,o]=await Promise.allSettled([personal?.quests.list(actor),pol?.quests.list(actor),authority?.(actor),organisations?.(actor)]); const context=a.status==='fulfilled'?a.value:null; let funds=null; if(bank&&context){try{ @@ -18,7 +23,7 @@ export function createGameBriefing({personal,pol,bank=null,authority,clock=Date. if(allowed.length)funds={balance:money(allowed.reduce((n,row)=>n+BigInt(row.balance_minor),0n)),available:money(allowed.reduce((n,row)=>n+BigInt(row.balance_minor)-BigInt(row.reserved_minor),0n)),currency:'DM'}; } }catch{/* Missing bank data is unavailable, never an invented zero balance. */}} - const names=kind=>context?[...new Set(context.entities.filter(e=>e.kind===kind&&e.canView).map(e=>e.name))]:null; + const names=kind=>organisations?(o.status==='fulfilled'?o.value?.[kind==='clan'?'clans':'companies']||null:null):context?[...new Set(context.entities.filter(e=>e.kind===kind&&e.canView).map(e=>e.name))]:null; const value={personal:p.status==='fulfilled'?summary(p.value):null,reputation:r.status==='fulfilled'?summary(r.value):null,bank:funds,clans:names('clan'),companies:names('company'),updatedAt:now}; for(const [id,row]of cache)if(row.until<=now)cache.delete(id); cache.set(actor.id,{until:now+30000,value});return value; diff --git a/website/node/pol-mentor-rewards.mjs b/website/node/pol-mentor-rewards.mjs index d3fe1cb3..1bf2fdce 100644 --- a/website/node/pol-mentor-rewards.mjs +++ b/website/node/pol-mentor-rewards.mjs @@ -12,7 +12,8 @@ export async function ensurePOLMentorPolicy(db,keys,{clock=Date.now}={}){ }}); } export async function currentMentorPolicy(tx,{lock=false}={}){ - const row=await tx.first("SELECT h.key_id,h.details_json,k.used_at,k.revoked_at,k.key_type,k.account_id,k.scope_id FROM jarvis_pol_progression_history h JOIN organisation_keys k ON k.id=h.key_id WHERE h.action='mentor-bonus-policy' AND k.scope_id=?"+(lock?' FOR UPDATE':''),[scopeId]);if(!row||row.used_at==null||row.revoked_at!==null||row.key_type!=='progression-policy'||row.account_id!==STAFF_OFFICE_ACCOUNT_ID)return null; + const sql="SELECT h.key_id,h.details_json,k.used_at,k.revoked_at,k.key_type,k.account_id,k.scope_id FROM jarvis_pol_progression_history h JOIN organisation_keys k ON k.id=h.key_id WHERE h.action='mentor-bonus-policy' AND k.scope_id=?"+(lock?' FOR UPDATE':''); + const row=typeof tx.first==='function'?await tx.first(sql,[scopeId]):(await tx.query(sql,[scopeId]))[0];if(!row||row.used_at==null||row.revoked_at!==null||row.key_type!=='progression-policy'||row.account_id!==STAFF_OFFICE_ACCOUNT_ID)return null; const p=JSON.parse(row.details_json);if(p.schema!=='pol-mentor-bonus-v1'||!['xpBonusBps','dmBonusBps'].every(k=>Number.isSafeInteger(p[k])&&p[k]>=0&&p[k]<=2500)||p.maximumBps!==2500)throw Error('Mentor bonus policy requires review');return {...p,keyId:row.key_id}; } const increased=(base,bps)=>{if(!Number.isSafeInteger(base)||base<0)throw Error('Invalid base quest reward');const value=BigInt(base)+(BigInt(base)*BigInt(bps)+9999n)/10000n;if(value>BigInt(Number.MAX_SAFE_INTEGER))throw Error('Quest reward overflow');return Number(value);}; diff --git a/website/tests/game-briefing.test.mjs b/website/tests/game-briefing.test.mjs index aa01f663..b65192bd 100644 --- a/website/tests/game-briefing.test.mjs +++ b/website/tests/game-briefing.test.mjs @@ -1,5 +1,15 @@ import test from 'node:test';import assert from 'node:assert/strict'; -import {createGameBriefing} from '../node/game-briefing.mjs'; +import {createGameBriefing,readGameMemberships} from '../node/game-briefing.mjs'; +import {LocalD1} from './d1-adapter.mjs'; +import {currentMentorPolicy,POL_MENTOR_POLICY} from '../node/pol-mentor-rewards.mjs'; +import {STAFF_OFFICE_ACCOUNT_ID} from '../node/organisation-keys.mjs'; +test('production query-only database can read the existing Reputation mentor policy without a transaction facade',async()=>{ + const policy=await currentMentorPolicy({async query(sql,args){assert.match(sql,/^SELECT /);assert.deepEqual(args,['policy:POL:S01:v3']);return [{key_id:'policy',details_json:JSON.stringify(POL_MENTOR_POLICY),used_at:100,revoked_at:null,key_type:'progression-policy',account_id:STAFF_OFFICE_ACCOUNT_ID,scope_id:args[0]}];}});assert.equal(policy.xpBonusBps,1000); +}); +test('membership display excludes purchased children and passive offices without replacing the existing roster',async()=>{ + const db=new LocalD1("CREATE TABLE site_clans(id TEXT,name TEXT,active INT);CREATE TABLE site_clan_members(clan_id TEXT,user_id TEXT);CREATE TABLE corrino_companies(id TEXT,name TEXT,status TEXT,ceo_account_id TEXT);CREATE TABLE site_company_members(company_id TEXT,user_id TEXT);INSERT INTO site_clans VALUES('our','Our clan',1),('bought','Purchased child',1);INSERT INTO site_clan_members VALUES('our','one'),('bought','other');INSERT INTO corrino_companies VALUES('our','Our company','active','one'),('bought','Purchased subsidiary','active','other'),('pol','Passive order','active','memorial');"); + try{const rows=await readGameMemberships({query:async(sql,args)=>(await db.prepare(sql).bind(...args).all()).results},{id:'one'});assert.deepEqual(rows,{clans:['Our clan'],companies:['Our company']});}finally{db.close();} +}); const journal={state:'active',profile:{level:2,totalXP:80,effectiveXP:50,reserveXP:30},season:{id:'S01',curveBase:25,levelCap:70},quests:[{title:'Real active quest',keyId:'q',state:'active'}]}; test('HUD reuses authoritative XP curves and limits bank balance to the current personal authority; reads are cached per actor',async()=>{ let queries=0,reads=0;const bank={async query(sql,args){queries++;assert.match(sql,/^SELECT /);assert.deepEqual(args,['personal-one','one']);return [{id:1,balance_minor:'12345',reserved_minor:'100'},{id:2,balance_minor:'99999999',reserved_minor:'0'}];}};