web/website/node/progression-xp-instruments.mjs

65 lines
6.4 KiB
JavaScript

import {lockXPAccount as account,readActiveXPSeason as activeSeason,saveXPAccount as save} from './progression-xp-store.mjs';
import {creditXP,transferReservedXP} from './progression-xp-ledger.mjs';
import {xpAtLevel} from './progression-definitions.mjs';
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
const positive=n=>Number.isSafeInteger(n)&&n>0;
const seasonId=v=>/^S\d{2,4}$/.test(v||'');
// Uses the ordinary J.A.R.V.I.S. issue/consume transaction. resolveCase must read
// the authoritative support decision, not browser-provided ticket metadata.
export function createXPInstruments(db,keys,{authorizeIssue,resolveCase,clock=Date.now}){
if(typeof authorizeIssue!=='function'||typeof resolveCase!=='function')throw TypeError('XP authority and support-case adapters required');
async function approved(tx,reference,accountId){const source=await resolveCase(tx,reference);if(!source||source.approved!==true||source.accountId!==accountId||!positive(source.maxXP))throw Error('An approved matching support case is required');return source;}
async function insert(tx,{keyId,accountId,kind,amount,reference,from=null,to=null,issuer,now}){
await tx.query('INSERT INTO jarvis_xp_instruments(key_id,account_id,kind,amount_xp,source_reference,source_season,target_season,issuer_id,created_at) VALUES(?,?,?,?,?,?,?,?,?)',[keyId,accountId,kind,amount,reference,from,to,issuer,now]);
}
return Object.freeze({
async issueCorrection(actor,{accountId,caseReference,amountXP,requestId}){
if(!uuid(actor?.id)||!uuid(accountId)||!uuid(requestId)||!positive(amountXP)||!/^[-a-zA-Z0-9_]{1,48}$/.test(caseReference||''))throw TypeError('Invalid XP correction');
const scopeId='correction:'+caseReference+':'+requestId;
return keys.issue({accountId,keyType:'xp-correction',scopeId,authorize:async(tx,{keyId})=>{
if(!await authorizeIssue(actor,'xp-correction',tx))throw Error('XP correction permission required');
await account(tx,accountId,clock());const source=await approved(tx,caseReference,accountId);
const prior=await tx.first('SELECT p.* FROM jarvis_xp_instruments p JOIN organisation_keys k ON k.id=p.key_id WHERE k.account_id=? AND k.key_type=? AND k.scope_id=? FOR UPDATE',[accountId,'xp-correction',scopeId]);
if(prior){if(Number(prior.amount_xp)!==amountXP||prior.issuer_id!==actor.id)throw Error('XP issue reference conflict');return;}
const used=await tx.first("SELECT COALESCE(SUM(p.amount_xp),0) total FROM jarvis_xp_instruments p JOIN organisation_keys k ON k.id=p.key_id WHERE p.account_id=? AND p.kind='correction' AND p.source_reference=? AND k.revoked_at IS NULL",[accountId,caseReference]);
if(amountXP>source.maxXP-Number(used.total))throw Error('XP correction exceeds the uncompensated case amount');
await insert(tx,{keyId,accountId,kind:'correction',amount:amountXP,reference:caseReference,issuer:actor.id,now:clock()});
}});
},
async issueTransfer(actor,{accountId,fromSeason,toSeason}){
if(!uuid(actor?.id)||!uuid(accountId)||!seasonId(fromSeason)||!seasonId(toSeason)||fromSeason===toSeason)throw TypeError('Invalid XP season transfer');
return keys.issue({accountId,keyType:'xp-transfer',scopeId:'transfer:'+fromSeason+':'+toSeason,authorize:async(tx,{keyId})=>{
if(!await authorizeIssue(actor,'xp-transfer',tx))throw Error('XP transfer permission required');
const now=clock(),state=await account(tx,accountId,now),source=await tx.first('SELECT * FROM jarvis_progression_seasons WHERE season_id=? FOR UPDATE',[fromSeason]);
if(!source||source.state!=='closed'||Number(source.ends_at)>now)throw Error('Source season is not sealed');
const target=await activeSeason(tx,now,toSeason);
const between=await tx.first('SELECT COUNT(*) total FROM jarvis_progression_seasons WHERE starts_at>=? AND ends_at<=?',[Number(source.ends_at),Number(target.starts_at)]);
if(Number(source.ends_at)>Number(target.starts_at)||Number(between.total)!==0)throw Error('XP transfers require consecutive seasons');
const prior=await tx.first('SELECT id FROM organisation_keys WHERE account_id=? AND key_type=? AND scope_id=? FOR UPDATE',[accountId,'xp-transfer','transfer:'+fromSeason+':'+toSeason]);if(prior)return;
if(!positive(state.reserveXP))throw Error('No reserved XP is available');
await insert(tx,{keyId,accountId,kind:'transfer',amount:state.reserveXP,reference:'season:'+fromSeason,from:fromSeason,to:toSeason,issuer:actor.id,now});
}});
},
async redeem(user,{code,keyType,requestId}){
if(!uuid(user?.id)||!['xp-correction','xp-transfer'].includes(keyType))throw TypeError('Invalid XP redemption');
return keys.consume({accountId:user.id,keyType,code,targetId:user.id,requestId,apply:async(tx,{keyId})=>{
if(typeof user.revalidate==='function'&&(await user.revalidate())?.id!==user.id)throw Error('XP redemption session changed');
const now=clock(),state=await account(tx,user.id,now),instrument=await tx.first('SELECT * FROM jarvis_xp_instruments WHERE key_id=? AND account_id=? FOR UPDATE',[keyId,user.id]);
if(!instrument||!positive(Number(instrument.amount_xp)))throw Error('XP instrument unavailable');
const season=await activeSeason(tx,now,keyType==='xp-transfer'?instrument.target_season:null),capXP=xpAtLevel(Number(season.level_cap),Number(season.curve_base));let next;
if(keyType==='xp-correction'){
if(instrument.kind!=='correction')throw Error('XP instrument purpose mismatch');
const source=await approved(tx,instrument.source_reference,user.id),used=await tx.first("SELECT COALESCE(SUM(p.amount_xp),0) total FROM jarvis_xp_instruments p JOIN organisation_keys k ON k.id=p.key_id WHERE p.account_id=? AND p.kind='correction' AND p.source_reference=? AND k.used_at IS NOT NULL",[user.id,instrument.source_reference]);
if(Number(instrument.amount_xp)>source.maxXP-Number(used.total))throw Error('XP correction approval changed');
next=creditXP(state,Number(instrument.amount_xp),{capXP});
}else{
if(instrument.kind!=='transfer')throw Error('XP instrument purpose mismatch');
const source=await tx.first('SELECT state,ends_at FROM jarvis_progression_seasons WHERE season_id=? FOR UPDATE',[instrument.source_season]);
if(source?.state!=='closed'||Number(source.ends_at)>now)throw Error('Source season is not sealed');
next=transferReservedXP(state,{sealedAmount:Number(instrument.amount_xp),capXP});
}
await save(tx,user.id,next,season,keyId,keyType,{sourceReference:instrument.source_reference,amountXP:Number(instrument.amount_xp)},now);
}});
}
});
}