Connect Imperial force-election rallies to existing signed ballots and office ledger
This commit is contained in:
parent
9bf00de169
commit
2e859e055d
18 changed files with 122 additions and 51 deletions
|
|
@ -1,3 +1,4 @@
|
|||
import {forcedElectionCalendar} from '../node/election-rallies.mjs';
|
||||
import {identity} from '../node/auth.mjs';
|
||||
import {accessFor} from '../node/permissions.mjs';
|
||||
import {createPoliticsPreview} from './politics-preview.mjs';
|
||||
|
|
@ -20,7 +21,7 @@ export function createElectionApplications(db,settings={},deps={}){
|
|||
const user=await auth(request);if(!user)return reply({message:'Sign in first.'},401);
|
||||
const permitted=async u=>(await access(u)).nodes.includes('web.menu.game')&&!await excluded(u);
|
||||
if(!await permitted(user))return reply({message:'A personal player account is required.'},403);
|
||||
if(request.method==='GET')return reply({applications:await list(db,user.id)});
|
||||
if(request.method==='GET'){const forced=await forcedElectionCalendar(db,clock());return reply({applications:await list(db,user.id),forcedImperialStart:forced&&clock()<forced.start?forced.start:null});}
|
||||
if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON is required.'},415);
|
||||
const raw=await request.text();if(raw.length>12000)return reply({message:'Application is too large.'},413);
|
||||
let input;try{input=JSON.parse(raw);}catch{return reply({message:'Invalid application.'},400);}
|
||||
|
|
@ -36,7 +37,7 @@ export function createElectionApplications(db,settings={},deps={}){
|
|||
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 naib=input.kind==='naib_chair'?await currentNaib(db,current.id):null;
|
||||
const context={clanId:naib?.clan_id||clan?.id,naib:!!naib,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 forced=input.kind==='imperial'?await forcedElectionCalendar(db,clock()):null;validateCandidature(input,context,clock(),forced&&clock()<forced.start?forced.start:null);}catch(error){return reply({message:error.message},400);}
|
||||
try{
|
||||
const result=await save(db,{actor:current,context,input,now:clock(),clock});
|
||||
return reply({application:result},result.created?201:200);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import {randomUUID} from 'node:crypto';
|
||||
import {forcedElectionCalendar} from '../node/election-rallies.mjs';
|
||||
import {validateCandidature} from './public/election-rules.mjs';
|
||||
import {currentNaib} from '../node/naib-membership.mjs';
|
||||
|
||||
|
|
@ -28,7 +29,7 @@ export function applicationNumber(prefix,year,value){
|
|||
// authenticated principal and freshly verified server-side game membership.
|
||||
export async function submitApplication(db,{actor,context,input,now=Date.now(),clock=Date.now,makeId=randomUUID}) {
|
||||
if(!actor?.id||!context?.playerUuid||!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(context.playerUuid))throw Error('Verified applicant identity required');
|
||||
const candidate=validateCandidature(input,context,now),start=Date.parse(candidate.start),player=context.playerUuid.toLowerCase();
|
||||
const forced=input.kind==='imperial'?await forcedElectionCalendar(db,now):null,approved=forced&&now<forced.start?forced.start:null;const candidate=validateCandidature(input,context,now,approved),start=Date.parse(candidate.start),player=context.playerUuid.toLowerCase();
|
||||
const prefix=applicationPrefix(candidate.kind,candidate.faction),year=new Date(now).getUTCFullYear(),scope=`${prefix}-${year}`;
|
||||
const [result]=await db.batch([{async run(connection){
|
||||
const query=async(sql,args=[])=>(await connection.execute(sql,args))[0];
|
||||
|
|
@ -46,7 +47,7 @@ export async function submitApplication(db,{actor,context,input,now=Date.now(),c
|
|||
return {id:row.id,publicId:row.public_id,created:false};
|
||||
}
|
||||
// A request waiting for a database lock must not slip past the deadline.
|
||||
validateCandidature(input,context,clock());
|
||||
const currentForced=input.kind==='imperial'?await forcedElectionCalendar({query,electionRalliesEnabled:db.electionRalliesEnabled},clock()):null;validateCandidature(input,context,clock(),currentForced&&clock()<currentForced.start?currentForced.start:null);
|
||||
const value=Number(counters[0].value)+1,publicId=applicationNumber(prefix,year,value),id=makeId();
|
||||
await query('UPDATE political_application_counters SET value=? WHERE scope=?',[value,scope]);
|
||||
await query('INSERT INTO political_applications(id,public_id,user_id,player_uuid,kind,faction,election_start,motivation,status,created_at) VALUES(?,?,?,?,?,?,?,?,?,?)',[id,publicId,actor.id,player,candidate.kind,candidate.faction,start,candidate.motivation,'submitted',now]);
|
||||
|
|
|
|||
|
|
@ -1,13 +1,14 @@
|
|||
import {clanDelegateAuthority,lockClanVotingDeed} from '../node/clan-voting-authority.mjs';
|
||||
import {connectionReader} from '../node/clan-deeds.mjs';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import {approvedForcedStart} from '../node/election-rallies.mjs';
|
||||
import {ELECTION_RULES,electionWindow,electionScope,voteCapacity} from './public/election-rules.mjs';
|
||||
import {currentNaib} from '../node/naib-membership.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){
|
||||
export function validateBallot(input,context,now=Date.now(),roundWindow=null,approvedStart=null){
|
||||
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 window=electionWindow(input.kind,input.start,now,approvedStart);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=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;
|
||||
|
|
@ -34,7 +35,7 @@ export async function castBallot(db,{actor,context,input,now=Date.now(),clock=Da
|
|||
if(input.kind==='naib_chair'){const seat=await currentNaib({query},actor.id,{lock:true});if(!seat||seat.clan_id!==context.clanId)throw Error('Current Arrakduin sietch ownership is required');}
|
||||
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!==electionScope(input.kind,context)||round.status!=='open')throw Error('Election round is not open');
|
||||
const vote=validateBallot(input,context,clock(),round),clanBallot=vote.kind==='clan_delegate',payload=JSON.stringify({kind:vote.kind,start:vote.start,roundId:round.id,...(clanBallot?{clanId:context.clanId}:{}),allocations:vote.allocations});
|
||||
const approved=await approvedForcedStart({query,electionRalliesEnabled:db.electionRalliesEnabled},round.kind,round.election_start);const vote=validateBallot(input,context,clock(),round,approved?Number(round.election_start):null),clanBallot=vote.kind==='clan_delegate',payload=JSON.stringify({kind:vote.kind,start:vote.start,roundId:round.id,...(clanBallot?{clanId:context.clanId}:{}),allocations:vote.allocations});
|
||||
if(clanBallot){
|
||||
await lockClanVotingDeed(db,connection,context.clanId);
|
||||
if(!await clanDelegateAuthority(connectionReader(db,connection),actor.id,context.clanId))throw Error('Current clan political authority is required');
|
||||
|
|
@ -51,7 +52,7 @@ export async function castBallot(db,{actor,context,input,now=Date.now(),clock=Da
|
|||
if(!clanBallot||previous.payload!==legacyPayload||legacy[0]?.ballot_id!==previous.id)throw Error('Submission identifier already used');
|
||||
}
|
||||
return{id:previous.id,created:false,remaining:clanBallot?0:Number(voter.capacity)-Number(voter.spent)};}
|
||||
validateBallot(input,context,clock(),round);
|
||||
validateBallot(input,context,clock(),round,approved?Number(round.election_start):null);
|
||||
// Allowance is captured at the first successful ballot; later changes cannot
|
||||
// manufacture additional votes. A lower current allowance also prevents spending.
|
||||
const available=clanBallot?vote.capacity:Math.min(Number(voter.capacity),vote.capacity)-Number(voter.spent);if(vote.total>available)throw Error('No sufficient votes remain');
|
||||
|
|
@ -82,9 +83,9 @@ export function electionOutcome(candidates){
|
|||
const high=Math.max(...rows.map(c=>c.votes)),leaders=rows.filter(c=>c.votes===high).map(c=>c.id).sort();
|
||||
return leaders.length===1?{status:'winner',winner:leaders[0],runoff:[]}:{status:'auction_required',winner:null,runoff:leaders};
|
||||
}
|
||||
export function planRoundResult({kind,start,round=0,candidates},now=Date.now()){
|
||||
export function planRoundResult({kind,start,round=0,candidates},now=Date.now(),approvedStart=null){
|
||||
if(!Number.isSafeInteger(round)||round<0||round>1000)throw Error('Invalid election round');
|
||||
const base=electionWindow(kind,start,now),opens=Date.parse(base.votingOpens)+round*10800000,closes=opens+10800000;
|
||||
const base=electionWindow(kind,start,now,approvedStart),opens=Date.parse(base.votingOpens)+round*10800000,closes=opens+10800000;
|
||||
if(now<closes)throw Error('Voting round has not closed');
|
||||
const result=electionOutcome(candidates);
|
||||
return {...result,round,opensAt:opens,closesAt:closes,nextRound:null,auction:result.status==='auction_required'?{durationMs:10800000,candidateIds:result.runoff}:null};
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import {randomUUID} from 'node:crypto';
|
||||
import {approvedForcedStart} from '../node/election-rallies.mjs';
|
||||
import {ELECTION_RULES,electionWindow} from './public/election-rules.mjs';
|
||||
import {currentNaib} from '../node/naib-membership.mjs';
|
||||
export const officeLedgerSchema=[
|
||||
|
|
@ -12,10 +13,10 @@ export async function initializeOfficeLedger(db){
|
|||
if(db.query&&!db.sqlite){const rows=await db.query("SHOW INDEX FROM political_office_terms WHERE Key_name='office_cycle'");if(rows.length&&rows.length===3){await db.query('ALTER TABLE political_office_terms DROP INDEX office_cycle, ADD UNIQUE KEY office_cycle(kind,faction,election_start,round_id)');}}
|
||||
}
|
||||
const uuid=/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i;
|
||||
export function planOfficeTerm(round,application,previous,now){
|
||||
export function planOfficeTerm(round,application,previous,now,approvedStart=null){
|
||||
if(!['winner','no_votes'].includes(round.status))throw Error('A final election result is required');
|
||||
const start=Number(round.election_start),closed=Number(round.closes_at),period=ELECTION_RULES[round.kind]?.weeks*604800000;
|
||||
electionWindow(round.kind,new Date(start).toISOString(),now);
|
||||
electionWindow(round.kind,new Date(start).toISOString(),now,approvedStart);
|
||||
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');
|
||||
|
|
@ -27,7 +28,7 @@ export function planOfficeTerm(round,application,previous,now){
|
|||
streak=previous&&Number(previous.election_start)===start-period&&previous.player_uuid===playerUuid&&previous.outcome==='winner'?Number(previous.streak)+1:1;
|
||||
}
|
||||
const title=office==='doci'?'Doci Emeritus':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&&office!=='naib_chair'?title:null};
|
||||
return {kind:round.kind,faction:round.faction,electionStart:start,office,userId,playerUuid,applicationId:round.status==='winner'?application.id:null,startsAt:closed,expiresAt:approvedStart===start?Date.parse(ELECTION_RULES[round.kind].first)+(Math.floor((start-Date.parse(ELECTION_RULES[round.kind].first))/period)+1)*period:start+period,outcome:round.status,streak,honour:streak>=3&&office!=='naib_chair'?title:null};
|
||||
}
|
||||
// This ledger records election facts only. It never edits account roles, game offices or paid/earned ranks.
|
||||
export async function reconcileOfficeResult(db,{roundId,now=Date.now(),makeId=randomUUID}){
|
||||
|
|
@ -43,7 +44,8 @@ export async function reconcileOfficeResult(db,{roundId,now=Date.now(),makeId=ra
|
|||
const [previous]=await q('SELECT * FROM political_office_terms WHERE kind=? AND faction=? ORDER BY election_start DESC,starts_at DESC LIMIT 1 FOR UPDATE',[round.kind,round.faction]);
|
||||
const [application]=round.winner_id?await q('SELECT * FROM political_applications WHERE id=?',[round.winner_id]):[];
|
||||
if(round.kind==='naib_chair'&&application&&!await currentNaib({query:q},application.user_id,{lock:true}))throw Error('Chair winner is no longer a Naib');
|
||||
const term=planOfficeTerm(round,application,previous,now),id=makeId();
|
||||
const approved=await approvedForcedStart({query:q,electionRalliesEnabled:db.electionRalliesEnabled},round.kind,round.election_start);const term=planOfficeTerm(round,application,previous,now,approved?Number(round.election_start):null),id=makeId();
|
||||
if(approved)await q("UPDATE political_office_terms SET outcome='superseded',expires_at=? WHERE kind=? AND faction=? AND outcome='winner' AND starts_at<=? AND expires_at>?",[term.startsAt,round.kind,round.faction,term.startsAt,term.startsAt]);
|
||||
await q('INSERT INTO political_office_terms(id,kind,faction,election_start,round_id,application_id,user_id,player_uuid,office,starts_at,expires_at,outcome,streak) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)',[id,term.kind,term.faction,term.electionStart,round.id,term.applicationId,term.userId,term.playerUuid,term.office,term.startsAt,term.expiresAt,term.outcome,term.streak]);
|
||||
await q('INSERT INTO political_office_events(id,term_id,event,payload,created_at) VALUES(?,?,?,?,?)',[makeId(),id,'result_recorded',JSON.stringify(term),now]);
|
||||
if(term.honour)await q('INSERT IGNORE INTO political_election_honours(player_uuid,kind,faction,title,term_id,earned_at) VALUES(?,?,?,?,?,?)',[term.playerUuid,term.kind,term.faction,term.honour,id,term.startsAt]);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import {randomUUID} from 'node:crypto';
|
||||
import {approvedForcedStart} from '../node/election-rallies.mjs';
|
||||
import {electionWindow} from './public/election-rules.mjs';
|
||||
import {planRoundResult} from './election-ballots.mjs';
|
||||
import {currentNaib} from '../node/naib-membership.mjs';
|
||||
|
|
@ -10,7 +11,7 @@ export const roundSchema=[
|
|||
];
|
||||
export async function initializeRounds(db){for(const sql of roundSchema)await db.prepare(sql).run();}
|
||||
export async function openFirstRound(db,{kind,faction,start,now=Date.now(),makeId=randomUUID}){
|
||||
const window=electionWindow(kind,start,now);if(window.phase==='applications')throw Error('Voting has not started');
|
||||
const approved=await approvedForcedStart(db,kind,Date.parse(start));const window=electionWindow(kind,start,now,approved?Date.parse(start):null);if(window.phase==='applications')throw Error('Voting has not started');
|
||||
if(kind==='imperial')faction='imperium';
|
||||
if(!/^[a-z_]{1,32}$/.test(faction||''))throw Error('Verified faction required');
|
||||
const opens=Date.parse(window.votingOpens),closes=Date.parse(window.votingCloses);
|
||||
|
|
@ -35,7 +36,7 @@ export async function finalizeRound(db,{roundId,now=Date.now(),makeId=randomUUID
|
|||
if(now<Number(round.closes_at))throw Error('Voting round has not closed');
|
||||
const totals=await query('SELECT c.application_id AS id,COALESCE(SUM(a.votes),0) AS votes FROM political_round_candidates c LEFT JOIN political_ballots b ON b.round_id=c.round_id LEFT JOIN political_ballot_allocations a ON a.ballot_id=b.id AND a.application_id=c.application_id WHERE c.round_id=? GROUP BY c.application_id',[round.id]);
|
||||
if(round.kind==='naib_chair')for(const row of totals){const [application]=await query('SELECT user_id FROM political_applications WHERE id=?',[row.id]);if(!application||!await currentNaib({query},application.user_id,{lock:true}))row.votes=0;}
|
||||
const outcome=planRoundResult({kind:round.kind,start:new Date(Number(round.election_start)).toISOString(),round:Number(round.round_number),candidates:totals.map(row=>({...row,votes:Number(row.votes)}))},now);
|
||||
const approved=await approvedForcedStart({query,electionRalliesEnabled:db.electionRalliesEnabled},round.kind,round.election_start);const outcome=planRoundResult({kind:round.kind,start:new Date(Number(round.election_start)).toISOString(),round:Number(round.round_number),candidates:totals.map(row=>({...row,votes:Number(row.votes)}))},now,approved?Number(round.election_start):null);
|
||||
let nextRoundId=null;
|
||||
if(outcome.auction){
|
||||
const candidates=[];
|
||||
|
|
|
|||
|
|
@ -5,12 +5,13 @@ import {createPoliticsPreview} from './politics-preview.mjs';
|
|||
import {ELECTION_RULES,electionScope,voteCapacity} from './public/election-rules.mjs';
|
||||
import {openFirstRound,finalizeRound} from './election-rounds.mjs';
|
||||
import {castBallot} from './election-ballots.mjs';
|
||||
import {forcedElectionCalendar} from '../node/election-rallies.mjs';
|
||||
import {currentNaib} from '../node/naib-membership.mjs';
|
||||
const houses=['atreides','harkonnen','corrino','ordos','fremen'];
|
||||
const reply=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}});
|
||||
export function cycleStart(kind,now){const rule=ELECTION_RULES[kind];if(!rule)throw Error('Unknown election');const first=Date.parse(rule.first),period=rule.weeks*604800000;return first+Math.max(0,Math.floor((now-first)/period))*period;}
|
||||
export async function advanceElection(db,kind,faction,now=Date.now()){
|
||||
const start=cycleStart(kind,now);if(now<start)return null;
|
||||
const forced=kind==='imperial'?await forcedElectionCalendar(db,now):null;const start=forced&&now>=forced.start?forced.start:cycleStart(kind,now);if(now<start)return null;
|
||||
await openFirstRound(db,{kind,faction,start:new Date(start).toISOString(),now});
|
||||
for(let step=0;step<12;step++){
|
||||
const round=await db.prepare('SELECT * FROM political_election_rounds WHERE kind=? AND faction=? AND election_start=? ORDER BY round_number DESC LIMIT 1').bind(kind,faction,start).first();
|
||||
|
|
@ -46,7 +47,7 @@ export function createElectionVoting(db,settings={},deps={}){
|
|||
const clans=kind==='clan_delegate'?await clanDelegateChoices(db,current.id):[],requestedClan=url.searchParams.get('clan'),clan=clans.find(c=>c.id===(requestedClan||clans[0]?.id));
|
||||
if(requestedClan&&!clan)return reply({message:'Current political authority for this clan is required.'},403);
|
||||
const naib=kind==='naib_chair'?await currentNaib(db,current.id):null;
|
||||
const context={clanId:naib?.clan_id||clan?.id,naib:!!naib,clanLeader:!!clan,linked:true,playerUuid:player,faction:kind==='naib_chair'?'arrakis':verified.faction,houseLeader:verified.houseLeader===true},faction=electionScope(kind,context),now=clock(),start=cycleStart(kind,now);
|
||||
const context={clanId:naib?.clan_id||clan?.id,naib:!!naib,clanLeader:!!clan,linked:true,playerUuid:player,faction:kind==='naib_chair'?'arrakis':verified.faction,houseLeader:verified.houseLeader===true},faction=electionScope(kind,context),now=clock(),forced=kind==='imperial'?await forcedElectionCalendar(db,now):null,start=forced&&now>=forced.start?forced.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);
|
||||
|
|
|
|||
|
|
@ -17,14 +17,15 @@ export function renderApplications({user,context,kind:onlyKind=null}){
|
|||
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');
|
||||
form.append(label,schedule,motivation,consent,submit,feedback);host.append(form);let rows=[],page=0,busy=false,access=false;
|
||||
function updateSchedule(){if(!select.value){schedule.textContent='No eligible candidature type is available for this election.';submit.disabled=true;return;}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.value;}
|
||||
form.append(label,schedule,motivation,consent,submit,feedback);host.append(form);let rows=[],page=0,busy=false,access=false,forcedImperialStart=null;
|
||||
const nextStart=()=>select.value==='imperial'&&forcedImperialStart?new Date(forcedImperialStart).toISOString():electionDates(select.value)[0];
|
||||
function updateSchedule(){if(!select.value){schedule.textContent='No eligible candidature type is available for this election.';submit.disabled=true;return;}const start=nextStart(),window=electionWindow(select.value,start,Date.now(),select.value==='imperial'?forcedImperialStart:null);schedule.textContent='Applications close '+date(Date.parse(start))+'. Voting ends '+date(Date.parse(window.votingCloses))+'.';submit.disabled=busy||!access||context?.linked!==true||!select.value;}
|
||||
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 ['Reference','Office','Submitted','Status','Votes','Result','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==='church'?'Doci':row.kind==='naib_chair'?'Council of Naibs Chair':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,office,date(row.created_at),closed?'Closed':'Ongoing',String(row.progress?.votes??0),row.progress?.result||'Pending'])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[1].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||[]).filter(row=>!onlyKind||row.kind===onlyKind);access=true;page=0;draw();}catch(error){access=false;status.textContent=error.message;}updateSchedule();}
|
||||
form.addEventListener('submit',async event=>{event.preventDefault();if(busy||!access||!form.reportValidity())return;busy=true;updateSchedule();feedback.textContent='Submitting…';try{const r=await fetch('/api/politics/applications',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({kind:select.value,start:electionDates(select.value)[0],motivation:text.value,accepted:check.checked})}),data=await r.json();if(!host.isConnected)return;if(!r.ok)throw Error(data.message||'Application could not be saved.');feedback.textContent='Application received: '+data.application.publicId+'.';text.value='';check.checked=false;await load();}catch(error){feedback.textContent=error.message;}finally{busy=false;updateSchedule();}});
|
||||
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.');forcedImperialStart=Number.isSafeInteger(data.forcedImperialStart)?data.forcedImperialStart:null;rows=(data.applications||[]).filter(row=>!onlyKind||row.kind===onlyKind);access=true;page=0;draw();}catch(error){access=false;status.textContent=error.message;}updateSchedule();}
|
||||
form.addEventListener('submit',async event=>{event.preventDefault();if(busy||!access||!form.reportValidity())return;busy=true;updateSchedule();feedback.textContent='Submitting…';try{const r=await fetch('/api/politics/applications',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({kind:select.value,start:nextStart(),motivation:text.value,accepted:check.checked})}),data=await r.json();if(!host.isConnected)return;if(!r.ok)throw Error(data.message||'Application could not be saved.');feedback.textContent='Application received: '+data.application.publicId+'.';text.value='';check.checked=false;await load();}catch(error){feedback.textContent=error.message;}finally{busy=false;updateSchedule();}});
|
||||
queueMicrotask(load);return host;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,23 +19,23 @@ export function electionDates(kind, now=Date.now(), count=4) {
|
|||
export function imperialVoteAllowance({linked=false,faction=null,houseLeader=false}={}) {
|
||||
return linked && faction ? houseLeader===true ? 5 : 1 : 0;
|
||||
}
|
||||
export function electionWindow(kind,start,now=Date.now()) {
|
||||
export function electionWindow(kind,start,now=Date.now(),approvedStart=null) {
|
||||
const rule=ELECTION_RULES[kind],timestamp=Date.parse(start);
|
||||
if(!rule||!Number.isFinite(timestamp)||!Number.isFinite(now))throw Error('Invalid election window');
|
||||
const first=Date.parse(rule.first),period=rule.weeks*7*86400000;
|
||||
if(timestamp<first||(timestamp-first)%period!==0)throw Error('Election is outside the confirmed calendar');
|
||||
if(timestamp<first||((timestamp-first)%period!==0&&!(kind==='imperial'&&approvedStart===timestamp)))throw Error('Election is outside the confirmed calendar');
|
||||
const closes=timestamp+3*3600000;
|
||||
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()) {
|
||||
export function validateCandidature(input,context,now=Date.now(),approvedStart=null) {
|
||||
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'&&!['atreides','harkonnen','corrino','ordos','fremen'].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');
|
||||
if(input.kind==='naib_chair'&&(!context.naib||!context.clanId))throw Error('Current Arrakduin sietch ownership is required');
|
||||
const window=electionWindow(input.kind,input.start,now);
|
||||
const window=electionWindow(input.kind,input.start,now,approvedStart);
|
||||
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');
|
||||
if(window.votingOpens!==(approvedStart!==null&&input.kind==='imperial'?new Date(approvedStart).toISOString():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.
|
||||
|
|
|
|||
|
|
@ -60,19 +60,16 @@ function electionPreview(imperial=false){
|
|||
const prev=el('button','Previous'),next=el('button','Next');prev.type=next.type='button';prev.disabled=page===0;next.disabled=(page+1)*9>=sorted().length;prev.addEventListener('click',()=>{page--;draw();});next.addEventListener('click',()=>{page++;draw();});pages.append(prev,el('span','Page '+(page+1)+' of '+Math.max(1,Math.ceil(sorted().length/9))),next);
|
||||
if(!grid.children.length)grid.append(el('p','No matching candidates. Your current selection is retained.'));}draw();ballot.append(filters,status,grid,pages,disabled('Submit vote — preview only'));host.append(ballot);return host;
|
||||
}
|
||||
function rallyPreview(){
|
||||
const box=card('Force elections','Two different Houses must agree before a new election is held.','seals/office-landsraad.png');
|
||||
const start=el('section');start.append(el('h4','Start a rally'),el('p','Call for a new election and explain why the chamber should return to the ballot.'));
|
||||
const label=el('label','Reason for the rally'),reason=el('textarea');reason.rows=4;reason.placeholder='Explain why a new election is needed';reason.disabled=true;label.append(reason);start.append(label,disabled('Start a rally'));
|
||||
const support=el('section');support.append(el('h4','House agreement'),el('p','Required support: 2 distinct Houses. Multiple endorsements from the same House count only once.'),el('p','No active rally — this is a design preview.'),disabled('Support this rally'));
|
||||
reason.value='DEMO: We ask the Houses to support a fresh election and a renewed mandate.';support.append(demoSupport());const grid=el('div',undefined,'politics-grid');start.className='politics-charter';support.className='politics-card';grid.append(start,support);box.append(grid);return box;
|
||||
}
|
||||
function counterRallyPreview(){
|
||||
const box=card('Counter rally','Rally House support against the proposed election. Agreement from two distinct Houses denies the election.','seals/emperor-v1.png');
|
||||
const label=el('label','Reason for the counter rally'),reason=el('textarea');reason.rows=4;reason.placeholder='Explain why the proposed election should not proceed';reason.disabled=true;label.append(reason);
|
||||
const draft=el('section',undefined,'politics-charter');draft.append(label,disabled('Start a counter rally'));
|
||||
reason.value='DEMO: Maintain the current mandate and allow the agreed programme to continue.';box.append(draft,el('p','Required support: 2 distinct Houses. Multiple endorsements from the same House count only once.'),el('p','No active counter rally — design preview only.'),demoSupport(true),disabled('Support this counter rally'));return box;
|
||||
function renderRally(counter=false){
|
||||
const box=card(counter?'Counter rally':'Force elections',counter?'Two distinct Houses may oppose an open rally before an election has been authorised.':'Two distinct current Houses must support a fresh Imperial election.','seals/'+(counter?'emperor-v1.png':'office-landsraad.png'));
|
||||
const status=el('p','Loading the official rally…'),votes=el('div'),reason=el('textarea'),label=el('label','Reason'),actions=el('div'),feedback=el('p');reason.rows=3;reason.maxLength=2000;label.append(reason);box.append(status,votes,label,actions,feedback);feedback.setAttribute('role','status');let busy=false;
|
||||
async function submit(action,id){if(busy)return;busy=true;for(const b of actions.querySelectorAll('button'))b.disabled=true;try{const r=await fetch('/api/politics/election-rallies',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({action,requestId:crypto.randomUUID(),rallyId:id,reason:reason.value,confirmed:true})}),data=await r.json();if(!r.ok)throw Error(data.message||'Rally not recorded.');feedback.textContent='Your institutional vote is recorded.';reason.value='';}catch(e){feedback.textContent=e.message;}finally{busy=false;await load();}}
|
||||
function action(label,kind,id){const b=el('button',label);b.type='button';b.onclick=()=>submit(kind,id);actions.append(b);}
|
||||
async function load(){try{const r=await fetch('/api/politics/election-rallies',{cache:'no-store'}),data=await r.json();if(!box.isConnected)return;if(!r.ok)throw Error(data.message||'Rally unavailable.');actions.replaceChildren();votes.replaceChildren();const rally=data.rally;status.textContent=rally?(rally.state==='scheduled'?'Imperial election authorised for '+new Date(rally.electionStart).toLocaleString()+'; the decision is final.':rally.reason+' · Voting closes '+new Date(rally.expiresAt).toLocaleString()):'No active Imperial rally.';for(const v of rally?.votes||[])votes.append(el('p',v.house+' · '+v.choice+(v.reason?' — '+v.reason:'')));if(rally?.canVote)action(counter?'Oppose this rally':'Support this rally',counter?'oppose':'support',rally.id);else if(!counter&&data.canStart)action('Start a rally','start',null);label.hidden=!actions.children.length;}catch(e){status.textContent=e.message;actions.replaceChildren();label.hidden=true;}}
|
||||
queueMicrotask(load);return box;
|
||||
}
|
||||
function rallyPreview(){return renderRally();}
|
||||
function counterRallyPreview(){return renderRally(true);}
|
||||
function revoltPreview(){
|
||||
const box=card('Start revolt','Bring a call for revolt before the Landsraad.','seals/office-landsraad.png');
|
||||
box.append(el('p','Design placeholder. Support requirements and consequences have not been defined; this action is not active.'),disabled('Start revolt'));return box;
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
|
|
@ -1,3 +1,4 @@
|
|||
import {forcedElectionCalendar} from './election-rallies.mjs';
|
||||
import {ELECTION_RULES} from '../control-panel/public/election-rules.mjs';
|
||||
// Election authority is derived at request time, never from a stale cosmetic rank.
|
||||
export async function electionAuthority(db,{userId,playerUuid,faction,now=Date.now()}){
|
||||
|
|
@ -5,10 +6,11 @@ export async function electionAuthority(db,{userId,playerUuid,faction,now=Date.n
|
|||
for(const kind of ['house','imperial']){
|
||||
const first=Date.parse(ELECTION_RULES[kind].first),period=ELECTION_RULES[kind].weeks*604800000;
|
||||
if(now<first+10800000){result[kind]={managed:false};continue;}
|
||||
const electionStart=first+Math.floor((now-first)/period)*period;
|
||||
let electionStart=first+Math.floor((now-first)/period)*period;
|
||||
result[kind]={managed:true,verified:true,active:false,expiresAt:null};
|
||||
if(!userId||!playerUuid||kind==='house'&&!faction)continue;
|
||||
try{
|
||||
if(kind==='imperial'){const forced=await forcedElectionCalendar(db,now);if(forced&&now>=forced.start){const settled=await db.prepare('SELECT id FROM political_office_terms WHERE kind=? AND faction=? AND election_start=? LIMIT 1').bind(kind,'imperium',forced.start).first();if(settled)electionStart=forced.start;}}
|
||||
const term=await db.prepare("SELECT t.user_id,t.player_uuid,t.kind,t.faction,t.election_start,t.starts_at,t.expires_at,t.outcome FROM political_office_terms t JOIN site_game_links l ON l.user_id=t.user_id AND LOWER(l.minecraft_uuid)=t.player_uuid JOIN site_accounts a ON a.id=t.user_id WHERE t.kind=? AND t.faction=? AND t.election_start=? AND t.user_id=? AND t.player_uuid=? AND t.outcome='winner' AND t.starts_at<=? AND t.expires_at>? AND a.password_hash NOT LIKE '!%' LIMIT 1").bind(kind,kind==='house'?faction:'imperium',electionStart,userId,playerUuid.toLowerCase(),now,now).first();
|
||||
if(term&&term.kind===kind&&term.faction===(kind==='house'?faction:'imperium')&&term.user_id===userId&&term.player_uuid===playerUuid.toLowerCase()&&Number(term.election_start)===electionStart&&term.outcome==='winner'&&Number(term.starts_at)<=now&&Number(term.expires_at)>now)result[kind]={managed:true,verified:true,active:true,expiresAt:Number(term.expires_at)};
|
||||
}catch{result[kind]={managed:true,verified:false,active:false,expiresAt:null};}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import {createHash,randomUUID} from 'node:crypto';
|
||||
import {approvedForcedStart} from './election-rallies.mjs';
|
||||
import {electionWindow} from '../control-panel/public/election-rules.mjs';
|
||||
import {ELECTIONS} from '../control-panel/public/political-catalog.mjs';
|
||||
import {JarvisError} from './jarvis-listings.mjs';
|
||||
|
|
@ -9,9 +10,9 @@ export const CAMPAIGN_SCHEMA=[
|
|||
`CREATE TABLE IF NOT EXISTS jarvis_campaign_hours(slot_key VARCHAR(120) NOT NULL,starts_at BIGINT NOT NULL,booking_id CHAR(36) NOT NULL,PRIMARY KEY(slot_key,starts_at),INDEX campaign_hours_booking(booking_id,starts_at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
|
||||
];
|
||||
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
|
||||
export function campaignQuote(application,input,now=Date.now()){
|
||||
export function campaignQuote(application,input,now=Date.now(),approvedStart=null){
|
||||
if(!application||application.status!=='submitted'||!Object.hasOwn(CAMPAIGN_RATES,application.kind))throw new JarvisError('A submitted candidature is required.',403);
|
||||
const start=Number(application.election_start);electionWindow(application.kind,new Date(start).toISOString(),now);
|
||||
const start=Number(application.election_start);electionWindow(application.kind,new Date(start).toISOString(),now,approvedStart);
|
||||
if(!['standard','featured'].includes(input?.placement)||!Array.isArray(input.hours)||!input.hours.length||input.hours.length>168)throw new JarvisError('Choose hourly campaign slots.');
|
||||
const channels=input.channels||[];if(!Array.isArray(channels)||channels.length>2||new Set(channels).size!==channels.length||channels.some(c=>!['boards','discord'].includes(c)))throw new JarvisError('Choose valid promotion channels.');
|
||||
const hours=input.hours.map(v=>typeof v==='number'?v:Date.parse(v));
|
||||
|
|
@ -39,7 +40,7 @@ export function createElectionCampaigns(central,bank,{reserveFee,clock=Date.now,
|
|||
const previous=await tx.first('SELECT * FROM jarvis_campaign_bookings WHERE request_id=? FOR UPDATE',[input.requestId]);
|
||||
if(previous){if(previous.fingerprint!==fingerprint||previous.actor_id!==actor.id)throw new JarvisError('Booking reference already used.',409);return {id:previous.id,replayed:true};}
|
||||
if((input.channels||[]).some(c=>!promotionChannels.includes(c)))throw new JarvisError('A selected promotion channel is unavailable. No charge was made.',503);
|
||||
const application=await candidate(actor,input.applicationId),quote=campaignQuote(application,input,clock());
|
||||
const application=await candidate(actor,input.applicationId),approved=await approvedForcedStart(central,application.kind,application.election_start),quote=campaignQuote(application,input,clock(),approved?Number(application.election_start):null);
|
||||
if(input.expectedTotalMinor!==quote.totalMinor)throw new JarvisError('The campaign price changed. Review the quote.',409);
|
||||
const id=randomUUID(),now=clock();
|
||||
await tx.query("INSERT INTO jarvis_campaign_bookings(id,request_id,actor_id,application_id,kind,faction,election_start,placement,title,message,price_minor,fingerprint,state,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,'booked',?)",[id,input.requestId,actor.id,application.id,application.kind,application.faction,application.election_start,input.placement,title,message,quote.totalMinor,fingerprint,now]);
|
||||
|
|
|
|||
42
website/node/election-rallies.mjs
Normal file
42
website/node/election-rallies.mjs
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
import {randomUUID} from 'node:crypto';
|
||||
import {currentOfficeController} from './entity-relations.mjs';
|
||||
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
|
||||
import {electionDates,ELECTION_RULES} from '../control-panel/public/election-rules.mjs';
|
||||
import {identity} from './auth.mjs';
|
||||
export const RALLY_HOUSES=Object.freeze(['atreides','harkonnen','corrino','ordos','fremen']);
|
||||
export const RALLY_SCHEMA=[
|
||||
`CREATE TABLE IF NOT EXISTS political_election_rallies(id CHAR(36) PRIMARY KEY,term_id CHAR(36) NOT NULL,reason TEXT NOT NULL,state VARCHAR(16) NOT NULL,created_at BIGINT NOT NULL,expires_at BIGINT NOT NULL,election_start BIGINT NULL,KEY rally_term(term_id,state)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
||||
`CREATE TABLE IF NOT EXISTS political_election_rally_votes(request_id CHAR(36) PRIMARY KEY,rally_id CHAR(36) NOT NULL,house VARCHAR(32) NOT NULL,actor_id CHAR(36) NOT NULL,term_id CHAR(36) NOT NULL,choice VARCHAR(8) NOT NULL,reason TEXT NOT NULL,key_id CHAR(36) NOT NULL UNIQUE,created_at BIGINT NOT NULL,UNIQUE KEY rally_house(rally_id,house),UNIQUE KEY rally_actor(rally_id,actor_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
|
||||
];
|
||||
const HOUR=3600000,uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
|
||||
const first=async(db,sql,args=[])=>db.first?db.first(sql,args):((await db.query(sql,args))[0]||null);
|
||||
const fail=(message,status=409)=>{throw Object.assign(Error(message),{status});};
|
||||
export async function initializeElectionRallies(db){for(const sql of RALLY_SCHEMA)await db.query(sql);db.electionRalliesEnabled=true;}
|
||||
export function forcedElectionStart(now){const next=Date.parse(electionDates('imperial',now,1)[0]),start=Math.ceil((now+24*HOUR)/60000)*60000;return start+6*HOUR<next?start:null;}
|
||||
function canOpenRally(now){return !!forcedElectionStart(now)&&Date.parse(electionDates('imperial',now,1)[0])-now>102*HOUR;}
|
||||
export function rallyOutcome(votes){const choices=new Map();for(const vote of votes){if(!RALLY_HOUSES.includes(vote.house)||!['support','oppose'].includes(vote.choice)||choices.has(vote.house))continue;choices.set(vote.house,vote.choice);}const support=[...choices.values()].filter(c=>c==='support').length,oppose=[...choices.values()].filter(c=>c==='oppose').length;return {support,oppose,state:oppose>=2?'denied':support>=2?'scheduled':'open'};}
|
||||
export async function approvedForcedStart(db,kind,start){if(kind!=='imperial'||!db.electionRalliesEnabled)return false;return !!await first(db,"SELECT id FROM political_election_rallies WHERE state='scheduled' AND election_start=?",[Number(start)]);}
|
||||
export async function forcedElectionCalendar(db,now=Date.now()){
|
||||
if(!db.electionRalliesEnabled)return null;
|
||||
const row=await first(db,"SELECT election_start,term_id FROM political_election_rallies WHERE state='scheduled' AND election_start IS NOT NULL ORDER BY election_start DESC LIMIT 1");if(!row)return null;
|
||||
const start=Number(row.election_start),firstRegular=Date.parse(ELECTION_RULES.imperial.first),period=ELECTION_RULES.imperial.weeks*7*86400000,nextRegular=firstRegular+(Math.floor((start-firstRegular)/period)+1)*period;
|
||||
return now<nextRegular?{start,nextRegular,termId:row.term_id}:null;
|
||||
}
|
||||
async function verifiedRallyAuthority(store,office,now){const h=await currentOfficeController(store,office,now);if(!h)return null;const proof=await first(store,"SELECT t.id FROM political_office_terms t JOIN site_game_links l ON l.user_id=t.user_id AND LOWER(l.minecraft_uuid)=LOWER(t.player_uuid) JOIN political_office_charters c ON c.office_key=? AND c.charter_kind='royal' JOIN organisation_keys k ON k.id=c.staff_key_id AND k.account_id=? AND k.key_type='staff-office-royal' AND k.scope_id=CONCAT('office:',c.office_key) AND k.used_at IS NOT NULL AND k.revoked_at IS NULL WHERE t.id=?",[office,STAFF_OFFICE_ACCOUNT_ID,h.termId]);return proof?h:null;}
|
||||
export function createRallyService(db,keys,{clock=Date.now,authority=verifiedRallyAuthority}={}){
|
||||
async function holder(store,actor,now){const matches=[];for(const house of RALLY_HOUSES){const h=await authority(store,house,now);if(h?.userId===actor.id)matches.push({house,termId:h.termId});}return matches.length===1?matches[0]:null;}
|
||||
async function current(store,now){const h=await authority(store,'emperor',now);return h?.termId||null;}
|
||||
async function signedVotes(store,id,now){const rows=await store.query("SELECT v.* FROM political_election_rally_votes v JOIN organisation_keys k ON k.id=v.key_id AND k.account_id=? AND k.key_type='entity-state' AND k.scope_id=CONCAT('state:imperial-rally-vote:',v.request_id) AND k.revoked_at IS NULL WHERE v.rally_id=? ORDER BY v.created_at,v.request_id",[STAFF_OFFICE_ACCOUNT_ID,id]);const out=[];for(const row of rows){const h=await authority(store,row.house,now);if(h?.termId===row.term_id&&h.userId===row.actor_id)out.push(row);}return out;}
|
||||
async function read(actor){const now=clock(),term=await current(db,now),seat=await holder(db,actor,now);const active=term?await first(db,"SELECT * FROM political_election_rallies WHERE term_id=? AND (state='scheduled' OR state='open' AND expires_at>?) ORDER BY created_at DESC,id DESC LIMIT 1",[term,now]):null;const votes=active?await signedVotes(db,active.id,now):[];return {seat:seat?.house||null,canStart:!!(seat&&term&&!active&&canOpenRally(now)&&!await forcedElectionCalendar(db,now)),rally:active?{id:active.id,reason:active.reason,state:active.state,expiresAt:Number(active.expires_at),electionStart:active.election_start==null?null:Number(active.election_start),votes:votes.map(v=>({house:v.house,choice:v.choice,reason:v.reason})),canVote:!!(seat&&active.state==='open'&&!votes.some(v=>v.house===seat.house||v.actor_id===actor.id))}:null};}
|
||||
async function vote(actor,input){if(!actor?.id||!input||!uuid(input.requestId)||!['start','support','oppose'].includes(input.action)||input.confirmed!==true||(input.action!=='start'&&!uuid(input.rallyId)))fail('Confirm a valid rally action.',400);const reason=typeof input.reason==='string'?input.reason.trim():'';if((input.action==='start'||input.action==='oppose')&&(reason.length<10||reason.length>2000)||reason.length>2000)fail('Supply a reason between 10 and 2000 characters.',400);if(!keys)fail('Rally key authority unavailable.',503);
|
||||
return db.transaction(async tx=>{const now=clock(),term=await current(tx,now);if(!term)fail('No current Imperial mandate.');await tx.first('SELECT id FROM political_office_terms WHERE id=? FOR UPDATE',[term]);if(await current(tx,now)!==term)fail('Imperial mandate changed.');const seat=await holder(tx,actor,now);if(!seat)fail('A current native House leader is required.',403);await tx.first('SELECT id FROM political_office_terms WHERE id=? FOR UPDATE',[seat.termId]);const live=await holder(tx,actor,now);if(live?.termId!==seat.termId)fail('House mandate changed.',403);
|
||||
const prior=await tx.first('SELECT * FROM political_election_rally_votes WHERE request_id=? FOR UPDATE',[input.requestId]);if(prior){if(prior.actor_id!==actor.id||prior.choice!==(input.action==='start'?'support':input.action)||prior.reason!==reason||input.action!=='start'&&prior.rally_id!==input.rallyId)fail('Rally reference already used.');return {replayed:true,rallyId:prior.rally_id};}
|
||||
await tx.query("UPDATE political_election_rallies SET state='expired' WHERE term_id=? AND state='open' AND expires_at<=?",[term,now]);let rally=await tx.first("SELECT * FROM political_election_rallies WHERE term_id=? AND state IN ('open','scheduled') ORDER BY created_at DESC LIMIT 1 FOR UPDATE",[term]);
|
||||
if(input.action==='start'){if(rally||!canOpenRally(now)||await forcedElectionCalendar({query:tx.query.bind(tx),electionRalliesEnabled:true},now))fail('A rally is already pending or the regular election is too close.');const id=randomUUID();const expires=now+72*HOUR;await tx.query("INSERT INTO political_election_rallies(id,term_id,reason,state,created_at,expires_at) VALUES(?,?,?,'open',?,?)",[id,term,reason,now,expires]);rally={id,state:'open',expires_at:expires};}
|
||||
if(!rally||rally.state!=='open'||(input.action!=='start'&&rally.id!==input.rallyId)||Number(rally.expires_at)<=now)fail('No open rally is available.');if(await tx.first('SELECT request_id FROM political_election_rally_votes WHERE rally_id=? AND (house=? OR actor_id=?) FOR UPDATE',[rally.id,seat.house,actor.id]))fail('This House has already voted.');
|
||||
await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',scopeId:'state:imperial-rally-vote:'+input.requestId,transactionStore:tx,authorize:async(_,{keyId})=>{await tx.query('INSERT INTO political_election_rally_votes(request_id,rally_id,house,actor_id,term_id,choice,reason,key_id,created_at) VALUES(?,?,?,?,?,?,?,?,?)',[input.requestId,rally.id,seat.house,actor.id,seat.termId,input.action==='start'?'support':input.action,reason,keyId,now]);}});
|
||||
const tally=rallyOutcome(await signedVotes(tx,rally.id,now));if(tally.state==='scheduled'){const start=forcedElectionStart(now);if(!start)fail('The regular election is too close.');await tx.query("UPDATE political_election_rallies SET state='scheduled',election_start=? WHERE id=?",[start,rally.id]);return {...tally,rallyId:rally.id,electionStart:start};}if(tally.state==='denied')await tx.query("UPDATE political_election_rallies SET state='denied' WHERE id=?",[rally.id]);return {...tally,rallyId:rally.id};
|
||||
});}
|
||||
return {read,vote};
|
||||
}
|
||||
export function createRallyAPI(db,service,{origin='https://cp.dunerealms.com',authenticate=r=>identity(r,db)}={}){const reply=(value,status=200)=>Response.json(value,{status,headers:{'Cache-Control':'private, no-store'}});return async request=>{try{const actor=await authenticate(request);if(!actor)return reply({message:'Sign in first.'},401);if(new URL(request.url).search)return reply({message:'Unexpected query.'},400);if(request.method==='GET')return reply(await service.read(actor));if(request.method!=='POST')return reply({message:'Method not allowed.'},405);if(request.headers.get('origin')!==origin)return reply({message:'Origin rejected.'},403);const raw=await request.text();if(raw.length>6000)return reply({message:'Request too large.'},413);let body;try{body=JSON.parse(raw);}catch{return reply({message:'Invalid rally request.'},400);}return reply(await service.vote(actor,body));}catch(e){return reply({message:e.status?e.message:'Rally processing unavailable.'},e.status||503);}};}
|
||||
|
|
@ -41,7 +41,7 @@ export function createOrganisationKeys(db,{secret,editions=null}={}){
|
|||
return Object.freeze({
|
||||
async inspect(code,{accountId=null,expectedType=null}={}){let parsed,keyType,hash;try{parsed=parseOrganisationCode(code);keyType=Object.keys(ORGANISATION_KEY_TYPES).find(k=>ORGANISATION_KEY_TYPES[k].prefix===parsed.prefix);if(!keyType)return{valid:false,state:'unsupported'};hash=hashOrganisationKey(code,keyType);}catch{return{valid:false,state:'invalid'};}const row=await readFirst(db,'SELECT id,account_id,key_type,expires_at,revoked_at,used_at FROM organisation_keys WHERE code_hash=?',[hash]);if(!row||accountId&&row.account_id!==accountId||expectedType&&row.key_type!==expectedType)return{valid:false,state:'invalid'};if(parsed.edition){if(!editions)return{valid:false,state:'unavailable'};const edition=await editions.read(row.id);if(['stage','version','season'].some(k=>edition[k]!==parsed.edition[k]))return{valid:false,state:'invalid'};}return{valid:true,type:row.key_type,purpose:type(row.key_type).purpose,state:row.revoked_at!=null?'revoked':row.used_at!=null?'used':row.expires_at!=null&&Number(row.expires_at)<=Date.now()?'expired':'available'};},
|
||||
async issue({accountId,keyType,scopeId,expiresAt=null,authorize=null,transactionStore=null}){
|
||||
if(transactionStore&&(!(keyType==='organisation-action'||keyType==='entity-state'&&accountId===STAFF_OFFICE_ACCOUNT_ID&&/^state:(?:political-decision|political-review-publication|political-agreement-reply|political-ballot-vote|naib-council|world-trade):[a-f0-9-]{36}$/i.test(scopeId))||typeof transactionStore.query!=='function'||typeof transactionStore.first!=='function'))throw TypeError('A scoped action transaction is required');
|
||||
if(transactionStore&&(!(keyType==='organisation-action'||keyType==='entity-state'&&accountId===STAFF_OFFICE_ACCOUNT_ID&&/^state:(?:political-decision|political-review-publication|political-agreement-reply|political-ballot-vote|imperial-rally-vote|naib-council|world-trade):[a-f0-9-]{36}$/i.test(scopeId))||typeof transactionStore.query!=='function'||typeof transactionStore.first!=='function'))throw TypeError('A scoped action transaction is required');
|
||||
type(keyType);
|
||||
if(keyType==='economy-operation'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||typeof authorize!=='function'||!/^economy\.(reset-balances|repay-loans|federal-cycle):[a-f0-9-]{36}$/i.test(scopeId)))throw TypeError('Economic keys require a scoped system authority adapter');
|
||||
if(keyType==='kit-definition'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||typeof authorize!=='function'||!/^kitset:[a-f0-9-]{36}:v[1-9]\d{0,5}$/i.test(scopeId)))throw TypeError('Kit definitions require a saved set and authority adapter');
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import {randomUUID} from 'node:crypto';
|
||||
import {approvedForcedStart} from './election-rallies.mjs';
|
||||
import {ELECTION_RULES} from '../control-panel/public/election-rules.mjs';
|
||||
import {PUBLIC_OFFICES} from './public-government.mjs';
|
||||
import {currentNaib} from './naib-membership.mjs';
|
||||
|
|
@ -18,7 +19,7 @@ export async function applyOfficeAuctionTransfer(central,job,{clock=Date.now}={}
|
|||
if(existing){if(existing.user_id!==job.winner_id)throw Error('Conflicting office transfer');return{termId:existing.id,replayed:true};}
|
||||
const candidates=JSON.parse(trigger.application_ids);let application=await tx.first("SELECT p.* FROM political_applications p JOIN site_accounts a ON a.id=p.user_id JOIN site_game_links l ON l.user_id=p.user_id AND LOWER(l.minecraft_uuid)=p.player_uuid WHERE p.user_id=? AND p.kind=? AND p.faction=? AND p.election_start=? AND p.status='submitted' AND a.password_hash NOT LIKE '!%'",[job.winner_id,trigger.kind,trigger.faction,trigger.election_start]);
|
||||
if(!candidates.length){const vacancy=await tx.first("SELECT i.player_uuid FROM political_auction_identities i JOIN site_accounts a ON a.id=i.user_id JOIN site_game_links l ON l.user_id=i.user_id AND LOWER(l.minecraft_uuid)=i.player_uuid WHERE i.source_id=? AND i.user_id=? AND a.password_hash NOT LIKE '!%'",[job.source_id,job.winner_id]);if(!vacancy)throw Error('Vacancy winner identity changed');application={id:null,player_uuid:vacancy.player_uuid};}else if(!application||!candidates.includes(application.id))throw Error('Winning candidature is no longer eligible');
|
||||
const now=clock(),expiry=Number(trigger.election_start)+ELECTION_RULES[trigger.kind].weeks*604800000;if(now>=expiry)throw Error('The office term already ended');
|
||||
const now=clock(),start=Number(trigger.election_start),period=ELECTION_RULES[trigger.kind].weeks*604800000,first=Date.parse(ELECTION_RULES[trigger.kind].first),forced=await approvedForcedStart({query:tx.query.bind(tx),electionRalliesEnabled:central.electionRalliesEnabled},trigger.kind,start),expiry=forced?first+(Math.floor((start-first)/period)+1)*period:start+period;if(now>=expiry)throw Error('The office term already ended');
|
||||
if(trigger.kind==='naib_chair'&&!await currentNaib(tx,job.winner_id,{lock:true}))throw Error('The chair must remain a current Naib');
|
||||
const prior=await tx.first('SELECT * FROM political_office_terms WHERE kind=? AND faction=? ORDER BY starts_at DESC,id DESC LIMIT 1 FOR UPDATE',[trigger.kind,trigger.faction]);
|
||||
if(prior&&Number(prior.election_start)>Number(trigger.election_start))throw Error('A newer election already governs this office');
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import {forcedElectionCalendar} from './election-rallies.mjs';
|
||||
import {ELECTION_RULES,electionDates,electionWindow} from '../control-panel/public/election-rules.mjs';
|
||||
import {ELECTIONS} from '../control-panel/public/political-catalog.mjs';
|
||||
import {naibSeats} from './naib-membership.mjs';
|
||||
|
|
@ -11,9 +12,9 @@ export function projectGovernment(terms,now=Date.now()){
|
|||
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()){
|
||||
export function publicElectionCalendar(now=Date.now(),forced=null){
|
||||
return Object.keys(ELECTION_RULES).map(kind=>{
|
||||
const dates=electionDates(kind,now-3*3600000,1),window=electionWindow(kind,dates[0],now);
|
||||
const exceptional=kind==='imperial'&&forced&&now<forced.start+3*3600000?forced.start:null;const dates=exceptional?[new Date(exceptional).toISOString()]:electionDates(kind,now-3*3600000,1),window=electionWindow(kind,dates[0],now,exceptional);
|
||||
return {kind,...window,termWeeks:4};
|
||||
});
|
||||
}
|
||||
|
|
@ -28,6 +29,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','muad_dib','spacing_guild','clan_delegate'],chambers:[{name:'Imperial Senate',offices:['emperor','atreides','harkonnen','corrino','ordos']},{name:'Small Council',offices:['veiled_concord','muad_dib','spacing_guild','clan_delegate']}],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','muad_dib','spacing_guild','clan_delegate'],chambers:[{name:'Imperial Senate',offices:['emperor','atreides','harkonnen','corrino','ordos']},{name:'Small Council',offices:['veiled_concord','muad_dib','spacing_guild','clan_delegate']}],clanAffiliation:'home_world',companiesBranch:'spacing_guild'},offices,elections:publicElectionCalendar(now,await forcedElectionCalendar(db,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'}});}
|
||||
};}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import {initializeElectionRallies} from './election-rallies.mjs';
|
||||
import {initializeClanFaith} from './clan-faith.mjs';
|
||||
import {initializeWorldTrade} from './world-trade-governance.mjs';
|
||||
import {POLITICAL_REVIEW_PUBLICATION_SCHEMA} from './political-reviews.mjs';
|
||||
|
|
@ -127,7 +128,7 @@ export function createApplication(db,settings={},dependencies={}) {
|
|||
};
|
||||
}
|
||||
export async function start(settings=process.env) {
|
||||
const db=await openDatabase(settings);await db.query(POLITICAL_DECISION_SCHEMA);await db.query(POLITICAL_REVIEW_PUBLICATION_SCHEMA);await initializeWorldTrade(db);await initializeClanFaith(db);db.worldTradeEnabled=settings.WORLD_TRADE_ENABLED==='true';db.politicalDecisionsEnabled=true;await initializeKitsets(db);if(db.organisationAccessEnabled)await initializeOrganisation(db);await initializeRanks(db);await initializeGitIdentities(db);await initializePublicRoster(db);await initializeLifeStatus(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;for(const sql of POLITICAL_APPOINTMENT_SCHEMA)await db.query(sql);db.politicalAppointmentsEnabled=true;await initializeShareLedger(db);if(settings.SYSTEM_BOARDS_ENABLED==='1')await prepareBoardKeyReadModel(db);const handle=createApplication(db,settings),origin=new URL(settings.PUBLIC_ORIGIN||'https://dunerealms.com').origin;
|
||||
const db=await openDatabase(settings);await db.query(POLITICAL_DECISION_SCHEMA);await db.query(POLITICAL_REVIEW_PUBLICATION_SCHEMA);await initializeWorldTrade(db);await initializeElectionRallies(db);await initializeClanFaith(db);db.worldTradeEnabled=settings.WORLD_TRADE_ENABLED==='true';db.politicalDecisionsEnabled=true;await initializeKitsets(db);if(db.organisationAccessEnabled)await initializeOrganisation(db);await initializeRanks(db);await initializeGitIdentities(db);await initializePublicRoster(db);await initializeLifeStatus(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;for(const sql of POLITICAL_APPOINTMENT_SCHEMA)await db.query(sql);db.politicalAppointmentsEnabled=true;await initializeShareLedger(db);if(settings.SYSTEM_BOARDS_ENABLED==='1')await prepareBoardKeyReadModel(db);const handle=createApplication(db,settings),origin=new URL(settings.PUBLIC_ORIGIN||'https://dunerealms.com').origin;
|
||||
let forgeHeader=settings.FORGEJO_AUTH_HEADER;
|
||||
if(!forgeHeader&&settings.FORGEJO_URL){const config=await readFile(settings.FORGEJO_CONFIG_FILE||'/home/dunerealms/apps/forgejo/custom/conf/app.ini','utf8');forgeHeader=forgejoIdentityHeader(config);}
|
||||
if(settings.FORGEJO_URL&&!/^[A-Za-z0-9-]+$/.test(forgeHeader||''))throw Error('DuneGit proxy identity header is not configured.');
|
||||
|
|
|
|||
16
website/tests/election-rallies.test.mjs
Normal file
16
website/tests/election-rallies.test.mjs
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto';
|
||||
import {STAFF_OFFICE_ACCOUNT_ID} from '../node/organisation-keys.mjs';
|
||||
import {applicationSchema,submitApplication} from '../control-panel/election-applications.mjs';
|
||||
import {roundSchema,openFirstRound,finalizeRound} from '../control-panel/election-rounds.mjs';
|
||||
import {ballotSchema,castBallot} from '../control-panel/election-ballots.mjs';
|
||||
import {officeLedgerSchema,reconcileOfficeResult} from '../control-panel/election-office-ledger.mjs';
|
||||
import {electionAuthority} from '../node/election-authority.mjs';
|
||||
import {companyFixture} from './company-deed-fixture.mjs';
|
||||
import {initializeElectionRallies,createRallyService,forcedElectionCalendar,approvedForcedStart,forcedElectionStart} from '../node/election-rallies.mjs';
|
||||
import {electionWindow,validateCandidature} from '../control-panel/public/election-rules.mjs';
|
||||
import {planRoundResult} from '../control-panel/election-ballots.mjs';import {planOfficeTerm} from '../control-panel/election-office-ledger.mjs';
|
||||
async function fixture(){const f=await companyFixture();const old=f.db.query.bind(f.db);f.db.query=(sql,args=[])=>old(sql.replace(/,\s*KEY \w+\([^)]*\)/g,''),args);f.db.sqlite.function('CONCAT',{varargs:true},(...args)=>args.join(''));f.db.sqlite.exec('DROP TABLE political_office_terms;CREATE TABLE political_office_charters(office_key TEXT PRIMARY KEY,charter_kind TEXT,staff_key_id TEXT);');for(const sql of [...applicationSchema,...roundSchema,...ballotSchema,...officeLedgerSchema])await f.db.query(sql.replace(/ ENGINE=InnoDB(?: DEFAULT CHARSET=utf8mb4)?/g,'').replace(/UNIQUE KEY \w+\s*\(/g,'UNIQUE('));f.db.batch=statements=>f.db.transaction(async tx=>{const results=[];for(const statement of statements)results.push(await statement.run({execute:async(sql,args)=>[await tx.query(sql.replace(/ FOR SHARE/g,''),args)]}));return results;});let now=Date.parse('2026-11-25T10:00:00Z');const terms={},players={},cycle=Date.parse('2026-11-15T15:00:00Z');for(const [name,house]of [['Owner','imperium'],['Ceo','atreides'],['Member','harkonnen'],['Other','corrino']]){const imperial=house==='imperium';const term=randomUUID(),office=imperial?'emperor':'house_leader',officeKey=imperial?'emperor':house,player=randomUUID();players[name]=player;terms[name]=term;await f.db.query('UPDATE site_game_links SET minecraft_uuid=? WHERE user_id=?',[player,f.people[name].id]);await f.db.query("INSERT INTO political_office_terms(id,user_id,kind,faction,office,outcome,starts_at,expires_at,election_start,round_id,player_uuid,streak) VALUES(?,?,?,?,?,'winner',?,?,?,?,?,1)",[term,f.people[name].id,imperial?'imperial':'house',house,office,now-86400000,now+10*86400000,cycle,randomUUID(),player]);const grant=await f.keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-office-royal',scopeId:'office:'+officeKey,authorize:async()=>true});await f.keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-office-royal',code:grant.code,targetId:randomUUID(),requestId:randomUUID(),apply:(tx,{keyId})=>tx.query('INSERT INTO political_office_charters VALUES(?,?,?)',[officeKey,'royal',keyId])});}await initializeElectionRallies(f.db);const service=createRallyService(f.db,f.keys,{clock:()=>now});const vote=(name,action,rallyId=null,requestId=randomUUID())=>service.vote(f.people[name],{action,rallyId,requestId,reason:action==='support'?'':'We request a new mandate for the elected chamber.',confirmed:true});return {...f,service,vote,terms,players,now:()=>now,advance:ms=>now+=ms};}
|
||||
test('two current distinct House mandates authorise one verified exceptional election, not the Emperor',async()=>{const f=await fixture();try{await assert.rejects(f.vote('Owner','start'),/House leader/);const first=await f.vote('Ceo','start');assert.equal(first.state,'open');await assert.rejects(f.vote('Ceo','support',first.rallyId),/already voted/);const second=await f.vote('Member','support',first.rallyId);assert.equal(second.state,'scheduled');assert.equal(second.electionStart,forcedElectionStart(f.now()));assert.equal(await approvedForcedStart(f.db,'imperial',second.electionStart),true);assert.equal((await forcedElectionCalendar(f.db,f.now())).termId,f.terms.Owner);await assert.rejects(f.vote('Other','oppose',first.rallyId),/No open rally/);await assert.rejects(f.vote('Other','start'),/already pending/);assert.equal((await f.service.read(f.people.Other)).rally.state,'scheduled');const start=new Date(second.electionStart).toISOString();assert.throws(()=>electionWindow('imperial',start,f.now()),/outside/);assert.equal(electionWindow('imperial',start,f.now(),second.electionStart).phase,'applications');assert.equal(validateCandidature({kind:'imperial',start,motivation:'A fresh mandate for our realm.',accepted:true},{linked:true},f.now(),second.electionStart).start,start);const result=planRoundResult({kind:'imperial',start,candidates:[]},second.electionStart+10800000,second.electionStart);assert.equal(result.status,'no_votes');const term=planOfficeTerm({kind:'imperial',faction:'imperium',election_start:second.electionStart,closes_at:second.electionStart+10800000,status:'no_votes'},null,null,second.electionStart+10800000,second.electionStart);assert.equal(term.expiresAt,(await forcedElectionCalendar(f.db,f.now())).nextRegular);}finally{f.db.close();}});
|
||||
test('two distinct opponents deny an open rally before scheduling',async()=>{const f=await fixture();try{const opened=await f.vote('Ceo','start');assert.equal((await f.vote('Member','oppose',opened.rallyId)).state,'open');assert.equal((await f.vote('Other','oppose',opened.rallyId)).state,'denied');assert.equal(await forcedElectionCalendar(f.db,f.now()),null);await assert.rejects(f.vote('Member','support',opened.rallyId),/No open rally/);}finally{f.db.close();}});
|
||||
test('expired proposals and revoked mandates never become authorisation',async()=>{const f=await fixture();try{const opened=await f.vote('Ceo','start');await f.db.query("UPDATE political_office_terms SET outcome='superseded' WHERE id=?",[f.terms.Ceo]);const one=await f.vote('Member','support',opened.rallyId);assert.equal(one.support,1);assert.equal(one.state,'open');f.advance(73*3600000);await assert.rejects(f.vote('Other','support',opened.rallyId),/No open rally/);assert.equal(await forcedElectionCalendar(f.db,f.now()),null);}finally{f.db.close();}});
|
||||
test('authorised rally completes the actual application, round, ballot and incumbent replacement flow',async()=>{const f=await fixture();try{const opened=await f.vote('Ceo','start'),accepted=await f.vote('Member','support',opened.rallyId),opens=accepted.electionStart,start=new Date(opens).toISOString(),context={linked:true,playerUuid:f.players.Other,faction:'corrino'},app=await submitApplication(f.db,{actor:f.people.Other,context,input:{kind:'imperial',start,accepted:true,motivation:'A new mandate to represent every House.'},now:f.now(),clock:f.now});assert.ok(app.created);const before=await electionAuthority(f.db,{userId:f.people.Owner.id,playerUuid:f.players.Owner,now:opens-1});assert.equal(before.imperial.active,true);const round=await openFirstRound(f.db,{kind:'imperial',faction:'imperium',start,now:opens});await castBallot(f.db,{actor:f.people.Other,context,input:{kind:'imperial',start,roundId:round.id,requestId:randomUUID(),confirmed:true,allocations:[{applicationId:app.id,votes:1}]},now:opens+1,clock:()=>opens+1});const closed=opens+10800000;assert.equal((await finalizeRound(f.db,{roundId:round.id,now:closed})).winner,app.id);const term=await reconcileOfficeResult(f.db,{roundId:round.id,now:closed});assert.equal(term.userId,f.people.Other.id);assert.equal((await f.db.first('SELECT outcome FROM political_office_terms WHERE id=?',[f.terms.Owner])).outcome,'superseded');const rights=await electionAuthority(f.db,{userId:f.people.Other.id,playerUuid:f.players.Other,now:closed+1});assert.equal(rights.imperial.active,true);assert.equal((await electionAuthority(f.db,{userId:f.people.Owner.id,playerUuid:f.players.Owner,now:closed+1})).imperial.active,false);f.advance(closed+1-f.now());assert.equal((await f.service.read(f.people.Ceo)).canStart,false);await assert.rejects(f.vote('Ceo','start'),/already pending/);}finally{f.db.close();}});
|
||||
Loading…
Reference in a new issue

Staff