Merge pull request 'Connect Voice of Arrakis to private funded sietch petitions' (#599) from dev/MC:feature/fremen-voice-petitions-20261125 into main
All checks were successful
DuneRealms Web CI / web (push) Successful in 3m55s
All checks were successful
DuneRealms Web CI / web (push) Successful in 3m55s
This commit is contained in:
commit
d5564d0db0
13 changed files with 120 additions and 13 deletions
|
|
@ -15,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==='organisation-passage'?'The signed charter is consumed at Guild quote, boarding and arrival for current direct organisation members.72h maximum, clipped to the original Imperial mandate. Revocation, expiry or leaving removes permission; normal fares and embargoes remain in force.':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'&&politicalDecision(id).agreementMode==='representation'?'The receiving Royal holder signs within72h. Acceptance and an actual observer appointment commit together, clipped to14d and both source terms. Projection rejects revoked source/response proofs or either ended mandate. No leadership or bank authority moves.':kind==='agreement'&&politicalDecision(id).agreementMode==='petition'?'A confidential petition requires a signed response from its original receiving Royal holder within72h. Acknowledgement is historical receipt only; hearings, votes and concession changes require separate authorised actions. No bank, vote, ownership or war rights 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: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, Reputation'+naibDecision(d.id).level+','+naibDecision(d.id).feeMinor/100+'DM from its active account or the legal Basic owner,'+naibDecision(d.id).xp+' Reputation and'+naibDecision(d.id).cooldownMs/3600000+'h 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 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)?.petitionOnly?'createNaibPetitions / createNaibCouncilFunding / createPoliticalAgreements':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)?.petitionOnly?'Current independent sietch owner,Rep15,1000DM from the same legal sietch funding route,250 Reputation and48h successor-safe cooldown. Private petition, not a Council ballot. Only the original Royal Emperor can sign its acknowledgement or refusal within72h; no gameplay authority is granted.':naibDecision(d.id)?'Current independent sietch deed, Reputation'+naibDecision(d.id).level+','+naibDecision(d.id).feeMinor/100+'DM from its active account or the legal Basic owner,'+naibDecision(d.id).xp+' Reputation and'+naibDecision(d.id).cooldownMs/3600000+'h 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;
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
import {mountNaibPetitions} from './cp-v2-naib-petitions.mjs';
|
||||
import {mountPoliticalAgreements} from './cp-v2-political-agreements.mjs';
|
||||
import {element as el,createCPV2Page} from './cp-v2-page-template.mjs';
|
||||
import {createUserAPI} from './cp-v2-user-api.mjs';
|
||||
import {renderApplications} from '../election-applications-view.mjs';
|
||||
|
|
@ -27,7 +29,7 @@ export function mountNaibCouncil(host){
|
|||
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'));
|
||||
if(data.accords?.length){decisions.append(el('h3','Council accords'));for(const accord of data.accords){const card=el('article',undefined,'politics-card');card.append(el('h4',accord.title),el('p',accord.terms),el('p',({active:'Active',expired:'Expired','insufficient-current-consent':'Not enough current participants'})[accord.state]+' · ends '+new Date(accord.endsAt).toLocaleString()),el('p','Current participants: '+(accord.participants.map(p=>p.name).join(', ')||'none')));if(accord.canWithdraw){const label=el('label','I confirm my sietch is leaving this accord'),sure=el('input'),leave=el('button','Leave accord');sure.type='checkbox';label.append(sure);leave.type='button';leave.disabled=true;const withdrawal={dossierId:accord.id,requestId:crypto.randomUUID(),confirmed:true};sure.onchange=()=>leave.disabled=!sure.checked;leave.onclick=async()=>{if(busy||!sure.checked)return;lock(true);leave.disabled=true;try{await api.request('/api/politics/naibs/withdraw',withdrawal);await load();status.textContent='Sietch consent withdrawn.';}catch(error){status.textContent=error.message;lock(false);leave.disabled=!sure.checked;}};card.append(label,leave);}decisions.append(card);}}
|
||||
powers.append(el('h3','Council powers'),el('p','Political powers are awaiting a separate design. No gameplay action is available from this page.'));
|
||||
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;
|
||||
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);mountNaibPetitions(diplomacy);mountPoliticalAgreements(diplomacy);busy=false;
|
||||
}
|
||||
void load();return()=>{active=false;controller.abort();disposeResults();};
|
||||
}
|
||||
|
|
|
|||
10
website/control-panel/public/cp-v2/cp-v2-naib-petitions.mjs
Normal file
10
website/control-panel/public/cp-v2/cp-v2-naib-petitions.mjs
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import {element as el} from './cp-v2-page-template.mjs';
|
||||
import {createUserAPI} from './cp-v2-user-api.mjs';
|
||||
export function mountNaibPetitions(host,{fetcher=fetch}={}){
|
||||
const api=createUserAPI(fetcher),root=el('section',undefined,'organisation-settings-card'),status=el('p','Reading sietch petition authority…'),form=el('div',undefined,'cp-political-decision-form'),review=el('p'),prepare=el('button','Review petition'),confirm=el('button','Confirm and pay'),refresh=el('button','Refresh petition');status.setAttribute('role','status');root.append(el('h3','Voice of Arrakis'),el('p','Send a private petition to the current Emperor. The original receiving holder has 72 hours to acknowledge or decline. Acknowledgement records receipt; a hearing, law, payment or war still needs its own authorised action.'),status,form,review,prepare,confirm,refresh);host.append(root);
|
||||
const field=(name,tag)=>{const label=el('label',name),control=el(tag);label.append(control);form.append(label);return control;},account=field('Sietch funding account','select'),title=field('Petition title','input'),message=field('Petition and requested action','textarea');title.maxLength=100;message.minLength=20;message.maxLength=4000;message.rows=5;let current=null,busy=false,pending=null;confirm.hidden=true;for(const b of[prepare,confirm,refresh])b.type='button';
|
||||
function controls(){for(const f of[account,title,message])f.disabled=busy||!!pending||!current?.canManage;prepare.disabled=busy||!!pending||!current?.canExecute;confirm.disabled=busy||!pending;refresh.disabled=busy||!!pending;}
|
||||
async function load(){busy=true;controls();try{const data=await api.request('/api/politics/naibs/petition');if(!root.isConnected)return;current=data;const selected=account.value;account.replaceChildren();for(const a of data.accounts){const o=el('option',a.name+' · '+a.number+' · '+(Number(a.availableMinor)/100).toFixed(2)+' DM available');o.value=a.id;account.append(o);}if(data.accounts.some(a=>a.id===selected))account.value=selected;status.textContent=data.canManage?(data.feeMinor/100).toFixed(2)+' DM · '+data.xp+' Reputation points · Reputation '+data.levelNow+'/'+data.level+' required. '+(data.cooldownUntil>Date.now()?'Available after '+new Date(data.cooldownUntil).toLocaleString():data.cooldownMs/3600000+'-hour sietch cooldown.')+(data.recipient?'':' No receiving Royal Emperor is currently available.'):'Only a current independent sietch owner may submit this petition.';}catch(error){status.textContent=error.message;}finally{busy=false;controls();}}
|
||||
prepare.onclick=()=>{if(!current?.canExecute||!account.value||title.value.trim().length<3||message.value.trim().length<20){status.textContent='Choose funding and complete your petition.';return;}const source=current.accounts.find(a=>String(a.id)===account.value);if(!source||BigInt(source.availableMinor)<BigInt(current.feeMinor)){status.textContent='The selected sietch account has insufficient available funds.';return;}pending={requestId:crypto.randomUUID(),sourceAccount:account.value,title:title.value,message:message.value,confirmed:true};review.textContent='Send “'+title.value.trim()+'” privately to the current Emperor for '+(current.feeMinor/100).toFixed(2)+' DM from '+source.name+'? The petition awards '+current.xp+' Reputation points and starts a 48-hour sietch cooldown. No other action is automatically granted.';confirm.hidden=false;controls();};
|
||||
confirm.onclick=async()=>{if(busy||!pending)return;busy=true;controls();try{const receipt=await api.request('/api/politics/naibs/petition',pending);pending=null;confirm.hidden=true;title.value=message.value='';review.textContent='Petition sent. J.A.R.V.I.S. reference: '+receipt.reference;await load();}catch(error){status.textContent=error.message+(error.uncertain?' Retry this same confirmation to check its recorded result.':'');if(!error.uncertain){pending=null;confirm.hidden=true;}}finally{busy=false;controls();}};refresh.onclick=load;load();return()=>root.remove();
|
||||
}
|
||||
|
|
@ -20,6 +20,7 @@ export const MASTER_KEY_TEMPLATES=[
|
|||
action('politics.naib-council-assembly','Fund an independent sietch Council proposal','entity-state',[field('kind','Registered Council decision','select',{options:['decision','defense-coalition','water-sharing','desert-alliance']}),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. FRE02:15000DM,400 Reputation,level25,7d cooldown and7d defensive accord. FRE03:2500DM,300 Reputation,level20,72h cooldown and7d water-sharing accord. FRE06:5000DM,500 Reputation,level30,7d cooldown and14d alliance. All use24h Council consent, frozen institutional electorate and the existing quorum rule. Only current sietches whose original Naib voted yes join; they may withdraw through the normal Council audit flow. No automatic war consent or delivery is fabricated. 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.organisation-passage','Imperial organisation travel charter','entity-state',[field('sourceAccount','Imperial office funding account'),field('targetKind','Organisation kind','select',{options:['clan','company']}),field('targetId','Current organisation UUID'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions / hasOrganisationPassage / createGuildService',executionStatus:'current-imperial-office-funded-organisational-passage',effect:'IMP-02 charges10000DM, awards250 Reputation at level15, with24h office cooldown. Current direct clan/company members receive up to72h Arrakis permission, ending with the issuing Emperor mandate. Guild quotes, boarding and arrival verify current membership and signed charter. No mother membership, free fare, embargo bypass or military rights.'}),
|
||||
action('politics.sietch-petition','Voice of Arrakis private petition','entity-state',[field('sourceAccount','Authorised sietch funding account'),field('title','Petition title'),field('message','Petition and requested action','textarea'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createNaibPetitions / createNaibCouncilFunding / createPoliticalAgreements',executionStatus:'current-independent-naib-funded-private-petition',effect:'FRE-07:current independent sietch owner,Reputation15,1000DM,250 Reputation and48h successor-safe sietch cooldown. Reuse the paid Council bank route and ordinary signature. Deliver privately to the original current Royal Emperor, who must hold the full72h response window. Only that holder can acknowledge or refuse. Original sietch ownership and both signed proofs checked; acknowledgement remains history. No Council vote, Imperial appointment or automatic gameplay outcome.'}),
|
||||
action('politics.clan-petition','Clan Delegate petition','entity-state',[field('decisionId','Petition','select',{options:['CLD-01','CLD-03','CLD-05']}),field('sourceAccount','Authorised Clan Delegate office account'),field('targetOffice','Receiving Royal office'),field('title','Petition title'),field('terms','Petition and requested action','textarea'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / createPoliticalAgreements',executionStatus:'current-delegate-funded-signed-petition-response',effect:'Three fixed Clan Delegate policies use their published office fee, Reputation requirement and successor-safe cooldown. Another current Royal holder has72h to acknowledge or decline. Both original mandates must cover the response window. A signed acknowledgement remains history; it does not create a hearing, vote, concession, grant, appointment or war.'}),
|
||||
action('politics.advisory-representation','Corrino advisory representation petition','entity-state',[field('sourceAccount','Authorised Corrino office account'),field('targetOffice','Receiving Royal office'),field('title','Petition title'),field('terms','Requested advisory representation','textarea'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions / createPoliticalAgreements / appointPoliticalInTransaction / activePoliticalAppointments',executionStatus:'signed-receiving-mandate-temporary-observer-deed',effect:'COR-07:Rep50,5000DM,1200 Reputation,7d office cooldown. A different Royal holder has72h to accept or decline. Acceptance atomically issues a real observer appointment, at most14d, clipped to both original mandates. Revoked proofs or either ended mandate remove its membership projection. An existing target-office appointment is preserved rather than replaced. No leadership, bank, election, ownership or war authority moves.'}),
|
||||
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','SG-01']}),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:'Six fixed diplomatic policies, including the seven-day Guild Transport Mandate, 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.'}),
|
||||
|
|
|
|||
|
|
@ -1,9 +1,10 @@
|
|||
export const NAIB_COUNCIL_DECISIONS=Object.freeze([
|
||||
{id:'FRE-07',kind:'petition',title:'Voice of Arrakis',level:15,xp:250,feeMinor:100000,cooldownMs:48*3600000,responseMs:72*3600000,durationMs:null,petitionOnly:true,effect:'A private sietch petition to the current Royal Emperor, with72h for a signed acknowledgement or refusal. Current independent owner, legal sietch funding, Reputation15 and48h seat cooldown. Acknowledgement records receipt and does not create a hearing, law, payment or war.'},
|
||||
{id:'FRE-01',kind:'decision',title:'Council Assembly',level:10,xp:200,feeMinor:100000,cooldownMs:86400000,durationMs:null},
|
||||
{id:'FRE-02',kind:'defense-coalition',title:'Defend Sietches',level:25,xp:400,feeMinor:1500000,cooldownMs:7*86400000,durationMs:7*86400000},
|
||||
{id:'FRE-03',kind:'water-sharing',title:'Water Discipline',level:20,xp:300,feeMinor:250000,cooldownMs:72*3600000,durationMs:7*86400000},
|
||||
{id:'FRE-06',kind:'desert-alliance',title:'Desert Alliance',level:30,xp:500,feeMinor:500000,cooldownMs:7*86400000,durationMs:14*86400000}
|
||||
].map(Object.freeze));
|
||||
export const NAIB_COUNCIL_DECISION=NAIB_COUNCIL_DECISIONS[0];
|
||||
export const NAIB_COUNCIL_DECISION=NAIB_COUNCIL_DECISIONS.find(d=>d.id==='FRE-01');
|
||||
export const naibDecision=id=>NAIB_COUNCIL_DECISIONS.find(d=>d.id===id)||null;
|
||||
export const naibProposal=kind=>NAIB_COUNCIL_DECISIONS.find(d=>d.kind===kind)||null;
|
||||
|
|
|
|||
|
|
@ -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 {createNaibPetitions} from '../node/naib-petitions.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';
|
||||
|
|
@ -288,7 +289,8 @@ export function createPanel(db,settings={},dependencies={}){
|
|||
const gameGuild=createGameGuildAPI(db,dependencies.bankDatabase||null,dependencies.organisationKeys,settings);
|
||||
const politicalConsultations=createPoliticalConsultations(db,dependencies.organisationKeys);
|
||||
const politicalConsultationAPI=createPoliticalConsultationAPI(db,politicalConsultations,{origin});
|
||||
const politicalAgreements=createPoliticalAgreements(db,dependencies.organisationKeys);
|
||||
const naibBilling=createNaibCouncilFunding(db,dependencies.bankDatabase||null,dependencies.organisationKeys),naibPetitions=createNaibPetitions(db,dependencies.organisationKeys,naibBilling);
|
||||
const politicalAgreements=createPoliticalAgreements(db,dependencies.organisationKeys,{petitions:naibPetitions});
|
||||
const politicalAgreementAPI=createPoliticalAgreementAPI(db,politicalAgreements,{origin});
|
||||
const politicalDecisions=createPoliticalDecisions(db,dependencies.bankDatabase||null,dependencies.organisationKeys,{marketReports:createPoliticalMarketReports(db,dependencies.bankDatabase||null,settings),clanGrants:createPoliticalClanGrants(db),agreements:politicalAgreements,consultations:politicalConsultations});
|
||||
const politicalDecisionAPI=createPoliticalDecisionAPI(db,politicalDecisions,{origin});
|
||||
|
|
@ -307,7 +309,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||[]});
|
||||
db.naibCouncilPaidEnabled=true;const naibCouncil=createNaibCouncilAPI(db,settings,{billing:createNaibCouncilFunding(db,dependencies.bankDatabase||null,dependencies.organisationKeys)});
|
||||
db.naibCouncilPaidEnabled=true;const naibCouncil=createNaibCouncilAPI(db,settings,{billing:naibBilling,petitions:naibPetitions});
|
||||
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});
|
||||
|
|
@ -412,7 +414,7 @@ export function createPanel(db,settings={},dependencies={}){
|
|||
if(path==='/api/jarvis/auctions'||path==='/api/jarvis/auction'||path==='/api/jarvis/auctions/bid')return officeAuctionAPI(request);
|
||||
if(['/api/jarvis/generator','/api/jarvis/generator/redeem','/api/jarvis/generator/history','/api/jarvis/generator/options'].includes(path))return masterKeyGenerator(request);
|
||||
if(path==='/api/jarvis/validate')return keyValidation(request);
|
||||
if(path==='/api/politics/naibs'||path==='/api/politics/naibs/propose'||path==='/api/politics/naibs/vote'||path==='/api/politics/naibs/withdraw')return naibCouncil(request);
|
||||
if(path==='/api/politics/naibs'||path==='/api/politics/naibs/propose'||path==='/api/politics/naibs/vote'||path==='/api/politics/naibs/withdraw'||path==='/api/politics/naibs/petition')return naibCouncil(request);
|
||||
if(path.startsWith('/api/jarvis/political-jobs'))return politicalJobs.api(request);
|
||||
if(['/api/jarvis/campaigns','/api/jarvis/campaigns/public'].includes(path))return electionCampaigns(request);
|
||||
if(path==='/api/war-exchange')return warExchange(request);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"schemaVersion": 1,
|
||||
"sourceHash": "26bc66dc745a13fe3e960e2bb91fa5747a75f98162389e1f354a7135c66f047b",
|
||||
"sourceHash": "21a11791700dcd378b6e5ff59d2b87e2094fd774b1463a5346073deecb0e3547",
|
||||
"actions": [
|
||||
{
|
||||
"id": "war.coalition-consent",
|
||||
|
|
@ -722,6 +722,49 @@
|
|||
"webIssue": false,
|
||||
"recordOnly": true
|
||||
},
|
||||
{
|
||||
"id": "politics.sietch-petition",
|
||||
"label": "POL & orders · Voice of Arrakis private petition",
|
||||
"version": 1,
|
||||
"keyType": "entity-state",
|
||||
"fields": [
|
||||
{
|
||||
"name": "ticketId",
|
||||
"label": "Ban / support ticket ID",
|
||||
"type": "text",
|
||||
"required": true,
|
||||
"maxLength": 80
|
||||
},
|
||||
{
|
||||
"name": "sourceAccount",
|
||||
"label": "Authorised sietch funding account",
|
||||
"type": "text",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "title",
|
||||
"label": "Petition title",
|
||||
"type": "text",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "message",
|
||||
"label": "Petition and requested action",
|
||||
"type": "textarea",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "requestId",
|
||||
"label": "Request UUID",
|
||||
"type": "text",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"effect": "FRE-07:current independent sietch owner,Reputation15,1000DM,250 Reputation and48h successor-safe sietch cooldown. Reuse the paid Council bank route and ordinary signature. Deliver privately to the original current Royal Emperor, who must hold the full72h response window. Only that holder can acknowledge or refuse. Original sietch ownership and both signed proofs checked; acknowledgement remains history. No Council vote, Imperial appointment or automatic gameplay outcome.",
|
||||
"fixedTargets": [],
|
||||
"webIssue": false,
|
||||
"recordOnly": true
|
||||
},
|
||||
{
|
||||
"id": "politics.clan-petition",
|
||||
"label": "POL & orders · Clan Delegate petition",
|
||||
|
|
|
|||
|
|
@ -10,13 +10,15 @@ export function createNaibCouncilAPI(db,settings={},deps={}){
|
|||
const url=new URL(request.url);if(url.search)return reply({message:'Account and sietch overrides are not accepted.'},400);
|
||||
const actor=await auth(request);if(!actor)return reply({message:'Sign in first.'},401);
|
||||
if(!(await access(actor)).nodes.includes('web.menu.game'))throw new JarvisError('Game account access required.',403);
|
||||
if(url.pathname==='/api/politics/naibs/petition'&&!deps.petitions)throw new JarvisError('Sietch petitions unavailable.',503);
|
||||
if(request.method==='GET'&&url.pathname==='/api/politics/naibs/petition')return reply(await deps.petitions.context(actor));
|
||||
if(request.method==='GET'&&url.pathname==='/api/politics/naibs')return reply(await service.context(actor));
|
||||
if(request.method!=='POST'||!['/api/politics/naibs/propose','/api/politics/naibs/vote','/api/politics/naibs/withdraw'].includes(url.pathname))return reply({message:'Method not allowed.'},405);
|
||||
if(request.method!=='POST'||!['/api/politics/naibs/propose','/api/politics/naibs/vote','/api/politics/naibs/withdraw','/api/politics/naibs/petition'].includes(url.pathname))return reply({message:'Method not allowed.'},405);
|
||||
if(request.headers.get('origin')!==origin)throw new JarvisError('Invalid request origin.',403);
|
||||
if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))throw new JarvisError('JSON required.',415);
|
||||
const raw=await request.text();if(raw.length>16000)throw new JarvisError('Proposal too large.',413);let input;try{input=JSON.parse(raw);}catch{throw new JarvisError('Invalid Council request.');}
|
||||
if(!input||typeof input!=='object'||Array.isArray(input))throw new JarvisError('Invalid Council request.');
|
||||
return reply(await (url.pathname.endsWith('/vote')?service.vote(actor,input):url.pathname.endsWith('/withdraw')?service.withdraw(actor,input):service.propose(actor,input)),201);
|
||||
return reply(await (url.pathname.endsWith('/petition')?deps.petitions.propose(actor,input):url.pathname.endsWith('/vote')?service.vote(actor,input):url.pathname.endsWith('/withdraw')?service.withdraw(actor,input):service.propose(actor,input)),201);
|
||||
}catch(error){return reply({message:error instanceof JarvisError?error.message:'Council records are temporarily unavailable.'},error instanceof JarvisError?error.status:503);}
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ 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']});
|
||||
const db=boardReadStore(raw,raw),banking=atomicBankAccess(db,bank,{verifyStorage,centralTables:['jarvis_naib_petitions','jarvis_political_agreement_replies','political_office_terms','political_office_charters','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{policies:NAIB_COUNCIL_DECISIONS.map(d=>({...d,canExecute:levelNow>=d.level&&accounts.some(a=>BigInt(a.availableMinor)>=BigInt(d.feeMinor))})),...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,kind='decision',now=clock()}){
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import {NAIB_PETITION_SCHEMA} from './naib-petitions.mjs';
|
||||
import {readCurrentCouncilAccords,withdrawCouncilAccord} from './naib-council-accords.mjs';
|
||||
import {NAIB_COUNCIL_DECISION as PAID_POLICY,NAIB_COUNCIL_DECISIONS,naibProposal} from '../control-panel/public/naib-council-policy.mjs';
|
||||
import {randomUUID,createHash} from 'node:crypto';
|
||||
|
|
@ -6,6 +7,7 @@ import {naibSeats,currentNaib} from './naib-membership.mjs';
|
|||
import {decisionBallotOutcome} from '../control-panel/public/decision-ballot-policy.mjs';
|
||||
export const COUNCIL_PROPOSAL_COOLDOWN_MS=86400000;
|
||||
export const NAIB_COUNCIL_SCHEMA=[
|
||||
NAIB_PETITION_SCHEMA,
|
||||
`CREATE TABLE IF NOT EXISTS jarvis_council_proposal_locks(scope_key VARCHAR(80) PRIMARY KEY,last_proposed_at BIGINT) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
||||
`CREATE TABLE IF NOT EXISTS jarvis_council_dossiers(id CHAR(36) PRIMARY KEY,request_id CHAR(36) NOT NULL UNIQUE,actor_id CHAR(36) NOT NULL,kind VARCHAR(24) NOT NULL,title VARCHAR(100) NOT NULL,message TEXT NOT NULL,fingerprint CHAR(64) NOT NULL,electorate TEXT NOT NULL,opens_at BIGINT NOT NULL,closes_at BIGINT NOT NULL,state VARCHAR(24) NOT NULL,result VARCHAR(24) NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
||||
`CREATE TABLE IF NOT EXISTS jarvis_council_votes(dossier_id CHAR(36) NOT NULL,clan_id CHAR(36) NOT NULL,user_id CHAR(36) NOT NULL,choice VARCHAR(16) NOT NULL,created_at BIGINT NOT NULL,PRIMARY KEY(dossier_id,clan_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
||||
|
|
@ -55,7 +57,7 @@ export function createNaibCouncil(db,{clock=Date.now,billing=null}={}){
|
|||
},
|
||||
async propose(actor,input){
|
||||
if(!uuid(actor?.id)||!uuid(input?.requestId)||input.confirmed!==true||!(input.kind==='imperial-peace'||naibProposal(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 policy=naibProposal(input.kind),paid=db.naibCouncilPaidEnabled===true&&!!policy,wait=policy?.cooldownMs||COUNCIL_PROPOSAL_COOLDOWN_MS;if(policy?.durationMs&&!paid)throw new JarvisError('Funded Council accords are unavailable.',503);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 policy=naibProposal(input.kind),paid=db.naibCouncilPaidEnabled===true&&!!policy,wait=policy?.cooldownMs||COUNCIL_PROPOSAL_COOLDOWN_MS;if(policy?.petitionOnly)throw new JarvisError('Use the private Voice of Arrakis petition form.',400);if(policy?.durationMs&&!paid)throw new JarvisError('Funded Council accords are unavailable.',503);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});
|
||||
|
|
|
|||
34
website/node/naib-petitions.mjs
Normal file
34
website/node/naib-petitions.mjs
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import {createHash} from 'node:crypto';
|
||||
import {boardReadStore} from './board-deed-source.mjs';
|
||||
import {currentNaib} from './naib-membership.mjs';
|
||||
import {currentOfficeController} from './entity-relations.mjs';
|
||||
import {officeAuthority} from './political-decisions.mjs';
|
||||
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
|
||||
import {validUuid} from './game-link.mjs';
|
||||
import {JarvisError} from './jarvis-listings.mjs';
|
||||
import {naibDecision} from '../control-panel/public/naib-council-policy.mjs';
|
||||
export const NAIB_PETITION_POLICY=naibDecision('FRE-07');
|
||||
export const NAIB_PETITION_SCHEMA=`CREATE TABLE IF NOT EXISTS jarvis_naib_petitions(request_id CHAR(36) PRIMARY KEY,key_id CHAR(36) NOT NULL UNIQUE,actor_id CHAR(36) NOT NULL,clan_id CHAR(36) NOT NULL,target_actor CHAR(36) NOT NULL,target_term CHAR(36) NOT NULL,title VARCHAR(100) NOT NULL,message TEXT NOT NULL,input_hash CHAR(64) NOT NULL,created_at BIGINT NOT NULL,response_until BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`;
|
||||
const fail=(message,status=409)=>{throw new JarvisError(message,status);},hash=v=>createHash('sha256').update(JSON.stringify(v)).digest('hex'),P=NAIB_PETITION_POLICY;
|
||||
export function createNaibPetitions(raw,keys,billing,{clock=Date.now}={}){
|
||||
if(!raw?.query||!raw?.transaction)return{context:async()=>fail('Sietch petitions unavailable.',503),propose:async()=>fail('Sietch petitions unavailable.',503),read:async()=>[],reply:async()=>fail('Sietch petition not found.',404)};
|
||||
const db=boardReadStore(raw,raw);
|
||||
async function emperor(tx,now,lock=false){const h=await currentOfficeController(tx,'emperor',now);if(!h||!await officeAuthority(tx,{office:'emperor'},{id:h.userId},now,lock))return null;const term=await tx.first('SELECT expires_at FROM political_office_terms WHERE id=?',[h.termId]);return{...h,expiresAt:Number(term?.expires_at||0)};}
|
||||
async function context(actor){const now=clock(),seat=await currentNaib(db,actor.id),recipient=await emperor(db,now),funding=seat&&billing?await billing.context(actor,seat):null,row=seat?await db.first('SELECT MAX(created_at) last_at FROM jarvis_naib_petitions WHERE clan_id=? OR actor_id=?',[seat.clan_id,actor.id]):null,cooldownUntil=row?.last_at==null?null:Number(row.last_at)+P.cooldownMs,policy=funding?.policies?.find(p=>p.id===P.id);return{...P,canManage:!!seat,canExecute:!!keys&&!!recipient&&recipient.userId!==actor.id&&recipient.expiresAt>now+P.responseMs&&!!policy?.canExecute&&(!cooldownUntil||now>=cooldownUntil),cooldownUntil,recipient:recipient?'Current Emperor':null,levelNow:funding?.levelNow||0,accounts:funding?.accounts||[]};}
|
||||
async function propose(actor,input){
|
||||
if(!input||Object.keys(input).sort().join(',')!=='confirmed,message,requestId,sourceAccount,title'||input.confirmed!==true||!validUuid(input.requestId)||typeof input.sourceAccount!=='string'||!/^\d{1,12}$/.test(input.sourceAccount)||typeof input.title!=='string'||input.title.trim().length<3||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))fail('Review the petition and its sietch funding.',400);
|
||||
if(!keys||!billing||raw.naibCouncilPaidEnabled!==true)fail('Sietch petition banking unavailable.',503);await billing.ready();const digest=hash([actor.id,input.sourceAccount,input.title.trim(),input.message.trim()]);
|
||||
return raw.transaction(async original=>{const tx=boardReadStore(original,db),now=clock(),seat=await currentNaib(tx,actor.id,{lock:true});if(!seat)fail('Current independent sietch ownership required.',403);
|
||||
const scope='petition:sietch:'+seat.clan_id;await tx.query('INSERT INTO jarvis_council_proposal_locks(scope_key) VALUES(?) ON DUPLICATE KEY UPDATE scope_key=VALUES(scope_key)',[scope]);await tx.first('SELECT scope_key FROM jarvis_council_proposal_locks WHERE scope_key=? FOR UPDATE',[scope]);
|
||||
const prior=await tx.first('SELECT * FROM jarvis_naib_petitions WHERE request_id=? FOR UPDATE',[input.requestId]);if(prior){if(prior.actor_id!==actor.id||prior.input_hash!==digest)fail('Petition reference conflict.');return{ok:true,replayed:true,reference:prior.key_id};}
|
||||
const previous=await tx.first('SELECT MAX(created_at) last_at FROM jarvis_naib_petitions WHERE clan_id=? OR actor_id=?',[seat.clan_id,actor.id]);if(previous?.last_at!=null&&now<Number(previous.last_at)+P.cooldownMs)fail('This sietch petition is on its48-hour cooldown.');
|
||||
const recipient=await emperor(tx,now,true);if(!recipient||recipient.userId===actor.id||recipient.expiresAt<=now+P.responseMs)fail('A different current Royal Emperor must hold the full72-hour response mandate.',403);
|
||||
const funding=await billing.charge(tx,{actor,seat,sourceAccount:input.sourceAccount,requestId:input.requestId,dossierId:input.requestId,kind:P.kind,now});
|
||||
await tx.query('INSERT INTO jarvis_naib_petitions VALUES(?,?,?,?,?,?,?,?,?,?,?)',[input.requestId,funding.keyId,actor.id,seat.clan_id,recipient.userId,recipient.termId,input.title.trim(),input.message.trim(),digest,now,now+P.responseMs]);return{ok:true,replayed:false,reference:funding.keyId,feeMinor:funding.feeMinor,xp:funding.xp};
|
||||
});
|
||||
}
|
||||
async function verified(tx,row,now){const 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",[row.key_id,STAFF_OFFICE_ACCOUNT_ID,'state:naib-council:'+row.request_id]);if(!key)return null;const seat=await currentNaib(tx,row.actor_id),target=await emperor(tx,now);return{current:seat?.clan_id===row.clan_id&&target?.userId===row.target_actor&&target.termId===row.target_term};}
|
||||
async function read(actor){const rows=await db.query('SELECT * FROM jarvis_naib_petitions WHERE actor_id=? OR target_actor=? ORDER BY created_at DESC,request_id DESC LIMIT 100',[actor.id,actor.id]),items=[],now=clock();for(const row of rows){const proof=await verified(db,row,now);if(!proof)continue;const answer=await db.first("SELECT r.*,k.id verified_key FROM jarvis_political_agreement_replies r LEFT JOIN organisation_keys k ON k.id=r.key_id AND k.account_id=? AND k.key_type='entity-state' AND k.scope_id=CONCAT('state:political-agreement-reply:',r.request_id) AND k.revoked_at IS NULL WHERE r.decision_request=?",[STAFF_OFFICE_ACCOUNT_ID,row.request_id]),valid=answer?.verified_key&&answer.actor_id===row.target_actor&&answer.term_id===row.target_term&&['accept','decline'].includes(answer.choice)&&Number(answer.created_at)>=Number(row.created_at)&&Number(answer.created_at)<Number(row.response_until)&&answer.input_hash===hash([answer.actor_id,row.request_id,answer.choice]),state=valid?(answer.choice==='accept'?'acknowledged':'declined'):answer?'response-unavailable':!proof.current?'mandate-ended':now>=Number(row.response_until)?'expired':'pending';items.push({id:row.request_id,mode:'petition',decisionId:P.id,title:row.title,terms:row.message,sourceOffice:'independent_sietch',targetOffice:'emperor',targetName:'Emperor',responseUntil:Number(row.response_until),respondedAt:valid?Number(answer.created_at):null,endsAt:null,state,canReply:state==='pending'&&actor.id===row.target_actor,reference:row.key_id});}return items;}
|
||||
async function reply(actor,input){if(!input||Object.keys(input).sort().join(',')!=='choice,confirmed,proposalId,requestId'||input.confirmed!==true||!validUuid(input.proposalId)||!validUuid(input.requestId)||!['accept','decline'].includes(input.choice))fail('Review this petition response.',400);if(!keys)fail('Petition signatures unavailable.',503);return raw.transaction(async original=>{const tx=boardReadStore(original,db),row=await tx.first('SELECT * FROM jarvis_naib_petitions WHERE request_id=? FOR UPDATE',[input.proposalId]);if(!row||row.target_actor!==actor.id)fail('This petition is not addressed to your account.',403);const digest=hash([actor.id,row.request_id,input.choice]),old=await tx.first('SELECT * FROM jarvis_political_agreement_replies WHERE decision_request=? OR request_id=? FOR UPDATE',[row.request_id,input.requestId]);if(old){if(old.request_id!==input.requestId||old.actor_id!==actor.id||old.input_hash!==digest)fail('This petition already has a response.');return{ok:true,replayed:true,reference:old.key_id};}const now=clock(),proof=await verified(tx,row,now);if(!proof?.current||now>=Number(row.response_until))fail('This petition or one of its original mandates has expired.');const seat=await currentNaib(tx,row.actor_id,{lock:true}),target=await emperor(tx,now,true);if(seat?.clan_id!==row.clan_id||target?.userId!==actor.id||target.termId!==row.target_term)fail('Both original mandates must remain current.',403);let reference;await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',scopeId:'state:political-agreement-reply:'+input.requestId,transactionStore:tx,authorize:async(_,{keyId})=>{reference=keyId;await tx.query('INSERT INTO jarvis_political_agreement_replies VALUES(?,?,?,?,?,?,?,?)',[row.request_id,input.requestId,keyId,actor.id,target.termId,input.choice,digest,now]);}});return{ok:true,replayed:false,reference};});}
|
||||
return{context,propose,read,reply};
|
||||
}
|
||||
|
|
@ -14,7 +14,7 @@ export const POLITICAL_COMPANY_REPLY_SCHEMA=`CREATE TABLE IF NOT EXISTS jarvis_p
|
|||
const replyTable=d=>d.targetKind==='company'?'jarvis_political_company_replies':'jarvis_political_agreement_replies';
|
||||
const fail=(message,status=409)=>{throw Object.assign(Error(message),{status});};
|
||||
const hash=v=>createHash('sha256').update(JSON.stringify(v)).digest('hex');
|
||||
export function createPoliticalAgreements(raw,keys,{clock=Date.now}={}){
|
||||
export function createPoliticalAgreements(raw,keys,{clock=Date.now,petitions=null}={}){
|
||||
if(typeof raw?.query!=='function')return{targets:async()=>[],create:async()=>fail('Political agreements unavailable.',503),read:async()=>fail('Political agreements unavailable.',503),reply:async()=>fail('Political agreements unavailable.',503)};
|
||||
const db=boardReadStore(raw,raw);
|
||||
async function holder(tx,office,actor,now,lock=false){const h=await officeAuthority(tx,{office},actor,now,lock);if(!h)return null;const term=await tx.first('SELECT expires_at FROM political_office_terms WHERE id=?',[h.termId]);return term?{...h,expiresAt:Number(term.expires_at)}:null;}
|
||||
|
|
@ -49,10 +49,11 @@ export function createPoliticalAgreements(raw,keys,{clock=Date.now}={}){
|
|||
if(v.d.agreementMode==='representation'&&state==='accepted'){const appointment=await tx.first("SELECT id FROM political_appointment_deeds WHERE request_id=? AND appointment_type='political-adviser' AND revoked_at IS NULL",[reply.request_id]);if(!appointment||(await activePoliticalAppointments(tx,{userId:row.actor_id,clock:()=>now})).every(a=>a.id!==appointment.id))state='representation-ended';}
|
||||
return{id:row.request_id,mode:petition?'petition':v.d.agreementMode==='representation'?'representation':'agreement',respondedAt:replyValid?Number(reply.created_at):null,title:v.payload.title,terms:v.payload.terms,decisionId:v.d.id,sourceOffice:v.d.office,targetOffice:v.a.targetOffice||null,targetName:v.a.targetName||PUBLIC_OFFICES.find(o=>o.key===v.a.targetOffice)?.scope||v.a.targetOffice,responseUntil:v.a.responseUntil,endsAt,state,canReply:state==='pending'&&actor.id===v.a.targetActorId,reference:row.key_id};
|
||||
}
|
||||
async function read(actor){const rows=await db.query('SELECT * FROM jarvis_political_decisions WHERE actor_id=? OR recipient_id=? ORDER BY created_at DESC,request_id DESC LIMIT 100',[actor.id,actor.id]),items=[];for(const row of rows){const item=await projection(db,row,actor,clock());if(item)items.push(item);}return{agreements:items};}
|
||||
async function read(actor){const rows=await db.query('SELECT * FROM jarvis_political_decisions WHERE actor_id=? OR recipient_id=? ORDER BY created_at DESC,request_id DESC LIMIT 100',[actor.id,actor.id]),items=[];for(const row of rows){const item=await projection(db,row,actor,clock());if(item)items.push(item);}return{agreements:[...items,...(petitions?await petitions.read(actor):[])]};}
|
||||
async function reply(actor,input){
|
||||
if(!input||Object.keys(input).sort().join(',')!=='choice,confirmed,proposalId,requestId'||input.confirmed!==true||!validUuid(input.requestId)||!validUuid(input.proposalId)||!['accept','decline'].includes(input.choice))fail('Review and confirm this proposal response.',400);
|
||||
if(!keys||!raw.transaction)fail('Agreement records unavailable.',503);
|
||||
if(petitions&&!await db.first('SELECT request_id FROM jarvis_political_decisions WHERE request_id=?',[input.proposalId]))return petitions.reply(actor,input);
|
||||
return raw.transaction(async original=>{const tx=boardReadStore(original,db),now=clock(),row=await tx.first('SELECT * FROM jarvis_political_decisions WHERE request_id=? FOR UPDATE',[input.proposalId]);if(!row||row.recipient_id!==actor.id)fail('This proposal is not addressed to your office.',403);
|
||||
const policy=politicalDecision(row.decision_id);if(policy?.kind!=='agreement')fail('Registered agreement required.',400);const digest=hash([actor.id,input.proposalId,input.choice]),old=await tx.first('SELECT * FROM '+replyTable(policy)+' WHERE decision_request=? OR request_id=? FOR UPDATE',[row.request_id,input.requestId]);
|
||||
if(old){if(old.request_id!==input.requestId||old.input_hash!==digest||old.actor_id!==actor.id)fail('This proposal already has a response.');return{ok:true,replayed:true,reference:old.key_id};}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
import {NAIB_COUNCIL_SCHEMA,createNaibCouncil} from '../node/naib-council.mjs';
|
||||
import {hasOrganisationPassage} from '../node/imperial-organisation-passage.mjs';
|
||||
import {createNaibPetitions,NAIB_PETITION_POLICY} from '../node/naib-petitions.mjs';
|
||||
import {createNaibCouncilAPI} from '../node/naib-council-api.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';
|
||||
|
|
@ -325,6 +327,13 @@ test('company ownership changes cannot transfer confidential pending consent to
|
|||
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})};}
|
||||
async function naibPetitionFixture(){const f=await paidNaibFixture(),office=PUBLIC_OFFICES.find(o=>o.key==='emperor'),emperorTerm=randomUUID(),charter=await f.keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-office-royal',scopeId:'office:emperor',authorize:async()=>true});await f.keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-office-royal',code:charter.code,targetId:randomUUID(),requestId:randomUUID(),apply:(tx,{keyId})=>tx.query("INSERT INTO political_office_charters VALUES('emperor','royal',?)",[keyId])});await f.db.query("INSERT INTO political_office_terms(id,user_id,kind,faction,office,outcome,starts_at,expires_at) VALUES(?,?,?,?,?,'winner',0,9999999999)",[emperorTerm,f.people.Ceo.id,office.kind,office.faction,office.office]);const petitions=createNaibPetitions(f.db,f.keys,f.billing,{clock:f.clock}),agreements=createPoliticalAgreements(f.db,f.keys,{clock:f.clock,petitions});return{...f,petitions,agreements,emperorTerm,petition:()=>({requestId:randomUUID(),sourceAccount:String(f.target.id),title:'Voice of our sietch',message:'Please hear the water and spice concerns of our independent sietch.',confirmed:true}),reply:(proposalId,choice='accept')=>({proposalId,choice,requestId:randomUUID(),confirmed:true})};}
|
||||
test('Voice of Arrakis is privately delivered through existing signatures and paid once by the actual independent sietch owner',async()=>{const f=await naibPetitionFixture();try{const view=await f.petitions.context(f.people.Other);assert.equal(view.canExecute,true);assert.equal(view.level,15);assert.equal(view.feeMinor,100000);assert.equal(NAIB_PETITION_POLICY.xp,250);const input=f.petition(),receipt=await f.petitions.propose(f.people.Other,input);assert.equal((await f.petitions.propose(f.people.Other,input)).reference,receipt.reference);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,400000);assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Other.id])).total_xp,10250);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,1);assert.equal((await f.agreements.read(f.people.Owner)).agreements.length,0);let item=(await f.agreements.read(f.people.Ceo)).agreements[0];assert.equal(item.mode,'petition');assert.equal(item.decisionId,'FRE-07');assert.equal(item.canReply,true);await assert.rejects(f.agreements.reply(f.people.Member,f.reply(input.requestId)),/not addressed/);const reply=f.reply(input.requestId),answer=await f.agreements.reply(f.people.Ceo,reply);assert.equal((await f.agreements.reply(f.people.Ceo,reply)).reference,answer.reference);item=(await f.agreements.read(f.people.Other)).agreements[0];assert.equal(item.state,'acknowledged');assert.equal(item.endsAt,null);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);assert.equal((await f.petitions.context(f.people.Other)).canExecute,false);}finally{f.db.close();}});
|
||||
test('private sietch petitions reject expired or changed original mandates and revoked source proofs',async()=>{for(const change of ['owner','emperor','charter','key','deadline']){const f=await naibPetitionFixture();try{const input=f.petition(),r=await f.petitions.propose(f.people.Other,input);if(change==='owner')await f.db.query('UPDATE site_clans SET owner_id=? WHERE id=?',[f.people.Member.id,f.clanId]);if(change==='emperor')await f.db.query("UPDATE political_office_terms SET outcome='ended' WHERE id=?",[f.emperorTerm]);if(change==='charter')await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=(SELECT staff_key_id FROM political_office_charters WHERE office_key=?)',['emperor']);if(change==='key')await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[r.reference]);if(change==='deadline')f.setTime(1000+72*3600000);await assert.rejects(f.agreements.reply(f.people.Ceo,f.reply(input.requestId)),/expired/);assert.equal((await f.agreements.read(f.people.Member)).agreements.length,0);}finally{f.db.close();}}});
|
||||
test('petition storage failures roll back sietch fees, Reputation and ordinary keys; replies never create gameplay powers',async()=>{const f=await naibPetitionFixture();try{const before=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;f.db.sqlite.exec("CREATE TRIGGER fail_petition BEFORE INSERT ON jarvis_naib_petitions BEGIN SELECT RAISE(ABORT,'petition journal failed');END");await assert.rejects(f.petitions.propose(f.people.Other,f.petition()),/petition 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);f.db.sqlite.exec('DROP TRIGGER fail_petition');const input=f.petition();await f.petitions.propose(f.people.Other,input);const count=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;f.db.sqlite.exec("CREATE TRIGGER fail_petition_reply BEFORE INSERT ON jarvis_political_agreement_replies BEGIN SELECT RAISE(ABORT,'petition response failed');END");await assert.rejects(f.agreements.reply(f.people.Ceo,f.reply(input.requestId)),/petition response failed/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,count);assert.equal((await f.agreements.read(f.people.Other)).agreements[0].state,'pending');f.db.sqlite.exec('DROP TRIGGER fail_petition_reply');await f.agreements.reply(f.people.Ceo,f.reply(input.requestId,'decline'));assert.equal((await f.agreements.read(f.people.Other)).agreements[0].state,'declined');assert.equal((await f.db.first('SELECT COUNT(*) n FROM political_office_terms')).n,2);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_entity_relations')).n,0);}finally{f.db.close();}});
|
||||
test('petitions require legal Naib authority, sufficient Reputation, published fields and a full receiving term',async()=>{const f=await naibPetitionFixture();try{await assert.rejects(f.petitions.propose(f.people.Owner,f.petition()),/independent sietch/);await assert.rejects(f.petitions.propose(f.people.Other,{...f.petition(),clanId:f.clanId}),/Review the petition/);await assert.rejects(f.council.propose(f.people.Other,{...f.input(),kind:'petition'}),/private Voice/);await f.db.query('UPDATE political_office_terms SET expires_at=2000 WHERE id=?',[f.emperorTerm]);await assert.rejects(f.petitions.propose(f.people.Other,f.petition()),/full72-hour/);await f.db.query('UPDATE political_office_terms SET expires_at=9999999999 WHERE id=?',[f.emperorTerm]);await f.pol.query('UPDATE jarvis_progression_accounts SET effective_xp=0,total_xp=0 WHERE account_id=?',[f.people.Other.id]);await assert.rejects(f.petitions.propose(f.people.Other,f.petition()),/Reputation level 15/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{f.db.close();}});
|
||||
test('the private petition API enforces origin and rejects supplied identities while acknowledgements remain historical',async()=>{const f=await naibPetitionFixture();try{const api=createNaibCouncilAPI(f.db,{}, {authenticate:async()=>f.people.Other,access:async()=>({nodes:['web.menu.game']}),billing:f.billing,petitions:f.petitions}),call=(input,origin='https://cp.dunerealms.com')=>api(new Request('https://cp.dunerealms.com/api/politics/naibs/petition',{method:'POST',headers:{origin,'Content-Type':'application/json'},body:JSON.stringify(input)}));assert.equal((await call(f.petition(),'https://example.invalid')).status,403);assert.equal((await call({...f.petition(),actorId:f.people.Owner.id})).status,400);const input=f.petition();assert.equal((await call(input)).status,201);await f.agreements.reply(f.people.Ceo,f.reply(input.requestId));await f.db.query("UPDATE political_office_terms SET outcome='ended' WHERE id=?",[f.emperorTerm]);f.setTime(1000+10*86400000);assert.equal((await f.agreements.read(f.people.Other)).agreements[0].state,'acknowledged');}finally{f.db.close();}});
|
||||
test('sietch ownership changes retain the petition cooldown and cannot inherit its private history or a revoked answer',async()=>{const f=await naibPetitionFixture();try{const input=f.petition();await f.petitions.propose(f.people.Other,input);const answer=await f.agreements.reply(f.people.Ceo,f.reply(input.requestId));await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[answer.reference]);assert.equal((await f.agreements.read(f.people.Other)).agreements[0].state,'response-unavailable');await assert.rejects(f.agreements.reply(f.people.Ceo,f.reply(input.requestId,'decline')),/already has a response/);await f.db.query('UPDATE site_clans SET owner_id=? WHERE id=?',[f.people.Member.id,f.clanId]);const link=await f.db.first('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?',[f.people.Member.id]);await f.db.query("INSERT INTO site_clan_members(user_id,minecraft_uuid,clan_id,clan_role,joined_at) VALUES(?,?,?,'owner',1)",[f.people.Member.id,link.minecraft_uuid,f.clanId]);assert.equal((await f.petitions.context(f.people.Member)).cooldownUntil,1000+48*3600000);await assert.rejects(f.petitions.propose(f.people.Member,f.petition()),/cooldown/);assert.equal((await f.agreements.read(f.people.Member)).agreements.length,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);}finally{f.db.close();}});
|
||||
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();}});
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff