Merge pull request 'Connect office diplomacy to private proposals and signed bilateral consent' (#589) from dev/MC:feature/political-diplomacy-20261125 into main
All checks were successful
DuneRealms Web CI / web (push) Successful in 3m12s
All checks were successful
DuneRealms Web CI / web (push) Successful in 3m12s
This commit is contained in:
commit
77fb95617d
13 changed files with 266 additions and 22 deletions
|
|
@ -12,7 +12,7 @@ const related={
|
|||
const authority={IMP:'Current Emperor deed',ATR:'Current Aerdrecht House office deed',HAR:'Current Harkveen House office deed',COR:'Current Korenholt House office deed',ORD:'Current Oordwijk House office deed',FRE:'Current recognised sietch deed; independent Council',BG:'Current Veiled Concord office deed',NF:'Current Church of Muad’Dib office deed',SG:'Current Spacing Guild office deed',CLD:'Current clan delegate deed'};
|
||||
function paidDecisionGap(id){
|
||||
const kind=politicalDecision(id)?.kind,base='Current office, Reputation, authorised office funding and successor-safe cooldown checked atomically. ';
|
||||
return base+(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.');
|
||||
return base+(kind==='agreement'?'A confidential proposal is delivered only to its original receiving office holder. Acceptance or refusal requires that same current Royal mandate, 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 decisionAudit=id=>DECISION_AUDIT.find(row=>row.id===id)||null;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,16 @@
|
|||
import {element as el} from './cp-v2-page-template.mjs';
|
||||
import {createUserAPI} from './cp-v2-user-api.mjs';
|
||||
export function mountPoliticalAgreements(host,{fetcher=fetch}={}){
|
||||
const root=el('section',undefined,'cp-political-agreement-inbox'),heading=el('h3','Diplomatic proposals'),status=el('p','Reading your diplomatic proposals…'),list=el('div'),refresh=el('button','Refresh proposals'),api=createUserAPI(fetcher);
|
||||
status.setAttribute('role','status');refresh.type='button';root.append(heading,status,list,refresh);host.append(root);let busy=false;
|
||||
async function load(){if(busy)return;busy=true;refresh.disabled=true;try{const data=await api.request('/api/politics/agreements');if(!root.isConnected)return;list.replaceChildren();status.textContent=data.agreements.length?'Only proposals addressed to you or issued by you are shown.':'No diplomatic proposals for your current account.';
|
||||
for(const a of data.agreements){const card=el('article'),title=el('h4',a.title),terms=el('p',a.terms),state=el('p',a.sourceOffice.replaceAll('_',' ')+' → '+a.targetOffice.replaceAll('_',' ')+' · '+a.state),deadline=el('p',(a.endsAt?'Ends: ':'Reply before: ')+new Date(a.endsAt||a.responseUntil).toLocaleString());card.append(title,terms,state,deadline,el('small','J.A.R.V.I.S. reference: '+a.reference));
|
||||
if(a.canReply){const review=el('p'),confirm=el('button','Confirm response'),cancel=el('button','Cancel'),accept=el('button','Review acceptance'),decline=el('button','Review refusal');for(const b of [confirm,cancel,accept,decline])b.type='button';confirm.hidden=cancel.hidden=true;let pending=null;
|
||||
const prepare=choice=>{pending={proposalId:a.id,requestId:crypto.randomUUID(),choice,confirmed:true};review.textContent=(choice==='accept'?'Accept':'Decline')+' “'+a.title+'”? This does not change votes, offices, ownership, travel or war participation.';confirm.hidden=cancel.hidden=false;accept.disabled=decline.disabled=true;};accept.onclick=()=>prepare('accept');decline.onclick=()=>prepare('decline');cancel.onclick=()=>{pending=null;review.textContent='';confirm.hidden=cancel.hidden=true;accept.disabled=decline.disabled=false;};
|
||||
confirm.onclick=async()=>{if(!pending||busy)return;busy=true;confirm.disabled=cancel.disabled=refresh.disabled=true;try{await api.request('/api/politics/agreements',pending);pending=null;busy=false;await load();}catch(error){status.textContent=error.message+(error.uncertain?' Retry this same response to check its recorded result.':'');if(!error.uncertain)cancel.onclick();}finally{busy=false;confirm.disabled=cancel.disabled=refresh.disabled=false;}};
|
||||
card.append(accept,decline,review,confirm,cancel);
|
||||
}list.append(card);
|
||||
}
|
||||
}catch(error){status.textContent=error.message;}finally{busy=false;refresh.disabled=false;}}
|
||||
refresh.onclick=load;load();
|
||||
}
|
||||
|
|
@ -7,8 +7,9 @@ export function mountPoliticalDecision(host,id,{fetcher=fetch}={}){
|
|||
const api=createUserAPI(fetcher),endpoint='/api/politics/decisions',status=el('p','Reading current office, funding and Reputation…'),form=el('div'),review=el('p'),prepare=el('button','Review decision'),confirm=el('button','Confirm and pay'),refresh=el('button','Refresh');
|
||||
status.setAttribute('role','status');form.className='cp-political-decision-form';const fields=[];
|
||||
function field(title,tag){const label=el('label',title),input=el(tag);label.append(input);form.append(label);fields.push(input);return input;}
|
||||
const account=field('Office funding account','select');let title,body,recipient,citation,search,find,startsAt,endsAt,percent,houseSelect,clanSelect,grantAmount,grantReason;
|
||||
if(d.kind==='proclamation'){title=field('Title','input');title.maxLength=120;title.minLength=3;body=field('Official message','textarea');body.maxLength=6000;body.minLength=10;body.rows=6;}
|
||||
const account=field('Office funding account','select');let title,body,recipient,citation,search,find,startsAt,endsAt,percent,houseSelect,clanSelect,grantAmount,grantReason,officeSelect;
|
||||
if(d.kind==='agreement'){officeSelect=field('Receiving political office','select');title=field('Proposal title','input');title.maxLength=100;body=field('Confidential diplomatic terms','textarea');body.minLength=20;body.maxLength=4000;body.rows=6;form.append(el('p','The receiving current Royal office holder must consent within 72 hours. Accepted terms last at most '+d.durationMs/86400000+' days and end with either mandate. No votes, ownership, war, bank or travel rights are transferred.'));}
|
||||
else if(d.kind==='proclamation'){title=field('Title','input');title.maxLength=120;title.minLength=3;body=field('Official message','textarea');body.maxLength=6000;body.minLength=10;body.rows=6;}
|
||||
else if(d.kind==='event'){title=field('Session title','input');title.maxLength=100;body=field('Purpose and invitation','textarea');body.maxLength=2000;body.rows=4;startsAt=field('Start time (UTC)','input');endsAt=field('End time (UTC)','input');startsAt.type=endsAt.type='datetime-local';form.append(el('p','Schedule at least one minute ahead and no more than 30 days ahead. The session must finish before your mandate ends and last at most '+(d.maxEventMs||86400000)/3600000+' hours. It appears in the existing political calendar.'));if(d.id==='SG-06')form.append(el('p','This convenes voluntary mediation. Participants must separately approve any treaty, coalition or peace through its existing consent flow.'));}
|
||||
else if(d.kind==='tariff'){percent=field('Guild surcharge','select');for(let n=0;n<=5;n++){const o=el('option',n===0?'0% · repeal':n+'%');o.value=String(n);percent.append(o);}form.append(el('p','Applies to new Guild bookings for seven days, while this mandate remains current. Confirmed fares remain unchanged. It does not open blocked routes or change smuggler fares.'));}
|
||||
else if(d.kind==='guild-discount'){houseSelect=field('Native House','select');for(const w of TRADE_WORLDS){const o=el('option',w.name+' · '+w.house);o.value=w.house;houseSelect.append(o);}form.append(el('p',d.discountPercent+'% preferred Guild fare for '+d.durationMs/3600000+' hours. The strongest eligible discount applies; discounts do not stack. It does not grant new routes, alter boarding windows or override an embargo or Imperial Arrakis permission.'));}
|
||||
|
|
@ -22,18 +23,20 @@ export function mountPoliticalDecision(host,id,{fetcher=fetch}={}){
|
|||
function controls(){for(const f of fields)f.disabled=busy||!!pending||!current?.canManage;prepare.disabled=busy||!!pending||!current?.canExecute;confirm.disabled=busy||!pending;refresh.disabled=busy;if(find)find.disabled=busy||!!pending||!current?.canManage;}
|
||||
async function load(){busy=true;controls();try{const data=await api.request(endpoint+'?decisionId='+encodeURIComponent(id)+(search?'&search='+encodeURIComponent(search.value):''));if(!host.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;
|
||||
if(officeSelect){const selected=officeSelect.value;officeSelect.replaceChildren();for(const o of data.diplomacyTargets){const option=el('option',o.name);option.value=o.id;officeSelect.append(option);}if(data.diplomacyTargets.some(o=>o.id===selected))officeSelect.value=selected;}
|
||||
if(clanSelect){const selected=clanSelect.value;clanSelect.replaceChildren();for(const c of data.clans){const o=el('option',c.name);o.value=c.id;clanSelect.append(o);}if(data.clans.some(c=>c.id===selected))clanSelect.value=selected;}
|
||||
if(recipient){const selected=recipient.value;recipient.replaceChildren();for(const r of data.recipients){const o=el('option',r.username);o.value=r.id;recipient.append(o);}if(data.recipients.some(r=>r.id===selected))recipient.value=selected;}
|
||||
status.textContent=(data.canManage?'Current office verified. ':'Current elected office required. ')+(d.feeMinor/100).toFixed(2)+' DM from the selected office account · '+d.xp+' Reputation points · Reputation level '+data.levelNow+'/'+d.level+' required. '+(data.cooldownUntil>Date.now()?'Available after '+new Date(data.cooldownUntil).toLocaleString():d.cooldownMs/3600000+'-hour office cooldown.')+(data.reportAvailable===false?' Verified reporting is unavailable; no payment can be made.':'');if(d.kind==='report')drawReport(data.report);
|
||||
if(d.kind==='clan-grant')status.textContent=(data.canManage?'Current House office verified. ':'Current House office required. ')+(d.grantMinMinor/100).toFixed(2)+'–'+(d.grantMaxMinor/100).toFixed(2)+' DM development allocation; up to '+d.xp+' Reputation points, proportional to the funded amount. Reputation '+data.levelNow+'/'+d.level+' required. '+(data.cooldownUntil>Date.now()?'Available after '+new Date(data.cooldownUntil).toLocaleString():d.cooldownMs/3600000+'-hour office cooldown.');
|
||||
}catch(e){status.textContent=e.message;}finally{busy=false;controls();}}
|
||||
prepare.onclick=()=>{
|
||||
const payload=d.kind==='proclamation'?{title:title.value,body:body.value}:d.kind==='event'?{title:title.value,description:body.value,startsAt:Date.parse(startsAt.value+'Z'),endsAt:Date.parse(endsAt.value+'Z')}:d.kind==='clan-grant'?{clanId:clanSelect.value,amountMinor:Math.round(Number(grantAmount.value)*100),reason:grantReason.value}:d.kind==='guild-discount'?{house:houseSelect.value}:d.kind==='tariff'?{percent:Number(percent.value)}:d.kind==='report'?{}:{recipientId:recipient.value,citation:citation.value};
|
||||
const payload=d.kind==='agreement'?{targetOffice:officeSelect.value,title:title.value,terms:body.value}:d.kind==='proclamation'?{title:title.value,body:body.value}:d.kind==='event'?{title:title.value,description:body.value,startsAt:Date.parse(startsAt.value+'Z'),endsAt:Date.parse(endsAt.value+'Z')}:d.kind==='clan-grant'?{clanId:clanSelect.value,amountMinor:Math.round(Number(grantAmount.value)*100),reason:grantReason.value}:d.kind==='guild-discount'?{house:houseSelect.value}:d.kind==='tariff'?{percent:Number(percent.value)}:d.kind==='report'?{}:{recipientId:recipient.value,citation:citation.value};
|
||||
if(d.kind==='agreement'&&(!officeSelect.value||title.value.trim().length<3||body.value.trim().length<20)){status.textContent='Choose a receiving office and complete the proposal title and terms.';return;}
|
||||
if(d.kind==='clan-grant'&&(!clanSelect.value||!grantAmount.reportValidity()||!Number.isSafeInteger(payload.amountMinor)||payload.amountMinor<d.grantMinMinor||payload.amountMinor>d.grantMaxMinor||grantReason.value.trim().length<10)){status.textContent='Choose a receiving clan, published grant amount and development purpose.';return;}
|
||||
if(!account.value||['proclamation','event'].includes(d.kind)&&(title.value.trim().length<3||body.value.trim().length<10)||d.kind==='event'&&(!Number.isSafeInteger(payload.startsAt)||!Number.isSafeInteger(payload.endsAt)||payload.startsAt<Date.now()+60000||payload.endsAt<=payload.startsAt)||d.kind==='honour'&&(!recipient.value||citation.value.trim().length<3)){status.textContent='Choose funding and complete the decision details and dates.';return;}
|
||||
const paymentMinor=d.kind==='clan-grant'?payload.amountMinor:d.feeMinor,rewardXP=d.kind==='clan-grant'?Math.max(1,Math.floor(d.xp*payload.amountMinor/d.grantMaxMinor)):d.xp;
|
||||
if(!current?.accounts.some(a=>String(a.id)===account.value&&BigInt(a.availableMinor)>=BigInt(paymentMinor))){status.textContent='The selected office account has insufficient available funds for this amount.';return;}
|
||||
pending={decisionId:id,requestId:crypto.randomUUID(),sourceAccount:account.value,...payload,confirmed:true};review.textContent='Confirm '+d.title+(recipient?' for '+recipient.selectedOptions[0].textContent:title?' “'+title.value.trim()+'”':clanSelect?' for '+clanSelect.selectedOptions[0].textContent:houseSelect?' for '+houseSelect.selectedOptions[0].textContent:percent?' '+percent.value+'%':'')+' · '+(paymentMinor/100).toFixed(2)+' DM from '+account.selectedOptions[0].textContent+'. '+rewardXP+' Reputation points; cooldown '+d.cooldownMs/3600000+' hours.';confirm.hidden=false;controls();
|
||||
pending={decisionId:id,requestId:crypto.randomUUID(),sourceAccount:account.value,...payload,confirmed:true};review.textContent='Confirm '+d.title+(officeSelect?' to '+officeSelect.selectedOptions[0].textContent:recipient?' for '+recipient.selectedOptions[0].textContent:title?' “'+title.value.trim()+'”':clanSelect?' for '+clanSelect.selectedOptions[0].textContent:houseSelect?' for '+houseSelect.selectedOptions[0].textContent:percent?' '+percent.value+'%':'')+' · '+(paymentMinor/100).toFixed(2)+' DM from '+account.selectedOptions[0].textContent+'. '+rewardXP+' Reputation points; cooldown '+d.cooldownMs/3600000+' hours.';confirm.hidden=false;controls();
|
||||
};
|
||||
confirm.onclick=async()=>{if(busy||!pending)return;busy=true;controls();try{const receipt=await api.request(endpoint,pending);pending=null;confirm.hidden=true;review.textContent=(receipt.grant?'Allocated '+(Number(receipt.grant.amountMinor)/100).toFixed(2)+' DM to '+receipt.grant.clanName+'. ':'Completed. ')+'J.A.R.V.I.S. reference: '+receipt.keyId;if(title){title.value='';body.value='';}if(citation)citation.value='';await load();}catch(e){status.textContent=e.message+(e.uncertain?' Retry this same confirmation to check or complete it without a second charge.':'');if(!e.uncertain){pending=null;confirm.hidden=true;}}finally{busy=false;controls();}};
|
||||
refresh.onclick=load;if(find)find.onclick=load;load();
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import {mountPoliticalAgreements} from './cp-v2-political-agreements.mjs';
|
||||
import {faithBlessing} from '../faith-blessing-policy.mjs';
|
||||
import {mountFaithInvitation} from './cp-v2-clan-faith.mjs';
|
||||
import {mountHouseFaith} from './cp-v2-house-faith.mjs';
|
||||
|
|
@ -34,7 +35,7 @@ export function mountProgressionDesign(host,{context='personal',dashboard=false,
|
|||
let connectorObserver=null,disposePersonal=null;const dossier=createProgressionDialog(root);
|
||||
const hero=el('header',undefined,'progression-hero'),head=el('div');head.append(el('small',manage?'IMPERIAL BUREAU · J.A.R.V.I.S.':'REALM PROGRESSION'),el('h2',manage?'Progression definitions':dashboard?'Quest Dashboard':'Missions & Decisions'),el('p','Your objectives, authority and recorded achievements.'));hero.append(image('exchange-quests-v1.png'),head);if(manage||(context!=='personal'&&context!=='clan')||!applyShellHeading(host,{title:context==='clan'?'Clan Missions & Decisions':dashboard?'Quest Dashboard':'Missions & Decisions',description:'Your objectives, authority and recorded achievements.',artwork:'exchange-quests-v1.png'}))root.append(hero);root.append(notice);
|
||||
const xpNav=el('nav',undefined,'progression-tabs progression-xp-types');xpNav.setAttribute('aria-label','XP type');const contextNav=el('nav',undefined,'progression-contexts'),gallery=el('section',undefined,'progression-gallery'),nav=el('nav',undefined,'progression-tabs'),content=el('section',undefined,'progression-content');nav.setAttribute('aria-label','Progression views');contextNav.setAttribute('aria-label','Progression contexts');
|
||||
root.append(gallery,xpNav,nav,content);host.replaceChildren(root);const report=!manage&&(context==='personal'||dashboard)?createProgressionSidebar(host,{onBranch:id=>{branch=id;if(tab==='missions')disposePersonal?.selectBranch?.(id);else{tab='missions';selected=null;render();}},onNavigate:(kind,view)=>{xpKind=kind;tab=view;selected=null;render();}}):{available:false,setJournal(){},setBranches(){},showBranches(){},setNavigation(){},dispose(){}};
|
||||
root.append(gallery,xpNav,nav,content);host.replaceChildren(root);if(context==='politics')mountPoliticalAgreements(root);const report=!manage&&(context==='personal'||dashboard)?createProgressionSidebar(host,{onBranch:id=>{branch=id;if(tab==='missions')disposePersonal?.selectBranch?.(id);else{tab='missions';selected=null;render();}},onNavigate:(kind,view)=>{xpKind=kind;tab=view;selected=null;render();}}):{available:false,setJournal(){},setBranches(){},showBranches(){},setNavigation(){},dispose(){}};
|
||||
function renderGallery(){gallery.replaceChildren();gallery.hidden=activeContext==='personal'||activeContext==='clan'||manage;gallery.className='progression-gallery'+(activeContext==='politics'&&officeCode==='IMP'?' progression-imperial':'');if(gallery.hidden)return;
|
||||
const title=activeContext==='politics'?OFFICES.find(([id])=>id===officeCode)?.[1]:organisation?.name||CONTEXTS[activeContext][0];gallery.append(el('h3',title||'Your organisation'));
|
||||
if(activeContext==='politics'&&officeCode==='IMP'){const throne=el('div',undefined,'progression-throne');throne.append(image('seals/emperor-v1.png'),el('strong','Padishah Emperor'),el('span','Officeholder avatar · preview'));gallery.append(throne);const seals=el('div',undefined,'progression-electors');for(const[name,file]of SEALS){const card=el('figure');card.append(image('seals/'+file),el('figcaption',name),el('span','Leader avatar · preview'));seals.append(card);}gallery.append(seals);return;}
|
||||
|
|
|
|||
|
|
@ -282,3 +282,4 @@
|
|||
|
||||
.cp-v2-news-form .article-picture{margin:18px 0}.cp-v2-news-form .article-picture img,.cp-v2-news-form video{display:block;max-width:100%;height:auto;border-radius:10px}.cp-v2-news-form .article-seal img{width:150px}.cp-v2-news-form figcaption{color:#c7cbae;font-size:.9rem}.cp-v2-news-form details>label{display:grid;gap:8px;margin:12px 0}
|
||||
.cp-political-decision-form{display:grid;gap:1rem;max-width:48rem}.cp-political-decision-form>label{display:grid;gap:.4rem;min-width:0}.cp-political-decision-form input,.cp-political-decision-form select,.cp-political-decision-form textarea{box-sizing:border-box;width:100%;min-width:0;max-width:100%}
|
||||
.cp-political-agreement-inbox{margin-block:1.5rem;padding:1rem;border:1px solid var(--border,#a58a45);border-radius:12px}.cp-political-agreement-inbox article{padding:1rem;margin-block:1rem;background:var(--panel,#102e23);border:1px solid var(--border,#a58a45);border-radius:8px;overflow-wrap:anywhere}.cp-political-agreement-inbox article p{white-space:pre-wrap}.cp-political-agreement-inbox button{margin:.35rem .35rem .35rem 0}
|
||||
|
|
|
|||
|
|
@ -14,11 +14,13 @@ export const MASTER_KEY_TEMPLATES=[
|
|||
action('company.subsidiary','Subsidiary founding','company-subsidiary',[field('parentCompanyId','Mother company'),field('recipient','Recipient')]),
|
||||
action('company.royal','Royal company charter','staff-company-royal',[field('companyId','Company'),reference])]},
|
||||
{id:'politics',label:'POL & orders',actions:[
|
||||
action('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.'}),
|
||||
action('politics.clan-development-grant','House clan development allocation','entity-state',[field('decisionId','Registered development grant','select',{options:['ATR-01','ATR-04','HAR-02','COR-02','COR-04']}),field('sourceAccount','Authorised House funding account'),field('clanId','Receiving clan UUID'),field('amountMinor','Development allocation in DM minor units','number',{min:10000}),field('reason','Development purpose','textarea'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / createPoliticalClanGrants / organisationRewardRoute',executionStatus:'current-house-office-and-current-clan-deed-consumer',effect:'Five fixed House policies re-read the native clan homeworld, current legal deed, active receiving bank account and authorised House source. Atreides Patronage is exactly10,000 DM; other published grants range from100 DM to their15,000/25,000 DM cap. Basic clans route to their current legal owner, keyed clans to their own account; mother control never substitutes for that owner. Actual funded amount scales Reputation up to the catalogue cap. Existing balanced bank transfer, immutable purpose, ordinary key and Reputation commit together; safe retries retain the original payment recipient. No P&O issuance, account activation, construction completion, inventory progress or ownership change is fabricated.'}),
|
||||
action('politics.guild-mediation','Convene Guild mediation','entity-state',[field('decisionId','Mediation decision','select',{options:['SG-06']}),field('sourceAccount','Authorised Guild funding account'),field('title','Session title'),field('description','Dispute and invitation','textarea'),field('startsAt','Start UTC timestamp','number'),field('endsAt','End UTC timestamp','number'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / createRealmEventRecord',executionStatus:'current-guild-officeholder-calendar-consumer',effect:'Current Royal Guild holder, Reputation35,5,000 DM office fee and600 Reputation points. A72h successor-safe cooldown; schedule voluntary mediation for at most72h, entirely within the source mandate and at most30 days ahead. Reuse the political EVT calendar and its existing management rights. Fee, calendar history, Reputation and ordinary key commit atomically. No automatic peace, treaty, war, coalition or participant consent is fabricated; participants use the existing mutual agreement flows.'}),
|
||||
action('politics.guild-preferred-fare','Guild preferred House fares','entity-state',[field('decisionId','Guild decision','select',{options:['SG-02','SG-07']}),field('sourceAccount','Authorised Guild funding account'),field('house','Native House','select',{options:['atreides','harkonnen','corrino','ordos','fremen']}),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / currentGuildDiscount / createGuildService',executionStatus:'current-guild-officeholder-preferred-fare-consumer',effect:'Priority Passage: Reputation 15, fixed 2,500 DM Guild fee, 250 Reputation, 25% preferred fare for72h and48h cooldown. Guild Favour: Reputation10, 5,000 DM fee, 200 Reputation,10% for7d and7d cooldown. Latest signed grant per decision replaces the earlier House; current source mandate and expiry required. Only the strongest eligible discount applies after any surcharge. No new routes, boarding priority, embargo override, Imperial Arrakis permission or smuggler rate. Confirmed ticket fares remain immutable and no grant activates by default.'}),
|
||||
action('politics.guild-surcharge','Guild transport surcharge','entity-state',[field('decisionId','Guild decision','select',{options:['SG-05']}),field('sourceAccount','Authorised Guild funding account'),field('percent','Surcharge percentage','number',{min:0,max:5}),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / currentGuildSurcharge / createGuildService',executionStatus:'current-guild-officeholder-fare-consumer',effect:'Royal Guild office holder, Reputation 40, fixed 5,000 DM office fee and 750 Reputation points. Seven-day successor-safe cooldown and at most seven-day 0–5% tariff, ending with its source mandate; 0 repeals. The latest signed unrevoked record controls new quote/boarding fares. Stale quotes cannot reserve funds. Existing confirmed fares and identical ticket retries retain their original amount; no route, embargo, Arrakis or smuggler right changes. No client plugin rollout or default activation.'}),
|
||||
action('faith.diplomatic-endorsement','Church diplomatic endorsement','entity-state',[field('decisionId','Faith decision','select',{options:['NF-07']}),field('sourceAccount','Authorised Church funding account'),field('recipientId','Other active player UUID'),field('citation','Diplomatic citation','textarea'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / politicalHonours',executionStatus:'current-church-officeholder-only',effect:'Current Royal Church office holder, Reputation 15, fixed 2,500 DM Church-account fee and 250 Reputation points. Seven-day ceremonial diplomatic endorsement on the recipient profile; one decision per 72 hours across succession. No self-award, faith conversion, clan membership, appointment, vote, rank, permissions or bonus. Payment, recognition and ordinary instrument commit once; expiry and key revocation remove the display.'}),
|
||||
action('faith.diplomatic-endorsement','Seven-day political favour','entity-state',[field('decisionId','Faith decision','select',{options:['NF-07','HAR-07']}),field('sourceAccount','Authorised Church funding account'),field('recipientId','Other active player UUID'),field('citation','Diplomatic citation','textarea'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / politicalHonours',executionStatus:'current-church-officeholder-only',effect:'Church: current Royal Church holder, Reputation15,2,500 DM and250 Reputation points. Baron: current Royal Harkonnen holder, Reputation50,5,000 DM and1200 Reputation points; the recipient must be another current House player and the office cooldown is7d. Seven-day ceremonial diplomatic endorsement on the recipient profile; Church cooldown72h; both cooldowns survive succession. No self-award, faith conversion, clan membership, appointment, vote, rank, permissions or bonus. Payment, recognition and ordinary instrument commit once; expiry and key revocation remove the display.'}),
|
||||
action('politics.court-audience','Official court calendar audience','entity-state',[field('decisionId','Court decision','select',{options:['COR-01']}),field('sourceAccount','Authorised office funding account'),field('requestId','Request UUID'),field('title','Audience title'),field('description','Purpose and invitation','textarea'),field('startsAt','Start UTC timestamp','number'),field('endsAt','End UTC timestamp','number')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / createRealmEventRecord',executionStatus:'current-corrino-office-calendar-consumer',effect:'Current Royal Corrino office holder, Reputation 10, fixed 1,000 DM office fee and 200 Reputation points. One decision per 24 hours across succession. Schedule at least one minute and at most 30 days ahead, for at most 24 hours and entirely within the source mandate. Existing political EVT calendar row, history, fee, Reputation and key commit on the same transaction. Exact retries never create or charge twice. No election, war, office, membership or travel changes.'}),
|
||||
action('politics.market-report','Funded political market intelligence','entity-state',[field('decisionId','Registered aggregate report','select',{options:['ORD-03','SG-04']}),field('sourceAccount','Authorised office funding account'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / createPoliticalMarketReports',executionStatus:'current-elected-office-aggregate-report-consumer',effect:'Ordos level 25, 400 Reputation; Guild level 30, 500 Reputation. Fixed 2,500 DM office-account fee and 72-hour successor-safe cooldown. Snapshot only valid, currently available native Exchange item listings; respect embargo and immutable creation-world metadata. Guild additionally receives confirmed seven-day arrival counts. Never disclose passenger identities, private orders or balances. Native tables must share the verified transaction server; unavailable or oversized sources roll back without fees or XP. Snapshot, payment, Reputation and ordinary key commit once; retries return the original report.'}),
|
||||
action('faith.house-referendum','House missionary-law referendum','entity-state',[field('decisionId','House decision','select',{options:['ATR-FAITH','HAR-FAITH','COR-FAITH','ORD-FAITH','FRE-FAITH']}),field('faith','Faith','select',{options:['veiled_concord','muad_dib']}),field('prohibited','Prohibit new conversions','boolean'),field('requestId','Referendum UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createHouseFaithLaws.propose / reconcile / missionaryFaithOutlawed',executionStatus:'current-house-authority-personal-ballot-consumer',effect:'Current Royal elected House holder and Reputation 5. Frozen verified House electorate; 48-hour vote, majority quorum and strict majority. Seven-day office cooldown survives succession. An adopted law lasts at most seven days and ends with its source mandate; the latest signed law gates only new faith offers and acceptance on the registered clan homeworld. Existing allegiance and earned rewards remain unchanged. No fee, XP, election-clock change or personal vote transfer. Private scheduled settlement is idempotent; key revocation never restores an older law.'}),
|
||||
|
|
|
|||
|
|
@ -1,5 +1,12 @@
|
|||
// Fixed catalogue prices are DM minor units. Browser fields cannot override policy.
|
||||
export const POLITICAL_DECISIONS=Object.freeze([
|
||||
...[
|
||||
['ATR-05','atreides','Diplomatic Envoy',30,500,250000,48,7],
|
||||
['COR-06','corrino','Dynastic Alliance',35,600,500000,168,14],
|
||||
['ORD-05','ordos','Shadow Negotiation',40,750,250000,72,7],
|
||||
['BG-05','veiled_concord','Whispered Alliance',35,600,500000,168,7],
|
||||
['NF-05','muad_dib','Whispered Alliance',35,600,500000,168,7]
|
||||
].map(([id,office,title,level,xp,feeMinor,hours,days])=>({id,office,title,level,xp,feeMinor,cooldownMs:hours*3600000,kind:'agreement',responseMs:72*3600000,durationMs:days*86400000})),
|
||||
{id:'ATR-01',office:'atreides',title:'Atreides Patronage',kind:'clan-grant',grantWorld:'caladan',level:10,xp:200,feeMinor:0,grantMinMinor:1000000,grantMaxMinor:1000000,cooldownMs:72*3600000},
|
||||
{id:'ATR-04',office:'atreides',title:'Waterworld Development',kind:'clan-grant',grantWorld:'caladan',level:25,xp:400,feeMinor:0,grantMinMinor:10000,grantMaxMinor:2500000,cooldownMs:7*86400000},
|
||||
{id:'HAR-02',office:'harkonnen',title:'Baronial Patronage',kind:'clan-grant',grantWorld:'giedi_prime',level:15,xp:250,feeMinor:0,grantMinMinor:10000,grantMaxMinor:1500000,cooldownMs:72*3600000},
|
||||
|
|
@ -13,6 +20,7 @@ export const POLITICAL_DECISIONS=Object.freeze([
|
|||
{id:'ORD-03',office:'ordos',title:'Market Intelligence',kind:'report',level:25,xp:400,feeMinor:250000,cooldownMs:72*3600000},
|
||||
{id:'SG-04',office:'spacing_guild',title:'Commercial Intelligence',kind:'report',level:30,xp:500,feeMinor:250000,cooldownMs:72*3600000},
|
||||
{id:'NF-07',office:'muad_dib',title:'Church’s Favour',kind:'honour',level:15,xp:250,feeMinor:250000,cooldownMs:72*3600000,durationMs:7*86400000},
|
||||
{id:'HAR-07',office:'harkonnen',house:'harkonnen',title:'Baron’s Favour',kind:'honour',level:50,xp:1200,feeMinor:500000,cooldownMs:7*86400000,durationMs:7*86400000},
|
||||
{id:'SG-05',office:'spacing_guild',title:'Transport Surcharge',kind:'tariff',level:40,xp:750,feeMinor:500000,cooldownMs:7*86400000,durationMs:7*86400000},
|
||||
{id:'SG-02',office:'spacing_guild',title:'Priority Passage',kind:'guild-discount',level:15,xp:250,feeMinor:250000,cooldownMs:48*3600000,durationMs:72*3600000,discountPercent:25},
|
||||
{id:'SG-07',office:'spacing_guild',title:'Guild’s Favour',kind:'guild-discount',level:10,xp:200,feeMinor:500000,cooldownMs:7*86400000,durationMs:7*86400000,discountPercent:10},
|
||||
|
|
@ -29,4 +37,4 @@ export const POLITICAL_DECISIONS=Object.freeze([
|
|||
].map(d=>Object.freeze({...d,durationMs:d.durationMs??(d.kind==='honour'?30*86400000:null)})));
|
||||
export const politicalDecision=id=>POLITICAL_DECISIONS.find(d=>d.id===id)||null;
|
||||
export function proclamationDecisionId(kind,faction){return kind==='imperial'?'IMP-04':kind==='guild'?'SG-PROCLAIM':kind==='house'?({atreides:'ATR-PROCLAIM',harkonnen:'HAR-PROCLAIM',corrino:'COR-PROCLAIM',ordos:'ORD-PROCLAIM',veiled_concord:'BG-04',muad_dib:'NF-04'})[faction]||null:null;}
|
||||
export const POLITICAL_DECISION_CATALOGUE=Object.freeze(POLITICAL_DECISIONS.map(d=>Object.freeze({...d,office:({emperor:'IMP',atreides:'ATR',harkonnen:'HAR',corrino:'COR',ordos:'ORD',veiled_concord:'BG',muad_dib:'NF',spacing_guild:'SG'})[d.office],cost:(d.kind==='clan-grant'?(d.grantMinMinor===d.grantMaxMinor?(d.grantMaxMinor/100).toLocaleString('en-GB'):'Grant amount'):(d.feeMinor/100).toLocaleString('en-GB'))+' / '+d.cooldownMs/3600000+'h',effect:d.kind==='clan-grant'?'Allocate '+(d.grantMaxMinor/100).toLocaleString('en-GB')+' DM'+(d.grantMinMinor===d.grantMaxMinor?'':' maximum')+' from this House to a current clan on its native world. Basic clans receive through the current legal owner; other clans use their own account. Reputation scales with the amount; allocation and its purpose are recorded together.':d.kind==='guild-discount'?'Give one native House '+d.discountPercent+'% off new Guild bookings for '+d.durationMs/3600000+' hours. Preferred fares never stack, open routes, change boarding windows or override embargoes and Imperial Arrakis access.':d.kind==='tariff'?'Set a 0–5% surcharge on new Guild bookings for seven days; choose 0 to repeal. Existing confirmed fares remain unchanged.':d.kind==='event'?(d.effect||'Schedule an official audience in the existing House calendar. Fixed office funding, Reputation and cooldown; no election, membership or travel change.'):d.kind==='report'?'Read a sealed aggregate of available Exchange stock. Guild reports also include seven-day confirmed arrival totals. No passenger identities, private orders or account balances. Fixed office funding and cooldown.':d.kind==='proclamation'?'Publish an official message in this office’s existing proclamation archive. Fixed office funding and cooldown; no membership or voting rights change.':'Ceremonial profile recognition for '+d.durationMs/86400000+' days. No office, rank, vote or permission is granted.'})));
|
||||
export const POLITICAL_DECISION_CATALOGUE=Object.freeze(POLITICAL_DECISIONS.map(d=>Object.freeze({...d,office:({emperor:'IMP',atreides:'ATR',harkonnen:'HAR',corrino:'COR',ordos:'ORD',veiled_concord:'BG',muad_dib:'NF',spacing_guild:'SG'})[d.office],cost:(d.kind==='clan-grant'?(d.grantMinMinor===d.grantMaxMinor?(d.grantMaxMinor/100).toLocaleString('en-GB'):'Grant amount'):(d.feeMinor/100).toLocaleString('en-GB'))+' / '+d.cooldownMs/3600000+'h',effect:d.kind==='agreement'?'Send a confidential diplomatic proposal to another current Royal office holder, who must consent within 72 hours. Accepted terms last '+d.durationMs/86400000+' days at most and end with either mandate. This records diplomatic terms without moving votes, ownership, military allegiance or bank rights.':d.kind==='clan-grant'?'Allocate '+(d.grantMaxMinor/100).toLocaleString('en-GB')+' DM'+(d.grantMinMinor===d.grantMaxMinor?'':' maximum')+' from this House to a current clan on its native world. Basic clans receive through the current legal owner; other clans use their own account. Reputation scales with the amount; allocation and its purpose are recorded together.':d.kind==='guild-discount'?'Give one native House '+d.discountPercent+'% off new Guild bookings for '+d.durationMs/3600000+' hours. Preferred fares never stack, open routes, change boarding windows or override embargoes and Imperial Arrakis access.':d.kind==='tariff'?'Set a 0–5% surcharge on new Guild bookings for seven days; choose 0 to repeal. Existing confirmed fares remain unchanged.':d.kind==='event'?(d.effect||'Schedule an official audience in the existing House calendar. Fixed office funding, Reputation and cooldown; no election, membership or travel change.'):d.kind==='report'?'Read a sealed aggregate of available Exchange stock. Guild reports also include seven-day confirmed arrival totals. No passenger identities, private orders or account balances. Fixed office funding and cooldown.':d.kind==='proclamation'?'Publish an official message in this office’s existing proclamation archive. Fixed office funding and cooldown; no membership or voting rights change.':'Ceremonial profile recognition for '+d.durationMs/86400000+' days. No office, rank, vote or permission is granted.'})));
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import {ensureFaithQuestPolicy} from '../node/progression-pol.mjs';
|
|||
import {initializeClanFaith,createClanFaithAPI,createClanFaith} from '../node/clan-faith.mjs';
|
||||
import {initializeHouseFaith,createHouseFaithAPI,createHouseFaithLaws,missionaryFaithOutlawed} from '../node/house-faith-laws.mjs';
|
||||
import {createPoliticalMarketReports} from '../node/political-market-reports.mjs';
|
||||
import {POLITICAL_AGREEMENT_SCHEMA,createPoliticalAgreements,createPoliticalAgreementAPI} from '../node/political-agreements.mjs';
|
||||
import {createPoliticalClanGrants} from '../node/political-clan-grants.mjs';
|
||||
import {initializeWorldTrade,createWorldTradeAPI} from '../node/world-trade-governance.mjs';
|
||||
import {publicWelcomeContext} from '../node/welcome-context.mjs';
|
||||
|
|
@ -283,7 +284,9 @@ export function createPanel(db,settings={},dependencies={}){
|
|||
const gameNativeState=createGameNativeStateAPI(db,settings,{read:currentNativeState});
|
||||
const gameOrganisations=createGameOrganisationsAPI(db,dependencies.organisationKeys,settings,{bank:dependencies.bankDatabase||null,readState:currentNativeState,extraWars:campaignWars});
|
||||
const gameGuild=createGameGuildAPI(db,dependencies.bankDatabase||null,dependencies.organisationKeys,settings);
|
||||
const politicalDecisions=createPoliticalDecisions(db,dependencies.bankDatabase||null,dependencies.organisationKeys,{marketReports:createPoliticalMarketReports(db,dependencies.bankDatabase||null,settings),clanGrants:createPoliticalClanGrants(db)});
|
||||
const politicalAgreements=createPoliticalAgreements(db,dependencies.organisationKeys);
|
||||
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});
|
||||
const politicalDecisionAPI=createPoliticalDecisionAPI(db,politicalDecisions,{origin});
|
||||
const clanFaith=createClanFaithAPI(db,dependencies.organisationKeys,{origin,service:createClanFaith(db,dependencies.organisationKeys,{isOutlawed:missionaryFaithOutlawed})});
|
||||
const houseFaith=createHouseFaithAPI(db,dependencies.organisationKeys,{origin});
|
||||
|
|
@ -393,6 +396,7 @@ export function createPanel(db,settings={},dependencies={}){
|
|||
if(/^\/api\/public\/(companies|political-houses)(?:\/|$)/.test(path))return publicOrganisations(request);
|
||||
if(path==='/api/rihla')return rihla(request);
|
||||
if(path==='/api/network/layout')return networkLayouts(request);
|
||||
if(path==='/api/politics/agreements')return politicalAgreementAPI(request);
|
||||
if(path==='/api/politics/decisions')return politicalDecisionAPI(request);
|
||||
if(path==='/api/politics/faith')return clanFaith(request);
|
||||
if(path==='/api/politics/house-faith')return houseFaith(request);
|
||||
|
|
@ -576,7 +580,7 @@ export async function startPanel(settings=process.env){
|
|||
inventoryPool.on('error',()=>console.error('Inventory database connection unavailable.'));
|
||||
}
|
||||
const bankDatabase=await openPostbankDatabase(settings);
|
||||
const db=await openDatabase(settings);await initializeItemDesigns(db);await initializeKitsets(db);await initializeResearchSpecialists(db);await db.query(POLITICAL_DECISION_SCHEMA);await initializeWorldTrade(db);await initializeClanFaith(db);await initializeHouseFaith(db);db.worldTradeEnabled=settings.WORLD_TRADE_ENABLED==='true';db.politicalDecisionsEnabled=true;await db.query(FAITH_BLESSING_SCHEMA);db.faithBlessingsEnabled=true;await db.query(IMPERIAL_PASSAGE_SCHEMA);await db.query(HOUSE_SELECTION_SCHEMA);await db.query(GAME_ORGANISATION_SCHEMA);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await initializeJarvisGenerator(db);await initializeEntityState(db);await initializeSystemCharacters(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys); /* Passive POL conversion waits for scoped adapters instead of company management. */await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;await initializeProgression(db);await initializeStarterKitEvents(db);db.starterKitEventsEnabled=true;await initializeServerProjects(db);if(bankDatabase)await bankDatabase.query(PROJECT_BANK_SCHEMA);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);await ensureStarterKitRewardPolicy(db,organisationKeys).catch(()=>console.error('Starter kit reward policy requires review; existing custom configuration was preserved'));await initializePOLProgression(db);await initializeSecondaryAffiliations(db);await initializePersonalActivityEvents(db);db.personalActivityEventsEnabled=true;await initializePOLActivityEvents(db);db.polActivityEventsEnabled=true;await initializeRebellionRewards(db);await ensurePOLProgressionPolicy(db,organisationKeys);await ensurePOLRepeatablePolicy(db,organisationKeys);await ensureElytraQuestPolicy(db,organisationKeys);await ensureWarQuestPolicy(db,organisationKeys);await ensureFaithQuestPolicy(db,organisationKeys);await ensurePOLMentorPolicy(db,organisationKeys);db.polMentorBonusEnabled=true;db.polRepeatablesEnabled=true;db.organisationResearchEnabled=true;db.researchSuppliesEnabled=true;const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const deedPurchases=bankDatabase&&settings.POSTBANK_ENABLED==='true'?createDeedPurchases(db,bankDatabase,organisationKeys,{authority:createPostbankAuthority(db,{bank:bankDatabase})}):null;const starterKitDelivery=await openStarterKitDelivery(db,settings);const boardRuntime=await openBoardKeyRuntime(db,organisationKeys,settings);const handle=createPanel(db,settings,{boardRuntime,inventoryPool,bankDatabase,organisationKeys,deedPurchases,officeAuctionRuntime,promotionDelivery,progressionRuntime}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com';
|
||||
const db=await openDatabase(settings);await initializeItemDesigns(db);await initializeKitsets(db);await initializeResearchSpecialists(db);await db.query(POLITICAL_DECISION_SCHEMA);await initializeWorldTrade(db);await initializeClanFaith(db);await initializeHouseFaith(db);await db.query(POLITICAL_AGREEMENT_SCHEMA);db.worldTradeEnabled=settings.WORLD_TRADE_ENABLED==='true';db.politicalDecisionsEnabled=true;await db.query(FAITH_BLESSING_SCHEMA);db.faithBlessingsEnabled=true;await db.query(IMPERIAL_PASSAGE_SCHEMA);await db.query(HOUSE_SELECTION_SCHEMA);await db.query(GAME_ORGANISATION_SCHEMA);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await initializeJarvisGenerator(db);await initializeEntityState(db);await initializeSystemCharacters(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys); /* Passive POL conversion waits for scoped adapters instead of company management. */await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;await initializeProgression(db);await initializeStarterKitEvents(db);db.starterKitEventsEnabled=true;await initializeServerProjects(db);if(bankDatabase)await bankDatabase.query(PROJECT_BANK_SCHEMA);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);await ensureStarterKitRewardPolicy(db,organisationKeys).catch(()=>console.error('Starter kit reward policy requires review; existing custom configuration was preserved'));await initializePOLProgression(db);await initializeSecondaryAffiliations(db);await initializePersonalActivityEvents(db);db.personalActivityEventsEnabled=true;await initializePOLActivityEvents(db);db.polActivityEventsEnabled=true;await initializeRebellionRewards(db);await ensurePOLProgressionPolicy(db,organisationKeys);await ensurePOLRepeatablePolicy(db,organisationKeys);await ensureElytraQuestPolicy(db,organisationKeys);await ensureWarQuestPolicy(db,organisationKeys);await ensureFaithQuestPolicy(db,organisationKeys);await ensurePOLMentorPolicy(db,organisationKeys);db.polMentorBonusEnabled=true;db.polRepeatablesEnabled=true;db.organisationResearchEnabled=true;db.researchSuppliesEnabled=true;const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const deedPurchases=bankDatabase&&settings.POSTBANK_ENABLED==='true'?createDeedPurchases(db,bankDatabase,organisationKeys,{authority:createPostbankAuthority(db,{bank:bankDatabase})}):null;const starterKitDelivery=await openStarterKitDelivery(db,settings);const boardRuntime=await openBoardKeyRuntime(db,organisationKeys,settings);const handle=createPanel(db,settings,{boardRuntime,inventoryPool,bankDatabase,organisationKeys,deedPurchases,officeAuctionRuntime,promotionDelivery,progressionRuntime}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com';
|
||||
await initializeInternalMailAccess(db);const stopElectionClock=startElectionClock(db);const stopOfficeLedger=startOfficeLedger(db);
|
||||
const stopBanSync=startModerationSync(db,settings),stopInternalMail=startInternalMailSync(db,{jarvisStore:bankDatabase}),stopCentralScheduler=startCentralScheduler(db,bankDatabase,settings,{extraTasks:[...(settings.MILITARY_PROJECTION_ENABLED==='true'&&organisationKeys?[{key:'military_affiliations',slot:now=>Math.floor(now/60000)*60000,run:()=>createMilitaryAffiliations(db,organisationKeys).drain()}]:[]),{key:'house_faith_ballots',slot:now=>Math.floor(now/60000)*60000,run:()=>createHouseFaithLaws(db,organisationKeys).reconcile()},{key:'starter_kit_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>starterKitDelivery.drain()},...(boardRuntime?[{key:'board_keys',slot:now=>Math.floor(now/60000)*60000,run:()=>boardRuntime.drain()}]:[]),...(bankDatabase?[{key:'federal_reserve',slot:now=>Math.floor(now/60000)*60000,run:()=>createEconomyRuntime(db,bankDatabase,organisationKeys).federal.run()},{key:'organisation_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createOrganisationFundedRewards(db,bankDatabase,organisationKeys).drain()},{key:'research_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createResearchFundedRewards(db,bankDatabase).drain()},{key:'pol_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createPOLFundedRewards(db,bankDatabase,organisationKeys).drain()},{key:'rebellion_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createRebellionRewards(db,bankDatabase,{sourceAccount:settings.REBELLION_REWARD_SOURCE_ACCOUNT,sourceOwnerId:settings.REBELLION_REWARD_SOURCE_OWNER_ID,useWebsiteTreasury:settings.REBELLION_REWARD_FUND==='website-treasury'}).drain()},...(deedPurchases?[{key:'deed_purchases',slot:now=>Math.floor(now/60000)*60000,run:()=>deedPurchases.drain()}]:[]),{key:'server_projects',slot:now=>Math.floor(now/60000)*60000,run:()=>createServerProjectRuntime(db,bankDatabase,organisationKeys).drain()},{key:'progression_completion',slot:now=>Math.floor(now/60000)*60000,run:async()=>{const completed=await progressionRuntime.quests.processCompletions();const news=await progressionRuntime.announcements.drain();return {completed,news};}},{key:'naib_council',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await reconcileNaibChairs(db);return createNaibCouncil(db).reconcile();}},{key:'jarvis_promotions',slot:now=>Math.floor(now/15000)*15000,run:()=>promotionDelivery.drain()},{key:'political_jobs',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await createPoliticalJobs(db,bankDatabase).reconcile();return drainPoliticalJobNotifications(db,{broker:internalMailBroker,eligible:internalMailEligible});}},{key:'order_membership',slot:now=>Math.floor(now/60000)*60000,run:()=>reconcileCrysknifeCompany(db,organisationKeys)},{key:'office_auctions',slot:now=>Math.floor(now/60000)*60000,run:()=>officeAuctionRuntime.process()},{key:'jarvis_settlement',slot:now=>standardCycle(now).cutoff,async run(cutoff){const payments=createJarvisPayments(bankDatabase,createPostbankAuthority(db,{bank:bankDatabase}));for(let i=0;i<40;i++){const result=await payments.settle(cutoff);if(result.failed)return result;if(result.attempted<100)return result;}return {failed:1};}}]:[])]});
|
||||
const security={'X-Robots-Tag':'noindex, nofollow, noarchive','X-Content-Type-Options':'nosniff','Referrer-Policy':'no-referrer','Cache-Control':'no-store','Content-Security-Policy':PANEL_SERVICE_CSP};
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"schemaVersion": 1,
|
||||
"sourceHash": "2f81c0d23013070ec5cb5850e8f34cae9c53af85bc8ab07fbfdef88e33c37f7e",
|
||||
"sourceHash": "6f4a3e5d3ff1857ae218f3f51db437b84de888575d242b84db567d9ee06ecbfe",
|
||||
"actions": [
|
||||
{
|
||||
"id": "war.coalition-consent",
|
||||
|
|
@ -431,6 +431,109 @@
|
|||
"webIssue": false,
|
||||
"recordOnly": false
|
||||
},
|
||||
{
|
||||
"id": "politics.diplomatic-proposal",
|
||||
"label": "POL & orders · Confidential diplomatic proposal",
|
||||
"version": 1,
|
||||
"keyType": "entity-state",
|
||||
"fields": [
|
||||
{
|
||||
"name": "ticketId",
|
||||
"label": "Ban / support ticket ID",
|
||||
"type": "text",
|
||||
"required": true,
|
||||
"maxLength": 80
|
||||
},
|
||||
{
|
||||
"name": "decisionId",
|
||||
"label": "Diplomatic decision",
|
||||
"type": "select",
|
||||
"required": true,
|
||||
"options": [
|
||||
"ATR-05",
|
||||
"COR-06",
|
||||
"ORD-05",
|
||||
"BG-05",
|
||||
"NF-05"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "sourceAccount",
|
||||
"label": "Authorised office funding account",
|
||||
"type": "text",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "targetOffice",
|
||||
"label": "Receiving Royal office",
|
||||
"type": "text",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "title",
|
||||
"label": "Proposal title",
|
||||
"type": "text",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "terms",
|
||||
"label": "Confidential diplomatic terms",
|
||||
"type": "textarea",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "requestId",
|
||||
"label": "Request UUID",
|
||||
"type": "text",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"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.",
|
||||
"fixedTargets": [],
|
||||
"webIssue": false,
|
||||
"recordOnly": true
|
||||
},
|
||||
{
|
||||
"id": "politics.diplomatic-response",
|
||||
"label": "POL & orders · Accept or refuse a diplomatic proposal",
|
||||
"version": 1,
|
||||
"keyType": "entity-state",
|
||||
"fields": [
|
||||
{
|
||||
"name": "ticketId",
|
||||
"label": "Ban / support ticket ID",
|
||||
"type": "text",
|
||||
"required": true,
|
||||
"maxLength": 80
|
||||
},
|
||||
{
|
||||
"name": "proposalId",
|
||||
"label": "Proposal UUID",
|
||||
"type": "text",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "choice",
|
||||
"label": "Response",
|
||||
"type": "select",
|
||||
"required": true,
|
||||
"options": [
|
||||
"accept",
|
||||
"decline"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "requestId",
|
||||
"label": "Response UUID",
|
||||
"type": "text",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"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.",
|
||||
"fixedTargets": [],
|
||||
"webIssue": false,
|
||||
"recordOnly": true
|
||||
},
|
||||
{
|
||||
"id": "politics.clan-development-grant",
|
||||
"label": "POL & orders · House clan development allocation",
|
||||
|
|
@ -662,7 +765,7 @@
|
|||
},
|
||||
{
|
||||
"id": "faith.diplomatic-endorsement",
|
||||
"label": "POL & orders · Church diplomatic endorsement",
|
||||
"label": "POL & orders · Seven-day political favour",
|
||||
"version": 1,
|
||||
"keyType": "entity-state",
|
||||
"fields": [
|
||||
|
|
@ -679,7 +782,8 @@
|
|||
"type": "select",
|
||||
"required": true,
|
||||
"options": [
|
||||
"NF-07"
|
||||
"NF-07",
|
||||
"HAR-07"
|
||||
]
|
||||
},
|
||||
{
|
||||
|
|
@ -707,7 +811,7 @@
|
|||
"required": true
|
||||
}
|
||||
],
|
||||
"effect": "Current Royal Church office holder, Reputation 15, fixed 2,500 DM Church-account fee and 250 Reputation points. Seven-day ceremonial diplomatic endorsement on the recipient profile; one decision per 72 hours across succession. No self-award, faith conversion, clan membership, appointment, vote, rank, permissions or bonus. Payment, recognition and ordinary instrument commit once; expiry and key revocation remove the display.",
|
||||
"effect": "Church: current Royal Church holder, Reputation15,2,500 DM and250 Reputation points. Baron: current Royal Harkonnen holder, Reputation50,5,000 DM and1200 Reputation points; the recipient must be another current House player and the office cooldown is7d. Seven-day ceremonial diplomatic endorsement on the recipient profile; Church cooldown72h; both cooldowns survive succession. No self-award, faith conversion, clan membership, appointment, vote, rank, permissions or bonus. Payment, recognition and ordinary instrument commit once; expiry and key revocation remove the display.",
|
||||
"fixedTargets": [],
|
||||
"webIssue": false,
|
||||
"recordOnly": true
|
||||
|
|
|
|||
|
|
@ -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|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|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');
|
||||
|
|
|
|||
63
website/node/political-agreements.mjs
Normal file
63
website/node/political-agreements.mjs
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
import {createHash} from 'node:crypto';
|
||||
import {boardReadStore} from './board-deed-source.mjs';
|
||||
import {officeAuthority} from './political-decisions.mjs';
|
||||
import {politicalDecision} from '../control-panel/public/political-decision-policy.mjs';
|
||||
import {PUBLIC_OFFICES} from './public-government.mjs';
|
||||
import {currentOfficeController} from './entity-relations.mjs';
|
||||
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
|
||||
import {validUuid} from './game-link.mjs';
|
||||
import {identity} from './auth.mjs';
|
||||
export const POLITICAL_AGREEMENT_SCHEMA=`CREATE TABLE IF NOT EXISTS jarvis_political_agreement_replies(decision_request CHAR(36) PRIMARY KEY,request_id CHAR(36) NOT NULL UNIQUE,key_id CHAR(36) NOT NULL UNIQUE,actor_id CHAR(36) NOT NULL,term_id CHAR(36) NOT NULL,choice VARCHAR(12) NOT NULL,input_hash CHAR(64) NOT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`;
|
||||
const fail=(message,status=409)=>{throw Object.assign(Error(message),{status});};
|
||||
const hash=v=>createHash('sha256').update(JSON.stringify(v)).digest('hex');
|
||||
export function createPoliticalAgreements(raw,keys,{clock=Date.now}={}){
|
||||
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;}
|
||||
async function resolve(tx,d,actor,office,now){
|
||||
if(office===d.office||!PUBLIC_OFFICES.some(o=>o.key===office))fail('Choose another current political office.',400);
|
||||
const target=await currentOfficeController(tx,office,now),h=target&&await holder(tx,office,{id:target.userId},now,true);
|
||||
if(!h||h.userId===actor.id)fail('A different current Royal office holder must receive this proposal.',403);
|
||||
return h;
|
||||
}
|
||||
async function targets(tx,d,actor,now){const rows=[];for(const o of PUBLIC_OFFICES){if(o.key===d.office)continue;const target=await currentOfficeController(tx,o.key,now);if(target&&target.userId!==actor.id&&await holder(tx,o.key,{id:target.userId},now))rows.push({id:o.key,name:o.scope});}return rows;}
|
||||
async function create(tx,{d,actor,payload,holder:source,now}){
|
||||
const target=await resolve(tx,d,actor,payload.targetOffice,now),sourceTerm=await tx.first('SELECT expires_at FROM political_office_terms WHERE id=?',[source.termId]),responseUntil=now+d.responseMs,mandateUntil=Math.min(Number(sourceTerm?.expires_at||0),target.expiresAt);
|
||||
if(mandateUntil<=responseUntil)fail('Both mandates must extend beyond the full proposal response window.');
|
||||
return{targetOffice:payload.targetOffice,targetActorId:target.userId,targetTermId:target.termId,responseUntil,mandateUntil,durationMs:d.durationMs};
|
||||
}
|
||||
async function verified(tx,row,now){
|
||||
const d=politicalDecision(row?.decision_id);if(!d||d.kind!=='agreement')return null;
|
||||
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:political-decision:'+row.request_id]);if(!key)return null;
|
||||
const receipt=JSON.parse(row.receipt_json),payload=JSON.parse(row.payload_json),a=receipt.agreement;
|
||||
if(!a||a.targetOffice!==payload.targetOffice||a.targetActorId!==row.recipient_id||a.responseUntil!==Number(row.created_at)+d.responseMs||a.durationMs!==d.durationMs||!validUuid(a.targetTermId)||!Number.isSafeInteger(a.mandateUntil))return null;
|
||||
const source=await holder(tx,d.office,{id:row.actor_id},now),target=await holder(tx,a.targetOffice,{id:a.targetActorId},now);
|
||||
return{d,a,payload,mandates:source?.termId===row.term_id&&target?.termId===a.targetTermId};
|
||||
}
|
||||
async function projection(tx,row,actor,now){
|
||||
if(![row.actor_id,row.recipient_id].includes(actor.id))return null;const v=await verified(tx,row,now);if(!v)return null;
|
||||
const reply=await tx.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]);
|
||||
const replyValid=reply?.verified_key&&reply.actor_id===v.a.targetActorId&&reply.term_id===v.a.targetTermId&&['accept','decline'].includes(reply.choice)&&Number(reply.created_at)>=Number(row.created_at)&&Number(reply.created_at)<v.a.responseUntil&&reply.input_hash===hash([reply.actor_id,row.request_id,reply.choice]);
|
||||
const endsAt=replyValid&&reply.choice==='accept'?Math.min(Number(reply.created_at)+v.a.durationMs,v.a.mandateUntil):null;
|
||||
const state=!v.mandates?'mandate-ended':reply&&!replyValid?'response-unavailable':replyValid?(reply.choice==='decline'?'declined':now<endsAt?'accepted':'expired'):now<v.a.responseUntil?'pending':'expired';
|
||||
return{id:row.request_id,title:v.payload.title,terms:v.payload.terms,decisionId:v.d.id,sourceOffice:v.d.office,targetOffice: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 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);
|
||||
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 digest=hash([actor.id,input.proposalId,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.input_hash!==digest||old.actor_id!==actor.id)fail('This proposal already has a response.');return{ok:true,replayed:true,reference:old.key_id};}
|
||||
const v=await verified(tx,row,now);if(!v||!v.mandates||now>=v.a.responseUntil)fail('The proposal or one of its mandates has expired.');
|
||||
const source=await holder(tx,v.d.office,{id:row.actor_id},now,true),target=await holder(tx,v.a.targetOffice,actor,now,true);if(source?.termId!==row.term_id||target?.termId!==v.a.targetTermId)fail('Both original mandates must still be 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{targets,create,read,reply};
|
||||
}
|
||||
export function createPoliticalAgreementAPI(db,service,{origin='https://cp.dunerealms.com',authenticate=r=>identity(r,db)}={}){return async request=>{const respond=(value,status=200)=>Response.json(value,{status,headers:{'Cache-Control':'private, no-store'}});try{
|
||||
if(!['GET','POST'].includes(request.method))return respond({message:'Method not allowed.'},405);const actor=await authenticate(request);if(!actor)return respond({message:'Sign in first.'},401);
|
||||
if(new URL(request.url).search)return respond({message:'Unexpected agreement fields.'},400);if(request.method==='GET')return respond(await service.read(actor));
|
||||
if(request.headers.get('origin')!==origin)return respond({message:'Origin rejected.'},403);const body=await request.text();if(body.length>4096)return respond({message:'Response too large.'},413);let input;try{input=JSON.parse(body);}catch{return respond({message:'Invalid response.'},400);}return respond(await service.reply(actor,input));
|
||||
}catch(error){return respond({message:error.status?error.message:'Political agreements are temporarily unavailable.'},error.status||503);}};}
|
||||
|
|
@ -25,10 +25,11 @@ const fingerprint=x=>createHash('sha256').update(JSON.stringify(x)).digest('hex'
|
|||
const funding=d=>entityId('office',d.office==='emperor'?'emperor':'leader:'+d.office);
|
||||
export function politicalDecisionReader(tx,base){const reader=boardReadStore(tx,base);if(tx!==base)reader.readSnapshot=async work=>work(reader);return reader;}
|
||||
export function decisionInput(input){
|
||||
const d=politicalDecision(input?.decisionId),fields=d?.kind==='proclamation'?'body,confirmed,decisionId,requestId,sourceAccount,title':d?.kind==='event'?'confirmed,decisionId,description,endsAt,requestId,sourceAccount,startsAt,title':d?.kind==='tariff'?'confirmed,decisionId,percent,requestId,sourceAccount':d?.kind==='guild-discount'?'confirmed,decisionId,house,requestId,sourceAccount':d?.kind==='clan-grant'?'amountMinor,clanId,confirmed,decisionId,reason,requestId,sourceAccount':d?.kind==='report'?'confirmed,decisionId,requestId,sourceAccount':'citation,confirmed,decisionId,recipientId,requestId,sourceAccount';
|
||||
const d=politicalDecision(input?.decisionId),fields=d?.kind==='agreement'?'confirmed,decisionId,requestId,sourceAccount,targetOffice,terms,title':d?.kind==='proclamation'?'body,confirmed,decisionId,requestId,sourceAccount,title':d?.kind==='event'?'confirmed,decisionId,description,endsAt,requestId,sourceAccount,startsAt,title':d?.kind==='tariff'?'confirmed,decisionId,percent,requestId,sourceAccount':d?.kind==='guild-discount'?'confirmed,decisionId,house,requestId,sourceAccount':d?.kind==='clan-grant'?'amountMinor,clanId,confirmed,decisionId,reason,requestId,sourceAccount':d?.kind==='report'?'confirmed,decisionId,requestId,sourceAccount':'citation,confirmed,decisionId,recipientId,requestId,sourceAccount';
|
||||
if(!d||!input||Object.keys(input).sort().join(',')!==fields||!validUuid(input.requestId)||input.confirmed!==true||typeof input.sourceAccount!=='string'||!/^\d{1,12}$/.test(input.sourceAccount))fail('Review and confirm a registered decision and its funding account.',400);
|
||||
const clean=(value,min,max)=>{if(typeof value!=='string'||value.trim().length<min||value.trim().length>max||/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value))fail('Invalid announcement or citation.',400);return value.replaceAll('\r\n','\n').trim();};
|
||||
const payload=d.kind==='proclamation'?{title:clean(input.title,3,120),body:clean(input.body,10,6000)}:d.kind==='event'?{title:clean(input.title,3,100),description:clean(input.description,10,2000),startsAt:input.startsAt,endsAt:input.endsAt}:d.kind==='clan-grant'?{clanId:typeof input.clanId==='string'?input.clanId.toLowerCase():input.clanId,amountMinor:input.amountMinor,reason:clean(input.reason,10,2000)}:d.kind==='guild-discount'?{house:input.house,percent:d.discountPercent}:d.kind==='tariff'?{percent:input.percent}:d.kind==='report'?{}:{recipientId:input.recipientId,citation:clean(input.citation,3,2000)};
|
||||
const payload=d.kind==='agreement'?{targetOffice:input.targetOffice,title:clean(input.title,3,100),terms:clean(input.terms,20,4000)}:d.kind==='proclamation'?{title:clean(input.title,3,120),body:clean(input.body,10,6000)}:d.kind==='event'?{title:clean(input.title,3,100),description:clean(input.description,10,2000),startsAt:input.startsAt,endsAt:input.endsAt}:d.kind==='clan-grant'?{clanId:typeof input.clanId==='string'?input.clanId.toLowerCase():input.clanId,amountMinor:input.amountMinor,reason:clean(input.reason,10,2000)}:d.kind==='guild-discount'?{house:input.house,percent:d.discountPercent}:d.kind==='tariff'?{percent:input.percent}:d.kind==='report'?{}:{recipientId:input.recipientId,citation:clean(input.citation,3,2000)};
|
||||
if(d.kind==='agreement'&&(!PUBLIC_OFFICES.some(o=>o.key===payload.targetOffice)||payload.targetOffice===d.office))fail('Choose another registered political office.',400);
|
||||
if(d.kind==='clan-grant'&&(!validUuid(payload.clanId)||!Number.isSafeInteger(payload.amountMinor)||payload.amountMinor<d.grantMinMinor||payload.amountMinor>d.grantMaxMinor))fail('Choose an eligible clan and a grant within the published budget.',400);
|
||||
if(d.kind==='guild-discount'&&!TRADE_WORLDS.some(w=>w.house===payload.house))fail('Choose a native House for the preferred fare.',400);
|
||||
if(d.kind==='tariff'&&(!Number.isInteger(payload.percent)||payload.percent<0||payload.percent>5))fail('Choose a Guild surcharge from 0 to 5 percent.',400);
|
||||
|
|
@ -50,7 +51,7 @@ export function createPoliticalDecisions(db,bank,keys,deps={}){
|
|||
// The production central pool exposes prepared reads rather than first().
|
||||
// Keep every transaction callback on its original connection.
|
||||
db={...boardReadStore(db,db),transaction:db.transaction.bind(db)};
|
||||
const clock=deps.clock||Date.now,banking=atomicBankAccess(db,bank,{verifyStorage:deps.verifyStorage,centralTables:['jarvis_political_decisions','political_proclamations','political_office_terms','political_office_charters','organisation_keys','organisation_key_events','codex_instance_editions','account_audit','jarvis_pol_progression_seasons','jarvis_pol_progression_accounts','jarvis_pol_progression_history','jarvis_pol_progression_outbox','site_clans','site_clan_deeds','site_clan_charters','site_clan_members','site_game_links','site_accounts']});
|
||||
const clock=deps.clock||Date.now,banking=atomicBankAccess(db,bank,{verifyStorage:deps.verifyStorage,centralTables:['jarvis_political_decisions','jarvis_political_agreement_replies','political_proclamations','political_office_terms','political_office_charters','organisation_keys','organisation_key_events','codex_instance_editions','account_audit','jarvis_pol_progression_seasons','jarvis_pol_progression_accounts','jarvis_pol_progression_history','jarvis_pol_progression_outbox','site_clans','site_clan_deeds','site_clan_charters','site_clan_members','site_game_links','site_accounts']});
|
||||
async function accounts(tx,actor,d){const b=banking.view(tx),r=politicalDecisionReader(tx,db),authority=deps.authority||createPostbankAuthority(r,{bank:b,clock});const rights=await authority(actor,{bank:b});return(await b.query(accountsSQL+' WHERE c.entity_id=? AND a.system_key IS NULL ORDER BY a.id',[funding(d)])).filter(a=>ordinaryPaymentAccount(a)&&canDebitAccount(rights,a.entity_id,a.id));}
|
||||
const eventBanking=atomicBankAccess(db,bank,{verifyStorage:deps.verifyStorage,bankTables:['jarvis_events','jarvis_event_history']});
|
||||
async function recipients(tx,actor,d,search=''){
|
||||
|
|
@ -64,7 +65,8 @@ export function createPoliticalDecisions(db,bank,keys,deps={}){
|
|||
const season=seasons.length===1?seasons[0]:null,level=season?levelForXP(Number(xp?.effective_xp||0),{base:Number(season.curve_base),cap:Number(season.level_cap)||null}):0;
|
||||
const choices=holder?await accounts(db,actor,d):[];let reportAvailable=true;if(d.kind==='report'){try{if(!deps.marketReports)throw Error('No reporting source');await deps.marketReports.ready();}catch{reportAvailable=false;}}
|
||||
const clans=holder&&d.kind==='clan-grant'&&deps.clanGrants?await deps.clanGrants.targets(db,d):[],grantAvailable=d.kind!=='clan-grant'||!!deps.clanGrants&&clans.length>0,minimum=d.kind==='clan-grant'?d.grantMinMinor:d.feeMinor;
|
||||
return{...d,clans,grantAvailable,canManage:!!holder,canExecute:grantAvailable&&reportAvailable&&!!holder&&!!keys&&!!season&&level>=d.level&&(!cooldownUntil||now>=cooldownUntil)&&choices.some(a=>BigInt(a.balance_minor)-BigInt(a.reserved_minor)>=BigInt(minimum)),reportAvailable,report:holder&&d.kind==='report'&&prior?JSON.parse(prior.receipt_json).report||null:null,levelNow:level,cooldownUntil,accounts:choices.map(a=>({id:String(a.id),name:a.display_name,number:a.account_number,availableMinor:String(BigInt(a.balance_minor)-BigInt(a.reserved_minor))})),recipients:holder?await recipients(db,actor,d,search):[]};
|
||||
const diplomacyTargets=holder&&d.kind==='agreement'&&deps.agreements?await deps.agreements.targets(db,d,actor,now):[];
|
||||
return{...d,diplomacyTargets,clans,grantAvailable,canManage:!!holder,canExecute:(d.kind!=='agreement'||diplomacyTargets.length>0)&&grantAvailable&&reportAvailable&&!!holder&&!!keys&&!!season&&level>=d.level&&(!cooldownUntil||now>=cooldownUntil)&&choices.some(a=>BigInt(a.balance_minor)-BigInt(a.reserved_minor)>=BigInt(minimum)),reportAvailable,report:holder&&d.kind==='report'&&prior?JSON.parse(prior.receipt_json).report||null:null,levelNow:level,cooldownUntil,accounts:choices.map(a=>({id:String(a.id),name:a.display_name,number:a.account_number,availableMinor:String(BigInt(a.balance_minor)-BigInt(a.reserved_minor))})),recipients:holder?await recipients(db,actor,d,search):[]};
|
||||
}
|
||||
async function execute(actor,input){
|
||||
const {d,requestId,sourceAccount,payload}=decisionInput(input);if(!keys)fail('Key service unavailable.',503);await banking.ready();if(d.kind==='event')await eventBanking.ready();const digest=fingerprint([actor.id,d.id,sourceAccount,payload]);
|
||||
|
|
@ -89,18 +91,19 @@ export function createPoliticalDecisions(db,bank,keys,deps={}){
|
|||
if(!tax||tax.state!=='active'||grant&&!ordinaryPaymentAccount(tax)||String(source.id)===String(tax.id)||BigInt(source.balance_minor)-BigInt(source.reserved_minor)<amount||BigInt(tax.balance_minor)+amount>9223372036854775807n)fail('Insufficient funds or unavailable treasury.');
|
||||
const pol=polProgressionStore(tx),season=await readActiveXPSeason(pol,now),state=await lockXPAccount(pol,actor.id,now),level=levelForXP(state.effectiveXP,{base:Number(season.curve_base),cap:Number(season.level_cap)||null});if(level<d.level)fail('Reputation level '+d.level+' is required.',403);
|
||||
let report=null;if(d.kind==='report'){if(!deps.marketReports)fail('Verified Exchange reporting unavailable. No decision was charged.',503);report=await deps.marketReports.report(tx,d,now);}
|
||||
let agreement=null;if(d.kind==='agreement'){if(!deps.agreements)fail('Political agreements unavailable.',503);agreement=await deps.agreements.create(tx,{d,actor,payload,holder,now});}
|
||||
const rewardXP=grant?Math.max(1,Math.floor(d.xp*payload.amountMinor/d.grantMaxMinor)):d.xp;
|
||||
let receipt;
|
||||
await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',scopeId:'state:political-decision:'+requestId,transactionStore:tx,authorize:async(_,{keyId})=>{
|
||||
const effectId=randomUUID(),expiresAt=d.durationMs?now+d.durationMs:null;
|
||||
receipt={ok:true,requestId,keyId,effectId,decisionId:d.id,feeMinor:String(amount),xp:rewardXP,expiresAt,cooldownUntil:now+d.cooldownMs,...(report?{report}:{}),...(grant?{grant:{clanId:grant.clanId,clanName:grant.clanName,amountMinor:String(amount),basicFallback:grant.basic,recipientKind:grant.recipientKind}}:{})};
|
||||
receipt={ok:true,requestId,keyId,effectId,decisionId:d.id,feeMinor:String(amount),xp:rewardXP,expiresAt,cooldownUntil:now+d.cooldownMs,...(report?{report}:{}),...(agreement?{agreement}:{}),...(grant?{grant:{clanId:grant.clanId,clanName:grant.clanName,amountMinor:String(amount),basicFallback:grant.basic,recipientKind:grant.recipientKind}}:{})};
|
||||
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,digest,String(amount),d.title,now]);
|
||||
await new PostbankPayments(bank,null,{clock}).post(b,{id:requestId,actor_id:actor.id,amount_minor:String(amount)},source,tax,false);
|
||||
if(d.kind==='proclamation')await tx.query('INSERT INTO political_proclamations(id,request_id,scope,title,body,author_id,created_at,version) VALUES(?,?,?,?,?,?,?,1)',[effectId,requestId,d.scope||'imperium',payload.title,payload.body,actor.id,now]);
|
||||
if(d.kind==='event'){const event=await createRealmEventRecord(eventBanking.view(tx),actor,{requestId,kind:'politics',scopeId:d.office,...payload},now);receipt.eventId=event.eventId;receipt.calendarScope=d.office;}
|
||||
const updated=creditXP(state,rewardXP,{capXP:Number(season.level_cap)===0?Number.MAX_SAFE_INTEGER:xpAtLevel(Number(season.level_cap),Number(season.curve_base))});
|
||||
await saveXPAccount(pol,actor.id,updated,season,keyId,'political-decision',{decisionId:d.id,termId:holder.termId,xp:rewardXP},now);
|
||||
await tx.query('INSERT INTO jarvis_political_decisions(request_id,key_id,decision_id,office_key,term_id,actor_id,recipient_id,input_hash,payload_json,receipt_json,created_at,expires_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)',[requestId,keyId,d.id,d.office,holder.termId,actor.id,payload.recipientId||null,digest,JSON.stringify(payload),JSON.stringify(receipt),now,expiresAt]);
|
||||
await tx.query('INSERT INTO jarvis_political_decisions(request_id,key_id,decision_id,office_key,term_id,actor_id,recipient_id,input_hash,payload_json,receipt_json,created_at,expires_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)',[requestId,keyId,d.id,d.office,holder.termId,actor.id,agreement?.targetActorId||payload.recipientId||null,digest,JSON.stringify(payload),JSON.stringify(receipt),now,expiresAt]);
|
||||
}});return receipt;
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,10 +14,11 @@ import {EVENT_SCHEMA} from '../node/jarvis-events.mjs';
|
|||
import {currentGuildSurcharge,currentGuildDiscount} from '../node/guild-tariff-policy.mjs';
|
||||
import {createPoliticalClanGrants} from '../node/political-clan-grants.mjs';
|
||||
import {initializeClans} from '../control-panel/clans.mjs';
|
||||
import {POLITICAL_AGREEMENT_SCHEMA,createPoliticalAgreements,createPoliticalAgreementAPI} from '../node/political-agreements.mjs';
|
||||
async function fixture(office='emperor',extra={}){
|
||||
const f=await companyFixture(),old=f.db.query.bind(f.db);f.db.query=(sql,args=[])=>old(sql.replace(/,\s*KEY \w+\([^)]*\)/g,''),args);f.db.sqlite.function('CONCAT',{varargs:true},(...args)=>args.join(''));
|
||||
f.db.sqlite.exec('ALTER TABLE political_office_terms ADD COLUMN id TEXT;ALTER TABLE political_office_terms ADD COLUMN kind TEXT;CREATE TABLE political_office_charters(office_key TEXT PRIMARY KEY,charter_kind TEXT,staff_key_id TEXT);CREATE TABLE site_character_choices(minecraft_uuid TEXT PRIMARY KEY,faction TEXT);');
|
||||
await f.db.query(POLITICAL_DECISION_SCHEMA);f.db.politicalDecisionsEnabled=true;
|
||||
await f.db.query(POLITICAL_DECISION_SCHEMA);await f.db.query(POLITICAL_AGREEMENT_SCHEMA);f.db.politicalDecisionsEnabled=true;
|
||||
f.db.sqlite.exec('CREATE TABLE political_proclamations(id TEXT PRIMARY KEY,request_id TEXT,scope TEXT,title TEXT,body TEXT,author_id TEXT,created_at INT,version INT);');
|
||||
await initializePOLProgression(f.db);let now=1000;const pol=polProgressionStore(f.db);await pol.query("INSERT INTO jarvis_progression_seasons VALUES('S01',0,9999999999,0,25,'active',1)");await pol.query('INSERT INTO jarvis_progression_accounts VALUES(?,10000,10000,28,1,0)',[f.people.Owner.id]);
|
||||
const grant=await f.keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-office-royal',scopeId:'office:'+office,authorize:async()=>true});await f.keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-office-royal',code:grant.code,targetId:randomUUID(),requestId:randomUUID(),apply:(tx,{keyId})=>tx.query('INSERT INTO political_office_charters VALUES(?,?,?)',[office,'royal',keyId])});
|
||||
|
|
@ -211,3 +212,41 @@ test('debit authority snapshots retain the existing transaction connection rathe
|
|||
const tx={query:async()=>[{id:'locked'}],first:async()=>({id:'locked'})},base={readSnapshot:async()=>{throw Error('A second connection would observe stale authority');}};
|
||||
const reader=politicalDecisionReader(tx,base);assert.equal(await reader.readSnapshot(async r=>(await r.prepare('SELECT id FROM political_office_terms').first()).id),'locked');
|
||||
});
|
||||
|
||||
async function diplomacyFixture(office='atreides'){
|
||||
const f=await fixture(office),targetOffice=office==='corrino'?'atreides':'corrino',target=PUBLIC_OFFICES.find(o=>o.key===targetOffice),targetTerm=randomUUID();await f.pol.query('UPDATE jarvis_progression_accounts SET effective_xp=50000,total_xp=50000');
|
||||
const grant=await f.keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-office-royal',scopeId:'office:'+targetOffice,authorize:async()=>true});await f.keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-office-royal',code:grant.code,targetId:randomUUID(),requestId:randomUUID(),apply:(tx,{keyId})=>tx.query('INSERT INTO political_office_charters VALUES(?,?,?)',[targetOffice,'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)",[targetTerm,f.people.Other.id,target.kind,target.faction,target.office]);
|
||||
const agreements=createPoliticalAgreements(f.db,f.keys,{clock:f.clock}),service=createPoliticalDecisions(f.db,f.db,f.keys,{verifyStorage:async()=>null,authority:f.authority,clock:f.clock,agreements});
|
||||
return{...f,agreements,service,targetOffice,targetTerm,proposal:(decisionId='ATR-05')=>({decisionId,requestId:randomUUID(),sourceAccount:String(f.source.id),targetOffice,title:'A diplomatic understanding',terms:'Both offices agree to maintain an open channel for peaceful diplomacy.',confirmed:true}),reply:(proposalId,choice='accept')=>({proposalId,choice,requestId:randomUUID(),confirmed:true})};
|
||||
}
|
||||
test('five diplomatic decisions deliver confidential proposals and require the original receiving mandate to consent',async()=>{
|
||||
for(const [office,id]of [['atreides','ATR-05'],['corrino','COR-06'],['ordos','ORD-05'],['veiled_concord','BG-05'],['muad_dib','NF-05']]){const f=await diplomacyFixture(office);try{
|
||||
const before=BigInt((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.source.id])).balance_minor),d=POLITICAL_DECISIONS.find(d=>d.id===id),input=f.proposal(id);assert((await f.service.read(f.people.Owner,id)).diplomacyTargets.some(o=>o.id===f.targetOffice));
|
||||
const receipt=await f.service.execute(f.people.Owner,input);assert.equal(receipt.agreement.targetActorId,f.people.Other.id);assert.equal((await f.service.execute(f.people.Owner,input)).keyId,receipt.keyId);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.source.id])).balance_minor,Number(before-BigInt(d.feeMinor)));assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);
|
||||
assert.equal((await f.agreements.read(f.people.Member)).agreements.length,0);let view=(await f.agreements.read(f.people.Other)).agreements[0];assert.equal(view.state,'pending');assert.equal(view.canReply,true);const response=f.reply(input.requestId);await assert.rejects(f.agreements.reply(f.people.Member,response),/not addressed/);const replied=await f.agreements.reply(f.people.Other,response);assert.equal((await f.agreements.reply(f.people.Other,response)).reference,replied.reference);view=(await f.agreements.read(f.people.Owner)).agreements[0];assert.equal(view.state,'accepted');assert.equal(view.endsAt,1000+d.durationMs);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);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('diplomatic refusal, response deadlines, revoked proposals and changed mandates cannot manufacture acceptance',async()=>{
|
||||
for(const change of ['decline','deadline','receiver','source','revoked']){const f=await diplomacyFixture();try{
|
||||
const input=f.proposal(),receipt=await f.service.execute(f.people.Owner,input),response=f.reply(input.requestId,change==='decline'?'decline':'accept');
|
||||
if(change==='deadline')f.setTime(receipt.agreement.responseUntil);if(change==='receiver')await f.db.query('UPDATE political_office_terms SET user_id=? WHERE id=?',[f.people.Member.id,f.targetTerm]);if(change==='source')await f.db.query("UPDATE political_office_terms SET outcome='ended' WHERE id=?",[f.term]);if(change==='revoked')await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[receipt.keyId]);
|
||||
if(change==='decline'){await f.agreements.reply(f.people.Other,response);assert.equal((await f.agreements.read(f.people.Owner)).agreements[0].state,'declined');}else await assert.rejects(f.agreements.reply(f.people.Other,response),/expired/);
|
||||
}finally{f.db.close();}}
|
||||
});
|
||||
test('diplomatic receipt and response failures roll back fees, Reputation, keys and acceptance',async()=>{
|
||||
const f=await diplomacyFixture();try{
|
||||
const input=f.proposal(),start=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;f.db.sqlite.exec("CREATE TRIGGER fail_diplomacy BEFORE INSERT ON jarvis_political_decisions BEGIN SELECT RAISE(ABORT,'proposal journal failed');END");await assert.rejects(f.service.execute(f.people.Owner,input),/proposal journal failed/);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.source.id])).balance_minor,2000000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,start);assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Owner.id])).total_xp,50000);f.db.sqlite.exec('DROP TRIGGER fail_diplomacy');await f.service.execute(f.people.Owner,input);
|
||||
const count=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;f.db.sqlite.exec("CREATE TRIGGER fail_response BEFORE INSERT ON jarvis_political_agreement_replies BEGIN SELECT RAISE(ABORT,'response journal failed');END");await assert.rejects(f.agreements.reply(f.people.Other,f.reply(input.requestId)),/response journal 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');
|
||||
}finally{f.db.close();}
|
||||
});
|
||||
test('diplomacy input rejects office impersonation, self approval and short mandates before charging',async()=>{
|
||||
const f=await diplomacyFixture();try{
|
||||
await assert.rejects(f.service.execute(f.people.Owner,{...f.proposal(),targetOffice:'atreides'}),/another registered/);await assert.rejects(f.service.execute(f.people.Owner,{...f.proposal(),actorId:f.people.Other.id}),/Review and confirm/);await f.db.query('UPDATE political_office_terms SET expires_at=? WHERE id=?',[2000,f.targetTerm]);await assert.rejects(f.service.execute(f.people.Owner,f.proposal()),/full proposal response/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);
|
||||
const api=createPoliticalAgreementAPI(f.db,f.agreements,{authenticate:async()=>f.people.Other}),input=f.reply(randomUUID());const post=(body,origin='https://cp.dunerealms.com')=>api(new Request('https://cp.dunerealms.com/api/politics/agreements',{method:'POST',headers:{origin},body:JSON.stringify(body)}));assert.equal((await post(input,'https://example.invalid')).status,403);assert.equal((await post({...input,userId:f.people.Owner.id})).status,400);
|
||||
}finally{f.db.close();}
|
||||
});
|
||||
|
||||
test('a revoked diplomatic response never restores acceptance or reopens a decided proposal',async()=>{const f=await diplomacyFixture();try{const input=f.proposal();await f.service.execute(f.people.Owner,input);const response=f.reply(input.requestId),receipt=await f.agreements.reply(f.people.Other,response);await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[receipt.reference]);const item=(await f.agreements.read(f.people.Other)).agreements[0];assert.equal(item.state,'response-unavailable');assert.equal(item.canReply,false);await assert.rejects(f.agreements.reply(f.people.Other,f.reply(input.requestId,'decline')),/already has a response/);}finally{f.db.close();}});
|
||||
test('accepted diplomacy expires at its fixed duration and cannot be accepted by a holder acting on both sides',async()=>{const f=await diplomacyFixture();try{await f.db.query('UPDATE political_office_terms SET user_id=? WHERE id=?',[f.people.Owner.id,f.targetTerm]);await assert.rejects(f.service.execute(f.people.Owner,f.proposal()),/different current/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);await f.db.query('UPDATE political_office_terms SET user_id=? WHERE id=?',[f.people.Other.id,f.targetTerm]);const input=f.proposal();await f.service.execute(f.people.Owner,input);await f.agreements.reply(f.people.Other,f.reply(input.requestId));f.setTime(1000+7*86400000);assert.equal((await f.agreements.read(f.people.Owner)).agreements[0].state,'expired');}finally{f.db.close();}});
|
||||
test('Baron’s Favour reuses House profile honours with seven-day expiry, fixed funding and no self or foreign House award',async()=>{const f=await fixture('harkonnen');try{await f.pol.query('UPDATE jarvis_progression_accounts SET effective_xp=50000,total_xp=50000');const link=await f.db.first('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?',[f.people.Other.id]);await f.db.query('INSERT INTO site_character_choices VALUES(?,?)',[link.minecraft_uuid,'harkonnen']);const input=f.input('HAR-07');await assert.rejects(f.service.execute(f.people.Owner,{...input,recipientId:f.people.Owner.id}),/another active/);const r=await f.service.execute(f.people.Owner,input);assert.equal(r.expiresAt,1000+7*86400000);assert.equal(r.xp,1200);assert.equal(r.feeMinor,'500000');assert.equal((await politicalHonours(f.db,f.people.Other.id,r.expiresAt)).length,0);}finally{f.db.close();}});
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff