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
7 changed files with 63 additions and 5 deletions

View file

@ -71,3 +71,6 @@ POST /api/bank/packages/change accepts entityId, packageId, expectedPackageKey,
Upgrading opens an included missing account at zero or reactivates its dormant record. Downgrades reject funded/reserved excluded products and excess current accounts; empty excluded savings/securities records become dormant rather than being deleted. Securities stays a planned service. New prices are disclosed and stored, but automated monthly billing remains planned. No money is debited by package switching. Payroll, game banking and securities trading remain outside scope.
Validation: 16 focused checks passed, covering stable numbers/balances, replay, dormant-account reuse, funded/reserved downgrade rejection, stale concurrent requests, foreign package access, revoked authority, audit-failure rollback, origin and current-consent checks. Worker build passed. Full CI and exact production promotion are still required before claiming live.
### Balance Guard preference — approved follow-up
Owner approved 1 DM per month per enabled eligible account. It applies to non-official accounts subject to the below-zero/client-lockdown policy; official 979 and system accounts are excluded. This batch stores the opt-in via POST /api/bank/accounts/options, checks actual operator authority and current consent, rejects stale updates, and records an idempotent audit receipt. The UI explicitly labels protection and billing as not active yet. No charge or automatic blocking is executed in this preference-only batch. Future monthly processing must block the opted-in account before an otherwise negative debit and avoid the related client-wide lockdown; do not apply protection or fees retroactively.

View file

@ -52,6 +52,17 @@ export function mountPostbankFoundation(host,page,{fetcher=fetch}={}){
return form;
}
function accountOptions(entity,account){
const details=el('details',undefined,'pb-account-options');details.append(el('summary','+ Account options'));
const form=el('form'),guard=el('input');guard.type='checkbox';guard.checked=Boolean(account.options.balanceGuard);guard.disabled=!entity.canPay;
const label=el('label',undefined,'pb-consent');label.append(guard,el('span','Balance Guard · 1.00 DM / month when enabled'));
const confirm=el('input');confirm.type='checkbox';confirm.required=true;confirm.disabled=!entity.canPay;const consent=el('label',undefined,'pb-consent');consent.append(confirm,el('span','I confirm this account option and its monthly price.'));
const button=el('button','Save account option');button.type='submit';button.disabled=!entity.canPay;
form.append(label,el('p','Configured for future activation. Balance Guard will block this account before a debit takes it below zero, preventing the related client-wide lockdown. Protection and monthly billing are not active yet; no charge is taken now.','pb-muted'),consent,button);
form.onsubmit=async event=>{event.preventDefault();if(busy||!form.reportValidity())return;busy=true;button.disabled=true;guard.disabled=true;confirm.disabled=true;frame.status.hidden=false;frame.status.textContent='Saving your account option…';try{await api.request('/api/bank/accounts/options',{accountId:account.id,balanceGuard:guard.checked,expectedBalanceGuard:Boolean(account.options.balanceGuard),termsVersion:view.termsVersion,accepted:true,requestId:crypto.randomUUID()});notice='Balance Guard preference saved. Protection and monthly billing are not active yet.';}catch(error){notice=error.message;}finally{busy=false;await load();}};
details.append(form);return details;
}
function render(){
frame.content.replaceChildren();const entities=Array.isArray(view.entities)?view.entities:[];
if(!entities.length)frame.content.append(el('p','No personal or organisational banking entity is currently available for this account.'));
@ -71,7 +82,7 @@ export function mountPostbankFoundation(host,page,{fetcher=fetch}={}){
const card=el('article',undefined,'pb-account pb-account-'+a.type);card.append(el('strong',accountNames[a.type]||'Bank account'),el('code',number(a.number)));
if(['planned','dormant','closed'].includes(a.state))card.append(el('span',a.state==='planned'?'Planned service · Not available for payments':a.state==='dormant'?'Dormant · Preserved after package change':'Closed','pb-muted'));
else card.append(el('strong',a.balance+' DM','pb-balance'),el('small','Available: '+a.available+' DM'));
const detail=el('details'),summary=el('summary','+ Account details');detail.append(summary);datum(detail,'Account holder',entity.name);datum(detail,'Client number',entity.clientNumber);datum(detail,'Banking entity',entity.kind);datum(detail,'Access',entity.canPay?'Account operator':'Read only');if(entity.expiresAt)datum(detail,'Authority expires',new Date(entity.expiresAt).toLocaleString('en-GB'));datum(detail,'Account state',a.state);datum(detail,'Package',entity.packages.find(p=>p.id===a.packageId)?.name||'Not available');card.append(detail);rows.append(card);
const detail=el('details'),summary=el('summary','+ Account details');detail.append(summary);datum(detail,'Account holder',entity.name);datum(detail,'Client number',entity.clientNumber);datum(detail,'Banking entity',entity.kind);datum(detail,'Access',entity.canPay?'Account operator':'Read only');if(entity.expiresAt)datum(detail,'Authority expires',new Date(entity.expiresAt).toLocaleString('en-GB'));datum(detail,'Account state',a.state);datum(detail,'Package',entity.packages.find(p=>p.id===a.packageId)?.name||'Not available');card.append(detail);if(page==='personal-bank'&&a.options?.balanceGuardEligible)card.append(accountOptions(entity,a));rows.append(card);
}
section.append(rows);frame.content.append(section);
}

View file

@ -195,3 +195,5 @@
@media(prefers-reduced-motion:reduce){.pb-choice-card{transition:none}.pb-choice-card:hover{transform:none}}@media(max-width:650px){.pb-choice-card{padding:26px 20px}.pb-choice-card input[type=radio]{right:18px}.pb-package-brand h5{font-size:29px}}
.pb-package-brand>div{min-width:0}.pb-package-brand h5{overflow-wrap:anywhere}.pb-change-panel{margin:18px 0;padding:22px;border:1px solid #a9935c;border-radius:12px;background:#0e291fe8}.pb-change-comparison:empty{display:none}.pb-change-comparison{padding:14px 18px;border-left:3px solid #d8b767;background:#67562b22;border-radius:6px;font-size:13px;line-height:1.8}
.pb-account-options{border-top:1px solid #b7c59b22;padding-top:12px}.pb-account-options summary{cursor:pointer;color:#e3cc89}.pb-account-options form{display:grid;gap:16px;margin-top:16px}.pb-account-options p{margin:0;line-height:1.7}.pb-account-options button{justify-self:start}

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)};
});
}
}

View file

@ -51,3 +51,13 @@ test('failed change audit rolls back package and account state together',async()
test('package-change API requires same-origin confirmation and current terms',async()=>{
const db=new BankFixture();try{const service=new PostbankService(db,authority),opened=await service.activate(user,input('pb_start'));const api=createPostbankApi(null,db,{}, {authenticate:async()=>user,authority}),data=changeInput(opened.packageId,'pb_start','pb_flow');const request=(body,origin='https://cp.dunerealms.com')=>new Request('https://cp.dunerealms.com/api/bank/packages/change',{method:'POST',headers:{Origin:origin,'Content-Type':'application/json'},body:JSON.stringify(body)});assert.equal((await api(request(data,'https://other.invalid'))).status,403);assert.equal((await api(request({...data,accepted:false}))).status,400);assert.equal((await api(request({...data,termsVersion:'old'}))).status,400);assert.equal((await api(request(data))).status,200);assert.equal((await db.first('SELECT * FROM pb_packages')).package_key,'pb_flow');}finally{db.close();}
});
const optionInput=(accountId,extra={})=>({accountId:String(accountId),balanceGuard:true,expectedBalanceGuard:false,termsVersion:BANK_VERSION,accepted:true,requestId:'82345678-1234-4234-8234-123456789abc',...extra});
test('Balance Guard preferences are stored at 1 DM without charging; retries and stale settings are safe',async()=>{
const db=new BankFixture();try{const service=new PostbankService(db,authority);await service.activate(user,input());const a=await db.first('SELECT * FROM pb_accounts ORDER BY id');const data=optionInput(a.id);const result=await service.setAccountOptions(user,data);assert.equal(result.monthly,'1.00');assert.equal(result.state,'configured_pending_billing');assert.equal((await service.setAccountOptions(user,data)).replayed,true);assert.equal((await db.first('SELECT * FROM pb_accounts WHERE id=?',[a.id])).balance_minor,0);assert.equal((await db.first('SELECT * FROM pb_account_options')).monthly_minor,100);const snap=await service.overview(user);assert.equal(snap.entities[0].accounts[0].options.balanceGuard,true);await assert.rejects(service.setAccountOptions(user,{...data,requestId:'92345678-1234-4234-8234-123456789abc'}),e=>e.status===409);await service.setAccountOptions(user,{...data,requestId:'92345678-1234-4234-8234-123456789abc',expectedBalanceGuard:true,balanceGuard:false});assert.equal((await db.first('SELECT * FROM pb_account_options')).monthly_minor,0);}finally{db.close();}
});
test('Balance Guard applies to eligible entity accounts, excludes official 979 and checks operator authority',async()=>{
for(const [kind,key]of [['person','pb_start'],['clan','pb_connect'],['house','pb_civic'],['staff','pb_public']]){
const db=new BankFixture(),e={...entity,kind};try{let allowed=true;const auth=async()=>({entities:[{...e,canPay:allowed}],readAdmin:true,manageAdmin:true}),service=new PostbankService(db,auth);await service.activate(user,input(key));const a=await db.first('SELECT * FROM pb_accounts');if(kind==='staff'){await assert.rejects(service.setAccountOptions(user,optionInput(a.id)),error=>error.status===400);assert.equal((await service.overview(user)).entities[0].accounts[0].options.balanceGuardEligible,false);}else{await service.setAccountOptions(user,optionInput(a.id));assert.equal((await db.first('SELECT * FROM pb_account_options')).balance_guard,1);allowed=false;await assert.rejects(service.setAccountOptions(user,optionInput(a.id,{balanceGuard:false,expectedBalanceGuard:true,requestId:'92345678-1234-4234-8234-123456789abc'})),error=>error.status===403);} }finally{db.close();}
}
});