Merge pull request '1.0.1.1: shared Realm CPs, J.A.R.V.I.S. keys and Realm Nexus' (#391) from code/realm-cp-1.0.1.1 into main
This commit is contained in:
commit
a511f0ba4b
43 changed files with 594 additions and 379 deletions
51
docs/design/REALM-CP-1.0.1.1.md
Normal file
51
docs/design/REALM-CP-1.0.1.1.md
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
# Realm CP 1.0.1.1
|
||||
|
||||
The Company and Politics CPs now use the existing clan dashboard and settings
|
||||
presentation, through one shared organisation shell. Company records come only
|
||||
from the authorised company register. Protected political House membership is a
|
||||
read projection of unambiguous current office deeds; ordinary faction citizens
|
||||
are not automatically members and personal clan membership is unchanged.
|
||||
Membership is checked again on each request and expires with the office deed.
|
||||
|
||||
The old authored CPs remain accessible at `/company-cp-reference` and
|
||||
`/politics-cp-reference`, with preserved browser entrypoints and their original
|
||||
navigation/style dependencies. They are reference implementations for the next
|
||||
design sessions. Their underlying API permission gates remain in effect.
|
||||
|
||||
The shared illustrated banner exposes three official-style switches only on the
|
||||
Clan, Company and Politics surfaces. Forums and other pages have no CP switcher.
|
||||
Realm Nexus links all three from the simplified shared main header. Main-header
|
||||
and workspace highlights still use the existing menu manager and permission rules.
|
||||
|
||||
Claim presentation reads the existing tariff catalogue: clan, company, protected.
|
||||
The company/protected adapters show their own tariff references and do not load
|
||||
another clan's live claims. Unconnected mutations and records stay explicitly
|
||||
unavailable. No company or political claim balance/land ownership is fabricated.
|
||||
|
||||
J.A.R.V.I.S. keeps existing CLAN and COM founding rights, with separate POL decision
|
||||
keys. New POL-CLAN keys are scoped to a live, unambiguous office deed and its exact
|
||||
expiry. CLAN-SUB / COM-SUB keys are parent-scoped, require a transactional authority
|
||||
adapter and cannot consume independent founding rights. The clan issuer requires
|
||||
a current Keyed/Royal mother deed; its private API checks game access and origin.
|
||||
Actual subhouse creation, purchase, conquest and release still need their domain
|
||||
handlers. The new key family does not itself transfer a deed or grant Royal rights.
|
||||
Staff issuance/replacement is explicitly deferred until preparation for live launch.
|
||||
|
||||
Recruitment quotes reuse the actual clan charter and member count. Basic is free;
|
||||
Keyed/Royal cost 10 DM plus 0.25 DM per occupied member per advertised place.
|
||||
The owner counts. Publishing must snapshot and recheck the quote and reserve
|
||||
payment. Listing publication/payment and Board/Discord delivery remain disabled
|
||||
until those adapters are implemented. The displayed quote does not debit money.
|
||||
|
||||
Git/release version is 1.0.1.1. The user manages any saved header-version override.
|
||||
No game services are restarted or updated by this web rollout. PR337 stays open.
|
||||
|
||||
Next: separate cleanup PR, then design review. Later kit/item update integrates
|
||||
tools, weapons and banners into clan equipment using existing generator code,
|
||||
MK I-XIV metadata and native rarity. No equipment-stat effects are enabled here.
|
||||
|
||||
Local governance and deed ownership are distinct for subordinated Houses. Their
|
||||
local leadership retains access to Heir, Consort and specialist appointments;
|
||||
local succession does not inherit the mother's deed or restore independent
|
||||
political powers. The mother retains final deed authority. This remains a required
|
||||
rule for the later relationship/transfer handlers, not a claimed completed feature.
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
import {issueClanSubhouseKey} from '../node/subhouse-keys.mjs';
|
||||
import {identity} from '../node/auth.mjs';
|
||||
import {accessFor} from '../node/permissions.mjs';
|
||||
import {ensureOriginalKeys} from '../node/organisation-key-service.mjs';
|
||||
|
|
@ -13,12 +14,13 @@ export function createClanKeyReceipts(db,{authenticate=r=>identity(r,db),access=
|
|||
if(!(await access(user)).nodes.includes('web.menu.game'))return reply({message:'Game account access required.'},403);
|
||||
if(!keys)return reply({message:'Founding codes are temporarily unavailable.'},503);
|
||||
let body;try{body=await request.json();}catch{return reply({message:'Invalid request.'},400);}
|
||||
if(body?.action==='issue-subhouse'){if(body.confirmed!==true||Object.keys(body).some(k=>!['action','parentClanId','requestId','confirmed'].includes(k)))return reply({message:'Confirm the mother-deed key request.'},400);try{const result=await issueClanSubhouseKey(db,keys,user,body);return reply({ok:true,keyId:result.id,created:result.created});}catch(error){if(error instanceof TypeError)return reply({message:error.message},400);if(error instanceof OrganisationKeyError)return reply({message:error.message},409);throw error;}}
|
||||
if(!body||typeof body!=='object'||Object.keys(body).some(k=>!['code','clanId','version','requestId','confirmed'].includes(k)))return reply({message:'Invalid founding request.'},400);
|
||||
try{const result=await upgradeOriginalClan(db,keys,user,body);return reply({ok:true,charter:'original',clanId:result.targetId,replayed:result.replayed});}
|
||||
catch(error){if(error instanceof TypeError)return reply({message:error.message},400);if(error instanceof OrganisationKeyError)return reply({message:error.message},409);throw error;}
|
||||
}
|
||||
if(keys)await ensureOriginalKeys(keys,user.id);
|
||||
const secrets=keys?new Map((await keys.list(user.id)).map(r=>[r.id,r])):new Map();
|
||||
const {results}=await db.prepare("SELECT k.id,k.key_type,k.created_at,k.used_at,k.expires_at,k.revoked_at,k.target_id,c.name,c.tag,ch.charter_kind FROM organisation_keys k LEFT JOIN site_clans c ON c.id=k.target_id LEFT JOIN site_clan_charters ch ON ch.clan_id=c.id WHERE k.account_id=? AND k.key_type IN ('clan-founding','company-founding','political-appointment') ORDER BY k.created_at,k.id LIMIT 100").bind(user.id).all();
|
||||
return reply({keys:results.map(r=>({id:r.id,type:r.key_type==='clan-founding'?'clan':r.key_type==='company-founding'?'company':'politics',createdAt:Number(r.created_at),status:r.revoked_at!=null?'Revoked':r.used_at!=null?'Applied':r.expires_at!=null&&Number(r.expires_at)<=Date.now()?'Expired':keys?'Available':'Issued',clan:r.name||null,clanId:r.target_id,charter:r.charter_kind||null,code:secrets.get(r.id)?.code||null,edition:secrets.get(r.id)?.edition||null}))});
|
||||
const {results}=await db.prepare("SELECT k.id,k.key_type,k.created_at,k.used_at,k.expires_at,k.revoked_at,k.target_id,c.name,c.tag,ch.charter_kind FROM organisation_keys k LEFT JOIN site_clans c ON c.id=k.target_id LEFT JOIN site_clan_charters ch ON ch.clan_id=c.id WHERE k.account_id=? AND k.key_type IN ('clan-founding','company-founding','political-appointment','political-clan','clan-subhouse','company-subsidiary') ORDER BY k.created_at,k.id LIMIT 100").bind(user.id).all();
|
||||
return reply({keys:results.map(r=>({id:r.id,type:r.key_type==='clan-founding'?'clan':r.key_type==='company-founding'?'company':r.key_type==='political-clan'?'politics-clan':r.key_type==='clan-subhouse'?'subhouse':r.key_type==='company-subsidiary'?'subsidiary':'politics',createdAt:Number(r.created_at),status:r.revoked_at!=null?'Revoked':r.used_at!=null?'Applied':r.expires_at!=null&&Number(r.expires_at)<=Date.now()?'Expired':keys?'Available':'Issued',clan:r.name||null,clanId:r.target_id,charter:r.charter_kind||null,code:secrets.get(r.id)?.code||null,edition:secrets.get(r.id)?.edition||null}))});
|
||||
};}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import {clanRecruitmentQuote} from '../node/jarvis-recruitment-policy.mjs';
|
||||
import {clanMemberLimit} from '../node/clan-membership-policy.mjs';
|
||||
import {normalisePalette} from './public/organisation-palette-model.mjs';
|
||||
import {initializeClanCharters} from '../node/clan-charters.mjs';
|
||||
|
|
@ -50,6 +51,7 @@ export function createClans(db,{origin='https://cp.dunerealms.com',authenticate=
|
|||
const emblem=await db.prepare('SELECT version,image_blob IS NOT NULL AS has_image FROM site_clan_emblems WHERE clan_id=?').bind(record.id).first();record.emblemVersion=Number(emblem?.version||0);record.hasEmblem=!!emblem?.has_image;record.emblem=clanEmblemUrl(record.id,record.emblemVersion);
|
||||
const authority=await clanDeedAuthority(db,user.id,record.id);record.charterKind=authority.deed?.kind||'basic';record.memberLimit=clanMemberLimit(record.charterKind,record.institution?.memberLimit??null);record.colors=authority.deed?.colors||normalisePalette(undefined,record.home_world);record.titles=clanTitles({...record,institution:record.institution});record.deed=authority.deed?publicDeed(authority.deed):null;
|
||||
const {results:members}=await db.prepare("SELECT a.username,m.clan_role,m.joined_at FROM site_clan_members m JOIN site_accounts a ON a.id=m.user_id WHERE m.clan_id=? ORDER BY CASE m.clan_role WHEN 'owner' THEN 0 WHEN 'officer' THEN 1 ELSE 2 END,a.username").bind(record.id).all();
|
||||
record.recruitment=clanRecruitmentQuote({charterKind:record.charterKind,memberCount:members.length,protectedInstitution:!!record.institution,institutionLimit:record.institution?.memberLimit??null});
|
||||
const role=own?.clan_id===record.id?own.clan_role:null,canReview=linked&&!record.institution&&(['owner','officer'].includes(role)||authority.canManage);
|
||||
const requests=canReview?(await db.prepare("SELECT a.username,r.created_at FROM site_clan_requests r JOIN site_accounts a ON a.id=r.user_id WHERE r.clan_id=? AND r.status='pending' ORDER BY r.created_at,a.username").bind(record.id).all()).results:[];
|
||||
record.motd=role?await readOrganisationMotd(db,'clan',record.id):null;
|
||||
|
|
|
|||
7
website/control-panel/company-cp-reference.mjs
Normal file
7
website/control-panel/company-cp-reference.mjs
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
import {clanCPDocument} from './clan-cp-shell.mjs';
|
||||
export function companyCPReferenceDocument(source){return clanCPDocument(source)
|
||||
.replace('<title>DuneRealms · Clan CP</title>','<title>DuneRealms · Company CP Reference</title>')
|
||||
.replace('data-cp-mode="clan" class="clan-cp-shell"','data-cp-mode="company" class="clan-cp-shell company-cp-shell"')
|
||||
.replace(/<script src="\/v2\/v2\.js(?:\?[^\"]*)?" defer><\/script>/,'<script type="module" src="/v2/cp-v2-company-reference.mjs"></script>')
|
||||
.replace('<script type="module" src="/v2/cp-v2-clan-size.mjs"></script>','')
|
||||
.replace('</head>','<link rel="stylesheet" href="/v2/cp-v2-company-shell.css"></head>');}
|
||||
|
|
@ -4,4 +4,4 @@ export function companyCPDocument(source){return clanCPDocument(source)
|
|||
.replace('data-cp-mode="clan" class="clan-cp-shell"','data-cp-mode="company" class="clan-cp-shell company-cp-shell"')
|
||||
.replace(/<script src="\/v2\/v2\.js(?:\?[^\"]*)?" defer><\/script>/,'<script type="module" src="/v2/cp-v2-company-shell.mjs"></script>')
|
||||
.replace('<script type="module" src="/v2/cp-v2-clan-size.mjs"></script>','')
|
||||
.replace('</head>','<link rel="stylesheet" href="/v2/cp-v2-company-shell.css"></head>');}
|
||||
.replace('</head>','<link rel="stylesheet" href="/v2/cp-v2-organisation-shell.css"></head>');}
|
||||
|
|
|
|||
16
website/control-panel/politics-cp-reference.mjs
Normal file
16
website/control-panel/politics-cp-reference.mjs
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
// Use the same authored shell and layout as User/Dev CP. Only the palette,
|
||||
// political navigation and public-page chrome differ on this surface.
|
||||
export function politicsCPReferenceDocument(source){
|
||||
return source.replace('<title>DuneRealms · Account Centre</title>','<title>DuneRealms · Politics CP Reference</title>')
|
||||
.replace(/<header class="dune-site-header">[\s\S]*?<\/header>/,'')
|
||||
.replace(/<footer class="site-footer">[\s\S]*?<\/footer>/,'')
|
||||
.replace(/<script src="https:\/\/www\.dunerealms\.com\/portal-navigation\.js" defer><\/script>/,'')
|
||||
.replace(/<link rel="stylesheet" href="https:\/\/www\.dunerealms\.com\/portal-navigation\.css">/,'')
|
||||
.replace('<body>','<body class="politics-cp-shell" data-cp-mode="politics">')
|
||||
.replace('<strong>✦ DuneRealms</strong>','<strong>✦ Political CP</strong>')
|
||||
.replace('CONTROL PANEL V2<small>Your imperial workspace</small>','IMPERIAL SENATE · SMALL COUNCIL<small>Four-week terms · Elections & Offices</small>')
|
||||
.replace('class="portals" aria-label="Workspace portals"','class="portals" hidden aria-hidden="true"')
|
||||
.replace('aria-controls="sidebar"','aria-controls="sidebar sidebar-right"')
|
||||
.replace(/<script src="\/v2\/v2\.js(?:\?[^\"]*)?" defer><\/script>/,'<script type="module" src="/v2/cp-v2-politics-reference.mjs"></script>')
|
||||
.replace('</head>','<link rel="stylesheet" href="/v2/cp-v2-politics-shell.css"></head>');
|
||||
}
|
||||
|
|
@ -1,16 +1,7 @@
|
|||
// Use the same authored shell and layout as User/Dev CP. Only the palette,
|
||||
// political navigation and public-page chrome differ on this surface.
|
||||
export function politicsCPDocument(source){
|
||||
return source.replace('<title>DuneRealms · Account Centre</title>','<title>DuneRealms · Political CP</title>')
|
||||
.replace(/<header class="dune-site-header">[\s\S]*?<\/header>/,'')
|
||||
.replace(/<footer class="site-footer">[\s\S]*?<\/footer>/,'')
|
||||
.replace(/<script src="https:\/\/www\.dunerealms\.com\/portal-navigation\.js" defer><\/script>/,'')
|
||||
.replace(/<link rel="stylesheet" href="https:\/\/www\.dunerealms\.com\/portal-navigation\.css">/,'')
|
||||
.replace('<body>','<body class="politics-cp-shell" data-cp-mode="politics">')
|
||||
.replace('<strong>✦ DuneRealms</strong>','<strong>✦ Political CP</strong>')
|
||||
.replace('CONTROL PANEL V2<small>Your imperial workspace</small>','IMPERIAL SENATE · SMALL COUNCIL<small>Four-week terms · Elections & Offices</small>')
|
||||
.replace('class="portals" aria-label="Workspace portals"','class="portals" hidden aria-hidden="true"')
|
||||
.replace('aria-controls="sidebar"','aria-controls="sidebar sidebar-right"')
|
||||
.replace(/<script src="\/v2\/v2\.js(?:\?[^\"]*)?" defer><\/script>/,'<script type="module" src="/v2/cp-v2-politics-shell.mjs"></script>')
|
||||
.replace('</head>','<link rel="stylesheet" href="/v2/cp-v2-politics-shell.css"></head>');
|
||||
}
|
||||
import {clanCPDocument} from './clan-cp-shell.mjs';
|
||||
export function politicsCPDocument(source){return clanCPDocument(source)
|
||||
.replace('<title>DuneRealms · Clan CP</title>','<title>DuneRealms · Political CP</title>')
|
||||
.replace('data-cp-mode="clan" class="clan-cp-shell"','data-cp-mode="politics" class="clan-cp-shell politics-cp-shell"')
|
||||
.replace(/<script src="\/v2\/v2\.js(?:\?[^\"]*)?" defer><\/script>/,'<script type="module" src="/v2/cp-v2-politics-shell.mjs"></script>')
|
||||
.replace('<script type="module" src="/v2/cp-v2-clan-size.mjs"></script>','')
|
||||
.replace('</head>','<link rel="stylesheet" href="/v2/cp-v2-organisation-shell.css"></head>');}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
// Shared syntax only: a readable edition is never proof of ownership or authority.
|
||||
const legacy=/^(CLAN|COM|POL)-([A-F0-9]{48})$/;
|
||||
const versioned=/^(CLAN|COM|POL)-(ALPHA|BETA|LIVE)-((?:0|[1-9]\d{0,2})(?:\.(?:0|[1-9]\d{0,2})){3})-(S\d{2,4})-([A-F0-9]{8}(?:-[A-F0-9]{8}){5})$/;
|
||||
const legacy=/^(CLAN-SUB|COM-SUB|POL-CLAN|CLAN|COM|POL)-([A-F0-9]{48})$/;
|
||||
const versioned=/^(CLAN-SUB|COM-SUB|POL-CLAN|CLAN|COM|POL)-(ALPHA|BETA|LIVE)-((?:0|[1-9]\d{0,2})(?:\.(?:0|[1-9]\d{0,2})){3})-(S\d{2,4})-([A-F0-9]{8}(?:-[A-F0-9]{8}){5})$/;
|
||||
export function parseOrganisationCode(value){
|
||||
if(typeof value!=='string'||value.length>128)throw new TypeError('Invalid organisation code');
|
||||
const code=value.trim().toUpperCase(),old=code.match(legacy);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import {claimDisplayName} from './cp-v2-claim-tariffs.mjs';
|
||||
import {claimTariffs,claimMoney,claimDisplayName} from './cp-v2-claim-tariffs.mjs';
|
||||
import {createClaimUpgrade} from './cp-v2-claim-upgrade.mjs';
|
||||
import {createUserAPI} from './cp-v2-user-api.mjs';
|
||||
import {createDeedArtwork} from './cp-v2-deed-art.mjs';
|
||||
|
|
@ -16,6 +16,7 @@ export function mountClaims(host,{kind='clan',name='Your organisation',clanId=nu
|
|||
const scroll=el('div',undefined,'claim-preview-scroll'),table=el('table',undefined,'claim-preview-table'),head=el('thead'),row=el('tr');
|
||||
for(const label of ['Estate','World','Chunks','Status']){const th=el('th',label);th.scope='col';row.append(th);}head.append(row);const body=el('tbody'),empty=el('td','Live claim records are not connected yet.');empty.colSpan=4;const emptyRow=el('tr');emptyRow.append(empty);body.append(emptyRow);table.append(head,body);scroll.append(table);scroll.tabIndex=0;scroll.setAttribute('role','region');scroll.setAttribute('aria-label','Your claimed areas');estates.append(scroll);root.append(estates);
|
||||
const details=el('details',undefined,'claims-card claims-reference');details.append(el('summary','Details · charter levels, prices & rules'),createDeedArtwork(kind));
|
||||
if(kind!=='clan'){const profile=el('table'),head=el('tr');for(const label of ['Estate','Chunks','Unlock','Monthly upkeep'])head.append(el('th',label));profile.append(head);for(const tier of claimTariffs(kind)){const row=el('tr');for(const value of [tier.displayName,String(tier.chunks),claimMoney(tier.unlockMinor),claimMoney(tier.upkeepMinor)])row.append(el('td',value));profile.append(row);}details.append(profile);}
|
||||
const rates=el('a','Compare tiers and prices in Rates & Charges →');rates.href='https://www.dunerealms.com/rates-and-charges.html#claims';rates.target='_top';details.append(rates);
|
||||
for(const [title,copy]of [['Claim capacity','One chunk is 16 × 16 blocks. Your allowance covers all your claimed chunks together.'],['Charter levels','Start Basic. An original key unlocks Keyed status; Royal status requires a political appointment. Personal voting rights are unchanged.'],['Subhouses & payments','A mother organisation manages subordinate claims. The original organisation keeps its accounts and pays upkeep and upgrades. Payments go to the Tax treasury.']]){details.append(el('h4',title),el('p',copy));}
|
||||
const subhouses=el('section',undefined,'claims-card claims-subhouses');subhouses.append(el('h3','Claims from subhouses'));const childList=el('div',undefined,'claims-child-list');childList.append(el('p','Subhouse claim access is being connected.','claims-muted'));subhouses.append(childList);root.append(subhouses,details);
|
||||
|
|
|
|||
|
|
@ -1,36 +1,38 @@
|
|||
import {parseOrganisationCode} from '../codex-code-format.mjs';
|
||||
import {createDeedArtwork} from './cp-v2-deed-art.mjs';
|
||||
import {element as el} from './cp-v2-page-template.mjs';
|
||||
|
||||
// Presentation only. Recognising a format never verifies ownership or grants a right.
|
||||
export function describeRedemption(value){
|
||||
const entered=String(value||'').trim().toUpperCase();let code=entered,edition=null;try{const parsed=parseOrganisationCode(entered);code=parsed.canonical;edition=parsed.edition;}catch{}
|
||||
const types=[
|
||||
[/^DRK-[A-Z2-7]{32}$/,'kit','Kit delivery','Requests your kit delivery. The game confirms arrival.','Redeem kit',true],
|
||||
[/^DRQ-[A-F0-9]{40}$/,'discovery','Discovery reward','Claims your earned discovery reward. The service checks eligibility before crediting.','Claim reward',true],
|
||||
[/^(?:DRU|UP)-[A-F0-9]{48}$/,'token','Upgrade Token','Apply this token to a saved kit in Imperial Tailor.','Open Imperial Tailor',false,'#realm/kits-exchange'],
|
||||
[/^CLAN-[A-F0-9]{48}$/,'clan','Clan founding right','Upgrades your existing Basic clan to an Original House that can become a mother house. A Royal House requires a separate political appointment.','Upgrade my Basic clan',true],
|
||||
[/^COM-[A-F0-9]{48}$/,'company','Company founding right','Upgrades your existing Basic company using its separate original founding right.','Company upgrades coming soon',false],
|
||||
[/^POL-[A-F0-9]{48}$/,'politics','Political appointment','Applies the specific appointment recorded by a political decision. The decision determines the organisation and title.','Political appointments coming soon',false]
|
||||
];
|
||||
for(const [pattern,kind,title,description,action,available,href] of types)if(pattern.test(code))return {code:entered,edition,kind,title,description,action,available,href};
|
||||
throw Error('Enter a complete private code. Community commands are used in game.');
|
||||
}
|
||||
|
||||
export function createCodeRedemption(){
|
||||
let reviewed=null,locked=false;
|
||||
const root=el('section',undefined,'code-redemption'),hero=el('header',undefined,'reward-code-banner'),art=el('img');art.src='https://www.dunerealms.com/assets/imperial-seal-128.png';art.alt='';const heading=el('div');heading.append(el('small','SPOST · IMPERIAL CODE OFFICE'),el('h4','Present your code. Open your next chapter.'),el('p','Your SPost counter for rewards, founding rights and political appointments.'));hero.append(art,heading);
|
||||
const layout=el('div',undefined,'code-redemption-layout'),form=el('form',undefined,'code-redemption-card'),entry=el('fieldset'),legend=el('legend','1 · Enter your private code'),label=el('label','Code'),input=el('input');input.type='text';input.autocomplete='off';input.spellcheck=false;input.autocapitalize='characters';input.required=true;input.maxLength=128;input.placeholder='Paste your complete code';input.setAttribute('aria-describedby','redemption-code-help');const help=el('p','Keep your code private. Checking its format does not use it.','code-redemption-muted');help.id='redemption-code-help';label.append(input);const inspect=el('button','Review code');inspect.type='button';entry.append(legend,label,help,inspect);
|
||||
const preview=el('fieldset',undefined,'code-redemption-preview');preview.hidden=true;preview.append(el('legend','2 · Review & confirm'));const badge=el('span',undefined,'reward-kind'),title=el('h5'),effect=el('p'),verification=el('p','Format recognised. Ownership and eligibility are checked when you submit.','code-redemption-muted'),check=el('input');check.type='checkbox';const consent=el('label',undefined,'code-redemption-consent');consent.append(check,el('span','I understand this action and want to use my code.'));const submit=el('button','Confirm redemption');submit.type='submit';submit.disabled=true;const destination=el('a');destination.hidden=true;preview.append(badge,title,effect,verification,consent,submit,destination);const result=el('p',undefined,'code-redemption-result');result.setAttribute('role','status');result.setAttribute('aria-live','polite');form.append(entry,preview,result);
|
||||
const guide=el('aside',undefined,'code-redemption-card code-redemption-guide');guide.append(el('small','WHAT CAN YOU PRESENT?'),el('h5','Your code chooses the route.'));
|
||||
for(const [kind,name,copy] of [['kit','Kits & discoveries','Existing DRK and DRQ codes can be redeemed here.'],['clan','House & company charters','Create your Basic clan first. CLAN upgrades your Basic clan to an Original House. Keep your separate COM code for Company CP.'],['politics','Political appointments','POL codes come from an approved decision. Founding alone does not confer a Royal title.'],['token','Upgrade Tokens','DRU tokens are applied to a saved kit in Imperial Tailor.']]){const card=el('div',undefined,'code-redemption-guide-item');card.append(el('span',name,'reward-kind reward-kind-'+kind),el('p',copy));guide.append(card);}const register=el('a','← View your codes');register.href='#';register.onclick=e=>{e.preventDefault();root.dispatchEvent(new CustomEvent('show-code-register',{bubbles:true}));};guide.append(createDeedArtwork('keys'),register);layout.append(form,guide);root.append(hero,layout);
|
||||
function sync(){submit.disabled=locked||!reviewed?.available||!check.checked;inspect.disabled=locked;input.disabled=locked;check.disabled=locked;}
|
||||
function invalidate(){reviewed=null;check.checked=false;preview.hidden=true;result.textContent='';sync();}
|
||||
input.oninput=invalidate;check.onchange=sync;
|
||||
inspect.onclick=()=>{if(locked)return;try{reviewed=describeRedemption(input.value);check.checked=false;badge.className='reward-kind reward-kind-'+reviewed.kind;badge.textContent=reviewed.available?'Ready to submit':'Dedicated route';title.textContent=reviewed.title;effect.textContent=reviewed.description;submit.textContent=reviewed.action;submit.hidden=!reviewed.available;consent.hidden=!reviewed.available;destination.hidden=!reviewed.href;if(reviewed.href){destination.href=reviewed.href;destination.textContent=reviewed.action;}verification.textContent=reviewed.available?'Format recognised. Ownership and eligibility are checked when you submit.':reviewed.href?'Continue in the dedicated workshop to choose your kit.':'This route is being connected. Your code has not been used.';preview.hidden=false;result.textContent='';sync();}catch(error){invalidate();result.textContent=error.message;input.focus();}};
|
||||
return {root,form,input,check,submit,result,setLocked(value){locked=!!value;sync();},reset(){form.reset();invalidate();},reviewedCode(){if(!reviewed?.available||describeRedemption(input.value).code!==reviewed.code||!check.checked)throw Error('Review your code and confirm the action first.');return reviewed.code;}};
|
||||
}
|
||||
|
||||
export function createCodeOfficeBranding(){
|
||||
const footer=el('footer',undefined,'code-office-provider'),brands=el('div',undefined,'code-office-provider-brands'),logo=el('img');logo.src='https://www.dunerealms.com/assets/spost-logo-v1.svg';logo.alt='SPost';logo.width=130;logo.height=43;const group=el('a');group.href='https://www.dunerealms.com/corrino-group.html';const art=el('img');art.src='https://www.dunerealms.com/assets/corrino-group-v4.png';art.alt='Corrino Group';art.width=116;art.height=42;group.append(el('span','part of'),art);brands.append(logo,group);footer.append(el('span','Code services provided by'),brands);return footer;
|
||||
}
|
||||
import {element as el} from './cp-v2-page-template.mjs';
|
||||
|
||||
// Presentation only. Recognising a format never verifies ownership or grants a right.
|
||||
export function describeRedemption(value){
|
||||
const entered=String(value||'').trim().toUpperCase();let code=entered,edition=null;try{const parsed=parseOrganisationCode(entered);code=parsed.canonical;edition=parsed.edition;}catch{}
|
||||
const types=[
|
||||
[/^POL-CLAN-[A-F0-9]{48}$/,'politics-clan','Political clan membership','Bound to the current office deed, not a political decision or Royal appointment.','Open Politics CP',false,'https://www.dunerealms.com/government.html'],
|
||||
[/^(?:CLAN-SUB|COM-SUB)-[A-F0-9]{48}$/,'subhouse','Subordinate organisation founding','This key is bound to its mother deed. It cannot create an independent or Royal charter.','Subhouse creation adapter pending',false],
|
||||
[/^DRK-[A-Z2-7]{32}$/,'kit','Kit delivery','Requests your kit delivery. The game confirms arrival.','Redeem kit',true],
|
||||
[/^DRQ-[A-F0-9]{40}$/,'discovery','Discovery reward','Claims your earned discovery reward. The service checks eligibility before crediting.','Claim reward',true],
|
||||
[/^(?:DRU|UP)-[A-F0-9]{48}$/,'token','Upgrade Token','Apply this token to a saved kit in Imperial Tailor.','Open Imperial Tailor',false,'#realm/kits-exchange'],
|
||||
[/^CLAN-[A-F0-9]{48}$/,'clan','Clan founding right','Upgrades your existing Basic clan to an Original House that can become a mother house. A Royal House requires a separate political appointment.','Upgrade my Basic clan',true],
|
||||
[/^COM-[A-F0-9]{48}$/,'company','Company founding right','Upgrades your existing Basic company using its separate original founding right.','Company upgrades coming soon',false],
|
||||
[/^POL-[A-F0-9]{48}$/,'politics','Political appointment','Applies the specific appointment recorded by a political decision. The decision determines the organisation and title.','Political appointments coming soon',false]
|
||||
];
|
||||
for(const [pattern,kind,title,description,action,available,href] of types)if(pattern.test(code))return {code:entered,edition,kind,title,description,action,available,href};
|
||||
throw Error('Enter a complete private code. Community commands are used in game.');
|
||||
}
|
||||
|
||||
export function createCodeRedemption(){
|
||||
let reviewed=null,locked=false;
|
||||
const root=el('section',undefined,'code-redemption'),hero=el('header',undefined,'reward-code-banner'),art=el('img');art.src='https://www.dunerealms.com/assets/imperial-seal-128.png';art.alt='';const heading=el('div');heading.append(el('small','SPOST · IMPERIAL CODE OFFICE'),el('h4','Present your code. Open your next chapter.'),el('p','Your SPost counter for rewards, founding rights and political appointments.'));hero.append(art,heading);
|
||||
const layout=el('div',undefined,'code-redemption-layout'),form=el('form',undefined,'code-redemption-card'),entry=el('fieldset'),legend=el('legend','1 · Enter your private code'),label=el('label','Code'),input=el('input');input.type='text';input.autocomplete='off';input.spellcheck=false;input.autocapitalize='characters';input.required=true;input.maxLength=128;input.placeholder='Paste your complete code';input.setAttribute('aria-describedby','redemption-code-help');const help=el('p','Keep your code private. Checking its format does not use it.','code-redemption-muted');help.id='redemption-code-help';label.append(input);const inspect=el('button','Review code');inspect.type='button';entry.append(legend,label,help,inspect);
|
||||
const preview=el('fieldset',undefined,'code-redemption-preview');preview.hidden=true;preview.append(el('legend','2 · Review & confirm'));const badge=el('span',undefined,'reward-kind'),title=el('h5'),effect=el('p'),verification=el('p','Format recognised. Ownership and eligibility are checked when you submit.','code-redemption-muted'),check=el('input');check.type='checkbox';const consent=el('label',undefined,'code-redemption-consent');consent.append(check,el('span','I understand this action and want to use my code.'));const submit=el('button','Confirm redemption');submit.type='submit';submit.disabled=true;const destination=el('a');destination.hidden=true;preview.append(badge,title,effect,verification,consent,submit,destination);const result=el('p',undefined,'code-redemption-result');result.setAttribute('role','status');result.setAttribute('aria-live','polite');form.append(entry,preview,result);
|
||||
const guide=el('aside',undefined,'code-redemption-card code-redemption-guide');guide.append(el('small','WHAT CAN YOU PRESENT?'),el('h5','Your code chooses the route.'));
|
||||
for(const [kind,name,copy] of [['kit','Kits & discoveries','Existing DRK and DRQ codes can be redeemed here.'],['clan','House & company charters','Create your Basic clan first. CLAN upgrades your Basic clan to an Original House. Keep your separate COM code for Company CP.'],['politics','Political appointments','POL codes come from an approved decision. Founding alone does not confer a Royal title.'],['token','Upgrade Tokens','DRU tokens are applied to a saved kit in Imperial Tailor.']]){const card=el('div',undefined,'code-redemption-guide-item');card.append(el('span',name,'reward-kind reward-kind-'+kind),el('p',copy));guide.append(card);}const register=el('a','← View your codes');register.href='#';register.onclick=e=>{e.preventDefault();root.dispatchEvent(new CustomEvent('show-code-register',{bubbles:true}));};guide.append(createDeedArtwork('keys'),register);layout.append(form,guide);root.append(hero,layout);
|
||||
function sync(){submit.disabled=locked||!reviewed?.available||!check.checked;inspect.disabled=locked;input.disabled=locked;check.disabled=locked;}
|
||||
function invalidate(){reviewed=null;check.checked=false;preview.hidden=true;result.textContent='';sync();}
|
||||
input.oninput=invalidate;check.onchange=sync;
|
||||
inspect.onclick=()=>{if(locked)return;try{reviewed=describeRedemption(input.value);check.checked=false;badge.className='reward-kind reward-kind-'+reviewed.kind;badge.textContent=reviewed.available?'Ready to submit':'Dedicated route';title.textContent=reviewed.title;effect.textContent=reviewed.description;submit.textContent=reviewed.action;submit.hidden=!reviewed.available;consent.hidden=!reviewed.available;destination.hidden=!reviewed.href;if(reviewed.href){destination.href=reviewed.href;destination.textContent=reviewed.action;}verification.textContent=reviewed.available?'Format recognised. Ownership and eligibility are checked when you submit.':reviewed.href?'Continue in the dedicated workshop to choose your kit.':'This route is being connected. Your code has not been used.';preview.hidden=false;result.textContent='';sync();}catch(error){invalidate();result.textContent=error.message;input.focus();}};
|
||||
return {root,form,input,check,submit,result,setLocked(value){locked=!!value;sync();},reset(){form.reset();invalidate();},reviewedCode(){if(!reviewed?.available||describeRedemption(input.value).code!==reviewed.code||!check.checked)throw Error('Review your code and confirm the action first.');return reviewed.code;}};
|
||||
}
|
||||
|
||||
export function createCodeOfficeBranding(){
|
||||
const footer=el('footer',undefined,'code-office-provider'),brands=el('div',undefined,'code-office-provider-brands'),logo=el('img');logo.src='https://www.dunerealms.com/assets/spost-logo-v1.svg';logo.alt='SPost';logo.width=130;logo.height=43;const group=el('a');group.href='https://www.dunerealms.com/corrino-group.html';const art=el('img');art.src='https://www.dunerealms.com/assets/corrino-group-v4.png';art.alt='Corrino Group';art.width=116;art.height=42;group.append(el('span','part of'),art);brands.append(logo,group);footer.append(el('span','Code services provided by'),brands);return footer;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import {element as el} from './cp-v2-page-template.mjs';
|
||||
const types={clan:['Clan founding','Silver charter · upgrades a Basic clan to Keyed.','silver'],politics:['Royal appointment','Gold charter · a political appointment grants Royal status.','gold'],company:['Company founding','Separate original founding entitlement for a company.','nav-exchange-v2.webp'],kit:['Kit','Private kit delivery entitlement.','items/office_water.png'],token:['Upgrade Token','Applied to a saved kit in Imperial Tailor.','reward-gold-ingot-transparent-v1.png'],community:['Community reward','An earned community reward.','nav-manual-v2.webp']};
|
||||
const types={'politics-clan':['Political clan membership','Bound to an active political office deed; separate from decision keys.','gold'],subhouse:['Subhouse founding','Bound to the mother deed; no new independent founding right.','silver'],subsidiary:['Subsidiary founding','Bound to the mother company deed.','silver'],clan:['Clan founding','Silver charter · upgrades a Basic clan to Keyed.','silver'],politics:['Royal appointment','Gold charter · a political appointment grants Royal status.','gold'],company:['Company founding','Separate original founding entitlement for a company.','nav-exchange-v2.webp'],kit:['Kit','Private kit delivery entitlement.','items/office_water.png'],token:['Upgrade Token','Applied to a saved kit in Imperial Tailor.','reward-gold-ingot-transparent-v1.png'],community:['Community reward','An earned community reward.','nav-manual-v2.webp']};
|
||||
export function createCodeTypeIcon(kind){
|
||||
const [name,description,art]=types[kind]||[kind,'Private entitlement.','nav-manual-v2.webp'];
|
||||
const details=el('details',undefined,'reward-type'),summary=el('summary'),image=el('span',undefined,'reward-type-image'),text=el('span',name,'reward-type-name'),help=el('p',description,'reward-type-help');
|
||||
|
|
|
|||
|
|
@ -0,0 +1,41 @@
|
|||
import {startCPAuthentication} from './cp-v2-auth.mjs';
|
||||
import {element as el} from './cp-v2-page-template.mjs';
|
||||
import {COMPANY_MENU,companyPage} from './cp-v2-company-navigation.mjs';
|
||||
import {mountNativeService} from './cp-v2-native-services.mjs';
|
||||
import {mountClaims} from './cp-v2-claims.mjs';
|
||||
import {watchMenuHighlights} from './cp-v2-menu-highlights.mjs';
|
||||
const outer='https://corp.dunerealms.com',assets='https://www.dunerealms.com/assets/',content=document.querySelector('#content'),left=document.querySelector('#sidebar'),right=document.querySelector('#sidebar-right'),portals=document.querySelector('#portals');
|
||||
let companies=[],selected=null,ready=false,dispose=()=>{};
|
||||
const picture=(src,cls='')=>{const image=el('img',undefined,cls);image.src=assets+src;image.alt='';return image;};
|
||||
function measure(){if(parent!==window){const height=Math.ceil(document.body.scrollHeight)+2;if(height>=100&&height<=200000)parent.postMessage({type:'dune-embed-size',height},outer);}}
|
||||
const observer=new ResizeObserver(()=>requestAnimationFrame(measure));observer.observe(document.body);
|
||||
window.addEventListener('message',event=>{if(event.source===parent&&event.origin===outer&&event.data?.type==='dune-embed-measure')measure();});
|
||||
function render(){
|
||||
if(!ready)return;dispose();dispose=()=>{};const page=companyPage(location.hash),company=companies.find(c=>c.id===selected),label=COMPANY_MENU.find(([id])=>id===page)[1];
|
||||
left.replaceChildren(el('div','COMPANY AFFAIRS','side-hero'));right.replaceChildren(el('div','THE CORPORATE LEDGER','side-hero'));portals.replaceChildren();portals.classList.add('company-switcher');
|
||||
const selector=el('select'),selectionLabel=el('label','Your companies');selector.setAttribute('aria-label','Choose your company');for(const item of companies){const option=el('option',item.name);option.value=item.id;selector.append(option);}if(!companies.length){const option=el('option','No companies available');option.value='';selector.append(option);}selector.value=selected||'';selector.disabled=!companies.length;selector.onchange=()=>{selected=selector.value;const url=new URL(location.href);url.searchParams.set('company',selected);history.replaceState(null,'',url);render();};selectionLabel.append(selector);portals.append(picture('clans/vaerkring-v1.png'),selectionLabel);
|
||||
const group=el('section',undefined,'category-block');group.append(el('div','Company workspace','category-heading'));for(const[id,title]of COMPANY_MENU){const link=el('a',title,'navitem');link.href='#company/'+id;link.dataset.menuHref=outer+'/#company/'+id;if(id===page)link.setAttribute('aria-current','page');group.append(link);}left.append(group);
|
||||
const back=el('a','← Account Centre','navitem');back.href='https://cp.dunerealms.com/';back.target='_top';left.append(back);
|
||||
const identity=el('section',undefined,'company-record');identity.append(picture('clans/vaerkring-v1.png'),el('h2',company?.name||'Company CP'),el('p',company?company.role+' · '+company.status:'Your corporate workspace'),el('p','A charter. A purpose. A place among the stars.'));right.append(identity);
|
||||
const guide=el('section',undefined,'company-record');guide.append(el('h3','Charters & estates'),el('p','Company land will belong to the organisation. Officers, boundaries and estate upgrades will be managed here.'));right.append(guide);
|
||||
const hero=el('header',undefined,'hero company-hero'),copy=el('div');copy.append(el('small','VAERKRING · COMMERCE & ENTERPRISE'),el('h1',label),el('p',company?.name||'Select an enterprise to open its workspace.'));hero.append(picture('clans/vaerkring-v1.png'),copy);
|
||||
const cards=el('div',undefined,'cards'),card=el('article',undefined,'card full citizen-page-full'),host=el('div',undefined,'citizen-live-host');card.append(host);cards.append(card);content.replaceChildren(hero,cards);
|
||||
if(!company){host.append(el('h2','Your enterprise starts here'),el('p','No company is currently registered with you as founder or CEO. Your companies will appear here when the registry grants you access.'));}
|
||||
else if(page==='claims')dispose=mountClaims(host,{kind:'company',name:company.name});
|
||||
else if(page==='boards'){dispose=mountNativeService(host,'company-boards',{singleHeading:true,organisationId:company.id});}
|
||||
else if(page==='overview'){
|
||||
const banner=el('section',undefined,'company-charter');banner.append(el('small','REGISTERED ENTERPRISE'),el('h2',company.name),el('p',company.description||'The company charter has no description yet.'));host.append(banner);
|
||||
const grid=el('div',undefined,'company-facts');for(const [key,value]of [['Registry',company.slug],['Standing',company.status],['Founder',company.founder_name||'Not listed'],['CEO',company.ceo_name||'Not appointed']]){const tile=el('article');tile.append(el('small',key),el('strong',value));grid.append(tile);}host.append(grid);
|
||||
const claims=el('a','Explore Claims →','company-primary-link');claims.href='#company/claims';host.append(claims);
|
||||
}else{
|
||||
const descriptions={people:'Company officers, members and their responsibilities will be managed here.',treasury:'Company accounts and obligations remain in Imperial Postbank. Your estate budgets and upkeep will appear here.',commerce:'Company procurement, contracts and trading permissions will be gathered here.',acquisitions:'Company sales are coming soon. A player may found one company; selling it does not restore that allowance. Further companies can be acquired by purchase.',subsidiaries:'Bought companies remain separate, keeping their records, claims and loans. Previous owners retain access; special powers and final management authority pass to the mother company.',projects:'Company quests, commissions and shared projects will appear here.',settings:'Company charter settings and role permissions will be managed here.'};
|
||||
const panel=el('section',undefined,'company-planned');panel.append(picture(page==='treasury'?'imperial-postbank-v2.png':'corrino-founding-marks-v1.png'),el('small','COMING SOON'),el('h2',label),el('p',descriptions[page]));host.append(panel);
|
||||
if(page==='treasury'){const bank=el('a','Open Imperial Postbank →','company-primary-link');bank.href='https://cp.dunerealms.com/#bank/personal-bank';bank.target='_top';host.append(bank);}
|
||||
}
|
||||
const route='company/'+page;history.replaceState(null,'','#'+route);if(parent!==window)parent.postMessage({type:'dune-company-route',page,company:selected},outer);left.classList.remove('open');right.classList.remove('open');document.querySelector('#mobile-menu').setAttribute('aria-expanded','false');measure();
|
||||
}
|
||||
document.querySelector('#mobile-menu').onclick=()=>{const open=left.classList.toggle('open');right.classList.toggle('open',open);document.querySelector('#mobile-menu').setAttribute('aria-expanded',String(open));};
|
||||
window.addEventListener('hashchange',render);const stopBadges=watchMenuHighlights(document.body);window.addEventListener('pagehide',()=>{dispose();observer.disconnect();stopBadges();},{once:true});
|
||||
startCPAuthentication(async()=>{
|
||||
content.replaceChildren(el('p','Opening your company register…'));try{const query=new URL(location.href).searchParams.get('company'),r=await fetch('/api/companies/workspace'+(query?'?company='+encodeURIComponent(query):''),{cache:'no-store',credentials:'same-origin'}),data=await r.json();if(!r.ok)throw Error(data.message||'Company register unavailable.');companies=data.companies;selected=data.selected;ready=true;render();}catch(error){content.replaceChildren(el('p',error.message));}
|
||||
});
|
||||
|
|
@ -1,41 +1,2 @@
|
|||
import {startCPAuthentication} from './cp-v2-auth.mjs';
|
||||
import {element as el} from './cp-v2-page-template.mjs';
|
||||
import {COMPANY_MENU,companyPage} from './cp-v2-company-navigation.mjs';
|
||||
import {mountNativeService} from './cp-v2-native-services.mjs';
|
||||
import {mountClaims} from './cp-v2-claims.mjs';
|
||||
import {watchMenuHighlights} from './cp-v2-menu-highlights.mjs';
|
||||
const outer='https://corp.dunerealms.com',assets='https://www.dunerealms.com/assets/',content=document.querySelector('#content'),left=document.querySelector('#sidebar'),right=document.querySelector('#sidebar-right'),portals=document.querySelector('#portals');
|
||||
let companies=[],selected=null,ready=false,dispose=()=>{};
|
||||
const picture=(src,cls='')=>{const image=el('img',undefined,cls);image.src=assets+src;image.alt='';return image;};
|
||||
function measure(){if(parent!==window){const height=Math.ceil(document.body.scrollHeight)+2;if(height>=100&&height<=200000)parent.postMessage({type:'dune-embed-size',height},outer);}}
|
||||
const observer=new ResizeObserver(()=>requestAnimationFrame(measure));observer.observe(document.body);
|
||||
window.addEventListener('message',event=>{if(event.source===parent&&event.origin===outer&&event.data?.type==='dune-embed-measure')measure();});
|
||||
function render(){
|
||||
if(!ready)return;dispose();dispose=()=>{};const page=companyPage(location.hash),company=companies.find(c=>c.id===selected),label=COMPANY_MENU.find(([id])=>id===page)[1];
|
||||
left.replaceChildren(el('div','COMPANY AFFAIRS','side-hero'));right.replaceChildren(el('div','THE CORPORATE LEDGER','side-hero'));portals.replaceChildren();portals.classList.add('company-switcher');
|
||||
const selector=el('select'),selectionLabel=el('label','Your companies');selector.setAttribute('aria-label','Choose your company');for(const item of companies){const option=el('option',item.name);option.value=item.id;selector.append(option);}if(!companies.length){const option=el('option','No companies available');option.value='';selector.append(option);}selector.value=selected||'';selector.disabled=!companies.length;selector.onchange=()=>{selected=selector.value;const url=new URL(location.href);url.searchParams.set('company',selected);history.replaceState(null,'',url);render();};selectionLabel.append(selector);portals.append(picture('clans/vaerkring-v1.png'),selectionLabel);
|
||||
const group=el('section',undefined,'category-block');group.append(el('div','Company workspace','category-heading'));for(const[id,title]of COMPANY_MENU){const link=el('a',title,'navitem');link.href='#company/'+id;link.dataset.menuHref=outer+'/#company/'+id;if(id===page)link.setAttribute('aria-current','page');group.append(link);}left.append(group);
|
||||
const back=el('a','← Account Centre','navitem');back.href='https://cp.dunerealms.com/';back.target='_top';left.append(back);
|
||||
const identity=el('section',undefined,'company-record');identity.append(picture('clans/vaerkring-v1.png'),el('h2',company?.name||'Company CP'),el('p',company?company.role+' · '+company.status:'Your corporate workspace'),el('p','A charter. A purpose. A place among the stars.'));right.append(identity);
|
||||
const guide=el('section',undefined,'company-record');guide.append(el('h3','Charters & estates'),el('p','Company land will belong to the organisation. Officers, boundaries and estate upgrades will be managed here.'));right.append(guide);
|
||||
const hero=el('header',undefined,'hero company-hero'),copy=el('div');copy.append(el('small','VAERKRING · COMMERCE & ENTERPRISE'),el('h1',label),el('p',company?.name||'Select an enterprise to open its workspace.'));hero.append(picture('clans/vaerkring-v1.png'),copy);
|
||||
const cards=el('div',undefined,'cards'),card=el('article',undefined,'card full citizen-page-full'),host=el('div',undefined,'citizen-live-host');card.append(host);cards.append(card);content.replaceChildren(hero,cards);
|
||||
if(!company){host.append(el('h2','Your enterprise starts here'),el('p','No company is currently registered with you as founder or CEO. Your companies will appear here when the registry grants you access.'));}
|
||||
else if(page==='claims')dispose=mountClaims(host,{kind:'company',name:company.name});
|
||||
else if(page==='boards'){dispose=mountNativeService(host,'company-boards',{singleHeading:true,organisationId:company.id});}
|
||||
else if(page==='overview'){
|
||||
const banner=el('section',undefined,'company-charter');banner.append(el('small','REGISTERED ENTERPRISE'),el('h2',company.name),el('p',company.description||'The company charter has no description yet.'));host.append(banner);
|
||||
const grid=el('div',undefined,'company-facts');for(const [key,value]of [['Registry',company.slug],['Standing',company.status],['Founder',company.founder_name||'Not listed'],['CEO',company.ceo_name||'Not appointed']]){const tile=el('article');tile.append(el('small',key),el('strong',value));grid.append(tile);}host.append(grid);
|
||||
const claims=el('a','Explore Claims →','company-primary-link');claims.href='#company/claims';host.append(claims);
|
||||
}else{
|
||||
const descriptions={people:'Company officers, members and their responsibilities will be managed here.',treasury:'Company accounts and obligations remain in Imperial Postbank. Your estate budgets and upkeep will appear here.',commerce:'Company procurement, contracts and trading permissions will be gathered here.',acquisitions:'Company sales are coming soon. A player may found one company; selling it does not restore that allowance. Further companies can be acquired by purchase.',subsidiaries:'Bought companies remain separate, keeping their records, claims and loans. Previous owners retain access; special powers and final management authority pass to the mother company.',projects:'Company quests, commissions and shared projects will appear here.',settings:'Company charter settings and role permissions will be managed here.'};
|
||||
const panel=el('section',undefined,'company-planned');panel.append(picture(page==='treasury'?'imperial-postbank-v2.png':'corrino-founding-marks-v1.png'),el('small','COMING SOON'),el('h2',label),el('p',descriptions[page]));host.append(panel);
|
||||
if(page==='treasury'){const bank=el('a','Open Imperial Postbank →','company-primary-link');bank.href='https://cp.dunerealms.com/#bank/personal-bank';bank.target='_top';host.append(bank);}
|
||||
}
|
||||
const route='company/'+page;history.replaceState(null,'','#'+route);if(parent!==window)parent.postMessage({type:'dune-company-route',page,company:selected},outer);left.classList.remove('open');right.classList.remove('open');document.querySelector('#mobile-menu').setAttribute('aria-expanded','false');measure();
|
||||
}
|
||||
document.querySelector('#mobile-menu').onclick=()=>{const open=left.classList.toggle('open');right.classList.toggle('open',open);document.querySelector('#mobile-menu').setAttribute('aria-expanded',String(open));};
|
||||
window.addEventListener('hashchange',render);const stopBadges=watchMenuHighlights(document.body);window.addEventListener('pagehide',()=>{dispose();observer.disconnect();stopBadges();},{once:true});
|
||||
startCPAuthentication(async()=>{
|
||||
content.replaceChildren(el('p','Opening your company register…'));try{const query=new URL(location.href).searchParams.get('company'),r=await fetch('/api/companies/workspace'+(query?'?company='+encodeURIComponent(query):''),{cache:'no-store',credentials:'same-origin'}),data=await r.json();if(!r.ok)throw Error(data.message||'Company register unavailable.');companies=data.companies;selected=data.selected;ready=true;render();}catch(error){content.replaceChildren(el('p',error.message));}
|
||||
});
|
||||
import {startOrganisationCP} from './cp-v2-organisation-shell.mjs';
|
||||
startOrganisationCP('company');
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ export function mountExchangeDesign(host,{context='public',view='browse',fetcher
|
|||
const categories=context==='user'?TYPES.filter(([id])=>id==='items'):context==='clan'?TYPES.filter(([id])=>!id.startsWith('kits')):TYPES;const buttons=[];for(const [id,title,art]of categories){const node=button(title,()=>{category=id;page=0;if(context==='public'){const url=new URL(location.href);if(id==='all')url.searchParams.delete('type');else url.searchParams.set('type',id);history.replaceState(null,'',url);}render();});node.prepend(image(art));if(id.startsWith('kits-'))node.dataset.subcategory='true';node.setAttribute('aria-pressed',String(id===category));buttons.push([node,id]);aside.append(node);}
|
||||
const legend=el('details',undefined,'codex-exchange-legend');if(context==='public')legend.open=true;legend.append(el('summary','J.A.R.V.I.S. symbols · What each listing means'));const icons=el('div');for(const [type,title,art,description]of TYPES.slice(1).filter(([id])=>!id.startsWith('kits-')&&(context==='public'||id!=='kits'))){const row=el('section');row.append(image(art),el('strong',title),el('span',description));icons.append(row);}legend.append(icons);browse.append(legend);
|
||||
const mine=el('div');mine.append(el('h3','My listings'),empty(['Artwork','Title','Type','Applications','Promotion','Status','Action'],'J.A.R.V.I.S. listing records are not connected. No records or balances are inferred.'),button('Post a listing',()=>selectPost?.()));
|
||||
const post=el('div',undefined,'codex-exchange-form-grid'),form=el('form',undefined,'codex-exchange-form'),formTitle=el('h3',context==='user'?'List an item':'Post a listing');form.onsubmit=e=>e.preventDefault();form.append(formTitle);const kind=field('Listing type',context==='user'?['Minecraft item']:['Clan recruitment','Quest · Keyed required','Event · Keyed required','Contract · Keyed required']);if(context==='clan')for(const option of [...kind.input.options].slice(1))option.disabled=true;const title=field('Title','A clear title for your listing'),message=field('Message','message'),audience=field('Audience',['Public exchange','Clan only']),promotion=el('fieldset');promotion.append(el('legend','Promotion'));for(const text of ['Publish to Boards','Publish to Discord']){const label=el('label'),input=el('input');input.type='checkbox';label.append(input,el('span',text));promotion.append(label);}const outcome=el('p','Preview only · Nothing has been submitted.','codex-exchange-status');form.append(kind.box,title.box,message.box,audience.box,promotion,button('Preview listing',()=>{previewCard.replaceChildren(el('small','LOCAL PREVIEW · NOT PUBLISHED'),el('h3',title.input.value||'Your listing title'),el('p',message.input.value||'Your message will appear here.'),el('p',kind.input.value));outcome.textContent='Local preview updated. Publishing is unavailable until the J.A.R.V.I.S. service is connected.';}),button(context==='user'?'Create through /exchange in game':'Publish listing',null,true),outcome);const previewCard=el('article',undefined,'codex-exchange-listing-preview');previewCard.append(image(context==='user'?'minecraft-items/diamond.png':'exchange-clan-recruitment-v1.png'),el('h3','Your next chapter'),el('p','Preview your listing before publication.'));post.append(form,previewCard);
|
||||
const post=el('div',undefined,'codex-exchange-form-grid'),form=el('form',undefined,'codex-exchange-form'),formTitle=el('h3',context==='user'?'List an item':'Post a listing');form.onsubmit=e=>e.preventDefault();const listingPrice=el('p','Recruitment price is being checked.','codex-exchange-status');form.append(formTitle);if(context==='clan')form.append(listingPrice);const kind=field('Listing type',context==='user'?['Minecraft item']:['Clan recruitment','Quest · Keyed required','Event · Keyed required','Contract · Keyed required']);if(context==='clan')for(const option of [...kind.input.options].slice(1))option.disabled=true;const title=field('Title','A clear title for your listing'),message=field('Message','message'),audience=field('Audience',['Public exchange','Clan only']),promotion=el('fieldset');promotion.append(el('legend','Promotion'));for(const text of ['Publish to Boards','Publish to Discord']){const label=el('label'),input=el('input');input.type='checkbox';label.append(input,el('span',text));promotion.append(label);}const outcome=el('p','Preview only · Nothing has been submitted.','codex-exchange-status');form.append(kind.box,title.box,message.box,audience.box,promotion,button('Preview listing',()=>{previewCard.replaceChildren(el('small','LOCAL PREVIEW · NOT PUBLISHED'),el('h3',title.input.value||'Your listing title'),el('p',message.input.value||'Your message will appear here.'),el('p',kind.input.value));outcome.textContent='Local preview updated. Publishing is unavailable until the J.A.R.V.I.S. service is connected.';}),button(context==='user'?'Create through /exchange in game':'Publish listing',null,true),outcome);const previewCard=el('article',undefined,'codex-exchange-listing-preview');previewCard.append(image(context==='user'?'minecraft-items/diamond.png':'exchange-clan-recruitment-v1.png'),el('h3','Your next chapter'),el('p','Preview your listing before publication.'));post.append(form,previewCard);
|
||||
const applications=el('div');applications.append(el('h3','Applications'),empty(['Applicant','Listing','Received','Status','Review'],'Application service not connected. Existing clan join requests remain available from the dashboard.'),button('Accept application',null,true),button('Decline application',null,true));
|
||||
const promotions=el('div',undefined,'codex-exchange-promotion');promotions.append(el('h3','Promotions & delivery'),el('p','Basic: five initial shared credits. Each Board post costs one; each Discord post costs one. Choose any mix. Quest rewards may add credits. Keyed and Royal remove the Basic credit limit; configured promotion fees apply.'),empty(['Listing','Channel','Cost','State','Last attempt'],'Delivery history is not connected.'),el('p','Available credits: not connected. No charge is made in this preview.'));
|
||||
const eligibility=el('p','Checking your deed…','codex-exchange-eligibility');if(context==='clan')root.append(eligibility);
|
||||
|
|
@ -28,7 +28,7 @@ export function mountExchangeDesign(host,{context='public',view='browse',fetcher
|
|||
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.'):'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);}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;status.textContent=rows.length+' live Minecraft listings · J.A.R.V.I.S. opportunities pending connection.';render();}catch{if(!active)return;rows=[];status.textContent='Live listings are unavailable. Design examples stay separate and cannot be purchased.';render();}}
|
||||
if(context==='clan')Promise.resolve().then(async()=>{const response=await fetcher('/api/clans',{signal:controller.signal});if(!response.ok)throw Error();const data=await response.json(),clan=data.membership?.clan||data.clan||data.clans?.find(c=>c.role);if(!clan)throw Error();clanKind=clan.charterKind||clan.deed?.charterKind||'unknown';if(!active)return;const tier={basic:['Basic',5],original:['Keyed',25],royal:['Royal',50]}[clanKind];eligibility.textContent=tier?tier[0]+' deed · '+tier[1]+' members maximum · '+(clanKind==='basic'?'Free recruitment; other listing types unlock with an upgrade.':'Advanced listing types available after J.A.R.V.I.S. integration.'):'Deed eligibility is not connected. Advanced listing types remain locked.';if(['original','royal'].includes(clanKind))for(const option of kind.input.options)option.disabled=false;}).catch(()=>{if(active)eligibility.textContent='Deed eligibility could not be confirmed. Advanced listing types remain locked.';});
|
||||
if(context==='clan')Promise.resolve().then(async()=>{const response=await fetcher('/api/clans',{signal:controller.signal});if(!response.ok)throw Error();const data=await response.json(),clanId=data.membership?.clan_id;let clan=data.membership?.clan||data.clan||data.clans?.find(c=>c.role);if(clanId){const detail=await fetcher('/api/clans/'+encodeURIComponent(clanId),{signal:controller.signal});if(!detail.ok)throw Error();clan=(await detail.json()).clan;}if(!clan)throw Error();clanKind=clan.charterKind||clan.deed?.charterKind||'unknown';const quote=clan.recruitment;if(quote&&active){listingPrice.textContent=quote.unitPriceMinor===null?'Recruitment is reserved for the institution roster.':(quote.unitPriceMinor===0?'Free recruitment':(quote.unitPriceMinor/100).toFixed(2)+' DM per recruitment place')+' · '+quote.occupiedMembers+' / '+quote.memberLimit+' members · '+quote.availablePlaces+' places available. Publication will recheck the price before charging.';}if(!active)return;const tier={basic:['Basic',5],original:['Keyed',25],royal:['Royal',50]}[clanKind];eligibility.textContent=tier?tier[0]+' deed · '+tier[1]+' members maximum · '+(clanKind==='basic'?'Free recruitment; other listing types unlock with an upgrade.':'Advanced listing types available after J.A.R.V.I.S. integration.'):'Deed eligibility is not connected. Advanced listing types remain locked.';if(['original','royal'].includes(clanKind))for(const option of kind.input.options)option.disabled=false;}).catch(()=>{if(active){eligibility.textContent='Deed eligibility could not be confirmed. Advanced listing types remain locked.';listingPrice.textContent='Recruitment price is unavailable. Nothing can be charged.';}});
|
||||
if(context==='user')Promise.resolve().then(async()=>{const response=await fetcher('/api/exchange/listings?view=mine',{signal:controller.signal,credentials:'same-origin'});if(!response.ok)throw Error();const data=await response.json();if(!active)return;const records=Array.isArray(data.listings)?data.listings:[];const table=empty(['Item','World','Quantity','Each · DM'],'No active item listings. List goods through /exchange in game.');if(records.length){const body=table.querySelector('tbody');body.replaceChildren();for(const item of records){const row=el('tr');for(const value of [item.displayName||words(item.material),words(item.origin),String(item.quantity),String(item.price)])row.append(el('td',value));body.append(row);}}mine.replaceChildren(el('h3','My item listings'),table,el('p',data.linked===false?'Link your Minecraft account to see your listings.':'Existing Minecraft listings · manage in game through /exchange.'));}).catch(()=>{if(active)mine.replaceChildren(el('h3','My item listings'),el('p','Your listings are unavailable. Refresh to retry.'));});
|
||||
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){status.textContent=rows.length+' Minecraft listings · '+kitRows.length+' published kit designs · J.A.R.V.I.S. opportunities pending.';render();}}).catch(()=>{if(active){const note=el('p','Kit catalogue is unavailable. Minecraft listings remain separate.','codex-exchange-status');browse.prepend(note);}});
|
||||
render();load();return()=>{active=false;controller.abort();root.remove();};
|
||||
|
|
|
|||
|
|
@ -0,0 +1 @@
|
|||
.organisation-switcher{display:flex;gap:20px;align-items:center;padding:20px 28px;border-bottom:1px solid #a68d54;background:#122f27}.organisation-switcher>img{width:76px;height:76px;object-fit:contain}.organisation-switcher label{display:grid;gap:9px;color:#e7cd8e;font:700 16px Georgia,serif}.organisation-switcher select{min-width:280px;max-width:100%;padding:12px;background:#102a24;color:#eee2c5;border:1px solid #ae9454;border-radius:7px}.organisation-workspace-hero{margin:24px 0;padding:28px;border:1px solid #b69a59;border-radius:18px;background:linear-gradient(90deg,#173d32ee,#10281fbb),url('https://www.dunerealms.com/assets/clan-atelier-v1.webp') center/cover}.organisation-workspace-hero>img{width:116px;height:116px;object-fit:contain}.organisation-reference{display:block;margin:18px 10px;color:#dfc98a;font-size:13px}.company-cp-shell .organisation-workspace-hero{background:linear-gradient(90deg,#173b46ec,#10282fbb),url('https://www.dunerealms.com/assets/exchange-starport-header-v2.webp') center/cover}.politics-cp-shell .organisation-workspace-hero{background:linear-gradient(90deg,#30273eed,#132a25bb),url('https://www.dunerealms.com/assets/political-imperial-chamber-v1.png') center/cover}.company-cp-shell .organisation-switcher{background:#17363f}.politics-cp-shell .organisation-switcher{background:#252c35}.organisation-settings-card{overflow-wrap:anywhere}.clan-center .organisation-dashboard-members img{max-width:100%;object-fit:contain}@media(max-width:720px){.organisation-switcher{padding:16px;gap:12px}.organisation-switcher select{min-width:0;width:100%}.organisation-switcher label{min-width:0;flex:1}.organisation-switcher>img{width:52px;height:52px}.organisation-workspace-hero{padding:20px}.organisation-workspace-hero>img{width:80px;height:80px}}
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
import {startCPAuthentication} from './cp-v2-auth.mjs';
|
||||
import {element as el} from './cp-v2-page-template.mjs';
|
||||
import {createOrganisationDashboard} from '../organisation-dashboard.mjs';
|
||||
import {createOrganisationSettings} from '../organisation-settings.mjs';
|
||||
import {mountClaims} from './cp-v2-claims.mjs';
|
||||
import {mountNativeService} from './cp-v2-native-services.mjs';
|
||||
import {mountPoliticsPage} from './cp-v2-politics-pages.mjs';
|
||||
import {watchMenuHighlights} from './cp-v2-menu-highlights.mjs';
|
||||
const assets='https://www.dunerealms.com/assets/';
|
||||
const groups=[['Your organisation',[['overview','Dashboard'],['settings','Settings']]],['Organisation affairs',[['boards','Boards'],['commerce','Exchange'],['tailor','Tailor']]],['Estates & relations',[['claims','Claims'],['subsidiaries','Subhouses'],['directory','Directory'],['projects','Expeditions'],['campaigns','Campaigns']]]];
|
||||
export function startOrganisationCP(kind){
|
||||
const company=kind==='company',noun=company?'Company':'Office',prefix=company?'company':'household',outer=company?'https://corp.dunerealms.com':'https://www.dunerealms.com',fallback=company?'guild.webp':'seals/office-landsraad.png';
|
||||
const content=document.querySelector('#content'),left=document.querySelector('#sidebar'),right=document.querySelector('#sidebar-right'),portals=document.querySelector('#portals');let ready=false,records=[],selected=null,user=null,dispose=()=>{},generation=0,stopped=false,lastHeight=0;
|
||||
const image=file=>{const n=el('img');n.src=file.startsWith('https://')?file:assets+file;n.alt='';return n;};
|
||||
const reference=()=>{const a=el('a','Open previous '+noun+' CP · reference ↗','organisation-reference');a.href='/'+(company?'company':'politics')+'-cp-reference';a.target='_blank';a.rel='noopener';return a;};
|
||||
const go=id=>{location.hash=prefix+'/'+id;};
|
||||
function measure(){if(stopped||parent===window)return;const height=Math.ceil(document.body.getBoundingClientRect().height)+2;if(height!==lastHeight&&height>=100&&height<=200000){lastHeight=height;parent.postMessage({type:'dune-embed-size',height},outer);}}
|
||||
const observer=new ResizeObserver(()=>requestAnimationFrame(measure));observer.observe(document.body);const onMeasure=e=>{if(e.source===parent&&e.origin===outer&&e.data?.type==='dune-embed-measure')measure();};window.addEventListener('message',onMeasure);
|
||||
const route=()=>{const raw=location.hash.slice(1).split('/').at(-1),ids=groups.flatMap(([,items])=>items.map(([id])=>id));return [...ids,'people','applications'].includes(raw)?raw:raw==='politics-overview'?'overview':null;};
|
||||
function pending(host,title,copy){const box=el('section',undefined,'organisation-settings-card');box.append(el('h3',title),el('p',copy),reference());host.append(box);}
|
||||
function render(){
|
||||
if(!ready||stopped)return;dispose();dispose=()=>{};const turn=++generation,record=records.find(r=>r.id===selected),page=route()||'overview';
|
||||
left.replaceChildren(el('div',company?'YOUR COMPANY':'YOUR POLITICAL HOUSE','side-hero'));right.replaceChildren(el('div',company?'COMPANY DIRECTORY':'POLITICAL HOUSES','side-hero'));portals.replaceChildren();portals.hidden=false;portals.classList.add('organisation-switcher');
|
||||
const label=el('label',company?'Your companies':'Political Houses'),select=el('select');select.setAttribute('aria-label',company?'Choose your company':'Choose a political House');for(const r of records){const option=el('option',r.name);option.value=r.id;select.append(option);}if(!records.length){const option=el('option','No verified organisation available');option.value='';select.append(option);}select.value=selected||'';select.disabled=!records.length;select.onchange=()=>{selected=select.value;const u=new URL(location.href);u.searchParams.set(company?'company':'office',selected);history.replaceState(null,'',u);render();};label.append(select);portals.append(image(record?.emblem||fallback),label);
|
||||
for(let i=0;i<groups.length;i++){const [heading,items]=groups[i],host=i<2?left:right,block=el('section',undefined,'category-block'),links=el('div',undefined,'category-links');block.append(el('div',heading,'category-heading'));for(const[id,title]of items){const a=el('a',title==='Subhouses'&&company?'Subsidiaries':title,'navitem');a.href='#'+prefix+'/'+id;a.dataset.menuHref=(company?outer+'/':outer+'/government.html')+a.getAttribute('href');if(id===page)a.setAttribute('aria-current','page');links.append(a);}block.append(links);host.append(block);}left.append(reference());
|
||||
const hero=el('header',undefined,'hero organisation-workspace-hero'),copy=el('div');copy.append(el('small',company?'SPACING GUILD · COMMERCIAL AFFAIRS':'IMPERIAL HOUSES · OFFICE DEEDS'),el('h1',record?.name||noun+' Dashboard'),el('p',company?'Your enterprise, its people and its next chapter.':'Protected Houses · membership follows current office deeds.'));hero.append(image(record?.emblem||fallback),copy);
|
||||
const cards=el('div',undefined,'cards'),card=el('article',undefined,'card full citizen-page-full'),host=el('div',undefined,'citizen-live-host clan-center');card.append(host);cards.append(card);content.replaceChildren(hero,cards);
|
||||
if(!record){pending(host,'Your '+noun.toLowerCase()+' workspace',company?'No company is registered to you as founder or CEO.':'Political office membership could not be verified.');return;}
|
||||
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||[],role:record.role==='Founder'||record.role==='CEO'?'owner':record.role,memberSummary:company?'Verified leadership · the full company roster will be connected here.':undefined,activityStatus:'unavailable',links:{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}));host.append(createOrganisationSettings(sections));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?k.type==='company':k.type==='politics-clan');const box=el('section',undefined,'organisation-settings-card');box.append(el('h3',noun+' clan keys'));for(const key of rows){box.append(el('p',key.status+(key.code?' · '+key.code:'')));}if(!rows.length)box.append(el('p','No organisation-clan keys are present in your private register.'));host.append(box);}).catch(()=>{if(turn===generation)note.append(el('span',' The private key register is unavailable.'));});
|
||||
}else if(page==='claims'){dispose=mountClaims(host,{kind:company?'company':'protected',name:record.name});}
|
||||
else if(page==='boards'){if(company)dispose=mountNativeService(host,'company-boards',{singleHeading:true,organisationId:record.id});else dispose=mountNativeService(host,'election-boards',{singleHeading:true});}
|
||||
else if(!company&&page==='directory')dispose=mountPoliticsPage(host,'all-applications');
|
||||
else if(!company&&page==='campaigns')dispose=mountPoliticsPage(host,'house-elections');
|
||||
else if(page==='commerce'){pending(host,'J.A.R.V.I.S. Exchange','Organisation listings will use the central Exchange with organisation-scoped keys and deeds.');const a=el('a','Open the central Exchange →');a.href='https://www.dunerealms.com/exchange.html';a.target='_top';host.append(a);}
|
||||
else if(page==='people'||page==='applications'){pending(host,'Members & applications',company?'Company membership management will use its own roster.':'Only verified current officeholders are automatically linked to this protected House.');for(const m of record.members||[])host.append(el('p',m.name||m.username));}
|
||||
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();
|
||||
}
|
||||
const mobile=()=>{const open=left.classList.toggle('open');right.classList.toggle('open',open);document.querySelector('#mobile-menu').setAttribute('aria-expanded',String(open));};document.querySelector('#mobile-menu').onclick=mobile;window.addEventListener('hashchange',render);watchMenuHighlights(document.body);
|
||||
window.addEventListener('pagehide',()=>{stopped=true;generation++;dispose();observer.disconnect();window.removeEventListener('hashchange',render);window.removeEventListener('message',onMeasure);},{once:true});
|
||||
startCPAuthentication(async account=>{user=account;if(!user.permissions?.includes('web.menu.game')){content.replaceChildren(el('p','Game account access is required.'));return;}const id=new URL(location.href).searchParams.get(company?'company':'office');try{const response=await fetch(company?'/api/companies/workspace'+(id?'?company='+encodeURIComponent(id):''):'/api/politics/workspace'+(id?'?office='+encodeURIComponent(id):''),{credentials:'same-origin',cache:'no-store'}),data=await response.json();if(!response.ok)throw Error(data.message||'Organisation unavailable.');if(stopped)return;records=company?data.companies.map(c=>({...c,emblem:assets+'guild.webp',members:[...new Set([c.founder_name,c.ceo_name].filter(Boolean))].map(username=>({username,role:'leadership'}))})):data.organisations;selected=data.selected;ready=true;render();}catch(e){content.replaceChildren(el('p',e.message),reference());}});
|
||||
}
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
import {mountNativeService} from './cp-v2-native-services.mjs';
|
||||
import {mountPolicyDecisions} from './cp-v2-politics-decisions.mjs';
|
||||
import {watchMenuHighlights} from './cp-v2-menu-highlights.mjs';
|
||||
import {startCPAuthentication} from './cp-v2-auth.mjs';
|
||||
import {mountPoliticsPage} from './cp-v2-politics-pages.mjs';
|
||||
import {element as el} from './cp-v2-page-template.mjs';
|
||||
import {ELECTIONS} from '../political-catalog.mjs';
|
||||
import {POLITICAL_TABS,politicalRoute} from './cp-v2-politics-navigation.mjs';
|
||||
const outer='https://www.dunerealms.com',content=document.querySelector('#content'),sidebar=document.querySelector('#sidebar'),sidebarRight=document.querySelector('#sidebar-right'),tabs=document.querySelector('#portals');
|
||||
const artwork={elections:'seals/office-house_leader.png',offices:'seals/office-landsraad.png',tools:'seals/emperor-v1.png',decisions:'seals/office-landsraad.png'};
|
||||
const icon=tab=>{const image=el('img');image.src=outer+'/assets/'+artwork[tab];image.alt='';return image;};
|
||||
let ready=false,dispose=()=>{},current='',queued=false,lastHeight=0;
|
||||
document.body.classList.toggle('politics-cp-embedded',parent!==window);
|
||||
function measure(){queued=false;if(parent===window)return;const height=Math.ceil(Math.max(document.body.scrollHeight,document.body.getBoundingClientRect().height))+2;if(height!==lastHeight&&height>=100&&height<=200000){lastHeight=height;parent.postMessage({type:'dune-embed-size',height},outer);}}
|
||||
function schedule(){if(!queued){queued=true;requestAnimationFrame(measure);}}
|
||||
const observer=new ResizeObserver(schedule);observer.observe(document.body);
|
||||
window.addEventListener('message',event=>{if(event.source===parent&&event.origin===outer&&event.data?.type==='dune-embed-measure')schedule();});
|
||||
function show(){
|
||||
if(!ready)return;const route=politicalRoute(location.hash),key=route.tab+'/'+route.page;if(key===current)return;current=key;dispose();dispose=()=>{};
|
||||
const tab=POLITICAL_TABS.find(t=>t.id===route.tab),page=tab.pages.find(([id])=>id===route.page);
|
||||
content.setAttribute('aria-label',page[1]);
|
||||
sidebar.replaceChildren(el('div','ELECTION CHAMBERS','side-hero'));sidebarRight.replaceChildren(el('div','OFFICES & INSTRUMENTS','side-hero'));
|
||||
const menu=(host,title,items)=>{const block=el('section',undefined,'category-block');const summary=el('div',title,'category-heading'),links=el('div',undefined,'category-links');for(const[id,label]of items){const group=POLITICAL_TABS.find(t=>t.pages.some(([p])=>p===id));const link=el('a',undefined,'navitem');link.href='#'+group.id+'/'+id;link.dataset.menuHref=outer+'/government.html'+link.getAttribute('href');link.append(icon(group.id==='directory'?'elections':group.id),el('span',label));if(id===page[0])link.setAttribute('aria-current','page');links.append(link);}block.append(summary,links);host.append(block);};
|
||||
menu(sidebar,'Imperial Senate',[['imperial-elections','Emperor election'],['house-elections','House Leader elections']]);
|
||||
menu(sidebar,'Small Council',ELECTIONS.filter(e=>e.chamber==='Small Council').map(e=>['election-'+e.id,e.label]));
|
||||
menu(sidebar,'Voting Directory',POLITICAL_TABS.find(t=>t.id==='directory').pages);
|
||||
menu(sidebar,'Decisions & Schemes',POLITICAL_TABS.find(t=>t.id==='decisions').pages);
|
||||
menu(sidebar,'Participation',[['applications','My applications'],['electoral-roll','Electoral Roll']]);
|
||||
if(route.tab==='decisions'){const status=el('section',undefined,'policy-watch');for(const title of ['Active orders','Preparations','Commitments & alerts'])status.append(el('h3',title),el('p','Records will appear here when these powers become available.'));sidebarRight.append(status);}
|
||||
menu(sidebarRight,'Offices',[['office-register','All offices'],['imperial-senate','Imperial Senate'],['small-council','Small Council'],['politics-overview','My political record']]);
|
||||
menu(sidebarRight,'Councils',[['landsraad','Landsraad assembly'],['formal-council','House council'],['imperial-command','Imperial council']]);
|
||||
menu(sidebarRight,'Tools',POLITICAL_TABS.find(t=>t.id==='tools').pages);
|
||||
const hero=el('header',undefined,'hero'),seal=el('img'),heading=el('div');seal.src=outer+'/assets/seals/office-landsraad.png';seal.alt='';heading.append(el('h1',page[1]),el('p',tab.id==='decisions'?'Decisions and schemes of this office · Economic, Political and Communal.':tab.id==='directory'?'Meet the candidates, explore their campaigns and cast your eligible votes.':tab.id==='elections'?'Candidatures, verified eligibility and the existing ballots.':tab.id==='offices'?'The offices, councils and elected representatives of the realms.':'Proclamations and the existing government instruments.'));hero.append(seal,heading);
|
||||
const cards=el('div',undefined,'cards'),card=el('article',undefined,'card full citizen-page-full'),host=el('div',undefined,'citizen-live-host');card.append(host);cards.append(card);content.replaceChildren(hero,cards);
|
||||
dispose=page[0]==='election-boards'?mountNativeService(host,'election-boards',{singleHeading:true}):route.tab==='decisions'?mountPolicyDecisions(host,page[0].slice('decisions-'.length)):['office-register','imperial-senate','small-council'].includes(page[0])?mountOfficeRegister(host,page[0]):mountPoliticsPage(host,page[0]);
|
||||
history.replaceState(null,'','#'+key);if(parent!==window)parent.postMessage({type:'dune-politics-route',tab:route.tab,page:route.page},outer);
|
||||
sidebar.classList.remove('open');sidebarRight.classList.remove('open');document.querySelector('#mobile-menu').setAttribute('aria-expanded','false');schedule();
|
||||
}
|
||||
function mountOfficeRegister(host,view='office-register'){
|
||||
const controller=new AbortController();let active=true;const status=el('p','Checking the public office register…');status.setAttribute('role','status');host.append(status);
|
||||
fetch('/api/public/government',{credentials:'same-origin',cache:'no-store',signal:controller.signal}).then(async response=>{const data=await response.json();if(!response.ok)throw Error(data.message||'Office register unavailable.');if(!active)return;const grid=el('div',undefined,'politics-office-grid');
|
||||
for(const office of data.offices.filter(o=>view==='office-register'||o.chamber===(view==='imperial-senate'?'Imperial Senate':'Small Council'))){const card=el('article',undefined,'politics-office-card'),image=el('img');image.src=outer+'/assets/seals/'+office.art;image.alt='';image.width=image.height=76;card.append(image,el('small',office.scope),el('h2',office.name),el('p',office.description));if(office.holder){const link=el('a',office.holder.name);link.href=outer+'/people/'+encodeURIComponent(office.holder.username);link.target='_top';card.append(el('strong','In office'),link);}else card.append(el('p',office.state==='vacant'?'Awaiting an elected officeholder.':'Officeholder verification pending.'));grid.append(card);}
|
||||
host.replaceChildren(grid);
|
||||
}).catch(error=>{if(active)status.textContent=error.message;});return()=>{active=false;controller.abort();};
|
||||
}
|
||||
watchMenuHighlights(document.body);
|
||||
tabs.hidden=true;tabs.replaceChildren();
|
||||
document.querySelector('#mobile-menu').onclick=()=>{const open=sidebar.classList.toggle('open');sidebarRight.classList.toggle('open',open);document.querySelector('#mobile-menu').setAttribute('aria-expanded',String(open));};
|
||||
window.addEventListener('hashchange',show);window.addEventListener('pagehide',()=>{dispose();observer.disconnect();},{once:true});
|
||||
startCPAuthentication(user=>{if(!user.permissions?.includes('web.menu.game')){tabs.hidden=true;sidebar.hidden=true;sidebarRight.hidden=true;content.replaceChildren(el('p','Your account does not have access to the political chambers.'));return;}ready=true;show();});
|
||||
|
|
@ -1,50 +1,2 @@
|
|||
import {mountNativeService} from './cp-v2-native-services.mjs';
|
||||
import {mountPolicyDecisions} from './cp-v2-politics-decisions.mjs';
|
||||
import {watchMenuHighlights} from './cp-v2-menu-highlights.mjs';
|
||||
import {startCPAuthentication} from './cp-v2-auth.mjs';
|
||||
import {mountPoliticsPage} from './cp-v2-politics-pages.mjs';
|
||||
import {element as el} from './cp-v2-page-template.mjs';
|
||||
import {ELECTIONS} from '../political-catalog.mjs';
|
||||
import {POLITICAL_TABS,politicalRoute} from './cp-v2-politics-navigation.mjs';
|
||||
const outer='https://www.dunerealms.com',content=document.querySelector('#content'),sidebar=document.querySelector('#sidebar'),sidebarRight=document.querySelector('#sidebar-right'),tabs=document.querySelector('#portals');
|
||||
const artwork={elections:'seals/office-house_leader.png',offices:'seals/office-landsraad.png',tools:'seals/emperor-v1.png',decisions:'seals/office-landsraad.png'};
|
||||
const icon=tab=>{const image=el('img');image.src=outer+'/assets/'+artwork[tab];image.alt='';return image;};
|
||||
let ready=false,dispose=()=>{},current='',queued=false,lastHeight=0;
|
||||
document.body.classList.toggle('politics-cp-embedded',parent!==window);
|
||||
function measure(){queued=false;if(parent===window)return;const height=Math.ceil(Math.max(document.body.scrollHeight,document.body.getBoundingClientRect().height))+2;if(height!==lastHeight&&height>=100&&height<=200000){lastHeight=height;parent.postMessage({type:'dune-embed-size',height},outer);}}
|
||||
function schedule(){if(!queued){queued=true;requestAnimationFrame(measure);}}
|
||||
const observer=new ResizeObserver(schedule);observer.observe(document.body);
|
||||
window.addEventListener('message',event=>{if(event.source===parent&&event.origin===outer&&event.data?.type==='dune-embed-measure')schedule();});
|
||||
function show(){
|
||||
if(!ready)return;const route=politicalRoute(location.hash),key=route.tab+'/'+route.page;if(key===current)return;current=key;dispose();dispose=()=>{};
|
||||
const tab=POLITICAL_TABS.find(t=>t.id===route.tab),page=tab.pages.find(([id])=>id===route.page);
|
||||
content.setAttribute('aria-label',page[1]);
|
||||
sidebar.replaceChildren(el('div','ELECTION CHAMBERS','side-hero'));sidebarRight.replaceChildren(el('div','OFFICES & INSTRUMENTS','side-hero'));
|
||||
const menu=(host,title,items)=>{const block=el('section',undefined,'category-block');const summary=el('div',title,'category-heading'),links=el('div',undefined,'category-links');for(const[id,label]of items){const group=POLITICAL_TABS.find(t=>t.pages.some(([p])=>p===id));const link=el('a',undefined,'navitem');link.href='#'+group.id+'/'+id;link.dataset.menuHref=outer+'/government.html'+link.getAttribute('href');link.append(icon(group.id==='directory'?'elections':group.id),el('span',label));if(id===page[0])link.setAttribute('aria-current','page');links.append(link);}block.append(summary,links);host.append(block);};
|
||||
menu(sidebar,'Imperial Senate',[['imperial-elections','Emperor election'],['house-elections','House Leader elections']]);
|
||||
menu(sidebar,'Small Council',ELECTIONS.filter(e=>e.chamber==='Small Council').map(e=>['election-'+e.id,e.label]));
|
||||
menu(sidebar,'Voting Directory',POLITICAL_TABS.find(t=>t.id==='directory').pages);
|
||||
menu(sidebar,'Decisions & Schemes',POLITICAL_TABS.find(t=>t.id==='decisions').pages);
|
||||
menu(sidebar,'Participation',[['applications','My applications'],['electoral-roll','Electoral Roll']]);
|
||||
if(route.tab==='decisions'){const status=el('section',undefined,'policy-watch');for(const title of ['Active orders','Preparations','Commitments & alerts'])status.append(el('h3',title),el('p','Records will appear here when these powers become available.'));sidebarRight.append(status);}
|
||||
menu(sidebarRight,'Offices',[['office-register','All offices'],['imperial-senate','Imperial Senate'],['small-council','Small Council'],['politics-overview','My political record']]);
|
||||
menu(sidebarRight,'Councils',[['landsraad','Landsraad assembly'],['formal-council','House council'],['imperial-command','Imperial council']]);
|
||||
menu(sidebarRight,'Tools',POLITICAL_TABS.find(t=>t.id==='tools').pages);
|
||||
const hero=el('header',undefined,'hero'),seal=el('img'),heading=el('div');seal.src=outer+'/assets/seals/office-landsraad.png';seal.alt='';heading.append(el('h1',page[1]),el('p',tab.id==='decisions'?'Decisions and schemes of this office · Economic, Political and Communal.':tab.id==='directory'?'Meet the candidates, explore their campaigns and cast your eligible votes.':tab.id==='elections'?'Candidatures, verified eligibility and the existing ballots.':tab.id==='offices'?'The offices, councils and elected representatives of the realms.':'Proclamations and the existing government instruments.'));hero.append(seal,heading);
|
||||
const cards=el('div',undefined,'cards'),card=el('article',undefined,'card full citizen-page-full'),host=el('div',undefined,'citizen-live-host');card.append(host);cards.append(card);content.replaceChildren(hero,cards);
|
||||
dispose=page[0]==='election-boards'?mountNativeService(host,'election-boards',{singleHeading:true}):route.tab==='decisions'?mountPolicyDecisions(host,page[0].slice('decisions-'.length)):['office-register','imperial-senate','small-council'].includes(page[0])?mountOfficeRegister(host,page[0]):mountPoliticsPage(host,page[0]);
|
||||
history.replaceState(null,'','#'+key);if(parent!==window)parent.postMessage({type:'dune-politics-route',tab:route.tab,page:route.page},outer);
|
||||
sidebar.classList.remove('open');sidebarRight.classList.remove('open');document.querySelector('#mobile-menu').setAttribute('aria-expanded','false');schedule();
|
||||
}
|
||||
function mountOfficeRegister(host,view='office-register'){
|
||||
const controller=new AbortController();let active=true;const status=el('p','Checking the public office register…');status.setAttribute('role','status');host.append(status);
|
||||
fetch('/api/public/government',{credentials:'same-origin',cache:'no-store',signal:controller.signal}).then(async response=>{const data=await response.json();if(!response.ok)throw Error(data.message||'Office register unavailable.');if(!active)return;const grid=el('div',undefined,'politics-office-grid');
|
||||
for(const office of data.offices.filter(o=>view==='office-register'||o.chamber===(view==='imperial-senate'?'Imperial Senate':'Small Council'))){const card=el('article',undefined,'politics-office-card'),image=el('img');image.src=outer+'/assets/seals/'+office.art;image.alt='';image.width=image.height=76;card.append(image,el('small',office.scope),el('h2',office.name),el('p',office.description));if(office.holder){const link=el('a',office.holder.name);link.href=outer+'/people/'+encodeURIComponent(office.holder.username);link.target='_top';card.append(el('strong','In office'),link);}else card.append(el('p',office.state==='vacant'?'Awaiting an elected officeholder.':'Officeholder verification pending.'));grid.append(card);}
|
||||
host.replaceChildren(grid);
|
||||
}).catch(error=>{if(active)status.textContent=error.message;});return()=>{active=false;controller.abort();};
|
||||
}
|
||||
watchMenuHighlights(document.body);
|
||||
tabs.hidden=true;tabs.replaceChildren();
|
||||
document.querySelector('#mobile-menu').onclick=()=>{const open=sidebar.classList.toggle('open');sidebarRight.classList.toggle('open',open);document.querySelector('#mobile-menu').setAttribute('aria-expanded',String(open));};
|
||||
window.addEventListener('hashchange',show);window.addEventListener('pagehide',()=>{dispose();observer.disconnect();},{once:true});
|
||||
startCPAuthentication(user=>{if(!user.permissions?.includes('web.menu.game')){tabs.hidden=true;sidebar.hidden=true;sidebarRight.hidden=true;content.replaceChildren(el('p','Your account does not have access to the political chambers.'));return;}ready=true;show();});
|
||||
import {startOrganisationCP} from './cp-v2-organisation-shell.mjs';
|
||||
startOrganisationCP('politics');
|
||||
|
|
|
|||
|
|
@ -1,42 +1,42 @@
|
|||
import {organisationCodeIs,parseOrganisationCode} from '../codex-code-format.mjs';
|
||||
import {createCodeTypeIcon} from './cp-v2-code-type-icon.mjs';
|
||||
import {createCPV2Page,element as el} from './cp-v2-page-template.mjs';
|
||||
import {createCodeRedemption,createCodeOfficeBranding} from './cp-v2-code-redemption.mjs';
|
||||
import {createUserAPI} from './cp-v2-user-api.mjs';
|
||||
import {kitReceiptStatus,groupKitReceipts} from '../kit-receipt-status.mjs';
|
||||
|
||||
export function privateKitCodes(orders){return groupKitReceipts(orders).purchases.filter(row=>kitReceiptStatus(row).canRedeem&&typeof row.code==='string'&&/^DRK-[A-Z2-7]{32}$/.test(row.code));}
|
||||
export function redemptionRequest(value,confirmed){
|
||||
if(confirmed!==true)throw Error('Confirm that you want to redeem this private code.');
|
||||
const code=String(value||'').trim().toUpperCase();
|
||||
if(/^DRK-[A-Z2-7]{32}$/.test(code))return {path:'/api/kits/redeem',body:{code},kind:'kit'};
|
||||
if(/^DRQ-[A-F0-9]{40}$/.test(code))return {path:'/api/quest/rewards/claim',body:{code},kind:'discovery'};
|
||||
if(/^DRU-/.test(code))throw Error('Use Upgrade Tokens inside your saved Legendary Player Kit in Imperial Tailor.');
|
||||
throw Error('Enter a complete kit (DRK) or discovery (DRQ) code. Community commands are redeemed in game.');
|
||||
}
|
||||
function table(target,head,rows){const wrap=el('div',undefined,'cp-v2-company-table-wrap'),t=el('table',undefined,'cp-v2-company-table'),thead=el('thead'),heading=el('tr'),tbody=el('tbody');for(const label of head){const th=el('th',label);th.scope='col';heading.append(th);}thead.append(heading);for(const values of rows){const tr=el('tr');for(const value of values){const td=el('td');if(typeof value==='object'&&value!==null)td.append(value);else td.textContent=String(value??'—');tr.append(td);}tbody.append(tr);}if(!rows.length){const tr=el('tr'),td=el('td','No records in this view.');td.colSpan=head.length;tr.append(td);tbody.append(tr);}t.append(thead,tbody);wrap.append(t);target.replaceChildren(wrap);}
|
||||
export function mountRewards(host,{fetcher=fetch,initialTab}={}){
|
||||
let active=true,busy=false,uncertain=false,orders=[];const controller=new AbortController(),{request}=createUserAPI(fetcher,controller.signal);
|
||||
const codes=el('section'),community=el('section'),tokens=el('section'),refresh=el('button','Refresh codes'),status=el('p','Opening your private rewards register…');status.setAttribute('role','status');refresh.type='button';codes.append(refresh);
|
||||
const directory=el('section',undefined,'reward-code-directory'),filter=el('input'),typeFilter=el('select'),listing=el('div'),groups=new Map();filter.type='search';filter.placeholder='Search codes, rewards or references';filter.setAttribute('aria-label','Search your codes');typeFilter.setAttribute('aria-label','Filter code type');for(const [value,label] of [['all','All code types'],['kit','Kits'],['token','Upgrade Tokens'],['clan','Clan founding'],['company','Company founding'],['politics','Royal appointments'],['community','Community rewards']]){const option=el('option',label);option.value=value;typeFilter.append(option);}const controls=el('div',undefined,'reward-code-controls');controls.append(filter,typeFilter);const banner=el('header',undefined,'reward-code-banner'),crest=el('img');crest.src='https://www.dunerealms.com/assets/imperial-seal-128.png';crest.alt='';const copy=el('div');copy.append(el('small','SPOST · PRIVATE ENTITLEMENT REGISTER'),el('h4','Your codes. Your next chapter.'),el('p','Kits KIT-… · Upgrades UP-… · Clans CLAN-… · Companies COM-… · Royal POL-…'));banner.append(crest,copy);directory.append(banner,controls,listing);codes.append(status,directory);
|
||||
function paintCodes(){const q=filter.value.trim().toLowerCase(),rows=[];for(const [kind,group] of groups){if(typeFilter.value!=='all'&&typeFilter.value!==kind)continue;for(const row of group.rows){if(q&&!([group.title,...row.map(v=>typeof v==='object'?v.textContent:v)].join(' ').toLowerCase().includes(q)))continue;rows.push([createCodeTypeIcon(kind),...row]);}}table(listing,['Type','Reward / entitlement','Reference / amount','Status','Private code / action'],rows);}
|
||||
function setCodes(kind,title,rows){groups.set(kind,{title,rows:rows.length?rows:[[title+' register','—','No records','—']]});paintCodes();}
|
||||
for(const [kind,title] of [['clan','Clan founding'],['company','Company founding']])setCodes(kind,title,[[title+' register','Once per account','Loading…','—']]);for(const [kind,title] of [['kit','Kit'],['token','Upgrade Token'],['community','Community reward']])setCodes(kind,title,[[title+' register','—','Loading…','—']]);filter.oninput=typeFilter.onchange=paintCodes;const tailor=el('a','Apply Upgrade Tokens in Imperial Tailor →');tailor.href='#realm/kits-exchange';directory.append(tailor);directory.append(el('p','Clan and Royal grants appear here after issuance. Applied grants are receipts and cannot be reused. Formats: KIT-…, UP-…, CLAN-… and COM-…. Existing DRK/DRU codes remain valid.','reward-code-note'));
|
||||
import {createCPV2Page,element as el} from './cp-v2-page-template.mjs';
|
||||
import {createCodeRedemption,createCodeOfficeBranding} from './cp-v2-code-redemption.mjs';
|
||||
import {createUserAPI} from './cp-v2-user-api.mjs';
|
||||
import {kitReceiptStatus,groupKitReceipts} from '../kit-receipt-status.mjs';
|
||||
|
||||
const desk=createCodeRedemption(),{form,input,check,result}=desk,redemption=desk.root;
|
||||
const {root,activate}=createCPV2Page({shellHost:host,title:'Codes & founding rights',description:'Your private rewards, founding rights and political appointments.',artwork:'imperial-seal-128.png',tabs:[{id:'unclaimed-codes',label:'Your codes',content:codes},{id:'redeem',label:'Redeem a code',content:redemption}]});root.append(createCodeOfficeBranding());host.replaceChildren(root);redemption.addEventListener('show-code-register',()=>activate('unclaimed-codes'));if(initialTab==='redeem')activate(initialTab);
|
||||
function codeCell(code,command=false){const details=el('details');details.append(el('summary',command?'Show private command':'Show private code'),el('code',code));try{const {edition}=parseOrganisationCode(code);if(edition){const info=el('small',edition.stage.toUpperCase()+' '+edition.version+' · '+edition.season);info.className='reward-code-edition';details.append(info);}}catch{}const copy=el('button','Copy');copy.type='button';copy.onclick=async()=>{try{await navigator.clipboard.writeText(code);if(active)copy.textContent='Copied';}catch{if(active)copy.textContent='Select and copy the code above';}};details.append(copy);if(organisationCodeIs(code,'CLAN')){const use=el('button','Use clan key');use.type='button';use.onclick=()=>{activate('redeem');input.value=code;input.dispatchEvent(new Event('input'));input.focus();};details.append(use);}return details;}
|
||||
function render(){setCodes('kit','Kit',privateKitCodes(orders).map(row=>[row.name,row.orderId,kitReceiptStatus(row).label,codeCell(row.code)]));}
|
||||
async function load(){if(busy)return;busy=true;refresh.disabled=true;desk.setLocked(true);status.textContent='Loading current private entitlements…';
|
||||
try{const session=await request('/api/auth/session');if(!session.authenticated)throw Error('Sign in to open your private rewards.');if(session.user?.username?.toLowerCase()==='dev')throw Error('The Dev service exemption does not receive player rewards.');
|
||||
const data=await Promise.allSettled([request('/api/kits/orders'),request('/api/community/rewards'),request('/api/kits/upgrade-tokens'),request('/api/organisation-keys')]);if(!active)return;
|
||||
if(data[0].status==='fulfilled'){orders=data[0].value.orders;groupKitReceipts(orders);render();uncertain=false;}else{orders=[];setCodes('kit','Kit',[['Kit register','—',data[0].reason.message,'—']]);}
|
||||
community.replaceChildren();if(data[1].status==='fulfilled'){const d=data[1].value;if(!Array.isArray(d.available)||!Array.isArray(d.history))setCodes('community','Community reward',[['Community register','—','Community reward records could not be confirmed.','—']]);else{setCodes('community','Community reward',[...d.available,...d.history].map(row=>[row.month==='season-tavren-ii'?'Tavren II Aedrecht':row.month,row.reward_amount+' DM',row.delivered_at?'Delivered':row.delivery_ready===false?'Delivery not available':'Available',row.personal_code&&row.delivery_ready!==false&&/^[a-z0-9-]{8,128}$/i.test(row.personal_code)?codeCell('/communitycode '+row.personal_code,true):'—']));if(!d.linked)community.append(el('p','Link your Minecraft identity to see earned community rewards.'));}}else setCodes('community','Community reward',[['Community register','—',data[1].reason.message,'—']]);
|
||||
tokens.replaceChildren();if(data[2].status==='fulfilled'&&Array.isArray(data[2].value.tokens)){setCodes('token','Upgrade Token',data[2].value.tokens.map(row=>['Upgrade Token',new Date(row.createdAt).toLocaleString(),row.usedAt?'Used':'Available',!row.usedAt&&/^DRU-[A-F0-9]{48}$/.test(row.code||'')?codeCell(row.code):'—']));const workshop=el('a','Apply tokens in Imperial Tailor →');workshop.href='#realm/kits-exchange';tokens.append(workshop);}else setCodes('token','Upgrade Token',[['Token register','—',data[2].reason?.message||'Upgrade Token records could not be confirmed.','—']]);
|
||||
if(data[3].status==='fulfilled'){const records=data[3].value.keys||[];for(const [kind,title]of [['clan','Clan founding'],['company','Company founding'],['politics','Royal appointment']])setCodes(kind,title,records.filter(r=>r.type===kind).map(r=>[r.clan||title,r.id,r.status,r.status==='Applied'?'Applied to '+(r.clan||'your organisation')+' · '+(r.charter==='royal'?'Royal House':'Keyed House'):r.code?codeCell(r.code):'—']));}else for(const [kind,title]of [['clan','Clan founding'],['company','Company founding'],['politics','Royal appointment']])setCodes(kind,title,[[title,'—',data[3].reason.message,'—']]);
|
||||
status.textContent=data.every(row=>row.status==='fulfilled')?'Your private reward records are loaded.':'Some reward services are unavailable. Other records remain visible.';
|
||||
}catch(error){if(active){status.textContent=error.message;groups.clear();paintCodes();orders=[];community.replaceChildren();tokens.replaceChildren();uncertain=true;}}finally{busy=false;if(active){refresh.disabled=false;desk.setLocked(uncertain);}}
|
||||
}
|
||||
form.onsubmit=async event=>{event.preventDefault();if(busy||uncertain)return;let payload;try{const code=desk.reviewedCode();if(organisationCodeIs(code,'CLAN')){payload={kind:'clan',code};}else payload=redemptionRequest(code,check.checked);}catch(error){result.textContent=error.message;return;}busy=true;refresh.disabled=true;desk.setLocked(true);result.textContent='Presenting your code…';try{if(payload.kind==='clan'){const membership=(await request('/api/clans')).membership;if(!membership)throw Error('Create your Basic clan first, then return here to use your key.');const detail=await request('/api/clans/'+encodeURIComponent(membership.clan_id));if(detail.role!=='owner'||!detail.canManage)throw Error('Only the current linked owner can upgrade their Basic clan.');if(detail.clan.charterKind!=='basic')throw Error('Your clan already has an Original or Royal charter.');payload.path='/api/organisation-keys';payload.body={code:payload.code,clanId:membership.clan_id,version:detail.clan.version,requestId:crypto.randomUUID(),confirmed:true};}const d=await request(payload.path,payload.body);if(payload.kind==='clan'&&(d.ok!==true||d.charter!=='original'||d.clanId!==payload.body.clanId))throw Object.assign(Error('Clan upgrade was not confirmed. Refresh your codes before retrying.'),{uncertain:true});if(!active)return;if(payload.kind==='discovery'&&(d.ok!==true||typeof d.credited!=='boolean'||d.amount!==1000))throw Object.assign(Error('Discovery credit was not confirmed.'),{uncertain:true});if(payload.kind==='kit'&&!['queued','delivered','pending','claimed','redeemed','pending_delivery'].includes(d.status))throw Object.assign(Error('The delivery result was not confirmed.'),{uncertain:true});desk.reset();busy=false;await load();if(active)result.textContent=payload.kind==='clan'?'Your clan is now an Original House. Its founding key has been used; Royal status still requires a political appointment.':payload.kind==='kit'?(d.status==='delivered'?'Delivery is already confirmed by the game.':'Delivery requested. Join a planetary server with four empty inventory slots; the game confirms arrival.'):(d.credited?'Your earned 1,000 DM reward was credited.':'This reward was already redeemed; no duplicate credit was made.');}catch(error){if(active){uncertain=!!error.uncertain;result.textContent=error.message+(uncertain?' Refresh your codes and check the result before retrying.':'');}}finally{busy=false;if(active){refresh.disabled=false;desk.setLocked(uncertain);}}};
|
||||
refresh.onclick=()=>void load();void load();return()=>{active=false;controller.abort();input.value='';orders=[];root.remove();};
|
||||
}
|
||||
export function privateKitCodes(orders){return groupKitReceipts(orders).purchases.filter(row=>kitReceiptStatus(row).canRedeem&&typeof row.code==='string'&&/^DRK-[A-Z2-7]{32}$/.test(row.code));}
|
||||
export function redemptionRequest(value,confirmed){
|
||||
if(confirmed!==true)throw Error('Confirm that you want to redeem this private code.');
|
||||
const code=String(value||'').trim().toUpperCase();
|
||||
if(/^DRK-[A-Z2-7]{32}$/.test(code))return {path:'/api/kits/redeem',body:{code},kind:'kit'};
|
||||
if(/^DRQ-[A-F0-9]{40}$/.test(code))return {path:'/api/quest/rewards/claim',body:{code},kind:'discovery'};
|
||||
if(/^DRU-/.test(code))throw Error('Use Upgrade Tokens inside your saved Legendary Player Kit in Imperial Tailor.');
|
||||
throw Error('Enter a complete kit (DRK) or discovery (DRQ) code. Community commands are redeemed in game.');
|
||||
}
|
||||
function table(target,head,rows){const wrap=el('div',undefined,'cp-v2-company-table-wrap'),t=el('table',undefined,'cp-v2-company-table'),thead=el('thead'),heading=el('tr'),tbody=el('tbody');for(const label of head){const th=el('th',label);th.scope='col';heading.append(th);}thead.append(heading);for(const values of rows){const tr=el('tr');for(const value of values){const td=el('td');if(typeof value==='object'&&value!==null)td.append(value);else td.textContent=String(value??'—');tr.append(td);}tbody.append(tr);}if(!rows.length){const tr=el('tr'),td=el('td','No records in this view.');td.colSpan=head.length;tr.append(td);tbody.append(tr);}t.append(thead,tbody);wrap.append(t);target.replaceChildren(wrap);}
|
||||
export function mountRewards(host,{fetcher=fetch,initialTab}={}){
|
||||
let active=true,busy=false,uncertain=false,orders=[];const controller=new AbortController(),{request}=createUserAPI(fetcher,controller.signal);
|
||||
const codes=el('section'),community=el('section'),tokens=el('section'),refresh=el('button','Refresh codes'),status=el('p','Opening your private rewards register…');status.setAttribute('role','status');refresh.type='button';codes.append(refresh);
|
||||
const directory=el('section',undefined,'reward-code-directory'),filter=el('input'),typeFilter=el('select'),listing=el('div'),groups=new Map();filter.type='search';filter.placeholder='Search codes, rewards or references';filter.setAttribute('aria-label','Search your codes');typeFilter.setAttribute('aria-label','Filter code type');for(const [value,label] of [['all','All code types'],['kit','Kits'],['token','Upgrade Tokens'],['clan','Clan founding'],['company','Company clan founding'],['politics-clan','Political clan membership'],['subhouse','Subhouse founding'],['subsidiary','Subsidiary founding'],['politics','Political decisions'],['community','Community rewards']]){const option=el('option',label);option.value=value;typeFilter.append(option);}const controls=el('div',undefined,'reward-code-controls');controls.append(filter,typeFilter);const banner=el('header',undefined,'reward-code-banner'),crest=el('img');crest.src='https://www.dunerealms.com/assets/imperial-seal-128.png';crest.alt='';const copy=el('div');copy.append(el('small','SPOST · PRIVATE ENTITLEMENT REGISTER'),el('h4','Your codes. Your next chapter.'),el('p','Kits KIT-… · Upgrades UP-… · Clans CLAN-… · Companies COM-… · Royal POL-…'));banner.append(crest,copy);directory.append(banner,controls,listing);codes.append(status,directory);
|
||||
function paintCodes(){const q=filter.value.trim().toLowerCase(),rows=[];for(const [kind,group] of groups){if(typeFilter.value!=='all'&&typeFilter.value!==kind)continue;for(const row of group.rows){if(q&&!([group.title,...row.map(v=>typeof v==='object'?v.textContent:v)].join(' ').toLowerCase().includes(q)))continue;rows.push([createCodeTypeIcon(kind),...row]);}}table(listing,['Type','Reward / entitlement','Reference / amount','Status','Private code / action'],rows);}
|
||||
function setCodes(kind,title,rows){groups.set(kind,{title,rows:rows.length?rows:[[title+' register','—','No records','—']]});paintCodes();}
|
||||
for(const [kind,title] of [['clan','Clan founding'],['company','Company clan founding'],['politics-clan','Political clan membership'],['subhouse','Subhouse founding'],['subsidiary','Subsidiary founding']])setCodes(kind,title,[[title+' register','Once per account','Loading…','—']]);for(const [kind,title] of [['kit','Kit'],['token','Upgrade Token'],['community','Community reward']])setCodes(kind,title,[[title+' register','—','Loading…','—']]);filter.oninput=typeFilter.onchange=paintCodes;const tailor=el('a','Apply Upgrade Tokens in Imperial Tailor →');tailor.href='#realm/kits-exchange';directory.append(tailor);directory.append(el('p','Clan and Royal grants appear here after issuance. Applied grants are receipts and cannot be reused. Formats: KIT-…, UP-…, CLAN-… and COM-…. Existing DRK/DRU codes remain valid.','reward-code-note'));
|
||||
|
||||
const desk=createCodeRedemption(),{form,input,check,result}=desk,redemption=desk.root;
|
||||
const {root,activate}=createCPV2Page({shellHost:host,title:'Codes & founding rights',description:'Your private rewards, founding rights and political appointments.',artwork:'imperial-seal-128.png',tabs:[{id:'unclaimed-codes',label:'Your codes',content:codes},{id:'redeem',label:'Redeem a code',content:redemption}]});root.append(createCodeOfficeBranding());host.replaceChildren(root);redemption.addEventListener('show-code-register',()=>activate('unclaimed-codes'));if(initialTab==='redeem')activate(initialTab);
|
||||
function codeCell(code,command=false){const details=el('details');details.append(el('summary',command?'Show private command':'Show private code'),el('code',code));try{const {edition}=parseOrganisationCode(code);if(edition){const info=el('small',edition.stage.toUpperCase()+' '+edition.version+' · '+edition.season);info.className='reward-code-edition';details.append(info);}}catch{}const copy=el('button','Copy');copy.type='button';copy.onclick=async()=>{try{await navigator.clipboard.writeText(code);if(active)copy.textContent='Copied';}catch{if(active)copy.textContent='Select and copy the code above';}};details.append(copy);if(organisationCodeIs(code,'CLAN')){const use=el('button','Use clan key');use.type='button';use.onclick=()=>{activate('redeem');input.value=code;input.dispatchEvent(new Event('input'));input.focus();};details.append(use);}return details;}
|
||||
function render(){setCodes('kit','Kit',privateKitCodes(orders).map(row=>[row.name,row.orderId,kitReceiptStatus(row).label,codeCell(row.code)]));}
|
||||
async function load(){if(busy)return;busy=true;refresh.disabled=true;desk.setLocked(true);status.textContent='Loading current private entitlements…';
|
||||
try{const session=await request('/api/auth/session');if(!session.authenticated)throw Error('Sign in to open your private rewards.');if(session.user?.username?.toLowerCase()==='dev')throw Error('The Dev service exemption does not receive player rewards.');
|
||||
const data=await Promise.allSettled([request('/api/kits/orders'),request('/api/community/rewards'),request('/api/kits/upgrade-tokens'),request('/api/organisation-keys')]);if(!active)return;
|
||||
if(data[0].status==='fulfilled'){orders=data[0].value.orders;groupKitReceipts(orders);render();uncertain=false;}else{orders=[];setCodes('kit','Kit',[['Kit register','—',data[0].reason.message,'—']]);}
|
||||
community.replaceChildren();if(data[1].status==='fulfilled'){const d=data[1].value;if(!Array.isArray(d.available)||!Array.isArray(d.history))setCodes('community','Community reward',[['Community register','—','Community reward records could not be confirmed.','—']]);else{setCodes('community','Community reward',[...d.available,...d.history].map(row=>[row.month==='season-tavren-ii'?'Tavren II Aedrecht':row.month,row.reward_amount+' DM',row.delivered_at?'Delivered':row.delivery_ready===false?'Delivery not available':'Available',row.personal_code&&row.delivery_ready!==false&&/^[a-z0-9-]{8,128}$/i.test(row.personal_code)?codeCell('/communitycode '+row.personal_code,true):'—']));if(!d.linked)community.append(el('p','Link your Minecraft identity to see earned community rewards.'));}}else setCodes('community','Community reward',[['Community register','—',data[1].reason.message,'—']]);
|
||||
tokens.replaceChildren();if(data[2].status==='fulfilled'&&Array.isArray(data[2].value.tokens)){setCodes('token','Upgrade Token',data[2].value.tokens.map(row=>['Upgrade Token',new Date(row.createdAt).toLocaleString(),row.usedAt?'Used':'Available',!row.usedAt&&/^DRU-[A-F0-9]{48}$/.test(row.code||'')?codeCell(row.code):'—']));const workshop=el('a','Apply tokens in Imperial Tailor →');workshop.href='#realm/kits-exchange';tokens.append(workshop);}else setCodes('token','Upgrade Token',[['Token register','—',data[2].reason?.message||'Upgrade Token records could not be confirmed.','—']]);
|
||||
if(data[3].status==='fulfilled'){const records=data[3].value.keys||[];for(const [kind,title]of [['clan','Clan founding'],['company','Company clan founding'],['politics-clan','Political clan membership'],['subhouse','Subhouse founding'],['subsidiary','Subsidiary founding'],['politics','Royal appointment']])setCodes(kind,title,records.filter(r=>r.type===kind).map(r=>[r.clan||title,r.id,r.status,r.status==='Applied'?'Applied to '+(r.clan||'your organisation')+' · '+(['subhouse','subsidiary'].includes(r.type)?'Parent-bound charter':r.type==='politics-clan'?'Office membership':r.charter==='royal'?'Royal House':'Registered charter'):r.code?codeCell(r.code):'—']));}else for(const [kind,title]of [['clan','Clan founding'],['company','Company clan founding'],['politics-clan','Political clan membership'],['subhouse','Subhouse founding'],['subsidiary','Subsidiary founding'],['politics','Royal appointment']])setCodes(kind,title,[[title,'—',data[3].reason.message,'—']]);
|
||||
status.textContent=data.every(row=>row.status==='fulfilled')?'Your private reward records are loaded.':'Some reward services are unavailable. Other records remain visible.';
|
||||
}catch(error){if(active){status.textContent=error.message;groups.clear();paintCodes();orders=[];community.replaceChildren();tokens.replaceChildren();uncertain=true;}}finally{busy=false;if(active){refresh.disabled=false;desk.setLocked(uncertain);}}
|
||||
}
|
||||
form.onsubmit=async event=>{event.preventDefault();if(busy||uncertain)return;let payload;try{const code=desk.reviewedCode();if(organisationCodeIs(code,'CLAN')){payload={kind:'clan',code};}else payload=redemptionRequest(code,check.checked);}catch(error){result.textContent=error.message;return;}busy=true;refresh.disabled=true;desk.setLocked(true);result.textContent='Presenting your code…';try{if(payload.kind==='clan'){const membership=(await request('/api/clans')).membership;if(!membership)throw Error('Create your Basic clan first, then return here to use your key.');const detail=await request('/api/clans/'+encodeURIComponent(membership.clan_id));if(detail.role!=='owner'||!detail.canManage)throw Error('Only the current linked owner can upgrade their Basic clan.');if(detail.clan.charterKind!=='basic')throw Error('Your clan already has an Original or Royal charter.');payload.path='/api/organisation-keys';payload.body={code:payload.code,clanId:membership.clan_id,version:detail.clan.version,requestId:crypto.randomUUID(),confirmed:true};}const d=await request(payload.path,payload.body);if(payload.kind==='clan'&&(d.ok!==true||d.charter!=='original'||d.clanId!==payload.body.clanId))throw Object.assign(Error('Clan upgrade was not confirmed. Refresh your codes before retrying.'),{uncertain:true});if(!active)return;if(payload.kind==='discovery'&&(d.ok!==true||typeof d.credited!=='boolean'||d.amount!==1000))throw Object.assign(Error('Discovery credit was not confirmed.'),{uncertain:true});if(payload.kind==='kit'&&!['queued','delivered','pending','claimed','redeemed','pending_delivery'].includes(d.status))throw Object.assign(Error('The delivery result was not confirmed.'),{uncertain:true});desk.reset();busy=false;await load();if(active)result.textContent=payload.kind==='clan'?'Your clan is now an Original House. Its founding key has been used; Royal status still requires a political appointment.':payload.kind==='kit'?(d.status==='delivered'?'Delivery is already confirmed by the game.':'Delivery requested. Join a planetary server with four empty inventory slots; the game confirms arrival.'):(d.credited?'Your earned 1,000 DM reward was credited.':'This reward was already redeemed; no duplicate credit was made.');}catch(error){if(active){uncertain=!!error.uncertain;result.textContent=error.message+(uncertain?' Refresh your codes and check the result before retrying.':'');}}finally{busy=false;if(active){refresh.disabled=false;desk.setLocked(uncertain);}}};
|
||||
refresh.onclick=()=>void load();void load();return()=>{active=false;controller.abort();input.value='';orders=[];root.remove();};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,25 +1,25 @@
|
|||
import {organisationTabs} from './organisation-tabs.mjs';
|
||||
import {claimDisplayName} from './cp-v2/cp-v2-claim-tariffs.mjs';
|
||||
import {claimTariffs} from './cp-v2/cp-v2-claim-tariffs.mjs';
|
||||
import {createActivityFeed} from './organisation-activity.mjs';
|
||||
// Shared presentation only. Callers supply verified records and existing navigation.
|
||||
const el=(tag,text,cls)=>{const node=document.createElement(tag);if(text!==undefined)node.textContent=text;if(cls)node.className=cls;return node;};
|
||||
const assets='https://www.dunerealms.com/assets/';
|
||||
export function createOrganisationDashboard({kind='clan',organisation,members=[],role,canReview=false,requests=[],onMembers,onRequests,loadMailbox,loadTreasury,loadClaims,activity=[],activityStatus}={}){
|
||||
if(!document.querySelector('link[data-organisation-dashboard]')){const css=el('link');css.rel='stylesheet';css.href=new URL('./organisation-dashboard.css',import.meta.url).href;css.dataset.organisationDashboard='';document.head.append(css);}
|
||||
const company=kind==='company',noun=company?'Company':'Clan',root=el('div',undefined,'organisation-dashboard');
|
||||
const backgrounds={'Members':'guild.webp','Applications':'political-small-council-v1.png','News & activity':'political-imperial-chamber-v1.png','Events':'clan-atelier-v1.webp','Treasury':'postbank-transfer-hall-v1.png','Land & claims':'guild.webp','Mailbox':'imperial-post-office-v1.png','Needs attention':'political-small-council-v1.png','Subhouses & subsidiaries':'clan-atelier-v1.webp'};
|
||||
function card(title,art,{pending=false}={}){const box=el('article',undefined,'organisation-dashboard-card'),header=el('header'),image=el('img');image.src=assets+art;image.alt='';image.width=image.height=48;box.dataset.dashboardCard=title.toLowerCase().replaceAll(/[^a-z]+/g,'-');box.style.setProperty('--dashboard-art','url("'+assets+(backgrounds[title]||'political-imperial-chamber-v1.png')+'")');header.append(image,el('h3',title));if(pending)header.append(el('span','Coming soon','organisation-dashboard-status'));box.append(header);root.append(box);return box;}
|
||||
function action(box,label,handler){const button=el('button',label);button.type='button';button.onclick=handler;box.append(button);}
|
||||
const welcome=card('Welcome to '+organisation.name,company?'clans/vaerkring-v1.png':'nav-clan-v2.webp');welcome.classList.add('organisation-dashboard-welcome');const emblem=welcome.querySelector('header img');if(organisation.emblem)emblem.src=organisation.emblem;welcome.append(el('small','YOUR '+noun.toUpperCase()+' · YOUR PEOPLE · YOUR NEXT CHAPTER'));const welcomeBoxes=el('div',undefined,'organisation-welcome-boxes');for(const [title,message] of [[noun+' description',organisation.description||'No introduction has been published yet.'],['Message of the day',organisation.motd||(role?'No message of the day has been published.':'The message of the day is visible to members.')]]){const box=el('section',undefined,'organisation-welcome-subbox');box.append(el('h4',title),el('p',message));welcomeBoxes.append(box);}welcome.append(welcomeBoxes,el('p','['+organisation.tag+'] · '+(organisation.homeworldName||'Homeworld not selected')+' · '+(organisation.titles?.[role]||{owner:noun+' owner',heir:'Heir',officer:'Officer',member:'Member'}[role]||'Visitor')));
|
||||
|
||||
const people=card('Members','nav-account-v2.webp'),faces=el('div',undefined,'organisation-dashboard-members');people.append(el('p',members.length+' '+(members.length===1?'member':'members')+' in the register'));
|
||||
for(const member of members.slice(0,8)){const link=el('a',undefined,'organisation-dashboard-member'),image=el('img'),copy=el('span');image.src='https://cp.dunerealms.com/api/avatars/face/roster/'+encodeURIComponent(member.username);image.alt='';image.width=image.height=44;image.loading='lazy';copy.append(el('strong',member.username),el('small',organisation.titles?.[member.clan_role||member.role]||({owner:noun+' owner',heir:'Heir',officer:'Officer',member:'Member'})[member.clan_role||member.role]||'Member'));link.href='https://www.dunerealms.com/people/'+encodeURIComponent(member.username);link.target='_top';link.append(image,copy);faces.append(link);}people.append(faces);if(onMembers)action(people,'View all members →',onMembers);
|
||||
const applications=card('Applications','nav-support-v2.webp');applications.append(el('p',canReview?(requests.length?requests.length+' '+(requests.length===1?'application awaits':'applications await')+' review.':'No applications are waiting for review.'):'Applications are reviewed by the owner and authorised officers.'));
|
||||
if(canReview){for(const request of requests.slice(0,3))applications.append(el('p',request.username,'organisation-dashboard-request'));if(onRequests)action(applications,'Review applications →',onRequests);}
|
||||
const news=card('News & activity','nav-manual-v2.webp');news.append(createActivityFeed(activity,{emptyMessage:activityStatus==='restricted'?'Activity is visible to organisation members.':activityStatus==='unavailable'?'Activity could not be loaded.':'No clan activity has been recorded yet.'}));
|
||||
for(const [title,art,message] of [['Events','nav-manual-full-v2.webp','Upcoming activities, dates and participation will appear here.'],['Treasury','imperial-postbank-v2.png','Available funds and the account reference will appear here once the authorised bank summary is connected.'],['Land & claims','clans/house-veyr-v1.png','Claims share one total chunk budget. Capacity upgrades will be performed ingame by right-clicking the Home Block.']]){const box=card(title,art,{pending:title==='Events'||title==='Land & claims'&&!loadClaims});box.append(el('p',message),el('small','Not connected yet · no records are shown.'));if(title==='Land & claims'){box.querySelectorAll('p,small').forEach(n=>n.remove());const note=el('p',loadClaims?'Checking your claim registry…':'Claims are not connected for this organisation yet.'),info=el('dl');box.append(note,info);if(loadClaims)Promise.resolve().then(loadClaims).then(view=>{if(!root.isConnected)return;if(view.state!=='connected')throw Error('unavailable');note.textContent='Your registered land and claim allowance.';for(const [label,value]of [['Estate rank',claimDisplayName(view.tier)],['Claimed chunks',view.usedChunks+' / '+view.capacity],['Available chunks',view.availableChunks],['Monthly upkeep',view.monthlyUpkeep]])info.append(el('dt',label),el('dd',String(value)));}).catch(()=>{if(root.isConnected)note.textContent='Claim records could not be loaded. Open Claims to refresh.';});const link=el('a','Open land & claims →');link.href=company?'https://corp.dunerealms.com/#company/company-claims':'https://clans.dunerealms.com/#clan/clan-claims';link.target='_top';box.append(link);}if(title==='Treasury'){const table=el('table');for(const [label,value] of [['Available funds','Not connected'],['Account','Authorised view required']]){const row=el('tr');row.append(el('th',label),el('td',value));table.append(row);}box.append(table);if(loadTreasury){box.querySelectorAll('p,small').forEach(n=>n.remove());table.replaceChildren();const note=el('p','Checking authorised clan funds…');box.append(note);Promise.resolve().then(loadTreasury).then(entity=>{if(!root.isConnected)return;note.textContent=entity.state==='not_activated'?'Clan banking has not been activated.':'Current accounts · Imperial Postbank';table.replaceChildren();for(const account of entity.accounts){const row=el('tr'),link=el('a',account.number);link.href='https://cp.dunerealms.com/#bank/bank-statements/'+encodeURIComponent(account.id);link.target='_top';const cell=el('td');cell.append(link);row.append(cell,el('td',account.available+' DM available'));table.append(row);}if(!entity.accounts.length&&entity.state!=='not_activated')note.textContent='No active current accounts are visible with your bank permissions.';}).catch(()=>{if(root.isConnected){table.replaceChildren();note.textContent='Clan funds could not be confirmed. Open Imperial Postbank to check your access.';}});}else{table.replaceChildren();box.querySelector('p').textContent='Clan funds are available only with authorised banking access.';}const bank=el('a','Open Imperial Postbank →');bank.href='https://cp.dunerealms.com/#bank/bank-overview';bank.target='_top';box.append(bank);}}
|
||||
const children=card('Subhouses & subsidiaries','clans/vaerkring-v1.png',{pending:true});children.append(el('p','Subordinate organisations will appear here. Claim rights and management pass to the mother organisation; upkeep and upgrade costs remain with the original organisation.'));const relations=el('table'),head=el('thead'),heading=el('tr');for(const label of ['Organisation','Type','Relationship']){const cell=el('th',label);cell.scope='col';heading.append(cell);}head.append(heading);const body=el('tbody'),row=el('tr'),empty=el('td','Hierarchy records are not connected yet.');empty.colSpan=3;row.append(empty);body.append(row);relations.append(head,body);children.append(relations);
|
||||
const mail=card('Mailbox','imperial-post-office-v1.png'),mailStatus=el('p',loadMailbox?'Checking unread clan mail…':'Clan mail is available to the owner and authorised officers.');mailStatus.setAttribute('role','status');mail.append(mailStatus);if(loadMailbox){const link=el('a','Open clan mailbox →');link.href='https://clans.dunerealms.com/#clan/clan-mail';link.target='_top';mail.append(link);Promise.resolve().then(loadMailbox).then(count=>{if(root.isConnected)mailStatus.textContent=Number.isSafeInteger(count)&&count>=0?'You have '+count+' unread '+(count===1?'message.':'messages.'):'Unread count is unavailable.';}).catch(()=>{if(root.isConnected)mailStatus.textContent='Mail service unavailable. Open the mailbox to retry.';});}
|
||||
import {claimDisplayName} from './cp-v2/cp-v2-claim-tariffs.mjs';
|
||||
import {claimTariffs} from './cp-v2/cp-v2-claim-tariffs.mjs';
|
||||
import {createActivityFeed} from './organisation-activity.mjs';
|
||||
// Shared presentation only. Callers supply verified records and existing navigation.
|
||||
const el=(tag,text,cls)=>{const node=document.createElement(tag);if(text!==undefined)node.textContent=text;if(cls)node.className=cls;return node;};
|
||||
const assets='https://www.dunerealms.com/assets/';
|
||||
export function createOrganisationDashboard({kind='clan',organisation,members=[],role,canReview=false,requests=[],onMembers,onRequests,loadMailbox,loadTreasury,loadClaims,activity=[],activityStatus,links={},memberSummary}={}){
|
||||
if(!document.querySelector('link[data-organisation-dashboard]')){const css=el('link');css.rel='stylesheet';css.href=new URL('./organisation-dashboard.css',import.meta.url).href;css.dataset.organisationDashboard='';document.head.append(css);}
|
||||
const company=kind==='company',noun=kind==='politics'?'Office':company?'Company':'Clan',root=el('div',undefined,'organisation-dashboard');
|
||||
const backgrounds={'Members':'guild.webp','Applications':'political-small-council-v1.png','News & activity':'political-imperial-chamber-v1.png','Events':'clan-atelier-v1.webp','Treasury':'postbank-transfer-hall-v1.png','Land & claims':'guild.webp','Mailbox':'imperial-post-office-v1.png','Needs attention':'political-small-council-v1.png','Subhouses & subsidiaries':'clan-atelier-v1.webp'};
|
||||
function card(title,art,{pending=false}={}){const box=el('article',undefined,'organisation-dashboard-card'),header=el('header'),image=el('img');image.src=assets+art;image.alt='';image.width=image.height=48;box.dataset.dashboardCard=title.toLowerCase().replaceAll(/[^a-z]+/g,'-');box.style.setProperty('--dashboard-art','url("'+assets+(backgrounds[title]||'political-imperial-chamber-v1.png')+'")');header.append(image,el('h3',title));if(pending)header.append(el('span','Coming soon','organisation-dashboard-status'));box.append(header);root.append(box);return box;}
|
||||
function action(box,label,handler){const button=el('button',label);button.type='button';button.onclick=handler;box.append(button);}
|
||||
const welcome=card('Welcome to '+organisation.name,company?'clans/vaerkring-v1.png':'nav-clan-v2.webp');welcome.classList.add('organisation-dashboard-welcome');const emblem=welcome.querySelector('header img');if(organisation.emblem)emblem.src=organisation.emblem;welcome.append(el('small','YOUR '+noun.toUpperCase()+' · YOUR PEOPLE · YOUR NEXT CHAPTER'));const welcomeBoxes=el('div',undefined,'organisation-welcome-boxes');for(const [title,message] of [[noun+' description',organisation.description||'No introduction has been published yet.'],['Message of the day',organisation.motd||(role?'No message of the day has been published.':'The message of the day is visible to members.')]]){const box=el('section',undefined,'organisation-welcome-subbox');box.append(el('h4',title),el('p',message));welcomeBoxes.append(box);}welcome.append(welcomeBoxes,el('p','['+organisation.tag+'] · '+(organisation.homeworldName||'Homeworld not selected')+' · '+(organisation.titles?.[role]||{owner:noun+' owner',heir:'Heir',officer:'Officer',member:'Member'}[role]||'Visitor')));
|
||||
|
||||
const people=card('Members','nav-account-v2.webp'),faces=el('div',undefined,'organisation-dashboard-members');people.append(el('p',memberSummary||members.length+' '+(members.length===1?'member':'members')+' in the register'));
|
||||
for(const member of members.slice(0,8)){const link=el('a',undefined,'organisation-dashboard-member'),image=el('img'),copy=el('span');image.src='https://cp.dunerealms.com/api/avatars/face/roster/'+encodeURIComponent(member.username);image.alt='';image.width=image.height=44;image.loading='lazy';copy.append(el('strong',member.username),el('small',organisation.titles?.[member.clan_role||member.role]||({owner:noun+' owner',heir:'Heir',officer:'Officer',member:'Member'})[member.clan_role||member.role]||'Member'));link.href='https://www.dunerealms.com/people/'+encodeURIComponent(member.username);link.target='_top';link.append(image,copy);faces.append(link);}people.append(faces);if(onMembers)action(people,'View all members →',onMembers);
|
||||
const applications=card('Applications','nav-support-v2.webp');applications.append(el('p',canReview?(requests.length?requests.length+' '+(requests.length===1?'application awaits':'applications await')+' review.':'No applications are waiting for review.'):'Applications are reviewed by the owner and authorised officers.'));
|
||||
if(canReview){for(const request of requests.slice(0,3))applications.append(el('p',request.username,'organisation-dashboard-request'));if(onRequests)action(applications,'Review applications →',onRequests);}
|
||||
const news=card('News & activity','nav-manual-v2.webp');news.append(createActivityFeed(activity,{emptyMessage:activityStatus==='restricted'?'Activity is visible to organisation members.':activityStatus==='unavailable'?'Activity could not be loaded.':'No clan activity has been recorded yet.'}));
|
||||
for(const [title,art,message] of [['Events','nav-manual-full-v2.webp','Upcoming activities, dates and participation will appear here.'],['Treasury','imperial-postbank-v2.png','Available funds and the account reference will appear here once the authorised bank summary is connected.'],['Land & claims','clans/house-veyr-v1.png','Claims share one total chunk budget. Capacity upgrades will be performed ingame by right-clicking the Home Block.']]){const box=card(title,art,{pending:title==='Events'||title==='Land & claims'&&!loadClaims});box.append(el('p',message),el('small','Not connected yet · no records are shown.'));if(title==='Land & claims'){box.querySelectorAll('p,small').forEach(n=>n.remove());const note=el('p',loadClaims?'Checking your claim registry…':'Claims are not connected for this organisation yet.'),info=el('dl');box.append(note,info);if(loadClaims)Promise.resolve().then(loadClaims).then(view=>{if(!root.isConnected)return;if(view.state!=='connected')throw Error('unavailable');note.textContent='Your registered land and claim allowance.';for(const [label,value]of [['Estate rank',claimDisplayName(view.tier)],['Claimed chunks',view.usedChunks+' / '+view.capacity],['Available chunks',view.availableChunks],['Monthly upkeep',view.monthlyUpkeep]])info.append(el('dt',label),el('dd',String(value)));}).catch(()=>{if(root.isConnected)note.textContent='Claim records could not be loaded. Open Claims to refresh.';});const link=el('a','Open land & claims →');link.href=links.claims||(company?'https://corp.dunerealms.com/#company/claims':'https://clans.dunerealms.com/#clan/clan-claims');link.target='_top';box.append(link);}if(title==='Treasury'){const table=el('table');for(const [label,value] of [['Available funds','Not connected'],['Account','Authorised view required']]){const row=el('tr');row.append(el('th',label),el('td',value));table.append(row);}box.append(table);if(loadTreasury){box.querySelectorAll('p,small').forEach(n=>n.remove());table.replaceChildren();const note=el('p','Checking authorised clan funds…');box.append(note);Promise.resolve().then(loadTreasury).then(entity=>{if(!root.isConnected)return;note.textContent=entity.state==='not_activated'?'Clan banking has not been activated.':'Current accounts · Imperial Postbank';table.replaceChildren();for(const account of entity.accounts){const row=el('tr'),link=el('a',account.number);link.href='https://cp.dunerealms.com/#bank/bank-statements/'+encodeURIComponent(account.id);link.target='_top';const cell=el('td');cell.append(link);row.append(cell,el('td',account.available+' DM available'));table.append(row);}if(!entity.accounts.length&&entity.state!=='not_activated')note.textContent='No active current accounts are visible with your bank permissions.';}).catch(()=>{if(root.isConnected){table.replaceChildren();note.textContent='Clan funds could not be confirmed. Open Imperial Postbank to check your access.';}});}else{table.replaceChildren();box.querySelector('p').textContent='Clan funds are available only with authorised banking access.';}const bank=el('a','Open Imperial Postbank →');bank.href='https://cp.dunerealms.com/#bank/bank-overview';bank.target='_top';box.append(bank);}}
|
||||
const children=card('Subhouses & subsidiaries','clans/vaerkring-v1.png',{pending:true});children.append(el('p','Subordinate organisations will appear here. Claim rights and management pass to the mother organisation; upkeep and upgrade costs remain with the original organisation.'));const relations=el('table'),head=el('thead'),heading=el('tr');for(const label of ['Organisation','Type','Relationship']){const cell=el('th',label);cell.scope='col';heading.append(cell);}head.append(heading);const body=el('tbody'),row=el('tr'),empty=el('td','Hierarchy records are not connected yet.');empty.colSpan=3;row.append(empty);body.append(row);relations.append(head,body);children.append(relations);
|
||||
const mail=card('Mailbox','imperial-post-office-v1.png'),mailStatus=el('p',loadMailbox?'Checking unread clan mail…':'Clan mail is available to the owner and authorised officers.');mailStatus.setAttribute('role','status');mail.append(mailStatus);if(loadMailbox){const link=el('a','Open clan mailbox →');link.href=links.mail||'https://clans.dunerealms.com/#clan/clan-mail';link.target='_top';mail.append(link);Promise.resolve().then(loadMailbox).then(count=>{if(root.isConnected)mailStatus.textContent=Number.isSafeInteger(count)&&count>=0?'You have '+count+' unread '+(count===1?'message.':'messages.'):'Unread count is unavailable.';}).catch(()=>{if(root.isConnected)mailStatus.textContent='Mail service unavailable. Open the mailbox to retry.';});}
|
||||
const attention=card('Needs attention','nav-support-v2.webp');attention.append(el('p',canReview&&requests.length?requests.length+' pending '+(requests.length===1?'application needs':'applications need')+' your attention.':'No additional dashboard alerts are connected yet.'));if(canReview&&requests.length&&onRequests)action(attention,'Open pending applications →',onRequests);const groups=[['overview','Overview',['welcome','land-claims','needs-attention']],['people','People',['members','applications']],['household','Household',['treasury','mailbox','subhouses-subsidiaries']],['activity','Activity',['news-activity','events']]].map(([id,title,names])=>{const content=el('div',undefined,'organisation-dashboard');for(const node of [...root.children])if(names.includes(node.dataset.dashboardCard)||id==='overview'&&node.classList.contains('organisation-dashboard-welcome'))content.append(node);return{id,title,content};});root.classList.remove('organisation-dashboard');root.replaceChildren(organisationTabs(groups,{label:noun+' dashboard sections'}));return root;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue

Staff