From 3b5961a91a812490eb36ae837bba786a054cb78f Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:12:22 +0100 Subject: [PATCH 1/4] Show verified current political offices and seals on person profiles --- website/docs/political-cp.md | 7 +++ website/node/member-political-offices.mjs | 11 +++++ website/node/member-profiles.mjs | 5 +- website/node/public-government.mjs | 8 +++- website/node/public/passport.css | 1 + website/node/public/passport.html | 1 + website/node/public/passport.js | 11 +++++ .../tests/member-political-offices.test.mjs | 47 +++++++++++++++++++ 8 files changed, 88 insertions(+), 3 deletions(-) create mode 100644 website/node/member-political-offices.mjs create mode 100644 website/tests/member-political-offices.test.mjs diff --git a/website/docs/political-cp.md b/website/docs/political-cp.md index 61dff73e..5eef9a5a 100644 --- a/website/docs/political-cp.md +++ b/website/docs/political-cp.md @@ -18,3 +18,10 @@ the same read-only public government projection as the public directory. Outer/inner route and height messages verify both frame source and exact origin. Routes are restricted to the fixed political page catalogue; heights are bounded. The responsive sidebar and nested service frames resize into the outer page. + +Person profiles show current political offices, scope, term dates and the +matching existing seal. Both the dedicated profile section and recognition +gallery use the same current-term projection as Government. Expired, future, +conflicting and disabled-identity terms cannot produce a current office. A +register outage is reported as unavailable. Recognition ranks and forum caches +do not establish the current public mandate; profile access rules are unchanged. diff --git a/website/node/member-political-offices.mjs b/website/node/member-political-offices.mjs new file mode 100644 index 00000000..a1a59ef2 --- /dev/null +++ b/website/node/member-political-offices.mjs @@ -0,0 +1,11 @@ +import {readGovernmentOffices} from './public-government.mjs'; +// Display only the same unambiguous, active elected terms as Government. +// Recognition ranks and expiring forum caches cannot establish current office. +export async function memberPoliticalOffices(db,target,{clock=Date.now}={}){ + const observedAt=clock(); + try{ + const offices=await readGovernmentOffices(db,observedAt),username=target.username.toLowerCase(); + const records=offices.filter(office=>office.holder?.username.toLowerCase()===username).map(office=>({key:office.key,label:office.name,scope:office.scope,office:office.office,faction:office.faction,seal:'https://www.dunerealms.com/assets/seals/'+office.art,startsAt:office.term.startsAt,expiresAt:office.term.expiresAt})); + return {status:'available',records,observedAt}; + }catch{return {status:'unavailable',records:[],observedAt};} +} diff --git a/website/node/member-profiles.mjs b/website/node/member-profiles.mjs index 4c85e4ff..4d2777e8 100644 --- a/website/node/member-profiles.mjs +++ b/website/node/member-profiles.mjs @@ -1,6 +1,7 @@ import {gameStaffSeals,protectedStaffRanks} from './game-staff-seals.mjs'; import {AWARD_LABELS,AWARD_FILES} from './recognition.mjs'; import {politicalSeals} from './political-heraldry.mjs'; +import {memberPoliticalOffices} from './member-political-offices.mjs'; import{readFileSync,existsSync}from'node:fs'; import{createHash}from'node:crypto'; import{identity}from'./auth.mjs'; @@ -67,11 +68,13 @@ export async function memberProfileData(db,target,settings={}){ for(const key of (showcase?Object.keys(departments):departmentsFor(access.nodes,access.ranks,target.username).filter(key=>departmentAwardEarned(stats,key))))add('team-'+key,departments[key]+' Award',base+'award-'+key+'-150.png','Awards'); for(const seal of gameStaffSeals(access.ranks))add(seal.key,seal.label,base+seal.file,'Official'); for(const seal of politicalSeals(access.ranks))add(seal.key,seal.label,base+seal.file,seal.group); + const politicalOffices=await memberPoliticalOffices(db,target,{clock:settings.clock||Date.now}); + for(const office of politicalOffices.records)add('current-office-'+office.key,office.label,office.seal,'Current political offices'); const office=await optional(()=>db.prepare('SELECT roles_json,expires_at FROM drforum_dune_political_roles WHERE website_id=?').bind(target.id).first(),null); if(office&&Number(office.expires_at)>Date.now()/1000){const known={emperor:'Emperor',house_leader:'Faction leader',specerhuis:'Specerhuis',welvaart:'House of Water',guild_staff:'Vaerkring',landsraad:'Landsraad'};for(const key of JSON.parse(office.roles_json||'[]'))if(known[key])add('office-'+key,known[key],'https://forums.dunerealms.com/assets/seals/office-'+key+'.png','Political offices');} const memorial=await optional(()=>db.prepare("SELECT m.slug FROM site_memorials m LEFT JOIN site_life_status l ON l.user_id=m.user_id WHERE m.user_id=? AND (l.status IS NULL OR l.status='deceased')").bind(target.id).first(),null); const clan=await optional(()=>db.prepare('SELECT c.id,c.name,c.tag,c.description,m.clan_role,m.joined_at,(SELECT COUNT(*) FROM site_clan_members n WHERE n.clan_id=c.id) AS member_count FROM site_clan_members m JOIN site_clans c ON c.id=m.clan_id WHERE m.user_id=? AND c.active=1').bind(target.id).first(),undefined); - return{personnelNumber:await personnelNumberFor(db,target.id),showcase,memorial:memorial?'/memorial/'+memorial.slug:null,personalSeal:namedPersonal?medals.find(m=>m.key==='personal-role'):null,username:target.username,displayName:target.display_name,joinedAt:Number(target.created_at),functions:access.organisation?.assignments||[],avatar:'https://cp.dunerealms.com/api/avatars/face/member/'+encodeURIComponent(target.username),avatarMode:'image',bio:publicProfile.bio,publicInfo:publicProfile.publicInfo,socials:publicProfile.socials,ranks,medals,forum:await publicForumFor(db,target.id),support:{status:staff?(stats?'available':'unavailable'):'not-staff',closed:stats?.totalClosed??null,departments:stats?.departments||{}},quests:{status:'placeholder',completed:null,active:null},clan:clan===undefined?{status:'unavailable'}:clan?{status:'member',emblem:'https://cp.dunerealms.com/api/clan-emblems/'+clan.id,name:clan.name,tag:clan.tag,description:clan.description,role:clan.clan_role,joinedAt:Number(clan.joined_at),members:Math.max(0,Number(clan.member_count))}:{status:'none'}}; + return{politicalOffices,personnelNumber:await personnelNumberFor(db,target.id),showcase,memorial:memorial?'/memorial/'+memorial.slug:null,personalSeal:namedPersonal?medals.find(m=>m.key==='personal-role'):null,username:target.username,displayName:target.display_name,joinedAt:Number(target.created_at),functions:access.organisation?.assignments||[],avatar:'https://cp.dunerealms.com/api/avatars/face/member/'+encodeURIComponent(target.username),avatarMode:'image',bio:publicProfile.bio,publicInfo:publicProfile.publicInfo,socials:publicProfile.socials,ranks,medals,forum:await publicForumFor(db,target.id),support:{status:staff?(stats?'available':'unavailable'):'not-staff',closed:stats?.totalClosed??null,departments:stats?.departments||{}},quests:{status:'placeholder',completed:null,active:null},clan:clan===undefined?{status:'unavailable'}:clan?{status:'member',emblem:'https://cp.dunerealms.com/api/clan-emblems/'+clan.id,name:clan.name,tag:clan.tag,description:clan.description,role:clan.clan_role,joinedAt:Number(clan.joined_at),members:Math.max(0,Number(clan.member_count))}:{status:'none'}}; } export function createMemberProfiles(db,settings={}){return async request=>{ const from=request.headers.get('origin');if(from&&from!==origin)return json({message:'Origin rejected.'},403); diff --git a/website/node/public-government.mjs b/website/node/public-government.mjs index cb6e22d2..e093e8f2 100644 --- a/website/node/public-government.mjs +++ b/website/node/public-government.mjs @@ -19,11 +19,15 @@ export function publicElectionCalendar(now=Date.now()){ return {kind,...window,termWeeks:kind==='house'?2:4}; }); } +export async function readGovernmentOffices(db,now=Date.now()){ + const rows=await db.prepare("SELECT t.kind,t.faction,t.office,t.starts_at,t.expires_at,t.outcome,a.username,a.display_name FROM political_office_terms t LEFT JOIN site_accounts a ON a.id=t.user_id AND a.password_hash NOT LIKE '!%' WHERE t.outcome='winner' AND t.starts_at<=? AND t.expires_at>? ORDER BY t.starts_at DESC LIMIT 100").bind(now,now).all(); + return projectGovernment(rows.results||[],now); +} export function createPublicGovernment(db,{clock=Date.now}={}){return async request=>{ if(request.method!=='GET')return Response.json({message:'Read-only public office register.'},{status:405}); if(new URL(request.url).search)return Response.json({message:'No identity overrides are accepted.'},{status:400}); try{ - const now=clock(),rows=await db.prepare("SELECT t.kind,t.faction,t.office,t.starts_at,t.expires_at,t.outcome,a.username,a.display_name FROM political_office_terms t LEFT JOIN site_accounts a ON a.id=t.user_id AND a.password_hash NOT LIKE '!%' WHERE t.outcome='winner' AND t.starts_at<=? AND t.expires_at>? ORDER BY t.starts_at DESC LIMIT 100").bind(now,now).all(); - return Response.json({structure:{landsraad:['emperor','atreides','harkonnen','corrino','ordos'],realms:['atreides','harkonnen','corrino','ordos','fremen'],court:['veiled_concord','spacing_guild'],clanAffiliation:'home_world',companiesBranch:'spacing_guild'},offices:projectGovernment(rows.results||[],now),elections:publicElectionCalendar(now),observedAt:now},{headers:{'Cache-Control':'public,max-age=30'}}); + const now=clock(),offices=await readGovernmentOffices(db,now); + return Response.json({structure:{landsraad:['emperor','atreides','harkonnen','corrino','ordos'],realms:['atreides','harkonnen','corrino','ordos','fremen'],court:['veiled_concord','spacing_guild'],clanAffiliation:'home_world',companiesBranch:'spacing_guild'},offices,elections:publicElectionCalendar(now),observedAt:now},{headers:{'Cache-Control':'public,max-age=30'}}); }catch{return Response.json({message:'The public office register is temporarily unavailable.'},{status:503,headers:{'Cache-Control':'no-store'}});} };} diff --git a/website/node/public/passport.css b/website/node/public/passport.css index e2ab8dc1..1efcb279 100644 --- a/website/node/public/passport.css +++ b/website/node/public/passport.css @@ -1,3 +1,4 @@ *{box-sizing:border-box}body{margin:0;background:#0b221b;color:#eee6ce;font:15px/1.7 system-ui,sans-serif}a{color:#e4ca83}.citizen-profile{max-width:1240px;margin:36px auto 60px;padding:0 28px}.citizen-profile [hidden]{display:none!important}.profile-breadcrumb{margin-bottom:22px;font-size:13px;color:#b8c5b7}.profile-breadcrumb a{text-decoration:none}.profile-hero,.profile-panel{border:1px solid #7f8c61;border-radius:16px;padding:30px;margin-bottom:24px;background:linear-gradient(135deg,#1d4031,#102c23);box-shadow:0 8px 25px #0002}.profile-hero{border-top:3px solid #d2b76b;background:linear-gradient(105deg,#173e2bf2,#102e28e8),url('/assets/sietch.webp') center/cover}.citizen-profile .eyebrow{font-size:10px;font-weight:700;letter-spacing:.16em;color:#c4ad6d;margin:0 0 12px}.identity{display:flex;align-items:center;gap:26px;margin:22px 0}.identity>div{min-width:0}#avatar{width:112px;height:112px;flex-shrink:0;border-radius:13px;border:2px solid #c6ab64;object-fit:cover;image-rendering:pixelated;background:#0a241b}.citizen-profile h1,.citizen-profile h2,.citizen-profile h3{font-family:Georgia,serif;color:#efdcab;line-height:1.25;overflow-wrap:anywhere}.citizen-profile h1{font-size:38px;margin:0 0 6px}.citizen-profile h2{font-size:25px;margin:0 0 18px}.citizen-profile h3{font-size:18px}.citizen-profile p{margin-top:0}.muted,#handle,#status{color:#b9ccbd}#handle{margin-bottom:6px}.metadata{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:24px;margin-top:26px}.metadata>div{border-top:1px solid #8d9a6b55;padding-top:16px}.metadata small{display:block;color:#b5c6b5;font-size:12px;margin-bottom:5px}.metadata strong{overflow-wrap:anywhere}.chips{display:flex;gap:10px;flex-wrap:wrap}.chip{display:inline-block;border:1px solid #a89058;border-radius:20px;padding:5px 13px;background:#9b87481c;font-size:12px;text-decoration:none}.chip[data-staff=true]{border-color:#90b2bb;color:#b8d8e3;background:#456d7b30}.profile-columns{display:grid;grid-template-columns:minmax(0,1.1fr) minmax(0,1fr);gap:24px}.profile-prose{white-space:pre-line;overflow-wrap:anywhere;color:#d4dfce}.profile-functions{display:grid;gap:12px;margin-bottom:20px}.profile-function{padding:13px 16px;border:1px solid #71856677;border-left:3px solid #d1b66c;border-radius:8px;background:#0b281d}.profile-function strong{display:block;color:#e4cb8e}.profile-function span,.profile-function small{display:block;color:#b8cdbb;font-size:12px}.profile-award-groups{display:grid;gap:28px;margin-top:26px}.profile-awards{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:18px}.profile-seal{margin:0!important;min-width:0;padding:22px 16px;border:1px solid #7f8b645c;border-radius:12px;background:linear-gradient(145deg,#274936,#102d24);text-align:center;display:flex;flex-direction:column;align-items:center;gap:14px}.profile-seal img{width:128px;height:128px;max-width:100%;object-fit:contain;filter:drop-shadow(0 4px 7px #0005)}.profile-seal figcaption{font-size:13px;color:#e8d6a5;overflow-wrap:anywhere;line-height:1.5;width:100%}.profile-seal small{font-size:11px;color:#b4bd9f}.personal-seal-panel,.profile-order{display:flex;align-items:center;justify-content:space-between;gap:30px}.personal-seal-panel .profile-seal{min-width:210px}.profile-order{justify-content:flex-start;border-color:#c7a955;background:linear-gradient(115deg,#5d502936,#173b2c)}.profile-order>img{object-fit:contain;flex-shrink:0}.profile-community{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:18px}.profile-community>article{padding:20px;border:1px solid #6e886777;border-radius:10px;background:#0c281e}.profile-community strong{display:block;color:#e8d6a5;font-size:21px}.profile-community small{color:#b7cbb8}.profile-community a{font-size:12px}.citizen-profile a:focus-visible{outline:2px solid #e8cb7c;outline-offset:4px} .profile-clan-emblem{display:block;width:110px;height:110px;object-fit:contain;margin:0 auto 18px;filter:drop-shadow(0 4px 8px #0005)} +.profile-political-offices{border:3px double #c7a05a;background:linear-gradient(120deg,#4b252c,#261e22);box-shadow:inset 0 0 0 3px #d5ad6114}.profile-political-office-list{display:grid;gap:16px}.profile-political-office{display:flex;align-items:center;gap:24px;padding:20px;border:1px solid #b8975688;border-radius:10px;background:#f6eddd0a;min-width:0}.profile-political-office>img{width:96px;height:96px;object-fit:contain;flex-shrink:0;filter:drop-shadow(0 4px 8px #0005)}.profile-political-office small{color:#d4ba82;letter-spacing:.08em;text-transform:uppercase}.profile-political-office h3{margin:7px 0 10px}.profile-political-office strong{color:#edd7a0;font-size:13px}.profile-political-office p{margin:8px 0 0;font-size:12px}@media(max-width:520px){.profile-political-office{align-items:flex-start;flex-direction:column;gap:14px;padding:16px}.profile-political-office>img{width:80px;height:80px}} diff --git a/website/node/public/passport.html b/website/node/public/passport.html index 9e8f8a81..ed5edeb9 100644 --- a/website/node/public/passport.html +++ b/website/node/public/passport.html @@ -3,6 +3,7 @@

DUNEREALMS · CITIZEN REGISTER

Citizen profile

Loading the member record…

Member since—
Clan—
Community forum—

THE PERSON BEHIND THE NAME

About

No public biography added yet.

CURRENT RESPONSIBILITIES

Functions & service

+

SERVICE & RECOGNITION

Seals & earned awards

Current function seals and recorded community achievements.

diff --git a/website/node/public/passport.js b/website/node/public/passport.js index b25c8674..5bfa43c0 100644 --- a/website/node/public/passport.js +++ b/website/node/public/passport.js @@ -1,6 +1,16 @@ const $=id=>document.getElementById(id),el=(tag,value,cls)=>{const n=document.createElement(tag);if(value!=null)n.textContent=value;if(cls)n.className=cls;return n;}; const text=(id,value)=>{$(id).textContent=value??'—';},username=decodeURIComponent(location.pathname.split('/').filter(Boolean)[1]||''); function sealCard(m){const card=el('figure',null,'profile-seal'),image=el('img');image.src=m.url;image.alt=m.label;image.loading='lazy';image.width=image.height=128;card.append(image,el('figcaption',m.label),el('small',m.group||'Recognition'));return card;} +function renderPoliticalOffices(host,data){ + host.replaceChildren();if(!data||data.status!=='unavailable'&&!data.records?.length)return false; + if(data.status==='unavailable'){host.append(el('p','The current political office register is temporarily unavailable.','muted'));return true;} + const date=value=>new Date(value).toLocaleDateString('en-GB',{timeZone:'Europe/Brussels',day:'numeric',month:'short',year:'numeric'}); + for(const office of data.records){const card=el('article',null,'profile-political-office'); + if(/^https:\/\/www\.dunerealms\.com\/assets\/seals\/[a-z0-9_-]+\.png$/.test(office.seal||'')){const image=el('img');image.src=office.seal;image.alt=office.label+' seal';image.width=image.height=96;image.loading='lazy';card.append(image);} + const description=el('div');description.append(el('small',office.scope),el('h3',office.label),el('strong','Currently in office'),el('p','Term: '+date(office.startsAt)+' — '+date(office.expiresAt)+' · Brussels','muted'));card.append(description);host.append(card); + } + return true; +} function render(p){ document.title=(p.displayName||p.username)+' | DuneRealms';text('passport-title',p.displayName||p.username);text('handle','@'+p.username+(p.personnelNumber?' · '+p.personnelNumber:''));text('status',p.showcase?'Verified official DuneRealms account':'DuneRealms community member');if(p.showcase){text('recognition-title','Seal & award showcase');text('recognition-description','The general DuneRealms catalogue. Personal seals and the Holy Order of the Crysknife are excluded.');}text('joined',p.joinedAt?new Date(p.joinedAt).toLocaleDateString('en-GB'):null);text('clan',p.clan?.status==='member'?p.clan.name:'No clan listed');text('forum',p.forum?.status==='linked'?p.forum.username:'Not linked'); if(typeof p.avatar==='string'&&/^https:\/\/cp\.dunerealms\.com\/api\/avatars\//.test(p.avatar)){$('avatar').src=p.avatar;$('avatar').hidden=false;} @@ -8,6 +18,7 @@ function render(p){ const functions=p.functions||[]; for(const f of functions){const card=el('article',null,'profile-function');card.append(el('strong',f.roleLabel),el('span',f.scopeLabel));$('department').append(card);} if(!functions.length)$('department').append(el('p','No staff functions listed.','muted')); + $('political-offices-panel').hidden=!renderPoliticalOffices($('political-offices'),p.politicalOffices); if(p.support?.status==='available')text('tickets',(p.support.closed??0)+' verified support tickets closed'); if(p.bio)text('bio',p.bio);if(p.publicInfo){text('public-info',p.publicInfo);$('public-info').hidden=false;} for(const [label,value]of Object.entries(p.socials||{})){try{const u=new URL(value);if(u.protocol!=='https:'||u.username||u.password)continue;const a=el('a',label,'chip');a.href=u.href;a.rel='noopener noreferrer';a.target='_blank';$('socials').append(a);}catch{}} diff --git a/website/tests/member-political-offices.test.mjs b/website/tests/member-political-offices.test.mjs new file mode 100644 index 00000000..a740aed8 --- /dev/null +++ b/website/tests/member-political-offices.test.mjs @@ -0,0 +1,47 @@ +import test from 'node:test';import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs';import {runInNewContext} from 'node:vm'; +import {LocalD1} from './d1-adapter.mjs'; +import {memberPoliticalOffices} from '../node/member-political-offices.mjs'; +import {readGovernmentOffices} from '../node/public-government.mjs'; +const now=Date.parse('2026-11-15T18:00:00Z'),clock=()=>now; +function fixture(){const db=new LocalD1("CREATE TABLE site_accounts(id TEXT,username TEXT,display_name TEXT,password_hash TEXT);CREATE TABLE political_office_terms(kind TEXT,faction TEXT,office TEXT,starts_at INTEGER,expires_at INTEGER,outcome TEXT,user_id TEXT);");db.sqlite.exec("INSERT INTO site_accounts VALUES('member','CitizenQA','Citizen QA','hash'),('other','OtherQA','Other QA','hash')");const term=async({kind='house',faction='atreides',office='house_leader',starts=now-1000,expires=now+86400000,outcome='winner',user='member'}={})=>db.prepare('INSERT INTO political_office_terms VALUES(?,?,?,?,?,?,?)').bind(kind,faction,office,starts,expires,outcome,user).run();return {db,term};} + +test('current political offices and seals match the public Government register',async()=>{ + const {db,term}=fixture();try{ + await term();await term({kind:'imperial',faction:'imperium',office:'emperor'}); + const data=await memberPoliticalOffices(db,{username:'citizenqa'},{clock}),publicOffices=await readGovernmentOffices(db,now); + assert.equal(data.status,'available');assert.equal(data.records.length,2);assert.equal(data.observedAt,now); + for(const record of data.records){const office=publicOffices.find(o=>o.key===record.key);assert.equal(record.label,office.name);assert.equal(record.seal,'https://www.dunerealms.com/assets/seals/'+office.art);assert.equal(record.startsAt,office.term.startsAt);assert.equal(record.expiresAt,office.term.expiresAt);assert.equal('userId' in record,false);assert.equal('playerUuid' in record,false);} + assert.equal(data.records.find(r=>r.key==='emperor').seal,'https://www.dunerealms.com/assets/seals/emperor-v1.png'); + }finally{db.close();} +}); + +test('expired, future, no-vote and other-member terms cannot create a current office',async()=>{ + const {db,term}=fixture();try{ + await term({expires:now});await term({faction:'harkonnen',starts:now+1});await term({faction:'corrino',outcome:'no_votes'});await term({faction:'ordos',user:'other'}); + const data=await memberPoliticalOffices(db,{username:'CitizenQA',role:'seal_emperor'},{clock});assert.equal(data.status,'available');assert.deepEqual(data.records,[]); + }finally{db.close();} +}); + +test('conflicting active officeholders are withheld rather than attributed to either profile',async()=>{ + const {db,term}=fixture();try{await term();await term({user:'other'});for(const username of ['CitizenQA','OtherQA'])assert.deepEqual((await memberPoliticalOffices(db,{username},{clock})).records,[]);}finally{db.close();} +}); + +test('disabled identities and missing office data never invent an office',async()=>{ + const {db,term}=fixture();try{await term();await db.prepare("UPDATE site_accounts SET password_hash='!disabled' WHERE id='member'").run();assert.deepEqual((await memberPoliticalOffices(db,{username:'CitizenQA'},{clock})).records,[]);}finally{db.close();} + const missing=new LocalD1();try{const data=await memberPoliticalOffices(missing,{username:'CitizenQA'},{clock});assert.equal(data.status,'unavailable');assert.deepEqual(data.records,[]);}finally{missing.close();} +}); + +test('court offices use their own existing seals and labels',async()=>{ + const {db,term}=fixture();try{await term({faction:'veiled_concord',office:'reverent_mother'});await term({kind:'court',faction:'spacing_guild',office:'guild_leader'});const data=await memberPoliticalOffices(db,{username:'CitizenQA'},{clock});assert.equal(data.records.length,2);assert(data.records.some(r=>r.seal.endsWith('/veiled-concord-v1.png')));assert(data.records.some(r=>r.label==='Vaerkring Leadership'));}finally{db.close();} +}); + +class Node{constructor(tag){this.tagName=tag.toUpperCase();this.children=[];this._text='';}set textContent(value){this._text=String(value);this.children=[];}get textContent(){return this._text+this.children.map(n=>n.textContent).join('');}append(...nodes){this.children.push(...nodes);}replaceChildren(...nodes){this.children=[];this._text='';this.append(...nodes);}} +function renderer(){const source=readFileSync(new URL('../node/public/passport.js',import.meta.url),'utf8');return runInNewContext(source.slice(0,source.indexOf('function render(p)'))+';renderPoliticalOffices',{document:{createElement:tag=>new Node(tag),getElementById:()=>null},location:{pathname:'/people/CitizenQA'}});} +test('public profile displays current office, matching seal and term dates',()=>{ + const host=new Node('div'),render=renderer();assert.equal(render(host,{status:'available',records:[{label:'Office of the Emperor',scope:'The Imperium',seal:'https://www.dunerealms.com/assets/seals/emperor-v1.png',startsAt:now,expiresAt:now+86400000}]}),true);assert(host.textContent.includes('Office of the Emperor'));assert(host.textContent.includes('Currently in office'));assert(host.textContent.includes('Brussels'));assert.equal(host.children[0].children[0].src,'https://www.dunerealms.com/assets/seals/emperor-v1.png');assert.equal(host.children[0].children[0].alt,'Office of the Emperor seal'); +}); +test('profiles hide absent office sections, report outages, and reject external seal URLs',()=>{ + const host=new Node('div'),render=renderer();assert.equal(render(host,{status:'available',records:[]}),false);assert.equal(host.children.length,0);assert.equal(render(host,{status:'unavailable',records:[]}),true);assert(host.textContent.includes('temporarily unavailable')); + render(host,{status:'available',records:[{label:'',scope:'The Imperium',seal:'https://evil.invalid/seal.png',startsAt:now,expiresAt:now+1000}]});assert.equal(host.children[0].children.length,1);assert(host.textContent.includes('')); +}); From e7c89515118cb8ec1a8bf5ee429608ad33f8cc9b Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:41:11 +0100 Subject: [PATCH 2/4] Add two-chamber election catalog and searchable candidate register --- .../election-application-route.mjs | 3 +- .../control-panel/election-applications.mjs | 5 ++- website/control-panel/election-ballots.mjs | 22 ++++++---- website/control-panel/election-directory.mjs | 29 +++++++++++++ .../control-panel/election-office-ledger.mjs | 4 +- website/control-panel/election-voting.mjs | 14 ++++--- .../control-panel/public/election-rules.mjs | 15 +++++-- .../public/political-catalog.mjs | 7 ++++ website/control-panel/server.mjs | 7 +++- website/node/public-government.mjs | 19 ++++----- .../tests/member-political-offices.test.mjs | 2 +- website/tests/public-government.test.mjs | 2 +- website/tests/voting-directory.test.mjs | 41 +++++++++++++++++++ 13 files changed, 132 insertions(+), 38 deletions(-) create mode 100644 website/control-panel/election-directory.mjs create mode 100644 website/control-panel/public/political-catalog.mjs create mode 100644 website/tests/voting-directory.test.mjs diff --git a/website/control-panel/election-application-route.mjs b/website/control-panel/election-application-route.mjs index 8681b834..881e16b2 100644 --- a/website/control-panel/election-application-route.mjs +++ b/website/control-panel/election-application-route.mjs @@ -32,7 +32,8 @@ export function createElectionApplications(db,settings={},deps={}){ if(!current||current.id!==user.id)return reply({message:'Sign in again.'},401); if(!await permitted(current))return reply({message:'Access changed.'},403); if((await linked(current))?.toLowerCase()!==player.toLowerCase())return reply({message:'Linked account changed. Refresh.'},409); - const context={linked:verified.linked===true,playerUuid:player,faction:verified.factionStatus==='verified'?verified.faction:null}; + const clan=input.kind==='clan_delegate'?await db.prepare("SELECT c.id FROM site_clans c JOIN site_clan_members m ON m.clan_id=c.id JOIN site_game_links l ON l.user_id=m.user_id AND l.minecraft_uuid=m.minecraft_uuid WHERE m.user_id=? AND c.active=1").bind(current.id).first():null; + const context={clanId:clan?.id,linked:verified.linked===true,playerUuid:player,faction:verified.factionStatus==='verified'?verified.faction:null}; try{validateCandidature(input,context,clock());}catch(error){return reply({message:error.message},400);} try{ const result=await save(db,{actor:current,context,input,now:clock(),clock}); diff --git a/website/control-panel/election-applications.mjs b/website/control-panel/election-applications.mjs index 46c0901d..4a91d635 100644 --- a/website/control-panel/election-applications.mjs +++ b/website/control-panel/election-applications.mjs @@ -18,9 +18,9 @@ export const applicationSchema = [ export async function initializeApplications(db) { for(const sql of applicationSchema)await db.prepare(sql).run(); } -export function applicationPrefix(kind,faction){return kind==='imperial'?'IMP':faction==='veiled_concord'?'CON':'HSE';} +export function applicationPrefix(kind,faction){return kind==='guild'?'GLD':kind==='clan_delegate'?'CLN':kind==='imperial'?'IMP':faction==='veiled_concord'?'CON':'HSE';} export function applicationNumber(prefix,year,value){ - if(!['IMP','CON','HSE'].includes(prefix)||!Number.isInteger(year)||year<2026||!Number.isInteger(value)||value<1||value>999999)throw Error('Application number range exhausted or invalid'); + if(!['IMP','CON','HSE','GLD','CLN'].includes(prefix)||!Number.isInteger(year)||year<2026||!Number.isInteger(value)||value<1||value>999999)throw Error('Application number range exhausted or invalid'); return `APP-${prefix}-${year}-${String(value).padStart(6,'0')}`; } // Transactional repository, not a publicly mounted route. Call only with an @@ -36,6 +36,7 @@ export async function submitApplication(db,{actor,context,input,now=Date.now(),c const counters=await query('SELECT value FROM political_application_counters WHERE scope=? FOR UPDATE',[scope]); const links=await query('SELECT minecraft_uuid FROM site_game_links WHERE user_id=? FOR UPDATE',[actor.id]); if(links[0]?.minecraft_uuid?.toLowerCase()!==player)throw Error('Linked account changed'); + if(candidate.kind==='clan_delegate'){const [member]=await query("SELECT c.id FROM site_clans c JOIN site_clan_members m ON m.clan_id=c.id AND m.minecraft_uuid=? WHERE m.user_id=? AND c.id=? AND c.active=1 FOR SHARE",[player,actor.id,context.clanId]);if(!member)throw Error('Active linked clan membership required');} const existing=await query('SELECT id,public_id,user_id,motivation,faction FROM political_applications WHERE player_uuid=? AND kind=? AND election_start=? FOR UPDATE',[player,candidate.kind,start]); if(existing.length){ const row=existing[0];if(row.user_id!==actor.id)throw Error('An application already exists for this player'); diff --git a/website/control-panel/election-ballots.mjs b/website/control-panel/election-ballots.mjs index bd648796..240dc612 100644 --- a/website/control-panel/election-ballots.mjs +++ b/website/control-panel/election-ballots.mjs @@ -1,18 +1,19 @@ import {randomUUID} from 'node:crypto'; -import {electionWindow,imperialVoteAllowance} from './public/election-rules.mjs'; +import {ELECTION_RULES,electionWindow,electionScope,voteCapacity} from './public/election-rules.mjs'; const uuid=/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i; export function validateBallot(input,context,now=Date.now(),roundWindow=null){ - if(!input||!uuid.test(input.requestId||'')||!['house','imperial'].includes(input.kind)||input.confirmed!==true)throw Error('Confirm your definitive vote'); - if(!context?.linked||!context.faction||!uuid.test(context.playerUuid||''))throw Error('Verified faction membership required'); + if(!input||!uuid.test(input.requestId||'')||!Object.hasOwn(ELECTION_RULES,input.kind)||input.confirmed!==true)throw Error('Confirm your definitive vote'); + if(!context?.linked||(['house','imperial'].includes(input.kind)&&!context.faction)||!uuid.test(context.playerUuid||''))throw Error('Verified faction membership required'); const window=electionWindow(input.kind,input.start,now);if(roundWindow)window.phase=now>=Number(roundWindow.opens_at)&&nowcapacity)throw Error('Choose eligible candidates'); const seen=new Set();let total=0; const allocations=input.allocations.map(a=>{if(!a||!uuid.test(a.applicationId||'')||seen.has(a.applicationId.toLowerCase())||!Number.isInteger(a.votes)||a.votes<1||a.votes>capacity)throw Error('Invalid vote allocation');seen.add(a.applicationId.toLowerCase());total+=a.votes;return{applicationId:a.applicationId.toLowerCase(),votes:a.votes};}).sort((a,b)=>a.applicationId.localeCompare(b.applicationId)); if(total>capacity)throw Error('Vote allowance exceeded'); - return {kind:input.kind,start:Date.parse(window.votingOpens),faction:input.kind==='house'?context.faction:'imperium',capacity,total,allocations,requestId:input.requestId.toLowerCase()}; + return {kind:input.kind,start:Date.parse(window.votingOpens),faction:electionScope(input.kind,context),capacity,total,allocations,requestId:input.requestId.toLowerCase()}; } export const ballotSchema=[ + `CREATE TABLE IF NOT EXISTS political_clan_votes(round_id CHAR(36) NOT NULL,clan_id CHAR(36) NOT NULL,ballot_id CHAR(36) NOT NULL UNIQUE,PRIMARY KEY(round_id,clan_id)) ENGINE=InnoDB`, `CREATE TABLE IF NOT EXISTS political_voters (round_id CHAR(36) NOT NULL,player_uuid CHAR(36) NOT NULL,kind VARCHAR(16) NOT NULL,election_start BIGINT NOT NULL,user_id CHAR(36) NOT NULL,faction VARCHAR(32) NOT NULL,capacity INTEGER NOT NULL,spent INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(player_uuid,round_id)) ENGINE=InnoDB`, `CREATE TABLE IF NOT EXISTS political_ballots (id CHAR(36) PRIMARY KEY,round_id CHAR(36) NOT NULL,request_id CHAR(36) NOT NULL,player_uuid CHAR(36) NOT NULL,kind VARCHAR(16) NOT NULL,election_start BIGINT NOT NULL,payload TEXT NOT NULL,created_at BIGINT NOT NULL,UNIQUE KEY voter_request(player_uuid,request_id)) ENGINE=InnoDB`, `CREATE TABLE IF NOT EXISTS political_ballot_allocations (ballot_id CHAR(36) NOT NULL,application_id CHAR(36) NOT NULL,votes INTEGER NOT NULL,PRIMARY KEY(ballot_id,application_id)) ENGINE=InnoDB`, @@ -28,11 +29,11 @@ export async function castBallot(db,{actor,context,input,now=Date.now(),clock=Da const [result]=await db.batch([{async run(connection){ const query=async(sql,args=[])=>(await connection.execute(sql,args))[0]; const [round]=await query('SELECT * FROM political_election_rounds WHERE id=? FOR UPDATE',[input.roundId]); - if(!round||round.kind!==input.kind||Number(round.election_start)!==Date.parse(input.start)||round.faction!==(input.kind==='house'?context.faction:'imperium')||round.status!=='open')throw Error('Election round is not open'); + if(!round||round.kind!==input.kind||Number(round.election_start)!==Date.parse(input.start)||round.faction!==electionScope(input.kind,context)||round.status!=='open')throw Error('Election round is not open'); const vote=validateBallot(input,context,clock(),round),payload=JSON.stringify({kind:vote.kind,start:vote.start,roundId:round.id,allocations:vote.allocations}); - await query('INSERT INTO political_voters(round_id,player_uuid,kind,election_start,user_id,faction,capacity,spent) VALUES(?,?,?,?,?,?,?,0) ON DUPLICATE KEY UPDATE player_uuid=VALUES(player_uuid)',[round.id,player,vote.kind,vote.start,actor.id,context.faction,vote.capacity]); + await query('INSERT INTO political_voters(round_id,player_uuid,kind,election_start,user_id,faction,capacity,spent) VALUES(?,?,?,?,?,?,?,0) ON DUPLICATE KEY UPDATE player_uuid=VALUES(player_uuid)',[round.id,player,vote.kind,vote.start,actor.id,context.faction||vote.faction,vote.capacity]); const [voter]=await query('SELECT user_id,faction,capacity,spent FROM political_voters WHERE player_uuid=? AND round_id=? FOR UPDATE',[player,round.id]); - if(voter.user_id!==actor.id||voter.faction!==context.faction)throw Error('Voter identity or faction changed'); + if(voter.user_id!==actor.id||voter.faction!==(context.faction||vote.faction))throw Error('Voter identity or faction changed'); const [link]=await query('SELECT minecraft_uuid FROM site_game_links WHERE user_id=? FOR UPDATE',[actor.id]);if(link?.minecraft_uuid?.toLowerCase()!==player)throw Error('Linked account changed'); const [previous]=await query('SELECT id,payload FROM political_ballots WHERE player_uuid=? AND request_id=?',[player,vote.requestId]); if(previous){if(previous.payload!==payload)throw Error('Submission identifier already used');return{id:previous.id,created:false,remaining:Number(voter.capacity)-Number(voter.spent)};} @@ -46,6 +47,11 @@ export async function castBallot(db,{actor,context,input,now=Date.now(),clock=Da if(!candidate||candidate.kind!==vote.kind||Number(candidate.election_start)!==vote.start||candidate.faction!==vote.faction||candidate.status!=='submitted')throw Error('Candidate is not eligible for this election'); } const id=makeId(); + if(vote.kind==='clan_delegate'){ + const [clan]=await query("SELECT c.id FROM site_clans c JOIN site_clan_members m ON m.clan_id=c.id AND m.user_id=c.owner_id AND m.clan_role='owner' JOIN site_game_links l ON l.user_id=m.user_id AND l.minecraft_uuid=m.minecraft_uuid WHERE c.id=? AND c.owner_id=? AND c.active=1 FOR UPDATE",[context.clanId,actor.id]); + if(!clan)throw Error('Current linked clan leadership is required'); + await query('INSERT INTO political_clan_votes(round_id,clan_id,ballot_id) VALUES(?,?,?)',[round.id,clan.id,id]); + } await query('INSERT INTO political_ballots(id,round_id,request_id,player_uuid,kind,election_start,payload,created_at) VALUES(?,?,?,?,?,?,?,?)',[id,round.id,vote.requestId,player,vote.kind,vote.start,payload,now]); for(const a of vote.allocations)await query('INSERT INTO political_ballot_allocations(ballot_id,application_id,votes) VALUES(?,?,?)',[id,a.applicationId,a.votes]); await query('UPDATE political_voters SET spent=spent+? WHERE player_uuid=? AND round_id=?',[vote.total,player,round.id]); diff --git a/website/control-panel/election-directory.mjs b/website/control-panel/election-directory.mjs new file mode 100644 index 00000000..e231b608 --- /dev/null +++ b/website/control-panel/election-directory.mjs @@ -0,0 +1,29 @@ +import {identity} from '../node/auth.mjs'; +import {accessFor} from '../node/permissions.mjs'; +import {ELECTIONS} from './public/political-catalog.mjs'; +export function directoryQuery(url){ + const q=(url.searchParams.get('q')||'').trim(),election=url.searchParams.get('election')||'',status=url.searchParams.get('status')||'',page=Number(url.searchParams.get('page')||0); + if(q.length>100||election&&!ELECTIONS.some(e=>e.id===election)||!['','upcoming','voting','closed'].includes(status)||!Number.isInteger(page)||page<0||page>10000)throw Error('Invalid search filters.'); + return {q,election,status,page}; +} +export function createElectionDirectory(db,{authenticate=r=>identity(r,db),access=u=>accessFor(db,u),clock=Date.now}={}){return async request=>{ + const reply=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}}); + if(request.method!=='GET')return reply({message:'Read-only directory.'},405); + const user=await authenticate(request);if(!user)return reply({message:'Sign in first.'},401); + if(!(await access(user)).nodes.includes('web.menu.game'))return reply({message:'Player access required.'},403); + let filters;try{filters=directoryQuery(new URL(request.url));}catch(error){return reply({message:error.message},400);} + const where=["a.status='submitted'","u.password_hash NOT LIKE '!%'"],args=[],now=clock(); + if(filters.q){where.push("(LOWER(u.username) LIKE ? ESCAPE '!' OR LOWER(COALESCE(u.display_name,'')) LIKE ? ESCAPE '!' OR LOWER(a.motivation) LIKE ? ESCAPE '!' OR LOWER(COALESCE(p.bio,'')) LIKE ? ESCAPE '!')");const term='%'+filters.q.toLowerCase().replace(/[!%_]/g,'!$&')+'%';args.push(term,term,term,term);} + if(filters.election){const e=ELECTIONS.find(e=>e.id===filters.election);where.push('a.kind=? AND a.faction=?');args.push(e.kind,e.faction);} + // Keep retired offices in the historical ledger, outside the new election directory. + where.push('('+ELECTIONS.map(e=>{args.push(e.kind,e.faction);return '(a.kind=? AND a.faction=?)';}).join(' OR ')+')'); + const phase="CASE WHEN a.election_start>? THEN 'upcoming' WHEN r.status='open' AND r.closes_at>? THEN 'voting' ELSE 'closed' END"; + const from=` FROM political_applications a JOIN site_accounts u ON u.id=a.user_id LEFT JOIN site_profiles p ON p.user_id=u.id LEFT JOIN political_election_rounds r ON r.kind=a.kind AND r.faction=a.faction AND r.election_start=a.election_start AND NOT EXISTS(SELECT 1 FROM political_election_rounds newer WHERE newer.kind=r.kind AND newer.faction=r.faction AND newer.election_start=r.election_start AND newer.round_number>r.round_number) WHERE ${where.join(' AND ')}`; + if(filters.status){where.push(`${phase}=?`);args.push(now,now,filters.status);} + const filteredFrom=from+(filters.status?` AND ${phase}=?`:''); + try{ + const count=await db.prepare('SELECT COUNT(*) AS total'+filteredFrom).bind(...args).first(); + const rows=await db.prepare(`SELECT a.id,a.public_id,a.kind,a.faction,a.election_start,a.motivation,u.username,u.display_name,p.bio,${phase} AS phase,r.id AS round_id,r.status AS round_status,r.opens_at,r.closes_at,EXISTS(SELECT 1 FROM political_round_candidates c WHERE c.round_id=r.id AND c.application_id=a.id) AS in_round`+filteredFrom+' ORDER BY a.election_start DESC,a.kind,a.faction,u.username,a.id LIMIT 24 OFFSET ?').bind(now,now,...args,filters.page*24).all(); + return reply({applications:rows.results.map(r=>({id:r.id,publicId:r.public_id,kind:r.kind,faction:r.faction,start:new Date(Number(r.election_start)).toISOString(),username:r.username,name:r.display_name||r.username,bio:r.bio||'',motivation:r.motivation,phase:r.phase,round:r.round_id?{id:r.round_id,status:r.round_status,opensAt:Number(r.opens_at),closesAt:Number(r.closes_at),eligible:!!Number(r.in_round)}:null})),total:Number(count.total),page:filters.page,pageSize:24}); + }catch{return reply({message:'The voting directory is temporarily unavailable.'},503);} +};} diff --git a/website/control-panel/election-office-ledger.mjs b/website/control-panel/election-office-ledger.mjs index 48189cf5..9c35ae80 100644 --- a/website/control-panel/election-office-ledger.mjs +++ b/website/control-panel/election-office-ledger.mjs @@ -15,14 +15,14 @@ export function planOfficeTerm(round,application,previous,now){ if(!Number.isFinite(closed)||closed=start)throw Error('Process office results in chronological order'); - const office=round.kind==='imperial'?'emperor':round.faction==='veiled_concord'?'reverent_mother':'house_leader'; + const office=round.kind==='guild'?'guild_leader':round.kind==='clan_delegate'?'clan_delegate':round.kind==='imperial'?'emperor':round.faction==='veiled_concord'?'reverent_mother':'house_leader'; let userId=null,playerUuid=null,streak=0; if(round.status==='winner'){ if(!application||application.id!==round.winner_id||application.kind!==round.kind||application.faction!==round.faction||Number(application.election_start)!==start||!uuid.test(application.user_id)||!uuid.test(application.player_uuid))throw Error('Winner identity does not match election'); userId=application.user_id;playerUuid=application.player_uuid.toLowerCase(); streak=previous&&Number(previous.election_start)===start-period&&previous.player_uuid===playerUuid&&previous.outcome==='winner'?Number(previous.streak)+1:1; } - const title=office==='emperor'?'Emperor Emeritus of the Three Crowns':office==='reverent_mother'?'Grand Matriarch of the Veil':'High Lord of the Three Banners'; + const title=office==='guild_leader'?'Guild Elder':office==='clan_delegate'?'Elder of the Clans':office==='emperor'?'Emperor Emeritus of the Three Crowns':office==='reverent_mother'?'Grand Matriarch of the Veil':'High Lord of the Three Banners'; return {kind:round.kind,faction:round.faction,electionStart:start,office,userId,playerUuid,applicationId:round.status==='winner'?application.id:null,startsAt:closed,expiresAt:start+period,outcome:round.status,streak,honour:streak>=3?title:null}; } // This ledger records election facts only. It never edits account roles, game offices or paid/earned ranks. diff --git a/website/control-panel/election-voting.mjs b/website/control-panel/election-voting.mjs index 25f9e67c..bf467837 100644 --- a/website/control-panel/election-voting.mjs +++ b/website/control-panel/election-voting.mjs @@ -1,7 +1,7 @@ import {identity} from '../node/auth.mjs'; import {accessFor} from '../node/permissions.mjs'; import {createPoliticsPreview} from './politics-preview.mjs'; -import {ELECTION_RULES,imperialVoteAllowance} from './public/election-rules.mjs'; +import {ELECTION_RULES,electionScope,voteCapacity} from './public/election-rules.mjs'; import {openFirstRound,finalizeRound} from './election-rounds.mjs'; import {castBallot} from './election-ballots.mjs'; const houses=['atreides','harkonnen','corrino','ordos','fremen']; @@ -19,7 +19,7 @@ export async function advanceElection(db,kind,faction,now=Date.now()){ } export function startElectionClock(db,{clock=Date.now,onError=()=>console.error('Election clock failed')}={}){ let busy=false,stopped=false; - const tick=async()=>{if(busy||stopped)return;busy=true;try{const now=clock();for(const faction of houses)await advanceElection(db,'house',faction,now);await advanceElection(db,'imperial','imperium',now);}catch(error){onError(error);}finally{busy=false;}}; + const tick=async()=>{if(busy||stopped)return;busy=true;try{const now=clock();for(const faction of houses.filter(f=>f!=='fremen'))await advanceElection(db,'house',faction,now);for(const kind of ['imperial','bene','guild','clan_delegate'])await advanceElection(db,kind,electionScope(kind),now);}catch(error){onError(error);}finally{busy=false;}}; const timer=setInterval(tick,15000);timer.unref?.();void tick();return()=>{stopped=true;clearInterval(timer);}; } export function createElectionVoting(db,settings={},deps={}){ @@ -39,9 +39,10 @@ export function createElectionVoting(db,settings={},deps={}){ const response=await preview(new Request(origin+'/api/politics/preview',{headers:request.headers}));if(!response.ok)return reply({message:'Faction verification unavailable.'},503); const verified=await response.json(),current=await auth(request); if(!current||current.id!==user.id||!await permitted(current)||(await linked(current))?.toLowerCase()!==player.toLowerCase())return reply({message:'Account access changed. Refresh.'},403); - if(!verified.linked||verified.factionStatus!=='verified'||!houses.includes(verified.faction))return reply({message:'Verified faction membership required.'},403); + if(!verified.linked||(['house','imperial'].includes(kind)&&(verified.factionStatus!=='verified'||!houses.includes(verified.faction)||kind==='house'&&verified.faction==='fremen')))return reply({message:'Verified faction membership required.'},403); if(kind==='imperial'&&verified.officeStatus!=='verified')return reply({message:'Current office could not be verified. No votes have been spent.'},503); - const context={linked:true,playerUuid:player,faction:verified.faction,houseLeader:verified.houseLeader===true},faction=kind==='house'?context.faction:'imperium',now=clock(),start=cycleStart(kind,now); + const clan=kind==='clan_delegate'?await db.prepare("SELECT c.id,m.clan_role,c.owner_id FROM site_clans c JOIN site_clan_members m ON m.clan_id=c.id JOIN site_game_links l ON l.user_id=m.user_id AND l.minecraft_uuid=m.minecraft_uuid WHERE m.user_id=? AND c.active=1").bind(current.id).first():null; + const context={clanId:clan?.id,clanLeader:clan?.owner_id===current.id&&clan?.clan_role==='owner',linked:true,playerUuid:player,faction:verified.faction,houseLeader:verified.houseLeader===true},faction=electionScope(kind,context),now=clock(),start=cycleStart(kind,now); const round=await advance(db,kind,faction,now); if(request.method==='POST'){ if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); @@ -54,7 +55,8 @@ export function createElectionVoting(db,settings={},deps={}){ if(round){const result=await db.prepare('SELECT a.id,a.public_id,a.motivation,u.username,COALESCE(SUM(v.votes),0) AS votes FROM political_round_candidates c JOIN political_applications a ON a.id=c.application_id JOIN site_accounts u ON u.id=a.user_id LEFT JOIN political_ballots b ON b.round_id=c.round_id LEFT JOIN political_ballot_allocations v ON v.ballot_id=b.id AND v.application_id=a.id WHERE c.round_id=? GROUP BY a.id,a.public_id,a.motivation,u.username ORDER BY votes DESC,u.username ASC').bind(round.id).all();candidates=result.results;} else {const result=await db.prepare("SELECT a.id,a.public_id,a.motivation,u.username,0 AS votes FROM political_applications a JOIN site_accounts u ON u.id=a.user_id WHERE a.kind=? AND a.faction=? AND a.election_start=? AND a.status='submitted' ORDER BY u.username").bind(kind,faction,start).all();candidates=result.results;} const voter=round?await db.prepare('SELECT capacity,spent FROM political_voters WHERE player_uuid=? AND round_id=?').bind(player.toLowerCase(),round.id).first():null; - const capacity=kind==='house'?1:imperialVoteAllowance(context),remaining=voter?Math.max(0,Math.min(capacity,Number(voter.capacity))-Number(voter.spent)):capacity; - return reply({kind,faction,start:new Date(start).toISOString(),round:round?{id:round.id,number:Number(round.round_number),status:round.status,opensAt:Number(round.opens_at),closesAt:Number(round.closes_at),winnerId:round.winner_id}:null,remaining,candidates:candidates.map(c=>({...c,votes:Number(c.votes)}))}); + const capacity=voteCapacity(kind,context),remaining=voter?Math.max(0,Math.min(capacity,Number(voter.capacity))-Number(voter.spent)):capacity; + const clanVote=kind==='clan_delegate'&&round&&clan?await db.prepare('SELECT ballot_id FROM political_clan_votes WHERE round_id=? AND clan_id=?').bind(round.id,clan.id).first():null; + return reply({kind,faction,start:new Date(start).toISOString(),round:round?{id:round.id,number:Number(round.round_number),status:round.status,opensAt:Number(round.opens_at),closesAt:Number(round.closes_at),winnerId:round.winner_id}:null,remaining:clanVote?0:remaining,candidates:candidates.map(c=>({...c,votes:Number(c.votes)}))}); }; } diff --git a/website/control-panel/public/election-rules.mjs b/website/control-panel/public/election-rules.mjs index 54ac6a52..e0b781bf 100644 --- a/website/control-panel/public/election-rules.mjs +++ b/website/control-panel/public/election-rules.mjs @@ -1,6 +1,9 @@ // Owner-confirmed schedule, 8 November 2026. GMT is UTC, not local summer time. export const ELECTION_RULES = Object.freeze({ - house: Object.freeze({first:'2026-11-15T09:00:00.000Z',weeks:2}), + house: Object.freeze({first:'2026-11-15T09:00:00.000Z',weeks:4}), + bene: Object.freeze({first:'2026-11-15T15:00:00.000Z',weeks:4}), + guild: Object.freeze({first:'2026-11-15T15:00:00.000Z',weeks:4}), + clan_delegate: Object.freeze({first:'2026-11-15T15:00:00.000Z',weeks:4}), imperial: Object.freeze({first:'2026-11-15T15:00:00.000Z',weeks:4}), }); export function electionDates(kind, now=Date.now(), count=4) { @@ -23,14 +26,18 @@ export function electionWindow(kind,start,now=Date.now()) { return {applicationsClose:new Date(timestamp).toISOString(),votingOpens:new Date(timestamp).toISOString(),votingCloses:new Date(closes).toISOString(),phase:now4000||/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/.test(motivation))throw Error('Motivation must contain 20–4000 readable characters'); // Never take faction or office authority from the submitted form. - return {kind:input.kind,start:window.votingOpens,faction:input.kind==='house'?context.faction:'imperium',motivation}; + return {kind:input.kind,start:window.votingOpens,faction:electionScope(input.kind,context),motivation}; } + +export function electionScope(kind,context={}){return kind==='house'?context.faction:({imperial:'imperium',bene:'veiled_concord',guild:'spacing_guild',clan_delegate:'clans'})[kind];} +export function voteCapacity(kind,context={}){return kind==='imperial'?imperialVoteAllowance(context):kind==='clan_delegate'?(context.clanLeader&&context.clanId?1:0):1;} diff --git a/website/control-panel/public/political-catalog.mjs b/website/control-panel/public/political-catalog.mjs new file mode 100644 index 00000000..ae0a7831 --- /dev/null +++ b/website/control-panel/public/political-catalog.mjs @@ -0,0 +1,7 @@ +export const ELECTIONS=Object.freeze([ + {id:'emperor',kind:'imperial',faction:'imperium',label:'Emperor',chamber:'Imperial Senate',seal:'emperor-v1.png'}, + ...[['atreides','Aerdrecht','house-aerdrecht-v1.png'],['harkonnen','Harkveen','house-harkveen-v1.png'],['corrino','Korenholt','house-korenholt-v1.png'],['ordos','Oordwijk','house-oordwijk-v1.png']].map(([faction,name,seal])=>({id:faction,kind:'house',faction,label:'House '+name+' Leader',chamber:'Imperial Senate',seal})), + {id:'bene',kind:'bene',faction:'veiled_concord',label:'Bene Gesserit · Reverent Mother',chamber:'Small Council',seal:'veiled-concord-v1.png'}, + {id:'guild',kind:'guild',faction:'spacing_guild',label:'Spacing Guild Leader',chamber:'Small Council',seal:'office-landsraad.png'}, + {id:'clan-delegate',kind:'clan_delegate',faction:'clans',label:'Clan Delegate',chamber:'Small Council',seal:'office-house_leader.png'} +]); diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs index 00c36e64..33fcf7b8 100644 --- a/website/control-panel/server.mjs +++ b/website/control-panel/server.mjs @@ -1,3 +1,4 @@ +import {createElectionDirectory} from './election-directory.mjs'; import {createMenuBadges} from '../node/menu-badges.mjs'; import {startCentralScheduler} from '../node/postbank-payments.mjs'; import {createPostbankApi} from '../node/postbank-api.mjs'; @@ -143,6 +144,7 @@ export function createPanel(db,settings={},dependencies={}){ const overview=createOverview(db);const menuBadges=createMenuBadges(db,settings); const banBridge=createBanBridge(db,settings,dependencies.bans); const banRegister=createBanRegister(db,settings,dependencies.bans); + const electionDirectory=createElectionDirectory(db,dependencies.electionDirectory); const electionVoting=createElectionVoting(db,settings,dependencies.electionVoting); const imperialCharters=createImperialCharters(db,settings); const proclamations=createProclamations(db,settings); @@ -164,7 +166,8 @@ export function createPanel(db,settings={},dependencies={}){ const onboarding=await firstLoginGate(request,db);if(onboarding)return onboarding; if(settings.POSTBANK_ENABLED==='true'&&path.startsWith('/api/bank/'))return postbank(request); if(settings.POSTBANK_ENABLED==='true'&&path==='/api/v1/me/bank')return json({message:'The game-linked bank has been retired from this website.'},410); - if(['/api/politics/ballot/house','/api/politics/ballot/imperial'].includes(path))return electionVoting(request); + if(path==='/api/politics/directory')return electionDirectory(request); + if(['/api/politics/ballot/house','/api/politics/ballot/imperial','/api/politics/ballot/bene','/api/politics/ballot/guild','/api/politics/ballot/clan_delegate'].includes(path))return electionVoting(request); if(path==='/api/politics/charters')return imperialCharters(request); if(path==='/api/politics/proclamations')return proclamations(request); if(path==='/api/politics/electoral-roll')return electoralRoll(request); @@ -278,7 +281,7 @@ export function createPanel(db,settings={},dependencies={}){ return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/'+file,import.meta.url)),{headers:{'Content-Type':moduleFile?'text/javascript; charset=utf-8':file.endsWith('.css')?'text/css; charset=utf-8':'text/html; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}}); } const file=path==='/'?'index.html':path==='/servers'?'servers.html':path.slice(1); - if(!['user-service.html','user-service-entry.mjs','user-service.css','kit-receipt-status.mjs','clan-center.html','clan-center-entry.mjs','clan-center.css','bank-transfer-view.mjs','bank-dashboard.mjs','mail-service-ui.mjs','mail-workspace.css','hosting-control.mjs','internal-mail.mjs','internal-mail.css','election-voting-view.mjs','imperial-charters-view.mjs','proclamations-view.mjs','electoral-roll-view.mjs','election-applications-view.mjs','election-rules.mjs','menu-ribbons.mjs','council-preview.mjs','politics.mjs','crysknife.mjs','x-news-draft.mjs','terms.html','admin-registration.mjs','mail-signature.mjs','webmail.mjs','git-control.mjs','git-control.css','site-profile.mjs','site-profile.css','servers.html','servers.js','servers.css','pages.mjs','user-page-hero.mjs','commerce-settings.mjs','shop-management.mjs','center-portals.mjs','panel-layout.mjs','embed-size.mjs','dev-request-access.mjs','center-portals.css','overview.mjs','overview.css','page-groups.mjs','ban-register.mjs','moderation-form-response.mjs','ban-record-cards.css','ban-evidence.mjs','ban-evidence.css','ranks.mjs','ranks.css','staff-manual.mjs','luckperms.mjs','community-admin.mjs','native-community.mjs','exchange.mjs','exchange.css','clans.mjs','clan-shop.mjs','house-tailor.mjs','banking.mjs','banking.css','game-ranks.mjs','upgrade-shop.mjs','kit-generator.mjs','kit-generator.css','kit-market.mjs','kit-market.css','kit-cart.mjs','imperial-atelier.mjs','quests.mjs','quests.css','clans.css','clan-request-gate.mjs','clan-profile-panels.mjs','quest-rewards.mjs','quest-rewards.css','inventory/inventory-view.mjs','inventory/inventory-mount.mjs','inventory/inventory.css'].includes(file))return new Response('Not found',{status:404}); + if(!['user-service.html','user-service-entry.mjs','user-service.css','kit-receipt-status.mjs','clan-center.html','clan-center-entry.mjs','clan-center.css','bank-transfer-view.mjs','bank-dashboard.mjs','mail-service-ui.mjs','mail-workspace.css','hosting-control.mjs','internal-mail.mjs','internal-mail.css','election-voting-view.mjs','imperial-charters-view.mjs','proclamations-view.mjs','electoral-roll-view.mjs','election-applications-view.mjs','election-rules.mjs','political-catalog.mjs','menu-ribbons.mjs','council-preview.mjs','politics.mjs','crysknife.mjs','x-news-draft.mjs','terms.html','admin-registration.mjs','mail-signature.mjs','webmail.mjs','git-control.mjs','git-control.css','site-profile.mjs','site-profile.css','servers.html','servers.js','servers.css','pages.mjs','user-page-hero.mjs','commerce-settings.mjs','shop-management.mjs','center-portals.mjs','panel-layout.mjs','embed-size.mjs','dev-request-access.mjs','center-portals.css','overview.mjs','overview.css','page-groups.mjs','ban-register.mjs','moderation-form-response.mjs','ban-record-cards.css','ban-evidence.mjs','ban-evidence.css','ranks.mjs','ranks.css','staff-manual.mjs','luckperms.mjs','community-admin.mjs','native-community.mjs','exchange.mjs','exchange.css','clans.mjs','clan-shop.mjs','house-tailor.mjs','banking.mjs','banking.css','game-ranks.mjs','upgrade-shop.mjs','kit-generator.mjs','kit-generator.css','kit-market.mjs','kit-market.css','kit-cart.mjs','imperial-atelier.mjs','quests.mjs','quests.css','clans.css','clan-request-gate.mjs','clan-profile-panels.mjs','quest-rewards.mjs','quest-rewards.css','inventory/inventory-view.mjs','inventory/inventory-mount.mjs','inventory/inventory.css'].includes(file))return new Response('Not found',{status:404}); return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/'+file,import.meta.url)),{headers:{'Content-Type':types[file.slice(file.lastIndexOf('.'))],'Cache-Control':'no-store'}}); }; } diff --git a/website/node/public-government.mjs b/website/node/public-government.mjs index e093e8f2..fb068f6b 100644 --- a/website/node/public-government.mjs +++ b/website/node/public-government.mjs @@ -1,22 +1,19 @@ -import {electionDates,electionWindow} from '../control-panel/public/election-rules.mjs'; -export const PUBLIC_OFFICES=Object.freeze([ - {key:'emperor',kind:'imperial',faction:'imperium',office:'emperor',name:'Office of the Emperor',scope:'The Imperium',art:'emperor-v1.png',description:'The elected imperial office, representing the realms across the Imperium.'}, - ...[['atreides','House Aerdrecht','house-aerdrecht-v1.png'],['harkonnen','House Harkveen','house-harkveen-v1.png'],['corrino','House Korenholt','house-korenholt-v1.png'],['ordos','House Oordwijk','house-oordwijk-v1.png'],['fremen','Vrijduin','house-vrijduin-v1.png'],['veiled_concord','The Veiled Concord','veiled-concord-v1.png']].map(([faction,scope,art])=>({key:faction,kind:faction==='veiled_concord'?'court':'house',faction,office:faction==='veiled_concord'?'reverent_mother':'house_leader',name:faction==='veiled_concord'?'Office of the Reverent Mother':faction==='fremen'?'Office of the Naib':scope+' Leadership',scope,art,description:faction==='veiled_concord'?'The elected leadership of the Veiled Concord.':'The elected leadership and public representation of '+scope+'.'})), - {key:'spacing_guild',kind:'court',faction:'spacing_guild',office:'guild_leader',name:'Vaerkring Leadership',scope:'Vaerkring · Spacing Guild',art:'office-landsraad.png',description:'The economic branch of the Imperial Court, connecting companies and their trade interests.'} -]); +import {ELECTION_RULES,electionDates,electionWindow} from '../control-panel/public/election-rules.mjs'; +import {ELECTIONS} from '../control-panel/public/political-catalog.mjs'; +export const PUBLIC_OFFICES=Object.freeze(ELECTIONS.map(e=>({key:({bene:'veiled_concord',guild:'spacing_guild','clan-delegate':'clan_delegate'})[e.id]||e.id,kind:e.kind,faction:e.faction,office:({imperial:'emperor',house:'house_leader',bene:'reverent_mother',guild:'guild_leader',clan_delegate:'clan_delegate'})[e.kind],name:e.label,scope:e.kind==='house'?e.label.replace(' Leader',''):e.label,chamber:e.chamber,art:e.seal,description:e.chamber+' · Elected for four weeks.'}))); export function projectGovernment(terms,now=Date.now()){ return PUBLIC_OFFICES.map(office=>{ - const ledgerKind=office.faction==='veiled_concord'?'house':office.kind; - const active=terms.filter(t=>t.kind===ledgerKind&&t.faction===office.faction&&t.office===office.office&&t.outcome==='winner'&&Number(t.starts_at)<=now&&Number(t.expires_at)>now); + const ledgerKinds=office.kind==='bene'?['bene','house']:office.kind==='guild'?['guild','court']:[office.kind]; + const active=terms.filter(t=>ledgerKinds.includes(t.kind)&&t.faction===office.faction&&t.office===office.office&&t.outcome==='winner'&&Number(t.starts_at)<=now&&Number(t.expires_at)>now); const term=active.length===1?active[0]:null; const holder=term&&/^[a-z0-9_]{3,32}$/i.test(term.username||'')?{username:term.username,name:term.display_name||term.username,profile:'/people/'+encodeURIComponent(term.username),avatar:'https://cp.dunerealms.com/api/avatars/face/roster/'+encodeURIComponent(term.username)}:null; return {...office,state:holder?'occupied':active.length?'verification_pending':'vacant',holder,term:holder?{startsAt:Number(term.starts_at),expiresAt:Number(term.expires_at)}:null}; }); } export function publicElectionCalendar(now=Date.now()){ - return ['house','imperial'].map(kind=>{ + return Object.keys(ELECTION_RULES).map(kind=>{ const dates=electionDates(kind,now-3*3600000,1),window=electionWindow(kind,dates[0],now); - return {kind,...window,termWeeks:kind==='house'?2:4}; + return {kind,...window,termWeeks:4}; }); } export async function readGovernmentOffices(db,now=Date.now()){ @@ -28,6 +25,6 @@ export function createPublicGovernment(db,{clock=Date.now}={}){return async requ if(new URL(request.url).search)return Response.json({message:'No identity overrides are accepted.'},{status:400}); try{ const now=clock(),offices=await readGovernmentOffices(db,now); - return Response.json({structure:{landsraad:['emperor','atreides','harkonnen','corrino','ordos'],realms:['atreides','harkonnen','corrino','ordos','fremen'],court:['veiled_concord','spacing_guild'],clanAffiliation:'home_world',companiesBranch:'spacing_guild'},offices,elections:publicElectionCalendar(now),observedAt:now},{headers:{'Cache-Control':'public,max-age=30'}}); + return Response.json({structure:{landsraad:['emperor','atreides','harkonnen','corrino','ordos'],realms:['atreides','harkonnen','corrino','ordos','fremen'],court:['veiled_concord','spacing_guild','clan_delegate'],chambers:[{name:'Imperial Senate',offices:['emperor','atreides','harkonnen','corrino','ordos']},{name:'Small Council',offices:['veiled_concord','spacing_guild','clan_delegate']}],clanAffiliation:'home_world',companiesBranch:'spacing_guild'},offices,elections:publicElectionCalendar(now),observedAt:now},{headers:{'Cache-Control':'public,max-age=30'}}); }catch{return Response.json({message:'The public office register is temporarily unavailable.'},{status:503,headers:{'Cache-Control':'no-store'}});} };} diff --git a/website/tests/member-political-offices.test.mjs b/website/tests/member-political-offices.test.mjs index a740aed8..7cab3ac8 100644 --- a/website/tests/member-political-offices.test.mjs +++ b/website/tests/member-political-offices.test.mjs @@ -33,7 +33,7 @@ test('disabled identities and missing office data never invent an office',async( }); test('court offices use their own existing seals and labels',async()=>{ - const {db,term}=fixture();try{await term({faction:'veiled_concord',office:'reverent_mother'});await term({kind:'court',faction:'spacing_guild',office:'guild_leader'});const data=await memberPoliticalOffices(db,{username:'CitizenQA'},{clock});assert.equal(data.records.length,2);assert(data.records.some(r=>r.seal.endsWith('/veiled-concord-v1.png')));assert(data.records.some(r=>r.label==='Vaerkring Leadership'));}finally{db.close();} + const {db,term}=fixture();try{await term({faction:'veiled_concord',office:'reverent_mother'});await term({kind:'court',faction:'spacing_guild',office:'guild_leader'});const data=await memberPoliticalOffices(db,{username:'CitizenQA'},{clock});assert.equal(data.records.length,2);assert(data.records.some(r=>r.seal.endsWith('/veiled-concord-v1.png')));assert(data.records.some(r=>r.label==='Spacing Guild Leader'));}finally{db.close();} }); class Node{constructor(tag){this.tagName=tag.toUpperCase();this.children=[];this._text='';}set textContent(value){this._text=String(value);this.children=[];}get textContent(){return this._text+this.children.map(n=>n.textContent).join('');}append(...nodes){this.children.push(...nodes);}replaceChildren(...nodes){this.children=[];this._text='';this.append(...nodes);}} diff --git a/website/tests/public-government.test.mjs b/website/tests/public-government.test.mjs index 8c0889a9..0aa9f29a 100644 --- a/website/tests/public-government.test.mjs +++ b/website/tests/public-government.test.mjs @@ -3,5 +3,5 @@ import {projectGovernment,createPublicGovernment,publicElectionCalendar} from '. const now=Date.parse('2026-11-15T10:00:00Z'); test('every office remains present before the first election',()=>{const offices=projectGovernment([],now);assert.equal(offices.length,8);assert.ok(offices.every(o=>o.state==='vacant'&&o.holder===null));assert.equal(offices.filter(o=>o.kind==='imperial').length,1);}); test('only a single active elected term can supply an officeholder',()=>{const term={kind:'imperial',faction:'imperium',office:'emperor',outcome:'winner',starts_at:now-1,expires_at:now+1,username:'citizen_one',display_name:'Citizen One',player_uuid:'private'};const office=projectGovernment([term],now)[0];assert.equal(office.state,'occupied');assert.equal(office.holder.profile,'/people/citizen_one');assert.ok(!JSON.stringify(office).includes('private'));for(const row of [{...term,expires_at:now},{...term,starts_at:now+1},{...term,outcome:'no_votes'}])assert.equal(projectGovernment([row],now)[0].state,'vacant');assert.equal(projectGovernment([term,term],now)[0].state,'verification_pending');}); -test('public calendar includes the currently open voting window',()=>{const calendar=publicElectionCalendar(now);assert.equal(calendar[0].phase,'voting');assert.equal(calendar[0].termWeeks,2);assert.equal(calendar[1].phase,'applications');}); +test('public calendar includes the currently open voting window',()=>{const calendar=publicElectionCalendar(now);assert.equal(calendar[0].phase,'voting');assert.equal(calendar[0].termWeeks,4);assert.equal(calendar[1].phase,'applications');}); test('public office read rejects overrides and never invents vacancies on a database outage',async()=>{const api=createPublicGovernment({prepare(){throw Error('DB unavailable');}},{clock:()=>now});assert.equal((await api(new Request('https://www.dunerealms.com/api/public/government?user=other'))).status,400);assert.equal((await api(new Request('https://www.dunerealms.com/api/public/government',{method:'POST'}))).status,405);const response=await api(new Request('https://www.dunerealms.com/api/public/government'));assert.equal(response.status,503);assert.equal((await response.json()).offices,undefined);}); diff --git a/website/tests/voting-directory.test.mjs b/website/tests/voting-directory.test.mjs new file mode 100644 index 00000000..72ffaaa0 --- /dev/null +++ b/website/tests/voting-directory.test.mjs @@ -0,0 +1,41 @@ +import test from 'node:test';import assert from 'node:assert/strict'; +import {LocalD1} from './d1-adapter.mjs'; +import {createElectionDirectory,directoryQuery} from '../control-panel/election-directory.mjs'; +import {castBallot,validateBallot,electionOutcome} from '../control-panel/election-ballots.mjs'; +import {ELECTION_RULES,electionDates,validateCandidature} from '../control-panel/public/election-rules.mjs'; +import {ELECTIONS} from '../control-panel/public/political-catalog.mjs'; +import {createElectionVoting} from '../control-panel/election-voting.mjs'; +const id=n=>'00000000-0000-4000-8000-'+String(n).padStart(12,'0'),actor={id:id(1)},player=id(2),candidate=id(3),roundId=id(4),start='2026-11-15T15:00:00.000Z',now=Date.parse(start)+1000; +const input=(kind='imperial',votes=1)=>({kind,start,roundId,requestId:id(5),confirmed:true,allocations:[{applicationId:candidate,votes}]}),context={linked:true,playerUuid:player,faction:'atreides',houseLeader:false}; +test('all agreed offices belong to two chambers and use four-week calendars',()=>{assert.equal(ELECTIONS.length,8);assert.deepEqual([...new Set(ELECTIONS.map(e=>e.chamber))],['Imperial Senate','Small Council']);for(const kind of Object.keys(ELECTION_RULES)){const dates=electionDates(kind,Date.parse('2026-11-14'),2);assert.equal(Date.parse(dates[1])-Date.parse(dates[0]),28*86400000);}}); +test('existing imperial allowances, confirmation, allocation limits and runoff ties remain intact',()=>{assert.equal(validateBallot(input(),context,now).capacity,1);assert.equal(validateBallot(input('imperial',5),{...context,houseLeader:true},now).capacity,5);assert.throws(()=>validateBallot(input('imperial',2),context,now));assert.throws(()=>validateBallot({...input(),confirmed:false},context,now));assert.throws(()=>validateBallot(input(),context,Date.parse(start)+10800000));assert.deepEqual(electionOutcome([{id:'a',votes:2},{id:'b',votes:2}]).runoff,['a','b']);}); +test('Small Council permits verified citizens without faction; Clan Delegate requires clan leadership',()=>{for(const kind of ['bene','guild'])assert.equal(validateBallot(input(kind),{...context,faction:null},now).capacity,1);assert.throws(()=>validateBallot(input('clan_delegate'),context,now));assert.equal(validateBallot(input('clan_delegate'),{...context,clanId:id(9),clanLeader:true},now).capacity,1);assert.throws(()=>validateCandidature({kind:'clan_delegate',start,accepted:true,motivation:'A thoughtful campaign for every clan.'},context,now-2000));}); +function ballots(kind='imperial'){ + const db=new LocalD1(`CREATE TABLE political_election_rounds(id TEXT PRIMARY KEY,kind TEXT,faction TEXT,election_start INTEGER,status TEXT,opens_at INTEGER,closes_at INTEGER);CREATE TABLE political_voters(round_id TEXT,player_uuid TEXT,kind TEXT,election_start INTEGER,user_id TEXT,faction TEXT,capacity INTEGER,spent INTEGER,PRIMARY KEY(player_uuid,round_id));CREATE TABLE political_ballots(id TEXT PRIMARY KEY,round_id TEXT,request_id TEXT,player_uuid TEXT,kind TEXT,election_start INTEGER,payload TEXT,created_at INTEGER,UNIQUE(player_uuid,request_id));CREATE TABLE political_ballot_allocations(ballot_id TEXT,application_id TEXT,votes INTEGER);CREATE TABLE political_ballot_events(id TEXT,ballot_id TEXT,actor_id TEXT,event TEXT,created_at INTEGER);CREATE TABLE political_applications(id TEXT,kind TEXT,faction TEXT,election_start INTEGER,status TEXT);CREATE TABLE political_round_candidates(round_id TEXT,application_id TEXT);CREATE TABLE site_game_links(user_id TEXT,minecraft_uuid TEXT);CREATE TABLE site_clans(id TEXT PRIMARY KEY,owner_id TEXT,active INTEGER);CREATE TABLE site_clan_members(clan_id TEXT,user_id TEXT,clan_role TEXT,minecraft_uuid TEXT);CREATE TABLE political_clan_votes(round_id TEXT,clan_id TEXT,ballot_id TEXT,PRIMARY KEY(round_id,clan_id));`); + const faction=({imperial:'imperium',bene:'veiled_concord',guild:'spacing_guild',clan_delegate:'clans'})[kind]; + db.sqlite.prepare('INSERT INTO political_election_rounds VALUES(?,?,?,?,?,?,?)').run(roundId,kind,faction,Date.parse(start),'open',Date.parse(start),Date.parse(start)+10800000); + db.sqlite.prepare('INSERT INTO political_applications VALUES(?,?,?,?,?)').run(candidate,kind,faction,Date.parse(start),'submitted');db.sqlite.prepare('INSERT INTO political_round_candidates VALUES(?,?)').run(roundId,candidate);db.sqlite.prepare('INSERT INTO site_game_links VALUES(?,?)').run(actor.id,player); + const execute=async(sql,args=[])=>{sql=sql.replace(/ FOR (UPDATE|SHARE)/g,'');if(sql.includes('ON DUPLICATE KEY'))sql=sql.replace('INSERT INTO','INSERT OR IGNORE INTO').replace(/ ON DUPLICATE KEY UPDATE.*/,'');const statement=db.sqlite.prepare(sql);return [statement.columns().length?statement.all(...args):statement.run(...args)];}; + db.batch=async statements=>{db.sqlite.exec('BEGIN');try{const results=[];for(const s of statements)results.push(await s.run({execute}));db.sqlite.exec('COMMIT');return results;}catch(error){db.sqlite.exec('ROLLBACK');throw error;}}; + return db; +} +test('direct card payload uses the existing transactional ballot, audit and idempotency',async()=>{const db=ballots();try{const args={actor,context,input:input(),now,clock:()=>now};assert.equal((await castBallot(db,args)).remaining,0);assert.equal((await castBallot(db,args)).created,false);await assert.rejects(castBallot(db,{...args,input:{...input(),requestId:id(6)}}));assert.equal(db.sqlite.prepare('SELECT COUNT(*) AS n FROM political_ballots').get().n,1);assert.equal(db.sqlite.prepare('SELECT COUNT(*) AS n FROM political_ballot_events').get().n,1);}finally{db.close();}}); +test('foreign candidates and changed linked identities roll back without spending votes',async()=>{for(const changed of ['candidate','link']){const db=ballots();try{if(changed==='candidate')db.sqlite.exec('DELETE FROM political_round_candidates');else db.sqlite.prepare('UPDATE site_game_links SET minecraft_uuid=?').run(id(8));await assert.rejects(castBallot(db,{actor,context,input:input(),now,clock:()=>now}));assert.equal(db.sqlite.prepare('SELECT COUNT(*) AS n FROM political_ballots').get().n,0);assert.equal(db.sqlite.prepare('SELECT COUNT(*) AS n FROM political_voters').get().n,0);}finally{db.close();}}}); +test('both new citizen ballots use their correct election scope and audit mechanism',async()=>{for(const kind of ['bene','guild']){const db=ballots(kind);try{assert.equal((await castBallot(db,{actor,context:{...context,faction:null},input:input(kind),now,clock:()=>now})).remaining,0);}finally{db.close();}}}); +test('one clan vote survives leadership transfer; inactive or unlinked leaders cannot vote',async()=>{const db=ballots('clan_delegate'),clanId=id(9);try{db.sqlite.prepare('INSERT INTO site_clans VALUES(?,?,1)').run(clanId,actor.id);db.sqlite.prepare("INSERT INTO site_clan_members VALUES(?,?,'owner',?)").run(clanId,actor.id,player);const args={actor,context:{...context,clanId,clanLeader:true},input:input('clan_delegate'),now,clock:()=>now};await castBallot(db,args);const next={id:id(10)},uuid=id(11);db.sqlite.prepare('UPDATE site_clans SET owner_id=?').run(next.id);db.sqlite.prepare('UPDATE site_clan_members SET user_id=?,minecraft_uuid=?').run(next.id,uuid);db.sqlite.prepare('INSERT INTO site_game_links VALUES(?,?)').run(next.id,uuid);await assert.rejects(castBallot(db,{...args,actor:next,context:{...args.context,playerUuid:uuid},input:{...input('clan_delegate'),requestId:id(12)}}));assert.equal(db.sqlite.prepare('SELECT COUNT(*) AS n FROM political_clan_votes').get().n,1);assert.equal(db.sqlite.prepare('SELECT COUNT(*) AS n FROM political_ballots').get().n,1);}finally{db.close();}}); +function directory(){const db=new LocalD1(`CREATE TABLE political_applications(id TEXT,public_id TEXT,kind TEXT,faction TEXT,election_start INTEGER,motivation TEXT,status TEXT,user_id TEXT);CREATE TABLE site_accounts(id TEXT,username TEXT,display_name TEXT,password_hash TEXT);CREATE TABLE site_profiles(user_id TEXT,bio TEXT);CREATE TABLE political_election_rounds(id TEXT,kind TEXT,faction TEXT,election_start INTEGER,round_number INTEGER,status TEXT,opens_at INTEGER,closes_at INTEGER);CREATE TABLE political_round_candidates(round_id TEXT,application_id TEXT);`);db.sqlite.prepare('INSERT INTO site_accounts VALUES(?,?,?,?)').run(actor.id,'CandidateOne','Candidate One','hash');db.sqlite.prepare('INSERT INTO site_profiles VALUES(?,?)').run(actor.id,'A public biography');db.sqlite.prepare('INSERT INTO political_applications VALUES(?,?,?,?,?,?,?,?)').run(candidate,'APP-IMP-1','imperial','imperium',Date.parse(start),'A campaign for citizens','submitted',actor.id);const api=createElectionDirectory(db,{authenticate:async()=>actor,access:async()=>({nodes:['web.menu.game']}),clock:()=>now-2000});return{db,api};} +test('directory search covers public biographies and campaigns; filters and pagination are server-side',async()=>{const{db,api}=directory();try{for(const q of ['biography','campaign','CandidateOne']){const r=await api(new Request('https://cp.dunerealms.com/api/politics/directory?election=emperor&status=upcoming&q='+q));assert.equal(r.status,200);const data=await r.json();assert.equal(data.total,1);assert.equal(data.applications[0].phase,'upcoming');assert.equal(data.applications[0].bio,'A public biography');assert(!JSON.stringify(data).includes(actor.id));}assert.equal((await(await api(new Request('https://cp.dunerealms.com/api/politics/directory?q=%25'))).json()).total,0);assert.equal((await(await api(new Request('https://cp.dunerealms.com/api/politics/directory?page=1'))).json()).applications.length,0);}finally{db.close();}}); +test('directory rejects invalid filters, writes and unauthenticated access',async()=>{assert.throws(()=>directoryQuery(new URL('https://a.test/?election=unknown')));assert.throws(()=>directoryQuery(new URL('https://a.test/?page=-1')));const{db,api}=directory();try{assert.equal((await api(new Request('https://cp.dunerealms.com/api/politics/directory',{method:'POST'}))).status,405);assert.equal((await createElectionDirectory(db,{authenticate:async()=>null})(new Request('https://cp.dunerealms.com/api/politics/directory'))).status,401);}finally{db.close();}}); +test('original ballot HTTP eligibility and allowances remain authoritative for card voting',async()=>{ + const db={prepare(){return{bind(){return this;},async all(){return{results:[]};},async first(){return null;}};}}; + const route=(verified,extra={})=>createElectionVoting(db,{}, {authenticate:async()=>actor,access:async()=>({nodes:['web.menu.game']}),excluded:async()=>false,linked:async()=>player,preview:async()=>Response.json({linked:true,factionStatus:'verified',officeStatus:'verified',faction:'atreides',...verified}),advance:async()=>null,clock:()=>now,...extra}); + const request=kind=>new Request('https://cp.dunerealms.com/api/politics/ballot/'+kind); + assert.equal((await(await route({})(request('house'))).json()).remaining,1); + assert.equal((await(await route({houseLeader:true})(request('imperial'))).json()).remaining,5); + assert.equal((await(await route({faction:'fremen'})(request('imperial'))).json()).remaining,1); + assert.equal((await route({officeStatus:'unavailable'})(request('imperial'))).status,503); + assert.equal((await route({faction:null,factionStatus:'unavailable'})(request('house'))).status,403); + assert.equal((await route({faction:null,factionStatus:'unavailable'})(request('guild'))).status,200); + assert.equal((await route({})(new Request(request('imperial'),{method:'POST',headers:{Origin:'https://evil.invalid'}}))).status,403); + assert.equal((await route({},{linked:async()=>null})(request('imperial'))).status,403); +}); From 84edcf31e71ed3ce77cbc15b9535050ebcbb341f Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:43:04 +0100 Subject: [PATCH 3/4] Build central Political CP with campaign cards and imperial artwork --- website/control-panel/politics-cp-shell.mjs | 4 +- .../public/cp-v2/cp-v2-politics-native.css | 17 +++++++ .../cp-v2/cp-v2-politics-navigation.mjs | 6 ++- .../public/cp-v2/cp-v2-politics-pages.mjs | 2 + .../public/cp-v2/cp-v2-politics-shell.css | 36 +++++++++++++++ .../public/cp-v2/cp-v2-politics-shell.mjs | 29 ++++++------ .../public/cp-v2/cp-v2-voting-directory.mjs | 42 ++++++++++++++++++ .../public/election-applications-view.mjs | 8 ++-- website/control-panel/public/politics.mjs | 6 +-- website/docs/political-artwork.md | 8 ++++ website/node/electoral-roll.mjs | 2 +- website/tests/political-cp.test.mjs | 9 ++-- .../assets/political-imperial-chamber-v1.png | Bin 0 -> 2178011 bytes .../web/assets/political-small-council-v1.png | Bin 0 -> 2124819 bytes website/web/government-cp.css | 2 + website/web/government-cp.js | 2 +- website/web/government.html | 2 +- website/web/government.js | 8 ++-- 18 files changed, 148 insertions(+), 35 deletions(-) create mode 100644 website/control-panel/public/cp-v2/cp-v2-voting-directory.mjs create mode 100644 website/docs/political-artwork.md create mode 100644 website/web/assets/political-imperial-chamber-v1.png create mode 100644 website/web/assets/political-small-council-v1.png diff --git a/website/control-panel/politics-cp-shell.mjs b/website/control-panel/politics-cp-shell.mjs index 1bb071cc..d6b67d1a 100644 --- a/website/control-panel/politics-cp-shell.mjs +++ b/website/control-panel/politics-cp-shell.mjs @@ -8,8 +8,8 @@ export function politicsCPDocument(source){ .replace(//,'') .replace('','') .replace('✦ DuneRealms','✦ Political CP') - .replace('CONTROL PANEL V2Your imperial workspace','REALMS · COURT · LANDSRAADElections, Offices & Tools') - .replace('class="portals" aria-label="Workspace portals"','class="portals" role="tablist" aria-label="Political workspace"') + .replace('CONTROL PANEL V2Your imperial workspace','IMPERIAL SENATE · SMALL COUNCILFour-week terms · Elections & Offices') + .replace('class="portals" aria-label="Workspace portals"','class="portals" hidden aria-hidden="true"') .replace('aria-controls="sidebar"','aria-controls="sidebar sidebar-right"') .replace(/') .replace('',''); diff --git a/website/control-panel/public/cp-v2/cp-v2-politics-native.css b/website/control-panel/public/cp-v2/cp-v2-politics-native.css index 03faad58..7b96d4d2 100644 --- a/website/control-panel/public/cp-v2/cp-v2-politics-native.css +++ b/website/control-panel/public/cp-v2/cp-v2-politics-native.css @@ -1,3 +1,20 @@ body[data-service=politics]{color-scheme:light;background:#fffcf6;color:#34271f;font-family:Georgia,serif;min-height:0}body[data-service=politics] a{color:#71342d}body[data-service=politics] h1,body[data-service=politics] h2,body[data-service=politics] h3,body[data-service=politics] h4{color:#632f2c}body[data-service=politics] .politics-card,body[data-service=politics] .politics-charter,body[data-service=politics] .politics-candidate,body[data-service=politics] .politics-calendar-card,body[data-service=politics] .politics-leaders,body[data-service=politics] table{background:#f6eddd;color:#34271f;border-color:#bfa77b;box-shadow:none}body[data-service=politics] input,body[data-service=politics] textarea,body[data-service=politics] select,body[data-service=politics] button{background:#fffcf6;color:#4b3229;border:1px solid #aa8755}body[data-service=politics] button:disabled{opacity:.6}body[data-service=politics] .politics-calendar li,body[data-service=politics] .politics-calendar time,body[data-service=politics] th,body[data-service=politics] td{background:#f3e7d1;color:#4b3229;border-color:#c5ae83}body[data-service=politics] .politics-demo-note{color:#755326;background:#ede0c7}body[data-service=politics] .politics-oath{color:#71342d} body[data-service=politics] .politics-card,body[data-service=politics] .politics-charter,body[data-service=politics] .politics-candidate,body[data-service=politics] .politics-calendar-card,body[data-service=politics] .politics-leaders{border:3px double #c7a05a;border-radius:7px;box-shadow:inset 0 0 0 3px #efe0c0} +/* Scope above the legacy faction skins so every political page stays readable. */ +body[data-service=politics]{background:#33252a;color:#f0e3ca;color-scheme:dark} +body[data-service=politics] #dashboard{background:#33252a;color:#f0e3ca;border-color:#ab8c54;padding:10px} +body[data-service=politics] #dashboard .politics-page{background:transparent;color:#f0e3ca;padding:10px} +body[data-service=politics] #dashboard .politics-page :is(.politics-card,.politics-charter,.politics-candidate,.politics-calendar-card,.politics-leaders,.politics-hero,.politics-oath){background:linear-gradient(110deg,#432931ed,#2e2027f5),url('https://www.dunerealms.com/assets/political-small-council-v1.png') center/cover!important;color:#f0e3ca;border:3px double #b7975b;box-shadow:none} +body[data-service=politics] #dashboard .politics-page :is(h1,h2,h3,h4,h5,summary,strong,a,.politics-candidate-count){color:#f0cf8f} +body[data-service=politics] #dashboard .politics-page :is(p,small,label,li,dt,dd,span,time){color:#e6dac4} +body[data-service=politics] #dashboard .politics-page :is(input,textarea,select){background:#ded0b9;color:#342329;border:1px solid #b7975b;accent-color:#9f6c4c;box-sizing:border-box;max-width:100%} +body[data-service=politics] #dashboard .politics-page button{background:linear-gradient(#d5b46a,#ae8c48);color:#2c1b20;border:1px solid #e0be7b;box-shadow:none} +body[data-service=politics] #dashboard .politics-page :is(th,td,.politics-calendar li,.politics-calendar time){background:#432e36;color:#f0e3ca;border-color:#a98c5555} +body[data-service=politics] #dashboard .politics-page :is(.politics-demo-note,.politics-intro){background:#51363c;color:#eedfc1;border-color:#ab8c54} +body[data-service=politics] #dashboard .politics-page :is(input,textarea,select):focus-visible{outline:2px solid #edcc80;outline-offset:2px} +body[data-service=politics] #dashboard .politics-page a{color:#f0cf8f;text-decoration-thickness:1px;text-underline-offset:3px} +body[data-service=politics] #dashboard .politics-page .politics-hero{min-height:190px;background:linear-gradient(90deg,#35171fe8,#35171f88),url('https://www.dunerealms.com/assets/political-imperial-chamber-v1.png') center/cover!important} +body[data-service=politics] #service-heading{display:none} +body[data-service=politics] #dashboard .politics-page .politics-preview-note{background:#51353d;color:#f0dfc1;border-color:#aa8b54} +body[data-service=politics] #dashboard .politics-page .politics-card a{background:#50313b;color:#f0cf8f;border-color:#ad8c53} diff --git a/website/control-panel/public/cp-v2/cp-v2-politics-navigation.mjs b/website/control-panel/public/cp-v2/cp-v2-politics-navigation.mjs index a43ffed4..e9881b29 100644 --- a/website/control-panel/public/cp-v2/cp-v2-politics-navigation.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-politics-navigation.mjs @@ -1,6 +1,8 @@ +import {ELECTIONS} from '../political-catalog.mjs'; export const POLITICAL_TABS=Object.freeze([ - {id:'elections',label:'Elections',pages:[['house-elections','Faction Elections'],['imperial-elections','Emperor Elections'],['applications','Applications'],['electoral-roll','Electoral Roll']]}, - {id:'offices',label:'Offices',pages:[['office-register','Government & Offices'],['politics-overview','Your Political Record'],['landsraad','Landsraad Assembly'],['formal-council','Faction Council'],['imperial-command','Imperial Council']]}, + {id:'elections',label:'Elections',pages:[['house-elections','Faction Elections'],['imperial-elections','Emperor Elections'],...ELECTIONS.filter(e=>e.kind!=='house'&&e.kind!=='imperial').map(e=>['election-'+e.id,e.label]),['applications','My applications'],['electoral-roll','Electoral Roll']]}, + {id:'directory',label:'Voting Directory',pages:[['all-applications','All applications'],...ELECTIONS.map(e=>['candidates-'+e.id,e.label])]}, + {id:'offices',label:'Offices',pages:[['office-register','Government & Offices'],['imperial-senate','Imperial Senate'],['small-council','Small Council'],['politics-overview','Your Political Record'],['landsraad','Landsraad Assembly'],['formal-council','Faction Council'],['imperial-command','Imperial Council']]}, {id:'tools',label:'Tools',pages:[['council-motd','Proclamations'],['imperial-water','Water Rights'],['imperial-spice','Spice Rights']]} ]); export function politicalRoute(value=''){ diff --git a/website/control-panel/public/cp-v2/cp-v2-politics-pages.mjs b/website/control-panel/public/cp-v2/cp-v2-politics-pages.mjs index 843f7414..8f4d8939 100644 --- a/website/control-panel/public/cp-v2/cp-v2-politics-pages.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-politics-pages.mjs @@ -1,8 +1,10 @@ +import {mountVotingDirectory} from './cp-v2-voting-directory.mjs'; import {mountNativeService} from './cp-v2-native-services.mjs'; import {createCPV2Page,element as el} from './cp-v2-page-template.mjs'; import {createUserAPI} from './cp-v2-user-api.mjs'; export const POLITICS_PAGES=Object.freeze({'landsraad':'Landsraad Assembly','council-motd':'Proclamations','house-elections':'House Elections','imperial-elections':'Emperor Elections','applications':'Election Applications','electoral-roll':'Electoral Roll','formal-council':'Faction Council','imperial-command':'Imperial Council','imperial-water':'Water Rights','imperial-spice':'Spice Rights'}); export function mountPoliticsPage(host,id,{fetcher=fetch}={}){ + if(id==='all-applications'||id.startsWith('candidates-')||id.startsWith('election-'))return mountVotingDirectory(host,id==='all-applications'?'':id.replace(/^(candidates-|election-)/,'')); if(Object.hasOwn(POLITICS_PAGES,id))return mountNativeService(host,'politics',{fetcher,singleHeading:true,title:POLITICS_PAGES[id],initialTab:id}); if(id!=='politics-overview')throw Error('Unknown political workspace.'); const controller=new AbortController(),api=createUserAPI(fetcher,controller.signal);let active=true; diff --git a/website/control-panel/public/cp-v2/cp-v2-politics-shell.css b/website/control-panel/public/cp-v2/cp-v2-politics-shell.css index 19b45ef5..41dbbbbe 100644 --- a/website/control-panel/public/cp-v2/cp-v2-politics-shell.css +++ b/website/control-panel/public/cp-v2/cp-v2-politics-shell.css @@ -8,3 +8,39 @@ html:has(body.politics-cp-embedded){overflow:hidden}body.politics-cp-shell{displ .politics-cp-shell button,.politics-cp-shell input,.politics-cp-shell select{background:#f6ecda;color:#4b3229;border-color:#aa8755}.politics-cp-shell .cp-v2-auth{background:#fffcf6;color:#38271f;border-color:#c7a05a}.politics-cp-shell .alpha-stat{background:#f4ebdb;color:#4b3229;border-color:#c7a05a}.politics-cp-shell .cp-v2-native-frame iframe{width:100%;border:0}.politics-office-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}.politics-office-card{border:3px double #c7a05a;border-radius:7px;box-shadow:inset 0 0 0 3px #efe0c0;background:linear-gradient(145deg,#fff7e5,#f0e2c7);padding:22px;display:flex;flex-direction:column;align-items:flex-start;gap:9px;min-width:0}.politics-office-card h2,.politics-office-card p{margin:0}.politics-cp-shell .politics-office-card h2{font-size:23px}.politics-office-card img{object-fit:contain}.politics-office-card small{letter-spacing:.08em;text-transform:uppercase;font:11px Arial,sans-serif} .politics-cp-shell .content .cards>.card.citizen-page-full{background:linear-gradient(140deg,#fffcf6,#f4ead7)!important;border:4px double #c7a05a!important;box-shadow:inset 0 0 0 4px #efe0c0,0 7px 16px #3c1b211a!important} @media(max-width:1100px){.politics-office-grid{grid-template-columns:1fr}}@media(max-width:720px){.politics-cp-shell .portals{grid-template-columns:repeat(3,minmax(0,1fr))}.politics-cp-shell .mobile-tools{background:#eee4d2}.politics-cp-shell .side.open{max-height:none;overflow:visible}} +/* Political chambers share the CP geometry, with a quieter parchment and burgundy palette. */ +body.politics-cp-shell{--political-art:url('https://www.dunerealms.com/assets/political-imperial-chamber-v1.png');background:#c9bba5;color:#f0e3ca} +body.politics-cp-shell #portals{display:none!important} +.politics-cp-shell .content{background:linear-gradient(#28171be8,#28171bf5),var(--political-art) center top/cover;color:#f0e3ca;border-color:#b7975b} +.politics-cp-shell .side{background:linear-gradient(#342126ed,#23171bf5),url('https://www.dunerealms.com/assets/political-small-council-v1.png') center/cover;color:#f0e3ca} +.politics-cp-shell .category-block{background:#38262be8;border-color:#9e814d} +.politics-cp-shell .category-heading{background:linear-gradient(90deg,#58333b,#3d272d);color:#eed4a0;border-color:#9e814d} +.politics-cp-shell .navitem{color:#ecdfc6;border-color:#9e814d55} +.politics-cp-shell .navitem:hover,.politics-cp-shell .navitem[aria-current=page]{background:#714550;color:#fff2cf} +.politics-cp-shell .content .hero{min-height:190px;background:linear-gradient(90deg,#35171fe8,#35171f80),var(--political-art) center 48%/cover;color:#f8e8c9;box-shadow:0 6px 20px #160c1055} +.politics-cp-shell .command-banner{background:linear-gradient(90deg,#35171fe8,#35171f9c),var(--political-art) center 22%/cover} +.politics-cp-shell .content .cards>.card.citizen-page-full{background:#33252a!important;border:3px double #b7975b!important;box-shadow:0 8px 22px #10090c33!important;color:#f0e3ca} +.politics-cp-shell .card p,.politics-cp-shell .card small,.politics-cp-shell .cp-v2-native-workspace{color:#e5d7bd} +.politics-cp-shell h2,.politics-cp-shell h3,.politics-cp-shell .alpha-stat strong{color:#efd295} +.politics-cp-shell a{color:#f0cf8f} +.politics-cp-shell .alpha-stat{background:#442d34;color:#f0e3ca;border-color:#a68a54} +.politics-office-card{background:linear-gradient(#3c2530e8,#312126fa),url('https://www.dunerealms.com/assets/political-small-council-v1.png') center/cover;box-shadow:none;border-color:#ad8b4d;color:#ecdfc6} +.politics-cp-shell .card .politics-office-card h2{color:#f0cf8f} +.campaign-filters{display:grid;grid-template-columns:minmax(170px,2fr) minmax(130px,1fr) minmax(120px,1fr);gap:12px;margin-bottom:18px} +.politics-cp-shell .campaign-filters input,.politics-cp-shell .campaign-filters select{width:100%;min-width:0;box-sizing:border-box;border-radius:6px;padding:12px;background:#dfd2bc;color:#38252a} +.campaign-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(100%,300px),1fr));gap:22px;align-items:start} +.campaign-card{overflow:hidden;border:3px double #c4a164;border-radius:10px;background:#39242c;box-shadow:0 8px 20px #120a0e55;min-width:0} +.campaign-portrait{position:relative;min-height:180px;display:flex;align-items:center;padding:26px;background:linear-gradient(90deg,#2b152153,#2b1521b8),url('https://www.dunerealms.com/assets/political-imperial-chamber-v1.png') center/cover;border-bottom:1px solid #c4a164} +.campaign-card:nth-child(even) .campaign-portrait{background-image:linear-gradient(90deg,#2b152153,#2b1521b8),url('https://www.dunerealms.com/assets/political-small-council-v1.png')} +.campaign-portrait>img:first-child{width:112px;height:112px;image-rendering:pixelated;border:3px double #ddbb73;box-shadow:0 6px 18px #0007;border-radius:9px;background:#3b252b} +.campaign-seal{position:absolute;right:20px;top:22px;object-fit:contain;filter:drop-shadow(0 3px 5px #0008)} +.campaign-kicker{position:absolute;bottom:14px;right:18px;font:11px/1.4 Arial,sans-serif;letter-spacing:.12em;text-transform:uppercase;color:#ffe5aa} +.campaign-body{padding:22px}.politics-cp-shell .campaign-body h2{margin:10px 0;font-size:29px;line-height:1.1;overflow-wrap:anywhere}.campaign-body h2 a{text-decoration:none} +.campaign-office{display:block;color:#e6c176}.campaign-bio{font-style:italic;line-height:1.6;border-bottom:1px solid #b7975b55;padding-bottom:16px;white-space:pre-wrap;overflow-wrap:anywhere} +.campaign-message summary{cursor:pointer;color:#f2d494}.campaign-message p{white-space:pre-wrap;overflow-wrap:anywhere;line-height:1.65;max-height:13em;overflow:auto;padding-right:6px} +.campaign-footer{display:flex;justify-content:space-between;align-items:center;gap:12px;margin-top:20px}.campaign-footer>span{font:10px Arial,sans-serif;color:#cdbb9e} +.politics-cp-shell .campaign-footer button,.politics-cp-shell .campaign-confirm button{background:linear-gradient(#d9b96e,#b59450);color:#2c1b20;border:1px solid #edcd83;border-radius:5px;padding:10px 18px;cursor:pointer;font-weight:bold} +.politics-cp-shell button:disabled{opacity:.6;cursor:default}.campaign-pagination{display:flex;align-items:center;gap:12px;margin-top:24px}.campaign-pagination button{padding:9px 14px} +.campaign-confirm{background:#35232b;color:#f4e3c3;border:3px double #c4a164;border-radius:10px;padding:28px;max-width:min(460px,calc(100vw - 48px));box-shadow:0 20px 80px #0008}.campaign-confirm::backdrop{background:#160c13b8;backdrop-filter:blur(4px)}.campaign-confirm label{display:flex;align-items:center;gap:16px}.campaign-confirm input{max-width:100px;padding:9px}.campaign-confirm button{margin:12px 12px 0 0} +@media(max-width:900px){.campaign-filters{grid-template-columns:1fr}.politics-cp-shell .content .hero{min-height:150px}.campaign-portrait{min-height:150px}.campaign-body{padding:18px}} +@media(prefers-reduced-motion:no-preference){.campaign-card{transition:box-shadow .2s,border-color .2s}.campaign-card:hover{border-color:#e1be78;box-shadow:0 10px 25px #10070c77}} diff --git a/website/control-panel/public/cp-v2/cp-v2-politics-shell.mjs b/website/control-panel/public/cp-v2/cp-v2-politics-shell.mjs index 4864dd8a..ddaeaeb3 100644 --- a/website/control-panel/public/cp-v2/cp-v2-politics-shell.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-politics-shell.mjs @@ -1,6 +1,7 @@ import {startCPAuthentication} from './cp-v2-auth.mjs'; import {mountPoliticsPage} from './cp-v2-politics-pages.mjs'; import {element as el} from './cp-v2-page-template.mjs'; +import {ELECTIONS} from '../political-catalog.mjs'; import {POLITICAL_TABS,politicalRoute} from './cp-v2-politics-navigation.mjs'; const outer='https://www.dunerealms.com',content=document.querySelector('#content'),sidebar=document.querySelector('#sidebar'),sidebarRight=document.querySelector('#sidebar-right'),tabs=document.querySelector('#portals'); const artwork={elections:'seals/office-house_leader.png',offices:'seals/office-landsraad.png',tools:'seals/emperor-v1.png'}; @@ -14,28 +15,30 @@ window.addEventListener('message',event=>{if(event.source===parent&&event.origin function show(){ if(!ready)return;const route=politicalRoute(location.hash),key=route.tab+'/'+route.page;if(key===current)return;current=key;dispose();dispose=()=>{}; const tab=POLITICAL_TABS.find(t=>t.id===route.tab),page=tab.pages.find(([id])=>id===route.page); - content.setAttribute('role','tabpanel');content.setAttribute('aria-labelledby','politics-tab-'+tab.id); - for(const button of tabs.children){const selected=button.dataset.tab===tab.id;button.setAttribute('aria-selected',String(selected));button.tabIndex=selected?0:-1;} - sidebar.replaceChildren(el('div',tab.label.toUpperCase(),'side-hero'));sidebarRight.replaceChildren(el('div',tab.label.toUpperCase()+' · DIRECTORY','side-hero')); - const split=Math.ceil(tab.pages.length/2); - for(const [index,pages]of [tab.pages.slice(0,split),tab.pages.slice(split)].entries()){ - const block=el('details',undefined,'category-block');block.open=matchMedia('(min-width:721px)').matches||pages.some(([id])=>id===page[0]);const heading=el('summary',undefined,'category-heading');heading.append(icon(tab.id),el('span',index?'Directory':'Chambers','category-name'),el('span',String(pages.length),'category-count'));block.append(heading);const links=el('div',undefined,'category-links'); - for(const [id,label]of pages){const link=el('a',undefined,'navitem');link.href='#'+tab.id+'/'+id;link.append(icon(tab.id),el('span',label));if(id===page[0])link.setAttribute('aria-current','page');links.append(link);}block.append(links);(index?sidebarRight:sidebar).append(block); - } - const hero=el('header',undefined,'hero'),seal=el('img'),heading=el('div');seal.src=outer+'/assets/seals/office-landsraad.png';seal.alt='';heading.append(el('h1',page[1]),el('p',tab.id==='elections'?'Candidatures, verified eligibility and the existing ballots.':tab.id==='offices'?'The offices, councils and elected representatives of the realms.':'Proclamations and the existing government instruments.'));hero.append(seal,heading); + content.setAttribute('aria-label',page[1]); + sidebar.replaceChildren(el('div','ELECTION CHAMBERS','side-hero'));sidebarRight.replaceChildren(el('div','OFFICES & INSTRUMENTS','side-hero')); + const menu=(host,title,items)=>{const block=el('details',undefined,'category-block');block.open=items.some(([id])=>id===page[0])||title==='Imperial Senate';const summary=el('summary',title,'category-heading'),links=el('div',undefined,'category-links');for(const[id,label]of items){const group=POLITICAL_TABS.find(t=>t.pages.some(([p])=>p===id));const link=el('a',undefined,'navitem');link.href='#'+group.id+'/'+id;link.append(icon(group.id==='directory'?'elections':group.id),el('span',label));if(id===page[0])link.setAttribute('aria-current','page');links.append(link);}block.append(summary,links);host.append(block);}; + menu(sidebar,'Imperial Senate',[['imperial-elections','Emperor election'],['house-elections','House Leader elections']]); + menu(sidebar,'Small Council',ELECTIONS.filter(e=>e.chamber==='Small Council').map(e=>['election-'+e.id,e.label])); + menu(sidebar,'Voting Directory',POLITICAL_TABS.find(t=>t.id==='directory').pages); + menu(sidebar,'Participation',[['applications','My applications'],['electoral-roll','Electoral Roll']]); + menu(sidebarRight,'Offices',[['office-register','All offices'],['imperial-senate','Imperial Senate'],['small-council','Small Council'],['politics-overview','My political record']]); + menu(sidebarRight,'Councils',[['landsraad','Landsraad assembly'],['formal-council','House council'],['imperial-command','Imperial council']]); + menu(sidebarRight,'Tools',POLITICAL_TABS.find(t=>t.id==='tools').pages); + const hero=el('header',undefined,'hero'),seal=el('img'),heading=el('div');seal.src=outer+'/assets/seals/office-landsraad.png';seal.alt='';heading.append(el('h1',page[1]),el('p',tab.id==='directory'?'Meet the candidates, explore their campaigns and cast your eligible votes.':tab.id==='elections'?'Candidatures, verified eligibility and the existing ballots.':tab.id==='offices'?'The offices, councils and elected representatives of the realms.':'Proclamations and the existing government instruments.'));hero.append(seal,heading); const cards=el('div',undefined,'cards'),card=el('article',undefined,'card full citizen-page-full'),host=el('div',undefined,'citizen-live-host');card.append(host);cards.append(card);content.replaceChildren(hero,cards); - dispose=page[0]==='office-register'?mountOfficeRegister(host):mountPoliticsPage(host,page[0]); + dispose=['office-register','imperial-senate','small-council'].includes(page[0])?mountOfficeRegister(host,page[0]):mountPoliticsPage(host,page[0]); history.replaceState(null,'','#'+key);if(parent!==window)parent.postMessage({type:'dune-politics-route',tab:route.tab,page:route.page},outer); sidebar.classList.remove('open');sidebarRight.classList.remove('open');document.querySelector('#mobile-menu').setAttribute('aria-expanded','false');schedule(); } -function mountOfficeRegister(host){ +function mountOfficeRegister(host,view='office-register'){ const controller=new AbortController();let active=true;const status=el('p','Checking the public office register…');status.setAttribute('role','status');host.append(status); fetch('/api/public/government',{credentials:'same-origin',cache:'no-store',signal:controller.signal}).then(async response=>{const data=await response.json();if(!response.ok)throw Error(data.message||'Office register unavailable.');if(!active)return;const grid=el('div',undefined,'politics-office-grid'); - for(const office of data.offices){const card=el('article',undefined,'politics-office-card'),image=el('img');image.src=outer+'/assets/seals/'+office.art;image.alt='';image.width=image.height=76;card.append(image,el('small',office.scope),el('h2',office.name),el('p',office.description));if(office.holder){const link=el('a',office.holder.name);link.href=outer+'/people/'+encodeURIComponent(office.holder.username);link.target='_top';card.append(el('strong','In office'),link);}else card.append(el('p',office.state==='vacant'?'Awaiting an elected officeholder.':'Officeholder verification pending.'));grid.append(card);} + for(const office of data.offices.filter(o=>view==='office-register'||o.chamber===(view==='imperial-senate'?'Imperial Senate':'Small Council'))){const card=el('article',undefined,'politics-office-card'),image=el('img');image.src=outer+'/assets/seals/'+office.art;image.alt='';image.width=image.height=76;card.append(image,el('small',office.scope),el('h2',office.name),el('p',office.description));if(office.holder){const link=el('a',office.holder.name);link.href=outer+'/people/'+encodeURIComponent(office.holder.username);link.target='_top';card.append(el('strong','In office'),link);}else card.append(el('p',office.state==='vacant'?'Awaiting an elected officeholder.':'Officeholder verification pending.'));grid.append(card);} host.replaceChildren(grid); }).catch(error=>{if(active)status.textContent=error.message;});return()=>{active=false;controller.abort();}; } -for(const tab of POLITICAL_TABS){const button=el('button',undefined,'portal');button.append(icon(tab.id),el('span',tab.label));button.type='button';button.dataset.tab=tab.id;button.id='politics-tab-'+tab.id;button.setAttribute('role','tab');button.setAttribute('aria-controls','content');button.onclick=()=>{location.hash=tab.id+'/'+tab.pages[0][0];};button.onkeydown=event=>{if(!['ArrowLeft','ArrowRight','Home','End'].includes(event.key))return;event.preventDefault();const index=POLITICAL_TABS.indexOf(tab),next=event.key==='Home'?0:event.key==='End'?POLITICAL_TABS.length-1:(index+(event.key==='ArrowRight'?1:POLITICAL_TABS.length-1))%POLITICAL_TABS.length;tabs.children[next].click();tabs.children[next].focus();};tabs.append(button);} +tabs.hidden=true;tabs.replaceChildren(); document.querySelector('#mobile-menu').onclick=()=>{const open=sidebar.classList.toggle('open');sidebarRight.classList.toggle('open',open);document.querySelector('#mobile-menu').setAttribute('aria-expanded',String(open));}; window.addEventListener('hashchange',show);window.addEventListener('pagehide',()=>{dispose();observer.disconnect();},{once:true}); startCPAuthentication(user=>{if(!user.permissions?.includes('web.menu.game')){tabs.hidden=true;sidebar.hidden=true;sidebarRight.hidden=true;content.replaceChildren(el('p','Your account does not have access to the political chambers.'));return;}ready=true;show();}); diff --git a/website/control-panel/public/cp-v2/cp-v2-voting-directory.mjs b/website/control-panel/public/cp-v2/cp-v2-voting-directory.mjs new file mode 100644 index 00000000..01518cae --- /dev/null +++ b/website/control-panel/public/cp-v2/cp-v2-voting-directory.mjs @@ -0,0 +1,42 @@ +import {element as el} from './cp-v2-page-template.mjs'; +import {ELECTIONS} from '../political-catalog.mjs'; +export function mountVotingDirectory(host,selected=''){ + const controller=new AbortController();let active=true,page=0,serial=0,timer,busy=false; + const filters=el('form',undefined,'campaign-filters'),search=el('input'),election=el('select'),phase=el('select'),status=el('p','Opening the candidate register…'),grid=el('div',undefined,'campaign-grid'),pages=el('nav',undefined,'campaign-pagination'); + search.type='search';search.placeholder='Search players, biographies and campaign messages';search.setAttribute('aria-label','Search candidates'); + for(const [select,label,items]of [[election,'Election',[['','All elections'],...ELECTIONS.map(e=>[e.id,e.label])]],[phase,'Election status',[['','All statuses'],['upcoming','Applications open'],['voting','Voting open'],['closed','Closed']]]]){select.setAttribute('aria-label',label);for(const[value,text]of items){const option=el('option',text);option.value=value;select.append(option);}} + election.value=selected;status.setAttribute('role','status');filters.append(search,election,phase);host.replaceChildren(filters,status,grid,pages); + const dialog=el('dialog',undefined,'campaign-confirm');dialog.setAttribute('aria-label','Confirm your vote');host.append(dialog); + function card(candidate){ + const scope=ELECTIONS.find(e=>e.kind===candidate.kind&&e.faction===candidate.faction);if(!scope)return null; + const card=el('article',undefined,'campaign-card'),portrait=el('div',undefined,'campaign-portrait'),avatar=el('img'),seal=el('img',undefined,'campaign-seal'); + avatar.src='/api/avatars/face/roster/'+encodeURIComponent(candidate.username);avatar.alt=candidate.username+' Minecraft avatar';avatar.loading='lazy';avatar.onerror=()=>{avatar.onerror=null;avatar.src='/api/avatars/fallback';};avatar.width=avatar.height=128; + seal.src='https://www.dunerealms.com/assets/seals/'+scope.seal;seal.alt=scope.label+' seal';seal.width=seal.height=64;portrait.append(avatar,seal,el('span','Meet your candidate','campaign-kicker')); + const body=el('div',undefined,'campaign-body'),profile=el('a',candidate.name||candidate.username);profile.href='https://www.dunerealms.com/people/'+encodeURIComponent(candidate.username);profile.target='_top';const name=el('h2');name.append(profile); + const date=new Date(candidate.start).toLocaleDateString('en-GB',{timeZone:'UTC',dateStyle:'medium'}); + body.append(el('small',scope.chamber+' · '+date),name,el('strong',scope.label,'campaign-office'),el('p',candidate.bio||'This player has not added a public biography.','campaign-bio')); + const message=el('details',undefined,'campaign-message'),summary=el('summary','Campaign message');message.open=true;message.append(summary,el('p',candidate.motivation));body.append(message); + const footer=el('div',undefined,'campaign-footer'),label=candidate.phase==='voting'&&candidate.round?.eligible?'Vote':candidate.phase==='upcoming'?'Voting opens at election time':'Voting closed',vote=el('button',label);vote.type='button';vote.disabled=label!=='Vote';vote.onclick=()=>confirm(candidate,scope);footer.append(el('span',candidate.publicId),vote);body.append(footer);card.append(portrait,body);return card; + } + async function confirm(candidate,scope){ + if(busy)return;busy=true;dialog.replaceChildren(el('h2','Vote for '+candidate.username+'?'),el('p',scope.label+' · Your submitted vote is final.')); + const feedback=el('p','Checking your eligibility and remaining votes…'),cancel=el('button','Cancel'),submit=el('button','Confirm vote'),amount=el('input'),label=el('label','Votes');amount.type='number';amount.min='1';amount.step='1';amount.value='1';amount.setAttribute('aria-label','Number of votes');label.append(amount);submit.disabled=true;cancel.type=submit.type='button';feedback.setAttribute('role','status');dialog.append(label,feedback,cancel,submit);dialog.showModal(); + cancel.onclick=()=>dialog.close();dialog.onclose=()=>{busy=false;};let ballot; + try{const response=await fetch('/api/politics/ballot/'+candidate.kind,{credentials:'same-origin',cache:'no-store',signal:controller.signal});ballot=await response.json();if(!active)return;if(!response.ok)throw Error(ballot.message||'Could not verify your ballot.'); + if(ballot.faction!==candidate.faction||ballot.start!==candidate.start||ballot.round?.id!==candidate.round?.id||ballot.round?.status!=='open'||Date.now()=ballot.round.closesAt||!ballot.candidates.some(c=>c.id===candidate.id))throw Error('This candidate is outside your current eligible ballot.'); + if(ballot.remaining<1)throw Error('You have no votes remaining for this election.');amount.max=String(ballot.remaining);feedback.textContent=ballot.remaining+' vote(s) available.';submit.disabled=false; + }catch(error){feedback.textContent=error.message;} + const requestId=crypto.randomUUID();let sending=false,payload=null; + submit.onclick=async()=>{if(submit.disabled||sending)return;const votes=Number(amount.value);if(!Number.isInteger(votes)||votes<1||votes>ballot.remaining){feedback.textContent='Choose a whole number within your remaining allowance.';return;} + sending=true;submit.disabled=true;cancel.disabled=true;amount.disabled=true;dialog.oncancel=event=>event.preventDefault(); + payload||={kind:candidate.kind,start:ballot.start,roundId:ballot.round.id,requestId,confirmed:true,allocations:[{applicationId:candidate.id,votes}]}; + try{const response=await fetch('/api/politics/ballot/'+candidate.kind,{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload),signal:controller.signal}),result=await response.json();if(!active)return;if(!response.ok)throw Error(result.message||'Vote not accepted.');feedback.textContent='Your vote is recorded. '+result.ballot.remaining+' vote(s) remain.';submit.remove();cancel.textContent='Close';await load();} + catch(error){feedback.textContent=error.message+' Check your ballot before retrying.';submit.textContent='Retry same submission';submit.disabled=false;} + finally{sending=false;cancel.disabled=false;dialog.oncancel=null;} + }; + } + async function load(){const request=++serial;status.textContent='Loading candidates…';try{const query=new URLSearchParams({q:search.value,election:election.value,status:phase.value,page:String(page)}),response=await fetch('/api/politics/directory?'+query,{cache:'no-store',credentials:'same-origin',signal:controller.signal}),data=await response.json();if(!active||request!==serial)return;if(!response.ok)throw Error(data.message||'Directory unavailable.');grid.replaceChildren();for(const candidate of data.applications){const item=card(candidate);if(item)grid.append(item);}status.textContent=data.total?data.total+' application(s) · grouped by election, newest first.':'No applications match these filters.';pages.replaceChildren();for(const[label,delta]of [['Previous',-1],['Next',1]]){const button=el('button',label);button.type='button';button.disabled=delta<0?page===0:(page+1)*data.pageSize>=data.total;button.onclick=()=>{page+=delta;void load();};pages.append(button);}pages.append(el('span','Page '+(page+1)));} + catch(error){if(active&&request===serial)status.textContent=error.message;}} + filters.onsubmit=event=>{event.preventDefault();page=0;void load();};search.oninput=()=>{clearTimeout(timer);timer=setTimeout(()=>{page=0;void load();},250);};election.onchange=phase.onchange=()=>{page=0;void load();};void load(); + return()=>{active=false;clearTimeout(timer);controller.abort();if(dialog.open)dialog.close();}; +} diff --git a/website/control-panel/public/election-applications-view.mjs b/website/control-panel/public/election-applications-view.mjs index 45c0b871..85be8af8 100644 --- a/website/control-panel/public/election-applications-view.mjs +++ b/website/control-panel/public/election-applications-view.mjs @@ -1,7 +1,7 @@ import {electionDates,electionWindow} from './election-rules.mjs'; const node=(tag,text,cls)=>{const e=document.createElement(tag);if(text!==undefined)e.textContent=text;if(cls)e.className=cls;return e;}; const date=value=>new Date(Number(value)).toLocaleString('en-GB',{timeZone:'UTC',dateStyle:'medium',timeStyle:'short'})+' GMT'; -export function applicationElectionId(row){const code=row.kind==='imperial'?'IMP':row.faction==='veiled_concord'?'CON':'HSE';return 'ELC-'+code+'-'+new Date(Number(row.election_start)).toISOString().slice(0,10).replaceAll('-','');} +export function applicationElectionId(row){const code=row.kind==='guild'?'GLD':row.kind==='clan_delegate'?'CLN':row.kind==='imperial'?'IMP':row.faction==='veiled_concord'?'CON':'HSE';return 'ELC-'+code+'-'+new Date(Number(row.election_start)).toISOString().slice(0,10).replaceAll('-','');} export function renderApplications({user,context}){ const host=node('div',undefined,'applications-dashboard'); const register=node('article',undefined,'politics-card');register.append(node('h3','Your application register'),node('p','Your latest 100 candidatures, round totals and recorded results. Votes shown belong to your latest participating round; runoff votes are counted separately. Cosmetic rank and seal delivery is still being connected.')); @@ -9,8 +9,8 @@ export function renderApplications({user,context}){ const area=node('div',undefined,'applications-table-wrap'),details=node('section',undefined,'politics-card applications-details');details.hidden=true;details.tabIndex=-1;host.append(register,details); const form=node('form',undefined,'politics-card politics-charter');form.append(node('h3','Stand before the banners'),node('p','Apply for the next scheduled election. Submitting does not grant an office or award.')); const label=node('label','Application type'),select=node('select');select.required=true; - if(context?.factionStatus==='verified'&&context.faction){const o=node('option',context.faction==='veiled_concord'?'CON · Reverent Mother':'HSE · House Leader');o.value='house';select.append(o);} - const imp=node('option','IMP · Emperor');imp.value='imperial';select.append(imp);label.append(select); + if(context?.factionStatus==='verified'&&['atreides','harkonnen','corrino','ordos'].includes(context.faction)){const o=node('option',context.faction==='veiled_concord'?'CON · Reverent Mother':'HSE · House Leader');o.value='house';select.append(o);} + for(const [kind,label] of [['imperial','Emperor'],['bene','Reverent Mother · Bene Gesserit'],['guild','Spacing Guild Leader'],['clan_delegate','Clan Delegate']]){const o=node('option',label);o.value=kind;select.append(o);}label.append(select); const schedule=node('p'),motivation=node('label','Motivation and plans'),text=node('textarea');text.rows=5;text.minLength=20;text.maxLength=4000;text.required=true;motivation.append(text); const consent=node('label',undefined,'politics-accept'),check=node('input');check.type='checkbox';check.required=true;consent.append(check,node('span','I accept the responsibilities of this candidature.')); const submit=node('button','Submit application');submit.type='submit';submit.disabled=true;const feedback=node('p');feedback.setAttribute('role','status'); @@ -18,7 +18,7 @@ export function renderApplications({user,context}){ function updateSchedule(){const start=electionDates(select.value)[0],window=electionWindow(select.value,start);schedule.textContent='Applications close '+date(Date.parse(start))+'. Voting ends '+date(Date.parse(window.votingCloses))+'.';submit.disabled=busy||!access||context?.linked!==true;} select.addEventListener('change',updateSchedule);updateSchedule(); function draw(){area.replaceChildren();const table=node('table',undefined,'applications-table');table.append(node('caption','Your numbered election applications'));const head=node('thead'),tr=node('tr');for(const h of ['Application ID','User name','Function','Date','Election ID','Status','Votes received','Result / rank awarded','3× honour','Details']){const th=node('th',h);th.scope='col';tr.append(th);}head.append(tr);table.append(head);const body=node('tbody'); - for(const row of rows.slice(page*9,page*9+9)){const office=row.kind==='imperial'?'Emperor':row.faction==='veiled_concord'?'Reverent Mother':'House Leader',closed=row.progress?.state==='closed';const tr=node('tr');for(const value of [row.public_id,user?.username||'',office,date(row.created_at),applicationElectionId(row),closed?'Closed':'Open (ongoing)',String(row.progress?.votes??0),row.progress?.result||'Pending',row.progress?.honour?'Yes':'No'])tr.append(node('td',value));const art=node('img');art.src='https://www.dunerealms.com/assets/seals/'+(row.kind==='imperial'?'emperor-v1.png':row.faction==='veiled_concord'?'veiled-concord-v1.png':'office-house_leader.png');art.alt='';art.width=art.height=28;tr.children[2].prepend(art);const td=node('td'),button=node('button','Details');button.type='button';button.onclick=()=>{details.replaceChildren(node('h3',row.public_id+' · '+office));const data=node('dl',undefined,'applications-detail-grid');for(const [key,value]of [['Applicant',user?.username||''],['Faction',row.faction],['Election ID',applicationElectionId(row)],['Application received',date(row.created_at)],['Voting starts / applications close',date(row.election_start)],['Voting closes',date(Number(row.election_start)+10800000)],['Record state',row.status],['Result',row.progress?.result||'Pending'],['Voting',row.progress?.phase||'Awaiting round'],['Office ledger',row.progress?.officeRecorded?'Term recorded; cosmetic rank delivery is separate':'No term recorded'],['Three-term honour',row.progress?.honour?.title||'Not earned'],['Round totals',(row.progress?.rounds||[]).map(r=>'Round '+r.number+': '+(r.eligible?r.votes+' votes':'Not in this runoff')).join('; ')||'Voting has not started']])data.append(node('dt',key),node('dd',value));details.append(data,node('h4','Motivation'),node('p',row.motivation));details.hidden=false;details.focus();};td.append(button);tr.append(td);body.append(tr);}table.append(body);area.append(table); + for(const row of rows.slice(page*9,page*9+9)){const office=row.kind==='guild'?'Spacing Guild Leader':row.kind==='clan_delegate'?'Clan Delegate':row.kind==='imperial'?'Emperor':row.faction==='veiled_concord'?'Reverent Mother':'House Leader',closed=row.progress?.state==='closed';const tr=node('tr');for(const value of [row.public_id,user?.username||'',office,date(row.created_at),applicationElectionId(row),closed?'Closed':'Open (ongoing)',String(row.progress?.votes??0),row.progress?.result||'Pending',row.progress?.honour?'Yes':'No'])tr.append(node('td',value));const art=node('img');art.src='https://www.dunerealms.com/assets/seals/'+(row.kind==='imperial'?'emperor-v1.png':row.faction==='veiled_concord'?'veiled-concord-v1.png':'office-house_leader.png');art.alt='';art.width=art.height=28;tr.children[2].prepend(art);const td=node('td'),button=node('button','Details');button.type='button';button.onclick=()=>{details.replaceChildren(node('h3',row.public_id+' · '+office));const data=node('dl',undefined,'applications-detail-grid');for(const [key,value]of [['Applicant',user?.username||''],['Faction',row.faction],['Election ID',applicationElectionId(row)],['Application received',date(row.created_at)],['Voting starts / applications close',date(row.election_start)],['Voting closes',date(Number(row.election_start)+10800000)],['Record state',row.status],['Result',row.progress?.result||'Pending'],['Voting',row.progress?.phase||'Awaiting round'],['Office ledger',row.progress?.officeRecorded?'Term recorded; cosmetic rank delivery is separate':'No term recorded'],['Three-term honour',row.progress?.honour?.title||'Not earned'],['Round totals',(row.progress?.rounds||[]).map(r=>'Round '+r.number+': '+(r.eligible?r.votes+' votes':'Not in this runoff')).join('; ')||'Voting has not started']])data.append(node('dt',key),node('dd',value));details.append(data,node('h4','Motivation'),node('p',row.motivation));details.hidden=false;details.focus();};td.append(button);tr.append(td);body.append(tr);}table.append(body);area.append(table); if(rows.length>9){const nav=node('nav',undefined,'politics-pagination');for(const [label,step]of [['Previous',-1],['Next',1]]){const b=node('button',label);b.type='button';b.disabled=step<0?page===0:(page+1)*9>=rows.length;b.onclick=()=>{page+=step;draw();};nav.append(b);}nav.append(node('span','Page '+(page+1)+' of '+Math.ceil(rows.length/9)));area.append(nav);}status.textContent=rows.length?rows.length+' submitted application(s).':'No applications submitted yet.';if(!area.isConnected)register.append(area); } async function load(){try{const r=await fetch('/api/politics/applications',{cache:'no-store'}),data=await r.json();if(!host.isConnected)return;if(!r.ok)throw Error(data.message||'Could not load your register.');rows=data.applications||[];access=true;page=0;draw();}catch(error){access=false;status.textContent=error.message;}updateSchedule();} diff --git a/website/control-panel/public/politics.mjs b/website/control-panel/public/politics.mjs index 7945127b..58ccd52e 100644 --- a/website/control-panel/public/politics.mjs +++ b/website/control-panel/public/politics.mjs @@ -28,7 +28,7 @@ function disabled(text){const b=el('button',text);b.type='button';b.disabled=tru function demoNote(){return el('p','DEMO DATA · Fictional names, votes and support. Nothing is submitted or saved.','politics-demo-note');} function demoSupport(counter=false){const box=el('div',undefined,'politics-demo-support');box.append(demoNote());for(const [name,state]of [['House Amber','Supports'],['House Jade',counter?'Supports':'Awaiting agreement']]){const row=el('p');row.append(el('strong',name+' · '),el('span',state));box.append(row);}box.append(el('strong',counter?'Demo outcome: 2 / 2 Houses — election denied':'Demo progress: 1 / 2 Houses'));return box;} function electionCalendar(imperial=false){ - const weeks=imperial?4:2,hour=imperial?15:9; + const weeks=4,hour=imperial?15:9; const box=card(imperial?'The Imperial Almanac':'The House Almanac',`Every ${weeks} weeks · Sunday · ${String(hour).padStart(2,'0')}:00 GMT. Term: ${weeks} weeks.`,imperial?'seals/emperor-v1.png':'seals/office-house_leader.png'); box.classList.add('politics-calendar-card'); box.append(el('p','CONFIRMED CALENDAR · First election Sunday: 15 November 2026. Voting availability is confirmed by the election service.','politics-demo-note')); @@ -38,7 +38,7 @@ function electionCalendar(imperial=false){ time.append(el('small',new Intl.DateTimeFormat('en-GB',{month:'short',year:'numeric',timeZone:'UTC'}).format(date)),el('strong',String(date.getUTCDate()).padStart(2,'0')),el('span',`Sunday · ${String(hour).padStart(2,'0')}:00 GMT`)); entry.append(time,el('small','Scheduled'));list.append(entry); } - box.append(list,el('p',imperial?'On an Imperial election Sunday, Faction Elections take place at 09:00 GMT, followed by Emperor Elections at 15:00 GMT.':'Faction Elections run every two weeks. Every second House election Sunday also includes Emperor Elections at 15:00 GMT.'),el('p','Times stay fixed to GMT throughout the year.'));return box; + box.append(list,el('p',imperial?'On an Imperial election Sunday, Faction Elections take place at 09:00 GMT, followed by Emperor Elections at 15:00 GMT.':'House Leader elections run every four weeks. Emperor elections follow at 15:00 GMT.'),el('p','Times stay fixed to GMT throughout the year.'));return box; } function electionPreview(imperial=false){ const host=el('div',undefined,'politics-content');const overview=el('div',undefined,'politics-election-overview');overview.append(electionCalendar(imperial));host.append(overview); @@ -135,7 +135,7 @@ fetch('/api/auth/session',{cache:'no-store'}).then(r=>r.ok?r.json():null).then(d function applicationsDashboard(){ const host=el('div',undefined,'applications-dashboard'); const types=[['HSE','House Leader'],['CON','Reverent Mother'],['IMP','Emperor']]; - const records=types.map(([prefix,role],i)=>({id:`APP-${prefix}-2026-000001`,prefix,user:'Demo '+['DuneWeaver','MoonSurveyor','AmberWarden'][i],role,date:'2026-11-08',election:`ELC-${prefix}-2026-000001`,status:i===2?'Closed':'Open (ongoing)',votes:[24,18,84][i],result:i===2?'Emperor':'Pending',honour:false,motivation:'Fictional example: I would represent our community through open discussion, clear decisions and shared projects.',term:prefix==='IMP'?'4 weeks':'2 weeks',time:prefix==='IMP'?'Sunday 15:00 GMT':'Sunday 09:00 GMT'})); + const records=types.map(([prefix,role],i)=>({id:`APP-${prefix}-2026-000001`,prefix,user:'Demo '+['DuneWeaver','MoonSurveyor','AmberWarden'][i],role,date:'2026-11-08',election:`ELC-${prefix}-2026-000001`,status:i===2?'Closed':'Open (ongoing)',votes:[24,18,84][i],result:i===2?'Emperor':'Pending',honour:false,motivation:'Fictional example: I would represent our community through open discussion, clear decisions and shared projects.',term:'4 weeks',time:prefix==='IMP'?'Sunday 15:00 GMT':'Sunday 09:00 GMT'})); const register=card('Application register','Numbered candidatures and their linked election results.','seals/office-landsraad.png');register.append(demoNote()); const stats=el('div',undefined,'applications-stats');for(const [label,value]of [['Election Applications',records.length],['Open',2],['Closed',1]]){const box=el('div');box.append(el('strong',String(value)),el('span',label));stats.append(box);}register.append(stats); const wrap=el('div',undefined,'applications-table-wrap'),table=el('table',undefined,'applications-table');const caption=el('caption','Illustrative application history — no real submissions');table.append(caption);const head=el('thead'),heading=el('tr');for(const title of ['Application ID','User name','Function','Date','Election ID','Status','Votes received','Result / rank awarded','3× honour','Details']){const th=el('th',title);th.scope='col';heading.append(th);}head.append(heading);table.append(head);const body=el('tbody'); diff --git a/website/docs/political-artwork.md b/website/docs/political-artwork.md new file mode 100644 index 00000000..5d35f725 --- /dev/null +++ b/website/docs/political-artwork.md @@ -0,0 +1,8 @@ +# Political CP artwork + +Generated with the built-in image generation tool, 15 November 2026. + +- web/assets/political-imperial-chamber-v1.png: Wide cinematic imperial governmental parliament, detailed Minecraft voxel sandstone architecture inspired by a Dune desert empire; burgundy banners, antique gold ornaments, warm muted desert light, distant sandstone city, painterly game environment, no people, text, logos or watermark. +- web/assets/political-small-council-v1.png: Atmospheric imperial Minecraft desert-world Small Council library, circular voxel sandstone architecture, gilded celestial globe and map table, burgundy draperies, brass emblems, desert through arches; painterly game environment, no people, readable text, logos or watermark. + +Images serve as decorative backgrounds beneath solid readable content panels. diff --git a/website/node/electoral-roll.mjs b/website/node/electoral-roll.mjs index 363b820a..01c01ff7 100644 --- a/website/node/electoral-roll.mjs +++ b/website/node/electoral-roll.mjs @@ -1,5 +1,5 @@ const houses={atreides:'House Aerdrecht',harkonnen:'House Harkveen',corrino:'House Korenholt',ordos:'House Oordwijk',fremen:'House Vrijduin',veiled_concord:'Veiled Concord'}; -export function rollRow(r){return {username:r.username,election:(r.kind==='imperial'?'Emperor':houses[r.faction]||r.faction)+' · '+new Date(Number(r.election_start)).toISOString().slice(0,10)+' · Round '+(Number(r.round_number)+1),votes:Number(r.votes)};} +export function rollRow(r){return {username:r.username,election:(({imperial:'Emperor',bene:'Bene Gesserit',guild:'Spacing Guild',clan_delegate:'Clan Delegate'})[r.kind]||houses[r.faction]||r.faction)+' · '+new Date(Number(r.election_start)).toISOString().slice(0,10)+' · Round '+(Number(r.round_number)+1),votes:Number(r.votes)};} export async function votingHonour(db,userId,now=Date.now()){ const row=await db.prepare(`SELECT MAX(r.closes_at) AS expires_at FROM political_election_rounds r WHERE r.status='open' AND r.opens_at<=? AND r.closes_at>? diff --git a/website/tests/political-cp.test.mjs b/website/tests/political-cp.test.mjs index f52e3950..ee6482f1 100644 --- a/website/tests/political-cp.test.mjs +++ b/website/tests/political-cp.test.mjs @@ -9,8 +9,8 @@ import {governmentRoute,politicalFrameMessage} from '../web/government-cp.js'; import {workspacesForSurface} from '../control-panel/public/cp-v2/cp-v2-surface.mjs'; import {politicsCPDocument} from '../control-panel/politics-cp-shell.mjs'; -test('Political CP exposes exactly Elections, Offices and Tools with every existing chamber',()=>{ - assert.deepEqual(POLITICAL_TABS.map(t=>t.label),['Elections','Offices','Tools']); +test('Political CP exposes central Elections, Voting Directory, Offices and Tools menus with every existing chamber',()=>{ + assert.deepEqual(POLITICAL_TABS.map(t=>t.label),['Elections','Voting Directory','Offices','Tools']); const pages=POLITICAL_TABS.flatMap(t=>t.pages.map(([id])=>id));assert.equal(new Set(pages).size,pages.length); for(const tab of POLITICAL_TABS)for(const [page]of tab.pages){const route=tab.id+'/'+page;assert.deepEqual(politicalRoute('#'+route),{tab:tab.id,page});assert.equal(governmentRoute(route),route);assert.equal(governmentRoute('politics/'+page),route);assert.equal(politicsDestination('politics',page),'https://www.dunerealms.com/government.html#'+route);assert.equal(politicsDestination(page),'https://www.dunerealms.com/government.html#'+route);} assert.equal(politicalRoute('elections').page,'house-elections');assert.equal(politicalRoute('offices').page,'office-register');assert.equal(politicalRoute('tools').page,'council-motd'); @@ -27,16 +27,17 @@ test('the real server serves an independent Political CP and styles without the const response=await app(new Request('https://cp.dunerealms.com/politics-cp'));assert.equal(response.status,200);assert.match(response.headers.get('content-type'),/text\/html/);const html=await response.text();assert.match(html,/data-cp-mode="politics"/);assert.match(html,/cp-v2-politics-shell.mjs/);assert.match(html,/class="command-banner"/);assert.match(html,/id="sidebar-right"/);assert.doesNotMatch(html,/src="\/v2\/v2.js|class="dune-site-header"/); assert.equal((await app(new Request('https://cp.dunerealms.com/politics-cp',{method:'HEAD'}))).status,200);assert.equal((await app(new Request('https://cp.dunerealms.com/politics-cp',{method:'POST'}))).status,405); for(const file of ['cp-v2-politics-shell.mjs','cp-v2-politics-shell.css','cp-v2-politics-navigation.mjs','cp-v2-politics-native.css'])assert.equal((await app(new Request('https://cp.dunerealms.com/v2/'+file))).status,200,file); + assert.equal((await app(new Request('https://cp.dunerealms.com/political-catalog.mjs'))).status,200); assert.equal((await app(new Request('https://cp.dunerealms.com/api/public/government?user=other'))).status,400);assert.equal((await app(new Request('https://cp.dunerealms.com/api/public/government',{method:'POST'}))).status,405); }finally{db.close();} }); test('Political CP reuses the authored CP layout and normal CP remains a valid classic script',async()=>{ const template=await readFile(new URL('../control-panel/public/cp-v2/index.html',import.meta.url),'utf8'),html=politicsCPDocument(template); - const layout=template.slice(template.indexOf('