diff --git a/docs/design/DUNEREALM-ITEM-CODEX.md b/docs/design/DUNEREALM-ITEM-CODEX.md index 4b3b032b..1f2416c5 100644 --- a/docs/design/DUNEREALM-ITEM-CODEX.md +++ b/docs/design/DUNEREALM-ITEM-CODEX.md @@ -1,16 +1,19 @@ -# Dunerealm Item Codex — design agreement +# J.A.R.V.I.S. — design agreement -Status: design implementation and CI publication authorised. New Codex backend +Renamed J.A.R.V.I.S. on 17 November 2026. Existing technical identifiers, +database names and links remain compatible; the previous system name was Codex. + +Status: design implementation and CI publication authorised. New J.A.R.V.I.S. backend operations remain placeholders until design approval. -The Dunerealm Item Codex is the shared repository for item/kit definitions, +The J.A.R.V.I.S. is the shared repository for item/kit definitions, keys, entitlements, deeds and Writs. The existing key generator becomes its Keys & Entitlements module; Chancery handles Writ records and lifecycle. Dedicated typed tables and validated metadata, rather than one unstructured Writ table for everything. Existing bank, mail, clan and election services remain authoritative for their operations. -Exchange reads existing cargo listings and eligible public Codex records into +Exchange reads existing cargo listings and eligible public J.A.R.V.I.S. records into one shared card model. Categories and sorting make items, jobs, quests, events, political positions and companies/deeds easy to find. Jobs may be clan, company or faction recruitment. Private diplomacy is displayed through its own @@ -42,13 +45,13 @@ promotion fee on permanent failure. No automatic announcement for every listing. Workflow: agree on the images and interactions here, then implement the page and its backend together in a focused CI-reviewed change. Initial integration -order: shared typed Codex/key metadata, Exchange adapter, clan recruitment flow; -reuse the same foundation for later companies, factions, quests and politics. -## Design batch: Codex Management and lifecycle contracts +order: shared typed J.A.R.V.I.S./key metadata, Exchange adapter, clan recruitment flow; +reuse the same foundation for later companies, factions, quests and politics. +## Design batch: J.A.R.V.I.S. Management and lifecycle contracts Status: design implementation authorised. Backend operations stay disabled until approved. -Imperial Bureau > Management > Codex Management replaces the separate Item +Imperial Bureau > Management > J.A.R.V.I.S. Management replaces the separate Item Management, Kit Management, Kit Publishing, Kit Claims and Exchange Management navigation entries. Legacy links resolve to the corresponding consolidated tab. Keep shop administration, honours/seal design, banks and personal reward registers. @@ -116,7 +119,7 @@ confers ownership. Basic/Keyed/Royal limits 5/25/50 derive from the deed. Basic receives four recruitment vacancies subject to actual free slots, and five shared promotion credits: one per Board post and one per Discord post. Both cost two. Credits may be earned from quests. Upgrades remove the Basic token limit; -other promotions use configurable fees. Credits never bypass membership/authority. +other promotions use configurable fees. Credits never bypass membership/authority. ### Immutable edition metadata @@ -129,7 +132,7 @@ entitlement/provenance lineage but is explicitly a replacement, not a second historical collectible. Never increase historical original issuance counts. Display origin in item detail and filters when the backend supplies it; do not label unversioned legacy Minecraft listings as Alpha originals. Actual scarcity -counts require the authoritative instance ledger. +counts require the authoritative instance ledger. Quality reuses existing Common / Uncommon / Rare / Very Rare / Legendary tiers. Quality is independent of immutable edition, season and actual surviving count. @@ -137,7 +140,7 @@ A Rare Netherite Shovel from an older Alpha release remains that edition; no promise of resale value or artificial rarity count is made. Issuer provenance also stores the issuing citizen and, where applicable, verified political deed/office and term references. A royal key issued by the first Emperor -can retain that factual provenance without granting a second political entitlement. +can retain that factual provenance without granting a second political entitlement. ### Persistent versus consumable items diff --git a/website/control-panel/public/codex-code-format.mjs b/website/control-panel/public/codex-code-format.mjs index eb61bcd1..68b643d9 100644 --- a/website/control-panel/public/codex-code-format.mjs +++ b/website/control-panel/public/codex-code-format.mjs @@ -9,8 +9,8 @@ export function parseOrganisationCode(value){ return {prefix:parts[1],canonical:parts[1]+'-'+parts[5].replaceAll('-',''),edition:{stage:parts[2].toLowerCase(),version:parts[3],season:parts[4]}}; } export function validateCodeEdition(edition){ - if(!edition||!['alpha','beta','live'].includes(edition.stage)||typeof edition.version!=='string'||!/^(?:0|[1-9]\d{0,2})(?:\.(?:0|[1-9]\d{0,2})){3}$/.test(edition.version)||typeof edition.season!=='string'||!/^S\d{2,4}$/.test(edition.season))throw new TypeError('Invalid Codex edition'); + if(!edition||!['alpha','beta','live'].includes(edition.stage)||typeof edition.version!=='string'||!/^(?:0|[1-9]\d{0,2})(?:\.(?:0|[1-9]\d{0,2})){3}$/.test(edition.version)||typeof edition.season!=='string'||!/^S\d{2,4}$/.test(edition.season))throw new TypeError('Invalid J.A.R.V.I.S. edition'); return {stage:edition.stage,version:edition.version,season:edition.season}; } export function formatOrganisationCode(value,edition){const parsed=parseOrganisationCode(value),checked=validateCodeEdition(edition),token=parsed.canonical.slice(parsed.prefix.length+1);return [parsed.prefix,checked.stage.toUpperCase(),checked.version,checked.season,...token.match(/.{8}/g)].join('-');} -export function organisationCodeIs(value,prefix){try{return parseOrganisationCode(value).prefix===prefix;}catch{return false;}} +export function organisationCodeIs(value,prefix){try{return parseOrganisationCode(value).prefix===prefix;}catch{return false;}} diff --git a/website/control-panel/public/codex-dossier-format.mjs b/website/control-panel/public/codex-dossier-format.mjs index 544a4e62..a07615be 100644 --- a/website/control-panel/public/codex-dossier-format.mjs +++ b/website/control-panel/public/codex-dossier-format.mjs @@ -1,3 +1,3 @@ // Safe public dossier identity. This reference is not a bearer token. -export function codexLoanReference(id){if(typeof id!=='string'||!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(id))throw new TypeError('Invalid Codex dossier identity');return 'COD-LOAN-'+id.toUpperCase();} -export function codexLoanStatus(state){if(state==='submitted')return 'pending';if(state==='declined')return 'denied';if(['approved_pending','offered','payout_queued','active','arrears','paid','repaid','refinanced'].includes(state))return 'accepted';if(['withdrawn','expired'].includes(state))return state;return state==='requested'?'requested':'verification_pending';} +export function codexLoanReference(id){if(typeof id!=='string'||!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(id))throw new TypeError('Invalid J.A.R.V.I.S. dossier identity');return 'COD-LOAN-'+id.toUpperCase();} +export function codexLoanStatus(state){if(state==='submitted')return 'pending';if(state==='declined')return 'denied';if(['approved_pending','offered','payout_queued','active','arrears','paid','repaid','refinanced'].includes(state))return 'accepted';if(['withdrawn','expired'].includes(state))return state;return state==='requested'?'requested':'verification_pending';} diff --git a/website/control-panel/public/cp-v2/cp-v2-codex-management.mjs b/website/control-panel/public/cp-v2/cp-v2-codex-management.mjs index c140f6dd..28d15521 100644 --- a/website/control-panel/public/cp-v2/cp-v2-codex-management.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-codex-management.mjs @@ -1,7 +1,7 @@ import {organisationTabs} from '../organisation-tabs.mjs'; const assets='https://www.dunerealms.com/assets/'; const make=(tag,text,className)=>{const node=document.createElement(tag);if(text!==undefined)node.textContent=text;if(className)node.className=className;return node;}; -const TYPES=[['Clan upgrade','Silver charter','Upgrade a Basic clan','Original or staff issue'],['Company upgrade','Silver charter','Upgrade a Basic company','Original or staff issue'],['Royal appointment','Gold charter','Political appointment or authorised reward','Original or staff issue'],['Political office','Office deed','Appointment for a defined term','Political decision'],['Kit','Equipment seal','Single redemption of a defined kit','Kit service'],['Custom item','Item instance','Unique physical or redeemable item','Codex publication'],['Promotion credit','Dispatch seal','One Board or Discord publication','Reward or authorised grant']]; +const TYPES=[['Clan upgrade','Silver charter','Upgrade a Basic clan','Original or staff issue'],['Company upgrade','Silver charter','Upgrade a Basic company','Original or staff issue'],['Royal appointment','Gold charter','Political appointment or authorised reward','Original or staff issue'],['Political office','Office deed','Appointment for a defined term','Political decision'],['Kit','Equipment seal','Single redemption of a defined kit','Kit service'],['Custom item','Item instance','Unique physical or redeemable item','J.A.R.V.I.S. publication'],['Promotion credit','Dispatch seal','One Board or Discord publication','Reward or authorised grant']]; function image(name){const img=make('img');img.src=assets+name;img.alt='';img.loading='lazy';return img;} function field(label,options){const wrapper=make('label',undefined,'codex-field');wrapper.append(make('span',label));let input;if(Array.isArray(options)){input=make('select');for(const option of options){const node=make('option',option);input.append(node);}}else{input=make(options==='message'?'textarea':'input');input.type='text';input.placeholder=options||'';}wrapper.append(input);return wrapper;} function locked(label){const button=make('button',label);button.type='button';button.disabled=true;button.title='Design preview: service connection pending';return button;} @@ -10,18 +10,18 @@ function empty(headers,copy){const wrapper=table(headers,[]),row=make('tr'),cell function box(title,copy){const node=make('article',undefined,'codex-management-box');node.append(make('h3',title));if(copy)node.append(make('p',copy));return node;} export function mountCodexManagement(host,{initial='keys'}={}){ if(!document.querySelector('link[data-codex-management]')){const css=make('link');css.rel='stylesheet';css.href=new URL('./cp-v2-codex-management.css',import.meta.url).href;css.dataset.codexManagement='';document.head.append(css);} - const root=make('section',undefined,'codex-management'),hero=make('header',undefined,'codex-management-hero');hero.append(image('exchange-quests-v1.png'));const heading=make('div');heading.append(make('small','IMPERIAL BUREAU · MANAGEMENT'),make('h2','Dunerealm Item Codex'),make('p','Issue, register and deliver the instruments of the realm.'));hero.append(heading);root.append(hero,make('p','Design preview · No live records are loaded. Issuing, replacing, transferring and delivery actions remain unavailable.','codex-preview-notice')); + const root=make('section',undefined,'codex-management'),hero=make('header',undefined,'codex-management-hero');hero.append(image('exchange-quests-v1.png'));const heading=make('div');heading.append(make('small','IMPERIAL BUREAU · MANAGEMENT'),make('h2','J.A.R.V.I.S.'),make('p','Issue, register and deliver the instruments of the realm.'));hero.append(heading);root.append(hero,make('p','Design preview · No live records are loaded. Issuing, replacing, transferring and delivery actions remain unavailable.','codex-preview-notice')); const disposers=[];let mounted=true;const groups=[]; function retained(content,label,path,name,args=[]){const node=make('details',undefined,'codex-retained-service'),summary=make('summary',label),host=make('div');let started=false;summary.onclick=()=>{if(started)return;started=true;import(path).then(module=>{if(mounted)disposers.push(module[name](host,...args));}).catch(()=>{if(mounted)host.textContent='Existing service unavailable. Reload to retry.';});};node.append(summary,host);content.append(node);} const keys=make('div',undefined,'codex-management-grid'),matrix=box('Keys & deeds','A common register, with the authority of each instrument kept distinct.');matrix.append(table(['Instrument','Seal','Purpose','Source'],TYPES));keys.append(matrix);const provenance=box('The mark of origin','Original keys carry an original seal. Authorised staff issues carry a staff seal.');for(const [title,copy] of [['Original seal','An original key may replace a staff-issued upgrade without granting duplicate rights.'],['Staff seal','Each issue records the issuer, reason and a server-signed issue proof.'],['Replacement','A replacement invalidates the unused predecessor and retains its original provenance.']]){const row=make('section',undefined,'codex-seal-note');row.append(make('strong',title),make('p',copy));provenance.append(row);}keys.append(provenance);groups.push({id:'keys',title:'Keys & deeds',content:keys}); - const issuance=make('div',undefined,'codex-management-grid'),issue=box('Issue an instrument','Staff issuance uses the same generator and lifecycle as original keys.');const form=make('form',undefined,'codex-management-form');form.onsubmit=e=>e.preventDefault();form.append(field('Instrument',TYPES.map(row=>row[0])),field('Quality',['Common','Uncommon','Rare','Very Rare','Legendary']),field('Recipient','Citizen or organisation'),field('Issue reason',['Support resolution','Event reward','Authorised grant']),field('Season','Current season · supplied by server'),field('Validity','Optional expiry'),field('Reason / decision reference','Required audit reference'),locked('Generate key'));issue.append(form);const replace=box('Replace or revoke','Select an existing unused instance. No second entitlement is created.');replace.append(field('Instance ID','Unique Codex instance'),field('Reason','Required audit reason'),locked('Replace key'),locked('Revoke unused key'));issuance.append(issue,replace);groups.push({id:'issuance',title:'Issuance',content:issuance}); + const issuance=make('div',undefined,'codex-management-grid'),issue=box('Issue an instrument','Staff issuance uses the same generator and lifecycle as original keys.');const form=make('form',undefined,'codex-management-form');form.onsubmit=e=>e.preventDefault();form.append(field('Instrument',TYPES.map(row=>row[0])),field('Quality',['Common','Uncommon','Rare','Very Rare','Legendary']),field('Recipient','Citizen or organisation'),field('Issue reason',['Support resolution','Event reward','Authorised grant']),field('Season','Current season · supplied by server'),field('Validity','Optional expiry'),field('Reason / decision reference','Required audit reference'),locked('Generate key'));issue.append(form);const replace=box('Replace or revoke','Select an existing unused instance. No second entitlement is created.');replace.append(field('Instance ID','Unique J.A.R.V.I.S. instance'),field('Reason','Required audit reason'),locked('Replace key'),locked('Revoke unused key'));issuance.append(issue,replace);groups.push({id:'issuance',title:'Issuance',content:issuance}); const definitions=box('Items & definitions','Definitions describe a type; every issued item receives its own unique instance ID.');definitions.append(field('Search definitions','Name, type or definition ID'),empty(['Artwork','Definition','Type','Quality','Revision','State'],'Definition service not connected.'),locked('Create definition'));retained(definitions,'Open existing item catalogue','./cp-v2-item-register.mjs','mountItemRegister');groups.push({id:'items',title:'Items & definitions',content:definitions}); - const kits=box('Kits','Kit definitions, equipment and redeemable kit instances share the Codex catalogue.');kits.append(empty(['Kit','Revision','Contents','Availability'],'Kit catalogue adapter pending.'),locked('Define kit'));retained(kits,'Open existing kit service','./cp-v2-kit-directorate.mjs','mountKitDirectorate',['server-kits']);groups.push({id:'kits',title:'Kits',content:kits}); + const kits=box('Kits','Kit definitions, equipment and redeemable kit instances share the J.A.R.V.I.S. catalogue.');kits.append(empty(['Kit','Revision','Contents','Availability'],'Kit catalogue adapter pending.'),locked('Define kit'));retained(kits,'Open existing kit service','./cp-v2-kit-directorate.mjs','mountKitDirectorate',['server-kits']);groups.push({id:'kits',title:'Kits',content:kits}); const publication=box('Publication','Review versions and their distribution channels before publication.');publication.append(empty(['Definition','Revision','Approval','Channels','State'],'Publication queue is not connected.'),locked('Publish approved revision'));retained(publication,'Open existing publication service','./cp-v2-kit-directorate.mjs','mountKitDirectorate',['kit-publishing']);groups.push({id:'publication',title:'Publication',content:publication}); const delivery=box('Deliveries & claims','Track each delivery attempt against one instance. Retries retain the same delivery identity.');delivery.append(field('Delivery state',['All states','Queued','Processing','Delivered','Failed','Redeemed','Revoked']),empty(['Instance','Recipient','Method','State','Last attempt','Action'],'Delivery service not connected. No delivery totals are inferred.'),locked('Retry selected delivery'));groups.push({id:'delivery',title:'Delivery',content:delivery}); - const listings=box('Listings & distribution','One exchange for goods and eligible Codex instruments. Listings retain the record owner and instance reference.');listings.append(empty(['Listing','Type','Owner','Audience','State'],'Listing administration adapter pending.'),locked('Review listing'));retained(listings,'Open existing exchange controls','./cp-v2-exchange-authority.mjs','mountExchangeAuthority');groups.push({id:'listings',title:'Listings',content:listings}); + const listings=box('Listings & distribution','One exchange for goods and eligible J.A.R.V.I.S. instruments. Listings retain the record owner and instance reference.');listings.append(empty(['Listing','Type','Owner','Audience','State'],'Listing administration adapter pending.'),locked('Review listing'));retained(listings,'Open existing exchange controls','./cp-v2-exchange-authority.mjs','mountExchangeAuthority');groups.push({id:'listings',title:'Listings',content:listings}); const history=box('History','Issuance, replacements, transfers, redemption and delivery attempts are recorded without exposing private key material.');history.append(field('Search history','Instance, issuer, recipient or decision'),empty(['Time','Instrument','Action','Actor','Reason','Result'],'Audit service not connected.'));groups.push({id:'history',title:'History',content:history}); const seasons=box('Seasons & signing keys','Each season or isolated test run has its own signing-key version. Existing deeds and historical items retain their origin.');seasons.append(table(['Policy','Behaviour'],[['Origin','Season, Alpha/Beta/Live stage, release version and issue date stay attached to the instance.'],['Historical originals','Staff regeneration creates a new current-version instance; it never relabels the historical original.'],['Quality','Common, Uncommon, Rare, Very Rare and Legendary describe quality independently from edition age and actual scarcity.'],['Carry-over','Deeds persist. Unused older-season keys and rare items remain valid and transferable when their type permits.'],['Key rotation','New issues use the active signing key; historical signatures remain verifiable.'],['Test isolation','Test-run instances belong to their own namespace and cannot be redeemed in production.'],['Duplicate protection','Validate on use, redemption or transfer; atomic processing accepts an instance only once.']]),locked('Rotate active signing key'),locked('Create isolated test run'));groups.push({id:'seasons',title:'Seasons',content:seasons}); - root.append(organisationTabs(groups,{label:'Codex Management sections',initial}));host.replaceChildren(root);return()=>{mounted=false;for(const dispose of disposers)if(typeof dispose==='function')dispose();root.remove();}; -} + root.append(organisationTabs(groups,{label:'J.A.R.V.I.S. Management sections',initial}));host.replaceChildren(root);return()=>{mounted=false;for(const dispose of disposers)if(typeof dispose==='function')dispose();root.remove();}; +} diff --git a/website/control-panel/public/cp-v2/cp-v2-exchange-design.mjs b/website/control-panel/public/cp-v2/cp-v2-exchange-design.mjs index 617dd57f..58b8ecce 100644 --- a/website/control-panel/public/cp-v2/cp-v2-exchange-design.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-exchange-design.mjs @@ -12,24 +12,24 @@ export function mountExchangeDesign(host,{context='public',view='browse',fetcher if(!document.querySelector('link[data-codex-exchange]')){const css=el('link');css.rel='stylesheet';css.href=new URL('./cp-v2-exchange-design.css',import.meta.url).href;css.dataset.codexExchange='';document.head.append(css);} let active=true,rows=[],kitRows=[],category=context==='user'?'items':context==='public'&&TYPES.some(([id])=>id===new URLSearchParams(location.search).get('type'))?new URLSearchParams(location.search).get('type'):'all',page=0,examples=false,clanKind='unknown';const controller=new AbortController(); const root=el('section',undefined,'codex-exchange'+(context==='public'?' codex-exchange-public':'')),hero=el('header',undefined,'codex-exchange-hero'),copy=el('div');copy.append(el('small',context==='public'?'SPACING GUILD · STARPORT EXCHANGE':'STARPORT · DUNEREALM ITEM CODEX'),el('h2',context==='clan'?'Household Exchange':context==='user'?'Item Exchange':'Starport Exchange'),el('p','Find your next trade, calling or adventure.'));hero.append(image(context==='public'?'faction-guild.svg':'nav-exchange-v2.webp'),copy);root.append(hero); - const banner=el('p',context==='user'?'Minecraft goods use the existing listings service. Trading remains in game.':'Codex design preview · New listings, applications and promotions are not connected.','codex-exchange-notice');root.append(banner); + const banner=el('p',context==='user'?'Minecraft goods use the existing listings service. Trading remains in game.':'J.A.R.V.I.S. design preview · New listings, applications and promotions are not connected.','codex-exchange-notice');root.append(banner); const browse=el('div'),layout=el('div',undefined,'codex-exchange-layout'),aside=el('aside',undefined,'codex-exchange-categories'),main=el('div',undefined,'codex-exchange-main'),tools=el('div',undefined,'codex-exchange-tools'); const search=field('Search','Items, opportunities, sellers or worlds');search.input.type='search';const sort=field('Sort',['Newest first','Price: low to high','Price: high to low','Title']);const quality=field('Quality',['All qualities','Common','Uncommon','Rare','Very Rare','Legendary']);const stage=field('Edition',['All stages','Alpha','Beta','Live']);const season=field('Season',['All seasons','Current season','Earlier seasons']);const preview=el('label',undefined,'codex-exchange-preview'),toggle=el('input');toggle.type='checkbox';preview.append(toggle,el('span','Show design examples'));toggle.onchange=()=>{examples=toggle.checked;page=0;render();};tools.append(search.box,sort.box,quality.box,stage.box,season.box);if(context!=='user')tools.append(preview);const status=el('p','Loading live Minecraft listings…','codex-exchange-status');status.setAttribute('role','status');const cards=el('div',undefined,'codex-exchange-cards'),pager=el('div',undefined,'codex-exchange-pager');main.append(tools,status,cards,pager);layout.append(aside,main);browse.append(layout); 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','Codex 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'],'Codex 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 Codex 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 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 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); let selectPost;const groups=[{id:'browse',title:'Browse',content:browse}];if(context!=='public'){groups.push({id:'mine',title:'My listings',content:mine},{id:'post',title:context==='user'?'Post an item':'Post a listing',content:post});if(context==='clan')groups.push({id:'applications',title:'Applications',content:applications},{id:'promotions',title:'Promotions',content:promotions});}const tabbed=organisationTabs(groups,{label:'Exchange sections',initial:view});selectPost=()=>tabbed.querySelector('[role=tab][aria-controls$="-post-panel"]')?.click();root.append(tabbed); const footer=el('footer',undefined,'codex-exchange-logistics');footer.append(el('span',context==='public'?'Logistics by SPost':'Exchange logistics supplied by'),image('spost-logo-v1.svg'),el('small','part of'),image('corrino-group-v4.png'));root.append(footer);host.replaceChildren(root); - function render(){for(const [node,id]of buttons)node.setAttribute('aria-pressed',String(id===category));let matches=[...rows,...kitRows,...(examples?SAMPLES.filter(row=>context!=='clan'||['recruitment','quests','events'].includes(row.type)):[])].filter(row=>(category==='all'||row.type===category||row.kitCategory===category)&&[row.title,row.owner,row.world].join(' ').toLowerCase().includes(search.input.value.toLowerCase()));if(season.input.selectedIndex>0||stage.input.selectedIndex>0)matches=[];if(quality.input.selectedIndex>0)matches=matches.filter(row=>words(row.quality).toLowerCase()===quality.input.value.toLowerCase());matches.sort((a,b)=>sort.input.selectedIndex===1?a.price-b.price:sort.input.selectedIndex===2?b.price-a.price:sort.input.selectedIndex===3?a.title.localeCompare(b.title):Number(b.id)-Number(a.id)||0);page=Math.min(page,Math.max(0,Math.ceil(matches.length/8)-1));cards.replaceChildren();if(!matches.length)cards.append(el('p',season.input.selectedIndex||quality.input.selectedIndex||stage.input.selectedIndex?'Existing goods do not yet carry Codex edition and quality metadata. Matching records will appear after Codex integration.':'No matching listings. Design examples can be enabled separately.','codex-exchange-empty'));for(const row of matches.slice(page*8,page*8+8)){const sample=String(row.id).startsWith('preview-'),type=TYPES.find(([id])=>id===row.type),card=el('article',undefined,'codex-exchange-card');card.append(el('small',sample?'DESIGN EXAMPLE':type?.[1]||'ITEM'));const art=row.type==='items'?'minecraft-items/'+String(row.material).toLowerCase()+'.png':row.type==='kits'?'minecraft-items/'+(row.quality==='legendary'?'netherite_chestplate':'leather_chestplate')+'.png':type?.[2],img=image(art,['items','kits'].includes(row.type)?'minecraft-texture':undefined);img.onerror=()=>{img.remove();card.prepend(el('span','▧','codex-exchange-missing-icon'));};card.append(img,el('h3',row.title),el('p',row.owner+' · '+row.world),el('strong',row.type==='items'?row.price.toFixed(2)+' DM · '+row.quantity+' available':row.type==='kits'?row.price.toFixed(2)+' DM · '+words(row.quality):'View opportunity'),button(row.type==='items'?'View item':row.type==='kits'?'View kit':row.type==='recruitment'?'View vacancy':'View details',()=>detail(row,sample)));cards.append(card);}pager.replaceChildren(button('← Previous',()=>{page--;render();},page===0),el('span',(page+1)+' / '+Math.max(1,Math.ceil(matches.length/8))),button('Next →',()=>{page++;render();},(page+1)*8>=matches.length));} + function render(){for(const [node,id]of buttons)node.setAttribute('aria-pressed',String(id===category));let matches=[...rows,...kitRows,...(examples?SAMPLES.filter(row=>context!=='clan'||['recruitment','quests','events'].includes(row.type)):[])].filter(row=>(category==='all'||row.type===category||row.kitCategory===category)&&[row.title,row.owner,row.world].join(' ').toLowerCase().includes(search.input.value.toLowerCase()));if(season.input.selectedIndex>0||stage.input.selectedIndex>0)matches=[];if(quality.input.selectedIndex>0)matches=matches.filter(row=>words(row.quality).toLowerCase()===quality.input.value.toLowerCase());matches.sort((a,b)=>sort.input.selectedIndex===1?a.price-b.price:sort.input.selectedIndex===2?b.price-a.price:sort.input.selectedIndex===3?a.title.localeCompare(b.title):Number(b.id)-Number(a.id)||0);page=Math.min(page,Math.max(0,Math.ceil(matches.length/8)-1));cards.replaceChildren();if(!matches.length)cards.append(el('p',season.input.selectedIndex||quality.input.selectedIndex||stage.input.selectedIndex?'Existing goods do not yet carry J.A.R.V.I.S. edition and quality metadata. Matching records will appear after J.A.R.V.I.S. integration.':'No matching listings. Design examples can be enabled separately.','codex-exchange-empty'));for(const row of matches.slice(page*8,page*8+8)){const sample=String(row.id).startsWith('preview-'),type=TYPES.find(([id])=>id===row.type),card=el('article',undefined,'codex-exchange-card');card.append(el('small',sample?'DESIGN EXAMPLE':type?.[1]||'ITEM'));const art=row.type==='items'?'minecraft-items/'+String(row.material).toLowerCase()+'.png':row.type==='kits'?'minecraft-items/'+(row.quality==='legendary'?'netherite_chestplate':'leather_chestplate')+'.png':type?.[2],img=image(art,['items','kits'].includes(row.type)?'minecraft-texture':undefined);img.onerror=()=>{img.remove();card.prepend(el('span','▧','codex-exchange-missing-icon'));};card.append(img,el('h3',row.title),el('p',row.owner+' · '+row.world),el('strong',row.type==='items'?row.price.toFixed(2)+' DM · '+row.quantity+' available':row.type==='kits'?row.price.toFixed(2)+' DM · '+words(row.quality):'View opportunity'),button(row.type==='items'?'View item':row.type==='kits'?'View kit':row.type==='recruitment'?'View vacancy':'View details',()=>detail(row,sample)));cards.append(card);}pager.replaceChildren(button('← Previous',()=>{page--;render();},page===0),el('span',(page+1)+' / '+Math.max(1,Math.ceil(matches.length/8))),button('Next →',()=>{page++;render();},(page+1)*8>=matches.length));} function detail(row,sample){const dialog=el('dialog',undefined,'codex-exchange-dialog');dialog.append(el('h3',row.title),el('p',row.description||row.owner+' · '+row.world),el('p',sample?'Design example. Applications and purchases are disabled.':row.type==='kits'?(row.purchaseAvailable?'Continue to the existing kit checkout.':'Published design · purchase or delivery is not available yet.'):'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 · Codex 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 Codex 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.';}); + 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==='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 · Codex opportunities pending.';render();}}).catch(()=>{if(active){const note=el('p','Kit catalogue is unavailable. Minecraft listings remain separate.','codex-exchange-status');browse.prepend(note);}}); + 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();}; -} +} diff --git a/website/control-panel/public/cp-v2/cp-v2-postbank-credit.mjs b/website/control-panel/public/cp-v2/cp-v2-postbank-credit.mjs index ab8cc599..6c1d77c1 100644 --- a/website/control-panel/public/cp-v2/cp-v2-postbank-credit.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-postbank-credit.mjs @@ -1,58 +1,58 @@ import {codexLoanReference,codexLoanStatus} from '../codex-dossier-format.mjs'; -import {element as el,createCPV2ContentPage} from './cp-v2-page-template.mjs'; -import {createUserAPI} from './cp-v2-user-api.mjs'; -import {packageBrand} from './cp-v2-postbank-foundation.mjs'; -export const creditTheme=p=>({grant_start:'start',grant_build:'connect',grant_advance:'scale',personal_loan:'flow',personal_overdraft:'start',personal_card:'public',business_loan:'connect',civic_loan:'civic'}[p.key]||(p.group==='refinancing'?'scale':'flow')); -const title={'loan-centre':'Loans & Grants','bank-loans':'My Credit','loan-administration':'Credit Management'},human=s=>String(s).replace(/_/g,' ').replace(/\b[a-z]/g,c=>c.toUpperCase()); -function field(name,input){const label=el('label',undefined,'pb-transfer-field');label.append(el('span',name),input);return label;} -function option(select,label,value){const o=el('option',label);o.value=value;select.append(o);} -function grid(headers){const wrap=el('div',undefined,'pb-ledger-scroll'),t=el('table',undefined,'pb-ledger'),body=el('tbody'),head=el('thead'),tr=el('tr');for(const h of headers)tr.append(el('th',h));head.append(tr);t.append(head,body);wrap.append(t);return {wrap,body};} -export function creditReviewSelection(search=''){ - const query=new URLSearchParams(search),loanId=query.get('creditApplication'),action=query.get('creditDecision'); - if(query.getAll('creditApplication').length!==1||query.getAll('creditDecision').length!==1||!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(loanId||'')||!['approve','decline'].includes(action))return null; - return {loanId,action}; -} +import {element as el,createCPV2ContentPage} from './cp-v2-page-template.mjs'; +import {createUserAPI} from './cp-v2-user-api.mjs'; +import {packageBrand} from './cp-v2-postbank-foundation.mjs'; +export const creditTheme=p=>({grant_start:'start',grant_build:'connect',grant_advance:'scale',personal_loan:'flow',personal_overdraft:'start',personal_card:'public',business_loan:'connect',civic_loan:'civic'}[p.key]||(p.group==='refinancing'?'scale':'flow')); +const title={'loan-centre':'Loans & Grants','bank-loans':'My Credit','loan-administration':'Credit Management'},human=s=>String(s).replace(/_/g,' ').replace(/\b[a-z]/g,c=>c.toUpperCase()); +function field(name,input){const label=el('label',undefined,'pb-transfer-field');label.append(el('span',name),input);return label;} +function option(select,label,value){const o=el('option',label);o.value=value;select.append(o);} +function grid(headers){const wrap=el('div',undefined,'pb-ledger-scroll'),t=el('table',undefined,'pb-ledger'),body=el('tbody'),head=el('thead'),tr=el('tr');for(const h of headers)tr.append(el('th',h));head.append(tr);t.append(head,body);wrap.append(t);return {wrap,body};} +export function creditReviewSelection(search=''){ + const query=new URLSearchParams(search),loanId=query.get('creditApplication'),action=query.get('creditDecision'); + if(query.getAll('creditApplication').length!==1||query.getAll('creditDecision').length!==1||!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(loanId||'')||!['approve','decline'].includes(action))return null; + return {loanId,action}; +} export function codexLoanSelection(search=''){const query=new URLSearchParams(search);const id=query.get('codexLoan');return query.getAll('codexLoan').length===1&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(id||'')?id.toLowerCase():null;} -export function mountPostbankCredit(host,id,{fetcher=fetch,reviewSearch=globalThis.location?.search||''}={}){ - const review=id==='loan-administration'?creditReviewSelection(reviewSearch):null,dossierId=codexLoanSelection(reviewSearch)||review?.loanId||null; - const abort=new AbortController(),api=createUserAPI(fetcher,abort.signal);let active=true,busy=false,view,notice=null; - const frame=createCPV2ContentPage({host,title:title[id],description:id==='loan-centre'?'Explore launch grants and credit, compare repayments and review the full cost.':id==='bank-loans'?'Your applications, borrowing and repayment records, kept separate for each banking client.':'Review applications, evidence and client-specific borrowing risk.',reload:()=>void load()}); - async function load(){if(busy)return;busy=true;frame.status.hidden=false;frame.status.textContent='Loading authorised credit records…';try{view=await api.request(id==='loan-administration'?'/api/bank/admin/credit'+(dossierId?'?loanId='+encodeURIComponent(dossierId):''):'/api/bank/credit/overview');if(!active)return;frame.content.replaceChildren();if(id==='loan-centre')catalogue();else if(dossierId)dossier();else if(id==='bank-loans')myCredit();else management();frame.status.hidden=!notice;if(notice){frame.status.textContent=notice;notice=null;}frame.diagnostics.textContent='Central API · Independent bank database · '+new Date().toLocaleString('en-GB');}catch(e){if(active)frame.status.textContent=e.message;}finally{busy=false;}} - function catalogue(){ - frame.content.append(el('p','Choose your borrowing account and compare the full repayment cost. A simulation never moves money.','pb-muted')); - const accounts=view.accounts.filter(a=>a.canApply);if(!accounts.length){frame.content.append(el('p','Activate an eligible personal or organisational current account in My Products first.'));return;} - let selected=accounts[0];const tabs=el('div',undefined,'pb-credit-account-tabs'),stage=el('section',undefined,'pb-credit-stage');tabs.setAttribute('role','tablist');tabs.setAttribute('aria-label','Borrowing account');stage.id='pb-credit-account-panel';stage.setAttribute('role','tabpanel');const buttons=[]; - for(const account of accounts){const button=el('button',undefined,'pb-credit-account-tab');button.type='button';button.setAttribute('role','tab');button.id='pb-credit-account-tab-'+buttons.length;button.setAttribute('aria-controls',stage.id);button.append(el('strong',account.holder||account.name),el('small',account.name+' · '+account.number.replace(/(.{4})/g,'$1 ').trim()));button.onclick=()=>{if(busy)return;selected=account;renderProducts();};buttons.push({button,account});tabs.append(button);} - frame.content.append(tabs,stage); - function renderProducts(){for(const {button,account} of buttons){const chosen=account.id===selected.id;button.setAttribute('aria-selected',String(chosen));button.tabIndex=chosen?0:-1;if(chosen)stage.setAttribute('aria-labelledby',button.id);}stage.replaceChildren();const products=el('div',undefined,'pb-credit-products');stage.append(products);for(const [group,label]of [['grants','Launch Grants'],['personal','Personal Loans'],['professional','Business & Civic Loans'],['refinancing','Refinancing']]){const choices=(selected.products||view.products).filter(p=>p.group===group&&p.kinds.includes(selected.kind));if(!choices.length)continue;const section=el('section',undefined,'pb-credit-category'),cards=el('div',undefined,'pb-package-choices');section.append(el('h2',label),cards); - for(const product of choices){const theme=product.packageBenefit?'pro':creditTheme(product),card=el('section',undefined,'pb-choice-card pb-credit-product pb-plan-'+theme),brand=packageBrand({key:'pb_'+theme,name:product.name}),price=el('div',undefined,'pb-credit-price');price.append(el('strong',product.amount?product.amount+' DM':product.min+'–'+product.max+' DM'),el('small',(product.annualBps/100).toFixed(2)+'% annual interest'));const list=el('ul');for(const text of group==='grants'?['No collateral required','Choose your monthly repayment','Up to 12 monthly instalments']:['Fixed repayment schedule','First instalment: 5% before issue','First instalment deducted from the remaining debt'])list.append(el('li',text));if(product.packageBenefit)list.append(el('li',product.packageBenefit));const choose=el('button',product.revolving?'Coming soon':'Simulate repayments','pb-credit-simulate');choose.type='button';choose.disabled=!!product.revolving;choose.onclick=()=>{if(busy)return;stage.replaceChildren();simulator(product,selected,stage,renderProducts);};card.append(brand,price,list,choose);cards.append(card);}products.append(section);} - } - tabs.onkeydown=e=>{const index=buttons.findIndex(b=>b.button===e.target);if(index<0||!['ArrowLeft','ArrowRight','Home','End'].includes(e.key)||busy)return;e.preventDefault();const next=e.key==='Home'?0:e.key==='End'?buttons.length-1:(index+(e.key==='ArrowRight'?1:-1)+buttons.length)%buttons.length;buttons[next].button.onclick();buttons[next].button.focus();};renderProducts(); - } - function simulator(product,account,host,back){ - const navigation=el('div',undefined,'pb-credit-step'),returnButton=el('button','← Back to credit products');returnButton.type='button';returnButton.onclick=()=>{if(!busy)back();};navigation.append(returnButton,el('span','1. Choose credit / 2. Simulate repayments'));host.append(navigation,el('h2',product.name)); - const layout=el('div',undefined,'pb-credit-calculator'),form=el('form',undefined,'pb-transfer-form pb-credit-inputs'),amount=el('input'),term=el('select'),monthly=el('input'),send=el('button','Calculate repayments','pb-credit-simulate'),result=el('aside',undefined,'pb-credit-quote'),message=el('p');result.setAttribute('aria-live','polite');result.append(el('h3','Your repayment estimate'),el('p','Choose your amount and repayment period to see your monthly payment and total cost.'));amount.type=monthly.type='text';amount.inputMode=monthly.inputMode='decimal';amount.required=monthly.required=true;amount.value=product.amount||product.min;monthly.value=product.amount?Math.ceil(Number(product.amount)/12).toFixed(2):'';send.type='submit';form.append(el('p',(account.holder||account.name)+' · '+account.number,'pb-muted'));if(product.group==='grants'){amount.readOnly=true;form.append(field('Grant amount · DM',amount),field('Monthly repayment · DM',monthly));}else{for(const m of product.terms)option(term,m+' months',String(m));if(product.group==='refinancing')form.append(el('p','We calculate the exact settlement of all interest-bearing loans for this client. Grants remain separate.'));else form.append(field('Loan amount · DM',amount));form.append(field('Repayment period',term));}form.append(send,message);layout.append(form,result);host.append(layout);const details=el('div',undefined,'pb-credit-quote-details');host.append(details); - const stale=()=>{result.replaceChildren(el('h3','Update your estimate'),el('p','Your selection changed. Calculate again for the current repayment cost.'));details.replaceChildren();};amount.oninput=monthly.oninput=term.onchange=stale; - form.onsubmit=async e=>{e.preventDefault();if(busy||!form.reportValidity())return;busy=true;send.disabled=true;returnButton.disabled=true;message.textContent='Calculating…';const values={accountId:account.id,productKey:product.key,...(product.group==='grants'?{monthly:monthly.value}:{amount:amount.value,months:Number(term.value)})};amount.disabled=monthly.disabled=term.disabled=true;try{const data=await api.request('/api/bank/credit/simulate',values);if(!active)return;message.textContent='';result.replaceChildren(el('small','Estimated monthly repayment'),el('strong',data.quote.monthly+' DM','pb-credit-monthly'));const totals=el('dl');for(const [label,value]of [['Repayment period',data.quote.months+' months'],['Annual interest',data.quote.annualRate+'%'],['Total interest',data.quote.totalInterest+' DM'],['Total repayment',data.quote.totalRepayment+' DM'],['First instalment · before issue',(data.firstInstalment||data.quote.firstInstalment||'0.00')+' DM'],['Principal after first instalment',(data.remainingPrincipal||data.quote.remainingPrincipal||data.quote.amount||'—')+' DM']])totals.append(el('dt',label),el('dd',value));result.append(totals,el('p','Simulation only · no application or payment','pb-muted'));details.replaceChildren(el('p',data.notice));const detail=el('details'),{wrap,body:rows}=grid(['Instalment','Payment · DM','Principal · DM','Interest · DM','Outstanding · DM']);detail.append(el('summary','+ Full repayment schedule'));for(const row of data.quote.schedule){const tr=el('tr');for(const value of [row.number,row.amount,row.principal,row.interest,row.balance])tr.append(el('td',String(value)));rows.append(tr);}detail.append(wrap);details.append(detail);if(view.intakeEnabled)applicationForm(details,product,account,values,data);else details.append(el('p','Application intake is not open yet. This quotation does not create a loan.','pb-muted'));}catch(error){if(active){message.textContent=error.message;result.replaceChildren(el('h3','Estimate unavailable'),el('p','Review your details and try again.'));details.replaceChildren();}}finally{busy=false;if(active){send.disabled=returnButton.disabled=false;amount.disabled=monthly.disabled=term.disabled=false;}}}; - } - function instruction(host,label,path,makeBody,{reason=true,amount=false,risk=false,confirmationField='confirmed',confirmation='I have reviewed and confirm this instruction.'}={}){ - const form=el('form',undefined,'pb-credit-action-form'),reasonField=el('textarea'),amountField=el('input'),riskField=el('input'),check=el('input'),send=el('button',label),message=el('p');reasonField.minLength=5;reasonField.maxLength=500;reasonField.required=reason;if(reason)form.append(field('Reason',reasonField));amountField.type='text';amountField.inputMode='decimal';amountField.required=amount;if(amount)form.append(field('Amount · DM',amountField));riskField.type='checkbox';if(risk)form.append(field('I have reviewed the risk flags and explicitly authorise this override.',riskField));check.type='checkbox';check.required=true;form.append(field(confirmation,check));send.type='submit';form.append(send,message);host.append(form);let pending=null; - form.onsubmit=async event=>{event.preventDefault();if(busy||!form.reportValidity()||!check.checked)return;busy=true;send.disabled=true;if(!pending)pending={requestId:crypto.randomUUID(),...makeBody(),[confirmationField]:true,...reason?{reason:reasonField.value.trim()}:{} ,...amount?{amount:amountField.value}:{} ,...risk?{riskOverride:riskField.checked}:{}};reasonField.disabled=amountField.disabled=riskField.disabled=check.disabled=true;for(const control of form.elements||[])if(control!==send)control.disabled=true;message.textContent='Submitting…';try{const response=await api.request(path,pending);if(!active)return;pending=null;notice=response.notice||'Credit instruction accepted. Its current status is shown below.';message.textContent=notice;busy=false;await load();if(active)frame.status.scrollIntoView?.({block:'center',behavior:'smooth'});}catch(error){if(active){message.textContent=error.uncertain?'Result not confirmed. Retry this same instruction; do not create a new one.':error.message;if(!error.uncertain){pending=null;reasonField.disabled=amountField.disabled=riskField.disabled=check.disabled=false;for(const control of form.elements||[])control.disabled=false;}send.textContent=pending?'Retry same instruction':label;}}finally{busy=false;if(active)send.disabled=false;}};return form; - } - function applicationForm(host,product,account,values,data){ - const grant=product.group==='grants',box=el('section',undefined,'pb-box'),motivation=el('textarea');motivation.required=!grant;motivation.minLength=10;motivation.maxLength=4000;box.append(el('h3',grant?'Accept your launch grant':'Request this credit'));const form=instruction(box,product.group==='grants'?'Accept launch grant':'Submit for bank review','/api/bank/credit/apply',()=>({...values,...(grant?{}:{motivation:motivation.value.trim()}),accepted:true,termsVersion:view.termsVersion}),{reason:false,confirmationField:'accepted',confirmation:'I accept the credit terms: '+data.quote.amount+' DM, '+data.quote.annualRate+'% annually, '+data.quote.monthly+' DM per month. '+(product.group==='grants'?'Disbursement is queued; this grant must be repaid.':'A bank decision and separate offer acceptance are required before funding.')});if(!grant)form.prepend(field('Purpose and repayment plan',motivation));host.append(box); - } - function dossier(){const staff=id==='loan-administration',loan=(staff?view.applications:view.loans).find(row=>row.id.toLowerCase()===dossierId);const back=el('a',staff?'← Credit Management':'← My Credit');back.href='/#bank/'+(staff?'loan-administration':'bank-loans');frame.content.append(back);if(!loan){frame.content.append(el('p','This Codex dossier is unavailable to your account.'));return;}const header=el('section',undefined,'pb-box');header.append(el('small','CODEX · IMPERIAL POSTBANK'),el('h3','Credit application dossier'),el('strong',loan.codex?.reference||codexLoanReference(loan.id)),el('p','Status: '+human(loan.codex?.status||codexLoanStatus(loan.state))+' · Bank state: '+human(loan.state)),el('p',human(loan.productKey)+' · '+loan.principal+' DM'));if(staff)header.append(el('p','Credit score: '+loan.score.score+' / 1000 · '+loan.score.band),el('p',loan.score.flags.join(' · ')));frame.content.append(header);const details=contractDetails(frame.content,loan,staff);queueMicrotask(()=>{if(active){details.open=true;void details.ontoggle();}});} +export function mountPostbankCredit(host,id,{fetcher=fetch,reviewSearch=globalThis.location?.search||''}={}){ + const review=id==='loan-administration'?creditReviewSelection(reviewSearch):null,dossierId=codexLoanSelection(reviewSearch)||review?.loanId||null; + const abort=new AbortController(),api=createUserAPI(fetcher,abort.signal);let active=true,busy=false,view,notice=null; + const frame=createCPV2ContentPage({host,title:title[id],description:id==='loan-centre'?'Explore launch grants and credit, compare repayments and review the full cost.':id==='bank-loans'?'Your applications, borrowing and repayment records, kept separate for each banking client.':'Review applications, evidence and client-specific borrowing risk.',reload:()=>void load()}); + async function load(){if(busy)return;busy=true;frame.status.hidden=false;frame.status.textContent='Loading authorised credit records…';try{view=await api.request(id==='loan-administration'?'/api/bank/admin/credit'+(dossierId?'?loanId='+encodeURIComponent(dossierId):''):'/api/bank/credit/overview');if(!active)return;frame.content.replaceChildren();if(id==='loan-centre')catalogue();else if(dossierId)dossier();else if(id==='bank-loans')myCredit();else management();frame.status.hidden=!notice;if(notice){frame.status.textContent=notice;notice=null;}frame.diagnostics.textContent='Central API · Independent bank database · '+new Date().toLocaleString('en-GB');}catch(e){if(active)frame.status.textContent=e.message;}finally{busy=false;}} + function catalogue(){ + frame.content.append(el('p','Choose your borrowing account and compare the full repayment cost. A simulation never moves money.','pb-muted')); + const accounts=view.accounts.filter(a=>a.canApply);if(!accounts.length){frame.content.append(el('p','Activate an eligible personal or organisational current account in My Products first.'));return;} + let selected=accounts[0];const tabs=el('div',undefined,'pb-credit-account-tabs'),stage=el('section',undefined,'pb-credit-stage');tabs.setAttribute('role','tablist');tabs.setAttribute('aria-label','Borrowing account');stage.id='pb-credit-account-panel';stage.setAttribute('role','tabpanel');const buttons=[]; + for(const account of accounts){const button=el('button',undefined,'pb-credit-account-tab');button.type='button';button.setAttribute('role','tab');button.id='pb-credit-account-tab-'+buttons.length;button.setAttribute('aria-controls',stage.id);button.append(el('strong',account.holder||account.name),el('small',account.name+' · '+account.number.replace(/(.{4})/g,'$1 ').trim()));button.onclick=()=>{if(busy)return;selected=account;renderProducts();};buttons.push({button,account});tabs.append(button);} + frame.content.append(tabs,stage); + function renderProducts(){for(const {button,account} of buttons){const chosen=account.id===selected.id;button.setAttribute('aria-selected',String(chosen));button.tabIndex=chosen?0:-1;if(chosen)stage.setAttribute('aria-labelledby',button.id);}stage.replaceChildren();const products=el('div',undefined,'pb-credit-products');stage.append(products);for(const [group,label]of [['grants','Launch Grants'],['personal','Personal Loans'],['professional','Business & Civic Loans'],['refinancing','Refinancing']]){const choices=(selected.products||view.products).filter(p=>p.group===group&&p.kinds.includes(selected.kind));if(!choices.length)continue;const section=el('section',undefined,'pb-credit-category'),cards=el('div',undefined,'pb-package-choices');section.append(el('h2',label),cards); + for(const product of choices){const theme=product.packageBenefit?'pro':creditTheme(product),card=el('section',undefined,'pb-choice-card pb-credit-product pb-plan-'+theme),brand=packageBrand({key:'pb_'+theme,name:product.name}),price=el('div',undefined,'pb-credit-price');price.append(el('strong',product.amount?product.amount+' DM':product.min+'–'+product.max+' DM'),el('small',(product.annualBps/100).toFixed(2)+'% annual interest'));const list=el('ul');for(const text of group==='grants'?['No collateral required','Choose your monthly repayment','Up to 12 monthly instalments']:['Fixed repayment schedule','First instalment: 5% before issue','First instalment deducted from the remaining debt'])list.append(el('li',text));if(product.packageBenefit)list.append(el('li',product.packageBenefit));const choose=el('button',product.revolving?'Coming soon':'Simulate repayments','pb-credit-simulate');choose.type='button';choose.disabled=!!product.revolving;choose.onclick=()=>{if(busy)return;stage.replaceChildren();simulator(product,selected,stage,renderProducts);};card.append(brand,price,list,choose);cards.append(card);}products.append(section);} + } + tabs.onkeydown=e=>{const index=buttons.findIndex(b=>b.button===e.target);if(index<0||!['ArrowLeft','ArrowRight','Home','End'].includes(e.key)||busy)return;e.preventDefault();const next=e.key==='Home'?0:e.key==='End'?buttons.length-1:(index+(e.key==='ArrowRight'?1:-1)+buttons.length)%buttons.length;buttons[next].button.onclick();buttons[next].button.focus();};renderProducts(); + } + function simulator(product,account,host,back){ + const navigation=el('div',undefined,'pb-credit-step'),returnButton=el('button','← Back to credit products');returnButton.type='button';returnButton.onclick=()=>{if(!busy)back();};navigation.append(returnButton,el('span','1. Choose credit / 2. Simulate repayments'));host.append(navigation,el('h2',product.name)); + const layout=el('div',undefined,'pb-credit-calculator'),form=el('form',undefined,'pb-transfer-form pb-credit-inputs'),amount=el('input'),term=el('select'),monthly=el('input'),send=el('button','Calculate repayments','pb-credit-simulate'),result=el('aside',undefined,'pb-credit-quote'),message=el('p');result.setAttribute('aria-live','polite');result.append(el('h3','Your repayment estimate'),el('p','Choose your amount and repayment period to see your monthly payment and total cost.'));amount.type=monthly.type='text';amount.inputMode=monthly.inputMode='decimal';amount.required=monthly.required=true;amount.value=product.amount||product.min;monthly.value=product.amount?Math.ceil(Number(product.amount)/12).toFixed(2):'';send.type='submit';form.append(el('p',(account.holder||account.name)+' · '+account.number,'pb-muted'));if(product.group==='grants'){amount.readOnly=true;form.append(field('Grant amount · DM',amount),field('Monthly repayment · DM',monthly));}else{for(const m of product.terms)option(term,m+' months',String(m));if(product.group==='refinancing')form.append(el('p','We calculate the exact settlement of all interest-bearing loans for this client. Grants remain separate.'));else form.append(field('Loan amount · DM',amount));form.append(field('Repayment period',term));}form.append(send,message);layout.append(form,result);host.append(layout);const details=el('div',undefined,'pb-credit-quote-details');host.append(details); + const stale=()=>{result.replaceChildren(el('h3','Update your estimate'),el('p','Your selection changed. Calculate again for the current repayment cost.'));details.replaceChildren();};amount.oninput=monthly.oninput=term.onchange=stale; + form.onsubmit=async e=>{e.preventDefault();if(busy||!form.reportValidity())return;busy=true;send.disabled=true;returnButton.disabled=true;message.textContent='Calculating…';const values={accountId:account.id,productKey:product.key,...(product.group==='grants'?{monthly:monthly.value}:{amount:amount.value,months:Number(term.value)})};amount.disabled=monthly.disabled=term.disabled=true;try{const data=await api.request('/api/bank/credit/simulate',values);if(!active)return;message.textContent='';result.replaceChildren(el('small','Estimated monthly repayment'),el('strong',data.quote.monthly+' DM','pb-credit-monthly'));const totals=el('dl');for(const [label,value]of [['Repayment period',data.quote.months+' months'],['Annual interest',data.quote.annualRate+'%'],['Total interest',data.quote.totalInterest+' DM'],['Total repayment',data.quote.totalRepayment+' DM'],['First instalment · before issue',(data.firstInstalment||data.quote.firstInstalment||'0.00')+' DM'],['Principal after first instalment',(data.remainingPrincipal||data.quote.remainingPrincipal||data.quote.amount||'—')+' DM']])totals.append(el('dt',label),el('dd',value));result.append(totals,el('p','Simulation only · no application or payment','pb-muted'));details.replaceChildren(el('p',data.notice));const detail=el('details'),{wrap,body:rows}=grid(['Instalment','Payment · DM','Principal · DM','Interest · DM','Outstanding · DM']);detail.append(el('summary','+ Full repayment schedule'));for(const row of data.quote.schedule){const tr=el('tr');for(const value of [row.number,row.amount,row.principal,row.interest,row.balance])tr.append(el('td',String(value)));rows.append(tr);}detail.append(wrap);details.append(detail);if(view.intakeEnabled)applicationForm(details,product,account,values,data);else details.append(el('p','Application intake is not open yet. This quotation does not create a loan.','pb-muted'));}catch(error){if(active){message.textContent=error.message;result.replaceChildren(el('h3','Estimate unavailable'),el('p','Review your details and try again.'));details.replaceChildren();}}finally{busy=false;if(active){send.disabled=returnButton.disabled=false;amount.disabled=monthly.disabled=term.disabled=false;}}}; + } + function instruction(host,label,path,makeBody,{reason=true,amount=false,risk=false,confirmationField='confirmed',confirmation='I have reviewed and confirm this instruction.'}={}){ + const form=el('form',undefined,'pb-credit-action-form'),reasonField=el('textarea'),amountField=el('input'),riskField=el('input'),check=el('input'),send=el('button',label),message=el('p');reasonField.minLength=5;reasonField.maxLength=500;reasonField.required=reason;if(reason)form.append(field('Reason',reasonField));amountField.type='text';amountField.inputMode='decimal';amountField.required=amount;if(amount)form.append(field('Amount · DM',amountField));riskField.type='checkbox';if(risk)form.append(field('I have reviewed the risk flags and explicitly authorise this override.',riskField));check.type='checkbox';check.required=true;form.append(field(confirmation,check));send.type='submit';form.append(send,message);host.append(form);let pending=null; + form.onsubmit=async event=>{event.preventDefault();if(busy||!form.reportValidity()||!check.checked)return;busy=true;send.disabled=true;if(!pending)pending={requestId:crypto.randomUUID(),...makeBody(),[confirmationField]:true,...reason?{reason:reasonField.value.trim()}:{} ,...amount?{amount:amountField.value}:{} ,...risk?{riskOverride:riskField.checked}:{}};reasonField.disabled=amountField.disabled=riskField.disabled=check.disabled=true;for(const control of form.elements||[])if(control!==send)control.disabled=true;message.textContent='Submitting…';try{const response=await api.request(path,pending);if(!active)return;pending=null;notice=response.notice||'Credit instruction accepted. Its current status is shown below.';message.textContent=notice;busy=false;await load();if(active)frame.status.scrollIntoView?.({block:'center',behavior:'smooth'});}catch(error){if(active){message.textContent=error.uncertain?'Result not confirmed. Retry this same instruction; do not create a new one.':error.message;if(!error.uncertain){pending=null;reasonField.disabled=amountField.disabled=riskField.disabled=check.disabled=false;for(const control of form.elements||[])control.disabled=false;}send.textContent=pending?'Retry same instruction':label;}}finally{busy=false;if(active)send.disabled=false;}};return form; + } + function applicationForm(host,product,account,values,data){ + const grant=product.group==='grants',box=el('section',undefined,'pb-box'),motivation=el('textarea');motivation.required=!grant;motivation.minLength=10;motivation.maxLength=4000;box.append(el('h3',grant?'Accept your launch grant':'Request this credit'));const form=instruction(box,product.group==='grants'?'Accept launch grant':'Submit for bank review','/api/bank/credit/apply',()=>({...values,...(grant?{}:{motivation:motivation.value.trim()}),accepted:true,termsVersion:view.termsVersion}),{reason:false,confirmationField:'accepted',confirmation:'I accept the credit terms: '+data.quote.amount+' DM, '+data.quote.annualRate+'% annually, '+data.quote.monthly+' DM per month. '+(product.group==='grants'?'Disbursement is queued; this grant must be repaid.':'A bank decision and separate offer acceptance are required before funding.')});if(!grant)form.prepend(field('Purpose and repayment plan',motivation));host.append(box); + } + function dossier(){const staff=id==='loan-administration',loan=(staff?view.applications:view.loans).find(row=>row.id.toLowerCase()===dossierId);const back=el('a',staff?'← Credit Management':'← My Credit');back.href='/#bank/'+(staff?'loan-administration':'bank-loans');frame.content.append(back);if(!loan){frame.content.append(el('p','This J.A.R.V.I.S. dossier is unavailable to your account.'));return;}const header=el('section',undefined,'pb-box');header.append(el('small','CODEX · IMPERIAL POSTBANK'),el('h3','Credit application dossier'),el('strong',loan.codex?.reference||codexLoanReference(loan.id)),el('p','Status: '+human(loan.codex?.status||codexLoanStatus(loan.state))+' · Bank state: '+human(loan.state)),el('p',human(loan.productKey)+' · '+loan.principal+' DM'));if(staff)header.append(el('p','Credit score: '+loan.score.score+' / 1000 · '+loan.score.band),el('p',loan.score.flags.join(' · ')));frame.content.append(header);const details=contractDetails(frame.content,loan,staff);queueMicrotask(()=>{if(active){details.open=true;void details.ontoggle();}});} function contractDetails(host,loan,staff=false,detailRow=null){ - if(!dossierId){const link=el('a','Open Codex dossier →');link.href='/?codexLoan='+encodeURIComponent(loan.id)+'#bank/'+(staff?'loan-administration':'bank-loans');const reference=el('small',loan.codex?.reference||codexLoanReference(loan.id));host.append(reference,link);return link;} - let loaded=false;const expand=el('details'),summary=el('summary','+ Contract details & actions'),body=el('div');body.className='pb-credit-contract-panel';body.id='credit-contract-'+loan.id;summary.setAttribute('aria-controls',body.id);if(detailRow){detailRow.firstElementChild.append(body);expand.append(summary);}else expand.append(summary,body);host.append(expand);expand.ontoggle=async()=>{if(detailRow)detailRow.hidden=!expand.open;summary.setAttribute('aria-expanded',String(expand.open));if(!expand.open||loaded)return;loaded=true;body.textContent='Loading current contract…';try{const d=await api.request((staff?'/api/bank/admin/credit/details':'/api/bank/credit/details')+'?loanId='+encodeURIComponent(loan.id));if(!active)return;body.replaceChildren(el('p',loan.motivation),el('p','Annual rate: '+d.quote.annualRate+'% · Total repayment: '+d.quote.totalRepayment+' DM · First instalment: '+(d.quote.firstInstalment||'0.00')+' DM'+(d.collateral!=='0.00'?' · Historical pledged collateral: '+d.collateral+' DM':'')),el('p','Settlement estimate today: '+d.settlement+' DM'),el('p',d.decision||'No decision recorded.'));if(d.codex){body.append(el('p','Codex dossier: '+d.codex.reference+' · '+human(d.codex.status)));}if(d.replacedBy)body.append(el('p','Replaced by refinancing contract '+d.replacedBy+'. Original history is retained.'));for(const notice of d.notices||[]){const box=el('aside',undefined,'pb-credit-notice'+(d.state==='arrears'?' pb-credit-notice-alert':''));box.append(el('strong',notice.subject),el('p',notice.body));body.append(box);}const enabled=staff?view.processing==='active'&&view.canManage:view.intakeEnabled; - if(!staff&&d.maximumRepayment!==undefined)body.append(el('p','Queued repayments / recoveries: '+d.queuedRepayments+' DM · Maximum additional repayment today: '+d.maximumRepayment+' DM. Available account funds are checked separately.')); - if(enabled&&!staff){if(d.state==='offered')instruction(body,'Accept credit offer','/api/bank/credit/action',()=>({loanId:loan.id,action:'accept',expectedVersion:d.version,reason:'Accepted the disclosed credit offer'}),{reason:false,confirmation:'I accept the full repayment cost and authorise the first instalment from my own funds before the loan is issued. It reduces my remaining debt.'});if(['submitted','approved_pending','offered','payout_queued'].includes(d.state))instruction(body,'Withdraw application','/api/bank/credit/action',()=>({loanId:loan.id,action:'withdraw'}));if(['active','arrears'].includes(d.state))instruction(body,'Make a repayment','/api/bank/credit/action',()=>({loanId:loan.id,action:'repay'}),{amount:true,confirmation:'Debit the linked current account at the next four-hour bank window. Earned interest is charged; future interest is waived. Confirmed reserved funds retain their bank value date.'});} - if(enabled&&staff){if(d.state==='submitted'&&loan.canReview){const approveForm=instruction(body,'Approve application','/api/bank/admin/credit/decision',()=>({loanId:loan.id,action:'approve'}),{risk:loan.score.score<400||loan.score.flags.includes('High Monthly Commitments')});const declineForm=instruction(body,'Reject application','/api/bank/admin/credit/decision',()=>({loanId:loan.id,action:'decline'}));if(review?.loanId===loan.id){const selected=review.action==='approve'?approveForm:declineForm;selected.classList.add('pb-credit-selected-decision');selected.prepend(el('h3',review.action==='approve'?'Confirm approval':'Confirm rejection'));queueMicrotask(()=>{if(active){selected.scrollIntoView?.({block:'center',behavior:'smooth'});selected.querySelector?.('textarea')?.focus();}});}}if(d.state==='arrears')instruction(body,'Recover pledged collateral','/api/bank/admin/credit/recover',()=>({loanId:loan.id,action:'recover'}),{amount:true,confirmation:'Recover only this contract’s pledged DM to reduce its debt. No inventory is involved.'});} - if(d.schedule.length){const {wrap,body:rows}=grid(['Due date','Principal · DM','Interest · DM','Paid · DM','Status']);for(const row of d.schedule){const tr=el('tr');for(const value of [new Date(row.dueAt).toLocaleDateString('en-GB'),row.principal,row.interest,row.paid,human(row.state)])tr.append(el('td',value));rows.append(tr);}body.append(wrap);}else body.append(el('p','The repayment schedule starts only when funds are disbursed.'));const history=el('details');history.append(el('summary','Dossier history'));if(Array.isArray(d.events)&&d.events.length){const {wrap,body:rows}=grid(['Recorded','Action']);for(const event of d.events){const row=el('tr');row.append(el('td',new Date(event.createdAt).toLocaleString('en-GB')),el('td',human(event.action)));rows.append(row);}history.append(wrap);}else history.append(el('p',Array.isArray(d.events)?'No dossier events are recorded.':'Dossier history is unavailable.'));body.append(history);if(review?.loanId===loan.id&&(!enabled||!loan.canReview||d.state!=='submitted')){const explanation=d.state!=='submitted'?'This application is already '+human(d.state).toLowerCase()+'.':!enabled?'Credit decisions are unavailable for your account or processing is paused.':'A different bank manager must review this application because you submitted it or control its borrowing account. No decision has been recorded; the Codex dossier remains pending.';const message=el('aside',explanation,'pb-credit-notice');message.setAttribute('role','status');body.prepend(message);queueMicrotask(()=>{if(active)message.scrollIntoView?.({block:'center'});});} - }catch(error){if(active){body.textContent=error.message;loaded=false;}}};return expand; - } - function myCredit(){const {wrap,body}=grid(['Application','Product','Status','Principal · DM','Outstanding · DM','Monthly · DM','Details']);for(const loan of view.loans){const tr=el('tr'),cell=el('td'),expanded=el('tr'),content=el('td');expanded.className='pb-credit-detail-row';expanded.hidden=true;content.colSpan=7;expanded.append(content);contractDetails(cell,loan,false,expanded);for(const value of [loan.codex?.reference||codexLoanReference(loan.id),human(loan.productKey),human(loan.state),loan.principal,loan.outstanding,loan.monthly])tr.append(el('td',value));tr.append(cell);body.append(tr,expanded);}frame.content.append(wrap);if(!view.loans.length)frame.content.append(el('p','No applications or loans are registered for your authorised banking clients.'));} - function management(){frame.content.append(el('p',view.processing==='active'?'Review the evidence before deciding. Treasury funds are reserved for approved offers; the borrower must accept before disbursement.':'Credit processing is not active yet.','pb-muted'));const {wrap,body}=grid(['Client','Product','Submitted','Amount · DM','State','Review']);for(const loan of view.applications){const tr=el('tr'),cell=el('td'),expanded=el('tr'),content=el('td');expanded.className='pb-credit-detail-row';expanded.hidden=true;content.colSpan=6;expanded.append(content);cell.append(el('p','Credit score: '+loan.score.score+' / 1000 · '+loan.score.band+(loan.score.limitedHistory?' · Limited history':'')),el('p',loan.score.flags.join(' · ')));const details=contractDetails(cell,loan,true,expanded);if(review?.loanId===loan.id)queueMicrotask(()=>{if(active){details.open=true;void details.ontoggle();}});for(const value of [loan.entity,human(loan.productKey),new Date(loan.createdAt).toLocaleDateString('en-GB'),loan.principal,human(loan.state)])tr.append(el('td',value));tr.append(cell);body.append(tr,expanded);}frame.content.append(wrap);if(!view.applications.length)frame.content.append(el('p',review?'This credit application was not found or is unavailable to your account.':'No credit applications are awaiting review.'));if(review){const back=el('a','View all credit applications');back.href='/#bank/loan-administration';frame.content.prepend(el('p','Reviewing the linked Codex application dossier. No decision is submitted until you confirm.'),back);}} - void load();return()=>{active=false;abort.abort();frame.root.remove();}; -} + if(!dossierId){const link=el('a','Open J.A.R.V.I.S. dossier →');link.href='/?codexLoan='+encodeURIComponent(loan.id)+'#bank/'+(staff?'loan-administration':'bank-loans');const reference=el('small',loan.codex?.reference||codexLoanReference(loan.id));host.append(reference,link);return link;} + let loaded=false;const expand=el('details'),summary=el('summary','+ Contract details & actions'),body=el('div');body.className='pb-credit-contract-panel';body.id='credit-contract-'+loan.id;summary.setAttribute('aria-controls',body.id);if(detailRow){detailRow.firstElementChild.append(body);expand.append(summary);}else expand.append(summary,body);host.append(expand);expand.ontoggle=async()=>{if(detailRow)detailRow.hidden=!expand.open;summary.setAttribute('aria-expanded',String(expand.open));if(!expand.open||loaded)return;loaded=true;body.textContent='Loading current contract…';try{const d=await api.request((staff?'/api/bank/admin/credit/details':'/api/bank/credit/details')+'?loanId='+encodeURIComponent(loan.id));if(!active)return;body.replaceChildren(el('p',loan.motivation),el('p','Annual rate: '+d.quote.annualRate+'% · Total repayment: '+d.quote.totalRepayment+' DM · First instalment: '+(d.quote.firstInstalment||'0.00')+' DM'+(d.collateral!=='0.00'?' · Historical pledged collateral: '+d.collateral+' DM':'')),el('p','Settlement estimate today: '+d.settlement+' DM'),el('p',d.decision||'No decision recorded.'));if(d.codex){body.append(el('p','J.A.R.V.I.S. dossier: '+d.codex.reference+' · '+human(d.codex.status)));}if(d.replacedBy)body.append(el('p','Replaced by refinancing contract '+d.replacedBy+'. Original history is retained.'));for(const notice of d.notices||[]){const box=el('aside',undefined,'pb-credit-notice'+(d.state==='arrears'?' pb-credit-notice-alert':''));box.append(el('strong',notice.subject),el('p',notice.body));body.append(box);}const enabled=staff?view.processing==='active'&&view.canManage:view.intakeEnabled; + if(!staff&&d.maximumRepayment!==undefined)body.append(el('p','Queued repayments / recoveries: '+d.queuedRepayments+' DM · Maximum additional repayment today: '+d.maximumRepayment+' DM. Available account funds are checked separately.')); + if(enabled&&!staff){if(d.state==='offered')instruction(body,'Accept credit offer','/api/bank/credit/action',()=>({loanId:loan.id,action:'accept',expectedVersion:d.version,reason:'Accepted the disclosed credit offer'}),{reason:false,confirmation:'I accept the full repayment cost and authorise the first instalment from my own funds before the loan is issued. It reduces my remaining debt.'});if(['submitted','approved_pending','offered','payout_queued'].includes(d.state))instruction(body,'Withdraw application','/api/bank/credit/action',()=>({loanId:loan.id,action:'withdraw'}));if(['active','arrears'].includes(d.state))instruction(body,'Make a repayment','/api/bank/credit/action',()=>({loanId:loan.id,action:'repay'}),{amount:true,confirmation:'Debit the linked current account at the next four-hour bank window. Earned interest is charged; future interest is waived. Confirmed reserved funds retain their bank value date.'});} + if(enabled&&staff){if(d.state==='submitted'&&loan.canReview){const approveForm=instruction(body,'Approve application','/api/bank/admin/credit/decision',()=>({loanId:loan.id,action:'approve'}),{risk:loan.score.score<400||loan.score.flags.includes('High Monthly Commitments')});const declineForm=instruction(body,'Reject application','/api/bank/admin/credit/decision',()=>({loanId:loan.id,action:'decline'}));if(review?.loanId===loan.id){const selected=review.action==='approve'?approveForm:declineForm;selected.classList.add('pb-credit-selected-decision');selected.prepend(el('h3',review.action==='approve'?'Confirm approval':'Confirm rejection'));queueMicrotask(()=>{if(active){selected.scrollIntoView?.({block:'center',behavior:'smooth'});selected.querySelector?.('textarea')?.focus();}});}}if(d.state==='arrears')instruction(body,'Recover pledged collateral','/api/bank/admin/credit/recover',()=>({loanId:loan.id,action:'recover'}),{amount:true,confirmation:'Recover only this contract’s pledged DM to reduce its debt. No inventory is involved.'});} + if(d.schedule.length){const {wrap,body:rows}=grid(['Due date','Principal · DM','Interest · DM','Paid · DM','Status']);for(const row of d.schedule){const tr=el('tr');for(const value of [new Date(row.dueAt).toLocaleDateString('en-GB'),row.principal,row.interest,row.paid,human(row.state)])tr.append(el('td',value));rows.append(tr);}body.append(wrap);}else body.append(el('p','The repayment schedule starts only when funds are disbursed.'));const history=el('details');history.append(el('summary','Dossier history'));if(Array.isArray(d.events)&&d.events.length){const {wrap,body:rows}=grid(['Recorded','Action']);for(const event of d.events){const row=el('tr');row.append(el('td',new Date(event.createdAt).toLocaleString('en-GB')),el('td',human(event.action)));rows.append(row);}history.append(wrap);}else history.append(el('p',Array.isArray(d.events)?'No dossier events are recorded.':'Dossier history is unavailable.'));body.append(history);if(review?.loanId===loan.id&&(!enabled||!loan.canReview||d.state!=='submitted')){const explanation=d.state!=='submitted'?'This application is already '+human(d.state).toLowerCase()+'.':!enabled?'Credit decisions are unavailable for your account or processing is paused.':'A different bank manager must review this application because you submitted it or control its borrowing account. No decision has been recorded; the J.A.R.V.I.S. dossier remains pending.';const message=el('aside',explanation,'pb-credit-notice');message.setAttribute('role','status');body.prepend(message);queueMicrotask(()=>{if(active)message.scrollIntoView?.({block:'center'});});} + }catch(error){if(active){body.textContent=error.message;loaded=false;}}};return expand; + } + function myCredit(){const {wrap,body}=grid(['Application','Product','Status','Principal · DM','Outstanding · DM','Monthly · DM','Details']);for(const loan of view.loans){const tr=el('tr'),cell=el('td'),expanded=el('tr'),content=el('td');expanded.className='pb-credit-detail-row';expanded.hidden=true;content.colSpan=7;expanded.append(content);contractDetails(cell,loan,false,expanded);for(const value of [loan.codex?.reference||codexLoanReference(loan.id),human(loan.productKey),human(loan.state),loan.principal,loan.outstanding,loan.monthly])tr.append(el('td',value));tr.append(cell);body.append(tr,expanded);}frame.content.append(wrap);if(!view.loans.length)frame.content.append(el('p','No applications or loans are registered for your authorised banking clients.'));} + function management(){frame.content.append(el('p',view.processing==='active'?'Review the evidence before deciding. Treasury funds are reserved for approved offers; the borrower must accept before disbursement.':'Credit processing is not active yet.','pb-muted'));const {wrap,body}=grid(['Client','Product','Submitted','Amount · DM','State','Review']);for(const loan of view.applications){const tr=el('tr'),cell=el('td'),expanded=el('tr'),content=el('td');expanded.className='pb-credit-detail-row';expanded.hidden=true;content.colSpan=6;expanded.append(content);cell.append(el('p','Credit score: '+loan.score.score+' / 1000 · '+loan.score.band+(loan.score.limitedHistory?' · Limited history':'')),el('p',loan.score.flags.join(' · ')));const details=contractDetails(cell,loan,true,expanded);if(review?.loanId===loan.id)queueMicrotask(()=>{if(active){details.open=true;void details.ontoggle();}});for(const value of [loan.entity,human(loan.productKey),new Date(loan.createdAt).toLocaleDateString('en-GB'),loan.principal,human(loan.state)])tr.append(el('td',value));tr.append(cell);body.append(tr,expanded);}frame.content.append(wrap);if(!view.applications.length)frame.content.append(el('p',review?'This credit application was not found or is unavailable to your account.':'No credit applications are awaiting review.'));if(review){const back=el('a','View all credit applications');back.href='/#bank/loan-administration';frame.content.prepend(el('p','Reviewing the linked J.A.R.V.I.S. application dossier. No decision is submitted until you confirm.'),back);}} + void load();return()=>{active=false;abort.abort();frame.root.remove();}; +} diff --git a/website/control-panel/public/cp-v2/v2.js b/website/control-panel/public/cp-v2/v2.js index 34a03461..cce42bd8 100644 --- a/website/control-panel/public/cp-v2/v2.js +++ b/website/control-panel/public/cp-v2/v2.js @@ -1,248 +1,248 @@ -const menu={"version":2,"mode":"static-design-preview","source":"independent-v2-registry","workspaces":[{"id":"realm","label":"My Realm","icon":"user-round","groups":[{"label":"Identity","items":[{"id":"game","label":"Citizen Passport","viewPermission":"web.cp.v2.game.view","managePermission":"web.cp.v2.game.manage"},{"id":"site-profile","label":"Personal Records","viewPermission":"web.cp.v2.site.profile.view","managePermission":"web.cp.v2.site.profile.manage"},{"id":"security","label":"Account Security","viewPermission":"web.cp.v2.security.view","managePermission":"web.cp.v2.security.manage"},{"id":"discord-link","label":"Discord Link","viewPermission":"web.cp.v2.discord.link.view","managePermission":"web.cp.v2.discord.link.manage"},{"id":"planetary-inventory","label":"My Inventory","viewPermission":"web.cp.v2.planetary.inventory.view","managePermission":"web.cp.v2.planetary.inventory.manage"}]},{"label":"Communications","items":[{"id":"shared-inbox","label":"My Correspondence","viewPermission":"web.cp.v2.shared.inbox.view","managePermission":"web.cp.v2.shared.inbox.manage"},{"id":"tickets","label":"Petition Hall","viewPermission":"web.cp.v2.tickets.view","managePermission":"web.cp.v2.tickets.manage"},{"id":"rewards-codes","label":"Rewards & Seals","viewPermission":"web.cp.v2.rewards.codes.view","managePermission":"web.cp.v2.rewards.codes.manage"}]},{"label":"Adventures","items":[{"id":"crysknife","label":"Order of the Crysknife","viewPermission":"web.cp.v2.crysknife.view","managePermission":"web.cp.v2.crysknife.manage"}]},{"label":"Commerce","items":[{"id":"personal-bank","label":"My Treasury","viewPermission":"web.cp.v2.personal.bank.view","managePermission":"web.cp.v2.personal.bank.manage"},{"id":"transactions","label":"Transaction Ledger","viewPermission":"web.cp.v2.transactions.view","managePermission":"web.cp.v2.transactions.manage"},{"id":"sales-history","label":"Sales History","viewPermission":"web.cp.v2.sales.history.view","managePermission":"web.cp.v2.sales.history.manage"},{"id":"exchange-settings","label":"Exchange Preferences","viewPermission":"web.cp.v2.exchange.settings.view","managePermission":"web.cp.v2.exchange.settings.manage"},{"id":"shop-settings","label":"Merchant Preferences","viewPermission":"web.cp.v2.shop.settings.view","managePermission":"web.cp.v2.shop.settings.manage"},{"id":"item-exchange","label":"Item Exchange","viewPermission":"web.menu.inventory"},{"id":"item-listings","label":"My Item Listings","viewPermission":"web.menu.inventory"},{"id":"item-post","label":"Post an Item","viewPermission":"web.menu.inventory"}]}]},{"id":"clan","label":"My Clan","icon":"flag","groups":[{"label":"Your Household","items":[{"id":"clan-overview","label":"Household Dashboard"},{"id":"clan-roster","label":"Clan Roster","dashboardOnly":true},{"id":"clan-requests","label":"Join Requests","dashboardOnly":true},{"id":"clan-settings","label":"Clan Settings"}]},{"label":"Household Affairs","items":[{"id":"clan-boards","label":"Clan Boards"},{"id":"clan-mail","label":"Clan Correspondence","dashboardOnly":true},{"id":"clan-bank","label":"Clan Treasury","dashboardOnly":true},{"id":"clan-shop","label":"Clan Exchange"},{"id":"clan-tailor","label":"Clan Tailor"},{"id":"clan-listings","label":"My Listings"},{"id":"clan-post-listing","label":"Post a Listing"}]},{"label":"Campaigns & Realms","items":[{"id":"clan-claims","label":"Claims"},{"id":"clan-subhouses","label":"Subhouses"},{"id":"clan-patronage","label":"Patronage Directory"},{"id":"clan-quests","label":"Clan Expeditions"},{"id":"clan-campaigns","label":"Campaigns"},{"id":"clan-directory","label":"Clan Directory"}]}]},{"id":"bureau","label":"Imperial Bureau","icon":"shield","groups":[{"label":"Accounts & Permissions","items":[{"id":"user-management","label":"Personnel Management","viewPermission":"web.cp.v2.user.management.view","managePermission":"web.cp.v2.user.management.manage"},{"id":"permissions","label":"Roles & Permissions","viewPermission":"web.cp.v2.permissions.view","managePermission":"web.cp.v2.permissions.manage"},{"id":"manual-seals","label":"Seals & Honours","viewPermission":"web.cp.v2.manual.seals.view","managePermission":"web.cp.v2.manual.seals.manage"},{"id":"seal-generator","label":"Seal Designer","viewPermission":"web.cp.v2.manual.seals.view","managePermission":"web.cp.v2.manual.seals.manage"},{"id":"company-management","label":"Company Registry","viewPermission":"web.cp.v2.company.management.view","managePermission":"web.cp.v2.company.management.manage"},{"id":"company-management-v2","label":"Company Management","viewPermission":"web.cp.v2.company.management.v2.view","managePermission":"web.cp.v2.company.management.v2.manage"},{"id":"company-audit","label":"Company Audit","viewPermission":"web.cp.v2.company.audit.view","managePermission":"web.cp.v2.company.audit.manage"}]},{"label":"Management","items":[{"id":"codex-management","label":"Codex Management","viewPermission":"web.cp.v2.items.view","managePermission":"web.cp.v2.items.manage"}]},{"label":"Shops & Items","items":[{"id":"staff-bank","label":"Treasury Accounts","viewPermission":"web.cp.v2.staff.bank.view","managePermission":"web.cp.v2.staff.bank.manage"},{"id":"server-kits","label":"Kit Management","viewPermission":"web.cp.v2.server.kits.view","managePermission":"web.cp.v2.server.kits.manage","dashboardOnly":true},{"id":"kit-publishing","label":"Kit Publishing","viewPermission":"web.cp.v2.kit.publishing.view","managePermission":"web.cp.v2.kit.publishing.manage","dashboardOnly":true},{"id":"kit-claims","label":"Kit Claims","viewPermission":"web.cp.v2.kit.claims.view","managePermission":"web.cp.v2.kit.claims.manage","dashboardOnly":true},{"id":"exchange-admin","label":"Exchange Management","viewPermission":"web.cp.v2.exchange.admin.view","managePermission":"web.cp.v2.exchange.admin.manage","dashboardOnly":true},{"id":"shop-admin","label":"Shop Management","viewPermission":"web.cp.v2.shop.admin.view","managePermission":"web.cp.v2.shop.admin.manage"},{"id":"items","label":"Item Management","viewPermission":"web.cp.v2.items.view","managePermission":"web.cp.v2.items.manage","dashboardOnly":true}]},{"label":"Community Services","items":[{"id":"website-posts","label":"News Management","viewPermission":"web.cp.v2.website.posts.view","managePermission":"web.cp.v2.website.posts.manage"},{"id":"staff-tickets","label":"Support Tickets","viewPermission":"web.cp.v2.staff.tickets.view","managePermission":"web.cp.v2.staff.tickets.manage"},{"id":"bans","label":"Bans & Appeals","viewPermission":"web.cp.v2.bans.view","managePermission":"web.cp.v2.bans.manage"},{"id":"ban-evidence","label":"Ban Evidence","viewPermission":"web.cp.v2.ban.evidence.view","managePermission":"web.cp.v2.ban.evidence.manage"},{"id":"forum-admin","label":"Forum Moderation","viewPermission":"web.cp.v2.forum.admin.view","managePermission":"web.cp.v2.forum.admin.manage"},{"id":"quests-admin","label":"Quest Management","viewPermission":"web.cp.v2.quests.admin.view","managePermission":"web.cp.v2.quests.admin.manage"},{"id":"community-goals","label":"Community Projects","viewPermission":"web.cp.v2.community.goals.view","managePermission":"web.cp.v2.community.goals.manage"},{"id":"support-management","label":"Support Administration","viewPermission":"web.cp.v2.support.management.view","managePermission":"web.cp.v2.support.management.manage"},{"id":"menu-badges","label":"Menu badges"}]},{"label":"Infrastructure","items":[{"id":"server-operations","label":"Server Operations","viewPermission":"web.cp.v2.server.operations.view","managePermission":"web.cp.v2.server.operations.manage"},{"id":"hosting-control","label":"Hosting Management","viewPermission":"web.cp.v2.hosting.control.view","managePermission":"web.cp.v2.hosting.control.manage"}]},{"label":"Bank Management","items":[{"id":"tax-treasury","label":"Tax Treasury Payments","viewPermission":"web.bank.staff.manage","managePermission":"web.bank.staff.manage"},{"id":"account-authorisations","label":"Account Authorisations","viewPermission":"web.bank.staff.view","managePermission":"web.bank.staff.manage"}]}]},{"id":"forge","label":"DuneForge","icon":"code-2","groups":[{"label":"Dev Control","items":[{"id":"dev-panel","label":"Dev Control","viewPermission":"web.cp.v2.dev.panel.view","managePermission":"web.cp.v2.dev.panel.manage"},{"id":"dev-queue","label":"Dev Listing","viewPermission":"web.cp.v2.dev.queue.view","managePermission":"web.cp.v2.dev.queue.manage"},{"id":"dev-approvals","label":"Dev Approvals","viewPermission":"web.cp.v2.dev.approvals.view","managePermission":"web.cp.v2.dev.approvals.manage"},{"id":"dev-new","label":"Submit Dev Request","viewPermission":"web.cp.v2.dev.new.view","managePermission":"web.cp.v2.dev.new.manage"},{"id":"dev-archive","label":"Dev Archive","viewPermission":"web.cp.v2.dev.archive.view","managePermission":"web.cp.v2.dev.archive.manage"}]},{"label":"Engineering","items":[{"id":"dev-builds","label":"Build & CI Monitor","viewPermission":"web.cp.v2.dev.builds.view","managePermission":"web.cp.v2.dev.builds.manage"},{"id":"dev-releases","label":"Release Ledger","viewPermission":"web.cp.v2.dev.releases.view","managePermission":"web.cp.v2.dev.releases.manage"},{"id":"dev-api","label":"API Reference","viewPermission":"web.cp.v2.dev.api.view","managePermission":"web.cp.v2.dev.api.manage"},{"id":"dev-audit","label":"Change Audit","viewPermission":"web.cp.v2.dev.audit.view","managePermission":"web.cp.v2.dev.audit.manage"}]},{"label":"DuneGit","items":[{"id":"git-workspace","label":"DuneGit Workspace","viewPermission":"web.menu.security","managePermission":"web.git.admin"},{"id":"git-repositories","label":"Repositories","viewPermission":"web.menu.security","managePermission":"web.git.admin"},{"id":"git-administration","label":"Git Administration","viewPermission":"web.git.admin","managePermission":"web.git.admin"}]}]},{"id":"politics","label":"Realm & Politics","icon":"crown","groups":[{"label":"Assembly","items":[{"id":"politics-overview","label":"Overview","viewPermission":"web.menu.game"},{"id":"landsraad","label":"Landsraad Assembly","viewPermission":"web.menu.game"},{"id":"council-motd","label":"Proclamations","viewPermission":"web.menu.game"},{"id":"applications","label":"Election Applications","viewPermission":"web.menu.game"},{"id":"house-elections","label":"House Elections","viewPermission":"web.menu.game"},{"id":"imperial-elections","label":"Emperor Elections","viewPermission":"web.menu.game"},{"id":"electoral-roll","label":"Electoral Roll","viewPermission":"web.menu.game"}]},{"label":"Councils","items":[{"id":"formal-council","label":"Faction Council","viewPermission":"web.menu.game"},{"id":"imperial-command","label":"Imperial Council","viewPermission":"web.menu.game"},{"id":"imperial-water","label":"Water Rights","viewPermission":"web.menu.game"},{"id":"imperial-spice","label":"Spice Rights","viewPermission":"web.menu.game"}]}]},{"id":"post","label":"Imperial Post","icon":"mail","groups":[{"label":"Correspondence","items":[{"id":"mail-inbox","label":"Incoming Dispatches","viewPermission":"web.cp.v2.mail.inbox.view","managePermission":"web.cp.v2.mail.inbox.manage"},{"id":"mail-compose","label":"Compose Dispatch","viewPermission":"web.cp.v2.mail.compose.view","managePermission":"web.cp.v2.mail.compose.manage"},{"id":"mail-sent","label":"Sent Dispatches","viewPermission":"web.cp.v2.mail.sent.view","managePermission":"web.cp.v2.mail.sent.manage"},{"id":"mail-drafts","label":"Draft Dispatches","viewPermission":"web.cp.v2.mail.drafts.view","managePermission":"web.cp.v2.mail.drafts.manage"},{"id":"mail-archive","label":"Imperial Archives","viewPermission":"web.cp.v2.mail.archive.view","managePermission":"web.cp.v2.mail.archive.manage"},{"id":"mail-trash","label":"Discarded Dispatches","viewPermission":"web.cp.v2.mail.trash.view","managePermission":"web.cp.v2.mail.trash.manage"}]},{"label":"Channels","items":[{"id":"shared-inbox","label":"Internal Dispatches","viewPermission":"web.cp.v2.shared.inbox.view","managePermission":"web.cp.v2.shared.inbox.manage"},{"id":"webmail","label":"External Mail","viewPermission":"web.cp.v2.webmail.view","managePermission":"web.cp.v2.webmail.manage"},{"id":"mail-contacts","label":"Address Book","viewPermission":"web.cp.v2.mail.contacts.view","managePermission":"web.cp.v2.mail.contacts.manage"},{"id":"mail-settings","label":"Correspondence Settings","viewPermission":"web.cp.v2.mail.settings.view","managePermission":"web.cp.v2.mail.settings.manage"},{"id":"mail-admin","label":"Postmaster Administration","viewPermission":"web.cp.v2.mail.admin.view","managePermission":"web.cp.v2.mail.admin.manage"}]}]},{"id":"bank","label":"Imperial Postbank","icon":"landmark","groups":[{"label":"Accounts & Payments","items":[{"id":"bank-overview","label":"My Accounts","viewPermission":"web.cp.v2.bank.overview.view","managePermission":"web.cp.v2.bank.overview.manage"},{"id":"personal-bank","label":"My Products","viewPermission":"web.cp.v2.personal.bank.view","managePermission":"web.cp.v2.personal.bank.manage"},{"id":"bank-transfers","label":"Transfers","viewPermission":"web.cp.v2.bank.transfers.view","managePermission":"web.cp.v2.bank.transfers.manage"},{"id":"bank-statements","label":"Transactions","viewPermission":"web.cp.v2.bank.statements.view","managePermission":"web.cp.v2.bank.statements.manage"},{"id":"bank-beneficiaries","label":"Beneficiaries","viewPermission":"web.cp.v2.bank.beneficiaries.view","managePermission":"web.cp.v2.bank.beneficiaries.manage"},{"id":"bank-authorisations","label":"My Authorisations","viewPermission":"web.bank.personal.view"}]},{"label":"Credit","items":[{"id":"loan-centre","label":"Loans & Grants","viewPermission":"web.cp.v2.loan.centre.view","managePermission":"web.cp.v2.loan.centre.manage"},{"id":"bank-loans","label":"My Credit","viewPermission":"web.cp.v2.bank.loans.view","managePermission":"web.cp.v2.bank.loans.manage"},{"id":"loan-administration","label":"Credit Management","viewPermission":"web.cp.v2.loan.administration.view","managePermission":"web.cp.v2.loan.administration.manage"}]},{"label":"Transparency","items":[{"id":"federal-reserve","label":"Federal Reserve Ledger"}]},{"label":"Administration","items":[{"id":"bank-dashboard","label":"Operations Dashboard","viewPermission":"web.cp.v2.bank.dashboard.view","managePermission":"web.cp.v2.bank.dashboard.manage"},{"id":"staff-bank","label":"Treasury Accounts","viewPermission":"web.cp.v2.staff.bank.view","managePermission":"web.cp.v2.staff.bank.manage"},{"id":"company-finance","label":"Business Accounts","viewPermission":"web.cp.v2.company.finance.view","managePermission":"web.cp.v2.company.finance.manage"},{"id":"bank-audit","label":"Audit Log","viewPermission":"web.cp.v2.bank.audit.view","managePermission":"web.cp.v2.bank.audit.manage"}]},{"label":"Currency & Heritage","items":[{"id":"dunemark-collection","label":"Dunemark Collection"}]}]},{"id":"market","label":"CHOAM Exchange","icon":"chart-no-axes-combined","groups":[{"label":"Commodity Exchange","items":[{"id":"commodity-listings","label":"Player Goods"},{"id":"commodity-mine","label":"My Listings"}]},{"label":"Markets","items":[{"id":"stock-overview","label":"Market Overview","viewPermission":"web.cp.v2.stock.overview.view","managePermission":"web.cp.v2.stock.overview.manage"},{"id":"stock-listings","label":"Listed Enterprises","viewPermission":"web.cp.v2.stock.listings.view","managePermission":"web.cp.v2.stock.listings.manage"},{"id":"stock-quotes","label":"Market Prices","viewPermission":"web.cp.v2.stock.quotes.view","managePermission":"web.cp.v2.stock.quotes.manage"},{"id":"stock-portfolio","label":"My Holdings","viewPermission":"web.cp.v2.stock.portfolio.view","managePermission":"web.cp.v2.stock.portfolio.manage"},{"id":"stock-orders","label":"Trading Floor","viewPermission":"web.cp.v2.stock.orders.view","managePermission":"web.cp.v2.stock.orders.manage"},{"id":"stock-trades","label":"Trade Ledger","viewPermission":"web.cp.v2.stock.trades.view","managePermission":"web.cp.v2.stock.trades.manage"},{"id":"stock-watchlist","label":"Watchlist","viewPermission":"web.cp.v2.stock.watchlist.view","managePermission":"web.cp.v2.stock.watchlist.manage"}]},{"label":"Enterprises","items":[{"id":"stock-ipo","label":"Listing Applications","viewPermission":"web.cp.v2.stock.ipo.view","managePermission":"web.cp.v2.stock.ipo.manage"},{"id":"stock-dividends","label":"Dividends","viewPermission":"web.cp.v2.stock.dividends.view","managePermission":"web.cp.v2.stock.dividends.manage"}]},{"label":"Oversight","items":[{"id":"stock-admin","label":"Market Authority","viewPermission":"web.cp.v2.stock.admin.view","managePermission":"web.cp.v2.stock.admin.manage"},{"id":"stock-surveillance","label":"Market Surveillance","viewPermission":"web.cp.v2.stock.surveillance.view","managePermission":"web.cp.v2.stock.surveillance.manage"}]}]},{"id":"quests","label":"Quests","icon":"scroll","groups":[{"label":"Your Journal","items":[{"id":"quests","label":"Contracts & Quests"}]}]},{"id":"kits","label":"Kits","icon":"package","groups":[{"label":"Equipment","items":[{"id":"kits-exchange","label":"Imperial Tailor"}]}]},{"id":"events","label":"Events","icon":"calendar","groups":[{"label":"Gatherings","items":[{"id":"events-calendar","label":"Event Calendar"}]}]}]};const art={clan:'nav-clan-v2.webp',quests:'nav-manual-v2.webp',kits:'items/office_water.png',events:'nav-home-v2.webp',politics:'seals/office-landsraad.png',realm:'nav-account-v2.webp',bureau:'nav-staff-v2.webp',forge:'nav-manual-v2.webp',post:'nav-support-v2.webp',bank:'imperial-postbank-v2.png',market:'nav-exchange-v2.webp'};const asset=n=>/^https:\/\//.test(n)?n:'https://www.dunerealms.com/assets/'+n;const portals=document.querySelector('#portals'),sidebar=document.querySelector('#sidebar'),content=document.querySelector('#content');let current='realm';let disposePage=()=>{};let postMenuTime=0,postMenuRequest=null,renderSequence=0; -// This entry is a classic deferred script; keep bookmark routing synchronous. -function politicsDestination(workspace,page){const groups={elections:['house-elections','imperial-elections','applications','electoral-roll'],offices:['office-register','politics-overview','landsraad','formal-council','imperial-command'],tools:['council-motd','imperial-water','imperial-spice']},known=Object.values(groups).flat();if(workspace!=='politics'&&!known.includes(workspace)&&!(['realm','game'].includes(workspace)&&known.includes(page)))return null;const selected=workspace==='politics'||['realm','game'].includes(workspace)?page:workspace,tab=Object.keys(groups).find(key=>groups[key].includes(selected))||(Object.hasOwn(groups,selected)?selected:'elections'),target=groups[tab].includes(selected)?selected:groups[tab][0];return 'https://www.dunerealms.com/government.html#'+tab+'/'+target;} -const requestedPolitics=politicsDestination(...location.hash.slice(1).split('?')[0].split('/'));if(requestedPolitics)location.replace(requestedPolitics); -const clanSurface=document.body.dataset.cpMode==='clan';const clanWorkspaces=new Set(['clan','quests','kits','events']); -function el(tag,cls,txt){const e=document.createElement(tag);if(cls)e.className=cls;if(txt!==undefined)e.textContent=txt;return e} -function image(name){const x=el('img');x.src=asset(name);x.alt='';x.loading='lazy';return x} -/* V1 artwork inventory: use existing /assets/ files; avoid generic repeated symbols. - New artwork guide: match V1 Minecraft-styled 3D objects, warm antique gold highlights, - deep forest-green shadows, transparent backgrounds, no text, 256px square WebP. - Missing concepts require dedicated art review before assets are published. */ -const CATEGORY_ARTWORK={ -'Identity':'nav-account-v2.webp','Communications':'nav-support-v2.webp', -'Adventures':'nav-clan-v2.webp','Commerce':'nav-exchange-v2.webp', -'Companies':'nav-clan-v2.webp','Citizens & Authority':'nav-staff-v2.webp', -'Commerce & Kits':'nav-exchange-v2.webp','Community':'nav-discord-v2.webp', -'Network':'nav-staff-v2.webp','Development':'nav-manual-v2.webp', -'Engineering':'nav-manual-v2.webp','Correspondence':'nav-support-v2.webp', -'Channels':'nav-discord-v2.webp','Accounts':'imperial-postbank-v2.png', -'Credit':'imperial-postbank-v2.png','Administration':'nav-staff-v2.webp', -'Markets':'nav-exchange-v2.webp','Enterprises':'nav-clan-v2.webp', -'Oversight':'nav-staff-v2.webp'}; -function categoryArtwork(label,workspace){return CATEGORY_ARTWORK[label]||art[workspace]} -// Missing category artwork is generated as original, lightweight SVG icons in the -// existing V1 green/gold palette. No external asset dependency, no text in icons. -// Art recipe: 48x48 transparent viewBox; dark forest-green backing; double antique- -// gold ring; warm amber highlights; beveled geometric symbols; avoid flat emoji. -// Reuse V1 assets for all other categories. Export future raster art at 256x256 WebP. -const NEW_CATEGORY_SYMBOLS={ -'Adventures':'sword','Commerce & Kits':'kit','Engineering':'gear', -'Credit':'coins','Markets':'chart','Oversight':'shield','Correspondence':'letter' -}; -function generatedCategoryArt(kind){ -const shapes={ -sword:'', -kit:'', -gear:'', -coins:'', -chart:'', -shield:'', -letter:''}; -const svg=''+(shapes[kind]||shapes.shield)+''; -return 'data:image/svg+xml;charset=utf-8,'+encodeURIComponent(svg) -} - -// Submenu artwork: prioritize the original V1 asset by subject; use the matching -// generated category crest only for subjects without a dedicated V1 illustration. -const V1_SUBMENU_ART=[ -[/bank|treasury|loan|credit|solari|finance|revenue|ledger|transfer|account statement/i,'imperial-postbank-v2.png'], -[/stock|exchange|market|trading|trade|merchant|shop|sales|commerce|ipo|dividend|portfolio/i,'nav-exchange-v2.webp'], -[/mail|inbox|dispatch|correspondence|message|ticket|support|petition|appeal/i,'nav-support-v2.webp'], -[/discord|channel|forum|community/i,'nav-discord-v2.webp'], -[/company|companies|clan|alliance|faction|guild/i,'nav-clan-v2.webp'], -[/server|staff|permission|rank|citizen|ban|moderation|admin|authority|election/i,'nav-staff-v2.webp'], -[/develop|forge|code|git|api|module|build|system|log|audit|engineering/i,'nav-manual-v2.webp'], -[/inventory|kit|item|reward|quest|adventure|crysknife/i,'items/office_water.png'], -[/identity|profile|personal|security|registration/i,'nav-account-v2.webp'] -]; -/* Distinct icon per menu item, including Identity. Existing V1 artwork stays for - top-level workspace cards and page banners; repeated submenu icons are replaced - with individually generated gold/green emblems, keyed by stable page ID. - Art generation: 48x48 SVG, forest-green backing, antique gold outlines, - warm sand highlights, transparent exterior, no words, deterministic ID seed. - A new icon is generated for every distinct submenu ID; no identical repeats. */ -function uniqueMenuIcon(key){ - const str=String(key);let hash=2166136261;for(let i=0;i>>0; - const motifs=[ - '', - '', - '', - '', - '', - '', - '', - '', - '' - ]; - const motif=motifs[hash%motifs.length];const rotation=(hash>>>8)%360; - const accents=['#d9a95a','#e5bf70','#c99847','#f1cf87']; - const dots=Array.from({length:3},(_,i)=>{const a=((hash>>>(i*6))%360)*Math.PI/180;const x=(24+17*Math.cos(a)).toFixed(1),y=(24+17*Math.sin(a)).toFixed(1);return ''}).join(''); - const svg=''+motif+''+dots+''; - return 'data:image/svg+xml;charset=utf-8,'+encodeURIComponent(svg) -} -function submenuArtwork(item,group,workspace){const img=el('img');img.src=item.artwork?'/assets/'+item.artwork:uniqueMenuIcon(workspace+'/'+group.label+'/'+item.id);img.alt='';img.width=48;img.height=48;return img} -function categoryTitleImage(label,workspace){const img=el('img');img.src=uniqueMenuIcon('category/'+workspace+'/'+label);img.alt='';img.width=48;img.height=48;return img} - - -// CP V2 Alpha module registry. Each existing V1-derived page renders a typed, -// accessible placeholder module rather than a generic blank screen. -/* Staff-first implementation: explicit staff page modules, no production writes. - Every staff route gets its own descriptive workflow and sample records. */ -/* Citizens Registry: first API-conform staff page. - V1 verified: GET /api/auth/session; GET /api/admin/register-user - (rank options); POST /api/admin/register-user with username,email, - ageBand,ranks. No unverified list-users endpoint is assumed. - Preview mode never sends requests or creates accounts. */ -function citizenRegistryPage(overview,actions){ - const section=el('section','citizen-module');section.setAttribute('aria-label','Citizen Registry'); - const intro=el('p','hint','V1-compatible account registration workflow. Live account listing is unavailable until its API contract is confirmed.'); - const form=el('form','citizen-form');form.autocomplete='off'; - function field(title,type,name){const label=el('label','citizen-field');label.append(el('span','',title));const input=el('input','module-search');input.type=type;input.name=name;input.required=true;label.append(input);form.append(label);return input} - const username=field('Minecraft / website username','text','username');username.pattern='[A-Za-z0-9_]{3,32}';username.maxLength=32; - const email=field('Email address or no_reply','text','email');email.maxLength=254; - const ageLabel=el('label','citizen-field');ageLabel.append(el('span','','Declared age group'));const age=el('select','module-search');age.name='ageBand';age.required=true;for(const [value,title] of [['','Choose age group'],['15plus','15 or older'],['under15','Under 15']]){const o=el('option','',title);o.value=value;age.append(o)}ageLabel.append(age);form.append(ageLabel); - const ranks=el('fieldset','citizen-ranks');ranks.append(el('legend','','Website ranks (verified API options only)'));const rankNote=el('p','hint','Ranks will load from GET /api/admin/register-user after staff authorization.');ranks.append(rankNote);form.append(ranks); - const notice=el('p','alpha-muted','Preview mode: account creation is disabled.');notice.setAttribute('role','status');form.append(notice); - const submit=el('button','gold-button','Create account');submit.type='submit';submit.disabled=true;form.append(submit); - form.addEventListener('submit',event=>event.preventDefault()); - section.append(intro,form); - const contract=el('details','citizen-contract');contract.append(el('summary','','Verified V1 API contract'));const pre=el('pre','','GET /api/auth/session\nGET /api/admin/register-user\nPOST /api/admin/register-user\nBody: { username, email, ageBand, ranks }\nPermission: server-enforced staff authorization\nAccount listing: endpoint not yet verified');contract.append(pre);section.append(contract); - const note=el('p','alpha-muted','Temporary credentials must be shown only after a successful authorized response, and must never be stored in this preview.');section.append(note); - overview.append(section); -} -/* Future-proof component boundary: placeholders are presentation-only. - API-backed implementations can replace each data-slot without changing layout, - navigation, permissions or the page registry. Never fabricate live records. */ -const STATIC_COMPONENTS={ - 'user-management':[{id:'citizen-directory',title:'Citizen Directory',kind:'data-grid',state:'api-pending',endpoint:'/api/admin/register-user?view=accounts&page=1',detail:'Account listing API exists on the staff development branch; staging integration and authorization tests remain pending.'},{id:'citizen-profile',title:'Citizen Profile',kind:'detail-panel',state:'contract-pending',detail:'Selected citizen identity, ranks and linked accounts will render here when the profile API contract is confirmed.'},{id:'citizen-audit',title:'Account Activity',kind:'timeline',state:'contract-pending',detail:'Audit events and account history require an authorized read endpoint.'}], - 'permissions':[{id:'effective-access',title:'Effective Permissions',kind:'matrix',state:'contract-pending',detail:'Role inheritance and permission resolution will be displayed after API validation.'}], - 'luckperms':[{id:'game-rank-tree',title:'Game Rank Hierarchy',kind:'tree',state:'contract-pending',detail:'Minecraft group inheritance will appear here after the LuckPerms API is validated.'}], - 'server-operations':[{id:'network-health',title:'Network Health',kind:'status-grid',state:'contract-pending',detail:'Proxy and backend health metrics require verified telemetry.'}], - 'kit-claims':[{id:'claim-delivery',title:'Claim Delivery',kind:'timeline',state:'contract-pending',detail:'Game delivery status and retry history require the kit claim API.'}], - 'ban-evidence':[{id:'evidence-viewer',title:'Evidence Viewer',kind:'media-panel',state:'contract-pending',detail:'Secure evidence access and audit logging must be validated before media is displayed.'}] -}; -function staticComponentsFor(workspace,page){const components=STATIC_COMPONENTS[page];if(components)return components;return [{id:page+'-details',title:'Details & Activity',kind:'detail-panel',state:'contract-pending',detail:'This component is reserved for the verified '+workspace+' API. Its layout and navigation are stable; no live data is implied.'}]} -function renderStaticComponents(workspace,page){ - const host=el('section','future-components');host.dataset.componentScope=workspace+'/'+page; - const heading=el('h3','future-components-heading','Planned Components');host.append(heading); - for(const component of staticComponentsFor(workspace,page)){ - const panel=el('article','future-component');panel.dataset.componentId=component.id;panel.dataset.componentKind=component.kind;panel.dataset.integrationState=component.state; - const header=el('div','future-component-header');header.append(el('strong','',component.title),el('span','future-component-tag',component.state==='api-pending'?'API PENDING':'DESIGN READY'));panel.append(header); - const content=el('div','future-component-body');content.dataset.slot=component.id; - const skeleton=el('div','future-skeleton');skeleton.setAttribute('aria-hidden','true'); - if(component.kind==='data-grid'||component.kind==='matrix'){for(let i=0;i<3;i++)skeleton.append(el('div','future-skeleton-line'))} - else if(component.kind==='timeline'||component.kind==='tree'){for(let i=0;i<3;i++)skeleton.append(el('div','future-skeleton-step'))} - else skeleton.append(el('div','future-skeleton-card')); - content.append(skeleton,el('p','alpha-muted',component.detail));panel.append(content);host.append(panel) - } - return host -} -const STAFF_MODULES={ -'user-management':['Citizen Registry','Manage linked accounts, staff status and access reviews.',['Username','Minecraft UUID','Website rank','Account status'],['Search citizen','Review account','Manage roles']], -'permissions':['Website Permissions','Review role grants, inherited permissions and audit decisions.',['Role','Permission node','Effect','Scope'],['Inspect role','Compare grants','Audit changes']], -'luckperms':['Minecraft Permissions','Review LuckPerms groups and effective Minecraft permissions.',['Group','Permission','World','Effect'],['Inspect group','Review inheritance','Sync preview']], -'manual-seals':['Awards & Seals','Review manual awards and issuance history.',['Recipient','Award','Issued by','State'],['Review award','Issue seal','View history']], -'company-management-v2':['Company Administration','Review registered companies, officers and compliance.',['Company','Owner','Members','Status'],['Inspect company','Review application','Audit']], -'staff-bank':['Imperial Revenue','Review staff-side treasury and revenue events.',['Reference','Account','Amount','State'],['Inspect ledger','Review transfer','Export audit']], -'server-kits':['Kit Directorate','Review all configured game kits and their publication status.',['Kit','Rarity','Published','Delivery'],['Inspect kit','Review definition','View claims']], -'kit-publishing':['Kit Publications','Stage kit catalog changes with approval gates.',['Kit','Revision','Approval','Publication'],['Review draft','Validate listing','Publish (locked)']], -'kit-claims':['Claim Registry','Track kit purchase, redemption and game delivery.',['Claim','Player','Kit','Delivery'],['Inspect claim','Retry (locked)','View receipt']], -'exchange-admin':['Exchange Authority','Review marketplace listings and enforcement queues.',['Listing','Seller','Price','Moderation'],['Inspect listing','Review report','Moderate (locked)']], -'shop-admin':['Merchant Directorate','Review merchant inventory, shop settings and sales.',['Merchant','Listing','Revenue','State'],['Inspect shop','Review inventory','View sales']], -'website-posts':['Imperial Newsroom','Review website news drafts and publication approvals.',['Article','Author','Revision','State'],['Review draft','Preview article','Publish (locked)']], -'staff-tickets':['Petition Office','Triage and assign citizen support requests.',['Ticket','Requester','Priority','Status'],['Inspect ticket','Assign (locked)','Reply (locked)']], -'bans':['Tribunal','Review ban records, appeals and moderation decisions.',['Case','Player','Reason','Appeal'],['Inspect case','Review appeal','Moderate (locked)']], -'ban-evidence':['Evidence Registry','Review moderation evidence and chain of custody.',['Evidence','Case','Submitted by','Integrity'],['Inspect evidence','Review history','Attach (locked)']], -'forum-admin':['Forum Wardens','Review forum moderation queues and reports.',['Thread','Reporter','Category','State'],['Inspect thread','Review report','Moderate (locked)']], -'quests-admin':['Campaign Directorate','Review quests, milestones and reward configurations.',['Quest','Owner','Reward','Status'],['Inspect quest','Review rewards','Publish (locked)']], -'support-management':['Petition Administration','Review service-level queues and support staffing.',['Queue','Owner','Open','Escalation'],['Inspect queue','Review assignment','Configure (locked)']], -'server-operations':['Network Command','Review network service status and proposed actions.',['Server','World','Health','Last check'],['Inspect server','View logs','Control (locked)']], -'git-admin':['Repository Authority','Review repository changes and release approvals.',['Repository','Branch','Review','Checks'],['Inspect change','View checks','Approve (locked)']], -'mail-admin':['Postmaster Administration','Review mail delivery, queues and access controls.',['Queue','Direction','Messages','State'],['Inspect queue','View delivery','Configure (locked)']] -}; -function staffModule(id){const spec=STAFF_MODULES[id];if(!spec)return null;const [entity,description,columns,actions]=spec;return {entity,description,create:'Create (locked)',metrics:[['Total','—'],['Awaiting review','—'],['Alerts','—']],columns,actions,instructions:'Staff preview only. Role checks, audit logging, API integration and staging acceptance are required before actions are enabled.',sample:(i)=>[entity+' '+(i+1),['Unassigned','Pending','Review'][i],'—','Preview']}} -const PAGE_MODULES={ -records:{entity:'Records',create:'New record',description:'Review records, ownership and pending changes.',metrics:[['Total','—'],['Pending','—'],['Updated','—']],columns:['Record','Owner','State','Updated'],actions:['View details','Edit record','Export'],instructions:'Record actions are locked until staging API validation.',sample:(i,n)=>[n+' '+(i+1),'Not linked',i?'Draft':'Preview','—']}, -identity:{entity:'Account details',create:'Edit profile',description:'Personal account, linked Minecraft identity and security details.',metrics:[['Linked player','—'],['Rank','—'],['Last login','—']],columns:['Field','Current value','Verification','Action'],actions:['Link account','Update profile','Security settings'],instructions:'Identity changes require verified login and permission checks.',sample:(i)=>[['Minecraft account','Not connected','Pending','View'],['Discord account','Not connected','Pending','Link'],['Account security','Not connected','Pending','Review']][i]}, -finance:{entity:'Transactions',create:'New transfer',description:'Solari balances, statements and transaction records.',metrics:[['Available','— Solari'],['Reserved','— Solari'],['Pending','—']],columns:['Reference','Type','Amount','Status'],actions:['Transfer Solari','View statement','Download receipt'],instructions:'All monetary actions are disabled in design mode.',sample:(i)=>['TX-PREVIEW-'+(i+1),['Deposit','Transfer','Withdrawal'][i],'— Solari','Sample']}, -market:{entity:'Listings',create:'Create listing',description:'Browse listings, trades, holdings and market activity.',metrics:[['Listings','—'],['Open orders','—'],['Volume','—']],columns:['Listing','Market','Price','Status'],actions:['Browse market','Place order','Trade history'],instructions:'Market orders require live quote and idempotency integration.',sample:(i)=>['Market item '+(i+1),'CHOAM','— Solari','Preview']}, -kits:{entity:'Kits',create:'Publish kit',description:'Browse kit definitions, availability, publication and claim paths.',metrics:[['Published','—'],['Unpublished','—'],['Claims','—']],columns:['Kit','Rarity','Availability','Claim state'],actions:['Browse kits','Manage publication','View claims'],instructions:'Publishing and game delivery remain gated pending native API verification.',sample:(i)=>['Kit '+(i+1),['Common','Rare','Legendary'][i],'Unknown','Not connected']}, -messaging:{entity:'Messages',create:'Compose message',description:'Inbox, outgoing correspondence, delivery and support requests.',metrics:[['Unread','—'],['Open','—'],['Sent','—']],columns:['Subject','From / To','Received','Status'],actions:['Compose','Open inbox','Archive'],instructions:'Messaging requires authenticated inbox and server-side delivery.',sample:(i)=>['Sample message '+(i+1),'Not connected','—','Preview']}, -operations:{entity:'Services',create:'New operation',description:'Server health, service controls and operational audit.',metrics:[['Healthy','—'],['Unknown','—'],['Alerts','—']],columns:['Service','Environment','Health','Last check'],actions:['Inspect service','View logs','Request action'],instructions:'Operational controls must be restricted to authorized staff.',sample:(i)=>[['Proxy','Network','Unknown','—'],['Minecraft backend','Game','Unknown','—'],['Website API','Web','Unknown','—']][i]}, -developer:{entity:'Tasks',create:'New work order',description:'Developer queue, review workflow, modules and build diagnostics.',metrics:[['Open tasks','—'],['Reviews','—'],['Builds','—']],columns:['Work item','Module','Stage','Owner'],actions:['Create work order','Review changes','View build logs'],instructions:'Development actions are design-only until authenticated workflows are connected.',sample:(i)=>['DEV-'+(i+1),'Module '+(i+1),'Preview','Unassigned']} -}; -function pageType(id,label,workspace){const s=(id+' '+label).toLowerCase();if(/kit|claim|tailor|crysknife/.test(s))return 'kits';if(/bank|treasury|loan|credit|solari|transaction|finance|ledger|revenue/.test(s))return 'finance';if(/stock|market|trade|exchange|merchant|shop|sale|listing|dividend|portfolio/.test(s))return 'market';if(/mail|inbox|dispatch|correspondence|message|ticket|support|petition|appeal/.test(s))return 'messaging';if(/server|network|hosting|monitor|operation|world|backup|status|ban/.test(s))return 'operations';if(workspace==='forge'||/developer|build|forge|git|module|api|blueprint|archive/.test(s))return 'developer';if(/identity|profile|security|discord.link|personal.record/.test(s))return 'identity';return 'records'} -function legacyRoute(wid,pid){if(wid==='realm'&&pid==='clans')return {wid:'clan',pid:'clan-overview'};if(wid==='realm'&&pid==='quests')return {wid:'quests',pid:'quests'};if(wid==='realm'&&pid==='kits-exchange')return {wid:'kits',pid:'kits-exchange'};if(wid==='bank'&&pid==='bank-information')return {wid:'bank',pid:'bank-overview'};if(wid==='bank'&&pid==='bank-history')return {wid:'bank',pid:'bank-statements'};if(wid==='realm'&&pid==='personal-bank')return {wid:'bank',pid:'personal-bank'};if(wid==='realm'&&pid==='transactions')return {wid:'bank',pid:'bank-statements'};if(['realm','post'].includes(wid)&&pid==='shared-inbox')return {wid:'post',pid:'mail-inbox'};if(menu.workspaces.some(w=>w.id===wid))return {wid,pid};const aliases={'clans':['clan','clan-overview'],'clan-portal':['clan','clan-overview'],'clan-shops':['clan','clan-shop'],'clan-kits':['clan','clan-tailor'],'clan-bank':['clan','clan-bank'],'clan-settings':['clan','clan-settings'],'exchange':['market','commodity-listings'],'rewards-redeem':['realm','rewards-codes','redeem'],'redeem-code':['realm','rewards-codes','redeem'],'discovery-rewards':['realm','rewards-codes','redeem'],'kit-checkout':['kits','kits-exchange','kit-checkout'],'clan-inbox':['post','clan-inbox'],'faction-inbox':['post','faction-inbox'],'imperial-inbox':['post','imperial-inbox'],'staff-inbox':['post','staff-inbox'],'internal-mail':['post','mail-inbox'],'shared-inbox':['post','mail-inbox'],'personal-bank':['bank','personal-bank'],'transactions':['bank','bank-history']};if(aliases[wid]){const [workspace,page,initialTab]=aliases[wid];return {wid:workspace,pid:page,initialTab};}const workspace=menu.workspaces.find(w=>w.groups.some(g=>g.items.some(item=>item.id===wid)));return workspace?{wid:workspace.id,pid:wid}:{wid,pid};} -let cpReady=false,centralOrganisation=false; -function go(wid,pid,context={}){if(wid==='companies'||pid==='companies'||['realm','market'].includes(wid)&&String(pid||'').startsWith('company-')){location.assign('https://corp.dunerealms.com/');return;}const politicalTarget=politicsDestination(wid,pid);if(politicalTarget){location.assign(politicalTarget);return;}if(!cpReady||!menu.workspaces.length)return;const navigation=++renderSequence;const route=legacyRoute(wid,pid);wid=route.wid;pid=route.pid;if(!clanSurface&&clanWorkspaces.has(wid)){location.assign('https://clans.dunerealms.com/#'+wid+'/'+(pid||''));return;} -if(wid==='post'&&!context.mailDirectoryReady&&Date.now()-postMenuTime>30000){disposePage();disposePage=()=>{};current='post';sidebar.replaceChildren(el('p','','Loading your inboxes…'));content.replaceChildren(el('p','cp-v2-news-status','Loading your authorised inboxes…'));document.querySelector('#sidebar-right').replaceChildren();if(!postMenuRequest)postMenuRequest=import('/v2/cp-v2-post-menu.mjs').then(({loadMailboxMenu})=>loadMailboxMenu()).finally(()=>{postMenuRequest=null;});postMenuRequest.then(inboxes=>{if(navigation!==renderSequence)return;const post=menu.workspaces.find(w=>w.id==='post'),channels=post.groups.find(g=>g.label==='Channels')?.items||[];post.groups=[{label:'Inboxes',items:inboxes},{label:'Channels',items:channels.filter(item=>item.id!=='shared-inbox')}];postMenuTime=Date.now();go('post',pid,{...context,mailDirectoryReady:true});}).catch(error=>{if(navigation!==renderSequence)return;const retry=el('button','gold-button','Retry inbox directory');retry.onclick=()=>go('post',pid);content.replaceChildren(el('p','cp-v2-news-status',error.message),retry);});return;} -const initialTab=route.initialTab||context.initialTab;const requestedDesignTab=pid; if(['realm','market'].includes(wid)&&['company-directory','company-registration','company-profile','company-members','company-finance','company-permissions','company-applications'].includes(pid))pid='companies';if(wid==='bureau'&&pid==='dev-approvals'){wid='forge';pid='dev-approvals';}disposePage();disposePage=()=>{};if(wid==='bureau'&&pid==='luckperms')pid='permissions';const w=menu.workspaces.find(x=>x.id===wid)||menu.workspaces[0];current=w.id;document.body.dataset.workspace=w.id;const items=w.groups.flatMap(g=>g.items);const item=items.find(x=>x.id===pid)||items[0];if(clanSurface&&parent!==window)parent.postMessage({type:'dune-clan-route',workspace:w.id,page:item.id},'https://clans.dunerealms.com');for(const b of portals.children)b.setAttribute('aria-selected',String(b.dataset.id===w.id));sidebar.replaceChildren();const sidebarRight=document.querySelector('#sidebar-right');sidebarRight.replaceChildren();const banner=el('div','side-hero',w.id==='forge'?'DEV':w.label.toUpperCase());sidebar.append(banner);sidebarRight.append(el('div','side-hero',w.id==='forge'?'DUNEGIT':w.label.toUpperCase()+' · DIRECTORY'));if(w.id==='realm'){const mail=el('button','mail-shortcut','✉ You’ve Got Mail');mail.onclick=()=>go('post','mail-inbox');sidebar.append(mail)} -const groups=w.groups.map(g=>({...g,items:g.items.filter(x=>!x.dashboardOnly)})).filter(g=>g.items.length);let split=groups.length,best=Infinity;for(let i=1;in+g.items.length+2,0),b=groups.slice(i).reduce((n,g)=>n+g.items.length+2,0),delta=Math.abs(a-b);if(deltag.label==='DuneGit');if(w.id==='post')split=1;for(const [gi,g] of groups.entries()){const target=gix.id===item.id);const heading=el('summary','category-heading');heading.append(categoryTitleImage(g.label,w.id),el('span','category-name',g.label),el('span','category-count',String(g.items.length)));block.append(heading);const links=el('div','category-links');for(const x of g.items){const b=el('button','navitem');b.type='button';b.append(submenuArtwork(x,g,w.id),el('span','',x.label));b.setAttribute('aria-current',x.id===item.id?'page':'false');b.onclick=()=>go(w.id,x.id);links.append(b)}block.append(links);target.append(block)}content.replaceChildren();const hero=el('div','hero');hero.append(image(art[w.id]));const title=el('div');title.append(el('h1','',item.label),el('p','',w.id==='clan'?'Your household, its banner and the people who carry it.':'Realm management, account tools and personal operations.'));hero.append(title);content.append(hero); -const cards=el('div','cards');content.append(cards); -function card(name,icon,full=false){const c=el('article','card'+(full?' full':''));const h=el('h2');h.append(image(icon),document.createTextNode(name));c.append(h);cards.append(c);return c} -function button(name,fn){const b=el('button','gold-button',name);b.onclick=fn;return b} -function tiles(c,values){const wrap=el('div','tiles');for(const [label,icon,ws,page] of values){const b=el('button','tile');b.append(image(icon),el('span','',label));b.onclick=()=>go(ws,page);wrap.append(b)}c.append(wrap)} -if(['clan','quests','kits','events'].includes(w.id)){const overview=card(item.label,art[w.id],true),host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-play-workspaces.mjs').then(({mountPlayWorkspace})=>{if(host.isConnected)disposePage=mountPlayWorkspace(host,w.id,item.id,{initialTab,listingId:context.listingId});}).catch(error=>{if(host.isConnected)host.textContent='Workspace unavailable: '+error.message;});history.replaceState(null,'','#'+w.id+'/'+item.id);return;} -if(w.id==='realm'&&item.id==='crysknife'){const overview=card(item.label,'seals/order-crysknife-v1.png',true),host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-crysknife.mjs').then(({mountCrysknife})=>{if(host.isConnected)disposePage=mountCrysknife(host)}).catch(error=>{if(host.isConnected)host.textContent='Order register unavailable: '+error.message});history.replaceState(null,'','#realm/crysknife');return;} -if(w.id==='realm'&&['item-exchange','item-listings','item-post','game','site-profile','security','discord-link','planetary-inventory','quests','tickets','clans','shared-inbox','kits-exchange','rewards-codes','personal-bank','transactions','shop-settings','exchange-settings'].includes(item.id)){const overview=card(item.label,art[w.id],true),host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-user-pages.mjs').then(({mountUserPage})=>{if(host.isConnected)disposePage=mountUserPage(host,item.id,{initialTab,listingId:context.listingId})}).catch(error=>{if(host.isConnected)host.textContent='User workspace unavailable: '+error.message});history.replaceState(null,'','#'+w.id+'/'+item.id);return;} -if(w.id==='realm'&&item.id==='game'){const mail=card('You’ve Got Mail','nav-support-v2.webp');mail.append(el('p','mail-text','Imperial Post inbox · no live messages in preview'),button('Open Mail »',()=>go('post','mail-inbox')));const status=card('Realm Status','nav-account-v2.webp');const rows=el('div','status');for(const [k,v] of [['Realm','Preview'],['Rank','Not connected'],['Companies','—'],['Kits','—'],['Last Login','—']])rows.append(el('i','','●'),el('span','',k+':'),el('span','',v));status.append(rows);tiles(card('Quick Actions','nav-clan-v2.webp'),[['Manage Kits','items/office_water.png','realm','kits-exchange'],['Banking','imperial-postbank-v2.png','bank','bank-overview'],['Trading','nav-exchange-v2.webp','market','stock-overview']]);tiles(card('Developer Tools','nav-manual-v2.webp'),[['API Console','nav-manual-v2.webp','forge','dev-api'],['Module Manager','nav-staff-v2.webp','forge','dev-builds'],['System Logs','nav-manual-v2.webp','forge','dev-audit'],['Dev Utilities','nav-account-v2.webp','forge','dev-panel']]);const news=card('System Announcements','nav-manual-v2.webp',true);for(const [badge,text] of [['V2','Alphastyle independent control panel preview'],['DEV','Company, banking and stockmarket workspaces'],['ART','Existing DuneRealms navigation artwork']]){const row=el('div','dispatch');row.append(el('b','',badge),el('span','',text),el('small','','PREVIEW'));news.append(row)}}else{ -const sectionType=pageType(item.id,item.label,w.id); -const descriptor=(w.id==='bureau'?staffModule(item.id):null)||PAGE_MODULES[sectionType]; -const overview=card(item.label,art[w.id]); -if(w.id==='market'&&['commodity-listings','commodity-mine'].includes(item.id)){overview.classList.add('citizen-page-full');const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-choam-pages.mjs').then(({mountCommodityExchange})=>{if(host.isConnected)disposePage=mountCommodityExchange(host,item.id)}).catch(error=>{if(host.isConnected)host.textContent='Commodity Exchange unavailable: '+error.message});history.replaceState(null,'','#market/'+item.id);return;} -if(w.id==='politics'){overview.classList.add('citizen-page-full');const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-politics-pages.mjs').then(({mountPoliticsPage})=>{if(host.isConnected)disposePage=mountPoliticsPage(host,item.id)}).catch(error=>{if(host.isConnected)host.textContent='Political workspace unavailable: '+error.message});history.replaceState(null,'','#politics/'+item.id);return;} -if(w.id==='bureau'&&['codex-management','items','server-kits','kit-publishing','kit-claims','exchange-admin'].includes(item.id)){overview.classList.add('citizen-page-full');const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-codex-management.mjs').then(({mountCodexManagement})=>{if(host.isConnected)disposePage=mountCodexManagement(host,{initial:({'items':'items','server-kits':'kits','kit-publishing':'publication','kit-claims':'delivery','exchange-admin':'listings'})[item.id]||'keys'})}).catch(error=>{if(host.isConnected)host.textContent='Codex Management unavailable: '+error.message});history.replaceState(null,'','#bureau/'+item.id);return;} -if(w.id==='bureau'&&item.id==='account-authorisations'){overview.classList.add('citizen-page-full');const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-authorisations.mjs').then(({mountAuthorisations})=>{if(host.isConnected)disposePage=mountAuthorisations(host,{staff:true})}).catch(error=>{if(host.isConnected)host.textContent='Authorisations unavailable: '+error.message});history.replaceState(null,'','#bureau/account-authorisations');return;} -if(w.id==='bureau'&&item.id==='tax-treasury'){overview.classList.add('citizen-page-full');const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-tax-treasury.mjs').then(({mountTaxTreasury})=>{if(host.isConnected)disposePage=mountTaxTreasury(host)}).catch(error=>{if(host.isConnected)host.textContent='Tax treasury unavailable: '+error.message});history.replaceState(null,'','#bureau/tax-treasury');return;} -if(w.id==='bureau'&&item.id==='menu-badges'){overview.classList.add('citizen-page-full');const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-menu-badges.mjs').then(({mountMenuBadges})=>{if(host.isConnected)disposePage=mountMenuBadges(host)}).catch(error=>{if(host.isConnected)host.textContent=error.message});history.replaceState(null,'','#bureau/menu-badges');return;} -if(w.id==='bank'){overview.classList.add('citizen-page-full');const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-bank-pages.mjs').then(({mountBankPage})=>{if(host.isConnected)disposePage=mountBankPage(host,item.id,{accountId:context.accountId})}).catch(error=>{if(host.isConnected)host.textContent='Postbank unavailable: '+error.message});history.replaceState(null,'','#bank/'+item.id+(item.id==='bank-statements'&&/^\d{1,12}$/.test(context.accountId||'')?'/'+context.accountId:''));return;} -if(w.id==='post'){overview.classList.add('citizen-page-full');const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-post-pages.mjs').then(({mountPostPage})=>{if(host.isConnected)disposePage=mountPostPage(host,item.id,{initialTab,title:item.label})}).catch(error=>{if(host.isConnected)host.textContent='Imperial Post unavailable: '+error.message});history.replaceState(null,'','#post/'+item.id);return;} -if(w.id==='forge'){overview.classList.add('citizen-page-full');const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-forge-pages.mjs').then(({mountForgePage})=>{if(host.isConnected)disposePage=mountForgePage(host,item.id)}).catch(error=>{if(host.isConnected)host.textContent='DuneForge unavailable: '+error.message});history.replaceState(null,'','#'+w.id+'/'+item.id);return;} -if(["realm/companies","market/companies","realm/sales-history","post/mail-inbox","post/mail-compose","post/mail-sent","post/mail-drafts","post/mail-archive","post/mail-trash","post/mail-contacts","post/mail-settings","post/mail-admin","bank/bank-overview","bank/bank-transfers","bank/bank-statements","bank/bank-history","bank/bank-beneficiaries","bank/bank-loans","bank/company-finance","bank/bank-audit","market/stock-overview","market/stock-listings","market/stock-quotes","market/stock-portfolio","market/stock-orders","market/stock-trades","market/stock-watchlist","market/stock-ipo","market/stock-dividends","market/stock-admin","market/stock-surveillance","forge/dev-builds","forge/dev-releases","forge/dev-api","forge/dev-audit","bureau/kit-claims"].includes(w.id+'/'+item.id)){overview.classList.add('citizen-page-full');const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-design-pages.mjs').then(({mountDesignPage})=>{if(host.isConnected)disposePage=mountDesignPage(host,w.id+'/'+item.id,{initialTab:requestedDesignTab})}).catch(error=>{if(host.isConnected)host.textContent='Design workbench unavailable: '+error.message});history.replaceState(null,'','#'+w.id+'/'+(requestedDesignTab||item.id));return;} - -if((w.id==='bureau'&&['user-management','permissions','manual-seals','seal-generator','company-management','company-management-v2','company-audit','staff-bank','server-kits','kit-publishing','kit-claims','exchange-admin','shop-admin','items','website-posts','staff-tickets','bans','ban-evidence','forum-admin','quests-admin','community-goals','support-management','server-operations','hosting-control','dev-approvals'].includes(item.id))||(w.id==='market'&&['stock-overview','stock-listings','stock-quotes','stock-portfolio','stock-orders','stock-trades','stock-watchlist','companies','company-directory','company-profile','stock-ipo','stock-dividends','stock-admin','stock-surveillance'].includes(item.id))||(w.id==='bank'&&['bank-information','bank-overview','personal-bank','bank-transfers','bank-statements','bank-history','bank-beneficiaries','loan-centre','bank-loans','loan-administration','bank-dashboard','staff-bank','company-finance','bank-audit'].includes(item.id)))overview.classList.add('citizen-page-full'); -overview.append(el('p','hint',descriptor.description)); -if(w.id==='bureau'&&item.id==='user-management'){ - const host=el('div','citizen-live-host');overview.append(host); - const state=el('p','alpha-muted','Loading the authorized Citizens Registry…');host.append(state); - const migrationPreview=centralOrganisation||new URL(location.href).searchParams.get('migration')==='1'; - import(migrationPreview?'/v2/citizen-directory.mjs':'/v2/citizens-registry.mjs?v=cpalpha-20261112c').then(module=>{ - if(host.isConnected)disposePage=migrationPreview?module.mountCitizenDirectory(host):module.mountCitizensRegistry(host) - }).catch(error=>{if(host.isConnected)state.textContent='Citizens Registry could not load: '+error.message}); - history.replaceState(null,'','#'+w.id+'/'+item.id); - return; -} -if(w.id==='bureau'&&item.id==='permissions'&&(centralOrganisation||new URL(location.href).searchParams.get('migration')==='1')){const host=el('div','citizen-live-host');overview.append(host);import('/v2/organisation-permissions.mjs').then(({mountOrganisationPermissions})=>{if(host.isConnected)disposePage=mountOrganisationPermissions(host)}).catch(error=>{if(host.isConnected)host.textContent=error.message});history.replaceState(null,'','#bureau/permissions');return;} -if(w.id==='bureau'&&item.id==='permissions'){const host=el('div','citizen-live-host');overview.append(host);host.append(el('p','alpha-muted','Loading Imperial Permissions…'));import('/v2/imperial-permissions.mjs?v=rankdelete-20261112a').then(({mountImperialPermissions})=>{if(host.isConnected)mountImperialPermissions(host)}).catch(error=>{if(host.isConnected)host.textContent='Imperial Permissions unavailable: '+error.message});history.replaceState(null,'','#'+w.id+'/'+item.id);return;} -if(w.id==='bureau'&&item.id==='manual-seals'){const host=el('div','citizen-live-host');overview.append(host);host.append(el('p','alpha-muted','Loading Honours & Seals…'));import('/v2/honours-seals.mjs?v=sealupload-20261112a').then(({mountHonoursSeals})=>{if(host.isConnected)mountHonoursSeals(host)}).catch(error=>{if(host.isConnected)host.textContent='Honours & Seals unavailable: '+error.message});history.replaceState(null,'','#'+w.id+'/'+item.id);return;} -if(w.id==='bureau'&&['company-management','company-management-v2','company-audit','staff-bank','server-kits','kit-publishing','kit-claims','exchange-admin','shop-admin','items','website-posts','staff-tickets','bans','ban-evidence','forum-admin','quests-admin','community-goals','support-management','server-operations','hosting-control','dev-approvals'].includes(item.id)){const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-bureau-pages.mjs?v=bureau-registers-20261112c').then(({mountBureauPlaceholder})=>{if(host.isConnected)disposePage=mountBureauPlaceholder(host,item.id)}).catch(error=>{if(host.isConnected)host.textContent='Bureau page unavailable: '+error.message});history.replaceState(null,'','#'+w.id+'/'+item.id);return;} -if(w.id==='bank'&&['bank-information','bank-overview','personal-bank','bank-transfers','bank-statements','bank-history','bank-beneficiaries','loan-centre','bank-loans','loan-administration','bank-dashboard','staff-bank','company-finance','bank-audit'].includes(item.id)){const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-planned-pages.mjs?v=bank-admin-20261112a').then(({mountBankPlaceholder})=>{if(host.isConnected)mountBankPlaceholder(host,item.id)}).catch(error=>{if(host.isConnected)host.textContent='Postbank placeholder unavailable: '+error.message});history.replaceState(null,'','#'+w.id+'/'+item.id);return;} -if(w.id==='market'&&['stock-overview','stock-listings','stock-quotes','stock-portfolio','stock-orders','stock-trades','stock-watchlist','companies','company-directory','company-profile','stock-ipo','stock-dividends','stock-admin','stock-surveillance'].includes(item.id)){const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-choam-pages.mjs?v=choam-all-20261112a').then(({mountCHOAMPlaceholder})=>{if(host.isConnected)mountCHOAMPlaceholder(host,item.id)}).catch(error=>{if(host.isConnected)host.textContent='CHOAM page unavailable: '+error.message});history.replaceState(null,'','#'+w.id+'/'+item.id);return;} -if(w.id==='bureau'&&item.id==='seal-generator'){const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-planned-pages.mjs?v=bank-admin-20261112a').then(({mountSealGeneratorPlaceholder})=>{if(host.isConnected)mountSealGeneratorPlaceholder(host)}).catch(error=>{if(host.isConnected)host.textContent='Seal Generator placeholder unavailable: '+error.message});history.replaceState(null,'','#'+w.id+'/'+item.id);return;} -overview.append(renderStaticComponents(w.id,item.id)); - -const ribbon=el('div','alpha-ribbon');ribbon.append(el('span','alpha-pill','ALPHA · UI PREVIEW'),el('span','alpha-muted','Planned service · No live data or writes'));overview.append(ribbon); -const toolbar=el('div','module-toolbar');const search=el('input','module-search');search.type='search';search.placeholder='Filter '+descriptor.entity.toLowerCase()+'…';search.setAttribute('aria-label','Filter placeholder records');toolbar.append(search); -const add=button('+ '+descriptor.create,()=>{});add.disabled=true;add.title='Available after API and permission integration';toolbar.append(add);overview.append(toolbar); -const statgrid=el('div','alpha-stats');for(const [name,value] of descriptor.metrics){const tile=el('div','alpha-stat');tile.append(el('small','',name),el('strong','',value));statgrid.append(tile)}overview.append(statgrid); -const tableWrap=el('div','alpha-table-wrap');const t=el('table','placeholder-table alpha-table');const thead=el('thead');const head=el('tr');for(const name of descriptor.columns)head.append(el('th','',name));thead.append(head);t.append(thead);const tbody=el('tbody');for(let i=0;i<3;i++){const tr=el('tr');const cells=descriptor.sample(i,item.label);for(const val of cells)tr.append(el('td','',val));tbody.append(tr)}t.append(tbody);tableWrap.append(t);overview.append(tableWrap); -const viewTools=el('div','alpha-view-tools'); -const viewTitle=el('span','alpha-muted','Preview state:'); -const viewOptions=[['Sample','sample'],['Empty','empty'],['Loading','loading'],['Error','error']]; -viewTools.append(viewTitle); -const viewButtons=[]; -function setPreviewState(state){for(const [button,value] of viewButtons)button.setAttribute('aria-pressed',String(value===state));tableWrap.hidden=state!=='sample';const msg=overview.querySelector('.alpha-state-message');if(msg)msg.remove();if(state!=='sample'){const message=el('div','alpha-state-message');message.setAttribute('role','status');const stateText={empty:'No records yet. Connect the staging API to populate this workspace.',loading:'Loading preview — simulated state; no network request is made.',error:'Preview error state — retry will become available after API integration.'};message.textContent=stateText[state];viewTools.after(message)}} -for(const [label,value] of viewOptions){const b=el('button','alpha-view-button',label);b.type='button';b.setAttribute('aria-pressed',String(value==='sample'));b.onclick=()=>setPreviewState(value);viewButtons.push([b,value]);viewTools.append(b)} -overview.append(viewTools); -const empty=el('p','alpha-muted alpha-empty','Sample records are illustrative only.');overview.append(empty); -search.addEventListener('input',()=>{const q=search.value.toLowerCase();let visible=0;for(const tr of tbody.children){const match=tr.textContent.toLowerCase().includes(q);tr.hidden=!match;if(match)visible++}empty.textContent=visible?'Sample records are illustrative only.':'No matching sample records.'}); -const actions=card('Workspace Tools',art[w.id]);actions.append(el('p','hint',descriptor.instructions));const actionList=el('div','alpha-actions');for(const label of descriptor.actions){const b=button(label,()=>{});b.disabled=true;b.title='Preview only; backend integration pending';actionList.append(b)}actions.append(actionList); -const status=el('div','alpha-readiness');for(const [name,value] of [['UI','READY FOR REVIEW'],['API','NOT CONNECTED'],['AUTHORIZATION','PENDING'],['WRITE OPERATIONS','DISABLED']]){const row=el('div');row.append(el('span','',name),el('strong','',value));status.append(row)}actions.append(status); -const note=card('Integration Checklist','nav-manual-v2.webp',true);const checklist=el('ul','alpha-checklist');for(const step of ['Confirm V1 feature parity and page ownership','Map read endpoints and permission checks','Connect staging API with mock-data fallback','Test empty, loading, error and mobile states','Review and approve before enabling writes'])checklist.append(el('li','',step));note.append(checklist);note.append(el('p','hint','Permission nodes: '+item.viewPermission+' · '+item.managePermission)); -} -history.replaceState(null,'','#'+w.id+'/'+item.id)} -document.querySelector('#mobile-menu').onclick=()=>{const opened=sidebar.classList.toggle('open');document.querySelector('#sidebar-right').classList.toggle('open',sidebar.classList.contains('open'));document.querySelector('#mobile-menu').setAttribute('aria-expanded',String(opened))};sidebar.addEventListener('click',e=>{if(e.target.closest('.navitem')&&matchMedia('(max-width:720px)').matches)(sidebar.classList.remove('open'),document.querySelector('#sidebar-right').classList.remove('open'))});window.addEventListener('hashchange',()=>{const [w,p,accountId]=location.hash.slice(1).split('?')[0].split('/');go(w,p,{accountId,listingId:new URL(location.href).searchParams.get('kit-listing')})});Promise.all([import('/v2/cp-v2-auth.mjs'),import('/v2/cp-v2-access.mjs')]).then(([{startCPAuthentication},{accessibleCPMenu,workspacesForSurface}])=>startCPAuthentication(user=>{art.clan='https://cp.dunerealms.com/api/clan-emblems/member/'+encodeURIComponent(user.username);centralOrganisation=user.managementModel==='organisation-v2';menu.workspaces=workspacesForSurface(accessibleCPMenu(menu,user).workspaces,clanSurface);cpReady=true;portals.replaceChildren();for(const w of menu.workspaces){const b=el('button','portal');b.dataset.id=w.id;b.append(image(art[w.id]),el('span','',w.label));b.onclick=()=>go(w.id);portals.append(b)}if(!menu.workspaces.length){content.replaceChildren(el('p','cp-v2-news-status','No workspaces are available for this account.'));return;}const [initial,page,accountId]=location.hash.slice(1).split('?')[0].split('/');go(initial||(clanSurface?'clan':'realm'),page,{accountId,listingId:new URL(location.href).searchParams.get('kit-listing')});})).catch(error=>{content.textContent='Account access is temporarily unavailable: '+error.message}); - -// Finish the shared page pattern for retained adapters as they mount. -const headingObserver=new MutationObserver(()=>{const hero=content.querySelector(':scope > .hero');if(!hero)return;for(const host of content.querySelectorAll('.citizen-live-host')){for(const heading of host.querySelectorAll(':scope > .cp-v2-template-page > .cp-v2-template-heading')){const title=heading.querySelector('h3')?.textContent,copy=heading.querySelector('p')?.textContent,icon=heading.querySelector('img');if(title)hero.querySelector('h1').textContent=title;if(copy)hero.querySelector('p').textContent=copy;if(icon)hero.querySelector('img').src=icon.src;heading.remove();}for(const duplicate of host.closest('article.card')?.querySelectorAll(':scope > h2, :scope > .hint')||[])duplicate.remove();}});headingObserver.observe(content,{childList:true,subtree:true}); +const menu={"version":2,"mode":"static-design-preview","source":"independent-v2-registry","workspaces":[{"id":"realm","label":"My Realm","icon":"user-round","groups":[{"label":"Identity","items":[{"id":"game","label":"Citizen Passport","viewPermission":"web.cp.v2.game.view","managePermission":"web.cp.v2.game.manage"},{"id":"site-profile","label":"Personal Records","viewPermission":"web.cp.v2.site.profile.view","managePermission":"web.cp.v2.site.profile.manage"},{"id":"security","label":"Account Security","viewPermission":"web.cp.v2.security.view","managePermission":"web.cp.v2.security.manage"},{"id":"discord-link","label":"Discord Link","viewPermission":"web.cp.v2.discord.link.view","managePermission":"web.cp.v2.discord.link.manage"},{"id":"planetary-inventory","label":"My Inventory","viewPermission":"web.cp.v2.planetary.inventory.view","managePermission":"web.cp.v2.planetary.inventory.manage"}]},{"label":"Communications","items":[{"id":"shared-inbox","label":"My Correspondence","viewPermission":"web.cp.v2.shared.inbox.view","managePermission":"web.cp.v2.shared.inbox.manage"},{"id":"tickets","label":"Petition Hall","viewPermission":"web.cp.v2.tickets.view","managePermission":"web.cp.v2.tickets.manage"},{"id":"rewards-codes","label":"Rewards & Seals","viewPermission":"web.cp.v2.rewards.codes.view","managePermission":"web.cp.v2.rewards.codes.manage"}]},{"label":"Adventures","items":[{"id":"crysknife","label":"Order of the Crysknife","viewPermission":"web.cp.v2.crysknife.view","managePermission":"web.cp.v2.crysknife.manage"}]},{"label":"Commerce","items":[{"id":"personal-bank","label":"My Treasury","viewPermission":"web.cp.v2.personal.bank.view","managePermission":"web.cp.v2.personal.bank.manage"},{"id":"transactions","label":"Transaction Ledger","viewPermission":"web.cp.v2.transactions.view","managePermission":"web.cp.v2.transactions.manage"},{"id":"sales-history","label":"Sales History","viewPermission":"web.cp.v2.sales.history.view","managePermission":"web.cp.v2.sales.history.manage"},{"id":"exchange-settings","label":"Exchange Preferences","viewPermission":"web.cp.v2.exchange.settings.view","managePermission":"web.cp.v2.exchange.settings.manage"},{"id":"shop-settings","label":"Merchant Preferences","viewPermission":"web.cp.v2.shop.settings.view","managePermission":"web.cp.v2.shop.settings.manage"},{"id":"item-exchange","label":"Item Exchange","viewPermission":"web.menu.inventory"},{"id":"item-listings","label":"My Item Listings","viewPermission":"web.menu.inventory"},{"id":"item-post","label":"Post an Item","viewPermission":"web.menu.inventory"}]}]},{"id":"clan","label":"My Clan","icon":"flag","groups":[{"label":"Your Household","items":[{"id":"clan-overview","label":"Household Dashboard"},{"id":"clan-roster","label":"Clan Roster","dashboardOnly":true},{"id":"clan-requests","label":"Join Requests","dashboardOnly":true},{"id":"clan-settings","label":"Clan Settings"}]},{"label":"Household Affairs","items":[{"id":"clan-boards","label":"Clan Boards"},{"id":"clan-mail","label":"Clan Correspondence","dashboardOnly":true},{"id":"clan-bank","label":"Clan Treasury","dashboardOnly":true},{"id":"clan-shop","label":"Clan Exchange"},{"id":"clan-tailor","label":"Clan Tailor"},{"id":"clan-listings","label":"My Listings"},{"id":"clan-post-listing","label":"Post a Listing"}]},{"label":"Campaigns & Realms","items":[{"id":"clan-claims","label":"Claims"},{"id":"clan-subhouses","label":"Subhouses"},{"id":"clan-patronage","label":"Patronage Directory"},{"id":"clan-quests","label":"Clan Expeditions"},{"id":"clan-campaigns","label":"Campaigns"},{"id":"clan-directory","label":"Clan Directory"}]}]},{"id":"bureau","label":"Imperial Bureau","icon":"shield","groups":[{"label":"Accounts & Permissions","items":[{"id":"user-management","label":"Personnel Management","viewPermission":"web.cp.v2.user.management.view","managePermission":"web.cp.v2.user.management.manage"},{"id":"permissions","label":"Roles & Permissions","viewPermission":"web.cp.v2.permissions.view","managePermission":"web.cp.v2.permissions.manage"},{"id":"manual-seals","label":"Seals & Honours","viewPermission":"web.cp.v2.manual.seals.view","managePermission":"web.cp.v2.manual.seals.manage"},{"id":"seal-generator","label":"Seal Designer","viewPermission":"web.cp.v2.manual.seals.view","managePermission":"web.cp.v2.manual.seals.manage"},{"id":"company-management","label":"Company Registry","viewPermission":"web.cp.v2.company.management.view","managePermission":"web.cp.v2.company.management.manage"},{"id":"company-management-v2","label":"Company Management","viewPermission":"web.cp.v2.company.management.v2.view","managePermission":"web.cp.v2.company.management.v2.manage"},{"id":"company-audit","label":"Company Audit","viewPermission":"web.cp.v2.company.audit.view","managePermission":"web.cp.v2.company.audit.manage"}]},{"label":"Management","items":[{"id":"codex-management","label":"J.A.R.V.I.S. Management","viewPermission":"web.cp.v2.items.view","managePermission":"web.cp.v2.items.manage"}]},{"label":"Shops & Items","items":[{"id":"staff-bank","label":"Treasury Accounts","viewPermission":"web.cp.v2.staff.bank.view","managePermission":"web.cp.v2.staff.bank.manage"},{"id":"server-kits","label":"Kit Management","viewPermission":"web.cp.v2.server.kits.view","managePermission":"web.cp.v2.server.kits.manage","dashboardOnly":true},{"id":"kit-publishing","label":"Kit Publishing","viewPermission":"web.cp.v2.kit.publishing.view","managePermission":"web.cp.v2.kit.publishing.manage","dashboardOnly":true},{"id":"kit-claims","label":"Kit Claims","viewPermission":"web.cp.v2.kit.claims.view","managePermission":"web.cp.v2.kit.claims.manage","dashboardOnly":true},{"id":"exchange-admin","label":"Exchange Management","viewPermission":"web.cp.v2.exchange.admin.view","managePermission":"web.cp.v2.exchange.admin.manage","dashboardOnly":true},{"id":"shop-admin","label":"Shop Management","viewPermission":"web.cp.v2.shop.admin.view","managePermission":"web.cp.v2.shop.admin.manage"},{"id":"items","label":"Item Management","viewPermission":"web.cp.v2.items.view","managePermission":"web.cp.v2.items.manage","dashboardOnly":true}]},{"label":"Community Services","items":[{"id":"website-posts","label":"News Management","viewPermission":"web.cp.v2.website.posts.view","managePermission":"web.cp.v2.website.posts.manage"},{"id":"staff-tickets","label":"Support Tickets","viewPermission":"web.cp.v2.staff.tickets.view","managePermission":"web.cp.v2.staff.tickets.manage"},{"id":"bans","label":"Bans & Appeals","viewPermission":"web.cp.v2.bans.view","managePermission":"web.cp.v2.bans.manage"},{"id":"ban-evidence","label":"Ban Evidence","viewPermission":"web.cp.v2.ban.evidence.view","managePermission":"web.cp.v2.ban.evidence.manage"},{"id":"forum-admin","label":"Forum Moderation","viewPermission":"web.cp.v2.forum.admin.view","managePermission":"web.cp.v2.forum.admin.manage"},{"id":"quests-admin","label":"Quest Management","viewPermission":"web.cp.v2.quests.admin.view","managePermission":"web.cp.v2.quests.admin.manage"},{"id":"community-goals","label":"Community Projects","viewPermission":"web.cp.v2.community.goals.view","managePermission":"web.cp.v2.community.goals.manage"},{"id":"support-management","label":"Support Administration","viewPermission":"web.cp.v2.support.management.view","managePermission":"web.cp.v2.support.management.manage"},{"id":"menu-badges","label":"Menu badges"}]},{"label":"Infrastructure","items":[{"id":"server-operations","label":"Server Operations","viewPermission":"web.cp.v2.server.operations.view","managePermission":"web.cp.v2.server.operations.manage"},{"id":"hosting-control","label":"Hosting Management","viewPermission":"web.cp.v2.hosting.control.view","managePermission":"web.cp.v2.hosting.control.manage"}]},{"label":"Bank Management","items":[{"id":"tax-treasury","label":"Tax Treasury Payments","viewPermission":"web.bank.staff.manage","managePermission":"web.bank.staff.manage"},{"id":"account-authorisations","label":"Account Authorisations","viewPermission":"web.bank.staff.view","managePermission":"web.bank.staff.manage"}]}]},{"id":"forge","label":"DuneForge","icon":"code-2","groups":[{"label":"Dev Control","items":[{"id":"dev-panel","label":"Dev Control","viewPermission":"web.cp.v2.dev.panel.view","managePermission":"web.cp.v2.dev.panel.manage"},{"id":"dev-queue","label":"Dev Listing","viewPermission":"web.cp.v2.dev.queue.view","managePermission":"web.cp.v2.dev.queue.manage"},{"id":"dev-approvals","label":"Dev Approvals","viewPermission":"web.cp.v2.dev.approvals.view","managePermission":"web.cp.v2.dev.approvals.manage"},{"id":"dev-new","label":"Submit Dev Request","viewPermission":"web.cp.v2.dev.new.view","managePermission":"web.cp.v2.dev.new.manage"},{"id":"dev-archive","label":"Dev Archive","viewPermission":"web.cp.v2.dev.archive.view","managePermission":"web.cp.v2.dev.archive.manage"}]},{"label":"Engineering","items":[{"id":"dev-builds","label":"Build & CI Monitor","viewPermission":"web.cp.v2.dev.builds.view","managePermission":"web.cp.v2.dev.builds.manage"},{"id":"dev-releases","label":"Release Ledger","viewPermission":"web.cp.v2.dev.releases.view","managePermission":"web.cp.v2.dev.releases.manage"},{"id":"dev-api","label":"API Reference","viewPermission":"web.cp.v2.dev.api.view","managePermission":"web.cp.v2.dev.api.manage"},{"id":"dev-audit","label":"Change Audit","viewPermission":"web.cp.v2.dev.audit.view","managePermission":"web.cp.v2.dev.audit.manage"}]},{"label":"DuneGit","items":[{"id":"git-workspace","label":"DuneGit Workspace","viewPermission":"web.menu.security","managePermission":"web.git.admin"},{"id":"git-repositories","label":"Repositories","viewPermission":"web.menu.security","managePermission":"web.git.admin"},{"id":"git-administration","label":"Git Administration","viewPermission":"web.git.admin","managePermission":"web.git.admin"}]}]},{"id":"politics","label":"Realm & Politics","icon":"crown","groups":[{"label":"Assembly","items":[{"id":"politics-overview","label":"Overview","viewPermission":"web.menu.game"},{"id":"landsraad","label":"Landsraad Assembly","viewPermission":"web.menu.game"},{"id":"council-motd","label":"Proclamations","viewPermission":"web.menu.game"},{"id":"applications","label":"Election Applications","viewPermission":"web.menu.game"},{"id":"house-elections","label":"House Elections","viewPermission":"web.menu.game"},{"id":"imperial-elections","label":"Emperor Elections","viewPermission":"web.menu.game"},{"id":"electoral-roll","label":"Electoral Roll","viewPermission":"web.menu.game"}]},{"label":"Councils","items":[{"id":"formal-council","label":"Faction Council","viewPermission":"web.menu.game"},{"id":"imperial-command","label":"Imperial Council","viewPermission":"web.menu.game"},{"id":"imperial-water","label":"Water Rights","viewPermission":"web.menu.game"},{"id":"imperial-spice","label":"Spice Rights","viewPermission":"web.menu.game"}]}]},{"id":"post","label":"Imperial Post","icon":"mail","groups":[{"label":"Correspondence","items":[{"id":"mail-inbox","label":"Incoming Dispatches","viewPermission":"web.cp.v2.mail.inbox.view","managePermission":"web.cp.v2.mail.inbox.manage"},{"id":"mail-compose","label":"Compose Dispatch","viewPermission":"web.cp.v2.mail.compose.view","managePermission":"web.cp.v2.mail.compose.manage"},{"id":"mail-sent","label":"Sent Dispatches","viewPermission":"web.cp.v2.mail.sent.view","managePermission":"web.cp.v2.mail.sent.manage"},{"id":"mail-drafts","label":"Draft Dispatches","viewPermission":"web.cp.v2.mail.drafts.view","managePermission":"web.cp.v2.mail.drafts.manage"},{"id":"mail-archive","label":"Imperial Archives","viewPermission":"web.cp.v2.mail.archive.view","managePermission":"web.cp.v2.mail.archive.manage"},{"id":"mail-trash","label":"Discarded Dispatches","viewPermission":"web.cp.v2.mail.trash.view","managePermission":"web.cp.v2.mail.trash.manage"}]},{"label":"Channels","items":[{"id":"shared-inbox","label":"Internal Dispatches","viewPermission":"web.cp.v2.shared.inbox.view","managePermission":"web.cp.v2.shared.inbox.manage"},{"id":"webmail","label":"External Mail","viewPermission":"web.cp.v2.webmail.view","managePermission":"web.cp.v2.webmail.manage"},{"id":"mail-contacts","label":"Address Book","viewPermission":"web.cp.v2.mail.contacts.view","managePermission":"web.cp.v2.mail.contacts.manage"},{"id":"mail-settings","label":"Correspondence Settings","viewPermission":"web.cp.v2.mail.settings.view","managePermission":"web.cp.v2.mail.settings.manage"},{"id":"mail-admin","label":"Postmaster Administration","viewPermission":"web.cp.v2.mail.admin.view","managePermission":"web.cp.v2.mail.admin.manage"}]}]},{"id":"bank","label":"Imperial Postbank","icon":"landmark","groups":[{"label":"Accounts & Payments","items":[{"id":"bank-overview","label":"My Accounts","viewPermission":"web.cp.v2.bank.overview.view","managePermission":"web.cp.v2.bank.overview.manage"},{"id":"personal-bank","label":"My Products","viewPermission":"web.cp.v2.personal.bank.view","managePermission":"web.cp.v2.personal.bank.manage"},{"id":"bank-transfers","label":"Transfers","viewPermission":"web.cp.v2.bank.transfers.view","managePermission":"web.cp.v2.bank.transfers.manage"},{"id":"bank-statements","label":"Transactions","viewPermission":"web.cp.v2.bank.statements.view","managePermission":"web.cp.v2.bank.statements.manage"},{"id":"bank-beneficiaries","label":"Beneficiaries","viewPermission":"web.cp.v2.bank.beneficiaries.view","managePermission":"web.cp.v2.bank.beneficiaries.manage"},{"id":"bank-authorisations","label":"My Authorisations","viewPermission":"web.bank.personal.view"}]},{"label":"Credit","items":[{"id":"loan-centre","label":"Loans & Grants","viewPermission":"web.cp.v2.loan.centre.view","managePermission":"web.cp.v2.loan.centre.manage"},{"id":"bank-loans","label":"My Credit","viewPermission":"web.cp.v2.bank.loans.view","managePermission":"web.cp.v2.bank.loans.manage"},{"id":"loan-administration","label":"Credit Management","viewPermission":"web.cp.v2.loan.administration.view","managePermission":"web.cp.v2.loan.administration.manage"}]},{"label":"Transparency","items":[{"id":"federal-reserve","label":"Federal Reserve Ledger"}]},{"label":"Administration","items":[{"id":"bank-dashboard","label":"Operations Dashboard","viewPermission":"web.cp.v2.bank.dashboard.view","managePermission":"web.cp.v2.bank.dashboard.manage"},{"id":"staff-bank","label":"Treasury Accounts","viewPermission":"web.cp.v2.staff.bank.view","managePermission":"web.cp.v2.staff.bank.manage"},{"id":"company-finance","label":"Business Accounts","viewPermission":"web.cp.v2.company.finance.view","managePermission":"web.cp.v2.company.finance.manage"},{"id":"bank-audit","label":"Audit Log","viewPermission":"web.cp.v2.bank.audit.view","managePermission":"web.cp.v2.bank.audit.manage"}]},{"label":"Currency & Heritage","items":[{"id":"dunemark-collection","label":"Dunemark Collection"}]}]},{"id":"market","label":"CHOAM Exchange","icon":"chart-no-axes-combined","groups":[{"label":"Commodity Exchange","items":[{"id":"commodity-listings","label":"Player Goods"},{"id":"commodity-mine","label":"My Listings"}]},{"label":"Markets","items":[{"id":"stock-overview","label":"Market Overview","viewPermission":"web.cp.v2.stock.overview.view","managePermission":"web.cp.v2.stock.overview.manage"},{"id":"stock-listings","label":"Listed Enterprises","viewPermission":"web.cp.v2.stock.listings.view","managePermission":"web.cp.v2.stock.listings.manage"},{"id":"stock-quotes","label":"Market Prices","viewPermission":"web.cp.v2.stock.quotes.view","managePermission":"web.cp.v2.stock.quotes.manage"},{"id":"stock-portfolio","label":"My Holdings","viewPermission":"web.cp.v2.stock.portfolio.view","managePermission":"web.cp.v2.stock.portfolio.manage"},{"id":"stock-orders","label":"Trading Floor","viewPermission":"web.cp.v2.stock.orders.view","managePermission":"web.cp.v2.stock.orders.manage"},{"id":"stock-trades","label":"Trade Ledger","viewPermission":"web.cp.v2.stock.trades.view","managePermission":"web.cp.v2.stock.trades.manage"},{"id":"stock-watchlist","label":"Watchlist","viewPermission":"web.cp.v2.stock.watchlist.view","managePermission":"web.cp.v2.stock.watchlist.manage"}]},{"label":"Enterprises","items":[{"id":"stock-ipo","label":"Listing Applications","viewPermission":"web.cp.v2.stock.ipo.view","managePermission":"web.cp.v2.stock.ipo.manage"},{"id":"stock-dividends","label":"Dividends","viewPermission":"web.cp.v2.stock.dividends.view","managePermission":"web.cp.v2.stock.dividends.manage"}]},{"label":"Oversight","items":[{"id":"stock-admin","label":"Market Authority","viewPermission":"web.cp.v2.stock.admin.view","managePermission":"web.cp.v2.stock.admin.manage"},{"id":"stock-surveillance","label":"Market Surveillance","viewPermission":"web.cp.v2.stock.surveillance.view","managePermission":"web.cp.v2.stock.surveillance.manage"}]}]},{"id":"quests","label":"Quests","icon":"scroll","groups":[{"label":"Your Journal","items":[{"id":"quests","label":"Contracts & Quests"}]}]},{"id":"kits","label":"Kits","icon":"package","groups":[{"label":"Equipment","items":[{"id":"kits-exchange","label":"Imperial Tailor"}]}]},{"id":"events","label":"Events","icon":"calendar","groups":[{"label":"Gatherings","items":[{"id":"events-calendar","label":"Event Calendar"}]}]}]};const art={clan:'nav-clan-v2.webp',quests:'nav-manual-v2.webp',kits:'items/office_water.png',events:'nav-home-v2.webp',politics:'seals/office-landsraad.png',realm:'nav-account-v2.webp',bureau:'nav-staff-v2.webp',forge:'nav-manual-v2.webp',post:'nav-support-v2.webp',bank:'imperial-postbank-v2.png',market:'nav-exchange-v2.webp'};const asset=n=>/^https:\/\//.test(n)?n:'https://www.dunerealms.com/assets/'+n;const portals=document.querySelector('#portals'),sidebar=document.querySelector('#sidebar'),content=document.querySelector('#content');let current='realm';let disposePage=()=>{};let postMenuTime=0,postMenuRequest=null,renderSequence=0; +// This entry is a classic deferred script; keep bookmark routing synchronous. +function politicsDestination(workspace,page){const groups={elections:['house-elections','imperial-elections','applications','electoral-roll'],offices:['office-register','politics-overview','landsraad','formal-council','imperial-command'],tools:['council-motd','imperial-water','imperial-spice']},known=Object.values(groups).flat();if(workspace!=='politics'&&!known.includes(workspace)&&!(['realm','game'].includes(workspace)&&known.includes(page)))return null;const selected=workspace==='politics'||['realm','game'].includes(workspace)?page:workspace,tab=Object.keys(groups).find(key=>groups[key].includes(selected))||(Object.hasOwn(groups,selected)?selected:'elections'),target=groups[tab].includes(selected)?selected:groups[tab][0];return 'https://www.dunerealms.com/government.html#'+tab+'/'+target;} +const requestedPolitics=politicsDestination(...location.hash.slice(1).split('?')[0].split('/'));if(requestedPolitics)location.replace(requestedPolitics); +const clanSurface=document.body.dataset.cpMode==='clan';const clanWorkspaces=new Set(['clan','quests','kits','events']); +function el(tag,cls,txt){const e=document.createElement(tag);if(cls)e.className=cls;if(txt!==undefined)e.textContent=txt;return e} +function image(name){const x=el('img');x.src=asset(name);x.alt='';x.loading='lazy';return x} +/* V1 artwork inventory: use existing /assets/ files; avoid generic repeated symbols. + New artwork guide: match V1 Minecraft-styled 3D objects, warm antique gold highlights, + deep forest-green shadows, transparent backgrounds, no text, 256px square WebP. + Missing concepts require dedicated art review before assets are published. */ +const CATEGORY_ARTWORK={ +'Identity':'nav-account-v2.webp','Communications':'nav-support-v2.webp', +'Adventures':'nav-clan-v2.webp','Commerce':'nav-exchange-v2.webp', +'Companies':'nav-clan-v2.webp','Citizens & Authority':'nav-staff-v2.webp', +'Commerce & Kits':'nav-exchange-v2.webp','Community':'nav-discord-v2.webp', +'Network':'nav-staff-v2.webp','Development':'nav-manual-v2.webp', +'Engineering':'nav-manual-v2.webp','Correspondence':'nav-support-v2.webp', +'Channels':'nav-discord-v2.webp','Accounts':'imperial-postbank-v2.png', +'Credit':'imperial-postbank-v2.png','Administration':'nav-staff-v2.webp', +'Markets':'nav-exchange-v2.webp','Enterprises':'nav-clan-v2.webp', +'Oversight':'nav-staff-v2.webp'}; +function categoryArtwork(label,workspace){return CATEGORY_ARTWORK[label]||art[workspace]} +// Missing category artwork is generated as original, lightweight SVG icons in the +// existing V1 green/gold palette. No external asset dependency, no text in icons. +// Art recipe: 48x48 transparent viewBox; dark forest-green backing; double antique- +// gold ring; warm amber highlights; beveled geometric symbols; avoid flat emoji. +// Reuse V1 assets for all other categories. Export future raster art at 256x256 WebP. +const NEW_CATEGORY_SYMBOLS={ +'Adventures':'sword','Commerce & Kits':'kit','Engineering':'gear', +'Credit':'coins','Markets':'chart','Oversight':'shield','Correspondence':'letter' +}; +function generatedCategoryArt(kind){ +const shapes={ +sword:'', +kit:'', +gear:'', +coins:'', +chart:'', +shield:'', +letter:''}; +const svg=''+(shapes[kind]||shapes.shield)+''; +return 'data:image/svg+xml;charset=utf-8,'+encodeURIComponent(svg) +} + +// Submenu artwork: prioritize the original V1 asset by subject; use the matching +// generated category crest only for subjects without a dedicated V1 illustration. +const V1_SUBMENU_ART=[ +[/bank|treasury|loan|credit|solari|finance|revenue|ledger|transfer|account statement/i,'imperial-postbank-v2.png'], +[/stock|exchange|market|trading|trade|merchant|shop|sales|commerce|ipo|dividend|portfolio/i,'nav-exchange-v2.webp'], +[/mail|inbox|dispatch|correspondence|message|ticket|support|petition|appeal/i,'nav-support-v2.webp'], +[/discord|channel|forum|community/i,'nav-discord-v2.webp'], +[/company|companies|clan|alliance|faction|guild/i,'nav-clan-v2.webp'], +[/server|staff|permission|rank|citizen|ban|moderation|admin|authority|election/i,'nav-staff-v2.webp'], +[/develop|forge|code|git|api|module|build|system|log|audit|engineering/i,'nav-manual-v2.webp'], +[/inventory|kit|item|reward|quest|adventure|crysknife/i,'items/office_water.png'], +[/identity|profile|personal|security|registration/i,'nav-account-v2.webp'] +]; +/* Distinct icon per menu item, including Identity. Existing V1 artwork stays for + top-level workspace cards and page banners; repeated submenu icons are replaced + with individually generated gold/green emblems, keyed by stable page ID. + Art generation: 48x48 SVG, forest-green backing, antique gold outlines, + warm sand highlights, transparent exterior, no words, deterministic ID seed. + A new icon is generated for every distinct submenu ID; no identical repeats. */ +function uniqueMenuIcon(key){ + const str=String(key);let hash=2166136261;for(let i=0;i>>0; + const motifs=[ + '', + '', + '', + '', + '', + '', + '', + '', + '' + ]; + const motif=motifs[hash%motifs.length];const rotation=(hash>>>8)%360; + const accents=['#d9a95a','#e5bf70','#c99847','#f1cf87']; + const dots=Array.from({length:3},(_,i)=>{const a=((hash>>>(i*6))%360)*Math.PI/180;const x=(24+17*Math.cos(a)).toFixed(1),y=(24+17*Math.sin(a)).toFixed(1);return ''}).join(''); + const svg=''+motif+''+dots+''; + return 'data:image/svg+xml;charset=utf-8,'+encodeURIComponent(svg) +} +function submenuArtwork(item,group,workspace){const img=el('img');img.src=item.artwork?'/assets/'+item.artwork:uniqueMenuIcon(workspace+'/'+group.label+'/'+item.id);img.alt='';img.width=48;img.height=48;return img} +function categoryTitleImage(label,workspace){const img=el('img');img.src=uniqueMenuIcon('category/'+workspace+'/'+label);img.alt='';img.width=48;img.height=48;return img} + + +// CP V2 Alpha module registry. Each existing V1-derived page renders a typed, +// accessible placeholder module rather than a generic blank screen. +/* Staff-first implementation: explicit staff page modules, no production writes. + Every staff route gets its own descriptive workflow and sample records. */ +/* Citizens Registry: first API-conform staff page. + V1 verified: GET /api/auth/session; GET /api/admin/register-user + (rank options); POST /api/admin/register-user with username,email, + ageBand,ranks. No unverified list-users endpoint is assumed. + Preview mode never sends requests or creates accounts. */ +function citizenRegistryPage(overview,actions){ + const section=el('section','citizen-module');section.setAttribute('aria-label','Citizen Registry'); + const intro=el('p','hint','V1-compatible account registration workflow. Live account listing is unavailable until its API contract is confirmed.'); + const form=el('form','citizen-form');form.autocomplete='off'; + function field(title,type,name){const label=el('label','citizen-field');label.append(el('span','',title));const input=el('input','module-search');input.type=type;input.name=name;input.required=true;label.append(input);form.append(label);return input} + const username=field('Minecraft / website username','text','username');username.pattern='[A-Za-z0-9_]{3,32}';username.maxLength=32; + const email=field('Email address or no_reply','text','email');email.maxLength=254; + const ageLabel=el('label','citizen-field');ageLabel.append(el('span','','Declared age group'));const age=el('select','module-search');age.name='ageBand';age.required=true;for(const [value,title] of [['','Choose age group'],['15plus','15 or older'],['under15','Under 15']]){const o=el('option','',title);o.value=value;age.append(o)}ageLabel.append(age);form.append(ageLabel); + const ranks=el('fieldset','citizen-ranks');ranks.append(el('legend','','Website ranks (verified API options only)'));const rankNote=el('p','hint','Ranks will load from GET /api/admin/register-user after staff authorization.');ranks.append(rankNote);form.append(ranks); + const notice=el('p','alpha-muted','Preview mode: account creation is disabled.');notice.setAttribute('role','status');form.append(notice); + const submit=el('button','gold-button','Create account');submit.type='submit';submit.disabled=true;form.append(submit); + form.addEventListener('submit',event=>event.preventDefault()); + section.append(intro,form); + const contract=el('details','citizen-contract');contract.append(el('summary','','Verified V1 API contract'));const pre=el('pre','','GET /api/auth/session\nGET /api/admin/register-user\nPOST /api/admin/register-user\nBody: { username, email, ageBand, ranks }\nPermission: server-enforced staff authorization\nAccount listing: endpoint not yet verified');contract.append(pre);section.append(contract); + const note=el('p','alpha-muted','Temporary credentials must be shown only after a successful authorized response, and must never be stored in this preview.');section.append(note); + overview.append(section); +} +/* Future-proof component boundary: placeholders are presentation-only. + API-backed implementations can replace each data-slot without changing layout, + navigation, permissions or the page registry. Never fabricate live records. */ +const STATIC_COMPONENTS={ + 'user-management':[{id:'citizen-directory',title:'Citizen Directory',kind:'data-grid',state:'api-pending',endpoint:'/api/admin/register-user?view=accounts&page=1',detail:'Account listing API exists on the staff development branch; staging integration and authorization tests remain pending.'},{id:'citizen-profile',title:'Citizen Profile',kind:'detail-panel',state:'contract-pending',detail:'Selected citizen identity, ranks and linked accounts will render here when the profile API contract is confirmed.'},{id:'citizen-audit',title:'Account Activity',kind:'timeline',state:'contract-pending',detail:'Audit events and account history require an authorized read endpoint.'}], + 'permissions':[{id:'effective-access',title:'Effective Permissions',kind:'matrix',state:'contract-pending',detail:'Role inheritance and permission resolution will be displayed after API validation.'}], + 'luckperms':[{id:'game-rank-tree',title:'Game Rank Hierarchy',kind:'tree',state:'contract-pending',detail:'Minecraft group inheritance will appear here after the LuckPerms API is validated.'}], + 'server-operations':[{id:'network-health',title:'Network Health',kind:'status-grid',state:'contract-pending',detail:'Proxy and backend health metrics require verified telemetry.'}], + 'kit-claims':[{id:'claim-delivery',title:'Claim Delivery',kind:'timeline',state:'contract-pending',detail:'Game delivery status and retry history require the kit claim API.'}], + 'ban-evidence':[{id:'evidence-viewer',title:'Evidence Viewer',kind:'media-panel',state:'contract-pending',detail:'Secure evidence access and audit logging must be validated before media is displayed.'}] +}; +function staticComponentsFor(workspace,page){const components=STATIC_COMPONENTS[page];if(components)return components;return [{id:page+'-details',title:'Details & Activity',kind:'detail-panel',state:'contract-pending',detail:'This component is reserved for the verified '+workspace+' API. Its layout and navigation are stable; no live data is implied.'}]} +function renderStaticComponents(workspace,page){ + const host=el('section','future-components');host.dataset.componentScope=workspace+'/'+page; + const heading=el('h3','future-components-heading','Planned Components');host.append(heading); + for(const component of staticComponentsFor(workspace,page)){ + const panel=el('article','future-component');panel.dataset.componentId=component.id;panel.dataset.componentKind=component.kind;panel.dataset.integrationState=component.state; + const header=el('div','future-component-header');header.append(el('strong','',component.title),el('span','future-component-tag',component.state==='api-pending'?'API PENDING':'DESIGN READY'));panel.append(header); + const content=el('div','future-component-body');content.dataset.slot=component.id; + const skeleton=el('div','future-skeleton');skeleton.setAttribute('aria-hidden','true'); + if(component.kind==='data-grid'||component.kind==='matrix'){for(let i=0;i<3;i++)skeleton.append(el('div','future-skeleton-line'))} + else if(component.kind==='timeline'||component.kind==='tree'){for(let i=0;i<3;i++)skeleton.append(el('div','future-skeleton-step'))} + else skeleton.append(el('div','future-skeleton-card')); + content.append(skeleton,el('p','alpha-muted',component.detail));panel.append(content);host.append(panel) + } + return host +} +const STAFF_MODULES={ +'user-management':['Citizen Registry','Manage linked accounts, staff status and access reviews.',['Username','Minecraft UUID','Website rank','Account status'],['Search citizen','Review account','Manage roles']], +'permissions':['Website Permissions','Review role grants, inherited permissions and audit decisions.',['Role','Permission node','Effect','Scope'],['Inspect role','Compare grants','Audit changes']], +'luckperms':['Minecraft Permissions','Review LuckPerms groups and effective Minecraft permissions.',['Group','Permission','World','Effect'],['Inspect group','Review inheritance','Sync preview']], +'manual-seals':['Awards & Seals','Review manual awards and issuance history.',['Recipient','Award','Issued by','State'],['Review award','Issue seal','View history']], +'company-management-v2':['Company Administration','Review registered companies, officers and compliance.',['Company','Owner','Members','Status'],['Inspect company','Review application','Audit']], +'staff-bank':['Imperial Revenue','Review staff-side treasury and revenue events.',['Reference','Account','Amount','State'],['Inspect ledger','Review transfer','Export audit']], +'server-kits':['Kit Directorate','Review all configured game kits and their publication status.',['Kit','Rarity','Published','Delivery'],['Inspect kit','Review definition','View claims']], +'kit-publishing':['Kit Publications','Stage kit catalog changes with approval gates.',['Kit','Revision','Approval','Publication'],['Review draft','Validate listing','Publish (locked)']], +'kit-claims':['Claim Registry','Track kit purchase, redemption and game delivery.',['Claim','Player','Kit','Delivery'],['Inspect claim','Retry (locked)','View receipt']], +'exchange-admin':['Exchange Authority','Review marketplace listings and enforcement queues.',['Listing','Seller','Price','Moderation'],['Inspect listing','Review report','Moderate (locked)']], +'shop-admin':['Merchant Directorate','Review merchant inventory, shop settings and sales.',['Merchant','Listing','Revenue','State'],['Inspect shop','Review inventory','View sales']], +'website-posts':['Imperial Newsroom','Review website news drafts and publication approvals.',['Article','Author','Revision','State'],['Review draft','Preview article','Publish (locked)']], +'staff-tickets':['Petition Office','Triage and assign citizen support requests.',['Ticket','Requester','Priority','Status'],['Inspect ticket','Assign (locked)','Reply (locked)']], +'bans':['Tribunal','Review ban records, appeals and moderation decisions.',['Case','Player','Reason','Appeal'],['Inspect case','Review appeal','Moderate (locked)']], +'ban-evidence':['Evidence Registry','Review moderation evidence and chain of custody.',['Evidence','Case','Submitted by','Integrity'],['Inspect evidence','Review history','Attach (locked)']], +'forum-admin':['Forum Wardens','Review forum moderation queues and reports.',['Thread','Reporter','Category','State'],['Inspect thread','Review report','Moderate (locked)']], +'quests-admin':['Campaign Directorate','Review quests, milestones and reward configurations.',['Quest','Owner','Reward','Status'],['Inspect quest','Review rewards','Publish (locked)']], +'support-management':['Petition Administration','Review service-level queues and support staffing.',['Queue','Owner','Open','Escalation'],['Inspect queue','Review assignment','Configure (locked)']], +'server-operations':['Network Command','Review network service status and proposed actions.',['Server','World','Health','Last check'],['Inspect server','View logs','Control (locked)']], +'git-admin':['Repository Authority','Review repository changes and release approvals.',['Repository','Branch','Review','Checks'],['Inspect change','View checks','Approve (locked)']], +'mail-admin':['Postmaster Administration','Review mail delivery, queues and access controls.',['Queue','Direction','Messages','State'],['Inspect queue','View delivery','Configure (locked)']] +}; +function staffModule(id){const spec=STAFF_MODULES[id];if(!spec)return null;const [entity,description,columns,actions]=spec;return {entity,description,create:'Create (locked)',metrics:[['Total','—'],['Awaiting review','—'],['Alerts','—']],columns,actions,instructions:'Staff preview only. Role checks, audit logging, API integration and staging acceptance are required before actions are enabled.',sample:(i)=>[entity+' '+(i+1),['Unassigned','Pending','Review'][i],'—','Preview']}} +const PAGE_MODULES={ +records:{entity:'Records',create:'New record',description:'Review records, ownership and pending changes.',metrics:[['Total','—'],['Pending','—'],['Updated','—']],columns:['Record','Owner','State','Updated'],actions:['View details','Edit record','Export'],instructions:'Record actions are locked until staging API validation.',sample:(i,n)=>[n+' '+(i+1),'Not linked',i?'Draft':'Preview','—']}, +identity:{entity:'Account details',create:'Edit profile',description:'Personal account, linked Minecraft identity and security details.',metrics:[['Linked player','—'],['Rank','—'],['Last login','—']],columns:['Field','Current value','Verification','Action'],actions:['Link account','Update profile','Security settings'],instructions:'Identity changes require verified login and permission checks.',sample:(i)=>[['Minecraft account','Not connected','Pending','View'],['Discord account','Not connected','Pending','Link'],['Account security','Not connected','Pending','Review']][i]}, +finance:{entity:'Transactions',create:'New transfer',description:'Solari balances, statements and transaction records.',metrics:[['Available','— Solari'],['Reserved','— Solari'],['Pending','—']],columns:['Reference','Type','Amount','Status'],actions:['Transfer Solari','View statement','Download receipt'],instructions:'All monetary actions are disabled in design mode.',sample:(i)=>['TX-PREVIEW-'+(i+1),['Deposit','Transfer','Withdrawal'][i],'— Solari','Sample']}, +market:{entity:'Listings',create:'Create listing',description:'Browse listings, trades, holdings and market activity.',metrics:[['Listings','—'],['Open orders','—'],['Volume','—']],columns:['Listing','Market','Price','Status'],actions:['Browse market','Place order','Trade history'],instructions:'Market orders require live quote and idempotency integration.',sample:(i)=>['Market item '+(i+1),'CHOAM','— Solari','Preview']}, +kits:{entity:'Kits',create:'Publish kit',description:'Browse kit definitions, availability, publication and claim paths.',metrics:[['Published','—'],['Unpublished','—'],['Claims','—']],columns:['Kit','Rarity','Availability','Claim state'],actions:['Browse kits','Manage publication','View claims'],instructions:'Publishing and game delivery remain gated pending native API verification.',sample:(i)=>['Kit '+(i+1),['Common','Rare','Legendary'][i],'Unknown','Not connected']}, +messaging:{entity:'Messages',create:'Compose message',description:'Inbox, outgoing correspondence, delivery and support requests.',metrics:[['Unread','—'],['Open','—'],['Sent','—']],columns:['Subject','From / To','Received','Status'],actions:['Compose','Open inbox','Archive'],instructions:'Messaging requires authenticated inbox and server-side delivery.',sample:(i)=>['Sample message '+(i+1),'Not connected','—','Preview']}, +operations:{entity:'Services',create:'New operation',description:'Server health, service controls and operational audit.',metrics:[['Healthy','—'],['Unknown','—'],['Alerts','—']],columns:['Service','Environment','Health','Last check'],actions:['Inspect service','View logs','Request action'],instructions:'Operational controls must be restricted to authorized staff.',sample:(i)=>[['Proxy','Network','Unknown','—'],['Minecraft backend','Game','Unknown','—'],['Website API','Web','Unknown','—']][i]}, +developer:{entity:'Tasks',create:'New work order',description:'Developer queue, review workflow, modules and build diagnostics.',metrics:[['Open tasks','—'],['Reviews','—'],['Builds','—']],columns:['Work item','Module','Stage','Owner'],actions:['Create work order','Review changes','View build logs'],instructions:'Development actions are design-only until authenticated workflows are connected.',sample:(i)=>['DEV-'+(i+1),'Module '+(i+1),'Preview','Unassigned']} +}; +function pageType(id,label,workspace){const s=(id+' '+label).toLowerCase();if(/kit|claim|tailor|crysknife/.test(s))return 'kits';if(/bank|treasury|loan|credit|solari|transaction|finance|ledger|revenue/.test(s))return 'finance';if(/stock|market|trade|exchange|merchant|shop|sale|listing|dividend|portfolio/.test(s))return 'market';if(/mail|inbox|dispatch|correspondence|message|ticket|support|petition|appeal/.test(s))return 'messaging';if(/server|network|hosting|monitor|operation|world|backup|status|ban/.test(s))return 'operations';if(workspace==='forge'||/developer|build|forge|git|module|api|blueprint|archive/.test(s))return 'developer';if(/identity|profile|security|discord.link|personal.record/.test(s))return 'identity';return 'records'} +function legacyRoute(wid,pid){if(wid==='realm'&&pid==='clans')return {wid:'clan',pid:'clan-overview'};if(wid==='realm'&&pid==='quests')return {wid:'quests',pid:'quests'};if(wid==='realm'&&pid==='kits-exchange')return {wid:'kits',pid:'kits-exchange'};if(wid==='bank'&&pid==='bank-information')return {wid:'bank',pid:'bank-overview'};if(wid==='bank'&&pid==='bank-history')return {wid:'bank',pid:'bank-statements'};if(wid==='realm'&&pid==='personal-bank')return {wid:'bank',pid:'personal-bank'};if(wid==='realm'&&pid==='transactions')return {wid:'bank',pid:'bank-statements'};if(['realm','post'].includes(wid)&&pid==='shared-inbox')return {wid:'post',pid:'mail-inbox'};if(menu.workspaces.some(w=>w.id===wid))return {wid,pid};const aliases={'clans':['clan','clan-overview'],'clan-portal':['clan','clan-overview'],'clan-shops':['clan','clan-shop'],'clan-kits':['clan','clan-tailor'],'clan-bank':['clan','clan-bank'],'clan-settings':['clan','clan-settings'],'exchange':['market','commodity-listings'],'rewards-redeem':['realm','rewards-codes','redeem'],'redeem-code':['realm','rewards-codes','redeem'],'discovery-rewards':['realm','rewards-codes','redeem'],'kit-checkout':['kits','kits-exchange','kit-checkout'],'clan-inbox':['post','clan-inbox'],'faction-inbox':['post','faction-inbox'],'imperial-inbox':['post','imperial-inbox'],'staff-inbox':['post','staff-inbox'],'internal-mail':['post','mail-inbox'],'shared-inbox':['post','mail-inbox'],'personal-bank':['bank','personal-bank'],'transactions':['bank','bank-history']};if(aliases[wid]){const [workspace,page,initialTab]=aliases[wid];return {wid:workspace,pid:page,initialTab};}const workspace=menu.workspaces.find(w=>w.groups.some(g=>g.items.some(item=>item.id===wid)));return workspace?{wid:workspace.id,pid:wid}:{wid,pid};} +let cpReady=false,centralOrganisation=false; +function go(wid,pid,context={}){if(wid==='companies'||pid==='companies'||['realm','market'].includes(wid)&&String(pid||'').startsWith('company-')){location.assign('https://corp.dunerealms.com/');return;}const politicalTarget=politicsDestination(wid,pid);if(politicalTarget){location.assign(politicalTarget);return;}if(!cpReady||!menu.workspaces.length)return;const navigation=++renderSequence;const route=legacyRoute(wid,pid);wid=route.wid;pid=route.pid;if(!clanSurface&&clanWorkspaces.has(wid)){location.assign('https://clans.dunerealms.com/#'+wid+'/'+(pid||''));return;} +if(wid==='post'&&!context.mailDirectoryReady&&Date.now()-postMenuTime>30000){disposePage();disposePage=()=>{};current='post';sidebar.replaceChildren(el('p','','Loading your inboxes…'));content.replaceChildren(el('p','cp-v2-news-status','Loading your authorised inboxes…'));document.querySelector('#sidebar-right').replaceChildren();if(!postMenuRequest)postMenuRequest=import('/v2/cp-v2-post-menu.mjs').then(({loadMailboxMenu})=>loadMailboxMenu()).finally(()=>{postMenuRequest=null;});postMenuRequest.then(inboxes=>{if(navigation!==renderSequence)return;const post=menu.workspaces.find(w=>w.id==='post'),channels=post.groups.find(g=>g.label==='Channels')?.items||[];post.groups=[{label:'Inboxes',items:inboxes},{label:'Channels',items:channels.filter(item=>item.id!=='shared-inbox')}];postMenuTime=Date.now();go('post',pid,{...context,mailDirectoryReady:true});}).catch(error=>{if(navigation!==renderSequence)return;const retry=el('button','gold-button','Retry inbox directory');retry.onclick=()=>go('post',pid);content.replaceChildren(el('p','cp-v2-news-status',error.message),retry);});return;} +const initialTab=route.initialTab||context.initialTab;const requestedDesignTab=pid; if(['realm','market'].includes(wid)&&['company-directory','company-registration','company-profile','company-members','company-finance','company-permissions','company-applications'].includes(pid))pid='companies';if(wid==='bureau'&&pid==='dev-approvals'){wid='forge';pid='dev-approvals';}disposePage();disposePage=()=>{};if(wid==='bureau'&&pid==='luckperms')pid='permissions';const w=menu.workspaces.find(x=>x.id===wid)||menu.workspaces[0];current=w.id;document.body.dataset.workspace=w.id;const items=w.groups.flatMap(g=>g.items);const item=items.find(x=>x.id===pid)||items[0];if(clanSurface&&parent!==window)parent.postMessage({type:'dune-clan-route',workspace:w.id,page:item.id},'https://clans.dunerealms.com');for(const b of portals.children)b.setAttribute('aria-selected',String(b.dataset.id===w.id));sidebar.replaceChildren();const sidebarRight=document.querySelector('#sidebar-right');sidebarRight.replaceChildren();const banner=el('div','side-hero',w.id==='forge'?'DEV':w.label.toUpperCase());sidebar.append(banner);sidebarRight.append(el('div','side-hero',w.id==='forge'?'DUNEGIT':w.label.toUpperCase()+' · DIRECTORY'));if(w.id==='realm'){const mail=el('button','mail-shortcut','✉ You’ve Got Mail');mail.onclick=()=>go('post','mail-inbox');sidebar.append(mail)} +const groups=w.groups.map(g=>({...g,items:g.items.filter(x=>!x.dashboardOnly)})).filter(g=>g.items.length);let split=groups.length,best=Infinity;for(let i=1;in+g.items.length+2,0),b=groups.slice(i).reduce((n,g)=>n+g.items.length+2,0),delta=Math.abs(a-b);if(deltag.label==='DuneGit');if(w.id==='post')split=1;for(const [gi,g] of groups.entries()){const target=gix.id===item.id);const heading=el('summary','category-heading');heading.append(categoryTitleImage(g.label,w.id),el('span','category-name',g.label),el('span','category-count',String(g.items.length)));block.append(heading);const links=el('div','category-links');for(const x of g.items){const b=el('button','navitem');b.type='button';b.append(submenuArtwork(x,g,w.id),el('span','',x.label));b.setAttribute('aria-current',x.id===item.id?'page':'false');b.onclick=()=>go(w.id,x.id);links.append(b)}block.append(links);target.append(block)}content.replaceChildren();const hero=el('div','hero');hero.append(image(art[w.id]));const title=el('div');title.append(el('h1','',item.label),el('p','',w.id==='clan'?'Your household, its banner and the people who carry it.':'Realm management, account tools and personal operations.'));hero.append(title);content.append(hero); +const cards=el('div','cards');content.append(cards); +function card(name,icon,full=false){const c=el('article','card'+(full?' full':''));const h=el('h2');h.append(image(icon),document.createTextNode(name));c.append(h);cards.append(c);return c} +function button(name,fn){const b=el('button','gold-button',name);b.onclick=fn;return b} +function tiles(c,values){const wrap=el('div','tiles');for(const [label,icon,ws,page] of values){const b=el('button','tile');b.append(image(icon),el('span','',label));b.onclick=()=>go(ws,page);wrap.append(b)}c.append(wrap)} +if(['clan','quests','kits','events'].includes(w.id)){const overview=card(item.label,art[w.id],true),host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-play-workspaces.mjs').then(({mountPlayWorkspace})=>{if(host.isConnected)disposePage=mountPlayWorkspace(host,w.id,item.id,{initialTab,listingId:context.listingId});}).catch(error=>{if(host.isConnected)host.textContent='Workspace unavailable: '+error.message;});history.replaceState(null,'','#'+w.id+'/'+item.id);return;} +if(w.id==='realm'&&item.id==='crysknife'){const overview=card(item.label,'seals/order-crysknife-v1.png',true),host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-crysknife.mjs').then(({mountCrysknife})=>{if(host.isConnected)disposePage=mountCrysknife(host)}).catch(error=>{if(host.isConnected)host.textContent='Order register unavailable: '+error.message});history.replaceState(null,'','#realm/crysknife');return;} +if(w.id==='realm'&&['item-exchange','item-listings','item-post','game','site-profile','security','discord-link','planetary-inventory','quests','tickets','clans','shared-inbox','kits-exchange','rewards-codes','personal-bank','transactions','shop-settings','exchange-settings'].includes(item.id)){const overview=card(item.label,art[w.id],true),host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-user-pages.mjs').then(({mountUserPage})=>{if(host.isConnected)disposePage=mountUserPage(host,item.id,{initialTab,listingId:context.listingId})}).catch(error=>{if(host.isConnected)host.textContent='User workspace unavailable: '+error.message});history.replaceState(null,'','#'+w.id+'/'+item.id);return;} +if(w.id==='realm'&&item.id==='game'){const mail=card('You’ve Got Mail','nav-support-v2.webp');mail.append(el('p','mail-text','Imperial Post inbox · no live messages in preview'),button('Open Mail »',()=>go('post','mail-inbox')));const status=card('Realm Status','nav-account-v2.webp');const rows=el('div','status');for(const [k,v] of [['Realm','Preview'],['Rank','Not connected'],['Companies','—'],['Kits','—'],['Last Login','—']])rows.append(el('i','','●'),el('span','',k+':'),el('span','',v));status.append(rows);tiles(card('Quick Actions','nav-clan-v2.webp'),[['Manage Kits','items/office_water.png','realm','kits-exchange'],['Banking','imperial-postbank-v2.png','bank','bank-overview'],['Trading','nav-exchange-v2.webp','market','stock-overview']]);tiles(card('Developer Tools','nav-manual-v2.webp'),[['API Console','nav-manual-v2.webp','forge','dev-api'],['Module Manager','nav-staff-v2.webp','forge','dev-builds'],['System Logs','nav-manual-v2.webp','forge','dev-audit'],['Dev Utilities','nav-account-v2.webp','forge','dev-panel']]);const news=card('System Announcements','nav-manual-v2.webp',true);for(const [badge,text] of [['V2','Alphastyle independent control panel preview'],['DEV','Company, banking and stockmarket workspaces'],['ART','Existing DuneRealms navigation artwork']]){const row=el('div','dispatch');row.append(el('b','',badge),el('span','',text),el('small','','PREVIEW'));news.append(row)}}else{ +const sectionType=pageType(item.id,item.label,w.id); +const descriptor=(w.id==='bureau'?staffModule(item.id):null)||PAGE_MODULES[sectionType]; +const overview=card(item.label,art[w.id]); +if(w.id==='market'&&['commodity-listings','commodity-mine'].includes(item.id)){overview.classList.add('citizen-page-full');const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-choam-pages.mjs').then(({mountCommodityExchange})=>{if(host.isConnected)disposePage=mountCommodityExchange(host,item.id)}).catch(error=>{if(host.isConnected)host.textContent='Commodity Exchange unavailable: '+error.message});history.replaceState(null,'','#market/'+item.id);return;} +if(w.id==='politics'){overview.classList.add('citizen-page-full');const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-politics-pages.mjs').then(({mountPoliticsPage})=>{if(host.isConnected)disposePage=mountPoliticsPage(host,item.id)}).catch(error=>{if(host.isConnected)host.textContent='Political workspace unavailable: '+error.message});history.replaceState(null,'','#politics/'+item.id);return;} +if(w.id==='bureau'&&['codex-management','items','server-kits','kit-publishing','kit-claims','exchange-admin'].includes(item.id)){overview.classList.add('citizen-page-full');const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-codex-management.mjs').then(({mountCodexManagement})=>{if(host.isConnected)disposePage=mountCodexManagement(host,{initial:({'items':'items','server-kits':'kits','kit-publishing':'publication','kit-claims':'delivery','exchange-admin':'listings'})[item.id]||'keys'})}).catch(error=>{if(host.isConnected)host.textContent='J.A.R.V.I.S. Management unavailable: '+error.message});history.replaceState(null,'','#bureau/'+item.id);return;} +if(w.id==='bureau'&&item.id==='account-authorisations'){overview.classList.add('citizen-page-full');const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-authorisations.mjs').then(({mountAuthorisations})=>{if(host.isConnected)disposePage=mountAuthorisations(host,{staff:true})}).catch(error=>{if(host.isConnected)host.textContent='Authorisations unavailable: '+error.message});history.replaceState(null,'','#bureau/account-authorisations');return;} +if(w.id==='bureau'&&item.id==='tax-treasury'){overview.classList.add('citizen-page-full');const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-tax-treasury.mjs').then(({mountTaxTreasury})=>{if(host.isConnected)disposePage=mountTaxTreasury(host)}).catch(error=>{if(host.isConnected)host.textContent='Tax treasury unavailable: '+error.message});history.replaceState(null,'','#bureau/tax-treasury');return;} +if(w.id==='bureau'&&item.id==='menu-badges'){overview.classList.add('citizen-page-full');const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-menu-badges.mjs').then(({mountMenuBadges})=>{if(host.isConnected)disposePage=mountMenuBadges(host)}).catch(error=>{if(host.isConnected)host.textContent=error.message});history.replaceState(null,'','#bureau/menu-badges');return;} +if(w.id==='bank'){overview.classList.add('citizen-page-full');const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-bank-pages.mjs').then(({mountBankPage})=>{if(host.isConnected)disposePage=mountBankPage(host,item.id,{accountId:context.accountId})}).catch(error=>{if(host.isConnected)host.textContent='Postbank unavailable: '+error.message});history.replaceState(null,'','#bank/'+item.id+(item.id==='bank-statements'&&/^\d{1,12}$/.test(context.accountId||'')?'/'+context.accountId:''));return;} +if(w.id==='post'){overview.classList.add('citizen-page-full');const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-post-pages.mjs').then(({mountPostPage})=>{if(host.isConnected)disposePage=mountPostPage(host,item.id,{initialTab,title:item.label})}).catch(error=>{if(host.isConnected)host.textContent='Imperial Post unavailable: '+error.message});history.replaceState(null,'','#post/'+item.id);return;} +if(w.id==='forge'){overview.classList.add('citizen-page-full');const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-forge-pages.mjs').then(({mountForgePage})=>{if(host.isConnected)disposePage=mountForgePage(host,item.id)}).catch(error=>{if(host.isConnected)host.textContent='DuneForge unavailable: '+error.message});history.replaceState(null,'','#'+w.id+'/'+item.id);return;} +if(["realm/companies","market/companies","realm/sales-history","post/mail-inbox","post/mail-compose","post/mail-sent","post/mail-drafts","post/mail-archive","post/mail-trash","post/mail-contacts","post/mail-settings","post/mail-admin","bank/bank-overview","bank/bank-transfers","bank/bank-statements","bank/bank-history","bank/bank-beneficiaries","bank/bank-loans","bank/company-finance","bank/bank-audit","market/stock-overview","market/stock-listings","market/stock-quotes","market/stock-portfolio","market/stock-orders","market/stock-trades","market/stock-watchlist","market/stock-ipo","market/stock-dividends","market/stock-admin","market/stock-surveillance","forge/dev-builds","forge/dev-releases","forge/dev-api","forge/dev-audit","bureau/kit-claims"].includes(w.id+'/'+item.id)){overview.classList.add('citizen-page-full');const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-design-pages.mjs').then(({mountDesignPage})=>{if(host.isConnected)disposePage=mountDesignPage(host,w.id+'/'+item.id,{initialTab:requestedDesignTab})}).catch(error=>{if(host.isConnected)host.textContent='Design workbench unavailable: '+error.message});history.replaceState(null,'','#'+w.id+'/'+(requestedDesignTab||item.id));return;} + +if((w.id==='bureau'&&['user-management','permissions','manual-seals','seal-generator','company-management','company-management-v2','company-audit','staff-bank','server-kits','kit-publishing','kit-claims','exchange-admin','shop-admin','items','website-posts','staff-tickets','bans','ban-evidence','forum-admin','quests-admin','community-goals','support-management','server-operations','hosting-control','dev-approvals'].includes(item.id))||(w.id==='market'&&['stock-overview','stock-listings','stock-quotes','stock-portfolio','stock-orders','stock-trades','stock-watchlist','companies','company-directory','company-profile','stock-ipo','stock-dividends','stock-admin','stock-surveillance'].includes(item.id))||(w.id==='bank'&&['bank-information','bank-overview','personal-bank','bank-transfers','bank-statements','bank-history','bank-beneficiaries','loan-centre','bank-loans','loan-administration','bank-dashboard','staff-bank','company-finance','bank-audit'].includes(item.id)))overview.classList.add('citizen-page-full'); +overview.append(el('p','hint',descriptor.description)); +if(w.id==='bureau'&&item.id==='user-management'){ + const host=el('div','citizen-live-host');overview.append(host); + const state=el('p','alpha-muted','Loading the authorized Citizens Registry…');host.append(state); + const migrationPreview=centralOrganisation||new URL(location.href).searchParams.get('migration')==='1'; + import(migrationPreview?'/v2/citizen-directory.mjs':'/v2/citizens-registry.mjs?v=cpalpha-20261112c').then(module=>{ + if(host.isConnected)disposePage=migrationPreview?module.mountCitizenDirectory(host):module.mountCitizensRegistry(host) + }).catch(error=>{if(host.isConnected)state.textContent='Citizens Registry could not load: '+error.message}); + history.replaceState(null,'','#'+w.id+'/'+item.id); + return; +} +if(w.id==='bureau'&&item.id==='permissions'&&(centralOrganisation||new URL(location.href).searchParams.get('migration')==='1')){const host=el('div','citizen-live-host');overview.append(host);import('/v2/organisation-permissions.mjs').then(({mountOrganisationPermissions})=>{if(host.isConnected)disposePage=mountOrganisationPermissions(host)}).catch(error=>{if(host.isConnected)host.textContent=error.message});history.replaceState(null,'','#bureau/permissions');return;} +if(w.id==='bureau'&&item.id==='permissions'){const host=el('div','citizen-live-host');overview.append(host);host.append(el('p','alpha-muted','Loading Imperial Permissions…'));import('/v2/imperial-permissions.mjs?v=rankdelete-20261112a').then(({mountImperialPermissions})=>{if(host.isConnected)mountImperialPermissions(host)}).catch(error=>{if(host.isConnected)host.textContent='Imperial Permissions unavailable: '+error.message});history.replaceState(null,'','#'+w.id+'/'+item.id);return;} +if(w.id==='bureau'&&item.id==='manual-seals'){const host=el('div','citizen-live-host');overview.append(host);host.append(el('p','alpha-muted','Loading Honours & Seals…'));import('/v2/honours-seals.mjs?v=sealupload-20261112a').then(({mountHonoursSeals})=>{if(host.isConnected)mountHonoursSeals(host)}).catch(error=>{if(host.isConnected)host.textContent='Honours & Seals unavailable: '+error.message});history.replaceState(null,'','#'+w.id+'/'+item.id);return;} +if(w.id==='bureau'&&['company-management','company-management-v2','company-audit','staff-bank','server-kits','kit-publishing','kit-claims','exchange-admin','shop-admin','items','website-posts','staff-tickets','bans','ban-evidence','forum-admin','quests-admin','community-goals','support-management','server-operations','hosting-control','dev-approvals'].includes(item.id)){const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-bureau-pages.mjs?v=bureau-registers-20261112c').then(({mountBureauPlaceholder})=>{if(host.isConnected)disposePage=mountBureauPlaceholder(host,item.id)}).catch(error=>{if(host.isConnected)host.textContent='Bureau page unavailable: '+error.message});history.replaceState(null,'','#'+w.id+'/'+item.id);return;} +if(w.id==='bank'&&['bank-information','bank-overview','personal-bank','bank-transfers','bank-statements','bank-history','bank-beneficiaries','loan-centre','bank-loans','loan-administration','bank-dashboard','staff-bank','company-finance','bank-audit'].includes(item.id)){const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-planned-pages.mjs?v=bank-admin-20261112a').then(({mountBankPlaceholder})=>{if(host.isConnected)mountBankPlaceholder(host,item.id)}).catch(error=>{if(host.isConnected)host.textContent='Postbank placeholder unavailable: '+error.message});history.replaceState(null,'','#'+w.id+'/'+item.id);return;} +if(w.id==='market'&&['stock-overview','stock-listings','stock-quotes','stock-portfolio','stock-orders','stock-trades','stock-watchlist','companies','company-directory','company-profile','stock-ipo','stock-dividends','stock-admin','stock-surveillance'].includes(item.id)){const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-choam-pages.mjs?v=choam-all-20261112a').then(({mountCHOAMPlaceholder})=>{if(host.isConnected)mountCHOAMPlaceholder(host,item.id)}).catch(error=>{if(host.isConnected)host.textContent='CHOAM page unavailable: '+error.message});history.replaceState(null,'','#'+w.id+'/'+item.id);return;} +if(w.id==='bureau'&&item.id==='seal-generator'){const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-planned-pages.mjs?v=bank-admin-20261112a').then(({mountSealGeneratorPlaceholder})=>{if(host.isConnected)mountSealGeneratorPlaceholder(host)}).catch(error=>{if(host.isConnected)host.textContent='Seal Generator placeholder unavailable: '+error.message});history.replaceState(null,'','#'+w.id+'/'+item.id);return;} +overview.append(renderStaticComponents(w.id,item.id)); + +const ribbon=el('div','alpha-ribbon');ribbon.append(el('span','alpha-pill','ALPHA · UI PREVIEW'),el('span','alpha-muted','Planned service · No live data or writes'));overview.append(ribbon); +const toolbar=el('div','module-toolbar');const search=el('input','module-search');search.type='search';search.placeholder='Filter '+descriptor.entity.toLowerCase()+'…';search.setAttribute('aria-label','Filter placeholder records');toolbar.append(search); +const add=button('+ '+descriptor.create,()=>{});add.disabled=true;add.title='Available after API and permission integration';toolbar.append(add);overview.append(toolbar); +const statgrid=el('div','alpha-stats');for(const [name,value] of descriptor.metrics){const tile=el('div','alpha-stat');tile.append(el('small','',name),el('strong','',value));statgrid.append(tile)}overview.append(statgrid); +const tableWrap=el('div','alpha-table-wrap');const t=el('table','placeholder-table alpha-table');const thead=el('thead');const head=el('tr');for(const name of descriptor.columns)head.append(el('th','',name));thead.append(head);t.append(thead);const tbody=el('tbody');for(let i=0;i<3;i++){const tr=el('tr');const cells=descriptor.sample(i,item.label);for(const val of cells)tr.append(el('td','',val));tbody.append(tr)}t.append(tbody);tableWrap.append(t);overview.append(tableWrap); +const viewTools=el('div','alpha-view-tools'); +const viewTitle=el('span','alpha-muted','Preview state:'); +const viewOptions=[['Sample','sample'],['Empty','empty'],['Loading','loading'],['Error','error']]; +viewTools.append(viewTitle); +const viewButtons=[]; +function setPreviewState(state){for(const [button,value] of viewButtons)button.setAttribute('aria-pressed',String(value===state));tableWrap.hidden=state!=='sample';const msg=overview.querySelector('.alpha-state-message');if(msg)msg.remove();if(state!=='sample'){const message=el('div','alpha-state-message');message.setAttribute('role','status');const stateText={empty:'No records yet. Connect the staging API to populate this workspace.',loading:'Loading preview — simulated state; no network request is made.',error:'Preview error state — retry will become available after API integration.'};message.textContent=stateText[state];viewTools.after(message)}} +for(const [label,value] of viewOptions){const b=el('button','alpha-view-button',label);b.type='button';b.setAttribute('aria-pressed',String(value==='sample'));b.onclick=()=>setPreviewState(value);viewButtons.push([b,value]);viewTools.append(b)} +overview.append(viewTools); +const empty=el('p','alpha-muted alpha-empty','Sample records are illustrative only.');overview.append(empty); +search.addEventListener('input',()=>{const q=search.value.toLowerCase();let visible=0;for(const tr of tbody.children){const match=tr.textContent.toLowerCase().includes(q);tr.hidden=!match;if(match)visible++}empty.textContent=visible?'Sample records are illustrative only.':'No matching sample records.'}); +const actions=card('Workspace Tools',art[w.id]);actions.append(el('p','hint',descriptor.instructions));const actionList=el('div','alpha-actions');for(const label of descriptor.actions){const b=button(label,()=>{});b.disabled=true;b.title='Preview only; backend integration pending';actionList.append(b)}actions.append(actionList); +const status=el('div','alpha-readiness');for(const [name,value] of [['UI','READY FOR REVIEW'],['API','NOT CONNECTED'],['AUTHORIZATION','PENDING'],['WRITE OPERATIONS','DISABLED']]){const row=el('div');row.append(el('span','',name),el('strong','',value));status.append(row)}actions.append(status); +const note=card('Integration Checklist','nav-manual-v2.webp',true);const checklist=el('ul','alpha-checklist');for(const step of ['Confirm V1 feature parity and page ownership','Map read endpoints and permission checks','Connect staging API with mock-data fallback','Test empty, loading, error and mobile states','Review and approve before enabling writes'])checklist.append(el('li','',step));note.append(checklist);note.append(el('p','hint','Permission nodes: '+item.viewPermission+' · '+item.managePermission)); +} +history.replaceState(null,'','#'+w.id+'/'+item.id)} +document.querySelector('#mobile-menu').onclick=()=>{const opened=sidebar.classList.toggle('open');document.querySelector('#sidebar-right').classList.toggle('open',sidebar.classList.contains('open'));document.querySelector('#mobile-menu').setAttribute('aria-expanded',String(opened))};sidebar.addEventListener('click',e=>{if(e.target.closest('.navitem')&&matchMedia('(max-width:720px)').matches)(sidebar.classList.remove('open'),document.querySelector('#sidebar-right').classList.remove('open'))});window.addEventListener('hashchange',()=>{const [w,p,accountId]=location.hash.slice(1).split('?')[0].split('/');go(w,p,{accountId,listingId:new URL(location.href).searchParams.get('kit-listing')})});Promise.all([import('/v2/cp-v2-auth.mjs'),import('/v2/cp-v2-access.mjs')]).then(([{startCPAuthentication},{accessibleCPMenu,workspacesForSurface}])=>startCPAuthentication(user=>{art.clan='https://cp.dunerealms.com/api/clan-emblems/member/'+encodeURIComponent(user.username);centralOrganisation=user.managementModel==='organisation-v2';menu.workspaces=workspacesForSurface(accessibleCPMenu(menu,user).workspaces,clanSurface);cpReady=true;portals.replaceChildren();for(const w of menu.workspaces){const b=el('button','portal');b.dataset.id=w.id;b.append(image(art[w.id]),el('span','',w.label));b.onclick=()=>go(w.id);portals.append(b)}if(!menu.workspaces.length){content.replaceChildren(el('p','cp-v2-news-status','No workspaces are available for this account.'));return;}const [initial,page,accountId]=location.hash.slice(1).split('?')[0].split('/');go(initial||(clanSurface?'clan':'realm'),page,{accountId,listingId:new URL(location.href).searchParams.get('kit-listing')});})).catch(error=>{content.textContent='Account access is temporarily unavailable: '+error.message}); + +// Finish the shared page pattern for retained adapters as they mount. +const headingObserver=new MutationObserver(()=>{const hero=content.querySelector(':scope > .hero');if(!hero)return;for(const host of content.querySelectorAll('.citizen-live-host')){for(const heading of host.querySelectorAll(':scope > .cp-v2-template-page > .cp-v2-template-heading')){const title=heading.querySelector('h3')?.textContent,copy=heading.querySelector('p')?.textContent,icon=heading.querySelector('img');if(title)hero.querySelector('h1').textContent=title;if(copy)hero.querySelector('p').textContent=copy;if(icon)hero.querySelector('img').src=icon.src;heading.remove();}for(const duplicate of host.closest('article.card')?.querySelectorAll(':scope > h2, :scope > .hint')||[])duplicate.remove();}});headingObserver.observe(content,{childList:true,subtree:true}); diff --git a/website/node/codex-consumables.mjs b/website/node/codex-consumables.mjs index cdaf0b1b..9fd52439 100644 --- a/website/node/codex-consumables.mjs +++ b/website/node/codex-consumables.mjs @@ -6,30 +6,30 @@ export async function initializeCodexConsumables(db){await db.query(CODEX_CONSUM // Internal foundation: no public issuance endpoint. Every definition supplies domain checks. export function createCodexConsumables(db,{proofs,definitions,edition,clock=Date.now}){ const types=new Map(Object.entries(definitions)); - for(const [id,d] of types)if(!/^[a-z][a-z0-9-]{0,63}$/.test(id)||!['authorizeIssue','authorizeUse','apply'].every(k=>typeof d[k]==='function'))throw TypeError('Incomplete Codex definition'); - const definition=id=>{const d=types.get(id);if(!d)throw Error('Unknown Codex definition');return d;}; + for(const [id,d] of types)if(!/^[a-z][a-z0-9-]{0,63}$/.test(id)||!['authorizeIssue','authorizeUse','apply'].every(k=>typeof d[k]==='function'))throw TypeError('Incomplete J.A.R.V.I.S. definition'); + const definition=id=>{const d=types.get(id);if(!d)throw Error('Unknown J.A.R.V.I.S. definition');return d;}; const output=row=>({id:row.id,definitionId:row.definition_id,state:row.state,edition:{stage:row.release_stage,version:row.release_version,season:row.season_id},proof:row.state==='available'?proofs.issue({instanceId:row.id,revision:Number(row.revision)}):null}); return Object.freeze({ async issue(actor,{definitionId,accountId,requestId}){ - if(!uuid(actor?.id)||!uuid(accountId)||!uuid(requestId))throw TypeError('Invalid Codex issuance'); + if(!uuid(actor?.id)||!uuid(accountId)||!uuid(requestId))throw TypeError('Invalid J.A.R.V.I.S. issuance'); const d=definition(definitionId),origin=validateCodeEdition(await edition()); return db.transaction(async tx=>{ await d.authorizeIssue(tx,actor,{accountId}); const prior=await tx.first('SELECT * FROM codex_consumable_instances WHERE issue_request_id=? FOR UPDATE',[requestId]); - if(prior){if(prior.account_id!==accountId||prior.definition_id!==definitionId||prior.environment_id!==proofs.environment||prior.issuer_id!==actor.id)throw Error('Codex request conflict');return output(prior);} + if(prior){if(prior.account_id!==accountId||prior.definition_id!==definitionId||prior.environment_id!==proofs.environment||prior.issuer_id!==actor.id)throw Error('J.A.R.V.I.S. request conflict');return output(prior);} const row={id:randomUUID(),definition_id:definitionId,account_id:accountId,release_stage:origin.stage,release_version:origin.version,season_id:origin.season,revision:1,state:'available'}; await tx.query('INSERT INTO codex_consumable_instances(id,definition_id,account_id,issuer_id,environment_id,issue_request_id,release_stage,release_version,season_id,created_at,revision,state) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)',[row.id,definitionId,accountId,actor.id,proofs.environment,requestId,origin.stage,origin.version,origin.season,clock(),1,'available']); return output(row); }); }, async use(actor,{proof,requestId}){ - if(!uuid(requestId))throw TypeError('Invalid Codex action');const identity=proofs.verify(proof); + if(!uuid(requestId))throw TypeError('Invalid J.A.R.V.I.S. action');const identity=proofs.verify(proof); return db.transaction(async tx=>{ const row=await tx.first('SELECT * FROM codex_consumable_instances WHERE id=? FOR UPDATE',[identity.instanceId]); - if(!row||row.environment_id!==identity.environment)throw Error('Codex instance unavailable'); + if(!row||row.environment_id!==identity.environment)throw Error('J.A.R.V.I.S. instance unavailable'); const d=definition(row.definition_id);await d.authorizeUse(tx,actor,{accountId:row.account_id,instanceId:row.id}); if(row.state==='used'&&row.use_request_id===requestId)return {id:row.id,replayed:true}; - if(row.state!=='available'||Number(row.revision)!==identity.revision)throw Error('Codex instance already used or changed'); + if(row.state!=='available'||Number(row.revision)!==identity.revision)throw Error('J.A.R.V.I.S. instance already used or changed'); // Handler writes must use tx; external delivery belongs in its durable outbox. await d.apply(tx,actor,{instanceId:row.id,accountId:row.account_id,requestId}); await tx.query("UPDATE codex_consumable_instances SET state='used',revision=revision+1,use_request_id=?,used_at=? WHERE id=?",[requestId,clock(),row.id]); @@ -37,4 +37,4 @@ export function createCodexConsumables(db,{proofs,definitions,edition,clock=Date }); } }); -} +} diff --git a/website/node/codex-equipment.mjs b/website/node/codex-equipment.mjs index f4bd5bbe..07c5c1a6 100644 --- a/website/node/codex-equipment.mjs +++ b/website/node/codex-equipment.mjs @@ -8,20 +8,20 @@ export const CODEX_EQUIPMENT_SCHEMA=`CREATE TABLE IF NOT EXISTS codex_equipment_ const rarities=new Set(['common','uncommon','rare','very_rare','legendary']); const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v); export function codexEquipmentMetadata({equipmentMark=1,rarity='common',enhancementPolicyVersion=null}={}){ - if(!Number.isInteger(equipmentMark)||equipmentMark<1||equipmentMark>14||!rarities.has(rarity)||enhancementPolicyVersion!==null&&(typeof enhancementPolicyVersion!=='string'||!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(enhancementPolicyVersion)))throw TypeError('Invalid Codex equipment metadata'); + if(!Number.isInteger(equipmentMark)||equipmentMark<1||equipmentMark>14||!rarities.has(rarity)||enhancementPolicyVersion!==null&&(typeof enhancementPolicyVersion!=='string'||!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(enhancementPolicyVersion)))throw TypeError('Invalid J.A.R.V.I.S. equipment metadata'); return {equipmentMark,rarity,enhancementPolicyVersion}; } export async function initializeCodexEquipment(db){await db.query(CODEX_EQUIPMENT_SCHEMA);} // Internal only: caller verifies the instance and domain authority, then uses its transaction. // Separate metadata avoids treating future physical equipment as a consumable entitlement. export async function insertCodexEquipment(tx,instanceId,metadata){ - if(!uuid(instanceId))throw TypeError('Invalid Codex instance');const value=codexEquipmentMetadata(metadata); + if(!uuid(instanceId))throw TypeError('Invalid J.A.R.V.I.S. instance');const value=codexEquipmentMetadata(metadata); await tx.query('INSERT INTO codex_equipment_metadata(instance_id,equipment_mark,rarity,enhancement_policy_version) VALUES(?,?,?,?)',[instanceId,value.equipmentMark,value.rarity,value.enhancementPolicyVersion]); return value; } export async function readCodexEquipment(db,instanceId,{nativeRarity='common'}={}){ - if(!uuid(instanceId)||!rarities.has(nativeRarity))throw TypeError('Invalid Codex equipment identity'); + if(!uuid(instanceId)||!rarities.has(nativeRarity))throw TypeError('Invalid J.A.R.V.I.S. equipment identity'); const [row]=await db.query('SELECT equipment_mark,rarity,enhancement_policy_version FROM codex_equipment_metadata WHERE instance_id=?',[instanceId]); // Legacy equipment defaults to MK I, retaining its existing rarity, without migration. return row?codexEquipmentMetadata({equipmentMark:Number(row.equipment_mark),rarity:row.rarity,enhancementPolicyVersion:row.enhancement_policy_version}):codexEquipmentMetadata({rarity:nativeRarity}); -} +} diff --git a/website/node/codex-proofs.mjs b/website/node/codex-proofs.mjs index a04dc4fa..1c8068d4 100644 --- a/website/node/codex-proofs.mjs +++ b/website/node/codex-proofs.mjs @@ -2,30 +2,30 @@ import {createHmac,timingSafeEqual} from 'node:crypto'; // Internal proof codec. Domain authority and atomic ledger consumption remain mandatory. export function createCodexProofs({environment,activeKeyId,keys}) { - if(!/^[a-z0-9-]{1,48}$/.test(environment||''))throw TypeError('Invalid Codex environment'); + if(!/^[a-z0-9-]{1,48}$/.test(environment||''))throw TypeError('Invalid J.A.R.V.I.S. environment'); const ring=new Map(Object.entries(keys||{}).map(([id,key])=>{ - if(!/^[A-Za-z0-9_-]{1,48}$/.test(id)||typeof key!=='string'||!/^[a-f0-9]{64}$/i.test(key))throw TypeError('Invalid Codex signing key'); + if(!/^[A-Za-z0-9_-]{1,48}$/.test(id)||typeof key!=='string'||!/^[a-f0-9]{64}$/i.test(key))throw TypeError('Invalid J.A.R.V.I.S. signing key'); return [id,Buffer.from(key,'hex')]; })); - if(!ring.has(activeKeyId))throw TypeError('Active Codex signing key unavailable'); + if(!ring.has(activeKeyId))throw TypeError('Active J.A.R.V.I.S. signing key unavailable'); const valid=p=>p&&p.v===1&&p.environment===environment&&typeof p.instanceId==='string'&&/^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i.test(p.instanceId)&&Number.isSafeInteger(p.revision)&&p.revision>=1; const signature=(key,body)=>createHmac('sha256',key).update('dunerealms:codex:proof:v1\0').update(body).digest(); return Object.freeze({ environment, issue({instanceId,revision}) { - const p={v:1,environment,instanceId,revision};if(!valid(p))throw TypeError('Invalid Codex instance identity'); + const p={v:1,environment,instanceId,revision};if(!valid(p))throw TypeError('Invalid J.A.R.V.I.S. instance identity'); const body=Buffer.from(JSON.stringify(p)).toString('base64url'); return `${activeKeyId}.${body}.${signature(ring.get(activeKeyId),body).toString('base64url')}`; }, verify(proof) { - if(typeof proof!=='string'||proof.length>1024)throw Error('Invalid Codex proof'); - const parts=proof.split('.');if(parts.length!==3||parts.some(x=>!x||!/^[A-Za-z0-9_-]+$/.test(x)))throw Error('Invalid Codex proof'); - const [keyId,body,mac]=parts,key=ring.get(keyId);if(!key)throw Error('Unknown Codex signing key'); + if(typeof proof!=='string'||proof.length>1024)throw Error('Invalid J.A.R.V.I.S. proof'); + const parts=proof.split('.');if(parts.length!==3||parts.some(x=>!x||!/^[A-Za-z0-9_-]+$/.test(x)))throw Error('Invalid J.A.R.V.I.S. proof'); + const [keyId,body,mac]=parts,key=ring.get(keyId);if(!key)throw Error('Unknown J.A.R.V.I.S. signing key'); const received=Buffer.from(mac,'base64url'),expected=signature(key,body); - if(received.length!==expected.length||!timingSafeEqual(received,expected))throw Error('Invalid Codex proof'); - let p;try{p=JSON.parse(Buffer.from(body,'base64url').toString('utf8'));}catch{throw Error('Invalid Codex proof');} - if(!valid(p)||Object.keys(p).sort().join(',')!=='environment,instanceId,revision,v')throw Error('Invalid Codex proof'); + if(received.length!==expected.length||!timingSafeEqual(received,expected))throw Error('Invalid J.A.R.V.I.S. proof'); + let p;try{p=JSON.parse(Buffer.from(body,'base64url').toString('utf8'));}catch{throw Error('Invalid J.A.R.V.I.S. proof');} + if(!valid(p)||Object.keys(p).sort().join(',')!=='environment,instanceId,revision,v')throw Error('Invalid J.A.R.V.I.S. proof'); return Object.freeze({...p,keyId}); } }); -} +} diff --git a/website/node/postbank-api.mjs b/website/node/postbank-api.mjs index c7710544..f9b60c36 100644 --- a/website/node/postbank-api.mjs +++ b/website/node/postbank-api.mjs @@ -1,250 +1,250 @@ -import {canInspectAllBankAccounts} from './postbank-recipient-policy.mjs'; -import {randomUUID} from 'node:crypto'; -import {PostbankPayroll} from './postbank-payroll.mjs'; -import {PostbankPayrollCycle} from './postbank-payroll-cycle.mjs'; -import {PostbankFinancialPolicies} from './postbank-financial-policy.mjs'; -import {PostbankRatePublications} from './postbank-rate-publications.mjs'; -import {PostbankClientManagement} from './postbank-client-management.mjs'; -import {PostbankCompensation} from './postbank-compensation.mjs'; -import {PostbankStandingInstructions} from './postbank-standing-instructions.mjs'; -import {CentralScheduler} from './central-scheduler.mjs'; -import {canRunScheduler} from './scheduler-authority.mjs'; -import {createPostbankTasks} from './postbank-payments.mjs'; -import {PostbankTransferSecurity} from './postbank-transfer-security.mjs'; -import {PostbankCreditEngine} from './postbank-credit-engine.mjs'; -import {PostbankAuthorisations} from './postbank-authorisations.mjs'; -import {createReserveLedger} from './postbank-reserve-ledger.mjs'; -import {PostbankCredit} from './postbank-credit.mjs'; -import {reconcilePostbankClans} from './postbank-registry.mjs'; -import {PostbankStatementArchive,statementSettings} from './postbank-statement-archive.mjs'; -import {PostbankBeneficiaries} from './postbank-beneficiaries.mjs'; -import {PostbankAdmin,RESERVE_OWNER_ID} from './postbank-admin.mjs'; -import {createPostbankPayments,standardCycle} from './postbank-payments.mjs'; -import {identity} from './auth.mjs'; -import {PostbankService} from './postbank-service.mjs'; -import {createPostbankAuthority} from './postbank-authority.mjs'; -import {POSTBANK_CONTRACTS} from './postbank-contract.mjs'; -export function createPostbankApi(central,bank,settings={},deps={}){ - const auth=deps.authenticate||(request=>identity(request,central)),authority=deps.authority||createPostbankAuthority(central,{bank}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com'; - const service=bank?new PostbankService(bank,authority,deps):null,payments=createPostbankPayments(central,bank,{...deps,authority}); - const credit=bank?new PostbankCredit(bank,authority,{...deps,central}):null; - const creditEnabled=settings.POSTBANK_CREDIT_ENABLED==='true',creditEngine=bank?new PostbankCreditEngine(bank,central,authority,deps):null; - const scheduler=bank?new CentralScheduler(bank,deps.scheduledTasks||createPostbankTasks(central,bank,settings,deps),deps):null; - const payroll=bank?new PostbankPayroll(central,bank,deps):null,financialPolicies=bank?new PostbankFinancialPolicies(bank,central,authority,deps):null; - const payrollCycle=bank?new PostbankPayrollCycle(central,bank,deps):null; - const transferSecurity=bank?new PostbankTransferSecurity(bank,central,deps):null; - const admin=bank?new PostbankAdmin(bank,central,authority,deps):null; - const clients=bank?new PostbankClientManagement(bank,authority,deps):null; - const compensation=bank?new PostbankCompensation(bank,authority,deps):null,standing=bank?new PostbankStandingInstructions(bank,authority,deps):null; - const beneficiaries=bank?new PostbankBeneficiaries(bank,{...deps,canInspectAll:deps.canInspectAll||(user=>canInspectAllBankAccounts(central,user))}):null; - const statements=bank?new PostbankStatementArchive(bank,payments,{...deps,...statementSettings(settings)}):null; - const reserveLedger=createReserveLedger(bank,deps); - const rates=bank?new PostbankRatePublications(bank,{...deps,python:settings.POSTBANK_PYTHON,logo:settings.POSTBANK_STATEMENT_LOGO}):null; - const authorisations=bank?new PostbankAuthorisations(bank,central,authority,deps):null; - const lookups=new Map(),transferAttempts=new Map(); - const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}}); - return async request=>{ - const url=new URL(request.url),path=url.pathname; - if(path==='/api/bank/public/reserve-ledger')return reserveLedger(request); - if(['/api/bank/public/rates','/api/bank/public/rates.pdf'].includes(path))return rates?rates.publicResponse(request):Response.json({message:'The public tariff register is being prepared.'},{status:503,headers:{'Access-Control-Allow-Origin':'*','Cache-Control':'no-store'}}); - const user=await auth(request);if(!user)return reply({message:'Sign in to use Imperial Postbank.'},401); - if(!service)return reply({message:'The independent bank database is not linked yet.',state:'not_linked'},503); - try{await reconcilePostbankClans(central,bank);}catch{return reply({message:'The bank could not verify the current organisation registry. Please retry shortly.'},503);} - if(!['/api/bank/recipients','/api/bank/activity','/api/bank/statements','/api/bank/statements/archive','/api/bank/authorisations','/api/bank/authorisations/lookup','/api/bank/credit/details'].includes(path)&&!path.startsWith('/api/bank/admin/')&&url.search)return reply({message:'Banking identity and account overrides are not accepted.'},400); - if(path==='/api/bank/transfer-security'){ - try{ - if(request.method==='GET')return reply(await transferSecurity.settings(user)); - if(request.method!=='POST')return reply({message:'Method not allowed.'},405); - if(request.headers.get('origin')!==origin)return reply({message:'Origin rejected.'},403); - if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); - const raw=await request.text();if(raw.length>3000)return reply({message:'Request too large.'},413); - let body;try{body=JSON.parse(raw);}catch{return reply({message:'Invalid security settings.'},400);} - return reply(await transferSecurity.save(user,body,{revalidate:()=>auth(request)})); - }catch(error){return reply({message:error.status?error.message:'Payment security could not be confirmed. Reload before retrying.'},error.status||503);} - } - if(path==='/api/bank/statements/archive'){ - if(request.method!=='GET')return reply({message:'Method not allowed.'},405); - if([...url.searchParams.keys()].some(k=>!['accountId','page'].includes(k))||url.searchParams.getAll('accountId').length!==1||url.searchParams.getAll('page').length>1)return reply({message:'Select an archive account.'},400); - try{const accountId=url.searchParams.get('accountId'),data=await statements.list(user,{accountId,page:url.searchParams.get('page')||1}),fresh=await auth(request);if(!fresh||fresh.id!==user.id||!(await payments.accounts(fresh)).some(a=>a.id===accountId))return reply({message:'Your account access changed.'},403);return reply(data);}catch(error){return reply({message:error.status?error.message:'The statement archive could not be loaded.'},error.status||503);} - } - if(path==='/api/bank/statements'){ - if(request.method!=='GET')return reply({message:'Method not allowed.'},405); - if([...url.searchParams.keys()].some(k=>!['accountId','month'].includes(k))||['accountId','month'].some(k=>url.searchParams.getAll(k).length!==1))return reply({message:'Choose one account and month.'},400); - try{const accountId=url.searchParams.get('accountId'),result=await statements.download(user,{accountId,month:url.searchParams.get('month')}),fresh=await auth(request); - if(!fresh||fresh.id!==user.id||!(await payments.accounts(fresh)).some(a=>a.id===accountId))return reply({message:'Your account access changed. Reload the workspace.'},403); - return new Response(result.pdf,{headers:{'Content-Type':'application/pdf','Content-Disposition':'attachment; filename="'+result.filename+'"','Cache-Control':'private, no-store',Vary:'Cookie','X-Content-Type-Options':'nosniff'}}); - }catch(error){return reply({message:error.status?error.message:'Your archived statement could not be downloaded. Please retry shortly.'},error.status||503);} - } - if(path==='/api/bank/beneficiaries'&&request.method==='GET'){ - try{const data=await beneficiaries.list(user),fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed. Reload the workspace.'},403);return reply(data);}catch{return reply({message:'Saved beneficiaries could not be confirmed.'},503);} - } - if(['/api/bank/beneficiaries/save','/api/bank/beneficiaries/remove'].includes(path)){ - if(request.method!=='POST')return reply({message:'Method not allowed.'},405); - if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403); - if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); - const raw=await request.text();if(raw.length>2000)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the beneficiary form.'},400);} - try{return reply(await beneficiaries.write(user,input,path.endsWith('/remove'),{revalidate:()=>auth(request)}));}catch(error){return reply({message:error.status?error.message:'The beneficiary change was not confirmed. Reload the list before retrying.'},error.status||503);} - } - if(path.startsWith('/api/bank/credit/')){ - try{ - if(path==='/api/bank/credit/overview'&&request.method==='GET'){ - if(url.search)return reply({message:'Account overrides are not accepted.'},400); - const fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403); - // Rebuild with fresh authority so a revoked organisational scope cannot leak records. - return reply({...await credit.overview(fresh),intakeEnabled:creditEnabled}); - } - if(path==='/api/bank/credit/details'&&request.method==='GET'){ - if([...url.searchParams.keys()].some(k=>k!=='loanId')||url.searchParams.getAll('loanId').length!==1)return reply({message:'Choose one credit contract.'},400);const fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403);return reply(await credit.details(fresh,url.searchParams.get('loanId'))); - } - if(!['/api/bank/credit/simulate','/api/bank/credit/apply','/api/bank/credit/action'].includes(path))return reply({message:'Credit route not found.'},404); - if(request.method!=='POST')return reply({message:'Method not allowed.'},405); - if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403); - if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); - if(url.search)return reply({message:'Account overrides are not accepted.'},400); - const raw=await request.text();if(raw.length>7000)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the credit form.'},400);} - if(!path.endsWith('/simulate')&&!creditEnabled)return reply({message:'Credit application intake is not open yet. No application or payment was made.',state:'not_active'},409); - const fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403); - if(path.endsWith('/apply')){const result=await credit.apply(fresh,input,{revalidate:()=>auth(request)});return reply(result);} - if(path.endsWith('/action')){const options={revalidate:()=>auth(request)};if(input.action==='accept')return reply(await creditEngine.accept(fresh,input,options));if(input.action==='withdraw')return reply(await creditEngine.decision(fresh,input,options));if(input.action==='repay')return reply(await creditEngine.requestRepayment(fresh,input,options));return reply({message:'Unknown credit action.'},400);} - return reply(await credit.simulate(fresh,input)); - }catch(error){return reply({message:error.status?error.message:'The credit operation could not be confirmed.'},error.status||503);} - } - if(path==='/api/bank/admin/credit/details'){ - if(request.method!=='GET')return reply({message:'Method not allowed.'},405);if([...url.searchParams.keys()].some(k=>k!=='loanId')||url.searchParams.getAll('loanId').length!==1)return reply({message:'Choose one credit contract.'},400); - try{const fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403);return reply(await credit.details(fresh,url.searchParams.get('loanId'),true));}catch(error){return reply({message:error.status?error.message:'Credit details could not be confirmed.'},error.status||503);} - } - if(['/api/bank/admin/credit/decision','/api/bank/admin/credit/recover'].includes(path)){ - if(request.method!=='POST')return reply({message:'Method not allowed.'},405);if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403);if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);if(url.search)return reply({message:'Account overrides are not accepted.'},400);if(!creditEnabled)return reply({message:'Credit processing is not active.'},409); - try{const raw=await request.text();if(raw.length>2500)return reply({message:'Request too large.'},413);const input=JSON.parse(raw),fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403);if(!(await authority(fresh)).manageAdmin)return reply({message:'Bank management permission is required.'},403);const recovery=path.endsWith('/recover');if(recovery?input.action!=='recover':!['approve','decline'].includes(input.action))return reply({message:'Unknown staff credit action.'},400);const result=await (recovery?creditEngine.requestRepayment(fresh,input,{revalidate:()=>auth(request)}):creditEngine.decision(fresh,input,{revalidate:()=>auth(request)}));if(!recovery)return reply({...result,notice:input.action==='approve'?'Approval recorded in the Codex dossier. The borrower must accept the offer before payment at a four-hour bank window.':'Rejection recorded in the Codex dossier.'});return reply(result);}catch(error){return reply({message:error.status?error.message:'The credit instruction could not be confirmed.'},error.status||503);} - } - if(['/api/bank/authorisations','/api/bank/authorisations/lookup','/api/bank/authorisations/change','/api/bank/admin/authorisations','/api/bank/admin/authorisations/lookup','/api/bank/admin/authorisations/change'].includes(path)){ - const staff=path.startsWith('/api/bank/admin/'); - try{ - if(request.method==='GET'&&!path.endsWith('/change')){ - const lookup=path.endsWith('/lookup'),allowed=lookup?['q','kind']:['q','accountId'];if([...url.searchParams.keys()].some(k=>!allowed.includes(k)||url.searchParams.getAll(k).length!==1))return reply({message:'Invalid authorisation filters.'},400); - const fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403);return reply(lookup?await authorisations.lookup(fresh,url.searchParams.get('q'),url.searchParams.get('kind')||'user',staff):await authorisations.list(fresh,staff,Object.fromEntries(url.searchParams))); - } - if(request.method!=='POST'||!path.endsWith('/change'))return reply({message:'Method not allowed.'},405); - if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403);if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);if(url.search)return reply({message:'Account overrides are not accepted.'},400);const raw=await request.text();if(raw.length>3000)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the authorisation form.'},400);}return reply(await authorisations.write(user,input,staff,{revalidate:()=>auth(request)})); - }catch(error){return reply({message:error.status?error.message:'The authorisation change could not be confirmed.'},error.status||503);} - } - if(['/api/bank/admin/payroll','/api/bank/admin/payroll/run'].includes(path)){ - try{ - if(url.search)return reply({message:'Payroll overrides are not accepted.'},400); - const fresh=await auth(request);if(!fresh||fresh.id!==user.id||!await canRunScheduler(central,fresh))return reply({message:'P&O payroll management is reserved for the Big Four.'},403); - if(request.method==='GET'&&!path.endsWith('/run')){const result={...await payroll.overview(),cycle:await payrollCycle.preview(),additionalCycle:await payrollCycle.previewAdditional()},current=await auth(request);if(!current||current.id!==user.id||!await canRunScheduler(central,current))return reply({message:'Payroll access changed.'},403);return reply(result);} - if(request.method!=='POST')return reply({message:'Method not allowed.'},405); - if(request.headers.get('origin')!==origin)return reply({message:'Origin rejected.'},403); - if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); - const raw=await request.text();if(raw.length>4000)return reply({message:'Request too large.'},413); - let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the payroll settings.'},400);} - if(path.endsWith('/run'))return reply(await payrollCycle.run(fresh,input,{revalidate:()=>auth(request)})); - return reply(await financialPolicies.save(fresh,'payroll',input,{revalidate:()=>auth(request)})); - }catch(error){return reply({message:error.status?error.message:'Payroll could not be confirmed. Reload before retrying.'},error.status||503);} - } - if(['/api/bank/admin/scheduler','/api/bank/admin/scheduler/run'].includes(path)){ - try{ - if(url.search)return reply({message:'Scheduler overrides are not accepted.'},400); - const fresh=await auth(request);if(!fresh||fresh.id!==user.id||!await canRunScheduler(central,fresh))return reply({message:'Only the Big Four may run the central scheduler.'},403); - if(path.endsWith('/run')){ - if(request.method!=='POST')return reply({message:'Method not allowed.'},405); - if(request.headers.get('origin')!==origin)return reply({message:'Origin rejected.'},403); - if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); - const raw=await request.text();if(raw.length>300)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Confirm the scheduler run.'},400);} - if(!input||input.confirmed!==true||Object.keys(input).some(k=>k!=='confirmed'))return reply({message:'Confirm running due tasks. Future dates cannot be forced.'},400); - const auditId=randomUUID();await bank.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[auditId,fresh.id,'central_scheduler_run',null,JSON.stringify({state:'started',recheckAll:true}),Date.now()]);const result=await scheduler.runDue({recheck:true,beforeTask:async()=>{const current=await auth(request);if(!current||current.id!==fresh.id||!await canRunScheduler(central,current))throw Error('Scheduler access changed');}});await bank.query('UPDATE pb_audit SET details=? WHERE id=?',[JSON.stringify({state:'completed',recheckAll:true,...result}),auditId]);return reply(result); - } - if(request.method!=='GET')return reply({message:'Method not allowed.'},405);return reply({tasks:await scheduler.status()}); - }catch{return reply({message:'The scheduler result could not be confirmed. Reload its status before retrying.'},503);} - } - if(path.startsWith('/api/bank/admin/')){ - try{ - if(['/api/bank/admin/compensation','/api/bank/admin/compensation/pay','/api/bank/admin/standing-instructions'].includes(path)){ - if(url.search)return reply({message:'No account overrides are accepted.'},400); - if(request.method==='GET'&&!path.endsWith('/pay')){const result=path.endsWith('/compensation')?await compensation.overview(user):await standing.overview(user),fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403);await (path.endsWith('/compensation')?compensation.access(fresh):standing.access(fresh));return reply(result);} - if(request.method!=='POST'||path.endsWith('/compensation'))return reply({message:'Method not allowed.'},405); - if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403); - if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); - const raw=await request.text();if(raw.length>2500)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the bank instruction.'},400);} - return reply(await (path.endsWith('/pay')?compensation.pay(user,input,{revalidate:()=>auth(request)}):standing.save(user,input,{revalidate:()=>auth(request)}))); - } - if(['/api/bank/admin/client','/api/bank/admin/client/package','/api/bank/admin/client/options'].includes(path)){ - if(path.endsWith('/client')){ - if(request.method!=='GET')return reply({message:'Method not allowed.'},405); - if([...url.searchParams.keys()].some(k=>k!=='entityId')||url.searchParams.getAll('entityId').length!==1)return reply({message:'Select one banking client.'},400); - const result=await clients.detail(user,url.searchParams.get('entityId')),fresh=await auth(request); - if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403); - const latest=await clients.scope(fresh,url.searchParams.get('entityId'));result.canManage=latest.canManage;return reply(result); - } - if(request.method!=='POST')return reply({message:'Method not allowed.'},405); - if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403); - if(url.search)return reply({message:'Account overrides are not accepted.'},400); - if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); - const raw=await request.text();if(raw.length>3000)return reply({message:'Request too large.'},413); - let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the client management form.'},400);} - return reply(await clients.change(user,input,path.endsWith('/package')?'package':'options',{revalidate:()=>auth(request)})); - } - if(['/api/bank/admin/transfers/cancel','/api/bank/admin/treasuries/transfer','/api/bank/admin/reserve/grants','/api/bank/admin/taxes/payments'].includes(path)){ - if(request.method!=='POST')return reply({message:'Method not allowed.'},405); - if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403); - if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); - if(url.search)return reply({message:'Account overrides are not accepted.'},400);const raw=await request.text();if(raw.length>2000)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the cancellation form.'},400);} - return reply(await (path.endsWith('/cancel')?admin.cancel(user,input,{revalidate:()=>auth(request)}):path.endsWith('/grants')?admin.issueGrant(user,input,{revalidate:()=>auth(request)}):path.endsWith('/taxes/payments')?admin.taxPayment(user,input,{revalidate:()=>auth(request)}):admin.treasuryTransfer(user,input,{revalidate:()=>auth(request)}))); - } - if(request.method!=='GET')return reply({message:'Method not allowed.'},405); - const permitted=path==='/api/bank/admin/credit'?['loanId']:path.endsWith('/taxes/recipients')?['q']:path.endsWith('/overview')?[]:path.endsWith('/accounts')?['entityId']:path.endsWith('/activity')?['accountId','page']:['q','kind','page'];if([...url.searchParams.keys()].some(k=>!permitted.includes(k)||url.searchParams.getAll(k).length!==1))return reply({message:'Invalid bank administration filter.'},400); - const input=Object.fromEntries(url.searchParams);let result; - if(path==='/api/bank/admin/overview')result=await admin.overview(user); - else if(path==='/api/bank/admin/entities')result=await admin.entities(user,input); - else if(path==='/api/bank/admin/corporate')result=await admin.entities(user,input,true); - else if(path==='/api/bank/admin/taxes/overview')result=await admin.taxOverview(user); - else if(path==='/api/bank/admin/taxes/recipients')result=await admin.taxRecipients(user,input.q); - else if(path==='/api/bank/admin/treasuries')result=await admin.treasuries(user,input); - else if(path==='/api/bank/admin/credit')result={...await credit.staff(user,input),processing:creditEnabled?'active':'not_active'}; - else if(path==='/api/bank/admin/accounts')result=await admin.accounts(user,input.entityId); - else if(path==='/api/bank/admin/activity')result=await admin.activity(user,input); - else if(path==='/api/bank/admin/audit')result=await admin.audit(user,input); - else if(path==='/api/bank/admin/pending')result=await admin.pending(user,input); - else return reply({message:'Bank administration route not found.'},404); - const fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed. Reload the bank workspace.'},403);const rights=await admin.access(fresh);if(result.permissions){try{result.permissions.canRunScheduler=await canRunScheduler(central,fresh);}catch{result.permissions.canRunScheduler=false;}result.permissions.canManage=rights.manageAdmin;result.permissions.canCompensate=!!(rights.manageAdmin||rights.manageClients);result.permissions.canIssueReserve=fresh.id===RESERVE_OWNER_ID&&!!rights.manageAdmin;}if('canManage' in result)result.canManage=rights.manageAdmin; - return reply(result); - }catch(error){return reply({message:error.status?error.message:'The bank could not confirm the administrative operation.'},error.status||503);} - } - if(request.method==='GET'&&['/api/bank/overview','/api/bank/client','/api/bank/accounts'].includes(path)){ - try{return reply(await service.overview(user));}catch{return reply({message:'The bank could not confirm the current records. Reload the workspace.'},503);} - } - if(request.method==='GET'&&['/api/bank/transfer-options','/api/bank/recipients','/api/bank/activity'].includes(path)){ - try{ - if(path==='/api/bank/transfer-options')return reply({accounts:await payments.accounts(user),beneficiaries:(await beneficiaries.list(user)).beneficiaries,actorId:user.id,security:await transferSecurity.settings(user),standard:{state:'active',processing:'Standard payments are processed in batches every four hours: 00:00, 04:00, 08:00, 12:00, 16:00 and 20:00 Europe/Brussels.',nextAt:standardCycle().nextAt},fees:{state:'planned',message:'Transfer fees are not currently being charged.'}}); - if(path==='/api/bank/recipients'){ - if([...url.searchParams.keys()].some(k=>!['q','page'].includes(k))||url.searchParams.getAll('q').length!==1||url.searchParams.getAll('page').length>1)return reply({message:'Use the recipient search and page fields.'},400); - const now=Date.now();for(const [key,value]of lookups)if(value.until10000)return reply({message:'Recipient lookup is busy. Try shortly.'},429); - const value=lookups.get(user.id)||{until:now+60000,count:0};value.count++;lookups.set(user.id,value);if(value.count>20)return reply({message:'Too many recipient searches. Try again in one minute.'},429); - const rawPage=url.searchParams.get('page')||'1';if(!/^[1-9]\d{0,3}$/.test(rawPage))return reply({message:'Choose a valid beneficiary page.'},400); - const result=await payments.recipientPage(user,url.searchParams.get('q'),{page:Number(rawPage)}),fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed. Search again.'},403);return reply(result); - } - if([...url.searchParams.keys()].some(k=>!['accountId','page','q','state','from','to'].includes(k))||url.searchParams.getAll('accountId').length>1||['page','q','state','from','to'].some(k=>url.searchParams.getAll(k).length>1))return reply({message:'Invalid statement filter.'},400); - const raw=url.searchParams.get('page')||'1';if(!/^[1-9]\d{0,3}$/.test(raw))return reply({message:'Choose a valid statement page.'},400); - return reply(await payments.activity(user,{accountId:url.searchParams.get('accountId'),page:Number(raw),...Object.fromEntries(['q','state','from','to'].map(k=>[k,url.searchParams.get(k)||'']))})); - }catch(error){return reply({message:error.status?error.message:'The bank could not confirm the requested records.'},error.status||503);} - } - if(path==='/api/bank/transfers'){ - if(request.method!=='POST')return reply({message:'Method not allowed.'},405); - if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403); - if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); - const now=Date.now();for(const [key,value]of transferAttempts)if(value.until10||transferAttempts.size>10000)return reply({message:'Too many payment attempts. Keep the same payment reference and try again in one minute.'},429); - const raw=await request.text();if(raw.length>3000)return reply({message:'Request too large.'},413);let body;try{body=JSON.parse(raw);}catch{return reply({message:'Complete the transfer form.'},400);} - try{return reply(await payments.transfer(user,body,{revalidate:()=>auth(request)}));}catch(error){return reply({message:error.status?error.message:'The transfer result could not be confirmed. Keep the same payment reference when retrying.'},error.status||503);} - } - if(path==='/api/bank/contracts'&&request.method==='GET')return reply({contracts:{...POSTBANK_CONTRACTS,loans:{...POSTBANK_CONTRACTS.loans,state:creditEnabled?'active':'prepared'}}}); - if(['/api/bank/activate','/api/bank/packages/change','/api/bank/accounts/options'].includes(path)){ - if(request.method!=='POST')return reply({message:'Method not allowed.'},405); - if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403); - if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); - const text=await request.text();if(text.length>3000)return reply({message:'Request too large.'},413); - let body;try{body=JSON.parse(text);}catch{return reply({message:'Select your package again.'},400);} - try{return reply(await (path==='/api/bank/activate'?service.activate(user,body,{revalidate:()=>auth(request)}):path==='/api/bank/packages/change'?service.changePackage(user,body,{revalidate:()=>auth(request)}):service.setAccountOptions(user,body,{revalidate:()=>auth(request)})));}catch(error){return reply({message:error.status?error.message:'The package operation was not confirmed. Reload the current records before trying again.',returnTo:'package_selection'},error.status||503);} - } - return reply({message:'This bank function is not implemented yet. No request was forwarded to the old game bank.',state:'planned'},501); - }; -} +import {canInspectAllBankAccounts} from './postbank-recipient-policy.mjs'; +import {randomUUID} from 'node:crypto'; +import {PostbankPayroll} from './postbank-payroll.mjs'; +import {PostbankPayrollCycle} from './postbank-payroll-cycle.mjs'; +import {PostbankFinancialPolicies} from './postbank-financial-policy.mjs'; +import {PostbankRatePublications} from './postbank-rate-publications.mjs'; +import {PostbankClientManagement} from './postbank-client-management.mjs'; +import {PostbankCompensation} from './postbank-compensation.mjs'; +import {PostbankStandingInstructions} from './postbank-standing-instructions.mjs'; +import {CentralScheduler} from './central-scheduler.mjs'; +import {canRunScheduler} from './scheduler-authority.mjs'; +import {createPostbankTasks} from './postbank-payments.mjs'; +import {PostbankTransferSecurity} from './postbank-transfer-security.mjs'; +import {PostbankCreditEngine} from './postbank-credit-engine.mjs'; +import {PostbankAuthorisations} from './postbank-authorisations.mjs'; +import {createReserveLedger} from './postbank-reserve-ledger.mjs'; +import {PostbankCredit} from './postbank-credit.mjs'; +import {reconcilePostbankClans} from './postbank-registry.mjs'; +import {PostbankStatementArchive,statementSettings} from './postbank-statement-archive.mjs'; +import {PostbankBeneficiaries} from './postbank-beneficiaries.mjs'; +import {PostbankAdmin,RESERVE_OWNER_ID} from './postbank-admin.mjs'; +import {createPostbankPayments,standardCycle} from './postbank-payments.mjs'; +import {identity} from './auth.mjs'; +import {PostbankService} from './postbank-service.mjs'; +import {createPostbankAuthority} from './postbank-authority.mjs'; +import {POSTBANK_CONTRACTS} from './postbank-contract.mjs'; +export function createPostbankApi(central,bank,settings={},deps={}){ + const auth=deps.authenticate||(request=>identity(request,central)),authority=deps.authority||createPostbankAuthority(central,{bank}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com'; + const service=bank?new PostbankService(bank,authority,deps):null,payments=createPostbankPayments(central,bank,{...deps,authority}); + const credit=bank?new PostbankCredit(bank,authority,{...deps,central}):null; + const creditEnabled=settings.POSTBANK_CREDIT_ENABLED==='true',creditEngine=bank?new PostbankCreditEngine(bank,central,authority,deps):null; + const scheduler=bank?new CentralScheduler(bank,deps.scheduledTasks||createPostbankTasks(central,bank,settings,deps),deps):null; + const payroll=bank?new PostbankPayroll(central,bank,deps):null,financialPolicies=bank?new PostbankFinancialPolicies(bank,central,authority,deps):null; + const payrollCycle=bank?new PostbankPayrollCycle(central,bank,deps):null; + const transferSecurity=bank?new PostbankTransferSecurity(bank,central,deps):null; + const admin=bank?new PostbankAdmin(bank,central,authority,deps):null; + const clients=bank?new PostbankClientManagement(bank,authority,deps):null; + const compensation=bank?new PostbankCompensation(bank,authority,deps):null,standing=bank?new PostbankStandingInstructions(bank,authority,deps):null; + const beneficiaries=bank?new PostbankBeneficiaries(bank,{...deps,canInspectAll:deps.canInspectAll||(user=>canInspectAllBankAccounts(central,user))}):null; + const statements=bank?new PostbankStatementArchive(bank,payments,{...deps,...statementSettings(settings)}):null; + const reserveLedger=createReserveLedger(bank,deps); + const rates=bank?new PostbankRatePublications(bank,{...deps,python:settings.POSTBANK_PYTHON,logo:settings.POSTBANK_STATEMENT_LOGO}):null; + const authorisations=bank?new PostbankAuthorisations(bank,central,authority,deps):null; + const lookups=new Map(),transferAttempts=new Map(); + const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}}); + return async request=>{ + const url=new URL(request.url),path=url.pathname; + if(path==='/api/bank/public/reserve-ledger')return reserveLedger(request); + if(['/api/bank/public/rates','/api/bank/public/rates.pdf'].includes(path))return rates?rates.publicResponse(request):Response.json({message:'The public tariff register is being prepared.'},{status:503,headers:{'Access-Control-Allow-Origin':'*','Cache-Control':'no-store'}}); + const user=await auth(request);if(!user)return reply({message:'Sign in to use Imperial Postbank.'},401); + if(!service)return reply({message:'The independent bank database is not linked yet.',state:'not_linked'},503); + try{await reconcilePostbankClans(central,bank);}catch{return reply({message:'The bank could not verify the current organisation registry. Please retry shortly.'},503);} + if(!['/api/bank/recipients','/api/bank/activity','/api/bank/statements','/api/bank/statements/archive','/api/bank/authorisations','/api/bank/authorisations/lookup','/api/bank/credit/details'].includes(path)&&!path.startsWith('/api/bank/admin/')&&url.search)return reply({message:'Banking identity and account overrides are not accepted.'},400); + if(path==='/api/bank/transfer-security'){ + try{ + if(request.method==='GET')return reply(await transferSecurity.settings(user)); + if(request.method!=='POST')return reply({message:'Method not allowed.'},405); + if(request.headers.get('origin')!==origin)return reply({message:'Origin rejected.'},403); + if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); + const raw=await request.text();if(raw.length>3000)return reply({message:'Request too large.'},413); + let body;try{body=JSON.parse(raw);}catch{return reply({message:'Invalid security settings.'},400);} + return reply(await transferSecurity.save(user,body,{revalidate:()=>auth(request)})); + }catch(error){return reply({message:error.status?error.message:'Payment security could not be confirmed. Reload before retrying.'},error.status||503);} + } + if(path==='/api/bank/statements/archive'){ + if(request.method!=='GET')return reply({message:'Method not allowed.'},405); + if([...url.searchParams.keys()].some(k=>!['accountId','page'].includes(k))||url.searchParams.getAll('accountId').length!==1||url.searchParams.getAll('page').length>1)return reply({message:'Select an archive account.'},400); + try{const accountId=url.searchParams.get('accountId'),data=await statements.list(user,{accountId,page:url.searchParams.get('page')||1}),fresh=await auth(request);if(!fresh||fresh.id!==user.id||!(await payments.accounts(fresh)).some(a=>a.id===accountId))return reply({message:'Your account access changed.'},403);return reply(data);}catch(error){return reply({message:error.status?error.message:'The statement archive could not be loaded.'},error.status||503);} + } + if(path==='/api/bank/statements'){ + if(request.method!=='GET')return reply({message:'Method not allowed.'},405); + if([...url.searchParams.keys()].some(k=>!['accountId','month'].includes(k))||['accountId','month'].some(k=>url.searchParams.getAll(k).length!==1))return reply({message:'Choose one account and month.'},400); + try{const accountId=url.searchParams.get('accountId'),result=await statements.download(user,{accountId,month:url.searchParams.get('month')}),fresh=await auth(request); + if(!fresh||fresh.id!==user.id||!(await payments.accounts(fresh)).some(a=>a.id===accountId))return reply({message:'Your account access changed. Reload the workspace.'},403); + return new Response(result.pdf,{headers:{'Content-Type':'application/pdf','Content-Disposition':'attachment; filename="'+result.filename+'"','Cache-Control':'private, no-store',Vary:'Cookie','X-Content-Type-Options':'nosniff'}}); + }catch(error){return reply({message:error.status?error.message:'Your archived statement could not be downloaded. Please retry shortly.'},error.status||503);} + } + if(path==='/api/bank/beneficiaries'&&request.method==='GET'){ + try{const data=await beneficiaries.list(user),fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed. Reload the workspace.'},403);return reply(data);}catch{return reply({message:'Saved beneficiaries could not be confirmed.'},503);} + } + if(['/api/bank/beneficiaries/save','/api/bank/beneficiaries/remove'].includes(path)){ + if(request.method!=='POST')return reply({message:'Method not allowed.'},405); + if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403); + if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); + const raw=await request.text();if(raw.length>2000)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the beneficiary form.'},400);} + try{return reply(await beneficiaries.write(user,input,path.endsWith('/remove'),{revalidate:()=>auth(request)}));}catch(error){return reply({message:error.status?error.message:'The beneficiary change was not confirmed. Reload the list before retrying.'},error.status||503);} + } + if(path.startsWith('/api/bank/credit/')){ + try{ + if(path==='/api/bank/credit/overview'&&request.method==='GET'){ + if(url.search)return reply({message:'Account overrides are not accepted.'},400); + const fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403); + // Rebuild with fresh authority so a revoked organisational scope cannot leak records. + return reply({...await credit.overview(fresh),intakeEnabled:creditEnabled}); + } + if(path==='/api/bank/credit/details'&&request.method==='GET'){ + if([...url.searchParams.keys()].some(k=>k!=='loanId')||url.searchParams.getAll('loanId').length!==1)return reply({message:'Choose one credit contract.'},400);const fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403);return reply(await credit.details(fresh,url.searchParams.get('loanId'))); + } + if(!['/api/bank/credit/simulate','/api/bank/credit/apply','/api/bank/credit/action'].includes(path))return reply({message:'Credit route not found.'},404); + if(request.method!=='POST')return reply({message:'Method not allowed.'},405); + if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403); + if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); + if(url.search)return reply({message:'Account overrides are not accepted.'},400); + const raw=await request.text();if(raw.length>7000)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the credit form.'},400);} + if(!path.endsWith('/simulate')&&!creditEnabled)return reply({message:'Credit application intake is not open yet. No application or payment was made.',state:'not_active'},409); + const fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403); + if(path.endsWith('/apply')){const result=await credit.apply(fresh,input,{revalidate:()=>auth(request)});return reply(result);} + if(path.endsWith('/action')){const options={revalidate:()=>auth(request)};if(input.action==='accept')return reply(await creditEngine.accept(fresh,input,options));if(input.action==='withdraw')return reply(await creditEngine.decision(fresh,input,options));if(input.action==='repay')return reply(await creditEngine.requestRepayment(fresh,input,options));return reply({message:'Unknown credit action.'},400);} + return reply(await credit.simulate(fresh,input)); + }catch(error){return reply({message:error.status?error.message:'The credit operation could not be confirmed.'},error.status||503);} + } + if(path==='/api/bank/admin/credit/details'){ + if(request.method!=='GET')return reply({message:'Method not allowed.'},405);if([...url.searchParams.keys()].some(k=>k!=='loanId')||url.searchParams.getAll('loanId').length!==1)return reply({message:'Choose one credit contract.'},400); + try{const fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403);return reply(await credit.details(fresh,url.searchParams.get('loanId'),true));}catch(error){return reply({message:error.status?error.message:'Credit details could not be confirmed.'},error.status||503);} + } + if(['/api/bank/admin/credit/decision','/api/bank/admin/credit/recover'].includes(path)){ + if(request.method!=='POST')return reply({message:'Method not allowed.'},405);if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403);if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);if(url.search)return reply({message:'Account overrides are not accepted.'},400);if(!creditEnabled)return reply({message:'Credit processing is not active.'},409); + try{const raw=await request.text();if(raw.length>2500)return reply({message:'Request too large.'},413);const input=JSON.parse(raw),fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403);if(!(await authority(fresh)).manageAdmin)return reply({message:'Bank management permission is required.'},403);const recovery=path.endsWith('/recover');if(recovery?input.action!=='recover':!['approve','decline'].includes(input.action))return reply({message:'Unknown staff credit action.'},400);const result=await (recovery?creditEngine.requestRepayment(fresh,input,{revalidate:()=>auth(request)}):creditEngine.decision(fresh,input,{revalidate:()=>auth(request)}));if(!recovery)return reply({...result,notice:input.action==='approve'?'Approval recorded in the J.A.R.V.I.S. dossier. The borrower must accept the offer before payment at a four-hour bank window.':'Rejection recorded in the J.A.R.V.I.S. dossier.'});return reply(result);}catch(error){return reply({message:error.status?error.message:'The credit instruction could not be confirmed.'},error.status||503);} + } + if(['/api/bank/authorisations','/api/bank/authorisations/lookup','/api/bank/authorisations/change','/api/bank/admin/authorisations','/api/bank/admin/authorisations/lookup','/api/bank/admin/authorisations/change'].includes(path)){ + const staff=path.startsWith('/api/bank/admin/'); + try{ + if(request.method==='GET'&&!path.endsWith('/change')){ + const lookup=path.endsWith('/lookup'),allowed=lookup?['q','kind']:['q','accountId'];if([...url.searchParams.keys()].some(k=>!allowed.includes(k)||url.searchParams.getAll(k).length!==1))return reply({message:'Invalid authorisation filters.'},400); + const fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403);return reply(lookup?await authorisations.lookup(fresh,url.searchParams.get('q'),url.searchParams.get('kind')||'user',staff):await authorisations.list(fresh,staff,Object.fromEntries(url.searchParams))); + } + if(request.method!=='POST'||!path.endsWith('/change'))return reply({message:'Method not allowed.'},405); + if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403);if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);if(url.search)return reply({message:'Account overrides are not accepted.'},400);const raw=await request.text();if(raw.length>3000)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the authorisation form.'},400);}return reply(await authorisations.write(user,input,staff,{revalidate:()=>auth(request)})); + }catch(error){return reply({message:error.status?error.message:'The authorisation change could not be confirmed.'},error.status||503);} + } + if(['/api/bank/admin/payroll','/api/bank/admin/payroll/run'].includes(path)){ + try{ + if(url.search)return reply({message:'Payroll overrides are not accepted.'},400); + const fresh=await auth(request);if(!fresh||fresh.id!==user.id||!await canRunScheduler(central,fresh))return reply({message:'P&O payroll management is reserved for the Big Four.'},403); + if(request.method==='GET'&&!path.endsWith('/run')){const result={...await payroll.overview(),cycle:await payrollCycle.preview(),additionalCycle:await payrollCycle.previewAdditional()},current=await auth(request);if(!current||current.id!==user.id||!await canRunScheduler(central,current))return reply({message:'Payroll access changed.'},403);return reply(result);} + if(request.method!=='POST')return reply({message:'Method not allowed.'},405); + if(request.headers.get('origin')!==origin)return reply({message:'Origin rejected.'},403); + if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); + const raw=await request.text();if(raw.length>4000)return reply({message:'Request too large.'},413); + let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the payroll settings.'},400);} + if(path.endsWith('/run'))return reply(await payrollCycle.run(fresh,input,{revalidate:()=>auth(request)})); + return reply(await financialPolicies.save(fresh,'payroll',input,{revalidate:()=>auth(request)})); + }catch(error){return reply({message:error.status?error.message:'Payroll could not be confirmed. Reload before retrying.'},error.status||503);} + } + if(['/api/bank/admin/scheduler','/api/bank/admin/scheduler/run'].includes(path)){ + try{ + if(url.search)return reply({message:'Scheduler overrides are not accepted.'},400); + const fresh=await auth(request);if(!fresh||fresh.id!==user.id||!await canRunScheduler(central,fresh))return reply({message:'Only the Big Four may run the central scheduler.'},403); + if(path.endsWith('/run')){ + if(request.method!=='POST')return reply({message:'Method not allowed.'},405); + if(request.headers.get('origin')!==origin)return reply({message:'Origin rejected.'},403); + if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); + const raw=await request.text();if(raw.length>300)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Confirm the scheduler run.'},400);} + if(!input||input.confirmed!==true||Object.keys(input).some(k=>k!=='confirmed'))return reply({message:'Confirm running due tasks. Future dates cannot be forced.'},400); + const auditId=randomUUID();await bank.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[auditId,fresh.id,'central_scheduler_run',null,JSON.stringify({state:'started',recheckAll:true}),Date.now()]);const result=await scheduler.runDue({recheck:true,beforeTask:async()=>{const current=await auth(request);if(!current||current.id!==fresh.id||!await canRunScheduler(central,current))throw Error('Scheduler access changed');}});await bank.query('UPDATE pb_audit SET details=? WHERE id=?',[JSON.stringify({state:'completed',recheckAll:true,...result}),auditId]);return reply(result); + } + if(request.method!=='GET')return reply({message:'Method not allowed.'},405);return reply({tasks:await scheduler.status()}); + }catch{return reply({message:'The scheduler result could not be confirmed. Reload its status before retrying.'},503);} + } + if(path.startsWith('/api/bank/admin/')){ + try{ + if(['/api/bank/admin/compensation','/api/bank/admin/compensation/pay','/api/bank/admin/standing-instructions'].includes(path)){ + if(url.search)return reply({message:'No account overrides are accepted.'},400); + if(request.method==='GET'&&!path.endsWith('/pay')){const result=path.endsWith('/compensation')?await compensation.overview(user):await standing.overview(user),fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403);await (path.endsWith('/compensation')?compensation.access(fresh):standing.access(fresh));return reply(result);} + if(request.method!=='POST'||path.endsWith('/compensation'))return reply({message:'Method not allowed.'},405); + if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403); + if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); + const raw=await request.text();if(raw.length>2500)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the bank instruction.'},400);} + return reply(await (path.endsWith('/pay')?compensation.pay(user,input,{revalidate:()=>auth(request)}):standing.save(user,input,{revalidate:()=>auth(request)}))); + } + if(['/api/bank/admin/client','/api/bank/admin/client/package','/api/bank/admin/client/options'].includes(path)){ + if(path.endsWith('/client')){ + if(request.method!=='GET')return reply({message:'Method not allowed.'},405); + if([...url.searchParams.keys()].some(k=>k!=='entityId')||url.searchParams.getAll('entityId').length!==1)return reply({message:'Select one banking client.'},400); + const result=await clients.detail(user,url.searchParams.get('entityId')),fresh=await auth(request); + if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403); + const latest=await clients.scope(fresh,url.searchParams.get('entityId'));result.canManage=latest.canManage;return reply(result); + } + if(request.method!=='POST')return reply({message:'Method not allowed.'},405); + if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403); + if(url.search)return reply({message:'Account overrides are not accepted.'},400); + if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); + const raw=await request.text();if(raw.length>3000)return reply({message:'Request too large.'},413); + let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the client management form.'},400);} + return reply(await clients.change(user,input,path.endsWith('/package')?'package':'options',{revalidate:()=>auth(request)})); + } + if(['/api/bank/admin/transfers/cancel','/api/bank/admin/treasuries/transfer','/api/bank/admin/reserve/grants','/api/bank/admin/taxes/payments'].includes(path)){ + if(request.method!=='POST')return reply({message:'Method not allowed.'},405); + if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403); + if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); + if(url.search)return reply({message:'Account overrides are not accepted.'},400);const raw=await request.text();if(raw.length>2000)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the cancellation form.'},400);} + return reply(await (path.endsWith('/cancel')?admin.cancel(user,input,{revalidate:()=>auth(request)}):path.endsWith('/grants')?admin.issueGrant(user,input,{revalidate:()=>auth(request)}):path.endsWith('/taxes/payments')?admin.taxPayment(user,input,{revalidate:()=>auth(request)}):admin.treasuryTransfer(user,input,{revalidate:()=>auth(request)}))); + } + if(request.method!=='GET')return reply({message:'Method not allowed.'},405); + const permitted=path==='/api/bank/admin/credit'?['loanId']:path.endsWith('/taxes/recipients')?['q']:path.endsWith('/overview')?[]:path.endsWith('/accounts')?['entityId']:path.endsWith('/activity')?['accountId','page']:['q','kind','page'];if([...url.searchParams.keys()].some(k=>!permitted.includes(k)||url.searchParams.getAll(k).length!==1))return reply({message:'Invalid bank administration filter.'},400); + const input=Object.fromEntries(url.searchParams);let result; + if(path==='/api/bank/admin/overview')result=await admin.overview(user); + else if(path==='/api/bank/admin/entities')result=await admin.entities(user,input); + else if(path==='/api/bank/admin/corporate')result=await admin.entities(user,input,true); + else if(path==='/api/bank/admin/taxes/overview')result=await admin.taxOverview(user); + else if(path==='/api/bank/admin/taxes/recipients')result=await admin.taxRecipients(user,input.q); + else if(path==='/api/bank/admin/treasuries')result=await admin.treasuries(user,input); + else if(path==='/api/bank/admin/credit')result={...await credit.staff(user,input),processing:creditEnabled?'active':'not_active'}; + else if(path==='/api/bank/admin/accounts')result=await admin.accounts(user,input.entityId); + else if(path==='/api/bank/admin/activity')result=await admin.activity(user,input); + else if(path==='/api/bank/admin/audit')result=await admin.audit(user,input); + else if(path==='/api/bank/admin/pending')result=await admin.pending(user,input); + else return reply({message:'Bank administration route not found.'},404); + const fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed. Reload the bank workspace.'},403);const rights=await admin.access(fresh);if(result.permissions){try{result.permissions.canRunScheduler=await canRunScheduler(central,fresh);}catch{result.permissions.canRunScheduler=false;}result.permissions.canManage=rights.manageAdmin;result.permissions.canCompensate=!!(rights.manageAdmin||rights.manageClients);result.permissions.canIssueReserve=fresh.id===RESERVE_OWNER_ID&&!!rights.manageAdmin;}if('canManage' in result)result.canManage=rights.manageAdmin; + return reply(result); + }catch(error){return reply({message:error.status?error.message:'The bank could not confirm the administrative operation.'},error.status||503);} + } + if(request.method==='GET'&&['/api/bank/overview','/api/bank/client','/api/bank/accounts'].includes(path)){ + try{return reply(await service.overview(user));}catch{return reply({message:'The bank could not confirm the current records. Reload the workspace.'},503);} + } + if(request.method==='GET'&&['/api/bank/transfer-options','/api/bank/recipients','/api/bank/activity'].includes(path)){ + try{ + if(path==='/api/bank/transfer-options')return reply({accounts:await payments.accounts(user),beneficiaries:(await beneficiaries.list(user)).beneficiaries,actorId:user.id,security:await transferSecurity.settings(user),standard:{state:'active',processing:'Standard payments are processed in batches every four hours: 00:00, 04:00, 08:00, 12:00, 16:00 and 20:00 Europe/Brussels.',nextAt:standardCycle().nextAt},fees:{state:'planned',message:'Transfer fees are not currently being charged.'}}); + if(path==='/api/bank/recipients'){ + if([...url.searchParams.keys()].some(k=>!['q','page'].includes(k))||url.searchParams.getAll('q').length!==1||url.searchParams.getAll('page').length>1)return reply({message:'Use the recipient search and page fields.'},400); + const now=Date.now();for(const [key,value]of lookups)if(value.until10000)return reply({message:'Recipient lookup is busy. Try shortly.'},429); + const value=lookups.get(user.id)||{until:now+60000,count:0};value.count++;lookups.set(user.id,value);if(value.count>20)return reply({message:'Too many recipient searches. Try again in one minute.'},429); + const rawPage=url.searchParams.get('page')||'1';if(!/^[1-9]\d{0,3}$/.test(rawPage))return reply({message:'Choose a valid beneficiary page.'},400); + const result=await payments.recipientPage(user,url.searchParams.get('q'),{page:Number(rawPage)}),fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed. Search again.'},403);return reply(result); + } + if([...url.searchParams.keys()].some(k=>!['accountId','page','q','state','from','to'].includes(k))||url.searchParams.getAll('accountId').length>1||['page','q','state','from','to'].some(k=>url.searchParams.getAll(k).length>1))return reply({message:'Invalid statement filter.'},400); + const raw=url.searchParams.get('page')||'1';if(!/^[1-9]\d{0,3}$/.test(raw))return reply({message:'Choose a valid statement page.'},400); + return reply(await payments.activity(user,{accountId:url.searchParams.get('accountId'),page:Number(raw),...Object.fromEntries(['q','state','from','to'].map(k=>[k,url.searchParams.get(k)||'']))})); + }catch(error){return reply({message:error.status?error.message:'The bank could not confirm the requested records.'},error.status||503);} + } + if(path==='/api/bank/transfers'){ + if(request.method!=='POST')return reply({message:'Method not allowed.'},405); + if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403); + if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); + const now=Date.now();for(const [key,value]of transferAttempts)if(value.until10||transferAttempts.size>10000)return reply({message:'Too many payment attempts. Keep the same payment reference and try again in one minute.'},429); + const raw=await request.text();if(raw.length>3000)return reply({message:'Request too large.'},413);let body;try{body=JSON.parse(raw);}catch{return reply({message:'Complete the transfer form.'},400);} + try{return reply(await payments.transfer(user,body,{revalidate:()=>auth(request)}));}catch(error){return reply({message:error.status?error.message:'The transfer result could not be confirmed. Keep the same payment reference when retrying.'},error.status||503);} + } + if(path==='/api/bank/contracts'&&request.method==='GET')return reply({contracts:{...POSTBANK_CONTRACTS,loans:{...POSTBANK_CONTRACTS.loans,state:creditEnabled?'active':'prepared'}}}); + if(['/api/bank/activate','/api/bank/packages/change','/api/bank/accounts/options'].includes(path)){ + if(request.method!=='POST')return reply({message:'Method not allowed.'},405); + if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403); + if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); + const text=await request.text();if(text.length>3000)return reply({message:'Request too large.'},413); + let body;try{body=JSON.parse(text);}catch{return reply({message:'Select your package again.'},400);} + try{return reply(await (path==='/api/bank/activate'?service.activate(user,body,{revalidate:()=>auth(request)}):path==='/api/bank/packages/change'?service.changePackage(user,body,{revalidate:()=>auth(request)}):service.setAccountOptions(user,body,{revalidate:()=>auth(request)})));}catch(error){return reply({message:error.status?error.message:'The package operation was not confirmed. Reload the current records before trying again.',returnTo:'package_selection'},error.status||503);} + } + return reply({message:'This bank function is not implemented yet. No request was forwarded to the old game bank.',state:'planned'},501); + }; +} diff --git a/website/tests/postbank-credit-ui.test.mjs b/website/tests/postbank-credit-ui.test.mjs index 8f386962..5baae930 100644 --- a/website/tests/postbank-credit-ui.test.mjs +++ b/website/tests/postbank-credit-ui.test.mjs @@ -1,50 +1,50 @@ -import {randomUUID} from 'node:crypto';import {BankFixture} from './postbank-fixture.mjs';import {PostbankService} from '../node/postbank-service.mjs';import {PostbankCredit} from '../node/postbank-credit.mjs';import {BANK_VERSION} from '../node/postbank-catalogue.mjs';import {CREDIT_VERSION} from '../node/postbank-credit-model.mjs'; -import test from 'node:test';import assert from 'node:assert/strict';import {mountPostbankCredit,creditTheme,creditReviewSelection} from '../control-panel/public/cp-v2/cp-v2-postbank-credit.mjs'; -class Node{constructor(tag){this.tagName=tag.toUpperCase();this.children=[];this.attrs={};this.classList={add:()=>{}};this.value='';this.disabled=false;this.dataset={};this._text='';}set textContent(v){this._text=String(v);this.children=[];}get textContent(){return this._text+this.children.map(n=>n.textContent).join('');}append(...nodes){for(const n of nodes){n.parent=this;this.children.push(n);if(this.tagName==='SELECT'&&!this.value)this.value=n.value;}}prepend(...nodes){for(const n of nodes)n.parent=this;this.children.unshift(...nodes);}get firstElementChild(){return this.children[0]||null;}get elements(){return all(this).filter(n=>['INPUT','SELECT','TEXTAREA','BUTTON'].includes(n.tagName));}replaceChildren(...nodes){this._text='';this.children=[];this.append(...nodes);}setAttribute(k,v){this.attrs[k]=String(v);}closest(){return null;}remove(){if(this.parent)this.parent.children=this.parent.children.filter(n=>n!==this);}focus(){}reportValidity(){return true;}} -const all=n=>n.children.flatMap(c=>[c,...all(c)]),settle=async()=>{for(let i=0;i<6;i++)await new Promise(r=>setImmediate(r));}; -async function fixture(run,{enabled=false,uncertain=false,validateApplication=null,includeGrant=false,loans=[],pageId="loan-centre",reviewSearch="",detailState="disbursed"}={}){const prior=globalThis.document;globalThis.document={createElement:t=>new Node(t),createElementNS:(ns,t)=>new Node(t)};let applyAttempts=0;const host=new Node('div'),calls=[],products=[...(includeGrant?[{key:'grant_start',name:'Launch Start',group:'grants',kinds:['person'],amount:'2500.00',annualBps:0}]:[]),{key:'personal_loan',name:'Personal Loan',group:'personal',kinds:['person'],min:'1000.00',max:'25000.00',annualBps:839,terms:[3,6]},{key:'business_loan',name:'Business Loan',group:'professional',kinds:['clan'],min:'5000.00',max:'100000.00',annualBps:450,terms:[6,12]}],accounts=[{id:'1',name:'Personal current',number:'DR25102000000005',kind:'person',canApply:true},{id:'2',name:'Clan current',number:'DR14105000000004',kind:'clan',canApply:true}],fetcher=async(path,options={})=>{calls.push({path,...options});if(path.includes('/details?'))return Response.json({quote:{annualRate:'0.00',totalRepayment:'10000.00'},collateral:'0.00',settlement:'10000.00',schedule:[],state:detailState});if(path.endsWith('/apply')&&validateApplication){try{const result=await validateApplication(JSON.parse(options.body));if(!uncertain||applyAttempts++>0)return Response.json(result);}catch(error){return Response.json({message:error.message},{status:error.status||400});}}if(path.endsWith('/apply')&&uncertain&&applyAttempts++===0)return Response.json({message:'Uncertain result'},{status:503});return Response.json(path.endsWith('/simulate')?{quote:{monthly:'100.00',annualRate:'8.39',months:12,totalInterest:'200.00',totalRepayment:'1200.00',schedule:[]},collateral:'250.00',notice:'No financial change'}:{accounts,products,loans,applications:loans,canManage:enabled,processing:enabled?'active':'not_active',intakeEnabled:enabled,termsVersion:CREDIT_VERSION});};const dispose=mountPostbankCredit(host,pageId,{fetcher,reviewSearch});try{await settle();await run({host,calls,nodes:()=>all(host)});}finally{dispose();globalThis.document=prior;}} -test('borrowing tabs filter product cards and simulation replaces the catalogue rather than appearing below it',()=>fixture(async({nodes,calls})=>{const tabs=nodes().filter(n=>n.attrs.role==='tab');assert.equal(tabs.length,2);assert.equal(nodes().filter(n=>n.tagName==='SELECT').length,0);assert.ok(nodes().some(n=>n.className?.includes('pb-choice-card')&&n.className.includes('pb-plan-flow')));tabs[1].onclick();assert.ok(nodes().some(n=>n.tagName==='H5'&&n.textContent==='Business Loan'));assert.ok(!nodes().some(n=>n.tagName==='H5'&&n.textContent==='Personal Loan'));nodes().find(n=>n.tagName==='BUTTON'&&n.textContent==='Simulate repayments').onclick();assert.ok(!nodes().some(n=>n.className?.includes('pb-credit-products')));assert.ok(nodes().some(n=>n.className==='pb-credit-calculator'));const form=nodes().find(n=>n.tagName==='FORM');await form.onsubmit({preventDefault(){}});assert.equal(JSON.parse(calls.find(c=>c.method==='POST').body).accountId,'2');assert.ok(nodes().some(n=>n.className==='pb-credit-monthly'&&n.textContent==='100.00 DM'));nodes().find(n=>n.tagName==='INPUT').oninput();assert.ok(!nodes().some(n=>n.className==='pb-credit-monthly'));nodes().find(n=>n.tagName==='BUTTON'&&n.textContent.startsWith('← Back')).onclick();assert.ok(nodes().some(n=>n.tagName==='H5'&&n.textContent==='Business Loan'));assert.equal(calls.filter(c=>c.method==='POST').length,1);})); -test('credit groups reuse the banking package palette',()=>{assert.equal(creditTheme({key:'grant_start'}),'start');assert.equal(creditTheme({key:'grant_build'}),'connect');assert.equal(creditTheme({key:'grant_advance'}),'scale');assert.equal(creditTheme({key:'business_loan'}),'connect');assert.equal(creditTheme({key:'civic_loan'}),'civic');assert.equal(creditTheme({key:'personal_refinance',group:'refinancing'}),'scale');}); - -test('application confirmation and uncertain retry retain the same request and frozen disclosures',()=>fixture(async({nodes,calls})=>{nodes().find(n=>n.tagName==='BUTTON'&&n.textContent==='Simulate repayments').onclick();await nodes().find(n=>n.tagName==='FORM').onsubmit({preventDefault(){}});let form=nodes().find(n=>n.className==='pb-credit-action-form');const motivation=all(form).find(n=>n.tagName==='TEXTAREA'),check=all(form).find(n=>n.type==='checkbox');motivation.value='A genuine loan purpose';await form.onsubmit({preventDefault(){}});assert.equal(calls.filter(c=>c.path.endsWith('/apply')).length,0);check.checked=true;await form.onsubmit({preventDefault(){}});assert.equal(motivation.disabled,true);assert.ok(all(form).some(n=>n.tagName==='BUTTON'&&n.textContent==='Retry same instruction'));await form.onsubmit({preventDefault(){}});const posts=calls.filter(c=>c.path.endsWith('/apply'));assert.equal(posts.length,2);assert.equal(posts[0].body,posts[1].body);assert.equal(JSON.parse(posts[0].body).accountId,'1');assert.equal(JSON.parse(posts[0].body).motivation,'A genuine loan purpose');},{enabled:true,uncertain:true})); - -test('bank oversight menus require staff view permission rather than ordinary personal banking',async()=>{const {visibleCPItem}=await import('../control-panel/public/cp-v2/cp-v2-access.mjs');for(const id of ['bank-dashboard','company-finance','loan-administration']){assert.equal(visibleCPItem({permissions:['web.bank.personal.view']},'bank',{id}),false);assert.equal(visibleCPItem({permissions:['web.bank.staff.view']},'bank',{id}),true);}assert.equal(visibleCPItem({permissions:['web.bank.personal.view']},'bank',{id:'loan-centre'}),true);}); - -test('the real credit form payload is accepted by the strict application service without stray confirmation fields',async()=>{const db=new BankFixture(),user={id:randomUUID(),username:'UI contract borrower'},entity={id:randomUUID(),kind:'person',key:user.id,name:user.username},authority=async()=>({entities:[{...entity,canView:true,canActivate:true,canPay:true}]});try{await new PostbankService(db,authority).activate(user,{entityId:entity.id,packageKey:'pb_flow',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});const credit=new PostbankCredit(db,authority);await fixture(async({nodes,calls})=>{nodes().find(n=>n.tagName==='BUTTON'&&n.textContent==='Simulate repayments').onclick();await nodes().find(n=>n.tagName==='FORM').onsubmit({preventDefault(){}});const form=nodes().find(n=>n.className==='pb-credit-action-form');all(form).find(n=>n.tagName==='TEXTAREA').value='Testing the new submitted credit flow';all(form).find(n=>n.type==='checkbox').checked=true;await form.onsubmit({preventDefault(){}});const payload=JSON.parse(calls.find(c=>c.path.endsWith('/apply')).body);assert.equal(Object.hasOwn(payload,'confirmed'),false);assert.equal(payload.accepted,true);assert.equal((await db.first('SELECT COUNT(*) n FROM pb_credit_loans')).n,1);assert.equal((await db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);assert.ok(nodes().some(n=>!n.hidden&&n.textContent.includes('Application recorded for bank review.')));},{enabled:true,validateApplication:body=>credit.apply(user,body)});}finally{db.close();}}); - -test('autoaccepted grants show no motivation field and submit without a motivation property',()=>fixture(async({nodes,calls})=>{nodes().find(n=>n.tagName==='BUTTON'&&n.textContent==='Simulate repayments').onclick();await nodes().find(n=>n.tagName==='FORM').onsubmit({preventDefault(){}});assert.equal(nodes().filter(n=>n.tagName==='TEXTAREA').length,0);const form=nodes().find(n=>n.className==='pb-credit-action-form');all(form).find(n=>n.type==='checkbox').checked=true;await form.onsubmit({preventDefault(){}});const payload=JSON.parse(calls.find(c=>c.path.endsWith('/apply')).body);assert.equal(payload.productKey,'grant_start');assert.equal(Object.hasOwn(payload,'motivation'),false);assert.equal(payload.accepted,true);},{enabled:true,includeGrant:true})); - +import {randomUUID} from 'node:crypto';import {BankFixture} from './postbank-fixture.mjs';import {PostbankService} from '../node/postbank-service.mjs';import {PostbankCredit} from '../node/postbank-credit.mjs';import {BANK_VERSION} from '../node/postbank-catalogue.mjs';import {CREDIT_VERSION} from '../node/postbank-credit-model.mjs'; +import test from 'node:test';import assert from 'node:assert/strict';import {mountPostbankCredit,creditTheme,creditReviewSelection} from '../control-panel/public/cp-v2/cp-v2-postbank-credit.mjs'; +class Node{constructor(tag){this.tagName=tag.toUpperCase();this.children=[];this.attrs={};this.classList={add:()=>{}};this.value='';this.disabled=false;this.dataset={};this._text='';}set textContent(v){this._text=String(v);this.children=[];}get textContent(){return this._text+this.children.map(n=>n.textContent).join('');}append(...nodes){for(const n of nodes){n.parent=this;this.children.push(n);if(this.tagName==='SELECT'&&!this.value)this.value=n.value;}}prepend(...nodes){for(const n of nodes)n.parent=this;this.children.unshift(...nodes);}get firstElementChild(){return this.children[0]||null;}get elements(){return all(this).filter(n=>['INPUT','SELECT','TEXTAREA','BUTTON'].includes(n.tagName));}replaceChildren(...nodes){this._text='';this.children=[];this.append(...nodes);}setAttribute(k,v){this.attrs[k]=String(v);}closest(){return null;}remove(){if(this.parent)this.parent.children=this.parent.children.filter(n=>n!==this);}focus(){}reportValidity(){return true;}} +const all=n=>n.children.flatMap(c=>[c,...all(c)]),settle=async()=>{for(let i=0;i<6;i++)await new Promise(r=>setImmediate(r));}; +async function fixture(run,{enabled=false,uncertain=false,validateApplication=null,includeGrant=false,loans=[],pageId="loan-centre",reviewSearch="",detailState="disbursed"}={}){const prior=globalThis.document;globalThis.document={createElement:t=>new Node(t),createElementNS:(ns,t)=>new Node(t)};let applyAttempts=0;const host=new Node('div'),calls=[],products=[...(includeGrant?[{key:'grant_start',name:'Launch Start',group:'grants',kinds:['person'],amount:'2500.00',annualBps:0}]:[]),{key:'personal_loan',name:'Personal Loan',group:'personal',kinds:['person'],min:'1000.00',max:'25000.00',annualBps:839,terms:[3,6]},{key:'business_loan',name:'Business Loan',group:'professional',kinds:['clan'],min:'5000.00',max:'100000.00',annualBps:450,terms:[6,12]}],accounts=[{id:'1',name:'Personal current',number:'DR25102000000005',kind:'person',canApply:true},{id:'2',name:'Clan current',number:'DR14105000000004',kind:'clan',canApply:true}],fetcher=async(path,options={})=>{calls.push({path,...options});if(path.includes('/details?'))return Response.json({quote:{annualRate:'0.00',totalRepayment:'10000.00'},collateral:'0.00',settlement:'10000.00',schedule:[],state:detailState});if(path.endsWith('/apply')&&validateApplication){try{const result=await validateApplication(JSON.parse(options.body));if(!uncertain||applyAttempts++>0)return Response.json(result);}catch(error){return Response.json({message:error.message},{status:error.status||400});}}if(path.endsWith('/apply')&&uncertain&&applyAttempts++===0)return Response.json({message:'Uncertain result'},{status:503});return Response.json(path.endsWith('/simulate')?{quote:{monthly:'100.00',annualRate:'8.39',months:12,totalInterest:'200.00',totalRepayment:'1200.00',schedule:[]},collateral:'250.00',notice:'No financial change'}:{accounts,products,loans,applications:loans,canManage:enabled,processing:enabled?'active':'not_active',intakeEnabled:enabled,termsVersion:CREDIT_VERSION});};const dispose=mountPostbankCredit(host,pageId,{fetcher,reviewSearch});try{await settle();await run({host,calls,nodes:()=>all(host)});}finally{dispose();globalThis.document=prior;}} +test('borrowing tabs filter product cards and simulation replaces the catalogue rather than appearing below it',()=>fixture(async({nodes,calls})=>{const tabs=nodes().filter(n=>n.attrs.role==='tab');assert.equal(tabs.length,2);assert.equal(nodes().filter(n=>n.tagName==='SELECT').length,0);assert.ok(nodes().some(n=>n.className?.includes('pb-choice-card')&&n.className.includes('pb-plan-flow')));tabs[1].onclick();assert.ok(nodes().some(n=>n.tagName==='H5'&&n.textContent==='Business Loan'));assert.ok(!nodes().some(n=>n.tagName==='H5'&&n.textContent==='Personal Loan'));nodes().find(n=>n.tagName==='BUTTON'&&n.textContent==='Simulate repayments').onclick();assert.ok(!nodes().some(n=>n.className?.includes('pb-credit-products')));assert.ok(nodes().some(n=>n.className==='pb-credit-calculator'));const form=nodes().find(n=>n.tagName==='FORM');await form.onsubmit({preventDefault(){}});assert.equal(JSON.parse(calls.find(c=>c.method==='POST').body).accountId,'2');assert.ok(nodes().some(n=>n.className==='pb-credit-monthly'&&n.textContent==='100.00 DM'));nodes().find(n=>n.tagName==='INPUT').oninput();assert.ok(!nodes().some(n=>n.className==='pb-credit-monthly'));nodes().find(n=>n.tagName==='BUTTON'&&n.textContent.startsWith('← Back')).onclick();assert.ok(nodes().some(n=>n.tagName==='H5'&&n.textContent==='Business Loan'));assert.equal(calls.filter(c=>c.method==='POST').length,1);})); +test('credit groups reuse the banking package palette',()=>{assert.equal(creditTheme({key:'grant_start'}),'start');assert.equal(creditTheme({key:'grant_build'}),'connect');assert.equal(creditTheme({key:'grant_advance'}),'scale');assert.equal(creditTheme({key:'business_loan'}),'connect');assert.equal(creditTheme({key:'civic_loan'}),'civic');assert.equal(creditTheme({key:'personal_refinance',group:'refinancing'}),'scale');}); + +test('application confirmation and uncertain retry retain the same request and frozen disclosures',()=>fixture(async({nodes,calls})=>{nodes().find(n=>n.tagName==='BUTTON'&&n.textContent==='Simulate repayments').onclick();await nodes().find(n=>n.tagName==='FORM').onsubmit({preventDefault(){}});let form=nodes().find(n=>n.className==='pb-credit-action-form');const motivation=all(form).find(n=>n.tagName==='TEXTAREA'),check=all(form).find(n=>n.type==='checkbox');motivation.value='A genuine loan purpose';await form.onsubmit({preventDefault(){}});assert.equal(calls.filter(c=>c.path.endsWith('/apply')).length,0);check.checked=true;await form.onsubmit({preventDefault(){}});assert.equal(motivation.disabled,true);assert.ok(all(form).some(n=>n.tagName==='BUTTON'&&n.textContent==='Retry same instruction'));await form.onsubmit({preventDefault(){}});const posts=calls.filter(c=>c.path.endsWith('/apply'));assert.equal(posts.length,2);assert.equal(posts[0].body,posts[1].body);assert.equal(JSON.parse(posts[0].body).accountId,'1');assert.equal(JSON.parse(posts[0].body).motivation,'A genuine loan purpose');},{enabled:true,uncertain:true})); + +test('bank oversight menus require staff view permission rather than ordinary personal banking',async()=>{const {visibleCPItem}=await import('../control-panel/public/cp-v2/cp-v2-access.mjs');for(const id of ['bank-dashboard','company-finance','loan-administration']){assert.equal(visibleCPItem({permissions:['web.bank.personal.view']},'bank',{id}),false);assert.equal(visibleCPItem({permissions:['web.bank.staff.view']},'bank',{id}),true);}assert.equal(visibleCPItem({permissions:['web.bank.personal.view']},'bank',{id:'loan-centre'}),true);}); + +test('the real credit form payload is accepted by the strict application service without stray confirmation fields',async()=>{const db=new BankFixture(),user={id:randomUUID(),username:'UI contract borrower'},entity={id:randomUUID(),kind:'person',key:user.id,name:user.username},authority=async()=>({entities:[{...entity,canView:true,canActivate:true,canPay:true}]});try{await new PostbankService(db,authority).activate(user,{entityId:entity.id,packageKey:'pb_flow',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});const credit=new PostbankCredit(db,authority);await fixture(async({nodes,calls})=>{nodes().find(n=>n.tagName==='BUTTON'&&n.textContent==='Simulate repayments').onclick();await nodes().find(n=>n.tagName==='FORM').onsubmit({preventDefault(){}});const form=nodes().find(n=>n.className==='pb-credit-action-form');all(form).find(n=>n.tagName==='TEXTAREA').value='Testing the new submitted credit flow';all(form).find(n=>n.type==='checkbox').checked=true;await form.onsubmit({preventDefault(){}});const payload=JSON.parse(calls.find(c=>c.path.endsWith('/apply')).body);assert.equal(Object.hasOwn(payload,'confirmed'),false);assert.equal(payload.accepted,true);assert.equal((await db.first('SELECT COUNT(*) n FROM pb_credit_loans')).n,1);assert.equal((await db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);assert.ok(nodes().some(n=>!n.hidden&&n.textContent.includes('Application recorded for bank review.')));},{enabled:true,validateApplication:body=>credit.apply(user,body)});}finally{db.close();}}); + +test('autoaccepted grants show no motivation field and submit without a motivation property',()=>fixture(async({nodes,calls})=>{nodes().find(n=>n.tagName==='BUTTON'&&n.textContent==='Simulate repayments').onclick();await nodes().find(n=>n.tagName==='FORM').onsubmit({preventDefault(){}});assert.equal(nodes().filter(n=>n.tagName==='TEXTAREA').length,0);const form=nodes().find(n=>n.className==='pb-credit-action-form');all(form).find(n=>n.type==='checkbox').checked=true;await form.onsubmit({preventDefault(){}});const payload=JSON.parse(calls.find(c=>c.path.endsWith('/apply')).body);assert.equal(payload.productKey,'grant_start');assert.equal(Object.hasOwn(payload,'motivation'),false);assert.equal(payload.accepted,true);},{enabled:true,includeGrant:true})); + const personalLoan={id:'11111111-1111-4111-8111-111111111111',productKey:'grant_advance',state:'active',principal:'10000.00',outstanding:'10000.00',monthly:'834.00'}; -test('My Credit links to an authorised Codex dossier instead of fetching inline ticket details',()=>fixture(async({nodes,calls})=>{ - const link=nodes().find(n=>n.tagName==='A'&&n.textContent==='Open Codex dossier →');assert(link);assert.equal(link.href,'/?codexLoan='+personalLoan.id+'#bank/bank-loans');assert.equal(calls.some(c=>c.path.includes('/details?')),false);assert.equal(calls.filter(c=>c.method==='POST').length,0); +test('My Credit links to an authorised J.A.R.V.I.S. dossier instead of fetching inline ticket details',()=>fixture(async({nodes,calls})=>{ + const link=nodes().find(n=>n.tagName==='A'&&n.textContent==='Open J.A.R.V.I.S. dossier →');assert(link);assert.equal(link.href,'/?codexLoan='+personalLoan.id+'#bank/bank-loans');assert.equal(calls.some(c=>c.path.includes('/details?')),false);assert.equal(calls.filter(c=>c.method==='POST').length,0); },{pageId:'bank-loans',loans:[personalLoan]})); -test('a personal Codex dossier loads full contract details without changing the bank workflow',()=>fixture(async({nodes,calls})=>{ +test('a personal J.A.R.V.I.S. dossier loads full contract details without changing the bank workflow',()=>fixture(async({nodes,calls})=>{ assert(nodes().some(n=>n.tagName==='H3'&&n.textContent==='Credit application dossier'));assert(nodes().some(n=>n.textContent.includes('Settlement estimate today: 10000.00 DM')));assert(calls.some(c=>c.path==='/api/bank/credit/details?loanId='+personalLoan.id));assert.equal(calls.filter(c=>c.method==='POST').length,0); },{pageId:'bank-loans',loans:[personalLoan],reviewSearch:'?codexLoan='+personalLoan.id})); -const linkedLoan={id:'bfaaccf2-a33e-4fa1-a64e-995c19b388cb',entity:'Independent applicant',productKey:'civic_loan',state:'submitted',principal:'50000.00',canReview:true,createdAt:1,score:{score:600,band:'Standard',flags:[]},motivation:'A considered public project'}; -test('Support decision links open only the linked contract without submitting a decision',()=>fixture(async({nodes,calls})=>{ - assert.equal(calls[0].path,'/api/bank/admin/credit?loanId='+linkedLoan.id); - assert.ok(calls.some(c=>c.path==='/api/bank/admin/credit/details?loanId='+linkedLoan.id)); - assert.ok(nodes().some(n=>n.tagName==='H3'&&n.textContent==='Confirm approval')); - assert.ok(nodes().some(n=>n.tagName==='FORM'&&n.textContent.includes('Reason'))); - assert.equal(calls.filter(c=>c.method==='POST').length,0); -},{pageId:'loan-administration',loans:[linkedLoan],enabled:true,detailState:'submitted',reviewSearch:'?creditApplication='+linkedLoan.id+'&creditDecision=approve'})); -test('an already decided Support application cannot offer another approval',()=>fixture(async({nodes,calls})=>{ - assert.ok(!nodes().some(n=>n.tagName==='BUTTON'&&n.textContent==='Approve application')); - assert.ok(nodes().some(n=>n.textContent.includes('already offered'))); - assert.equal(calls.filter(c=>c.method==='POST').length,0); -},{pageId:'loan-administration',loans:[linkedLoan],enabled:true,detailState:'offered',reviewSearch:'?creditApplication='+linkedLoan.id+'&creditDecision=decline'})); -test('Support review selection rejects invalid identities, duplicate parameters and unknown actions',()=>{ - assert.equal(creditReviewSelection('?creditApplication=bad&creditDecision=approve'),null); - assert.equal(creditReviewSelection('?creditApplication='+linkedLoan.id+'&creditDecision=approve&creditDecision=decline'),null); - assert.equal(creditReviewSelection('?creditApplication='+linkedLoan.id+'&creditDecision=pay'),null); -}); - -test('a self-review link explains why confirmation is blocked and keeps the Codex dossier pending',()=>fixture(async({nodes,calls})=>{ - assert.ok(nodes().some(n=>n.attrs.role==='status'&&n.textContent.includes('A different bank manager'))); - assert.ok(nodes().some(n=>n.textContent.includes('Codex dossier remains pending'))); - assert.ok(!nodes().some(n=>n.tagName==='BUTTON'&&n.textContent==='Approve application')); - assert.equal(calls.filter(c=>c.method==='POST').length,0); -},{pageId:'loan-administration',loans:[{...linkedLoan,canReview:false}],enabled:true,detailState:'submitted',reviewSearch:'?creditApplication='+linkedLoan.id+'&creditDecision=approve'})); +const linkedLoan={id:'bfaaccf2-a33e-4fa1-a64e-995c19b388cb',entity:'Independent applicant',productKey:'civic_loan',state:'submitted',principal:'50000.00',canReview:true,createdAt:1,score:{score:600,band:'Standard',flags:[]},motivation:'A considered public project'}; +test('Support decision links open only the linked contract without submitting a decision',()=>fixture(async({nodes,calls})=>{ + assert.equal(calls[0].path,'/api/bank/admin/credit?loanId='+linkedLoan.id); + assert.ok(calls.some(c=>c.path==='/api/bank/admin/credit/details?loanId='+linkedLoan.id)); + assert.ok(nodes().some(n=>n.tagName==='H3'&&n.textContent==='Confirm approval')); + assert.ok(nodes().some(n=>n.tagName==='FORM'&&n.textContent.includes('Reason'))); + assert.equal(calls.filter(c=>c.method==='POST').length,0); +},{pageId:'loan-administration',loans:[linkedLoan],enabled:true,detailState:'submitted',reviewSearch:'?creditApplication='+linkedLoan.id+'&creditDecision=approve'})); +test('an already decided Support application cannot offer another approval',()=>fixture(async({nodes,calls})=>{ + assert.ok(!nodes().some(n=>n.tagName==='BUTTON'&&n.textContent==='Approve application')); + assert.ok(nodes().some(n=>n.textContent.includes('already offered'))); + assert.equal(calls.filter(c=>c.method==='POST').length,0); +},{pageId:'loan-administration',loans:[linkedLoan],enabled:true,detailState:'offered',reviewSearch:'?creditApplication='+linkedLoan.id+'&creditDecision=decline'})); +test('Support review selection rejects invalid identities, duplicate parameters and unknown actions',()=>{ + assert.equal(creditReviewSelection('?creditApplication=bad&creditDecision=approve'),null); + assert.equal(creditReviewSelection('?creditApplication='+linkedLoan.id+'&creditDecision=approve&creditDecision=decline'),null); + assert.equal(creditReviewSelection('?creditApplication='+linkedLoan.id+'&creditDecision=pay'),null); +}); + +test('a self-review link explains why confirmation is blocked and keeps the J.A.R.V.I.S. dossier pending',()=>fixture(async({nodes,calls})=>{ + assert.ok(nodes().some(n=>n.attrs.role==='status'&&n.textContent.includes('A different bank manager'))); + assert.ok(nodes().some(n=>n.textContent.includes('J.A.R.V.I.S. dossier remains pending'))); + assert.ok(!nodes().some(n=>n.tagName==='BUTTON'&&n.textContent==='Approve application')); + assert.equal(calls.filter(c=>c.method==='POST').length,0); +},{pageId:'loan-administration',loans:[{...linkedLoan,canReview:false}],enabled:true,detailState:'submitted',reviewSearch:'?creditApplication='+linkedLoan.id+'&creditDecision=approve'}));