54 lines
6.1 KiB
JavaScript
54 lines
6.1 KiB
JavaScript
import {randomUUID,createHash} from 'node:crypto';
|
|
import {JarvisError} from './jarvis-listings.mjs';
|
|
import {currentNaib} from './naib-membership.mjs';
|
|
export const POLITICAL_SUCCESSION_SCHEMA=[
|
|
`CREATE TABLE IF NOT EXISTS political_auction_identities(source_id CHAR(36) NOT NULL,user_id CHAR(36) NOT NULL,player_uuid CHAR(36) NOT NULL,PRIMARY KEY(source_id,user_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
`CREATE TABLE IF NOT EXISTS political_succession_flows(id CHAR(36) PRIMARY KEY,source_term_id CHAR(36) NOT NULL UNIQUE,kind VARCHAR(16) NOT NULL,faction VARCHAR(32) NOT NULL,office VARCHAR(32) NOT NULL,reason VARCHAR(24) NOT NULL,state VARCHAR(24) NOT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
`CREATE TABLE IF NOT EXISTS political_resignations(request_id CHAR(36) PRIMARY KEY,term_id CHAR(36) NOT NULL UNIQUE,user_id CHAR(36) NOT NULL,fingerprint CHAR(64) NOT NULL,successor_flow_id CHAR(36) NOT NULL,created_at BIGINT NOT NULL) 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 createPoliticalSuccession(db,{clock=Date.now}={}){
|
|
return Object.freeze({
|
|
async resign(actor,{termId,requestId,confirmed}){
|
|
if(!uuid(actor?.id)||!uuid(termId)||!uuid(requestId)||confirmed!==true)throw new JarvisError('Confirm the office resignation.',400);
|
|
const fingerprint=createHash('sha256').update(actor.id+':'+termId).digest('hex');
|
|
return db.transaction(async tx=>{
|
|
const term=await tx.first('SELECT * FROM political_office_terms WHERE id=? FOR UPDATE',[termId]);
|
|
if(!term||term.user_id!==actor.id)throw new JarvisError('Only the current office holder may resign.',403);
|
|
const previous=await tx.first('SELECT * FROM political_resignations WHERE request_id=?',[requestId]);
|
|
if(previous){if(previous.fingerprint!==fingerprint)throw new JarvisError('Resignation reference already used.',409);return{termId,successorFlowId:previous.successor_flow_id,replayed:true};}
|
|
const now=clock();if(term.outcome!=='winner'||Number(term.starts_at)>now||Number(term.expires_at)<=now)throw new JarvisError('This office is no longer active.',409);
|
|
const flowId=randomUUID();
|
|
await tx.query("UPDATE political_office_terms SET outcome='resigned',expires_at=? WHERE id=?",[now,termId]);
|
|
await tx.query("INSERT INTO political_succession_flows(id,source_term_id,kind,faction,office,reason,state,created_at) VALUES(?,?,?,?,?,'resignation','queued',?)",[flowId,termId,term.kind,term.faction,term.office,now]);
|
|
await tx.query('INSERT INTO political_resignations(request_id,term_id,user_id,fingerprint,successor_flow_id,created_at) VALUES(?,?,?,?,?,?)',[requestId,termId,actor.id,fingerprint,flowId,now]);
|
|
await tx.query('INSERT INTO political_office_events(id,term_id,event,payload,created_at) VALUES(?,?,?,?,?)',[randomUUID(),termId,'resigned',JSON.stringify({successorFlowId:flowId}),now]);
|
|
// Existing authority reads require outcome=winner and an unexpired term.
|
|
// The new successor flow never rewrites the old election or auction result.
|
|
return {termId,successorFlowId:flowId,replayed:false};
|
|
});
|
|
},
|
|
async history(userId){
|
|
if(!uuid(userId))throw new JarvisError('Choose a citizen.',400);
|
|
return db.query('SELECT kind,faction,office,starts_at,expires_at,outcome FROM political_office_terms WHERE user_id=? ORDER BY starts_at DESC,id DESC LIMIT 100',[userId]);
|
|
}
|
|
});
|
|
}
|
|
|
|
export async function queueVacantOfficeAuction(central,flow,{clock=Date.now}={}){
|
|
return central.transaction(async tx=>{
|
|
const locked=await tx.first('SELECT * FROM political_succession_flows WHERE id=? FOR UPDATE',[flow.id]);if(!locked||locked.state!=='queued')return {replayed:true};
|
|
const term=await tx.first('SELECT * FROM political_office_terms WHERE id=?',[locked.source_term_id]);if(!term||!(term.outcome==='resigned'||term.kind==='naib_chair'&&term.outcome==='ineligible'))throw Error('Vacated office source unavailable');
|
|
const existing=await tx.first('SELECT round_id FROM political_auction_triggers WHERE round_id=?',[flow.id]);if(existing)return {replayed:true};
|
|
// Use the canonical web identity/faction data; never infer eligibility from a
|
|
// displayed name, an honorary title or a client-provided faction.
|
|
const people=await tx.query("SELECT a.id,l.minecraft_uuid,c.faction FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id LEFT JOIN site_character_choices c ON c.user_id=a.id AND c.minecraft_uuid=l.minecraft_uuid WHERE a.password_hash NOT LIKE '!%' AND a.role NOT IN ('official_account','memorial') AND NOT EXISTS(SELECT 1 FROM site_account_policies p WHERE p.user_id=a.id AND p.game_link_exempt=1) AND NOT EXISTS(SELECT 1 FROM cp_account_ranks r WHERE r.user_id=a.id AND r.rank_key IN ('official_account','memorial')) ORDER BY a.id LIMIT 1001");
|
|
if(people.length>1000)throw Error('Vacancy eligibility requires paginated reconciliation');
|
|
const candidates=[];for(const user of people){if(!uuid(user.id)||!uuid(user.minecraft_uuid))continue;if(locked.kind==='naib_chair'&&!await currentNaib(tx,user.id))continue;if(locked.kind==='house'&&user.faction!==locked.faction)continue;if(locked.kind==='clan_delegate'&&!await tx.first('SELECT m.clan_id FROM site_clan_members m JOIN site_clans c ON c.id=m.clan_id WHERE m.user_id=? AND c.active=1',[user.id]))continue;candidates.push(user);}
|
|
if(candidates.length>1000)throw Error('Vacancy eligibility requires paginated reconciliation');
|
|
if(!candidates.length)throw Error('No eligible players available for the vacant office');
|
|
const now=clock();for(const user of candidates)await tx.query('INSERT INTO political_auction_identities(source_id,user_id,player_uuid) VALUES(?,?,?)',[flow.id,user.id,user.minecraft_uuid.toLowerCase()]);
|
|
await tx.query("INSERT INTO political_auction_triggers(round_id,kind,faction,election_start,application_ids,candidate_ids,opens_at,state,created_at) VALUES(?,?,?,?,?,?,?,'queued',?)",[flow.id,locked.kind,locked.faction,term.election_start,'[]',JSON.stringify(candidates.map(p=>p.id)),now,now]);
|
|
await tx.query("UPDATE political_succession_flows SET state='auction_queued' WHERE id=?",[flow.id]);return{replayed:false};
|
|
});
|
|
}
|

Staff