forked from unimatrix/web
16 lines
8 KiB
JavaScript
16 lines
8 KiB
JavaScript
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();}});
|

Staff