diff --git a/website/control-panel/public/codex-code-format.mjs b/website/control-panel/public/codex-code-format.mjs index 8942b4fa..6f8448ed 100644 --- a/website/control-panel/public/codex-code-format.mjs +++ b/website/control-panel/public/codex-code-format.mjs @@ -1,6 +1,6 @@ // Shared syntax only: a readable edition is never proof of ownership or authority. -const legacy=/^(HOUSE|ORG|ITM|KSET|BRD|STAFF-CLAIM|SYS-ID|ESK|ACC-TEST|CLAN-ADM|PRJ|PRG|NEWS|XPC|XPX|ECO-SNAP|STAFF-LINK|STAFF-COM|STAFF-POL|XFR|CLAN-SUB|COM-SUB|POL-CLAN|QST|QSM|CLAN|COM|POL)-([A-F0-9]{48})$/; -const versioned=/^(HOUSE|ORG|ITM|KSET|BRD|STAFF-CLAIM|SYS-ID|ESK|ACC-TEST|CLAN-ADM|PRJ|PRG|NEWS|XPC|XPX|ECO-SNAP|STAFF-LINK|STAFF-COM|STAFF-POL|XFR|CLAN-SUB|COM-SUB|POL-CLAN|QST|QSM|CLAN|COM|POL)-(ALPHA|BETA|LIVE)-((?:0|[1-9]\d{0,2})(?:\.(?:0|[1-9]\d{0,2})){3})-(S\d{2,4})-([A-F0-9]{8}(?:-[A-F0-9]{8}){5})$/; +const legacy=/^(HOUSE|ORG|ITM|KSET|BRD|STAFF-CLAIM|SYS-ID|ESK|ACC-TEST|CLAN-ADM|PRJ|PRG|NEWS|XPC|XPX|ECO-SNAP|ECO|STAFF-LINK|STAFF-COM|STAFF-POL|XFR|CLAN-SUB|COM-SUB|POL-CLAN|QST|QSM|CLAN|COM|POL)-([A-F0-9]{48})$/; +const versioned=/^(HOUSE|ORG|ITM|KSET|BRD|STAFF-CLAIM|SYS-ID|ESK|ACC-TEST|CLAN-ADM|PRJ|PRG|NEWS|XPC|XPX|ECO-SNAP|ECO|STAFF-LINK|STAFF-COM|STAFF-POL|XFR|CLAN-SUB|COM-SUB|POL-CLAN|QST|QSM|CLAN|COM|POL)-(ALPHA|BETA|LIVE)-((?:0|[1-9]\d{0,2})(?:\.(?:0|[1-9]\d{0,2})){3})-(S\d{2,4})-([A-F0-9]{8}(?:-[A-F0-9]{8}){5})$/; export function parseOrganisationCode(value){ if(typeof value!=='string'||value.length>128)throw new TypeError('Invalid organisation code'); const code=value.trim().toUpperCase(),old=code.match(legacy); diff --git a/website/control-panel/public/cp-v2/cp-v2-economy-chart.mjs b/website/control-panel/public/cp-v2/cp-v2-economy-chart.mjs index 141c28c7..1a2f76ea 100644 --- a/website/control-panel/public/cp-v2/cp-v2-economy-chart.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-economy-chart.mjs @@ -29,7 +29,7 @@ export function mountEconomyChart(host,{fetcher=fetch}={}){ selector.onchange=()=>{selected=Number(selector.value);draw();showDetails();}; async function load(){request?.abort();const abort=new AbortController();request=abort;message.hidden=false;message.textContent='Loading sealed economic observations…';for(const b of periods.children)b.setAttribute('aria-pressed',String(b.dataset.period===period)); try{const response=await fetcher('/api/bank/public/economy?period='+period,{credentials:'omit',signal:AbortSignal.any([abort.signal,AbortSignal.timeout(15000)])}),data=await response.json();if(!response.ok)throw Error(data.message||'Economic observations unavailable.');if(!active||abort.signal.aborted)return; - records=data.records||[];selected=Math.max(0,records.length-1);selector.replaceChildren(...records.map((r,i)=>{const o=el('option',date(r.observedAt));o.value=String(i);return o;}));selector.value=String(selected);selection.hidden=!records.length;message.hidden=!!records.length;message.textContent='Economic history begins after the new budget and first sealed observation. No historical data has been invented.';draw();showDetails(); + records=data.records||[];selected=Math.max(0,records.length-1);selector.replaceChildren(...records.map((r,i)=>{const o=el('option',date(r.observedAt));o.value=String(i);return o;}));selector.value=String(selected);selection.hidden=!records.length;message.hidden=!!records.length;message.textContent=data.message||'Economic history begins after the new budget and first sealed observation. No historical data has been invented.';draw();showDetails(); }catch(e){if(active&&!abort.signal.aborted){records=[];plot.replaceChildren();details.replaceChildren();selection.hidden=true;message.textContent=e.message;}} } void load();return()=>{active=false;request?.abort();root.remove();}; diff --git a/website/control-panel/public/cp-v2/cp-v2-postbank-credit.mjs b/website/control-panel/public/cp-v2/cp-v2-postbank-credit.mjs index 0196b026..eaa629a5 100644 --- a/website/control-panel/public/cp-v2/cp-v2-postbank-credit.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-postbank-credit.mjs @@ -1,60 +1,60 @@ import {JARVIS_EXPANSION} from '../jarvis-brand.mjs'; 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||''}={}){ +export function mountPostbankCredit(host,id,{fetcher=fetch,reviewSearch=globalThis.location?.search||''}={}){ if(!document.querySelector('link[data-credit-dossier]')){const css=el('link');css.rel='stylesheet';css.href=new URL('./cp-v2-credit-dossier.css',import.meta.url).href;css.dataset.creditDossier='';document.head.append(css);} - 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); - } + 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:data.quote.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 pb-credit-dossier-header');header.append(el('small','J.A.R.V.I.S. · 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(' · ')));header.append(el('p',JARVIS_EXPANSION,'pb-credit-brand-name'));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 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;const facts=el('div',undefined,'pb-credit-detail-grid'),card=(title,copy)=>{const node=el('section',undefined,'pb-credit-fact-card');node.append(el('h4',title),copy);facts.append(node);return node;};card('Application',el('p',loan.motivation||'No motivation was provided.'));const terms=el('dl');for(const [label,value]of [['Annual interest',d.quote.annualRate+'%'],['Total repayment',d.quote.totalRepayment+' DM'],['First instalment',(d.quote.firstInstalment||'0.00')+' DM']])terms.append(el('dt',label),el('dd',value));if(typeof d.collateral==='string'&&d.collateral!=='0.00')terms.append(el('dt','Historical pledged collateral'),el('dd',d.collateral+' DM'));card('Contract terms',terms);const settlement=el('dl');settlement.append(el('dt','Settlement estimate today'),el('dd',d.settlement+' DM'));card('Settlement',settlement);card('Recorded decision',el('p',d.decision||'No decision recorded.'));body.replaceChildren(facts);if(d.codex){body.append(el('p','J.A.R.V.I.S. dossier: '+d.codex.reference+' · '+human(d.codex.status),'pb-credit-dossier-reference'));}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.','pb-credit-limit-note')); - 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();}; -} + 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;const facts=el('div',undefined,'pb-credit-detail-grid'),card=(title,copy)=>{const node=el('section',undefined,'pb-credit-fact-card');node.append(el('h4',title),copy);facts.append(node);return node;};card('Application',el('p',loan.motivation||'No motivation was provided.'));const terms=el('dl');for(const [label,value]of [['Annual interest',d.quote.annualRate+'%'],['Total repayment',d.quote.totalRepayment+' DM'],['First instalment',(d.quote.firstInstalment||'0.00')+' DM']])terms.append(el('dt',label),el('dd',value));if(typeof d.collateral==='string'&&d.collateral!=='0.00')terms.append(el('dt','Historical pledged collateral'),el('dd',d.collateral+' DM'));card('Contract terms',terms);const settlement=el('dl');settlement.append(el('dt','Settlement estimate today'),el('dd',d.settlement+' DM'));card('Settlement',settlement);card('Recorded decision',el('p',d.decision||'No decision recorded.'));body.replaceChildren(facts);if(d.codex){body.append(el('p','J.A.R.V.I.S. dossier: '+d.codex.reference+' · '+human(d.codex.status),'pb-credit-dossier-reference'));}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.','pb-credit-limit-note')); + if(enabled&&!staff){if(d.state==='offered')instruction(body,'Accept credit offer','/api/bank/credit/action',()=>({loanId:loan.id,action:'accept',expectedVersion:d.version,reason:'Accepted the disclosed credit offer'}),{reason:false,confirmation:'I accept the full repayment cost and authorise the first instalment from my own funds before the loan is issued. It reduces my remaining debt.'});if(['submitted','approved_pending','offered','payout_queued'].includes(d.state))instruction(body,'Withdraw application','/api/bank/credit/action',()=>({loanId:loan.id,action:'withdraw'}));if(['active','arrears'].includes(d.state))instruction(body,'Make a repayment','/api/bank/credit/action',()=>({loanId:loan.id,action:'repay'}),{amount:true,confirmation:'Debit the linked current account at the next four-hour bank window. Earned interest is charged; future interest is waived. Confirmed reserved funds retain their bank value date.'});} + if(enabled&&staff){if(d.state==='submitted'&&loan.canReview){const approveForm=instruction(body,'Approve application','/api/bank/admin/credit/decision',()=>({loanId:loan.id,action:'approve'}),{risk:loan.score.score<400||loan.score.flags.includes('High Monthly Commitments')});const declineForm=instruction(body,'Reject application','/api/bank/admin/credit/decision',()=>({loanId:loan.id,action:'decline'}));if(review?.loanId===loan.id){const selected=review.action==='approve'?approveForm:declineForm;selected.classList.add('pb-credit-selected-decision');selected.prepend(el('h3',review.action==='approve'?'Confirm approval':'Confirm rejection'));queueMicrotask(()=>{if(active){selected.scrollIntoView?.({block:'center',behavior:'smooth'});selected.querySelector?.('textarea')?.focus();}});}}if(d.state==='arrears')instruction(body,'Recover pledged collateral','/api/bank/admin/credit/recover',()=>({loanId:loan.id,action:'recover'}),{amount:true,confirmation:'Recover only this contract’s pledged DM to reduce its debt. No inventory is involved.'});} + if(d.schedule.length){const {wrap,body:rows}=grid(['Due date','Principal · DM','Interest · DM','Paid · DM','Status']);for(const row of d.schedule){const tr=el('tr');for(const value of [new Date(row.dueAt).toLocaleDateString('en-GB'),row.principal,row.interest,row.paid,human(row.state)])tr.append(el('td',value));rows.append(tr);}body.append(wrap);}else body.append(el('p','The repayment schedule starts only when funds are disbursed.'));const history=el('details');history.append(el('summary','Dossier history'));if(Array.isArray(d.events)&&d.events.length){const {wrap,body:rows}=grid(['Recorded','Action']);for(const event of d.events){const row=el('tr');row.append(el('td',new Date(event.createdAt).toLocaleString('en-GB')),el('td',human(event.action)));rows.append(row);}history.append(wrap);}else history.append(el('p',Array.isArray(d.events)?'No dossier events are recorded.':'Dossier history is unavailable.'));body.append(history);if(review?.loanId===loan.id&&(!enabled||!loan.canReview||d.state!=='submitted')){const explanation=d.state!=='submitted'?'This application is already '+human(d.state).toLowerCase()+'.':!enabled?'Credit decisions are unavailable for your account or processing is paused.':'A different bank manager must review this application because you submitted it or control its borrowing account. No decision has been recorded; the J.A.R.V.I.S. dossier remains pending.';const message=el('aside',explanation,'pb-credit-notice');message.setAttribute('role','status');body.prepend(message);queueMicrotask(()=>{if(active)message.scrollIntoView?.({block:'center'});});} + }catch(error){if(active){body.textContent=error.message;loaded=false;}}};return expand; + } + function myCredit(){const {wrap,body}=grid(['Application','Product','Status','Principal · DM','Outstanding · DM','Monthly · DM','Details']);for(const loan of view.loans){const tr=el('tr'),cell=el('td'),expanded=el('tr'),content=el('td');expanded.className='pb-credit-detail-row';expanded.hidden=true;content.colSpan=7;expanded.append(content);contractDetails(cell,loan,false,expanded);for(const value of [loan.codex?.reference||codexLoanReference(loan.id),human(loan.productKey),human(loan.state),loan.principal,loan.outstanding,loan.monthly])tr.append(el('td',value));tr.append(cell);body.append(tr,expanded);}frame.content.append(wrap);if(!view.loans.length)frame.content.append(el('p','No applications or loans are registered for your authorised banking clients.'));} + function management(){frame.content.append(el('p',view.processing==='active'?'Review the evidence before deciding. Treasury funds are reserved for approved offers; the borrower must accept before disbursement.':'Credit processing is not active yet.','pb-muted'));const {wrap,body}=grid(['Client','Product','Submitted','Amount · DM','State','Review']);for(const loan of view.applications){const tr=el('tr'),cell=el('td'),expanded=el('tr'),content=el('td');expanded.className='pb-credit-detail-row';expanded.hidden=true;content.colSpan=6;expanded.append(content);cell.append(el('p','Credit score: '+loan.score.score+' / 1000 · '+loan.score.band+(loan.score.limitedHistory?' · Limited history':'')),el('p',loan.score.flags.join(' · ')));const details=contractDetails(cell,loan,true,expanded);if(review?.loanId===loan.id)queueMicrotask(()=>{if(active){details.open=true;void details.ontoggle();}});for(const value of [loan.entity,human(loan.productKey),new Date(loan.createdAt).toLocaleDateString('en-GB'),loan.principal,human(loan.state)])tr.append(el('td',value));tr.append(cell);body.append(tr,expanded);}frame.content.append(wrap);if(!view.applications.length)frame.content.append(el('p',review?'This credit application was not found or is unavailable to your account.':'No credit applications are awaiting review.'));if(review){const back=el('a','View all credit applications');back.href='/#bank/loan-administration';frame.content.prepend(el('p','Reviewing the linked J.A.R.V.I.S. application dossier. No decision is submitted until you confirm.'),back);}} + void load();return()=>{active=false;abort.abort();frame.root.remove();}; +} diff --git a/website/control-panel/public/jarvis-master-keys.mjs b/website/control-panel/public/jarvis-master-keys.mjs index e7e3c9c9..110ad55c 100644 --- a/website/control-panel/public/jarvis-master-keys.mjs +++ b/website/control-panel/public/jarvis-master-keys.mjs @@ -27,7 +27,7 @@ export const MASTER_KEY_TEMPLATES=[ {id:'boards',label:'Organisation boards',actions:[ action('boards.state','Deed-linked board state','board-state',[field('kind','Organisation kind'),field('id','Organisation')],{webIssue:false,recordOnly:true,domainAdapter:'boardStateKeys.refresh',executionStatus:'resolved-deed-background-publication',effect:'One writable BRD dossier follows the complete current deed and roster. The native publisher preserves existing forum IDs and content; page reads cannot provision boards.'}), action('boards.delegate-control','Temporarily delegate board control','staff-parent-link',[field('kind','Organisation kind'),field('id','Organisation'),field('memberId','Current member'),field('expiresAt','Expiry','datetime-local'),field('reason','Staff reason')],{webIssue:false,domainAdapter:'boardDelegations.issue',executionStatus:'scoped-forum-staff-service',effect:'Existing expiring staff overwrite key delegates only board management. Revocation, expiry, member departure or a source ownership transfer restores the current deed policy. No ownership, bank, vote or game permissions change.'})]}, - {id:'economy',label:'Economy',actions:[action('economy.snapshot','Sealed economic snapshot','economy-snapshot',[field('snapshotId','Verified snapshot'),reference],{recordOnly:true})]}, + {id:'economy',label:'Economy',actions:[action('economy.snapshot','Sealed economic snapshot','economy-snapshot',[field('snapshotId','Verified snapshot'),reference],{recordOnly:true}),action('economy.reset-balances','Authorised ledger-preserving economic reset','economy-operation',[field('epoch','Explicit seasonal reset ID')],{webIssue:false,domainAdapter:'createEconomyReset',executionStatus:'private-scoped-system-consumer',effect:'Explicit server execution only. Consume one approved seasonal instrument, lock every bank account, reject unresolved reservations/payments and return all balances including issuers to zero through balanced two-leg ledger orders. Retain accounts, contracts, owners and financial history. One bank receipt prevents a retry from erasing later earnings. Enable Federal Reserve awaiting the first completed post-reset payroll; never run payroll or reset on startup.'}),action('economy.federal-cycle','Federal Reserve daily economic cycle','economy-operation',[field('epoch','Current economic epoch'),field('day','Brussels policy day')],{webIssue:false,domainAdapter:'createFederalReserve',executionStatus:'scoped-central-scheduler',effect:'One daily instrument follows actual customer circulation and a positive funded payroll baseline. Bound spice buyback movement to 5% daily within 0.5–2 times its base; new-loan rates move at most 25 basis points daily and fixed contracts remain unchanged. Monthly wage policy moves by at most 5%; this service never executes payroll. Seal each economic observation. Player Exchange prices, taxes and existing package contracts remain under their existing authority.'})]}, {id:'claims',label:'Home Blocks',actions:[action('claims.home-relocate','Move an organisation Home Block','organisation-action',[field('kind','Clan or company'),field('id','Organisation'),field('worldKey','Destination world'),field('quoteHash','Reviewed quote hash'),field('sourceAccount','Authorised funding account'),field('requestId','Request UUID')],{webIssue:false,recordOnly:true,domainAdapter:'createHomeRelocation.accept',executionStatus:'authenticated-claim-manager',effect:'Atomically charge 10% of the eligible treasury (Basic: owner personal accounts) and issue one relocation instrument. Deny active wars and fixed official offices. Hide the old Home Block until its source connector confirms native and WorldGuard cleanup. Preserve charter capacity, deed, rosters, bank and history. Clan destination follows the current owner race; company chooses its world. Set the physical replacement through the existing game menu.'}),action('claims.game-expand','Expand registered estate','organisation-action',[field('kind','Organisation kind'),field('id','Organisation'),field('uuid','Current player UUID'),field('direction','Expansion direction','select',{options:['north','east','south','west','all']}),field('expectedRevision','Estate revision','number',{min:1})],{webIssue:false,recordOnly:true,domainAdapter:'createGameOrganisations.execute',executionStatus:'authenticated-game-service',effect:'Expand an existing estate within its already paid central-bank claim entitlement. Revalidate current deed, home world, estate revision, overlap and active war. Preserve the Home Block and unrelated native land; only the connector projects approved chunks into Factions/Towny. No native player claim permissions are granted.'}),action('claims.game-home','Register a game Home Block','organisation-action',[field('kind','Organisation kind'),field('id','Organisation'),field('uuid','Current Minecraft UUID'),field('requestId','Request UUID'),field('expectedRevision','Claim revision','number',{min:0})],{webIssue:false,recordOnly:true,domainAdapter:'createGameOrganisations.execute',executionStatus:'authenticated-game-service',effect:'Record the current player position under the current organisation deed. Preserve upgraded estates, deny world changes and active wars, and project only one native Home Block claim.'}),action('transport.home','Personal home journey','organisation-action',[field('uuid','Linked Minecraft UUID'),field('requestId','Journey UUID'),field('server','Native backend'),field('destinationHash','Saved home digest')],{webIssue:false,recordOnly:true,domainAdapter:'createHomeTravelService.execute',executionStatus:'authenticated-game-service',effect:'DuneEss waits five seconds and validates a same-world saved home. Reserve 25 DM in the central personal bank; settle once after native arrival. A durable native journal retries uncertain outcomes. Failed teleports release the reservation. Fifteen-minute global cooldown follows successful arrival, with no expiry script or Guild quest credit.'}),action('transport.guild','Imperial Guild passage','organisation-action',[field('uuid','Current Minecraft UUID'),field('requestId','Request UUID'),field('keyId','Current House key'),field('version','House version','number',{min:1}),field('fareMinor','Quoted fare in minor units','number',{min:1})],{webIssue:false,recordOnly:true,domainAdapter:'createGuildService',executionStatus:'authenticated-game-service',effect:'Reserve the central personal account fare only during boarding for the current House world. Settle once on destination arrival; expire failed transfers without charging. Arrival records the verified Guild travel quest milestone.'}),action('transport.organisation','Organisation passage or war deployment','organisation-action',[field('kind','Organisation kind'),field('id','Organisation'),field('uuid','Current Minecraft UUID'),field('requestId','Request UUID')],{webIssue:false,recordOnly:true,domainAdapter:'createGameOrganisations.execute',executionStatus:'authenticated-game-service',effect:'Revalidate membership and destination. Issue a short-lived arrival receipt during the shared five-minute boarding window; war deployment additionally requires an active war key. No native instant-travel authority or personal wallet is used.'}),action('claims.remove-homeblock','Remove Home Block with staff overwrite','staff-claim',[field('kind','Organisation kind'),field('id','Organisation'),field('expectedRevision','Current claim revision','number',{min:1}),field('reason','Staff reason')],{webIssue:false,domainAdapter:'staffHomeBlockKeys',executionStatus:'staff-key-consumer',effect:'Remove only the Home Block marker through existing staff overwrite authority. Preserve estates, balances, rosters and history. Existing rebellion checks then deny the chain; no control panel or timer.'})]}, {id:'state',label:'Entity state',actions:[action('state.estate-freeze','Freeze estate from lore-death ESK','entity-state',[field('keyId','Verified lore-death ESK'),reference],{domainAdapter:'PostbankEstates.freeze',executionStatus:'bank-staff-consumer',effect:'Restrict existing personal accounts using a verified lore-death ESK; no balance changes.'}),action('state.estate-unlock','Unlock ESK estate','entity-state',[field('keyId','Existing ESK'),field('revision','Current bank effect revision','number',{min:1}),reference],{domainAdapter:'PostbankEstates.unlock',executionStatus:'bank-staff-consumer',effect:'Bank staff restore only the accounts held by the named ESK. Original death evidence remains unchanged.'}),action('state.record','Entity State Key','entity-state',[field('eventId','Unique source event ID'),field('action','State event'),field('targetUuid','Target entity UUID'),field('targetKind','Player or mob'),field('entityType','Entity type'),field('actorUuid','Killer / actor UUID','text',{required:false}),field('cause','Cause / reason'),field('scope','Server / lore scope'),field('world','World'),field('occurredAt','Event timestamp','number',{min:0}),reference],{recordOnly:true,domainAdapter:'entityStateKeys',executionStatus:'verified-service-record',artwork:'esk-key-v1.png',effect:'Record a verified death, respawn, ban or unban. Shared quest/contract/deed evidence with separate once-only consumer receipts. No Minecraft producer or ban migration in this batch.'})]}, {id:'progression',label:'Progression & XP',actions:[ diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs index 652af1a5..cf160a44 100644 --- a/website/control-panel/server.mjs +++ b/website/control-panel/server.mjs @@ -1,3 +1,4 @@ +import {createEconomyRuntime} from '../node/economy-runtime.mjs'; import {createWarExchange} from '../node/war-exchange.mjs'; import {createMilitaryAffiliations} from '../node/war-military-affiliations.mjs'; import {createGameWarAPI,createClanCampaignResolver,createClanWarSettlementAdapter,createClanRosterResolver} from '../node/game-wars.mjs'; @@ -563,7 +564,7 @@ export async function startPanel(settings=process.env){ const bankDatabase=await openPostbankDatabase(settings); const db=await openDatabase(settings);await initializeItemDesigns(db);await initializeKitsets(db);await initializeResearchSpecialists(db);await db.query(POLITICAL_DECISION_SCHEMA);db.politicalDecisionsEnabled=true;await db.query(FAITH_BLESSING_SCHEMA);db.faithBlessingsEnabled=true;await db.query(IMPERIAL_PASSAGE_SCHEMA);await db.query(HOUSE_SELECTION_SCHEMA);await db.query(GAME_ORGANISATION_SCHEMA);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await initializeJarvisGenerator(db);await initializeEntityState(db);await initializeSystemCharacters(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys); /* Passive POL conversion waits for scoped adapters instead of company management. */await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;await initializeProgression(db);await initializeStarterKitEvents(db);db.starterKitEventsEnabled=true;await initializeServerProjects(db);if(bankDatabase)await bankDatabase.query(PROJECT_BANK_SCHEMA);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);await ensureStarterKitRewardPolicy(db,organisationKeys).catch(()=>console.error('Starter kit reward policy requires review; existing custom configuration was preserved'));await initializePOLProgression(db);await initializeSecondaryAffiliations(db);await initializePersonalActivityEvents(db);db.personalActivityEventsEnabled=true;await initializePOLActivityEvents(db);db.polActivityEventsEnabled=true;await initializeRebellionRewards(db);await ensurePOLProgressionPolicy(db,organisationKeys);await ensurePOLRepeatablePolicy(db,organisationKeys);await ensureElytraQuestPolicy(db,organisationKeys);await ensurePOLMentorPolicy(db,organisationKeys);db.polMentorBonusEnabled=true;db.polRepeatablesEnabled=true;db.organisationResearchEnabled=true;db.researchSuppliesEnabled=true;const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const deedPurchases=bankDatabase&&settings.POSTBANK_ENABLED==='true'?createDeedPurchases(db,bankDatabase,organisationKeys,{authority:createPostbankAuthority(db,{bank:bankDatabase})}):null;const starterKitDelivery=await openStarterKitDelivery(db,settings);const boardRuntime=await openBoardKeyRuntime(db,organisationKeys,settings);const handle=createPanel(db,settings,{boardRuntime,inventoryPool,bankDatabase,organisationKeys,deedPurchases,officeAuctionRuntime,promotionDelivery,progressionRuntime}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com'; await initializeInternalMailAccess(db);const stopElectionClock=startElectionClock(db);const stopOfficeLedger=startOfficeLedger(db); - const stopBanSync=startModerationSync(db,settings),stopInternalMail=startInternalMailSync(db,{jarvisStore:bankDatabase}),stopCentralScheduler=startCentralScheduler(db,bankDatabase,settings,{extraTasks:[...(settings.MILITARY_PROJECTION_ENABLED==='true'&&organisationKeys?[{key:'military_affiliations',slot:now=>Math.floor(now/60000)*60000,run:()=>createMilitaryAffiliations(db,organisationKeys).drain()}]:[]),{key:'starter_kit_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>starterKitDelivery.drain()},...(boardRuntime?[{key:'board_keys',slot:now=>Math.floor(now/60000)*60000,run:()=>boardRuntime.drain()}]:[]),...(bankDatabase?[{key:'research_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createResearchFundedRewards(db,bankDatabase).drain()},{key:'pol_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createPOLFundedRewards(db,bankDatabase,organisationKeys).drain()},{key:'rebellion_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createRebellionRewards(db,bankDatabase,{sourceAccount:settings.REBELLION_REWARD_SOURCE_ACCOUNT,sourceOwnerId:settings.REBELLION_REWARD_SOURCE_OWNER_ID,useWebsiteTreasury:settings.REBELLION_REWARD_FUND==='website-treasury'}).drain()},...(deedPurchases?[{key:'deed_purchases',slot:now=>Math.floor(now/60000)*60000,run:()=>deedPurchases.drain()}]:[]),{key:'server_projects',slot:now=>Math.floor(now/60000)*60000,run:()=>createServerProjectRuntime(db,bankDatabase,organisationKeys).drain()},{key:'progression_completion',slot:now=>Math.floor(now/60000)*60000,run:async()=>{const completed=await progressionRuntime.quests.processCompletions();const news=await progressionRuntime.announcements.drain();return {completed,news};}},{key:'naib_council',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await reconcileNaibChairs(db);return createNaibCouncil(db).reconcile();}},{key:'jarvis_promotions',slot:now=>Math.floor(now/15000)*15000,run:()=>promotionDelivery.drain()},{key:'political_jobs',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await createPoliticalJobs(db,bankDatabase).reconcile();return drainPoliticalJobNotifications(db,{broker:internalMailBroker,eligible:internalMailEligible});}},{key:'order_membership',slot:now=>Math.floor(now/60000)*60000,run:()=>reconcileCrysknifeCompany(db,organisationKeys)},{key:'office_auctions',slot:now=>Math.floor(now/60000)*60000,run:()=>officeAuctionRuntime.process()},{key:'jarvis_settlement',slot:now=>standardCycle(now).cutoff,async run(cutoff){const payments=createJarvisPayments(bankDatabase,createPostbankAuthority(db,{bank:bankDatabase}));for(let i=0;i<40;i++){const result=await payments.settle(cutoff);if(result.failed)return result;if(result.attempted<100)return result;}return {failed:1};}}]:[])]}); + const stopBanSync=startModerationSync(db,settings),stopInternalMail=startInternalMailSync(db,{jarvisStore:bankDatabase}),stopCentralScheduler=startCentralScheduler(db,bankDatabase,settings,{extraTasks:[...(settings.MILITARY_PROJECTION_ENABLED==='true'&&organisationKeys?[{key:'military_affiliations',slot:now=>Math.floor(now/60000)*60000,run:()=>createMilitaryAffiliations(db,organisationKeys).drain()}]:[]),{key:'starter_kit_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>starterKitDelivery.drain()},...(boardRuntime?[{key:'board_keys',slot:now=>Math.floor(now/60000)*60000,run:()=>boardRuntime.drain()}]:[]),...(bankDatabase?[{key:'federal_reserve',slot:now=>Math.floor(now/60000)*60000,run:()=>createEconomyRuntime(db,bankDatabase,organisationKeys).federal.run()},{key:'research_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createResearchFundedRewards(db,bankDatabase).drain()},{key:'pol_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createPOLFundedRewards(db,bankDatabase,organisationKeys).drain()},{key:'rebellion_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createRebellionRewards(db,bankDatabase,{sourceAccount:settings.REBELLION_REWARD_SOURCE_ACCOUNT,sourceOwnerId:settings.REBELLION_REWARD_SOURCE_OWNER_ID,useWebsiteTreasury:settings.REBELLION_REWARD_FUND==='website-treasury'}).drain()},...(deedPurchases?[{key:'deed_purchases',slot:now=>Math.floor(now/60000)*60000,run:()=>deedPurchases.drain()}]:[]),{key:'server_projects',slot:now=>Math.floor(now/60000)*60000,run:()=>createServerProjectRuntime(db,bankDatabase,organisationKeys).drain()},{key:'progression_completion',slot:now=>Math.floor(now/60000)*60000,run:async()=>{const completed=await progressionRuntime.quests.processCompletions();const news=await progressionRuntime.announcements.drain();return {completed,news};}},{key:'naib_council',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await reconcileNaibChairs(db);return createNaibCouncil(db).reconcile();}},{key:'jarvis_promotions',slot:now=>Math.floor(now/15000)*15000,run:()=>promotionDelivery.drain()},{key:'political_jobs',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await createPoliticalJobs(db,bankDatabase).reconcile();return drainPoliticalJobNotifications(db,{broker:internalMailBroker,eligible:internalMailEligible});}},{key:'order_membership',slot:now=>Math.floor(now/60000)*60000,run:()=>reconcileCrysknifeCompany(db,organisationKeys)},{key:'office_auctions',slot:now=>Math.floor(now/60000)*60000,run:()=>officeAuctionRuntime.process()},{key:'jarvis_settlement',slot:now=>standardCycle(now).cutoff,async run(cutoff){const payments=createJarvisPayments(bankDatabase,createPostbankAuthority(db,{bank:bankDatabase}));for(let i=0;i<40;i++){const result=await payments.settle(cutoff);if(result.failed)return result;if(result.attempted<100)return result;}return {failed:1};}}]:[])]}); const security={'X-Robots-Tag':'noindex, nofollow, noarchive','X-Content-Type-Options':'nosniff','Referrer-Policy':'no-referrer','Cache-Control':'no-store','Content-Security-Policy':PANEL_SERVICE_CSP}; const server=createServer(async(req,res)=>{try{ req.setTimeout(req.url==='/api/internal-mail/messages/send'?120000:30000);const bodyLimit=panelBodyLimit(req.method,req.url);let length=0;const chunks=[];for await(const chunk of req){length+=chunk.length;if(length>bodyLimit){res.writeHead(413,{...security,'Content-Type':'application/json'});res.end(JSON.stringify({message:'The upload exceeds the permitted request size.'}));return;}chunks.push(chunk);} diff --git a/website/integrations/osticket/dev-jarvis-catalogue.json b/website/integrations/osticket/dev-jarvis-catalogue.json index dd3f920b..33a4a114 100644 --- a/website/integrations/osticket/dev-jarvis-catalogue.json +++ b/website/integrations/osticket/dev-jarvis-catalogue.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "sourceHash": "6a32cfb6fe8f61f367efbbab9c1aacbb99e7740a0543bd6c53cddfa6b774cb42", + "sourceHash": "729cc6f156f363bcdaa6b9302bf4cfe71aa89c57cf177216ce6b424344d61060", "actions": [ { "id": "war.calendar-agreement", @@ -842,6 +842,62 @@ "webIssue": false, "recordOnly": true }, + { + "id": "economy.reset-balances", + "label": "Economy · Authorised ledger-preserving economic reset", + "version": 1, + "keyType": "economy-operation", + "fields": [ + { + "name": "ticketId", + "label": "Ban / support ticket ID", + "type": "text", + "required": true, + "maxLength": 80 + }, + { + "name": "epoch", + "label": "Explicit seasonal reset ID", + "type": "text", + "required": true + } + ], + "effect": "Explicit server execution only. Consume one approved seasonal instrument, lock every bank account, reject unresolved reservations/payments and return all balances including issuers to zero through balanced two-leg ledger orders. Retain accounts, contracts, owners and financial history. One bank receipt prevents a retry from erasing later earnings. Enable Federal Reserve awaiting the first completed post-reset payroll; never run payroll or reset on startup.", + "fixedTargets": [], + "webIssue": false, + "recordOnly": false + }, + { + "id": "economy.federal-cycle", + "label": "Economy · Federal Reserve daily economic cycle", + "version": 1, + "keyType": "economy-operation", + "fields": [ + { + "name": "ticketId", + "label": "Ban / support ticket ID", + "type": "text", + "required": true, + "maxLength": 80 + }, + { + "name": "epoch", + "label": "Current economic epoch", + "type": "text", + "required": true + }, + { + "name": "day", + "label": "Brussels policy day", + "type": "text", + "required": true + } + ], + "effect": "One daily instrument follows actual customer circulation and a positive funded payroll baseline. Bound spice buyback movement to 5% daily within 0.5–2 times its base; new-loan rates move at most 25 basis points daily and fixed contracts remain unchanged. Monthly wage policy moves by at most 5%; this service never executes payroll. Seal each economic observation. Player Exchange prices, taxes and existing package contracts remain under their existing authority.", + "fixedTargets": [], + "webIssue": false, + "recordOnly": false + }, { "id": "claims.home-relocate", "label": "Home Blocks · Move an organisation Home Block", diff --git a/website/node/economy-operations.mjs b/website/node/economy-operations.mjs new file mode 100644 index 00000000..9401913e --- /dev/null +++ b/website/node/economy-operations.mjs @@ -0,0 +1,41 @@ +import {createHash} from 'node:crypto'; +import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs'; +export const ECONOMY_OPERATION_SCHEMA=`CREATE TABLE IF NOT EXISTS pb_economy_operations(id CHAR(36) PRIMARY KEY,key_id CHAR(36) NOT NULL UNIQUE,action_id VARCHAR(80) NOT NULL,manifest_hash CHAR(64) NOT NULL,receipt_json MEDIUMTEXT NOT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`; +export const economyHash=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex'); +export function economyId(value){const h=economyHash(value);return h.slice(0,8)+'-'+h.slice(8,12)+'-4'+h.slice(13,16)+'-a'+h.slice(17,20)+'-'+h.slice(20,32);} +const first=(db,sql,args=[])=>db.first?db.first(sql,args):db.prepare(sql).bind(...args).first(); +// Central authority is consumed first; the separate bank commits one immutable +// receipt. If the reply is lost, the same key recovers that receipt without +// applying another reset or changing money received after the first commit. +export function createEconomyOperations(central,bank,keys,{authorize,clock=Date.now}={}){ + if(!keys||typeof authorize!=='function')throw TypeError('Verified economic authority required'); + return async({action,id,fields,apply})=>{ + if(!['economy.reset-balances','economy.federal-cycle'].includes(action)||typeof apply!=='function')throw TypeError('Unsupported economic operation'); + const manifest={schema:1,action,id,fields},encoded=JSON.stringify(manifest),fingerprint=economyHash(manifest),load=store=>first(store,'SELECT * FROM jarvis_generated_instructions WHERE request_id=? AND action_id=?',[id,action]); + const previous=await load(central);if(previous&&previous.fields_json!==encoded)throw Error('Economic instruction reference conflict'); + if(previous?.state==='applied')return {...JSON.parse(previous.manifest_json).receipt,replayed:true}; + const grant=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'economy-operation',scopeId:action+':'+id,authorize:async(tx,{keyId})=>{ + await authorize(tx,manifest);const old=await load(tx);if(old){if(old.fields_json!==encoded)throw Error('Economic instruction changed');return;} + await tx.query("INSERT INTO jarvis_generated_instructions VALUES(?,?,?,?,1,?,?,'issued',?)",[keyId,id,STAFF_OFFICE_ACCOUNT_ID,action,encoded,JSON.stringify({manifest}),clock()]); + }}); + let instruction=await load(central);if(instruction?.key_id!==grant.id||instruction.fields_json!==encoded)throw Error('Economic key binding changed'); + if(instruction.state==='issued'){ + const available=(await keys.list(STAFF_OFFICE_ACCOUNT_ID)).find(k=>k.id===grant.id&&k.status==='available');if(!available?.code)throw Error('Economic system key unavailable'); + await keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'economy-operation',code:available.code,targetId:id,requestId:id,apply:async(tx,{keyId,scopeId})=>{ + const locked=await load(tx);if(scopeId!==action+':'+id||locked?.key_id!==keyId||locked.fields_json!==encoded||locked.state!=='issued')throw Error('Economic key scope changed');await authorize(tx,manifest); + await tx.query("UPDATE jarvis_generated_instructions SET state='queued' WHERE key_id=?",[keyId]); + }}); + } + instruction=await load(central);if(!['queued','applied'].includes(instruction?.state))throw Error('Economic operation is not authorised'); + if(instruction.state==='applied')return {...JSON.parse(instruction.manifest_json).receipt,replayed:true}; + const result=await bank.transaction(async tx=>{ + const receipt=await tx.first('SELECT * FROM pb_economy_operations WHERE id=? FOR UPDATE',[id]);if(receipt){if(receipt.key_id!==grant.id||receipt.manifest_hash!==fingerprint)throw Error('Economic bank receipt conflict');return {...JSON.parse(receipt.receipt_json),replayed:true};} + // Recheck the consumed instrument before the first bank mutation. + const key=await first(central,'SELECT used_at,revoked_at FROM organisation_keys WHERE id=?',[grant.id]);if(key?.used_at==null||key.revoked_at!==null)throw Error('Consumed economic authority required'); + await authorize(null,manifest); + const value=await apply(tx,{keyId:grant.id,id,manifest,now:clock()}); + await tx.query('INSERT INTO pb_economy_operations VALUES(?,?,?,?,?,?)',[id,grant.id,action,fingerprint,JSON.stringify(value),clock()]);return value; + }); + await central.query("UPDATE jarvis_generated_instructions SET state='applied',manifest_json=? WHERE key_id=? AND state='queued'",[JSON.stringify({manifest,receipt:result}),grant.id]);return result; + }; +} diff --git a/website/node/economy-reset.mjs b/website/node/economy-reset.mjs new file mode 100644 index 00000000..3f719fdc --- /dev/null +++ b/website/node/economy-reset.mjs @@ -0,0 +1,29 @@ +import {economyId,economyHash} from './economy-operations.mjs'; +import {initialiseFederalReserve} from './federal-reserve.mjs'; +const min=-9223372036854775808n,max=9223372036854775807n; +export function createEconomyReset(operate,{actorId,epoch='s1-economy-20261124'}={}){ + if(!actorId||!/^[-a-z0-9_]{1,64}$/.test(epoch))throw TypeError('Explicit authorised reset identity required'); + return ()=>operate({action:'economy.reset-balances',id:economyId(['balance-reset',epoch]),fields:{epoch,allAccounts:true,preserveOwners:true,preserveContracts:true,preserveHistory:true,enableFederalReserve:true,payroll:false},apply:async(tx,{now,keyId,id})=>{ + const accounts=await tx.query('SELECT id,system_key,balance_minor,reserved_minor,state FROM pb_accounts ORDER BY id FOR UPDATE'); + if(!accounts.length||accounts.length>10000||accounts.some(a=>BigInt(a.reserved_minor)!==0n))throw Error('Economic reset requires reconciled account reservations'); + const pending=await tx.first("SELECT id FROM pb_orders WHERE state NOT IN ('posted','failed','cancelled','rejected') AND NOT(mode='claimref' AND state='included') LIMIT 1 FOR UPDATE");if(pending)throw Error('A pending payment must finish before the economic reset'); + if(accounts.reduce((sum,a)=>sum+BigInt(a.balance_minor),0n)!==0n)throw Error('The ledger is not balanced; refusing an unbalanced reset'); + const issuer=accounts.find(a=>a.system_key==='sys_bank_capital_issuer');if(!issuer)throw Error('Federal Reserve ledger account unavailable'); + const before=accounts.map(a=>({id:String(a.id),balanceMinor:String(a.balance_minor)})),startEntries=await tx.first('SELECT COUNT(*) n FROM pb_entries');let issuerBalance=BigInt(issuer.balance_minor),movements=0; + // Return positive balances first, then clear negative issuer balances. Every + // reset movement has exactly two ledger legs; no posted history is erased. + const targets=accounts.filter(a=>String(a.id)!==String(issuer.id)&&BigInt(a.balance_minor)!==0n).sort((a,b)=>Number(BigInt(b.balance_minor)>0n)-Number(BigInt(a.balance_minor)>0n)); + for(const account of targets){ + const balance=BigInt(account.balance_minor),amount=balance>0n?balance:-balance;if(amount>max)throw Error('Reset movement exceeds ledger limit'); + issuerBalance+=balance;if(issuerBalancemax)throw Error('Reset issuer balance exceeds ledger range'); + const from=balance>0n?account:issuer,to=balance>0n?issuer:account,orderId=economyId([id,'account',String(account.id)]),fingerprint=economyHash([keyId,orderId,String(amount)]); + await tx.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at,posted_at) VALUES(?,?,?,?,?,?,?,'reset','posted',?,?)",[orderId,actorId,from.id,to.id,fingerprint,String(amount),'Economic reset · '+epoch,now,now]); + await tx.query('UPDATE pb_accounts SET balance_minor=0 WHERE id=?',[account.id]);await tx.query('UPDATE pb_accounts SET balance_minor=? WHERE id=?',[String(issuerBalance),issuer.id]); + for(const [a,change,after]of [[account,-balance,0n],[issuer,balance,issuerBalance]])await tx.query('INSERT INTO pb_entries(order_id,account_id,amount_minor,balance_after_minor,created_at) VALUES(?,?,?,?,?)',[orderId,a.id,String(change),String(after),now]);movements++; + } + if(issuerBalance!==0n||await tx.first('SELECT id FROM pb_accounts WHERE balance_minor<>0 OR reserved_minor<>0 LIMIT 1'))throw Error('Economic reset did not reach zero'); + await initialiseFederalReserve(tx,{epoch,resetAt:now,actor:actorId}); + const receipt={resetId:id,keyId,epoch,resetAt:now,accounts:accounts.length,changedAccounts:before.filter(a=>a.balanceMinor!=='0').length,movements,ledgerEntriesBefore:Number(startEntries.n),beforeHash:economyHash(before),beforeBalances:before,allBalancesZero:true,federalReserve:'enabled-awaiting-payroll',payrollExecuted:false}; + await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,NULL,?,?)',[id,actorId,'economy_balances_reset',JSON.stringify(receipt),now]);return receipt; + }}); +} diff --git a/website/node/economy-runtime.mjs b/website/node/economy-runtime.mjs new file mode 100644 index 00000000..91e56c88 --- /dev/null +++ b/website/node/economy-runtime.mjs @@ -0,0 +1,21 @@ +import {createEconomyOperations} from './economy-operations.mjs'; +import {createEconomyReset} from './economy-reset.mjs'; +import {createFederalReserve,readFederalReserve,federalDay} from './federal-reserve.mjs'; +import {createEconomicSnapshots} from './jarvis-economic-snapshots.mjs'; +import {OFFICIAL_ACCOUNT} from './official-account.mjs'; +import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs'; +export const ECONOMY_EPOCH='s1-economy-20261124'; +export function createEconomyRuntime(central,bank,keys,{allowReset=false,epoch=ECONOMY_EPOCH,clock=Date.now}={}){ + const owner=async tx=>{const db=tx||central;const row=db.first?await db.first("SELECT id FROM site_accounts WHERE id=? AND username='unimatrix999' AND password_hash NOT LIKE '!%'",[OFFICIAL_ACCOUNT.ownerId]):await db.prepare("SELECT id FROM site_accounts WHERE id=? AND username='unimatrix999' AND password_hash NOT LIKE '!%'").bind(OFFICIAL_ACCOUNT.ownerId).first();if(!row)throw Error('The authorised economy owner is unavailable');}; + const operate=createEconomyOperations(central,bank,keys,{clock,authorize:async(tx,manifest)=>{ + if(manifest.action==='economy.reset-balances'){if(!allowReset||manifest.fields.epoch!==epoch||manifest.fields.allAccounts!==true||manifest.fields.payroll!==false)throw Error('This reset is not authorised');await owner(tx);} + else{const fed=await readFederalReserve(bank);if(!fed?.enabled||fed.epoch!==manifest.fields.epoch||manifest.fields.day!==federalDay(clock()))throw Error('The economic cycle is not current');} + }}); + const recordSnapshot=async observation=>{ + const rows=await bank.query("SELECT key_id,receipt_json FROM pb_economy_operations WHERE action_id='economy.federal-cycle' ORDER BY created_at DESC LIMIT 8"),proof=rows.find(r=>JSON.parse(r.receipt_json).observation?.id===observation.id); + if(!proof||JSON.stringify(JSON.parse(proof.receipt_json).observation)!==JSON.stringify(observation))throw Error('Sealed bank observation required'); + const snapshots=createEconomicSnapshots(central,keys,{clock,authorize:async(actor,tx)=>actor.id===STAFF_OFFICE_ACCOUNT_ID&&!!await tx.first('SELECT id FROM organisation_keys WHERE id=? AND used_at IS NOT NULL AND revoked_at IS NULL',[proof.key_id])}); + return snapshots.capture({id:STAFF_OFFICE_ACCOUNT_ID},observation); + }; + return {reset:createEconomyReset(operate,{actorId:OFFICIAL_ACCOUNT.ownerId,epoch}),federal:createFederalReserve(bank,operate,{actorId:STAFF_OFFICE_ACCOUNT_ID,clock,recordSnapshot})}; +} diff --git a/website/node/federal-reserve.mjs b/website/node/federal-reserve.mjs new file mode 100644 index 00000000..8faab138 --- /dev/null +++ b/website/node/federal-reserve.mjs @@ -0,0 +1,57 @@ +import {ECONOMY_POLICY,economicIndex,systemPrice,indexedRateBps,indexedPay} from './jarvis-economy-policy.mjs'; +import {readFinancialPolicy,validateFinancialPolicy,queueRatesPublication} from './postbank-financial-policy.mjs'; +import {SPICE_POLICY} from './spice-policy.mjs'; +import {economyId} from './economy-operations.mjs'; +export const FED_POLICY_KEY='federal_reserve'; +const calendar=new Intl.DateTimeFormat('en-CA',{timeZone:'Europe/Brussels',year:'numeric',month:'2-digit',day:'2-digit'}); +export function federalDay(now){const p=Object.fromEntries(calendar.formatToParts(new Date(now)).map(p=>[p.type,p.value]));return p.year+'-'+p.month+'-'+p.day;} +export async function readFederalReserve(db){const row=await db.first('SELECT policy_json,version FROM pb_financial_policies WHERE policy_key=?',[FED_POLICY_KEY]);return row?{...JSON.parse(row.policy_json),revision:Number(row.version)}:null;} +export async function writeFederalPolicy(tx,key,value,actor,now){ + const old=await tx.first('SELECT version FROM pb_financial_policies WHERE policy_key=? FOR UPDATE',[key]); + await tx.query('INSERT INTO pb_financial_policies(policy_key,policy_json,version,updated_by,updated_at) VALUES(?,?,?,?,?) ON DUPLICATE KEY UPDATE policy_json=VALUES(policy_json),version=VALUES(version),updated_by=VALUES(updated_by),updated_at=VALUES(updated_at)',[key,JSON.stringify(value),Number(old?.version||0)+1,actor,now]); +} +export async function initialiseFederalReserve(tx,{epoch,resetAt,actor}){ + const bank=await readFinancialPolicy(tx,'bank_rates'),payroll=await readFinancialPolicy(tx,'payroll'); + const value={schema:1,enabled:true,epoch,resetAt,state:'awaiting-payroll',referenceMinor:null,baselineId:epoch,indexMicros:1000000,baseBankRates:bank.value,basePayroll:payroll.value,lastDay:null,lastPayMonth:federalDay(resetAt).slice(0,7),prices:{'spice.guild':SPICE_POLICY.guild,'spice.smuggler':SPICE_POLICY.smuggler},basePrices:{'spice.guild':SPICE_POLICY.guild,'spice.smuggler':SPICE_POLICY.smuggler},priceStep:ECONOMY_POLICY.dailyPriceStep,minPriceFactor:ECONOMY_POLICY.minPriceFactor,maxPriceFactor:ECONOMY_POLICY.maxPriceFactor}; + await writeFederalPolicy(tx,FED_POLICY_KEY,value,actor,resetAt);return value; +} +export async function federalSpicePolicy(db){const fed=await readFederalReserve(db);return fed?.enabled?{...SPICE_POLICY,guild:fed.prices['spice.guild'],smuggler:fed.prices['spice.smuggler'],economyDay:fed.lastDay}:SPICE_POLICY;} +async function fundedPayroll(db,resetAt){ + const runs=await db.query("SELECT period,state,created_at FROM pb_payroll_runs WHERE state='completed' AND created_at>=? UNION ALL SELECT period,state,created_at FROM pb_payroll_additional_runs WHERE state='completed' AND created_at>=? ORDER BY created_at,period LIMIT 1",[resetAt,resetAt]); + if(!runs.length)return false; + return !!await db.first("SELECT id FROM pb_orders WHERE mode='payroll' AND state='posted' AND posted_at>=? LIMIT 1",[resetAt]); +} +export async function federalCirculation(db){const row=await db.first('SELECT COALESCE(SUM(CASE WHEN balance_minor>0 THEN balance_minor ELSE 0 END),0) total FROM pb_accounts WHERE system_key IS NULL');const value=Number(row.total);if(!Number.isSafeInteger(value)||value<0)throw Error('Economic circulation exceeds supported range');return value;} +export function createFederalReserve(bank,operate,{actorId,clock=Date.now,recordSnapshot=async()=>{}}={}){ + return {async run(){ + const policy=await readFederalReserve(bank),day=federalDay(clock());if(!policy?.enabled)return {enabled:false}; + if(!policy.referenceMinor&&(!await fundedPayroll(bank,policy.resetAt)||!await federalCirculation(bank)))return {state:'awaiting-payroll',payrollExecuted:false}; + const id=economyId(['federal-cycle',policy.epoch,day]); + if(policy.lastDay===day){const saved=await bank.first('SELECT receipt_json FROM pb_economy_operations WHERE id=?',[id]);const receipt=saved&&JSON.parse(saved.receipt_json);if(receipt?.observation)await recordSnapshot(receipt.observation);return {state:policy.state,unchanged:true};} + const result=await operate({action:'economy.federal-cycle',id,fields:{epoch:policy.epoch,day,policyVersion:ECONOMY_POLICY.version},apply:async(tx,{now,keyId})=>{ + await tx.query("INSERT INTO pb_financial_policies(policy_key,policy_json,version,updated_by,updated_at) VALUES('publication_guard','{}',0,?,?) ON DUPLICATE KEY UPDATE policy_key=VALUES(policy_key)",[actorId,now]); + await tx.first("SELECT policy_key FROM pb_financial_policies WHERE policy_key='publication_guard' FOR UPDATE"); + await tx.first('SELECT policy_key FROM pb_financial_policies WHERE policy_key=? FOR UPDATE',[FED_POLICY_KEY]);const current=await readFederalReserve(tx); + if(!current?.enabled||current.epoch!==policy.epoch||current.lastDay&¤t.lastDay>=day)throw Error('Federal policy period changed'); + const circulation=await federalCirculation(tx); + if(!current.referenceMinor){if(!await fundedPayroll(tx,current.resetAt)||!circulation)throw Error('A funded completed payroll is required for the baseline');current.referenceMinor=circulation;current.baselineAt=now;} + const index=economicIndex({circulatingMinor:circulation,referenceMinor:current.referenceMinor}),rates=await readFinancialPolicy(tx,'bank_rates'); + for(const [key,base]of Object.entries(current.basePrices))current.prices[key]=systemPrice({baseMinor:base,currentMinor:current.prices[key],index}); + for(const [product,base]of Object.entries(current.baseBankRates.creditAnnualBps)){ + if(base===0){rates.value.creditAnnualBps[product]=0;continue;} + const target=indexedRateBps({baseBps:base,index,sensitivityBps:ECONOMY_POLICY.loanSensitivityBps,minBps:Math.floor(base/2),maxBps:Math.min(10000,base*2)}),old=rates.value.creditAnnualBps[product];rates.value.creditAnnualBps[product]=Math.max(old-25,Math.min(old+25,target)); + } + validateFinancialPolicy('bank_rates',rates.value);await writeFederalPolicy(tx,'bank_rates',rates.value,actorId,now); + if(current.lastPayMonth!==day.slice(0,7)){ + const payroll=await readFinancialPolicy(tx,'payroll');for(const role of Object.keys(payroll.value.netMinor)){const base=current.basePayroll.netMinor[role];payroll.value.netMinor[role]=Math.max(100,Math.floor(base/2),Math.min(base*2,indexedPay({baseMinor:base,currentMinor:payroll.value.netMinor[role],index})));}validateFinancialPolicy('payroll',payroll.value);await writeFederalPolicy(tx,'payroll',payroll.value,actorId,now);current.lastPayMonth=day.slice(0,7); + } + current.state='active';current.indexMicros=Math.round(index*1000000);current.lastDay=day;current.lastKeyId=keyId;current.circulatingMinor=circulation; + await writeFederalPolicy(tx,FED_POLICY_KEY,current,actorId,now);const publication=await queueRatesPublication(tx,actorId,now); + const pay=await readFinancialPolicy(tx,'payroll'),payBase=Object.values(current.basePayroll.netMinor).reduce((a,b)=>a+b,0),payNow=Object.values(pay.value.netMinor).reduce((a,b)=>a+b,0); + const observation={id:economyId(['federal-observation',current.epoch,day]),baselineId:current.baselineId,observedAt:now,policyVersion:ECONOMY_POLICY.version,circulatingMinor:circulation,referenceMinor:current.referenceMinor,indexMicros:current.indexMicros,priceIndexMicros:Math.round(current.prices['spice.guild']/current.basePrices['spice.guild']*1000000),payIndexMicros:Math.round(payNow/payBase*1000000),loanBps:rates.value.creditAnnualBps.personal_loan}; + return {state:'active',epoch:current.epoch,day,keyId,publication,observation,payrollExecuted:false}; + }}); + // Retry this sealed observation even after a lost central acknowledgement. + if(result.observation)await recordSnapshot(result.observation);return result; + }}; +} diff --git a/website/node/game-spice.mjs b/website/node/game-spice.mjs index 213c971a..e0c92ab8 100644 --- a/website/node/game-spice.mjs +++ b/website/node/game-spice.mjs @@ -2,22 +2,21 @@ import {createHash} from 'node:crypto'; import {gameAuthorized,validUuid,json} from './game-link.mjs'; import {postPayrollIssue} from './postbank-payroll-issuer.mjs'; import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs'; +import {SPICE_POLICY,spiceQuote} from './spice-policy.mjs'; +import {federalSpicePolicy} from './federal-reserve.mjs'; +export {SPICE_POLICY,spiceQuote} from './spice-policy.mjs'; // Preserve the existing 15 DM commodity price and sanctioned Guild +33%. // A quote is not payment: only Core's committed inventory receipt earns DM. -export const SPICE_POLICY=Object.freeze({version:1,guild:1995,smuggler:1500,levyBasisPoints:121}); export const spiceFingerprint=(uuid,channel,amount)=>createHash('sha256').update(`spice-sale-v1\n${uuid}\n${channel}\n${amount}`).digest('hex'); -export function spiceQuote(channel,amount){ - if(!['guild','smuggler'].includes(channel)||!Number.isInteger(amount)||amount<1||amount>21312)throw Error('Choose between 1 and 21312 spice.'); - const gross=SPICE_POLICY[channel]*amount,tax=Math.round(gross*SPICE_POLICY.levyBasisPoints/10000); - return {channel,amount,unitMinor:SPICE_POLICY[channel],grossMinor:gross,taxMinor:tax,netMinor:gross-tax}; -} export const activeSmugglerQuest=journal=>!!journal?.quests?.some(q=>q.state==='active'&&(q.branch==='smugglers'||q.id?.startsWith('RPT-CARGO-'))); const accounts=`SELECT a.*,e.active entity_active,p.state package_state FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id JOIN pb_packages p ON p.id=a.package_id WHERE e.kind='person' AND e.external_key=? AND a.type_code IN ('102','103','104','108') ORDER BY CASE WHEN a.type_code='102' THEN 0 ELSE 1 END,a.id`; export async function ensureSpiceSaleStorage(bank){ await bank.query(`CREATE TABLE IF NOT EXISTS pb_spice_sales (id CHAR(36) PRIMARY KEY,actor_id CHAR(36) NOT NULL,player_uuid CHAR(36) NOT NULL,channel VARCHAR(16) NOT NULL,quantity INT NOT NULL,fingerprint CHAR(64) NOT NULL,created_at BIGINT NOT NULL,expires_at BIGINT NOT NULL,quest_reported_at BIGINT NULL,INDEX(player_uuid,created_at)) ENGINE=InnoDB`); const found=await bank.first("SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='pb_spice_sales' AND COLUMN_NAME='quest_reported_at'"); if(!found)try{await bank.query('ALTER TABLE pb_spice_sales ADD COLUMN quest_reported_at BIGINT NULL');}catch(e){if(e.code!=='ER_DUP_FIELDNAME'&&e.errno!==1060)throw e;} + const quote=await bank.first("SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='pb_spice_sales' AND COLUMN_NAME='quote_json'"); + if(!quote)try{await bank.query('ALTER TABLE pb_spice_sales ADD COLUMN quote_json TEXT NULL');}catch(e){if(e.code!=='ER_DUP_FIELDNAME'&&e.errno!==1060)throw e;} } export function createGameSpiceAPI(db,bank,pool,settings,{pol,clock=Date.now,verifyStorage,recordSale}={}){ let storage,schema; @@ -44,19 +43,19 @@ export function createGameSpiceAPI(db,bank,pool,settings,{pol,clock=Date.now,ver if(!fields||Object.keys(input).length!==fields.length||!fields.every(k=>Object.hasOwn(input,k))||!validUuid(input.uuid)||input.server!=='arrakis'||!['read','pending'].includes(input.action)&&!validUuid(input.requestId))return json({message:'Spice sales are available on Arrakis only.'},400); try{ await ready();const user=await actor(input.uuid);if(!user)return json({message:'Link your personal account first.'},403); - if(input.action==='read')return json({ok:true,playerUuid:input.uuid,policy:SPICE_POLICY,smugglerEnabled:await smuggler(user),hasAccount:!!await recipient(bank,user)}); + if(input.action==='read')return json({ok:true,playerUuid:input.uuid,policy:await federalSpicePolicy(bank),smugglerEnabled:await smuggler(user),hasAccount:!!await recipient(bank,user)}); if(input.action==='pending'){const rows=await bank.query('SELECT s.id FROM pb_spice_sales s JOIN `'+schema+'`.dune_exchange_inventory_ops r ON r.id=s.id LEFT JOIN pb_orders o ON o.id=s.id WHERE s.player_uuid=? AND s.actor_id=? AND (o.id IS NULL'+(recordSale?' OR s.quest_reported_at IS NULL':'')+') ORDER BY s.created_at LIMIT 16',[input.uuid,user.id]);return json({ok:true,pending:rows.map(r=>r.id)});} if(input.action==='prepare'){ - if(input.confirmed!==true)throw Error('Confirm the sale first.');const quote=spiceQuote(input.channel,input.amount); + if(input.confirmed!==true)throw Error('Confirm the sale first.');const quote=spiceQuote(input.channel,input.amount,await federalSpicePolicy(bank)); if(input.channel==='smuggler'&&!await smuggler(user))return json({message:'Start a Smuggler quest before selling to Esmar Tuek.'},403); if(!await recipient(bank,user))throw Error('An active personal bank account is required.'); const fingerprint=spiceFingerprint(input.uuid,input.channel,input.amount),now=clock(); - const row=await bank.transaction(async tx=>{const prior=await tx.first('SELECT * FROM pb_spice_sales WHERE id=? FOR UPDATE',[input.requestId]);if(prior){if(prior.actor_id!==user.id||prior.player_uuid!==input.uuid||prior.fingerprint!==fingerprint)throw Error('Sale reference conflict.');return prior;}await tx.query('INSERT INTO pb_spice_sales(id,actor_id,player_uuid,channel,quantity,fingerprint,created_at,expires_at) VALUES(?,?,?,?,?,?,?,?)',[input.requestId,user.id,input.uuid,input.channel,input.amount,fingerprint,now,now+30000]);return {expires_at:now+30000};}); - return json({ok:true,allowed:true,action:'prepare_spice',playerUuid:input.uuid,requestId:input.requestId,fingerprint,expiresAt:Number(row.expires_at),...quote}); + const row=await bank.transaction(async tx=>{const prior=await tx.first('SELECT * FROM pb_spice_sales WHERE id=? FOR UPDATE',[input.requestId]);if(prior){if(prior.actor_id!==user.id||prior.player_uuid!==input.uuid||prior.fingerprint!==fingerprint)throw Error('Sale reference conflict.');return prior;}await tx.query('INSERT INTO pb_spice_sales(id,actor_id,player_uuid,channel,quantity,fingerprint,created_at,expires_at,quote_json) VALUES(?,?,?,?,?,?,?,?,?)',[input.requestId,user.id,input.uuid,input.channel,input.amount,fingerprint,now,now+30000,JSON.stringify(quote)]);return {expires_at:now+30000,quote_json:JSON.stringify(quote)};}); + return json({ok:true,allowed:true,action:'prepare_spice',playerUuid:input.uuid,requestId:input.requestId,fingerprint,expiresAt:Number(row.expires_at),...(row.quote_json?JSON.parse(row.quote_json):spiceQuote(input.channel,input.amount))}); } const paid=await bank.transaction(async tx=>{ const sale=await tx.first('SELECT * FROM pb_spice_sales WHERE id=? FOR UPDATE',[input.requestId]);if(!sale||sale.actor_id!==user.id||sale.player_uuid!==input.uuid)throw Error('Spice receipt unavailable.'); - const quote=spiceQuote(sale.channel,Number(sale.quantity)); + const quote=sale.quote_json?JSON.parse(sale.quote_json):spiceQuote(sale.channel,Number(sale.quantity)); // Native receipts are append-only; the sale and bank-order locks serialize payment. // Do not require write/locking privileges on the game's inventory evidence. const receipt=await tx.first('SELECT id,actor_uuid,kind,fingerprint,listing_id,created_at FROM `'+schema+'`.dune_exchange_inventory_ops WHERE id=?',[sale.id]); diff --git a/website/node/jarvis-economy-public.mjs b/website/node/jarvis-economy-public.mjs index dc102146..2237b346 100644 --- a/website/node/jarvis-economy-public.mjs +++ b/website/node/jarvis-economy-public.mjs @@ -1,13 +1,16 @@ import {createEconomicSnapshots} from './jarvis-economic-snapshots.mjs'; +import {readFederalReserve} from './federal-reserve.mjs'; const periods={'7D':7,'30D':30,'90D':90,'1Y':366}; -export function createEconomyHistory(db,{clock=Date.now}={}){ +export function createEconomyHistory(db,{clock=Date.now,bank=null}={}){ const reply=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':status===200?'public, max-age=30':'no-store','X-Content-Type-Options':'nosniff'}}); return async request=>{ if(request.method!=='GET')return reply({message:'Read-only economic records.'},405); const url=new URL(request.url),period=url.searchParams.get('period')||'30D'; if([...url.searchParams.keys()].some(k=>k!=='period')||url.searchParams.getAll('period').length>1||!Object.hasOwn(periods,period))return reply({message:'Choose a valid observation period.'},400); try{ - const now=clock(),latest=(await db.query('SELECT baseline_id FROM jarvis_economic_snapshots WHERE observed_at<=? ORDER BY observed_at DESC,id DESC LIMIT 1',[now]))[0]; + const now=clock(),fed=bank?await readFederalReserve(bank):null; + if(fed?.enabled&&fed.state==='awaiting-payroll')return reply({state:'awaiting-payroll',period,baselineId:fed.epoch,records:[],asOf:now,resetAt:fed.resetAt,message:'Federal Reserve enabled. The first completed payroll after the reset establishes the reference. No payroll is started automatically by this service.'}); + const latest=fed?.enabled?{baseline_id:fed.baselineId}:(await db.query('SELECT baseline_id FROM jarvis_economic_snapshots WHERE observed_at<=? ORDER BY observed_at DESC,id DESC LIMIT 1',[now]))[0]; if(!latest)return reply({state:'awaiting-baseline',period,records:[],asOf:now}); const reader=createEconomicSnapshots(db,null,{authorize:async()=>false,clock}); const records=await reader.history({baselineId:latest.baseline_id,since:Math.max(0,now-periods[period]*86400000),until:now,limit:1464}); diff --git a/website/node/organisation-key-policy.mjs b/website/node/organisation-key-policy.mjs index 8fbc65bd..48bfcc96 100644 --- a/website/node/organisation-key-policy.mjs +++ b/website/node/organisation-key-policy.mjs @@ -15,6 +15,7 @@ export const KEY_TYPES=Object.freeze({ 'xp-correction':player('XPC','approved-xp-correction'), 'xp-transfer':player('XPX','season-xp-transfer'), 'economy-snapshot':system('ECO-SNAP','immutable-economic-record','record'), + 'economy-operation':system('ECO','verified-economic-operation'), 'staff-parent-link':system('STAFF-LINK','protected-parent-link'), 'staff-claim':system('STAFF-CLAIM','home-block-staff-overwrite'), 'entity-transfer':system('XFR','entity-transfer'), diff --git a/website/node/organisation-keys.mjs b/website/node/organisation-keys.mjs index 5aacfd45..24a38c6f 100644 --- a/website/node/organisation-keys.mjs +++ b/website/node/organisation-keys.mjs @@ -43,6 +43,7 @@ export function createOrganisationKeys(db,{secret,editions=null}={}){ async issue({accountId,keyType,scopeId,expiresAt=null,authorize=null,transactionStore=null}){ if(transactionStore&&(!(keyType==='organisation-action'||keyType==='entity-state'&&accountId===STAFF_OFFICE_ACCOUNT_ID&&/^state:political-decision:[a-f0-9-]{36}$/i.test(scopeId))||typeof transactionStore.query!=='function'||typeof transactionStore.first!=='function'))throw TypeError('A scoped action transaction is required'); type(keyType); + if(keyType==='economy-operation'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||typeof authorize!=='function'||!/^economy\.(reset-balances|federal-cycle):[a-f0-9-]{36}$/i.test(scopeId)))throw TypeError('Economic keys require a scoped system authority adapter'); if(keyType==='kit-definition'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||typeof authorize!=='function'||!/^kitset:[a-f0-9-]{36}:v[1-9]\d{0,5}$/i.test(scopeId)))throw TypeError('Kit definitions require a saved set and authority adapter'); if(keyType==='item-definition'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||typeof authorize!=='function'||!/^item:[a-f0-9-]{36}:v[1-9]\d{0,5}$/i.test(scopeId)))throw TypeError('Item definitions require a versioned system record and editor authority adapter'); if(keyType==='organisation-action'&&(expiresAt!==null||typeof authorize!=='function'||!/^game:[a-f0-9-]{36}$/.test(scopeId)))throw TypeError('Game organisation actions require a current deed adapter'); @@ -82,6 +83,10 @@ export function createOrganisationKeys(db,{secret,editions=null}={}){ if(keyType==='gazette-news')await authorize(tx,{accountId,keyType,scopeId,keyId:id}); if(['xp-correction','xp-transfer'].includes(keyType))await authorize(tx,{accountId,keyType,scopeId,keyId:id}); if(keyType==='economy-snapshot')await authorize(tx,{accountId,keyType,scopeId,keyId:id}); + if(keyType==='economy-operation'){ + if(accountId!==STAFF_OFFICE_ACCOUNT_ID||typeof authorize!=='function')throw new OrganisationKeyError('Economic system authority required'); + await authorize(tx,{accountId,keyType,scopeId,keyId:id}); + } if(['staff-parent-link','entity-transfer'].includes(keyType))await authorize(tx,{accountId,keyType,scopeId,keyId:id}); if(keyType==='staff-claim')await authorize(tx,{accountId,keyType,scopeId,keyId:id}); if(['quest','quest-milestone'].includes(keyType))await authorize(tx,{accountId,keyType,scopeId,keyId:id}); diff --git a/website/node/postbank-api.mjs b/website/node/postbank-api.mjs index 9606e062..5130098f 100644 --- a/website/node/postbank-api.mjs +++ b/website/node/postbank-api.mjs @@ -44,7 +44,7 @@ export function createPostbankApi(central,bank,settings={},deps={}){ 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 economyHistory=createEconomyHistory(central,deps); + const economyHistory=createEconomyHistory(central,{...deps,bank}); 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(); diff --git a/website/node/postbank-credit.mjs b/website/node/postbank-credit.mjs index 22c1dd65..07482e85 100644 --- a/website/node/postbank-credit.mjs +++ b/website/node/postbank-credit.mjs @@ -1,63 +1,66 @@ import {creditCodexDossier} from './codex-credit-dossier.mjs'; -import {createHash} from 'node:crypto'; -import {BankError} from './postbank-service.mjs'; -import {currentPayoff,cents} from './postbank-credit-ledger.mjs'; -import {refinanceConcession} from './postbank-credit-concessions.mjs'; -import {money,minorAmount} from './postbank-catalogue.mjs'; -import {CREDIT_PRODUCTS,CREDIT_VERSION,creditProduct,creditProductsForPackage,creditQuote,creditScore} from './postbank-credit-model.mjs'; -const uuid=s=>typeof s==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(s); -const accountSQL='SELECT a.*,e.id entity_id,e.kind,e.external_key,e.display_name entity_name,e.active entity_active,e.created_at entity_created,p.state package_state,p.package_key FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id JOIN pb_packages p ON p.id=a.package_id'; -const eligible=a=>a&&Number(a.entity_active)===1&&a.state==='active'&&a.package_state==='active'&&!a.system_key&&['102','105','107','108'].includes(a.type_code)&&['person','clan','company','house','office'].includes(a.kind); -export class PostbankCredit{ - constructor(db,authority,{clock=Date.now,central=null}={}){this.db=db;this.authority=authority;this.clock=clock;this.central=central;} - async account(user,id,store=this.db){if(typeof id!=='string'||!/^\d{1,12}$/.test(id))throw new BankError('Choose a borrowing account.');const a=await store.first(accountSQL+' WHERE a.id=?',[id]),context=await this.authority(user,{bank:store});if(!eligible(a)||!context.entities.some(e=>e.id===a.entity_id&&e.canActivate))throw new BankError('You cannot apply for credit for this account.',403);return a;} - async overview(user){const c=await this.authority(user),ids=c.entities.filter(e=>e.canActivate).map(e=>e.id);if(!ids.length)return {accounts:[],loans:[],products:CREDIT_PRODUCTS,termsVersion:CREDIT_VERSION};const rows=await this.db.query(accountSQL+' WHERE e.id IN ('+ids.map(()=>'?').join(',')+') ORDER BY a.id',ids),clients=[...new Set(rows.map(a=>a.client_number))];const loans=clients.length?await this.db.query('SELECT * FROM pb_credit_loans WHERE client_number IN ('+clients.map(()=>'?').join(',')+') ORDER BY created_at DESC LIMIT 100',clients):[];return {accounts:rows.filter(eligible).map(a=>({id:String(a.id),name:a.display_name,holder:a.entity_name,number:a.account_number,kind:a.kind,packageKey:a.package_key,products:creditProductsForPackage(a.package_key),canApply:c.entities.some(e=>e.id===a.entity_id&&e.canActivate)})),loans:loans.map(l=>({id:l.id,codex:creditCodexDossier(l),accountId:String(l.account_id),productKey:l.product_key,state:l.state,principal:money(l.principal_minor),outstanding:money(l.outstanding_minor),monthly:money(l.monthly_minor),annualRate:(l.annual_bps/100).toFixed(2),months:Number(l.months),createdAt:Number(l.created_at),version:Number(l.version),collateral:money(l.collateral_minor),nextDueAt:l.next_due_at?Number(l.next_due_at):null,motivation:l.motivation,decision:l.decision_reason||null})),products:CREDIT_PRODUCTS,termsVersion:CREDIT_VERSION};} - async staff(user,{loanId}={}){if(loanId!==undefined&&!uuid(loanId))throw new BankError('Choose a valid credit contract.');const rights=await this.authority(user);if(!rights.readAdmin)throw new BankError('Bank administration view permission is required.',403);const rows=await this.db.query('SELECT l.*,e.display_name entity_name FROM pb_credit_loans l JOIN pb_entities e ON e.id=l.entity_id'+(loanId?' WHERE l.id=?':'')+' ORDER BY l.created_at DESC LIMIT 100',loanId?[loanId]:[]);return {canManage:!!rights.manageAdmin,applications:rows.map(l=>({id:l.id,codex:creditCodexDossier(l),entity:l.entity_name,productKey:l.product_key,state:l.state,principal:money(l.principal_minor),monthly:money(l.monthly_minor),annualRate:(l.annual_bps/100).toFixed(2),months:Number(l.months),collateral:money(l.collateral_minor),createdAt:Number(l.created_at),version:Number(l.version),outstanding:money(l.outstanding_minor),createdBy:l.created_by,canReview:l.created_by!==user.id&&!rights.entities.some(e=>e.id===l.entity_id&&e.canActivate),motivation:l.motivation,score:JSON.parse(l.score_json),quote:JSON.parse(l.quote_json)})),processing:'not_active'};} - async details(user,loanId,staff=false){ - if(!uuid(loanId))throw new BankError('Choose a valid credit contract.');const loan=await this.db.first('SELECT * FROM pb_credit_loans WHERE id=?',[loanId]);if(!loan)throw new BankError('Credit contract not found.',404);if(staff){if(!(await this.authority(user)).readAdmin)throw new BankError('Credit-management access denied.',403);}else if(!(await this.authority(user)).entities.some(e=>e.id===loan.entity_id&&e.canActivate))throw new BankError('Credit-contract access denied.',403); - const schedule=await this.db.query('SELECT sequence_no,due_at,principal_minor,interest_minor,paid_principal,paid_interest,state FROM pb_credit_instalments WHERE loan_id=? ORDER BY sequence_no',[loanId]),events=await this.db.query('SELECT action,details,created_at FROM pb_credit_events WHERE loan_id=? ORDER BY created_at DESC LIMIT 30',[loanId]),payoff=await currentPayoff(this.db,loan,this.clock()); - const pending=await this.db.first("SELECT COALESCE(SUM(amount_minor),0) total FROM pb_credit_actions WHERE loan_id=? AND state='queued'",[loanId]),queued=BigInt(pending.total),maximum=payoff.total>queued?payoff.total-queued:0n; - const notices=await this.db.query('SELECT subject,body,created_at FROM pb_credit_notices WHERE loan_id=? ORDER BY created_at DESC LIMIT 10',[loanId]);return {codex:creditCodexDossier(loan),notices:notices.map(n=>({subject:n.subject,body:n.body,createdAt:Number(n.created_at)})),id:loan.id,replacedBy:loan.replaced_by||null,state:loan.state,version:Number(loan.version),settlement:money(payoff.total),queuedRepayments:money(queued),maximumRepayment:money(maximum),collateral:money(loan.collateral_minor),decision:loan.decision_reason||null,quote:JSON.parse(loan.quote_json),schedule:schedule.map(r=>({number:Number(r.sequence_no),dueAt:Number(r.due_at),principal:money(r.principal_minor),interest:money(r.interest_minor),paid:money(BigInt(r.paid_principal)+BigInt(r.paid_interest)),state:r.state})),events:events.map(r=>({action:r.action,details:JSON.parse(r.details),createdAt:Number(r.created_at)}))}; - } - async score(account,db=this.db,additional=0n,replaced=[]){ - const now=this.clock(),denials=await db.query("SELECT updated_at FROM pb_credit_loans WHERE client_number=? AND state='declined' AND updated_at>=?",[account.client_number,now-90*86400000]),loans=await db.query("SELECT id,monthly_minor,outstanding_minor,state FROM pb_credit_loans WHERE client_number=? AND state IN ('active','arrears')",[account.client_number]); - const instalments=await db.query("SELECT i.state,i.due_at,i.paid_at FROM pb_credit_instalments i JOIN pb_credit_loans l ON l.id=i.loan_id WHERE l.client_number=? AND i.due_at<=? AND i.due_at>=?",[account.client_number,now,now-365*86400000]); - const current=new Date(now),monthStart=Date.UTC(current.getUTCFullYear(),current.getUTCMonth(),1),since=new Date(monthStart);since.setUTCMonth(since.getUTCMonth()-3); - const entries=await db.query("SELECT x.amount_minor,x.created_at,o.mode,a.client_number,CASE WHEN x.amount_minor>0 THEN src.client_number ELSE dst.client_number END counterparty_client FROM pb_entries x JOIN pb_accounts a ON a.id=x.account_id JOIN pb_orders o ON o.id=x.order_id LEFT JOIN pb_accounts src ON src.id=o.source_id LEFT JOIN pb_accounts dst ON dst.id=o.target_id WHERE a.client_number=? AND a.type_code<>'106' AND x.created_at>=? AND x.created_at0n)bucket.income+=n;else bucket.expenses-=n;} - return creditScore({ageDays:Math.max(0,Math.floor((now-Number(account.entity_created))/86400000)),earnedMonths:[...months.values()].map(v=>v.income),expenseMonths:[...months.values()].map(v=>v.expenses),paid:instalments.filter(i=>i.state==='paid'&&Number(i.paid_at)<=Number(i.due_at)+7*86400000).length,late:instalments.filter(i=>i.state==='late'||i.state==='paid'&&Number(i.paid_at)>Number(i.due_at)+7*86400000).length,overdueMinor:loans.filter(l=>l.state==='arrears').reduce((n,l)=>n+BigInt(l.outstanding_minor),0n),monthlyDebtMinor:additional+loans.filter(l=>!replaced.includes(l.id)).reduce((sum,l)=>sum+BigInt(l.monthly_minor),0n),denials:denials.map(l=>Math.floor((now-Number(l.updated_at))/86400000))}); - } - async simulate(user,input,store=this.db){ - if(!input||Object.keys(input).some(k=>!['accountId','productKey','amount','months','monthly'].includes(k)))throw new BankError('Choose valid simulation details.');const a=await this.account(user,input.accountId,store),product=creditProduct(input.productKey);if(!product.kinds.includes(a.kind))throw new BankError('This credit product is not available to this client.');if(product.revolving)throw new BankError('The revolving credit flow is not open yet.',409); - let request={...input},refinanced=[],concession=null; - if(product.group==='refinancing'){ - const old=await store.query("SELECT * FROM pb_credit_loans WHERE client_number=? AND state IN ('active','arrears') ORDER BY id LIMIT 101",[a.client_number]);const loans=old.filter(l=>!l.product_key.startsWith('grant_')); - if(!loans.length)throw new BankError('There are no interest-bearing loans to refinance for this client.',409);if(loans.length>100)throw new BankError('Contact credit management to reconcile these contracts.',409); - for(const l of loans){const payoff=await currentPayoff(store,l,this.clock());refinanced.push({id:l.id,payoffMinor:String(payoff.total),collateralMinor:String(l.collateral_minor),createdAt:Number(l.created_at)});} - const principal=refinanced.reduce((n,l)=>n+BigInt(l.payoffMinor),0n);request.amount=money(principal);concession=await refinanceConcession(this.central,store,a,user,principal,this.clock(),loans); - } - const quote=creditQuote(request,{annualBps:concession?.annualBps,packageKey:a.package_key});if(concession)quote.concession=concession;const collateral=0n; - return {quote,refinanced,collateral:money(collateral),firstInstalment:quote.firstInstalment,remainingPrincipal:quote.remainingPrincipal,score:await this.score(a,store,minorAmount(quote.monthly),refinanced.map(l=>l.id)),disbursement:'not_active',notice:product.group==='refinancing'?'Refinancing replaces all interest-bearing contracts for this same client. Grants remain separate; there is no additional cash payout.':'Simulation only. No application, collateral movement or payment has been made.'}; - } - async apply(user,input,{revalidate=async()=>user}={}){ - if(!input||Object.keys(input).some(k=>!['requestId','accountId','productKey','amount','months','monthly','motivation','accepted','termsVersion'].includes(k))||!uuid(input.requestId)||input.accepted!==true||input.termsVersion!==CREDIT_VERSION)throw new BankError('Accept the current credit terms and confirm this application.'); - const applicationProduct=creditProduct(input.productKey),motivation=typeof input.motivation==='string'?input.motivation.trim():''; - if(input.motivation!==undefined&&typeof input.motivation!=='string'||typeof input.motivation==='string'&&input.motivation.length>4000||applicationProduct.group!=='grants'&&motivation.length<10)throw new BankError(applicationProduct.group==='grants'?'The optional grant note must be plain text of at most 4,000 characters.':'Enter a motivation of 10–4,000 characters.'); - const a=await this.account(user,input.accountId),fingerprint=createHash('sha256').update(JSON.stringify([user.id,input.accountId,input.productKey,input.amount||null,input.months||null,input.monthly||null,motivation,CREDIT_VERSION])).digest('hex'); - return this.db.transaction(async tx=>{ - await tx.first('SELECT id FROM pb_entities WHERE id=? FOR UPDATE',[a.entity_id]);await tx.first('SELECT client_number FROM pb_clients WHERE client_number=? FOR UPDATE',[a.client_number]);const previous=await tx.first('SELECT * FROM pb_credit_events WHERE request_id=?',[input.requestId]);if(previous){if(previous.actor_id!==user.id||previous.fingerprint!==fingerprint)throw new BankError('This application reference was already used.',409);return {applicationId:previous.loan_id,replayed:true};} - const locked=await tx.first(accountSQL+' WHERE a.id=? FOR UPDATE',[a.id]),fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed.',403);const rights=await this.authority(fresh,{bank:tx});if(!eligible(locked)||!rights.entities.some(e=>e.id===locked.entity_id&&e.canActivate))throw new BankError('Your borrowing authority changed.',403); - const simulation=await this.simulate(fresh,{accountId:input.accountId,productKey:input.productKey,amount:input.amount,months:input.months,monthly:input.monthly},tx),product=creditProduct(input.productKey),quote=simulation.quote; - const pending=await tx.first("SELECT id FROM pb_credit_loans WHERE client_number=? AND state IN ('submitted','approved_pending','offered','payout_queued') LIMIT 1",[a.client_number]);if(pending)throw new BankError('An application is already being processed for this client.',409); - if(product.group==='grants'&&await tx.first('SELECT loan_id FROM pb_credit_grants WHERE client_number=?',[a.client_number]))throw new BankError('This client has already used its launch grant.',409); - const now=this.clock(),state=product.group==='grants'?'approved_pending':'submitted'; - await tx.query('INSERT INTO pb_credit_loans(id,client_number,entity_id,account_id,product_key,state,principal_minor,outstanding_minor,monthly_minor,annual_bps,months,collateral_minor,first_instalment_minor,treasury_hold_minor,created_by,motivation,quote_json,score_json,refinance_json,created_at,updated_at) VALUES(?,?,?,?,?,?,?,0,?,?,?,?,?,0,?,?,?,?,?,?,?)',[input.requestId,a.client_number,a.entity_id,a.id,product.key,state,String(minorAmount(quote.amount)),String(minorAmount(quote.monthly)),Math.round(Number(quote.annualRate)*100),quote.months,'0',String(cents(quote.firstInstalment)),user.id,motivation,JSON.stringify(quote),JSON.stringify(simulation.score),JSON.stringify(simulation.refinanced),now,now]); - if(product.group==='grants')await tx.query('INSERT INTO pb_credit_grants(client_number,loan_id) VALUES(?,?)',[a.client_number,input.requestId]); - - await tx.query('INSERT INTO pb_credit_events(request_id,loan_id,actor_id,action,fingerprint,details,created_at) VALUES(?,?,?,?,?,?,?)',[input.requestId,input.requestId,user.id,'application_submitted',fingerprint,JSON.stringify({state,disbursement:'awaiting_bank_processing',termsVersion:CREDIT_VERSION}),now]); - await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[input.requestId,user.id,'credit_application_submitted',a.entity_id,JSON.stringify({loanId:input.requestId,product:product.key,principal:quote.amount,state}),now]); - return {applicationId:input.requestId,state,replayed:false,notice:state==='approved_pending'?'Launch grant accepted. Disbursement is queued for the next four-hour bank processing window, subject to available bank liquidity.':'Application recorded for bank review. No money or collateral moved.'}; - }); - } -} +import {readFinancialPolicy} from './postbank-financial-policy.mjs'; +import {createHash} from 'node:crypto'; +import {BankError} from './postbank-service.mjs'; +import {currentPayoff,cents} from './postbank-credit-ledger.mjs'; +import {refinanceConcession} from './postbank-credit-concessions.mjs'; +import {money,minorAmount} from './postbank-catalogue.mjs'; +import {CREDIT_PRODUCTS,CREDIT_VERSION,creditProduct,creditProductsForPackage,creditQuote,creditScore} from './postbank-credit-model.mjs'; +const uuid=s=>typeof s==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(s); +const accountSQL='SELECT a.*,e.id entity_id,e.kind,e.external_key,e.display_name entity_name,e.active entity_active,e.created_at entity_created,p.state package_state,p.package_key FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id JOIN pb_packages p ON p.id=a.package_id'; +const eligible=a=>a&&Number(a.entity_active)===1&&a.state==='active'&&a.package_state==='active'&&!a.system_key&&['102','105','107','108'].includes(a.type_code)&&['person','clan','company','house','office'].includes(a.kind); +export class PostbankCredit{ + constructor(db,authority,{clock=Date.now,central=null}={}){this.db=db;this.authority=authority;this.clock=clock;this.central=central;} + async account(user,id,store=this.db){if(typeof id!=='string'||!/^\d{1,12}$/.test(id))throw new BankError('Choose a borrowing account.');const a=await store.first(accountSQL+' WHERE a.id=?',[id]),context=await this.authority(user,{bank:store});if(!eligible(a)||!context.entities.some(e=>e.id===a.entity_id&&e.canActivate))throw new BankError('You cannot apply for credit for this account.',403);return a;} + async overview(user){const rates=await readFinancialPolicy(this.db,'bank_rates'),products=CREDIT_PRODUCTS.map(p=>({...p,annualBps:rates.value.creditAnnualBps[p.key]})),c=await this.authority(user),ids=c.entities.filter(e=>e.canActivate).map(e=>e.id);if(!ids.length)return {accounts:[],loans:[],products,termsVersion:CREDIT_VERSION};const rows=await this.db.query(accountSQL+' WHERE e.id IN ('+ids.map(()=>'?').join(',')+') ORDER BY a.id',ids),clients=[...new Set(rows.map(a=>a.client_number))];const loans=clients.length?await this.db.query('SELECT * FROM pb_credit_loans WHERE client_number IN ('+clients.map(()=>'?').join(',')+') ORDER BY created_at DESC LIMIT 100',clients):[];return {accounts:rows.filter(eligible).map(a=>({id:String(a.id),name:a.display_name,holder:a.entity_name,number:a.account_number,kind:a.kind,packageKey:a.package_key,products:creditProductsForPackage(a.package_key),canApply:c.entities.some(e=>e.id===a.entity_id&&e.canActivate)})),loans:loans.map(l=>({id:l.id,codex:creditCodexDossier(l),accountId:String(l.account_id),productKey:l.product_key,state:l.state,principal:money(l.principal_minor),outstanding:money(l.outstanding_minor),monthly:money(l.monthly_minor),annualRate:(l.annual_bps/100).toFixed(2),months:Number(l.months),createdAt:Number(l.created_at),version:Number(l.version),collateral:money(l.collateral_minor),nextDueAt:l.next_due_at?Number(l.next_due_at):null,motivation:l.motivation,decision:l.decision_reason||null})),products,termsVersion:CREDIT_VERSION};} + async staff(user,{loanId}={}){if(loanId!==undefined&&!uuid(loanId))throw new BankError('Choose a valid credit contract.');const rights=await this.authority(user);if(!rights.readAdmin)throw new BankError('Bank administration view permission is required.',403);const rows=await this.db.query('SELECT l.*,e.display_name entity_name FROM pb_credit_loans l JOIN pb_entities e ON e.id=l.entity_id'+(loanId?' WHERE l.id=?':'')+' ORDER BY l.created_at DESC LIMIT 100',loanId?[loanId]:[]);return {canManage:!!rights.manageAdmin,applications:rows.map(l=>({id:l.id,codex:creditCodexDossier(l),entity:l.entity_name,productKey:l.product_key,state:l.state,principal:money(l.principal_minor),monthly:money(l.monthly_minor),annualRate:(l.annual_bps/100).toFixed(2),months:Number(l.months),collateral:money(l.collateral_minor),createdAt:Number(l.created_at),version:Number(l.version),outstanding:money(l.outstanding_minor),createdBy:l.created_by,canReview:l.created_by!==user.id&&!rights.entities.some(e=>e.id===l.entity_id&&e.canActivate),motivation:l.motivation,score:JSON.parse(l.score_json),quote:JSON.parse(l.quote_json)})),processing:'not_active'};} + async details(user,loanId,staff=false){ + if(!uuid(loanId))throw new BankError('Choose a valid credit contract.');const loan=await this.db.first('SELECT * FROM pb_credit_loans WHERE id=?',[loanId]);if(!loan)throw new BankError('Credit contract not found.',404);if(staff){if(!(await this.authority(user)).readAdmin)throw new BankError('Credit-management access denied.',403);}else if(!(await this.authority(user)).entities.some(e=>e.id===loan.entity_id&&e.canActivate))throw new BankError('Credit-contract access denied.',403); + const schedule=await this.db.query('SELECT sequence_no,due_at,principal_minor,interest_minor,paid_principal,paid_interest,state FROM pb_credit_instalments WHERE loan_id=? ORDER BY sequence_no',[loanId]),events=await this.db.query('SELECT action,details,created_at FROM pb_credit_events WHERE loan_id=? ORDER BY created_at DESC LIMIT 30',[loanId]),payoff=await currentPayoff(this.db,loan,this.clock()); + const pending=await this.db.first("SELECT COALESCE(SUM(amount_minor),0) total FROM pb_credit_actions WHERE loan_id=? AND state='queued'",[loanId]),queued=BigInt(pending.total),maximum=payoff.total>queued?payoff.total-queued:0n; + const notices=await this.db.query('SELECT subject,body,created_at FROM pb_credit_notices WHERE loan_id=? ORDER BY created_at DESC LIMIT 10',[loanId]);return {codex:creditCodexDossier(loan),notices:notices.map(n=>({subject:n.subject,body:n.body,createdAt:Number(n.created_at)})),id:loan.id,replacedBy:loan.replaced_by||null,state:loan.state,version:Number(loan.version),settlement:money(payoff.total),queuedRepayments:money(queued),maximumRepayment:money(maximum),collateral:money(loan.collateral_minor),decision:loan.decision_reason||null,quote:JSON.parse(loan.quote_json),schedule:schedule.map(r=>({number:Number(r.sequence_no),dueAt:Number(r.due_at),principal:money(r.principal_minor),interest:money(r.interest_minor),paid:money(BigInt(r.paid_principal)+BigInt(r.paid_interest)),state:r.state})),events:events.map(r=>({action:r.action,details:JSON.parse(r.details),createdAt:Number(r.created_at)}))}; + } + async score(account,db=this.db,additional=0n,replaced=[]){ + const now=this.clock(),denials=await db.query("SELECT updated_at FROM pb_credit_loans WHERE client_number=? AND state='declined' AND updated_at>=?",[account.client_number,now-90*86400000]),loans=await db.query("SELECT id,monthly_minor,outstanding_minor,state FROM pb_credit_loans WHERE client_number=? AND state IN ('active','arrears')",[account.client_number]); + const instalments=await db.query("SELECT i.state,i.due_at,i.paid_at FROM pb_credit_instalments i JOIN pb_credit_loans l ON l.id=i.loan_id WHERE l.client_number=? AND i.due_at<=? AND i.due_at>=?",[account.client_number,now,now-365*86400000]); + const current=new Date(now),monthStart=Date.UTC(current.getUTCFullYear(),current.getUTCMonth(),1),since=new Date(monthStart);since.setUTCMonth(since.getUTCMonth()-3); + const entries=await db.query("SELECT x.amount_minor,x.created_at,o.mode,a.client_number,CASE WHEN x.amount_minor>0 THEN src.client_number ELSE dst.client_number END counterparty_client FROM pb_entries x JOIN pb_accounts a ON a.id=x.account_id JOIN pb_orders o ON o.id=x.order_id LEFT JOIN pb_accounts src ON src.id=o.source_id LEFT JOIN pb_accounts dst ON dst.id=o.target_id WHERE a.client_number=? AND a.type_code<>'106' AND x.created_at>=? AND x.created_at0n)bucket.income+=n;else bucket.expenses-=n;} + return creditScore({ageDays:Math.max(0,Math.floor((now-Number(account.entity_created))/86400000)),earnedMonths:[...months.values()].map(v=>v.income),expenseMonths:[...months.values()].map(v=>v.expenses),paid:instalments.filter(i=>i.state==='paid'&&Number(i.paid_at)<=Number(i.due_at)+7*86400000).length,late:instalments.filter(i=>i.state==='late'||i.state==='paid'&&Number(i.paid_at)>Number(i.due_at)+7*86400000).length,overdueMinor:loans.filter(l=>l.state==='arrears').reduce((n,l)=>n+BigInt(l.outstanding_minor),0n),monthlyDebtMinor:additional+loans.filter(l=>!replaced.includes(l.id)).reduce((sum,l)=>sum+BigInt(l.monthly_minor),0n),denials:denials.map(l=>Math.floor((now-Number(l.updated_at))/86400000))}); + } + async simulate(user,input,store=this.db){ + if(!input||Object.keys(input).some(k=>!['accountId','productKey','amount','months','monthly'].includes(k)))throw new BankError('Choose valid simulation details.');const a=await this.account(user,input.accountId,store),product=creditProduct(input.productKey);if(!product.kinds.includes(a.kind))throw new BankError('This credit product is not available to this client.');if(product.revolving)throw new BankError('The revolving credit flow is not open yet.',409); + let request={...input},refinanced=[],concession=null; + if(product.group==='refinancing'){ + const old=await store.query("SELECT * FROM pb_credit_loans WHERE client_number=? AND state IN ('active','arrears') ORDER BY id LIMIT 101",[a.client_number]);const loans=old.filter(l=>!l.product_key.startsWith('grant_')); + if(!loans.length)throw new BankError('There are no interest-bearing loans to refinance for this client.',409);if(loans.length>100)throw new BankError('Contact credit management to reconcile these contracts.',409); + for(const l of loans){const payoff=await currentPayoff(store,l,this.clock());refinanced.push({id:l.id,payoffMinor:String(payoff.total),collateralMinor:String(l.collateral_minor),createdAt:Number(l.created_at)});} + const principal=refinanced.reduce((n,l)=>n+BigInt(l.payoffMinor),0n);request.amount=money(principal);concession=await refinanceConcession(this.central,store,a,user,principal,this.clock(),loans); + } + const rates=await readFinancialPolicy(store,'bank_rates'),published=rates.value.creditAnnualBps[product.key],rate=concession?Math.min(concession.annualBps,published):published; + const quote=creditQuote(request,{annualBps:rate,packageKey:a.package_key});quote.termsVersion=CREDIT_VERSION+(rates.version?':rates-'+rates.version:'');if(concession)quote.concession=concession;const collateral=0n; + return {quote,refinanced,collateral:money(collateral),firstInstalment:quote.firstInstalment,remainingPrincipal:quote.remainingPrincipal,score:await this.score(a,store,minorAmount(quote.monthly),refinanced.map(l=>l.id)),disbursement:'not_active',notice:product.group==='refinancing'?'Refinancing replaces all interest-bearing contracts for this same client. Grants remain separate; there is no additional cash payout.':'Simulation only. No application, collateral movement or payment has been made.'}; + } + async apply(user,input,{revalidate=async()=>user}={}){ + if(!input||Object.keys(input).some(k=>!['requestId','accountId','productKey','amount','months','monthly','motivation','accepted','termsVersion'].includes(k))||!uuid(input.requestId)||input.accepted!==true||typeof input.termsVersion!=='string'||input.termsVersion.length>160)throw new BankError('Accept the current credit terms and confirm this application.'); + const applicationProduct=creditProduct(input.productKey),motivation=typeof input.motivation==='string'?input.motivation.trim():''; + if(input.motivation!==undefined&&typeof input.motivation!=='string'||typeof input.motivation==='string'&&input.motivation.length>4000||applicationProduct.group!=='grants'&&motivation.length<10)throw new BankError(applicationProduct.group==='grants'?'The optional grant note must be plain text of at most 4,000 characters.':'Enter a motivation of 10–4,000 characters.'); + const a=await this.account(user,input.accountId),fingerprint=createHash('sha256').update(JSON.stringify([user.id,input.accountId,input.productKey,input.amount||null,input.months||null,input.monthly||null,motivation,input.termsVersion])).digest('hex'); + return this.db.transaction(async tx=>{ + await tx.first('SELECT id FROM pb_entities WHERE id=? FOR UPDATE',[a.entity_id]);await tx.first('SELECT client_number FROM pb_clients WHERE client_number=? FOR UPDATE',[a.client_number]);const previous=await tx.first('SELECT * FROM pb_credit_events WHERE request_id=?',[input.requestId]);if(previous){if(previous.actor_id!==user.id||previous.fingerprint!==fingerprint)throw new BankError('This application reference was already used.',409);return {applicationId:previous.loan_id,replayed:true};} + const locked=await tx.first(accountSQL+' WHERE a.id=? FOR UPDATE',[a.id]),fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed.',403);const rights=await this.authority(fresh,{bank:tx});if(!eligible(locked)||!rights.entities.some(e=>e.id===locked.entity_id&&e.canActivate))throw new BankError('Your borrowing authority changed.',403); + const simulation=await this.simulate(fresh,{accountId:input.accountId,productKey:input.productKey,amount:input.amount,months:input.months,monthly:input.monthly},tx),product=creditProduct(input.productKey),quote=simulation.quote; + if(input.termsVersion!==quote.termsVersion)throw new BankError('The published credit rate changed. Simulate and accept the current quote again.',409); + const pending=await tx.first("SELECT id FROM pb_credit_loans WHERE client_number=? AND state IN ('submitted','approved_pending','offered','payout_queued') LIMIT 1",[a.client_number]);if(pending)throw new BankError('An application is already being processed for this client.',409); + if(product.group==='grants'&&await tx.first('SELECT loan_id FROM pb_credit_grants WHERE client_number=?',[a.client_number]))throw new BankError('This client has already used its launch grant.',409); + const now=this.clock(),state=product.group==='grants'?'approved_pending':'submitted'; + await tx.query('INSERT INTO pb_credit_loans(id,client_number,entity_id,account_id,product_key,state,principal_minor,outstanding_minor,monthly_minor,annual_bps,months,collateral_minor,first_instalment_minor,treasury_hold_minor,created_by,motivation,quote_json,score_json,refinance_json,created_at,updated_at) VALUES(?,?,?,?,?,?,?,0,?,?,?,?,?,0,?,?,?,?,?,?,?)',[input.requestId,a.client_number,a.entity_id,a.id,product.key,state,String(minorAmount(quote.amount)),String(minorAmount(quote.monthly)),Math.round(Number(quote.annualRate)*100),quote.months,'0',String(cents(quote.firstInstalment)),user.id,motivation,JSON.stringify(quote),JSON.stringify(simulation.score),JSON.stringify(simulation.refinanced),now,now]); + if(product.group==='grants')await tx.query('INSERT INTO pb_credit_grants(client_number,loan_id) VALUES(?,?)',[a.client_number,input.requestId]); + + await tx.query('INSERT INTO pb_credit_events(request_id,loan_id,actor_id,action,fingerprint,details,created_at) VALUES(?,?,?,?,?,?,?)',[input.requestId,input.requestId,user.id,'application_submitted',fingerprint,JSON.stringify({state,disbursement:'awaiting_bank_processing',termsVersion:quote.termsVersion}),now]); + await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[input.requestId,user.id,'credit_application_submitted',a.entity_id,JSON.stringify({loanId:input.requestId,product:product.key,principal:quote.amount,state}),now]); + return {applicationId:input.requestId,state,replayed:false,notice:state==='approved_pending'?'Launch grant accepted. Disbursement is queued for the next four-hour bank processing window, subject to available bank liquidity.':'Application recorded for bank review. No money or collateral moved.'}; + }); + } +} diff --git a/website/node/postbank-db.mjs b/website/node/postbank-db.mjs index f914c336..013fc815 100644 --- a/website/node/postbank-db.mjs +++ b/website/node/postbank-db.mjs @@ -1,4 +1,5 @@ import {WAR_CAMPAIGN_SCHEMA} from './war-campaign-store.mjs'; +import {ECONOMY_OPERATION_SCHEMA} from './economy-operations.mjs'; import {WAR_SETTLEMENT_JOB_SCHEMA} from './war-settlement-jobs.mjs'; import {WAR_EXCHANGE_SCHEMA} from './war-exchange.mjs'; import {GUILD_SCHEMA} from './game-guild.mjs'; @@ -25,7 +26,7 @@ export async function openPostbankDatabase(settings){ const pool=mysql.createPool({host:settings.BANK_DB_HOST||'127.0.0.1',port:Number(settings.BANK_DB_PORT||3306),database:name,user:settings.BANK_DB_USER,password:settings.BANK_DB_PASSWORD,connectionLimit:4,supportBigNumbers:true,bigNumberStrings:true,charset:'utf8mb4',connectTimeout:8000}); const api=c=>({async query(sql,args=[]){return(await c.execute(sql,args))[0];},async first(sql,args=[]){return(await c.execute(sql,args))[0][0]||null;}}); const db={async query(sql,args=[]){return(await pool.execute(sql,args))[0];},async first(sql,args=[]){return(await pool.execute(sql,args))[0][0]||null;},async transaction(work){const c=await pool.getConnection();try{await c.beginTransaction();const result=await work(api(c));await c.commit();return result;}catch(error){await c.rollback();throw error;}finally{c.release();}},async close(){await pool.end();}}; - try{for(const sql of(await readFile(new URL('./postbank-schema.sql',import.meta.url),'utf8')).split(';').map(s=>s.trim()).filter(Boolean))await db.query(sql);for(const sql of [...CLAIM_PRODUCT_SCHEMA,CLAIM_RESET_SCHEMA])await db.query(sql+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');await db.query(NETWORTH_SCHEMA);for(const sql of [...RIHLA_SCHEMA,...EVENT_SCHEMA,...WAR_EXCHANGE_SCHEMA,WAR_CAMPAIGN_SCHEMA,WAR_SETTLEMENT_JOB_SCHEMA,...CAMPAIGN_SCHEMA])await db.query(sql);await initializeJarvisListings(db);await db.query(DEED_PURCHASE_SCHEMA);await db.query(ESTATE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');await db.query(PROMOTION_DELIVERY_SCHEMA);for(const sql of POLITICAL_JOB_BANK_SCHEMA)await db.query(sql);await db.query(JARVIS_CHARGE_SCHEMA);await db.query(GUILD_SCHEMA);await db.query(HOME_SCHEMA);await ensureClaimBatchColumns(db);await ensureCreditColumns(db);await ensurePostbankIndexes(db);}catch(error){await pool.end();throw error;} + try{for(const sql of(await readFile(new URL('./postbank-schema.sql',import.meta.url),'utf8')).split(';').map(s=>s.trim()).filter(Boolean))await db.query(sql);for(const sql of [...CLAIM_PRODUCT_SCHEMA,CLAIM_RESET_SCHEMA])await db.query(sql+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');await db.query(NETWORTH_SCHEMA);for(const sql of [...RIHLA_SCHEMA,...EVENT_SCHEMA,...WAR_EXCHANGE_SCHEMA,WAR_CAMPAIGN_SCHEMA,WAR_SETTLEMENT_JOB_SCHEMA,...CAMPAIGN_SCHEMA])await db.query(sql);await initializeJarvisListings(db);await db.query(DEED_PURCHASE_SCHEMA);await db.query(ESTATE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');await db.query(PROMOTION_DELIVERY_SCHEMA);for(const sql of POLITICAL_JOB_BANK_SCHEMA)await db.query(sql);await db.query(JARVIS_CHARGE_SCHEMA);await db.query(GUILD_SCHEMA);await db.query(HOME_SCHEMA);await ensureClaimBatchColumns(db);await ensureCreditColumns(db);await ensurePostbankIndexes(db);await db.query(ECONOMY_OPERATION_SCHEMA);}catch(error){await pool.end();throw error;} return db; } diff --git a/website/node/spice-policy.mjs b/website/node/spice-policy.mjs new file mode 100644 index 00000000..7f047b64 --- /dev/null +++ b/website/node/spice-policy.mjs @@ -0,0 +1,6 @@ +export const SPICE_POLICY=Object.freeze({version:1,guild:1995,smuggler:1500,levyBasisPoints:121}); +export function spiceQuote(channel,amount,policy=SPICE_POLICY){ + if(!['guild','smuggler'].includes(channel)||!Number.isInteger(amount)||amount<1||amount>21312||!Number.isSafeInteger(policy[channel])||policy[channel]<1||!Number.isInteger(policy.levyBasisPoints)||policy.levyBasisPoints<0||policy.levyBasisPoints>10000)throw Error('Choose between 1 and 21312 spice.'); + const gross=policy[channel]*amount,tax=Math.round(gross*policy.levyBasisPoints/10000); + return {channel,amount,unitMinor:policy[channel],grossMinor:gross,taxMinor:tax,netMinor:gross-tax}; +} diff --git a/website/ops/run-economy-reset.mjs b/website/ops/run-economy-reset.mjs new file mode 100644 index 00000000..6bd865ac --- /dev/null +++ b/website/ops/run-economy-reset.mjs @@ -0,0 +1,17 @@ +import {pathToFileURL} from 'node:url'; +import {openDatabase} from '../node/mysql.mjs'; +import {openPostbankDatabase} from '../node/postbank-db.mjs'; +import {openOrganisationKeyService} from '../node/organisation-key-service.mjs'; +import {createEconomyRuntime,ECONOMY_EPOCH} from '../node/economy-runtime.mjs'; +// Explicit server-only entry point for the owner's already authorised reset. +// No web route, startup hook, secret output or automatic payroll execution. +export async function runAuthorisedEconomyReset(settings){ + const central=await openDatabase(settings);let bank; + try{bank=await openPostbankDatabase(settings);if(!bank)throw Error('The central bank is unavailable');const keys=await openOrganisationKeyService(central,settings);return await createEconomyRuntime(central,bank,keys,{allowReset:true,epoch:ECONOMY_EPOCH}).reset();} + finally{await Promise.allSettled([central.close(),bank?.close()]);} +} +if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href){ + if(process.argv.length!==3||process.argv[2]!=='--execute-authorised-reset='+ECONOMY_EPOCH)throw Error('The exact authorised economic epoch is required'); + try{const result=await runAuthorisedEconomyReset(process.env);const {beforeBalances,...summary}=result;console.log(JSON.stringify(summary));} + catch(error){console.error('Economic reset not confirmed:',error.code||error.message);process.exitCode=1;} +} diff --git a/website/tests/economy-reset-fed.test.mjs b/website/tests/economy-reset-fed.test.mjs new file mode 100644 index 00000000..0a94e8c1 --- /dev/null +++ b/website/tests/economy-reset-fed.test.mjs @@ -0,0 +1,56 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {randomUUID} from 'node:crypto'; +import {companyFixture} from './company-deed-fixture.mjs'; +import {BankFixture} from './postbank-fixture.mjs'; +import {GENERATOR_SCHEMA} from '../node/jarvis-master-generator.mjs'; +import {ECONOMY_OPERATION_SCHEMA,createEconomyOperations} from '../node/economy-operations.mjs'; +import {createEconomyReset} from '../node/economy-reset.mjs'; +import {createFederalReserve,readFederalReserve} from '../node/federal-reserve.mjs'; +import {STAFF_OFFICE_ACCOUNT_ID} from '../node/organisation-keys.mjs'; +const start=Date.UTC(2026,10,24,12); +async function rig(){ + const f=await companyFixture(),bank=new BankFixture();await f.db.query(GENERATOR_SCHEMA);await bank.query(ECONOMY_OPERATION_SCHEMA.replace(' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4',''));let now=start; + for(const [key,amount]of [['sys_bank_capital_issuer',-1600],['sys_payroll_po',-300],['sys_tax_treasury',900],[null,1000]])await bank.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,created_at) VALUES(?,'979','Account',?,?)",[key,amount,now]); + const user=await bank.first('SELECT * FROM pb_accounts WHERE system_key IS NULL'),po=await bank.first("SELECT * FROM pb_accounts WHERE system_key='sys_payroll_po'"); + const operate=createEconomyOperations(f.db,bank,f.keys,{authorize:async()=>{},clock:()=>now}),reset=createEconomyReset(operate,{actorId:f.people.Owner.id}),observations=[]; + const federal=createFederalReserve(bank,operate,{actorId:STAFF_OFFICE_ACCOUNT_ID,clock:()=>now,recordSnapshot:async o=>{if(!observations.some(x=>x.id===o.id))observations.push(o);}}); + async function mint(amount,mode='spice'){ + const id=randomUUID(),u=await bank.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[user.id]),p=await bank.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[po.id]); + await bank.query('UPDATE pb_accounts SET balance_minor=? WHERE id=?',[String(BigInt(u.balance_minor)+BigInt(amount)),user.id]);await bank.query('UPDATE pb_accounts SET balance_minor=? WHERE id=?',[String(BigInt(p.balance_minor)-BigInt(amount)),po.id]); + await bank.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at,posted_at) VALUES(?,?,?,?,?,?,'Funding',?,'posted',?,?)",[id,f.people.Owner.id,po.id,user.id,'x'.repeat(64),amount,mode,now,now]); + } + return {...f,bank,user,po,reset,operate,federal,observations,mint,time:n=>now=n,close:()=>{bank.close();f.db.close();}}; +} +test('all accounts including both issuers reach zero by balanced postings; replay preserves later earnings',async()=>{ + const f=await rig();try{ + const ids=(await f.bank.query('SELECT id FROM pb_accounts ORDER BY id')).map(a=>a.id),r=await f.reset();assert.equal(r.allBalancesZero,true);assert.equal(r.accounts,4);assert.equal(r.payrollExecuted,false); + assert.equal((await f.bank.first('SELECT SUM(amount_minor) n FROM pb_entries')).n,0);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_accounts WHERE balance_minor<>0')).n,0);assert.deepEqual((await f.bank.query('SELECT id FROM pb_accounts ORDER BY id')).map(a=>a.id),ids); + await f.mint(200);const count=(await f.bank.first('SELECT COUNT(*) n FROM pb_entries')).n;assert.equal((await f.reset()).replayed,true);assert.equal((await f.bank.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.user.id])).balance_minor,200);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_entries')).n,count); + assert.equal((await f.db.first("SELECT COUNT(*) n FROM organisation_keys WHERE key_type='economy-operation'")).n,1); + }finally{f.close();} +}); +test('a bank failure rolls back every reset leg and retries the consumed instruction exactly once',async()=>{ + const f=await rig();try{ + const before=await f.bank.query('SELECT id,balance_minor FROM pb_accounts ORDER BY id');f.bank.sqlite.exec("CREATE TRIGGER fail_reset BEFORE INSERT ON pb_entries BEGIN SELECT RAISE(ABORT,'ledger unavailable'); END"); + await assert.rejects(f.reset(),/ledger unavailable/);assert.deepEqual(await f.bank.query('SELECT id,balance_minor FROM pb_accounts ORDER BY id'),before);assert.equal((await f.db.first('SELECT state FROM jarvis_generated_instructions')).state,'queued'); + f.bank.sqlite.exec('DROP TRIGGER fail_reset');await f.reset();assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_economy_operations')).n,1);assert.equal((await f.db.first('SELECT state FROM jarvis_generated_instructions')).state,'applied'); + }finally{f.close();} +}); +test('lost central acknowledgement recovers the bank receipt without resetting new money',async()=>{ + const f=await rig();try{const original=f.db.query.bind(f.db);let fail=true;f.db.query=async(sql,args)=>{if(fail&&sql.includes("SET state='applied',manifest_json=")){fail=false;throw Error('Lost acknowledgement');}return original(sql,args);}; + await assert.rejects(f.reset(),/Lost acknowledgement/);await f.mint(50);await f.reset();assert.equal((await f.bank.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.user.id])).balance_minor,50);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_economy_operations')).n,1); + }finally{f.close();} +}); +test('reserved funds and an unbalanced ledger are rejected without wiping accounts',async()=>{ + const f=await rig();try{await f.bank.query('UPDATE pb_accounts SET reserved_minor=10 WHERE id=?',[f.user.id]);await assert.rejects(f.reset(),/reservations/);await f.bank.query('UPDATE pb_accounts SET reserved_minor=0,balance_minor=1001 WHERE id=?',[f.user.id]);await assert.rejects(f.reset(),/not balanced/);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_entries')).n,0);}finally{f.close();} +}); +test('Fed waits for real completed post-reset payroll; baseline is positive and daily repricing is bounded and once-only',async()=>{ + const f=await rig();try{ + await f.reset();assert.equal((await f.federal.run()).state,'awaiting-payroll');assert.equal((await readFederalReserve(f.bank)).referenceMinor,null);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_economy_operations')).n,1); + f.time(start+1000);await f.mint(1000,'payroll');await f.bank.query("INSERT INTO pb_payroll_runs VALUES('2026-11',1,0,'completed',?)",[start+1000]);await f.federal.run();const base=await readFederalReserve(f.bank);assert.equal(base.referenceMinor,1000);assert.equal(base.prices['spice.guild'],1995);assert.equal(f.observations.length,1); + await f.mint(15000);f.time(start+86400000);await f.federal.run();const next=await readFederalReserve(f.bank);assert.equal(next.indexMicros,2000000);assert.equal(next.prices['spice.guild'],2094);const rates=JSON.parse((await f.bank.first("SELECT policy_json FROM pb_financial_policies WHERE policy_key='bank_rates'")).policy_json);assert.equal(rates.creditAnnualBps.personal_loan,864);assert.equal(rates.creditAnnualBps.grant_start,0);assert.equal(f.observations.length,2); + assert.equal((await f.federal.run()).unchanged,true);assert.equal(f.observations.length,2);assert.equal((await f.bank.first("SELECT COUNT(*) n FROM pb_orders WHERE mode='payroll'")).n,1,'Fed did not issue any payroll'); + }finally{f.close();} +}); +test('economic keys cannot be issued to players or with arbitrary operation scopes',async()=>{const f=await rig();try{await assert.rejects(f.keys.issue({accountId:f.people.Owner.id,keyType:'economy-operation',scopeId:'arbitrary',authorize:async()=>{}}),/scoped system/);}finally{f.close();}}); diff --git a/website/tests/game-spice.test.mjs b/website/tests/game-spice.test.mjs index 453524e9..2e3ec5e7 100644 --- a/website/tests/game-spice.test.mjs +++ b/website/tests/game-spice.test.mjs @@ -6,7 +6,7 @@ async function fixture({readOnlyReceipts=false,recordSale}={}){ await new PostbankService(bank,async()=>({entities:[{...entity,canView:true,canActivate:true,canPay:true}]})).activate(user,{entityId:entity.id,packageKey:'pb_flow',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()}); const target=await bank.first("SELECT * FROM pb_accounts WHERE type_code='102'"); for(const key of ['sys_payroll_po','sys_tax_treasury'])await bank.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,state,created_at) VALUES(?,'979',?,0,'active',1)",[key,key]); - bank.sqlite.exec("ATTACH DATABASE ':memory:' AS game;CREATE TABLE game.dune_exchange_inventory_ops(id TEXT PRIMARY KEY,actor_uuid TEXT,kind TEXT,fingerprint TEXT,listing_id INT,created_at INT);CREATE TABLE pb_spice_sales(id TEXT PRIMARY KEY,actor_id TEXT,player_uuid TEXT,channel TEXT,quantity INT,fingerprint TEXT,created_at INT,expires_at INT,quest_reported_at INT);"); + bank.sqlite.exec("ATTACH DATABASE ':memory:' AS game;CREATE TABLE game.dune_exchange_inventory_ops(id TEXT PRIMARY KEY,actor_uuid TEXT,kind TEXT,fingerprint TEXT,listing_id INT,created_at INT);CREATE TABLE pb_spice_sales(id TEXT PRIMARY KEY,actor_id TEXT,player_uuid TEXT,channel TEXT,quantity INT,fingerprint TEXT,created_at INT,expires_at INT,quest_reported_at INT,quote_json TEXT);"); const db={query:async(sql,args)=>args[0]===uuid?[user]:[]},secret='spice-api-test-secret-123456789012345'; const receiptReader={query:bank.query.bind(bank),first:bank.first.bind(bank),transaction:work=>bank.transaction(tx=>work({...tx,first(sql,args){if(sql.includes('dune_exchange_inventory_ops')&&/FOR\s+(UPDATE|SHARE)|LOCK\s+IN/i.test(sql))throw Error('Inventory receipts are read-only');return tx.first(sql,args);}}))}; const api=createGameSpiceAPI(db,readOnlyReceipts?receiptReader:bank,null,{GAME_LINK_SECRET:secret},{verifyStorage:async()=> 'game',clock:()=>now,recordSale,pol:{quests:{list:async()=>({quests:[{id:'POL-SMUGGLERS-02',branch:'smugglers',state:active?'active':'claimed'}]})}}}); @@ -15,6 +15,12 @@ async function fixture({readOnlyReceipts=false,recordSale}={}){ async function receipt(input){await bank.query('INSERT INTO game.dune_exchange_inventory_ops VALUES(?,?,?,?,?,?)',[input.requestId,uuid,'spice-'+input.channel,spiceFingerprint(uuid,input.channel,input.amount),input.amount,now+100]);} return {bank,user,uuid,target,call,prepare,receipt,active:()=>{active=true;},expire:()=>{now+=60000;}}; } +test('prepared sale keeps its accepted price after a Federal Reserve repricing',async()=>{ + const f=await fixture();try{const input=f.prepare(),accepted=await f.call(input);assert.equal(accepted.status,200); + await f.bank.query('INSERT INTO pb_financial_policies(policy_key,policy_json,version,updated_by,updated_at) VALUES(?,?,1,?,1)',['federal_reserve',JSON.stringify({enabled:true,lastDay:'2026-11-25',prices:{'spice.guild':2094,'spice.smuggler':1575}}),f.user.id]); + assert.equal((await f.call(input)).body.netMinor,accepted.body.netMinor);await f.receipt(input);const paid=await f.call({action:'settle',requestId:input.requestId});assert.equal(paid.status,200);assert.equal(Number((await f.bank.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor),spiceQuote('guild',64).netMinor); + }finally{f.bank.close();} +}); test('quotes are bounded and Smuggler access requires an actually active quest',()=>{assert.throws(()=>spiceQuote('guild',0));assert.throws(()=>spiceQuote('guild',21313));assert.throws(()=>spiceQuote('exchange',1));assert.notEqual(spiceQuote('guild',64).netMinor,spiceQuote('smuggler',64).netMinor);assert.equal(activeSmugglerQuest({quests:[{branch:'smugglers',state:'available'}]}),false);assert.equal(activeSmugglerQuest({quests:[{branch:'smugglers',state:'claimed'}]}),false);assert.equal(activeSmugglerQuest({quests:[{branch:'smugglers',state:'active'}]}),true);}); test('an expired committed sale settles once with read-only inventory access',async()=>{const f=await fixture({readOnlyReceipts:true});try{const input=f.prepare();assert.equal((await f.call(input)).status,200);await f.receipt(input);f.expire();assert.equal((await f.call({action:'settle',requestId:input.requestId})).status,200);assert.equal((await f.call({action:'settle',requestId:input.requestId})).body.replayed,true);assert.equal(Number((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n),2);}finally{f.bank.close();}}); test('Arrakis-only and authenticated; locked Smuggler cannot prepare and quotes do not pay',async()=>{const f=await fixture();try{assert.equal((await f.call({action:'read'},'bad')).status,401);assert.equal((await f.call({action:'read',server:'caladan'})).status,400);assert.equal((await f.call(f.prepare('smuggler'))).status,403);f.active();assert.equal((await f.call(f.prepare('smuggler'))).status,200);assert.equal((await f.bank.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,0);}finally{f.bank.close();}}); diff --git a/website/tests/jarvis-economy-public.test.mjs b/website/tests/jarvis-economy-public.test.mjs index 359743cc..3dd6fae9 100644 --- a/website/tests/jarvis-economy-public.test.mjs +++ b/website/tests/jarvis-economy-public.test.mjs @@ -20,3 +20,5 @@ test('normalisation preserves gaps and never invents a line from a zero baseline assert.deepEqual(normalisedEconomicSeries([{v:null},{v:50}],'v'),[null,{i:1,value:100}]); assert.deepEqual(normalisedEconomicSeries([],'v'),[]); }); + +test('a reset hides old-epoch charts while awaiting the real payroll',async()=>{const route=createEconomyHistory({query:async()=>{throw Error('Old history must not be read');}},{clock:()=>10000,bank:{first:async()=>({policy_json:JSON.stringify({enabled:true,state:'awaiting-payroll',epoch:'new-epoch',resetAt:9000}),version:1})}});const data=await(await route(new Request('https://cp.dunerealms.com/api/bank/public/economy'))).json();assert.equal(data.state,'awaiting-payroll');assert.deepEqual(data.records,[]);assert.match(data.message,/first completed payroll/);}); diff --git a/website/tests/postbank-credit-support.test.mjs b/website/tests/postbank-credit-support.test.mjs index 18f6e9f3..f59934cb 100644 --- a/website/tests/postbank-credit-support.test.mjs +++ b/website/tests/postbank-credit-support.test.mjs @@ -1,26 +1,29 @@ -import test from 'node:test';import assert from 'node:assert/strict';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 {PostbankCreditSupport} from '../node/postbank-credit-support.mjs';import {BANK_VERSION} from '../node/postbank-catalogue.mjs';import {CREDIT_VERSION} from '../node/postbank-credit-model.mjs'; -async function fixture(){ - const db=new BankFixture(),user={id:randomUUID(),username:'Applicant'},entity={id:randomUUID(),kind:'person',key:user.id,name:'Applicant'}; - const authority=async()=>({entities:[{...entity,canActivate:true,canPay:true,canView:true}]}); - await new PostbankService(db,authority).activate(user,{entityId:entity.id,packageKey:'pb_flow',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()}); - const account=await db.first("SELECT id FROM pb_accounts WHERE type_code='102'"); - const input={requestId:randomUUID(),accountId:String(account.id),productKey:'personal_loan',amount:'1000.00',months:12,motivation:'Working supplies and a repayment plan',accepted:true,termsVersion:CREDIT_VERSION}; - const central={prepare(){return{bind(){return this;},async first(){return{username:user.username};}};}}; - return{db,user,input,central,credit:new PostbankCredit(db,authority)}; -} -test('New applications use their bank identity as Codex dossiers and create no Support job',async()=>{ - const f=await fixture();try{await f.credit.apply(f.user,f.input);await f.credit.apply(f.user,f.input);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_credit_support_jobs')).n,0);}finally{f.db.close();} - const g=await fixture();try{await g.credit.apply(g.user,{...g.input,productKey:'grant_start',amount:undefined,months:undefined,monthly:'250.00'});assert.equal((await g.db.first('SELECT COUNT(*) n FROM pb_credit_support_jobs')).n,0);}finally{g.db.close();} -}); -test('Retained historical Support jobs can still be reconciled explicitly without altering bank decisions',async()=>{ - const f=await fixture();let unavailable=true,now=1000000;const seen=[]; - try{await f.credit.apply(f.user,f.input);await f.db.query('INSERT INTO pb_credit_support_jobs(loan_id) VALUES(?)',[f.input.requestId]);const worker=new PostbankCreditSupport(f.db,f.central,{clock:()=>now,createTicket:async payload=>{seen.push(payload);if(unavailable)throw Error('Outage');return{ok:true,ticketId:123,ticketNumber:'BANK-123'};}}); - assert.equal((await worker.process()).failed,1);assert.equal((await f.db.first('SELECT state FROM pb_credit_loans')).state,'submitted');assert.equal((await f.db.first('SELECT lease_until FROM pb_credit_support_jobs')).lease_until,0); - unavailable=false;now+=61000;assert.equal((await worker.process()).linked,1);const job=await f.db.first('SELECT * FROM pb_credit_support_jobs');assert.equal(job.ticket_id,123);assert.equal(job.state,'linked');assert.equal(seen[0].applicationId,seen[1].applicationId);assert.equal(seen[1].userId,f.user.id); - await f.db.query("UPDATE pb_credit_loans SET state='declined'");now+=61000;await worker.process();assert.equal((await f.db.first('SELECT state FROM pb_credit_support_jobs')).state,'closed');assert.equal(seen.at(-1).state,'declined');assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0); - }finally{f.db.close();} -}); -test('Audit failure rolls back the loan and its review job together',async()=>{ - const f=await fixture();try{f.db.sqlite.exec("CREATE TRIGGER fail_loan_audit BEFORE INSERT ON pb_audit BEGIN SELECT RAISE(ABORT,'audit fault'); END;");await assert.rejects(f.credit.apply(f.user,f.input),/audit fault/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_credit_support_jobs')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_credit_loans')).n,0);}finally{f.db.close();} -}); +import test from 'node:test';import assert from 'node:assert/strict';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 {PostbankCreditSupport} from '../node/postbank-credit-support.mjs';import {BANK_VERSION} from '../node/postbank-catalogue.mjs';import {CREDIT_VERSION} from '../node/postbank-credit-model.mjs'; +async function fixture(){ + const db=new BankFixture(),user={id:randomUUID(),username:'Applicant'},entity={id:randomUUID(),kind:'person',key:user.id,name:'Applicant'}; + const authority=async()=>({entities:[{...entity,canActivate:true,canPay:true,canView:true}]}); + await new PostbankService(db,authority).activate(user,{entityId:entity.id,packageKey:'pb_flow',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()}); + const account=await db.first("SELECT id FROM pb_accounts WHERE type_code='102'"); + const input={requestId:randomUUID(),accountId:String(account.id),productKey:'personal_loan',amount:'1000.00',months:12,motivation:'Working supplies and a repayment plan',accepted:true,termsVersion:CREDIT_VERSION}; + const central={prepare(){return{bind(){return this;},async first(){return{username:user.username};}};}}; + return{db,user,input,central,credit:new PostbankCredit(db,authority)}; +} +test('New applications use their bank identity as Codex dossiers and create no Support job',async()=>{ + const f=await fixture();try{await f.credit.apply(f.user,f.input);await f.credit.apply(f.user,f.input);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_credit_support_jobs')).n,0);}finally{f.db.close();} + const g=await fixture();try{await g.credit.apply(g.user,{...g.input,productKey:'grant_start',amount:undefined,months:undefined,monthly:'250.00'});assert.equal((await g.db.first('SELECT COUNT(*) n FROM pb_credit_support_jobs')).n,0);}finally{g.db.close();} +}); +test('Retained historical Support jobs can still be reconciled explicitly without altering bank decisions',async()=>{ + const f=await fixture();let unavailable=true,now=1000000;const seen=[]; + try{await f.credit.apply(f.user,f.input);await f.db.query('INSERT INTO pb_credit_support_jobs(loan_id) VALUES(?)',[f.input.requestId]);const worker=new PostbankCreditSupport(f.db,f.central,{clock:()=>now,createTicket:async payload=>{seen.push(payload);if(unavailable)throw Error('Outage');return{ok:true,ticketId:123,ticketNumber:'BANK-123'};}}); + assert.equal((await worker.process()).failed,1);assert.equal((await f.db.first('SELECT state FROM pb_credit_loans')).state,'submitted');assert.equal((await f.db.first('SELECT lease_until FROM pb_credit_support_jobs')).lease_until,0); + unavailable=false;now+=61000;assert.equal((await worker.process()).linked,1);const job=await f.db.first('SELECT * FROM pb_credit_support_jobs');assert.equal(job.ticket_id,123);assert.equal(job.state,'linked');assert.equal(seen[0].applicationId,seen[1].applicationId);assert.equal(seen[1].userId,f.user.id); + await f.db.query("UPDATE pb_credit_loans SET state='declined'");now+=61000;await worker.process();assert.equal((await f.db.first('SELECT state FROM pb_credit_support_jobs')).state,'closed');assert.equal(seen.at(-1).state,'declined');assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0); + }finally{f.db.close();} +}); +test('Audit failure rolls back the loan and its review job together',async()=>{ + const f=await fixture();try{f.db.sqlite.exec("CREATE TRIGGER fail_loan_audit BEFORE INSERT ON pb_audit BEGIN SELECT RAISE(ABORT,'audit fault'); END;");await assert.rejects(f.credit.apply(f.user,f.input),/audit fault/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_credit_support_jobs')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_credit_loans')).n,0);}finally{f.db.close();} +}); + +import {defaultBankRates} from '../node/postbank-financial-policy.mjs'; +test('published rates invalidate stale quotes and leave existing loan contracts unchanged',async()=>{const f=await fixture();try{const value=defaultBankRates();value.creditAnnualBps.personal_loan=1000;await f.db.query('INSERT INTO pb_financial_policies VALUES(?,?,1,?,1)',['bank_rates',JSON.stringify(value),f.user.id]);const details={accountId:f.input.accountId,productKey:f.input.productKey,amount:f.input.amount,months:f.input.months},quote=(await f.credit.simulate(f.user,details)).quote;assert.equal(quote.annualRate,'10.00');await assert.rejects(f.credit.apply(f.user,f.input),e=>e.status===409);await f.credit.apply(f.user,{...f.input,termsVersion:quote.termsVersion});value.creditAnnualBps.personal_loan=1100;await f.db.query('UPDATE pb_financial_policies SET policy_json=?,version=2 WHERE policy_key=?',[JSON.stringify(value),'bank_rates']);assert.equal((await f.credit.simulate(f.user,details)).quote.annualRate,'11.00');assert.equal((await f.db.first('SELECT annual_bps FROM pb_credit_loans')).annual_bps,1000);}finally{f.db.close();}}); diff --git a/website/tests/postbank-credit-ui.test.mjs b/website/tests/postbank-credit-ui.test.mjs index b39aea87..b351a708 100644 --- a/website/tests/postbank-credit-ui.test.mjs +++ b/website/tests/postbank-credit-ui.test.mjs @@ -2,7 +2,7 @@ import {randomUUID} from 'node:crypto';import {BankFixture} from './postbank-fix 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={head:new Node('head'),querySelector:()=>null,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;}} +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={head:new Node('head'),querySelector:()=>null,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:{termsVersion:CREDIT_VERSION,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');});