MC/website/node/deed-purchase-payments.mjs
2026-11-27 23:43:05 +00:00

30 lines
6 KiB
JavaScript

import {createHash,randomUUID} from 'node:crypto';
import {PostbankPayments} from './postbank-payments.mjs';
import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs';
import {canDebitAccount} from './postbank-authorisations.mjs';
import {entityId} from './postbank-authority.mjs';
import {JarvisError} from './jarvis-listings.mjs';
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
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';
// Product adapter only: the existing Postbank posting engine owns balances,
// double-entry records and audit. An escrow order is excluded from normal queue
// processing until the matching XFR has its verified central transfer receipt.
export function createDeedPurchasePayments(bank,authority,{verifyTransfer,canRelease,clock=Date.now}={}){
if(![authority,verifyTransfer,canRelease].every(f=>typeof f==='function'))throw TypeError('Verified deed payment adapters required');
const payments=new PostbankPayments(bank,authority,{clock});
const identity=input=>{if(!uuid(input.keyId)||!uuid(input.listingId)||!uuid(input.requestId)||!uuid(input.actorId)||!uuid(input.sellerId)||!uuid(input.parentId)||!['clan','company'].includes(input.parentKind)||!Number.isSafeInteger(input.priceMinor)||input.priceMinor<1||!/^\d{1,12}$/.test(input.sourceAccount)||!/^\d{1,12}$/.test(input.recipientAccount)||input.sourceAccount===input.recipientAccount)throw new JarvisError('Review the confirmed deed payment.');return createHash('sha256').update(JSON.stringify([input.keyId,input.listingId,input.actorId,input.sellerId,input.parentKind,input.parentId,input.sourceAccount,input.recipientAccount,input.priceMinor])).digest('hex');};
async function orderFor(tx,input){const fingerprint=identity(input),row=await tx.first('SELECT * FROM pb_orders WHERE id=? FOR UPDATE',[input.requestId]);if(row&&(row.mode!=='deed'||row.actor_id!==input.actorId||row.fingerprint!==fingerprint))throw new JarvisError('Deed payment reference conflict.',409);return {fingerprint,row};}
return Object.freeze({
async reserve(tx,actor,input){
if(actor?.id!==input.actorId)throw new JarvisError('Current buyer required.',403);const {fingerprint,row}=await orderFor(tx,input);if(row){if(row.state!=='escrow')throw new JarvisError('This deed payment already has a final outcome.',409);return {replayed:true};}
const rights=await authority(actor,{bank:tx}),rows=await tx.query(accountSQL+' WHERE a.id IN (?,?) ORDER BY a.id FOR UPDATE',[input.sourceAccount,input.recipientAccount]),source=rows.find(a=>String(a.id)===input.sourceAccount),target=rows.find(a=>String(a.id)===input.recipientAccount),amount=BigInt(input.priceMinor);
if(!ordinaryPaymentAccount(source)||source.entity_id!==entityId(input.parentKind,input.parentId)||!canDebitAccount(rights,source.entity_id,source.id))throw new JarvisError('Current purchasing-organisation payment authority required.',403);
if(!ordinaryPaymentAccount(target)||target.kind!=='person'||target.external_key!==input.sellerId)throw new JarvisError('The seller payment account changed.',409);
if(BigInt(source.balance_minor)-BigInt(source.reserved_minor)<amount||BigInt(target.balance_minor)+amount>9223372036854775807n)throw new JarvisError('Available funds or recipient balance require review.',409);
await tx.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'deed','escrow',?)",[input.requestId,actor.id,source.id,target.id,fingerprint,amount.toString(),'Deed acquisition · '+input.requestId,clock()]);
await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor+? WHERE id=?',[amount.toString(),source.id]);await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),actor.id,'deed_escrow_reserved',source.entity_id,JSON.stringify({paymentId:input.requestId,keyId:input.keyId,listingId:input.listingId}),clock()]);return {replayed:false};
},
async release(tx,input){const {row}=await orderFor(tx,input);if(!row)throw new JarvisError('Deed payment unavailable.',409);if(row.state==='cancelled')return {replayed:true};if(row.state!=='escrow'||await canRelease(input)!==true)throw new JarvisError('Purchase transfer must be reconciled before releasing funds.',409);const source=await tx.first('SELECT * FROM pb_accounts WHERE id=? FOR UPDATE',[row.source_id]);if(!source||BigInt(source.reserved_minor)<BigInt(row.amount_minor))throw new JarvisError('Purchase reserve requires reconciliation.',409);await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor-? WHERE id=?',[row.amount_minor,source.id]);await tx.query("UPDATE pb_orders SET state='cancelled' WHERE id=?",[row.id]);await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),row.actor_id,'deed_escrow_released',entityId(input.parentKind,input.parentId),JSON.stringify({paymentId:row.id,keyId:input.keyId}),clock()]);return {replayed:false};},
async settle(tx,input){const {row}=await orderFor(tx,input);if(!row)throw new JarvisError('Deed payment unavailable.',409);if(row.state==='posted')return {replayed:true};if(row.state!=='escrow'||await verifyTransfer(input)!==true)throw new JarvisError('A matching applied deed key is required before payment.',409);const rows=await tx.query(accountSQL+' WHERE a.id IN (?,?) ORDER BY a.id FOR UPDATE',[row.source_id,row.target_id]),source=rows.find(a=>String(a.id)===String(row.source_id)),target=rows.find(a=>String(a.id)===String(row.target_id));if(!ordinaryPaymentAccount(source)||!ordinaryPaymentAccount(target)||target.kind!=='person'||target.external_key!==input.sellerId||BigInt(source.reserved_minor)<BigInt(row.amount_minor))throw new JarvisError('Reserved purchase accounts require reconciliation.',409);await payments.post(tx,row,source,target,true);return {replayed:false};}
});
}