web/website/tests/office-auction-runtime.test.mjs

22 lines
6.5 KiB
JavaScript

import {POLITICAL_SUCCESSION_SCHEMA,createPoliticalSuccession} from '../node/political-succession.mjs';
import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto';
import {BankFixture} from './postbank-fixture.mjs';import {officeLedgerSchema} from '../control-panel/election-office-ledger.mjs';import {roundSchema,finalizeRound} from '../control-panel/election-rounds.mjs';
import {createOfficeAuctionRuntime} from '../node/office-auction-runtime.mjs';import {OFFICE_AUCTION_SCHEMA} from '../node/jarvis-office-auctions.mjs';import {AUCTION_HOLD_SCHEMA} from '../node/jarvis-auction-payments.mjs';import {OFFICE_TRANSFER_SCHEMA} from '../node/political-auction-transfer.mjs';import {readGovernmentOffices} from '../node/public-government.mjs';
const normalize=sql=>sql.replace(/,UNIQUE KEY office_cycle\([^)]*\)/g,'').replace(/ ENGINE=InnoDB(?: DEFAULT CHARSET=utf8mb4)?/g,'').replace(/UNIQUE KEY \w+\(/g,'UNIQUE(');
async function fixture(){const central=new BankFixture(),bank=new BankFixture();for(const sql of [...officeLedgerSchema,...roundSchema,...POLITICAL_SUCCESSION_SCHEMA])await central.query(normalize(sql));for(const sql of [...OFFICE_AUCTION_SCHEMA,AUCTION_HOLD_SCHEMA,OFFICE_TRANSFER_SCHEMA])await bank.query(normalize(sql));
central.prepare=sql=>({bind(...args){return{first:()=>central.first(sql,args),all:async()=>({results:await central.query(sql,args)}),run:async()=>({meta:{changes:(await central.query(sql,args)).affectedRows}})};},all:async()=>({results:await central.query(sql)})});central.batch=async entries=>central.transaction(async tx=>Promise.all(entries.map(entry=>entry.run({execute:async(sql,args)=>[await tx.query(sql,args)]}))));
central.sqlite.exec('CREATE TABLE site_accounts(id TEXT PRIMARY KEY,username TEXT,display_name TEXT,role TEXT,password_hash TEXT);CREATE TABLE site_game_links(user_id TEXT PRIMARY KEY,minecraft_uuid TEXT);CREATE TABLE political_applications(id TEXT PRIMARY KEY,user_id TEXT,player_uuid TEXT,kind TEXT,faction TEXT,election_start INT,status TEXT);CREATE TABLE political_ballots(id TEXT,round_id TEXT);CREATE TABLE political_ballot_allocations(ballot_id TEXT,application_id TEXT,votes INT);CREATE TABLE site_character_choices(user_id TEXT,minecraft_uuid TEXT,faction TEXT);CREATE TABLE site_account_policies(user_id TEXT,game_link_exempt INT);CREATE TABLE cp_account_ranks(user_id TEXT,rank_key TEXT)');
const start=Date.parse('2026-11-15T15:00:00Z'),round=randomUUID(),people=[0,1,2].map(i=>({id:randomUUID(),applicationId:randomUUID(),player:randomUUID(),username:'candidate'+i}));let now=start+10800000;
await central.query("INSERT INTO political_election_rounds VALUES(?,'imperial','imperium',?,0,?,?,'open',NULL)",[round,start,start,now]);
for(const [index,user]of people.entries()){await central.query("INSERT INTO site_accounts VALUES(?,?,?,'user','hash')",[user.id,user.username,user.username]);await central.query('INSERT INTO site_game_links VALUES(?,?)',[user.id,user.player]);await central.query("INSERT INTO political_applications VALUES(?,?,?,'imperial','imperium',?,'submitted')",[user.applicationId,user.id,user.player,start]);await central.query('INSERT INTO political_round_candidates VALUES(?,?)',[round,user.applicationId]);const ballot=randomUUID();await central.query('INSERT INTO political_ballots VALUES(?,?)',[ballot,round]);await central.query('INSERT INTO political_ballot_allocations VALUES(?,?,?)',[ballot,user.applicationId,index===2?1:3]);}
const runtime=createOfficeAuctionRuntime(central,bank,{clock:()=>now,authority:async()=>({entities:[]})});return{central,bank,people,start,round,runtime,now:()=>now,advance:()=>now+=10800000,close(){central.close();bank.close();}};
}
test('real tied round queues one auction; no-bid lottery assigns the protected office through the durable transfer and retries do not duplicate terms',async()=>{const f=await fixture();try{
const result=await finalizeRound(f.central,{roundId:f.round,now:f.now()});assert.equal(result.status,'auction_required');assert.equal(result.nextRound,null);assert.equal((await finalizeRound(f.central,{roundId:f.round,now:f.now()})).replayed,true);
const trigger=await f.central.first('SELECT * FROM political_auction_triggers');assert.deepEqual(new Set(JSON.parse(trigger.candidate_ids)),new Set(f.people.slice(0,2).map(p=>p.id)));
let tick=await f.runtime.process();assert.equal(tick.failed,0);assert.equal(tick.opened,1);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM jarvis_office_auctions')).n,1);f.advance();tick=await f.runtime.process();assert.equal(tick.failed,0);assert.equal(tick.transferred,1);
const term=await f.central.first('SELECT * FROM political_office_terms');assert.ok(f.people.slice(0,2).some(p=>p.id===term.user_id));assert.equal(term.outcome,'winner');assert.equal(term.office,'emperor');assert.equal(term.expires_at,f.start+4*7*86400000);
const government=await readGovernmentOffices(f.central,f.now());assert.equal(government.find(o=>o.key==='emperor').state,'occupied');assert.equal((await f.runtime.process()).failed,0);assert.equal((await f.central.first('SELECT COUNT(*) n FROM political_office_terms')).n,1);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,0);
}finally{f.close();}});
test('resignation queues a fresh auction open to eligible non-candidates and preserves the previous resignation',async()=>{const f=await fixture();try{await finalizeRound(f.central,{roundId:f.round,now:f.now()});await f.runtime.process();f.advance();await f.runtime.process();const first=await f.central.first('SELECT * FROM political_office_terms');const succession=createPoliticalSuccession(f.central,{clock:f.now});const resigned=await succession.resign({id:first.user_id},{termId:first.id,requestId:randomUUID(),confirmed:true});let result=await f.runtime.process();assert.equal(result.failed,0);const auction=await f.bank.first('SELECT * FROM jarvis_office_auctions WHERE source_id=?',[resigned.successorFlowId]);assert.ok(auction);assert.equal(JSON.parse(auction.candidate_ids).length,3);assert.equal(await f.runtime.eligible(null,f.people[2],auction),true);f.advance();result=await f.runtime.process();assert.equal(result.failed,0);assert.equal(result.transferred,1);assert.equal((await f.central.first('SELECT outcome FROM political_office_terms WHERE id=?',[first.id])).outcome,'resigned');assert.equal((await f.central.first('SELECT COUNT(*) n FROM political_office_terms')).n,2);assert.equal((await f.central.first("SELECT COUNT(*) n FROM political_office_terms WHERE outcome='winner' AND expires_at>?",[f.now()])).n,1);}finally{f.close();}});