Merge pull request 'Show loan processing in the payment waiting list' (#340) from release/alpha1009-payments-current into main

This commit is contained in:
unimatrix 2026-11-16 05:52:32 +00:00
commit 4a7911e767
5 changed files with 89 additions and 3 deletions

40
AGENTS.md Normal file
View file

@ -0,0 +1,40 @@
# DuneRealms default working instructions
These are the user's default preferences for future DuneRealms work. Apply them unless the user changes them.
## Tools and access
- Prefer the connected Composio Gitea/Forgejo integration for DuneGit repository reads, pull requests, workflow dispatch, CI status, and deployment actions.
- Discover the actual tools and schemas before use. Do not assume that a GitHub tool targets DuneGit.
- Use local Git for local edits, diffs, commits, and efficient pushes of tested local changes. This does not require SSH access to the server.
- Use direct SSH only for server operations that repository/CI tools cannot perform. Keep SSH use minimal. Do not require Gateway when it is unavailable or its quota is exhausted.
- Never save passwords, private keys, tokens, or credential-bearing URLs in instructions, commits, logs, or PR descriptions.
## Small batches through CI
- Implement, check, commit, and publish small coherent batches as work progresses. Do not hold all completed work until the entire feature is finished.
- Reuse existing infrastructure, permissions, audit records, and payment/voting mechanisms wherever possible.
- Run checks appropriate to each batch. Fix failures caused by the change before publishing. Report any existing unrelated failures accurately.
- Push changes to the user's current feature/PR branch. Keep the ongoing feature PR open until the entire agreed scope is finished; PR #337 is the ongoing Alpha 1.0.0.9 PR until the user changes this.
- Deploy verified batches through the established website CI and deployment pipeline. A workflow dispatch being accepted, or an artifact being uploaded, does not establish that production is updated.
- Follow CI and deployment through completion, then verify the live release and affected behavior before claiming it is live.
- If deployment requires main while the umbrella PR must stay open, use a separate release branch/PR containing only the completed batch, based on freshly fetched current main. Do not merge or close the umbrella PR prematurely.
- If a dispatch reports an error after HTTP 204, or a write times out, inspect the resulting run/remote state before retrying. Avoid duplicate writes or deployments.
## Protect existing progress
- Inspect the working tree and remote branch heads before changing branches or publishing. Preserve unrelated edits and work in progress.
- Explicitly fetch the intended remote branch ref into its tracking ref when needed, and verify it matches the remote head. Do not assume a plain fetch refreshed an old tracking branch.
- Never restore an old release, force-push, hard-reset, replace live files from an old backup, or resolve conflicts by discarding newer work merely to make deployment pass.
- Stop and diagnose unexpected ancestry, missing files, or modify/delete conflicts. Preserve the current state; do not force a merge or push.
- Keep backups outside the source tree and do not copy credentials into ordinary build artifacts.
- Do not run broad cleanup, destructive migrations, or financial transactions unless the user has authorized the actual action.
## Collaboration and product behavior
- Continue authorized work without repeated permission questions or handoffs. Do not switch to Work mode.
- Give concise progress updates describing results, blockers, and the next useful step.
- Preserve existing working voting and banking behavior. Personal voting rights are absolute; organisation voting changes must not transfer personal votes.
- Place new features in the existing navigation structure when an item already exists. Avoid duplicate menus.
- Use the established CP design, readable colors, gold framing, and appropriate original Dune/Minecraft-inspired artwork. Company CP uses the Vaerkring/Spacing Guild-inspired palette.
- Clearly mark unfinished features as coming soon. Do not display invented records, offers, payments, or completed actions.

View file

@ -19,7 +19,7 @@ export function mountPostbankAdmin(host,id,{fetcher=fetch}={}){
if(mode==='payroll'){const pane=el('section');frame.content.append(pane);await renderPayroll(pane,{api,isActive:()=>active&&mode==='payroll'});frame.status.hidden=true;return;}if(mode==='compensation'){const pane=el('section');frame.content.append(pane);await renderServiceCompensation(pane,{api,original:selectedPayment,canManage:stats.permissions.canManage,isActive:()=>active&&mode==='compensation'});frame.status.hidden=true;return;}const tools=el('form',undefined,'pb-admin-tools'),search=el('input');search.type='search';search.value=query;search.placeholder=mode==='audit'?'Action or entity name':'Name or client number';search.maxLength=80;const type=el('select');selectOption(type,'All entity types','');for(const value of mode==='corporate'?['clan','company']:['person','clan','company','house','office','staff'])selectOption(type,human(value),value);type.value=kind;const apply=el('button','Search');apply.type='submit';
if(mode!=='pending'){tools.append(field('Search',search));if(!['audit','treasuries'].includes(mode))tools.append(field('Entity type',type));tools.append(apply);tools.onsubmit=e=>{e.preventDefault();query=search.value;kind=type.value;page=1;void load();};frame.content.append(tools);}
const endpoint=mode==='treasuries'?'treasuries':mode==='pending'?'pending':mode==='audit'?'audit':mode==='corporate'?'corporate':'entities',data=await api.request('/api/bank/admin/'+endpoint+'?page='+page+(query?'&q='+encodeURIComponent(query):'')+(kind?'&kind='+encodeURIComponent(kind):''));if(!active)return;
if(!data.records.length)frame.content.append(el('p',mode==='pending'?'No standard payments are awaiting settlement.':mode==='corporate'?'No matching business entities. Companies appear only after registration; no example companies are created.':'No matching bank records.'));
if(mode==='pending'){renderPending(data);renderPendingCredit(data.creditRecords||[]);}else if(!data.records.length)frame.content.append(el('p',mode==='pending'?'No standard payments are awaiting settlement.':mode==='corporate'?'No matching business entities. Companies appear only after registration; no example companies are created.':'No matching bank records.'));
else if(mode==='clients'||mode==='corporate')renderEntities(data);else if(mode==='treasuries')renderTreasuries(data,stats.permissions.canManage,stats.permissions.canIssueReserve);else if(mode==='audit')renderAudit(data);else renderPending(data);
const nav=el('nav',undefined,'pb-ledger-pagination'),previous=el('button','Previous'),next=el('button','Next');previous.type=next.type='button';previous.disabled=page===1;next.disabled=!data.hasMore;previous.onclick=()=>{page--;void load();};next.onclick=()=>{page++;void load();};nav.append(previous,el('span','Page '+page),next);frame.content.append(nav);frame.status.hidden=true;frame.diagnostics.textContent='Central API · Bank administration permission confirmed · '+new Date().toLocaleString('en-GB');
}catch(error){if(active)message(error.message);}finally{busy=false;if(active)frame.reloadButton.disabled=false;}}
@ -65,6 +65,12 @@ export function mountPostbankAdmin(host,id,{fetcher=fetch}={}){
function renderEntities(data){const {wrap,body}=table(['Client / Entity','Type','Package','State','Available · DM','Accounts']);for(const r of data.records){const row=el('tr'),name=el('td');name.append(el('strong',r.name));const details=el('details');details.append(el('summary','+ Client number'),el('code',r.clientNumber||'Not activated'));name.append(details);row.append(name,el('td',human(r.kind)),el('td',r.packageKey?human(r.packageKey):'Awaiting selection'),el('td',human(r.state)),el('td',r.available===null?'—':r.available));const action=el('td'),button=el('button','View '+r.accountCount);button.type='button';action.append(button);row.append(action);body.append(row);const expanded=el('tr'),cell=el('td');cell.colSpan=6;expanded.hidden=true;expanded.append(cell);body.append(expanded);button.onclick=async()=>{expanded.hidden=!expanded.hidden;if(expanded.hidden)return;button.disabled=true;cell.replaceChildren(el('p','Loading authorised accounts…'));try{const records=await api.request('/api/bank/admin/accounts?entityId='+encodeURIComponent(r.id));if(!active)return;cell.replaceChildren();const management=el('section',undefined,'pb-admin-account');cell.append(management);void renderClientManagement(management,r.id,{api,isActive:()=>active});if(!records.accounts.length)cell.append(el('p','The authorised representative must activate this entity in My Products.'));for(const a of records.accounts){const account=el('section',undefined,'pb-admin-account'),open=el('button','View transactions');open.type='button';account.append(el('strong',a.name),el('code',number(a.number)),el('span',a.balance+' DM · Available '+a.available+' DM · '+human(a.state)),open);const activity=el('div');account.append(activity);open.onclick=()=>void accountActivity(a.id,activity,1);cell.append(account);}}catch(error){if(active)cell.replaceChildren(el('p',error.message));}finally{if(active)button.disabled=false;}};}frame.content.append(wrap);}
async function accountActivity(accountId,host,page){host.replaceChildren(el('p','Loading transactions…'));try{const data=await api.request('/api/bank/admin/activity?accountId='+accountId+'&page='+page);if(!active)return;host.replaceChildren();const {wrap,body}=table(['Date','Reference','From','To','Amount · DM','Status','Balance after','Done by']);for(const r of data.records){const row=el('tr');row.dataset.direction=r.direction;row.append(el('td',new Date(r.createdAt).toLocaleString('en-GB')),el('td',r.reference,'pb-ledger-reference'),party(r.from),party(r.to),el('td',(r.direction==='debit'?'-':'+')+r.amount),paymentStatus(r),el('td',r.balanceAfter||'—'),el('td',r.doneBy||'Not recorded'));if(r.payroll){const details=el('details');details.append(el('summary','+ Payroll breakdown · '+r.payroll.person));for(const [key,label]of [['net','Net salary'],['gross','Gross salary'],['employeeSocial','Employee social'],['incomeTax','Income tax'],['employerSocial','Employer social'],['government','Total to I.D. Taxes'],['employerCost','Total employer cost']])details.append(el('p',label+': '+r.payroll[key]+' DM'));row.children[1].append(details);}if(canCompensate&&r.state==='posted'&&['standard','instant'].includes(r.mode)){const comp=el('button','Compensate payer');comp.type='button';comp.onclick=()=>{selectedPayment=r;mode='compensation';void load();};row.children[1].append(comp);}body.append(row);}host.append(wrap);if(!data.records.length)host.append(el('p','No transactions for this account.'));const nav=el('nav',undefined,'pb-ledger-pagination'),back=el('button','Previous'),next=el('button','Next');back.type=next.type='button';back.disabled=page===1;next.disabled=!data.hasMore;back.onclick=()=>void accountActivity(accountId,host,page-1);next.onclick=()=>void accountActivity(accountId,host,page+1);nav.append(back,el('span','Page '+page),next);host.append(nav);}catch(error){if(active)host.replaceChildren(el('p',error.message));}}
function renderAudit(data){const {wrap,body}=table(['Date','Action','Performed by','Entity','Details']);for(const r of data.records){const row=el('tr'),details=el('td'),expand=el('details');expand.append(el('summary','+ Event details'));for(const [key,value]of Object.entries(r.details)){const line=el('p');line.append(el('strong',human(key)+': '),el('span',String(value)));expand.append(line);}if(!Object.keys(r.details).length)expand.append(el('p','No additional public details.'));details.append(expand);row.append(el('td',new Date(r.createdAt).toLocaleString('en-GB')),el('td',human(r.action)),el('td',r.actor),el('td',r.entity),details);body.append(row);}frame.content.append(wrap);}
function renderPending(data){frame.content.append(el('p','Standard settlement: every four hours. Posted payments cannot be reversed here.','pb-muted'));const {wrap,body}=table(['Submitted','Reference','From','To','Amount · DM','Control']);for(const r of data.records){const row=el('tr'),reference=el('td');reference.append(el('strong',r.reference),el('small','Submitted by '+r.actor));const control=el('td');if(data.canManage){const panel=el('details');panel.append(el('summary','Cancel queued payment'));const form=el('form',undefined,'pb-cancel-payment'),reason=el('input');reason.required=true;reason.minLength=5;reason.maxLength=120;const confirm=el('input');confirm.type='checkbox';confirm.required=true;const label=el('label',undefined,'pb-consent');label.append(confirm,el('span','I confirm cancellation and release of the reserved amount.'));const send=el('button','Confirm cancellation');send.type='submit';form.append(field('Cancellation reason',reason),label,send);form.onsubmit=async e=>{e.preventDefault();if(busy||!form.reportValidity())return;busy=true;send.disabled=true;try{await api.request('/api/bank/admin/transfers/cancel',{requestId:crypto.randomUUID(),paymentId:r.paymentId,reason:reason.value,confirmed:true});busy=false;await load();}catch(error){if(active)message(error.message);}finally{busy=false;if(active)send.disabled=false;}};panel.append(form);control.append(panel);}else control.append(el('span','Read only'));row.append(el('td',new Date(r.createdAt).toLocaleString('en-GB')),reference,party(r.from),party(r.to),el('td',r.amount),control);body.append(row);}frame.content.append(wrap);}
function renderPending(data){if(!data.records.length){frame.content.append(el('p','No standard payments are awaiting settlement.'));return;}frame.content.append(el('p','Standard settlement: every four hours. Posted payments cannot be reversed here.','pb-muted'));const {wrap,body}=table(['Submitted','Reference','From','To','Amount · DM','Control']);for(const r of data.records){const row=el('tr'),reference=el('td');reference.append(el('strong',r.reference),el('small','Submitted by '+r.actor));const control=el('td');if(data.canManage){const panel=el('details');panel.append(el('summary','Cancel queued payment'));const form=el('form',undefined,'pb-cancel-payment'),reason=el('input');reason.required=true;reason.minLength=5;reason.maxLength=120;const confirm=el('input');confirm.type='checkbox';confirm.required=true;const label=el('label',undefined,'pb-consent');label.append(confirm,el('span','I confirm cancellation and release of the reserved amount.'));const send=el('button','Confirm cancellation');send.type='submit';form.append(field('Cancellation reason',reason),label,send);form.onsubmit=async e=>{e.preventDefault();if(busy||!form.reportValidity())return;busy=true;send.disabled=true;try{await api.request('/api/bank/admin/transfers/cancel',{requestId:crypto.randomUUID(),paymentId:r.paymentId,reason:reason.value,confirmed:true});busy=false;await load();}catch(error){if(active)message(error.message);}finally{busy=false;if(active)send.disabled=false;}};panel.append(form);control.append(panel);}else control.append(el('span','Read only'));row.append(el('td',new Date(r.createdAt).toLocaleString('en-GB')),reference,party(r.from),party(r.to),el('td',r.amount),control);body.append(row);}frame.content.append(wrap);}
function renderPendingCredit(records){
frame.content.append(el('h3','Loan processing'),el('p','Loan payouts, queued repayments and due instalments use the existing four-hour bank ticker. Loans awaiting treasury funds stay queued until funds are available. Review and approval remain in Credit Management.','pb-muted'));
if(!records.length){frame.content.append(el('p','No loan processing is currently waiting.'));return;}
const {wrap,body}=table(['Queued / Due','Client','Processing','Amount · DM','Status','Contract']);
for(const r of records){const row=el('tr'),client=el('td'),contract=el('td'),link=el('a','Open credit contract →');client.append(el('strong',r.entity),el('small',number(r.accountNumber)));link.href='https://cp.dunerealms.com/?creditApplication='+encodeURIComponent(r.loanId)+'#bank/loan-administration';link.target='_top';contract.append(link);const status=r.state==='approved_pending'?'Awaiting treasury reservation':r.state==='payout_queued'?'Payout queued':r.state==='late'?'Collection awaiting funds':'Awaiting scheduled processing';row.append(el('td',new Date(r.createdAt).toLocaleString('en-GB')),client,el('td',r.kind==='payout'?'Loan payout':r.kind==='instalment'?'Due instalment':human(r.kind)),el('td',r.amount),el('td',status),contract);body.append(row);}frame.content.append(wrap);
}
void load();return()=>{active=false;controller.abort();frame.root.remove();};
}

View file

@ -1,3 +1,4 @@
import {pendingCredit} from "./postbank-pending-credit.mjs";
import {REGISTRY_ACTOR} from './postbank-registry.mjs';
import {personnelLabel} from './personnel-numbers.mjs';
import {payrollOrderId} from './postbank-payroll.mjs';
@ -99,7 +100,7 @@ export class PostbankAdmin{
async audit(user,input={}){await this.access(user);const {q,page}=this.filter(input),args=q?[escapeLike(q),escapeLike(q)]:[],rows=await this.db.query('SELECT a.*,e.display_name entity_name FROM pb_audit a LEFT JOIN pb_entities e ON e.id=a.entity_id'+(q?" WHERE a.action LIKE ? ESCAPE '!' OR e.display_name LIKE ? ESCAPE '!'":'')+' ORDER BY a.created_at DESC,a.id DESC LIMIT 26 OFFSET '+((page-1)*25),args),names=await this.actors([...new Set(rows.slice(0,25).map(r=>r.actor_id))]);
const visible=['packageKey','from','to','packageId','requestId','paymentId','accountId','balanceGuard','monthlyMinor','state','reason','batch','perAccountDM','totalDM','resetRequiredOnFinalDeployment','performedBy','originalPaymentId','funding','amountDM'];return {records:rows.slice(0,25).map(r=>{let raw={};try{raw=JSON.parse(r.details);}catch{}return {id:r.id,createdAt:Number(r.created_at),actor:r.actor_id===REGISTRY_ACTOR?'Bank registry synchroniser':names.get(r.actor_id)||'Former account',entity:r.entity_name||'Bank service',action:r.action,details:Object.fromEntries(visible.filter(k=>Object.hasOwn(raw,k)).map(k=>[k,raw[k]]))};}),hasMore:rows.length>25,page};
}
async pending(user,input={}){const c=await this.access(user),{page}=this.filter(input);const rows=await this.db.query("SELECT o.id,o.actor_id,o.amount_minor,o.memo,o.created_at,s.account_number source_number,t.account_number target_number,es.display_name source_name,et.display_name target_name FROM pb_orders o JOIN pb_accounts s ON s.id=o.source_id JOIN pb_clients cs ON cs.client_number=s.client_number JOIN pb_entities es ON es.id=cs.entity_id JOIN pb_accounts t ON t.id=o.target_id JOIN pb_clients ct ON ct.client_number=t.client_number JOIN pb_entities et ON et.id=ct.entity_id WHERE o.state='queued' AND o.mode='standard' ORDER BY o.created_at,o.id LIMIT 26 OFFSET "+((page-1)*25)),names=await this.actors([...new Set(rows.slice(0,25).map(r=>r.actor_id))]);return {records:rows.slice(0,25).map(r=>({paymentId:r.id,actor:r.actor_id===REGISTRY_ACTOR?'Bank registry synchroniser':names.get(r.actor_id)||'Former account',reference:r.memo,amount:money(r.amount_minor),createdAt:Number(r.created_at),from:{name:r.source_name,number:r.source_number},to:{name:r.target_name,number:r.target_number}})),canManage:c.manageAdmin,hasMore:rows.length>25,page};}
async pending(user,input={}){const c=await this.access(user),{page}=this.filter(input);const rows=await this.db.query("SELECT o.id,o.actor_id,o.amount_minor,o.memo,o.created_at,s.account_number source_number,t.account_number target_number,es.display_name source_name,et.display_name target_name FROM pb_orders o JOIN pb_accounts s ON s.id=o.source_id JOIN pb_clients cs ON cs.client_number=s.client_number JOIN pb_entities es ON es.id=cs.entity_id JOIN pb_accounts t ON t.id=o.target_id JOIN pb_clients ct ON ct.client_number=t.client_number JOIN pb_entities et ON et.id=ct.entity_id WHERE o.state='queued' AND o.mode='standard' ORDER BY o.created_at,o.id LIMIT 26 OFFSET "+((page-1)*25)),names=await this.actors([...new Set(rows.slice(0,25).map(r=>r.actor_id))]),credit=await pendingCredit(this.db,{page,now:this.clock()});return {creditRecords:credit.records,records:rows.slice(0,25).map(r=>({paymentId:r.id,actor:r.actor_id===REGISTRY_ACTOR?'Bank registry synchroniser':names.get(r.actor_id)||'Former account',reference:r.memo,amount:money(r.amount_minor),createdAt:Number(r.created_at),from:{name:r.source_name,number:r.source_number},to:{name:r.target_name,number:r.target_number}})),canManage:c.manageAdmin,hasMore:rows.length>25||credit.hasMore,page};}
// Staff-only attribution comes from the stored authoriser, never the account label.
async attributeActivity(result,orders=null,user=null){
if(!result.records.length)return result;const ids=result.records.map(r=>r.paymentId),rows=orders||await this.db.query('SELECT id,actor_id FROM pb_orders WHERE id IN ('+ids.map(()=>'?').join(',')+')',ids),actors=new Map(rows.map(r=>[r.id,r.actor_id])),names=await this.actors([...new Set(rows.map(r=>r.actor_id).filter(Boolean))]);

View file

@ -0,0 +1,18 @@
import {money} from './postbank-catalogue.mjs';
// Read-only projection of the existing credit worker's queues. No processing here.
export async function pendingCredit(db,{page,now}){
const offset=(page-1)*25;
const rows=await db.query(`SELECT q.*,e.display_name entity_name,a.account_number FROM (
SELECT l.id queue_id,l.id loan_id,l.entity_id,l.account_id,l.product_key,l.principal_minor amount_minor,COALESCE(l.queued_at,l.updated_at) queued_at,l.state status,'payout' kind
FROM pb_credit_loans l WHERE l.state IN ('approved_pending','payout_queued')
UNION ALL
SELECT x.id,x.loan_id,l.entity_id,l.account_id,l.product_key,x.amount_minor,x.created_at,x.state,x.kind
FROM pb_credit_actions x JOIN pb_credit_loans l ON l.id=x.loan_id WHERE x.state='queued'
UNION ALL
SELECT CONCAT(i.loan_id,':',i.sequence_no),i.loan_id,l.entity_id,l.account_id,l.product_key,i.principal_minor+i.interest_minor-i.paid_principal-i.paid_interest,i.due_at,i.state,'instalment'
FROM pb_credit_instalments i JOIN pb_credit_loans l ON l.id=i.loan_id
WHERE l.state IN ('active','arrears') AND l.next_due_at<=? AND i.due_at<=? AND i.state IN ('pending','late') AND i.principal_minor+i.interest_minor>i.paid_principal+i.paid_interest
) q JOIN pb_entities e ON e.id=q.entity_id JOIN pb_accounts a ON a.id=q.account_id
ORDER BY q.queued_at,q.queue_id LIMIT 26 OFFSET ${offset}`,[now,now]);
return {records:rows.slice(0,25).map(r=>({id:r.queue_id,loanId:r.loan_id,kind:r.kind,state:r.status,productKey:r.product_key,entity:r.entity_name,accountNumber:r.account_number,amount:money(r.amount_minor),createdAt:Number(r.queued_at)})),hasMore:rows.length>25};
}

View file

@ -24,3 +24,24 @@ test('tax treasury excludes payroll/collateral/inactive targets and cannot overs
test('tax payment permission revocation and audit failure roll back balances and ledger',async()=>{for(const failure of ['permission','audit']){const f=await setup();try{const r=await f.db.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,state,created_at) VALUES('sys_tax_treasury','979','I.D. Taxes',10000,'active',1)");await f.db.query('UPDATE pb_accounts SET account_number=? WHERE id=?',[bankNumber('979',r.insertId),r.insertId]);if(failure==='audit')f.db.sqlite.exec("CREATE TRIGGER fail_tax_audit BEFORE INSERT ON pb_audit WHEN NEW.action='tax_treasury_payment' BEGIN SELECT RAISE(ABORT,'injected audit failure'); END;");const b={requestId:randomUUID(),targetNumber:f.target.account_number,amount:'5.00',reference:'Approved project',confirmed:true};await assert.rejects(f.admin.taxPayment(f.users[2],b,{revalidate:async()=>{if(failure==='permission')f.revokeManage();return f.users[2];}}));assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[r.insertId])).balance_minor,10000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,0);}finally{f.db.close();}}});
test('staff ledger shows the recorded authoriser while customer activity omits attribution',async()=>{const f=await setup();try{const tax=await f.db.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,state,created_at) VALUES('sys_tax_treasury','979','I.D. Taxes',10000,'active',1)");await f.db.query('UPDATE pb_accounts SET account_number=? WHERE id=?',[bankNumber('979',tax.insertId),tax.insertId]);const input={requestId:randomUUID(),targetNumber:f.target.account_number,amount:'5.00',reference:'Recorded staff allocation',confirmed:true};await f.admin.taxPayment(f.users[2],input);const treasury=await f.admin.activity(f.users[2],{accountId:String(tax.insertId)}),customerAccount=await f.admin.activity(f.users[2],{accountId:String(f.target.id)});assert.equal(treasury.records[0].doneBy,f.users[2].username);assert.equal(customerAccount.records[0].doneBy,f.users[2].username);assert.equal(Object.hasOwn((await f.payments.activity(f.users[0],{accountId:String(f.target.id)})).records[0],'doneBy'),false);await assert.rejects(f.admin.activity(f.users[0],{accountId:String(tax.insertId)}),e=>e.status===403);await f.db.query("UPDATE pb_orders SET actor_id='unknown-historical-actor' WHERE id=?",[input.requestId]);assert.equal((await f.admin.activity(f.users[2],{accountId:String(tax.insertId)})).records[0].doneBy,'Not recorded');}finally{f.db.close();}});
test('waiting list includes actual credit queues and due instalments without changing contracts or balances',async()=>{
const f=await setup();try{
const now=Date.now(),ids={};
for(const state of ['approved_pending','payout_queued','active','submitted','offered']){
const id=ids[state]=randomUUID();
await f.db.query('INSERT INTO pb_credit_loans(id,client_number,entity_id,account_id,product_key,state,principal_minor,monthly_minor,annual_bps,months,created_by,motivation,quote_json,score_json,created_at,updated_at,queued_at,next_due_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',[id,f.source.client_number,f.entities[0].id,f.source.id,'personal_loan',state,10000,1000,500,12,f.users[0].id,'Test application','{}','{}',now-1000,now-1000,state==='payout_queued'?now-900:null,state==='active'?now-100:null]);
}
await f.db.query("INSERT INTO pb_credit_actions(id,loan_id,actor_id,kind,amount_minor,state,fingerprint,reason,created_at) VALUES(?,?,?,'repay',500,'queued','test','Test repayment',?)",[randomUUID(),ids.active,f.users[0].id,now-800]);
for(const [sequence,due]of [[1,now-100],[2,now+86400000]])await f.db.query('INSERT INTO pb_credit_instalments(loan_id,sequence_no,due_at,principal_minor,interest_minor) VALUES(?,?,?,?,?)',[ids.active,sequence,due,900,100]);
await assert.rejects(f.admin.pending(f.users[0]),e=>e.status===403);
const before=await f.db.first('SELECT balance_minor,reserved_minor FROM pb_accounts WHERE id=?',[f.source.id]),list=await f.admin.pending(f.users[3]);
assert.equal(list.canManage,false);assert.equal(list.creditRecords.length,4);
assert.deepEqual(list.creditRecords.map(r=>r.kind).sort(),['instalment','payout','payout','repay']);
assert.ok(!list.creditRecords.some(r=>[ids.submitted,ids.offered].includes(r.loanId)));
assert.equal(list.creditRecords.find(r=>r.kind==='instalment').amount,'10.00');
assert.deepEqual(await f.db.first('SELECT balance_minor,reserved_minor FROM pb_accounts WHERE id=?',[f.source.id]),before);
assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_credit_events')).n,0);
assert.equal((await f.admin.pending(f.users[3],{page:2})).creditRecords.length,0);
}finally{f.db.close();}
});