Configure Balance Guard for eligible accounts; exclude official accounts

This commit is contained in:
unimatrixgit 2026-11-13 21:28:17 +01:00
commit b96a2b6c93
3 changed files with 63 additions and 5 deletions

View file

@ -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(['/api/bank/activate','/api/bank/packages/change'].includes(path)){
if(['/api/bank/activate','/api/bank/packages/change','/api/bank/accounts/options'].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 (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);}
try{return reply(await (path==='/api/bank/activate'?service.activate(user,body,{revalidate:()=>auth(request)}):path==='/api/bank/packages/change'?service.changePackage(user,body,{revalidate:()=>auth(request)}):service.setAccountOptions(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);
};

View file

@ -65,3 +65,10 @@ CREATE TABLE IF NOT EXISTS pb_package_changes (
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;
CREATE TABLE IF NOT EXISTS pb_account_options (
account_id BIGINT UNSIGNED PRIMARY KEY, balance_guard INT NOT NULL DEFAULT 0,
monthly_minor BIGINT NOT NULL DEFAULT 0, accepted_by CHAR(36) NOT NULL,
terms_version VARCHAR(64) NOT NULL, updated_at BIGINT NOT NULL,
FOREIGN KEY(account_id) REFERENCES pb_accounts(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

View file

@ -20,8 +20,8 @@ export class PostbankService{
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 id,account_number,type_code,display_name,balance_minor,reserved_minor,state,package_id FROM pb_accounts WHERE client_number=? ORDER BY 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.map(a=>({id:String(a.id),number:a.account_number,type:a.type_code,name:a.display_name,balance:money(a.balance_minor),available:money(BigInt(a.balance_minor)-BigInt(a.reserved_minor)),state:a.state,packageId:a.package_id}))});
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.map(a=>({id:String(a.id),number:a.account_number,type:a.type_code,name:a.display_name,balance:money(a.balance_minor),available:money(BigInt(a.balance_minor)-BigInt(a.reserved_minor)),state:a.state,packageId:a.package_id,options:{balanceGuardEligible:a.type_code!=='979'&&!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.'}};
}
@ -99,4 +99,29 @@ export class PostbankService{
});
}
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])).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(current.type_code==='979'||current.system_key)throw new BankError('Balance Guard does not apply to official 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);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'}),now]);
return {ok:true,replayed:false,state:'configured_pending_billing',monthly:money(fee)};
});
}
}