From d5d067370bcef797dde06e06d03954809c5b530d Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Mon, 16 Nov 2026 01:42:50 +0100 Subject: [PATCH] Add confirmed credit review links to Support tickets --- .../public/cp-v2/cp-v2-postbank-credit.mjs | 18 ++++--- .../osticket/bank-credit-review.php | 18 +++++++ website/node/postbank-api.mjs | 4 +- website/node/postbank-credit.mjs | 2 +- .../scripts/install-bank-credit-support.py | 53 ++++++++++++++----- website/tests/postbank-credit-ui.test.mjs | 23 +++++++- website/tests/postbank-credit.test.mjs | 15 ++++++ 7 files changed, 110 insertions(+), 23 deletions(-) create mode 100644 website/integrations/osticket/bank-credit-review.php 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 df21d1b2..53372a43 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 @@ -6,10 +6,16 @@ const title={'loan-centre':'Loans & Grants','bank-loans':'My Credit','loan-admin 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 mountPostbankCredit(host,id,{fetcher=fetch}={}){ +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 mountPostbankCredit(host,id,{fetcher=fetch,reviewSearch=globalThis.location?.search||''}={}){ + const review=id==='loan-administration'?creditReviewSelection(reviewSearch):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':'/api/bank/credit/overview');if(!active)return;frame.content.replaceChildren();if(id==='loan-centre')catalogue();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;}} + 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'+(review?'?loanId='+encodeURIComponent(review.loanId):''):'/api/bank/credit/overview');if(!active)return;frame.content.replaceChildren();if(id==='loan-centre')catalogue();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;} @@ -38,11 +44,11 @@ export function mountPostbankCredit(host,id,{fetcher=fetch}={}){ let loaded=false;const expand=el('details'),summary=el('summary','+ Contract details & actions'),body=el('div');body.className='pb-credit-contract-panel';body.id='credit-contract-'+loan.id;summary.setAttribute('aria-controls',body.id);if(detailRow){detailRow.firstElementChild.append(body);expand.append(summary);}else expand.append(summary,body);host.append(expand);expand.ontoggle=async()=>{if(detailRow)detailRow.hidden=!expand.open;summary.setAttribute('aria-expanded',String(expand.open));if(!expand.open||loaded)return;loaded=true;body.textContent='Loading current contract…';try{const d=await api.request((staff?'/api/bank/admin/credit/details':'/api/bank/credit/details')+'?loanId='+encodeURIComponent(loan.id));if(!active)return;body.replaceChildren(el('p',loan.motivation),el('p','Annual rate: '+d.quote.annualRate+'% · Total repayment: '+d.quote.totalRepayment+' DM · First instalment: '+(d.quote.firstInstalment||'0.00')+' DM'+(d.collateral!=='0.00'?' · Historical pledged collateral: '+d.collateral+' DM':'')),el('p','Settlement estimate today: '+d.settlement+' DM'),el('p',d.decision||'No decision recorded.'));if(d.supportTicket){const line=el('p',d.supportTicket.number?'Support review ticket: '+d.supportTicket.number:'Support review ticket is being linked. Your application is saved.');if(/^https:\/\/support\.dunerealms\.com\/(?:scp\/tickets\.php\?id=\d+|tickets\.php)$/.test(d.supportTicket.url||'')){const link=el('a','Open Support →');link.href=d.supportTicket.url;link.target='_blank';link.rel='noopener';line.append(' · ',link);}body.append(line);}if(d.replacedBy)body.append(el('p','Replaced by refinancing contract '+d.replacedBy+'. Original history is retained.'));for(const notice of d.notices||[]){const box=el('aside',undefined,'pb-credit-notice'+(d.state==='arrears'?' pb-credit-notice-alert':''));box.append(el('strong',notice.subject),el('p',notice.body));body.append(box);}const enabled=staff?view.processing==='active'&&view.canManage:view.intakeEnabled; if(!staff&&d.maximumRepayment!==undefined)body.append(el('p','Queued repayments / recoveries: '+d.queuedRepayments+' DM · Maximum additional repayment today: '+d.maximumRepayment+' DM. Available account funds are checked separately.')); if(enabled&&!staff){if(d.state==='offered')instruction(body,'Accept credit offer','/api/bank/credit/action',()=>({loanId:loan.id,action:'accept',expectedVersion:d.version,reason:'Accepted the disclosed credit offer'}),{reason:false,confirmation:'I accept the full repayment cost and authorise the first instalment from my own funds before the loan is issued. It reduces my remaining debt.'});if(['submitted','approved_pending','offered','payout_queued'].includes(d.state))instruction(body,'Withdraw application','/api/bank/credit/action',()=>({loanId:loan.id,action:'withdraw'}));if(['active','arrears'].includes(d.state))instruction(body,'Make a repayment','/api/bank/credit/action',()=>({loanId:loan.id,action:'repay'}),{amount:true,confirmation:'Debit the linked current account at the next four-hour bank window. Earned interest is charged; future interest is waived. Confirmed reserved funds retain their bank value date.'});} - if(enabled&&staff){if(d.state==='submitted'&&loan.canReview){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')});instruction(body,'Decline application','/api/bank/admin/credit/decision',()=>({loanId:loan.id,action:'decline'}));}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.')); - }catch(error){if(active){body.textContent=error.message;loaded=false;}}}; + 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.'));if(review?.loanId===loan.id&&(!enabled||!loan.canReview||d.state!=='submitted'))body.append(el('p','No decision is available: this application has already progressed, processing is unavailable, or your account cannot independently review it.','pb-muted')); + }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.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(' · ')));contractDetails(cell,loan,true,expanded);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','No credit applications are awaiting review.'));} + 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 application linked to your Support ticket. No decision is submitted until you confirm.'),back);}} void load();return()=>{active=false;abort.abort();frame.root.remove();}; } diff --git a/website/integrations/osticket/bank-credit-review.php b/website/integrations/osticket/bank-credit-review.php new file mode 100644 index 00000000..0703fc21 --- /dev/null +++ b/website/integrations/osticket/bank-credit-review.php @@ -0,0 +1,18 @@ +checkStaffPerm($thisstaff)) return; +$result = db_query('SELECT application_id FROM dune_bank_credit_tickets WHERE ticket_id='.(int)$ticket->getId().' LIMIT 1'); +$binding = $result ? db_fetch_array($result) : null; +$application = $binding['application_id'] ?? ''; +if (!preg_match('/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i', $application)) return; +$base = 'https://cp.dunerealms.com/?creditApplication='.rawurlencode($application); +?> +
+

Imperial Postbank · Credit decision

+

Open the current contract and confirm your decision in Credit Management. Bank permissions and independent-review rules apply. Closing this ticket does not decide the application.

+

+ Approve application… + Reject application… +

+

A reason and explicit confirmation are required. Approval still requires the borrower to accept the offer before funding.

+
diff --git a/website/node/postbank-api.mjs b/website/node/postbank-api.mjs index 2f22c511..b2b9bf11 100644 --- a/website/node/postbank-api.mjs +++ b/website/node/postbank-api.mjs @@ -194,7 +194,7 @@ export function createPostbankApi(central,bank,settings={},deps={}){ return reply(await (path.endsWith('/cancel')?admin.cancel(user,input,{revalidate:()=>auth(request)}):path.endsWith('/grants')?admin.issueGrant(user,input,{revalidate:()=>auth(request)}):path.endsWith('/taxes/payments')?admin.taxPayment(user,input,{revalidate:()=>auth(request)}):admin.treasuryTransfer(user,input,{revalidate:()=>auth(request)}))); } if(request.method!=='GET')return reply({message:'Method not allowed.'},405); - const permitted=path.endsWith('/taxes/recipients')?['q']:path.endsWith('/overview')?[]:path.endsWith('/accounts')?['entityId']:path.endsWith('/activity')?['accountId','page']:['q','kind','page'];if([...url.searchParams.keys()].some(k=>!permitted.includes(k)||url.searchParams.getAll(k).length!==1))return reply({message:'Invalid bank administration filter.'},400); + const permitted=path==='/api/bank/admin/credit'?['loanId']:path.endsWith('/taxes/recipients')?['q']:path.endsWith('/overview')?[]:path.endsWith('/accounts')?['entityId']:path.endsWith('/activity')?['accountId','page']:['q','kind','page'];if([...url.searchParams.keys()].some(k=>!permitted.includes(k)||url.searchParams.getAll(k).length!==1))return reply({message:'Invalid bank administration filter.'},400); const input=Object.fromEntries(url.searchParams);let result; if(path==='/api/bank/admin/overview')result=await admin.overview(user); else if(path==='/api/bank/admin/entities')result=await admin.entities(user,input); @@ -202,7 +202,7 @@ export function createPostbankApi(central,bank,settings={},deps={}){ else if(path==='/api/bank/admin/taxes/overview')result=await admin.taxOverview(user); else if(path==='/api/bank/admin/taxes/recipients')result=await admin.taxRecipients(user,input.q); else if(path==='/api/bank/admin/treasuries')result=await admin.treasuries(user,input); - else if(path==='/api/bank/admin/credit')result={...await credit.staff(user),processing:creditEnabled?'active':'not_active'}; + else if(path==='/api/bank/admin/credit')result={...await credit.staff(user,input),processing:creditEnabled?'active':'not_active'}; else if(path==='/api/bank/admin/accounts')result=await admin.accounts(user,input.entityId); else if(path==='/api/bank/admin/activity')result=await admin.activity(user,input); else if(path==='/api/bank/admin/audit')result=await admin.audit(user,input); diff --git a/website/node/postbank-credit.mjs b/website/node/postbank-credit.mjs index 05a442f9..11e1cc2c 100644 --- a/website/node/postbank-credit.mjs +++ b/website/node/postbank-credit.mjs @@ -11,7 +11,7 @@ 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,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){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 ORDER BY l.created_at DESC LIMIT 100');return {canManage:!!rights.manageAdmin,applications:rows.map(l=>({id:l.id,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 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,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()); diff --git a/website/scripts/install-bank-credit-support.py b/website/scripts/install-bank-credit-support.py index fccc6da7..72f3cde8 100644 --- a/website/scripts/install-bank-credit-support.py +++ b/website/scripts/install-bank-credit-support.py @@ -1,16 +1,45 @@ -"""Install the existing-flow loan ticket adapter from a CI-approved release.""" +"""Install bank ticket integration from a CI-approved release.""" from pathlib import Path import os import subprocess import sys -source = Path(__file__).resolve().parents[1] / 'integrations/osticket/bank-credit-ticket.php' -target = Path('/home/dunerealms/apps/integrations/osticket/bank-credit-ticket.php') -subprocess.run(['php', '-l', str(source)], check=True) -if '--apply' not in sys.argv: - print('Plan: install one private CLI ticket adapter; no changes applied') - sys.exit(0) -temporary = target.with_name(target.name + '.migration-new') -temporary.write_bytes(source.read_bytes()) -temporary.chmod(0o644) -os.replace(temporary, target) -print('Installed private bank-credit ticket adapter; native core unchanged') + + +def ticket_review_hook(source): + hook = "require_once(dirname(__DIR__).'/bank-credit-review.php');" + if hook in source: + return source + anchor = "require_once(STAFFINC_DIR.$inc);" + if source.count(anchor) != 1: + raise RuntimeError('Native staff ticket view changed; no files installed') + return source.replace(anchor, hook + '\n' + anchor) + + +def install(apply=False): + source = Path(__file__).resolve().parents[1] / 'integrations/osticket' + target = Path('/home/dunerealms/apps/integrations/osticket') + files = {target / name: (source / name).read_bytes() + for name in ['bank-credit-ticket.php', 'bank-credit-review.php']} + ticket_view = target / 'scp/tickets.php' + files[ticket_view] = ticket_review_hook(ticket_view.read_text()).encode() + for name in ['bank-credit-ticket.php', 'bank-credit-review.php']: + subprocess.run(['php', '-l', str(source / name)], check=True) + if not apply: + print('Plan: install bank ticket adapter and staff decision links; no changes applied') + return + for path, content in files.items(): + if path.exists() and path.read_bytes() == content: + continue + temporary = path.with_name(path.name + '.migration-new') + temporary.write_bytes(content) + temporary.chmod(0o644) + try: + subprocess.run(['php', '-l', str(temporary)], check=True) + os.replace(temporary, path) + finally: + temporary.unlink(missing_ok=True) + print('Installed bank ticket adapter and staff decision links') + + +if __name__ == '__main__': + install('--apply' in sys.argv) diff --git a/website/tests/postbank-credit-ui.test.mjs b/website/tests/postbank-credit-ui.test.mjs index 55521588..51fc7bd6 100644 --- a/website/tests/postbank-credit-ui.test.mjs +++ b/website/tests/postbank-credit-ui.test.mjs @@ -1,8 +1,8 @@ import {randomUUID} from 'node:crypto';import {BankFixture} from './postbank-fixture.mjs';import {PostbankService} from '../node/postbank-service.mjs';import {PostbankCredit} from '../node/postbank-credit.mjs';import {BANK_VERSION} from '../node/postbank-catalogue.mjs';import {CREDIT_VERSION} from '../node/postbank-credit-model.mjs'; -import test from 'node:test';import assert from 'node:assert/strict';import {mountPostbankCredit,creditTheme} from '../control-panel/public/cp-v2/cp-v2-postbank-credit.mjs'; +import test from 'node:test';import assert from 'node:assert/strict';import {mountPostbankCredit,creditTheme,creditReviewSelection} from '../control-panel/public/cp-v2/cp-v2-postbank-credit.mjs'; class Node{constructor(tag){this.tagName=tag.toUpperCase();this.children=[];this.attrs={};this.classList={add:()=>{}};this.value='';this.disabled=false;this.dataset={};this._text='';}set textContent(v){this._text=String(v);this.children=[];}get textContent(){return this._text+this.children.map(n=>n.textContent).join('');}append(...nodes){for(const n of nodes){n.parent=this;this.children.push(n);if(this.tagName==='SELECT'&&!this.value)this.value=n.value;}}prepend(...nodes){for(const n of nodes)n.parent=this;this.children.unshift(...nodes);}get firstElementChild(){return this.children[0]||null;}get elements(){return all(this).filter(n=>['INPUT','SELECT','TEXTAREA','BUTTON'].includes(n.tagName));}replaceChildren(...nodes){this._text='';this.children=[];this.append(...nodes);}setAttribute(k,v){this.attrs[k]=String(v);}closest(){return null;}remove(){if(this.parent)this.parent.children=this.parent.children.filter(n=>n!==this);}focus(){}reportValidity(){return true;}} const all=n=>n.children.flatMap(c=>[c,...all(c)]),settle=async()=>{for(let i=0;i<6;i++)await new Promise(r=>setImmediate(r));}; -async function fixture(run,{enabled=false,uncertain=false,validateApplication=null,includeGrant=false,loans=[],pageId="loan-centre"}={}){const prior=globalThis.document;globalThis.document={createElement:t=>new Node(t),createElementNS:(ns,t)=>new Node(t)};let applyAttempts=0;const host=new Node('div'),calls=[],products=[...(includeGrant?[{key:'grant_start',name:'Launch Start',group:'grants',kinds:['person'],amount:'2500.00',annualBps:0}]:[]),{key:'personal_loan',name:'Personal Loan',group:'personal',kinds:['person'],min:'1000.00',max:'25000.00',annualBps:839,terms:[3,6]},{key:'business_loan',name:'Business Loan',group:'professional',kinds:['clan'],min:'5000.00',max:'100000.00',annualBps:450,terms:[6,12]}],accounts=[{id:'1',name:'Personal current',number:'DR25102000000005',kind:'person',canApply:true},{id:'2',name:'Clan current',number:'DR14105000000004',kind:'clan',canApply:true}],fetcher=async(path,options={})=>{calls.push({path,...options});if(path.includes('/details?'))return Response.json({quote:{annualRate:'0.00',totalRepayment:'10000.00'},collateral:'0.00',settlement:'10000.00',schedule:[],state:'disbursed'});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,intakeEnabled:enabled,termsVersion:CREDIT_VERSION});};const dispose=mountPostbankCredit(host,pageId,{fetcher});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={createElement:t=>new Node(t),createElementNS:(ns,t)=>new Node(t)};let applyAttempts=0;const host=new Node('div'),calls=[],products=[...(includeGrant?[{key:'grant_start',name:'Launch Start',group:'grants',kinds:['person'],amount:'2500.00',annualBps:0}]:[]),{key:'personal_loan',name:'Personal Loan',group:'personal',kinds:['person'],min:'1000.00',max:'25000.00',annualBps:839,terms:[3,6]},{key:'business_loan',name:'Business Loan',group:'professional',kinds:['clan'],min:'5000.00',max:'100000.00',annualBps:450,terms:[6,12]}],accounts=[{id:'1',name:'Personal current',number:'DR25102000000005',kind:'person',canApply:true},{id:'2',name:'Clan current',number:'DR14105000000004',kind:'clan',canApply:true}],fetcher=async(path,options={})=>{calls.push({path,...options});if(path.includes('/details?'))return Response.json({quote:{annualRate:'0.00',totalRepayment:'10000.00'},collateral:'0.00',settlement:'10000.00',schedule:[],state:detailState});if(path.endsWith('/apply')&&validateApplication){try{const result=await validateApplication(JSON.parse(options.body));if(!uncertain||applyAttempts++>0)return Response.json(result);}catch(error){return Response.json({message:error.message},{status:error.status||400});}}if(path.endsWith('/apply')&&uncertain&&applyAttempts++===0)return Response.json({message:'Uncertain result'},{status:503});return Response.json(path.endsWith('/simulate')?{quote:{monthly:'100.00',annualRate:'8.39',months:12,totalInterest:'200.00',totalRepayment:'1200.00',schedule:[]},collateral:'250.00',notice:'No financial change'}:{accounts,products,loans,applications:loans,canManage:enabled,processing:enabled?'active':'not_active',intakeEnabled:enabled,termsVersion:CREDIT_VERSION});};const dispose=mountPostbankCredit(host,pageId,{fetcher,reviewSearch});try{await settle();await run({host,calls,nodes:()=>all(host)});}finally{dispose();globalThis.document=prior;}} test('borrowing tabs filter product cards and simulation replaces the catalogue rather than appearing below it',()=>fixture(async({nodes,calls})=>{const tabs=nodes().filter(n=>n.attrs.role==='tab');assert.equal(tabs.length,2);assert.equal(nodes().filter(n=>n.tagName==='SELECT').length,0);assert.ok(nodes().some(n=>n.className?.includes('pb-choice-card')&&n.className.includes('pb-plan-flow')));tabs[1].onclick();assert.ok(nodes().some(n=>n.tagName==='H5'&&n.textContent==='Business Loan'));assert.ok(!nodes().some(n=>n.tagName==='H5'&&n.textContent==='Personal Loan'));nodes().find(n=>n.tagName==='BUTTON'&&n.textContent==='Simulate repayments').onclick();assert.ok(!nodes().some(n=>n.className?.includes('pb-credit-products')));assert.ok(nodes().some(n=>n.className==='pb-credit-calculator'));const form=nodes().find(n=>n.tagName==='FORM');await form.onsubmit({preventDefault(){}});assert.equal(JSON.parse(calls.find(c=>c.method==='POST').body).accountId,'2');assert.ok(nodes().some(n=>n.className==='pb-credit-monthly'&&n.textContent==='100.00 DM'));nodes().find(n=>n.tagName==='INPUT').oninput();assert.ok(!nodes().some(n=>n.className==='pb-credit-monthly'));nodes().find(n=>n.tagName==='BUTTON'&&n.textContent.startsWith('← Back')).onclick();assert.ok(nodes().some(n=>n.tagName==='H5'&&n.textContent==='Business Loan'));assert.equal(calls.filter(c=>c.method==='POST').length,1);})); test('credit groups reuse the banking package palette',()=>{assert.equal(creditTheme({key:'grant_start'}),'start');assert.equal(creditTheme({key:'grant_build'}),'connect');assert.equal(creditTheme({key:'grant_advance'}),'scale');assert.equal(creditTheme({key:'business_loan'}),'connect');assert.equal(creditTheme({key:'civic_loan'}),'civic');assert.equal(creditTheme({key:'personal_refinance',group:'refinancing'}),'scale');}); @@ -22,3 +22,22 @@ test('expanding a personal loan uses the full table width and collapses cleanly' assert.equal(expand.children.length,1); expand.open=false;await expand.ontoggle();assert.equal(row.hidden,true); },{pageId:'bank-loans',loans:[{id:'loan-1',productKey:'grant_advance',state:'disbursed',principal:'10000.00',outstanding:'10000.00',monthly:'834.00'}]})); + +const linkedLoan={id:'bfaaccf2-a33e-4fa1-a64e-995c19b388cb',entity:'Independent applicant',productKey:'civic_loan',state:'submitted',principal:'50000.00',canReview:true,createdAt:1,score:{score:600,band:'Standard',flags:[]},motivation:'A considered public project'}; +test('Support decision links open only the linked contract without submitting a decision',()=>fixture(async({nodes,calls})=>{ + assert.equal(calls[0].path,'/api/bank/admin/credit?loanId='+linkedLoan.id); + assert.ok(calls.some(c=>c.path==='/api/bank/admin/credit/details?loanId='+linkedLoan.id)); + assert.ok(nodes().some(n=>n.tagName==='H3'&&n.textContent==='Confirm approval')); + assert.ok(nodes().some(n=>n.tagName==='FORM'&&n.textContent.includes('Reason'))); + assert.equal(calls.filter(c=>c.method==='POST').length,0); +},{pageId:'loan-administration',loans:[linkedLoan],enabled:true,detailState:'submitted',reviewSearch:'?creditApplication='+linkedLoan.id+'&creditDecision=approve'})); +test('an already decided Support application cannot offer another approval',()=>fixture(async({nodes,calls})=>{ + assert.ok(!nodes().some(n=>n.tagName==='BUTTON'&&n.textContent==='Approve application')); + assert.ok(nodes().some(n=>n.textContent.includes('No decision is available'))); + assert.equal(calls.filter(c=>c.method==='POST').length,0); +},{pageId:'loan-administration',loans:[linkedLoan],enabled:true,detailState:'offered',reviewSearch:'?creditApplication='+linkedLoan.id+'&creditDecision=decline'})); +test('Support review selection rejects invalid identities, duplicate parameters and unknown actions',()=>{ + assert.equal(creditReviewSelection('?creditApplication=bad&creditDecision=approve'),null); + assert.equal(creditReviewSelection('?creditApplication='+linkedLoan.id+'&creditDecision=approve&creditDecision=decline'),null); + assert.equal(creditReviewSelection('?creditApplication='+linkedLoan.id+'&creditDecision=pay'),null); +}); diff --git a/website/tests/postbank-credit.test.mjs b/website/tests/postbank-credit.test.mjs index 0f2eaf63..d09bbb02 100644 --- a/website/tests/postbank-credit.test.mjs +++ b/website/tests/postbank-credit.test.mjs @@ -27,3 +27,18 @@ test('Pro borrowing limits follow the actual account package and are rechecked a assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_credit_loans')).n,0); }finally{f.db.close();} }); + +test('ticket review filters select only the requested contract and retain staff access checks',async()=>{ + const f=await fixture();try{ + const input=application(f);await f.credit.apply(f.user,input); + const manager={id:randomUUID()},rights=async()=>({readAdmin:true,manageAdmin:true,entities:[]}),credit=new PostbankCredit(f.db,rights); + assert.deepEqual((await credit.staff(manager,{loanId:input.requestId})).applications.map(l=>l.id),[input.requestId]); + assert.equal((await credit.staff(manager,{loanId:randomUUID()})).applications.length,0); + await assert.rejects(credit.staff(manager,{loanId:"' OR 1=1"}),e=>e.status===400); + await assert.rejects(f.credit.staff(f.user,{loanId:input.requestId}),e=>e.status===403); + const api=createPostbankApi(null,f.db,{POSTBANK_CREDIT_ENABLED:'true'},{authenticate:async()=>manager,authority:rights,resolveUser:async()=>manager}); + const response=await api(new Request('https://cp.dunerealms.com/api/bank/admin/credit?loanId='+input.requestId));assert.equal(response.status,200);assert.equal((await response.json()).applications[0].id,input.requestId); + assert.equal((await api(new Request('https://cp.dunerealms.com/api/bank/admin/credit?loanId='+input.requestId+'&loanId='+randomUUID()))).status,400); + assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0); + }finally{f.db.close();} +});