MC/website/node/postbank-service.mjs

129 lines
17 KiB
JavaScript

import {canViewAccount,canDebitAccount} from './postbank-authorisations.mjs';
import {randomUUID,createHash} from 'node:crypto';
import {PACKAGES,BANK_VERSION,clientCandidate,bankNumber,money,availablePackages} from './postbank-catalogue.mjs';
export class BankError extends Error{constructor(message,status=400){super(message);this.status=status;}}
const duplicate=e=>e.code==='ER_DUP_ENTRY'||String(e.message).includes('UNIQUE constraint');
export class PostbankService{
constructor(db,authority,{clock=Date.now,makeId=randomUUID,staffAudit=null}={}){this.db=db;this.authority=authority;this.clock=clock;this.makeId=makeId;this.staffAudit=staffAudit;}
async sync(user){
const context=await this.authority(user),now=this.clock();
await this.db.query("UPDATE pb_accounts SET state='blocked',display_name='Blocked Collateral Account' WHERE type_code='106' AND (state<>'blocked' OR display_name<>'Blocked Collateral Account')");
// Import identity metadata only. Imported entities remain unactivated and have
// no client/account number or balance until explicit acceptance succeeds.
const signature=JSON.stringify(context.entities.filter(e=>e.kind!=='person').map(e=>[e.id,e.kind,e.key,e.name]));
for(const e of signature===this.lastImportSignature?[]:context.entities){
if(e.kind==='person')continue;
await this.db.query('INSERT INTO pb_entities(id,kind,external_key,display_name,active,created_at) VALUES(?,?,?,?,1,?) ON DUPLICATE KEY UPDATE display_name=VALUES(display_name),active=1',[e.id,e.kind,e.key,e.name,now]);
}
this.lastImportSignature=signature;return context;
}
async overview(user){
const context=await this.sync(user),entities=[];
for(const e of context.entities.filter(e=>e.canView)){
const client=await this.db.first('SELECT client_number FROM pb_clients WHERE entity_id=?',[e.id]);
const packages=client?await this.db.query('SELECT id,package_key,monthly_minor,state FROM pb_packages WHERE client_number=? ORDER BY accepted_at,id',[client.client_number]):[];
const accounts=client?await this.db.query('SELECT a.id,a.account_number,a.type_code,a.display_name,a.balance_minor,a.reserved_minor,a.state,a.package_id,a.system_key,COALESCE(o.balance_guard,0) AS balance_guard FROM pb_accounts a LEFT JOIN pb_account_options o ON o.account_id=a.id WHERE a.client_number=? ORDER BY a.id',[client.client_number]):[];
entities.push({id:e.id,kind:e.kind,name:e.name,clientNumber:client?.client_number||null,state:client?'active':'not_activated',canActivate:e.canActivate,canPay:e.canPay,expiresAt:e.expiresAt,packages:packages.map(p=>({id:p.id,key:p.package_key,name:PACKAGES.find(s=>s.key===p.package_key)?.name||p.package_key,monthly:money(p.monthly_minor),state:p.state})),accounts:accounts.filter(a=>canViewAccount(context,e.id,a.id)).map(a=>({canPay:a.state==='active'&&a.type_code!=='106'&&canDebitAccount(context,e.id,a.id),id:String(a.id),number:a.account_number,type:a.type_code,name:a.display_name,balance:money(a.balance_minor),available:a.type_code==='106'?'0.00':money(BigInt(a.balance_minor)-BigInt(a.reserved_minor)),state:a.state,packageId:a.package_id,options:{balanceGuardEligible:!['979','106'].includes(a.type_code)&&!a.system_key,balanceGuard:Boolean(a.balance_guard),monthly:money(a.balance_guard?100:0),state:'configured_pending_billing'}}))});
}
return {entities,catalogue:PACKAGES.map(p=>({...p,monthly:money(p.monthly),extraFee:money(p.extraFee)})),termsVersion:BANK_VERSION,admin:{canView:context.readAdmin,canManage:context.manageAdmin},server:{state:'not_linked',name:'Game server account',message:'The game bank is not connected. No game balances or transactions are imported.'},billing:{state:'planned',message:'Monthly fees are disclosed in the package catalogue. Automated billing is not enabled in this foundation batch.'}};
}
async activate(user,input,{revalidate=async()=>user}={}){
if(!input||Object.keys(input).some(k=>!['entityId','packageKey','termsVersion','accepted','requestId'].includes(k))||input.accepted!==true||input.termsVersion!==BANK_VERSION||! /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(input.requestId||''))throw new BankError('Select a package and accept the current package terms.');
const context=await this.sync(user),entity=context.entities.find(e=>e.id===input.entityId&&e.canView&&e.canActivate);
if(!entity)throw new BankError('You are not authorised to activate this banking entity.',403);
const choice=availablePackages(entity.kind).find(p=>p.key===input.packageKey);if(!choice)throw new BankError('This package is not available for the selected banking entity.');
return this.db.transaction(async tx=>{
await tx.query('INSERT INTO pb_entities(id,kind,external_key,display_name,active,created_at) VALUES(?,?,?,?,1,?) ON DUPLICATE KEY UPDATE display_name=VALUES(display_name)',[entity.id,entity.kind,entity.key,entity.name,this.clock()]);
await tx.first('SELECT id FROM pb_entities WHERE id=? FOR UPDATE',[entity.id]);
const previous=await tx.first('SELECT p.id,p.package_key,c.client_number FROM pb_activations a JOIN pb_packages p ON p.id=a.package_id JOIN pb_clients c ON c.entity_id=a.entity_id WHERE a.entity_id=?',[entity.id]);
if(previous){if(previous.package_key!==choice.key)throw new BankError('This entity has already accepted a different package. Reload your accounts.',409);return {ok:true,replayed:true,clientNumber:previous.client_number,packageId:previous.id};}
let number=null;
for(let n=0;n<32;n++){const candidate=clientCandidate(entity.kind,entity.key,n);try{await tx.query('INSERT INTO pb_clients(client_number,entity_id,created_at) VALUES(?,?,?)',[candidate,entity.id,this.clock()]);number=candidate;break;}catch(error){if(!duplicate(error))throw error;}}
if(!number)throw new BankError('A unique client number could not be allocated. Please select your package again.',503);
const packageId=this.makeId(),now=this.clock();
await tx.query('INSERT INTO pb_packages(id,client_number,package_key,monthly_minor,terms_version,accepted_by,accepted_at,state) VALUES(?,?,?,?,?,?,?,?)',[packageId,number,choice.key,choice.monthly,BANK_VERSION,user.id,now,'active']);
const types=[choice.code,...(choice.savings?['103']:[])];
for(const code of types){
const result=await tx.query('INSERT INTO pb_accounts(client_number,package_id,type_code,display_name,balance_minor,reserved_minor,state,created_at) VALUES(?,?,?,?,0,0,?,?)',[number,packageId,code,entity.name+' · '+(code==='103'?'Savings':code==='106'?'Securities':'Current'),code==='106'?'planned':'active',now]);
const id=Number(result.insertId);await tx.query('UPDATE pb_accounts SET account_number=? WHERE id=?',[bankNumber(code,id),id]);
}
await tx.query('INSERT INTO pb_activations(entity_id,package_id) VALUES(?,?)',[entity.id,packageId]);
const fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed. Select your package again.',409);
const latest=await this.authority(fresh,{bank:tx});if(!latest.entities.some(e=>e.id===entity.id&&e.canActivate))throw new BankError('Your authority changed. Select your package again.',409);
await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[this.makeId(),user.id,'entity_activated',entity.id,JSON.stringify({packageKey:choice.key,requestId:input.requestId}),now]);
return {ok:true,replayed:false,clientNumber:number,packageId};
});
}
async changePackage(user,input,{revalidate=async()=>user}={}){
const keys=['entityId','packageId','expectedPackageKey','packageKey','termsVersion','accepted','requestId'];
const uuid=value=>typeof value==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value);
if(!input||typeof input!=='object'||Object.keys(input).some(k=>!keys.includes(k))||input.accepted!==true||input.termsVersion!==BANK_VERSION||!uuid(input.requestId)||!uuid(input.packageId)||!uuid(input.entityId)||typeof input.expectedPackageKey!=='string')throw new BankError('Choose a new package and confirm its current terms.');
const context=await this.sync(user),entity=context.entities.find(e=>e.id===input.entityId&&e.canView&&e.canActivate);
if(!entity)throw new BankError('You are not authorised to change this package.',403);
const choice=availablePackages(entity.kind).find(p=>p.key===input.packageKey);
if(!choice)throw new BankError('This package is not available for the selected banking entity.');
const fingerprint=createHash('sha256').update(JSON.stringify([user.id,input.entityId,input.packageId,input.expectedPackageKey,choice.key,BANK_VERSION,...(this.staffAudit?[this.staffAudit]:[])])).digest('hex');
return this.db.transaction(async tx=>{
await tx.first('SELECT id FROM pb_entities WHERE id=? FOR UPDATE',[entity.id]);
const replay=await tx.first('SELECT actor_id,fingerprint,package_id,to_key FROM pb_package_changes WHERE request_id=?',[input.requestId]);
if(replay){if(replay.actor_id!==user.id||replay.fingerprint!==fingerprint)throw new BankError('This request number was already used for a different change.',409);return {ok:true,replayed:true,packageId:replay.package_id,packageKey:replay.to_key};}
const current=await tx.first('SELECT p.id,p.package_key,p.client_number,p.state FROM pb_packages p JOIN pb_clients c ON c.client_number=p.client_number WHERE p.id=? AND c.entity_id=? FOR UPDATE',[input.packageId,entity.id]);
if(!current)throw new BankError('The package is not available for this banking entity.',404);
if(current.state!=='active')throw new BankError('Only an active package can be changed.',409);
if(current.package_key!==input.expectedPackageKey)throw new BankError('The package changed since you opened this form. Reload and review the current package.',409);
if(current.package_key===choice.key)throw new BankError('Choose a different package.');
const accounts=await tx.query('SELECT id,account_number,type_code,display_name,balance_minor,reserved_minor,state,package_id FROM pb_accounts WHERE package_id=? ORDER BY id FOR UPDATE',[current.id]);
const isCurrent=a=>['102','105','107','108','979'].includes(a.type_code);
const activeCurrent=accounts.filter(a=>isCurrent(a)&&a.state!=='closed'&&a.state!=='dormant');
if(!activeCurrent.length)throw new BankError('The package has no open current account. Contact the bank before switching.',409);
if(activeCurrent.some(a=>a.state!=='active'))throw new BankError('Resolve the account restriction before changing this package.',409);
if(activeCurrent.length>1+choice.extra)throw new BankError('This package allows '+(1+choice.extra)+' current accounts. Close additional accounts before switching.',409);
for(const a of accounts){
const removed=['103','104'].includes(a.type_code)&&!choice.savings;
if(!removed||['closed','dormant'].includes(a.state))continue;
if(BigInt(a.balance_minor)!==0n||BigInt(a.reserved_minor)!==0n)throw new BankError('Move the funds and resolve pending payments on '+a.display_name+' before switching. Its account number and history will be retained.',409);
if(!['active','planned'].includes(a.state))throw new BankError('Resolve the additional account restriction before switching.',409);
await tx.query("UPDATE pb_accounts SET state='dormant' WHERE id=?",[a.id]);
}
for(const code of [...(choice.savings?['103']:[])]){
const existing=accounts.find(a=>a.type_code===code&&a.state!=='closed');
const state=code==='106'?'planned':'active';
if(existing){if(existing.state==='dormant')await tx.query('UPDATE pb_accounts SET state=? WHERE id=?',[state,existing.id]);continue;}
const result=await tx.query('INSERT INTO pb_accounts(client_number,package_id,type_code,display_name,balance_minor,reserved_minor,state,created_at) VALUES(?,?,?,?,0,0,?,?)',[current.client_number,current.id,code,entity.name+' · '+(code==='103'?'Savings':'Securities'),state,this.clock()]);
const id=Number(result.insertId);await tx.query('UPDATE pb_accounts SET account_number=? WHERE id=?',[bankNumber(code,id),id]);
}
const fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed. Reload before changing the package.',409);
const latest=await this.authority(fresh,{bank:tx});if(!latest.entities.some(e=>e.id===entity.id&&e.canActivate))throw new BankError('Your authority to change this package has expired.',409);
const now=this.clock();await tx.query('UPDATE pb_packages SET package_key=?,monthly_minor=?,terms_version=?,accepted_by=?,accepted_at=? WHERE id=?',[choice.key,choice.monthly,BANK_VERSION,user.id,now,current.id]);
await tx.query('INSERT INTO pb_package_changes(request_id,actor_id,entity_id,package_id,fingerprint,from_key,to_key,created_at) VALUES(?,?,?,?,?,?,?,?)',[input.requestId,user.id,entity.id,current.id,fingerprint,current.package_key,choice.key,now]);
await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[this.makeId(),user.id,'package_changed',entity.id,JSON.stringify({packageId:current.id,from:current.package_key,to:choice.key,requestId:input.requestId,...(this.staffAudit?{reason:this.staffAudit.reason,performedBy:'bank_staff'}:{})}),now]);
return {ok:true,replayed:false,packageId:current.id,packageKey:choice.key};
});
}
async setAccountOptions(user,input,{revalidate=async()=>user}={}){
const keys=['accountId','balanceGuard','expectedBalanceGuard','termsVersion','accepted','requestId'];
if(!input||Object.keys(input).some(k=>!keys.includes(k))||typeof input.balanceGuard!=='boolean'||typeof input.expectedBalanceGuard!=='boolean'||input.accepted!==true||input.termsVersion!==BANK_VERSION||!/^\d{1,12}$/.test(input.accountId||'')||typeof input.accountId!=='string'||! /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(input.requestId||''))throw new BankError('Confirm the account option and its monthly price.');
const context=await this.authority(user),account=await this.db.first('SELECT a.id,c.entity_id FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number WHERE a.id=?',[input.accountId]);
const entity=account&&context.entities.find(e=>e.id===account.entity_id&&e.canPay);
if(!entity)throw new BankError('You are not authorised to change this account.',403);
const fingerprint=createHash('sha256').update(JSON.stringify([user.id,input.accountId,input.balanceGuard,input.expectedBalanceGuard,BANK_VERSION,...(this.staffAudit?[this.staffAudit]:[])])).digest('hex');
return this.db.transaction(async tx=>{
await tx.first('SELECT id FROM pb_entities WHERE id=? FOR UPDATE',[entity.id]);
const replay=await tx.first('SELECT actor_id,action,details FROM pb_audit WHERE id=?',[input.requestId]);
if(replay){let stored;try{stored=JSON.parse(replay.details);}catch{}if(replay.actor_id!==user.id||replay.action!=='account_options_changed'||stored?.fingerprint!==fingerprint)throw new BankError('This request number was already used for a different operation.',409);return {ok:true,replayed:true,state:'configured_pending_billing'};}
const current=await tx.first('SELECT a.id,a.type_code,a.system_key,c.entity_id FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number WHERE a.id=? FOR UPDATE',[input.accountId]);
if(!current||current.entity_id!==entity.id)throw new BankError('The account authority changed. Reload and try again.',409);
if(['979','106'].includes(current.type_code)||current.system_key)throw new BankError('Balance Guard does not apply to official or blocked collateral accounts.',400);
const previous=await tx.first('SELECT balance_guard FROM pb_account_options WHERE account_id=?',[input.accountId]);
if(Boolean(previous?.balance_guard)!==input.expectedBalanceGuard)throw new BankError('The account option changed. Reload before confirming.',409);
const fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed. Reload before confirming.',409);
const latest=await this.authority(fresh,{bank:tx});if(!latest.entities.some(e=>e.id===entity.id&&e.canPay))throw new BankError('Your account authority expired.',409);
const now=this.clock(),fee=input.balanceGuard?100:0;
await tx.query('INSERT INTO pb_account_options(account_id,balance_guard,monthly_minor,accepted_by,terms_version,updated_at) VALUES(?,?,?,?,?,?) ON DUPLICATE KEY UPDATE balance_guard=VALUES(balance_guard),monthly_minor=VALUES(monthly_minor),accepted_by=VALUES(accepted_by),terms_version=VALUES(terms_version),updated_at=VALUES(updated_at)',[current.id,input.balanceGuard?1:0,fee,user.id,BANK_VERSION,now]);
await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[input.requestId,user.id,'account_options_changed',entity.id,JSON.stringify({accountId:input.accountId,balanceGuard:input.balanceGuard,monthlyMinor:fee,fingerprint,state:'configured_pending_billing',...(this.staffAudit?{reason:this.staffAudit.reason,performedBy:'bank_staff'}:{})}),now]);
return {ok:true,replayed:false,state:'configured_pending_billing',monthly:money(fee)};
});
}
}