MC/website/node/personal-networth.mjs
2026-11-27 23:43:05 +00:00

19 lines
2.3 KiB
JavaScript

import {entityId} from './postbank-authority.mjs';
export const NETWORTH_SCHEMA=`CREATE TABLE IF NOT EXISTS pb_personal_networth(entity_id CHAR(36) NOT NULL,period BIGINT NOT NULL,sampled_at BIGINT NOT NULL,assets_minor DECIMAL(30,0) NOT NULL,debt_minor DECIMAL(30,0) NOT NULL,networth_minor DECIMAL(30,0) NOT NULL,PRIMARY KEY(entity_id,period)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`;
// Reserved funds remain owned assets. Corporate, office, civic and clandestine
// money never enter this personal projection; collateral stays a personal asset.
export async function snapshotPersonalNetworth(bank,period,{clock=Date.now}={}){
const sampledAt=clock();let cursor='',recorded=0;
if(!Number.isSafeInteger(period)||period<0)throw new TypeError('Invalid net worth period');
while(true){const count=await bank.transaction(async tx=>{
const rows=await tx.query("SELECT e.id,COALESCE((SELECT SUM(a.balance_minor) FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number WHERE c.entity_id=e.id AND a.type_code IN ('102','103','104','106','108') AND a.system_key IS NULL),0) assets_minor,COALESCE((SELECT SUM(l.outstanding_minor) FROM pb_credit_loans l WHERE l.entity_id=e.id AND l.state='active'),0) debt_minor FROM pb_entities e WHERE e.kind='person' AND e.active=1 AND e.id>? ORDER BY e.id LIMIT 200",[cursor]);
for(const row of rows){const assets=BigInt(row.assets_minor),debt=BigInt(row.debt_minor);await tx.query('INSERT INTO pb_personal_networth(entity_id,period,sampled_at,assets_minor,debt_minor,networth_minor) VALUES(?,?,?,?,?,?) ON DUPLICATE KEY UPDATE entity_id=VALUES(entity_id)',[row.id,period,sampledAt,String(assets),String(debt),String(assets-debt)]);cursor=row.id;}
return rows.length;
});recorded+=count;if(count<200)break;}
return {recorded};
}
export async function readPersonalNetworth(bank,userId,{clock=Date.now}={}){
if(!bank)return{state:'unavailable',points:[]};
let rows;try{rows=await bank.query('SELECT sampled_at,networth_minor FROM pb_personal_networth WHERE entity_id=? AND sampled_at>=? ORDER BY period DESC LIMIT 540',[entityId('person',userId),clock()-90*86400000]);}catch{return{state:'unavailable',points:[]};}
return{state:rows.length?'available':'empty',currency:'DM',periodDays:90,sampleHours:4,points:rows.reverse().map(row=>({at:Number(row.sampled_at),minor:String(row.networth_minor)}))};
}