web/website/control-panel/public/election-applications-view.mjs

30 lines
7.9 KiB
JavaScript

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==='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 ensureElectionRecordStyles(){if(!document.querySelector('link[data-election-records]')){const link=node('link');link.rel='stylesheet';link.href=new URL('./cp-v2/cp-v2-election-records.css',import.meta.url).href;link.dataset.electionRecords='';document.head.append(link);}}
export function renderApplications({user,context,kind:onlyKind=null}){
ensureElectionRecordStyles();
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 ballot. Tied elections proceed to an office auction. Cosmetic rank and seal delivery is still being connected.'));
const status=node('p','Loading your applications…');status.setAttribute('role','status');register.append(status);
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'&&['atreides','harkonnen','corrino','ordos','fremen'].includes(context.faction)){const o=node('option',context.faction==='veiled_concord'?'CON · Reverent Mother':'HSE · House Leader');o.value='house';select.append(o);}
if(context?.naib){const option=node('option','Council of Naibs Chair');option.value='naib_chair';select.append(option);}
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);}if(onlyKind){for(const option of [...select.options])if(option.value!==onlyKind)option.remove();select.value=onlyKind;}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');
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;}
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==='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();}});
queueMicrotask(load);return host;
}