forked from unimatrix/web
Manage eligible Postbank packages without replacing accounts
This commit is contained in:
parent
c58f3f2ffe
commit
b833f7e138
3 changed files with 115 additions and 28 deletions
|
|
@ -15,13 +15,13 @@ export function createPostbankApi(central,bank,settings={},deps={}){
|
|||
try{return reply(await service.overview(user));}catch{return reply({message:'The bank could not confirm the current records. Reload the workspace.'},503);}
|
||||
}
|
||||
if(path==='/api/bank/contracts'&&request.method==='GET')return reply({contracts:POSTBANK_CONTRACTS});
|
||||
if(path==='/api/bank/activate'){
|
||||
if(['/api/bank/activate','/api/bank/packages/change'].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);
|
||||
const text=await request.text();if(text.length>3000)return reply({message:'Request too large.'},413);
|
||||
let body;try{body=JSON.parse(text);}catch{return reply({message:'Select your package again.'},400);}
|
||||
try{return reply(await service.activate(user,body,{revalidate:()=>auth(request)}));}catch(error){return reply({message:error.status?error.message:'Activation failed. Return to the package selection and try again.',returnTo:'package_selection'},error.status||503);}
|
||||
try{return reply(await (path==='/api/bank/activate'?service.activate(user,body,{revalidate:()=>auth(request)}):service.changePackage(user,body,{revalidate:()=>auth(request)})));}catch(error){return reply({message:error.status?error.message:'The package operation was not confirmed. Reload the current records before trying again.',returnTo:'package_selection'},error.status||503);}
|
||||
}
|
||||
return reply({message:'This bank function is not implemented yet. No request was forwarded to the old game bank.',state:'planned'},501);
|
||||
};
|
||||
|
|
|
|||
|
|
@ -58,3 +58,10 @@ CREATE TABLE IF NOT EXISTS pb_payroll_items (
|
|||
state VARCHAR(24) NOT NULL, created_at BIGINT NOT NULL,
|
||||
PRIMARY KEY(period,actor_id), FOREIGN KEY(period) REFERENCES pb_payroll_runs(period)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS pb_package_changes (
|
||||
request_id CHAR(36) PRIMARY KEY, actor_id CHAR(36) NOT NULL, entity_id CHAR(36) NOT NULL,
|
||||
package_id CHAR(36) NOT NULL, fingerprint CHAR(64) NOT NULL, from_key VARCHAR(32) NOT NULL,
|
||||
to_key VARCHAR(32) NOT NULL, created_at BIGINT NOT NULL,
|
||||
FOREIGN KEY(entity_id) REFERENCES pb_entities(id), FOREIGN KEY(package_id) REFERENCES pb_packages(id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import {randomUUID} from 'node:crypto';
|
||||
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');
|
||||
|
|
@ -52,4 +52,51 @@ export class PostbankService{
|
|||
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])).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)||(a.type_code==='106'&&!choice.securities);
|
||||
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']:[]),...(choice.securities?['106']:[])]){
|
||||
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);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}),now]);
|
||||
return {ok:true,replayed:false,packageId:current.id,packageKey:choice.key};
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff