MC/website/node/political-jobs.mjs
2026-11-27 23:43:05 +00:00

46 lines
12 KiB
JavaScript

import {randomUUID,createHash} from 'node:crypto';
import {officeDeedFor,appointPoliticalInTransaction,activePoliticalAppointments} from './political-appointments.mjs';
import {JarvisError,publicJarvisListing} from './jarvis-listings.mjs';
import {PUBLIC_OFFICES} from './public-government.mjs';
export const POLITICAL_JOB_BANK_SCHEMA=[`CREATE TABLE IF NOT EXISTS jarvis_political_jobs(listing_id CHAR(36) PRIMARY KEY,source_term_id CHAR(36) NOT NULL,office_key VARCHAR(32) NOT NULL,expires_at BIGINT NOT NULL,FOREIGN KEY(listing_id) REFERENCES jarvis_listings(id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`];
export const POLITICAL_JOB_SCHEMA=[
`CREATE TABLE IF NOT EXISTS political_job_applications(id CHAR(36) PRIMARY KEY,listing_id CHAR(36) NOT NULL,user_id CHAR(36) NOT NULL,message TEXT NOT NULL,status VARCHAR(16) NOT NULL,deed_id CHAR(36) NULL,listing_closed_at BIGINT NULL,created_at BIGINT NOT NULL,updated_at BIGINT NOT NULL,UNIQUE KEY political_job_applicant(listing_id,user_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
`CREATE TABLE IF NOT EXISTS political_job_outbox(id CHAR(36) PRIMARY KEY,listing_id CHAR(36) NOT NULL,user_id CHAR(36) NOT NULL,decision VARCHAR(16) NOT NULL,state VARCHAR(16) NOT NULL DEFAULT 'queued',created_at BIGINT NOT NULL,UNIQUE KEY political_job_notice(listing_id,user_id,decision)) 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 createPoliticalJobs(central,bank,{clock=Date.now,reserveFee,edition,free=false,promotionChannels=[]}={}){
const current=async(actor,officeKey)=>central.transaction(async tx=>{const term=await officeDeedFor(tx,officeKey,clock());if(term.user_id!==actor.id)throw new JarvisError('Current office owner authority required.',403);return term;});
const rowFor=async id=>bank.first("SELECT l.*,j.source_term_id,j.office_key,j.expires_at FROM jarvis_listings l JOIN jarvis_political_jobs j ON j.listing_id=l.id WHERE l.id=?",[id]);
const live=async row=>{if(!row||row.state!=='open'||Number(row.expires_at)<=clock())return false;const term=await central.prepare("SELECT id FROM political_office_terms WHERE id=? AND outcome='winner' AND starts_at<=? AND expires_at>?").bind(row.source_term_id,clock(),clock()).first();return !!term;};
const projection=row=>({...publicJarvisListing(row),type:'political-job',category:'politics',officeKey:row.office_key,expiresAt:Number(row.expires_at),url:'https://cp.dunerealms.com/political-job?id='+row.id});
return {
async context(actor,officeKey,store=bank){const term=await current(actor,officeKey),members=new Set((await activePoliticalAppointments(central,{clock})).filter(a=>a.office_key===officeKey&&a.appointment_type!=='imperial-steward').map(a=>a.user_id));members.add(actor.id);const quote=free?0:1000+25*members.size;const listings=await store.query('SELECT l.*,j.source_term_id,j.office_key,j.expires_at FROM jarvis_listings l JOIN jarvis_political_jobs j ON j.listing_id=l.id WHERE j.office_key=? AND j.source_term_id=? ORDER BY l.created_at DESC LIMIT 100',[officeKey,term.id]);const ids=listings.map(l=>l.id),applications=ids.length?(await central.prepare('SELECT p.id,p.listing_id,p.message,p.status,p.deed_id,a.username FROM political_job_applications p JOIN site_accounts a ON a.id=p.user_id WHERE p.listing_id IN ('+ids.map(()=>'?').join(',')+') ORDER BY p.created_at DESC').bind(...ids).all()).results:[];return {promotionChannels,officeKey,termId:term.id,expiresAt:Number(term.expires_at),memberCount:members.size,limit:50,priceMinor:quote,listings:listings.map(projection),applications};},
async publish(actor,input){
if(!uuid(input?.requestId)||input.confirmed!==true||typeof input.title!=='string'||!input.title.trim()||input.title.length>100||typeof input.message!=='string'||input.message.length>1000||/[\x00-\x1f\x7f]/.test(input.title)||/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(input.message))throw new JarvisError('Review the vacancy and confirm publication.');
const channels=input.channels||[];if(!Array.isArray(channels)||channels.length>2||new Set(channels).size!==channels.length||channels.some(c=>!promotionChannels.includes(c)))throw new JarvisError('Choose an available promotion channel.');
const fingerprint=createHash('sha256').update(JSON.stringify([actor.id,input.officeKey,input.title.trim(),input.message.trim(),input.expiresAt,input.sourceAccount,input.expectedPriceMinor,[...channels].sort()])).digest('hex');
return bank.transaction(async tx=>{
const previous=await tx.first('SELECT * FROM jarvis_listings WHERE request_id=? FOR UPDATE',[input.requestId]);if(previous){if(previous.actor_id!==actor.id||previous.fingerprint!==fingerprint)throw new JarvisError('Publication reference already used.',409);return {id:previous.id,replayed:true};}
await tx.query('INSERT INTO jarvis_organisation_state(organisation_kind,organisation_id) VALUES(?,?) ON DUPLICATE KEY UPDATE organisation_id=VALUES(organisation_id)',['politics',input.officeKey]);await tx.first('SELECT organisation_id FROM jarvis_organisation_state WHERE organisation_kind=? AND organisation_id=? FOR UPDATE',['politics',input.officeKey]);
const context=await this.context(actor,input.officeKey,tx);if(context.memberCount>=50||context.listings.filter(l=>l.state==='open').length>=50-context.memberCount)throw new JarvisError('No unadvertised office membership place remains.',409);
const term=await current(actor,input.officeKey),now=clock(),expires=Math.min(Number(input.expiresAt),Number(term.expires_at));if(!Number.isSafeInteger(expires)||expires<=now)throw new JarvisError('Choose a future appointment expiry within this office term.');
if(context.priceMinor!==input.expectedPriceMinor)throw new JarvisError('The publication price changed. Refresh the quote.',409);
const id=randomUUID(),origin=await edition(),office=PUBLIC_OFFICES.find(o=>o.key===input.officeKey),title=input.title.trim(),message=input.message.trim();
if(context.priceMinor)await reserveFee(tx,{actor,sourceAccount:input.sourceAccount,amountMinor:context.priceMinor,requestId:input.requestId,listingId:id,title,purpose:'Political vacancy'});
await tx.query("INSERT INTO jarvis_listings(id,request_id,actor_id,organisation_kind,organisation_id,definition_id,title,message,organisation_name,world_name,fee_minor,release_stage,release_version,season_id,rarity,state,revision,fingerprint,created_at,updated_at) VALUES(?,?,?,'politics',?,'political-job',?,?,?,'Political office',?,?,?,?,'common','open',1,?,?,?)",[id,input.requestId,actor.id,input.officeKey,title,message,office.scope,context.priceMinor,origin.stage,origin.version,origin.season,fingerprint,now,now]);
await tx.query('INSERT INTO jarvis_political_jobs(listing_id,source_term_id,office_key,expires_at) VALUES(?,?,?,?)',[id,term.id,input.officeKey,expires]);for(const channel of channels)await tx.query("INSERT INTO jarvis_promotion_jobs(id,listing_id,channel,state,next_attempt,created_at) VALUES(?,?,?,'queued',?,?)",[randomUUID(),id,channel,now,now]);return{id,replayed:false};
});
},
async browse(){const rows=await bank.query("SELECT l.*,j.source_term_id,j.office_key,j.expires_at FROM jarvis_listings l JOIN jarvis_political_jobs j ON j.listing_id=l.id WHERE l.state='open' AND j.expires_at>? ORDER BY l.created_at DESC LIMIT 200",[clock()]);const output=[];for(const row of rows)if(await live(row))output.push(projection(row));return output;},
async apply(actor,input){if(!uuid(input?.listingId)||input.confirmed!==true||typeof input.message!=='string'||input.message.length>2000)throw new JarvisError('Confirm your application.');const row=await rowFor(input.listingId);if(!await live(row))throw new JarvisError('This office vacancy is closed.',409);if(actor.id===row.actor_id)throw new JarvisError('You cannot apply to your own vacancy.');return central.transaction(async tx=>{const person=await tx.first("SELECT a.id FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id WHERE a.id=? AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('official_account','memorial')",[actor.id]);if(!person)throw new JarvisError('An active linked player is required.',403);const previous=await tx.first('SELECT id,status FROM political_job_applications WHERE listing_id=? AND user_id=? FOR UPDATE',[row.id,actor.id]);if(previous)return {id:previous.id,status:previous.status,replayed:true};const id=randomUUID(),now=clock();await tx.query("INSERT INTO political_job_applications(id,listing_id,user_id,message,status,created_at,updated_at) VALUES(?,?,?,?,'pending',?,?)",[id,row.id,actor.id,input.message.trim(),now,now]);return{id,status:'pending',replayed:false};});},
async review(actor,input){
if(!uuid(input?.applicationId)||!['accept','decline'].includes(input.decision)||input.confirmed!==true)throw new JarvisError('Confirm the application decision.');
const stub=await central.prepare('SELECT listing_id FROM political_job_applications WHERE id=?').bind(input.applicationId).first();if(!stub)throw new JarvisError('Application not found.',404);const row=await rowFor(stub.listing_id);if(!row)throw new JarvisError('Vacancy not found.',404);
const result=await central.transaction(async tx=>{const term=await officeDeedFor(tx,row.office_key,clock());const application=await tx.first('SELECT * FROM political_job_applications WHERE id=? FOR UPDATE',[input.applicationId]);if(term.user_id!==actor.id||term.id!==row.source_term_id)throw new JarvisError('The current issuing office deed is required.',403);const status=input.decision==='accept'?'accepted':'declined';if(application.status!=='pending'){if(application.status!==status)throw new JarvisError('Application already decided.',409);return{listingId:row.id,status,replayed:true,deedId:application.deed_id};}let deed=null;
if(status==='accepted'){if(row.state!=='open'||Number(row.expires_at)<=clock())throw new JarvisError('Vacancy is no longer open.',409);const filled=await tx.first("SELECT id FROM political_job_applications WHERE listing_id=? AND status='accepted'",[row.id]);if(filled)throw new JarvisError('This vacancy has been filled.',409);deed=await appointPoliticalInTransaction(tx,actor,{officeKey:row.office_key,userId:application.user_id,requestId:application.id,type:'job',title:row.title,expiresAt:Number(row.expires_at)},{clock});}
await tx.query('UPDATE political_job_applications SET status=?,deed_id=?,updated_at=? WHERE id=?',[status,deed?.id||null,clock(),application.id]);await tx.query('INSERT INTO political_job_outbox(id,listing_id,user_id,decision,created_at) VALUES(?,?,?,?,?)',[randomUUID(),row.id,application.user_id,status,clock()]);if(status==='accepted'){const others=await tx.query("SELECT id,user_id FROM political_job_applications WHERE listing_id=? AND status='pending' FOR UPDATE",[row.id]);for(const other of others){await tx.query("UPDATE political_job_applications SET status='filled',updated_at=? WHERE id=?",[clock(),other.id]);await tx.query('INSERT INTO political_job_outbox(id,listing_id,user_id,decision,created_at) VALUES(?,?,?,?,?)',[randomUUID(),row.id,other.user_id,'filled',clock()]);}}return{listingId:row.id,status,deedId:deed?.id||null,replayed:false};});
if(result.status==='accepted'){await bank.query("UPDATE jarvis_listings SET state='filled',revision=revision+1,updated_at=? WHERE id=? AND state='open'",[clock(),result.listingId]);await central.query("UPDATE political_job_applications SET listing_closed_at=? WHERE listing_id=? AND status='accepted' AND listing_closed_at IS NULL",[clock(),result.listingId]);}return result;
},
async reconcile(){const {results}=await central.prepare("SELECT DISTINCT listing_id FROM political_job_applications WHERE status='accepted' AND listing_closed_at IS NULL ORDER BY listing_id LIMIT 500").all();for(const row of results){await bank.query("UPDATE jarvis_listings SET state='filled',revision=revision+1,updated_at=? WHERE id=? AND state='open'",[clock(),row.listing_id]);await central.query("UPDATE political_job_applications SET listing_closed_at=? WHERE listing_id=? AND status='accepted' AND listing_closed_at IS NULL",[clock(),row.listing_id]);}return{checked:results.length};}
};
}