import {createHash} from 'node:crypto'; import {canDebitAccount} from './postbank-authorisations.mjs'; import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs'; import {PostbankPayments,standardCycle} from './postbank-payments.mjs'; import {JarvisError} from './jarvis-listings.mjs'; export const JARVIS_CHARGE_SCHEMA=`CREATE TABLE IF NOT EXISTS pb_jarvis_charges(order_id CHAR(36) PRIMARY KEY,listing_id CHAR(36) NOT NULL UNIQUE,due_at BIGINT NOT NULL,FOREIGN KEY(order_id) REFERENCES pb_orders(id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`; const accountSQL='SELECT a.*,c.entity_id,e.kind,e.external_key,e.active AS entity_active,p.state AS 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'; // The caller owns the bank transaction, including the J.A.R.V.I.S. publication. // This product reserves now and uses the existing double-entry posting engine // at the ordinary four-hour bank window. The recipient is always Tax. export function createJarvisPayments(bank,authority,{clock=Date.now}={}){ const payments=new PostbankPayments(bank,authority,{clock}); return Object.freeze({ async reserve(tx,{actor,current,sourceAccount,amountMinor,requestId,listingId,title,purpose='Recruitment listing'}){ if(!/^[0-9]{1,12}$/.test(String(sourceAccount||''))||!Number.isSafeInteger(amountMinor)||amountMinor<=0||!current.payerEntityId)throw new JarvisError('Choose an authorised organisation payment account.'); const context=await authority(actor,{bank:tx}),sourceMeta=await tx.first(accountSQL+' WHERE a.id=?',[sourceAccount]); if(!sourceMeta||sourceMeta.entity_id!==current.payerEntityId||!canDebitAccount(context,sourceMeta.entity_id,sourceMeta.id))throw new JarvisError('Organisation payment authority required.',403); const taxMeta=await tx.first("SELECT id FROM pb_accounts WHERE system_key='sys_tax_treasury'");if(!taxMeta)throw new JarvisError('Tax treasury is unavailable.',503); const rows=await tx.query(accountSQL+' WHERE a.id IN (?,?) ORDER BY a.id FOR UPDATE',[sourceMeta.id,taxMeta.id]),source=rows.find(a=>String(a.id)===String(sourceMeta.id)),tax=rows.find(a=>String(a.id)===String(taxMeta.id)),amount=BigInt(amountMinor); if(!ordinaryPaymentAccount(source)||!tax||tax.state!=='active'||BigInt(source.balance_minor)-BigInt(source.reserved_minor)9223372036854775807n)throw new JarvisError('Insufficient available organisation funds or an account is unavailable.',409); const fingerprint=createHash('sha256').update(JSON.stringify(['jarvis-recruitment',actor.id,listingId,current.payerEntityId,String(source.id),String(tax.id),amountMinor])).digest('hex'),now=clock(); if(await tx.first('SELECT id FROM pb_orders WHERE id=?',[requestId]))throw new JarvisError('Payment reference already used.',409); await tx.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'jarvis','queued',?)",[requestId,actor.id,source.id,tax.id,fingerprint,amount.toString(),(purpose+' ยท '+title).slice(0,140),now]); await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor+? WHERE id=?',[amount.toString(),source.id]); await tx.query('INSERT INTO pb_jarvis_charges(order_id,listing_id,due_at) VALUES(?,?,?)',[requestId,listingId,standardCycle(now).nextAt]); }, async settle(cutoff){ const pending=await bank.query("SELECT c.order_id FROM pb_jarvis_charges c JOIN pb_orders o ON o.id=c.order_id WHERE c.due_at<=? AND o.mode='jarvis' AND o.state='queued' ORDER BY c.due_at,c.order_id LIMIT 100",[cutoff]);let posted=0,failed=0; for(const item of pending)try{const didPost=await bank.transaction(async tx=>{ const order=await tx.first('SELECT * FROM pb_orders WHERE id=? FOR UPDATE',[item.order_id]);if(!order||order.state!=='queued')return; const rows=await tx.query(accountSQL+' WHERE a.id IN (?,?) ORDER BY a.id FOR UPDATE',[order.source_id,order.target_id]),source=rows.find(a=>String(a.id)===String(order.source_id)),tax=rows.find(a=>String(a.id)===String(order.target_id)),amount=BigInt(order.amount_minor); if(!source||!tax||tax.system_key!=='sys_tax_treasury'||source.state!=='active'||tax.state!=='active'||BigInt(source.reserved_minor)9223372036854775807n)throw Error('Reserved product charge requires reconciliation'); await payments.post(tx,order,source,tax,true);return true; });if(didPost)posted++;}catch{failed++;} return {posted,failed,attempted:pending.length}; } }); }