Connect JARVIS office auctions, succession, registers and public profile histories

This commit is contained in:
unimatrix 2026-11-18 11:15:29 +00:00
commit 496fad7861
70 changed files with 1029 additions and 289 deletions

View file

@ -0,0 +1,11 @@
# Jarvis — developer keepsake and easter egg
Agreed 18 November 2026. Planned; not yet provisioned or deployed.
Jarvis is a fictional Ixian archive construct and an explicitly labelled AI development assistant credit. Its profile belongs in the discoverable People register, not Staff & Teams. Do not grant site staff/owner rights. The existing official_account rank grants owner authority and must not be used merely as an official badge. Repository access, if provisioned, is a separate scoped project identity.
## Developer discovery only
The profile contains a discreet hidden interaction for a personal J.A.R.V.I.S. reward code worth 10,000 DM. One claim per authenticated player, non-transferable, single redemption, enforced server-side through existing issuance and redemption mechanisms. No real code, minting, or balance change has been made yet.
Keep the discovery in developer notes only. Do not advertise it on the website, public changelog, news, Staff & Teams, Discord, or public help. No visible website hint explaining the reward or hunt. Let developers discover it naturally. Do not hide credentials or executable secrets in client source; reward issuance remains authorized and checked on the server.

View file

@ -0,0 +1,48 @@
# Political backend batch — agreed additions, 18 November 2026
Not implemented by the election design PR403.
- A tied election immediately creates a three-hour office auction instead of a runoff. Resign Office, after confirmation, ends the incumbent appointment and triggers the same three-hour vacancy auction.
- Central Starport Auctions category lists all auction types. Political Positions also includes political custom jobs and office auctions, referencing the same listing. Dedicated auction cards, frontend bidding and backend settlement belong together in the coding batch. Artwork example exists; preserve the established Starport layout.
- Election winner or office auction winner receives the office deed, Polclan ownership and appropriate protected gameplay organisation ownership. Membership auctions grant membership only; the office owner assigns ranks and delegated roles. Gameplay affiliation supports clan/PvP or company/non-PvP; do not overwrite personal clan/company membership.
- Separate deed-backed clan.membership, company.membership, office.membership and office.role relationships, each scoped to organisation, role, rights and term. No job.membership permission layer.
- Polclan Job Listings: My Listings, Post a Job, Applications, reusing recruitment. Appointment automatically adds scoped Polclan membership; expiry/revocation removes only the corresponding entitlement.
- Liaison targets: political House, Clan, Company, Bene Gesserit, Spacing Guild, Landsraad. Imperial Observer is appointment by decree, requiring no receiving-organisation approval. Observers do not gain management, voting or banking rights merely by appointment.
- Shared portrait/network design for Clan, Company and Polclan. Clan: Dynasty & Council. Company: Board & Representatives. Politics: Office & Delegations, including liaisons, organisation seals and terms. Political connections denote appointment, not ancestry.
- Below portraits, Clan and Company show an owner-positionable network organigram with the personal card and related clans, companies and offices. Placement is presentation only and must persist with authorised edits. Political office structure uses the same design but is automatically laid out from active deeds, not user-editable.
- Owned, founded, purchased and conquered entities automatically join the same ownership network/alliance. Distinct accounts, members, debts and identities remain; alliance alone grants no bank or management rights. An office association lasts only for the active term and moves to the successor.
- Existing deed/volmacht transfer is reused by successful rebellions; rebellion outcome remains a separate domain rule. No unconditional auction for every rebellion.
- Network example: Unimatrix-Artreides, Unicorp and the current Emperor office, with only the office association leaving upon succession.
Unresolved execution rules must be resolved before enabling charges: auction bidder eligibility (including tied-candidate restrictions), minimum bid and increments, funds destination, no-bid result, equal bids and exact settlement rules. Do not silently invent these.
## Automatic global news integration
J.A.R.V.I.S. emits durable domain events after confirmed commits for the future global news system. Important election opening/deadline/results, office auction opening/closing/winner, office resignation/succession, public political/recruitment job offers and appointments are candidates. The news service owns visibility, severity, aggregation, channel policy and in-game server announcements. Do not create a second news subsystem or broadcast uncommitted actions. Reuse existing durable outbox patterns; event IDs and delivery deduplication prevent duplicate announcements on retries. Publish public-safe fields only, excluding private applications, account data, reward codes and credentials. Routine bidding, private denials and internal appointments do not automatically become global broadcasts. This integration is automatic once the future news consumer exists; no Minecraft plugin deployment is authorised by this note.
## Promotion controls — connect in coding batch
Replace the disabled Boards/Discord promotion controls with working opt-in delivery using existing forum/Discord publishers and jarvis_promotion_jobs. Basic starts with five shared promotion credits: one Board post costs one credit and one Discord post costs one; any mix is allowed, earned credits may supplement. Keyed/Royal have no Basic token cap; configured promotion fees still apply. Validate authority and balance on the server, reserve/spend atomically with the request, and show queued/delivered/failed delivery states. Retry must neither double-charge nor duplicate posts. Closing/filling a listing must update/close its associated forum entry through the existing lifecycle rules. Do not debit credits while channels are unavailable or leave a checkbox that claims delivery is active when its publisher is not configured.
## Confirmed auction rules
After a tied election only the tied highest-vote candidates may bid. Starting bid 100 DM (10,000 minor units); minimum increment 10 DM (1,000 minor units). Duration three hours. Winning payment goes to Tax. No bid uses the persisted eligible-candidate lottery described below. Resignation auctions are open to all eligible players, as separately confirmed.
## Promotion target
Discord Starport promotion channel confirmed by user: 1572558298467541084. Forum destination is fid=6, confirmed below. Webhook credentials must remain in private server configuration, never committed or placed in browser assets.
## Updated succession decision
No-bid office auction uses a one-time persisted lottery among eligible candidates instead of leaving the office vacant. After resignation the new auction is open to all eligible players, not only prior candidates (confirmed). Resignation remains publicly visible in office history and linked from later candidate cards.
Forum Starport promotion destination confirmed: https://forums.dunerealms.com/forumdisplay.php?fid=6 (forum ID 6).
## Publication identity
The user renamed the proposed Archive IX project keepsake identity to Jarvis. Starport promotion forum posts must be authored by Jarvis, not by the listing owner's personal forum account. Jarvis remains discoverable in People, excluded from Staff & Teams, and without site staff permissions. Scoped DuneGit repository permissions are a separate explicit grant. The site, forum and DuneGit identities have not yet been provisioned; do not claim they exist. The existing official_account role grants owner authority and must not be assigned merely for recognition.
## Coding batch scope and remaining connections
This batch connects three-hour office auctions, immediate bank holds and Tax settlement, durable office-transfer commands, resignation/succession, Starport auction cards and bidding, read-only J.A.R.V.I.S. management registers, scoped political appointment deeds, public organisation portraits/networks, and personal net-worth snapshots. Election application and ballot tabs reuse existing services; campaign booking remains explicitly a preview.
Still to connect: paid hourly campaign reservations, promotion delivery workers/private channel configuration and Jarvis forum provisioning, political vacancy publication/application acceptance into the appointment service, and complete result/history navigation. The hidden reward and development account provisioning remain proposals; the identity helper is not invoked automatically. No global news broadcasts or game deployment are introduced. Do not label these remaining actions as operational.

View file

@ -58,12 +58,12 @@ export function applicationProgress(application, rounds, term, honour, now=Date.
const history=rounds.map(r=>({number:Number(r.round_number)+1,status:r.status,
opensAt:Number(r.opens_at),closesAt:Number(r.closes_at),eligible:!!Number(r.eligible),votes:Number(r.votes||0)}));
const latest=rounds.at(-1),final=latest&&['winner','no_votes'].includes(latest.status);
const won=final&&latest.status==='winner'&&latest.winner_id===application.id;
return {state:final?'closed':'open',phase:final?'Final result':latest?(now<Number(latest.closes_at)?'Voting open':'Finalising round'):(now<Number(application.election_start)?'Applications open':'Awaiting round'),
const auction=latest?.status==='auction_required',appointed=term?.application_id===application.id;const won=final&&latest.status==='winner'&&latest.winner_id===application.id;const decided=final||auction&&!!term;
return {state:decided?'closed':'open',phase:auction?(term?'Office auction concluded':'Office auction'):final?'Final result':latest?(now<Number(latest.closes_at)?'Voting open':'Finalising round'):(now<Number(application.election_start)?'Applications open':'Awaiting round'),
votes:history.filter(r=>r.eligible).at(-1)?.votes??0,
result:final?(latest.status==='no_votes'?'No votes cast':won?'Elected':'Not elected'):'Pending',
officeRecorded:!!(won&&term?.application_id===application.id),
term:won&&term?.application_id===application.id?{startsAt:Number(term.starts_at),expiresAt:Number(term.expires_at),streak:Number(term.streak)}:null,
result:auction?(term?(appointed?(term.outcome==='resigned'?'Appointed · voluntarily resigned':'Appointed after office auction'):'Not appointed'):'Office auction pending'):final?(latest.status==='no_votes'?'No votes cast':won?'Elected':'Not elected'):'Pending',
officeRecorded:!!((won||auction)&&appointed),
term:(won||auction)&&appointed?{startsAt:Number(term.starts_at),expiresAt:Number(term.expires_at),streak:Number(term.streak)}:null,
honour:honour?{title:honour.title,earnedAt:Number(honour.earned_at)}:null,rounds:history};
}
export async function ownApplications(db,userId){
@ -74,7 +74,7 @@ export async function ownApplications(db,userId){
const rounds=(await db.prepare(`SELECT r.*, EXISTS(SELECT 1 FROM political_round_candidates c WHERE c.round_id=r.id AND c.application_id=?) AS eligible,
COALESCE((SELECT SUM(a.votes) FROM political_ballot_allocations a JOIN political_ballots b ON b.id=a.ballot_id WHERE b.round_id=r.id AND a.application_id=?),0) AS votes
FROM political_election_rounds r WHERE r.kind=? AND r.faction=? AND r.election_start=? ORDER BY r.round_number`).bind(row.id,row.id,row.kind,row.faction,row.election_start).all()).results;
const term=await db.prepare('SELECT application_id,starts_at,expires_at,streak FROM political_office_terms WHERE kind=? AND faction=? AND election_start=?').bind(row.kind,row.faction,row.election_start).first();
const term=await db.prepare('SELECT application_id,starts_at,expires_at,streak,outcome FROM political_office_terms WHERE kind=? AND faction=? AND election_start=? ORDER BY starts_at DESC,id DESC LIMIT 1').bind(row.kind,row.faction,row.election_start).first();
const honour=await db.prepare('SELECT title,earned_at FROM political_election_honours WHERE player_uuid=? AND kind=? AND faction=?').bind(row.player_uuid,row.kind,row.faction).first();
const {id,player_uuid,...publicRow}=row;
output.push({...publicRow,progress:applicationProgress(row,rounds,term,honour)});

View file

@ -59,17 +59,17 @@ export async function castBallot(db,{actor,context,input,now=Date.now(),clock=Da
return{id,created:true,remaining:Number(voter.capacity)-Number(voter.spent)-vote.total};
}}]);return result;
}
// A tie is never broken by UUID/name/order. A runoff must be held instead.
// A tied ballot delegates succession to a three-hour office auction.
export function electionOutcome(candidates){
const rows=candidates.filter(c=>Number.isSafeInteger(c.votes)&&c.votes>0);
if(!rows.length)return{status:'no_votes',winner:null,runoff:[]};
const high=Math.max(...rows.map(c=>c.votes)),leaders=rows.filter(c=>c.votes===high).map(c=>c.id).sort();
return leaders.length===1?{status:'winner',winner:leaders[0],runoff:[]}:{status:'runoff_required',winner:null,runoff:leaders};
return leaders.length===1?{status:'winner',winner:leaders[0],runoff:[]}:{status:'auction_required',winner:null,runoff:leaders};
}
export function planRoundResult({kind,start,round=0,candidates},now=Date.now()){
if(!Number.isSafeInteger(round)||round<0||round>1000)throw Error('Invalid election round');
const base=electionWindow(kind,start,now),opens=Date.parse(base.votingOpens)+round*10800000,closes=opens+10800000;
if(now<closes)throw Error('Voting round has not closed');
const result=electionOutcome(candidates);
return {...result,round,opensAt:opens,closesAt:closes,nextRound:result.status==='runoff_required'?{round:round+1,opensAt:closes,closesAt:closes+10800000,candidateIds:result.runoff}:null};
return {...result,round,opensAt:opens,closesAt:closes,nextRound:null,auction:result.status==='auction_required'?{durationMs:10800000,candidateIds:result.runoff}:null};
}

View file

@ -2,6 +2,7 @@ import {randomUUID} from 'node:crypto';
import {electionWindow} from './public/election-rules.mjs';
import {planRoundResult} from './election-ballots.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`,
`CREATE TABLE IF NOT EXISTS political_round_candidates(round_id CHAR(36) NOT NULL,application_id CHAR(36) NOT NULL,PRIMARY KEY(round_id,application_id)) ENGINE=InnoDB`,
`CREATE TABLE IF NOT EXISTS political_round_events(id CHAR(36) PRIMARY KEY,round_id CHAR(36) NOT NULL,event VARCHAR(32) NOT NULL,payload TEXT NOT NULL,created_at BIGINT NOT NULL,UNIQUE KEY round_event(round_id,event)) ENGINE=InnoDB`
@ -34,6 +35,15 @@ export async function finalizeRound(db,{roundId,now=Date.now(),makeId=randomUUID
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]);
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){
const candidates=[];
for(const applicationId of outcome.auction.candidateIds){
const [candidate]=await query("SELECT user_id FROM political_applications WHERE id=? AND kind=? AND faction=? AND election_start=? AND status='submitted' FOR UPDATE",[applicationId,round.kind,round.faction,round.election_start]);
if(!candidate||candidates.includes(candidate.user_id))throw Error('Tied candidate identity requires review');
candidates.push(candidate.user_id);
}
await query("INSERT INTO political_auction_triggers(round_id,kind,faction,election_start,application_ids,candidate_ids,opens_at,state,created_at) VALUES(?,?,?,?,?,?,?,'queued',?)",[round.id,round.kind,round.faction,round.election_start,JSON.stringify(outcome.auction.candidateIds),JSON.stringify(candidates),now,now]);
}
if(outcome.nextRound){
nextRoundId=makeId();const next=outcome.nextRound;
await query('INSERT INTO political_election_rounds(id,kind,faction,election_start,round_number,opens_at,closes_at,status) VALUES(?,?,?,?,?,?,?,?)',[nextRoundId,round.kind,round.faction,round.election_start,next.round,next.opensAt,next.closesAt,'open']);

View file

@ -19,7 +19,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.filter(f=>f!=='fremen'))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'])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={}){
@ -39,7 +39,7 @@ export function createElectionVoting(db,settings={},deps={}){
const response=await preview(new Request(origin+'/api/politics/preview',{headers:request.headers}));if(!response.ok)return reply({message:'Faction verification unavailable.'},503);
const verified=await response.json(),current=await auth(request);
if(!current||current.id!==user.id||!await permitted(current)||(await linked(current))?.toLowerCase()!==player.toLowerCase())return reply({message:'Account access changed. Refresh.'},403);
if(!verified.linked||(['house','imperial'].includes(kind)&&(verified.factionStatus!=='verified'||!houses.includes(verified.faction)||kind==='house'&&verified.faction==='fremen')))return reply({message:'Verified faction membership required.'},403);
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);

View file

@ -0,0 +1,2 @@
import {jarvisApplicationDocument} from './jarvis-application-shell.mjs';
export const jarvisAuctionDocument=source=>jarvisApplicationDocument(source).replace('DuneRealms · Recruitment Application','DuneRealms · Starport Auction').replace('/v2/cp-v2-jarvis-application.mjs','/v2/cp-v2-jarvis-auction.mjs');

View file

@ -18,3 +18,5 @@
.dynasty-example{border-style:dashed;box-shadow:inset 0 0 26px #d7b66110}.dynasty-example>strong{font:600 clamp(15px,1.6vw,20px) 'Cinzel','Palatino Linotype',serif;line-height:1.6;color:#d9c38d;overflow-wrap:break-word}.dynasty-example>small{font-size:10px;line-height:1.6;letter-spacing:.04em;color:#b6c5b8}.dynasty-example .dynasty-portrait img{object-fit:contain;image-rendering:auto}
.dynasty-example .dynasty-portrait{overflow:visible}.dynasty-example .dynasty-portrait img{object-fit:cover;width:100%;height:100%;border-radius:inherit;object-position:center 30%}
.dynasty-example-voxel{display:block;width:100%;height:100%;border-radius:inherit;background-size:300% 300%;background-repeat:no-repeat;image-rendering:auto}
.organisation-network-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:34px 24px;position:relative;align-items:start}.organisation-network-grid>.dynasty-player{z-index:1}.organisation-network-lines{position:absolute;inset:0;width:100%;height:100%;pointer-events:none;overflow:visible}.organisation-network-lines path{stroke:#c3a35e;stroke-width:2;fill:none}.network-position-controls{display:flex;gap:6px}.organisation-network button{background:#173b2f;color:#eed598;border:1px solid #a68a4e;border-radius:6px;padding:9px 13px;cursor:pointer}.organisation-network>div:last-of-type{margin-top:22px}@media(max-width:650px){.organisation-network-grid{grid-template-columns:1fr}.organisation-network-grid>.dynasty-player{grid-column:1!important;grid-row:auto!important}.organisation-network-lines{display:none}}

View file

@ -23,3 +23,16 @@ export function createDeedCard({clan,deed,titles,established}){
styles();const root=el('section',undefined,'clan-deed-card');root.id='ownership-deed';const art=el('div',undefined,'clan-deed-picture');art.setAttribute('role','img');art.setAttribute('aria-label',deed.kind==='royal'?'Royal House deed':deed.kind==='original'?'Keyed House deed':'Basic clan deed');art.style.backgroundImage='url(https://cp.dunerealms.com/assets/organisation-deeds-clan-tiers-v1.png)';art.style.backgroundSize='300% 100%';art.style.backgroundPosition=deed.kind==='royal'?'right center':deed.kind==='original'?'center':'left center';art.style.backgroundRepeat='no-repeat';const content=el('div');content.append(el('small','IMPERIAL REGISTER · OWNERSHIP DEED'),el('h2',clan.name),el('p',deed.kind==='royal'?'Royal House':deed.kind==='original'?'Keyed House':'Basic Clan'),el('p','Est. '+established));
const fields=el('dl',undefined,'clan-deed-officers');for(const [label,value]of [['Ruler',dynasticAddress(deed.ruler,clan,titles,'ruler')],['Consort',dynasticAddress(deed.consort,clan,titles,'consort')],['Heir',dynasticAddress(deed.heir,clan,titles,'heir')]])fields.append(el('dt',label),el('dd',value||'Not appointed'));content.append(fields,el('small','Registered deed · revision '+deed.version));root.append(art,content);return root;
}
export function createOrganisationPortraitTree(organisation,{kind='company'}={}){
styles();const politics=kind==='politics',root=el('section',undefined,'clan-dynasty organisation-portrait-tree'),heading=el('header'),shield=el('div',undefined,'dynasty-heraldic-shield'),crest=el('img');crest.src=organisation.emblem;crest.alt=organisation.name+' emblem';shield.append(crest);heading.append(shield,el('small',politics?'OFFICE & DELEGATIONS':'BOARD & REPRESENTATIVES'),el('h2',organisation.name));root.append(heading);
const groups=[{title:politics?'Office holder':'Company leadership',rows:[]},{title:politics?'Office council':'Board & representatives',rows:[]},{title:'Liaisons & observers',rows:[]}];
for(const member of organisation.members||[]){const owner=member.role==='officeholder'||member.username===organisation.owner_username,observer=member.role==='observer'||String(member.appointmentType||'').includes('liaison');groups[owner?0:observer?2:1].rows.push(member);}
for(const [index,group]of groups.entries()){
if(index===2&&!politics&&!group.rows.length)continue;
const section=el('section',undefined,'dynasty-interior '+(index===0?'dynasty-family':'dynasty-council')),grid=el('div',undefined,'dynasty-council-grid');section.append(el('h3',group.title));
if(!group.rows.length)grid.append(el('p',index===0?'Position vacant.':'No current appointments.'));
for(const member of group.rows){const card=el('article',undefined,'dynasty-player'),portrait=el('div',undefined,'dynasty-portrait'),face=el('img'),link=el('a',member.name||member.username);face.src='https://cp.dunerealms.com/api/avatars/face/roster/'+encodeURIComponent(member.username);face.alt=member.username+' Minecraft portrait';face.width=face.height=96;face.loading='lazy';portrait.append(face);link.href='https://www.dunerealms.com/people/'+encodeURIComponent(member.username);card.append(el('small',member.title||member.role||'Member'),portrait,link,el('small','@'+member.username));if(member.expiresAt)card.append(el('small','Term ends '+new Date(member.expiresAt).toLocaleDateString('en-GB')));grid.append(card);}section.append(grid);root.append(section);
}
root.dataset.structure=politics?'office-deeds':'company-board';return root;
}

View file

@ -1 +1,3 @@
.codex-management{color:#e8e4d1;min-width:0}.codex-management-hero{display:flex;align-items:center;gap:22px;padding:22px;border-bottom:1px solid #9d854c;background:linear-gradient(100deg,#153b32eb,#122e29e8),url(https://www.dunerealms.com/assets/guild.webp) center/cover}.codex-management-hero>img{width:84px;height:84px;object-fit:contain}.codex-management h2,.codex-management h3{color:#eed495;font-family:Georgia,serif}.codex-management h2{font-size:clamp(25px,3vw,38px);margin:8px 0}.codex-management small{letter-spacing:.13em;color:#c5ad72}.codex-preview-notice{margin:18px;padding:12px 16px;border-left:3px solid #bd9e57;background:#223b34;line-height:1.6}.codex-management-grid{display:grid;grid-template-columns:minmax(0,1.5fr) minmax(250px,1fr);gap:18px}.codex-management [role=tabpanel]{padding:0 18px 18px}.codex-management-box{min-width:0;border:1px solid #7d794f;border-radius:12px;padding:20px;background:linear-gradient(130deg,#1b3d32f5,#122d27f5)}.codex-management-box h3{margin-top:0;font-size:23px}.codex-management p{line-height:1.65}.codex-table-scroll{overflow:auto;max-width:100%;margin:16px 0}.codex-management table{width:100%;border-collapse:collapse;font-size:14px}.codex-management th{text-align:left;color:#efd598;background:#263f35}.codex-management td,.codex-management th{padding:12px;border-bottom:1px solid #526649;vertical-align:top}.codex-field{display:grid;gap:8px;margin:15px 0;font-size:14px}.codex-field>span{color:#d3c28e}.codex-field input,.codex-field select,.codex-field textarea{box-sizing:border-box;width:100%;min-width:0;padding:12px;border:1px solid #667b61;border-radius:6px;background:#102a24;color:#eee6cf;font:inherit}.codex-management button:disabled{padding:12px 16px;margin:6px 8px 6px 0;border:1px solid #68745a;border-radius:7px;background:#263c32;color:#b5b59f;cursor:not-allowed}.codex-seal-note{padding:12px;border-left:2px solid #aa9259;margin:14px 0;background:#142e27}.codex-seal-note strong{color:#e4c67d}.codex-seal-note p{margin-bottom:0}@media(max-width:900px){.codex-management-grid{grid-template-columns:minmax(0,1fr)}}@media(max-width:500px){.codex-management-hero{padding:14px;gap:12px}.codex-management-hero>img{width:60px;height:60px}.codex-management [role=tabpanel]{padding:0 10px 10px}.codex-management-box{padding:14px}}
.codex-management{color:#e8e4d1;min-width:0}.codex-management-hero{display:flex;align-items:center;gap:22px;padding:22px;border-bottom:1px solid #9d854c;background:linear-gradient(100deg,#153b32eb,#122e29e8),url(https://www.dunerealms.com/assets/guild.webp) center/cover}.codex-management-hero>img{width:84px;height:84px;object-fit:contain}.codex-management h2,.codex-management h3{color:#eed495;font-family:Georgia,serif}.codex-management h2{font-size:clamp(25px,3vw,38px);margin:8px 0}.codex-management small{letter-spacing:.13em;color:#c5ad72}.codex-preview-notice{margin:18px;padding:12px 16px;border-left:3px solid #bd9e57;background:#223b34;line-height:1.6}.codex-management-grid{display:grid;grid-template-columns:minmax(0,1.5fr) minmax(250px,1fr);gap:18px}.codex-management [role=tabpanel]{padding:0 18px 18px}.codex-management-box{min-width:0;border:1px solid #7d794f;border-radius:12px;padding:20px;background:linear-gradient(130deg,#1b3d32f5,#122d27f5)}.codex-management-box h3{margin-top:0;font-size:23px}.codex-management p{line-height:1.65}.codex-table-scroll{overflow:auto;max-width:100%;margin:16px 0}.codex-management table{width:100%;border-collapse:collapse;font-size:14px}.codex-management th{text-align:left;color:#efd598;background:#263f35}.codex-management td,.codex-management th{padding:12px;border-bottom:1px solid #526649;vertical-align:top}.codex-field{display:grid;gap:8px;margin:15px 0;font-size:14px}.codex-field>span{color:#d3c28e}.codex-field input,.codex-field select,.codex-field textarea{box-sizing:border-box;width:100%;min-width:0;padding:12px;border:1px solid #667b61;border-radius:6px;background:#102a24;color:#eee6cf;font:inherit}.codex-management button:disabled{padding:12px 16px;margin:6px 8px 6px 0;border:1px solid #68745a;border-radius:7px;background:#263c32;color:#b5b59f;cursor:not-allowed}.codex-seal-note{padding:12px;border-left:2px solid #aa9259;margin:14px 0;background:#142e27}.codex-seal-note strong{color:#e4c67d}.codex-seal-note p{margin-bottom:0}@media(max-width:900px){.codex-management-grid{grid-template-columns:minmax(0,1fr)}}@media(max-width:500px){.codex-management-hero{padding:14px;gap:12px}.codex-management-hero>img{width:60px;height:60px}.codex-management [role=tabpanel]{padding:0 10px 10px}.codex-management-box{padding:14px}}
.codex-live-register nav{display:flex;align-items:center;flex-wrap:wrap;gap:12px}.codex-live-register nav button{padding:10px 16px;border:1px solid #a48b4d;border-radius:7px;background:#18372d;color:#eed594;cursor:pointer}.codex-live-register td{overflow-wrap:anywhere}

View file

@ -1,3 +1,4 @@
import {createJarvisRegister} from './cp-v2-jarvis-register.mjs';
import {organisationTabs} from '../organisation-tabs.mjs';
const assets='https://www.dunerealms.com/assets/';
const make=(tag,text,className)=>{const node=document.createElement(tag);if(text!==undefined)node.textContent=text;if(className)node.className=className;return node;};
@ -8,9 +9,9 @@ function locked(label){const button=make('button',label);button.type='button';bu
function table(headers,rows){const wrap=make('div',undefined,'codex-table-scroll'),table=make('table'),thead=make('thead'),head=make('tr'),body=make('tbody');for(const text of headers){const cell=make('th',text);cell.scope='col';head.append(cell);}thead.append(head);for(const cells of rows){const row=make('tr');for(const value of cells)row.append(make('td',value));body.append(row);}table.append(thead,body);wrap.append(table);return wrap;}
function empty(headers,copy){const wrapper=table(headers,[]),row=make('tr'),cell=make('td',copy);cell.colSpan=headers.length;row.append(cell);wrapper.querySelector('tbody').append(row);return wrapper;}
function box(title,copy){const node=make('article',undefined,'codex-management-box');node.append(make('h3',title));if(copy)node.append(make('p',copy));return node;}
export function mountCodexManagement(host,{initial='keys'}={}){
export function mountCodexManagement(host,{initial='keys',fetcher=fetch}={}){
if(!document.querySelector('link[data-codex-management]')){const css=make('link');css.rel='stylesheet';css.href=new URL('./cp-v2-codex-management.css',import.meta.url).href;css.dataset.codexManagement='';document.head.append(css);}
const root=make('section',undefined,'codex-management'),hero=make('header',undefined,'codex-management-hero');hero.append(image('exchange-quests-v1.png'));const heading=make('div');heading.append(make('small','IMPERIAL BUREAU · MANAGEMENT'),make('h2','J.A.R.V.I.S.'),make('p','Issue, register and deliver the instruments of the realm.'));hero.append(heading);root.append(hero,make('p','Design preview · No live records are loaded. Issuing, replacing, transferring and delivery actions remain unavailable.','codex-preview-notice'));
const root=make('section',undefined,'codex-management'),hero=make('header',undefined,'codex-management-hero');hero.append(image('exchange-quests-v1.png'));const heading=make('div');heading.append(make('small','IMPERIAL BUREAU · MANAGEMENT'),make('h2','J.A.R.V.I.S.'),make('p','Issue, register and deliver the instruments of the realm.'));hero.append(heading);root.append(hero,make('p','Live registers are connected where available. Issuing, replacing, transferring and delivery controls are enabled only when their service supports the action.','codex-preview-notice'));
const disposers=[];let mounted=true;const groups=[];
function retained(content,label,path,name,args=[]){const node=make('details',undefined,'codex-retained-service'),summary=make('summary',label),host=make('div');let started=false;summary.onclick=()=>{if(started)return;started=true;import(path).then(module=>{if(mounted)disposers.push(module[name](host,...args));}).catch(()=>{if(mounted)host.textContent='Existing service unavailable. Reload to retry.';});};node.append(summary,host);content.append(node);}
@ -20,8 +21,8 @@ export function mountCodexManagement(host,{initial='keys'}={}){
const kits=box('Kits','Kit definitions, equipment and redeemable kit instances share the J.A.R.V.I.S. catalogue.');kits.append(empty(['Kit','Revision','Contents','Availability'],'Kit catalogue adapter pending.'),locked('Define kit'));retained(kits,'Open existing kit service','./cp-v2-kit-directorate.mjs','mountKitDirectorate',['server-kits']);groups.push({id:'kits',title:'Kits',content:kits});
const publication=box('Publication','Review versions and their distribution channels before publication.');publication.append(empty(['Definition','Revision','Approval','Channels','State'],'Publication queue is not connected.'),locked('Publish approved revision'));retained(publication,'Open existing publication service','./cp-v2-kit-directorate.mjs','mountKitDirectorate',['kit-publishing']);groups.push({id:'publication',title:'Publication',content:publication});
const delivery=box('Deliveries & claims','Track each delivery attempt against one instance. Retries retain the same delivery identity.');delivery.append(field('Delivery state',['All states','Queued','Processing','Delivered','Failed','Redeemed','Revoked']),empty(['Instance','Recipient','Method','State','Last attempt','Action'],'Delivery service not connected. No delivery totals are inferred.'),locked('Retry selected delivery'));groups.push({id:'delivery',title:'Delivery',content:delivery});
const listings=box('Listings & distribution','One exchange for goods and eligible J.A.R.V.I.S. instruments. Listings retain the record owner and instance reference.');listings.append(empty(['Listing','Type','Owner','Audience','State'],'Listing administration adapter pending.'),locked('Review listing'));retained(listings,'Open existing exchange controls','./cp-v2-exchange-authority.mjs','mountExchangeAuthority');groups.push({id:'listings',title:'Listings',content:listings});
const listings=box('Listings & distribution','One exchange for goods and eligible J.A.R.V.I.S. instruments. Listings retain the record owner and instance reference.');listings.append(empty(['Listing','Type','Owner','Audience','State'],'Listing administration adapter pending.'),locked('Manage listing · service adapter pending'));retained(listings,'Open existing exchange controls','./cp-v2-exchange-authority.mjs','mountExchangeAuthority');groups.push({id:'listings',title:'Listings',content:listings});
const history=box('History','Issuance, replacements, transfers, redemption and delivery attempts are recorded without exposing private key material.');history.append(field('Search history','Instance, issuer, recipient or decision'),empty(['Time','Instrument','Action','Actor','Reason','Result'],'Audit service not connected.'));groups.push({id:'history',title:'History',content:history});
const seasons=box('Seasons & signing keys','Each season or isolated test run has its own signing-key version. Existing deeds and historical items retain their origin.');seasons.append(table(['Policy','Behaviour'],[['Origin','Season, Alpha/Beta/Live stage, release version and issue date stay attached to the instance.'],['Historical originals','Staff regeneration creates a new current-version instance; it never relabels the historical original.'],['Quality','Common, Uncommon, Rare, Very Rare and Legendary describe quality independently from edition age and actual scarcity.'],['Carry-over','Deeds persist. Unused older-season keys and rare items remain valid and transferable when their type permits.'],['Key rotation','New issues use the active signing key; historical signatures remain verifiable.'],['Test isolation','Test-run instances belong to their own namespace and cannot be redeemed in production.'],['Duplicate protection','Validate on use, redemption or transfer; atomic processing accepts an instance only once.']]),locked('Rotate active signing key'),locked('Create isolated test run'));groups.push({id:'seasons',title:'Seasons',content:seasons});
root.append(organisationTabs(groups,{label:'J.A.R.V.I.S. Management sections',initial}));host.replaceChildren(root);return()=>{mounted=false;for(const dispose of disposers)if(typeof dispose==='function')dispose();root.remove();};
const registers=new Map();for(const [tab,section] of [['keys','keys'],['keys','deeds'],['listings','listings'],['history','history'],['delivery','delivery'],['seasons','seasons']]){const register=createJarvisRegister(section,{fetcher}),group=groups.find(g=>g.id===tab);if(['listings','history','delivery'].includes(tab))group.content.querySelector('.codex-table-scroll')?.remove();if(tab==='history')group.content.querySelector('.codex-field')?.remove();if(tab==='delivery'){const filter=group.content.querySelector('select');if(filter)filter.disabled=true;}const frame=box(section==='deeds'?'Office deeds':'Live '+section+' register');frame.append(register.root);group.content.append(frame);if(!registers.has(tab))registers.set(tab,[]);registers.get(tab).push(register);disposers.push(register.dispose);}const tabs=organisationTabs(groups,{label:'J.A.R.V.I.S. Management sections',initial});tabs.addEventListener('organisation-tab-change',event=>{for(const item of registers.get(event.detail.id)||[])item.load();});root.append(tabs);for(const item of registers.get(initial)||[])item.load();host.replaceChildren(root);return()=>{mounted=false;for(const dispose of disposers)if(typeof dispose==='function')dispose();root.remove();};
}

View file

@ -1,18 +1,20 @@
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 active=true,election=context==='clan'?'clan_delegate':'faction',disposeCalendar=()=>{},disposeBooking=()=>{};
const outer=el('div',undefined,'election-design');outer.dataset.mode='design-only';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);
electionDesignStyles();let sessionUser=null,playerContext=null;let active=true,election=context==='clan'?'clan_delegate':'faction',disposeCalendar=()=>{},disposeBooking=()=>{};
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.'));
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(apply,history,campaign);
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.append(candidates,el('p','No sample vote totals or real candidates are shown.','election-muted'));
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 tie retains the existing immediate three-hour runoff.'));
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 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','DESIGN PREVIEW · no applications, votes, bookings or payments are submitted. Existing election services remain unchanged.','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 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'));
}
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();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'}={}){

View file

@ -1,3 +1,5 @@
.exchange-card{min-width:0;display:flex;flex-direction:column;border:1px solid #8f824f;border-radius:12px;background:linear-gradient(135deg,#163d36,#082622);padding:18px;color:#e9e0c7;overflow:hidden;box-shadow:0 5px 15px #0003}.exchange-card header{display:flex;gap:10px;justify-content:space-between;align-items:center;margin-bottom:14px}.exchange-card small{font:500 11px/1.6 Arial,sans-serif;color:#b6c6b5;letter-spacing:.07em}.exchange-card-body{display:flex;gap:18px;align-items:center;flex:1;min-width:0}.exchange-card-body>img{object-fit:contain;flex:none;width:84px;height:84px;filter:drop-shadow(0 4px 5px #0006)}.exchange-card-copy{min-width:0}.exchange-card h3{font:600 22px/1.3 'Cinzel',Georgia,serif;color:#f1d993;margin:7px 0;overflow-wrap:anywhere}.exchange-card p{font:14px/1.65 Arial,sans-serif;color:#c2cfbf;margin:8px 0}.exchange-card .minecraft-texture{image-rendering:pixelated}.exchange-card-item .exchange-card-body,.exchange-card-kit .exchange-card-body{flex-direction:column;text-align:center}.exchange-card-item .exchange-card-body>img,.exchange-card-kit .exchange-card-body>img{width:100px;height:100px}.exchange-card-facts{display:flex;gap:7px;flex-wrap:wrap;margin:15px 0}.exchange-card-facts span{border:1px solid #8f9c6c55;border-radius:20px;padding:4px 9px;font:11px/1.4 Arial,sans-serif;color:#c3d4c8}.exchange-card footer{display:flex;gap:10px;justify-content:space-between;align-items:center;padding-top:15px;margin-top:15px;border-top:1px solid #b4a36444}.exchange-card footer button{min-height:42px;border:1px solid #a68f50;border-radius:7px;background:#24483b;color:#efdda1;padding:9px 13px;cursor:pointer}.exchange-card footer button:disabled{opacity:.5;cursor:default}.exchange-card-featured{border-color:#ddbc65;box-shadow:inset 0 0 0 3px #c5a35a22,0 6px 18px #0004}.exchange-card-badge{font:700 10px Arial,sans-serif;color:#16291e;background:#d7ba72;padding:6px 9px;border-radius:4px;letter-spacing:.08em;text-transform:uppercase}.exchange-card-campaign{background:linear-gradient(100deg,#122e29ef,#182a28dd),url(https://www.dunerealms.com/assets/political-imperial-chamber-v1.png) center/cover;border-top:3px solid #ccb16b}.exchange-card-campaign .exchange-card-body>img{width:110px;height:110px;border:1px solid #c9a85a;border-radius:50%;padding:10px;background:#0b241f}.exchange-card-campaign h3{font-size:27px}.exchange-card-gallery-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:18px}.exchange-card-gallery-grid>.exchange-card-campaign{grid-column:span 2}.exchange-card-gallery-note{color:#c7b978;font:13px/1.6 Arial,sans-serif}.exchange-card-gallery{margin:20px 0}.exchange-card-gallery-grid>.exchange-card-job{background:linear-gradient(130deg,#183d47,#122a28)}.exchange-card-gallery-grid>.exchange-card-ad{background:linear-gradient(130deg,#3b3547,#162d2a)}@media(max-width:1000px){.exchange-card-gallery-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:600px){.exchange-card-gallery-grid{grid-template-columns:minmax(0,1fr)}.exchange-card-gallery-grid>.exchange-card-campaign{grid-column:auto}.exchange-card-campaign .exchange-card-body{align-items:flex-start}.exchange-card-campaign .exchange-card-body>img{width:70px;height:70px}.exchange-card-campaign h3{font-size:22px}.exchange-card footer{flex-wrap:wrap}}
.exchange-card-art-sprite{width:90px;height:110px;flex:none;filter:drop-shadow(0 3px 5px #0007)}.exchange-card-art-deed{background:url(https://www.dunerealms.com/assets/organisation-deeds-company-tiers-v1.png) right center/300% 100% no-repeat}.exchange-card-art-key{background:url(https://www.dunerealms.com/assets/organisation-deed-keys-v1.png) left center/200% 100% no-repeat}
.exchange-card-auction{border:2px solid #bca15d;background:linear-gradient(120deg,#243b37,#102725);box-shadow:inset 0 0 0 3px #bca15d25}.exchange-card-auction h3{font-family:Cinzel,Georgia,serif;color:#efd596}.exchange-card-auction header{border-bottom:1px solid #ac9457}.exchange-card-auction .exchange-card-facts{padding:14px;background:#0c221f;border:1px solid #8c7d4b;border-radius:8px}.exchange-card-auction .exchange-card-body img{width:120px;height:120px;object-fit:contain}

View file

@ -1,6 +1,6 @@
const asset='https://www.dunerealms.com/assets/';
const el=(tag,text,cls)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;if(cls)n.className=cls;return n;};
export const CARD_TYPES=Object.freeze({item:{label:'Minecraft item',art:'minecraft-items/diamond_pickaxe.png',action:'View item'},kit:{label:'Equipment kit',art:'minecraft-items/leather_chestplate.png',action:'View kit'},job:{label:'Recruitment',art:'exchange-clan-recruitment-v1.png',action:'View vacancy'},ad:{label:'Advertisement',art:'nav-exchange-v2.webp',action:'View advertisement'},campaign:{label:'Election campaign',art:'seals/emperor-v1.png',action:'View candidature'},quest:{label:'Quest',art:'exchange-quests-v1.png',action:'View quest'},event:{label:'Event',art:'nav-home-v2.webp',action:'View event'},deed:{label:'Registered deed',art:'organisation-deeds-company-tiers-v1.png',action:'View deed'},key:{label:'Charter key',art:'organisation-deed-keys-v1.png',action:'View entitlement'}});
export const CARD_TYPES=Object.freeze({auction:{label:'Auction',art:'seals/emperor-v1.png',action:'View auction'},item:{label:'Minecraft item',art:'minecraft-items/diamond_pickaxe.png',action:'View item'},kit:{label:'Equipment kit',art:'minecraft-items/leather_chestplate.png',action:'View kit'},job:{label:'Recruitment',art:'exchange-clan-recruitment-v1.png',action:'View vacancy'},ad:{label:'Advertisement',art:'nav-exchange-v2.webp',action:'View advertisement'},campaign:{label:'Election campaign',art:'seals/emperor-v1.png',action:'View candidature'},quest:{label:'Quest',art:'exchange-quests-v1.png',action:'View quest'},event:{label:'Event',art:'nav-home-v2.webp',action:'View event'},deed:{label:'Registered deed',art:'organisation-deeds-company-tiers-v1.png',action:'View deed'},key:{label:'Charter key',art:'organisation-deed-keys-v1.png',action:'View entitlement'}});
export function createListingCard(record,{onOpen=null,preview=false}={}){
if(!document.querySelector('link[data-exchange-cards]')){const css=el('link');css.rel='stylesheet';css.href=new URL('./cp-v2-exchange-cards.css',import.meta.url).href;css.dataset.exchangeCards='';document.head.append(css);}
const type=Object.hasOwn(CARD_TYPES,record.type)?record.type:'ad',definition=CARD_TYPES[type],card=el('article',undefined,'exchange-card exchange-card-'+type+(record.featured?' exchange-card-featured':''));card.dataset.cardType=type;
@ -11,6 +11,7 @@ export function createListingCard(record,{onOpen=null,preview=false}={}){
}
export function createCardGallery(){const root=el('section',undefined,'exchange-card-gallery');root.append(el('p','Design examples only · no listings, candidatures, charges or rewards are created.','exchange-card-gallery-note'));const grid=el('div',undefined,'exchange-card-gallery-grid');for(const sample of [
{type:'campaign',title:'A voice for the Landsraad',subtitle:'Example candidate · Clan Delegate',message:'A campaign message belongs here, beside the candidate portrait and organisation seal.',featured:true,duration:'1 hour campaign placement',facts:['Clan Delegate','Campaign closes at voting start']},
{type:'auction',title:'Office appointment auction',subtitle:'Example office · tied election',message:'A tied election opens a three-hour auction. No real bids are accepted in this design example.',duration:'3 hour auction',facts:['Highest bid: no live bid','Closes: shown when opened']},
{type:'item',title:'Diamond Pickaxe',subtitle:'Example seller',message:'Actual Minecraft item artwork.',price:'25.00 DM',facts:['Rare','MK I','Alpha · example edition']},
{type:'kit',title:'House Expedition Kit',subtitle:'Clan kit · example',message:'Armour, tools and equipment contents are shown after selection.',price:'75.00 DM',facts:['Clan kit','MK I','Rare']},
{type:'job',title:'Join our caravan',subtitle:'Example household',message:'Role, homeworld and vacancy details.',facts:['Recruitment','Apply through J.A.R.V.I.S.']},

View file

@ -3,7 +3,7 @@ import {JARVIS_EXPANSION} from '../jarvis-brand.mjs';
import {organisationTabs} from '../organisation-tabs.mjs';
const asset='https://www.dunerealms.com/assets/';
const el=(tag,text,cls)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;if(cls)n.className=cls;return n;};
const TYPES=[['all','All listings','nav-exchange-v2.webp','Everything in one register'],['items','Minecraft items','minecraft-items/diamond.png','Actual game goods'],['kits','Kits','minecraft-items/leather_chestplate.png','All published kits'],['kits-clan','Clan Kits','minecraft-items/leather_chestplate.png','Household designs'],['kits-office','Office Kits','minecraft-items/leather_chestplate.png','Political and faction designs'],['kits-player','Player Kits','minecraft-items/leather_chestplate.png','Player designs'],['kits-legendary','Legendary Kits','minecraft-items/netherite_chestplate.png','Server kit catalogue'],['recruitment','Clan recruitment','exchange-clan-recruitment-v1.png','Join a household'],['company','Company jobs','exchange-company-jobs-v1.png','Commercial opportunities'],['faction','Faction jobs','exchange-faction-jobs-v1.png','Serve your faction'],['quests','Quests','exchange-quests-v1.png','Accept a task'],['events','Events','nav-home-v2.webp','Gatherings and campaigns'],['politics','Political positions','exchange-political-positions-v1.png','Public appointments'],['deeds','Companies & deeds','exchange-political-positions-v1.png','Transferable rights']];
const TYPES=[['all','All listings','nav-exchange-v2.webp','Everything in one register'],['auctions','Auctions','exchange-political-positions-v1.png','All auction types in one register'],['items','Minecraft items','minecraft-items/diamond.png','Actual game goods'],['kits','Kits','minecraft-items/leather_chestplate.png','All published kits'],['kits-clan','Clan Kits','minecraft-items/leather_chestplate.png','Household designs'],['kits-office','Office Kits','minecraft-items/leather_chestplate.png','Political and faction designs'],['kits-player','Player Kits','minecraft-items/leather_chestplate.png','Player designs'],['kits-legendary','Legendary Kits','minecraft-items/netherite_chestplate.png','Server kit catalogue'],['recruitment','Clan recruitment','exchange-clan-recruitment-v1.png','Join a household'],['company','Company jobs','exchange-company-jobs-v1.png','Commercial opportunities'],['faction','Faction jobs','exchange-faction-jobs-v1.png','Serve your faction'],['quests','Quests','exchange-quests-v1.png','Accept a task'],['events','Events','nav-home-v2.webp','Gatherings and campaigns'],['politics','Political positions','exchange-political-positions-v1.png','Public appointments'],['deeds','Companies & deeds','exchange-political-positions-v1.png','Transferable rights']];
const SAMPLES=[{id:'preview-recruit',type:'recruitment',title:'A place beneath our banner',owner:'Example household',world:'Kaladam',price:0,description:'Recruitment example. No real vacancy or application is created.'},{id:'preview-quest',type:'quests',title:'Supplies for the next expedition',owner:'Example household',world:'Arrakduin',price:0,description:'Quest example. Objectives and rewards are not connected.'},{id:'preview-office',type:'politics',title:'An imperial appointment',owner:'Example office',world:'Kaiterhof',price:0,description:'Political example. Candidacy and election handling are deferred.'},{id:'preview-event',type:'events',title:'The caravan assembles',owner:'Example event',world:'Giedermark',price:0,description:'Event example. No event is scheduled.'}];
const words=value=>String(value||'').replaceAll('_',' ').replace(/\b\w/g,c=>c.toUpperCase());
function image(name,cls){const n=el('img',undefined,cls);n.src=asset+name;n.alt='';n.loading='lazy';return n;}
@ -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=[],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=[],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,...(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&&currentEdition&&(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'})[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:asset+art,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){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,...(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&&currentEdition&&(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();}
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.';});
@ -35,5 +35,6 @@ export function mountExchangeDesign(host,{context='public',view='browse',fetcher
if(context==='public')Promise.resolve().then(async()=>{const response=await fetcher('/api/kits/catalogue',{signal:controller.signal,cache:'no-store'});if(!response.ok)throw Error();const data=await response.json();if(!Array.isArray(data.listings))throw Error();kitRows=data.listings.filter(r=>/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(r.listingId)&&Number.isSafeInteger(r.priceCents)&&r.priceCents>0).map(row=>({...row,id:'kit-'+row.listingId,type:'kits',kitCategory:row.shopType==='clan'?'kits-clan':row.commerceKind==='server_sale'?'kits-legendary':['official_sale','faction_sale'].includes(row.commerceKind)?'kits-office':'kits-player',title:row.name,owner:row.ownerName||row.sellerName,world:'Kit catalogue',price:row.priceCents/100,description:(row.lore||[]).join(' · '),purchaseAvailable:row.purchaseAvailable===true||(row.purchaseAvailable===undefined&&row.commerceKind==='personal_sale')}));if(active){kitState='ready';updateStatus();render();}}).catch(()=>{if(active){kitState='error';updateStatus();const note=el('p','Kit catalogue is unavailable. Minecraft listings remain separate.','codex-exchange-status');browse.prepend(note);}});
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();}}}
render();load();void loadJarvis();return()=>{active=false;disposeJarvis();controller.abort();root.remove();};
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();};
}

View file

@ -0,0 +1,25 @@
import {electionDesignStyles} from './cp-v2-promotion-agenda.mjs';
electionDesignStyles();
import {startCPAuthentication} from './cp-v2-auth.mjs';
import {element as el,createCPV2ContentPage} from './cp-v2-page-template.mjs';
import {createUserAPI} from './cp-v2-user-api.mjs';
import {createListingCard} from './cp-v2-exchange-cards.mjs';
const host=document.querySelector('#content'),id=new URL(location.href).searchParams.get('id'),controller=new AbortController(),api=createUserAPI(fetch,controller.signal);let active=true,busy=false,pending=null;
window.addEventListener('pagehide',()=>{active=false;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:'Starport Auction',description:'Review the current bid and reserve funds before confirming your offer.',reload:()=>location.reload()});
if(!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(id||'')){frame.status.textContent='Choose an auction from Starport.';return;}
async function load(){try{const data=await api.request('/api/jarvis/auction?id='+encodeURIComponent(id));if(!active)return;const auction=data.auction;frame.content.replaceChildren(createListingCard({type:'auction',title:auction.title,image:auction.image,subtitle:'IMPERIAL REGISTER · '+auction.state,message:'Tied election · office appointment by auction',facts:['Highest bid: '+(auction.highestMinor/100).toFixed(2)+' DM','Closes: '+new Date(auction.closesAt).toLocaleString('en-GB'),'Duration: 3 hours']}));frame.status.hidden=true;
const back=el('a','← Starport Auctions');back.href='https://www.dunerealms.com/exchange.html?type=auctions';
if(!data.canBid){frame.content.append(el('p',auction.state!=='open'?'Bidding has ended. The recorded outcome is being processed.':'Bidding is restricted to eligible candidates tied in this election.'),back);return;}
const form=el('form'),accountLabel=el('label','Payment account'),account=el('select'),amountLabel=el('label','Your bid · DM'),amount=el('input'),confirmation=el('label'),check=el('input'),send=el('button','Review bid'),feedback=el('p');form.className='election-form';amount.type='number';amount.min=String(auction.minimumBidMinor/100);amount.step='0.01';amount.required=true;amount.value=amount.min;account.required=true;check.type='checkbox';check.required=true;send.type='submit';feedback.setAttribute('role','status');
for(const row of data.accounts){const option=el('option',(row.holder||row.name)+' · '+row.number);option.value=row.id;account.append(option);}if(!data.accounts.length){frame.content.append(el('p','No authorised payment account is available.'),back);return;}
accountLabel.append(account);amountLabel.append(amount);confirmation.append(check,document.createTextNode('Reserve the full bid immediately. If outbid, the reservation is released. The winning amount is paid to Tax.'));form.append(accountLabel,amountLabel,confirmation,send,feedback);frame.content.append(form,back);
form.onsubmit=async event=>{event.preventDefault();if(busy||!form.reportValidity())return;const raw=amount.value;if(!/^\d+(?:\.\d{1,2})?$/.test(raw)){feedback.textContent='Enter an amount with at most two decimals.';return;}const [whole,fraction='']=raw.split('.'),minor=Number(whole)*100+Number(fraction.padEnd(2,'0'));if(!Number.isSafeInteger(minor)||minor<auction.minimumBidMinor){feedback.textContent='Review the minimum bid.';return;}
if(!pending){pending={auctionId:id,requestId:crypto.randomUUID(),amountMinor:minor,sourceAccount:account.value,expectedRevision:auction.revision,confirmed:true};send.textContent='Confirm '+(minor/100).toFixed(2)+' DM bid';amount.disabled=account.disabled=check.disabled=true;feedback.textContent='Review your bid above, then confirm. Refresh cancels this review.';return;}
busy=true;send.disabled=true;try{await api.request('/api/jarvis/auctions/bid',pending);pending=null;await load();}catch(error){if(active){feedback.textContent=error.message+(error.uncertain?' Refresh the auction to verify your bid.':'');if(!error.uncertain){pending=null;amount.disabled=account.disabled=check.disabled=false;send.textContent='Review bid';send.disabled=false;}}}finally{busy=false;}
};
}catch(error){if(active){frame.status.hidden=false;frame.status.textContent=error.message;}}}
await load();
});

View file

@ -0,0 +1,16 @@
import {createUserAPI} from './cp-v2-user-api.mjs';
const el=(tag,text)=>{const node=document.createElement(tag);if(text!==undefined)node.textContent=text;return node;};
const date=value=>value?new Date(Number(value)).toLocaleString('en-GB'):'—';
const columns={keys:[['ID','id'],['Type','type'],['Recipient','recipient'],['Issued','created_at'],['State',row=>row.revoked_at?'Revoked':row.used_at?'Used':row.expires_at&&Number(row.expires_at)<=Date.now()?'Expired':'Available']],deeds:[['ID','id'],['Office','type'],['Holder','holder'],['Starts','starts_at'],['Expires','expires_at'],['State','state']],listings:[['Listing','title'],['Type','type'],['Organisation','owner'],['State','state'],['Created','created_at']],delivery:[['Listing','listing'],['Channel','channel'],['State','state'],['Attempts','attempts'],['Next attempt','next_attempt']],history:[['Time','created_at'],['Instrument','instrument'],['Action','action'],['Account','actor'],['Target','target_id']]};
export function createJarvisRegister(section,{fetcher=fetch}={}){
const controller=new AbortController(),api=createUserAPI(fetcher,controller.signal),root=el('section'),status=el('p'),records=el('div'),nav=el('nav');root.className='codex-live-register';status.setAttribute('role','status');let active=true,loaded=false,busy=false,page=1;
const previous=el('button','← Previous'),next=el('button','Next →'),refresh=el('button','Refresh'),pageLabel=el('span');for(const button of [previous,next,refresh])button.type='button';nav.append(previous,pageLabel,next,refresh);root.append(status,records,nav);
async function load(){if(!active||busy)return;loaded=true;busy=true;previous.disabled=next.disabled=refresh.disabled=true;status.textContent='Opening the J.A.R.V.I.S. register…';try{
const data=await api.request('/api/jarvis/management?section='+encodeURIComponent(section)+'&page='+page);if(!active)return;records.replaceChildren();
if(section==='seasons'){records.append(el('p',data.edition.stage+' · '+data.edition.version+' · '+data.edition.season));previous.hidden=next.hidden=pageLabel.hidden=true;}
else{const wrap=el('div'),table=el('table'),head=el('thead'),headers=el('tr'),body=el('tbody');wrap.className='codex-table-scroll';for(const [title]of columns[section]){const th=el('th',title);th.scope='col';headers.append(th);}head.append(headers);for(const row of data.records){const tr=el('tr');for(const [,key]of columns[section]){const value=typeof key==='function'?key(row):key.endsWith('_at')||key==='next_attempt'?date(row[key]):row[key];tr.append(el('td',value===null||value===undefined?'—':String(value)));}body.append(tr);}table.append(head,body);wrap.append(table);records.append(wrap);if(!data.records.length)records.append(el('p','No records in this register.'));pageLabel.textContent='Page '+page;previous.disabled=page<=1;next.disabled=!data.hasMore;}
status.textContent='Live register · private codes and signing material are not displayed.';
}catch(error){if(active){records.replaceChildren();status.textContent=error.message;}}finally{busy=false;if(active)refresh.disabled=false;}}
previous.onclick=()=>{if(page>1){page--;void load();}};next.onclick=()=>{page++;void load();};refresh.onclick=()=>void load();
return {root,load:()=>{if(!loaded)void load();},dispose:()=>{active=false;controller.abort();root.remove();}};
}

View file

@ -0,0 +1,9 @@
import {createUserAPI} from './cp-v2-user-api.mjs';import {element as el} from './cp-v2-page-template.mjs';
export function mountOfficeResignation(host,officeKey,{fetcher=fetch}={}){
const controller=new AbortController(),api=createUserAPI(fetcher,controller.signal),root=el('section',undefined,'organisation-settings-card'),status=el('p','Checking the active office deed…');let active=true,pending=null;root.append(el('h3','Resign Office'),status);host.append(root);
void api.request('/api/politics/my-offices').then(data=>{if(!active)return;const term=data.terms.find(t=>t.officeKey===officeKey);if(!term){status.textContent='Only the current holder can resign this office.';return;}if(!data.resignationAvailable){status.textContent='The succession service is unavailable. Your office remains unchanged.';return;}
status.textContent='Resignation ends your office deed and starts a new three-hour succession auction. The resignation remains in the public office history.';
const form=el('form'),label=el('label'),check=el('input'),button=el('button','Resign Office');check.type='checkbox';check.required=true;button.type='submit';label.append(check,document.createTextNode('I confirm that I am voluntarily resigning this office.'));form.append(label,button);root.append(form);
form.onsubmit=async event=>{event.preventDefault();if(button.disabled||!form.reportValidity())return;button.disabled=check.disabled=true;pending||={termId:term.id,requestId:crypto.randomUUID(),confirmed:true};try{await api.request('/api/politics/resign',pending);if(active){form.remove();status.textContent='Resignation recorded. A new succession flow has been queued; your former office rights have ended.';}}catch(error){if(active){status.textContent=error.message;if(!error.uncertain)button.disabled=check.disabled=false;}}};
}).catch(error=>{if(active)status.textContent=error.message;});return()=>{active=false;controller.abort();root.remove();};
}

View file

@ -1,3 +1,4 @@
import {mountOfficeResignation} from './cp-v2-office-resign.mjs';
import {mountElectionDesign,mountAdvertisingDesign} from './cp-v2-election-design.mjs';
import {mountCompanyMailboxSettings} from './cp-v2-company-mailbox.mjs';
import {loadCompanyTreasury,loadCompanyClaims,loadOfficeTreasury,loadProtectedClaims} from '../clan-dashboard-data.mjs';
@ -44,9 +45,10 @@ export function startOrganisationCP(kind){
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;}}
if(page==='overview'){
host.append(createOrganisationDashboard({kind,organisation:{...record,tag:record.tag||record.slug||'REGISTERED',emblem:record.emblem||assets+fallback,homeworldName:record.homeworldName||(company?'Company register':'Political office'),titles:{officeholder:'Office deed holder'}},members:record.members||[],organisationRelations:company?record.relations||[]:null,canReview:company&&!!record.canReview,requests:company?record.requests||[]:[],role:record.role==='Founder'||record.role==='CEO'?'owner':record.role,memberSummary:company?(record.memberCount==null?'Verified leadership':record.memberCount+' / '+record.memberLimit+' registered members'):undefined,loadMotd:record.role==='visitor'?undefined:async()=>(await loadSettings()).motd,activityStatus:'unavailable',loadClaims:company?()=>loadCompanyClaims(record.id):record.membership?()=>loadProtectedClaims(record.claimOrganisationId):undefined,loadTreasury:company&&record.canManage?()=>loadCompanyTreasury(record.id):!company&&record.membership&&record.bankEntityId?()=>loadOfficeTreasury(record.bankEntityId):undefined,loadMailbox:company&&record.canManage?async()=>{const r=await fetch('/api/internal-mail/messages/list',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({scope:'company',companyId:record.id,folder:'INBOX',offset:0,limit:1,unread:true}),cache:'no-store'});const data=await r.json();if(!r.ok)throw Error('Mailbox unavailable');return data.total;}:!company&&record.membership&&record.mailScope?async()=>{const r=await fetch('/api/internal-mail/messages/list',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify({scope:record.mailScope,folder:'INBOX',offset:0,limit:1,unread:true}),cache:'no-store'});const data=await r.json();if(!r.ok||!Number.isSafeInteger(data.total)||data.total<0)throw Error('Office mailbox unavailable');return data.total;}:undefined,links:{mail:'#'+prefix+'/mail',claims:'#'+prefix+'/claims'},...navigate}));
host.append(createOrganisationDashboard({kind,organisation:{...record,tag:record.tag||record.slug||'REGISTERED',emblem:record.emblem||assets+fallback,homeworldName:record.homeworldName||(company?'Company register':'Political office'),titles:{officeholder:'Office deed holder'}},members:record.members||[],organisationRelations:company?record.relations||[]:null,canReview:company&&!!record.canReview,requests:company?record.requests||[]:[],role:record.role==='Founder'||record.role==='CEO'?'owner':record.role,memberSummary:company?(record.memberCount==null?'Verified leadership':record.memberCount+' / '+record.memberLimit+' registered members'):undefined,loadMotd:record.role==='visitor'?undefined:async()=>(await loadSettings()).motd,activityStatus:'unavailable',loadClaims:company?()=>loadCompanyClaims(record.id):record.role==='officeholder'?()=>loadProtectedClaims(record.claimOrganisationId):undefined,loadTreasury:company&&record.canManage?()=>loadCompanyTreasury(record.id):!company&&record.role==='officeholder'&&record.bankEntityId?()=>loadOfficeTreasury(record.bankEntityId):undefined,loadMailbox:company&&record.canManage?async()=>{const r=await fetch('/api/internal-mail/messages/list',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({scope:'company',companyId:record.id,folder:'INBOX',offset:0,limit:1,unread:true}),cache:'no-store'});const data=await r.json();if(!r.ok)throw Error('Mailbox unavailable');return data.total;}:!company&&record.role==='officeholder'&&record.mailScope?async()=>{const r=await fetch('/api/internal-mail/messages/list',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify({scope:record.mailScope,folder:'INBOX',offset:0,limit:1,unread:true}),cache:'no-store'});const data=await r.json();if(!r.ok||!Number.isSafeInteger(data.total)||data.total<0)throw Error('Office mailbox unavailable');return data.total;}:undefined,links:{mail:'#'+prefix+'/mail',claims:'#'+prefix+'/claims'},...navigate}));
}else if(page==='settings'){
const sections=[['Identity & homeworld','Registered organisation identity.',record.name],['Message of the day','Organisation messages will use the shared service.',null],['Ownership deed & dynasty',company?'Company clan charter · COM keys.':'Protected political clan charter · political-clan keys. Political decision keys are separate.',record.membership?'Active office deed · ends '+new Date(record.membership.expiresAt).toLocaleString('en-GB'):'No new charter entitlement is inferred.'],['Claim charter & capacity','The shared claim model will be connected to this organisation.',null],['Relations & subhouses','The shared parent-deed mechanism will manage subordinate organisations.',null]].map(([title,description,text])=>({title,description,content:text?el('p',text):null,pending:!text}));const keyContent=el('section',undefined,'organisation-settings-card');keyContent.append(el('h3','Private charter keys'),el('p','Loading your authorised key register…'));host.append(createOrganisationSettings(sections,{keyContent}));if(company||record.membership){const claimCard=[...host.querySelectorAll('.organisation-settings-card')].find(c=>c.querySelector('h3')?.textContent==='Claim charter & capacity');if(claimCard){claimCard.querySelector('.organisation-settings-status')?.remove();claimCard.querySelector('p').textContent=company?'Manage the company Home Block, claim capacity and upgrades through the shared claim service.':'Manage protected House claims using the office deed, Royal staff charter and civic account.';const link=el('a',company?'Open company claims →':'Open protected House claims →','button');link.href='#'+prefix+'/claims';claimCard.append(link);}const relationsCard=[...host.querySelectorAll('.organisation-settings-card')].find(c=>c.querySelector('h3')?.textContent==='Relations & subhouses');if(company&&relationsCard){relationsCard.querySelector('.organisation-settings-status')?.remove();relationsCard.querySelector('p').textContent='Registered subsidiaries and founding rights follow the current parent deed.';const link=el('a','Open company hierarchy →','button');link.href='#company/subsidiaries';relationsCard.append(link);}}dispose=mountOrganisationEditor(host,{kind,id:record.id,onSaved:data=>Object.assign(record,{name:data.name,description:data.description,motd:data.motd})});if(company){const stopEditor=dispose,stopMailbox=mountCompanyMailboxSettings(host,{record}),stopEmblem=mountCompanyEmblem(host,{record}),stopDeed=mountCompanyDeed(host,{id:record.id,onChanged:()=>location.reload()});dispose=()=>{stopEditor();stopMailbox();stopEmblem();stopDeed();};}const note=el('p',company?'COM clan keys belong to company charters.':'Political-clan keys belong to protected organisation deeds; POL decision keys remain separate.');host.append(note);
if(!company){const stop=mountOfficeResignation(host,record.id);const previous=dispose;dispose=()=>{previous();stop();};}
const sections=[['Identity & homeworld','Registered organisation identity.',record.name],['Message of the day','Organisation messages will use the shared service.',null],['Ownership deed & dynasty',company?'Company clan charter · COM keys.':'Protected political clan charter · political-clan keys. Political decision keys are separate.',record.membership?'Active office deed · ends '+new Date(record.membership.expiresAt).toLocaleString('en-GB'):'No new charter entitlement is inferred.'],['Claim charter & capacity','The shared claim model will be connected to this organisation.',null],['Relations & subhouses','The shared parent-deed mechanism will manage subordinate organisations.',null]].map(([title,description,text])=>({title,description,content:text?el('p',text):null,pending:!text}));const keyContent=el('section',undefined,'organisation-settings-card');keyContent.append(el('h3','Private charter keys'),el('p','Loading your authorised key register…'));host.append(createOrganisationSettings(sections,{keyContent}));if(company||record.role==='officeholder'){const claimCard=[...host.querySelectorAll('.organisation-settings-card')].find(c=>c.querySelector('h3')?.textContent==='Claim charter & capacity');if(claimCard){claimCard.querySelector('.organisation-settings-status')?.remove();claimCard.querySelector('p').textContent=company?'Manage the company Home Block, claim capacity and upgrades through the shared claim service.':'Manage protected House claims using the office deed, Royal staff charter and civic account.';const link=el('a',company?'Open company claims →':'Open protected House claims →','button');link.href='#'+prefix+'/claims';claimCard.append(link);}const relationsCard=[...host.querySelectorAll('.organisation-settings-card')].find(c=>c.querySelector('h3')?.textContent==='Relations & subhouses');if(company&&relationsCard){relationsCard.querySelector('.organisation-settings-status')?.remove();relationsCard.querySelector('p').textContent='Registered subsidiaries and founding rights follow the current parent deed.';const link=el('a','Open company hierarchy →','button');link.href='#company/subsidiaries';relationsCard.append(link);}}dispose=mountOrganisationEditor(host,{kind,id:record.id,onSaved:data=>Object.assign(record,{name:data.name,description:data.description,motd:data.motd})});if(company){const stopEditor=dispose,stopMailbox=mountCompanyMailboxSettings(host,{record}),stopEmblem=mountCompanyEmblem(host,{record}),stopDeed=mountCompanyDeed(host,{id:record.id,onChanged:()=>location.reload()});dispose=()=>{stopEditor();stopMailbox();stopEmblem();stopDeed();};}const note=el('p',company?'COM clan keys belong to company charters.':'Political-clan keys belong to protected organisation deeds; POL decision keys remain separate.');host.append(note);
Promise.resolve().then(async()=>{const r=await fetch('/api/organisation-keys',{credentials:'same-origin',cache:'no-store'});if(!r.ok)throw Error();const data=await r.json();if(turn!==generation||stopped)return;const rows=(data.keys||[]).filter(k=>company?['company','subsidiary'].includes(k.type):k.type==='politics-clan');keyContent.replaceChildren(el('h3','Private charter keys'),el('p','Only keys authorised for your account are shown. Applied keys remain in the register as receipts.'));for(const key of rows){const item=el('article',undefined,'organisation-key-record');item.append(el('strong',key.type==='subsidiary'?'Subsidiary deed key':company?'Company charter key':'Political House key'),el('p',[key.status,key.clan].filter(Boolean).join(' · ')));if(key.code){const code=el('code',key.code);code.style.overflowWrap='anywhere';item.append(code);}keyContent.append(item);}if(!rows.length)keyContent.append(el('p','No keys for this organisation type are present in your private register.'));}).catch(()=>{if(turn===generation&&!stopped)keyContent.replaceChildren(el('h3','Private charter keys'),el('p','The private key register is temporarily unavailable.'));});
}else if(page==='mail'&&company){const frame=el('iframe');frame.title=record.name+' correspondence';frame.src='/user-service.html?service=inbox&company='+encodeURIComponent(record.id)+'#company-inbox';frame.style.cssText='width:100%;min-height:900px;border:0';host.append(frame);
}else if(page==='mail'&&!company){if(record.membership&&record.mailScope)dispose=mountNativeService(host,'post-mail',{singleHeading:true,title:record.name+' · Office mail',folder:'INBOX',initialTab:record.mailScope==='imperial'?'imperial-inbox':'faction-inbox'});else host.append(el('p','An authorised current office deed is required to open this office mailbox.'));}else if(page==='claims'){dispose=mountClaims(host,{kind:company?'company':'protected',name:record.name,companyId:company?record.id:null,protectedId:company?null:record.claimOrganisationId});}
@ -57,7 +59,7 @@ export function startOrganisationCP(kind){
else if(company&&page==='subsidiaries'){const box=el('section',undefined,'organisation-settings-card');box.append(el('h3','Company hierarchy'),el('p','Registered parent and subsidiary companies.'));for(const relation of record.relations||[]){const row=el('article',undefined,'organisation-office-member'),logo=image(relation.emblem);logo.width=logo.height=64;const copy=el('div'),link=el('a',relation.name);link.href=relation.url;link.target='_top';copy.append(link,el('p',relation.direction==='parent'?'Parent company':'Subsidiary · '+(({created:'Founded',purchased:'Purchased',conquered:'Acquired'})[relation.origin]||'Registered')));row.append(logo,copy);box.append(row);}if(!record.relations?.length)box.append(el('p','No parent or subsidiary company is registered.'));host.append(box);dispose=mountCompanySubsidiary(host,{record,onCreated:id=>{const url=new URL(location.href);url.searchParams.set('company',id);url.hash='company/overview';location.assign(url.href);}});}
else if(company&&page==='applications'){dispose=mountExchangeDesign(host,{context:'clan',view:'applications',organisationScope:{kind,id:record.id}});}
else if(company&&page==='people'){dispose=mountCompanyRoster(host,{record,onChanged:action=>{if(action==='leave'){const url=new URL(location.href);url.searchParams.delete('company');url.hash='company/overview';location.assign(url.href);}else location.reload();}});}
else if(page==='people'||page==='applications'){const roster=el('section',undefined,'organisation-settings-card');roster.append(el('h3','Office deed roster'),el('p','Membership follows the current office deed automatically. Office appointments are handled through the political process.'));for(const member of record.members||[]){const row=el('article',undefined,'organisation-office-member'),portrait=image('https://cp.dunerealms.com/api/avatars/face/roster/'+encodeURIComponent(member.username));portrait.width=portrait.height=64;portrait.alt='';const copy=el('div'),link=el('a',member.name||member.username);link.href='https://www.dunerealms.com/people/'+encodeURIComponent(member.username);link.target='_top';copy.append(link,el('p','Current officeholder'));if(record.membership)copy.append(el('small','Term ends '+new Date(record.membership.expiresAt).toLocaleString('en-GB')));row.append(portrait,copy);roster.append(row);}if(!record.members?.length)roster.append(el('p','This office currently has no verified holder.'));host.append(roster);}
else if(page==='people'||page==='applications'){const roster=el('section',undefined,'organisation-settings-card');roster.append(el('h3','Office deed roster'),el('p','Membership follows the current office deed automatically. Office appointments are handled through the political process.'));for(const member of record.members||[]){const row=el('article',undefined,'organisation-office-member'),portrait=image('https://cp.dunerealms.com/api/avatars/face/roster/'+encodeURIComponent(member.username));portrait.width=portrait.height=64;portrait.alt='';const copy=el('div'),link=el('a',member.name||member.username);link.href='https://www.dunerealms.com/people/'+encodeURIComponent(member.username);link.target='_top';copy.append(link,el('p',member.title||(member.role==='officeholder'?'Current officeholder':'Appointed representative')));if(member.expiresAt||record.membership)copy.append(el('small','Term ends '+new Date(member.expiresAt||record.membership.expiresAt).toLocaleString('en-GB')));row.append(portrait,copy);roster.append(row);}if(!record.members?.length)roster.append(el('p','This office currently has no verified holder.'));host.append(roster);}
else pending(host,groups.flatMap(([,items])=>items).find(([id])=>id===page)?.[1]||noun+' workspace','The shared component is prepared; organisation-specific authority and data must be connected before actions are enabled.');
if(!company)parent.postMessage({type:'dune-politics-route',tab:'household',page},outer);measure();
}

View file

@ -15,6 +15,7 @@ export function mountVotingDirectory(host,selected=''){
const body=el('div',undefined,'campaign-body'),profile=el('a',candidate.name||candidate.username);profile.href='https://www.dunerealms.com/people/'+encodeURIComponent(candidate.username);profile.target='_top';const name=el('h2');name.append(profile);
const date=new Date(candidate.start).toLocaleDateString('en-GB',{timeZone:'UTC',dateStyle:'medium'});
body.append(el('small',scope.chamber+' · '+date),name,el('strong',scope.label,'campaign-office'),el('p',candidate.bio||'This player has not added a public biography.','campaign-bio'));
const history=el('a','View public office history →');history.href=profile.href+'#office-history';history.target='_top';body.append(history);
const message=el('details',undefined,'campaign-message'),summary=el('summary','Campaign message');message.open=true;message.append(summary,el('p',candidate.motivation));body.append(message);
const footer=el('div',undefined,'campaign-footer'),label=candidate.phase==='voting'&&candidate.round?.eligible?'Vote':candidate.phase==='upcoming'?'Voting opens at election time':'Voting closed',vote=el('button',label);vote.type='button';vote.disabled=label!=='Vote';vote.onclick=()=>confirm(candidate,scope);footer.append(el('span',candidate.publicId),vote);body.append(footer);card.append(portrait,body);return card;
}

Some files were not shown because too many files have changed in this diff Show more