web/website/node/election-results.mjs
2026-11-21 20:22:37 +01:00

24 lines
3.6 KiB
JavaScript

import {identity} from './auth.mjs';import {accessFor} from './permissions.mjs';
import {createPoliticsPreview} from '../control-panel/politics-preview.mjs';
import {ELECTION_RULES,electionScope} from '../control-panel/public/election-rules.mjs';
export function createElectionResults(db,settings={},deps={}){
const auth=deps.authenticate||(r=>identity(r,db)),access=deps.access||(u=>accessFor(db,u)),preview=deps.preview||createPoliticsPreview(db,settings);
return async request=>{
const reply=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'private, no-store'}});
try{
const url=new URL(request.url),kind=url.pathname.split('/').at(-1),actor=await auth(request);
if(!actor)return reply({message:'Sign in first.'},401);
if(request.method!=='GET')return reply({message:'Read-only election register.'},405);
if(!(await access(actor)).nodes.includes('web.menu.game'))return reply({message:'Community game access required.'},403);
if(!Object.hasOwn(ELECTION_RULES,kind)||[...url.searchParams.keys()].some(k=>k!=='round')||url.searchParams.getAll('round').length>1)return reply({message:'Choose an election.'},400);
let context={};if(kind==='house'){const result=await preview(new Request('https://cp.dunerealms.com/api/politics/preview',{headers:request.headers}));if(!result.ok)return reply({message:'Faction could not be verified.'},503);context=await result.json();if(context.factionStatus!=='verified')return reply({message:'Verified faction required.'},403);}
const faction=electionScope(kind,context),roundId=url.searchParams.get('round');
if(roundId&&!/^[a-f0-9-]{36}$/i.test(roundId))return reply({message:'Choose a recorded round.'},400);
const {results:rounds}=await db.prepare('SELECT r.id,r.election_start,r.round_number,r.opens_at,r.closes_at,r.status,u.username winner,t.auction_id FROM political_election_rounds r LEFT JOIN political_applications a ON a.id=r.winner_id LEFT JOIN site_accounts u ON u.id=a.user_id LEFT JOIN political_auction_triggers t ON t.round_id=r.id WHERE r.kind=? AND r.faction=?'+(roundId?' AND r.id=?':'')+' ORDER BY r.election_start DESC,r.round_number DESC LIMIT 40').bind(kind,faction,...(roundId?[roundId]:[])).all();
if(roundId&&!rounds.length)return reply({message:'Round not found in this election.'},404);
const {results:terms}=await db.prepare('SELECT t.id,t.starts_at,t.expires_at,t.outcome,t.streak,t.round_id,u.username,COALESCE(u.display_name,u.username) name FROM political_office_terms t JOIN site_accounts u ON u.id=t.user_id WHERE t.kind=? AND t.faction=? ORDER BY t.starts_at DESC,t.id LIMIT 100').bind(kind,faction).all();
let candidates=[];if(roundId)candidates=(await db.prepare('SELECT a.public_id,a.motivation,u.username,COALESCE(SUM(v.votes),0) 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.public_id,a.motivation,u.username ORDER BY votes DESC,u.username').bind(roundId).all()).results;
return reply({kind,faction,rounds:rounds.map(r=>({...r,election_start:Number(r.election_start),opens_at:Number(r.opens_at),closes_at:Number(r.closes_at),round_number:Number(r.round_number)})),terms:terms.map(t=>({...t,starts_at:Number(t.starts_at),expires_at:Number(t.expires_at),streak:Number(t.streak)})),candidates:candidates.map(c=>({...c,votes:Number(c.votes)}))});
}catch{return reply({message:'Election history is temporarily unavailable.'},503);}
};
}