From 19d02f4c38282255a97bcdd7418db526cd50bc70 Mon Sep 17 00:00:00 2001 From: Dev Date: Tue, 24 Nov 2026 22:31:50 +0100 Subject: [PATCH] Connect consenting clan faith missions and P&O organisation rewards --- .../public/clan-deed-settings.mjs | 3 +- .../public/clan-faith-policy.mjs | 6 + .../public/cp-v2/cp-v2-clan-faith.mjs | 22 ++++ .../public/cp-v2/cp-v2-decision-audit.mjs | 3 +- .../public/cp-v2/cp-v2-faith-quests.mjs | 6 + .../cp-v2/cp-v2-pol-quest-catalogue.mjs | 2 + .../cp-v2/cp-v2-progression-catalogue.mjs | 3 +- .../public/cp-v2/cp-v2-progression.mjs | 4 +- .../public/jarvis-master-keys.mjs | 3 + website/control-panel/server.mjs | 11 +- .../osticket/dev-jarvis-catalogue.json | 109 +++++++++++++++++- website/node/atomic-bank-access.mjs | 4 +- website/node/bank-quest-activities.mjs | 4 +- website/node/clan-faith.mjs | 85 ++++++++++++++ website/node/faith-blessings.mjs | 2 +- website/node/faith-quest-evidence.mjs | 15 +++ website/node/organisation-quest-payments.mjs | 48 ++++++++ website/node/organisation-quest-rewards.mjs | 42 +++++++ .../node/organisation-research-rewards.mjs | 3 +- website/node/postbank-schema.sql | 6 + website/node/progression-pol-runtime.mjs | 5 +- website/node/progression-pol.mjs | 5 +- website/node/progression-policy.mjs | 5 +- website/node/server.mjs | 3 +- website/scripts/organisation-quest-grants.mjs | 15 +++ website/tests/bank-quest-activities.test.mjs | 6 +- website/tests/clan-faith-fixture.mjs | 15 +++ website/tests/clan-faith.test.mjs | 30 +++++ website/tests/faith-mission-rewards.test.mjs | 27 +++++ .../tests/organisation-quest-grants.test.mjs | 9 ++ website/tests/organisation-research.test.mjs | 22 +++- website/tests/progression-design.test.mjs | 2 +- 32 files changed, 503 insertions(+), 22 deletions(-) create mode 100644 website/control-panel/public/clan-faith-policy.mjs create mode 100644 website/control-panel/public/cp-v2/cp-v2-clan-faith.mjs create mode 100644 website/control-panel/public/cp-v2/cp-v2-faith-quests.mjs create mode 100644 website/node/clan-faith.mjs create mode 100644 website/node/faith-quest-evidence.mjs create mode 100644 website/node/organisation-quest-payments.mjs create mode 100644 website/node/organisation-quest-rewards.mjs create mode 100644 website/scripts/organisation-quest-grants.mjs create mode 100644 website/tests/clan-faith-fixture.mjs create mode 100644 website/tests/clan-faith.test.mjs create mode 100644 website/tests/faith-mission-rewards.test.mjs create mode 100644 website/tests/organisation-quest-grants.test.mjs diff --git a/website/control-panel/public/clan-deed-settings.mjs b/website/control-panel/public/clan-deed-settings.mjs index d65f75e6..89a8fe99 100644 --- a/website/control-panel/public/clan-deed-settings.mjs +++ b/website/control-panel/public/clan-deed-settings.mjs @@ -1,3 +1,4 @@ +import {mountClanFaithConsent} from './cp-v2/cp-v2-clan-faith.mjs'; import {createDeedCard} from './clan-dynasty.mjs';import {formatDuneDate} from './dune-date.mjs'; const el=(tag,text)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;return n;}; export function mountClanDeedSettings(host,clan){ @@ -6,5 +7,5 @@ export function mountClanDeedSettings(host,clan){ async function load(){try{data=await request();content.replaceChildren(createDeedCard({clan,deed:data.deed,titles:clan.titles||{},established:formatDuneDate(clan.created_at)}));const page=el('a','Open public clan page ↗');page.href='https://www.dunerealms.com/clans/'+encodeURIComponent(clan.tag);page.target='_blank';page.rel='noopener';content.append(page);for(const role of ['heir','consort','arms','envoy'].filter(role=>['arms','envoy'].includes(role)?data.canAppointArms:data.canAppoint)){ const form=el('form'),label=el('label',role==='envoy'?'Imperial Envoy':role==='arms'?(clan.titles?.arms||'Master-at-Arms'):role==='heir'?'Heir / successor':'Consort'),select=el('select'),empty=el('option','Not appointed');empty.value='';select.append(empty);select.setAttribute('aria-label','Appoint '+(role==='envoy'?'Imperial Envoy':role==='arms'?(clan.titles?.arms||'Master-at-Arms'):role));for(const p of (role==='consort'?data.consortCandidates:data.candidates)){const o=el('option',p.username.replace(/_+/g,' '));o.value=p.username;select.append(o);}select.value=data.deed[role]?.username||'';label.append(select);const check=el('input');check.type='checkbox';const consent=el('label',role==='envoy'?' I confirm this clan-election appointment. Personal voting rights and ownership are not delegated.':role==='arms'?' I confirm this kit and warfare appointment. It grants no ownership, banking or succession rights.':role==='heir'?' I confirm that the Heir receives the same clan management rights as the Ruler.':' I confirm this honorary appointment. It grants no extra management rights.');consent.prepend(check);const button=el('button','Save '+(role==='envoy'?'Imperial Envoy':role==='arms'?(clan.titles?.arms||'Master-at-Arms'):role==='heir'?'Heir':'Consort'));form.className='clan-appointment-form';consent.className='clan-appointment-consent';const consentText=el('span',consent.textContent);consent.replaceChildren(check,consentText);button.type='submit';button.disabled=true;check.onchange=()=>button.disabled=busy||!check.checked||role==='heir'&&!data.canAppointHeir;select.onchange=()=>{check.checked=false;button.disabled=true;};form.append(label,consent,button);if(role==='heir'&&!data.canAppointHeir)form.append(el('p','A Keyed or Royal charter unlocks the Heir appointment.'));form.onsubmit=async e=>{e.preventDefault();if(busy||!check.checked)return;busy=true;button.disabled=true;try{await request({role,candidate:select.value||null,version:data.deed.version,confirmed:true});await load();status.textContent='Dynastic appointment saved. Members and their ordinary ranks are unchanged.';}catch(error){status.textContent=error.message;}finally{busy=false;}};content.append(form); }status.textContent='Ruler follows the registered owner. Heir and Consort are separate dynastic appointments.';}catch(error){status.textContent=error.message;}} - void load();return content; + const faith=el('section');faith.className='politics-card';host.append(faith);mountClanFaithConsent(faith,clan.id);void load();return content; } diff --git a/website/control-panel/public/clan-faith-policy.mjs b/website/control-panel/public/clan-faith-policy.mjs new file mode 100644 index 00000000..01b8a8ae --- /dev/null +++ b/website/control-panel/public/clan-faith-policy.mjs @@ -0,0 +1,6 @@ +export const CLAN_FAITH_POLICY=Object.freeze({version:1,offerDurationMs:72*3600000,officeCooldownMs:86400000,clanCooldownMs:7*86400000,conversionGoals:Object.freeze([1,3,5])}); +export const CLAN_FAITH_DECISIONS=Object.freeze([ + {id:'BG-CONVERT',office:'veiled_concord',title:'Missionaria Protectiva',faith:'veiled_concord',name:'Old Faith'}, + {id:'NF-CONVERT',office:'muad_dib',title:'Spread the Word of Muad’Dib',faith:'muad_dib',name:'New Faith'} +].map(d=>Object.freeze({...d,level:5,xp:0,cooldownMs:CLAN_FAITH_POLICY.officeCooldownMs,effect:'Invite one clan to '+d.name+'. Its legal owner must consent within 72 hours. One faith per clan; seven days between changes. No ownership, vote or bank rights are transferred.'}))); +export const clanFaithDecision=id=>CLAN_FAITH_DECISIONS.find(d=>d.id===id)||null; diff --git a/website/control-panel/public/cp-v2/cp-v2-clan-faith.mjs b/website/control-panel/public/cp-v2/cp-v2-clan-faith.mjs new file mode 100644 index 00000000..e01cbdce --- /dev/null +++ b/website/control-panel/public/cp-v2/cp-v2-clan-faith.mjs @@ -0,0 +1,22 @@ +import {element as el} from './cp-v2-page-template.mjs'; +import {createUserAPI} from './cp-v2-user-api.mjs'; +import {CLAN_FAITH_DECISIONS} from '../clan-faith-policy.mjs'; +const name=office=>CLAN_FAITH_DECISIONS.find(d=>d.office===office)?.name||'No faith chosen'; +export function mountFaithInvitation(host,office,{fetcher=fetch}={}){ + const api=createUserAPI(fetcher),endpoint='/api/politics/faith',d=CLAN_FAITH_DECISIONS.find(d=>d.office===office);if(!d)return; + const status=el('p','Reading faith authority…'),label=el('label','Clan'),select=el('select'),review=el('p'),prepare=el('button','Review invitation'),confirm=el('button','Send invitation'),cancel=el('button','Cancel'),history=el('div');status.setAttribute('role','status');label.append(select);confirm.hidden=cancel.hidden=true;for(const b of [prepare,confirm,cancel])b.type='button';host.append(status,label,review,prepare,confirm,cancel,history); + let current=null,pending=null,busy=false; + function controls(){select.disabled=busy||!!pending||!current?.canManage;prepare.disabled=busy||!!pending||!current?.canExecute||!select.value;confirm.disabled=cancel.disabled=busy;} + async function load(){busy=true;controls();try{const data=await api.request(endpoint+'?office='+encodeURIComponent(office));if(!host.isConnected)return;current=data;const chosen=select.value;select.replaceChildren();for(const c of data.clans){const option=el('option',c.name);option.value=c.id;select.append(option);}if(data.clans.some(c=>c.id===chosen))select.value=chosen;status.textContent=(data.canManage?'Current faith mandate verified.':'A current faith leader or appointed officer is required.')+' Reputation '+data.levelNow+'/5. '+(data.cooldownUntil>Date.now()?'Next invitation: '+new Date(data.cooldownUntil).toLocaleString()+'.':'One invitation per day.');history.replaceChildren(el('h4','Recent invitations'));for(const offer of data.offers.slice(0,10)){const clan=data.clans.find(c=>c.id===offer.clan_id),expired=Number(offer.expires_at)<=Date.now()&&offer.state==='open';history.append(el('p',(clan?.name||'Clan')+' · '+(expired?'expired':offer.state)+' · '+new Date(Number(offer.expires_at)).toLocaleString()));}}catch(e){status.textContent=e.message;}finally{busy=false;controls();}} + prepare.onclick=()=>{pending={action:'offer',decisionId:d.id,clanId:select.value,requestId:crypto.randomUUID(),confirmed:true};review.textContent='Invite '+select.selectedOptions[0].textContent+' to '+d.name+'. The clan owner has 72 hours to accept in clan settings. No change takes effect without consent.';confirm.hidden=cancel.hidden=false;controls();}; + cancel.onclick=()=>{pending=null;confirm.hidden=cancel.hidden=true;review.textContent='';controls();}; + confirm.onclick=async()=>{if(!pending||busy)return;busy=true;controls();try{await api.request(endpoint,pending);pending=null;confirm.hidden=cancel.hidden=true;review.textContent='Invitation recorded. The clan owner decides whether to accept.';}catch(e){review.textContent=e.message+(e.uncertain?' Retry this same confirmation to check its result.':'');if(!e.uncertain){pending=null;confirm.hidden=cancel.hidden=true;}}finally{busy=false;await load();}}; + select.onchange=controls;load(); +} +export function mountClanFaithConsent(host,clanId,{fetcher=fetch}={}){ + const api=createUserAPI(fetcher),endpoint='/api/politics/faith',status=el('p','Reading clan faith…'),offers=el('div'),review=el('p'),confirm=el('button','Confirm clan choice'),cancel=el('button','Cancel');status.setAttribute('role','status');confirm.hidden=cancel.hidden=true;for(const b of [confirm,cancel])b.type='button';host.append(el('h3','Clan faith'),status,offers,review,confirm,cancel);let pending=null,busy=false; + function controls(){for(const b of offers.querySelectorAll('button'))b.disabled=busy||!!pending;confirm.disabled=cancel.disabled=busy;} + async function load(){busy=true;controls();try{const data=await api.request(endpoint+'?clanId='+encodeURIComponent(clanId));if(!host.isConnected)return;status.textContent=name(data.faith)+'. '+(data.canManage?'Only you, as the legal clan owner, can accept a change.':'The legal clan owner decides faith changes.')+(data.cooldownUntil>Date.now()?' A new faith can be accepted after '+new Date(data.cooldownUntil).toLocaleString()+'.':'');offers.replaceChildren();for(const offer of data.offers){const row=el('section');row.append(el('strong','Invitation to '+name(offer.office_key)),el('p','Expires '+new Date(Number(offer.expires_at)).toLocaleString()));for(const choice of ['accept','decline']){const b=el('button',choice==='accept'?'Review acceptance':'Review decline');b.type='button';b.onclick=()=>{pending={action:'reply',offerId:offer.request_id,choice,clanId,requestId:crypto.randomUUID(),confirmed:true};review.textContent=choice==='accept'?'Choose '+name(offer.office_key)+' as this clan’s only faith. The next change will be available after seven days.':'Decline this invitation and keep the clan’s current faith.';confirm.hidden=cancel.hidden=false;controls();};row.append(b);}offers.append(row);}if(!data.offers.length)offers.append(el('p','No outstanding faith invitations.'));}catch(e){status.textContent=e.message;}finally{busy=false;controls();}} + cancel.onclick=()=>{pending=null;confirm.hidden=cancel.hidden=true;review.textContent='';controls();}; + confirm.onclick=async()=>{if(!pending||busy)return;busy=true;controls();try{await api.request(endpoint,pending);pending=null;confirm.hidden=cancel.hidden=true;review.textContent='Clan choice recorded.';}catch(e){review.textContent=e.message+(e.uncertain?' Retry this same confirmation to check its result.':'');if(!e.uncertain){pending=null;confirm.hidden=cancel.hidden=true;}}finally{busy=false;await load();}};load(); +} diff --git a/website/control-panel/public/cp-v2/cp-v2-decision-audit.mjs b/website/control-panel/public/cp-v2/cp-v2-decision-audit.mjs index 04f5c0f3..2a7daa2f 100644 --- a/website/control-panel/public/cp-v2/cp-v2-decision-audit.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-decision-audit.mjs @@ -1,3 +1,4 @@ +import {clanFaithDecision} from '../clan-faith-policy.mjs'; import {tradeDecision} from '../world-trade-policy.mjs'; import {politicalDecision} from '../political-decision-policy.mjs'; import {faithBlessing} from '../faith-blessing-policy.mjs'; @@ -8,5 +9,5 @@ const related={ 'FRE-01':{adapter:'createNaibCouncil',gap:'The independent Council vote already enforces current sietch deed, one vote per sietch, 24 hours, quorum and tie rejection. The v2.2 1,000 DM fee and quest XP award are not enabled.'} }; const authority={IMP:'Current Emperor deed',ATR:'Current Aerdrecht House office deed',HAR:'Current Harkveen House office deed',COR:'Current Korenholt House office deed',ORD:'Current Oordwijk House office deed',FRE:'Current recognised sietch deed; independent Council',BG:'Current Veiled Concord office deed',SG:'Current Spacing Guild office deed',CLD:'Current clan delegate deed'}; -export const DECISION_AUDIT=Object.freeze(DECISION_CATALOGUE.map(d=>Object.freeze({id:d.id,office:d.office,status:tradeDecision(d.id)||politicalDecision(d.id)||d.id==='IMP-10'||faithBlessing(d.id)?'active':'design',currency:'DM',amountConversion:1,authority:authority[d.office],conditions:'Current unexpired and unrevoked deed, eligible target and all stated effect conditions must be checked by the domain consumer. Level and XP do not grant office authority.',costCooldown:d.cost,effect:d.effect,level:d.level,proposedXP:d.xp,adapter:tradeDecision(d.id)?'createWorldTradeGovernance / createGameExchangeService / createGuildService':politicalDecision(d.id)?'createPoliticalDecisions':faithBlessing(d.id)?'createFaithBlessings / faithAward':d.id==='IMP-10'?'createImperialPassage / createGuildService':related[d.id]?.adapter||null,gap:tradeDecision(d.id)?'Current Royal office and Reputation, immutable creation-world metadata, seven-day cooldown, retained stock and atomic seller-funded bank levy; no default activation.':politicalDecision(d.id)?'Current office, Reputation, authorised office funding and successor-safe cooldown checked atomically; existing publication/profile consumers display the result.':faithBlessing(d.id)?'Current Doci/Prior deed, target clan, expiry and cooldown are checked centrally; bonuses use funded quest consumers.':d.id==='IMP-10'?'Native House selection replaces the prior grant; seven-day office cooldown and current Emperor deed are checked centrally.':related[d.id]?.gap||'No complete registered domain consumer implements this exact target, price, cooldown, duration and effect. Execution remains unavailable.',repeatability:'Only after the stated cooldown; no implied stacking or automatic renewal.',executionEnabled:!!tradeDecision(d.id)||!!politicalDecision(d.id)||d.id==='IMP-10'||!!faithBlessing(d.id)}))); +export const DECISION_AUDIT=Object.freeze(DECISION_CATALOGUE.map(d=>Object.freeze({id:d.id,office:d.office,status:clanFaithDecision(d.id)||tradeDecision(d.id)||politicalDecision(d.id)||d.id==='IMP-10'||faithBlessing(d.id)?'active':'design',currency:'DM',amountConversion:1,authority:authority[d.office],conditions:'Current unexpired and unrevoked deed, eligible target and all stated effect conditions must be checked by the domain consumer. Level and XP do not grant office authority.',costCooldown:d.cost,effect:d.effect,level:d.level,proposedXP:d.xp,adapter:clanFaithDecision(d.id)?'createClanFaith.offer / reply':tradeDecision(d.id)?'createWorldTradeGovernance / createGameExchangeService / createGuildService':politicalDecision(d.id)?'createPoliticalDecisions':faithBlessing(d.id)?'createFaithBlessings / faithAward':d.id==='IMP-10'?'createImperialPassage / createGuildService':related[d.id]?.adapter||null,gap:clanFaithDecision(d.id)?'Current faith officer can invite; only the receiving clan’s legal owner can consent. Daily invitation and seven-day clan-change cooldowns are enforced; no membership or rights move.':tradeDecision(d.id)?'Current Royal office and Reputation, immutable creation-world metadata, seven-day cooldown, retained stock and atomic seller-funded bank levy; no default activation.':politicalDecision(d.id)?'Current office, Reputation, authorised office funding and successor-safe cooldown checked atomically; existing publication/profile consumers display the result.':faithBlessing(d.id)?'Current Doci/Prior deed, target clan, expiry and cooldown are checked centrally; bonuses use funded quest consumers.':d.id==='IMP-10'?'Native House selection replaces the prior grant; seven-day office cooldown and current Emperor deed are checked centrally.':related[d.id]?.gap||'No complete registered domain consumer implements this exact target, price, cooldown, duration and effect. Execution remains unavailable.',repeatability:'Only after the stated cooldown; no implied stacking or automatic renewal.',executionEnabled:!!clanFaithDecision(d.id)||!!tradeDecision(d.id)||!!politicalDecision(d.id)||d.id==='IMP-10'||!!faithBlessing(d.id)}))); export const decisionAudit=id=>DECISION_AUDIT.find(row=>row.id===id)||null; diff --git a/website/control-panel/public/cp-v2/cp-v2-faith-quests.mjs b/website/control-panel/public/cp-v2/cp-v2-faith-quests.mjs new file mode 100644 index 00000000..4daa5403 --- /dev/null +++ b/website/control-panel/public/cp-v2/cp-v2-faith-quests.mjs @@ -0,0 +1,6 @@ +const paths=[{id:'faith-sisterhood',office:'BG',faith:'veiled_concord',title:'Missionaria Protectiva',issuer:'jessica_atreides',issuerName:'Lady Jessica',theme:'The Old Faith · consenting clan communities'},{id:'faith-church',office:'NF',faith:'muad_dib',title:'The Word of Muad’Dib',issuer:'stilgar',issuerName:'Stilgar',theme:'The New Faith · consenting clan communities'}]; +export const FAITH_QUEST_BRANCHES=Object.freeze(paths.map(path=>Object.freeze({...path,xpType:'pol',quests:Object.freeze([1,3,5].map((target,index)=>{ + const id='POL-FAITH-'+(path.faith==='muad_dib'?'CHURCH':'SISTERHOOD')+'-0'+(index+1),xp=[150,250,400][index],personalXP=[20,30,50][index],amountMinor=[12500,20000,35000][index]; + return Object.freeze({id,xpType:'pol',title:['A Willing Community','A Growing Congregation','A Living Tradition'][index],objective:'As a current faith leader or officer, invite clans through the faith decision. Their legal owners must accept. Have '+target+' distinct active clan'+(target===1?'':'s')+' currently following this faith. Repeated invitations and declined offers do not count. Reward: '+xp+' Reputation points, '+personalXP+' Personal XP and '+amountMinor/100+' DM to this faith’s organisation account.',metric:'pol-faith-'+path.faith+'-conversions',target,requires:index?['POL-FAITH-'+(path.faith==='muad_dib'?'CHURCH':'SISTERHOOD')+'-0'+index]:[],requiresAny:[],branch:path.id,season:'S01',revision:1,optional:false,verifiedOnly:true,faithMission:true,faith:path.faith,owner:Object.freeze({kind:'office',id:path.faith}),xp,personalXP,amountMinor}); + }))}))); +export function faithQuestInitialReward(d){return d.faithMission?{schema:'pol-organisation-reward-v1',owner:d.owner,amountMinor:d.amountMinor,personalXP:d.personalXP}:null;} diff --git a/website/control-panel/public/cp-v2/cp-v2-pol-quest-catalogue.mjs b/website/control-panel/public/cp-v2/cp-v2-pol-quest-catalogue.mjs index 24e5bec1..31556015 100644 --- a/website/control-panel/public/cp-v2/cp-v2-pol-quest-catalogue.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-pol-quest-catalogue.mjs @@ -1,3 +1,4 @@ +import {FAITH_QUEST_BRANCHES} from './cp-v2-faith-quests.mjs'; import {ELYTRA_BRANCH} from './cp-v2-elytra-quests.mjs'; import {WAR_QUEST_BRANCH} from './cp-v2-war-quests.mjs'; // Server-owned content shared with the existing quest and POL Decision interfaces. @@ -1099,6 +1100,7 @@ export const POL_QUEST_BRANCHES=freeze([ } ] }, + ...FAITH_QUEST_BRANCHES, ELYTRA_BRANCH, WAR_QUEST_BRANCH ]); diff --git a/website/control-panel/public/cp-v2/cp-v2-progression-catalogue.mjs b/website/control-panel/public/cp-v2/cp-v2-progression-catalogue.mjs index 8f7fa14e..847663f2 100644 --- a/website/control-panel/public/cp-v2/cp-v2-progression-catalogue.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-progression-catalogue.mjs @@ -1,3 +1,4 @@ +import {CLAN_FAITH_DECISIONS} from '../clan-faith-policy.mjs'; import {TRADE_DECISIONS} from '../world-trade-policy.mjs'; import {decisionCooldownMs} from '../action-cooldown-policy.mjs'; import {IMPERIAL_PASSAGE_DECISION} from '../imperial-passage-policy.mjs'; @@ -946,4 +947,4 @@ export const DECISION_CATALOGUE=[ "cost": "2,500 / 72h", "office": "CLD" } -,...TRADE_DECISIONS.map(d=>({...d,office:({atreides:'ATR',harkonnen:'HAR',corrino:'COR',ordos:'ORD',fremen:'FRE',spacing_guild:'SG'})[d.office],xp:0,cost:'0 / 7d',xpType:'pol',executionStatus:'world-trade-controller'}))].flatMap(decision=>decision.office==='BG'?[decision,{...decision,id:decision.id.replace('BG-','NF-'),office:'NF',copiedFrom:decision.id,title:decision.title.replaceAll('Sisterhood','Church'),effect:decision.effect.replaceAll('Sisterhood','Church')}]:[decision]).map(decision=>Object.freeze({...decision,cooldownMs:decisionCooldownMs(decision)})); +,...TRADE_DECISIONS.map(d=>({...d,office:({atreides:'ATR',harkonnen:'HAR',corrino:'COR',ordos:'ORD',fremen:'FRE',spacing_guild:'SG'})[d.office],xp:0,cost:'0 / 7d',xpType:'pol',executionStatus:'world-trade-controller'}))].flatMap(decision=>decision.office==='BG'&&decision.id!=='BG-01'?[decision,{...decision,id:decision.id.replace('BG-','NF-'),office:'NF',copiedFrom:decision.id,title:decision.title.replaceAll('Sisterhood','Church'),effect:decision.effect.replaceAll('Sisterhood','Church')}]:[decision]).concat(CLAN_FAITH_DECISIONS.map(d=>({...d,office:d.office==='muad_dib'?'NF':'BG',cost:'0 / 24h',xpType:'pol',executionStatus:'clan-faith-controller'}))).map(decision=>Object.freeze({...decision,cooldownMs:decisionCooldownMs(decision)})); diff --git a/website/control-panel/public/cp-v2/cp-v2-progression.mjs b/website/control-panel/public/cp-v2/cp-v2-progression.mjs index bcd07fda..a4090f7a 100644 --- a/website/control-panel/public/cp-v2/cp-v2-progression.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-progression.mjs @@ -1,3 +1,4 @@ +import {mountFaithInvitation} from './cp-v2-clan-faith.mjs'; import {mountWorldTrade} from './cp-v2-world-trade.mjs'; import {appendOfficeMissionPreview,appendOfficeMissionBanner,appendOfficeDecisionBanner,planningImage} from './cp-v2-war-planning.mjs'; import {POL_PLANNING_ART,officeDecisionPreviews} from './cp-v2-war-planning-content.mjs'; @@ -40,6 +41,7 @@ export function mountProgressionDesign(host,{context='personal',dashboard=false, function details(row,isDecision=false){const pane=el('aside',undefined,'progression-detail');pane.setAttribute('aria-label','Selected '+(isDecision?'decision':'mission'));pane.append(image(isDecision?(POL_PLANNING_ART[officeCode]?.banner||'exchange-political-positions-v1.png'):artFor(branch)),el('small',row.id),el('h3',lore(row.title)),el('p',isDecision?lore(row.effect):row.title==='Repair Your Starter Kit'?'Collect four repair components and surrender the damaged Q0 kit to receive one intact kit.':'Complete the verified objective. Conditions and progress will be supplied by J.A.R.V.I.S.')); if(isDecision&&['NF-08','NF-09','NF-10'].includes(row.id)){mountFaithBlessing(pane,row.id);return pane;} if(isDecision&&politicalDecision(row.id)){mountPoliticalDecision(pane,row.id);return pane;} + if(isDecision&&row.executionStatus==='clan-faith-controller'){mountFaithInvitation(pane,row.office==='NF'?'muad_dib':'veiled_concord');return pane;} if(isDecision&&row.executionStatus==='world-trade-controller'){mountWorldTrade(pane,row.id);return pane;} if(isDecision&&row.id==='IMP-10'){mountImperialPassage(pane);return pane;} if(isDecision&&row.executionStatus==='war-exchange-controller'){const link=el('a','Open War Exchange →');link.href='#household/war-exchange';pane.append(el('p','Current organisation authority is checked on every action. Both organisations approve alliances; all sides must choose the same hour. Changes clear previous calendar consent. No DM or XP is awarded for a proposal.'),link);return pane;} @@ -58,7 +60,7 @@ export function mountProgressionDesign(host,{context='personal',dashboard=false, connectorObserver=new ResizeObserver(connect);connectorObserver.observe(tree);requestAnimationFrame(connect); } function renderDecisions(){if(activeContext==='politics')appendOfficeDecisionBanner(content,officeCode);if(activeContext==='politics'&&!manage){const live=el('div');content.append(live);disposePersonal=mountOfficeRebellionDecisions(live,{officeKey:organisation?.id||({IMP:'emperor',ATR:'atreides',HAR:'harkonnen',COR:'corrino',ORD:'ordos',FRE:'fremen',BG:'veiled_concord',NF:'muad_dib',SG:'spacing_guild',CLD:'clan_delegate'})[officeCode]});}const toolbar=el('div',undefined,'progression-toolbar'),search=el('input');search.type='search';search.placeholder='Search decisions';search.setAttribute('aria-label','Search decisions');search.value=query;search.oninput=()=>{query=search.value;renderDecisionsList();};toolbar.append(search);if(activeContext==='personal'&&xpKind==='pol'){const chooser=field('Questgiver',POL_QUEST_BRANCHES.map(b=>b.title));chooser.querySelector('select').selectedIndex=POL_QUEST_BRANCHES.findIndex(b=>b.id===polDecisionBranch);chooser.onchange=e=>{polDecisionBranch=POL_QUEST_BRANCHES[e.target.selectedIndex].id;selected=null;render();};toolbar.append(chooser);}if((dashboard&&activeContext==='politics')||manage){const chooser=field('Office catalogue',OFFICES.map(([,name])=>name));chooser.querySelector('select').selectedIndex=OFFICES.findIndex(([id])=>id===officeCode);chooser.onchange=e=>{officeCode=OFFICES[e.target.selectedIndex][0];selected=null;render();};toolbar.append(chooser);}content.append(toolbar);const listHost=el('div');content.append(listHost); - function renderDecisionsList(){listHost.replaceChildren();let rows=activeContext==='politics'||manage?[...DECISION_CATALOGUE.filter(d=>d.office===officeCode),...officeDecisionPreviews(officeCode)]:activeContext==='personal'&&xpKind==='pol'?(POL_QUEST_BRANCHES.find(b=>b.id===polDecisionBranch)?.decisions||[]):activeContext==='personal'?[{id:'P-MARK',title:'Equipment Mark eligibility',effect:'Level, materials and equipment restrictions remain necessary.',level:0,xp:0,cost:'Pending configuration'},{id:'P-RARITY',title:'Rarity enhancement eligibility',effect:'Use the existing rarity and Legendary upgrade policy.',level:0,xp:0,cost:'Pending configuration'},{id:'P-SEASON',title:'Seasonal completion entitlement',effect:'One non-tradable completion kit after all mandatory objectives.',level:0,xp:0,cost:'Earned entitlement'}]:[];rows=rows.filter(r=>(r.title+' '+r.effect).toLowerCase().includes(query.toLowerCase()));if(!rows.length){listHost.append(el('p','No decision definitions available for this selection. No authority is inferred.'));return;}selected=rows.find(r=>r.id===selected)?.id||rows[0].id;const layout=el('div',undefined,'progression-layout'),cards=el('div',undefined,'progression-decisions');for(const row of rows){const card=button('',()=>{selected=row.id;dossier.show(details(row,true),{title:lore(row.title),returnFocus:card});},'progression-decision');card.setAttribute('aria-haspopup','dialog');card.setAttribute('aria-pressed',String(row.id===selected));const art=activeContext==='politics'?POL_PLANNING_ART[officeCode]:activeContext==='personal'&&xpKind==='pol'?POL_PLANNING_ART[POL_QUEST_BRANCHES.find(b=>b.id===polDecisionBranch)?.office]:null;card.append(image(art?.banner||'exchange-political-positions-v1.png'),...(art?[planningImage(art.seal,art.title+' seal','pol-decision-seal')]:[]),el('small',row.id),el('strong',row.title),el('span',row.executionStatus==='world-trade-controller'?'Review trade decision':politicalDecision(row.id)?'Review funded decision':row.id==='IMP-10'?'Manage House passage':['NF-08','NF-09','NF-10'].includes(row.id)?'Prepare clan blessing':row.executionStatus==='war-exchange-controller'?'Manage war agreement':'View proposal · execution unavailable'));cards.append(card);}layout.append(cards);listHost.append(layout);}renderDecisionsList(); + function renderDecisionsList(){listHost.replaceChildren();let rows=activeContext==='politics'||manage?[...DECISION_CATALOGUE.filter(d=>d.office===officeCode),...officeDecisionPreviews(officeCode)]:activeContext==='personal'&&xpKind==='pol'?(POL_QUEST_BRANCHES.find(b=>b.id===polDecisionBranch)?.decisions||[]):activeContext==='personal'?[{id:'P-MARK',title:'Equipment Mark eligibility',effect:'Level, materials and equipment restrictions remain necessary.',level:0,xp:0,cost:'Pending configuration'},{id:'P-RARITY',title:'Rarity enhancement eligibility',effect:'Use the existing rarity and Legendary upgrade policy.',level:0,xp:0,cost:'Pending configuration'},{id:'P-SEASON',title:'Seasonal completion entitlement',effect:'One non-tradable completion kit after all mandatory objectives.',level:0,xp:0,cost:'Earned entitlement'}]:[];rows=rows.filter(r=>(r.title+' '+r.effect).toLowerCase().includes(query.toLowerCase()));if(!rows.length){listHost.append(el('p','No decision definitions available for this selection. No authority is inferred.'));return;}selected=rows.find(r=>r.id===selected)?.id||rows[0].id;const layout=el('div',undefined,'progression-layout'),cards=el('div',undefined,'progression-decisions');for(const row of rows){const card=button('',()=>{selected=row.id;dossier.show(details(row,true),{title:lore(row.title),returnFocus:card});},'progression-decision');card.setAttribute('aria-haspopup','dialog');card.setAttribute('aria-pressed',String(row.id===selected));const art=activeContext==='politics'?POL_PLANNING_ART[officeCode]:activeContext==='personal'&&xpKind==='pol'?POL_PLANNING_ART[POL_QUEST_BRANCHES.find(b=>b.id===polDecisionBranch)?.office]:null;card.append(image(art?.banner||'exchange-political-positions-v1.png'),...(art?[planningImage(art.seal,art.title+' seal','pol-decision-seal')]:[]),el('small',row.id),el('strong',row.title),el('span',row.executionStatus==='clan-faith-controller'?'Invite a clan':row.executionStatus==='world-trade-controller'?'Review trade decision':politicalDecision(row.id)?'Review funded decision':row.id==='IMP-10'?'Manage House passage':['NF-08','NF-09','NF-10'].includes(row.id)?'Prepare clan blessing':row.executionStatus==='war-exchange-controller'?'Manage war agreement':'View proposal · execution unavailable'));cards.append(card);}layout.append(cards);listHost.append(layout);}renderDecisionsList(); } function render(){dossier.close();connectorObserver?.disconnect();disposePersonal?.();disposePersonal=null;notice.textContent=activeContext==='personal'&&!manage?(xpKind==='pol'?'Reputation missions use verified J.A.R.V.I.S. records and their system questgivers. Decision execution awaits configuration.':'Personal missions use verified J.A.R.V.I.S. records. Decision and organisation integrations remain in preview.'):'Connected decisions open a review and confirmation. Other proposals remain unavailable until their consumers are connected.';root.dataset.context=activeContext;notice.hidden=activeContext==='personal'&&!manage;nav.hidden=report.available&&activeContext==='personal'&&!manage;report.setNavigation(xpKind,tab);report.showBranches(activeContext==='personal');xpNav.replaceChildren();xpNav.hidden=activeContext!=='personal'||manage||report.available;if(!xpNav.hidden)for(const [kind,label]of [['personal','Personal level'],['pol','Reputation level']]){const b=button(label,()=>{xpKind=kind;selected=null;render();});b.setAttribute('aria-pressed',String(kind===xpKind));xpNav.append(b);}contextNav.replaceChildren();for(const[id,[label]]of Object.entries(CONTEXTS)){const b=button(label,()=>{activeContext=id;selected=null;query='';render();});b.setAttribute('aria-pressed',String(id===activeContext));contextNav.append(b);}renderGallery();nav.replaceChildren();for(const[id,label]of [['missions',manage?'Mission Definitions':'Missions'],['decisions',manage?'Decision Definitions':'Decisions'],...(manage?[['rewards','Progression & Rewards']]:[]),['history','History']]){const b=button(label,()=>{tab=id;selected=null;render();});b.setAttribute('aria-pressed',String(tab===id));nav.append(b);}content.replaceChildren();if(activeContext==='clan'&&!manage){notice.hidden=true;disposePersonal=mountClanRebellions(content,{clanId:organisation?.id||null,embedded:true,view:tab,onDecisions:()=>{tab='decisions';render();}});return;}if(activeContext==='personal'&&!manage&&['missions','history'].includes(tab))disposePersonal=mountPersonalProgression(content,{view:tab,apiBase:xpKind==='pol'?'/api/progression/pol':'/api/progression',externalBranches:report.available,initialBranch:branch,onData:data=>report.setJournal(xpKind,data),onBranches:(rows,id)=>{branch=id;report.setBranches(rows,id);}});else if(tab==='missions')renderMissions();else if(tab==='decisions')renderDecisions();else if(tab==='rewards'){content.append(el('h3','Progression & Rewards'),field('Season cap',['70 · proposed']),field('Milestone announcements',['Halfway and completion only']),el('p','Rewards, XP curves, repair recipes and signing editions await backend review. No configuration writes enabled.'));}else content.append(el('h3','J.A.R.V.I.S. History'),el('p','Verified completion, claims, decisions and any staff overrides will appear here after integration. No sample audit records are shown.'));} render();return()=>{dossier.dispose();connectorObserver?.disconnect();disposePersonal?.();report.dispose();root.remove();}; diff --git a/website/control-panel/public/jarvis-master-keys.mjs b/website/control-panel/public/jarvis-master-keys.mjs index 7632dedb..26579d8f 100644 --- a/website/control-panel/public/jarvis-master-keys.mjs +++ b/website/control-panel/public/jarvis-master-keys.mjs @@ -14,6 +14,9 @@ export const MASTER_KEY_TEMPLATES=[ action('company.subsidiary','Subsidiary founding','company-subsidiary',[field('parentCompanyId','Mother company'),field('recipient','Recipient')]), action('company.royal','Royal company charter','staff-company-royal',[field('companyId','Company'),reference])]}, {id:'politics',label:'POL & orders',actions:[ + action('faith.invitation','Invite a clan to a faith','entity-state',[field('decisionId','Faith decision','select',{options:['BG-CONVERT','NF-CONVERT']}),field('clanId','Active clan UUID'),field('requestId','Invitation UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createClanFaith.offer',executionStatus:'current-faith-officer-service',effect:'Current Royal faith leader or canonical appointed officer, Reputation 5, one invitation per office per 24 hours. Signed offer expires after 72 hours. It changes no clan faith, membership, owner, vote or account. Target-clan owner must separately consent; missionary laws are checked again on acceptance.'}), + action('progression.faith-service-policy','Consenting faith community quest policy','progression-policy',[],{version:6,webIssue:false,recordOnly:true,domainAdapter:'ensureFaithQuestPolicy/faithQuestEvidence',executionStatus:'verified-consent-evidence-consumer',effect:'Install six Old Faith and New Faith Reputation quests through policy:POL:S01:v6. Count one, three and five distinct currently consenting active clans invited by the current authorised faith specialist. Re-read the signed invitation and legal-owner consent, current faith and current authority at claim. Small separate Personal XP rewards; fixed DM queued from P&O to the faith office payment account. New research payments use the same transaction and Basic organisations route to the current legal owner; legacy payment receipts remain unchanged.'}), + action('faith.clan-consent','Clan owner faith decision','entity-state',[field('clanId','Current clan UUID'),field('offerId','Sealed invitation UUID'),field('choice','Clan choice','select',{options:['accept','decline']}),field('requestId','Consent UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createClanFaith.reply',executionStatus:'current-legal-clan-owner-only',effect:'Re-read the current clan deed, signed invitation and current faith mandate. Accepting records the clan’s single faith and a seven-day change cooldown. Declining leaves allegiance unchanged. Immutable owner consent, key, offer and faith update commit together; revoking the latest receipt never revives an older faith. No personal voting, membership, bank or ownership change.'}), action('politics.world-trade','House levy or Guild embargo','entity-state',[field('decisionId','Registered trade decision'),field('requestId','Request UUID'),field('percent','House levy 0–5%','number',{required:false}),field('world','Embargo world','select',{required:false,options:['arrakis','caladan','giedi_prime','kaitain','sigma_draconis_iv']})],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createWorldTradeGovernance',executionStatus:'authenticated-office-trade-consumer',effect:'Current Royal elected House/Guild authority and Reputation checked again under transaction locks. House levy 1–5% (0 repeals), seven-day successor-safe cooldown. Guild embargo one world for 24h, seven-day global cooldown. Read creation PDC only; never infer from listing location or lore. No default activation, XP or balance issuance. Exchange stock is preserved, owned withdrawals and committed deliveries remain available. Seller tax and gross purchase settle with stock and exact native delivery on one bank transaction; immutable receipts prevent repeated levy.'}), action('politics.ceremonial-decision','Funded political publication or recognition','entity-state',[field('decisionId','Registered decision','select',{options:['IMP-04','IMP-09','ATR-03','COR-03']}),field('sourceAccount','Authorised office funding account'),field('requestId','Request UUID'),field('title','Proclamation title','text',{required:false}),field('body','Proclamation message','textarea',{required:false}),field('recipientId','Honour recipient','text',{required:false}),field('citation','Honour citation','textarea',{required:false})],{webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute',executionStatus:'current-elected-office-only',effect:'Atomic office-account charge, fixed Reputation XP, ordinary system ESK instrument and existing publication/profile effect. IMP-04: level 5, 1000 DM, 100 Reputation XP, 6h office cooldown. IMP-09: level 20, 5000 DM, 300 XP, 48h. ATR-03/COR-03: level 20, 2500 DM, 300 XP, 72h. Recognition is cosmetic for 30 days; House recipients must belong to the corresponding House. No self-awards, ranks, appointments, votes or native permission changes. Request retries cannot charge twice; cooldown survives office succession.'}), action('politics.rebellion','Declare open rebellion','quest',[field('clanId','Attacking clan'),field('officeKey','Elected office'),field('expectedTermId','Current office deed'),field('expectedHomeBlockId','Political office Home Block')],{webIssue:false,domainAdapter:'rebellionQuests.declare',executionStatus:'clan-leader-decision',effect:'Start a same-House rebellion after the previous clan key is 15 days old. Verified office Home Block victory grants the remaining term; defeat can place the clan under the office. First successful rebellion receives 5x additional base reward; verified Imperial counterchallenges receive 2x base.'}), diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs index 22f191ae..8b6531ad 100644 --- a/website/control-panel/server.mjs +++ b/website/control-panel/server.mjs @@ -1,3 +1,6 @@ +import {createOrganisationFundedRewards} from '../node/organisation-quest-rewards.mjs'; +import {ensureFaithQuestPolicy} from '../node/progression-pol.mjs'; +import {initializeClanFaith,createClanFaithAPI} from '../node/clan-faith.mjs'; import {initializeWorldTrade,createWorldTradeAPI} from '../node/world-trade-governance.mjs'; import {publicWelcomeContext} from '../node/welcome-context.mjs'; import {createEconomyRuntime} from '../node/economy-runtime.mjs'; @@ -279,6 +282,7 @@ export function createPanel(db,settings={},dependencies={}){ const gameGuild=createGameGuildAPI(db,dependencies.bankDatabase||null,dependencies.organisationKeys,settings); const politicalDecisions=createPoliticalDecisions(db,dependencies.bankDatabase||null,dependencies.organisationKeys); const politicalDecisionAPI=createPoliticalDecisionAPI(db,politicalDecisions,{origin}); + const clanFaith=createClanFaithAPI(db,dependencies.organisationKeys,{origin}); const worldTrade=createWorldTradeAPI(db,dependencies.organisationKeys,{origin,bank:dependencies.bankDatabase||null}); const imperialPassage=createImperialPassageAPI(db,dependencies.organisationKeys,{origin}); const faithBlessings=createFaithBlessingAPI(db,dependencies.organisationKeys,{origin}); @@ -386,6 +390,7 @@ export function createPanel(db,settings={},dependencies={}){ if(path==='/api/rihla')return rihla(request); if(path==='/api/network/layout')return networkLayouts(request); if(path==='/api/politics/decisions')return politicalDecisionAPI(request); + if(path==='/api/politics/faith')return clanFaith(request); if(path==='/api/politics/world-trade')return worldTrade(request); if(path==='/api/politics/arrakis-passage')return imperialPassage(request); if(path==='/api/politics/faith-blessings')return faithBlessings(request); @@ -554,7 +559,7 @@ export function createPanel(db,settings={},dependencies={}){ return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/'+file,import.meta.url)),{headers:{'Content-Type':moduleFile?'text/javascript; charset=utf-8':file.endsWith('.css')?'text/css; charset=utf-8':'text/html; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}}); } const file=path==='/'?'index.html':path==='/servers'?'servers.html':path.slice(1); - if(!['kitset-model.mjs','item-design-model.mjs','item-metadata-policy.mjs','mining-tool-policy.mjs','tool-template-policy.mjs','equipment-template-policy.mjs','organisation-refit-policy.mjs','organisation-research-policy.mjs','action-cooldown-policy.mjs','political-decision-policy.mjs','world-trade-policy.mjs','imperial-passage-policy.mjs','faith-blessing-policy.mjs','faith-pol-policy.mjs','item-lore-model.mjs','item-lore-view.mjs','item-lore.css','organisation-editor.mjs','organisation-register.mjs','user-service.html','user-service-entry.mjs','user-service.css','kit-receipt-status.mjs','clan-center.html','clan-center-entry.mjs','clan-center.css','bank-transfer-view.mjs','bank-dashboard.mjs','mail-service-ui.mjs','mail-workspace.css','hosting-control.mjs','internal-mail.mjs','internal-mail.css','election-voting-view.mjs','imperial-charters-view.mjs','proclamations-view.mjs','electoral-roll-view.mjs','election-applications-view.mjs','election-rules.mjs','political-catalog.mjs','menu-ribbons.mjs','council-preview.mjs','politics.mjs','crysknife.mjs','x-news-draft.mjs','terms.html','admin-registration.mjs','mail-signature.mjs','webmail.mjs','git-control.mjs','git-control.css','site-profile.mjs','site-profile.css','servers.html','servers.js','servers.css','pages.mjs','user-page-hero.mjs','commerce-settings.mjs','shop-management.mjs','center-portals.mjs','panel-layout.mjs','embed-size.mjs','dev-request-access.mjs','center-portals.css','overview.mjs','overview.css','page-groups.mjs','ban-register.mjs','moderation-form-response.mjs','ban-record-cards.css','ban-evidence.mjs','ban-evidence.css','ranks.mjs','ranks.css','staff-manual.mjs','luckperms.mjs','community-admin.mjs','native-community.mjs','exchange.mjs','exchange.css','clans.mjs','clan-shop.mjs','house-tailor.mjs','banking.mjs','banking.css','game-ranks.mjs','upgrade-shop.mjs','kit-generator.mjs','kit-design-model.mjs','starter-kit-policy.mjs','kit-equipment-editor.mjs','kit-texture-preview.mjs','kit-generator.css','kit-market.mjs','kit-market.css','kit-cart.mjs','imperial-atelier.mjs','quests.mjs','quests.css','clans.css','clan-request-gate.mjs','clan-directory-model.mjs','clan-directory-view.mjs','clan-profile-panels.mjs','clan-titles.mjs','dynastic-address.mjs','organisation-palette.mjs','organisation-palette-model.mjs','organisation-palette.css','clan-dynasty.mjs','clan-dynasty.css','clan-deed-settings.mjs','dune-date.mjs','organisation-settings.mjs','organisation-settings.css','organisation-dashboard.mjs','organisation-dashboard.css','organisation-activity.mjs','clan-dashboard-data.mjs','quest-rewards.mjs','quest-rewards.css','inventory/inventory-view.mjs','inventory/inventory-mount.mjs','inventory/inventory.css'].includes(file))return new Response('Not found',{status:404}); + if(!['kitset-model.mjs','item-design-model.mjs','item-metadata-policy.mjs','mining-tool-policy.mjs','tool-template-policy.mjs','equipment-template-policy.mjs','organisation-refit-policy.mjs','organisation-research-policy.mjs','action-cooldown-policy.mjs','political-decision-policy.mjs','world-trade-policy.mjs','clan-faith-policy.mjs','imperial-passage-policy.mjs','faith-blessing-policy.mjs','faith-pol-policy.mjs','item-lore-model.mjs','item-lore-view.mjs','item-lore.css','organisation-editor.mjs','organisation-register.mjs','user-service.html','user-service-entry.mjs','user-service.css','kit-receipt-status.mjs','clan-center.html','clan-center-entry.mjs','clan-center.css','bank-transfer-view.mjs','bank-dashboard.mjs','mail-service-ui.mjs','mail-workspace.css','hosting-control.mjs','internal-mail.mjs','internal-mail.css','election-voting-view.mjs','imperial-charters-view.mjs','proclamations-view.mjs','electoral-roll-view.mjs','election-applications-view.mjs','election-rules.mjs','political-catalog.mjs','menu-ribbons.mjs','council-preview.mjs','politics.mjs','crysknife.mjs','x-news-draft.mjs','terms.html','admin-registration.mjs','mail-signature.mjs','webmail.mjs','git-control.mjs','git-control.css','site-profile.mjs','site-profile.css','servers.html','servers.js','servers.css','pages.mjs','user-page-hero.mjs','commerce-settings.mjs','shop-management.mjs','center-portals.mjs','panel-layout.mjs','embed-size.mjs','dev-request-access.mjs','center-portals.css','overview.mjs','overview.css','page-groups.mjs','ban-register.mjs','moderation-form-response.mjs','ban-record-cards.css','ban-evidence.mjs','ban-evidence.css','ranks.mjs','ranks.css','staff-manual.mjs','luckperms.mjs','community-admin.mjs','native-community.mjs','exchange.mjs','exchange.css','clans.mjs','clan-shop.mjs','house-tailor.mjs','banking.mjs','banking.css','game-ranks.mjs','upgrade-shop.mjs','kit-generator.mjs','kit-design-model.mjs','starter-kit-policy.mjs','kit-equipment-editor.mjs','kit-texture-preview.mjs','kit-generator.css','kit-market.mjs','kit-market.css','kit-cart.mjs','imperial-atelier.mjs','quests.mjs','quests.css','clans.css','clan-request-gate.mjs','clan-directory-model.mjs','clan-directory-view.mjs','clan-profile-panels.mjs','clan-titles.mjs','dynastic-address.mjs','organisation-palette.mjs','organisation-palette-model.mjs','organisation-palette.css','clan-dynasty.mjs','clan-dynasty.css','clan-deed-settings.mjs','dune-date.mjs','organisation-settings.mjs','organisation-settings.css','organisation-dashboard.mjs','organisation-dashboard.css','organisation-activity.mjs','clan-dashboard-data.mjs','quest-rewards.mjs','quest-rewards.css','inventory/inventory-view.mjs','inventory/inventory-mount.mjs','inventory/inventory.css'].includes(file))return new Response('Not found',{status:404}); return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/'+file,import.meta.url)),{headers:{'Content-Type':types[file.slice(file.lastIndexOf('.'))],'Cache-Control':'no-store'}}); }; } @@ -566,9 +571,9 @@ export async function startPanel(settings=process.env){ inventoryPool.on('error',()=>console.error('Inventory database connection unavailable.')); } const bankDatabase=await openPostbankDatabase(settings); - const db=await openDatabase(settings);await initializeItemDesigns(db);await initializeKitsets(db);await initializeResearchSpecialists(db);await db.query(POLITICAL_DECISION_SCHEMA);await initializeWorldTrade(db);db.worldTradeEnabled=settings.WORLD_TRADE_ENABLED==='true';db.politicalDecisionsEnabled=true;await db.query(FAITH_BLESSING_SCHEMA);db.faithBlessingsEnabled=true;await db.query(IMPERIAL_PASSAGE_SCHEMA);await db.query(HOUSE_SELECTION_SCHEMA);await db.query(GAME_ORGANISATION_SCHEMA);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await initializeJarvisGenerator(db);await initializeEntityState(db);await initializeSystemCharacters(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys); /* Passive POL conversion waits for scoped adapters instead of company management. */await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;await initializeProgression(db);await initializeStarterKitEvents(db);db.starterKitEventsEnabled=true;await initializeServerProjects(db);if(bankDatabase)await bankDatabase.query(PROJECT_BANK_SCHEMA);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);await ensureStarterKitRewardPolicy(db,organisationKeys).catch(()=>console.error('Starter kit reward policy requires review; existing custom configuration was preserved'));await initializePOLProgression(db);await initializeSecondaryAffiliations(db);await initializePersonalActivityEvents(db);db.personalActivityEventsEnabled=true;await initializePOLActivityEvents(db);db.polActivityEventsEnabled=true;await initializeRebellionRewards(db);await ensurePOLProgressionPolicy(db,organisationKeys);await ensurePOLRepeatablePolicy(db,organisationKeys);await ensureElytraQuestPolicy(db,organisationKeys);await ensureWarQuestPolicy(db,organisationKeys);await ensurePOLMentorPolicy(db,organisationKeys);db.polMentorBonusEnabled=true;db.polRepeatablesEnabled=true;db.organisationResearchEnabled=true;db.researchSuppliesEnabled=true;const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const deedPurchases=bankDatabase&&settings.POSTBANK_ENABLED==='true'?createDeedPurchases(db,bankDatabase,organisationKeys,{authority:createPostbankAuthority(db,{bank:bankDatabase})}):null;const starterKitDelivery=await openStarterKitDelivery(db,settings);const boardRuntime=await openBoardKeyRuntime(db,organisationKeys,settings);const handle=createPanel(db,settings,{boardRuntime,inventoryPool,bankDatabase,organisationKeys,deedPurchases,officeAuctionRuntime,promotionDelivery,progressionRuntime}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com'; + const db=await openDatabase(settings);await initializeItemDesigns(db);await initializeKitsets(db);await initializeResearchSpecialists(db);await db.query(POLITICAL_DECISION_SCHEMA);await initializeWorldTrade(db);await initializeClanFaith(db);db.worldTradeEnabled=settings.WORLD_TRADE_ENABLED==='true';db.politicalDecisionsEnabled=true;await db.query(FAITH_BLESSING_SCHEMA);db.faithBlessingsEnabled=true;await db.query(IMPERIAL_PASSAGE_SCHEMA);await db.query(HOUSE_SELECTION_SCHEMA);await db.query(GAME_ORGANISATION_SCHEMA);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await initializeJarvisGenerator(db);await initializeEntityState(db);await initializeSystemCharacters(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys); /* Passive POL conversion waits for scoped adapters instead of company management. */await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;await initializeProgression(db);await initializeStarterKitEvents(db);db.starterKitEventsEnabled=true;await initializeServerProjects(db);if(bankDatabase)await bankDatabase.query(PROJECT_BANK_SCHEMA);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);await ensureStarterKitRewardPolicy(db,organisationKeys).catch(()=>console.error('Starter kit reward policy requires review; existing custom configuration was preserved'));await initializePOLProgression(db);await initializeSecondaryAffiliations(db);await initializePersonalActivityEvents(db);db.personalActivityEventsEnabled=true;await initializePOLActivityEvents(db);db.polActivityEventsEnabled=true;await initializeRebellionRewards(db);await ensurePOLProgressionPolicy(db,organisationKeys);await ensurePOLRepeatablePolicy(db,organisationKeys);await ensureElytraQuestPolicy(db,organisationKeys);await ensureWarQuestPolicy(db,organisationKeys);await ensureFaithQuestPolicy(db,organisationKeys);await ensurePOLMentorPolicy(db,organisationKeys);db.polMentorBonusEnabled=true;db.polRepeatablesEnabled=true;db.organisationResearchEnabled=true;db.researchSuppliesEnabled=true;const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const deedPurchases=bankDatabase&&settings.POSTBANK_ENABLED==='true'?createDeedPurchases(db,bankDatabase,organisationKeys,{authority:createPostbankAuthority(db,{bank:bankDatabase})}):null;const starterKitDelivery=await openStarterKitDelivery(db,settings);const boardRuntime=await openBoardKeyRuntime(db,organisationKeys,settings);const handle=createPanel(db,settings,{boardRuntime,inventoryPool,bankDatabase,organisationKeys,deedPurchases,officeAuctionRuntime,promotionDelivery,progressionRuntime}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com'; await initializeInternalMailAccess(db);const stopElectionClock=startElectionClock(db);const stopOfficeLedger=startOfficeLedger(db); - const stopBanSync=startModerationSync(db,settings),stopInternalMail=startInternalMailSync(db,{jarvisStore:bankDatabase}),stopCentralScheduler=startCentralScheduler(db,bankDatabase,settings,{extraTasks:[...(settings.MILITARY_PROJECTION_ENABLED==='true'&&organisationKeys?[{key:'military_affiliations',slot:now=>Math.floor(now/60000)*60000,run:()=>createMilitaryAffiliations(db,organisationKeys).drain()}]:[]),{key:'starter_kit_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>starterKitDelivery.drain()},...(boardRuntime?[{key:'board_keys',slot:now=>Math.floor(now/60000)*60000,run:()=>boardRuntime.drain()}]:[]),...(bankDatabase?[{key:'federal_reserve',slot:now=>Math.floor(now/60000)*60000,run:()=>createEconomyRuntime(db,bankDatabase,organisationKeys).federal.run()},{key:'research_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createResearchFundedRewards(db,bankDatabase).drain()},{key:'pol_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createPOLFundedRewards(db,bankDatabase,organisationKeys).drain()},{key:'rebellion_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createRebellionRewards(db,bankDatabase,{sourceAccount:settings.REBELLION_REWARD_SOURCE_ACCOUNT,sourceOwnerId:settings.REBELLION_REWARD_SOURCE_OWNER_ID,useWebsiteTreasury:settings.REBELLION_REWARD_FUND==='website-treasury'}).drain()},...(deedPurchases?[{key:'deed_purchases',slot:now=>Math.floor(now/60000)*60000,run:()=>deedPurchases.drain()}]:[]),{key:'server_projects',slot:now=>Math.floor(now/60000)*60000,run:()=>createServerProjectRuntime(db,bankDatabase,organisationKeys).drain()},{key:'progression_completion',slot:now=>Math.floor(now/60000)*60000,run:async()=>{const completed=await progressionRuntime.quests.processCompletions();const news=await progressionRuntime.announcements.drain();return {completed,news};}},{key:'naib_council',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await reconcileNaibChairs(db);return createNaibCouncil(db).reconcile();}},{key:'jarvis_promotions',slot:now=>Math.floor(now/15000)*15000,run:()=>promotionDelivery.drain()},{key:'political_jobs',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await createPoliticalJobs(db,bankDatabase).reconcile();return drainPoliticalJobNotifications(db,{broker:internalMailBroker,eligible:internalMailEligible});}},{key:'order_membership',slot:now=>Math.floor(now/60000)*60000,run:()=>reconcileCrysknifeCompany(db,organisationKeys)},{key:'office_auctions',slot:now=>Math.floor(now/60000)*60000,run:()=>officeAuctionRuntime.process()},{key:'jarvis_settlement',slot:now=>standardCycle(now).cutoff,async run(cutoff){const payments=createJarvisPayments(bankDatabase,createPostbankAuthority(db,{bank:bankDatabase}));for(let i=0;i<40;i++){const result=await payments.settle(cutoff);if(result.failed)return result;if(result.attempted<100)return result;}return {failed:1};}}]:[])]}); + const stopBanSync=startModerationSync(db,settings),stopInternalMail=startInternalMailSync(db,{jarvisStore:bankDatabase}),stopCentralScheduler=startCentralScheduler(db,bankDatabase,settings,{extraTasks:[...(settings.MILITARY_PROJECTION_ENABLED==='true'&&organisationKeys?[{key:'military_affiliations',slot:now=>Math.floor(now/60000)*60000,run:()=>createMilitaryAffiliations(db,organisationKeys).drain()}]:[]),{key:'starter_kit_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>starterKitDelivery.drain()},...(boardRuntime?[{key:'board_keys',slot:now=>Math.floor(now/60000)*60000,run:()=>boardRuntime.drain()}]:[]),...(bankDatabase?[{key:'federal_reserve',slot:now=>Math.floor(now/60000)*60000,run:()=>createEconomyRuntime(db,bankDatabase,organisationKeys).federal.run()},{key:'organisation_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createOrganisationFundedRewards(db,bankDatabase,organisationKeys).drain()},{key:'research_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createResearchFundedRewards(db,bankDatabase).drain()},{key:'pol_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createPOLFundedRewards(db,bankDatabase,organisationKeys).drain()},{key:'rebellion_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createRebellionRewards(db,bankDatabase,{sourceAccount:settings.REBELLION_REWARD_SOURCE_ACCOUNT,sourceOwnerId:settings.REBELLION_REWARD_SOURCE_OWNER_ID,useWebsiteTreasury:settings.REBELLION_REWARD_FUND==='website-treasury'}).drain()},...(deedPurchases?[{key:'deed_purchases',slot:now=>Math.floor(now/60000)*60000,run:()=>deedPurchases.drain()}]:[]),{key:'server_projects',slot:now=>Math.floor(now/60000)*60000,run:()=>createServerProjectRuntime(db,bankDatabase,organisationKeys).drain()},{key:'progression_completion',slot:now=>Math.floor(now/60000)*60000,run:async()=>{const completed=await progressionRuntime.quests.processCompletions();const news=await progressionRuntime.announcements.drain();return {completed,news};}},{key:'naib_council',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await reconcileNaibChairs(db);return createNaibCouncil(db).reconcile();}},{key:'jarvis_promotions',slot:now=>Math.floor(now/15000)*15000,run:()=>promotionDelivery.drain()},{key:'political_jobs',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await createPoliticalJobs(db,bankDatabase).reconcile();return drainPoliticalJobNotifications(db,{broker:internalMailBroker,eligible:internalMailEligible});}},{key:'order_membership',slot:now=>Math.floor(now/60000)*60000,run:()=>reconcileCrysknifeCompany(db,organisationKeys)},{key:'office_auctions',slot:now=>Math.floor(now/60000)*60000,run:()=>officeAuctionRuntime.process()},{key:'jarvis_settlement',slot:now=>standardCycle(now).cutoff,async run(cutoff){const payments=createJarvisPayments(bankDatabase,createPostbankAuthority(db,{bank:bankDatabase}));for(let i=0;i<40;i++){const result=await payments.settle(cutoff);if(result.failed)return result;if(result.attempted<100)return result;}return {failed:1};}}]:[])]}); const security={'X-Robots-Tag':'noindex, nofollow, noarchive','X-Content-Type-Options':'nosniff','Referrer-Policy':'no-referrer','Cache-Control':'no-store','Content-Security-Policy':PANEL_SERVICE_CSP}; const server=createServer(async(req,res)=>{try{ req.setTimeout(req.url==='/api/internal-mail/messages/send'?120000:30000);const bodyLimit=panelBodyLimit(req.method,req.url);let length=0;const chunks=[];for await(const chunk of req){length+=chunk.length;if(length>bodyLimit){res.writeHead(413,{...security,'Content-Type':'application/json'});res.end(JSON.stringify({message:'The upload exceeds the permitted request size.'}));return;}chunks.push(chunk);} diff --git a/website/integrations/osticket/dev-jarvis-catalogue.json b/website/integrations/osticket/dev-jarvis-catalogue.json index 1b087e54..13df7967 100644 --- a/website/integrations/osticket/dev-jarvis-catalogue.json +++ b/website/integrations/osticket/dev-jarvis-catalogue.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "sourceHash": "8dc45034a90dc64eca319ab4525e735708d1dec58172097c426be1771617da90", + "sourceHash": "dc02b5c58b8cd30002c592be3d5fb4142614d648f9c21f6ec76a7022c30a548b", "actions": [ { "id": "war.coalition-consent", @@ -431,6 +431,113 @@ "webIssue": false, "recordOnly": false }, + { + "id": "faith.invitation", + "label": "POL & orders · Invite a clan to a faith", + "version": 1, + "keyType": "entity-state", + "fields": [ + { + "name": "ticketId", + "label": "Ban / support ticket ID", + "type": "text", + "required": true, + "maxLength": 80 + }, + { + "name": "decisionId", + "label": "Faith decision", + "type": "select", + "required": true, + "options": [ + "BG-CONVERT", + "NF-CONVERT" + ] + }, + { + "name": "clanId", + "label": "Active clan UUID", + "type": "text", + "required": true + }, + { + "name": "requestId", + "label": "Invitation UUID", + "type": "text", + "required": true + } + ], + "effect": "Current Royal faith leader or canonical appointed officer, Reputation 5, one invitation per office per 24 hours. Signed offer expires after 72 hours. It changes no clan faith, membership, owner, vote or account. Target-clan owner must separately consent; missionary laws are checked again on acceptance.", + "fixedTargets": [], + "webIssue": false, + "recordOnly": true + }, + { + "id": "progression.faith-service-policy", + "label": "POL & orders · Consenting faith community quest policy", + "version": 6, + "keyType": "progression-policy", + "fields": [ + { + "name": "ticketId", + "label": "Ban / support ticket ID", + "type": "text", + "required": true, + "maxLength": 80 + } + ], + "effect": "Install six Old Faith and New Faith Reputation quests through policy:POL:S01:v6. Count one, three and five distinct currently consenting active clans invited by the current authorised faith specialist. Re-read the signed invitation and legal-owner consent, current faith and current authority at claim. Small separate Personal XP rewards; fixed DM queued from P&O to the faith office payment account. New research payments use the same transaction and Basic organisations route to the current legal owner; legacy payment receipts remain unchanged.", + "fixedTargets": [], + "webIssue": false, + "recordOnly": true + }, + { + "id": "faith.clan-consent", + "label": "POL & orders · Clan owner faith decision", + "version": 1, + "keyType": "entity-state", + "fields": [ + { + "name": "ticketId", + "label": "Ban / support ticket ID", + "type": "text", + "required": true, + "maxLength": 80 + }, + { + "name": "clanId", + "label": "Current clan UUID", + "type": "text", + "required": true + }, + { + "name": "offerId", + "label": "Sealed invitation UUID", + "type": "text", + "required": true + }, + { + "name": "choice", + "label": "Clan choice", + "type": "select", + "required": true, + "options": [ + "accept", + "decline" + ] + }, + { + "name": "requestId", + "label": "Consent UUID", + "type": "text", + "required": true + } + ], + "effect": "Re-read the current clan deed, signed invitation and current faith mandate. Accepting records the clan’s single faith and a seven-day change cooldown. Declining leaves allegiance unchanged. Immutable owner consent, key, offer and faith update commit together; revoking the latest receipt never revives an older faith. No personal voting, membership, bank or ownership change.", + "fixedTargets": [], + "webIssue": false, + "recordOnly": true + }, { "id": "politics.world-trade", "label": "POL & orders · House levy or Guild embargo", diff --git a/website/node/atomic-bank-access.mjs b/website/node/atomic-bank-access.mjs index 093f5d56..e5dab087 100644 --- a/website/node/atomic-bank-access.mjs +++ b/website/node/atomic-bank-access.mjs @@ -1,6 +1,6 @@ // Central domain writes and Postbank entries must share one MySQL transaction. // Never silently fall back to separate commits when databases are on different hosts. -export function atomicBankAccess(db,bank,{verifyStorage,centralTables=[]}={}){ +export function atomicBankAccess(db,bank,{verifyStorage,centralTables=[],bankTables=[]}={}){ let schema,storage; async function ready(){if(!storage)storage=(async()=>{ if(!bank)throw Error('Banking unavailable'); @@ -8,7 +8,7 @@ export function atomicBankAccess(db,bank,{verifyStorage,centralTables=[]}={}){ const [b,c]=await Promise.all([bank.first('SELECT DATABASE() db,@@hostname host,@@port port,@@server_id server_id'),db.first('SELECT DATABASE() db,@@hostname host,@@port port,@@server_id server_id')]); if(!/^[a-z][a-z0-9_]{2,63}$/.test(b?.db||'')||!c||['host','port','server_id'].some(k=>String(b[k])!==String(c[k])))throw Error('One transactional bank server required'); schema=b.db;await db.first('SELECT id FROM `'+schema+'`.pb_accounts LIMIT 1'); - for(const [database,tables]of [[schema,['pb_entities','pb_clients','pb_packages','pb_accounts','pb_account_authorisations','pb_orders','pb_entries','pb_audit']],[c.db,centralTables]]){ + for(const [database,tables]of [[schema,['pb_entities','pb_clients','pb_packages','pb_accounts','pb_account_authorisations','pb_orders','pb_entries','pb_audit',...bankTables]],[c.db,centralTables]]){ if(!tables.length)continue; const rows=await db.query('SELECT TABLE_NAME name,ENGINE engine FROM information_schema.TABLES WHERE TABLE_SCHEMA=? AND TABLE_NAME IN ('+tables.map(()=>'?').join(',')+')',[database,...tables]); if(tables.some(n=>!rows.some(r=>r.name===n&&String(r.engine).toLowerCase()==='innodb')))throw Error('Transactional tables required'); diff --git a/website/node/bank-quest-activities.mjs b/website/node/bank-quest-activities.mjs index ece79384..36dab64a 100644 --- a/website/node/bank-quest-activities.mjs +++ b/website/node/bank-quest-activities.mjs @@ -6,13 +6,13 @@ const purchases=`SELECT o.id,o.actor_id,o.posted_at 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.actor_id=? AND o.state='posted' - AND o.mode='exchange' AND o.source_id<>o.target_id AND target.client_number<>a.client_number + AND o.mode='exchange' AND NOT EXISTS(SELECT 1 FROM pb_exchange_levies levy WHERE levy.payment_id=o.id) AND o.source_id<>o.target_id AND target.client_number<>a.client_number AND o.posted_at>=? AND o.posted_at0 AND o.source_id<>o.target_id AND (source.client_number IS NULL OR source.client_number<>a.client_number) AND o.posted_at>=? AND o.posted_at<=?`,[accountId,startsAt,now]); const value={wages:Number(rows[0]?.wages||0),earned:Number(rows[0]?.earned||0)}; diff --git a/website/node/clan-faith.mjs b/website/node/clan-faith.mjs new file mode 100644 index 00000000..31b3afbc --- /dev/null +++ b/website/node/clan-faith.mjs @@ -0,0 +1,85 @@ +import {createHash} from 'node:crypto'; +import {boardReadStore} from './board-deed-source.mjs'; +import {readClanDeed} from './clan-deeds.mjs'; +import {officeDeedFor,activePoliticalAppointments} from './political-appointments.mjs'; +import {officeAuthority} from './political-decisions.mjs'; +import {faithPOL} from '../control-panel/public/faith-pol-policy.mjs'; +import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs'; +import {validUuid} from './game-link.mjs'; +import {identity} from './auth.mjs'; +import {accessFor} from './permissions.mjs'; +import {polProgressionStore} from './progression-pol.mjs'; +import {readActiveXPSeason} from './progression-xp-store.mjs'; +import {levelForXP} from './progression-definitions.mjs'; +import {CLAN_FAITH_POLICY as POLICY,clanFaithDecision} from '../control-panel/public/clan-faith-policy.mjs'; +export const CLAN_FAITH_SCHEMA=[ + `CREATE TABLE IF NOT EXISTS jarvis_clan_faith(clan_id CHAR(36) PRIMARY KEY,faith_key VARCHAR(32),request_id CHAR(36),changed_at BIGINT) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`, + `CREATE TABLE IF NOT EXISTS jarvis_faith_office_locks(office_key VARCHAR(32) PRIMARY KEY,last_offer_at BIGINT) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`, + `CREATE TABLE IF NOT EXISTS jarvis_faith_offers(request_id CHAR(36) PRIMARY KEY,key_id CHAR(36) NOT NULL UNIQUE,office_key VARCHAR(32) NOT NULL,source_term_id CHAR(36) NOT NULL,actor_id CHAR(36) NOT NULL,clan_id CHAR(36) NOT NULL,input_hash CHAR(64) NOT NULL,state VARCHAR(16) NOT NULL,created_at BIGINT NOT NULL,expires_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`, + `CREATE TABLE IF NOT EXISTS jarvis_faith_consents(request_id CHAR(36) PRIMARY KEY,key_id CHAR(36) NOT NULL UNIQUE,offer_id CHAR(36),clan_id CHAR(36) NOT NULL,actor_id CHAR(36) NOT NULL,faith_key VARCHAR(32),choice VARCHAR(16) NOT NULL,input_hash CHAR(64) NOT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4` +]; +const fail=(message,status=409)=>{throw Object.assign(Error(message),{status});}; +const digest=v=>createHash('sha256').update(JSON.stringify(v)).digest('hex'); +const exact=(v,fields)=>v&&typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).sort().join(',')===fields; +async function reputation(tx,actor,now){const pol=polProgressionStore(tx),season=await readActiveXPSeason(pol,now),row=await pol.first('SELECT effective_xp FROM jarvis_progression_accounts WHERE account_id=?',[actor.id]);return levelForXP(Number(row?.effective_xp||0),{base:Number(season.curve_base),cap:Number(season.level_cap)||null});} +export async function initializeClanFaith(db){for(const sql of CLAN_FAITH_SCHEMA)await db.query(sql);for(const office of ['veiled_concord','muad_dib'])await db.query('INSERT INTO jarvis_faith_office_locks(office_key) VALUES(?) ON DUPLICATE KEY UPDATE office_key=VALUES(office_key)',[office]);db.clanFaithEnabled=true;} +export async function currentClanFaith(store,clanId){ + const row=(await store.query("SELECT f.*,k.id verified_key FROM jarvis_clan_faith f LEFT JOIN organisation_keys k ON k.id=(SELECT c.key_id FROM jarvis_faith_consents c WHERE c.request_id=f.request_id AND c.clan_id=f.clan_id AND c.choice='accept' AND c.faith_key=f.faith_key) AND k.account_id=? AND k.key_type='entity-state' AND k.scope_id=CONCAT('state:clan-faith:',f.request_id) AND k.revoked_at IS NULL WHERE f.clan_id=?",[STAFF_OFFICE_ACCOUNT_ID,clanId]))[0]; + return{faith:row?.verified_key&&faithPOL(row.faith_key)?row.faith_key:null,requestId:row?.request_id||null,changedAt:row?.changed_at===null||row?.changed_at===undefined?null:Number(row.changed_at)}; +} +export async function faithAuthority(tx,office,actor,now,{clanId=null,lock=false}={}){ + if(!faithPOL(office))return null; + let term;try{term=await officeDeedFor(tx,office,now,{lock});}catch(e){if([403,404,409].includes(e.status))return null;throw e;} + const holder=await officeAuthority(tx,{office},{id:term.user_id},now,lock);if(!holder||holder.termId!==term.id)return null; + if(actor.id===term.user_id)return{termId:term.id,clanIds:null}; + const appointments=(await activePoliticalAppointments(tx,{userId:actor.id,clock:()=>now})).filter(a=>a.office_key===office&&a.appointment_type==='job'&&a.role_key==='officer'&&a.title===faithPOL(office).roles.officer); + const general=appointments.find(a=>a.target_kind===null);if(general){if(lock)await tx.first('SELECT id FROM political_appointment_deeds WHERE id=? FOR UPDATE',[general.id]);return{termId:term.id,clanIds:null};} + const ids=[];for(const a of appointments){if(a.target_kind!=='clan'||clanId&&a.target_id!==clanId)continue;if(await tx.first('SELECT clan_id FROM site_clan_members WHERE user_id=? AND clan_id=?',[actor.id,a.target_id]))ids.push(a.target_id);} + return ids.length?{termId:term.id,clanIds:ids}:null; +} +async function legalClanOwner(tx,actor,clanId){await tx.first('SELECT id FROM site_clans WHERE id=? AND active=1 FOR UPDATE',[clanId]);const deed=await readClanDeed(tx,clanId);if(deed.owner?.id!==actor.id)fail('Only this clan’s current legal owner can choose its faith.',403);return deed;} +export function createClanFaith(base,keys,{clock=Date.now,isOutlawed=async()=>false}={}){ + if(typeof base?.query!=='function')return{office:async()=>fail('Faith records unavailable.',503),clan:async()=>fail('Faith records unavailable.',503),offer:async()=>fail('Faith records unavailable.',503),reply:async()=>fail('Faith records unavailable.',503)}; + const db=boardReadStore(base,base); + async function office(actor,officeKey){const now=clock(),a=await faithAuthority(db,officeKey,actor,now),lock=await db.first('SELECT last_offer_at FROM jarvis_faith_office_locks WHERE office_key=?',[officeKey]);if(!faithPOL(officeKey))fail('Unknown faith.',400); + const clans=a?await db.query('SELECT id,name FROM site_clans WHERE active=1'+(a.clanIds?' AND id IN ('+a.clanIds.map(()=>'?').join(',')+')':'')+' ORDER BY name LIMIT 1000',a.clanIds||[]):[]; + const offers=a?await db.query('SELECT request_id,clan_id,state,created_at,expires_at FROM jarvis_faith_offers WHERE office_key=? ORDER BY created_at DESC,request_id DESC LIMIT 100',[officeKey]):[]; + const levelNow=a?await reputation(db,actor,now):0,cooldownUntil=lock?.last_offer_at===null||lock?.last_offer_at===undefined?null:Number(lock.last_offer_at)+POLICY.officeCooldownMs; + return{office:officeKey,name:faithPOL(officeKey).name,canManage:!!a,canExecute:!!a&&levelNow>=5&&(!cooldownUntil||now>=cooldownUntil),levelNow,clans,offers:offers.filter(o=>!a?.clanIds||a.clanIds.includes(o.clan_id)),cooldownUntil,policy:POLICY}; + } + async function clan(actor,clanId){if(!validUuid(clanId))fail('Choose a clan.',400);const deed=await readClanDeed(db,clanId),owner=deed.owner?.id===actor.id,faith=await currentClanFaith(db,clanId),offers=owner?await db.query("SELECT o.request_id,o.office_key,o.expires_at FROM jarvis_faith_offers o JOIN organisation_keys k ON k.id=o.key_id AND k.revoked_at IS NULL WHERE o.clan_id=? AND o.state='open' AND o.expires_at>? ORDER BY o.created_at DESC",[clanId,clock()]):[];return{clanId,name:deed.clan.name,...faith,canManage:owner,offers,cooldownUntil:faith.changedAt===null?null:faith.changedAt+POLICY.clanCooldownMs,policy:POLICY};} + async function offer(actor,input){ + if(!exact(input,'clanId,confirmed,decisionId,requestId')||input.confirmed!==true||!validUuid(input.requestId)||!validUuid(input.clanId)||!clanFaithDecision(input.decisionId))fail('Review the faith invitation.',400);if(!keys)fail('Key service unavailable.',503); + const d=clanFaithDecision(input.decisionId),hash=digest([actor.id,d.id,input.clanId]); + await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',scopeId:'state:faith-offer:'+input.requestId,authorize:async(raw,{keyId})=>{const tx=boardReadStore(raw,db),now=clock(),a=await faithAuthority(tx,d.office,actor,now,{clanId:input.clanId,lock:true});if(!a)fail('A current faith leader or appointed officer is required.',403); + const clan=await tx.first('SELECT id FROM site_clans WHERE id=? AND active=1 FOR UPDATE',[input.clanId]);if(!clan)fail('Active clan required.',404); + const lock=await tx.first('SELECT last_offer_at FROM jarvis_faith_office_locks WHERE office_key=? FOR UPDATE',[d.office]),prior=await tx.first('SELECT * FROM jarvis_faith_offers WHERE request_id=?',[input.requestId]);if(prior){if(prior.actor_id!==actor.id||prior.input_hash!==hash)fail('Invitation reference already used.');return;} + if(lock?.last_offer_at!==null&&lock?.last_offer_at!==undefined&&now{const tx=boardReadStore(raw,db),now=clock(),offer=await tx.first('SELECT * FROM jarvis_faith_offers WHERE request_id=? AND clan_id=?',[input.offerId,input.clanId]);if(!offer)fail('Faith invitation not found.',404); + const a=await faithAuthority(tx,offer.office_key,{id:offer.actor_id},now,{clanId:input.clanId,lock:true});await legalClanOwner(tx,actor,input.clanId); + const prior=await tx.first('SELECT * FROM jarvis_faith_consents WHERE request_id=?',[input.requestId]);if(prior){if(prior.actor_id!==actor.id||prior.input_hash!==hash)fail('Consent reference already used.');return;} + const current=await tx.first('SELECT * FROM jarvis_faith_offers WHERE request_id=? FOR UPDATE',[input.offerId]),key=await tx.first("SELECT id FROM organisation_keys WHERE id=? AND account_id=? AND key_type='entity-state' AND scope_id=? AND revoked_at IS NULL FOR SHARE",[offer.key_id,STAFF_OFFICE_ACCOUNT_ID,'state:faith-offer:'+input.offerId]); + if(!a||a.termId!==offer.source_term_id||!key||current.state!=='open'||Number(current.expires_at)<=now)fail('This invitation expired or its faith authority changed.'); + const faith=await currentClanFaith(tx,input.clanId);if(input.choice==='accept'){ + if(faith.changedAt!==null&&nowidentity(r,db),access=a=>accessFor(db,a),service=createClanFaith(db,keys)}={}){ + const response=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}}); + return async request=>{try{const actor=await authenticate(request);if(!actor)return response({message:'Sign in first.'},401);if(!(await access(actor)).nodes.includes('web.menu.game'))return response({message:'Player access required.'},403);const url=new URL(request.url); + if(request.method==='GET'){if(url.searchParams.size!==1)return response({message:'Choose one clan or faith office.'},400);if(url.searchParams.has('clanId'))return response(await service.clan(actor,url.searchParams.get('clanId')));if(url.searchParams.has('office'))return response(await service.office(actor,url.searchParams.get('office')));return response({message:'Unknown faith view.'},400);} + if(request.method!=='POST')return response({message:'Method not allowed.'},405);if(url.search||request.headers.get('origin')!==origin)return response({message:'Origin or query rejected.'},403);if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return response({message:'JSON required.'},415);const raw=await request.text();if(raw.length>2048)return response({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return response({message:'Invalid faith decision.'},400);}const action=input?.action;if(!['offer','reply'].includes(action))return response({message:'Unknown faith action.'},400);const {action:_,...body}=input;return response(await service[action](actor,body)); + }catch(e){return response({message:e.status?e.message:'Faith decision was not confirmed. Refresh before retrying.'},e.status||503);}}; +} diff --git a/website/node/faith-blessings.mjs b/website/node/faith-blessings.mjs index a1af602b..bdf707bb 100644 --- a/website/node/faith-blessings.mjs +++ b/website/node/faith-blessings.mjs @@ -39,7 +39,7 @@ export async function validFaithReward(db,proof,{accountId,claimedAt}){ export function faithAward(award,boost){ if(boost.xp===1&&boost.dm===1)return award; const xp=award.xp*boost.xp;if(!Number.isSafeInteger(xp))throw Error('Blessed XP exceeds limits');let reward=award.reward; - if(boost.dm===2&&['pol-funded-reward-v1','organisation-research-funded-v1'].includes(reward.schema)){const amount=reward.amountMinor*2;if(!Number.isSafeInteger(amount))throw Error('Blessed reward exceeds limits');reward={...reward,amountMinor:amount,faithBaseAmountMinor:reward.amountMinor,faith:boost.dmProof};} + if(boost.dm===2&&['pol-funded-reward-v1','organisation-research-funded-v1','organisation-research-funded-v2','pol-organisation-funded-v1'].includes(reward.schema)){const amount=reward.amountMinor*2;if(!Number.isSafeInteger(amount))throw Error('Blessed reward exceeds limits');reward={...reward,amountMinor:amount,faithBaseAmountMinor:reward.amountMinor,faith:boost.dmProof};} return{...award,xp,reward,basis:{...(award.basis||{}),...(boost.xpProof?{faithXP:boost.xpProof}:{})}}; } export function createFaithBlessingAPI(db,keys,{origin='https://cp.dunerealms.com',authenticate=r=>identity(r,db),access=a=>accessFor(db,a),clock=Date.now}={}){ diff --git a/website/node/faith-quest-evidence.mjs b/website/node/faith-quest-evidence.mjs new file mode 100644 index 00000000..dfc3dab5 --- /dev/null +++ b/website/node/faith-quest-evidence.mjs @@ -0,0 +1,15 @@ +import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs'; +import {currentActivityPlayer} from './quest-activity-events.mjs'; +import {faithAuthority} from './clan-faith.mjs'; +// Count distinct current communities, not invitations, repeated consents or +// arbitrary browser counters. Claiming re-reads these same sealed records. +export async function faithQuestEvidence(db,{accountId,minecraftUuid,startsAt,endsAt,now,lock=false}){ + if(!await currentActivityPlayer(db,accountId,minecraftUuid,{lock}))throw Error('Current faith quest identity required'); + const totals=new Map([['pol-faith-muad_dib-conversions',0],['pol-faith-veiled_concord-conversions',0]]),proofIds=[],seen=new Set(); + const rows=await db.query("SELECT c.*,o.key_id offer_key,o.office_key,o.state offer_state,f.faith_key current_faith,f.request_id current_request,ck.key_type consent_type,ck.account_id consent_issuer,ck.scope_id consent_scope,ck.revoked_at consent_revoked,ok.key_type offer_type,ok.account_id offer_issuer,ok.scope_id offer_scope,ok.revoked_at offer_revoked FROM jarvis_faith_consents c JOIN jarvis_faith_offers o ON o.request_id=c.offer_id JOIN jarvis_clan_faith f ON f.clan_id=c.clan_id JOIN site_clans clan ON clan.id=c.clan_id AND clan.active=1 JOIN organisation_keys ck ON ck.id=c.key_id JOIN organisation_keys ok ON ok.id=o.key_id WHERE o.actor_id=? AND c.choice='accept' AND c.created_at>=? AND c.created_ato.key===owner.id))throw Error('Registered political office required');return{kind:'office',id:owner.id}; +} +// The caller retains this central deed lock until the bank commit finishes. +// Mother control and specialist roles never replace the legal Basic owner. +export async function organisationRewardRoute(raw,owner){ + const ref=organisationRewardRef(owner),tx=boardReadStore(raw,raw); + if(ref.kind==='office')return{kind:'office',id:ref.id==='emperor'?'emperor':'leader:'+(({arrakis:'fremen'})[ref.id]||ref.id),basic:false}; + if(ref.kind==='clan'){ + await tx.first('SELECT id FROM site_clans WHERE id=? AND active=1 FOR UPDATE',[ref.id]);const deed=await readClanDeed(tx,ref.id);if(!deed.owner)throw Error('Current clan owner required');return deed.kind==='basic'?{kind:'person',id:deed.owner.id,basic:true}:{kind:'clan',id:ref.id,basic:false}; + } + await tx.first('SELECT company_id FROM site_company_deeds WHERE company_id=? FOR UPDATE',[ref.id]);const deed=await readCompanyDeed(tx,ref.id);if(deed.company.status!=='active')throw Error('Active company required');return deed.company.charter_kind==='basic'?{kind:'person',id:deed.company.owner_account_id,basic:true}:{kind:'company',id:ref.id,basic:false}; +} +const accounts='SELECT a.*,c.entity_id,e.kind,e.external_key,e.active entity_active,p.state 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'; +export function createOrganisationQuestPayments(bank,{authorize,resolveRoute,clock=Date.now}={}){ + if(typeof authorize!=='function'||typeof resolveRoute!=='function')throw TypeError('Verified claim and current deed adapters required'); + return{async pay({keyId,owner,amountMinor,purpose}){ + const ref=organisationRewardRef(owner);if(!validUuid(keyId)||!Number.isSafeInteger(amountMinor)||amountMinor<1||amountMinor>250000||!['research','mission'].includes(purpose))throw Error('Invalid bound organisation reward'); + const memo=(purpose==='research'?'Research reward ':'Organisation quest reward ')+keyId,fingerprint=createHash('sha256').update(JSON.stringify([ORGANISATION_QUEST_TREASURY,keyId,ref,amountMinor,memo])).digest('hex'); + return bank.transaction(async tx=>{ + if(!await authorize())throw Error('Consumed verified organisation claim required'); + const prior=await tx.first('SELECT r.*,o.fingerprint,o.state order_state,o.actor_id,o.amount_minor,o.target_id paid_target,s.system_key source_key,e.kind paid_kind,e.external_key paid_key FROM pb_organisation_quest_rewards r JOIN pb_orders o ON o.id=r.order_id JOIN pb_accounts s ON s.id=o.source_id 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 r.key_id=? FOR UPDATE',[keyId]); + if(prior){if(prior.fingerprint!==fingerprint||prior.actor_id!==OFFICIAL_ACCOUNT.id||prior.order_state!=='posted'||prior.source_key!==ORGANISATION_QUEST_TREASURY||Number(prior.amount_minor)!==amountMinor||prior.organisation_kind!==ref.kind||prior.organisation_id!==ref.id||String(prior.target_id)!==String(prior.paid_target)||prior.recipient_kind!==prior.paid_kind||prior.recipient_key!==prior.paid_key)throw Error('Organisation reward reference conflict');return{orderId:prior.order_id,replayed:true,basic:!!Number(prior.basic_fallback),recipientKind:prior.recipient_kind};} + if(await tx.first('SELECT id FROM pb_orders WHERE id=? FOR UPDATE',[keyId]))throw Error('Organisation reward requires reconciliation'); + const route=await resolveRoute(ref);if(!route||!['person','clan','company','office'].includes(route.kind)||route.basic!==true&&route.basic!==false||route.basic&&(route.kind!=='person'||!validUuid(route.id))||!route.basic&&(route.kind!==ref.kind||route.kind!=='office'&&route.id!==ref.id||route.kind==='office'&&route.id!==(ref.id==='emperor'?'emperor':'leader:'+(({arrakis:'fremen'})[ref.id]||ref.id))))throw Error('Current organisation reward route required'); + const entity=await tx.first('SELECT id FROM pb_entities WHERE kind=? AND external_key=? AND active=1 FOR UPDATE',[route.kind,route.id]);if(!entity)throw Error('Organisation reward recipient has no active bank entity'); + const rows=await tx.query(accounts+' WHERE a.system_key=? OR c.entity_id=? ORDER BY a.id FOR UPDATE',[ORGANISATION_QUEST_TREASURY,entity.id]),source=rows.find(a=>a.system_key===ORGANISATION_QUEST_TREASURY),target=rows.find(a=>a.entity_id===entity.id&&ordinaryPaymentAccount(a)&&BigInt(a.balance_minor)+BigInt(amountMinor)<=9223372036854775807n); + if(!source||source.state!=='active'||!target||String(source.id)===String(target.id))throw Error('P&O or organisation payment account unavailable'); + if(!await authorize())throw Error('Organisation claim authority changed'); + await tx.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'system','queued',?)",[keyId,OFFICIAL_ACCOUNT.id,source.id,target.id,fingerprint,String(amountMinor),memo,clock()]); + await postPayrollIssue(tx,{id:keyId,actor_id:OFFICIAL_ACCOUNT.id,amount_minor:String(amountMinor)},source,target,{now:clock()}); + await tx.query('INSERT INTO pb_organisation_quest_rewards(key_id,order_id,target_id,organisation_kind,organisation_id,recipient_kind,recipient_key,basic_fallback,created_at) VALUES(?,?,?,?,?,?,?,?,?)',[keyId,keyId,target.id,ref.kind,ref.id,route.kind,route.id,route.basic?1:0,clock()]); + return{orderId:keyId,replayed:false,basic:route.basic,recipientKind:route.kind}; + }); + }}; +} diff --git a/website/node/organisation-quest-rewards.mjs b/website/node/organisation-quest-rewards.mjs new file mode 100644 index 00000000..245e32c4 --- /dev/null +++ b/website/node/organisation-quest-rewards.mjs @@ -0,0 +1,42 @@ +import {atomicBankAccess} from './atomic-bank-access.mjs'; +import {boardReadStore} from './board-deed-source.mjs'; +import {createOrganisationQuestPayments,organisationRewardRoute,organisationRewardRef} from './organisation-quest-payments.mjs'; +import {POL_QUEST_DEFINITIONS} from '../control-panel/public/cp-v2/cp-v2-pol-quest-catalogue.mjs'; +import {researchDefinitions} from './organisation-research.mjs'; +import {RESEARCH_POLICY} from '../control-panel/public/organisation-research-policy.mjs'; +import {validFaithReward} from './faith-blessings.mjs'; +import {currentMentorPolicy} from './pol-mentor-rewards.mjs'; +import {createSystemCharacters} from './system-characters.mjs'; +import {OFFICIAL_ACCOUNT} from './official-account.mjs'; +import {creditXP} from './progression-xp-ledger.mjs'; +import {lockXPAccount,readActiveXPSeason,saveXPAccount} from './progression-xp-store.mjs'; +import {xpAtLevel} from './progression-definitions.mjs'; +export async function awardOrganisationMission(polStore,actor,d,issuer,award,{clock=Date.now,personalMultiplier=1,mentorEnabled=false}={}){ + const r=award.reward;if(!d.faithMission||r.schema!=='pol-organisation-reward-v1'||JSON.stringify(r.owner)!==JSON.stringify(d.owner)||r.amountMinor!==d.amountMinor||r.personalXP!==d.personalXP||![1,2].includes(personalMultiplier))throw Error('Configured organisation mission reward required'); + const policy=mentorEnabled?await currentMentorPolicy(polStore,{lock:true}):null,bps=policy&&issuer.capabilities.includes('quest.reward-bonus')?policy.dmBonusBps:0,amountMinor=d.amountMinor+Number((BigInt(d.amountMinor)*BigInt(bps)+9999n)/10000n),raw=polStore.sourceStore;if(!raw)throw Error('Atomic personal reward store required'); + const state=await lockXPAccount(raw,actor.id,clock()),season=await readActiveXPSeason(raw,clock(),d.season),capXP=Number(season.level_cap)===0?Number.MAX_SAFE_INTEGER:xpAtLevel(Number(season.level_cap),Number(season.curve_base)); + await saveXPAccount(raw,actor.id,creditXP(state,d.personalXP*personalMultiplier,{capXP}),season,award.keyId,'organisation-mission-claimed',{definitionId:d.id,xp:d.personalXP*personalMultiplier,organisation:d.owner},clock()); + return{...award,reward:{schema:'pol-organisation-funded-v1',owner:d.owner,accountId:actor.id,definitionId:d.id,seasonId:d.season,personalXP:d.personalXP,baseAmountMinor:d.amountMinor,amountMinor,bonusBps:bps,policyKeyId:policy?.keyId||null,issuerKeyId:issuer.keyId}}; +} +const schemas=['organisation-research-funded-v2','pol-organisation-funded-v1']; +export function createOrganisationFundedRewards(base,bank,keys,{clock=Date.now,verifyStorage}={}){ + const central=boardReadStore(base,base),banking=atomicBankAccess(central,bank,{verifyStorage,bankTables:['pb_organisation_quest_rewards'],centralTables:['jarvis_pol_quest_reward_jobs','jarvis_pol_quest_states','jarvis_pol_quest_claims','organisation_keys','site_clans','site_clan_deeds','site_clan_charters','corrino_companies','site_company_deeds']}); + async function process(keyId){await banking.ready();return base.transaction(async raw=>{const tx=boardReadStore(raw,central),job=await tx.first('SELECT * FROM jarvis_pol_quest_reward_jobs WHERE key_id=? FOR UPDATE',[keyId]);if(!job||job.state!=='queued')return'unchanged'; + const row=await tx.first('SELECT s.definition_id,s.account_id,s.season_id,s.state,c.reward_json,c.claimed_at,c.account_id claim_account,k.used_at,k.revoked_at,k.key_type,k.scope_id,k.account_id key_account FROM jarvis_pol_quest_states s JOIN jarvis_pol_quest_claims c ON c.key_id=s.key_id JOIN organisation_keys k ON k.id=s.key_id WHERE s.key_id=? FOR UPDATE',[keyId]); + if(!row||row.state!=='claimed'||row.used_at==null||row.revoked_at!==null||row.key_type!=='quest'||row.account_id!==job.account_id||row.claim_account!==job.account_id||row.key_account!==job.account_id||row.season_id!==job.season_id||row.scope_id!==job.season_id+':POL_'+row.definition_id||row.reward_json!==job.payload_json)throw Error('Consumed verified organisation claim required'); + const r=JSON.parse(job.payload_json);if(!schemas.includes(r.schema)||r.accountId!==row.account_id||r.definitionId!==row.definition_id||r.seasonId!==row.season_id)throw Error('Bound organisation reward required');organisationRewardRef(r.owner); + let definition,baseAmount,purpose; + if(r.schema==='organisation-research-funded-v2'){ + definition=researchDefinitions(r.owner,{season:row.season_id}).find(d=>d.id===row.definition_id);if(!definition||r.policy!==RESEARCH_POLICY||r.personalXP!==definition.personalXP)throw Error('Registered research reward required');baseAmount=definition.amountMinor;purpose='research'; + }else{ + definition=POL_QUEST_DEFINITIONS.find(d=>d.id===row.definition_id&&d.faithMission);if(!definition||JSON.stringify(r.owner)!==JSON.stringify(definition.owner)||r.personalXP!==definition.personalXP||r.baseAmountMinor!==definition.amountMinor)throw Error('Registered organisation mission reward required'); + const saved=await tx.first('SELECT issuer_key_id,issuer_name FROM jarvis_pol_quest_issuers WHERE quest_key_id=?',[keyId]),issuer=await createSystemCharacters(tx,keys,{authorizeOperator:async()=>false}).inspect(definition.issuer);if(!saved||saved.issuer_key_id!==r.issuerKeyId||saved.issuer_name!==definition.issuer||issuer?.keyId!==r.issuerKeyId||!issuer.capabilities.includes('quest.issue'))throw Error('Current scoped mission issuer required'); + const policy=r.policyKeyId?await currentMentorPolicy(tx,{lock:true}):null,bps=policy&&issuer.capabilities.includes('quest.reward-bonus')?policy.dmBonusBps:0;if(r.bonusBps!==bps||(r.policyKeyId||null)!==(policy?.keyId||null))throw Error('Current mission reward policy required');baseAmount=definition.amountMinor+Number((BigInt(definition.amountMinor)*BigInt(bps)+9999n)/10000n);purpose='mission'; + } + if(!Number.isSafeInteger(r.amountMinor)||r.amountMinor!==baseAmount*(r.faith?2:1)||r.faith&&(!await validFaithReward(tx,r.faith,{accountId:row.account_id,claimedAt:Number(row.claimed_at)})||r.faithBaseAmountMinor!==baseAmount)||!r.faith&&Object.hasOwn(r,'faithBaseAmountMinor'))throw Error('Verified organisation reward amount required'); + const official=await tx.first("SELECT username,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[OFFICIAL_ACCOUNT.id]);if(official?.username!==OFFICIAL_ACCOUNT.username||official.role!=='official_account')throw Error('Official payment identity required'); + const view=banking.view(tx),payments=createOrganisationQuestPayments({transaction:work=>work(view)},{clock,authorize:async()=>{const k=await tx.first('SELECT used_at,revoked_at FROM organisation_keys WHERE id=?',[keyId]);return k?.used_at!=null&&k.revoked_at===null;},resolveRoute:owner=>organisationRewardRoute(tx,owner)}); + await payments.pay({keyId,owner:r.owner,amountMinor:r.amountMinor,purpose});await tx.query("UPDATE jarvis_pol_quest_reward_jobs SET state='paid' WHERE key_id=?",[keyId]);return'paid'; + });} + return{async drain(){const rows=await central.query("SELECT key_id FROM jarvis_pol_quest_reward_jobs WHERE state='queued' AND JSON_EXTRACT(payload_json,'$.schema') IN (?,?) ORDER BY created_at,key_id LIMIT 25",schemas),results=[];for(const row of rows)try{results.push({keyId:row.key_id,state:await process(row.key_id)});}catch{results.push({keyId:row.key_id,state:'awaiting-account-or-review'});}return{attempted:rows.length,results};}}; +} diff --git a/website/node/organisation-research-rewards.mjs b/website/node/organisation-research-rewards.mjs index 9abe1aa6..31990a2f 100644 --- a/website/node/organisation-research-rewards.mjs +++ b/website/node/organisation-research-rewards.mjs @@ -11,13 +11,14 @@ export async function awardResearch(polStore,actor,d,award,{clock=Date.now,perso const state=await lockXPAccount(tx,actor.id,clock()),season=await readActiveXPSeason(tx,clock(),d.season),capXP=Number(season.level_cap)===0?Number.MAX_SAFE_INTEGER:xpAtLevel(Number(season.level_cap),Number(season.curve_base)); if(![1,2].includes(personalMultiplier))throw Error('Invalid research blessing multiplier');const personalXP=d.personalXP*personalMultiplier; await saveXPAccount(tx,actor.id,creditXP(state,personalXP,{capXP}),season,award.keyId,'research-claimed',{definitionId:d.id,xp:personalXP,organisation:d.owner},clock()); - return {...award,reward:{...r,schema:'organisation-research-funded-v1',policy:RESEARCH_POLICY,accountId:actor.id,definitionId:d.id,seasonId:d.season}}; + return {...award,reward:{...r,schema:'organisation-research-funded-v2',policy:RESEARCH_POLICY,accountId:actor.id,definitionId:d.id,seasonId:d.season}}; } export function researchRecipient(owner){ if(['clan','company'].includes(owner?.kind))return{kind:owner.kind,id:owner.id}; if(['office','politics'].includes(owner?.kind))return{kind:'office',id:owner.id==='emperor'?'emperor':'leader:'+(({arrakis:'fremen'})[owner.id]||owner.id)}; throw Error('Registered research organisation required.'); } +// Legacy v1 jobs retain their originally promised website-treasury settlement. export function createResearchFundedRewards(central,bank,{clock=Date.now}={}){ async function process(keyId){return central.transaction(async tx=>{ const job=await tx.first('SELECT * FROM jarvis_pol_quest_reward_jobs WHERE key_id=? FOR UPDATE',[keyId]);if(!job||job.state!=='queued')return'unchanged'; diff --git a/website/node/postbank-schema.sql b/website/node/postbank-schema.sql index f6fb6847..fcc01343 100644 --- a/website/node/postbank-schema.sql +++ b/website/node/postbank-schema.sql @@ -224,3 +224,9 @@ CREATE TABLE IF NOT EXISTS pb_exchange_levies ( gross_minor BIGINT NOT NULL, tax_minor BIGINT NOT NULL, net_minor BIGINT NOT NULL, house_entity_id CHAR(36), target_id BIGINT UNSIGNED, created_at BIGINT NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +CREATE TABLE IF NOT EXISTS pb_organisation_quest_rewards ( + key_id CHAR(36) PRIMARY KEY, order_id CHAR(36) NOT NULL UNIQUE, target_id BIGINT UNSIGNED NOT NULL, + organisation_kind VARCHAR(16) NOT NULL, organisation_id VARCHAR(64) NOT NULL, + recipient_kind VARCHAR(16) NOT NULL, recipient_key VARCHAR(64) NOT NULL, + basic_fallback INT NOT NULL, created_at BIGINT NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; diff --git a/website/node/progression-pol-runtime.mjs b/website/node/progression-pol-runtime.mjs index d0533df8..62293989 100644 --- a/website/node/progression-pol-runtime.mjs +++ b/website/node/progression-pol-runtime.mjs @@ -1,3 +1,5 @@ +import {awardOrganisationMission} from './organisation-quest-rewards.mjs'; +import {faithQuestEvidence} from './faith-quest-evidence.mjs'; import {mentorAward,currentMentorPolicy,mentorXP} from './pol-mentor-rewards.mjs'; import {grantSmugglerAffiliations,readSmugglerAffiliations} from './clandestine-institutions.mjs'; import {createPOLProgression} from './progression-pol.mjs'; @@ -34,10 +36,11 @@ export function createPOLProgressionRuntime(central,keys,{clock=Date.now,verifyO if(central.polRepeatablesEnabled){const deaths=await verifiedPOLDeathTotals(store,keys,input);for(const [metric,value]of deaths.totals)activity.totals.set(metric,value);activity.proofIds.push(...deaths.proofIds);} if(central.organisationResearchEnabled){const research=await researchEvidence(store,actor.id,season.season_id);for(const [metric,value]of research.totals)activity.totals.set(metric,value);activity.proofIds.push(...research.proofIds);} if(bank){const war=await warQuestEvidence(bank,store,input);for(const [metric,value]of war.totals)activity.totals.set(metric,value);activity.proofIds.push(...war.proofIds);} + if(central.clanFaithEnabled){const faith=await faithQuestEvidence(store,input);for(const [metric,value]of faith.totals)activity.totals.set(metric,value);activity.proofIds.push(...faith.proofIds);} applyElytraAlternative(activity.totals);return {...activity,season}; } const adapters={clock,authorizePlayer,authorizeIssuer,resolvePlayer, - resolveAward:async(actor,definition,tx,award)=>{const boost=await faithMultipliers(central,tx.sourceStore||tx,actor.id,{clock}),result=await mentorAward(tx,keys,{actor,definition,issuer:await authorizeIssuer(tx,definition),award,enabled:central.polMentorBonusEnabled});return faithAward(definition.research?await awardResearch(tx,actor,definition,result,{clock,personalMultiplier:boost.xp}):result,boost);}, + resolveAward:async(actor,definition,tx,award)=>{const boost=await faithMultipliers(central,tx.sourceStore||tx,actor.id,{clock}),issuer=await authorizeIssuer(tx,definition),result=await mentorAward(tx,keys,{actor,definition,issuer,award,enabled:central.polMentorBonusEnabled});return faithAward(definition.research?await awardResearch(tx,actor,definition,result,{clock,personalMultiplier:boost.xp}):definition.faithMission?await awardOrganisationMission(tx,actor,definition,issuer,result,{clock,personalMultiplier:boost.xp,mentorEnabled:central.polMentorBonusEnabled}):result,boost);}, authorizeObservation:async(actor,input,store)=>actor===observer||typeof verifyObservation==='function'&&await verifyObservation(actor,input,store),verifyAcquisition:async()=>false, authorizeClaim:async(actor,definition,polStore)=>{ if(definition.research)return authorizeResearchClaim(central,polStore,actor,definition,{clock}); diff --git a/website/node/progression-pol.mjs b/website/node/progression-pol.mjs index 452dfd80..db181f94 100644 --- a/website/node/progression-pol.mjs +++ b/website/node/progression-pol.mjs @@ -1,3 +1,4 @@ +import {faithQuestInitialReward} from '../control-panel/public/cp-v2/cp-v2-faith-quests.mjs'; import {repeatablePolicyDefinitions} from './pol-repeatable-quests.mjs'; import {PROGRESSION_SCHEMA} from './progression-schema.mjs'; import {ensureProgressionPolicy} from './progression-policy.mjs'; @@ -44,10 +45,12 @@ export function polPolicyKeys(keys){return { list:async id=>(await keys.list(id)).filter(k=>k.keyType==='progression-policy'&&k.scopeId.startsWith('policy:POL:')), consume:async input=>{const own=(await keys.list(input.accountId)).find(k=>k.code===input.code&&k.keyType==='progression-policy'&&k.scopeId.startsWith('policy:POL:'));if(!own)throw Error('POL policy instrument unavailable');return keys.consume({...input,apply:(tx,c)=>input.apply(polProgressionStore(tx),c)});} };} -export const ensurePOLProgressionPolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:POL_XP_POLICY,definitions:POL_QUEST_DEFINITIONS}); +export const ensurePOLProgressionPolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:POL_XP_POLICY,definitions:POL_QUEST_DEFINITIONS,rewardForDefinition:faithQuestInitialReward}); export const ensurePOLRepeatablePolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:{...POL_XP_POLICY,version:2},definitions:repeatablePolicyDefinitions()}); export const ensureElytraQuestPolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:{...POL_XP_POLICY,version:4},definitions:POL_QUEST_DEFINITIONS.filter(d=>d.branch==='elytra')}); export const ensureWarQuestPolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:{...POL_XP_POLICY,version:5},definitions:POL_QUEST_DEFINITIONS.filter(d=>d.branch==='war-service')}); + +export const ensureFaithQuestPolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:{...POL_XP_POLICY,version:6},definitions:POL_QUEST_DEFINITIONS.filter(d=>d.faithMission),rewardForDefinition:faithQuestInitialReward}); diff --git a/website/node/progression-policy.mjs b/website/node/progression-policy.mjs index 186e5735..9a711710 100644 --- a/website/node/progression-policy.mjs +++ b/website/node/progression-policy.mjs @@ -7,7 +7,7 @@ export function sixMonthsAfter(timestamp){ } // Installation is an ordinary recorded system instrument, not manual data editing. // Custom configuration is never overwritten by an application restart. -export async function ensureProgressionPolicy(db,keys,{clock=Date.now,policy=XP_POLICY,definitions=QUEST_DEFINITIONS}={}){ +export async function ensureProgressionPolicy(db,keys,{clock=Date.now,policy=XP_POLICY,definitions=QUEST_DEFINITIONS,rewardForDefinition=()=>null}={}){ const scopeId='policy:'+(policy.namespace==='pol'?'POL:':'')+policy.season+':v'+policy.version; const grant=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'progression-policy',scopeId,authorize:async()=>{}}); const key=(await keys.list(STAFF_OFFICE_ACCOUNT_ID)).find(k=>k.id===grant.id); @@ -20,7 +20,8 @@ export async function ensureProgressionPolicy(db,keys,{clock=Date.now,policy=XP_ await tx.query("INSERT INTO jarvis_progression_seasons(season_id,starts_at,ends_at,level_cap,curve_base,state) VALUES(?,?,?,?,?,'active')",[policy.season,now,sixMonthsAfter(now),policy.seasonCap,policy.base]); } let added=0;for(const d of definitions){const previous=await tx.first('SELECT definition_id FROM jarvis_quest_config WHERE definition_id=? FOR UPDATE',[d.id]);if(previous)continue; - await tx.query('INSERT INTO jarvis_quest_config(definition_id,revision,xp,reward_json,updated_by,updated_at) VALUES(?,?,?,NULL,?,?)',[d.id,1,d.xp,STAFF_OFFICE_ACCOUNT_ID,now]);added++; + const reward=rewardForDefinition(d);if(reward!==null&&(!reward||typeof reward!=='object'||Array.isArray(reward)||JSON.stringify(reward).length>4096))throw Error('Invalid initial quest reward'); + await tx.query('INSERT INTO jarvis_quest_config(definition_id,revision,xp,reward_json,updated_by,updated_at) VALUES(?,?,?,?,?,?)',[d.id,1,d.xp,reward===null?null:JSON.stringify(reward),STAFF_OFFICE_ACCOUNT_ID,now]);added++; } await tx.query('INSERT INTO jarvis_progression_history(id,account_id,key_id,action,details_json,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),STAFF_OFFICE_ACCOUNT_ID,keyId,'policy-configured',JSON.stringify({season:policy.season,added,monetaryPayouts:false}),now]); }}); diff --git a/website/node/server.mjs b/website/node/server.mjs index 20622fd4..0122fb91 100644 --- a/website/node/server.mjs +++ b/website/node/server.mjs @@ -1,3 +1,4 @@ +import {initializeClanFaith} from './clan-faith.mjs'; import {initializeWorldTrade} from './world-trade-governance.mjs'; import {POLITICAL_DECISION_SCHEMA} from './political-decisions.mjs'; import {initializeKitsets} from './kitsets.mjs'; @@ -125,7 +126,7 @@ export function createApplication(db,settings={},dependencies={}) { }; } export async function start(settings=process.env) { - const db=await openDatabase(settings);await db.query(POLITICAL_DECISION_SCHEMA);await initializeWorldTrade(db);db.worldTradeEnabled=settings.WORLD_TRADE_ENABLED==='true';db.politicalDecisionsEnabled=true;await initializeKitsets(db);if(db.organisationAccessEnabled)await initializeOrganisation(db);await initializeRanks(db);await initializeGitIdentities(db);await initializePublicRoster(db);await initializeLifeStatus(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;for(const sql of POLITICAL_APPOINTMENT_SCHEMA)await db.query(sql);db.politicalAppointmentsEnabled=true;await initializeShareLedger(db);if(settings.SYSTEM_BOARDS_ENABLED==='1')await prepareBoardKeyReadModel(db);const handle=createApplication(db,settings),origin=new URL(settings.PUBLIC_ORIGIN||'https://dunerealms.com').origin; + const db=await openDatabase(settings);await db.query(POLITICAL_DECISION_SCHEMA);await initializeWorldTrade(db);await initializeClanFaith(db);db.worldTradeEnabled=settings.WORLD_TRADE_ENABLED==='true';db.politicalDecisionsEnabled=true;await initializeKitsets(db);if(db.organisationAccessEnabled)await initializeOrganisation(db);await initializeRanks(db);await initializeGitIdentities(db);await initializePublicRoster(db);await initializeLifeStatus(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;for(const sql of POLITICAL_APPOINTMENT_SCHEMA)await db.query(sql);db.politicalAppointmentsEnabled=true;await initializeShareLedger(db);if(settings.SYSTEM_BOARDS_ENABLED==='1')await prepareBoardKeyReadModel(db);const handle=createApplication(db,settings),origin=new URL(settings.PUBLIC_ORIGIN||'https://dunerealms.com').origin; let forgeHeader=settings.FORGEJO_AUTH_HEADER; if(!forgeHeader&&settings.FORGEJO_URL){const config=await readFile(settings.FORGEJO_CONFIG_FILE||'/home/dunerealms/apps/forgejo/custom/conf/app.ini','utf8');forgeHeader=forgejoIdentityHeader(config);} if(settings.FORGEJO_URL&&!/^[A-Za-z0-9-]+$/.test(forgeHeader||''))throw Error('DuneGit proxy identity header is not configured.'); diff --git a/website/scripts/organisation-quest-grants.mjs b/website/scripts/organisation-quest-grants.mjs new file mode 100644 index 00000000..4653d06e --- /dev/null +++ b/website/scripts/organisation-quest-grants.mjs @@ -0,0 +1,15 @@ +import {fileURLToPath} from 'node:url'; +import {resolve} from 'node:path'; +import {execFileSync} from 'node:child_process'; +import {openDatabase} from '../node/mysql.mjs'; +import {openPostbankDatabase} from '../node/postbank-db.mjs'; +export async function organisationQuestGrantPlan(db,bank){ + const sql='SELECT DATABASE() db,@@hostname host,@@port port,@@server_id server_id',a=(await db.query(sql))[0],b=await bank.first(sql); + if(!a||!b||['host','port','server_id'].some(k=>String(a[k])!==String(b[k]))||!/^[a-z][a-z0-9_]{2,63}$/.test(b.db||''))throw Error('One transactional MySQL server required'); + const identity=(await db.query('SELECT CURRENT_USER() identity'))[0]?.identity?.split('@');if(identity?.length!==2||!identity.every(v=>/^[a-zA-Z0-9_.%:-]+$/.test(v)))throw Error('Unexpected central identity'); + return 'GRANT SELECT,INSERT ON `'+b.db+'`.`pb_organisation_quest_rewards` TO '+"'"+identity[0]+"'@'"+identity[1]+"';\n"; +} +if(process.argv[1]&&resolve(process.argv[1])===fileURLToPath(import.meta.url)){ + const apply=process.argv.slice(2).join(' ')==='--apply';if(process.argv.length>2&&!apply)throw Error('Use no arguments to review, or --apply'); + const db=await openDatabase(process.env),bank=await openPostbankDatabase(process.env);try{const sql=await organisationQuestGrantPlan(db,bank);if(apply){if(process.getuid?.()!==0)throw Error('Apply through the privileged deployment operator');execFileSync('mysql',['--batch'],{input:sql,stdio:['pipe','pipe','pipe']});console.log('Applied one scoped organisation reward receipt grant. No business records or balances changed.');}else process.stdout.write(sql);}finally{await Promise.allSettled([db.close(),bank?.close()]);} +} diff --git a/website/tests/bank-quest-activities.test.mjs b/website/tests/bank-quest-activities.test.mjs index 75af17ea..f51f074b 100644 --- a/website/tests/bank-quest-activities.test.mjs +++ b/website/tests/bank-quest-activities.test.mjs @@ -3,10 +3,11 @@ import {systemCharacterFixture} from './system-character-fixture.mjs';import {in test('only posted purchases across customers feed the existing purchase quest, with replay-safe order evidence',async()=>{ const f=await systemCharacterFixture(),sql=new DatabaseSync(':memory:');try{ const clock=()=>2000;await initializeProgression(f.db);await ensureProgressionPolicy(f.db,f.keys,{clock:()=>1000});await initializePersonalActivityEvents(f.db);const uuid=randomUUID();await f.db.query('UPDATE site_game_links SET minecraft_uuid=? WHERE user_id=?',[uuid,f.people.Member.id]); - sql.exec('CREATE TABLE pb_orders(id TEXT PRIMARY KEY,actor_id TEXT,source_id INT,target_id INT,state TEXT,mode TEXT,posted_at INT);CREATE TABLE pb_accounts(id INT PRIMARY KEY,client_number INT);CREATE TABLE pb_clients(client_number INT PRIMARY KEY,entity_id TEXT);CREATE TABLE pb_entities(id TEXT PRIMARY KEY,kind TEXT,external_key TEXT);'); + sql.exec('CREATE TABLE pb_orders(id TEXT PRIMARY KEY,actor_id TEXT,source_id INT,target_id INT,state TEXT,mode TEXT,posted_at INT);CREATE TABLE pb_accounts(id INT PRIMARY KEY,client_number INT);CREATE TABLE pb_clients(client_number INT PRIMARY KEY,entity_id TEXT);CREATE TABLE pb_entities(id TEXT PRIMARY KEY,kind TEXT,external_key TEXT);CREATE TABLE pb_exchange_levies(payment_id TEXT PRIMARY KEY);'); sql.prepare('INSERT INTO pb_entities VALUES(?,?,?)').run('owner','person',f.people.Member.id);sql.exec("INSERT INTO pb_clients VALUES(1,'owner'),(2,'other');INSERT INTO pb_accounts VALUES(1,1),(2,1),(3,2)"); const insert=(state,mode,target,actor=f.people.Member.id)=>{const id=randomUUID();sql.prepare('INSERT INTO pb_orders VALUES(?,?,1,?,?,?,1500)').run(id,actor,target,state,mode);return id;}; insert('queued','exchange',3);insert('posted','exchange',2);insert('posted','standard',3);insert('posted','exchange',3,f.people.Other.id); + const tax=insert('posted','exchange',3);sql.prepare('INSERT INTO pb_exchange_levies VALUES(?)').run(tax); const bank={query:async(text,args)=>sql.prepare(text).all(...args)},collect=createBankQuestActivities(f.db,bank,f.keys,{clock}),season={season_id:'S01',starts_at:1000}; await collect(f.people.Member,season);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_personal_activity_events')).n,0); const id=insert('posted','exchange',3);await collect(f.people.Member,season);await collect(f.people.Member,season); @@ -16,6 +17,7 @@ test('only posted purchases across customers feed the existing purchase quest, w }); test('earned DM is cumulative settled income across personal accounts, including incoming transfers and quest rewards, excluding refunds or self transfers',async()=>{ const db=new DatabaseSync(':memory:');try{ + db.exec('CREATE TABLE pb_organisation_quest_rewards(order_id INT,key_id INT,target_id INT)'); db.exec("CREATE TABLE pb_orders(id INT,source_id INT,target_id INT,amount_minor INT,state TEXT,mode TEXT,posted_at INT,memo TEXT);CREATE TABLE pb_accounts(id INT,client_number INT,balance_minor INT,system_key TEXT);CREATE TABLE pb_clients(client_number INT,entity_id TEXT);CREATE TABLE pb_entities(id TEXT,kind TEXT,external_key TEXT);INSERT INTO pb_accounts VALUES(1,1,9999999,NULL),(2,1,0,NULL),(3,2,0,NULL),(4,NULL,0,'sys_web_treasury'),(5,3,0,NULL);INSERT INTO pb_clients VALUES(1,'p'),(2,'other'),(3,'org');INSERT INTO pb_entities VALUES('p','person','player'),('other','person','someone'),('org','company','player');"); const insert=(id,from,to,amount,state,mode,at=1500)=>db.prepare('INSERT INTO pb_orders VALUES(?,?,?,?,?,?,?,NULL)').run(id,from,to,amount,state,mode,at); insert(1,4,1,100000,'posted','payroll');insert(2,3,2,80000,'posted','exchange'); @@ -25,6 +27,8 @@ test('earned DM is cumulative settled income across personal accounts, including const bank={query:async(text,args)=>db.prepare(text).all(...args)}; assert.deepEqual(await bankQuestIncome(bank,'player',1000,2000),{wages:1,earned:280000}); db.exec('UPDATE pb_accounts SET balance_minor=0');assert.deepEqual(await bankQuestIncome(bank,'player',1000,2000),{wages:1,earned:280000}); + insert(17,6,1,12000,'posted','system');assert.equal((await bankQuestIncome(bank,'player',1000,2000)).earned,280000); + db.exec('INSERT INTO pb_organisation_quest_rewards VALUES(17,17,1)');assert.equal((await bankQuestIncome(bank,'player',1000,2000)).earned,292000); assert.deepEqual(await bankQuestIncome(bank,'unknown',1000,2000),{wages:0,earned:0}); }finally{db.close();} }); diff --git a/website/tests/clan-faith-fixture.mjs b/website/tests/clan-faith-fixture.mjs new file mode 100644 index 00000000..ea365c82 --- /dev/null +++ b/website/tests/clan-faith-fixture.mjs @@ -0,0 +1,15 @@ +import {randomUUID} from 'node:crypto'; +import {companyFixture} from './company-deed-fixture.mjs'; +import {initializeClans} from '../control-panel/clans.mjs'; +import {POLITICAL_APPOINTMENT_SCHEMA} from '../node/political-appointments.mjs'; +import {PUBLIC_OFFICES} from '../node/public-government.mjs'; +import {STAFF_OFFICE_ACCOUNT_ID} from '../node/organisation-keys.mjs'; +import {initializeClanFaith,createClanFaith} from '../node/clan-faith.mjs'; +import {initializePOLProgression,polProgressionStore} from '../node/progression-pol.mjs'; +export async function clanFaithFixture(){ + const f=await companyFixture();f.db.sqlite.function('CONCAT',{varargs:true},(...v)=>v.join(''));f.db.sqlite.exec('DROP TABLE site_clan_members;DROP TABLE site_clans;ALTER TABLE political_office_terms ADD COLUMN id TEXT;ALTER TABLE political_office_terms ADD COLUMN kind TEXT;CREATE TABLE political_office_charters(office_key TEXT PRIMARY KEY,charter_kind TEXT,staff_key_id TEXT);');await initializeClans(f.db,{mysql:false});for(const sql of POLITICAL_APPOINTMENT_SCHEMA)await f.db.query(sql);await initializeClanFaith(f.db);await initializePOLProgression(f.db);const pol=polProgressionStore(f.db);await pol.query("INSERT INTO jarvis_progression_seasons VALUES('S01',0,9999999999,0,25,'active',1)");for(const person of Object.values(f.people))await pol.query('INSERT INTO jarvis_progression_accounts VALUES(?,10000,10000,28,1,0)',[person.id]); + const terms={};for(const [office,actor]of [['muad_dib',f.people.Owner],['veiled_concord',f.people.Ceo]]){const royal=await f.keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-office-royal',scopeId:'office:'+office,authorize:async()=>true});await f.keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-office-royal',code:royal.code,targetId:randomUUID(),requestId:randomUUID(),apply:(tx,{keyId})=>tx.query('INSERT INTO political_office_charters VALUES(?,?,?)',[office,'royal',keyId])});const o=PUBLIC_OFFICES.find(o=>o.key===office),id=randomUUID();terms[office]=id;await f.db.query("INSERT INTO political_office_terms(id,user_id,kind,faction,office,outcome,starts_at,expires_at) VALUES(?,?,?,?,?,'winner',0,9999999999)",[id,actor.id,o.kind,o.faction,o.office]);} + const clan=randomUUID();await f.db.query("INSERT INTO site_clans(id,name,name_key,tag,description,home_world,owner_id,created_at,updated_at) VALUES(?,'Faith Clan','faith clan','FAITH','Our clan','kaladam',?,1,1)",[clan,f.people.Other.id]); + for(const [person,role]of [[f.people.Other,'owner'],[f.people.Member,'member']]){const link=await f.db.first('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?',[person.id]);await f.db.query('INSERT INTO site_clan_members(user_id,minecraft_uuid,clan_id,clan_role,joined_at) VALUES(?,?,?,?,1)',[person.id,link.minecraft_uuid,clan,role]);} + let now=1000,outlawed=false;const service=createClanFaith(f.db,f.keys,{clock:()=>now,isOutlawed:async()=>outlawed});return{...f,clan,terms,pol,service,clock:()=>now,setTime:n=>now=n,outlaw:v=>outlawed=v,offer:(decisionId='NF-CONVERT')=>({decisionId,clanId:clan,requestId:randomUUID(),confirmed:true}),reply:(offerId,choice='accept')=>({offerId,choice,clanId:clan,requestId:randomUUID(),confirmed:true})}; +} diff --git a/website/tests/clan-faith.test.mjs b/website/tests/clan-faith.test.mjs new file mode 100644 index 00000000..d967e84b --- /dev/null +++ b/website/tests/clan-faith.test.mjs @@ -0,0 +1,30 @@ +import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto'; +import {clanFaithFixture} from './clan-faith-fixture.mjs'; +import {currentClanFaith,createClanFaithAPI} from '../node/clan-faith.mjs'; +import {CLAN_FAITH_POLICY as POLICY} from '../control-panel/public/clan-faith-policy.mjs'; +import {faithQuestEvidence} from '../node/faith-quest-evidence.mjs'; +test('a sealed invitation cannot change clan faith; only the legal owner can consent, idempotently',async()=>{const f=await clanFaithFixture();try{ + const offer=f.offer();await f.service.offer(f.people.Owner,offer);await f.service.offer(f.people.Owner,offer);assert.equal((await currentClanFaith(f.db,f.clan)).faith,null);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_faith_offers')).n,1);await assert.rejects(f.service.reply({...f.people.Owner,role:'owner'},f.reply(offer.requestId)),/legal owner/);const reply=f.reply(offer.requestId);await f.service.reply(f.people.Other,reply);await f.service.reply(f.people.Other,reply);assert.equal((await currentClanFaith(f.db,f.clan)).faith,'muad_dib');assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_faith_consents')).n,1);assert.equal((await f.db.first('SELECT owner_id FROM site_clans WHERE id=?',[f.clan])).owner_id,f.people.Other.id);assert.equal((await f.db.first('SELECT COUNT(*) n FROM site_clan_members WHERE clan_id=?',[f.clan])).n,2);await assert.rejects(f.service.reply(f.people.Other,{...reply,choice:'decline'}),/reference/); + }finally{f.db.close();}}); +test('parallel faiths cannot stack or bypass the clan cooldown, and revocation never revives a prior faith',async()=>{const f=await clanFaithFixture();try{ + const one=f.offer(),two=f.offer('BG-CONVERT');await f.service.offer(f.people.Owner,one);await f.service.offer(f.people.Ceo,two);await f.service.reply(f.people.Other,f.reply(one.requestId));await assert.rejects(f.service.reply(f.people.Other,f.reply(two.requestId)),/seven-day/);f.setTime(1000+POLICY.clanCooldownMs);const later=f.offer('BG-CONVERT');await f.service.offer(f.people.Ceo,later);const reply=f.reply(later.requestId);await f.service.reply(f.people.Other,reply);assert.equal((await currentClanFaith(f.db,f.clan)).faith,'veiled_concord');const row=await f.db.first('SELECT key_id FROM jarvis_faith_consents WHERE request_id=?',[reply.requestId]);await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[row.key_id]);assert.equal((await currentClanFaith(f.db,f.clan)).faith,null); + }finally{f.db.close();}}); +test('faith office cooldown survives succession, an expired invitation is inert, and outlawed conversions issue nothing',async()=>{const f=await clanFaithFixture();try{ + f.outlaw(true);const count=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;await assert.rejects(f.service.offer(f.people.Owner,f.offer()),/outlawed/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,count);f.outlaw(false);const offer=f.offer();await f.service.offer(f.people.Owner,offer);await assert.rejects(f.service.offer(f.people.Owner,f.offer()),/cooldown/);f.outlaw(true);await assert.rejects(f.service.reply(f.people.Other,f.reply(offer.requestId)),/outlawed/);assert.equal((await currentClanFaith(f.db,f.clan)).faith,null);f.outlaw(false);f.setTime(1000+POLICY.offerDurationMs);await assert.rejects(f.service.reply(f.people.Other,f.reply(offer.requestId)),/expired/); + f.setTime(2000);await f.db.query('UPDATE political_office_terms SET user_id=? WHERE id=?',[f.people.Member.id,f.terms.muad_dib]);await assert.rejects(f.service.offer(f.people.Member,f.offer()),/cooldown/); + }finally{f.db.close();}}); +test('revoked faith authority and consent journal failures leave no partial conversion or extra key',async()=>{const f=await clanFaithFixture();try{ + const offer=f.offer();await f.service.offer(f.people.Owner,offer);const before=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;f.db.sqlite.exec("CREATE TRIGGER consent_failure BEFORE INSERT ON jarvis_faith_consents BEGIN SELECT RAISE(ABORT,'consent journal failed');END");await assert.rejects(f.service.reply(f.people.Other,f.reply(offer.requestId)),/journal failed/);assert.equal((await currentClanFaith(f.db,f.clan)).faith,null);assert.equal((await f.db.first('SELECT state FROM jarvis_faith_offers')).state,'open');assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,before);f.db.sqlite.exec('DROP TRIGGER consent_failure');await f.db.query("UPDATE political_office_terms SET outcome='resigned' WHERE id=?",[f.terms.muad_dib]);await assert.rejects(f.service.reply(f.people.Other,f.reply(offer.requestId)),/authority changed/);assert.equal((await currentClanFaith(f.db,f.clan)).faith,null); + }finally{f.db.close();}}); +test('faith API rejects cross-origin consent, account overrides and unconfirmed replies',async()=>{const f=await clanFaithFixture();try{ + const api=createClanFaithAPI(f.db,f.keys,{service:f.service,authenticate:async()=>f.people.Owner,access:async()=>({nodes:['web.menu.game']})}),request=(body,origin='https://cp.dunerealms.com')=>new Request('https://cp.dunerealms.com/api/politics/faith',{method:'POST',headers:{origin,'Content-Type':'application/json'},body:JSON.stringify(body)});assert.equal((await api(request({action:'offer',...f.offer()},'https://evil.example'))).status,403);assert.equal((await api(request({action:'offer',...f.offer(),actorId:f.people.Other.id}))).status,400);assert.equal((await api(request({action:'reply',...f.reply(randomUUID()),confirmed:false}))).status,400); + }finally{f.db.close();}}); + +test('faith missions count current signed owner consent, not invitations, revoked proofs or former officeholders',async()=>{const f=await clanFaithFixture();try{ + const uuid=randomUUID();await f.db.query('UPDATE site_game_links SET minecraft_uuid=? WHERE user_id=?',[uuid,f.people.Owner.id]); + const evidence=()=>faithQuestEvidence(f.db,{accountId:f.people.Owner.id,minecraftUuid:uuid,startsAt:0,endsAt:9999999999,now:f.clock()}),metric='pol-faith-muad_dib-conversions',offer=f.offer(); + await f.service.offer(f.people.Owner,offer);assert.equal((await evidence()).totals.get(metric),0);const reply=f.reply(offer.requestId);await f.service.reply(f.people.Other,reply);assert.equal((await evidence()).totals.get(metric),1);assert.equal((await evidence()).proofIds.length,1); + await assert.rejects(faithQuestEvidence(f.db,{accountId:f.people.Member.id,minecraftUuid:uuid,startsAt:0,endsAt:9999999999,now:f.clock()}),/identity/); + await f.db.query("UPDATE political_office_terms SET outcome='resigned' WHERE id=?",[f.terms.muad_dib]);assert.equal((await evidence()).totals.get(metric),0);await f.db.query("UPDATE political_office_terms SET outcome='winner' WHERE id=?",[f.terms.muad_dib]); + await f.db.query('UPDATE organisation_keys SET revoked_at=? WHERE id=(SELECT key_id FROM jarvis_faith_consents WHERE request_id=?)',[f.clock(),reply.requestId]);assert.equal((await evidence()).totals.get(metric),0); + }finally{f.db.close();}}); diff --git a/website/tests/faith-mission-rewards.test.mjs b/website/tests/faith-mission-rewards.test.mjs new file mode 100644 index 00000000..271e8b93 --- /dev/null +++ b/website/tests/faith-mission-rewards.test.mjs @@ -0,0 +1,27 @@ +import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto'; +import {clanFaithFixture} from './clan-faith-fixture.mjs'; +import {initializeSystemCharacters,createSystemCharacters} from '../node/system-characters.mjs'; +import {initializeProgression} from '../node/progression-schema.mjs'; +import {ensureProgressionPolicy} from '../node/progression-policy.mjs'; +import {ensurePOLProgressionPolicy,ensureFaithQuestPolicy} from '../node/progression-pol.mjs'; +import {initializePOLActivityEvents} from '../node/pol-activity-events.mjs'; +import {createPOLProgressionRuntime} from '../node/progression-pol-runtime.mjs'; +import {createOrganisationFundedRewards} from '../node/organisation-quest-rewards.mjs'; +import {PostbankService} from '../node/postbank-service.mjs';import {BANK_VERSION} from '../node/postbank-catalogue.mjs';import {OFFICIAL_ACCOUNT} from '../node/official-account.mjs'; +test('one consenting faith community pays Reputation, small Personal XP and P&O office DM once through the existing quest claim',async()=>{ + const f=await clanFaithFixture();try{ + f.db.sqlite.exec("ALTER TABLE site_accounts ADD COLUMN password_salt TEXT;ALTER TABLE site_accounts ADD COLUMN created_at BIGINT;ALTER TABLE site_game_links ADD COLUMN minecraft_name TEXT;ALTER TABLE site_game_links ADD COLUMN linked_at BIGINT;CREATE TABLE site_game_identities(minecraft_uuid TEXT PRIMARY KEY,first_linked_at BIGINT,last_name TEXT);CREATE TABLE account_audit(id TEXT PRIMARY KEY,actor_id TEXT,action TEXT,details TEXT,created_at BIGINT);"); + await initializeSystemCharacters(f.db);await createSystemCharacters(f.db,f.keys,{clock:f.clock,authorizeOperator:async()=>true}).provision(f.people.Owner,'stilgar'); + await initializeProgression(f.db);await ensureProgressionPolicy(f.db,f.keys,{clock:f.clock});await ensurePOLProgressionPolicy(f.db,f.keys,{clock:f.clock});await ensureFaithQuestPolicy(f.db,f.keys,{clock:f.clock});await initializePOLActivityEvents(f.db);f.db.polActivityEventsEnabled=true; + await f.db.query('UPDATE site_game_links SET minecraft_uuid=? WHERE user_id=?',[randomUUID(),f.people.Owner.id]); + const runtime=createPOLProgressionRuntime(f.db,f.keys,{clock:f.clock}),id='POL-FAITH-CHURCH-01',offer=f.offer();await f.service.offer(f.people.Owner,offer);await runtime.collect(f.people.Owner); + assert.equal((await runtime.quests.list(f.people.Owner)).quests.find(q=>q.id===id).canClaim,false); + await f.service.reply(f.people.Other,f.reply(offer.requestId));await runtime.collect(f.people.Owner);const quest=(await runtime.quests.list(f.people.Owner)).quests.find(q=>q.id===id);assert.equal(quest.canClaim,true); + const before=(await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Owner.id])).total_xp,claim={definitionId:id,revision:quest.revision,requestId:randomUUID()};await runtime.quests.claim(f.people.Owner,claim);assert.equal((await runtime.quests.claim(f.people.Owner,claim)).replayed,true); + assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Owner.id])).total_xp,before+150);assert.equal((await f.db.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Owner.id])).total_xp,20); + await f.db.query("INSERT INTO site_accounts(id,username,display_name,role,password_hash) VALUES(?,?,?,'official_account','hash')",[OFFICIAL_ACCOUNT.id,OFFICIAL_ACCOUNT.username,'DuneRealms']); + const entity={id:randomUUID(),kind:'office',key:'leader:muad_dib',name:'Church of Muad’Dib',canView:true,canActivate:true,canPay:false};await new PostbankService(f.db,async()=>({entities:[entity],readAdmin:false,manageAdmin:false})).activate(f.people.Owner,{entityId:entity.id,packageKey:'pb_civic',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()}); + await f.db.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,reserved_minor,state,created_at) VALUES('sys_payroll_po','979','P&O',0,0,'active',1)"); + const worker=createOrganisationFundedRewards(f.db,f.db,f.keys,{clock:f.clock,verifyStorage:async()=>null});assert.equal((await worker.drain()).results[0].state,'paid');assert.equal((await worker.drain()).attempted,0);assert.equal((await f.db.first('SELECT amount_minor FROM pb_orders')).amount_minor,12500);assert.equal((await f.db.first('SELECT recipient_key FROM pb_organisation_quest_rewards')).recipient_key,'leader:muad_dib'); + }finally{f.db.close();} +}); diff --git a/website/tests/organisation-quest-grants.test.mjs b/website/tests/organisation-quest-grants.test.mjs new file mode 100644 index 00000000..33194b43 --- /dev/null +++ b/website/tests/organisation-quest-grants.test.mjs @@ -0,0 +1,9 @@ +import test from 'node:test';import assert from 'node:assert/strict'; +import {organisationQuestGrantPlan} from '../scripts/organisation-quest-grants.mjs'; +test('organisation reward settlement requests only receipt read/insert for the central connection on the same transactional server',async()=>{ + const identity={db:'dune_site',host:'central',port:3306,server_id:1},db={query:async sql=>[sql.includes('CURRENT_USER')?{identity:'dune_app@localhost'}:identity]},bank={first:async()=>({...identity,db:'dune_bank'})}; + assert.equal(await organisationQuestGrantPlan(db,bank),"GRANT SELECT,INSERT ON `dune_bank`.`pb_organisation_quest_rewards` TO 'dune_app'@'localhost';\n"); + await assert.rejects(organisationQuestGrantPlan(db,{first:async()=>({...identity,host:'foreign',db:'dune_bank'})}),/One transactional/); + await assert.rejects(organisationQuestGrantPlan(db,{first:async()=>({...identity,db:'dune_bank`;DROP'})}),/One transactional/); + await assert.rejects(organisationQuestGrantPlan({query:async sql=>[sql.includes('CURRENT_USER')?{identity:"app'@localhost"}:identity]},bank),/identity/); +}); diff --git a/website/tests/organisation-research.test.mjs b/website/tests/organisation-research.test.mjs index 52034dd9..4af154dc 100644 --- a/website/tests/organisation-research.test.mjs +++ b/website/tests/organisation-research.test.mjs @@ -6,6 +6,8 @@ import {GAME_ORGANISATION_SCHEMA} from '../node/game-organisations.mjs'; import {createGameResearch,researchDefinitions,researchEvidence,researchAuthority,researchClaims,authorizeResearchClaim,validateResearchDesign} from '../node/organisation-research.mjs'; import {awardResearch,researchRecipient,createResearchFundedRewards} from '../node/organisation-research-rewards.mjs'; import {BankFixture} from './postbank-fixture.mjs';import {PostbankService} from '../node/postbank-service.mjs';import {BANK_VERSION} from '../node/postbank-catalogue.mjs'; +import {createOrganisationFundedRewards} from '../node/organisation-quest-rewards.mjs'; +import {OFFICIAL_ACCOUNT} from '../node/official-account.mjs'; import {researchNode,researchId,researchUnlocked} from '../control-panel/public/organisation-research-policy.mjs'; import {defaultItemDesign} from '../control-panel/public/item-design-model.mjs'; import {supplyDefinition,researchSupplyDefinitions} from '../node/research-supplies.mjs'; @@ -78,11 +80,29 @@ test('reputation, cooldown and live specialist authority cannot be replaced by l await f.db.query('INSERT INTO site_company_members(company_id,user_id,joined_at) VALUES(?,?,?)',[f.company,f.people.Other.id,2000]);await f.db.query('UPDATE site_company_deeds SET owner_account_id=? WHERE company_id=?',[f.people.Other.id,f.company]);assert.equal(await researchAuthority(f.db,f.db,f.actor,f.owner),false);await assert.rejects(validateResearchDesign(f.db,f.db,f.actor,kit),/authority/); }finally{f.db.close();} }); -test('research DM is posted once to the organisation account, with pending delivery when no account exists',async()=>{ +test('legacy research DM retains its original organisation account and treasury settlement',async()=>{ const f=await fixture(),bank=new BankFixture();try{const d=f.definitions[0];await f.engine.start(f.actor,{definitionId:d.id});await f.submit(d);await f.engine.claim(f.actor,{definitionId:d.id,revision:1,requestId:randomUUID()}); + const job=await f.db.first('SELECT key_id,payload_json FROM jarvis_pol_quest_reward_jobs'),legacy=JSON.stringify({...JSON.parse(job.payload_json),schema:'organisation-research-funded-v1'});await f.db.query('UPDATE jarvis_pol_quest_reward_jobs SET payload_json=? WHERE key_id=?',[legacy,job.key_id]);await f.db.query('UPDATE jarvis_pol_quest_claims SET reward_json=? WHERE key_id=?',[legacy,job.key_id]); const worker=createResearchFundedRewards(f.db,bank,{clock:f.clock});assert.equal((await worker.drain()).results[0].state,'awaiting-funding-or-review');assert.equal((await bank.first('SELECT COUNT(*) n FROM pb_orders')).n,0); const entity={id:randomUUID(),kind:'company',key:f.company,name:'Test Enterprise',canView:true,canActivate:true,canPay:false};await new PostbankService(bank,async()=>({entities:[entity],readAdmin:false,manageAdmin:false})).activate(f.actor,{entityId:entity.id,packageKey:'pb_connect',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','Treasury',10000,0,'active',1)"); assert.equal((await worker.drain()).results[0].state,'paid');assert.equal((await worker.drain()).attempted,0);const order=await bank.first("SELECT * FROM pb_orders WHERE memo LIKE 'Research reward %'");assert.equal(order.amount_minor,1000);const recipient=await bank.first('SELECT c.entity_id FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number WHERE a.id=?',[order.target_id]);assert.equal(recipient.entity_id,entity.id); }finally{f.db.close();bank.close();} }); + +test('new Basic research rewards use P&O and the current legal owner, atomically and once only',async()=>{ + const f=await fixture();try{ + await f.db.query("INSERT INTO site_accounts(id,username,display_name,role,password_hash) VALUES(?,?,?,'official_account','hash')",[OFFICIAL_ACCOUNT.id,OFFICIAL_ACCOUNT.username,'DuneRealms']); + const d=f.definitions[0];await f.engine.start(f.actor,{definitionId:d.id});await f.submit(d);await f.engine.claim(f.actor,{definitionId:d.id,revision:1,requestId:randomUUID()}); + const worker=createOrganisationFundedRewards(f.db,f.db,f.keys,{clock:f.clock,verifyStorage:async()=>null}); + assert.equal((await worker.drain()).results[0].state,'awaiting-account-or-review');assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0); + await f.db.query('INSERT INTO site_company_members(company_id,user_id,joined_at) VALUES(?,?,?)',[f.company,f.people.Other.id,f.clock()]);await f.db.query('UPDATE site_company_deeds SET owner_account_id=? WHERE company_id=?',[f.people.Other.id,f.company]); + const entity={id:randomUUID(),kind:'person',key:f.people.Other.id,name:'New legal owner',canView:true,canActivate:true,canPay:false}; + await new PostbankService(f.db,async()=>({entities:[entity],readAdmin:false,manageAdmin:false})).activate(f.people.Other,{entityId:entity.id,packageKey:'pb_start',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()}); + await f.db.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,reserved_minor,state,created_at) VALUES('sys_payroll_po','979','P&O',0,0,'active',1)"); + f.db.sqlite.exec("CREATE TRIGGER reward_journal_failure BEFORE INSERT ON pb_organisation_quest_rewards BEGIN SELECT RAISE(ABORT,'journal failure');END");assert.equal((await worker.drain()).results[0].state,'awaiting-account-or-review');assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);assert.equal((await f.db.first("SELECT balance_minor FROM pb_accounts WHERE system_key='sys_payroll_po'")).balance_minor,0);f.db.sqlite.exec('DROP TRIGGER reward_journal_failure'); + assert.equal((await worker.drain()).results[0].state,'paid');assert.equal((await worker.drain()).attempted,0); + const receipt=await f.db.first('SELECT * FROM pb_organisation_quest_rewards');assert.equal(receipt.recipient_kind,'person');assert.equal(receipt.recipient_key,f.people.Other.id);assert.equal(receipt.basic_fallback,1); + assert.equal((await f.db.first("SELECT balance_minor FROM pb_accounts WHERE system_key='sys_payroll_po'")).balance_minor,-1000);assert.equal((await f.db.first('SELECT SUM(amount_minor) n FROM pb_entries')).n,0); + }finally{f.db.close();} +}); diff --git a/website/tests/progression-design.test.mjs b/website/tests/progression-design.test.mjs index affc8aba..99973f14 100644 --- a/website/tests/progression-design.test.mjs +++ b/website/tests/progression-design.test.mjs @@ -1,3 +1,3 @@ import test from 'node:test';import assert from 'node:assert/strict';import {MISSION_BRANCHES,DECISION_CATALOGUE} from '../control-panel/public/cp-v2/cp-v2-progression-catalogue.mjs'; test('accepted design includes all nine personal branches, repair quest and private discovery placeholder',()=>{assert.equal(MISSION_BRANCHES.filter(b=>/^[a-i]$/.test(b.id)).length,9);const equipment=MISSION_BRANCHES.find(b=>b.id==='h').missions;assert.match(equipment[0].title,/faction kit/i);assert.equal(equipment[1].title,'Repair Your Starter Kit');assert.equal(MISSION_BRANCHES.find(b=>b.id==='c').missions.length,8);assert(MISSION_BRANCHES.find(b=>b.id==='discoveries').missions.every(m=>m.hidden&&m.optional));assert(MISSION_BRANCHES.find(b=>b.id==='i').missions.filter(m=>/Sell/.test(m.title)).every(m=>m.optional));const ids=MISSION_BRANCHES.flatMap(b=>b.missions.map(m=>m.id));assert.equal(new Set(ids).size,ids.length);}); -test('original decision proposals and the parallel Church clone retain unique references and configured defaults',()=>{assert.equal(DECISION_CATALOGUE.length,80);assert.equal(new Set(DECISION_CATALOGUE.map(d=>d.id)).size,80);assert.deepEqual(Object.fromEntries(['IMP','ATR','HAR','COR','ORD','FRE','BG','NF','SG','CLD'].map(id=>[id,DECISION_CATALOGUE.filter(d=>d.office===id).length])),{IMP:10,ATR:8,HAR:8,COR:8,ORD:8,FRE:8,BG:7,NF:10,SG:8,CLD:5});assert.equal(DECISION_CATALOGUE.find(d=>d.id==='IMP-01').level,50);assert(DECISION_CATALOGUE.every(d=>Number.isInteger(d.level)&&d.level>=0&&Number.isInteger(d.xp)&&d.xp>=0&&d.cost));}); +test('decision catalogue keeps five to ten distinct proposals per office, including consenting faith invitations',()=>{assert.equal(DECISION_CATALOGUE.length,81);assert.equal(new Set(DECISION_CATALOGUE.map(d=>d.id)).size,81);assert.deepEqual(Object.fromEntries(['IMP','ATR','HAR','COR','ORD','FRE','BG','NF','SG','CLD'].map(id=>[id,DECISION_CATALOGUE.filter(d=>d.office===id).length])),{IMP:10,ATR:8,HAR:8,COR:8,ORD:8,FRE:8,BG:8,NF:10,SG:8,CLD:5});assert(DECISION_CATALOGUE.some(d=>d.id==='NF-CONVERT'));assert(!DECISION_CATALOGUE.some(d=>d.id==='NF-01'));assert.equal(DECISION_CATALOGUE.find(d=>d.id==='IMP-01').level,50);assert(DECISION_CATALOGUE.every(d=>Number.isInteger(d.level)&&d.level>=0&&Number.isInteger(d.xp)&&d.xp>=0&&d.cost));});