forked from unimatrix/web
Add bank administration and modern account navigation
This commit is contained in:
parent
de02bc9205
commit
0c0bedc8e3
5 changed files with 164 additions and 40 deletions
38
website/node/postbank-admin.mjs
Normal file
38
website/node/postbank-admin.mjs
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import {PostbankPayments} from './postbank-payments.mjs';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import {BankError} from './postbank-service.mjs';
|
||||
import {money} from './postbank-catalogue.mjs';
|
||||
const uuid=s=>typeof s==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(s);
|
||||
const entityBase='FROM pb_entities e LEFT JOIN pb_clients c ON c.entity_id=e.id LEFT JOIN pb_activations act ON act.entity_id=e.id LEFT JOIN pb_packages p ON p.id=act.package_id';
|
||||
const escapeLike=s=>'%'+s.replace(/[!%_]/g,c=>'!'+c)+'%';
|
||||
export class PostbankAdmin{
|
||||
constructor(db,central,authority,{clock=Date.now}={}){this.db=db;this.central=central;this.authority=authority;this.clock=clock;}
|
||||
async access(user,manage=false){const c=await this.authority(user);if(!c.readAdmin||manage&&!c.manageAdmin)throw new BankError(manage?'Bank management permission is required.':'Bank administration view permission is required.',403);return c;}
|
||||
filter(input){const q=input.q||'',page=Number(input.page||1),kind=input.kind||'';if(typeof q!=='string'||q.length>80||!Number.isInteger(page)||page<1||page>9999||kind&&!['person','clan','company','house','office','staff'].includes(kind))throw new BankError('Choose valid bank register filters.');return {q:q.trim(),page,kind};}
|
||||
async overview(user){const c=await this.access(user),clients=await this.db.first('SELECT COUNT(*) n FROM pb_clients'),accounts=await this.db.first('SELECT COUNT(*) n,COALESCE(SUM(balance_minor),0) total,COALESCE(SUM(reserved_minor),0) held FROM pb_accounts WHERE system_key IS NULL'),pending=await this.db.first("SELECT COUNT(*) n FROM pb_orders WHERE state='queued'");return {clients:Number(clients.n),accounts:Number(accounts.n),balances:money(accounts.total),reserved:money(accounts.held),pendingPayments:Number(pending.n),permissions:{canManage:c.manageAdmin}};}
|
||||
async entities(user,input={},corporate=false){await this.access(user);const {q,page,kind}=this.filter(input);if(corporate&&kind&&!['clan','company'].includes(kind))throw new BankError('Select a corporate entity type.');const where=['e.active=1'],args=[];if(corporate)where.push("e.kind IN ('clan','company')");if(kind){where.push('e.kind=?');args.push(kind);}if(q){where.push("(e.display_name LIKE ? ESCAPE '!' OR c.client_number LIKE ? ESCAPE '!')");args.push(escapeLike(q),escapeLike(q));}
|
||||
const rows=await this.db.query('SELECT e.id,e.kind,e.display_name,c.client_number,p.package_key,p.monthly_minor,(SELECT COUNT(*) FROM pb_accounts a WHERE a.client_number=c.client_number) account_count,(SELECT COALESCE(SUM(a.balance_minor-a.reserved_minor),0) FROM pb_accounts a WHERE a.client_number=c.client_number) available '+entityBase+' WHERE '+where.join(' AND ')+' ORDER BY e.display_name,e.id LIMIT 26 OFFSET '+((page-1)*25),args);
|
||||
return {records:rows.slice(0,25).map(r=>({id:r.id,kind:r.kind,name:r.display_name,clientNumber:r.client_number,state:r.client_number?'active':'not_activated',packageKey:r.package_key,monthly:r.monthly_minor===null?null:money(r.monthly_minor),accountCount:Number(r.account_count),available:r.client_number?money(r.available):null})),hasMore:rows.length>25,page};
|
||||
}
|
||||
async accounts(user,entityId){await this.access(user);if(!uuid(entityId))throw new BankError('Select a valid banking entity.');const rows=await this.db.query('SELECT a.id,a.account_number,a.display_name,a.type_code,a.balance_minor,a.reserved_minor,a.state,c.client_number FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number WHERE c.entity_id=? ORDER BY a.id',[entityId]);return {accounts:rows.map(a=>({id:String(a.id),number:a.account_number,name:a.display_name,type:a.type_code,balance:money(a.balance_minor),reserved:money(a.reserved_minor),available:money(BigInt(a.balance_minor)-BigInt(a.reserved_minor)),state:a.state,clientNumber:a.client_number}))};}
|
||||
async actors(ids){if(!ids.length)return new Map();const rows=(await this.central.prepare('SELECT id,username FROM site_accounts WHERE id IN ('+ids.map(()=>'?').join(',')+')').bind(...ids).all()).results||[];return new Map(rows.map(a=>[a.id,a.username]));}
|
||||
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'];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: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: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 activity(user,{accountId,page=1}={}){await this.access(user);if(typeof accountId!=='string'||!/^\d{1,12}$/.test(accountId))throw new BankError('Select a valid bank account.');const row=await this.db.first('SELECT c.entity_id FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number WHERE a.id=?',[accountId]);if(!row)throw new BankError('Bank account not found.',404);const reader=new PostbankPayments(this.db,async()=>({entities:[{id:row.entity_id,canView:true}],readAdmin:true,manageAdmin:false}));return reader.activity(user,{accountId,page:Number(page)});}
|
||||
async cancel(user,input,{revalidate=async()=>user}={}){
|
||||
await this.access(user,true);if(!input||Object.keys(input).some(k=>!['requestId','paymentId','reason','confirmed'].includes(k))||!uuid(input.requestId)||!uuid(input.paymentId)||input.confirmed!==true||typeof input.reason!=='string'||input.reason.trim().length<5||input.reason.trim().length>120||/[\u0000-\u001f]/.test(input.reason))throw new BankError('Confirm the cancellation and give a reason of 5–120 characters.');
|
||||
return this.db.transaction(async tx=>{
|
||||
const info=await tx.first('SELECT source_id,target_id FROM pb_orders WHERE id=?',[input.paymentId]);if(!info)throw new BankError('Payment not found.',404);
|
||||
const refs=await tx.query('SELECT a.id AS account_id,c.entity_id FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number WHERE a.id IN (?,?) ORDER BY c.entity_id',[info.source_id,info.target_id]);for(const id of [...new Set(refs.map(r=>r.entity_id))].sort())await tx.first('SELECT id FROM pb_entities WHERE id=? FOR UPDATE',[id]);
|
||||
const order=await tx.first('SELECT * FROM pb_orders WHERE id=? FOR UPDATE',[input.paymentId]);if(order.state==='rejected')return {ok:true,replayed:true,state:'rejected'};if(order.state!=='queued'||order.mode!=='standard')throw new BankError('Only a queued standard payment can be cancelled. Posted payments cannot be reversed here.',409);
|
||||
const previous=await tx.first('SELECT id FROM pb_audit WHERE id=?',[input.requestId]);if(previous)throw new BankError('This request reference has already been used.',409);
|
||||
const source=await tx.first('SELECT id,reserved_minor FROM pb_accounts WHERE id=? FOR UPDATE',[order.source_id]);if(!source||BigInt(source.reserved_minor)<BigInt(order.amount_minor))throw new BankError('This reservation needs reconciliation before cancellation.',409);
|
||||
const fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed. Cancellation was not confirmed.',409);await this.access(fresh,true);
|
||||
await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor-? WHERE id=?',[String(order.amount_minor),source.id]);
|
||||
const reason=input.reason.trim();await tx.query("UPDATE pb_orders SET state='rejected',failure=? WHERE id=?",['Cancelled by bank administration: '+reason,order.id]);
|
||||
await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[input.requestId,user.id,'transfer_cancelled',refs.find(r=>String(r.account_id)===String(order.source_id))?.entity_id||null,JSON.stringify({paymentId:order.id,reason}),this.clock()]);return {ok:true,replayed:false,state:'rejected'};
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
import {PostbankAdmin} from './postbank-admin.mjs';
|
||||
import {createPostbankPayments,standardCycle} from './postbank-payments.mjs';
|
||||
import {identity} from './auth.mjs';
|
||||
import {PostbankService} from './postbank-service.mjs';
|
||||
|
|
@ -6,19 +7,44 @@ import {POSTBANK_CONTRACTS} from './postbank-contract.mjs';
|
|||
export function createPostbankApi(central,bank,settings={},deps={}){
|
||||
const auth=deps.authenticate||(request=>identity(request,central)),authority=deps.authority||createPostbankAuthority(central),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com';
|
||||
const service=bank?new PostbankService(bank,authority,deps):null,payments=createPostbankPayments(central,bank,{...deps,authority});
|
||||
const admin=bank?new PostbankAdmin(bank,central,authority,deps):null;
|
||||
const lookups=new Map(),transferAttempts=new Map();
|
||||
const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}});
|
||||
return async request=>{
|
||||
const url=new URL(request.url),path=url.pathname;
|
||||
const user=await auth(request);if(!user)return reply({message:'Sign in to use Imperial Postbank.'},401);
|
||||
if(!service)return reply({message:'The independent bank database is not linked yet.',state:'not_linked'},503);
|
||||
if(!['/api/bank/recipients','/api/bank/activity'].includes(path)&&url.search)return reply({message:'Banking identity and account overrides are not accepted.'},400);
|
||||
if(!['/api/bank/recipients','/api/bank/activity'].includes(path)&&!path.startsWith('/api/bank/admin/')&&url.search)return reply({message:'Banking identity and account overrides are not accepted.'},400);
|
||||
if(path.startsWith('/api/bank/admin/')){
|
||||
try{
|
||||
if(path==='/api/bank/admin/transfers/cancel'){
|
||||
if(request.method!=='POST')return reply({message:'Method not allowed.'},405);
|
||||
if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403);
|
||||
if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);
|
||||
if(url.search)return reply({message:'Account overrides are not accepted.'},400);const raw=await request.text();if(raw.length>2000)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the cancellation form.'},400);}
|
||||
return reply(await admin.cancel(user,input,{revalidate:()=>auth(request)}));
|
||||
}
|
||||
if(request.method!=='GET')return reply({message:'Method not allowed.'},405);
|
||||
const permitted=path.endsWith('/overview')?[]:path.endsWith('/accounts')?['entityId']:path.endsWith('/activity')?['accountId','page']:['q','kind','page'];if([...url.searchParams.keys()].some(k=>!permitted.includes(k)||url.searchParams.getAll(k).length!==1))return reply({message:'Invalid bank administration filter.'},400);
|
||||
const input=Object.fromEntries(url.searchParams);let result;
|
||||
if(path==='/api/bank/admin/overview')result=await admin.overview(user);
|
||||
else if(path==='/api/bank/admin/entities')result=await admin.entities(user,input);
|
||||
else if(path==='/api/bank/admin/corporate')result=await admin.entities(user,input,true);
|
||||
else if(path==='/api/bank/admin/accounts')result=await admin.accounts(user,input.entityId);
|
||||
else if(path==='/api/bank/admin/activity')result=await admin.activity(user,input);
|
||||
else if(path==='/api/bank/admin/audit')result=await admin.audit(user,input);
|
||||
else if(path==='/api/bank/admin/pending')result=await admin.pending(user,input);
|
||||
else return reply({message:'Bank administration route not found.'},404);
|
||||
const fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed. Reload the bank workspace.'},403);const rights=await admin.access(fresh);if(result.permissions)result.permissions.canManage=rights.manageAdmin;if('canManage' in result)result.canManage=rights.manageAdmin;
|
||||
return reply(result);
|
||||
}catch(error){return reply({message:error.status?error.message:'The bank could not confirm the administrative operation.'},error.status||503);}
|
||||
}
|
||||
if(request.method==='GET'&&['/api/bank/overview','/api/bank/client','/api/bank/accounts'].includes(path)){
|
||||
try{return reply(await service.overview(user));}catch{return reply({message:'The bank could not confirm the current records. Reload the workspace.'},503);}
|
||||
}
|
||||
if(request.method==='GET'&&['/api/bank/transfer-options','/api/bank/recipients','/api/bank/activity'].includes(path)){
|
||||
try{
|
||||
if(path==='/api/bank/transfer-options')return reply({accounts:await payments.accounts(user),actorId:user.id,standard:{state:'active',processing:'Standard payments are processed in batches every four hours: 00:00, 04:00, 08:00, 12:00, 16:00 and 20:00 Europe/Brussels.',nextAt:standardCycle().nextAt},fees:{state:'planned',message:'Automated transfer fee billing is not active in this foundation batch.'}});
|
||||
if(path==='/api/bank/transfer-options')return reply({accounts:await payments.accounts(user),actorId:user.id,standard:{state:'active',processing:'Standard payments are processed in batches every four hours: 00:00, 04:00, 08:00, 12:00, 16:00 and 20:00 Europe/Brussels.',nextAt:standardCycle().nextAt},fees:{state:'planned',message:'Transfer fees are not currently being charged.'}});
|
||||
if(path==='/api/bank/recipients'){
|
||||
if([...url.searchParams.keys()].some(k=>k!=='q')||url.searchParams.getAll('q').length!==1)return reply({message:'Use only the recipient name or account search field.'},400);
|
||||
const now=Date.now();for(const [key,value]of lookups)if(value.until<now)lookups.delete(key);if(lookups.size>10000)return reply({message:'Recipient lookup is busy. Try shortly.'},429);
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ export function createPostbankAuthority(central,{clock=Date.now,rightsFor=access
|
|||
// Staff eligibility follows current central access roles, not cosmetic honours.
|
||||
const staff=await rows("SELECT a.id,a.username,a.role FROM site_accounts a LEFT JOIN site_account_policies p ON p.user_id=a.id WHERE a.password_hash NOT LIKE '!%' AND COALESCE(p.game_link_exempt,0)=0");
|
||||
const eligibleStaff=staff.filter(a=>STAFF_ROLES.has(a.role));
|
||||
for(const actor of eligibleStaff)add('staff',actor.id,actor.username+' · Staff',[actor.id]);
|
||||
for(const actor of eligibleStaff)add('staff',actor.id,actor.username+' · Staff',[actor.id]);
|
||||
return {entities:sources,readAdmin,manageAdmin,eligibleStaff:eligibleStaff.map(a=>({id:a.id,username:a.username})),server:{state:'not_linked',name:'Game server account'}};
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
export const POSTBANK_CONTRACTS=Object.freeze({
|
||||
server:{title:'Game server link',state:'not_linked',request:{method:'POST',path:'/api/bank/integrations/game/payments',fields:['requestId','sourceAccount','targetAccount','amount','reference','gameReceipt']},response:{paymentId:'unique payment reference',state:'queued | posted | rejected'},note:'Future server-to-server integration. No request is sent from this placeholder. Server credentials must never be supplied by a browser.'},
|
||||
server:{title:'Game server link',state:'not_linked',request:{method:'POST',path:'/api/bank/integrations/game/payments',fields:['requestId','sourceAccount','targetNumber','amount','reference','mode','gameReceipt']},response:{paymentId:'unique payment reference',state:'queued | posted | rejected'},note:'Future trusted server-to-server payment instructions only. The central bank authorises, reserves and posts; Java must not duplicate accounting or own bank balances. Standard instructions follow the same four-hour Brussels windows; instant instructions post immediately within bank limits. requestId is retained on retries and fulfilment waits for a confirmed posted bank result. No game link or request is enabled by this placeholder. Server credentials must never be supplied by a browser.'},
|
||||
mandates:{title:'Account authorisations',state:'planned',request:{method:'POST',path:'/api/bank/authorisations',fields:['accountNumber','clientNumber','permissions','startsAt','expiresAt','confirmed']},response:{authorisationId:'new authorisation reference',state:'active | pending'},note:'Creation, editing and revocation of mandates are deferred. Existing imported authority remains checked by the central API.'},
|
||||
investments:{title:'Securities service',state:'planned',request:{method:'POST',path:'/api/bank/investments/orders',fields:['requestId','securitiesAccount','settlementAccount','instrument','side','quantity','confirmed']},response:{orderId:'unique order reference',state:'accepted | rejected'},note:'No trading request is sent. Civic/Public and all 979 funding or settlement accounts are forbidden. Personal eligibility does not grant access to official money.'},
|
||||
loans:{title:'Credit applications',state:'planned',request:{method:'POST',path:'/api/bank/loans/applications',fields:['requestId','accountNumber','amount','motivation','confirmed']},response:{applicationId:'application reference',state:'submitted'},note:'Credit applications, approvals, payouts and repayments are deferred.'},
|
||||
|
|
|
|||
|
|
@ -106,7 +106,7 @@ export class PostbankPayments{
|
|||
const accounts=await this.db.query(accountSQL+' WHERE c.entity_id IN ('+ids.map(()=>'?').join(',')+') ORDER BY a.id',ids);
|
||||
const visible=accountId?accounts.filter(a=>String(a.id)===accountId):accounts;if(accountId&&!visible.length)throw new BankError('You cannot view this account.',403);if(!visible.length)return {records:[],hasMore:false,page};
|
||||
const values=visible.map(a=>String(a.id)),marks=values.map(()=>'?').join(',');
|
||||
const rows=await this.db.query('SELECT o.*,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.source_id IN ('+marks+') OR o.target_id IN ('+marks+')) ORDER BY o.created_at DESC,o.id DESC LIMIT 26 OFFSET '+((page-1)*25),[...values,...values]);
|
||||
const rows=await this.db.query('SELECT o.*,s.account_number source_number,t.account_number target_number,COALESCE(es.display_name,s.display_name) source_name,COALESCE(et.display_name,t.display_name) target_name FROM pb_orders o JOIN pb_accounts s ON s.id=o.source_id LEFT JOIN pb_clients cs ON cs.client_number=s.client_number LEFT JOIN pb_entities es ON es.id=cs.entity_id JOIN pb_accounts t ON t.id=o.target_id LEFT JOIN pb_clients ct ON ct.client_number=t.client_number LEFT JOIN pb_entities et ON et.id=ct.entity_id WHERE (o.source_id IN ('+marks+') OR o.target_id IN ('+marks+')) ORDER BY o.created_at DESC,o.id DESC LIMIT 26 OFFSET '+((page-1)*25),[...values,...values]);
|
||||
const records=[];for(const o of rows.slice(0,25)){
|
||||
const entry=accountId?await this.db.first('SELECT amount_minor,balance_after_minor FROM pb_entries WHERE order_id=? AND account_id=?',[o.id,accountId]):null;
|
||||
records.push({...receipt(o),from:{name:o.source_name,number:o.source_number},to:{name:o.target_name,number:o.target_number},direction:entry?BigInt(entry.amount_minor)<0n?'debit':'credit':values.includes(String(o.source_id))?values.includes(String(o.target_id))?'internal':'debit':'credit',balanceAfter:entry?money(entry.balance_after_minor):null});
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff