forked from unimatrix/web
Post audited service compensation through a shared rolling reserve
This commit is contained in:
parent
46685c5da0
commit
421b3a6ec0
6 changed files with 233 additions and 14 deletions
|
|
@ -5,7 +5,7 @@ import {BankError} from './postbank-service.mjs';
|
|||
import {money,minorAmount,validBankNumber} from './postbank-catalogue.mjs';
|
||||
const taxRecipientSQL='SELECT a.*,e.id entity_id,e.active entity_active,e.display_name holder,p.state package_state FROM pb_accounts a LEFT JOIN pb_clients c ON c.client_number=a.client_number LEFT JOIN pb_entities e ON e.id=c.entity_id LEFT JOIN pb_packages p ON p.id=a.package_id';
|
||||
const canReceiveTax=a=>a&&a.state==='active'&&a.type_code!=='106'&&a.system_key!=='sys_tax_treasury'&&(a.system_key?['sys_web_treasury','sys_game_treasury','sys_bank_capital_issuer'].includes(a.system_key):Number(a.entity_active)===1&&a.package_state==='active');
|
||||
const treasuryKeys=['sys_web_treasury','sys_game_treasury','sys_tax_treasury'];
|
||||
const treasuryKeys=['sys_web_treasury','sys_game_treasury','sys_tax_treasury','sys_service_compensation'];
|
||||
// The issuance mandate belongs to this central account, never to a rank or display name.
|
||||
export const RESERVE_OWNER_ID='f3ffda37-01e4-41ea-b89d-fbeda82e453e';
|
||||
const uuid=s=>typeof s==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(s);
|
||||
|
|
@ -66,7 +66,7 @@ export class PostbankAdmin{
|
|||
});
|
||||
}
|
||||
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,canIssueReserve:user.id===RESERVE_OWNER_ID&&!!c.manageAdmin}};}
|
||||
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,canCompensate:!!(c.manageAdmin||c.manageClients),canIssueReserve:user.id===RESERVE_OWNER_ID&&!!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=['1=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,e.active,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:Number(r.active)===0?'paused':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};
|
||||
|
|
@ -94,7 +94,7 @@ export class PostbankAdmin{
|
|||
});
|
||||
}
|
||||
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:r.actor_id===REGISTRY_ACTOR?'Bank registry synchroniser':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};
|
||||
const visible=['packageKey','from','to','packageId','requestId','paymentId','accountId','balanceGuard','monthlyMinor','state','reason','batch','perAccountDM','totalDM','resetRequiredOnFinalDeployment','performedBy','originalPaymentId','funding','amountDM'];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:r.actor_id===REGISTRY_ACTOR?'Bank registry synchroniser':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:r.actor_id===REGISTRY_ACTOR?'Bank registry synchroniser':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};}
|
||||
// Staff-only attribution comes from the stored authoriser, never the account label.
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
import {randomUUID} from 'node:crypto';
|
||||
import {PostbankClientManagement} from './postbank-client-management.mjs';
|
||||
import {PostbankCompensation} from './postbank-compensation.mjs';
|
||||
import {PostbankStandingInstructions} from './postbank-standing-instructions.mjs';
|
||||
import {CentralScheduler} from './central-scheduler.mjs';
|
||||
import {canRunScheduler} from './scheduler-authority.mjs';
|
||||
import {createPostbankTasks} from './postbank-payments.mjs';
|
||||
|
|
@ -28,6 +30,7 @@ export function createPostbankApi(central,bank,settings={},deps={}){
|
|||
const transferSecurity=bank?new PostbankTransferSecurity(bank,central,deps):null;
|
||||
const admin=bank?new PostbankAdmin(bank,central,authority,deps):null;
|
||||
const clients=bank?new PostbankClientManagement(bank,authority,deps):null;
|
||||
const compensation=bank?new PostbankCompensation(bank,authority,deps):null,standing=bank?new PostbankStandingInstructions(bank,authority,deps):null;
|
||||
const beneficiaries=bank?new PostbankBeneficiaries(bank,deps):null;
|
||||
const statements=bank?new PostbankStatementArchive(bank,payments,{...deps,...statementSettings(settings)}):null;
|
||||
const reserveLedger=createReserveLedger(bank,deps);
|
||||
|
|
@ -135,6 +138,15 @@ export function createPostbankApi(central,bank,settings={},deps={}){
|
|||
}
|
||||
if(path.startsWith('/api/bank/admin/')){
|
||||
try{
|
||||
if(['/api/bank/admin/compensation','/api/bank/admin/compensation/pay','/api/bank/admin/standing-instructions'].includes(path)){
|
||||
if(url.search)return reply({message:'No account overrides are accepted.'},400);
|
||||
if(request.method==='GET'&&!path.endsWith('/pay')){const result=path.endsWith('/compensation')?await compensation.overview(user):await standing.overview(user),fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403);await (path.endsWith('/compensation')?compensation.access(fresh):standing.access(fresh));return reply(result);}
|
||||
if(request.method!=='POST'||path.endsWith('/compensation'))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 raw=await request.text();if(raw.length>2500)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the bank instruction.'},400);}
|
||||
return reply(await (path.endsWith('/pay')?compensation.pay(user,input,{revalidate:()=>auth(request)}):standing.save(user,input,{revalidate:()=>auth(request)})));
|
||||
}
|
||||
if(['/api/bank/admin/client','/api/bank/admin/client/package','/api/bank/admin/client/options'].includes(path)){
|
||||
if(path.endsWith('/client')){
|
||||
if(request.method!=='GET')return reply({message:'Method not allowed.'},405);
|
||||
|
|
@ -173,7 +185,7 @@ export function createPostbankApi(central,bank,settings={},deps={}){
|
|||
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){try{result.permissions.canRunScheduler=await canRunScheduler(central,fresh);}catch{result.permissions.canRunScheduler=false;}result.permissions.canManage=rights.manageAdmin;result.permissions.canIssueReserve=fresh.id===RESERVE_OWNER_ID&&!!rights.manageAdmin;}if('canManage' in result)result.canManage=rights.manageAdmin;
|
||||
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){try{result.permissions.canRunScheduler=await canRunScheduler(central,fresh);}catch{result.permissions.canRunScheduler=false;}result.permissions.canManage=rights.manageAdmin;result.permissions.canCompensate=!!(rights.manageAdmin||rights.manageClients);result.permissions.canIssueReserve=fresh.id===RESERVE_OWNER_ID&&!!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);}
|
||||
}
|
||||
|
|
|
|||
42
website/node/postbank-compensation.mjs
Normal file
42
website/node/postbank-compensation.mjs
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
import {randomUUID,createHash} from 'node:crypto';
|
||||
import {BankError} from './postbank-service.mjs';import {PostbankPayments} from './postbank-payments.mjs';
|
||||
import {money,minorAmount} from './postbank-catalogue.mjs';
|
||||
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
|
||||
export const COMPENSATION_RESERVE='sys_service_compensation';
|
||||
const eligible=a=>a&&!a.system_key&&a.state==='active'&&a.type_code!=='106'&&Number(a.entity_active)===1&&a.package_state==='active';
|
||||
const accountsSQL='SELECT a.*,c.entity_id,e.kind entity_kind,e.active entity_active,p.state package_state FROM pb_accounts a LEFT JOIN pb_clients c ON c.client_number=a.client_number LEFT JOIN pb_entities e ON e.id=c.entity_id LEFT JOIN pb_packages p ON p.id=a.package_id';
|
||||
export class PostbankCompensation{
|
||||
constructor(db,authority,{clock=Date.now}={}){this.db=db;this.authority=authority;this.clock=clock;}
|
||||
async access(user,store=this.db){const c=await this.authority(user,{bank:store});if(!c.readAdmin||!c.manageAdmin&&!c.manageClients)throw new BankError('Bank client management permission is required.',403);return c;}
|
||||
async overview(user){await this.access(user);const row=await this.db.first('SELECT account_number,balance_minor,reserved_minor FROM pb_accounts WHERE system_key=?',[COMPENSATION_RESERVE]);return {reserve:row?{number:row.account_number,balance:money(row.balance_minor),available:money(BigInt(row.balance_minor)-BigInt(row.reserved_minor))}:null};}
|
||||
async pay(user,input,{revalidate=async()=>user}={}){
|
||||
await this.access(user);
|
||||
if(!input||Object.keys(input).some(k=>!['requestId','paymentId','amount','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>100||/[\u0000-\u001f]/.test(input.reason))throw new BankError('Confirm the original payment, compensation amount and a reason of 5–100 characters.');
|
||||
let amount;try{amount=minorAmount(input.amount);}catch(e){throw new BankError(e.message);}
|
||||
const reason=input.reason.trim(),fingerprint=createHash('sha256').update(JSON.stringify([user.id,input.paymentId,String(amount),reason,'service'])).digest('hex');
|
||||
return this.db.transaction(async tx=>{
|
||||
const meta=await tx.first('SELECT source_id,target_id FROM pb_orders WHERE id=?',[input.paymentId]);if(!meta)throw new BankError('Original payment not found.',404);
|
||||
const entities=await tx.query('SELECT 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',[meta.source_id,meta.target_id]);
|
||||
for(const id of [...new Set(entities.map(e=>e.entity_id))].sort())await tx.first('SELECT id FROM pb_entities WHERE id=? FOR UPDATE',[id]);
|
||||
const original=await tx.first('SELECT * FROM pb_orders WHERE id=? FOR UPDATE',[input.paymentId]);
|
||||
const rows=await tx.query(accountsSQL+' WHERE a.id IN (?,?) OR a.system_key=? ORDER BY a.id FOR UPDATE',[original.source_id,original.target_id,COMPENSATION_RESERVE]);
|
||||
const beneficiary=rows.find(a=>String(a.id)===String(original.source_id)),recovery=rows.find(a=>String(a.id)===String(original.target_id)),reserve=rows.find(a=>a.system_key===COMPENSATION_RESERVE);
|
||||
const fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed.',403);const rights=await this.access(fresh,tx);
|
||||
const prior=await tx.first('SELECT * FROM pb_orders WHERE id=? FOR UPDATE',[input.requestId]);if(prior){if(prior.actor_id!==user.id||prior.fingerprint!==fingerprint)throw new BankError('This request reference was already used.',409);return {ok:true,replayed:true,paymentId:prior.id,state:prior.state};}
|
||||
if(original.state!=='posted'||!['standard','instant'].includes(original.mode)||String(original.source_id)===String(original.target_id)||!eligible(beneficiary)||!eligible(recovery))throw new BankError('Select a posted customer transfer between available accounts.',409);
|
||||
if(!rights.manageAdmin&&[beneficiary,recovery].some(a=>['house','office','staff'].includes(a.entity_kind)))throw new BankError('Official account compensation requires bank management.',403);
|
||||
// Locking reads must bypass an older MySQL REPEATABLE READ snapshot when
|
||||
// another correction committed while this transaction waited on the payer.
|
||||
const corrections=await tx.query('SELECT amount_minor FROM pb_service_compensations WHERE original_order_id=? FOR UPDATE',[original.id]),used=corrections.reduce((n,row)=>n+BigInt(row.amount_minor),0n);
|
||||
if(amount>BigInt(original.amount_minor)-used)throw new BankError('Compensation exceeds the uncompensated amount of this payment.',409);
|
||||
const recoverable=BigInt(recovery.balance_minor)-BigInt(recovery.reserved_minor)>=amount;
|
||||
const source=recoverable?recovery:reserve,funding=recoverable?'recovery':'reserve';
|
||||
if(!source||source.state!=='active'||BigInt(source.balance_minor)-BigInt(source.reserved_minor)<amount)throw new BankError('The shared compensation reserve has insufficient available funds. Bank management can top it up.',409);
|
||||
const now=this.clock();await tx.query('INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,?,?,?)',[input.requestId,user.id,source.id,beneficiary.id,fingerprint,String(amount),'Service compensation — '+reason,'service','queued',now]);
|
||||
await new PostbankPayments(this.db,this.authority,{clock:this.clock}).post(tx,{id:input.requestId,actor_id:user.id,amount_minor:String(amount)},{...source,entity_id:source.entity_id||null},beneficiary,false);
|
||||
await tx.query('INSERT INTO pb_service_compensations(request_id,original_order_id,amount_minor,funding,reason,created_at) VALUES(?,?,?,?,?,?)',[input.requestId,original.id,String(amount),funding,reason,now]);
|
||||
await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),user.id,'service_compensation',beneficiary.entity_id,JSON.stringify({paymentId:input.requestId,originalPaymentId:original.id,reason,funding,amountDM:money(amount)}),now]);
|
||||
return {ok:true,replayed:false,paymentId:input.requestId,state:'posted',funding};
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
import {CentralScheduler} from './central-scheduler.mjs';
|
||||
import {PostbankStandingInstructions} from './postbank-standing-instructions.mjs';
|
||||
import {PostbankCreditSupport} from './postbank-credit-support.mjs';
|
||||
import {PostbankTransferSecurity} from './postbank-transfer-security.mjs';
|
||||
import {PostbankCreditEngine} from './postbank-credit-engine.mjs';
|
||||
|
|
@ -155,6 +156,7 @@ export function createPostbankTasks(central,bank,settings,deps={}){
|
|||
return {failed:failed+(morePayments||moreCredit?1:0)};
|
||||
}},
|
||||
{key:'credit_support',slot:now=>Math.floor(now/60000)*60000,run:()=>support.process()},
|
||||
{key:'standing_instructions',slot:now=>Math.floor(now/60000)*60000,run:()=>new PostbankStandingInstructions(bank,deps.authority||createPostbankAuthority(central,{bank}),deps).process()},
|
||||
{key:'statement_index',slot:now=>Math.floor(now/3600000)*3600000,run:()=>archives.seed()},
|
||||
{key:'statement_archives',slot:now=>Math.floor(now/60000)*60000,run:()=>archives.process()}
|
||||
];
|
||||
|
|
|
|||
|
|
@ -177,3 +177,15 @@ CREATE TABLE IF NOT EXISTS pb_scheduler_tasks (
|
|||
succeeded_at BIGINT NOT NULL DEFAULT 0, lease_token CHAR(36) NOT NULL DEFAULT '',
|
||||
lease_until BIGINT NOT NULL DEFAULT 0, last_error VARCHAR(200) NOT NULL DEFAULT ''
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS pb_service_compensations (
|
||||
request_id CHAR(36) PRIMARY KEY, original_order_id CHAR(36) NOT NULL,
|
||||
amount_minor BIGINT NOT NULL, funding VARCHAR(16) NOT NULL,
|
||||
reason VARCHAR(200) NOT NULL, created_at BIGINT NOT NULL,
|
||||
FOREIGN KEY(request_id) REFERENCES pb_orders(id), FOREIGN KEY(original_order_id) REFERENCES pb_orders(id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS pb_standing_instructions (
|
||||
instruction_key VARCHAR(64) PRIMARY KEY, source_key VARCHAR(40) NOT NULL,
|
||||
target_key VARCHAR(40) NOT NULL, amount_minor BIGINT NOT NULL,
|
||||
enabled INT NOT NULL DEFAULT 0, version INT NOT NULL DEFAULT 1,
|
||||
updated_by CHAR(36) NOT NULL, updated_at BIGINT NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
|
|
|||
47
website/node/postbank-standing-instructions.mjs
Normal file
47
website/node/postbank-standing-instructions.mjs
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
import {createHash,randomUUID} from 'node:crypto';import {BankError} from './postbank-service.mjs';import {PostbankPayments} from './postbank-payments.mjs';import {REGISTRY_ACTOR} from './postbank-registry.mjs';import {minorAmount,money,bankNumber} from './postbank-catalogue.mjs';
|
||||
export const COMPENSATION_INSTRUCTION='monthly_service_compensation';
|
||||
const reserve='sys_service_compensation',treasury='sys_web_treasury';
|
||||
const calendar=new Intl.DateTimeFormat('en-CA',{timeZone:'Europe/Brussels',year:'numeric',month:'2-digit'});
|
||||
export const instructionPeriod=now=>{const parts=Object.fromEntries(calendar.formatToParts(new Date(now)).map(p=>[p.type,p.value]));return parts.year+'-'+parts.month;};
|
||||
function orderId(key){const h=createHash('sha256').update(key).digest('hex');return h.slice(0,8)+'-'+h.slice(8,12)+'-5'+h.slice(13,16)+'-a'+h.slice(17,20)+'-'+h.slice(20,32);}
|
||||
export class PostbankStandingInstructions{
|
||||
constructor(db,authority,{clock=Date.now}={}){this.db=db;this.authority=authority;this.clock=clock;}
|
||||
async access(user,store=this.db){const rights=await this.authority(user,{bank:store});if(!rights.readAdmin||!rights.manageAdmin)throw new BankError('Bank management permission is required.',403);}
|
||||
async overview(user){await this.access(user);const row=await this.db.first('SELECT * FROM pb_standing_instructions WHERE instruction_key=?',[COMPENSATION_INSTRUCTION]);return {instruction:row?{key:row.instruction_key,amount:money(row.amount_minor),enabled:!!Number(row.enabled),version:Number(row.version),source:'Website bank treasury',target:'Service compensation reserve',frequency:'Monthly · unspent funds carry forward'}:null};}
|
||||
async save(user,input,{revalidate=async()=>user}={}){
|
||||
await this.access(user);if(!input||Object.keys(input).some(k=>!['requestId','amount','enabled','version','reason','confirmed'].includes(k))||! /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(input.requestId||'')||typeof input.enabled!=='boolean'||!Number.isSafeInteger(input.version)||input.version<1||input.confirmed!==true||typeof input.reason!=='string'||input.reason.trim().length<5||input.reason.trim().length>140||/[\u0000-\u001f]/.test(input.reason))throw new BankError('Confirm the monthly funding amount, current instruction version and reason.');
|
||||
let amount;try{amount=minorAmount(input.amount);}catch(e){throw new BankError(e.message);}const fingerprint=JSON.stringify([user.id,String(amount),input.enabled,input.version,input.reason.trim()]);
|
||||
return this.db.transaction(async tx=>{
|
||||
const current=await tx.first('SELECT * FROM pb_standing_instructions WHERE instruction_key=? FOR UPDATE',[COMPENSATION_INSTRUCTION]);
|
||||
const fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed.',403);await this.access(fresh,tx);
|
||||
const prior=await tx.first('SELECT actor_id,action,details FROM pb_audit WHERE id=? FOR UPDATE',[input.requestId]);if(prior){if(prior.actor_id!==user.id||prior.action!=='standing_instruction_changed'||JSON.parse(prior.details).fingerprint!==fingerprint)throw new BankError('Request reference already used.',409);return {ok:true,replayed:true};}
|
||||
if(!current||Number(current.version)!==input.version)throw new BankError('The instruction changed. Reload before editing.',409);
|
||||
await tx.query('UPDATE pb_standing_instructions SET amount_minor=?,enabled=?,version=version+1,updated_by=?,updated_at=? WHERE instruction_key=?',[String(amount),input.enabled?1:0,user.id,this.clock(),COMPENSATION_INSTRUCTION]);
|
||||
await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,NULL,?,?)',[input.requestId,user.id,'standing_instruction_changed',JSON.stringify({fingerprint,amountDM:money(amount),enabled:input.enabled,reason:input.reason.trim()}),this.clock()]);return {ok:true,replayed:false};
|
||||
});
|
||||
}
|
||||
async process(){const period=instructionPeriod(this.clock());
|
||||
try{return await this.db.transaction(async tx=>{
|
||||
const instruction=await tx.first('SELECT * FROM pb_standing_instructions WHERE instruction_key=? FOR UPDATE',[COMPENSATION_INSTRUCTION]);if(!instruction||!Number(instruction.enabled))return {funded:0,failed:0};
|
||||
if(instruction.source_key!==treasury||instruction.target_key!==reserve||BigInt(instruction.amount_minor)<=0n)throw Error('Invalid service funding mandate');
|
||||
const id=orderId('standing:'+COMPENSATION_INSTRUCTION+':'+period),previous=await tx.first('SELECT state FROM pb_orders WHERE id=? FOR UPDATE',[id]);if(previous){if(previous.state!=='posted')throw Error('Funding requires reconciliation');return {funded:0,failed:0};}
|
||||
const accounts=await tx.query('SELECT * FROM pb_accounts WHERE system_key IN (?,?) ORDER BY id FOR UPDATE',[treasury,reserve]),source=accounts.find(a=>a.system_key===treasury),target=accounts.find(a=>a.system_key===reserve),amount=BigInt(instruction.amount_minor);
|
||||
if(!source||!target||source.state!=='active'||target.state!=='active'||BigInt(source.balance_minor)-BigInt(source.reserved_minor)<amount)throw Error('Insufficient service funding');
|
||||
const fingerprint=createHash('sha256').update(JSON.stringify([COMPENSATION_INSTRUCTION,period,String(amount),instruction.version])).digest('hex');
|
||||
await tx.query('INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,?,?,?)',[id,REGISTRY_ACTOR,source.id,target.id,fingerprint,String(amount),'Monthly service compensation funding · '+period,'standing','queued',this.clock()]);
|
||||
await new PostbankPayments(this.db,this.authority,{clock:this.clock}).post(tx,{id,actor_id:REGISTRY_ACTOR,amount_minor:String(amount)},{...source,entity_id:null},target,false);
|
||||
return {funded:1,failed:0};
|
||||
});}catch{return {funded:0,failed:1};}
|
||||
}
|
||||
}
|
||||
export async function setupCompensationReserve(db,{actorId,apply=false,clock=Date.now}={}){
|
||||
if(!actorId)throw Error('Deployment actor required');
|
||||
if(!apply)return {plan:true,monthlyDM:'25000.00',reserve:'Service compensation reserve'};
|
||||
return db.transaction(async tx=>{
|
||||
const now=clock();await tx.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,reserved_minor,state,created_at) VALUES(?,'979','Service compensation reserve',0,0,'active',?) ON DUPLICATE KEY UPDATE system_key=VALUES(system_key)",[reserve,now]);
|
||||
const account=await tx.first('SELECT id,account_number FROM pb_accounts WHERE system_key=? FOR UPDATE',[reserve]);if(!account.account_number)await tx.query('UPDATE pb_accounts SET account_number=? WHERE id=?',[bankNumber('979',Number(account.id)),account.id]);
|
||||
const existing=await tx.first('SELECT instruction_key FROM pb_standing_instructions WHERE instruction_key=? FOR UPDATE',[COMPENSATION_INSTRUCTION]);
|
||||
if(!existing){await tx.query('INSERT INTO pb_standing_instructions(instruction_key,source_key,target_key,amount_minor,enabled,version,updated_by,updated_at) VALUES(?,?,?,2500000,1,1,?,?)',[COMPENSATION_INSTRUCTION,treasury,reserve,actorId,now]);await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,NULL,?,?)',[randomUUID(),actorId,'service_reserve_configured',JSON.stringify({accountId:String(account.id),monthlyDM:'25000.00',reason:'Owner approved shared compensation reserve with monthly standing funding and rollover'}),now]);}
|
||||
return {applied:true,created:!existing,accountId:String(account.id)};
|
||||
});
|
||||
}
|
||||
Loading…
Reference in a new issue

Staff