forked from unimatrix/web
Merge pull request 'Central Political CP, campaign directory and two-chamber elections' (#326) from dev/MC:dev/alpha-1.0.0.7-the-great-migration into main
This commit is contained in:
commit
385d10f109
38 changed files with 369 additions and 75 deletions
|
|
@ -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});
|
||||
|
|
|
|||
|
|
@ -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');
|
||||
|
|
|
|||
|
|
@ -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)&&now<Number(roundWindow.closes_at)?'voting':'closed';if(window.phase!=='voting')throw Error('Voting is not open');
|
||||
const capacity=input.kind==='house'?1:imperialVoteAllowance(context);
|
||||
const capacity=voteCapacity(input.kind,context);
|
||||
if(!Array.isArray(input.allocations)||!input.allocations.length||input.allocations.length>capacity)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]);
|
||||
|
|
|
|||
29
website/control-panel/election-directory.mjs
Normal file
29
website/control-panel/election-directory.mjs
Normal file
|
|
@ -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);}
|
||||
};}
|
||||
|
|
@ -15,14 +15,14 @@ export function planOfficeTerm(round,application,previous,now){
|
|||
if(!Number.isFinite(closed)||closed<start+10800000||now<closed)throw Error('Election has not closed');
|
||||
if(!/^[a-z_]{1,32}$/.test(round.faction)||round.kind==='imperial'&&round.faction!=='imperium')throw Error('Invalid office scope');
|
||||
if(previous&&Number(previous.election_start)>=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.
|
||||
|
|
|
|||
|
|
@ -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)}))});
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,8 +8,8 @@ export function politicsCPDocument(source){
|
|||
.replace(/<link rel="stylesheet" href="https:\/\/www\.dunerealms\.com\/portal-navigation\.css">/,'')
|
||||
.replace('<body>','<body class="politics-cp-shell" data-cp-mode="politics">')
|
||||
.replace('<strong>✦ DuneRealms</strong>','<strong>✦ Political CP</strong>')
|
||||
.replace('CONTROL PANEL V2<small>Your imperial workspace</small>','REALMS · COURT · LANDSRAAD<small>Elections, Offices & Tools</small>')
|
||||
.replace('class="portals" aria-label="Workspace portals"','class="portals" role="tablist" aria-label="Political workspace"')
|
||||
.replace('CONTROL PANEL V2<small>Your imperial workspace</small>','IMPERIAL SENATE · SMALL COUNCIL<small>Four-week terms · Elections & Offices</small>')
|
||||
.replace('class="portals" aria-label="Workspace portals"','class="portals" hidden aria-hidden="true"')
|
||||
.replace('aria-controls="sidebar"','aria-controls="sidebar sidebar-right"')
|
||||
.replace(/<script src="\/v2\/v2\.js(?:\?[^\"]*)?" defer><\/script>/,'<script type="module" src="/v2/cp-v2-politics-shell.mjs"></script>')
|
||||
.replace('</head>','<link rel="stylesheet" href="/v2/cp-v2-politics-shell.css"></head>');
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
|
|
|||
|
|
@ -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=''){
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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}}
|
||||
|
|
|
|||
|
|
@ -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();});
|
||||
|
|
|
|||
|
|
@ -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.opensAt||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();};
|
||||
}
|
||||
|
|
@ -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();}
|
||||
|
|
|
|||
|
|
@ -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:now<timestamp?'applications':now<closes?'voting':'closed'};
|
||||
}
|
||||
export function validateCandidature(input,context,now=Date.now()) {
|
||||
if(!input||!['house','imperial'].includes(input.kind)||input.accepted!==true)throw Error('Choose an election and accept your candidature');
|
||||
if(!input||!Object.hasOwn(ELECTION_RULES,input.kind)||input.accepted!==true)throw Error('Choose an election and accept your candidature');
|
||||
if(!context?.linked)throw Error('A verified Minecraft account is required');
|
||||
if(input.kind==='house'&&!context.faction)throw Error('A verified faction membership is required');
|
||||
if(input.kind==='house'&&!['atreides','harkonnen','corrino','ordos'].includes(context.faction))throw Error('A verified faction membership is required');
|
||||
if(input.kind==='clan_delegate'&&!context.clanId)throw Error('Active clan membership is required');
|
||||
const window=electionWindow(input.kind,input.start,now);
|
||||
if(window.phase!=='applications')throw Error('Applications for this election are closed');
|
||||
if(window.votingOpens!==electionDates(input.kind,now,1)[0])throw Error('Only the next scheduled election accepts applications');
|
||||
const motivation=typeof input.motivation==='string'?input.motivation.trim():'';
|
||||
if(motivation.length<20||motivation.length>4000||/[\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;}
|
||||
|
|
|
|||
7
website/control-panel/public/political-catalog.mjs
Normal file
7
website/control-panel/public/political-catalog.mjs
Normal file
|
|
@ -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'}
|
||||
]);
|
||||
|
|
@ -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');
|
||||
|
|
|
|||
|
|
@ -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'}});
|
||||
};
|
||||
}
|
||||
|
|
|
|||
8
website/docs/political-artwork.md
Normal file
8
website/docs/political-artwork.md
Normal file
|
|
@ -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.
|
||||
|
|
@ -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.
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue

Staff