From 28a322027bfb52168eb74c0ba1bae6a5ff9838f6 Mon Sep 17 00:00:00 2001 From: Dev Date: Wed, 25 Nov 2026 04:43:25 +0100 Subject: [PATCH] Fund independent Naib Council decisions through existing sietch banking --- .../public/cp-v2/cp-v2-decision-audit.mjs | 3 +- .../public/cp-v2/cp-v2-naib-council.css | 16 ++++--- .../public/cp-v2/cp-v2-naib-council.mjs | 12 ++--- .../cp-v2/cp-v2-progression-catalogue.mjs | 3 +- .../public/cp-v2/cp-v2-progression.mjs | 1 + .../public/jarvis-master-keys.mjs | 1 + .../public/naib-council-policy.mjs | 2 + website/control-panel/server.mjs | 5 ++- .../osticket/dev-jarvis-catalogue.json | 45 ++++++++++++++++++- website/node/naib-council-funding.mjs | 32 +++++++++++++ website/node/naib-council.mjs | 14 +++--- website/node/organisation-keys.mjs | 2 +- website/tests/political-decisions.test.mjs | 9 ++++ 13 files changed, 120 insertions(+), 25 deletions(-) create mode 100644 website/control-panel/public/naib-council-policy.mjs create mode 100644 website/node/naib-council-funding.mjs 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 47eba509..61bee6a4 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 {naibDecision} from '../naib-council-policy.mjs'; import {houseFaithDecision} from '../house-faith-policy.mjs'; import {clanFaithDecision} from '../clan-faith-policy.mjs'; import {tradeDecision} from '../world-trade-policy.mjs'; @@ -14,5 +15,5 @@ function paidDecisionGap(id){ const kind=politicalDecision(id)?.kind,base='Current office, Reputation, authorised office funding and successor-safe cooldown checked atomically. '; return base+(kind==='ballot'?'Paid consultation records a frozen institutional electorate. Current independent clan owners or original Royal Great House mandates cast one signed vote per seat; no personal election allocation is consumed. Shared quorum and strict-majority tally closes once; ties and low participation fail. This is a nonbinding resolution, with no automatic law or war change.':kind==='agreement'?'A confidential proposal is delivered only to its original receiving office holder or legal company owner. Acceptance or refusal requires that same current mandate or company ownership, a signed response and the 72-hour window. Accepted terms expire with either mandate; no votes, ownership or war rights move.':kind==='clan-grant'?'The current native clan deed selects its own active bank account or its legal Basic owner. The balanced transfer, recorded purpose and proportional Reputation commit together; retries cannot pay twice.':kind==='report'?'Verified aggregate snapshot, fee and reward share one receipt; no private identities or balances are disclosed.':kind==='event'?'The existing political calendar and event history commit with the fee and reward; a diplomatic meeting does not manufacture participant consent.':['tariff','guild-discount'].includes(kind)?'The latest signed current-mandate policy controls new Guild quote and boarding fares. Confirmed tickets retain their amount; no travel or embargo rights change.':'Existing publication/profile consumers display the result.'); } -export const DECISION_AUDIT=Object.freeze(DECISION_CATALOGUE.map(d=>Object.freeze({id:d.id,office:d.office,status:houseFaithDecision(d.id)||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:houseFaithDecision(d.id)?'createHouseFaithLaws / missionaryFaithOutlawed':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:houseFaithDecision(d.id)?'Royal House authority and Reputation checked before a sealed 48-hour personal referendum. Seven-day office cooldown survives succession; quorum and strict majority required. Only future invitations and clan-owner acceptance are gated by the latest live law; existing allegiance and earned rewards remain unchanged.':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)?paidDecisionGap(d.id):faithBlessing(d.id)?'Current faith leader/officer deed, owner-approved clan allegiance, appointment expiry and cooldown are checked centrally. Old Faith and New Faith use the same capped bonus consumer; historical queued rewards retain their claim-time consent proof.':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:!!houseFaithDecision(d.id)||!!clanFaithDecision(d.id)||!!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:naibDecision(d.id)||houseFaithDecision(d.id)||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:naibDecision(d.id)?'createNaibCouncil / createNaibCouncilFunding':houseFaithDecision(d.id)?'createHouseFaithLaws / missionaryFaithOutlawed':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:naibDecision(d.id)?'Current independent sietch deed, Reputation10,1000DM from its active account or the legal Basic owner,200 Reputation and24h seat cooldown. Fee, signed key, proposal electorate and reward commit together. No free production fallback; one Council vote per current sietch. Personal election votes are unchanged.':houseFaithDecision(d.id)?'Royal House authority and Reputation checked before a sealed 48-hour personal referendum. Seven-day office cooldown survives succession; quorum and strict majority required. Only future invitations and clan-owner acceptance are gated by the latest live law; existing allegiance and earned rewards remain unchanged.':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)?paidDecisionGap(d.id):faithBlessing(d.id)?'Current faith leader/officer deed, owner-approved clan allegiance, appointment expiry and cooldown are checked centrally. Old Faith and New Faith use the same capped bonus consumer; historical queued rewards retain their claim-time consent proof.':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:!!naibDecision(d.id)||!!houseFaithDecision(d.id)||!!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-naib-council.css b/website/control-panel/public/cp-v2/cp-v2-naib-council.css index e294e36b..9fc86485 100644 --- a/website/control-panel/public/cp-v2/cp-v2-naib-council.css +++ b/website/control-panel/public/cp-v2/cp-v2-naib-council.css @@ -1,8 +1,10 @@ -.naib-council{--text:#392b21;--gold:#876224;--line:#b69a63;color:#392b21;min-width:0} -.naib-council .cp-v2-template-heading{border:1px solid #aa884d;border-radius:12px;padding:24px;background:linear-gradient(100deg,#f2e5c9f5,#f2e5c9d9),url('https://www.dunerealms.com/assets/arrakis.webp') center/cover} -.naib-council .organisation-settings-card,.naib-council .politics-card{background:linear-gradient(135deg,#fbf3e4,#e9dcc1);border:1px solid #b69a63;border-radius:12px;padding:22px;margin-block:16px;min-width:0;color:#392b21} -.naib-council h3,.naib-council h4{color:#694b28}.naib-council a{color:#713c25}.naib-council label{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin-block:14px}.naib-council label:has(input:not([type=checkbox])),.naib-council label:has(textarea){display:grid} -.naib-council input:not([type=checkbox]),.naib-council textarea,.naib-council select{max-width:100%;min-width:0;color:#392b21;background:#fff9ed;border:1px solid #a9916d;border-radius:7px;padding:10px;box-sizing:border-box}.naib-council input[type=checkbox]{width:18px;height:18px;flex:none;accent-color:#876224} -.naib-council button{color:#fff6df;background:#76532f;border:1px solid #9c783d;border-radius:7px;padding:10px 16px;cursor:pointer}.naib-council button:disabled{opacity:.55;cursor:default}.naib-council button:focus-visible,.naib-council select:focus-visible{outline:3px solid #2c718a;outline-offset:3px}.naib-council button[role=tab][aria-selected=true]{background:#3c606b;color:#fff9ed} -.naib-council table{width:100%;border-collapse:collapse}.naib-council th,.naib-council td{padding:12px;text-align:left;border-bottom:1px solid #c4b18a;overflow-wrap:anywhere}.naib-council th{background:#e1cba2;color:#49371e}.naib-council small,.naib-council p{overflow-wrap:anywhere}.naib-council .applications-table-wrap{overflow:auto;max-width:100%}.naib-council .cp-v2-template-tabs{display:flex;flex-wrap:wrap;gap:8px} +.naib-council{--text:#efe4b9;--gold:#d6b964;--line:#8f7943;color:#efe4b9;min-width:0} +.naib-council .cp-v2-template-heading{border:1px solid #a58a45;border-radius:12px;padding:24px;background:linear-gradient(100deg,#09251cf2,#153a2de3),url('https://www.dunerealms.com/assets/arrakis.webp') center/cover} +.naib-council .organisation-settings-card,.naib-council .politics-card{background:linear-gradient(135deg,#173b2e,#102b22);border:1px solid #8f7943;border-radius:12px;padding:22px;margin-block:16px;min-width:0;color:#efe4b9} +.naib-council h3,.naib-council h4{color:#f1df9e}.naib-council a{color:#dcc477}.naib-council label{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin-block:14px}.naib-council label:has(input:not([type=checkbox])),.naib-council label:has(textarea){display:grid} +.naib-council input:not([type=checkbox]),.naib-council textarea,.naib-council select{max-width:100%;min-width:0;color:#efe4b9;background:#0b281f;border:1px solid #8f7943;border-radius:7px;padding:10px;box-sizing:border-box}.naib-council input[type=checkbox]{width:18px;height:18px;flex:none;accent-color:#d6b964} +.naib-council button{color:#f3e5b8;background:#284b34;border:1px solid #a58a45;border-radius:7px;padding:10px 16px;cursor:pointer}.naib-council button:disabled{opacity:.55;cursor:default}.naib-council button:focus-visible,.naib-council select:focus-visible{outline:3px solid #83b9a6;outline-offset:3px}.naib-council button[role=tab][aria-selected=true]{background:#4c673d;color:#fff3cb} +.naib-council table{width:100%;border-collapse:collapse}.naib-council th,.naib-council td{padding:12px;text-align:left;border-bottom:1px solid #527057;overflow-wrap:anywhere}.naib-council th{background:#254b39;color:#f0d78d}.naib-council small,.naib-council p{overflow-wrap:anywhere}.naib-council .applications-table-wrap{overflow:auto;max-width:100%}.naib-council .cp-v2-template-tabs{display:flex;flex-wrap:wrap;gap:8px} @media(max-width:650px){.naib-council .organisation-settings-card,.naib-council .politics-card{padding:14px}.naib-council .cp-v2-template-tabs button{flex:1 1 120px}.naib-council th,.naib-council td{padding:8px}} + +.naib-council input,.naib-council textarea,.naib-council select,.naib-council button{font:inherit}.naib-council [hidden]{display:none!important} diff --git a/website/control-panel/public/cp-v2/cp-v2-naib-council.mjs b/website/control-panel/public/cp-v2/cp-v2-naib-council.mjs index 0532e340..8fe9c74d 100644 --- a/website/control-panel/public/cp-v2/cp-v2-naib-council.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-naib-council.mjs @@ -5,7 +5,7 @@ import {renderVoting} from '../election-voting-view.mjs'; import {mountElectionResults} from './cp-v2-election-results.mjs'; export function mountNaibCouncil(host){ if(!document.querySelector('link[data-naib-council]')){const style=el('link');style.rel='stylesheet';style.href=new URL('./cp-v2-naib-council.css',import.meta.url).href;style.dataset.naibCouncil='';document.head.append(style);} - const controller=new AbortController(),api=createUserAPI(fetch,controller.signal);let active=true,busy=false,disposeResults=()=>{}; + const controller=new AbortController(),api=createUserAPI(fetch,controller.signal);let active=true,busy=false,selectedTab='sietches',selectedAccount='',disposeResults=()=>{}; const status=el('p','Loading the Council of Naibs…');status.setAttribute('role','status');host.replaceChildren(status); async function load(){try{const [data,session]=await Promise.all([api.request('/api/politics/naibs'),api.request('/api/auth/session')]);if(!active)return;draw(data,session.user);}catch(error){if(active)status.textContent=error.message;}} function draw(data,user){ @@ -17,16 +17,16 @@ export function mountNaibCouncil(host){ const form=el('form'),kind=el('select'),title=el('input'),message=el('textarea'),confirm=el('input'),send=el('button','Submit proposal');title.maxLength=100;title.required=true;message.rows=5;message.minLength=20;message.maxLength=4000;message.required=true;confirm.type='checkbox';confirm.required=true; const available=data.proposalKinds||[]; for(const entry of available){const option=el('option',entry.kind==='decision'?'Council proposal':'Imperial Peace offer');option.value=entry.kind;kind.append(option);} - const cooldownNotice=el('p');form.append(cooldownNotice); - const refreshProposal=()=>{const policy=available.find(p=>p.kind===kind.value);send.disabled=busy||!policy?.canPropose;cooldownNotice.textContent=!policy?'Only a current Naib or the Emperor can submit an eligible proposal.':policy.canPropose?'One proposal per sietch every 24 hours. Imperial Peace offers share one Council-wide 24-hour cooldown.':'Available again '+new Date(policy.cooldownUntil).toLocaleString('en-GB',{timeZone:'UTC'})+' UTC.';}; - kind.onchange=refreshProposal;refreshProposal(); + const fundingLabel=el('label','Sietch funding account'),account=el('select');fundingLabel.append(account);for(const a of data.funding?.accounts||[]){const option=el('option',a.name+' · '+a.number+' · '+(Number(a.availableMinor)/100).toFixed(2)+' DM available');option.value=a.id;account.append(option);}if(data.funding?.accounts?.some(a=>a.id===selectedAccount))account.value=selectedAccount;const cooldownNotice=el('p');form.append(cooldownNotice,fundingLabel); + const refreshProposal=()=>{const policy=available.find(p=>p.kind===kind.value),paid=kind.value==='decision'&&data.funding?.required,selected=data.funding?.accounts?.find(a=>a.id===account.value),canFund=!paid||!!selected&&BigInt(selected.availableMinor)>=BigInt(data.funding.feeMinor);fundingLabel.hidden=!paid;account.disabled=busy||!paid;send.textContent=paid?'Pay '+(data.funding.feeMinor/100).toLocaleString('en-GB')+' DM and submit':'Submit proposal';send.disabled=busy||!policy?.canPropose||!canFund;cooldownNotice.textContent=paid&&!data.funding.available?'Council banking is unavailable; no proposal payment can be made.':paid&&data.funding.levelNow{selectedAccount=account.value;refreshProposal();};refreshProposal(); for(const [text,field]of [['Proposal type',kind],['Title',title],['Terms and message',message],['I confirm this proposal',confirm]]){const label=el('label',text);label.append(field);form.append(label);}send.type='submit';form.append(send);diplomacy.append(form);let requestId=crypto.randomUUID();form.oninput=()=>{if(!busy)requestId=crypto.randomUUID();}; const lock=value=>{busy=value;for(const field of [title,message,confirm])field.disabled=value;kind.disabled=value||available.length<2;refreshProposal();};lock(false); - form.onsubmit=async event=>{event.preventDefault();if(busy||!available.find(p=>p.kind===kind.value)?.canPropose||!form.reportValidity())return;const input={requestId,kind:kind.value,title:title.value,message:message.value,confirmed:confirm.checked};lock(true);status.textContent='Recording the proposal…';try{await api.request('/api/politics/naibs/propose',input);await load();status.textContent='Council proposal recorded.';}catch(error){if(active){status.textContent=error.message;lock(false);}}}; + form.onsubmit=async event=>{event.preventDefault();if(busy||!available.find(p=>p.kind===kind.value)?.canPropose||!form.reportValidity())return;const input={requestId,kind:kind.value,title:title.value,message:message.value,confirmed:confirm.checked,...(kind.value==='decision'&&data.funding?.required?{sourceAccount:account.value}:{})};lock(true);status.textContent='Recording the proposal…';try{await api.request('/api/politics/naibs/propose',input);await load();status.textContent='Council proposal recorded.';}catch(error){if(active){status.textContent=error.message;lock(false);}}}; for(const dossier of data.dossiers){const card=el('article',undefined,'organisation-settings-card');card.append(el('small',dossier.reference),el('h3',dossier.title),el('p',dossier.message),el('p',dossier.state==='closed'?'Decision: '+dossier.result:'Voting closes '+new Date(dossier.closesAt).toLocaleString('en-GB',{timeZone:'UTC'})+' UTC'),el('p',dossier.electorate+' sietches in the recorded electorate'));if(dossier.tally)card.append(el('p',dossier.tally.participation+' votes · quorum '+dossier.tally.quorum+' · '+Object.entries(dossier.tally.counts).map(([choice,total])=>choice+': '+total).join(' · ')));if(dossier.ownVote)card.append(el('p','Your sietch voted: '+dossier.ownVote));else if(dossier.canVote){const choice=el('select');for(const value of dossier.choices){const option=el('option',value);option.value=value;choice.append(option);}const consent=el('label'),check=el('input');check.type='checkbox';consent.append(check,el('span','I confirm this definitive vote for my sietch.'));const button=el('button','Cast Council vote');button.type='button';button.onclick=async()=>{if(busy||!check.checked){status.textContent='Confirm your vote first.';return;}busy=true;button.disabled=true;try{await api.request('/api/politics/naibs/vote',{dossierId:dossier.id,choice:choice.value,confirmed:true});await load();status.textContent='Council vote recorded.';}catch(error){if(active){status.textContent=error.message;button.disabled=false;}}finally{busy=false;}};card.append(choice,consent,button);} (dossier.kind==='imperial-peace'?diplomacy:decisions).append(card);} elections.append(el('p','Naibs elect the chair from their own members. The existing general Fremen leadership election remains separate.'),renderApplications({user,context:{linked:true,naib:data.naib,clanId:data.seatId},kind:'naib_chair'}),renderVoting('naib_chair')); powers.append(el('h3','Council powers'),el('p','Political powers are awaiting a separate design. No gameplay action is available from this page.')); - const page=createCPV2Page({shellHost:host,title:'Council of Naibs',description:'House of Arrakis · independent sietches of Arrakduin',artwork:'seals/office-house_leader.png',tabs:[{id:'sietches',label:'Sietches',content:seats},{id:'decisions',label:'Decisions',content:decisions},{id:'diplomacy',label:'Diplomacy',content:diplomacy},{id:'elections',label:'Chair election',content:elections},{id:'results',label:'Results',content:results},{id:'powers',label:'Powers',content:powers}],onActivate:id=>{if(id==='results'){disposeResults();disposeResults=mountElectionResults(results,{kind:'naib_chair'});}}});host.replaceChildren(status,page.root);page.root.classList.add('naib-council');busy=false; + const restoreTab=selectedTab,page=createCPV2Page({shellHost:host,title:'Council of Naibs',description:'House of Arrakis · independent sietches of Arrakduin',artwork:'seals/office-house_leader.png',tabs:[{id:'sietches',label:'Sietches',content:seats},{id:'decisions',label:'Decisions',content:decisions},{id:'diplomacy',label:'Diplomacy',content:diplomacy},{id:'elections',label:'Chair election',content:elections},{id:'results',label:'Results',content:results},{id:'powers',label:'Powers',content:powers}],onActivate:id=>{selectedTab=id;if(id==='results'){disposeResults();disposeResults=mountElectionResults(results,{kind:'naib_chair'});}}});host.replaceChildren(status,page.root);page.root.classList.add('naib-council');page.activate(restoreTab);busy=false; } void load();return()=>{active=false;controller.abort();disposeResults();}; } 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 9053258c..9bba337f 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 {naibDecision} from '../naib-council-policy.mjs'; import {POLITICAL_DECISION_CATALOGUE} from '../political-decision-policy.mjs'; import {CLAN_FAITH_DECISIONS} from '../clan-faith-policy.mjs'; import {HOUSE_FAITH_DECISIONS} from '../house-faith-policy.mjs'; @@ -950,4 +951,4 @@ export const DECISION_CATALOGUE=[ "cost": "2,500 / 72h", "office": "CLD" } -,...POLITICAL_DECISION_CATALOGUE.filter(d=>d.id.endsWith('-PROCLAIM')),...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'}))).concat(HOUSE_FAITH_DECISIONS.map(d=>({...d,office:({atreides:'ATR',harkonnen:'HAR',corrino:'COR',ordos:'ORD',fremen:'FRE'})[d.office],xpType:'pol'}))).map(decision=>Object.freeze({...decision,...POLITICAL_DECISION_CATALOGUE.find(d=>d.id===decision.id),...FAITH_BLESSING_CATALOGUE.find(d=>d.id===decision.id),cooldownMs:FAITH_BLESSING_CATALOGUE.find(d=>d.id===decision.id)?.cooldownMs??POLITICAL_DECISION_CATALOGUE.find(d=>d.id===decision.id)?.cooldownMs??decisionCooldownMs(decision)})); +,...POLITICAL_DECISION_CATALOGUE.filter(d=>d.id.endsWith('-PROCLAIM')),...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'}))).concat(HOUSE_FAITH_DECISIONS.map(d=>({...d,office:({atreides:'ATR',harkonnen:'HAR',corrino:'COR',ordos:'ORD',fremen:'FRE'})[d.office],xpType:'pol'}))).map(decision=>Object.freeze({...decision,...(naibDecision(decision.id)?{...naibDecision(decision.id),executionStatus:'naib-council-controller'}:{}),...POLITICAL_DECISION_CATALOGUE.find(d=>d.id===decision.id),...FAITH_BLESSING_CATALOGUE.find(d=>d.id===decision.id),cooldownMs:FAITH_BLESSING_CATALOGUE.find(d=>d.id===decision.id)?.cooldownMs??POLITICAL_DECISION_CATALOGUE.find(d=>d.id===decision.id)?.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 0d0c1016..142d83d3 100644 --- a/website/control-panel/public/cp-v2/cp-v2-progression.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-progression.mjs @@ -43,6 +43,7 @@ export function mountProgressionDesign(host,{context='personal',dashboard=false, const roster=el('div',undefined,'progression-roster');for(const member of members.slice(0,12)){const person=el('figure');const avatar=member.avatar||member.avatarUrl||(member.username?'https://cp.dunerealms.com/api/avatars/face/roster/'+encodeURIComponent(member.username):null);if(avatar&&/^https:\/\//.test(avatar)){const img=el('img');img.src=avatar;img.alt='';person.append(img);}else person.append(image(CONTEXTS[activeContext][1]));person.append(el('figcaption',member.displayName||member.display_name||member.name||member.username||'Member'));roster.append(person);}if(!members.length)roster.append(image(CONTEXTS[activeContext][1]),el('p','Your verified roster and avatars will appear here. No sample memberships are assigned.'));gallery.append(roster); } 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&&row.executionStatus==='naib-council-controller'){const council=el('a','Open Council of Naibs →');council.href='https://www.dunerealms.com/government.html#household/naibs';pane.append(el('p','Independent sietch assembly: Reputation10,1,000 DM and200 Reputation points. One proposal per sietch every24h; existing Council voting and chair election remain separate.'),council);return pane;} if(isDecision&&faithBlessing(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;} diff --git a/website/control-panel/public/jarvis-master-keys.mjs b/website/control-panel/public/jarvis-master-keys.mjs index b9b359b1..77bd9a7c 100644 --- a/website/control-panel/public/jarvis-master-keys.mjs +++ b/website/control-panel/public/jarvis-master-keys.mjs @@ -16,6 +16,7 @@ export const MASTER_KEY_TEMPLATES=[ {id:'politics',label:'POL & orders',actions:[ action('politics.institutional-consultation','Convene an institutional resolution vote','entity-state',[field('decisionId','Registered Council decision','select',{options:['IMP-05','ATR-02']}),field('sourceAccount','Authorised office funding account'),field('title','Resolution title'),field('terms','Consultation terms','textarea'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / createPoliticalConsultations',executionStatus:'current-office-and-institutional-seat-consumer',effect:'Landsraad: Emperor, Reputation25,5000DM,400 Reputation,72h consultation/cooldown; snapshot occupied Royal Great House offices. Caladan: Atreides holder,Reputation15,2000DM,250 Reputation,48h consultation/cooldown; snapshot native active clans. The issuing mandate must cover the entire ballot. Current independent legal clan owners or the original House mandates cast one signed institutional vote per seat. More-than-half participation and strict majority; ties fail. Immutable final tally; no personal election votes, ownership, law or war participation change. Fee, electorate, scoped key and Reputation commit together.'}), action('politics.institutional-vote','Cast an institutional resolution vote','entity-state',[field('ballotId','Consultation UUID'),field('seatKey','Current institutional seat'),field('choice','Vote','select',{options:['yes','no']}),field('requestId','Vote UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalConsultations.vote / reconcile',executionStatus:'current-independent-institutional-deed-only',effect:'Revalidate the signed live ballot, original issuing mandate and current independent institutional seat under the same transaction. One signed vote per seat; exact retries retain the receipt. No fee or Reputation for voting. Mother control does not confer client clan votes; revoked recorded votes cannot be replaced. Final tally uses the existing quorum/strict-majority rule and remains fixed after closure.'}), + action('politics.naib-council-assembly','Fund an independent sietch Council proposal','entity-state',[field('requestId','Council request UUID'),field('sourceAccount','Authorised sietch funding account'),field('title','Council proposal title'),field('message','Consultation terms','textarea')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createNaibCouncil.propose / createNaibCouncilFunding',executionStatus:'current-independent-sietch-owner-funded-council',effect:'FRE01 uses the existing24h Council, current independent Naib ownership and one institutional vote per recognised sietch. Reputation10,1000DM to Tax and200 Reputation points;24h seat cooldown survives ownership transfer. Keyed sietches fund their own active payment account; Basic sietches use the current legal owner’s active personal account. Source authority, balances, Reputation, ordinary scoped ESK key and complete dossier commit atomically. No free production fallback or extra charge/reward for voting. Personal election rights and Imperial appointment authority remain unchanged.'}), action('politics.company-consortium','Ordos confidential company consortium','entity-state',[field('decisionId','Company agreement','select',{options:['ORD-02']}),field('sourceAccount','Authorised Ordos funding account'),field('targetCompanyId','Receiving active company UUID'),field('title','Proposal title'),field('terms','Confidential commercial terms','textarea'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / createPoliticalAgreements / readCompanyDeed',executionStatus:'current-ordos-office-and-original-company-owner-consent',effect:'Current Royal Ordos holder,Reputation35,5000DM,600 Reputation and7d cooldown. Reuse the confidential bilateral proposal flow, with72h response by a different current legal owner of an active company. CEO or mother-company control never substitutes for ownership. Accepted terms last at most14d, clipped to the source mandate, and end on ownership change. Separate typed company reply proofs preserve existing office replies without altering their table. No ownership, corporate control, bank, vote or war rights change.'}), action('politics.diplomatic-proposal','Confidential diplomatic proposal','entity-state',[field('decisionId','Diplomatic decision','select',{options:['ATR-05','COR-06','ORD-05','BG-05','NF-05']}),field('sourceAccount','Authorised office funding account'),field('targetOffice','Receiving Royal office'),field('title','Proposal title'),field('terms','Confidential diplomatic terms','textarea'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / createPoliticalAgreements',executionStatus:'current-officeholder-bilateral-consent-consumer',effect:'Five fixed diplomatic policies charge the published office fee and award Reputation atomically with a confidential proposal. A different current Royal office holder must answer within72h; both mandates must cover that full window. Accepted terms last at most7d, or14d for Corrino, and end with either original mandate. Original participants alone see the terms. No votes, ownership, bank authority, travel or war consent move.'}), action('politics.diplomatic-response','Accept or refuse a diplomatic proposal','entity-state',[field('proposalId','Proposal UUID'),field('choice','Response','select',{options:['accept','decline']}),field('requestId','Response UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalAgreements.reply',executionStatus:'original-receiving-officeholder-consent-consumer',effect:'Only the original receiving current Royal mandate can accept or refuse a live72h proposal. Recheck both original mandates and the unrevoked signed proposal under the same transaction; record one signed response. Exact retries return the original receipt; conflicting responses, changed holders, expired or revoked proposals cannot manufacture acceptance. No further payment or Reputation is issued for replying.'}), diff --git a/website/control-panel/public/naib-council-policy.mjs b/website/control-panel/public/naib-council-policy.mjs new file mode 100644 index 00000000..fd866f10 --- /dev/null +++ b/website/control-panel/public/naib-council-policy.mjs @@ -0,0 +1,2 @@ +export const NAIB_COUNCIL_DECISION=Object.freeze({id:'FRE-01',level:10,xp:200,feeMinor:100000,cooldownMs:86400000}); +export const naibDecision=id=>id===NAIB_COUNCIL_DECISION.id?NAIB_COUNCIL_DECISION:null; diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs index 793a1d39..464e3d8d 100644 --- a/website/control-panel/server.mjs +++ b/website/control-panel/server.mjs @@ -65,6 +65,7 @@ import {initializeProgression} from '../node/progression-schema.mjs'; import {ensureProgressionPolicy} from '../node/progression-policy.mjs'; import {createProgressionRuntime} from '../node/progression-runtime.mjs'; import {createProgressionAPI} from '../node/progression-api.mjs'; +import {createNaibCouncilFunding} from '../node/naib-council-funding.mjs'; import {createNaibCouncilAPI} from '../node/naib-council-api.mjs'; import {NAIB_COUNCIL_SCHEMA,createNaibCouncil,reconcileNaibChairs} from '../node/naib-council.mjs'; import {configurePromotionDelivery} from '../node/jarvis-promotions.mjs'; @@ -306,7 +307,7 @@ export function createPanel(db,settings={},dependencies={}){ const masterKeyGenerator=createMasterKeyGeneratorAPI(db,dependencies.organisationKeys,{origin}); const keyValidation=createKeyValidation(db,dependencies.organisationKeys,{origin}); const politicalJobs=createPoliticalJobAPI(db,dependencies.bankDatabase||null,settings,{promotionChannels:dependencies.promotionDelivery?.channels||[]}); - const naibCouncil=createNaibCouncilAPI(db,settings); + db.naibCouncilPaidEnabled=true;const naibCouncil=createNaibCouncilAPI(db,settings,{billing:createNaibCouncilFunding(db,dependencies.bankDatabase||null,dependencies.organisationKeys)}); const electionResults=createElectionResults(db,settings); const electionCampaigns=createElectionCampaignAPI(db,dependencies.bankDatabase||null,settings,{promotionChannels:dependencies.promotionDelivery?.channels||[]}); const warExchange=createWarExchange(db,dependencies.bankDatabase||null,{origin,resolveRoster:createClanRosterResolver(db),resolveCampaign:settings.WAR_BRIDGE_ENABLED==='true'?createClanCampaignResolver(db):null}); @@ -572,7 +573,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','clan-faith-policy.mjs','house-faith-policy.mjs','decision-ballot-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','naib-council-policy.mjs','world-trade-policy.mjs','clan-faith-policy.mjs','house-faith-policy.mjs','decision-ballot-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'}}); }; } diff --git a/website/integrations/osticket/dev-jarvis-catalogue.json b/website/integrations/osticket/dev-jarvis-catalogue.json index fe275b5e..5f9b4f61 100644 --- a/website/integrations/osticket/dev-jarvis-catalogue.json +++ b/website/integrations/osticket/dev-jarvis-catalogue.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "sourceHash": "2e74e986f3266c8872473684f5e2a28dadf53ba4688544f7f464d74df779890d", + "sourceHash": "177ce3976cdfc262862c146898ee459608d6acfe50590473d5c8b3aae74915d8", "actions": [ { "id": "war.coalition-consent", @@ -531,6 +531,49 @@ "webIssue": false, "recordOnly": true }, + { + "id": "politics.naib-council-assembly", + "label": "POL & orders · Fund an independent sietch Council proposal", + "version": 1, + "keyType": "entity-state", + "fields": [ + { + "name": "ticketId", + "label": "Ban / support ticket ID", + "type": "text", + "required": true, + "maxLength": 80 + }, + { + "name": "requestId", + "label": "Council request UUID", + "type": "text", + "required": true + }, + { + "name": "sourceAccount", + "label": "Authorised sietch funding account", + "type": "text", + "required": true + }, + { + "name": "title", + "label": "Council proposal title", + "type": "text", + "required": true + }, + { + "name": "message", + "label": "Consultation terms", + "type": "textarea", + "required": true + } + ], + "effect": "FRE01 uses the existing24h Council, current independent Naib ownership and one institutional vote per recognised sietch. Reputation10,1000DM to Tax and200 Reputation points;24h seat cooldown survives ownership transfer. Keyed sietches fund their own active payment account; Basic sietches use the current legal owner’s active personal account. Source authority, balances, Reputation, ordinary scoped ESK key and complete dossier commit atomically. No free production fallback or extra charge/reward for voting. Personal election rights and Imperial appointment authority remain unchanged.", + "fixedTargets": [], + "webIssue": false, + "recordOnly": true + }, { "id": "politics.company-consortium", "label": "POL & orders · Ordos confidential company consortium", diff --git a/website/node/naib-council-funding.mjs b/website/node/naib-council-funding.mjs new file mode 100644 index 00000000..67be95dc --- /dev/null +++ b/website/node/naib-council-funding.mjs @@ -0,0 +1,32 @@ +import {createHash} from 'node:crypto'; +import {JarvisError} from './jarvis-listings.mjs'; +import {boardReadStore} from './board-deed-source.mjs'; +import {atomicBankAccess} from './atomic-bank-access.mjs'; +import {entityId,createPostbankAuthority} from './postbank-authority.mjs'; +import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs'; +import {canDebitAccount} from './postbank-authorisations.mjs'; +import {readClanDeed} from './clan-deeds.mjs'; +import {currentNaib} from './naib-membership.mjs'; +import {PostbankPayments} from './postbank-payments.mjs'; +import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs'; +import {polProgressionStore} from './progression-pol.mjs'; +import {readActiveXPSeason,lockXPAccount,saveXPAccount} from './progression-xp-store.mjs'; +import {creditXP} from './progression-xp-ledger.mjs'; +import {levelForXP,xpAtLevel} from './progression-definitions.mjs'; +import {NAIB_COUNCIL_DECISION as POLICY} from '../control-panel/public/naib-council-policy.mjs'; +const fail=(message,status=409)=>{throw new JarvisError(message,status);}; +const accountsSQL='SELECT a.*,c.entity_id,e.active entity_active,p.state package_state FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id JOIN pb_packages p ON p.id=a.package_id'; +export function createNaibCouncilFunding(raw,bank,keys,{clock=Date.now,authority=null,verifyStorage}={}){ + if(typeof raw?.query!=='function')return{ready:async()=>fail('Council banking unavailable.',503),context:async()=>({...POLICY,required:true,available:false,canExecute:false,accounts:[],levelNow:0}),charge:async()=>fail('Council banking unavailable.',503)}; + const db=boardReadStore(raw,raw),banking=atomicBankAccess(db,bank,{verifyStorage,centralTables:['jarvis_council_dossiers','jarvis_council_events','jarvis_council_proposal_locks','site_clans','site_clan_deeds','site_clan_charters','site_clan_members','site_game_links','site_accounts','organisation_keys','organisation_key_events','codex_instance_editions','jarvis_pol_progression_seasons','jarvis_pol_progression_accounts','jarvis_pol_progression_history','jarvis_pol_progression_outbox']}); + async function sources(tx,actor,seat){const r=boardReadStore(tx,db),deed=await readClanDeed(r,seat.clan_id);if(deed.owner?.id!==actor.id)fail('Current independent sietch ownership required.',403);const funding=entityId(deed.kind==='basic'?'person':'clan',deed.kind==='basic'?actor.id:seat.clan_id),b=banking.view(r),rights=await(authority||createPostbankAuthority(r,{bank:b,clock}))(actor,{bank:b});return(await b.query(accountsSQL+' WHERE c.entity_id=? AND a.system_key IS NULL ORDER BY a.id',[funding])).filter(a=>ordinaryPaymentAccount(a)&&canDebitAccount(rights,a.entity_id,a.id));} + async function context(actor,seat){try{await banking.ready();if(!keys||!seat)throw Error('Council funding unavailable');const now=clock(),pol=polProgressionStore(db),season=await readActiveXPSeason(pol,now),row=await pol.first('SELECT effective_xp FROM jarvis_progression_accounts WHERE account_id=?',[actor.id]),levelNow=levelForXP(Number(row?.effective_xp||0),{base:Number(season.curve_base),cap:Number(season.level_cap)||null}),accounts=(await sources(db,actor,seat)).map(a=>({id:String(a.id),name:a.display_name,number:a.account_number,availableMinor:String(BigInt(a.balance_minor)-BigInt(a.reserved_minor))}));return{...POLICY,required:true,available:true,canExecute:levelNow>=POLICY.level&&accounts.some(a=>BigInt(a.availableMinor)>=BigInt(POLICY.feeMinor)),accounts,levelNow};}catch{return{...POLICY,required:true,available:false,canExecute:false,accounts:[],levelNow:0};}} + async function charge(original,{actor,seat,sourceAccount,requestId,dossierId,now=clock()}){ + if(!keys||typeof sourceAccount!=='string'||!/^\d{1,12}$/.test(sourceAccount))fail('Choose an authorised sietch funding account.',400);const tx=boardReadStore(original,db),current=await currentNaib(tx,actor.id,{lock:true});if(current?.clan_id!==seat.clan_id)fail('Current independent sietch ownership required.',403); + const b=banking.view(tx),taxMeta=await b.first("SELECT id FROM pb_accounts WHERE system_key='sys_tax_treasury'");if(!taxMeta)fail('Council Tax treasury unavailable.',503);await b.query('SELECT id FROM pb_accounts WHERE id IN (?,?) ORDER BY id FOR UPDATE',[sourceAccount,taxMeta.id]); + const source=(await sources(tx,actor,seat)).find(a=>String(a.id)===sourceAccount),tax=await b.first('SELECT * FROM pb_accounts WHERE id=?',[taxMeta.id]),amount=BigInt(POLICY.feeMinor);if(!source||!tax||tax.state!=='active'||BigInt(source.balance_minor)-BigInt(source.reserved_minor)9223372036854775807n)fail('Insufficient authorised sietch funds or unavailable treasury.'); + const pol=polProgressionStore(tx),season=await readActiveXPSeason(pol,now),state=await lockXPAccount(pol,actor.id,now);if(levelForXP(state.effectiveXP,{base:Number(season.curve_base),cap:Number(season.level_cap)||null}){const fingerprint=createHash('sha256').update(JSON.stringify([actor.id,seat.clan_id,sourceAccount,requestId,dossierId])).digest('hex');await b.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'system','queued',?)",[requestId,actor.id,source.id,tax.id,fingerprint,String(amount),'Council Assembly',now]);await new PostbankPayments(bank,null,{clock}).post(b,{id:requestId,actor_id:actor.id,amount_minor:String(amount)},source,tax,false);await saveXPAccount(pol,actor.id,creditXP(state,POLICY.xp,{capXP:Number(season.level_cap)===0?Number.MAX_SAFE_INTEGER:xpAtLevel(Number(season.level_cap),Number(season.curve_base))}),season,keyId,'naib-council-decision',{decisionId:POLICY.id,dossierId,clanId:seat.clan_id,xp:POLICY.xp},now);receipt={keyId,feeMinor:String(amount),xp:POLICY.xp};}});return receipt; + } + return{ready:banking.ready,context,charge}; +} diff --git a/website/node/naib-council.mjs b/website/node/naib-council.mjs index cde8e380..c04b3e59 100644 --- a/website/node/naib-council.mjs +++ b/website/node/naib-council.mjs @@ -1,3 +1,4 @@ +import {NAIB_COUNCIL_DECISION as PAID_POLICY} from '../control-panel/public/naib-council-policy.mjs'; import {randomUUID,createHash} from 'node:crypto'; import {JarvisError} from './jarvis-listings.mjs'; import {naibSeats,currentNaib} from './naib-membership.mjs'; @@ -33,25 +34,26 @@ export async function reconcileNaibChairs(db,{clock=Date.now}={}){ await tx.query('INSERT INTO political_office_events(id,term_id,event,payload,created_at) VALUES(?,?,?,?,?)',[randomUUID(),term.id,'eligibility_ended',JSON.stringify({successorFlowId:flowId,reason:'current-sietch-deed-required'}),now]);ended++; });return{ended}; } -export function createNaibCouncil(db,{clock=Date.now}={}){ +export function createNaibCouncil(db,{clock=Date.now,billing=null}={}){ const event=(tx,id,actor,type,payload,now)=>tx.query('INSERT INTO jarvis_council_events(id,dossier_id,actor_id,event_type,payload,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),id,actor,type,JSON.stringify(payload),now]); return Object.freeze({ async context(actor){ const seats=await naibSeats(db),now=clock(),{seat,emperor}=await proposalAuthority(db,actor,now); - const proposalKinds=[]; + const funding=db.naibCouncilPaidEnabled===true?(billing?await billing.context(actor,seat):{...PAID_POLICY,required:true,available:false,canExecute:false,accounts:[],levelNow:0}):null,proposalKinds=[]; for(const kind of ['decision','imperial-peace']){ if(!seat&&(kind!=='imperial-peace'||!emperor))continue; const scope=proposalScope(kind,seat),row=(await db.query('SELECT last_proposed_at FROM jarvis_council_proposal_locks WHERE scope_key=?',[scope]))[0],previous=await previousProposal(db,kind,actor.id); const cooldownUntil=row?.last_proposed_at==null&&previous===null?null:Math.max(Number(row?.last_proposed_at??-COUNCIL_PROPOSAL_COOLDOWN_MS),Number(previous??-COUNCIL_PROPOSAL_COOLDOWN_MS))+COUNCIL_PROPOSAL_COOLDOWN_MS; - proposalKinds.push({kind,cooldownUntil,canPropose:!cooldownUntil||now>=cooldownUntil}); + proposalKinds.push({kind,cooldownUntil,canPropose:(!cooldownUntil||now>=cooldownUntil)&&(kind!=='decision'||!funding||funding.canExecute)}); } const dossiers=await db.query('SELECT id,kind,title,message,opens_at,closes_at,state,result,electorate FROM jarvis_council_dossiers ORDER BY opens_at DESC,id LIMIT 100'); const votes=await db.query('SELECT v.dossier_id,v.clan_id,v.choice FROM jarvis_council_votes v JOIN jarvis_council_dossiers d ON d.id=v.dossier_id WHERE d.id IN (SELECT recent.id FROM (SELECT id FROM jarvis_council_dossiers ORDER BY opens_at DESC,id LIMIT 100) recent)'); - return {name:'Council of Naibs',house:'House of Arrakis',world:'Arrakduin',naib:!!seat,seatId:seat?.clan_id||null,proposalKinds,proposalCooldownMs:COUNCIL_PROPOSAL_COOLDOWN_MS,seats:seats.map(s=>({id:s.clan_id,name:s.clan_name,tag:s.tag,username:s.username,displayName:s.display_name||s.username})),dossiers:dossiers.map(d=>({id:d.id,reference:'JRV-NAIB-'+d.id,kind:d.kind,title:d.title,message:d.message,opensAt:Number(d.opens_at),closesAt:Number(d.closes_at),state:d.state,result:d.result,electorate:JSON.parse(d.electorate).length,choices:councilChoices(d.kind),ownVote:seat?votes.find(v=>v.dossier_id===d.id&&v.clan_id===seat.clan_id)?.choice||null:null,canVote:!!seat&&d.state==='open'&&nowv.dossier_id===d.id)):null})),powersAvailable:false}; + return {funding,name:'Council of Naibs',house:'House of Arrakis',world:'Arrakduin',naib:!!seat,seatId:seat?.clan_id||null,proposalKinds,proposalCooldownMs:COUNCIL_PROPOSAL_COOLDOWN_MS,seats:seats.map(s=>({id:s.clan_id,name:s.clan_name,tag:s.tag,username:s.username,displayName:s.display_name||s.username})),dossiers:dossiers.map(d=>({id:d.id,reference:'JRV-NAIB-'+d.id,kind:d.kind,title:d.title,message:d.message,opensAt:Number(d.opens_at),closesAt:Number(d.closes_at),state:d.state,result:d.result,electorate:JSON.parse(d.electorate).length,choices:councilChoices(d.kind),ownVote:seat?votes.find(v=>v.dossier_id===d.id&&v.clan_id===seat.clan_id)?.choice||null:null,canVote:!!seat&&d.state==='open'&&nowv.dossier_id===d.id)):null})),powersAvailable:false}; }, async propose(actor,input){ if(!uuid(actor?.id)||!uuid(input?.requestId)||input.confirmed!==true||!['decision','imperial-peace'].includes(input.kind)||typeof input.title!=='string'||!input.title.trim()||input.title.length>100||typeof input.message!=='string'||input.message.trim().length<20||input.message.length>4000||/[\x00-\x1f\x7f]/.test(input.title)||/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(input.message))throw new JarvisError('Confirm a Council proposal and its details.'); - const title=input.title.trim(),message=input.message.trim(),fingerprint=createHash('sha256').update(JSON.stringify([actor.id,input.kind,title,message])).digest('hex'); + const paid=db.naibCouncilPaidEnabled===true&&input.kind==='decision';if(paid){if(Object.keys(input).sort().join(',')!=='confirmed,kind,message,requestId,sourceAccount,title'||typeof input.sourceAccount!=='string'||!/^\d{1,12}$/.test(input.sourceAccount))throw new JarvisError('Choose funding and confirm the Council proposal.',400);if(!billing)throw new JarvisError('Council banking unavailable.',503);try{await billing.ready();}catch{throw new JarvisError('Council banking unavailable.',503);}} + const title=input.title.trim(),message=input.message.trim(),fingerprint=createHash('sha256').update(JSON.stringify([actor.id,input.kind,title,message,...(paid?[input.sourceAccount]:[])])).digest('hex'); return db.transaction(async tx=>{ const now=clock(),{seat,emperor}=await proposalAuthority(tx,actor,now,{lock:true}); if(!seat&&!(input.kind==='imperial-peace'&&emperor))throw new JarvisError('A current Naib deed is required; the Emperor may only submit an Imperial Peace offer.',403); @@ -65,7 +67,7 @@ export function createNaibCouncil(db,{clock=Date.now}={}){ const last=Math.max(Number(cooldown?.last_proposed_at??-COUNCIL_PROPOSAL_COOLDOWN_MS),Number(previous??-COUNCIL_PROPOSAL_COOLDOWN_MS)); if(nows.clan_id);if(!electorate.length)throw new JarvisError('No recognised sietches are available.',409); - const id=randomUUID();await tx.query("INSERT INTO jarvis_council_dossiers(id,request_id,actor_id,kind,title,message,fingerprint,electorate,opens_at,closes_at,state) VALUES(?,?,?,?,?,?,?,?,?,?,'open')",[id,input.requestId,actor.id,input.kind,title,message,fingerprint,JSON.stringify(electorate),now,now+86400000]);await tx.query('UPDATE jarvis_council_proposal_locks SET last_proposed_at=? WHERE scope_key=?',[now,scope]);await event(tx,id,actor.id,'proposal_recorded',{kind:input.kind,seats:electorate.length,cooldownUntil:now+COUNCIL_PROPOSAL_COOLDOWN_MS,gameplayEffect:false},now);return{id,replayed:false}; + const id=randomUUID(),fundingReceipt=paid?await billing.charge(tx,{actor,seat,sourceAccount:input.sourceAccount,requestId:input.requestId,dossierId:id,now}):null;await tx.query("INSERT INTO jarvis_council_dossiers(id,request_id,actor_id,kind,title,message,fingerprint,electorate,opens_at,closes_at,state) VALUES(?,?,?,?,?,?,?,?,?,?,'open')",[id,input.requestId,actor.id,input.kind,title,message,fingerprint,JSON.stringify(electorate),now,now+86400000]);await tx.query('UPDATE jarvis_council_proposal_locks SET last_proposed_at=? WHERE scope_key=?',[now,scope]);await event(tx,id,actor.id,'proposal_recorded',{kind:input.kind,seats:electorate.length,cooldownUntil:now+COUNCIL_PROPOSAL_COOLDOWN_MS,gameplayEffect:false,...(fundingReceipt?{funding:fundingReceipt}:{})},now);return{id,replayed:false,...(fundingReceipt?{funding:fundingReceipt}:{})}; }); }, async vote(actor,input){ diff --git a/website/node/organisation-keys.mjs b/website/node/organisation-keys.mjs index c93c07d3..f3d7f55e 100644 --- a/website/node/organisation-keys.mjs +++ b/website/node/organisation-keys.mjs @@ -41,7 +41,7 @@ export function createOrganisationKeys(db,{secret,editions=null}={}){ return Object.freeze({ async inspect(code,{accountId=null,expectedType=null}={}){let parsed,keyType,hash;try{parsed=parseOrganisationCode(code);keyType=Object.keys(ORGANISATION_KEY_TYPES).find(k=>ORGANISATION_KEY_TYPES[k].prefix===parsed.prefix);if(!keyType)return{valid:false,state:'unsupported'};hash=hashOrganisationKey(code,keyType);}catch{return{valid:false,state:'invalid'};}const row=await readFirst(db,'SELECT id,account_id,key_type,expires_at,revoked_at,used_at FROM organisation_keys WHERE code_hash=?',[hash]);if(!row||accountId&&row.account_id!==accountId||expectedType&&row.key_type!==expectedType)return{valid:false,state:'invalid'};if(parsed.edition){if(!editions)return{valid:false,state:'unavailable'};const edition=await editions.read(row.id);if(['stage','version','season'].some(k=>edition[k]!==parsed.edition[k]))return{valid:false,state:'invalid'};}return{valid:true,type:row.key_type,purpose:type(row.key_type).purpose,state:row.revoked_at!=null?'revoked':row.used_at!=null?'used':row.expires_at!=null&&Number(row.expires_at)<=Date.now()?'expired':'available'};}, async issue({accountId,keyType,scopeId,expiresAt=null,authorize=null,transactionStore=null}){ - if(transactionStore&&(!(keyType==='organisation-action'||keyType==='entity-state'&&accountId===STAFF_OFFICE_ACCOUNT_ID&&/^state:(?:political-decision|political-agreement-reply|political-ballot-vote|world-trade):[a-f0-9-]{36}$/i.test(scopeId))||typeof transactionStore.query!=='function'||typeof transactionStore.first!=='function'))throw TypeError('A scoped action transaction is required'); + if(transactionStore&&(!(keyType==='organisation-action'||keyType==='entity-state'&&accountId===STAFF_OFFICE_ACCOUNT_ID&&/^state:(?:political-decision|political-agreement-reply|political-ballot-vote|naib-council|world-trade):[a-f0-9-]{36}$/i.test(scopeId))||typeof transactionStore.query!=='function'||typeof transactionStore.first!=='function'))throw TypeError('A scoped action transaction is required'); type(keyType); if(keyType==='economy-operation'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||typeof authorize!=='function'||!/^economy\.(reset-balances|repay-loans|federal-cycle):[a-f0-9-]{36}$/i.test(scopeId)))throw TypeError('Economic keys require a scoped system authority adapter'); if(keyType==='kit-definition'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||typeof authorize!=='function'||!/^kitset:[a-f0-9-]{36}:v[1-9]\d{0,5}$/i.test(scopeId)))throw TypeError('Kit definitions require a saved set and authority adapter'); diff --git a/website/tests/political-decisions.test.mjs b/website/tests/political-decisions.test.mjs index 5a63b31d..99be6682 100644 --- a/website/tests/political-decisions.test.mjs +++ b/website/tests/political-decisions.test.mjs @@ -1,3 +1,5 @@ +import {NAIB_COUNCIL_SCHEMA,createNaibCouncil} from '../node/naib-council.mjs'; +import {createNaibCouncilFunding} from '../node/naib-council-funding.mjs'; import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto'; import {companyFixture} from './company-deed-fixture.mjs'; import {STAFF_OFFICE_ACCOUNT_ID} from '../node/organisation-keys.mjs'; @@ -273,3 +275,10 @@ async function companyAgreementFixture(){const f=await fixture('ordos');await f. test('Ordos confidential company agreement requires the legal owner and reuses the signed bilateral flow',async()=>{const f=await companyAgreementFixture();try{const view=await f.service.read(f.people.Owner,'ORD-02');assert(view.diplomacyTargets.some(c=>c.id===f.companyId));const input=f.proposal(),r=await f.service.execute(f.people.Owner,input);assert.equal(r.agreement.targetCompanyId,f.companyId);assert.equal(r.agreement.durationMs,14*86400000);assert.equal(r.feeMinor,'500000');await assert.rejects(f.agreements.reply(f.people.Ceo,f.reply(input.requestId)),/not addressed/);const response=f.reply(input.requestId);await f.agreements.reply(f.people.Other,response);assert.equal((await f.agreements.reply(f.people.Other,response)).replayed,true);const item=(await f.agreements.read(f.people.Owner)).agreements[0];assert.equal(item.state,'accepted');assert.equal(item.targetName,'Test Enterprise');assert.equal(item.endsAt,1000+14*86400000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);assert.equal((await f.db.first('SELECT owner_account_id FROM site_company_deeds WHERE company_id=?',[f.companyId])).owner_account_id,f.people.Other.id);}finally{f.db.close();}}); test('company ownership changes cannot transfer confidential pending consent to a successor or a CEO',async()=>{const f=await companyAgreementFixture();try{const input=f.proposal();await f.service.execute(f.people.Owner,input);await f.db.query('INSERT INTO site_company_members(company_id,user_id,joined_at) VALUES(?,?,1)',[f.companyId,f.people.Ceo.id]);await f.db.query('UPDATE site_company_deeds SET owner_account_id=? WHERE company_id=?',[f.people.Ceo.id,f.companyId]);await assert.rejects(f.agreements.reply(f.people.Other,f.reply(input.requestId)),/expired/);await assert.rejects(f.agreements.reply(f.people.Ceo,f.reply(input.requestId)),/not addressed/);assert.equal((await f.agreements.read(f.people.Ceo)).agreements.length,0);assert.equal((await f.agreements.read(f.people.Owner)).agreements[0].canReply,false);}finally{f.db.close();}}); test('inactive or self-owned companies cannot take an agreement fee; failed company replies roll back their key',async()=>{const f=await companyAgreementFixture();try{await f.db.query("UPDATE corrino_companies SET status='pending' WHERE id=?",[f.companyId]);await assert.rejects(f.service.execute(f.people.Owner,f.proposal()),/active company/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);await f.db.query("UPDATE corrino_companies SET status='active' WHERE id=?",[f.companyId]);await f.db.query('INSERT INTO site_company_members(company_id,user_id,joined_at) VALUES(?,?,1)',[f.companyId,f.people.Owner.id]);await f.db.query('UPDATE site_company_deeds SET owner_account_id=? WHERE company_id=?',[f.people.Owner.id,f.companyId]);await assert.rejects(f.service.execute(f.people.Owner,f.proposal()),/different current legal owner/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);await f.db.query('UPDATE site_company_deeds SET owner_account_id=? WHERE company_id=?',[f.people.Other.id,f.companyId]);const input=f.proposal();await f.service.execute(f.people.Owner,input);const before=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;f.db.sqlite.exec("CREATE TRIGGER fail_company_response BEFORE INSERT ON jarvis_political_company_replies BEGIN SELECT RAISE(ABORT,'company response failed');END");await assert.rejects(f.agreements.reply(f.people.Other,f.reply(input.requestId)),/company response failed/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,before);assert.equal((await f.agreements.read(f.people.Other)).agreements[0].state,'pending');}finally{f.db.close();}}); + +async function paidNaibFixture(){const f=await grantFixture();for(const sql of NAIB_COUNCIL_SCHEMA)await f.db.query(sql);await f.db.query("UPDATE site_clans SET home_world='arrakduin' WHERE id=?",[f.clanId]);await f.db.query('UPDATE pb_accounts SET balance_minor=500000 WHERE id=?',[f.target.id]);await f.pol.query('INSERT INTO jarvis_progression_accounts VALUES(?,10000,10000,28,1,0)',[f.people.Other.id]);f.db.naibCouncilPaidEnabled=true;const billing=createNaibCouncilFunding(f.db,f.db,f.keys,{clock:f.clock,verifyStorage:async()=>null,authority:async actor=>({entities:[{id:entityId('person',actor.id),canPay:true},{id:entityId('clan',f.clanId),canPay:actor.id===f.people.Other.id}]})}),council=createNaibCouncil(f.db,{clock:f.clock,billing});return{...f,billing,council,input:()=>({requestId:randomUUID(),kind:'decision',title:'Sietch water assembly',message:'Consult the recognised sietches about our water reserves.',sourceAccount:String(f.target.id),confirmed:true})};} +test('paid Naib assembly preserves independent seats and pays its fixed fee and Reputation exactly once',async()=>{const f=await paidNaibFixture();try{const view=await f.council.context(f.people.Other);assert.equal(view.funding.required,true);assert.equal(view.funding.feeMinor,100000);assert.equal(view.funding.levelNow,28);assert(view.funding.accounts.some(a=>a.id===String(f.target.id)));const input=f.input(),r=await f.council.propose(f.people.Other,input);assert.equal(r.funding.feeMinor,'100000');assert.equal(r.funding.xp,200);assert.equal((await f.council.propose(f.people.Other,input)).replayed,true);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,400000);assert.equal((await f.db.first("SELECT balance_minor FROM pb_accounts WHERE system_key='sys_tax_treasury'")).balance_minor,100000);assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Other.id])).total_xp,10200);assert.equal((await f.db.first('SELECT SUM(amount_minor) n FROM pb_entries')).n,0);await f.council.vote(f.people.Other,{dossierId:r.id,choice:'yes',confirmed:true});assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Other.id])).total_xp,10200);await assert.rejects(f.council.propose(f.people.Other,f.input()),/cooldown/);}finally{f.db.close();}}); +test('paid Council has no free production fallback and rejects foreign funding or client-side price overrides',async()=>{const f=await paidNaibFixture();try{const input=f.input();await assert.rejects(createNaibCouncil(f.db,{clock:f.clock}).propose(f.people.Other,input),/banking unavailable/);await assert.rejects(f.council.propose(f.people.Other,{...input,sourceAccount:String(f.source.id)}),/Insufficient authorised/);await assert.rejects(f.council.propose(f.people.Other,{...input,feeMinor:1}),/Choose funding/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_council_dossiers')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{f.db.close();}}); +test('Council journal failure rolls back its bank transfer, Reputation and ordinary scoped key',async()=>{const f=await paidNaibFixture();try{const before=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;f.db.sqlite.exec("CREATE TRIGGER fail_paid_council BEFORE INSERT ON jarvis_council_dossiers BEGIN SELECT RAISE(ABORT,'Council journal failed');END");await assert.rejects(f.council.propose(f.people.Other,f.input()),/Council journal failed/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,before);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,500000);assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Other.id])).total_xp,10000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{f.db.close();}}); +test('a keyed sietch funds its Council proposal from its own account rather than its owner’s personal account',async()=>{const f=await paidNaibFixture();try{const charter=await f.keys.issue({accountId:f.people.Other.id,keyType:'clan-founding',scopeId:'original',authorize:async()=>true});await f.keys.consume({accountId:f.people.Other.id,keyType:'clan-founding',code:charter.code,targetId:f.clanId,requestId:randomUUID(),apply:(tx,{keyId})=>tx.query("INSERT INTO site_clan_charters(clan_id,original_account_id,key_id,charter_kind,created_at) VALUES(?,?,?,'original',1)",[f.clanId,f.people.Other.id,keyId])});const source=await f.activate(f.people.Other,'clan',f.clanId);await f.db.query('UPDATE pb_accounts SET balance_minor=500000 WHERE id=?',[source.id]);const view=await f.council.context(f.people.Other);assert.equal(view.funding.accounts.some(a=>a.id===String(f.target.id)),false);await assert.rejects(f.council.propose(f.people.Other,f.input()),/Insufficient authorised/);await f.council.propose(f.people.Other,{...f.input(),sourceAccount:String(source.id)});assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[source.id])).balance_minor,400000);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,500000);}finally{f.db.close();}}); +test('Council Reputation and available funds are rechecked without charging ineligible proposals',async()=>{for(const reason of ['reputation','balance']){const f=await paidNaibFixture();try{if(reason==='reputation')await f.pol.query('UPDATE jarvis_progression_accounts SET effective_xp=0 WHERE account_id=?',[f.people.Other.id]);else await f.db.query('UPDATE pb_accounts SET balance_minor=99999 WHERE id=?',[f.target.id]);assert.equal((await f.council.context(f.people.Other)).funding.canExecute,false);await assert.rejects(f.council.propose(f.people.Other,f.input()),reason==='reputation'?/Reputation level 10/:/Insufficient authorised/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{f.db.close();}}});