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 53372a43..b361cbf7 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 @@ -35,7 +35,7 @@ export function mountPostbankCredit(host,id,{fetcher=fetch,reviewSearch=globalTh } 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();}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; + 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); @@ -45,7 +45,7 @@ export function mountPostbankCredit(host,id,{fetcher=fetch,reviewSearch=globalTh if(!staff&&d.maximumRepayment!==undefined)body.append(el('p','Queued repayments / recoveries: '+d.queuedRepayments+' DM · Maximum additional repayment today: '+d.maximumRepayment+' DM. Available account funds are checked separately.')); if(enabled&&!staff){if(d.state==='offered')instruction(body,'Accept credit offer','/api/bank/credit/action',()=>({loanId:loan.id,action:'accept',expectedVersion:d.version,reason:'Accepted the disclosed credit offer'}),{reason:false,confirmation:'I accept the full repayment cost and authorise the first instalment from my own funds before the loan is issued. It reduces my remaining debt.'});if(['submitted','approved_pending','offered','payout_queued'].includes(d.state))instruction(body,'Withdraw application','/api/bank/credit/action',()=>({loanId:loan.id,action:'withdraw'}));if(['active','arrears'].includes(d.state))instruction(body,'Make a repayment','/api/bank/credit/action',()=>({loanId:loan.id,action:'repay'}),{amount:true,confirmation:'Debit the linked current account at the next four-hour bank window. Earned interest is charged; future interest is waived. Confirmed reserved funds retain their bank value date.'});} if(enabled&&staff){if(d.state==='submitted'&&loan.canReview){const approveForm=instruction(body,'Approve application','/api/bank/admin/credit/decision',()=>({loanId:loan.id,action:'approve'}),{risk:loan.score.score<400||loan.score.flags.includes('High Monthly Commitments')});const declineForm=instruction(body,'Reject application','/api/bank/admin/credit/decision',()=>({loanId:loan.id,action:'decline'}));if(review?.loanId===loan.id){const selected=review.action==='approve'?approveForm:declineForm;selected.classList.add('pb-credit-selected-decision');selected.prepend(el('h3',review.action==='approve'?'Confirm approval':'Confirm rejection'));queueMicrotask(()=>{if(active){selected.scrollIntoView?.({block:'center',behavior:'smooth'});selected.querySelector?.('textarea')?.focus();}});}}if(d.state==='arrears')instruction(body,'Recover pledged collateral','/api/bank/admin/credit/recover',()=>({loanId:loan.id,action:'recover'}),{amount:true,confirmation:'Recover only this contract’s pledged DM to reduce its debt. No inventory is involved.'});} - if(d.schedule.length){const {wrap,body:rows}=grid(['Due date','Principal · DM','Interest · DM','Paid · DM','Status']);for(const row of d.schedule){const tr=el('tr');for(const value of [new Date(row.dueAt).toLocaleDateString('en-GB'),row.principal,row.interest,row.paid,human(row.state)])tr.append(el('td',value));rows.append(tr);}body.append(wrap);}else body.append(el('p','The repayment schedule starts only when funds are disbursed.'));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')); + 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')){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 Support ticket remains open.';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.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.'));} diff --git a/website/integrations/osticket/bank-credit-review.php b/website/integrations/osticket/bank-credit-review.php index 0703fc21..ee157bd6 100644 --- a/website/integrations/osticket/bank-credit-review.php +++ b/website/integrations/osticket/bank-credit-review.php @@ -7,12 +7,9 @@ $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.

-

+ + Imperial Postbank · Credit decision
Approve application… Reject application… -

-

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

-
+ Confirm your decision in CP. A different bank manager must review applications you submitted or control. The linked ticket updates after a recorded decision. + diff --git a/website/node/postbank-api.mjs b/website/node/postbank-api.mjs index b2b9bf11..30d7368d 100644 --- a/website/node/postbank-api.mjs +++ b/website/node/postbank-api.mjs @@ -117,7 +117,7 @@ export function createPostbankApi(central,bank,settings={},deps={}){ } if(['/api/bank/admin/credit/decision','/api/bank/admin/credit/recover'].includes(path)){ if(request.method!=='POST')return reply({message:'Method not allowed.'},405);if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403);if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);if(url.search)return reply({message:'Account overrides are not accepted.'},400);if(!creditEnabled)return reply({message:'Credit processing is not active.'},409); - try{const raw=await request.text();if(raw.length>2500)return reply({message:'Request too large.'},413);const input=JSON.parse(raw),fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403);if(!(await authority(fresh)).manageAdmin)return reply({message:'Bank management permission is required.'},403);const recovery=path.endsWith('/recover');if(recovery?input.action!=='recover':!['approve','decline'].includes(input.action))return reply({message:'Unknown staff credit action.'},400);return reply(await (recovery?creditEngine.requestRepayment(fresh,input,{revalidate:()=>auth(request)}):creditEngine.decision(fresh,input,{revalidate:()=>auth(request)})));}catch(error){return reply({message:error.status?error.message:'The credit instruction could not be confirmed.'},error.status||503);} + try{const raw=await request.text();if(raw.length>2500)return reply({message:'Request too large.'},413);const input=JSON.parse(raw),fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403);if(!(await authority(fresh)).manageAdmin)return reply({message:'Bank management permission is required.'},403);const recovery=path.endsWith('/recover');if(recovery?input.action!=='recover':!['approve','decline'].includes(input.action))return reply({message:'Unknown staff credit action.'},400);const result=await (recovery?creditEngine.requestRepayment(fresh,input,{revalidate:()=>auth(request)}):creditEngine.decision(fresh,input,{revalidate:()=>auth(request)}));if(!recovery){void bank.query("UPDATE pb_credit_support_jobs SET next_attempt=0 WHERE loan_id=? AND state<>'closed'",[input.loanId]).then(()=>creditSupport.process({loanId:input.loanId,limit:1})).catch(()=>{});return reply({...result,notice:input.action==='approve'?'Approval recorded. The linked Support ticket is updating. The borrower must accept the offer before payment at a four-hour bank window.':'Rejection recorded. The linked Support ticket is updating.'});}return reply(result);}catch(error){return reply({message:error.status?error.message:'The credit instruction could not be confirmed.'},error.status||503);} } if(['/api/bank/authorisations','/api/bank/authorisations/lookup','/api/bank/authorisations/change','/api/bank/admin/authorisations','/api/bank/admin/authorisations/lookup','/api/bank/admin/authorisations/change'].includes(path)){ const staff=path.startsWith('/api/bank/admin/'); diff --git a/website/scripts/install-bank-credit-support.py b/website/scripts/install-bank-credit-support.py index 72f3cde8..910796f9 100644 --- a/website/scripts/install-bank-credit-support.py +++ b/website/scripts/install-bank-credit-support.py @@ -7,11 +7,20 @@ import sys def ticket_review_hook(source): hook = "require_once(dirname(__DIR__).'/bank-credit-review.php');" - if hook in source: - return source + source = source.replace(hook + '\n', '') anchor = "require_once(STAFFINC_DIR.$inc);" if source.count(anchor) != 1: raise RuntimeError('Native staff ticket view changed; no files installed') + return source + + +def reply_review_hook(source): + hook = "" + if hook in source: + return source + anchor = " \">" + if source.count(anchor) != 1: + raise RuntimeError('Native reply controls changed; no files installed') return source.replace(anchor, hook + '\n' + anchor) @@ -22,6 +31,8 @@ def install(apply=False): 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() + reply_view = target / 'include/staff/ticket-view.inc.php' + files[reply_view] = reply_review_hook(reply_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: diff --git a/website/tests/postbank-credit-ui.test.mjs b/website/tests/postbank-credit-ui.test.mjs index 51fc7bd6..52bb5a13 100644 --- a/website/tests/postbank-credit-ui.test.mjs +++ b/website/tests/postbank-credit-ui.test.mjs @@ -33,7 +33,7 @@ test('Support decision links open only the linked contract without submitting a },{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.ok(nodes().some(n=>n.textContent.includes('already offered'))); assert.equal(calls.filter(c=>c.method==='POST').length,0); },{pageId:'loan-administration',loans:[linkedLoan],enabled:true,detailState:'offered',reviewSearch:'?creditApplication='+linkedLoan.id+'&creditDecision=decline'})); test('Support review selection rejects invalid identities, duplicate parameters and unknown actions',()=>{ @@ -41,3 +41,10 @@ test('Support review selection rejects invalid identities, duplicate parameters assert.equal(creditReviewSelection('?creditApplication='+linkedLoan.id+'&creditDecision=approve&creditDecision=decline'),null); assert.equal(creditReviewSelection('?creditApplication='+linkedLoan.id+'&creditDecision=pay'),null); }); + +test('a self-review link explains why confirmation is blocked and keeps the ticket open',()=>fixture(async({nodes,calls})=>{ + assert.ok(nodes().some(n=>n.attrs.role==='status'&&n.textContent.includes('A different bank manager'))); + assert.ok(nodes().some(n=>n.textContent.includes('Support ticket remains open'))); + assert.ok(!nodes().some(n=>n.tagName==='BUTTON'&&n.textContent==='Approve application')); + assert.equal(calls.filter(c=>c.method==='POST').length,0); +},{pageId:'loan-administration',loans:[{...linkedLoan,canReview:false}],enabled:true,detailState:'submitted',reviewSearch:'?creditApplication='+linkedLoan.id+'&creditDecision=approve'}));