forked from unimatrix/web
Merge pull request 'Alpha 1.0.1.2: connect elections and the Council of Naibs' (#405) from feature/elections-naib-council-1012-20261118 into main
This commit is contained in:
commit
73e48f4e69
71 changed files with 822 additions and 135 deletions
|
|
@ -3,6 +3,7 @@ import {accessFor} from '../node/permissions.mjs';
|
|||
import {createPoliticsPreview} from './politics-preview.mjs';
|
||||
import {submitApplication,ownApplications} from './election-applications.mjs';
|
||||
import {validateCandidature} from './public/election-rules.mjs';
|
||||
import {currentNaib} from '../node/naib-membership.mjs';
|
||||
const reply=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}});
|
||||
// Authenticated own-application route. Office grants and ballot writes are separate.
|
||||
export function createElectionApplications(db,settings={},deps={}){
|
||||
|
|
@ -33,7 +34,8 @@ export function createElectionApplications(db,settings={},deps={}){
|
|||
if(!await permitted(current))return reply({message:'Access changed.'},403);
|
||||
if((await linked(current))?.toLowerCase()!==player.toLowerCase())return reply({message:'Linked account changed. Refresh.'},409);
|
||||
const clan=input.kind==='clan_delegate'?await db.prepare("SELECT c.id FROM site_clans c JOIN site_clan_members m ON m.clan_id=c.id JOIN site_game_links l ON l.user_id=m.user_id AND l.minecraft_uuid=m.minecraft_uuid WHERE m.user_id=? AND c.active=1").bind(current.id).first():null;
|
||||
const context={clanId:clan?.id,linked:verified.linked===true,playerUuid:player,faction:verified.factionStatus==='verified'?verified.faction:null};
|
||||
const naib=input.kind==='naib_chair'?await currentNaib(db,current.id):null;
|
||||
const context={clanId:naib?.clan_id||clan?.id,naib:!!naib,linked:verified.linked===true,playerUuid:player,faction:verified.factionStatus==='verified'?verified.faction:null};
|
||||
try{validateCandidature(input,context,clock());}catch(error){return reply({message:error.message},400);}
|
||||
try{
|
||||
const result=await save(db,{actor:current,context,input,now:clock(),clock});
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import {randomUUID} from 'node:crypto';
|
||||
import {validateCandidature} from './public/election-rules.mjs';
|
||||
import {currentNaib} from '../node/naib-membership.mjs';
|
||||
|
||||
export const applicationSchema = [
|
||||
`CREATE TABLE IF NOT EXISTS political_application_counters (scope VARCHAR(24) PRIMARY KEY, value INTEGER NOT NULL) ENGINE=InnoDB`,
|
||||
|
|
@ -36,6 +37,7 @@ export async function submitApplication(db,{actor,context,input,now=Date.now(),c
|
|||
const counters=await query('SELECT value FROM political_application_counters WHERE scope=? FOR UPDATE',[scope]);
|
||||
const links=await query('SELECT minecraft_uuid FROM site_game_links WHERE user_id=? FOR UPDATE',[actor.id]);
|
||||
if(links[0]?.minecraft_uuid?.toLowerCase()!==player)throw Error('Linked account changed');
|
||||
if(candidate.kind==='naib_chair'&&!await currentNaib({query},actor.id,{lock:true}))throw Error('Current Arrakduin sietch ownership is required');
|
||||
if(candidate.kind==='clan_delegate'){const [member]=await query("SELECT c.id FROM site_clans c JOIN site_clan_members m ON m.clan_id=c.id AND m.minecraft_uuid=? WHERE m.user_id=? AND c.id=? AND c.active=1 FOR SHARE",[player,actor.id,context.clanId]);if(!member)throw Error('Active linked clan membership required');}
|
||||
const existing=await query('SELECT id,public_id,user_id,motivation,faction FROM political_applications WHERE player_uuid=? AND kind=? AND election_start=? FOR UPDATE',[player,candidate.kind,start]);
|
||||
if(existing.length){
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import {randomUUID} from 'node:crypto';
|
||||
import {ELECTION_RULES,electionWindow,electionScope,voteCapacity} from './public/election-rules.mjs';
|
||||
import {currentNaib} from '../node/naib-membership.mjs';
|
||||
const uuid=/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i;
|
||||
export function validateBallot(input,context,now=Date.now(),roundWindow=null){
|
||||
if(!input||!uuid.test(input.requestId||'')||!Object.hasOwn(ELECTION_RULES,input.kind)||input.confirmed!==true)throw Error('Confirm your definitive vote');
|
||||
|
|
@ -28,6 +29,7 @@ export async function castBallot(db,{actor,context,input,now=Date.now(),clock=Da
|
|||
const player=context.playerUuid.toLowerCase();
|
||||
const [result]=await db.batch([{async run(connection){
|
||||
const query=async(sql,args=[])=>(await connection.execute(sql,args))[0];
|
||||
if(input.kind==='naib_chair'){const seat=await currentNaib({query},actor.id,{lock:true});if(!seat||seat.clan_id!==context.clanId)throw Error('Current Arrakduin sietch ownership is required');}
|
||||
const [round]=await query('SELECT * FROM political_election_rounds WHERE id=? FOR UPDATE',[input.roundId]);
|
||||
if(!round||round.kind!==input.kind||Number(round.election_start)!==Date.parse(input.start)||round.faction!==electionScope(input.kind,context)||round.status!=='open')throw Error('Election round is not open');
|
||||
const vote=validateBallot(input,context,clock(),round),payload=JSON.stringify({kind:vote.kind,start:vote.start,roundId:round.id,allocations:vote.allocations});
|
||||
|
|
@ -43,11 +45,12 @@ export async function castBallot(db,{actor,context,input,now=Date.now(),clock=Da
|
|||
const available=Math.min(Number(voter.capacity),vote.capacity)-Number(voter.spent);if(vote.total>available)throw Error('No sufficient votes remain');
|
||||
for(const allocation of vote.allocations){
|
||||
const [entry]=await query('SELECT application_id FROM political_round_candidates WHERE round_id=? AND application_id=?',[round.id,allocation.applicationId]);if(!entry)throw Error('Candidate is not in this round');
|
||||
const [candidate]=await query('SELECT kind,faction,election_start,status FROM political_applications WHERE id=? FOR UPDATE',[allocation.applicationId]);
|
||||
const [candidate]=await query('SELECT kind,faction,election_start,status,user_id FROM political_applications WHERE id=? FOR UPDATE',[allocation.applicationId]);
|
||||
if(!candidate||candidate.kind!==vote.kind||Number(candidate.election_start)!==vote.start||candidate.faction!==vote.faction||candidate.status!=='submitted')throw Error('Candidate is not eligible for this election');
|
||||
if(vote.kind==='naib_chair'&&!await currentNaib({query},candidate.user_id,{lock:true}))throw Error('Candidate is no longer a Naib');
|
||||
}
|
||||
const id=makeId();
|
||||
if(vote.kind==='clan_delegate'){
|
||||
if(['clan_delegate','naib_chair'].includes(vote.kind)){
|
||||
const [clan]=await query("SELECT c.id FROM site_clans c JOIN site_clan_members m ON m.clan_id=c.id AND m.user_id=c.owner_id AND m.clan_role='owner' JOIN site_game_links l ON l.user_id=m.user_id AND l.minecraft_uuid=m.minecraft_uuid WHERE c.id=? AND c.owner_id=? AND c.active=1 FOR UPDATE",[context.clanId,actor.id]);
|
||||
if(!clan)throw Error('Current linked clan leadership is required');
|
||||
await query('INSERT INTO political_clan_votes(round_id,clan_id,ballot_id) VALUES(?,?,?)',[round.id,clan.id,id]);
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import {randomUUID} from 'node:crypto';
|
||||
import {ELECTION_RULES,electionWindow} from './public/election-rules.mjs';
|
||||
import {currentNaib} from '../node/naib-membership.mjs';
|
||||
export const officeLedgerSchema=[
|
||||
`CREATE TABLE IF NOT EXISTS political_office_terms(id CHAR(36) PRIMARY KEY,kind VARCHAR(16) NOT NULL,faction VARCHAR(32) NOT NULL,election_start BIGINT NOT NULL,round_id CHAR(36) NOT NULL UNIQUE,application_id CHAR(36),user_id CHAR(36),player_uuid CHAR(36),office VARCHAR(32) NOT NULL,starts_at BIGINT NOT NULL,expires_at BIGINT NOT NULL,outcome VARCHAR(16) NOT NULL,streak INTEGER NOT NULL,UNIQUE KEY office_cycle(kind,faction,election_start)) ENGINE=InnoDB`,
|
||||
`CREATE TABLE IF NOT EXISTS political_office_locks(scope VARCHAR(64) PRIMARY KEY) ENGINE=InnoDB`,
|
||||
|
|
@ -15,7 +16,7 @@ export function planOfficeTerm(round,application,previous,now){
|
|||
if(!Number.isFinite(closed)||closed<start+10800000||now<closed)throw Error('Election has not closed');
|
||||
if(!/^[a-z_]{1,32}$/.test(round.faction)||round.kind==='imperial'&&round.faction!=='imperium')throw Error('Invalid office scope');
|
||||
if(previous&&Number(previous.election_start)>=start)throw Error('Process office results in chronological order');
|
||||
const office=round.kind==='guild'?'guild_leader':round.kind==='clan_delegate'?'clan_delegate':round.kind==='imperial'?'emperor':round.faction==='veiled_concord'?'reverent_mother':'house_leader';
|
||||
const office=round.kind==='naib_chair'?'naib_chair':round.kind==='guild'?'guild_leader':round.kind==='clan_delegate'?'clan_delegate':round.kind==='imperial'?'emperor':round.faction==='veiled_concord'?'reverent_mother':'house_leader';
|
||||
let userId=null,playerUuid=null,streak=0;
|
||||
if(round.status==='winner'){
|
||||
if(!application||application.id!==round.winner_id||application.kind!==round.kind||application.faction!==round.faction||Number(application.election_start)!==start||!uuid.test(application.user_id)||!uuid.test(application.player_uuid))throw Error('Winner identity does not match election');
|
||||
|
|
@ -23,7 +24,7 @@ export function planOfficeTerm(round,application,previous,now){
|
|||
streak=previous&&Number(previous.election_start)===start-period&&previous.player_uuid===playerUuid&&previous.outcome==='winner'?Number(previous.streak)+1:1;
|
||||
}
|
||||
const title=office==='guild_leader'?'Guild Elder':office==='clan_delegate'?'Elder of the Clans':office==='emperor'?'Emperor Emeritus of the Three Crowns':office==='reverent_mother'?'Grand Matriarch of the Veil':'High Lord of the Three Banners';
|
||||
return {kind:round.kind,faction:round.faction,electionStart:start,office,userId,playerUuid,applicationId:round.status==='winner'?application.id:null,startsAt:closed,expiresAt:start+period,outcome:round.status,streak,honour:streak>=3?title:null};
|
||||
return {kind:round.kind,faction:round.faction,electionStart:start,office,userId,playerUuid,applicationId:round.status==='winner'?application.id:null,startsAt:closed,expiresAt:start+period,outcome:round.status,streak,honour:streak>=3&&office!=='naib_chair'?title:null};
|
||||
}
|
||||
// This ledger records election facts only. It never edits account roles, game offices or paid/earned ranks.
|
||||
export async function reconcileOfficeResult(db,{roundId,now=Date.now(),makeId=randomUUID}){
|
||||
|
|
@ -38,6 +39,7 @@ export async function reconcileOfficeResult(db,{roundId,now=Date.now(),makeId=ra
|
|||
if(existing){if(existing.round_id!==round.id)throw Error('Conflicting final result');return {id:existing.id,replayed:true};}
|
||||
const [previous]=await q('SELECT * FROM political_office_terms WHERE kind=? AND faction=? ORDER BY election_start DESC LIMIT 1 FOR UPDATE',[round.kind,round.faction]);
|
||||
const [application]=round.winner_id?await q('SELECT * FROM political_applications WHERE id=?',[round.winner_id]):[];
|
||||
if(round.kind==='naib_chair'&&application&&!await currentNaib({query:q},application.user_id,{lock:true}))throw Error('Chair winner is no longer a Naib');
|
||||
const term=planOfficeTerm(round,application,previous,now),id=makeId();
|
||||
await q('INSERT INTO political_office_terms(id,kind,faction,election_start,round_id,application_id,user_id,player_uuid,office,starts_at,expires_at,outcome,streak) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)',[id,term.kind,term.faction,term.electionStart,round.id,term.applicationId,term.userId,term.playerUuid,term.office,term.startsAt,term.expiresAt,term.outcome,term.streak]);
|
||||
await q('INSERT INTO political_office_events(id,term_id,event,payload,created_at) VALUES(?,?,?,?,?)',[makeId(),id,'result_recorded',JSON.stringify(term),now]);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import {randomUUID} from 'node:crypto';
|
||||
import {electionWindow} from './public/election-rules.mjs';
|
||||
import {planRoundResult} from './election-ballots.mjs';
|
||||
import {currentNaib} from '../node/naib-membership.mjs';
|
||||
export const roundSchema=[
|
||||
`CREATE TABLE IF NOT EXISTS political_auction_triggers(round_id CHAR(36) PRIMARY KEY,kind VARCHAR(16) NOT NULL,faction VARCHAR(32) NOT NULL,election_start BIGINT NOT NULL,application_ids TEXT NOT NULL,candidate_ids TEXT NOT NULL,opens_at BIGINT NOT NULL,state VARCHAR(16) NOT NULL,auction_id CHAR(36) NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB`,
|
||||
`CREATE TABLE IF NOT EXISTS political_election_rounds(id CHAR(36) PRIMARY KEY,kind VARCHAR(16) NOT NULL,faction VARCHAR(32) NOT NULL,election_start BIGINT NOT NULL,round_number INTEGER NOT NULL,opens_at BIGINT NOT NULL,closes_at BIGINT NOT NULL,status VARCHAR(32) NOT NULL,winner_id CHAR(36),UNIQUE KEY election_round(kind,faction,election_start,round_number)) ENGINE=InnoDB`,
|
||||
|
|
@ -33,6 +34,7 @@ export async function finalizeRound(db,{roundId,now=Date.now(),makeId=randomUUID
|
|||
if(round.status!=='open')return{status:round.status,winner:round.winner_id,replayed:true};
|
||||
if(now<Number(round.closes_at))throw Error('Voting round has not closed');
|
||||
const totals=await query('SELECT c.application_id AS id,COALESCE(SUM(a.votes),0) AS votes FROM political_round_candidates c LEFT JOIN political_ballots b ON b.round_id=c.round_id LEFT JOIN political_ballot_allocations a ON a.ballot_id=b.id AND a.application_id=c.application_id WHERE c.round_id=? GROUP BY c.application_id',[round.id]);
|
||||
if(round.kind==='naib_chair')for(const row of totals){const [application]=await query('SELECT user_id FROM political_applications WHERE id=?',[row.id]);if(!application||!await currentNaib({query},application.user_id,{lock:true}))row.votes=0;}
|
||||
const outcome=planRoundResult({kind:round.kind,start:new Date(Number(round.election_start)).toISOString(),round:Number(round.round_number),candidates:totals.map(row=>({...row,votes:Number(row.votes)}))},now);
|
||||
let nextRoundId=null;
|
||||
if(outcome.auction){
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import {createPoliticsPreview} from './politics-preview.mjs';
|
|||
import {ELECTION_RULES,electionScope,voteCapacity} from './public/election-rules.mjs';
|
||||
import {openFirstRound,finalizeRound} from './election-rounds.mjs';
|
||||
import {castBallot} from './election-ballots.mjs';
|
||||
import {currentNaib} from '../node/naib-membership.mjs';
|
||||
const houses=['atreides','harkonnen','corrino','ordos','fremen'];
|
||||
const reply=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}});
|
||||
export function cycleStart(kind,now){const rule=ELECTION_RULES[kind];if(!rule)throw Error('Unknown election');const first=Date.parse(rule.first),period=rule.weeks*604800000;return first+Math.max(0,Math.floor((now-first)/period))*period;}
|
||||
|
|
@ -19,7 +20,7 @@ export async function advanceElection(db,kind,faction,now=Date.now()){
|
|||
}
|
||||
export function startElectionClock(db,{clock=Date.now,onError=()=>console.error('Election clock failed')}={}){
|
||||
let busy=false,stopped=false;
|
||||
const tick=async()=>{if(busy||stopped)return;busy=true;try{const now=clock();for(const faction of houses)await advanceElection(db,'house',faction,now);for(const kind of ['imperial','bene','guild','clan_delegate'])await advanceElection(db,kind,electionScope(kind),now);}catch(error){onError(error);}finally{busy=false;}};
|
||||
const tick=async()=>{if(busy||stopped)return;busy=true;try{const now=clock();for(const faction of houses)await advanceElection(db,'house',faction,now);for(const kind of ['imperial','bene','guild','clan_delegate','naib_chair'])await advanceElection(db,kind,electionScope(kind),now);}catch(error){onError(error);}finally{busy=false;}};
|
||||
const timer=setInterval(tick,15000);timer.unref?.();void tick();return()=>{stopped=true;clearInterval(timer);};
|
||||
}
|
||||
export function createElectionVoting(db,settings={},deps={}){
|
||||
|
|
@ -42,7 +43,8 @@ export function createElectionVoting(db,settings={},deps={}){
|
|||
if(!verified.linked||(['house','imperial'].includes(kind)&&(verified.factionStatus!=='verified'||!houses.includes(verified.faction))))return reply({message:'Verified faction membership required.'},403);
|
||||
if(kind==='imperial'&&verified.officeStatus!=='verified')return reply({message:'Current office could not be verified. No votes have been spent.'},503);
|
||||
const clan=kind==='clan_delegate'?await db.prepare("SELECT c.id,m.clan_role,c.owner_id FROM site_clans c JOIN site_clan_members m ON m.clan_id=c.id JOIN site_game_links l ON l.user_id=m.user_id AND l.minecraft_uuid=m.minecraft_uuid WHERE m.user_id=? AND c.active=1").bind(current.id).first():null;
|
||||
const context={clanId:clan?.id,clanLeader:clan?.owner_id===current.id&&clan?.clan_role==='owner',linked:true,playerUuid:player,faction:verified.faction,houseLeader:verified.houseLeader===true},faction=electionScope(kind,context),now=clock(),start=cycleStart(kind,now);
|
||||
const naib=kind==='naib_chair'?await currentNaib(db,current.id):null;
|
||||
const context={clanId:naib?.clan_id||clan?.id,naib:!!naib,clanLeader:clan?.owner_id===current.id&&clan?.clan_role==='owner',linked:true,playerUuid:player,faction:kind==='naib_chair'?'arrakis':verified.faction,houseLeader:verified.houseLeader===true},faction=electionScope(kind,context),now=clock(),start=cycleStart(kind,now);
|
||||
const round=await advance(db,kind,faction,now);
|
||||
if(request.method==='POST'){
|
||||
if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);
|
||||
|
|
@ -56,7 +58,7 @@ export function createElectionVoting(db,settings={},deps={}){
|
|||
else {const result=await db.prepare("SELECT a.id,a.public_id,a.motivation,u.username,0 AS votes FROM political_applications a JOIN site_accounts u ON u.id=a.user_id WHERE a.kind=? AND a.faction=? AND a.election_start=? AND a.status='submitted' ORDER BY u.username").bind(kind,faction,start).all();candidates=result.results;}
|
||||
const voter=round?await db.prepare('SELECT capacity,spent FROM political_voters WHERE player_uuid=? AND round_id=?').bind(player.toLowerCase(),round.id).first():null;
|
||||
const capacity=voteCapacity(kind,context),remaining=voter?Math.max(0,Math.min(capacity,Number(voter.capacity))-Number(voter.spent)):capacity;
|
||||
const clanVote=kind==='clan_delegate'&&round&&clan?await db.prepare('SELECT ballot_id FROM political_clan_votes WHERE round_id=? AND clan_id=?').bind(round.id,clan.id).first():null;
|
||||
const clanVote=['clan_delegate','naib_chair'].includes(kind)&&round&&context.clanId?await db.prepare('SELECT ballot_id FROM political_clan_votes WHERE round_id=? AND clan_id=?').bind(round.id,context.clanId).first():null;
|
||||
return reply({kind,faction,start:new Date(start).toISOString(),round:round?{id:round.id,number:Number(round.round_number),status:round.status,opensAt:Number(round.opens_at),closesAt:Number(round.closes_at),winnerId:round.winner_id}:null,remaining:clanVote?0:remaining,candidates:candidates.map(c=>({...c,votes:Number(c.votes)}))});
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,8 +6,8 @@ const status=clan=>clan.institution_key?'Protected institution':isRoyalHouse(cla
|
|||
function view(clan,kind='clan'){const a=el('a','View '+(kind==='company'?'company':kind==='politics'?'House':'clan')+' →','clan-register-view');a.href=clanPublicUrl(clan,kind);a.target='_top';a.setAttribute('aria-label','View '+clan.name+' public profile');return a;}
|
||||
function logo(clan,size){const img=el('img');img.src=clan.emblem;img.alt='';img.width=img.height=size;img.loading='lazy';return img;}
|
||||
export function renderClanRegister(host,rows,{kind='clan'}={}){const noun=kind==='company'?'Company':kind==='politics'?'Political House':'Clan';
|
||||
host.replaceChildren();const royal=el('section',undefined,'clan-royal-directory'),grid=el('div',undefined,'clan-grid');royal.append(el('h3',kind==='politics'?'Protected Political Houses':kind==='company'?'Royal Companies':'Royal Houses'));const houses=rows.filter(r=>kind==='politics'||isRoyalHouse(r));
|
||||
for(const clan of houses){const card=el('article',undefined,'clan-card clan-recruit-card'),portrait=el('div',undefined,'clan-directory-portrait'),crest=logo(clan,160);crest.className='clan-directory-crest';portrait.append(crest,el('span',kind==='politics'?'PROTECTED HOUSE':'ROYAL HOUSE'));const body=el('div',undefined,'clan-directory-body'),tag=el('small','['+clan.tag+']','clan-directory-tag'),footer=el('div',undefined,'clan-directory-footer');footer.append(el('span',Number(clan.member_count)+' members'),view(clan,kind));body.append(tag,el('h3',clan.name),el('p',clan.realm||'Independent House'),el('p',clan.description||'This House has not published an introduction yet.','clan-directory-bio'),footer);card.append(portrait,body);grid.append(card);}if(!houses.length)grid.append(el('p','No Royal Houses match the current filters.','clan-register-empty'));royal.append(grid);if(kind!=='company')host.append(royal);
|
||||
host.replaceChildren();const royal=el('section',undefined,'clan-royal-directory'),grid=el('div',undefined,'clan-grid');royal.append(el('h3',kind==='politics'?'Protected Political Houses':kind==='company'?'Major Companies':'Royal Houses'));const houses=rows.filter(r=>kind==='politics'||isRoyalHouse(r));
|
||||
for(const clan of houses){const card=el('article',undefined,'clan-card clan-recruit-card'),portrait=el('div',undefined,'clan-directory-portrait'),crest=logo(clan,160);crest.className='clan-directory-crest';portrait.append(crest,el('span',kind==='politics'?'PROTECTED HOUSE':kind==='company'?'MAJOR COMPANY':'ROYAL HOUSE'));const body=el('div',undefined,'clan-directory-body'),tag=el('small','['+clan.tag+']','clan-directory-tag'),footer=el('div',undefined,'clan-directory-footer');footer.append(el('span',Number(clan.member_count)+' members'),view(clan,kind));body.append(tag,el('h3',clan.name),el('p',clan.realm||(kind==='company'?'Independent Company':'Independent House')),el('p',clan.description||(kind==='company'?'This company has not published an introduction yet.':'This House has not published an introduction yet.'),'clan-directory-bio'),footer);card.append(portrait,body);grid.append(card);}if(!houses.length)grid.append(el('p',kind==='company'?'No Major Companies match the current filters.':'No Royal Houses match the current filters.','clan-register-empty'));royal.append(grid);host.append(royal);
|
||||
const register=el('section',undefined,'clan-public-register');register.append(el('h3',noun+' Registry'),el('p','Registered organisations · public identity, leadership and membership.'));const wrap=el('div',undefined,'clan-register-scroll'),table=el('table'),head=el('thead'),tr=el('tr');for(const name of [noun,kind==='company'?'Chief Executive':kind==='politics'?'Officeholder':'Owner','Members','Status',kind==='clan'?'Homeworld':'Affiliation',kind==='politics'?'Term begins':'Established','View '+noun.toLowerCase()]){const th=el('th',name);th.scope='col';tr.append(th);}head.append(tr);const body=el('tbody');
|
||||
for(const clan of rows){const row=el('tr'),identity=el('td'),name=el('div',undefined,'clan-register-identity'),copy=el('div'),link=el('a',clan.name);link.href=clanPublicUrl(clan,kind);link.target='_top';copy.append(link,el('small','['+clan.tag+']'));name.append(logo(clan,36),copy);identity.append(name);const owner=el('td');if(clan.owner_username){const a=el('a',clan.owner_name||clan.owner_username);a.href='https://www.dunerealms.com/people/'+encodeURIComponent(clan.owner_username);a.target='_top';owner.append(a);}else owner.append(el('span','Not listed'));const action=el('td');action.append(view(clan,kind));row.append(identity,owner,el('td',clan.member_count==null?'Not published':String(Number(clan.member_count)||0)),el('td',kind==='clan'?status(clan):(clan.standing||'Protected House')),el('td',clan.homeworldName||clan.realm||'Not selected'),el('td',(clan.created_at||clan.term?.startsAt)?formatDuneDate(Number(clan.created_at||clan.term.startsAt)):'—'),action);body.append(row);}if(!rows.length){const row=el('tr'),cell=el('td','No organisations match the current filters.');cell.colSpan=7;row.append(cell);body.append(row);}table.append(head,body);wrap.append(table);register.append(wrap);host.append(register);
|
||||
for(const clan of rows){const row=el('tr'),identity=el('td'),name=el('div',undefined,'clan-register-identity'),copy=el('div'),link=el('a',clan.name);link.href=clanPublicUrl(clan,kind);link.target='_top';copy.append(link,el('small','['+clan.tag+']'));name.append(logo(clan,36),copy);identity.append(name);const owner=el('td');if(clan.owner_username){const a=el('a',clan.owner_name||clan.owner_username);a.href='https://www.dunerealms.com/'+(clan.owner_memorial?'memorial/'+encodeURIComponent(clan.owner_memorial):'people/'+encodeURIComponent(clan.owner_username));a.target='_top';owner.append(a);}else owner.append(el('span','Not listed'));const action=el('td');action.append(view(clan,kind));row.append(identity,owner,el('td',clan.member_count==null?'Not published':String(Number(clan.member_count)||0)),el('td',kind==='clan'?status(clan):(clan.standing||'Protected House')),el('td',clan.homeworldName||clan.realm||'Not selected'),el('td',(clan.created_at||clan.term?.startsAt)?formatDuneDate(Number(clan.created_at||clan.term.startsAt)):'—'),action);body.append(row);}if(!rows.length){const row=el('tr'),cell=el('td','No organisations match the current filters.');cell.colSpan=7;row.append(cell);body.append(row);}table.append(head,body);wrap.append(table);register.append(wrap);host.append(register);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,18 @@
|
|||
import {element as el} from './cp-v2-page-template.mjs';
|
||||
import {createUserAPI} from './cp-v2-user-api.mjs';
|
||||
export function mountCampaignBooking(host,{kind,calendarLibrary,applicationId=null}={}){
|
||||
const controller=new AbortController(),api=createUserAPI(fetch,controller.signal);let active=true,context=null,calendar=null,busy=false,pending=null,day=null;const hours=new Set();
|
||||
const root=el('section',undefined,'promotion-agenda'),status=el('p','Loading your campaign agenda…'),select=el('select'),title=el('input'),message=el('textarea'),placement=el('select'),account=el('select'),confirm=el('input'),submit=el('button','Reserve selected hours'),quote=el('p'),area=el('div',undefined,'promotion-calendar'),buttons=el('div',undefined,'promotion-hour-buttons'),bookings=el('div');
|
||||
status.setAttribute('role','status');title.maxLength=100;message.maxLength=1000;message.rows=4;confirm.type='checkbox';submit.type='button';submit.disabled=true;for(const [value,text]of [['standard','Standard campaign'],['featured','Featured · exclusive faction slot (+50%)']]){const option=el('option',text);option.value=value;placement.append(option);}
|
||||
const promotion=el('fieldset'),channels=[];promotion.append(el('legend','Optional promotion · 25 DM per channel per booking'));for(const [id,name]of [['boards','Boards'],['discord','Discord']]){const label=el('label'),input=el('input');input.type='checkbox';input.value=id;input.disabled=true;input.onchange=()=>changed();channels.push(input);label.append(input,el('span',name));promotion.append(label);}
|
||||
const form=el('div',undefined,'promotion-tools');for(const [name,input]of [['Candidature',select],['Campaign title',title],['Campaign message',message],['Placement',placement],['Personal payment account',account]]){const label=el('label',name);label.append(input);form.append(label);}const consent=el('label');consent.append(confirm,el('span','I confirm the selected hours and total payment to Tax.'));
|
||||
root.append(el('h3','Book your campaign'),el('p','Each booking belongs to one election. Select future whole hours in the seven days before voting. Times are UTC. Existing reservations cannot be overwritten.'),status,form,area,buttons,quote,promotion,consent,submit,el('h3','My reservations'),bookings);host.replaceChildren(root);
|
||||
const changed=()=>{pending=null;paint();};
|
||||
function paint(){for(const field of [select,title,message,placement,account,confirm])field.disabled=busy;for(const field of channels)field.disabled=busy||!context?.promotionChannels.includes(field.value);const unit=context?.rates[placement.value]||0,total=hours.size*unit+channels.filter(c=>c.checked).length*(context?.promotionFeeMinor||2500);quote.textContent=hours.size+' hour(s) × '+(unit/100).toFixed(2)+' DM + '+((total-hours.size*unit)/100).toFixed(2)+' DM promotion = '+(total/100).toFixed(2)+' DM (including selected promotion) · reserved now, settled to Tax through the bank.';submit.disabled=busy||!context||!hours.size||!title.value.trim()||!message.value.trim()||!account.value||!confirm.checked;buttons.replaceChildren();if(!context)return;const date=new Date(day||Math.max(context.window.opensAt,Date.now()));date.setUTCMinutes(0,0,0);date.setUTCHours(0);for(let hour=0;hour<24;hour++){const at=date.getTime()+hour*3600000,blocked=at<Math.ceil(Date.now()/3600000)*3600000||at<context.window.opensAt||at>=context.window.closesAt||placement.value==='featured'&&context.occupied.includes(at),button=el('button',String(hour).padStart(2,'0')+':00 · '+(blocked?'Unavailable':hours.has(at)?'Selected':'Free'));button.type='button';button.disabled=busy||blocked;button.setAttribute('aria-pressed',String(hours.has(at)));button.onclick=()=>pick(at);buttons.append(button);}if(calendar){for(const event of calendar.getEvents())if(event.id.startsWith('selected:'))event.remove();for(const at of hours)calendar.addEvent({id:'selected:'+at,title:'Your selection',start:new Date(at).toISOString(),end:new Date(at+3600000).toISOString(),classNames:['promotion-selected']});}}
|
||||
function pick(at){if(busy||!context)return;at=Math.floor(Number(at)/3600000)*3600000;if(at<Math.ceil(Date.now()/3600000)*3600000||at<context.window.opensAt||at>=context.window.closesAt||placement.value==='featured'&&context.occupied.includes(at))return;if(hours.has(at))hours.delete(at);else hours.add(at);day=at;changed();}
|
||||
async function load(){busy=true;submit.disabled=true;hours.clear();try{context=await api.request('/api/jarvis/campaigns?application='+encodeURIComponent(select.value));if(!active)return;for(const input of channels){input.disabled=!context.promotionChannels.includes(input.value);if(input.disabled)input.checked=false;}account.replaceChildren(el('option','Choose account'));account.firstChild.value='';for(const row of context.accounts){const option=el('option',row.id+' · '+(row.available||row.balance||'')+' DM');option.value=row.id;account.append(option);}bookings.replaceChildren();for(const row of context.bookings)bookings.append(el('p',row.title+' · '+row.placement+' · '+(row.priceMinor/100).toFixed(2)+' DM · '+row.state));if(!context.bookings.length)bookings.append(el('p','No campaign hours booked yet.'));calendar?.destroy();const {Calendar}=await calendarLibrary();if(!active)return;area.replaceChildren();day=Math.max(context.window.opensAt,Date.now());calendar=new Calendar(area,{initialView:matchMedia('(max-width:700px)').matches?'timeGridDay':'timeGridWeek',initialDate:new Date(day).toISOString(),timeZone:'UTC',height:550,allDaySlot:false,slotDuration:'01:00:00',validRange:{start:new Date(context.window.opensAt).toISOString(),end:new Date(context.window.closesAt).toISOString()},headerToolbar:{left:'prev,next',center:'title',right:'timeGridWeek,timeGridDay'},events:context.occupied.map(at=>({id:'booked:'+at,title:'Featured slot reserved',start:new Date(at).toISOString(),end:new Date(at+3600000).toISOString(),classNames:['promotion-booked']})),dateClick:info=>{if(!info.allDay)pick(Date.parse(info.dateStr));},eventClick:info=>{if(info.event.id.startsWith('selected:'))pick(Date.parse(info.event.startStr));},datesSet:info=>{day=info.view.currentStart;paint();}});calendar.render();status.textContent='Live availability. A reservation is confirmed only after the server accepts your payment and hours.';}catch(error){if(active){context=null;status.textContent=error.message;}}finally{busy=false;if(active)paint();}}
|
||||
select.onchange=()=>{pending=null;void load();};placement.onchange=()=>{hours.clear();changed();};for(const field of [title,message,account,confirm])field.oninput=changed;
|
||||
submit.onclick=async()=>{if(submit.disabled)return;pending||={applicationId:select.value,requestId:crypto.randomUUID(),title:title.value,message:message.value,placement:placement.value,hours:[...hours].sort(),sourceAccount:account.value,expectedTotalMinor:hours.size*context.rates[placement.value]+channels.filter(c=>c.checked).length*context.promotionFeeMinor,channels:channels.filter(c=>c.checked).map(c=>c.value),confirmed:true};busy=true;paint();status.textContent='Reserving your campaign hours…';try{const result=await api.request('/api/jarvis/campaigns',pending);if(!active)return;pending=null;await load();status.textContent='Booking '+result.id+' confirmed. Your payment is reserved.';confirm.checked=false;}catch(error){if(active)status.textContent=error.message+' Refresh availability before making a different booking.';}finally{busy=false;if(active)paint();}};
|
||||
void api.request('/api/jarvis/campaigns').then(data=>{if(!active)return;const rows=data.applications.filter(a=>a.kind===kind);for(const row of rows){const option=el('option',row.public_id+' · '+row.faction+' · '+new Date(Number(row.election_start)).toLocaleDateString('en-GB',{timeZone:'UTC'}));option.value=row.id;select.append(option);}if(!rows.length){status.textContent='Submit your candidature first. Only your submitted, linked applications can book campaign hours.';return;}if(applicationId&&rows.some(r=>r.id===applicationId))select.value=applicationId;void load();}).catch(error=>{if(active)status.textContent=error.message;});
|
||||
return()=>{active=false;controller.abort();calendar?.destroy();root.remove();};
|
||||
}
|
||||
3
website/control-panel/public/cp-v2/cp-v2-confirm.mjs
Normal file
3
website/control-panel/public/cp-v2/cp-v2-confirm.mjs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
import {element as el} from './cp-v2-page-template.mjs';
|
||||
function action(title,handler){const button=el('button',title);button.type='button';button.onclick=handler;return button;}
|
||||
export function confirmAction(title,message){return new Promise(resolve=>{const dialog=el('dialog',undefined,'codex-exchange-dialog');let confirmed=false;dialog.append(el('h3',title),el('p',message),action('Cancel',()=>dialog.close()),action('Confirm',()=>{confirmed=true;dialog.close();}));dialog.onclose=()=>{dialog.remove();resolve(confirmed);};document.body.append(dialog);dialog.showModal();});}
|
||||
|
|
@ -1,20 +1,21 @@
|
|||
import {mountElectionResults} from './cp-v2-election-results.mjs';
|
||||
import {renderApplications} from '../election-applications-view.mjs';
|
||||
import {renderVoting} from '../election-voting-view.mjs';
|
||||
import {createCPV2Page,element as el} from './cp-v2-page-template.mjs';
|
||||
import {mountPromotionAgenda,ELECTION_DESIGN_TYPES,electionDesignStyles} from './cp-v2-promotion-agenda.mjs';
|
||||
import {createCardGallery,createListingCard} from './cp-v2-exchange-cards.mjs';
|
||||
export function mountElectionDesign(host,{context='clan'}={}){
|
||||
electionDesignStyles();let sessionUser=null,playerContext=null;let active=true,election=context==='clan'?'clan_delegate':'faction',disposeCalendar=()=>{},disposeBooking=()=>{};
|
||||
electionDesignStyles();let sessionUser=null,playerContext=null;let active=true,election=context==='clan'?'clan_delegate':'faction',disposeCalendar=()=>{},disposeBooking=()=>{},disposeResults=()=>{};
|
||||
const outer=el('div',undefined,'election-design');outer.dataset.mode='connected-elections';const scope=el('div',undefined,'election-scope-selector');if(context!=='clan'){const label=el('label','Election'),select=el('select');select.setAttribute('aria-label','Choose election');for(const id of ['faction','emperor','bene','guild']){const option=el('option',ELECTION_DESIGN_TYPES[id].name);option.value=id;select.append(option);}select.onchange=()=>{election=select.value;draw();};label.append(select);scope.append(label);}const content=el('div');outer.append(scope,content);host.replaceChildren(outer);
|
||||
function draw(){disposeCalendar();disposeBooking();const type=ELECTION_DESIGN_TYPES[election],applications=el('section',undefined,'election-page-grid'),apply=el('article',undefined,'election-panel'),history=el('article',undefined,'election-panel');apply.append(el('small','YOUR CANDIDATURE','election-eyebrow'),el('h3','Stand before the banners'),el('p','Your verified character, eligibility and candidature dossier will appear here.'));
|
||||
function draw(){disposeCalendar();disposeBooking();disposeResults();const type=ELECTION_DESIGN_TYPES[election],applications=el('section',undefined,'election-page-grid'),apply=el('article',undefined,'election-panel'),history=el('article',undefined,'election-panel');apply.append(el('small','YOUR CANDIDATURE','election-eyebrow'),el('h3','Stand before the banners'),el('p','Your verified character, eligibility and candidature dossier will appear here.'));
|
||||
const form=el('form',undefined,'election-form');form.onsubmit=e=>e.preventDefault();for(const [text,tag,placeholder]of [['Campaign title','input','Your campaign headline'],['Motivation & programme','textarea','Your plans and responsibilities']]){const label=el('label',text),field=el(tag);field.placeholder=placeholder;field.disabled=true;label.append(field);form.append(label);}const submit=el('button','Submit candidature · backend in commit 2');submit.type='button';submit.disabled=true;form.append(submit);apply.append(form);history.append(el('small','J.A.R.V.I.S. REGISTER','election-eyebrow'),el('h3','My applications'),emptyTable(['Reference','Election','Status','Details'],'No live application records are loaded in this design preview.'));
|
||||
const campaign=el('article',undefined,'election-panel election-campaign-panel'),booking=el('div'),book=el('button','Preview campaign booking agenda');book.type='button';campaign.append(el('small','STARPORT CAMPAIGN','election-eyebrow'),el('h3','Give your campaign a voice'),el('p',type.price+' DM per hour · campaign advertising only in the seven days before voting. Featured surcharge is separate and still to be confirmed.'),createListingCard({type:'campaign',image:'https://www.dunerealms.com/assets/seals/'+type.art,title:'Your campaign headline',subtitle:type.name+' · Example candidate',message:'Your candidate portrait, House seal and message become an advertisement on Starport.',featured:true,duration:'Example · 1 hour placement'},{preview:true}),book,booking);book.onclick=()=>{disposeBooking();disposeBooking=mountPromotionAgenda(booking,{election,organisationKind:context});book.hidden=true;};applications.append(campaign);if(playerContext)applications.prepend(renderApplications({user:sessionUser,context:playerContext,kind:type.kind}));else applications.prepend(el('p','Checking your player election record…','election-muted'));
|
||||
const campaign=el('article',undefined,'election-panel election-campaign-panel'),booking=el('div'),book=el('button','Book campaign hours');book.type='button';campaign.append(el('small','STARPORT CAMPAIGN','election-eyebrow'),el('h3','Give your campaign a voice'),el('p',type.price+' DM per hour · campaign advertising only in the seven days before voting. Featured placement costs 50% more.'),createListingCard({type:'campaign',image:'https://www.dunerealms.com/assets/seals/'+type.art,title:'Your campaign headline',subtitle:type.name+' · Example candidate',message:'Your candidate portrait, House seal and message become an advertisement on Starport.',featured:true,duration:'Example · 1 hour placement'},{preview:true}),book,booking);book.onclick=()=>{disposeBooking();disposeBooking=mountPromotionAgenda(booking,{election,organisationKind:context});book.hidden=true;};applications.append(campaign);if(playerContext)applications.prepend(renderApplications({user:sessionUser,context:playerContext,kind:type.kind}));else applications.prepend(el('p','Checking your player election record…','election-muted'));
|
||||
const voting=el('section',undefined,'election-panel');voting.append(el('small','THE BALLOT CHAMBER','election-eyebrow'),el('h3','Voting'),el('p','The existing three-hour ballot, eligibility and vote allowance will be connected in commit 2.'));const candidates=el('div',undefined,'election-candidate-grid');for(const caption of ['Candidate portrait','Candidate portrait']){const card=el('article',undefined,'election-candidate-preview'),portrait=el('div','✦','election-portrait-placeholder');portrait.setAttribute('aria-label',caption);card.append(portrait,el('h4','Candidate record'),el('p','Character name · House identity'),el('p','Programme and linked campaign details.'));const button=el('button','Cast vote · not connected');button.type='button';button.disabled=true;card.append(button);candidates.append(card);}voting.replaceChildren(renderVoting(type.kind));
|
||||
const results=el('section',undefined,'election-panel');results.append(el('small','THE OFFICE REGISTER','election-eyebrow'),el('h3','Results & office history'),el('p','The result creates the office deed; the register preserves the history of the office. Current office deeds determine Polclan access.'),emptyTable(['Election','Winner','Term','Office deed','History'],'No result is inferred or changed by this preview.'),el('p','A tied result starts an automatic three-hour office auction on Starport. Auction execution is connected in the backend batch.'));
|
||||
const calendar=el('section');let calendarMounted=false;const page=createCPV2Page({shellHost:host,title:context==='clan'?'Clan Elections · Landsraad Delegate':type.name+' Elections',description:context==='clan'?'Applications, voting, results and calendar for the Clan Delegate to the Landsraad.':'Citizen election workspace · eligibility follows your existing personal and political records.',artwork:'seals/'+type.art,tabs:[{id:'applications',label:'Applications',content:applications},{id:'voting',label:'Voting',content:voting},{id:'results',label:'Results',content:results},{id:'calendar',label:'Calendar',content:calendar}],onActivate:id=>{if(id==='calendar'&&!calendarMounted){calendarMounted=true;queueMicrotask(()=>{if(active)disposeCalendar=mountPromotionAgenda(calendar,{election,remindersOnly:true});});}}});
|
||||
const notice=el('p','Applications and ballots use the existing election service. Advertising bookings remain a preview until the payment and reservation service is connected.','election-preview-notice');content.replaceChildren(notice,page.root);if(context==='company')content.prepend(el('p','Company membership does not create extra votes. This page follows your personal election eligibility.','election-muted'));
|
||||
const results=el('section',undefined,'election-panel');let resultsMounted=false;
|
||||
const calendar=el('section');let calendarMounted=false;const page=createCPV2Page({shellHost:host,title:context==='clan'?'Clan Elections · Landsraad Delegate':type.name+' Elections',description:context==='clan'?'Applications, voting, results and calendar for the Clan Delegate to the Landsraad.':'Citizen election workspace · eligibility follows your existing personal and political records.',artwork:'seals/'+type.art,tabs:[{id:'applications',label:'Applications',content:applications},{id:'voting',label:'Voting',content:voting},{id:'results',label:'Results',content:results},{id:'calendar',label:'Calendar',content:calendar}],onActivate:id=>{if(id==='results'&&!resultsMounted){resultsMounted=true;queueMicrotask(()=>{if(active)disposeResults=mountElectionResults(results,{kind:type.kind});});}if(id==='calendar'&&!calendarMounted){calendarMounted=true;queueMicrotask(()=>{if(active)disposeCalendar=mountPromotionAgenda(calendar,{election,remindersOnly:true});});}}});
|
||||
const notice=el('p','Applications, ballots, office history and paid campaign reservations use the existing election and J.A.R.V.I.S. services.','election-preview-notice');content.replaceChildren(notice,page.root);if(context==='company')content.prepend(el('p','Company membership does not create extra votes. This page follows your personal election eligibility.','election-muted'));
|
||||
}
|
||||
draw();void Promise.all([fetch('/api/auth/session',{cache:'no-store'}),fetch('/api/politics/preview',{cache:'no-store'})]).then(async responses=>{const [session,context]=await Promise.all(responses.map(async r=>r.ok?r.json():null));if(!active)return;sessionUser=session?.user;playerContext=context||{linked:false};draw();}).catch(()=>{if(active){playerContext={linked:false};draw();}});return()=>{active=false;disposeCalendar();disposeBooking();outer.remove();};
|
||||
draw();void Promise.all([fetch('/api/auth/session',{cache:'no-store'}),fetch('/api/politics/preview',{cache:'no-store'})]).then(async responses=>{const [session,context]=await Promise.all(responses.map(async r=>r.ok?r.json():null));if(!active)return;sessionUser=session?.user;playerContext=context||{linked:false};draw();}).catch(()=>{if(active){playerContext={linked:false};draw();}});return()=>{active=false;disposeCalendar();disposeBooking();disposeResults();outer.remove();};
|
||||
}
|
||||
function emptyTable(headings,message){const wrap=el('div',undefined,'election-table-scroll'),table=el('table'),head=el('thead'),row=el('tr');for(const text of headings)row.append(el('th',text));head.append(row);const body=el('tbody'),empty=el('tr'),cell=el('td',message);cell.colSpan=headings.length;empty.append(cell);body.append(empty);table.append(head,body);wrap.append(table);return wrap;}
|
||||
export function mountAdvertisingDesign(host,{context='clan'}={}){
|
||||
|
|
|
|||
|
|
@ -0,0 +1,9 @@
|
|||
.applications-dashboard,.politics-content{--election-panel:#15372d;--election-field:#0b271f;--election-ink:#f0e3be;--election-muted:#c3ccbb;--election-line:#a38b50;--election-accent:#dac17d;min-width:0;max-width:100%;font:15px/1.65 Arial,sans-serif;color:var(--election-ink)}
|
||||
.politics-cp-shell .applications-dashboard,.politics-cp-shell .politics-content{--election-panel:#f5ecda;--election-field:#fffaf0;--election-ink:#442d2c;--election-muted:#67564b;--election-line:#b79a5d;--election-accent:#71363c}
|
||||
.naib-council .applications-dashboard,.naib-council .politics-content{--election-panel:#f3e5cc;--election-field:#fff8ea;--election-ink:#443522;--election-muted:#695d46;--election-line:#b39661;--election-accent:#76532f}
|
||||
.applications-dashboard .politics-card,.applications-dashboard .politics-charter,.politics-content>.politics-card{box-sizing:border-box;max-width:none;width:100%;min-width:0;margin:0 0 22px;padding:24px;border:1px solid var(--election-line);border-radius:12px;background:var(--election-panel);color:var(--election-ink)}
|
||||
.applications-dashboard h3,.politics-content h3{font-family:Georgia,serif;margin:0 0 14px;color:var(--election-ink)}.applications-dashboard p,.politics-content p{color:inherit;max-width:none}.applications-dashboard .politics-card>p{color:var(--election-muted)}
|
||||
.applications-table-wrap{width:100%;max-width:100%;overflow-x:auto;border:1px solid var(--election-line);border-radius:9px;margin-top:18px}.applications-table{border-collapse:collapse;width:100%;min-width:760px;font:13px/1.5 Arial,sans-serif;color:var(--election-ink)}.applications-table caption{text-align:left;padding:12px 14px;font-weight:600;color:var(--election-muted)}.applications-table th,.applications-table td{padding:13px 12px;text-align:left;vertical-align:middle;border-bottom:1px solid color-mix(in srgb,var(--election-line) 40%,transparent);overflow-wrap:anywhere}.applications-table th{font-size:12px;font-weight:700;background:color-mix(in srgb,var(--election-accent) 12%,var(--election-panel));white-space:nowrap}.applications-table td:first-child{min-width:170px;font:12px/1.5 ui-monospace,monospace}.applications-table td:nth-child(2){min-width:135px}.applications-table td:nth-child(3){min-width:115px}.applications-table td:nth-child(2) img{display:inline-block;vertical-align:middle;width:30px;height:30px;margin-right:8px}.applications-table tbody tr:last-child td{border-bottom:0}
|
||||
.applications-dashboard .politics-charter{display:grid;gap:16px}.applications-dashboard .politics-charter>label:not(.politics-accept){display:grid;gap:7px;font-weight:600}.applications-dashboard .politics-charter :is(select,textarea){display:block;width:100%;max-width:100%;box-sizing:border-box;border:1px solid var(--election-line);border-radius:7px;background:var(--election-field);color:var(--election-ink);font:inherit;padding:12px}.applications-dashboard .politics-charter textarea{min-height:160px;resize:vertical}.applications-dashboard .politics-charter>p{margin:0}.applications-dashboard .politics-accept,.politics-content .politics-accept{display:flex;align-items:flex-start;gap:10px;font-weight:400;line-height:1.6}.applications-dashboard input[type=checkbox],.politics-content input[type=checkbox]{flex:none;width:18px;height:18px;margin:3px 0 0;accent-color:var(--election-accent)}
|
||||
.applications-dashboard button,.politics-content button{width:auto;justify-self:start;min-height:42px;border:1px solid var(--election-line);border-radius:7px;background:var(--election-accent);color:var(--election-panel);font:600 13px/1.4 Arial,sans-serif;padding:10px 16px;cursor:pointer}.applications-dashboard button:disabled,.politics-content button:disabled{opacity:.55;cursor:default}.applications-dashboard :is(button,select,textarea):focus-visible,.politics-content button:focus-visible{outline:3px solid #528ca0;outline-offset:3px}.applications-detail-grid{display:grid;grid-template-columns:minmax(130px,1fr) minmax(0,2fr);gap:9px 18px}.applications-detail-grid dt{font-weight:600;color:var(--election-muted)}.applications-detail-grid dd{margin:0;overflow-wrap:anywhere}
|
||||
@media(max-width:650px){.applications-dashboard .politics-card,.applications-dashboard .politics-charter,.politics-content>.politics-card{padding:16px}.applications-detail-grid{grid-template-columns:1fr;gap:4px}.applications-detail-grid dd{margin-bottom:10px}}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
import {element as el} from './cp-v2-page-template.mjs';
|
||||
const date=v=>new Date(Number(v)).toLocaleString('en-GB',{timeZone:'UTC',dateStyle:'medium',timeStyle:'short'})+' UTC';
|
||||
export function mountElectionResults(host,{kind,fetcher=fetch}={}){
|
||||
const controller=new AbortController();let active=true;const root=el('section',undefined,'election-panel'),status=el('p','Loading election results…'),rounds=el('div',undefined,'election-page-grid'),detail=el('section'),history=el('div',undefined,'election-page-grid'),refresh=el('button','Refresh results');refresh.type='button';status.setAttribute('role','status');root.append(el('h3','Results & office history'),el('p','The register preserves the history of the office. The current deed determines its authority.'),refresh,status,rounds,detail,el('h3','Recorded officeholders'),history);host.replaceChildren(root);
|
||||
async function load(round=null){refresh.disabled=true;try{const r=await fetcher('/api/politics/results/'+kind+(round?'?round='+encodeURIComponent(round):''),{cache:'no-store',signal:controller.signal}),data=await r.json();if(!r.ok)throw Error(data.message);if(!active)return;status.textContent='';if(round){detail.replaceChildren(el('h3','Recorded candidate totals'));for(const c of data.candidates){const card=el('article',undefined,'election-panel');card.append(el('strong',c.username+' · '+c.votes+' votes'),el('small',c.public_id),el('p',c.motivation));detail.append(card);}detail.scrollIntoView({block:'nearest'});return;}
|
||||
rounds.replaceChildren();history.replaceChildren();if(!data.rounds.length)rounds.append(el('p','No recorded election rounds yet.'));for(const row of data.rounds){const card=el('article',undefined,'election-panel'),button=el('button','Candidate totals');button.type='button';button.onclick=()=>void load(row.id);card.append(el('h4',date(row.election_start)),el('p',row.status.replaceAll('_',' ')+' · '+(row.winner||'No ballot winner')),button);if(row.auction_id){const link=el('a','Office auction →');link.href='/jarvis-auction?id='+encodeURIComponent(row.auction_id);card.append(link);}rounds.append(card);}for(const row of data.terms){const card=el('article',undefined,'election-panel'),link=el('a',row.name);link.href='https://www.dunerealms.com/people/'+encodeURIComponent(row.username);card.append(link,el('p',date(row.starts_at)+' — '+date(row.expires_at)),el('strong',row.outcome==='resigned'?'Voluntarily resigned':row.outcome.replaceAll('_',' ')),el('small','Office deed '+row.id));history.append(card);}if(!data.terms.length)history.append(el('p','No office term recorded yet.'));
|
||||
}catch(error){if(active)status.textContent=error.message;}finally{if(active)refresh.disabled=false;}}
|
||||
refresh.onclick=()=>void load();void load();return()=>{active=false;controller.abort();root.remove();};
|
||||
}
|
||||
|
|
@ -12,7 +12,7 @@ function field(label,options){const box=el('label',undefined,'codex-exchange-fie
|
|||
function empty(columns,message){const wrap=el('div',undefined,'codex-exchange-table'),table=el('table'),head=el('tr'),thead=el('thead'),body=el('tbody'),row=el('tr'),cell=el('td',message);for(const label of columns)head.append(el('th',label));thead.append(head);cell.colSpan=columns.length;row.append(cell);body.append(row);table.append(thead,body);wrap.append(table);return wrap;}
|
||||
export function mountExchangeDesign(host,{context='public',view='browse',fetcher=fetch,organisationScope=null}={}){
|
||||
if(!document.querySelector('link[data-codex-exchange]')){const css=el('link');css.rel='stylesheet';css.href=new URL('./cp-v2-exchange-design.css',import.meta.url).href;css.dataset.codexExchange='';document.head.append(css);}
|
||||
let disposeJarvis=()=>{},active=true,rows=[],kitRows=[],jarvisRows=[],auctionRows=[],currentEdition=null,category=context==='user'?'items':context==='public'&&TYPES.some(([id])=>id===new URLSearchParams(location.search).get('type'))?new URLSearchParams(location.search).get('type'):'all',page=0,examples=false,goodsState='loading',kitState=context==='public'?'loading':'hidden',jarvisState='loading';const controller=new AbortController();
|
||||
let disposeJarvis=()=>{},active=true,rows=[],kitRows=[],jarvisRows=[],auctionRows=[],campaignRows=[],politicalRows=[],currentEdition=null,category=context==='user'?'items':context==='public'&&TYPES.some(([id])=>id===new URLSearchParams(location.search).get('type'))?new URLSearchParams(location.search).get('type'):'all',page=0,examples=false,goodsState='loading',kitState=context==='public'?'loading':'hidden',jarvisState='loading';const controller=new AbortController();
|
||||
const root=el('section',undefined,'codex-exchange'+(context==='public'?' codex-exchange-public':'')),hero=el('header',undefined,'codex-exchange-hero'),copy=el('div');copy.append(el('small',context==='public'?'SPACING GUILD · STARPORT EXCHANGE':'STARPORT · J.A.R.V.I.S.'),el('h2',context==='clan'?(organisationScope?.kind==='company'?'Company Exchange':organisationScope?.kind==='politics'?'Political House Exchange':'Household Exchange'):context==='user'?'Item Exchange':'Starport Exchange'),el('p','Find your next trade, calling or adventure.'));hero.append(image(context==='public'?'faction-guild.svg':'nav-exchange-v2.webp'),copy);root.append(hero);
|
||||
const banner=el('p',context==='user'?'Minecraft goods use the existing listings service. Trading remains in game.':context==='clan'?'Opening the J.A.R.V.I.S. recruitment register…':'Browse live goods, kit designs and published recruitment opportunities.','codex-exchange-notice');root.append(banner);
|
||||
const browse=el('div'),layout=el('div',undefined,'codex-exchange-layout'),aside=el('aside',undefined,'codex-exchange-categories'),main=el('div',undefined,'codex-exchange-main'),tools=el('div',undefined,'codex-exchange-tools');
|
||||
|
|
@ -26,8 +26,8 @@ export function mountExchangeDesign(host,{context='public',view='browse',fetcher
|
|||
const eligibility=el('p','Checking your deed…','codex-exchange-eligibility');if(context==='clan')root.append(eligibility);
|
||||
let selectPost;const groups=[{id:'browse',title:'Browse',content:browse}];if(context!=='public'){groups.push({id:'mine',title:'My listings',content:mine},{id:'post',title:context==='user'?'Post an item':'Post a listing',content:post});if(context==='clan')groups.push({id:'applications',title:'Applications',content:applications},{id:'promotions',title:'Promotions',content:promotions});}const tabbed=organisationTabs(groups,{label:'Exchange sections',initial:view});selectPost=()=>tabbed.querySelector('[role=tab][aria-controls$="-post-panel"]')?.click();root.append(tabbed);
|
||||
const footer=el('footer',undefined,'codex-exchange-logistics');footer.append(el('span',context==='public'?'Logistics by SPost':'Exchange logistics supplied by'),image('spost-logo-v1.svg'),el('small','part of'),image('corrino-group-v4.png'));root.append(footer);const cardDesigns=el('details',undefined,'codex-exchange-legend');cardDesigns.append(el('summary','Card design previews · items, kits, campaigns, jobs and more'),createCardGallery());root.append(cardDesigns);host.replaceChildren(root);
|
||||
function render(){for(const [node,id]of buttons)node.setAttribute('aria-pressed',String(id===category));let matches=[...rows,...kitRows,...jarvisRows,...auctionRows,...(examples?SAMPLES.filter(row=>context!=='clan'||['recruitment','quests','events'].includes(row.type)):[])].filter(row=>(category==='all'||row.category===category||row.type===category&&!(category==='recruitment'&&row.organisationKind==='company')||row.kitCategory===category)&&[row.title,row.owner,row.world].join(' ').toLowerCase().includes(search.input.value.toLowerCase()));if(stage.input.selectedIndex>0)matches=matches.filter(row=>row.edition?.stage===stage.input.value.toLowerCase());if(season.input.selectedIndex>0)matches=matches.filter(row=>row.edition&¤tEdition&&(season.input.selectedIndex===1?row.edition.season===currentEdition.season:row.edition.season!==currentEdition.season));if(quality.input.selectedIndex>0)matches=matches.filter(row=>words(row.quality).toLowerCase()===quality.input.value.toLowerCase());matches.sort((a,b)=>sort.input.selectedIndex===1?a.price-b.price:sort.input.selectedIndex===2?b.price-a.price:sort.input.selectedIndex===3?a.title.localeCompare(b.title):Number(b.createdAt||b.created_at||b.id)-Number(a.createdAt||a.created_at||a.id)||0);page=Math.min(page,Math.max(0,Math.ceil(matches.length/8)-1));cards.replaceChildren();if(!matches.length)cards.append(el('p',season.input.selectedIndex||quality.input.selectedIndex||stage.input.selectedIndex?'No listings match these edition and quality filters. Goods without edition metadata are excluded.':'No matching listings. Design examples can be enabled separately.','codex-exchange-empty'));for(const row of matches.slice(page*8,page*8+8)){const sample=String(row.id).startsWith('preview-'),type=TYPES.find(([id])=>id===(row.category||row.type)),cardType=({'items':'item','kits':'kit','recruitment':'job','quests':'quest','events':'event','deeds':'deed','auctions':'auction'})[row.type]||'ad',art=row.type==='recruitment'&&row.organisationKind==='company'?'exchange-company-jobs-v1.png':row.type==='items'?'minecraft-items/'+String(row.material).toLowerCase()+'.png':row.type==='kits'?'minecraft-items/'+(row.quality==='legendary'?'netherite_chestplate':'leather_chestplate')+'.png':type?.[2]||'nav-exchange-v2.webp',facts=[row.world,...(row.edition?[words(row.edition.stage)+' '+row.edition.version+' · '+row.edition.season]:[]),...(row.type==='items'?[row.quantity+' available']:row.type==='kits'?[words(row.quality)]:[])].filter(Boolean),card=createListingCard({type:cardType,title:row.title,owner:row.owner,subtitle:row.owner,message:row.description||'',image:row.image||asset+art,facts:row.type==='auctions'?['Highest bid: '+(row.highestMinor/100).toFixed(2)+' DM','Closes: '+new Date(row.closesAt).toLocaleString('en-GB'),'3 hour office auction']:facts,price:['items','kits'].includes(row.type)?Number(row.price).toFixed(2)+' DM':null},{preview:sample,onOpen:()=>detail(row,sample)});card.classList.add('codex-exchange-card');cards.append(card);}pager.replaceChildren(button('← Previous',()=>{page--;render();},page===0),el('span',(page+1)+' / '+Math.max(1,Math.ceil(matches.length/8))),button('Next →',()=>{page++;render();},(page+1)*8>=matches.length));}
|
||||
function detail(row,sample){if(row.type==='auctions'&&!sample){window.location.href='https://cp.dunerealms.com/jarvis-auction?id='+encodeURIComponent(row.id);return;}const dialog=el('dialog',undefined,'codex-exchange-dialog');dialog.append(el('h3',row.title),el('p',row.description||row.owner+' · '+row.world),el('p',sample?'Design example. Applications and purchases are disabled.':row.type==='kits'?(row.purchaseAvailable?'Continue to the existing kit checkout.':'Published design · purchase or delivery is not available yet.'):row.type==='recruitment'?'Applications are free. The organisation reviews your request before membership starts.':'Trade in Minecraft: /exchange buy '+row.id),button('Close',()=>dialog.close()));if(row.type==='kits'&&row.purchaseAvailable){const checkout=el('a','Open kit checkout →');checkout.href='https://cp.dunerealms.com/?kit-listing='+encodeURIComponent(row.listingId)+'#realm/kits-exchange';dialog.append(checkout);}if(!sample&&row.type==='recruitment'){const apply=el('a','Apply to this '+(row.organisationKind==='company'?'company':'clan')+' →');apply.href='https://cp.dunerealms.com/jarvis-application?listing='+encodeURIComponent(row.id);apply.target='_top';dialog.append(apply);}dialog.onclose=()=>dialog.remove();root.append(dialog);dialog.showModal();}
|
||||
function render(){for(const [node,id]of buttons)node.setAttribute('aria-pressed',String(id===category));let matches=[...rows,...kitRows,...jarvisRows,...auctionRows,...campaignRows,...politicalRows,...(examples?SAMPLES.filter(row=>context!=='clan'||['recruitment','quests','events'].includes(row.type)):[])].filter(row=>(category==='all'||row.category===category||row.type===category&&!(category==='recruitment'&&row.organisationKind==='company')||row.kitCategory===category)&&[row.title,row.owner,row.world].join(' ').toLowerCase().includes(search.input.value.toLowerCase()));if(stage.input.selectedIndex>0)matches=matches.filter(row=>row.edition?.stage===stage.input.value.toLowerCase());if(season.input.selectedIndex>0)matches=matches.filter(row=>row.edition&¤tEdition&&(season.input.selectedIndex===1?row.edition.season===currentEdition.season:row.edition.season!==currentEdition.season));if(quality.input.selectedIndex>0)matches=matches.filter(row=>words(row.quality).toLowerCase()===quality.input.value.toLowerCase());matches.sort((a,b)=>sort.input.selectedIndex===1?a.price-b.price:sort.input.selectedIndex===2?b.price-a.price:sort.input.selectedIndex===3?a.title.localeCompare(b.title):Number(b.createdAt||b.created_at||b.id)-Number(a.createdAt||a.created_at||a.id)||0);page=Math.min(page,Math.max(0,Math.ceil(matches.length/8)-1));cards.replaceChildren();if(!matches.length)cards.append(el('p',season.input.selectedIndex||quality.input.selectedIndex||stage.input.selectedIndex?'No listings match these edition and quality filters. Goods without edition metadata are excluded.':'No matching listings. Design examples can be enabled separately.','codex-exchange-empty'));for(const row of matches.slice(page*8,page*8+8)){const sample=String(row.id).startsWith('preview-'),type=TYPES.find(([id])=>id===(row.category||row.type)),cardType=({'items':'item','kits':'kit','recruitment':'job','quests':'quest','events':'event','deeds':'deed','auctions':'auction','campaign':'campaign','political-job':'job'})[row.type]||'ad',art=row.type==='recruitment'&&row.organisationKind==='company'?'exchange-company-jobs-v1.png':row.type==='items'?'minecraft-items/'+String(row.material).toLowerCase()+'.png':row.type==='kits'?'minecraft-items/'+(row.quality==='legendary'?'netherite_chestplate':'leather_chestplate')+'.png':type?.[2]||'nav-exchange-v2.webp',facts=[row.world,...(row.edition?[words(row.edition.stage)+' '+row.edition.version+' · '+row.edition.season]:[]),...(row.type==='items'?[row.quantity+' available']:row.type==='kits'?[words(row.quality)]:[])].filter(Boolean),card=createListingCard({type:cardType,featured:row.featured===true,title:row.title,owner:row.owner,subtitle:row.subtitle||row.owner,message:row.description||'',image:row.image||asset+art,facts:row.type==='auctions'?['Highest bid: '+(row.highestMinor/100).toFixed(2)+' DM','Closes: '+new Date(row.closesAt).toLocaleString('en-GB'),'3 hour office auction']:facts,price:['items','kits'].includes(row.type)?Number(row.price).toFixed(2)+' DM':null},{preview:sample,onOpen:()=>detail(row,sample)});card.classList.add('codex-exchange-card');cards.append(card);}pager.replaceChildren(button('← Previous',()=>{page--;render();},page===0),el('span',(page+1)+' / '+Math.max(1,Math.ceil(matches.length/8))),button('Next →',()=>{page++;render();},(page+1)*8>=matches.length));}
|
||||
function detail(row,sample){if(['campaign','political-job'].includes(row.type)&&!sample){window.location.href=row.url;return;}if(row.type==='auctions'&&!sample){window.location.href='https://cp.dunerealms.com/jarvis-auction?id='+encodeURIComponent(row.id);return;}const dialog=el('dialog',undefined,'codex-exchange-dialog');dialog.append(el('h3',row.title),el('p',row.description||row.owner+' · '+row.world),el('p',sample?'Design example. Applications and purchases are disabled.':row.type==='kits'?(row.purchaseAvailable?'Continue to the existing kit checkout.':'Published design · purchase or delivery is not available yet.'):row.type==='recruitment'?'Applications are free. The organisation reviews your request before membership starts.':'Trade in Minecraft: /exchange buy '+row.id),button('Close',()=>dialog.close()));if(row.type==='kits'&&row.purchaseAvailable){const checkout=el('a','Open kit checkout →');checkout.href='https://cp.dunerealms.com/?kit-listing='+encodeURIComponent(row.listingId)+'#realm/kits-exchange';dialog.append(checkout);}if(!sample&&row.type==='recruitment'){const apply=el('a','Apply to this '+(row.organisationKind==='company'?'company':'clan')+' →');apply.href='https://cp.dunerealms.com/jarvis-application?listing='+encodeURIComponent(row.id);apply.target='_top';dialog.append(apply);}dialog.onclose=()=>dialog.remove();root.append(dialog);dialog.showModal();}
|
||||
search.input.oninput=()=>{page=0;render();};sort.input.onchange=quality.input.onchange=stage.input.onchange=season.input.onchange=()=>{page=0;render();};
|
||||
async function load(){try{const response=await fetcher(context==='public'?'/api/exchange/listings':'/api/exchange/listings?view=all',{credentials:'same-origin',signal:controller.signal});if(!response.ok)throw Error('unavailable');const data=await response.json();const source=Array.isArray(data)?data:Array.isArray(data.listings)?data.listings:Array.isArray(data.items)?data.items:[];rows=source.filter(row=>Number.isFinite(Number(row.price))&&Number.isFinite(Number(row.quantity))&&/^[A-Za-z0-9_]+$/.test(row.material||'')&&/^\d+$/.test(String(row.id))).map(row=>({...row,type:'items',title:row.displayName||words(row.material),owner:row.seller||row.seller_name||'Player listing',world:words(row.origin),price:Number(row.price),quantity:Number(row.quantity)}));if(!active)return;goodsState='ready';updateStatus();render();}catch{if(!active)return;rows=[];goodsState='error';updateStatus();render();}}
|
||||
if(context==='clan')import('./cp-v2-jarvis-recruitment.mjs').then(({mountJarvisRecruitment})=>{if(active)disposeJarvis=mountJarvisRecruitment({mine,post,applications,promotions,banner,eligibility,scope:organisationScope||{kind:'clan'},fetcher,signal:controller.signal,onChanged:()=>void loadJarvis()});}).catch(()=>{if(active)banner.textContent='Recruitment services could not be opened.';});
|
||||
|
|
@ -36,5 +36,7 @@ export function mountExchangeDesign(host,{context='public',view='browse',fetcher
|
|||
function updateStatus(){status.textContent=[goodsState==='ready'?rows.length+' Minecraft listings':goodsState==='error'?'Minecraft listings unavailable':'Loading Minecraft listings',kitState==='ready'?kitRows.length+' kit designs':kitState==='loading'?'Loading kits':kitState==='error'?'Kit catalogue unavailable':null,jarvisState==='ready'?jarvisRows.length+' recruitment listings':jarvisState==='error'?'Recruitment listings unavailable':'Loading recruitment'].filter(Boolean).join(' · ');}
|
||||
async function loadJarvis(){try{const response=await fetcher(context==='public'?'https://cp.dunerealms.com/api/jarvis/listings':'/api/jarvis/listings',{credentials:context==='public'?'omit':'same-origin',cache:'no-store',signal:controller.signal});if(!response.ok)throw Error();const data=await response.json();if(!active)return;jarvisRows=(data.listings||[]).map(row=>({...row,price:0}));currentEdition=data.edition||null;jarvisState='ready';updateStatus();render();}catch{if(active){jarvisState='error';updateStatus();}}}
|
||||
async function loadAuctions(){try{const response=await fetcher(context==='public'?'https://cp.dunerealms.com/api/jarvis/auctions':'/api/jarvis/auctions',{credentials:context==='public'?'omit':'same-origin',cache:'no-store',signal:controller.signal});if(!response.ok)throw Error();const data=await response.json();if(active){auctionRows=(data.auctions||[]).map(row=>({...row,price:row.highestMinor/100}));render();}}catch{if(active&&category==='auctions')status.textContent='The auction register is unavailable. Refresh to retry.';}}
|
||||
render();load();void loadJarvis();if(context!=='user')void loadAuctions();return()=>{active=false;disposeJarvis();controller.abort();root.remove();};
|
||||
async function loadCampaigns(){try{const response=await fetcher(context==='public'?'https://cp.dunerealms.com/api/jarvis/campaigns/public':'/api/jarvis/campaigns/public',{cache:'no-store',signal:controller.signal});if(!response.ok)throw Error();const data=await response.json();if(active){campaignRows=(data.listings||[]).map(row=>({...row,price:0}));render();}}catch{}}
|
||||
async function loadPoliticalJobs(){try{const response=await fetcher(context==='public'?'https://cp.dunerealms.com/api/jarvis/political-jobs/public':'/api/jarvis/political-jobs/public',{cache:'no-store',signal:controller.signal});if(!response.ok)throw Error();const data=await response.json();if(active){politicalRows=(data.listings||[]).map(row=>({...row,price:0}));render();}}catch{}}
|
||||
render();load();void loadJarvis();if(context!=='user')void loadPoliticalJobs();if(context!=='user')void loadCampaigns();if(context!=='user')void loadAuctions();return()=>{active=false;disposeJarvis();controller.abort();root.remove();};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
import {confirmAction} from './cp-v2-confirm.mjs';
|
||||
import {element as el} from './cp-v2-page-template.mjs';import {createUserAPI} from './cp-v2-user-api.mjs';
|
||||
const amount=n=>(Number(n)/100).toFixed(2)+' DM';
|
||||
function field(title,input){const label=el('label',title);label.append(input);return label;}
|
||||
function action(title,handler){const button=el('button',title);button.type='button';button.onclick=handler;return button;}
|
||||
function confirmAction(title,message){return new Promise(resolve=>{const dialog=el('dialog',undefined,'codex-exchange-dialog');let confirmed=false;dialog.append(el('h3',title),el('p',message),action('Cancel',()=>dialog.close()),action('Confirm',()=>{confirmed=true;dialog.close();}));dialog.onclose=()=>{dialog.remove();resolve(confirmed);};document.body.append(dialog);dialog.showModal();});}
|
||||
|
||||
function table(columns){const wrap=el('div',undefined,'codex-exchange-table'),node=el('table'),head=el('thead'),row=el('tr'),body=el('tbody');for(const column of columns)row.append(el('th',column));head.append(row);node.append(head,body);wrap.append(node);return{wrap,body};}
|
||||
export function mountJarvisRecruitment({mine,post,applications,promotions,banner,eligibility,scope={kind:'clan'},fetcher=fetch,signal,onChanged=()=>{}}){
|
||||
let active=true,context=null,busy=false,pending=null;const {request}=createUserAPI(fetcher,signal);
|
||||
|
|
|
|||
|
|
@ -0,0 +1,8 @@
|
|||
.naib-council{--text:#392b21;--gold:#876224;--line:#b69a63;color:#392b21;min-width:0}
|
||||
.naib-council .cp-v2-template-heading{border:1px solid #aa884d;border-radius:12px;padding:24px;background:linear-gradient(100deg,#f2e5c9f5,#f2e5c9d9),url('https://www.dunerealms.com/assets/arrakis.webp') center/cover}
|
||||
.naib-council .organisation-settings-card,.naib-council .politics-card{background:linear-gradient(135deg,#fbf3e4,#e9dcc1);border:1px solid #b69a63;border-radius:12px;padding:22px;margin-block:16px;min-width:0;color:#392b21}
|
||||
.naib-council h3,.naib-council h4{color:#694b28}.naib-council a{color:#713c25}.naib-council label{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin-block:14px}.naib-council label:has(input:not([type=checkbox])),.naib-council label:has(textarea){display:grid}
|
||||
.naib-council input:not([type=checkbox]),.naib-council textarea,.naib-council select{max-width:100%;min-width:0;color:#392b21;background:#fff9ed;border:1px solid #a9916d;border-radius:7px;padding:10px;box-sizing:border-box}.naib-council input[type=checkbox]{width:18px;height:18px;flex:none;accent-color:#876224}
|
||||
.naib-council button{color:#fff6df;background:#76532f;border:1px solid #9c783d;border-radius:7px;padding:10px 16px;cursor:pointer}.naib-council button:disabled{opacity:.55;cursor:default}.naib-council button:focus-visible,.naib-council select:focus-visible{outline:3px solid #2c718a;outline-offset:3px}.naib-council button[role=tab][aria-selected=true]{background:#3c606b;color:#fff9ed}
|
||||
.naib-council table{width:100%;border-collapse:collapse}.naib-council th,.naib-council td{padding:12px;text-align:left;border-bottom:1px solid #c4b18a;overflow-wrap:anywhere}.naib-council th{background:#e1cba2;color:#49371e}.naib-council small,.naib-council p{overflow-wrap:anywhere}.naib-council .applications-table-wrap{overflow:auto;max-width:100%}.naib-council .cp-v2-template-tabs{display:flex;flex-wrap:wrap;gap:8px}
|
||||
@media(max-width:650px){.naib-council .organisation-settings-card,.naib-council .politics-card{padding:14px}.naib-council .cp-v2-template-tabs button{flex:1 1 120px}.naib-council th,.naib-council td{padding:8px}}
|
||||
28
website/control-panel/public/cp-v2/cp-v2-naib-council.mjs
Normal file
28
website/control-panel/public/cp-v2/cp-v2-naib-council.mjs
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
import {element as el,createCPV2Page} from './cp-v2-page-template.mjs';
|
||||
import {createUserAPI} from './cp-v2-user-api.mjs';
|
||||
import {renderApplications} from '../election-applications-view.mjs';
|
||||
import {renderVoting} from '../election-voting-view.mjs';
|
||||
import {mountElectionResults} from './cp-v2-election-results.mjs';
|
||||
export function mountNaibCouncil(host){
|
||||
if(!document.querySelector('link[data-naib-council]')){const style=el('link');style.rel='stylesheet';style.href=new URL('./cp-v2-naib-council.css',import.meta.url).href;style.dataset.naibCouncil='';document.head.append(style);}
|
||||
const controller=new AbortController(),api=createUserAPI(fetch,controller.signal);let active=true,busy=false,disposeResults=()=>{};
|
||||
const status=el('p','Loading the Council of Naibs…');status.setAttribute('role','status');host.replaceChildren(status);
|
||||
async function load(){try{const [data,session]=await Promise.all([api.request('/api/politics/naibs'),api.request('/api/auth/session')]);if(!active)return;draw(data,session.user);}catch(error){if(active)status.textContent=error.message;}}
|
||||
function draw(data,user){
|
||||
disposeResults();const seats=el('section',undefined,'organisation-settings-card'),decisions=el('section',undefined,'organisation-settings-card'),diplomacy=el('section',undefined,'organisation-settings-card'),powers=el('section',undefined,'organisation-settings-card'),elections=el('section'),results=el('section');
|
||||
seats.append(el('h3','Recognised sietches'),el('p','One Council seat belongs to each active Arrakduin sietch. Its current clan owner is its Naib. Imperial appointments cannot grant or remove these seats.'));
|
||||
const table=el('table'),head=el('tr');for(const text of ['Sietch','Naib'])head.append(el('th',text));const thead=el('thead');thead.append(head);const tbody=el('tbody');for(const seat of data.seats){const row=el('tr'),name=el('td'),person=el('td'),link=el('a',seat.name);link.href='https://www.dunerealms.com/clans/'+encodeURIComponent(seat.tag);link.target='_top';name.append(link);const profile=el('a',seat.displayName);profile.href='https://www.dunerealms.com/people/'+encodeURIComponent(seat.username);profile.target='_top';person.append(profile);row.append(name,person);tbody.append(row);}table.append(thead,tbody);seats.append(table);if(!data.seats.length)seats.append(el('p','No recognised sietches are currently eligible.'));
|
||||
decisions.append(el('h3','Council decisions'),el('p','Voting lasts 24 hours. More than half of the recorded sietches must participate; a choice needs more than half of the votes cast. A tie does not adopt a proposal. The electorate is recorded when a proposal opens; a new owner inherits the existing sietch seat.'));
|
||||
diplomacy.append(el('h3','Imperial diplomacy'),el('p','Imperial Peace offers can be accepted, rejected or returned for negotiation. These are diplomatic records; automatic war, claim and PvP changes remain unavailable.'));
|
||||
const form=el('form'),kind=el('select'),title=el('input'),message=el('textarea'),confirm=el('input'),send=el('button','Submit proposal');title.maxLength=100;title.required=true;message.rows=5;message.minLength=20;message.maxLength=4000;message.required=true;confirm.type='checkbox';confirm.required=true;
|
||||
for(const [value,text]of [['decision','Council proposal'],['imperial-peace','Imperial Peace offer']]){const option=el('option',text);option.value=value;kind.append(option);}if(!data.naib){kind.value='imperial-peace';kind.disabled=true;}
|
||||
for(const [text,field]of [['Proposal type',kind],['Title',title],['Terms and message',message],['I confirm this proposal',confirm]]){const label=el('label',text);label.append(field);form.append(label);}send.type='submit';form.append(send);diplomacy.append(form);let requestId=crypto.randomUUID();form.oninput=()=>{if(!busy)requestId=crypto.randomUUID();};
|
||||
const lock=value=>{busy=value;for(const field of [title,message,confirm,send])field.disabled=value;kind.disabled=value||!data.naib;};
|
||||
form.onsubmit=async event=>{event.preventDefault();if(busy||!form.reportValidity())return;const input={requestId,kind:kind.value,title:title.value,message:message.value,confirmed:confirm.checked};lock(true);status.textContent='Recording the proposal…';try{await api.request('/api/politics/naibs/propose',input);await load();status.textContent='Council proposal recorded.';}catch(error){if(active){status.textContent=error.message;lock(false);}}};
|
||||
for(const dossier of data.dossiers){const card=el('article',undefined,'organisation-settings-card');card.append(el('small',dossier.reference),el('h3',dossier.title),el('p',dossier.message),el('p',dossier.state==='closed'?'Decision: '+dossier.result:'Voting closes '+new Date(dossier.closesAt).toLocaleString('en-GB',{timeZone:'UTC'})+' UTC'),el('p',dossier.electorate+' sietches in the recorded electorate'));if(dossier.tally)card.append(el('p',dossier.tally.participation+' votes · quorum '+dossier.tally.quorum+' · '+Object.entries(dossier.tally.counts).map(([choice,total])=>choice+': '+total).join(' · ')));if(dossier.ownVote)card.append(el('p','Your sietch voted: '+dossier.ownVote));else if(dossier.canVote){const choice=el('select');for(const value of dossier.choices){const option=el('option',value);option.value=value;choice.append(option);}const consent=el('label'),check=el('input');check.type='checkbox';consent.append(check,el('span','I confirm this definitive vote for my sietch.'));const button=el('button','Cast Council vote');button.type='button';button.onclick=async()=>{if(busy||!check.checked){status.textContent='Confirm your vote first.';return;}busy=true;button.disabled=true;try{await api.request('/api/politics/naibs/vote',{dossierId:dossier.id,choice:choice.value,confirmed:true});await load();status.textContent='Council vote recorded.';}catch(error){if(active){status.textContent=error.message;button.disabled=false;}}finally{busy=false;}};card.append(choice,consent,button);} (dossier.kind==='imperial-peace'?diplomacy:decisions).append(card);}
|
||||
elections.append(el('p','Naibs elect the chair from their own members. The existing general Fremen leadership election remains separate.'),renderApplications({user,context:{linked:true,naib:data.naib,clanId:data.seatId},kind:'naib_chair'}),renderVoting('naib_chair'));
|
||||
powers.append(el('h3','Council powers'),el('p','Political powers are awaiting a separate design. No gameplay action is available from this page.'));
|
||||
const page=createCPV2Page({shellHost:host,title:'Council of Naibs',description:'House of Arrakis · independent sietches of Arrakduin',artwork:'seals/office-house_leader.png',tabs:[{id:'sietches',label:'Sietches',content:seats},{id:'decisions',label:'Decisions',content:decisions},{id:'diplomacy',label:'Diplomacy',content:diplomacy},{id:'elections',label:'Chair election',content:elections},{id:'results',label:'Results',content:results},{id:'powers',label:'Powers',content:powers}],onActivate:id=>{if(id==='results'){disposeResults();disposeResults=mountElectionResults(results,{kind:'naib_chair'});}}});host.replaceChildren(status,page.root);page.root.classList.add('naib-council');busy=false;
|
||||
}
|
||||
void load();return()=>{active=false;controller.abort();disposeResults();};
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
export const ORGANISATION_MENU_GROUPS=Object.freeze([
|
||||
['Your organisation',[['overview','Dashboard'],['settings','Settings']]],
|
||||
['Organisation affairs',[['boards','Boards'],['events','Events'],['elections','Elections'],['advertising','Advertising'],['commerce','Exchange'],['tailor','Tailor']]],
|
||||
['Organisation affairs',[['boards','Boards'],['events','Events'],['elections','Elections'],['naibs','Council of Naibs'],['advertising','Advertising'],['commerce','Exchange'],['jobs','Office vacancies'],['tailor','Tailor']]],
|
||||
['Estates & relations',[['claims','Claims'],['subsidiaries','Subhouses'],['directory','Directory'],['projects','Expeditions'],['campaigns','Campaigns']]]
|
||||
]);
|
||||
export function organisationPage(hash=''){
|
||||
|
|
@ -12,5 +12,5 @@ export function organisationPage(hash=''){
|
|||
export function organisationMenuItems(kind){
|
||||
if(!['company','politics'].includes(kind))throw TypeError('Unknown organisation workspace');
|
||||
const company=kind==='company',base=company?'https://corp.dunerealms.com/#company/':'https://www.dunerealms.com/government.html#household/';
|
||||
return ORGANISATION_MENU_GROUPS.flatMap(([,items])=>items.map(([id,title])=>({label:company&&id==='subsidiaries'?'Subsidiaries':title,href:base+id,artwork:'https://www.dunerealms.com/assets/'+(company?'guild.webp':'seals/office-landsraad.png')})));
|
||||
return ORGANISATION_MENU_GROUPS.flatMap(([,items])=>items.filter(([id])=>!company||!['jobs','naibs'].includes(id)).map(([id,title])=>({label:company&&id==='subsidiaries'?'Subsidiaries':title,href:base+id,artwork:'https://www.dunerealms.com/assets/'+(company?'guild.webp':'seals/office-landsraad.png')})));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
import {mountNaibCouncil} from './cp-v2-naib-council.mjs';
|
||||
import {mountPoliticalJobs} from './cp-v2-political-jobs.mjs';
|
||||
import {mountRealmEvents} from './cp-v2-events.mjs';
|
||||
import {mountOfficeResignation} from './cp-v2-office-resign.mjs';
|
||||
import {mountElectionDesign,mountAdvertisingDesign} from './cp-v2-election-design.mjs';
|
||||
|
|
@ -33,15 +35,17 @@ export function startOrganisationCP(kind){
|
|||
if(!ready||stopped)return;dispose();dispose=()=>{};const turn=++generation,record=records.find(r=>r.id===selected),page=route()||'overview';
|
||||
left.replaceChildren(el('div',company?'YOUR COMPANY':'YOUR POLITICAL HOUSE','side-hero'));right.replaceChildren(el('div',company?'COMPANY DIRECTORY':'POLITICAL HOUSES','side-hero'));portals.replaceChildren();portals.hidden=false;portals.classList.remove('organisation-switcher');const tiles=el('div',undefined,'organisation-portals');for(const [id,title,art,href] of [['overview',company?'My Company':'My Political House',record?.emblem||fallback],['quests','Quests','nav-manual-v2.webp','https://www.dunerealms.com/exchange.html?type=quests'],['tailor','Kits',company?'minecraft-items/iron_pickaxe.png':'items/office_water.png','https://www.dunerealms.com/exchange.html?type=kits-'+(company?'clan':'office')],['campaigns','Events',company?'nav-home-v2.webp':'seals/emperor-v1.png']]){const a=el('a',undefined,'organisation-portal');a.href=href||'#'+prefix+'/'+id;if(href)a.target='_top';a.append(image(art),el('strong',title));if(id===page)a.setAttribute('aria-current','page');tiles.append(a);}portals.append(tiles);
|
||||
const label=el('label',company?'Your companies':'Political Houses'),select=el('select');select.setAttribute('aria-label',company?'Choose your company':'Choose a political House');for(const r of records){const option=el('option',r.name);option.value=r.id;select.append(option);}if(!records.length){const option=el('option','No verified organisation available');option.value='';select.append(option);}select.value=selected||'';select.disabled=!records.length;select.onchange=()=>{selected=select.value;const u=new URL(location.href);u.searchParams.set(company?'company':'office',selected);history.replaceState(null,'',u);render();};label.append(select);const selector=el('div',undefined,'organisation-switcher');selector.append(image(record?.emblem||fallback),label);selector.classList.add('organisation-sidebar-switcher');
|
||||
for(let i=0;i<groups.length;i++){const [heading,items]=groups[i],host=i<2?left:right,block=el('section',undefined,'category-block'),links=el('div',undefined,'category-links');block.append(el('div',heading,'category-heading'));for(const[id,title]of items){const a=el('a',title==='Subhouses'&&company?'Subsidiaries':title,'navitem');a.href='#'+prefix+'/'+id;a.dataset.menuHref=(company?outer+'/':outer+'/government.html')+a.getAttribute('href');if(id===page)a.setAttribute('aria-current','page');links.append(a);}block.append(links);host.append(block);}left.append(selector);
|
||||
for(let i=0;i<groups.length;i++){const [heading,items]=groups[i],host=i<2?left:right,block=el('section',undefined,'category-block'),links=el('div',undefined,'category-links');block.append(el('div',heading,'category-heading'));for(const[id,title]of items){if(company&&['jobs','naibs'].includes(id))continue;const a=el('a',title==='Subhouses'&&company?'Subsidiaries':title,'navitem');a.href='#'+prefix+'/'+id;a.dataset.menuHref=(company?outer+'/':outer+'/government.html')+a.getAttribute('href');if(id===page)a.setAttribute('aria-current','page');links.append(a);}block.append(links);host.append(block);}left.append(selector);
|
||||
const hero=el('header',undefined,'hero organisation-workspace-hero'),copy=el('div');copy.append(el('small',company?'SPACING GUILD · COMMERCIAL AFFAIRS':'IMPERIAL HOUSES · OFFICE DEEDS'),el('h1',record?.name||noun+' Dashboard'),el('p',company?'Your enterprise, its people and its next chapter.':'Protected Houses · membership follows current office deeds.'));hero.append(image(record?.emblem||fallback),copy);
|
||||
const cards=el('div',undefined,'cards'),card=el('article',undefined,'card full citizen-page-full'),host=el('div',undefined,'citizen-live-host clan-center');card.append(host);cards.append(card);content.replaceChildren(hero,cards);
|
||||
if(page==='events'){dispose=mountRealmEvents(host,{kind,scopeId:record.id});return;}
|
||||
if(page==='naibs'&&!company){dispose=mountNaibCouncil(host);return;}
|
||||
if(page==='elections'){dispose=mountElectionDesign(host,{context:company?'company':'citizen'});return;}
|
||||
if(page==='advertising'){dispose=mountAdvertisingDesign(host,{context:kind});return;}
|
||||
if(page==='directory'){dispose=mountOrganisationRegister(host,kind);return;}
|
||||
if(!record&&company){dispose=mountCompanyRegistration(host,{onCreated:id=>{const url=new URL(location.href);url.searchParams.set('company',id);url.hash='company/overview';location.assign(url.href);}});return;}
|
||||
if(!record){pending(host,'Your '+noun.toLowerCase()+' workspace',company?'No company is registered to you as founder or CEO.':'Political office membership could not be verified.');return;}
|
||||
if(page==='jobs'&&!company){dispose=mountPoliticalJobs(host,{officeKey:record.id});return;}
|
||||
const loadSettings=async()=>{const r=await fetch('/api/organisations/'+kind+'/'+encodeURIComponent(record.id)+'/settings',{credentials:'same-origin',cache:'no-store'});const data=await r.json();if(!r.ok)throw Error(data.message||'Settings unavailable.');return data;};
|
||||
const navigate={onMembers:()=>go('people'),onRequests:()=>go('applications')};
|
||||
if(page==='overview'&&(!company&&!route()&&location.hash&& !location.hash.startsWith('#household/'))){const old=location.hash.slice(1).split('/').at(-1);if(old&&!['politics-overview','dashboard'].includes(old)){dispose=mountPoliticsPage(host,old);return;}}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,3 @@
|
|||
import {startCPAuthentication} from './cp-v2-auth.mjs';import {createCPV2ContentPage,element as el} from './cp-v2-page-template.mjs';import {createUserAPI} from './cp-v2-user-api.mjs';
|
||||
const host=document.querySelector('#content'),id=new URL(location.href).searchParams.get('id'),controller=new AbortController(),api=createUserAPI(fetch,controller.signal);window.addEventListener('pagehide',()=>controller.abort(),{once:true});
|
||||
startCPAuthentication(async()=>{for(const selector of ['#portals','#sidebar','#sidebar-right','.mobile-tools'])document.querySelector(selector)?.setAttribute('hidden','');document.querySelector('.layout').style.display='block';const frame=createCPV2ContentPage({host,title:'Political role application',description:'Applications are free. Only acceptance creates a term-bound appointment deed.'});try{const data=await api.request('/api/jarvis/political-jobs/application?listing='+encodeURIComponent(id||'')),listing=data.listing;frame.status.hidden=true;frame.content.append(el('h3',listing.title),el('p',listing.owner),el('p',listing.description),el('p','Appointment expires '+new Date(data.expiresAt).toLocaleString('en-GB',{timeZone:'UTC'})+' UTC'));if(data.application||listing.state!=='open'||data.expiresAt<=Date.now()){frame.content.append(el('p',data.application?'Application: '+data.application:'This vacancy is closed.'));return;}const form=el('form',undefined,'jarvis-form'),label=el('label','Your application'),message=el('textarea'),consent=el('label'),check=el('input'),send=el('button','Apply'),status=el('p');message.maxLength=2000;message.rows=5;check.type='checkbox';check.required=true;send.type='submit';label.append(message);consent.append(check,el('span','Send this application. Appointment starts only after acceptance.'));form.append(label,consent,send,status);frame.content.append(form);form.onsubmit=async event=>{event.preventDefault();if(send.disabled||!form.reportValidity())return;send.disabled=true;try{await api.request('/api/jarvis/political-jobs/apply',{listingId:id,message:message.value,confirmed:check.checked});status.textContent='Application sent. The decision will arrive in your mailbox.';send.hidden=true;label.hidden=consent.hidden=true;}catch(error){status.textContent=error.message;send.disabled=false;}};}catch(error){frame.status.textContent=error.message;}});
|
||||
13
website/control-panel/public/cp-v2/cp-v2-political-jobs.mjs
Normal file
13
website/control-panel/public/cp-v2/cp-v2-political-jobs.mjs
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import {confirmAction} from './cp-v2-confirm.mjs';
|
||||
import {createCPV2Page,element as el} from './cp-v2-page-template.mjs';import {createUserAPI} from './cp-v2-user-api.mjs';
|
||||
export function mountPoliticalJobs(host,{officeKey,fetcher=fetch}={}){
|
||||
const controller=new AbortController(),api=createUserAPI(fetcher,controller.signal);let active=true,busy=false,data=null,pending=null;const mine=el('section'),post=el('section'),applications=el('section'),status=el('p','Loading office vacancies…');status.setAttribute('role','status');const frame=createCPV2Page({shellHost:host,title:'Office vacancies',description:'Publish roles, review applications and issue appointments through your current office deed.',artwork:'exchange-political-positions-v1.png',tabs:[{id:'mine',label:'My listings',content:mine},{id:'post',label:'Post a role',content:post},{id:'applications',label:'Applications',content:applications}]});frame.root.prepend(status);host.replaceChildren(frame.root);
|
||||
const field=(name,input)=>{const label=el('label',name);label.append(input);return label;};
|
||||
async function load(){try{data=await api.request('/api/jarvis/political-jobs?office='+encodeURIComponent(officeKey));if(!active)return;status.textContent=data.memberCount+' / '+data.limit+' members · public listings cost '+(data.priceMinor/100).toFixed(2)+' DM per place, payable by the officeholder.';draw();}catch(error){if(active)status.textContent=error.message;}}
|
||||
function draw(){mine.replaceChildren();for(const row of data.listings){const box=el('article',undefined,'organisation-settings-card'),link=el('a',row.title);link.href='/political-job?id='+encodeURIComponent(row.id);box.append(link,el('p',row.state+' · appointment ends '+new Date(row.expiresAt).toLocaleString('en-GB',{timeZone:'UTC'})));mine.append(box);}if(!data.listings.length)mine.append(el('p','No vacancies published.'));
|
||||
const form=el('form',undefined,'jarvis-form'),title=el('input'),message=el('textarea'),expires=el('input'),account=el('select'),check=el('input'),send=el('button','Publish vacancy'),feedback=el('p');title.maxLength=100;title.required=true;message.maxLength=1000;message.rows=4;message.required=true;expires.type='datetime-local';expires.required=true;expires.value=new Date(data.expiresAt).toISOString().slice(0,16);check.type='checkbox';check.required=true;send.type='submit';for(const row of data.accounts){const option=el('option',row.number+' · '+row.available+' DM available');option.value=row.id;account.append(option);}send.disabled=!data.accounts.length||data.memberCount>=data.limit;const promotion=el('fieldset'),channels=[];promotion.append(el('legend','Promotion'));for(const [id,name]of [['boards','Boards'],['discord','Discord']]){const input=el('input'),label=el('label');input.type='checkbox';input.value=id;input.disabled=!data.promotionChannels.includes(id);label.append(input,el('span',name));promotion.append(label);channels.push(input);}const consent=el('label');consent.append(check,el('span','Publish the role and reserve '+(data.priceMinor/100).toFixed(2)+' DM to Tax.'));form.append(field('Role title',title),field('Responsibilities and requirements',message),field('Appointment expiry · UTC',expires),field('My personal payment account',account),promotion,consent,send,feedback);post.replaceChildren(form);
|
||||
form.onsubmit=async event=>{event.preventDefault();if(busy||send.disabled||!form.reportValidity())return;pending||={officeKey,requestId:crypto.randomUUID(),title:title.value,message:message.value,expiresAt:Date.parse(expires.value+'Z'),sourceAccount:account.value,expectedPriceMinor:data.priceMinor,channels:channels.filter(c=>c.checked).map(c=>c.value),confirmed:check.checked};busy=true;send.disabled=true;try{await api.request('/api/jarvis/political-jobs/publish',pending);pending=null;await load();status.textContent='Vacancy published on Starport. No office authority is transferred by applying.';}catch(error){feedback.textContent=error.message;}finally{busy=false;send.disabled=false;}};
|
||||
applications.replaceChildren();for(const row of data.applications){const card=el('article',undefined,'organisation-settings-card');card.append(el('h4',row.username+' · '+(data.listings.find(l=>l.id===row.listing_id)?.title||'Vacancy')),el('p',row.message),el('strong',row.status));if(row.status==='pending')for(const [decision,label]of [['accept','Accept & appoint'],['decline','Decline']]){const button=el('button',label);button.type='button';button.onclick=async()=>{if(busy||!await confirmAction(label+'?',row.username+' · '+(decision==='accept'?'Issue the appointment deed and close this vacancy.':'Decline this application.')))return;busy=true;button.disabled=true;try{await api.request('/api/jarvis/political-jobs/review',{applicationId:row.id,decision,confirmed:true});await load();status.textContent=decision==='accept'?'Appointment deed issued; vacancy closed and decision mail queued.':'Decision recorded and mail queued.';}catch(error){status.textContent=error.message;}finally{busy=false;button.disabled=false;}};card.append(button);}applications.append(card);}if(!data.applications.length)applications.append(el('p','No applications recorded.'));
|
||||
}
|
||||
void load();return()=>{active=false;controller.abort();frame.root.remove();};
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue

Staff