web/website/node/political-appointments.mjs

46 lines
8.1 KiB
JavaScript

import {randomUUID} from 'node:crypto';import {PUBLIC_OFFICES} from './public-government.mjs';import {JarvisError} from './jarvis-listings.mjs';
import {currentNaib} from './naib-membership.mjs';
export const POLITICAL_APPOINTMENT_SCHEMA=[
`CREATE TABLE IF NOT EXISTS political_appointment_deeds(id CHAR(36) PRIMARY KEY,office_key VARCHAR(32) NOT NULL,source_term_id CHAR(36) NOT NULL,user_id CHAR(36) NOT NULL,role_key VARCHAR(64) NOT NULL,title VARCHAR(100) NOT NULL,appointment_type VARCHAR(24) NOT NULL,target_kind VARCHAR(16) NULL,target_id VARCHAR(36) NULL,starts_at BIGINT NOT NULL,expires_at BIGINT NOT NULL,revoked_at BIGINT NULL,issuer_id CHAR(36) NOT NULL,request_id CHAR(36) NOT NULL UNIQUE) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
`CREATE TABLE IF NOT EXISTS political_appointment_events(id CHAR(36) PRIMARY KEY,deed_id CHAR(36) NOT NULL,actor_id CHAR(36) NOT NULL,event_type VARCHAR(24) 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 const LIAISON_TYPES=Object.freeze(['house-liaison','clan-liaison','company-liaison','bene-liaison','guild-liaison','landsraad-liaison']);
export async function officeDeedFor(tx,officeKey,now){const office=PUBLIC_OFFICES.find(o=>o.key===officeKey);if(!office)throw new JarvisError('Political House not found.',404);const terms=await tx.query("SELECT * FROM political_office_terms WHERE kind=? AND faction=? AND office=? AND outcome='winner' AND starts_at<=? AND expires_at>? FOR UPDATE",[office.kind,office.faction,office.office,now,now]);if(terms.length!==1)throw new JarvisError('An unambiguous active office deed is required.',409);if(office.kind==='naib_chair'&&!await currentNaib(tx,terms[0].user_id,{lock:true}))throw new JarvisError('Council chair authority requires a current sietch deed.',403);return terms[0];}
// Membership is a projection of this deed joined to its still-active source term.
// No personal clan/company membership or global rank is modified.
export async function appointPoliticalInTransaction(tx,actor,input,{clock=Date.now}={}){
if(!uuid(actor?.id)||!uuid(input?.userId)||!uuid(input?.requestId)||typeof input.title!=='string'||!input.title.trim()||input.title.length>100||/[\x00-\x1f\x7f]/.test(input.title)||!['job',...LIAISON_TYPES].includes(input.type)||!Number.isSafeInteger(input.expiresAt))throw new JarvisError('Review the appointment and its term.',400);
const now=clock(),term=await officeDeedFor(tx,input.officeKey,now);
if(term.user_id!==actor.id)throw new JarvisError('Current office owner authority required.',403);
const expires=Math.min(input.expiresAt,Number(term.expires_at));if(expires<=now)throw new JarvisError('Choose a future expiry.',400);
if(input.type!=='job'&&input.officeKey!=='emperor')throw new JarvisError('An Imperial decree is required to place a liaison.',403);
if(input.type!=='job'&&input.targetKind==='politics'&&input.targetId==='arrakis')throw new JarvisError('The Council of Naibs is independent of Imperial appointments.',403);
const person=await tx.first("SELECT id FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[input.userId]);if(!person)throw new JarvisError('Active recipient required.',409);
const prior=await tx.first('SELECT * FROM political_appointment_deeds WHERE request_id=?',[input.requestId]);if(prior){if(prior.source_term_id!==term.id||prior.user_id!==input.userId||prior.title!==input.title.trim()||prior.appointment_type!==input.type||Number(prior.expires_at)!==expires||prior.target_kind!==(input.targetKind||null)||prior.target_id!==(input.targetId||null))throw new JarvisError('Appointment reference already used.',409);return {id:prior.id,replayed:true};}
const liaison=input.type!=='job';let officeKey=input.officeKey;
const requiredTarget={'house-liaison':'politics','clan-liaison':'clan','company-liaison':'company','bene-liaison':'politics','guild-liaison':'politics','landsraad-liaison':'politics'}[input.type];if(liaison&&input.targetKind!==requiredTarget)throw new JarvisError('Liaison type and target do not match.',400);if(input.type==='bene-liaison'&&input.targetId!=='veiled_concord'||input.type==='guild-liaison'&&input.targetId!=='spacing_guild')throw new JarvisError('Liaison institution does not match.',400);
if(liaison){
if(!['politics','clan','company'].includes(input.targetKind)||typeof input.targetId!=='string'||!/^[a-z0-9_-]{1,36}$/i.test(input.targetId))throw new JarvisError('Choose the liaison target.',400);
if(input.targetKind==='politics'){const office=PUBLIC_OFFICES.find(o=>o.key===input.targetId);if(!office)throw new JarvisError('Political House target unavailable.',404);officeKey=office.key;}
else{const table=input.targetKind==='clan'?'site_clans':'corrino_companies',target=await tx.first('SELECT id FROM '+table+' WHERE id=?',[input.targetId]);if(!target)throw new JarvisError('Liaison target unavailable.',404);}
}
await tx.query('INSERT INTO political_office_locks(scope) VALUES(?) ON DUPLICATE KEY UPDATE scope=VALUES(scope)',['membership:'+officeKey]);await tx.first('SELECT scope FROM political_office_locks WHERE scope=? FOR UPDATE',['membership:'+officeKey]);
const active=" FROM political_appointment_deeds d JOIN political_office_terms t ON t.id=d.source_term_id WHERE d.office_key=? AND d.revoked_at IS NULL AND d.starts_at<=? AND d.expires_at>? AND t.outcome='winner' AND t.starts_at<=? AND t.expires_at>?",args=[officeKey,now,now,now,now];
const membershipCount=await tx.first('SELECT COUNT(DISTINCT d.user_id) n'+active,args),existingMember=await tx.first('SELECT d.id'+active+' AND d.user_id=?',[...args,input.userId]);if(!existingMember&&Number(membershipCount.n)>=49)throw new JarvisError('The political House has no available member places.',409);
const id=randomUUID(),roleKey=liaison?'observer':'custom-role';await tx.query('INSERT INTO political_appointment_deeds(id,office_key,source_term_id,user_id,role_key,title,appointment_type,target_kind,target_id,starts_at,expires_at,issuer_id,request_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)',[id,officeKey,term.id,input.userId,roleKey,input.title.trim(),input.type,input.targetKind||null,input.targetId||null,now,expires,actor.id,input.requestId]);
await tx.query('INSERT INTO political_appointment_events(id,deed_id,actor_id,event_type,created_at) VALUES(?,?,?,?,?)',[randomUUID(),id,actor.id,'appointed',now]);return{id,replayed:false};
}
export function createPoliticalAppointments(central,{clock=Date.now}={}){
return Object.freeze({
async appoint(actor,input){return central.transaction(tx=>appointPoliticalInTransaction(tx,actor,input,{clock}));},
async revoke(actor,{deedId}){
return central.transaction(async tx=>{const deed=await tx.first('SELECT * FROM political_appointment_deeds WHERE id=? FOR UPDATE',[deedId]);if(!deed)throw new JarvisError('Appointment not found.',404);const source=await tx.first('SELECT * FROM political_office_terms WHERE id=? FOR UPDATE',[deed.source_term_id]);if(!source||source.user_id!==actor.id||source.outcome!=='winner'||Number(source.expires_at)<=clock())throw new JarvisError('Current appointing office authority required.',403);if(deed.revoked_at)return{replayed:true};await tx.query('UPDATE political_appointment_deeds SET revoked_at=? WHERE id=?',[clock(),deedId]);await tx.query('INSERT INTO political_appointment_events(id,deed_id,actor_id,event_type,created_at) VALUES(?,?,?,?,?)',[randomUUID(),deedId,actor.id,'revoked',clock()]);return{replayed:false};});
}
});
}
export async function activePoliticalAppointments(central,{userId=null,clock=Date.now}={}){
const now=clock(),args=[now,now,now,now];if(userId)args.push(userId);
return central.query("SELECT d.id,d.office_key,d.user_id,d.role_key,d.title,d.appointment_type,d.target_kind,d.target_id,d.starts_at,d.expires_at,a.username,a.display_name FROM political_appointment_deeds d JOIN political_office_terms t ON t.id=d.source_term_id JOIN site_accounts a ON a.id=d.user_id WHERE d.revoked_at IS NULL AND d.starts_at<=? AND d.expires_at>? AND t.outcome='winner' AND t.starts_at<=? AND t.expires_at>? AND a.password_hash NOT LIKE '!%'"+(userId?' AND d.user_id=?':'')+' ORDER BY d.office_key,d.title,d.id',args);
}