forked from unimatrix/web
Rename the visible Codex system to J.A.R.V.I.S.
This commit is contained in:
parent
ad036140b2
commit
00982cb957
12 changed files with 654 additions and 651 deletions
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -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;}}
|
||||
|
|
|
|||
|
|
@ -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';}
|
||||
|
|
|
|||
|
|
@ -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();};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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();};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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();};
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
|
|
@ -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
|
|||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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.until<now)lookups.delete(key);if(lookups.size>10000)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.until<now)transferAttempts.delete(key);const count=transferAttempts.get(user.id)||{until:now+60000,count:0};count.count++;transferAttempts.set(user.id,count);if(count.count>10||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.until<now)lookups.delete(key);if(lookups.size>10000)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.until<now)transferAttempts.delete(key);const count=transferAttempts.get(user.id)||{until:now+60000,count:0};count.count++;transferAttempts.set(user.id,count);if(count.count>10||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);
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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'}));
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff