web/website/node/project-banking.mjs
2026-11-27 23:43:05 +00:00

74 lines
7.8 KiB
JavaScript

import {createHash,randomUUID} from 'node:crypto';
import {PostbankService} from './postbank-service.mjs';
import {PostbankAdmin} from './postbank-admin.mjs';
import {PostbankPayments} from './postbank-payments.mjs';
import {BANK_VERSION,money} from './postbank-catalogue.mjs';
export const PROJECT_BANK_SCHEMA=`CREATE TABLE IF NOT EXISTS jarvis_project_banking(project_id CHAR(36) PRIMARY KEY,entity_id CHAR(36) NOT NULL UNIQUE,account_id BIGINT UNSIGNED NOT NULL UNIQUE,applicant_id CHAR(36) NOT NULL,request_id CHAR(36) NOT NULL UNIQUE,fingerprint CHAR(64) NOT NULL,state VARCHAR(16) NOT NULL,funded_at BIGINT NOT NULL,closed_at BIGINT NULL)`;
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
const hash=v=>createHash('sha256').update(JSON.stringify(v)).digest('hex');
const entityId=id=>{const h=hash(['server-project',id]);return h.slice(0,8)+'-'+h.slice(8,12)+'-5'+h.slice(13,16)+'-8'+h.slice(17,20)+'-'+h.slice(20,32);};
const boundStore=tx=>({query:tx.query.bind(tx),first:tx.first.bind(tx),transaction:fn=>fn(tx)});
// Private adapter for a confirmed J.A.R.V.I.S. project decision. It never grants
// support staff general Tax access or exposes a free-form payment endpoint.
export function createProjectBanking(bank,{authorize,clock=Date.now}){
if(typeof authorize!=='function')throw TypeError('Project decision authority required');
return Object.freeze({
async exhausted(){return bank.query("SELECT p.project_id FROM jarvis_project_banking p JOIN pb_accounts a ON a.id=p.account_id WHERE p.state='funded' AND a.state='active' AND a.balance_minor=0 AND a.reserved_minor=0 AND NOT EXISTS(SELECT 1 FROM pb_orders o WHERE (o.source_id=a.id OR o.target_id=a.id) AND o.state IN ('queued','pending')) ORDER BY p.funded_at,p.project_id LIMIT 20");},
async fund(actor,input){
const {projectId,applicantId,requestId,title,amountMinor}=input||{};
if(!input||Object.keys(input).some(k=>!['projectId','applicantId','requestId','title','amountMinor'].includes(k))||!uuid(actor?.id)||!uuid(projectId)||!uuid(applicantId)||!uuid(requestId)||typeof title!=='string'||!title.trim()||title.length>100||!Number.isSafeInteger(amountMinor)||amountMinor<1||amountMinor>1000000000000)throw TypeError('Invalid approved project funding');
const fingerprint=hash([actor.id,projectId,applicantId,title,amountMinor,requestId]),entity=entityId(projectId);
return bank.transaction(async tx=>{
if(!await authorize(actor,{action:'fund',...input},tx))throw Error('Approved project decision required');
// The entity lock also serialises competing first-funding attempts.
await tx.query("INSERT INTO pb_entities(id,kind,external_key,display_name,active,created_at) VALUES(?,'staff',?,?,1,?) ON DUPLICATE KEY UPDATE id=VALUES(id)",[entity,'project:'+projectId,title,clock()]);
await tx.first('SELECT id FROM pb_entities WHERE id=? FOR UPDATE',[entity]);
const previous=await tx.first('SELECT * FROM jarvis_project_banking WHERE project_id=?',[projectId]);
if(previous){if(previous.fingerprint!==fingerprint)throw Error('Project funding reference conflict');return{accountId:String(previous.account_id),state:previous.state,replayed:true};}
const scope={id:entity,kind:'staff',key:'project:'+projectId,name:title,canView:true,canPay:true,canActivate:true};
const authority=async user=>{
if(user?.id!==actor.id||!await authorize(user,{action:'fund',...input},tx))throw Error('Project funding authority changed');
return {entities:[scope],readAdmin:true,manageAdmin:true};
};
const store=boundStore(tx);
await new PostbankService(store,authority,{clock}).activate(actor,{entityId:entity,packageKey:'pb_public',termsVersion:BANK_VERSION,accepted:true,requestId});
const account=await tx.first("SELECT a.* FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number WHERE c.entity_id=? AND a.type_code='979' AND a.state='active' FOR UPDATE",[entity]);
if(!account)throw Error('Project bank account unavailable');
// Reuse the existing Tax payment and double-entry posting transaction.
await new PostbankAdmin(store,null,authority,{clock}).taxPayment(actor,{requestId,targetNumber:account.account_number,amount:money(amountMinor),reference:'Server project '+projectId,confirmed:true});
await tx.query("INSERT INTO pb_account_authorisations(id,account_id,grantee_kind,grantee_key,can_view,can_pay,starts_at,expires_at,state,created_by,created_at,updated_at,source_request) VALUES(?,?,'user',?,1,1,?,NULL,'active',?,?,?,?)",[randomUUID(),account.id,applicantId,clock(),actor.id,clock(),clock(),requestId]);
await tx.query("INSERT INTO jarvis_project_banking(project_id,entity_id,account_id,applicant_id,request_id,fingerprint,state,funded_at) VALUES(?,?,?,?,?,?,'funded',?)",[projectId,entity,account.id,applicantId,requestId,fingerprint,clock()]);
return {accountId:String(account.id),state:'funded',replayed:false};
});
},
async close(actor,{projectId,requestId,completed=false}){
if(!uuid(actor?.id)||!uuid(projectId)||!uuid(requestId)||typeof completed!=='boolean')throw TypeError('Invalid project closure');
return bank.transaction(async tx=>{
if(!await authorize(actor,{action:'close',projectId,requestId,completed},tx))throw Error('Project closure authority required');
const project=await tx.first('SELECT * FROM jarvis_project_banking WHERE project_id=? FOR UPDATE',[projectId]);
if(!project)return {closed:false,reason:'not-funded'};
if(project.state==='closed')return{closed:true,replayed:true};
const account=await tx.first('SELECT * FROM pb_accounts WHERE id=? FOR UPDATE',[project.account_id]);
if(!account||account.state!=='active'||account.type_code!=='979'||account.system_key||BigInt(account.balance_minor)<0n)throw Error('Project account requires reconciliation');
const pending=await tx.first("SELECT COUNT(*) total FROM pb_orders WHERE (source_id=? OR target_id=?) AND state IN ('queued','pending')",[account.id,account.id]);
const credit=await tx.first("SELECT COUNT(*) total FROM pb_credit_loans WHERE account_id=? AND state IN ('approved_pending','payout_queued','active','arrears')",[account.id]);
if(BigInt(account.reserved_minor)!==0n||Number(pending.total)||Number(credit.total))return{closed:false,reason:'pending-settlement'};
if(!completed&&BigInt(account.balance_minor)!==0n)return{closed:false,reason:'funds-remaining'};
if(BigInt(account.balance_minor)>0n){
const tax=await tx.first("SELECT * FROM pb_accounts WHERE system_key='sys_tax_treasury' FOR UPDATE");
if(tax?.state!=='active')throw Error('Tax treasury unavailable for project completion');
await tx.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'tax','queued',?)",[requestId,actor.id,account.id,tax.id,hash(['project-return',projectId,requestId]),String(account.balance_minor),'Unspent server project funding',clock()]);
await new PostbankPayments(boundStore(tx),async()=>({}),{clock}).post(tx,{id:requestId,actor_id:actor.id,amount_minor:String(account.balance_minor)},{...account,entity_id:project.entity_id},tax,false);
}
await tx.query("UPDATE pb_account_authorisations SET state='revoked',version=version+1,updated_at=? WHERE account_id=? AND state='active'",[clock(),account.id]);
await tx.query("UPDATE pb_accounts SET state='closed' WHERE id=?",[account.id]);
await tx.query("UPDATE pb_entities SET active=0 WHERE id=?",[project.entity_id]);
await tx.query("UPDATE jarvis_project_banking SET state='closed',closed_at=? WHERE project_id=?",[clock(),projectId]);
await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),actor.id,'project_account_closed',project.entity_id,JSON.stringify({projectId,requestId,completed}),clock()]);
return {closed:true,replayed:false};
});
}
});
}