Connect political campaigns, coalition consent and Reputation war service
This commit is contained in:
parent
1414ab5047
commit
3e9fbc9c06
31 changed files with 510 additions and 45 deletions
|
|
@ -76,3 +76,8 @@ Current priority: implement and test the server-only dev-key executor, starting
|
|||
- Group at least three genuine user requests in a batch; do not count individual technical edits as separate requests. War is one request, POL missions and POL decisions are the other two requests in the current batch.
|
||||
- Include the scope checklist, verification plan, PR/commit and actual live-release evidence in that ticket. Update its progress and complete it only when its stated scope is actually live and verified.
|
||||
- Placeholder pages must be explicitly marked as previews and include all appropriate DuneRealms artwork. Preserve working actions while the remaining consumers are built.
|
||||
|
||||
## Latest owner override (24 November 2026)
|
||||
|
||||
- The owner explicitly said “negeer tickets” and “just do it” for continuing backend work. Skip dev-ticket creation and approval; do not block implementation on support tickets. This supersedes the earlier ticket-first requirement.
|
||||
- Preserve the colleague’s design work. Continue the three backend requests: war system, POL missions, POL decisions.
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ const date=n=>new Date(n).toLocaleString(undefined,{dateStyle:'medium',timeStyle
|
|||
|
||||
// The server supplies all state, eligibility and rewards. The browser sends only
|
||||
// the selected definition and its displayed revision, never XP or counters.
|
||||
export function mountPersonalProgression(host,{view='missions',fetcher=fetch,apiBase='/api/progression',onData=()=>{},onBranches=()=>{},externalBranches=false,initialBranch='a'}={}){
|
||||
export function mountPersonalProgression(host,{view='missions',fetcher=fetch,apiBase='/api/progression',onData=()=>{},onBranches=()=>{},externalBranches=false,initialBranch='a',allowedBranches=null,artwork=null}={}){
|
||||
const controller=new AbortController(),status=el('p','Opening your mission journal…','progression-notice'),body=el('div');
|
||||
status.setAttribute('role','status');host.replaceChildren(status,body);
|
||||
let active=true,data=null,branch=initialBranch,selected=null,busy=false,uncertain=false,page=1,loadSequence=0,connectorObserver=null;
|
||||
|
|
@ -30,7 +30,7 @@ export function mountPersonalProgression(host,{view='missions',fetcher=fetch,api
|
|||
const sequence=++loadSequence;
|
||||
try{
|
||||
const fresh=await api(view==='history'?'/history?page='+page:'');if(!active||sequence!==loadSequence)return;
|
||||
data=fresh;uncertain=false;requestIds.clear();if(view!=='history')onData(fresh);render();
|
||||
data=allowedBranches&&Array.isArray(fresh.quests)?{...fresh,quests:fresh.quests.filter(q=>allowedBranches.includes(q.branch)),branches:fresh.branches?.filter(b=>allowedBranches.includes(b.id))}:fresh;uncertain=false;requestIds.clear();if(view!=='history')onData(fresh);render();
|
||||
message(view==='history'?'Your recorded J.A.R.V.I.S. activity.':data.state==='active'?'Only verified objectives can be claimed. Unconnected gameplay objectives remain pending.':'The next season has not opened yet.');status.hidden=data.state==='active'||view==='history';
|
||||
}catch(error){if(!active||sequence!==loadSequence)return;message(error.message);body.replaceChildren(button('Reload journal',load));}
|
||||
}
|
||||
|
|
@ -58,9 +58,9 @@ export function mountPersonalProgression(host,{view='missions',fetcher=fetch,api
|
|||
select.value=branch;select.onchange=()=>{branch=select.value;selected=null;render();};onBranches(availableBranches.filter(b=>data.quests.some(q=>q.branch===b.id)),branch);if(!externalBranches)body.append(select);
|
||||
const rows=data.quests.filter(q=>q.branch===branch).map(q=>({...q,channel:questChannel(q.executionRequirements)}));selected=rows.find(q=>q.id===selected)?.id||null;
|
||||
const layout=el('div',undefined,'progression-layout'),tree=el('div',undefined,'progression-tree');tree.setAttribute('aria-label','Mission tree');
|
||||
for(const row of rows){const card=button('',()=>{selected=row.id;detailOpen=true;render();});card.className='progression-mission';card.dataset.missionId=row.id;card.dataset.channel=row.channel==='website'?'website':'shared';card.setAttribute('aria-pressed',String(row.id===selected));card.setAttribute('aria-haspopup','dialog');card.append(image(questArtwork(row.channel)),el('strong',row.title),el('span',labels[row.state]||'Awaiting verification','progression-badge'));tree.append(card);}
|
||||
for(const row of rows){const card=button('',()=>{selected=row.id;detailOpen=true;render();});card.className='progression-mission';card.dataset.missionId=row.id;card.dataset.channel=row.channel==='website'?'website':'shared';card.setAttribute('aria-pressed',String(row.id===selected));card.setAttribute('aria-haspopup','dialog');card.append(image(artwork||questArtwork(row.channel)),el('strong',row.title),el('span',labels[row.state]||'Awaiting verification','progression-badge'));tree.append(card);}
|
||||
layout.append(tree);const row=rows.find(q=>q.id===selected);
|
||||
if(row&&detailOpen){const pane=el('aside',undefined,'progression-detail');pane.setAttribute('aria-label','Selected mission');pane.append(image(questArtwork(row.channel)),el('small',row.id),el('h3',row.title),el('small',row.channel==='website'?'Website quest':'Website / Minecraft quest'));
|
||||
if(row&&detailOpen){const pane=el('aside',undefined,'progression-detail');pane.setAttribute('aria-label','Selected mission');pane.append(image(artwork||questArtwork(row.channel)),el('small',row.id),el('h3',row.title),el('small',row.channel==='website'?'Website quest':'Website / Minecraft quest'));
|
||||
if(uncertain){const feedback=el('p',status.textContent,'progression-notice');feedback.setAttribute('role','alert');pane.append(feedback);}const guide=questGuidance(row);pane.append(el('h4','How to complete'),el('p',guide.objective),el('h4','Where'),el('p',guide.where));if(guide.connected===false&&row.state!=='claimed')pane.append(el('p',guide.verification,'progression-notice'));if(row.issuerName)pane.append(el('small','Questgiver · '+row.issuerName));if(row.recipe){pane.append(el('h4','Recipe · '+row.recipe.world));const table=el('table',undefined,'progression-recipe');table.setAttribute('aria-label','Elytra crafting recipe');for(const cells of row.recipe.grid){const tr=el('tr');for(const cell of cells)tr.append(el('td',cell));table.append(tr);}pane.append(table,el('p','Very Rare · MK XI · Craft on Arrakis'));}
|
||||
const source=data.sources?.sources?.find(s=>s.metrics?.includes(row.metric));
|
||||
const quantity=value=>row.metric?.endsWith('-minor')?(value/100).toLocaleString(undefined,{minimumFractionDigits:2,maximumFractionDigits:2})+' DM':value.toLocaleString();
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import {ELYTRA_BRANCH} from './cp-v2-elytra-quests.mjs';
|
||||
import {WAR_QUEST_BRANCH} from './cp-v2-war-quests.mjs';
|
||||
// Server-owned content shared with the existing quest and POL Decision interfaces.
|
||||
// Reward amounts, decision costs and timings require explicit configuration.
|
||||
const freeze=v=>{if(v&&typeof v==='object'){Object.values(v).forEach(freeze);Object.freeze(v);}return v;};
|
||||
|
|
@ -1098,8 +1099,9 @@ export const POL_QUEST_BRANCHES=freeze([
|
|||
}
|
||||
]
|
||||
},
|
||||
ELYTRA_BRANCH
|
||||
ELYTRA_BRANCH,
|
||||
WAR_QUEST_BRANCH
|
||||
]);
|
||||
const gameplayMetrics=new Set(['pol-smuggler-introduction','pol-sabotage','pol-water-supply','pol-spice-transport','pol-sietch-service','pol-verified-route','pol-route-service','pol-sealed-cargo','pol-restricted-delivery','pol-alternate-route','pol-opposed-delivery','pol-ghost-cargo','pol-escort','pol-interdiction','pol-cargo-recovery','pol-protection','pol-commissioned-recovery','pol-discreet-logistics','pol-protected-delivery']);
|
||||
export const POL_QUEST_DEFINITIONS=Object.freeze(POL_QUEST_BRANCHES.flatMap(b=>b.quests.map((q,index)=>Object.freeze({...q,issuer:b.issuer||({smugglers:"esmar_tuek",clan:"gurney_halleck",company:"roma_atani"})[b.id],issuerName:b.issuerName||({smugglers:"Esmar Tuek",clan:"Gurney Halleck",company:"Roma Atani"})[b.id],objective:q.objective,xp:q.xp??150+index*50,executionRequirements:Object.freeze({website:true,minecraft:gameplayMetrics.has(q.metric)||q.branch==='elytra'})}))));
|
||||
export const POL_QUEST_DEFINITIONS=Object.freeze(POL_QUEST_BRANCHES.flatMap(b=>b.quests.map((q,index)=>Object.freeze({...q,issuer:b.issuer||({smugglers:"esmar_tuek",clan:"gurney_halleck",company:"roma_atani"})[b.id],issuerName:b.issuerName||({smugglers:"Esmar Tuek",clan:"Gurney Halleck",company:"Roma Atani"})[b.id],objective:q.objective,xp:q.xp??150+index*50,executionRequirements:Object.freeze({website:true,minecraft:gameplayMetrics.has(q.metric)||['elytra','war-service'].includes(q.branch)})}))));
|
||||
export function polBranch(id){return POL_QUEST_BRANCHES.find(b=>b.id===id||b.office===id)||null;}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import {appendOfficeMissionPreview,appendOfficeDecisionBanner,planningImage} from './cp-v2-war-planning.mjs';
|
||||
import {appendOfficeMissionPreview,appendOfficeMissionBanner,appendOfficeDecisionBanner,planningImage} from './cp-v2-war-planning.mjs';
|
||||
import {POL_PLANNING_ART,officeDecisionPreviews} from './cp-v2-war-planning-content.mjs';
|
||||
import {mountPoliticalDecision} from './cp-v2-political-decisions.mjs';
|
||||
import {politicalDecision} from '../political-decision-policy.mjs';
|
||||
|
|
@ -40,12 +40,13 @@ export function mountProgressionDesign(host,{context='personal',dashboard=false,
|
|||
if(isDecision&&['NF-08','NF-09','NF-10'].includes(row.id)){mountFaithBlessing(pane,row.id);return pane;}
|
||||
if(isDecision&&politicalDecision(row.id)){mountPoliticalDecision(pane,row.id);return pane;}
|
||||
if(isDecision&&row.id==='IMP-10'){mountImperialPassage(pane);return pane;}
|
||||
if(isDecision&&row.executionStatus==='war-exchange-controller'){const link=el('a','Open War Exchange →');link.href='#household/war-exchange';pane.append(el('p','Current organisation authority is checked on every action. Both organisations approve alliances; all sides must choose the same hour. Changes clear previous calendar consent. No DM or XP is awarded for a proposal.'),link);return pane;}
|
||||
const dl=el('dl');for(const[label,value]of isDecision&&row.planned?[['Authority','Current political office · eligibility checked on connection'],['Timing','All sides agree the same calendar hour'],['Cooldown','Awaiting configuration'],['Status','Coming soon']]:isDecision&&row.xpType==='pol'?[['Authority','Current deed'],['Funding','Configured reward pool required'],['Scope',row.rewardScope],['Status','Awaiting configuration']]:isDecision?[['Authority','Current deed · checked on execution'],['Level',String(row.level)],['XP',row.xp+' · proposal'],['Cost / cooldown',row.cost+' · handover values'],['Currency','DM · same numerical handover values; no charge enabled']]:[['Progress','Not connected'],['Season','Season 1 · design'],['Completion',row.optional?'Optional / prestige':'Required objective'],['Reward','Configured reward · pending review']])dl.append(el('dt',label),el('dd',value));pane.append(dl);
|
||||
if(isDecision){const audit=decisionAudit(row.id);if(audit)pane.append(el('p',audit.authority+'. '+audit.gap,'progression-notice'));}
|
||||
if(row.title==='Repair Your Starter Kit'){const parts=el('div',undefined,'progression-repair');for(const item of STARTER_REPAIR_PARTS){const part=el('figure');part.append(image(item.art),el('figcaption',item.name+' × '+item.quantity));parts.append(part);}pane.append(el('p','Your '+STARTER_KIT_POLICY.tier+' faction kit starts with '+STARTER_KIT_POLICY.remainingDurabilityBps/100+'% durability. Collect all four parts and return that damaged kit for one intact replacement. Minecraft collection and surrender must be verified.'),parts);}
|
||||
if(isDecision)pane.append(field('Target',['Select eligible target · preview']));const action=button(isDecision?'Execute decision · pending integration':'Claim reward · pending integration');action.disabled=true;pane.append(action,el('p','J.A.R.V.I.S. dossier · no live execution reference exists yet.','progression-muted'));return pane;
|
||||
}
|
||||
function renderMissions(){if(activeContext==='politics'){appendOfficeMissionPreview(content,{officeCode,dialog:dossier});return;}const toolbar=el('div',undefined,'progression-toolbar'),select=field('Mission branch',MISSION_BRANCHES.map(b=>b.title)),season=field('Season',['Season 1','Season archive · preview']);select.querySelector('select').selectedIndex=MISSION_BRANCHES.findIndex(b=>b.id===branch);select.onchange=e=>{branch=MISSION_BRANCHES[e.target.selectedIndex].id;selected=null;render();};toolbar.append(select,season);content.append(toolbar);
|
||||
function renderMissions(){if(activeContext==='politics'){if(manage){appendOfficeMissionPreview(content,{officeCode,dialog:dossier});return;}appendOfficeMissionBanner(content,officeCode);const branch=POL_QUEST_BRANCHES.find(b=>b.office===officeCode),journal=el('div');content.append(journal);disposePersonal=mountPersonalProgression(journal,{apiBase:'/api/progression/pol',initialBranch:branch?.id||'war-service',allowedBranches:[branch?.id,'war-service'].filter(Boolean),artwork:POL_PLANNING_ART[officeCode]?.banner});return;}const toolbar=el('div',undefined,'progression-toolbar'),select=field('Mission branch',MISSION_BRANCHES.map(b=>b.title)),season=field('Season',['Season 1','Season archive · preview']);select.querySelector('select').selectedIndex=MISSION_BRANCHES.findIndex(b=>b.id===branch);select.onchange=e=>{branch=MISSION_BRANCHES[e.target.selectedIndex].id;selected=null;render();};toolbar.append(select,season);content.append(toolbar);
|
||||
if(activeContext==='personal'){const stats=el('div',undefined,'progression-stats');stats.append(el('strong','XP & level · awaiting connection'),el('span','Season cap 70 · proposed'),el('span','Halfway & completion milestones'),el('progress'));content.append(stats);}else{const info=el('p',activeContext==='politics'?'Office objectives are supplemental. Holding office is never required for personal seasonal completion.':'Organisation mission tree · shared component; organisation-specific objectives await definition.','progression-notice');content.append(info);}
|
||||
const b=MISSION_BRANCHES.find(b=>b.id===branch)||MISSION_BRANCHES[0],rows=activeContext==='personal'?b.missions:activeContext==='politics'?DECISION_CATALOGUE.filter(d=>d.office===officeCode).map(d=>({id:'MISSION-'+d.id,title:d.title+' · office objective',optional:true})):[];
|
||||
const layout=el('div',undefined,'progression-layout'),tree=el('div',undefined,'progression-tree');tree.setAttribute('aria-label','Mission tree');if(!rows.length){tree.append(image(CONTEXTS[activeContext][1]),el('h3','Organisation mission tree'),el('p','The roster, tree, objectives and reward panel are ready for shared definitions. Personal mission requirements are not copied onto organisations.'));layout.append(tree);content.append(layout);return;}
|
||||
|
|
@ -55,7 +56,7 @@ export function mountProgressionDesign(host,{context='personal',dashboard=false,
|
|||
connectorObserver=new ResizeObserver(connect);connectorObserver.observe(tree);requestAnimationFrame(connect);
|
||||
}
|
||||
function renderDecisions(){if(activeContext==='politics')appendOfficeDecisionBanner(content,officeCode);if(activeContext==='politics'&&!manage){const live=el('div');content.append(live);disposePersonal=mountOfficeRebellionDecisions(live,{officeKey:organisation?.id||({IMP:'emperor',ATR:'atreides',HAR:'harkonnen',COR:'corrino',ORD:'ordos',FRE:'fremen',BG:'veiled_concord',NF:'muad_dib',SG:'spacing_guild',CLD:'clan_delegate'})[officeCode]});}const toolbar=el('div',undefined,'progression-toolbar'),search=el('input');search.type='search';search.placeholder='Search decisions';search.setAttribute('aria-label','Search decisions');search.value=query;search.oninput=()=>{query=search.value;renderDecisionsList();};toolbar.append(search);if(activeContext==='personal'&&xpKind==='pol'){const chooser=field('Questgiver',POL_QUEST_BRANCHES.map(b=>b.title));chooser.querySelector('select').selectedIndex=POL_QUEST_BRANCHES.findIndex(b=>b.id===polDecisionBranch);chooser.onchange=e=>{polDecisionBranch=POL_QUEST_BRANCHES[e.target.selectedIndex].id;selected=null;render();};toolbar.append(chooser);}if((dashboard&&activeContext==='politics')||manage){const chooser=field('Office catalogue',OFFICES.map(([,name])=>name));chooser.querySelector('select').selectedIndex=OFFICES.findIndex(([id])=>id===officeCode);chooser.onchange=e=>{officeCode=OFFICES[e.target.selectedIndex][0];selected=null;render();};toolbar.append(chooser);}content.append(toolbar);const listHost=el('div');content.append(listHost);
|
||||
function renderDecisionsList(){listHost.replaceChildren();let rows=activeContext==='politics'||manage?[...DECISION_CATALOGUE.filter(d=>d.office===officeCode),...officeDecisionPreviews(officeCode)]:activeContext==='personal'&&xpKind==='pol'?(POL_QUEST_BRANCHES.find(b=>b.id===polDecisionBranch)?.decisions||[]):activeContext==='personal'?[{id:'P-MARK',title:'Equipment Mark eligibility',effect:'Level, materials and equipment restrictions remain necessary.',level:0,xp:0,cost:'Pending configuration'},{id:'P-RARITY',title:'Rarity enhancement eligibility',effect:'Use the existing rarity and Legendary upgrade policy.',level:0,xp:0,cost:'Pending configuration'},{id:'P-SEASON',title:'Seasonal completion entitlement',effect:'One non-tradable completion kit after all mandatory objectives.',level:0,xp:0,cost:'Earned entitlement'}]:[];rows=rows.filter(r=>(r.title+' '+r.effect).toLowerCase().includes(query.toLowerCase()));if(!rows.length){listHost.append(el('p','No decision definitions available for this selection. No authority is inferred.'));return;}selected=rows.find(r=>r.id===selected)?.id||rows[0].id;const layout=el('div',undefined,'progression-layout'),cards=el('div',undefined,'progression-decisions');for(const row of rows){const card=button('',()=>{selected=row.id;dossier.show(details(row,true),{title:lore(row.title),returnFocus:card});},'progression-decision');card.setAttribute('aria-haspopup','dialog');card.setAttribute('aria-pressed',String(row.id===selected));const art=activeContext==='politics'?POL_PLANNING_ART[officeCode]:activeContext==='personal'&&xpKind==='pol'?POL_PLANNING_ART[POL_QUEST_BRANCHES.find(b=>b.id===polDecisionBranch)?.office]:null;card.append(image(art?.banner||'exchange-political-positions-v1.png'),...(art?[planningImage(art.seal,art.title+' seal','pol-decision-seal')]:[]),el('small',row.id),el('strong',row.title),el('span',politicalDecision(row.id)?'Review funded decision':row.id==='IMP-10'?'Manage House passage':['NF-08','NF-09','NF-10'].includes(row.id)?'Prepare clan blessing':'View proposal · execution unavailable'));cards.append(card);}layout.append(cards);listHost.append(layout);}renderDecisionsList();
|
||||
function renderDecisionsList(){listHost.replaceChildren();let rows=activeContext==='politics'||manage?[...DECISION_CATALOGUE.filter(d=>d.office===officeCode),...officeDecisionPreviews(officeCode)]:activeContext==='personal'&&xpKind==='pol'?(POL_QUEST_BRANCHES.find(b=>b.id===polDecisionBranch)?.decisions||[]):activeContext==='personal'?[{id:'P-MARK',title:'Equipment Mark eligibility',effect:'Level, materials and equipment restrictions remain necessary.',level:0,xp:0,cost:'Pending configuration'},{id:'P-RARITY',title:'Rarity enhancement eligibility',effect:'Use the existing rarity and Legendary upgrade policy.',level:0,xp:0,cost:'Pending configuration'},{id:'P-SEASON',title:'Seasonal completion entitlement',effect:'One non-tradable completion kit after all mandatory objectives.',level:0,xp:0,cost:'Earned entitlement'}]:[];rows=rows.filter(r=>(r.title+' '+r.effect).toLowerCase().includes(query.toLowerCase()));if(!rows.length){listHost.append(el('p','No decision definitions available for this selection. No authority is inferred.'));return;}selected=rows.find(r=>r.id===selected)?.id||rows[0].id;const layout=el('div',undefined,'progression-layout'),cards=el('div',undefined,'progression-decisions');for(const row of rows){const card=button('',()=>{selected=row.id;dossier.show(details(row,true),{title:lore(row.title),returnFocus:card});},'progression-decision');card.setAttribute('aria-haspopup','dialog');card.setAttribute('aria-pressed',String(row.id===selected));const art=activeContext==='politics'?POL_PLANNING_ART[officeCode]:activeContext==='personal'&&xpKind==='pol'?POL_PLANNING_ART[POL_QUEST_BRANCHES.find(b=>b.id===polDecisionBranch)?.office]:null;card.append(image(art?.banner||'exchange-political-positions-v1.png'),...(art?[planningImage(art.seal,art.title+' seal','pol-decision-seal')]:[]),el('small',row.id),el('strong',row.title),el('span',politicalDecision(row.id)?'Review funded decision':row.id==='IMP-10'?'Manage House passage':['NF-08','NF-09','NF-10'].includes(row.id)?'Prepare clan blessing':row.executionStatus==='war-exchange-controller'?'Manage war agreement':'View proposal · execution unavailable'));cards.append(card);}layout.append(cards);listHost.append(layout);}renderDecisionsList();
|
||||
}
|
||||
function render(){dossier.close();connectorObserver?.disconnect();disposePersonal?.();disposePersonal=null;notice.textContent=activeContext==='personal'&&!manage?(xpKind==='pol'?'Reputation missions use verified J.A.R.V.I.S. records and their system questgivers. Decision execution awaits configuration.':'Personal missions use verified J.A.R.V.I.S. records. Decision and organisation integrations remain in preview.'):'Connected decisions open a review and confirmation. Other proposals remain unavailable until their consumers are connected.';root.dataset.context=activeContext;notice.hidden=activeContext==='personal'&&!manage;nav.hidden=report.available&&activeContext==='personal'&&!manage;report.setNavigation(xpKind,tab);report.showBranches(activeContext==='personal');xpNav.replaceChildren();xpNav.hidden=activeContext!=='personal'||manage||report.available;if(!xpNav.hidden)for(const [kind,label]of [['personal','Personal level'],['pol','Reputation level']]){const b=button(label,()=>{xpKind=kind;selected=null;render();});b.setAttribute('aria-pressed',String(kind===xpKind));xpNav.append(b);}contextNav.replaceChildren();for(const[id,[label]]of Object.entries(CONTEXTS)){const b=button(label,()=>{activeContext=id;selected=null;query='';render();});b.setAttribute('aria-pressed',String(id===activeContext));contextNav.append(b);}renderGallery();nav.replaceChildren();for(const[id,label]of [['missions',manage?'Mission Definitions':'Missions'],['decisions',manage?'Decision Definitions':'Decisions'],...(manage?[['rewards','Progression & Rewards']]:[]),['history','History']]){const b=button(label,()=>{tab=id;selected=null;render();});b.setAttribute('aria-pressed',String(tab===id));nav.append(b);}content.replaceChildren();if(activeContext==='clan'&&!manage){notice.hidden=true;disposePersonal=mountClanRebellions(content,{clanId:organisation?.id||null,embedded:true,view:tab,onDecisions:()=>{tab='decisions';render();}});return;}if(activeContext==='personal'&&!manage&&['missions','history'].includes(tab))disposePersonal=mountPersonalProgression(content,{view:tab,apiBase:xpKind==='pol'?'/api/progression/pol':'/api/progression',externalBranches:report.available,initialBranch:branch,onData:data=>report.setJournal(xpKind,data),onBranches:(rows,id)=>{branch=id;report.setBranches(rows,id);}});else if(tab==='missions')renderMissions();else if(tab==='decisions')renderDecisions();else if(tab==='rewards'){content.append(el('h3','Progression & Rewards'),field('Season cap',['70 · proposed']),field('Milestone announcements',['Halfway and completion only']),el('p','Rewards, XP curves, repair recipes and signing editions await backend review. No configuration writes enabled.'));}else content.append(el('h3','J.A.R.V.I.S. History'),el('p','Verified completion, claims, decisions and any staff overrides will appear here after integration. No sample audit records are shown.'));}
|
||||
render();return()=>{dossier.dispose();connectorObserver?.disconnect();disposePersonal?.();report.dispose();root.remove();};
|
||||
|
|
|
|||
|
|
@ -3,6 +3,9 @@
|
|||
const live=(objective,where,verification)=>({objective,where,verification,connected:true});
|
||||
const pending=(objective,where)=>({objective,where,verification:'Gameplay connection coming soon; this objective cannot yet be verified.',connected:false});
|
||||
export const QUEST_GUIDANCE=Object.freeze({
|
||||
'pol-war-deployment':live('Be enrolled in the frozen roster of an agreed campaign when its shared calendar hour begins. Publishing or viewing a proposal does not count.','Clan / POL CP → War Exchange → Roster and shared calendar','Prepared campaign with a started calendar hour and your verified Minecraft identity'),
|
||||
'pol-war-capture':live('Capture an enemy Home Block in person during the agreed campaign. Stay on the enrolled side and interact with the registered objective.','Ingame → Active war Home Block objective','Original authenticated native capture receipt'),
|
||||
'pol-war-victory':live('Capture at least one Home Block for the winning side and finish the campaign. Wait for its J.A.R.V.I.S. conquest deed settlement, then refresh this journal.','War Exchange → Campaign report → Conquest deeds updated','Consumed victory instrument matching the completed campaign and your capture'),
|
||||
onboarding:live('Complete account onboarding and link your Minecraft account to this website account.','My Account → Account Center','Verified linked account and completed onboarding'),
|
||||
faction:live('Choose and confirm your House. The choice must belong to the Minecraft account linked to your website account.','Imperial Codex → Your House, or the website House selector','Current central House selection'),
|
||||
profile:live('Set your display name and save a biography of at least 10 characters. Choosing a House alone does not complete your profile.','My Account → Profile','Saved display name and biography'),
|
||||
|
|
|
|||
|
|
@ -26,6 +26,23 @@ export function mountWarExchange(host,{kind='clan',scopeId=null,fetcher=fetch}={
|
|||
const proposal=row(id);if(!proposal)return;calendar?.destroy();calendar=null;currentId=id;selected=proposal.selections.find(s=>s.partyKey===warPartyKey(context))?.startsAt??null;let rosterDirty=false;
|
||||
const pane=el('section',undefined,'war-exchange-detail'),state=el('p',warProposalFacts(proposal).join(' · ')),teams=el('div',undefined,'war-exchange-teams'),area=el('div',undefined,'promotion-calendar'),choice=el('p'),confirm=el('button','Select this block'),withdraw=el('button','Withdraw proposal');confirm.type=withdraw.type='button';
|
||||
pane.append(el('p',proposal.message),state,teams);for(let i=0;i<proposal.parties.length;i++){const party=proposal.parties[i],slot=proposal.selections.find(s=>s.partyKey===warPartyKey(party)),card=el('article',undefined,'election-panel');card.dataset.side=String(i+1);card.append(el('strong',party.name),el('p',slot?date(slot.startsAt):'No block selected'));teams.append(card);}
|
||||
const named=proposal.parties.some(p=>warPartyKey(p)===warPartyKey(context));
|
||||
if(proposal.mode!=='clan'){
|
||||
const allies=el('fieldset',undefined,'war-roster');allies.append(el('legend','Coalition agreements'),el('p','Both organisations must approve. Every change clears the saved rosters and calendar choices.'));
|
||||
for(const agreement of proposal.coalitions||[]){
|
||||
const side=proposal.parties.find(p=>warPartyKey(p)===agreement.sideKey),ally=data.parties.find(p=>warPartyKey(p)===warPartyKey(agreement.ally));if(!side||!ally)continue;
|
||||
const row=el('article',undefined,'election-panel');row.append(el('strong',ally.name+' → '+side.name),el('p',agreement.accepted?'Both organisations approved':'Awaiting both current authorities'));
|
||||
if(proposal.state==='open'&&[agreement.sideKey,warPartyKey(agreement.ally)].includes(warPartyKey(context)))for(const [accept,label]of [[true,'Approve coalition'],[false,'Remove agreement']]){const action=el('button',label);action.type='button';action.disabled=busy||uncertain;action.onclick=async()=>{action.disabled=true;if(await write({action:'ally',id,revision:proposal.revision,side:{kind:side.kind,id:side.id},ally:agreement.ally,accept})&&active)await open(id);};row.append(action);}
|
||||
allies.append(row);
|
||||
}
|
||||
if(proposal.state==='open'){
|
||||
const side=el('select'),ally=el('select'),invite=el('button',named?'Propose alliance':'Request to join side');side.setAttribute('aria-label','Coalition side');ally.setAttribute('aria-label','Allied organisation');invite.type='button';
|
||||
for(const p of proposal.parties.filter(p=>!named||warPartyKey(p)===warPartyKey(context))){const o=el('option',p.name);o.value=warPartyKey(p);side.append(o);}
|
||||
for(const p of data.parties.filter(p=>!proposal.parties.some(r=>warPartyKey(r)===warPartyKey(p))&&(!named?warPartyKey(p)===warPartyKey(context):true)&&(p.id!=='emperor'||proposal.mode==='world'))){const o=el('option',p.name);o.value=warPartyKey(p);ally.append(o);}
|
||||
invite.disabled=busy||uncertain||!side.options.length||!ally.options.length;invite.onclick=async()=>{const a=data.parties.find(p=>warPartyKey(p)===ally.value),s=proposal.parties.find(p=>warPartyKey(p)===side.value);if(!a||!s)return;invite.disabled=true;if(await write({action:'ally',id,revision:proposal.revision,side:{kind:s.kind,id:s.id},ally:{kind:a.kind,id:a.id},accept:true})&&active)await open(id);};allies.append(side,ally,invite);
|
||||
}
|
||||
pane.append(allies);
|
||||
}
|
||||
if(proposal.roster){
|
||||
const roster=el('fieldset',undefined,'war-roster'),count=el('p'),save=el('button','Save roster'),selectedPlayers=new Set(proposal.roster.selected),checks=[];
|
||||
roster.append(el('legend','Your war roster'),el('p','Members of your mother clan and client clans. Save changes before choosing the calendar hour; changes clear every side’s previous calendar choice.'));
|
||||
|
|
@ -43,7 +60,7 @@ export function mountWarExchange(host,{kind='clan',scopeId=null,fetcher=fetch}={
|
|||
pane.append(el('p','Scheduled: '+date(proposal.block.startsAt)),el('p','Combat deployment and capture reports will appear here when the game bridge is connected.'));
|
||||
const progress=el('progress');progress.max=100;progress.removeAttribute('value');progress.setAttribute('aria-label','Awaiting verified war progress');pane.append(progress);
|
||||
}
|
||||
const paint=()=>{choice.textContent=rosterDirty?'Save your roster changes before selecting a calendar block.':selected===null?'Choose a future hour on the calendar.':'Your selected block: '+date(selected);confirm.disabled=busy||uncertain||rosterDirty||proposal.state!=='open'||selected===null||selected<=Date.now();withdraw.disabled=busy||uncertain||!['open','scheduled'].includes(proposal.state)||!!proposal.block&&proposal.block.startsAt<=Date.now();};paint();
|
||||
const paint=()=>{choice.textContent=!named?'Your coalition leader selects the shared calendar hour.':rosterDirty?'Save your roster changes before selecting a calendar block.':selected===null?'Choose a future hour on the calendar.':'Your selected block: '+date(selected);confirm.disabled=!named||busy||uncertain||rosterDirty||proposal.state!=='open'||selected===null||selected<=Date.now();withdraw.disabled=!named||busy||uncertain||!['open','scheduled'].includes(proposal.state)||!!proposal.block&&proposal.block.startsAt<=Date.now();};paint();
|
||||
confirm.onclick=async()=>{if(selected===null)return;confirm.disabled=withdraw.disabled=true;if(await write({action:'select',id,revision:proposal.revision,startsAt:selected,endsAt:selected+WAR_BLOCK_MS})&&active)await open(id);else if(active)paint();};
|
||||
withdraw.onclick=async()=>{withdraw.disabled=confirm.disabled=true;if(await write({action:'withdraw',id,revision:proposal.revision})&&active){dossier.close();activate('history');}else if(active)paint();};
|
||||
dossier.show(pane,{title:proposal.title});
|
||||
|
|
|
|||
|
|
@ -31,6 +31,6 @@ export function officeDecisionPreviews(code){
|
|||
const office=POL_PLANNING_ART[code]||POL_PLANNING_ART.IMP,branch=POL_QUEST_BRANCHES.find(b=>b.office===code);
|
||||
const planned=[['WORLD','Propose a World Campaign','Prepare a world-war proposal and seek the other side’s agreement.'],['ROSTER','Approve the War Roster','Choose eligible military-clan and client-clan members within the scenario limit.'],['ALLIES','Invite Allied Clans','Prepare coalition or hired-clan terms for an agreed campaign.'],['COALITION','Choose a Universal Coalition','Prepare your world’s preferred side: Empire, Rebellion or Countercoalition.'],['FAITH','Choose a Side in the War of Faith','Review support for the Guild, Church or independent world coalition.']];
|
||||
if(code==='IMP')planned.push(['INTERVENE','Imperial Intervention','Support one side in a world war and substitute the Imperial Home Block province. Clan wars are excluded.']);
|
||||
return [...(branch?.decisions||[]),...planned.map(([id,title,effect])=>({id:'PREVIEW-WAR-'+code+'-'+id,office:code,title,effect,planned:true,xpType:'pol',rewardScope:'war',executionStatus:'coming-soon'}))];
|
||||
return [...(branch?.decisions||[]),...planned.map(([id,title,effect])=>({id:'WAR-'+code+'-'+id,office:code,title,effect,planned:false,xpType:'pol',rewardScope:'war',executionStatus:'war-exchange-controller'}))];
|
||||
}
|
||||
export const planningArtAssets=()=>[...new Set([...WAR_PLANS.flatMap(p=>[p.art,p.seal]),...Object.values(POL_PLANNING_ART).flatMap(p=>[p.banner,p.seal])])];
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ export function appendOfficeMissionPreview(host,{officeCode='IMP',dialog}={}){
|
|||
root.append(grid);host.append(root);return root;
|
||||
}
|
||||
export function appendOfficeDecisionBanner(host,officeCode){planningStyles();const office=POL_PLANNING_ART[officeCode]||POL_PLANNING_ART.IMP;host.append(banner(office.banner,office.title+' · Decisions','Open a decision to review its effect. Connected actions keep their normal confirmation; planned actions are marked unavailable.'));}
|
||||
export function appendOfficeMissionBanner(host,officeCode){planningStyles();const office=POL_PLANNING_ART[officeCode]||POL_PLANNING_ART.IMP;host.append(banner(office.banner,office.title+' · Missions','Verified Reputation missions · campaign service uses agreed deployment, native captures and settled victory.'));}
|
||||
export function mountWarPlanning(host,{kind='clan',scopeId=null}={}){
|
||||
planningStyles();const overview=el('section'),coalitions=el('section'),reports=el('section');
|
||||
const {root}=createCPV2Page({shellHost:host,title:'War Room',description:'Campaign plans, coalitions and Home Block provinces.',artwork:'seals/emperor-v1.png',tabs:[{id:'scenarios',label:'War scenarios',artwork:'nav-clan-v2.webp',content:overview},{id:'coalitions',label:'Sides & rosters',artwork:'seals/office-landsraad.png',content:coalitions},{id:'reports',label:'Campaign reports',artwork:'nav-manual-v2.webp',content:reports}]});
|
||||
|
|
|
|||
5
website/control-panel/public/cp-v2/cp-v2-war-quests.mjs
Normal file
5
website/control-panel/public/cp-v2/cp-v2-war-quests.mjs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
export const WAR_QUEST_BRANCH=Object.freeze({id:'war-service',title:'Campaign service',issuer:'thufir_hawat',issuerName:'Thufir Hawat',theme:'Agreed deployment, verified Home Block capture and victory',quests:[
|
||||
{id:'POL-WAR-01',title:'Answer the Muster',objective:'Be included in the frozen roster of a unanimously agreed war when its calendar hour begins. Publishing a proposal alone does not count.',metric:'pol-war-deployment',xp:150},
|
||||
{id:'POL-WAR-02',title:'Secure a Province',objective:'During an agreed war, capture an enemy Home Block in person. Only a verified server capture counts.',metric:'pol-war-capture',xp:200},
|
||||
{id:'POL-WAR-03',title:'A Settled Victory',objective:'Capture at least one province for the winning side and finish the campaign. The victory must complete its J.A.R.V.I.S. deed settlement.',metric:'pol-war-victory',xp:250}
|
||||
].map((q,i)=>Object.freeze({...q,target:1,requires:i?['POL-WAR-0'+i]:[],requiresAny:[],branch:'war-service',season:'S01',revision:1,optional:false,verifiedOnly:true,xpType:'pol',executionRequirements:{website:true,minecraft:true}})),decisions:[]});
|
||||
File diff suppressed because one or more lines are too long
|
|
@ -38,7 +38,7 @@ import {createDeedPurchases} from '../node/deed-purchases.mjs';
|
|||
import {createRebellionQuests,initializeRebellionRewards} from '../node/rebellion-quests.mjs';
|
||||
import {createRebellionAPI} from '../node/rebellion-api.mjs';
|
||||
import {createPOLProgressionRuntime} from '../node/progression-pol-runtime.mjs';
|
||||
import {initializePOLProgression,ensurePOLProgressionPolicy,ensurePOLRepeatablePolicy,ensureElytraQuestPolicy,polProgressionStore} from '../node/progression-pol.mjs';
|
||||
import {initializePOLProgression,ensurePOLProgressionPolicy,ensurePOLRepeatablePolicy,ensureElytraQuestPolicy,ensureWarQuestPolicy,polProgressionStore} from '../node/progression-pol.mjs';
|
||||
import {initializeSystemCharacters} from '../node/system-characters.mjs';
|
||||
import {initializeEntityState} from '../node/entity-state-keys.mjs';
|
||||
import {createDMPaint} from './dmpaint.mjs';
|
||||
|
|
@ -264,7 +264,7 @@ export function createPanel(db,settings={},dependencies={}){
|
|||
const auctionRuntime=dependencies.officeAuctionRuntime||createOfficeAuctionRuntime(db,dependencies.bankDatabase||null);const politicalActions=createPoliticalActions(db,{enabled:!!auctionRuntime,origin});const officeAuctionAPI=createOfficeAuctionAPI(db,dependencies.bankDatabase||null,auctionRuntime,settings,dependencies.officeAuctionAPI);
|
||||
const progressionRuntime=dependencies.progressionRuntime||(dependencies.organisationKeys?createProgressionRuntime(db,dependencies.bankDatabase||null,dependencies.organisationKeys):null);
|
||||
const progression=createProgressionAPI(db,{...progressionRuntime,origin});
|
||||
const polRuntime=dependencies.polProgressionRuntime||(dependencies.organisationKeys?createPOLProgressionRuntime(db,dependencies.organisationKeys):null);
|
||||
const polRuntime=dependencies.polProgressionRuntime||(dependencies.organisationKeys?createPOLProgressionRuntime(db,dependencies.organisationKeys,{bank:dependencies.bankDatabase||null}):null);
|
||||
const gameHouseSelection=createHouseSelectionAPI(db,dependencies.organisationKeys,settings,{readBriefing:createGameBriefing({personal:progressionRuntime,pol:polRuntime,bank:dependencies.bankDatabase||null,authority:createPostbankAuthority(db,{bank:dependencies.bankDatabase||null}),organisations:actor=>readGameMemberships(db,actor),identity:actor=>readGamePublicIdentity(db,actor)})});
|
||||
const gameStarter=dependencies.organisationKeys?createGameStarterKit(db,dependencies.organisationKeys,settings):null;
|
||||
const gameResearch=dependencies.organisationKeys?createGameResearch(db,dependencies.organisationKeys):null;
|
||||
|
|
@ -562,7 +562,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);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 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);db.politicalDecisionsEnabled=true;await db.query(FAITH_BLESSING_SCHEMA);db.faithBlessingsEnabled=true;await db.query(IMPERIAL_PASSAGE_SCHEMA);await db.query(HOUSE_SELECTION_SCHEMA);await db.query(GAME_ORGANISATION_SCHEMA);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await initializeJarvisGenerator(db);await initializeEntityState(db);await initializeSystemCharacters(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys); /* Passive POL conversion waits for scoped adapters instead of company management. */await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;await initializeProgression(db);await initializeStarterKitEvents(db);db.starterKitEventsEnabled=true;await initializeServerProjects(db);if(bankDatabase)await bankDatabase.query(PROJECT_BANK_SCHEMA);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);await ensureStarterKitRewardPolicy(db,organisationKeys).catch(()=>console.error('Starter kit reward policy requires review; existing custom configuration was preserved'));await initializePOLProgression(db);await initializeSecondaryAffiliations(db);await initializePersonalActivityEvents(db);db.personalActivityEventsEnabled=true;await initializePOLActivityEvents(db);db.polActivityEventsEnabled=true;await initializeRebellionRewards(db);await ensurePOLProgressionPolicy(db,organisationKeys);await ensurePOLRepeatablePolicy(db,organisationKeys);await ensureElytraQuestPolicy(db,organisationKeys);await ensureWarQuestPolicy(db,organisationKeys);await ensurePOLMentorPolicy(db,organisationKeys);db.polMentorBonusEnabled=true;db.polRepeatablesEnabled=true;db.organisationResearchEnabled=true;db.researchSuppliesEnabled=true;const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const deedPurchases=bankDatabase&&settings.POSTBANK_ENABLED==='true'?createDeedPurchases(db,bankDatabase,organisationKeys,{authority:createPostbankAuthority(db,{bank:bankDatabase})}):null;const starterKitDelivery=await openStarterKitDelivery(db,settings);const boardRuntime=await openBoardKeyRuntime(db,organisationKeys,settings);const handle=createPanel(db,settings,{boardRuntime,inventoryPool,bankDatabase,organisationKeys,deedPurchases,officeAuctionRuntime,promotionDelivery,progressionRuntime}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com';
|
||||
await initializeInternalMailAccess(db);const stopElectionClock=startElectionClock(db);const stopOfficeLedger=startOfficeLedger(db);
|
||||
const stopBanSync=startModerationSync(db,settings),stopInternalMail=startInternalMailSync(db,{jarvisStore:bankDatabase}),stopCentralScheduler=startCentralScheduler(db,bankDatabase,settings,{extraTasks:[...(settings.MILITARY_PROJECTION_ENABLED==='true'&&organisationKeys?[{key:'military_affiliations',slot:now=>Math.floor(now/60000)*60000,run:()=>createMilitaryAffiliations(db,organisationKeys).drain()}]:[]),{key:'starter_kit_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>starterKitDelivery.drain()},...(boardRuntime?[{key:'board_keys',slot:now=>Math.floor(now/60000)*60000,run:()=>boardRuntime.drain()}]:[]),...(bankDatabase?[{key:'federal_reserve',slot:now=>Math.floor(now/60000)*60000,run:()=>createEconomyRuntime(db,bankDatabase,organisationKeys).federal.run()},{key:'research_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createResearchFundedRewards(db,bankDatabase).drain()},{key:'pol_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createPOLFundedRewards(db,bankDatabase,organisationKeys).drain()},{key:'rebellion_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createRebellionRewards(db,bankDatabase,{sourceAccount:settings.REBELLION_REWARD_SOURCE_ACCOUNT,sourceOwnerId:settings.REBELLION_REWARD_SOURCE_OWNER_ID,useWebsiteTreasury:settings.REBELLION_REWARD_FUND==='website-treasury'}).drain()},...(deedPurchases?[{key:'deed_purchases',slot:now=>Math.floor(now/60000)*60000,run:()=>deedPurchases.drain()}]:[]),{key:'server_projects',slot:now=>Math.floor(now/60000)*60000,run:()=>createServerProjectRuntime(db,bankDatabase,organisationKeys).drain()},{key:'progression_completion',slot:now=>Math.floor(now/60000)*60000,run:async()=>{const completed=await progressionRuntime.quests.processCompletions();const news=await progressionRuntime.announcements.drain();return {completed,news};}},{key:'naib_council',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await reconcileNaibChairs(db);return createNaibCouncil(db).reconcile();}},{key:'jarvis_promotions',slot:now=>Math.floor(now/15000)*15000,run:()=>promotionDelivery.drain()},{key:'political_jobs',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await createPoliticalJobs(db,bankDatabase).reconcile();return drainPoliticalJobNotifications(db,{broker:internalMailBroker,eligible:internalMailEligible});}},{key:'order_membership',slot:now=>Math.floor(now/60000)*60000,run:()=>reconcileCrysknifeCompany(db,organisationKeys)},{key:'office_auctions',slot:now=>Math.floor(now/60000)*60000,run:()=>officeAuctionRuntime.process()},{key:'jarvis_settlement',slot:now=>standardCycle(now).cutoff,async run(cutoff){const payments=createJarvisPayments(bankDatabase,createPostbankAuthority(db,{bank:bankDatabase}));for(let i=0;i<40;i++){const result=await payments.settle(cutoff);if(result.failed)return result;if(result.attempted<100)return result;}return {failed:1};}}]:[])]});
|
||||
const 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};
|
||||
|
|
|
|||
44
website/docs/WAR-POL-CAMPAIGNS.md
Normal file
44
website/docs/WAR-POL-CAMPAIGNS.md
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
# Campaign backend
|
||||
|
||||
The existing War Exchange, calendar, native bridge and system parent-link
|
||||
consumer support clan (2 × 8), world (2 × 16), universal (3 × 86) and religious
|
||||
(3 × 86) campaigns. No new game tunnel or command execution endpoint is added.
|
||||
|
||||
Political sides require current occupied Royal offices, verified Minecraft
|
||||
identities and registered physical Home Blocks. Coalition partners each approve
|
||||
their own agreement. Changing an alliance or roster clears all calendar choices.
|
||||
All named sides must choose the same future hour. Overlapping players and Home
|
||||
Blocks cannot be deployed in another simultaneous campaign.
|
||||
|
||||
Universal conflicts place the Empire first. Religious conflicts place Guild,
|
||||
Church, independent world in that order; the Emperor joins the Guild. The Emperor
|
||||
may join a world campaign on either side with mutual consent, substituting its
|
||||
Home Block for that side's principal province. Clan wars exclude intervention.
|
||||
The universal/religious Imperial finale is hidden and immune until a challenger
|
||||
owns every other province, then stays revealed through counterattacks.
|
||||
|
||||
Original clan ownership, primary membership and nested client links are retained.
|
||||
Completed conquest consumes one existing system parent-link instrument. Political
|
||||
victory reparents losing clan mothers, not every child. Imperial defeat additionally
|
||||
transfers the remaining current office term to the winning political controller
|
||||
and retains the former Emperor's personal mother estates under the Imperial
|
||||
institution. Expiry of an old military affiliation cannot undo a conquest edge.
|
||||
No balances, payroll or historical election results are rewritten.
|
||||
|
||||
POL campaign-service missions use the existing quest and Reputation engine:
|
||||
enrolment in an agreed campaign at its start (150 base XP), a native capture
|
||||
(200), and a capture for the winning side with consumed victory settlement (250).
|
||||
The separate v5 policy preserves existing configured rewards and season dates.
|
||||
Claims re-read the original evidence; private generic game activity submissions
|
||||
cannot assert war progress. Existing Mentat/faith modifiers still apply. There
|
||||
is no automatic DM award for opening proposals, calendar choices or invitations.
|
||||
|
||||
POL mission panels use the real journal with office artwork. War decisions open
|
||||
the authenticated War Exchange controller. Existing proclamation, honour, passage
|
||||
and faith consumers retain their authority, funding and cooldowns. Other proposed
|
||||
intelligence, sabotage and cargo-contract mechanics remain explicitly unavailable
|
||||
until their actual domain consumers exist; this release does not fabricate them.
|
||||
|
||||
Deployment requires `WAR_BRIDGE_ENABLED=true` and the existing generic native
|
||||
campaign consumer. An unregistered office Home Block is a prerequisite failure,
|
||||
not grounds to invent a location or start a demonstration war in production.
|
||||
|
|
@ -1,7 +1,81 @@
|
|||
{
|
||||
"schemaVersion": 1,
|
||||
"sourceHash": "f89b64fc9ac6102b9e05483113e1385dd2a5edfc9bd43ebbe949b6da387b23e7",
|
||||
"sourceHash": "b0634684051ae5075b5ddc009b6f70baa126f09cc684db1eae0c3c6a6e812c6e",
|
||||
"actions": [
|
||||
{
|
||||
"id": "war.coalition-consent",
|
||||
"label": "War Exchange · Approve a political coalition",
|
||||
"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": "side",
|
||||
"label": "Declared political side",
|
||||
"type": "text",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "ally",
|
||||
"label": "Current clan or political organisation",
|
||||
"type": "text",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "accept",
|
||||
"label": "Approve or withdraw",
|
||||
"type": "boolean",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "revision",
|
||||
"label": "Proposal revision",
|
||||
"type": "number",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "requestId",
|
||||
"label": "Request UUID",
|
||||
"type": "text",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"effect": "Each organisation signs only for itself through its current deed authority. Both must agree before scheduling; changes clear rosters and calendar choices. A current Emperor can intervene on either world-war side and substitute the Imperial province. The Guild includes the Emperor in religious war. Immutable request receipts make retries safe; no browser command, cash movement or unilateral foreign signature.",
|
||||
"fixedTargets": [],
|
||||
"webIssue": false,
|
||||
"recordOnly": true
|
||||
},
|
||||
{
|
||||
"id": "progression.war-service-policy",
|
||||
"label": "War Exchange · Campaign Reputation quest policy",
|
||||
"version": 5,
|
||||
"keyType": "progression-policy",
|
||||
"fields": [
|
||||
{
|
||||
"name": "ticketId",
|
||||
"label": "Ban / support ticket ID",
|
||||
"type": "text",
|
||||
"required": true,
|
||||
"maxLength": 80
|
||||
}
|
||||
],
|
||||
"effect": "Install the three campaign-service Reputation quests through policy:POL:S01:v5. Credit only a frozen agreed deployment, an original native capture and a consumed victory settlement bound to the current Minecraft identity and season. Claims re-read the original evidence. Default XP is 150/200/250, existing Mentat modifiers apply, Personal XP and configured funding remain separate. No browser-supplied progress or default DM issuance.",
|
||||
"fixedTargets": [],
|
||||
"webIssue": false,
|
||||
"recordOnly": true
|
||||
},
|
||||
{
|
||||
"id": "war.calendar-agreement",
|
||||
"label": "War Exchange · War proposal and calendar agreement",
|
||||
|
|
@ -107,7 +181,7 @@
|
|||
"required": true
|
||||
}
|
||||
],
|
||||
"effect": "Retain owners, heirs and nested client branches. Install one operation-owned parent edge and restore its previous edge on ordinary end. Skip restoration after a subsequent conquest or other parent instruction. Read current Royal POL charters, terms and appointed members. A system parent-link instrument temporarily attaches only an owned mother; expiry consumes a separate scoped instrument and restores the previous edge. Native military counterparts reuse POL art, Home Block and bank reference without duplicate primary memberships or new accounts. MILITARY_PROJECTION_ENABLED remains off until coordinated native0.5.33 rollout; no website issuance or arbitrary parent writes.",
|
||||
"effect": "Retain owners, heirs and nested client branches. Install one operation-owned parent edge and restore its previous edge on ordinary end. Skip restoration after a subsequent conquest or other parent instruction. Read current Royal POL charters, terms and appointed members. A system parent-link instrument temporarily attaches only an owned mother; expiry consumes a separate scoped instrument and restores the previous edge. Native military counterparts reuse POL art, Home Block and bank reference without duplicate primary memberships or new accounts. MILITARY_PROJECTION_ENABLED gates the coordinated native projection; no website issuance or arbitrary parent writes.",
|
||||
"fixedTargets": [],
|
||||
"webIssue": false,
|
||||
"recordOnly": true
|
||||
|
|
@ -115,7 +189,7 @@
|
|||
{
|
||||
"id": "war.homeblock-capture",
|
||||
"label": "War Exchange · Verified campaign province capture",
|
||||
"version": 1,
|
||||
"version": 2,
|
||||
"keyType": "entity-state",
|
||||
"fields": [
|
||||
{
|
||||
|
|
@ -156,15 +230,15 @@
|
|||
"required": true
|
||||
}
|
||||
],
|
||||
"effect": "Only a prepared, unanimously scheduled campaign can advance. Revalidate the native actor, server, position and current Home Block through a required trusted verifier. Persist one receipt and revision and update province colours. In universal/religious wars the Imperial final province stays hidden and immune until one challenger holds every other province; once revealed it remains visible through counterattacks. Clan native capture, read-only war menus and key-backed conquest settlement are connected behind WAR_BRIDGE_ENABLED. Larger political coalition wars are not connected yet.",
|
||||
"effect": "Only a prepared, unanimously scheduled campaign can advance. Revalidate the native actor, server, position and current Home Block through a required trusted verifier. Persist one receipt and revision and update province colours. In universal/religious wars the Imperial final province stays hidden and immune until one challenger holds every other province; once revealed it remains visible through counterattacks. Clan native capture, read-only war menus and key-backed conquest settlement are connected behind WAR_BRIDGE_ENABLED. World, universal and religious campaigns resolve current POL mandates, military members, allied clan branches and physical Home Blocks through the existing authenticated bridge.",
|
||||
"fixedTargets": [],
|
||||
"webIssue": false,
|
||||
"recordOnly": true
|
||||
},
|
||||
{
|
||||
"id": "war.conquest-settlement",
|
||||
"label": "War Exchange · Settle a verified clan campaign victory",
|
||||
"version": 1,
|
||||
"label": "War Exchange · Settle a verified campaign victory",
|
||||
"version": 2,
|
||||
"keyType": "staff-parent-link",
|
||||
"fields": [
|
||||
{
|
||||
|
|
@ -193,7 +267,7 @@
|
|||
"required": true
|
||||
}
|
||||
],
|
||||
"effect": "Read only a stored native campaign victory. Revalidate current charters, owners and Home Blocks, issue one scoped system parent-link key, and consume it atomically through the existing conquest/deed primitive. Preserve original owners, primary memberships and every nested client link. A bank-side outbox safely retries the same instrument after an interruption; no balance or payroll action.",
|
||||
"effect": "Read only a stored native campaign victory. Revalidate current charters, owners and Home Blocks, issue one scoped system parent-link key, and consume it atomically through the existing conquest/deed primitive. Preserve original owners, primary memberships and every nested client link. A bank-side outbox safely retries the same instrument after an interruption; Political victories use the same instrument; losing mother clans retain their nested clients. A defeated Imperial final province transfers the current office term and retains its former holder’s mother estates under the Imperial institution. No balance or payroll action.",
|
||||
"fixedTargets": [],
|
||||
"webIssue": false,
|
||||
"recordOnly": false
|
||||
|
|
|
|||
|
|
@ -7,13 +7,19 @@ import {campaignPhase,warCampaignReport} from './war-campaign-model.mjs';
|
|||
import {createClanWarConquests} from './war-conquests.mjs';
|
||||
import {drainWarSettlements} from './war-settlement-jobs.mjs';
|
||||
import {boardReadStore} from './board-deed-source.mjs';
|
||||
import {buildPoliticalCampaignSnapshot,politicalTeam,currentPoliticalCampaign} from './war-political-rosters.mjs';
|
||||
import {politicalConquestAuthority,settlePoliticalConquest} from './war-political-conquests.mjs';
|
||||
const fail=message=>{throw Object.assign(Error(message),{status:409});};
|
||||
async function charters(db){return (await db.prepare('SELECT clan_id,key_id FROM site_clan_charters ORDER BY clan_id LIMIT 501').all()).results;}
|
||||
export function createClanCampaignResolver(db,{readState=()=>readGameNativeState(db)}={}){
|
||||
return async proposal=>proposal.mode==='clan'?buildClanCampaignSnapshot(await readState(),proposal.parties,await charters(db),proposal.rosters):null;
|
||||
return async proposal=>proposal.mode==='clan'?buildClanCampaignSnapshot(await readState(),proposal.parties,await charters(db),proposal.rosters):buildPoliticalCampaignSnapshot(await readState(),proposal,await charters(db));
|
||||
}
|
||||
export function createClanRosterResolver(db,{readState=()=>readGameNativeState(db)}={}){
|
||||
return async(party,mode,selection=null)=>{
|
||||
return async(party,mode,selection=null,proposal=null)=>{
|
||||
if(party.kind==='politics'&&mode!=='clan'&&proposal?.parties?.some(p=>p.kind===party.kind&&p.id===party.id)){
|
||||
const {team}=politicalTeam(await readState(),party,mode,proposal.allies||[],selection);
|
||||
return {capacity:mode==='world'?16:86,selected:team.roster.map(m=>m.uuid),candidates:[...team.roster,...team.reserves]};
|
||||
}
|
||||
if(party.kind!=='clan'||mode!=='clan')return null;
|
||||
const branch=clanWarBranch((await readState()).clans,party.id);
|
||||
if(branch[0].protected)fail('Protected official clans cannot enter clan wars.');
|
||||
|
|
@ -23,6 +29,7 @@ export function createClanRosterResolver(db,{readState=()=>readGameNativeState(d
|
|||
}
|
||||
|
||||
export function currentClanCampaign(campaign,state,keys){
|
||||
if(campaign.mode!=='clan')return currentPoliticalCampaign(campaign,state,keys);
|
||||
const validPlayers=new Set();
|
||||
for(const team of campaign.teams){
|
||||
if(team.party?.kind!=='clan')fail('This campaign requires its political coalition adapter.');
|
||||
|
|
@ -38,9 +45,12 @@ export function currentClanCampaign(campaign,state,keys){
|
|||
}
|
||||
|
||||
export function createClanWarSettlementAdapter(db,store,keys,{clock=Date.now}={}){
|
||||
return createClanWarConquests(db,keys,{clock,readWinningCampaign:async id=>{const row=await store.first('SELECT snapshot_json FROM jarvis_war_campaigns WHERE id=?',[id]);return row?JSON.parse(row.snapshot_json):null;},verifySnapshot:async(tx,campaign)=>{
|
||||
return createClanWarConquests(db,keys,{clock,settlePolitical:settlePoliticalConquest,readWinningCampaign:async id=>{const row=await store.first('SELECT snapshot_json FROM jarvis_war_campaigns WHERE id=?',[id]);return row?JSON.parse(row.snapshot_json):null;},verifySnapshot:async(tx,campaign)=>{
|
||||
for(const term of campaign.teams.flatMap(t=>(t.mandates||[]).map(m=>m.termId)).sort())await tx.first('SELECT id FROM political_office_terms WHERE id=? FOR UPDATE',[term]);
|
||||
for(const clan of [...new Set(campaign.teams.flatMap(t=>(t.clanDeeds||[]).map(c=>c.id)))].sort())await tx.first('SELECT id FROM site_clans WHERE id=? FOR UPDATE',[clan]);
|
||||
const reader=boardReadStore(tx,db);reader.readSnapshot=undefined;
|
||||
const state=await readGameNativeState(reader,{clock}),deeds=await tx.query('SELECT clan_id,key_id FROM site_clan_charters ORDER BY clan_id LIMIT 501');currentClanCampaign(campaign,state,deeds);
|
||||
if(campaign.mode!=='clan')return politicalConquestAuthority(tx,campaign,state);
|
||||
const winner=await tx.first('SELECT owner_id FROM site_clans WHERE id=? AND active=1 FOR UPDATE',[campaign.winnerSideId]);if(!winner)fail('Winning clan deed unavailable.');
|
||||
return {winnerId:campaign.winnerSideId,winnerOwnerId:winner.owner_id,loserIds:campaign.teams.filter(t=>t.id!==campaign.winnerSideId).map(t=>t.id)};
|
||||
}});
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}
|
|||
// transaction. Election and auction source records are never rewritten here.
|
||||
export async function transferOfficeDeed(tx,{termId,sourceTermId,officeKey,winnerId,playerUuid,sourceId,method,now}){
|
||||
const office=PUBLIC_OFFICES.find(o=>o.key===officeKey);
|
||||
if(!office||![termId,sourceTermId,winnerId,playerUuid,sourceId].every(uuid)||method!=='rebellion'||!Number.isSafeInteger(now))throw TypeError('Invalid office deed transfer');
|
||||
if(!office||![termId,sourceTermId,winnerId,playerUuid,sourceId].every(uuid)||!['rebellion','war'].includes(method)||!Number.isSafeInteger(now))throw TypeError('Invalid office deed transfer');
|
||||
const scope=office.kind+':'+office.faction;await tx.query('INSERT INTO political_office_locks(scope) VALUES(?) ON DUPLICATE KEY UPDATE scope=VALUES(scope)',[scope]);await tx.first('SELECT scope FROM political_office_locks WHERE scope=? FOR UPDATE',[scope]);
|
||||
const prior=await tx.first('SELECT * FROM political_office_terms WHERE round_id=?',[sourceId]);
|
||||
if(prior){if(prior.id!==termId||prior.user_id!==winnerId||prior.kind!==office.kind||prior.faction!==office.faction)throw Error('Office transfer reference conflict');return {termId:prior.id,replayed:true};}
|
||||
|
|
@ -14,6 +14,6 @@ export async function transferOfficeDeed(tx,{termId,sourceTermId,officeKey,winne
|
|||
const source=active[0],person=await tx.first("SELECT a.id FROM site_accounts a JOIN site_game_links g ON g.user_id=a.id WHERE a.id=? AND LOWER(g.minecraft_uuid)=? AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('official_account','system_account','memorial')",[winnerId,playerUuid.toLowerCase()]);if(!person)throw Error('Current personal winner identity required');
|
||||
await tx.query("UPDATE political_office_terms SET outcome='superseded',expires_at=? WHERE id=?",[now,sourceTermId]);
|
||||
await tx.query("INSERT INTO political_office_terms(id,kind,faction,election_start,round_id,application_id,user_id,player_uuid,office,starts_at,expires_at,outcome,streak) VALUES(?,?,?,?,?,NULL,?,?,?,?,?,'winner',0)",[termId,office.kind,office.faction,source.election_start,sourceId,winnerId,playerUuid.toLowerCase(),office.office,now,source.expires_at]);
|
||||
for(const [id,event,payload]of [[sourceTermId,'superseded_by_rebellion',{successorTermId:termId,sourceId}],[termId,'rebellion_awarded',{previousTermId:sourceTermId,previousHolderId:source.user_id,sourceId,method}]])await tx.query('INSERT INTO political_office_events(id,term_id,event,payload,created_at) VALUES(?,?,?,?,?)',[randomUUID(),id,event,JSON.stringify(payload),now]);
|
||||
for(const [id,event,payload]of [[sourceTermId,'superseded_by_'+method,{successorTermId:termId,sourceId}],[termId,method+'_awarded',{previousTermId:sourceTermId,previousHolderId:source.user_id,sourceId,method}]])await tx.query('INSERT INTO political_office_events(id,term_id,event,payload,created_at) VALUES(?,?,?,?,?)',[randomUUID(),id,event,JSON.stringify(payload),now]);
|
||||
return {termId,previousTermId:sourceTermId,expiresAt:Number(source.expires_at),replayed:false};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,7 +12,8 @@ import {currentResearchDefinitions,researchEvidence,authorizeResearchClaim} from
|
|||
import {RESEARCH_COOLDOWN_MS} from '../control-panel/public/organisation-research-policy.mjs';
|
||||
import {awardResearch} from './organisation-research-rewards.mjs';
|
||||
import {faithMultipliers,faithAward} from './faith-blessings.mjs';
|
||||
export function createPOLProgressionRuntime(central,keys,{clock=Date.now,verifyObservation=null}={}){
|
||||
import {warQuestEvidence} from './war-quest-evidence.mjs';
|
||||
export function createPOLProgressionRuntime(central,keys,{clock=Date.now,verifyObservation=null,bank=null}={}){
|
||||
const observer=Object.freeze({internal:'pol-key-source-reader'});
|
||||
const resolvePlayer=async id=>(await central.query("SELECT id,username,display_name,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[id]))[0]||null;
|
||||
const authorizePlayer=async(actor,store)=>{
|
||||
|
|
@ -32,6 +33,7 @@ export function createPOLProgressionRuntime(central,keys,{clock=Date.now,verifyO
|
|||
const season=seasons[0],input={accountId:actor.id,minecraftUuid:links[0].minecraft_uuid.toLowerCase(),seasonId:season.season_id,startsAt:Number(season.starts_at),endsAt:Number(season.ends_at),now,lock},activity=await verifiedPOLActivities(store,keys,input);
|
||||
if(central.polRepeatablesEnabled){const deaths=await verifiedPOLDeathTotals(store,keys,input);for(const [metric,value]of deaths.totals)activity.totals.set(metric,value);activity.proofIds.push(...deaths.proofIds);}
|
||||
if(central.organisationResearchEnabled){const research=await researchEvidence(store,actor.id,season.season_id);for(const [metric,value]of research.totals)activity.totals.set(metric,value);activity.proofIds.push(...research.proofIds);}
|
||||
if(bank){const war=await warQuestEvidence(bank,store,input);for(const [metric,value]of war.totals)activity.totals.set(metric,value);activity.proofIds.push(...war.proofIds);}
|
||||
applyElytraAlternative(activity.totals);return {...activity,season};
|
||||
}
|
||||
const adapters={clock,authorizePlayer,authorizeIssuer,resolvePlayer,
|
||||
|
|
|
|||
|
|
@ -49,3 +49,5 @@ export const ensurePOLProgressionPolicy=(db,keys,options={})=>ensureProgressionP
|
|||
export const ensurePOLRepeatablePolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:{...POL_XP_POLICY,version:2},definitions:repeatablePolicyDefinitions()});
|
||||
|
||||
export const ensureElytraQuestPolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:{...POL_XP_POLICY,version:4},definitions:POL_QUEST_DEFINITIONS.filter(d=>d.branch==='elytra')});
|
||||
|
||||
export const ensureWarQuestPolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:{...POL_XP_POLICY,version:5},definitions:POL_QUEST_DEFINITIONS.filter(d=>d.branch==='war-service')});
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import {createHash} from 'node:crypto';
|
|||
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
|
||||
import {createSystemCharacters} from './system-characters.mjs';
|
||||
import {POL_QUEST_DEFINITIONS} from '../control-panel/public/cp-v2/cp-v2-pol-quest-catalogue.mjs';
|
||||
const activityDefinition=metric=>POL_QUEST_DEFINITIONS.find(d=>d.metric===metric)||POL_REPEATABLES.find(d=>['SPICE','CARGO'].includes(d.key)&&d.metric===metric);
|
||||
const activityDefinition=metric=>POL_QUEST_DEFINITIONS.find(d=>d.metric===metric&&d.branch!=='war-service')||POL_REPEATABLES.find(d=>['SPICE','CARGO'].includes(d.key)&&d.metric===metric);
|
||||
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
|
||||
const hash=v=>createHash('sha256').update(JSON.stringify(v)).digest('hex');
|
||||
const first=async(db,sql,args=[])=>(await db.query(sql,args))[0]||null;
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ const homeChunk=home=>({x:Math.floor(home.position.x/16),z:Math.floor(home.posit
|
|||
|
||||
// Internal server model. Callers supply an authenticated, current deed/claim
|
||||
// snapshot, never browser-provided province ownership or player rosters.
|
||||
export function createWarCampaign({id,mode,startsAt,endsAt,teams,provinces}){
|
||||
export function createWarCampaign({id,mode,startsAt,endsAt,teams,provinces,coalitions=[]}){
|
||||
const policy=WAR_MODES[mode];
|
||||
if(!uuid(id)||!policy||!Number.isSafeInteger(startsAt)||startsAt<0||startsAt%3600000!==0||endsAt!==startsAt+3600000||!Array.isArray(teams)||teams.length!==policy.parties||!Array.isArray(provinces)||!provinces.length||provinces.length>500)reject('Invalid campaign snapshot.');
|
||||
const sideIds=new Set(),players=new Set();
|
||||
|
|
@ -29,6 +29,7 @@ export function createWarCampaign({id,mode,startsAt,endsAt,teams,provinces}){
|
|||
if(imperial>1||new Set(provinces.map(p=>p.id)).size!==provinces.length||teams.some(t=>!provinces.some(p=>p.sideId===t.id)))reject('Every side needs distinct registered provinces.');
|
||||
if(['universal','religious'].includes(mode)&&imperial!==1)reject('This campaign requires the protected Imperial final province.');
|
||||
const result={id,mode,startsAt,endsAt,revision:1,teams:clone(teams),provinces:provinces.map(p=>({...clone(p),ownerSideId:p.sideId})),captures:[],winnerSideId:null,imperialUnlockedAt:null};
|
||||
if(mode!=='clan')result.coalitions=clone(coalitions);
|
||||
for(const team of result.teams)for(const member of team.roster)member.uuid=member.uuid.toLowerCase();
|
||||
return result;
|
||||
}
|
||||
|
|
|
|||
32
website/node/war-coalitions.mjs
Normal file
32
website/node/war-coalitions.mjs
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import {warPartyKey} from '../control-panel/public/war-exchange-policy.mjs';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
export const WAR_COALITION_SCHEMA=`CREATE TABLE IF NOT EXISTS jarvis_war_coalitions(proposal_id CHAR(36) NOT NULL,side_key VARCHAR(50) NOT NULL,ally_kind VARCHAR(12) NOT NULL,ally_id VARCHAR(36) NOT NULL,side_actor_id CHAR(36) NULL,ally_actor_id CHAR(36) NULL,updated_at BIGINT NOT NULL,PRIMARY KEY(proposal_id,ally_kind,ally_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`;
|
||||
const fail=message=>{throw Object.assign(Error(message),{status:409});};
|
||||
export async function readWarCoalitions(store,id,{authorize=null,requireAgreement=false}={}){
|
||||
const rows=await store.query('SELECT * FROM jarvis_war_coalitions WHERE proposal_id=? ORDER BY side_key,ally_kind,ally_id',[id]),result=[];
|
||||
for(const row of rows){const [kind,...rest]=row.side_key.split(':'),side={kind,id:rest.join(':')},ally={kind:row.ally_kind,id:row.ally_id};let accepted=!!row.side_actor_id&&!!row.ally_actor_id;
|
||||
if(accepted&&authorize)accepted=!!await authorize({id:row.side_actor_id},side.kind,side.id)&&!!await authorize({id:row.ally_actor_id},ally.kind,ally.id);
|
||||
if(requireAgreement&&!accepted)fail('Every coalition invitation needs current approval from both organisations.');result.push({sideKey:row.side_key,ally,accepted});
|
||||
}return result;
|
||||
}
|
||||
export async function changeWarCoalition(tx,{proposal,input,actor,authorize,choices,now}){
|
||||
const intent={requestId:input.requestId,party:input.party,side:input.side,ally:input.ally,accept:input.accept};
|
||||
const history=await tx.query("SELECT actor_id,details FROM jarvis_war_history WHERE proposal_id=? AND action='coalition-consent'",[proposal.id]);
|
||||
const previous=history.find(h=>JSON.parse(h.details).intent.requestId===input.requestId);
|
||||
if(previous){const saved=JSON.parse(previous.details);if(previous.actor_id!==actor.id||JSON.stringify(saved.intent)!==JSON.stringify(intent))fail('Coalition reference conflict.');return {...saved.result,replayed:true};}
|
||||
if(proposal.state!=='open'||proposal.mode==='clan'||Number(proposal.revision)!==input.revision)fail('Coalition terms are editable only on a current open political proposal.');
|
||||
const parties=JSON.parse(proposal.parties_json),side=parties.find(p=>warPartyKey(p)===warPartyKey(input.side||{})),ally=choices.find(p=>warPartyKey(p)===warPartyKey(input.ally||{}));
|
||||
if(!side||!ally||parties.some(p=>warPartyKey(p)===warPartyKey(ally))||!['politics','clan'].includes(ally.kind))fail('Choose an independent clan or political office and a declared side.');
|
||||
if(ally.id==='emperor'&&proposal.mode!=='world')fail('The Emperor already has a fixed side in this scenario.');
|
||||
const acting=warPartyKey(input.party),sideKey=warPartyKey(side),allyKey=warPartyKey(ally);if(![sideKey,allyKey].includes(acting)||!await authorize(actor,input.party.kind,input.party.id))fail('Only the side and invited organisation may change this agreement.');
|
||||
const old=await tx.first('SELECT * FROM jarvis_war_coalitions WHERE proposal_id=? AND ally_kind=? AND ally_id=? FOR UPDATE',[proposal.id,ally.kind,ally.id]);
|
||||
if(!old&&(await tx.query('SELECT ally_id FROM jarvis_war_coalitions WHERE proposal_id=?',[proposal.id])).length>=32)fail('This coalition register is full.');
|
||||
if(old&&old.side_key!==sideKey)fail('This organisation already has a proposal on another side. Leave it before switching sides.');
|
||||
if(typeof input.accept!=='boolean')fail('Confirm or withdraw your coalition consent.');
|
||||
if(!input.accept){if(old)await tx.query('DELETE FROM jarvis_war_coalitions WHERE proposal_id=? AND ally_kind=? AND ally_id=?',[proposal.id,ally.kind,ally.id]);}
|
||||
else{const sideActor=acting===sideKey?actor.id:old?.side_actor_id||null,allyActor=acting===allyKey?actor.id:old?.ally_actor_id||null;await tx.query('INSERT INTO jarvis_war_coalitions VALUES(?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE side_actor_id=VALUES(side_actor_id),ally_actor_id=VALUES(ally_actor_id),updated_at=VALUES(updated_at)',[proposal.id,sideKey,ally.kind,ally.id,sideActor,allyActor,now]);}
|
||||
await tx.query('DELETE FROM jarvis_war_slots WHERE proposal_id=?',[proposal.id]);await tx.query('DELETE FROM jarvis_war_rosters WHERE proposal_id=?',[proposal.id]);await tx.query('UPDATE jarvis_war_proposals SET revision=revision+1,updated_at=? WHERE id=?',[now,proposal.id]);
|
||||
const result={sideKey,ally:{kind:ally.kind,id:ally.id},accepted:!!input.accept&&!!(acting===sideKey||old?.side_actor_id)&&!!(acting===allyKey||old?.ally_actor_id)};
|
||||
await tx.query('INSERT INTO jarvis_war_history VALUES(?,?,?,?,?,?)',[randomUUID(),proposal.id,actor.id,'coalition-consent',JSON.stringify({intent,result}),now]);
|
||||
return result;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue

Staff