diff --git a/website/control-panel/public/cp-v2/cp-v2-war-exchange.css b/website/control-panel/public/cp-v2/cp-v2-war-exchange.css index 4d271082..f37d978e 100644 --- a/website/control-panel/public/cp-v2/cp-v2-war-exchange.css +++ b/website/control-panel/public/cp-v2/cp-v2-war-exchange.css @@ -1 +1,2 @@ .war-exchange-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,270px),1fr));gap:1rem;margin-block:1rem}.war-exchange-grid .exchange-card{max-width:440px}.war-exchange-detail{display:grid;gap:1rem}.war-exchange-teams{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:.75rem}.war-exchange-teams [data-side="1"]{border-top:4px solid #3276c9}.war-exchange-teams [data-side="2"]{border-top:4px solid #c64b4b}.war-exchange-teams [data-side="3"]{border-top:4px solid #45885b}.war-exchange-detail progress{width:100%;accent-color:#d7b465}.war-exchange-detail .promotion-calendar{min-width:0}.war-exchange-detail .fc{font-size:.85rem}.exchange-card-war .exchange-card-body img{object-fit:contain} +.war-province-map{background:#09221a;border:1px solid #b49550;padding:.7rem;border-radius:.45rem}.war-province-map-canvas{background-size:cover;background-position:center;border:2px solid #c8a75c;box-shadow:inset 0 0 25px #0009}.war-province-map svg{display:block;width:100%;height:auto}.war-province-cell{fill-opacity:.62;stroke:#eed99d;stroke-width:3;stroke-linejoin:round;transition:fill .4s;vector-effect:non-scaling-stroke}.war-province-cell[role="button"]{cursor:pointer}.war-province-cell[role="button"]:hover,.war-province-cell:focus{fill-opacity:.85;stroke:#fff2c8;outline:none}.war-province-number{font:700 23px Georgia,serif;fill:#fff2c8;stroke:#11271d;stroke-width:4;paint-order:stroke;text-anchor:middle;pointer-events:none}.war-province-legend{display:flex;flex-wrap:wrap;gap:.4rem 1rem}.war-province-legend p{display:flex;gap:.5rem;align-items:center}.war-province-swatch{display:inline-block;width:.85rem;height:.85rem;border:1px solid #e8d29d}.war-province-map>p:last-child{font-size:.8rem;color:#bdc9bd} diff --git a/website/control-panel/public/cp-v2/cp-v2-war-exchange.mjs b/website/control-panel/public/cp-v2/cp-v2-war-exchange.mjs index d7f1ea64..a9acd77c 100644 --- a/website/control-panel/public/cp-v2/cp-v2-war-exchange.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-war-exchange.mjs @@ -4,6 +4,7 @@ import {createProgressionDialog} from './cp-v2-progression-dialog.mjs'; import {calendarLibrary,electionDesignStyles} from './cp-v2-promotion-agenda.mjs'; import {createUserAPI} from './cp-v2-user-api.mjs'; import {WAR_MODES,WAR_BLOCK_MS,warPartyKey,warProposalFacts} from '../war-exchange-policy.mjs'; +import {createWarProvinceMap} from './cp-v2-war-map.mjs'; const endpoint='/api/war-exchange',date=n=>new Date(n).toLocaleString('en-GB',{timeZone:'UTC'})+' UTC'; export function mountWarExchange(host,{kind='clan',scopeId=null,fetcher=fetch}={}){ electionDesignStyles();const controller=new AbortController(),api=createUserAPI(fetcher,controller.signal); @@ -26,7 +27,9 @@ export function mountWarExchange(host,{kind='clan',scopeId=null,fetcher=fetch}={ 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;is.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);} pane.append(el('p','All sides choosing the same hour automatically schedules the war. No separate accept button is required.'),area,choice,confirm,withdraw); - if(proposal.state==='scheduled'){ + if(proposal.campaignReport){ + pane.append(el('p','Campaign: '+proposal.campaignReport.phase),createWarProvinceMap(proposal.campaignReport)); + }else if(proposal.state==='scheduled'){ 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); } diff --git a/website/control-panel/public/cp-v2/cp-v2-war-map.mjs b/website/control-panel/public/cp-v2/cp-v2-war-map.mjs new file mode 100644 index 00000000..8efe6c80 --- /dev/null +++ b/website/control-panel/public/cp-v2/cp-v2-war-map.mjs @@ -0,0 +1,27 @@ +import {warProvinceGeometry} from './cp-v2-war-province-geometry.mjs'; +const el=(tag,text)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;return n;}; +const svg=tag=>document.createElementNS('http://www.w3.org/2000/svg',tag); +const artwork={clan:'clan',world:'world',universal:'universal',religious:'universal'}; +export function createWarProvinceMap(report,{onProvince=null}={}){ + const root=el('section');root.className='war-province-map'; + const canvas=el('div');canvas.className='war-province-map-canvas'; + const map=svg('svg');map.setAttribute('viewBox','0 0 1000 560');map.setAttribute('role','group');map.setAttribute('aria-label','Campaign Home Block provinces'); + const mode=artwork[report.mode];if(!mode)throw TypeError('Unknown campaign map'); + canvas.style.backgroundImage='url("https://www.dunerealms.com/assets/war-maps/'+mode+'-frontier-v1.png")'; + const geometry=warProvinceGeometry(report.provinceCount),known=new Map(report.provinces.map(p=>[p.slot,p])); + for(const cell of geometry){ + const province=known.get(cell.slot),path=svg('path');path.setAttribute('d',cell.path);path.setAttribute('class','war-province-cell'); + path.setAttribute('fill',province&&/^#[a-f0-9]{6}$/i.test(province.color)?province.color:'#1b2925'); + if(province){ + const title=svg('title');title.textContent=province.name+' · '+(report.teams.find(t=>t.id===province.ownerSideId)?.name||'Unassigned');path.append(title); + if(onProvince){path.setAttribute('tabindex','0');path.setAttribute('role','button');path.setAttribute('aria-label',title.textContent);path.addEventListener('click',()=>onProvince(province));path.addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();onProvince(province);}});} + }else path.setAttribute('aria-hidden','true'); + map.append(path); + if(province){const label=svg('text');label.setAttribute('x',String(cell.x));label.setAttribute('y',String(cell.y));label.setAttribute('class','war-province-number');label.textContent=String(cell.slot+1);map.append(label);} + } + canvas.append(map);root.append(canvas); + const legend=el('div');legend.className='war-province-legend'; + for(const team of report.teams){const row=el('p'),dot=el('span');dot.className='war-province-swatch';if(/^#[a-f0-9]{6}$/i.test(team.color))dot.style.backgroundColor=team.color;row.append(dot,document.createTextNode(team.name+' · '+team.homeBlocks+'/'+team.totalHomeBlocks+' Home Blocks · '+team.progressPercent+'%'));legend.append(row);} + root.append(legend,el('p','Strategic provinces represent registered Home Blocks. This map does not reveal their world coordinates.')); + return root; +} diff --git a/website/control-panel/public/cp-v2/cp-v2-war-province-geometry.mjs b/website/control-panel/public/cp-v2/cp-v2-war-province-geometry.mjs new file mode 100644 index 00000000..bb870f87 --- /dev/null +++ b/website/control-panel/public/cp-v2/cp-v2-war-province-geometry.mjs @@ -0,0 +1,25 @@ +// Abstract strategic provinces, deliberately unrelated to Minecraft coordinates. +// Fixed slots keep borders still when the protected final province is revealed. +export function warProvinceGeometry(count){ + if(!Number.isInteger(count)||count<1||count>500)throw TypeError('Invalid province count'); + const columns=Math.ceil(Math.sqrt(count*1.8)),rows=Math.ceil(count/columns); + const points=Array.from({length:count},(_,i)=>{ + const x=i%columns,y=Math.floor(i/columns),noise=n=>((Math.imul(n+17,1103515245)>>>0)%997)/997; + return {x:1000*(x+.3+.4*noise(i))/columns,y:560*(y+.3+.4*noise(i+count))/rows}; + }); + return points.map((point,index)=>{ + let polygon=[[0,0],[1000,0],[1000,560],[0,560]]; + for(let j=0;j(i?'L':'M')+p.map(n=>n.toFixed(2)).join(',')).join(' ')+' Z'}; + }); +} diff --git a/website/control-panel/public/jarvis-master-keys.mjs b/website/control-panel/public/jarvis-master-keys.mjs index 7997a99f..9c91f7c7 100644 --- a/website/control-panel/public/jarvis-master-keys.mjs +++ b/website/control-panel/public/jarvis-master-keys.mjs @@ -4,7 +4,7 @@ export const STAFF_KEY_FIELDS=Object.freeze([{name:'ticketId',label:'Ban / suppo const action=(id,label,keyType,fields,extra={})=>({id,label,keyType,fields:[...STAFF_KEY_FIELDS,...fields],version:1,...extra}); const reference=field('reference','Reason / decision reference','text',{required:false}); export const MASTER_KEY_TEMPLATES=[ - {id:'war',label:'War Exchange',actions:[action('war.calendar-agreement','War proposal and calendar agreement','entity-state',[field('proposalId','Proposal UUID'),field('party','Current clan or political side'),field('mode','War mode'),field('startsAt','Shared calendar hour','number'),field('requestId','Request UUID')],{webIssue:false,recordOnly:true,domainAdapter:'createWarExchange',executionStatus:'authenticated-proposal-calendar-service',effect:'Separate proposal register; reuse Exchange cards and existing EVT calendar records. Only current named clan/POL authorities may choose their own hour. Two or three matching blocks schedule once; partial or different selections never schedule. Withdrawal cancels the linked event before start. No personal ownership transfer, live combat, money movement or invented capture progress.'})]}, + {id:'war',label:'War Exchange',actions:[action('war.calendar-agreement','War proposal and calendar agreement','entity-state',[field('proposalId','Proposal UUID'),field('party','Current clan or political side'),field('mode','War mode'),field('startsAt','Shared calendar hour','number'),field('requestId','Request UUID')],{webIssue:false,recordOnly:true,domainAdapter:'createWarExchange',executionStatus:'authenticated-proposal-calendar-service',effect:'Separate proposal register; reuse Exchange cards and existing EVT calendar records. Only current named clan/POL authorities may choose their own hour. Two or three matching blocks schedule once; partial or different selections never schedule. Withdrawal cancels the linked event before start. No personal ownership transfer, live combat, money movement or invented capture progress.'}),action('war.military-affiliation','MILCLAN temporary supermother','entity-state',[field('operationId','Campaign or appointment UUID'),field('childKind','Clan or company'),field('childId','Existing mother UUID'),field('parentId','Military mother UUID'),field('sourceKeyId','Verified political deed UUID'),field('requestId','Operation UUID')],{webIssue:false,recordOnly:true,domainAdapter:'attachWarSupermother/endWarSupermother',executionStatus:'internal-transaction-primitives-only',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. MILCLAN issuance and automatic office lifecycle are not connected yet; no website issuance or arbitrary parent writes.'}),action('war.homeblock-capture','Verified campaign province capture','entity-state',[field('campaignId','Prepared campaign UUID'),field('eventId','Native capture event UUID'),field('provinceId','Registered Home Block UUID'),field('claimRevision','Current claim revision','number'),field('expectedRevision','Campaign revision','number')],{webIssue:false,recordOnly:true,domainAdapter:'createWarCaptureService',executionStatus:'validated-model-and-storage-native-verifier-pending',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, update province colours and retain the protected Imperial final province. Native capture production and conquest deed settlement are not connected yet.'})]}, {id:'clan',label:'Clan',actions:[ action('clan.clear-protected-rosters','Clear protected clan rosters','clan-administration',[reference],{webIssue:true,permission:'web.jarvis.clans.reset',effect:'Remove members and owner from Vaerkring and Veiled Concord. Preserve clans, claims, POL and Crysknife.',fixedTargets:['Vaerkring','Veiled Concord']}), action('clan.original','Original clan charter','clan-founding',[]), diff --git a/website/integrations/osticket/dev-jarvis-catalogue.json b/website/integrations/osticket/dev-jarvis-catalogue.json index d5ec1564..452ca75d 100644 --- a/website/integrations/osticket/dev-jarvis-catalogue.json +++ b/website/integrations/osticket/dev-jarvis-catalogue.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "sourceHash": "7640b162917d2f778feb803af7b512bc51983512ed39a9ebd8a9a4290b4adb83", + "sourceHash": "ace6362337c5ed0b37dae4b5d33da402750b3e675fb723087622a50c0acfcc82", "actions": [ { "id": "war.calendar-agreement", @@ -51,6 +51,110 @@ "webIssue": false, "recordOnly": true }, + { + "id": "war.military-affiliation", + "label": "War Exchange · MILCLAN temporary supermother", + "version": 1, + "keyType": "entity-state", + "fields": [ + { + "name": "ticketId", + "label": "Ban / support ticket ID", + "type": "text", + "required": true, + "maxLength": 80 + }, + { + "name": "operationId", + "label": "Campaign or appointment UUID", + "type": "text", + "required": true + }, + { + "name": "childKind", + "label": "Clan or company", + "type": "text", + "required": true + }, + { + "name": "childId", + "label": "Existing mother UUID", + "type": "text", + "required": true + }, + { + "name": "parentId", + "label": "Military mother UUID", + "type": "text", + "required": true + }, + { + "name": "sourceKeyId", + "label": "Verified political deed UUID", + "type": "text", + "required": true + }, + { + "name": "requestId", + "label": "Operation UUID", + "type": "text", + "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. MILCLAN issuance and automatic office lifecycle are not connected yet; no website issuance or arbitrary parent writes.", + "fixedTargets": [], + "webIssue": false, + "recordOnly": true + }, + { + "id": "war.homeblock-capture", + "label": "War Exchange · Verified campaign province capture", + "version": 1, + "keyType": "entity-state", + "fields": [ + { + "name": "ticketId", + "label": "Ban / support ticket ID", + "type": "text", + "required": true, + "maxLength": 80 + }, + { + "name": "campaignId", + "label": "Prepared campaign UUID", + "type": "text", + "required": true + }, + { + "name": "eventId", + "label": "Native capture event UUID", + "type": "text", + "required": true + }, + { + "name": "provinceId", + "label": "Registered Home Block UUID", + "type": "text", + "required": true + }, + { + "name": "claimRevision", + "label": "Current claim revision", + "type": "number", + "required": true + }, + { + "name": "expectedRevision", + "label": "Campaign revision", + "type": "number", + "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, update province colours and retain the protected Imperial final province. Native capture production and conquest deed settlement are not connected yet.", + "fixedTargets": [], + "webIssue": false, + "recordOnly": true + }, { "id": "clan.clear-protected-rosters", "label": "Clan · Clear protected clan rosters", diff --git a/website/node/company-deeds.mjs b/website/node/company-deeds.mjs index 2daeaf3b..ca5c8e36 100644 --- a/website/node/company-deeds.mjs +++ b/website/node/company-deeds.mjs @@ -1,4 +1,5 @@ import {ENTITY_RELATION_SCHEMA,ENTITY_RELATION_GUARD_SCHEMA,entityParent,entityControllers} from './entity-relations.mjs'; +import {WAR_AFFILIATION_SCHEMA} from './war-affiliations.mjs'; import {COMPANY_ROYAL_MAIL_SCHEMA} from './company-royal-mail.mjs'; import {CLAIM_REGISTRY_SCHEMA} from './claim-registry.mjs'; import {JARVIS_COMPANY_REQUEST_SCHEMA} from './jarvis-request-domains.mjs'; @@ -9,6 +10,7 @@ import {clanMemberLimit} from './clan-membership-policy.mjs'; export const COMPANY_DEED_SCHEMA=[ ENTITY_RELATION_SCHEMA, ENTITY_RELATION_GUARD_SCHEMA, + WAR_AFFILIATION_SCHEMA, `CREATE TABLE IF NOT EXISTS site_company_institutions(company_id CHAR(36) PRIMARY KEY,institution_key VARCHAR(40) NOT NULL UNIQUE,FOREIGN KEY(company_id) REFERENCES corrino_companies(id))`, CLAIM_REGISTRY_SCHEMA, COMPANY_ROYAL_MAIL_SCHEMA, diff --git a/website/node/entity-relations.mjs b/website/node/entity-relations.mjs index 27b9bad2..fd8c6d16 100644 --- a/website/node/entity-relations.mjs +++ b/website/node/entity-relations.mjs @@ -26,7 +26,7 @@ export async function entityControllers(db,kind,id,{clock=Date.now}={}){ } // Internal transaction primitive: the caller must validate its deed/key and both parties. export async function setEntityParent(tx,{childKind,childId,parentKind,parentId,origin,keyId,requestId,actorId,now=Date.now()}){ - if(!['company','clan'].includes(childKind)||!['company','clan','politics'].includes(parentKind)||!uuid(childId)||!uuid(keyId)||!uuid(requestId)||!uuid(actorId)||!['created','purchase','submission','conquest','staff'].includes(origin)||parentKind!=='politics'&&!uuid(parentId)||parentKind==='politics'&&!PUBLIC_OFFICES.some(o=>o.key===parentId))throw TypeError('Invalid parent deed instruction'); + if(!['company','clan'].includes(childKind)||!['company','clan','politics'].includes(parentKind)||!uuid(childId)||!uuid(keyId)||!uuid(requestId)||!uuid(actorId)||!['created','purchase','submission','conquest','staff','war'].includes(origin)||parentKind!=='politics'&&!uuid(parentId)||parentKind==='politics'&&!PUBLIC_OFFICES.some(o=>o.key===parentId))throw TypeError('Invalid parent deed instruction'); if(!await tx.first('SELECT id FROM jarvis_entity_relation_guard WHERE id=1 FOR UPDATE'))throw Error('Entity relation guard unavailable'); const lock=await tx.first(childKind==='company'?'SELECT owner_account_id FROM site_company_deeds WHERE company_id=? FOR UPDATE':'SELECT owner_id FROM site_clans WHERE id=? AND active=1 FOR UPDATE',[childId]);if(!lock)throw Error('Child deed unavailable'); let next={kind:parentKind,id:parentId};const seen=new Set([childKind+':'+childId]); diff --git a/website/node/postbank-db.mjs b/website/node/postbank-db.mjs index 2cf1caf4..ae2e741c 100644 --- a/website/node/postbank-db.mjs +++ b/website/node/postbank-db.mjs @@ -1,3 +1,4 @@ +import {WAR_CAMPAIGN_SCHEMA} from './war-campaign-store.mjs'; import {WAR_EXCHANGE_SCHEMA} from './war-exchange.mjs'; import {GUILD_SCHEMA} from './game-guild.mjs'; import {HOME_SCHEMA} from './game-home.mjs'; @@ -23,7 +24,7 @@ export async function openPostbankDatabase(settings){ const pool=mysql.createPool({host:settings.BANK_DB_HOST||'127.0.0.1',port:Number(settings.BANK_DB_PORT||3306),database:name,user:settings.BANK_DB_USER,password:settings.BANK_DB_PASSWORD,connectionLimit:4,supportBigNumbers:true,bigNumberStrings:true,charset:'utf8mb4',connectTimeout:8000}); const api=c=>({async query(sql,args=[]){return(await c.execute(sql,args))[0];},async first(sql,args=[]){return(await c.execute(sql,args))[0][0]||null;}}); const db={async query(sql,args=[]){return(await pool.execute(sql,args))[0];},async first(sql,args=[]){return(await pool.execute(sql,args))[0][0]||null;},async transaction(work){const c=await pool.getConnection();try{await c.beginTransaction();const result=await work(api(c));await c.commit();return result;}catch(error){await c.rollback();throw error;}finally{c.release();}},async close(){await pool.end();}}; - try{for(const sql of(await readFile(new URL('./postbank-schema.sql',import.meta.url),'utf8')).split(';').map(s=>s.trim()).filter(Boolean))await db.query(sql);for(const sql of [...CLAIM_PRODUCT_SCHEMA,CLAIM_RESET_SCHEMA])await db.query(sql+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');await db.query(NETWORTH_SCHEMA);for(const sql of [...RIHLA_SCHEMA,...EVENT_SCHEMA,...WAR_EXCHANGE_SCHEMA,...CAMPAIGN_SCHEMA])await db.query(sql);await initializeJarvisListings(db);await db.query(DEED_PURCHASE_SCHEMA);await db.query(ESTATE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');await db.query(PROMOTION_DELIVERY_SCHEMA);for(const sql of POLITICAL_JOB_BANK_SCHEMA)await db.query(sql);await db.query(JARVIS_CHARGE_SCHEMA);await db.query(GUILD_SCHEMA);await db.query(HOME_SCHEMA);await ensureClaimBatchColumns(db);await ensureCreditColumns(db);await ensurePostbankIndexes(db);}catch(error){await pool.end();throw error;} + try{for(const sql of(await readFile(new URL('./postbank-schema.sql',import.meta.url),'utf8')).split(';').map(s=>s.trim()).filter(Boolean))await db.query(sql);for(const sql of [...CLAIM_PRODUCT_SCHEMA,CLAIM_RESET_SCHEMA])await db.query(sql+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');await db.query(NETWORTH_SCHEMA);for(const sql of [...RIHLA_SCHEMA,...EVENT_SCHEMA,...WAR_EXCHANGE_SCHEMA,WAR_CAMPAIGN_SCHEMA,...CAMPAIGN_SCHEMA])await db.query(sql);await initializeJarvisListings(db);await db.query(DEED_PURCHASE_SCHEMA);await db.query(ESTATE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');await db.query(PROMOTION_DELIVERY_SCHEMA);for(const sql of POLITICAL_JOB_BANK_SCHEMA)await db.query(sql);await db.query(JARVIS_CHARGE_SCHEMA);await db.query(GUILD_SCHEMA);await db.query(HOME_SCHEMA);await ensureClaimBatchColumns(db);await ensureCreditColumns(db);await ensurePostbankIndexes(db);}catch(error){await pool.end();throw error;} return db; } diff --git a/website/node/war-affiliations.mjs b/website/node/war-affiliations.mjs new file mode 100644 index 00000000..cbab5d0d --- /dev/null +++ b/website/node/war-affiliations.mjs @@ -0,0 +1,50 @@ +import {randomUUID} from 'node:crypto'; +import {entityParent,setEntityParent} from './entity-relations.mjs'; + +export const WAR_AFFILIATION_SCHEMA=`CREATE TABLE IF NOT EXISTS jarvis_war_affiliations(operation_id CHAR(36) NOT NULL,child_kind VARCHAR(12) NOT NULL,child_id CHAR(36) NOT NULL,parent_kind VARCHAR(12) NOT NULL,parent_id VARCHAR(36) NOT NULL,key_id CHAR(36) NOT NULL,installed_request_id CHAR(36) NOT NULL UNIQUE,previous_json TEXT NOT NULL,state VARCHAR(16) NOT NULL,created_at BIGINT NOT NULL,ended_at BIGINT NULL,PRIMARY KEY(operation_id,child_kind,child_id))`; +const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v); +const invalid=message=>{throw Object.assign(Error(message),{status:409});}; +async function guard(tx){if(!await tx.first('SELECT id FROM jarvis_entity_relation_guard WHERE id=1 FOR UPDATE'))throw Error('Entity relation guard unavailable');} +async function previousParent(tx,kind,id){ + const current=await entityParent(tx,kind,id);if(current)return current; + if(kind==='company'){const old=await tx.first('SELECT parent_company_id,relation_origin FROM site_company_relations WHERE company_id=?',[id]);return old?{parent_kind:'company',parent_id:old.parent_company_id,relation_origin:old.relation_origin}:null;} + const old=await tx.first('SELECT parent_clan_id FROM site_clan_deeds WHERE clan_id=?',[id]);return old?.parent_clan_id?{parent_kind:'clan',parent_id:old.parent_clan_id,relation_origin:'created'}:null; +} + +// Transaction primitives, not web actions. The campaign/office adapter must +// validate the live MILCLAN deed and authority before calling either function. +// Attach the existing mother only; every original nested child link stays intact. +export async function attachWarSupermother(tx,{operationId,childKind,childId,parentKind,parentId,keyId,requestId,actorId,now=Date.now()}){ + if(!uuid(operationId)||!['clan','company'].includes(childKind)||childKind!==parentKind)invalid('A military affiliation requires matching organisation kinds.'); + await guard(tx); + const prior=await tx.first('SELECT * FROM jarvis_war_affiliations WHERE operation_id=? AND child_kind=? AND child_id=? FOR UPDATE',[operationId,childKind,childId]); + if(prior){if(prior.parent_kind!==parentKind||prior.parent_id!==parentId||prior.key_id!==keyId||prior.installed_request_id!==requestId)invalid('Military affiliation reference conflict.');return {state:prior.state,replayed:true};} + const previous=await previousParent(tx,childKind,childId); + if(previous?.parent_kind===parentKind&&previous.parent_id===parentId)invalid('The organisation already belongs to that mother.'); + if(previous?.relation_origin==='war')invalid('End the existing military affiliation first.'); + await setEntityParent(tx,{childKind,childId,parentKind,parentId,origin:'war',keyId,requestId,actorId,now}); + await tx.query("INSERT INTO jarvis_war_affiliations VALUES(?,?,?,?,?,?,?,?,'active',?,NULL)",[operationId,childKind,childId,parentKind,parentId,keyId,requestId,JSON.stringify(previous),now]); + return {state:'active',replayed:false}; +} + +export async function endWarSupermother(tx,{operationId,childKind,childId,actorId,now=Date.now()}){ + if(!uuid(operationId)||!uuid(actorId)||!['clan','company'].includes(childKind)||!uuid(childId))invalid('Invalid military affiliation.'); + await guard(tx); + const row=await tx.first('SELECT * FROM jarvis_war_affiliations WHERE operation_id=? AND child_kind=? AND child_id=? FOR UPDATE',[operationId,childKind,childId]); + if(!row)invalid('Military affiliation not found.'); + if(row.state!=='active')return {state:row.state,replayed:true}; + const current=await entityParent(tx,childKind,childId); + const owned=current?.request_id===row.installed_request_id&¤t.key_id===row.key_id&¤t.relation_origin==='war'&¤t.parent_kind===row.parent_kind&¤t.parent_id===row.parent_id; + if(!owned){await tx.query("UPDATE jarvis_war_affiliations SET state='superseded',ended_at=? WHERE operation_id=? AND child_kind=? AND child_id=?",[now,operationId,childKind,childId]);return {state:'superseded',replayed:false};} + const previous=JSON.parse(row.previous_json); + if(previous){ + await setEntityParent(tx,{childKind,childId,parentKind:previous.parent_kind,parentId:previous.parent_id,origin:previous.relation_origin||'created',keyId:previous.key_id||row.key_id,requestId:randomUUID(),actorId,now}); + }else{ + await tx.query('DELETE FROM jarvis_entity_relations WHERE child_kind=? AND child_id=?',[childKind,childId]); + if(childKind==='company'){await tx.query('DELETE FROM site_company_relations WHERE company_id=?',[childId]);await tx.query('UPDATE site_company_deeds SET version=version+1,updated_at=? WHERE company_id=?',[now,childId]);} + else await tx.query('UPDATE site_clan_deeds SET parent_clan_id=NULL,version=version+1,updated_at=? WHERE clan_id=?',[now,childId]); + } + await tx.query('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),actorId,'war-affiliation-ended',JSON.stringify({operationId,childKind,childId,keyId:row.key_id,restored:previous?{kind:previous.parent_kind,id:previous.parent_id}:null}),now]); + await tx.query("UPDATE jarvis_war_affiliations SET state='restored',ended_at=? WHERE operation_id=? AND child_kind=? AND child_id=?",[now,operationId,childKind,childId]); + return {state:'restored',replayed:false}; +} diff --git a/website/node/war-campaign-model.mjs b/website/node/war-campaign-model.mjs index 70118703..ae68b85d 100644 --- a/website/node/war-campaign-model.mjs +++ b/website/node/war-campaign-model.mjs @@ -5,12 +5,13 @@ export const IMPERIAL_PROVINCE_COLOR='#9855c5'; const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v); const reject=message=>{throw Object.assign(Error(message),{status:409});}; const clone=value=>structuredClone(value); +const homeChunk=home=>({x:Math.floor(home.position.x/16),z:Math.floor(home.position.z/16)}); // 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}){ const policy=WAR_MODES[mode]; - if(!uuid(id)||!policy||!Number.isSafeInteger(startsAt)||endsAt!==startsAt+3600000||!Array.isArray(teams)||teams.length!==policy.parties||!Array.isArray(provinces)||!provinces.length||provinces.length>500)reject('Invalid campaign snapshot.'); + 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(); for(const team of teams){ if(typeof team.id!=='string'||!/^[a-z0-9_-]{1,36}$/i.test(team.id)||sideIds.has(team.id)||typeof team.name!=='string'||!team.name.trim()||!Array.isArray(team.roster)||!team.roster.length||team.roster.length>policy.playersPerSide)reject('Review campaign sides and roster limits.'); @@ -20,8 +21,8 @@ export function createWarCampaign({id,mode,startsAt,endsAt,teams,provinces}){ const identities=new Set(),homes=new Set();let imperial=0; for(const province of provinces){ const home=province.homeBlock,identity=province.kind+':'+province.organisationId; - if(!['clan','protected'].includes(province.kind)||!uuid(province.id)||identities.has(identity)||!uuid(province.organisationId)||!sideIds.has(province.sideId)||!uuid(province.deedKeyId)||!Number.isSafeInteger(province.claimRevision)||province.claimRevision<1||!home||!uuid(home.worldUuid)||!Number.isSafeInteger(home.chunkX)||!Number.isSafeInteger(home.chunkZ)||typeof province.server!=='string'||!['caladan','arrakis','kaitain','giedi-prime','sigma-draconis-iv'].includes(province.server))reject('A province requires its verified Home Block and deed.'); - const location=home.worldUuid.toLowerCase()+':'+home.chunkX+':'+home.chunkZ; + if(!['clan','protected'].includes(province.kind)||!uuid(province.id)||typeof province.name!=='string'||!province.name.trim()||identities.has(identity)||!uuid(province.organisationId)||!sideIds.has(province.sideId)||!uuid(province.deedKeyId)||!Number.isSafeInteger(province.claimRevision)||province.claimRevision<1||!home||home.id!==province.id||home.source!=='minecraft'||!uuid(home.worldUuid)||!['x','y','z'].every(k=>Number.isSafeInteger(home.position?.[k]))||typeof province.server!=='string'||!['caladan','arrakis','kaitain','giedi-prime','sigma-draconis-iv'].includes(province.server))reject('A province requires its verified Home Block and deed.'); + const chunk=homeChunk(home),location=home.worldUuid.toLowerCase()+':'+chunk.x+':'+chunk.z; if(homes.has(location))reject('Two provinces cannot share one Home Block.');homes.add(location);identities.add(identity); if(province.imperial){imperial++;if(mode==='clan')reject('The Emperor cannot intervene in a clan war.');} } @@ -37,7 +38,7 @@ export function imperialProvinceLocked(campaign,province){ } export function campaignPhase(campaign,now=Date.now()){ - return campaign.winnerSideId?'completed':now=campaign.endsAt?'expired':'active'; + return campaign.cancelledAt!=null?'cancelled':campaign.winnerSideId?'completed':now=campaign.endsAt?'expired':'active'; } // A trusted native capture producer must already have checked physical position, @@ -54,7 +55,8 @@ export function captureWarProvince(campaign,{eventId,playerUuid,provinceId,serve const team=campaign.teams.find(t=>t.roster.some(p=>p.uuid===playerUuid)); const province=campaign.provinces.find(p=>p.id===provinceId); if(!team||!province||province.ownerSideId===team.id||imperialProvinceLocked(campaign,province))reject('This player cannot capture that province.'); - if(province.server!==server||province.homeBlock.worldUuid!==worldUuid||province.homeBlock.chunkX!==chunkX||province.homeBlock.chunkZ!==chunkZ||province.claimRevision!==claimRevision)reject('The registered Home Block changed.'); + const chunk=homeChunk(province.homeBlock); + if(province.server!==server||province.homeBlock.worldUuid!==worldUuid||chunk.x!==chunkX||chunk.z!==chunkZ||province.claimRevision!==claimRevision)reject('The registered Home Block changed.'); const next=clone(campaign),target=next.provinces.find(p=>p.id===provinceId); target.ownerSideId=team.id;next.revision++; next.captures.push({eventId,playerUuid,provinceId,server,worldUuid,chunkX,chunkZ,claimRevision,sideId:team.id,capturedAt:now}); @@ -65,5 +67,6 @@ export function captureWarProvince(campaign,{eventId,playerUuid,provinceId,serve export function warCampaignReport(campaign,now=Date.now()){ return {id:campaign.id,mode:campaign.mode,phase:campaignPhase(campaign,now),revision:campaign.revision,startsAt:campaign.startsAt,endsAt:campaign.endsAt,winnerSideId:campaign.winnerSideId, teams:campaign.teams.map((t,i)=>({id:t.id,name:t.name,color:WAR_SIDE_COLORS[i],players:t.roster.length,capacity:WAR_MODES[campaign.mode].playersPerSide,homeBlocks:campaign.provinces.filter(p=>p.ownerSideId===t.id).length,totalHomeBlocks:campaign.provinces.length,progressPercent:Math.round(100*campaign.provinces.filter(p=>p.ownerSideId===t.id).length/campaign.provinces.length)})), - provinces:campaign.provinces.filter(p=>!imperialProvinceLocked(campaign,p)).map(p=>({id:p.id,name:p.name,ownerSideId:p.ownerSideId,imperial:!!p.imperial,color:p.imperial&&p.ownerSideId===p.sideId?IMPERIAL_PROVINCE_COLOR:WAR_SIDE_COLORS[campaign.teams.findIndex(t=>t.id===p.ownerSideId)]}))}; + provinceCount:campaign.provinces.length, + provinces:campaign.provinces.map((p,slot)=>({...p,slot})).filter(p=>!imperialProvinceLocked(campaign,p)).map(p=>({id:p.id,name:p.name,slot:p.slot,ownerSideId:p.ownerSideId,imperial:!!p.imperial,color:p.imperial&&p.ownerSideId===p.sideId?IMPERIAL_PROVINCE_COLOR:WAR_SIDE_COLORS[campaign.teams.findIndex(t=>t.id===p.ownerSideId)]}))}; } diff --git a/website/node/war-campaign-store.mjs b/website/node/war-campaign-store.mjs new file mode 100644 index 00000000..fcdf6aca --- /dev/null +++ b/website/node/war-campaign-store.mjs @@ -0,0 +1,43 @@ +import {createWarCampaign,captureWarProvince,warCampaignReport} from './war-campaign-model.mjs'; +import {warPartyKey} from '../control-panel/public/war-exchange-policy.mjs'; +export const WAR_CAMPAIGN_SCHEMA=`CREATE TABLE IF NOT EXISTS jarvis_war_campaigns(id CHAR(36) PRIMARY KEY,snapshot_json MEDIUMTEXT NOT NULL,revision INTEGER NOT NULL,starts_at BIGINT NOT NULL,ends_at BIGINT NOT NULL,updated_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`; +const conflict=message=>{throw Object.assign(Error(message),{status:409});}; + +// Only a server-side domain resolver may prepare this snapshot. It must resolve +// current claims, rosters and MILCLAN deeds; no website endpoint accepts it. +export async function prepareWarCampaign(tx,proposal,snapshot,now=Date.now()){ + if(proposal.state!=='scheduled'||!proposal.block||proposal.block.startsAt<=now)conflict('Agree a future calendar block before preparing deployment.'); + if(snapshot.teams.length!==proposal.parties.length||snapshot.teams.some((t,i)=>!t.party||warPartyKey(t.party)!==warPartyKey(proposal.parties[i])))conflict('Campaign sides must match the agreed proposal.'); + const campaign=createWarCampaign({...snapshot,id:proposal.id,mode:proposal.mode,...proposal.block}); + const previous=await tx.first('SELECT * FROM jarvis_war_campaigns WHERE id=? FOR UPDATE',[campaign.id]); + if(previous){const recorded=JSON.parse(previous.snapshot_json);if(recorded.revision!==1||JSON.stringify(recorded)!==JSON.stringify(campaign))conflict('Deployment already has a different verified snapshot.');return {campaign:recorded,replayed:true};} + await tx.query('INSERT INTO jarvis_war_campaigns VALUES(?,?,?,?,?,?)',[campaign.id,JSON.stringify(campaign),campaign.revision,campaign.startsAt,campaign.endsAt,now]); + return {campaign,replayed:false}; +} + +export async function readWarCampaignReport(store,id,now=Date.now()){ + const row=await store.first('SELECT snapshot_json FROM jarvis_war_campaigns WHERE id=?',[id]); + return row?warCampaignReport(JSON.parse(row.snapshot_json),now):null; +} + +export async function cancelPreparedWarCampaign(tx,id,now=Date.now()){ + const row=await tx.first('SELECT * FROM jarvis_war_campaigns WHERE id=? FOR UPDATE',[id]);if(!row)return; + const campaign=JSON.parse(row.snapshot_json);if(campaign.cancelledAt!=null)return; + if(now>=campaign.startsAt||campaign.winnerSideId)conflict('Use active campaign controls after deployment starts.'); + campaign.cancelledAt=now;campaign.revision++; + await tx.query('UPDATE jarvis_war_campaigns SET snapshot_json=?,revision=?,updated_at=? WHERE id=?',[JSON.stringify(campaign),campaign.revision,now,id]); +} + +// The native producer's identity, position, source server and current deed/claim +// must be revalidated by verifyCapture. No verifier means no capture adapter. +export function createWarCaptureService(store,{verifyCapture,clock=Date.now}={}){ + if(typeof verifyCapture!=='function')throw TypeError('A current native capture verifier is required.'); + return async(id,event)=>store.transaction(async tx=>{ + const row=await tx.first('SELECT * FROM jarvis_war_campaigns WHERE id=? FOR UPDATE',[id]);if(!row)conflict('Campaign deployment not found.'); + const campaign=JSON.parse(row.snapshot_json); + if(await verifyCapture(campaign,event)!==true)conflict('The native capture could not be verified.'); + const result=captureWarProvince(campaign,event,clock()); + if(!result.replayed)await tx.query('UPDATE jarvis_war_campaigns SET snapshot_json=?,revision=?,updated_at=? WHERE id=?',[JSON.stringify(result.campaign),result.campaign.revision,clock(),id]); + return {report:warCampaignReport(result.campaign,clock()),replayed:result.replayed}; + }); +} diff --git a/website/node/war-exchange.mjs b/website/node/war-exchange.mjs index c921d02b..84e985b3 100644 --- a/website/node/war-exchange.mjs +++ b/website/node/war-exchange.mjs @@ -2,6 +2,7 @@ import {randomUUID,createHash} from 'node:crypto'; import {identity} from './auth.mjs'; import {createEventAuthority,eventInput} from './jarvis-events.mjs'; import {createRealmEventRecord} from './realm-event-records.mjs'; +import {readWarCampaignReport,cancelPreparedWarCampaign} from './war-campaign-store.mjs'; import {PUBLIC_OFFICES} from './public-government.mjs'; import {WAR_BLOCK_MS,WAR_MODES,warPartyKey,agreedWarBlock} from '../control-panel/public/war-exchange-policy.mjs'; export const WAR_EXCHANGE_SCHEMA=[ @@ -38,7 +39,7 @@ export function createWarExchange(central,store,{authenticate=r=>identity(r,cent if(kind&&id&&!contexts.some(p=>p.kind===kind&&p.id===id))fail('Current clan or political deed required.',403); const proposals=await store.query('SELECT * FROM jarvis_war_proposals ORDER BY created_at DESC,id LIMIT 501');if(proposals.length>500)fail('Narrow the war proposal register.',409); const visible=proposals.filter(r=>JSON.parse(r.parties_json).some(p=>warPartyKey(p)===warPartyKey(context))),result=[]; - for(const p of visible)result.push(project(p,await store.query('SELECT * FROM jarvis_war_slots WHERE proposal_id=?',[p.id]))); + for(const p of visible){const proposal=project(p,await store.query('SELECT * FROM jarvis_war_slots WHERE proposal_id=?',[p.id]));proposal.campaignReport=await readWarCampaignReport(store,p.id,clock());result.push(proposal);} return reply({contexts,parties:choices,proposals:result,context,canManage:true,blockMinutes:60}); } if(request.method!=='POST')return reply({message:'Method not allowed.'},405); @@ -79,6 +80,7 @@ export function createWarExchange(central,store,{authenticate=r=>identity(r,cent if(Number(current.revision)!==input.revision||!['open','scheduled'].includes(current.state))fail('Proposal changed. Refresh before responding.',409); if(input.action==='withdraw'){ const block=agreedWarBlock(members,rows(selected));if(block&&block.startsAt<=clock())fail('A started war must use its war controls.',409); + await cancelPreparedWarCampaign(tx,current.id,clock()); if(current.calendar_event_id){await tx.query("UPDATE jarvis_events SET state='cancelled',revision=revision+1,updated_at=? WHERE id=? AND state='scheduled'",[clock(),current.calendar_event_id]);await tx.query('INSERT INTO jarvis_event_history VALUES(?,?,?,?,?)',[randomUUID(),current.calendar_event_id,actor.id,'cancel',clock()]);} await tx.query("UPDATE jarvis_war_proposals SET state='cancelled',revision=revision+1,updated_at=? WHERE id=?",[clock(),current.id]);await audit(tx,current.id,actor,'withdrawn',{party:input.party,requestId:input.requestId}); }else{ diff --git a/website/tests/war-affiliations.test.mjs b/website/tests/war-affiliations.test.mjs new file mode 100644 index 00000000..9a3f8992 --- /dev/null +++ b/website/tests/war-affiliations.test.mjs @@ -0,0 +1,67 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {randomUUID} from 'node:crypto'; +import {companyFixture} from './company-deed-fixture.mjs'; +import {entityParent,setEntityParent} from '../node/entity-relations.mjs'; +import {attachWarSupermother,endWarSupermother} from '../node/war-affiliations.mjs'; + +async function rig(){ + const f=await companyFixture();f.db.sqlite.exec('CREATE TABLE account_audit(id TEXT PRIMARY KEY,actor_id TEXT,action TEXT,details TEXT,created_at INTEGER)'); + const mother=await f.create();await f.db.query("UPDATE site_company_deeds SET charter_kind='royal' WHERE company_id=?",[mother]); + async function organisation(){const id=randomUUID(),now=Date.now();await f.db.query("INSERT INTO corrino_companies(id,slug,name,description,founded_by,status,created_at,updated_at) VALUES(?,?,?,'A chartered company',?,'active',?,?)",[id,id,'Company '+id,f.people.Other.id,now,now]);await f.db.query("INSERT INTO site_company_deeds(company_id,owner_account_id,charter_kind,version,created_at,updated_at) VALUES(?,?,'royal',1,?,?)",[id,f.people.Other.id,now,now]);return id;} + const military=await organisation(),client=await organisation(),other=await organisation(); + const link=(child,parent,origin='staff')=>f.db.transaction(tx=>setEntityParent(tx,{childKind:'company',childId:child,parentKind:'company',parentId:parent,origin,keyId:randomUUID(),requestId:randomUUID(),actorId:f.people.Owner.id})); + await link(client,mother); + const instruction={operationId:randomUUID(),childKind:'company',childId:mother,parentKind:'company',parentId:military,keyId:randomUUID(),requestId:randomUUID(),actorId:f.people.Owner.id}; + const attach=()=>f.db.transaction(tx=>attachWarSupermother(tx,instruction)),end=()=>f.db.transaction(tx=>endWarSupermother(tx,instruction)); + return {...f,mother,military,client,other,instruction,link,attach,end}; +} +test('military supermother preserves owners and the entire existing client branch; ordinary end removes only its link',async()=>{ + const f=await rig();try{ + const owner=await f.db.first('SELECT * FROM site_company_deeds WHERE company_id=?',[f.mother]),client=await entityParent(f.db,'company',f.client); + assert.equal((await f.attach()).state,'active');assert.equal((await f.attach()).replayed,true); + assert.equal((await entityParent(f.db,'company',f.mother)).parent_id,f.military); + assert.deepEqual(await entityParent(f.db,'company',f.client),client); + assert.equal((await f.db.first('SELECT owner_account_id FROM site_company_deeds WHERE company_id=?',[f.mother])).owner_account_id,owner.owner_account_id); + assert.equal((await f.end()).state,'restored');assert.equal(await entityParent(f.db,'company',f.mother),null); + assert.equal(await f.db.first('SELECT * FROM site_company_relations WHERE company_id=?',[f.mother]),null); + assert.deepEqual(await entityParent(f.db,'company',f.client),client);assert.equal((await f.end()).replayed,true); + }finally{f.db.close();} +}); +test('an original mother relationship is restored without flattening its descendants',async()=>{ + const f=await rig();try{ + await f.link(f.mother,f.other);await f.attach();await f.end(); + assert.equal((await entityParent(f.db,'company',f.mother)).parent_id,f.other); + assert.equal((await entityParent(f.db,'company',f.client)).parent_id,f.mother); + }finally{f.db.close();} +}); +test('war cleanup never reverses a later settled conquest or purchase',async()=>{ + const f=await rig();try{ + await f.attach();await f.link(f.mother,f.other,'conquest');const conquest=await entityParent(f.db,'company',f.mother); + assert.equal((await f.end()).state,'superseded');assert.deepEqual(await entityParent(f.db,'company',f.mother),conquest); + assert.equal((await entityParent(f.db,'company',f.client)).parent_id,f.mother); + }finally{f.db.close();} +}); +test('altered retries and nested temporary affiliations cannot replace a current military link',async()=>{ + const f=await rig();try{ + await f.attach();const current=await entityParent(f.db,'company',f.mother); + await assert.rejects(f.db.transaction(tx=>attachWarSupermother(tx,{...f.instruction,parentId:f.other})),/reference conflict/); + await assert.rejects(f.db.transaction(tx=>attachWarSupermother(tx,{...f.instruction,operationId:randomUUID(),requestId:randomUUID(),parentId:f.other})),/End the existing/); + assert.deepEqual(await entityParent(f.db,'company',f.mother),current); + }finally{f.db.close();} +}); + +test('clan supermother also retains nested clients and the original owner through cleanup',async()=>{ + const f=await companyFixture();try{ + f.db.sqlite.exec('CREATE TABLE account_audit(id TEXT PRIMARY KEY,actor_id TEXT,action TEXT,details TEXT,created_at INTEGER);CREATE TABLE site_clan_charters(clan_id TEXT PRIMARY KEY,charter_kind TEXT);CREATE TABLE site_clan_deeds(clan_id TEXT PRIMARY KEY,parent_clan_id TEXT,version INTEGER,updated_at INTEGER)'); + const [mother,military,client]=[randomUUID(),randomUUID(),randomUUID()]; + for(const id of [mother,military,client]){await f.db.query('INSERT INTO site_clans(id,name,owner_id,active) VALUES(?,?,?,1)',[id,id,f.people.Owner.id]);await f.db.query("INSERT INTO site_clan_charters VALUES(?,'royal')",[id]);await f.db.query('INSERT INTO site_clan_deeds VALUES(?,NULL,1,0)',[id]);} + const base={childKind:'clan',parentKind:'clan',keyId:randomUUID(),requestId:randomUUID(),actorId:f.people.Owner.id}; + await f.db.transaction(tx=>setEntityParent(tx,{...base,childId:client,parentId:mother,origin:'created'})); + const instruction={...base,requestId:randomUUID(),operationId:randomUUID(),childId:mother,parentId:military}; + await f.db.transaction(tx=>attachWarSupermother(tx,instruction));assert.equal((await entityParent(f.db,'clan',client)).parent_id,mother); + await f.db.transaction(tx=>endWarSupermother(tx,instruction));assert.equal(await entityParent(f.db,'clan',mother),null); + assert.equal((await f.db.first('SELECT owner_id FROM site_clans WHERE id=?',[mother])).owner_id,f.people.Owner.id); + assert.equal((await f.db.first('SELECT parent_clan_id FROM site_clan_deeds WHERE clan_id=?',[client])).parent_clan_id,mother); + }finally{f.db.close();} +}); diff --git a/website/tests/war-campaign-model.test.mjs b/website/tests/war-campaign-model.test.mjs index 2f07466d..b56df445 100644 --- a/website/tests/war-campaign-model.test.mjs +++ b/website/tests/war-campaign-model.test.mjs @@ -5,14 +5,14 @@ import {createWarCampaign,captureWarProvince,warCampaignReport,campaignPhase} fr const startsAt=3600000,now=startsAt+1000; function fixture(mode='clan'){ const teams=Array.from({length:['universal','religious'].includes(mode)?3:2},(_,i)=>({id:'side-'+i,name:'Side '+i,roster:[{uuid:randomUUID()}]})); - const province=(sideId,imperial=false)=>({id:randomUUID(),kind:imperial?'protected':'clan',organisationId:randomUUID(),name:'Home Block',sideId,deedKeyId:randomUUID(),claimRevision:1,server:'arrakis',homeBlock:{worldUuid:randomUUID(),chunkX:0,chunkZ:0},imperial}); + const province=(sideId,imperial=false)=>{const id=randomUUID();return {id,kind:imperial?'protected':'clan',organisationId:randomUUID(),name:'Home Block',sideId,deedKeyId:randomUUID(),claimRevision:1,server:'arrakis',homeBlock:{id,source:'minecraft',worldUuid:randomUUID(),position:{x:0,y:64,z:0}},imperial};}; const provinces=teams.map(t=>province(t.id));if(['universal','religious'].includes(mode))provinces.push(province(teams[0].id,true)); const input={id:randomUUID(),mode,startsAt,endsAt:startsAt+3600000,teams,provinces}; return {input,campaign:createWarCampaign(input),teams,provinces}; } function receipt(campaign,provinceId,side=0){ const p=campaign.provinces.find(p=>p.id===provinceId); - return {eventId:randomUUID(),playerUuid:campaign.teams[side].roster[0].uuid,provinceId,server:p.server,...p.homeBlock,claimRevision:p.claimRevision,expectedRevision:campaign.revision}; + return {eventId:randomUUID(),playerUuid:campaign.teams[side].roster[0].uuid,provinceId,server:p.server,worldUuid:p.homeBlock.worldUuid,chunkX:Math.floor(p.homeBlock.position.x/16),chunkZ:Math.floor(p.homeBlock.position.z/16),claimRevision:p.claimRevision,expectedRevision:campaign.revision}; } test('campaigns enforce their agreed roster caps and reject ambiguous team membership',()=>{ for(const [mode,cap] of [['clan',8],['world',16],['universal',86],['religious',86]]){ @@ -54,5 +54,5 @@ test('Imperial intervention is forbidden in clan wars and does not hide a world- }); test('an expired campaign does not invent a victory or transfer deeds',()=>{ const {campaign}=fixture();assert.equal(campaignPhase(campaign,campaign.endsAt),'expired');assert.equal(warCampaignReport(campaign,campaign.endsAt).winnerSideId,null); - const invalid=fixture();invalid.input.provinces[1].homeBlock=structuredClone(invalid.input.provinces[0].homeBlock);assert.throws(()=>createWarCampaign(invalid.input),/share one Home Block/); + const invalid=fixture();invalid.input.provinces[1].homeBlock={...structuredClone(invalid.input.provinces[0].homeBlock),id:invalid.input.provinces[1].id};assert.throws(()=>createWarCampaign(invalid.input),/share one Home Block/); }); diff --git a/website/tests/war-campaign-store.test.mjs b/website/tests/war-campaign-store.test.mjs new file mode 100644 index 00000000..826c7b57 --- /dev/null +++ b/website/tests/war-campaign-store.test.mjs @@ -0,0 +1,50 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {randomUUID} from 'node:crypto'; +import {BankFixture} from './postbank-fixture.mjs'; +import {WAR_CAMPAIGN_SCHEMA,prepareWarCampaign,readWarCampaignReport,createWarCaptureService,cancelPreparedWarCampaign} from '../node/war-campaign-store.mjs'; +import {warProvinceGeometry} from '../control-panel/public/cp-v2/cp-v2-war-province-geometry.mjs'; +const now=3600000; +async function fixture(){ + const store=new BankFixture();await store.query(WAR_CAMPAIGN_SCHEMA.replace(' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4','')); + const parties=[0,1].map(()=>({kind:'clan',id:randomUUID()})); + const proposal={id:randomUUID(),state:'scheduled',mode:'clan',parties,block:{startsAt:now+3600000,endsAt:now+7200000}}; + const snapshot={teams:parties.map((party,i)=>({id:'side-'+i,name:'Side '+i,party,roster:[{uuid:randomUUID()}]})),provinces:parties.map((p,i)=>{const id=randomUUID();return {id,kind:'clan',organisationId:p.id,name:'Home',sideId:'side-'+i,deedKeyId:randomUUID(),claimRevision:2,server:'arrakis',homeBlock:{id,source:'minecraft',worldUuid:randomUUID(),position:{x:i*16,y:64,z:0}}};})}; + return {store,proposal,snapshot,prepare:()=>store.transaction(tx=>prepareWarCampaign(tx,proposal,snapshot,now))}; +} +test('only an agreed future block and its exact named sides can prepare a deployment',async()=>{ + const f=await fixture();try{ + assert.equal((await f.prepare()).replayed,false);assert.equal((await f.prepare()).replayed,true); + assert.equal((await readWarCampaignReport(f.store,f.proposal.id,now)).phase,'scheduled'); + f.snapshot.teams[0].party={kind:'clan',id:randomUUID()};await assert.rejects(f.prepare(),/match the agreed/); + }finally{f.store.close();} +}); +test('capture verifier and durable campaign revision prevent unverified effects and duplicate progress',async()=>{ + const f=await fixture();try{ + const {campaign}=await f.prepare(),p=campaign.provinces[1]; + const event={eventId:randomUUID(),playerUuid:campaign.teams[0].roster[0].uuid,provinceId:p.id,server:p.server,worldUuid:p.homeBlock.worldUuid,chunkX:Math.floor(p.homeBlock.position.x/16),chunkZ:Math.floor(p.homeBlock.position.z/16),claimRevision:p.claimRevision,expectedRevision:1}; + assert.throws(()=>createWarCaptureService(f.store),/verifier/); + const denied=createWarCaptureService(f.store,{clock:()=>campaign.startsAt+1,verifyCapture:async()=>false});await assert.rejects(denied(campaign.id,event),/could not be verified/); + assert.equal((await readWarCampaignReport(f.store,campaign.id)).revision,1); + const service=createWarCaptureService(f.store,{clock:()=>campaign.startsAt+1,verifyCapture:async()=>true}); + assert.equal((await service(campaign.id,event)).report.winnerSideId,'side-0');assert.equal((await service(campaign.id,event)).replayed,true); + assert.equal((await readWarCampaignReport(f.store,campaign.id)).revision,2); + }finally{f.store.close();} +}); +test('province geometry covers the whole strategic map without overlaps or moving slot assignments',()=>{ + for(const count of [1,2,3,12,40]){ + const cells=warProvinceGeometry(count);assert.deepEqual(cells,warProvinceGeometry(count));assert.equal(cells.length,count); + let area=0; + for(const cell of cells){const points=[...cell.path.matchAll(/[ML]([\d.]+),([\d.]+)/g)].map(m=>[Number(m[1]),Number(m[2])]);assert.ok(points.length>=3);area+=Math.abs(points.reduce((sum,p,i)=>{const q=points[(i+1)%points.length];return sum+p[0]*q[1]-q[0]*p[1];},0)/2);} + assert.ok(Math.abs(area-560000)<25,'Provinces must partition the complete map.'); + } +}); + +test('withdrawing a prepared future campaign prevents it becoming active later',async()=>{ + const f=await fixture();try{ + await f.prepare();await f.store.transaction(tx=>cancelPreparedWarCampaign(tx,f.proposal.id,now)); + assert.equal((await readWarCampaignReport(f.store,f.proposal.id,now+3600001)).phase,'cancelled'); + const p=f.snapshot.provinces[1],event={eventId:randomUUID(),playerUuid:f.snapshot.teams[0].roster[0].uuid,provinceId:p.id,server:p.server,worldUuid:p.homeBlock.worldUuid,chunkX:1,chunkZ:0,claimRevision:2,expectedRevision:2}; + const service=createWarCaptureService(f.store,{verifyCapture:async()=>true,clock:()=>now+3600001});await assert.rejects(service(f.proposal.id,event),/not active/); + }finally{f.store.close();} +}); diff --git a/website/tests/war-exchange.test.mjs b/website/tests/war-exchange.test.mjs index 00b174c7..6df48360 100644 --- a/website/tests/war-exchange.test.mjs +++ b/website/tests/war-exchange.test.mjs @@ -3,12 +3,13 @@ import assert from 'node:assert/strict'; import {randomUUID} from 'node:crypto'; import {BankFixture} from './postbank-fixture.mjs'; import {WAR_EXCHANGE_SCHEMA,createWarExchange} from '../node/war-exchange.mjs'; +import {WAR_CAMPAIGN_SCHEMA} from '../node/war-campaign-store.mjs'; import {EVENT_SCHEMA,createRealmEvents} from '../node/jarvis-events.mjs'; import {PUBLIC_OFFICES} from '../node/public-government.mjs'; import {agreedWarBlock} from '../control-panel/public/war-exchange-policy.mjs'; const now=3600000,start=now+3*3600000; async function rig(kind='clan',count=2){ - const bank=new BankFixture();for(const sql of [...EVENT_SCHEMA,...WAR_EXCHANGE_SCHEMA])await bank.query(sql.replace(' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4','')); + const bank=new BankFixture();for(const sql of [...EVENT_SCHEMA,...WAR_EXCHANGE_SCHEMA,WAR_CAMPAIGN_SCHEMA])await bank.query(sql.replace(' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4','')); const parties=Array.from({length:count},(_,i)=>({kind,id:kind==='clan'?randomUUID():PUBLIC_OFFICES[i].key})),actors=parties.map(()=>({id:randomUUID()})),rights=new Map(actors.map((a,i)=>[a.id,parties[i]]));let actor=actors[0]; const central={prepare:()=>({all:async()=>({results:kind==='clan'?parties.map((p,i)=>({id:p.id,name:'Clan '+i})):[]})})}; const authorize=async(a,k,id)=>rights.get(a.id)?.kind===k&&rights.get(a.id)?.id===id; diff --git a/website/web/assets/war-maps/clan-frontier-v1.png b/website/web/assets/war-maps/clan-frontier-v1.png new file mode 100644 index 00000000..45f0e69f Binary files /dev/null and b/website/web/assets/war-maps/clan-frontier-v1.png differ diff --git a/website/web/assets/war-maps/universal-frontier-v1.png b/website/web/assets/war-maps/universal-frontier-v1.png new file mode 100644 index 00000000..70810565 Binary files /dev/null and b/website/web/assets/war-maps/universal-frontier-v1.png differ diff --git a/website/web/assets/war-maps/world-frontier-v1.png b/website/web/assets/war-maps/world-frontier-v1.png new file mode 100644 index 00000000..066c1289 Binary files /dev/null and b/website/web/assets/war-maps/world-frontier-v1.png differ