55 lines
13 KiB
JavaScript
55 lines
13 KiB
JavaScript
import {AsyncLocalStorage} from 'node:async_hooks';
|
|
import {createHash} from 'node:crypto';
|
|
import {createDeedSaleKeys} from './deed-sale-keys.mjs';
|
|
import {createDeedPurchasePayments} from './deed-purchase-payments.mjs';
|
|
import {PostbankPayments,standardCycle} from './postbank-payments.mjs';
|
|
import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs';
|
|
import {JarvisError} from './jarvis-listings.mjs';
|
|
import {entityId} from './postbank-authority.mjs';
|
|
export const DEED_PURCHASE_SCHEMA="CREATE TABLE IF NOT EXISTS jarvis_deed_purchases(id CHAR(36) PRIMARY KEY,listing_id CHAR(36) NOT NULL,listing_revision INTEGER NOT NULL,actor_id CHAR(36) NOT NULL,seller_id CHAR(36) NOT NULL,key_id CHAR(36) NOT NULL,parent_kind VARCHAR(12) NOT NULL,parent_id CHAR(36) NOT NULL,source_account BIGINT NOT NULL,recipient_account BIGINT NOT NULL,price_minor BIGINT NOT NULL,fingerprint CHAR(64) NOT NULL,quote_json TEXT NOT NULL,state VARCHAR(16) NOT NULL,due_at BIGINT NOT NULL,cleanup_needed INTEGER NOT NULL DEFAULT 0,last_error VARCHAR(80) NULL,created_at BIGINT NOT NULL,updated_at BIGINT NOT NULL,INDEX deed_purchase_due(state,due_at),INDEX deed_purchase_listing(listing_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
|
|
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';
|
|
const fail=(message,status=409)=>{throw new JarvisError(message,status);};
|
|
const paymentInput=j=>({keyId:j.key_id,listingId:j.listing_id,requestId:j.id,actorId:j.actor_id,sellerId:j.seller_id,parentKind:j.parent_kind,parentId:j.parent_id,sourceAccount:String(j.source_account),recipientAccount:String(j.recipient_account),priceMinor:Number(j.price_minor)});
|
|
const matches=(j,p)=>j&&j.id===p.requestId&&j.actor_id===p.buyerId&&j.seller_id===p.sellerId&&j.key_id===p.keyId&&j.listing_id===p.listingId&&j.parent_kind===p.parent.kind&&j.parent_id===p.parent.id&&String(j.source_account)===p.sourceAccount&&String(j.recipient_account)===p.recipientAccount&&Number(j.price_minor)===p.priceMinor;
|
|
const receipt=j=>({purchaseId:j.id,listingId:j.listing_id,state:j.state,nextProcessingAt:Number(j.due_at),paymentReference:j.id,complete:j.state==='posted',message:j.state==='posted'?'Deed acquisition and payment completed.':j.state==='failed'?'The deed or payment authority changed. No purchase was completed.':j.state==='applied'?'Deed transfer recorded. The reserved payment is awaiting bank reconciliation.':'Purchase reserved for the ordinary bank processing window.'});
|
|
export function createDeedPurchases(central,bank,keys,{authority,clock=Date.now,resolveActor=async id=>(await central.query("SELECT id,username,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[id]))[0]||null}={}){
|
|
if(typeof authority!=='function')throw TypeError('Current bank authority adapter required');
|
|
const bankScope=new AsyncLocalStorage(),reader=()=>bankScope.getStore()||bank;
|
|
const transaction=work=>bank.transaction(tx=>bankScope.run(tx,()=>work(tx)));
|
|
const job=async id=>reader().first('SELECT * FROM jarvis_deed_purchases WHERE id=?',[id]);
|
|
const sales=createDeedSaleKeys(central,keys,{clock,
|
|
verifyPurchaseIntent:async(_actor,p)=>{const j=await job(p.requestId);if(!matches(j,p))return false;const order=await reader().first('SELECT state FROM pb_orders WHERE id=?',[j.id]);return p.releasing?j.state==='failed'&&(!order||order.state==='cancelled'):j.state==='preparing'&&!order;},
|
|
verifyPurchaseFunding:async(_actor,p)=>{const j=await job(p.requestId);if(!matches(j,p)||j.state!=='funded')return false;const o=await reader().first('SELECT * FROM pb_orders WHERE id=?',[j.id]);return !!o&&o.mode==='deed'&&o.state==='escrow'&&o.actor_id===j.actor_id&&String(o.source_id)===String(j.source_account)&&String(o.target_id)===String(j.recipient_account)&&Number(o.amount_minor)===Number(j.price_minor);}
|
|
});
|
|
const payments=createDeedPurchasePayments(bank,authority,{clock,
|
|
verifyTransfer:async input=>{const j=await job(input.requestId),s=await sales.purchaseState(input.keyId);return j?.state==='applied'&&s?.applied===true&&s.requestId===j.id&&s.buyerId===j.actor_id;},
|
|
canRelease:async input=>{const j=await job(input.requestId),s=await sales.purchaseState(input.keyId);return j?.state==='funded'&&s&&!s.keyUsed&&s.state==='reserved'&&s.requestId===j.id&&s.buyerId===j.actor_id;}
|
|
});
|
|
async function parents(actor){const rows=[];if(central.clanDeedsEnabled)rows.push(...(await central.query("SELECT c.id,c.name,'clan' kind FROM site_clans c JOIN site_clan_charters ch ON ch.clan_id=c.id LEFT JOIN site_clan_institutions i ON i.clan_id=c.id WHERE c.active=1 AND c.owner_id=? AND ch.charter_kind IN ('original','royal') AND i.institution_key IS NULL",[actor.id])));if(central.companyDeedsEnabled)rows.push(...(await central.query("SELECT c.id,c.name,'company' kind FROM corrino_companies c JOIN site_company_deeds d ON d.company_id=c.id LEFT JOIN site_company_institutions i ON i.company_id=c.id WHERE c.status='active' AND d.owner_account_id=? AND d.charter_kind IN ('original','royal') AND i.institution_key IS NULL",[actor.id])));return rows;}
|
|
async function payout(sellerId){const rows=await bank.query(accountSQL+" WHERE e.kind='person' AND e.external_key=? ORDER BY a.id",[sellerId]);const account=rows.find(ordinaryPaymentAccount);if(!account)fail('The seller needs an active personal payment account.');return account;}
|
|
async function currentOffer(listingId){const listing=await bank.first("SELECT * FROM jarvis_listings WHERE id=? AND definition_id='entity-transfer' AND state='open'",[listingId]);if(!listing)fail('This deed offer is no longer open.');const offer=await sales.purchaseOffer(listingId);if(listing.actor_id!==offer.sellerId||listing.organisation_id!==offer.entityId||listing.organisation_kind!==offer.kind)fail('The listing and deed disagree.');return {listing,offer};}
|
|
async function cleanup(j){const s=await sales.purchaseState(j.key_id);if(s?.state==='reserved'&&s.requestId===j.id&&s.buyerId===j.actor_id)await sales.releasePurchase({id:j.actor_id},{keyId:j.key_id,requestId:j.id});else if(s?.keyUsed||s?.state==='reserved')return;await bank.query('UPDATE jarvis_deed_purchases SET cleanup_needed=0 WHERE id=? AND state=\'failed\'',[j.id]);}
|
|
async function abort(id,error){await transaction(async tx=>{const j=await tx.first('SELECT * FROM jarvis_deed_purchases WHERE id=? FOR UPDATE',[id]);if(!j||!['preparing','funded'].includes(j.state))return;if(j.state==='funded')await payments.release(tx,paymentInput(j));await tx.query("UPDATE jarvis_deed_purchases SET state='failed',cleanup_needed=1,last_error=?,updated_at=? WHERE id=?",[(error.name+':'+error.status).slice(0,80),clock(),id]);await tx.query("UPDATE jarvis_listings SET state='open',revision=revision+1,updated_at=? WHERE id=? AND state='reserved' AND revision=?",[clock(),j.listing_id,Number(j.listing_revision)+1]);});const j=await job(id);if(j?.state==='failed'&&Number(j.cleanup_needed))await cleanup(j);}
|
|
async function process(id){
|
|
for(let step=0;step<3;step++)try{const result=await transaction(async tx=>{
|
|
const j=await tx.first('SELECT * FROM jarvis_deed_purchases WHERE id=? FOR UPDATE',[id]);if(!j)fail('Purchase not found.',404);
|
|
if(j.state==='preparing'){const actor=await resolveActor(j.actor_id);if(!actor)fail('The purchasing account is unavailable.',403);await sales.reservePurchase(actor,{keyId:j.key_id,requestId:j.id,parentKind:j.parent_kind,parentId:j.parent_id,sourceAccount:String(j.source_account),recipientAccount:String(j.recipient_account)});await payments.reserve(tx,actor,paymentInput(j));await tx.query("UPDATE jarvis_deed_purchases SET state='funded',updated_at=? WHERE id=?",[clock(),id]);return 'continue';}
|
|
if(j.state==='funded'){if(Number(j.due_at)>clock())return 'wait';const actor=await resolveActor(j.actor_id);if(!actor)fail('The purchasing account is unavailable.',403);await sales.applyPurchase(actor,{keyId:j.key_id,requestId:j.id});await tx.query("UPDATE jarvis_deed_purchases SET state='applied',updated_at=? WHERE id=?",[clock(),id]);return 'continue';}
|
|
if(j.state==='applied'){await payments.settle(tx,paymentInput(j));await tx.query("UPDATE jarvis_deed_purchases SET state='posted',updated_at=? WHERE id=?",[clock(),id]);await tx.query("UPDATE jarvis_listings SET state='sold',revision=revision+1,updated_at=? WHERE id=? AND state='reserved'",[clock(),j.listing_id]);return 'done';}
|
|
return 'done';
|
|
});if(result!=='continue')break;}catch(error){const j=await job(id);if(!j)throw error;const s=await sales.purchaseState(j.key_id);if(error.status>=400&&error.status<500&&(j.state==='preparing'||j.state==='funded'&&s&&!s.keyUsed&&s.state==='reserved'&&s.requestId===id)){await abort(id,error);}else await bank.query('UPDATE jarvis_deed_purchases SET last_error=?,updated_at=? WHERE id=?',[(error.name||'Error').slice(0,80),clock(),id]);break;}
|
|
const j=await job(id);if(j.state==='failed'&&Number(j.cleanup_needed))await cleanup(j);return receipt(j);
|
|
}
|
|
return Object.freeze({sales,
|
|
async quote(actor,listingId){if(!uuid(actor?.id)||!uuid(listingId))fail('Choose a deed offer.',400);const {listing,offer}=await currentOffer(listingId);if(offer.sellerId===actor.id)fail('Choose a deed belonging to another owner.');const recipient=await payout(offer.sellerId),owned=await parents(actor),accounts=(await new PostbankPayments(bank,authority,{clock}).accounts(actor)).filter(a=>a.canDebit);return {listingId,revision:Number(listing.revision),name:offer.name,kind:offer.kind,priceMinor:offer.priceMinor,recipientAccount:String(recipient.id),recipientName:recipient.display_name,recipientNumber:recipient.account_number,parents:owned.filter(p=>p.kind===offer.kind&&p.id!==offer.entityId).map(p=>({...p,entityId:entityId(p.kind,p.id)})),accounts,nextProcessingAt:standardCycle(clock()).nextAt,terms:'Acquire parent-deed control. The local owner, roster and personal votes remain unchanged. Payment and transfer complete at the ordinary bank processing window.'};},
|
|
async begin(actor,input){
|
|
const fields=['listingId','revision','parentKind','parentId','sourceAccount','recipientAccount','expectedPriceMinor','requestId','confirmed'];if(!uuid(actor?.id)||!input||Object.keys(input).some(k=>!fields.includes(k))||input.confirmed!==true||!uuid(input.listingId)||!uuid(input.requestId)||!uuid(input.parentId)||!['clan','company'].includes(input.parentKind)||!Number.isSafeInteger(input.revision)||input.revision<1||!Number.isSafeInteger(input.expectedPriceMinor)||input.expectedPriceMinor<1||!/^\d{1,12}$/.test(input.sourceAccount)||!/^\d{1,12}$/.test(input.recipientAccount))fail('Review and confirm the current deed purchase.',400);
|
|
const fingerprint=createHash('sha256').update(JSON.stringify([actor.id,...fields.filter(k=>k!=='confirmed').map(k=>input[k])])).digest('hex');let previous=await job(input.requestId);if(previous){if(previous.actor_id!==actor.id||previous.fingerprint!==fingerprint)fail('Purchase reference conflict.');return process(previous.id);}
|
|
const {listing,offer}=await currentOffer(input.listingId);if(input.parentKind!==offer.kind)fail('Ordinary deed purchases require the same organisation type.');const recipient=await payout(offer.sellerId);if(offer.sellerId===actor.id||Number(listing.revision)!==input.revision||offer.priceMinor!==input.expectedPriceMinor||String(recipient.id)!==input.recipientAccount)fail('The deed price or recipient changed. Refresh before confirming.');if(!(await parents(actor)).some(p=>p.id===input.parentId&&p.kind===input.parentKind))fail('Current purchasing deed authority required.',403);
|
|
await transaction(async tx=>{const row=await tx.first('SELECT * FROM jarvis_listings WHERE id=? FOR UPDATE',[input.listingId]),prior=await tx.first('SELECT * FROM jarvis_deed_purchases WHERE id=?',[input.requestId]);if(prior){if(prior.actor_id!==actor.id||prior.fingerprint!==fingerprint)fail('Purchase reference conflict.');return;}if(!row||row.state!=='open'||Number(row.revision)!==input.revision)fail('This deed is no longer available.');const now=clock();await tx.query("INSERT INTO jarvis_deed_purchases(id,listing_id,listing_revision,actor_id,seller_id,key_id,parent_kind,parent_id,source_account,recipient_account,price_minor,fingerprint,quote_json,state,due_at,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,'preparing',?,?,?)",[input.requestId,input.listingId,input.revision,actor.id,offer.sellerId,offer.keyId,input.parentKind,input.parentId,input.sourceAccount,input.recipientAccount,offer.priceMinor,fingerprint,JSON.stringify(offer),standardCycle(now).nextAt,now,now]);await tx.query("UPDATE jarvis_listings SET state='reserved',revision=revision+1,updated_at=? WHERE id=?",[now,input.listingId]);});return process(input.requestId);
|
|
},
|
|
async status(actor,id){const j=uuid(id)&&await job(id);if(!j||j.actor_id!==actor?.id)fail('Purchase not found.',404);return receipt(j);},
|
|
async drain(){const jobs=await bank.query("SELECT id FROM jarvis_deed_purchases WHERE state='preparing' OR state='funded' AND due_at<=? OR state='applied' OR state='failed' AND cleanup_needed=1 ORDER BY created_at,id LIMIT 25",[clock()]);let posted=0,failed=0;for(const j of jobs)try{const result=await process(j.id);if(result.state==='posted')posted++;if(result.state==='failed')failed++;}catch{failed++;}return {attempted:jobs.length,posted,failed};}
|
|
});
|
|
}
|

Staff