MC/website/node/postbank-claim-products.mjs
2026-11-27 23:43:05 +00:00

87 lines
13 KiB
JavaScript

import {resolveClaimFunding} from './claim-funding.mjs';
import {clanDeedAuthority} from './clan-deeds.mjs';
import {createHash} from 'node:crypto';
import {BankError} from './postbank-service.mjs';
import {entityId} from './postbank-authority.mjs';
import {canDebitAccount} from './postbank-authorisations.mjs';
import {PostbankPayments,standardCycle} from './postbank-payments.mjs';
import {money} from './postbank-catalogue.mjs';
import {readClaimRegistry} from './claim-registry.mjs';
import {claimTariffs,CLAIM_TARIFF_VERSION,claimDisplayName} from '../control-panel/public/cp-v2/cp-v2-claim-tariffs.mjs';
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
export const CLAIM_PRODUCT_SCHEMA=[
`CREATE TABLE IF NOT EXISTS pb_claim_entitlements (entity_id CHAR(36) PRIMARY KEY,tier VARCHAR(16) NOT NULL,revision INTEGER NOT NULL,updated_at BIGINT NOT NULL,FOREIGN KEY(entity_id) REFERENCES pb_entities(id))`,
`CREATE TABLE IF NOT EXISTS pb_claim_purchases (request_id CHAR(36) PRIMARY KEY,actor_id CHAR(36) NOT NULL,entity_id CHAR(36) NOT NULL,fingerprint CHAR(64) NOT NULL,tier VARCHAR(16) NOT NULL,revision INTEGER NOT NULL,amount_minor BIGINT NOT NULL,created_at BIGINT NOT NULL,FOREIGN KEY(entity_id) REFERENCES pb_entities(id),FOREIGN KEY(request_id) REFERENCES pb_orders(id))`,
`CREATE TABLE IF NOT EXISTS pb_claim_batches (order_id CHAR(36) PRIMARY KEY,entity_id CHAR(36) NOT NULL,payer_entity_id CHAR(36) NULL,due_at BIGINT NOT NULL,FOREIGN KEY(order_id) REFERENCES pb_orders(id),FOREIGN KEY(entity_id) REFERENCES pb_entities(id))`,
`CREATE TABLE IF NOT EXISTS pb_claim_batch_items (request_id CHAR(36) PRIMARY KEY,order_id CHAR(36) NOT NULL,FOREIGN KEY(request_id) REFERENCES pb_orders(id),FOREIGN KEY(order_id) REFERENCES pb_orders(id))`
];
const accountsSQL="SELECT a.*,c.entity_id,e.kind entity_kind,e.external_key entity_key,e.active entity_active,p.state package_state FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id JOIN pb_packages p ON p.id=a.package_id";
export class PostbankClaimProducts{
constructor(central,bank,authority,{clock=Date.now,readRegistry,readCharter=async()=> 'basic',domain=null}={}){this.kind=domain?.kind||'clan';if(!['clan','company','protected'].includes(this.kind)||this.kind!=='clan'&&typeof domain?.owner!=='function')throw TypeError('An explicit claim domain adapter is required.');this.idField=this.kind==='protected'?'protectedId':this.kind==='company'?'companyId':'clanId';this.domainOwner=domain?.owner;this.resolveFunding=domain?.resolveFunding||resolveClaimFunding;this.central=central;this.bank=bank;this.authority=authority;this.clock=clock;this.readRegistry=readRegistry||(id=>readClaimRegistry(central,this.kind,id));this.readCharter=readCharter;}
async entitlement(clanId){return this.bank.first('SELECT tier,revision FROM pb_claim_entitlements WHERE entity_id=?',[entityId(this.kind,clanId)]);}
async owner(user,clanId){
if(this.domainOwner)return this.domainOwner(user,clanId);
if(!uuid(clanId))throw new BankError('Choose a valid clan.');
let clan=await this.central.prepare("SELECT c.id,c.name,c.owner_id,i.institution_key FROM site_clans c JOIN site_clan_members m ON m.clan_id=c.id AND m.user_id=c.owner_id AND m.clan_role='owner' JOIN site_game_links l ON l.user_id=m.user_id AND l.minecraft_uuid=m.minecraft_uuid LEFT JOIN site_clan_institutions i ON i.clan_id=c.id WHERE c.id=? AND c.active=1 AND c.owner_id=?").bind(clanId,user.id).first();
if(!clan&&this.central.clanDeedsEnabled){const authority=await clanDeedAuthority(this.central,user.id,clanId);if(authority.canManage)clan={id:clanId,name:authority.deed.clan.name,owner_id:authority.deed.clan.owner_id,institution_key:authority.deed.clan.institution_key};}
if(!clan)throw new BankError('Only the currently linked clan owner can purchase this upgrade.',403);
return clan;
}
async quote(user,clanId,{store=this.bank,lock=false}={}){
const clan=await this.owner(user,clanId),id=entityId(this.kind,clan.id),base=await this.readRegistry(clan.id);
if(!base)throw new BankError('Register a Home Block before upgrading claims.',409);
const current=await store.first('SELECT tier,revision FROM pb_claim_entitlements WHERE entity_id=?'+(lock?' FOR UPDATE':''),[id]),tier=current?.tier||base.tier,revision=Number(current?.revision||1),rows=claimTariffs(clan.institution_key?'protected':this.kind),index=rows.findIndex(r=>r.code===tier);
if(index<0)throw new BankError('The registered claim tier requires review.',409);
const next=rows[index+1]||null,charter=await this.readCharter(clan.id);let blocked=null;
const available=[];let total=0;for(const row of rows.slice(index+1)){total+=row.unlockMinor;if(row.stage==='Keyed'&&!['original','royal'].includes(charter)||row.stage==='Royal'&&charter!=='royal')break;available.push({...row,unlockMinor:total});}
if(next?.stage==='Keyed'&&!['original','royal'].includes(charter))blocked=this.kind==='company'?'An original COM key is required for Keyed tiers.':'An original clan key is required for Keyed tiers.';
if(next?.stage==='Royal'&&charter!=='royal')blocked='A Royal appointment is required.';
const funding=await this.resolveFunding(this.central,clan,charter),context=await this.authority(user,{bank:store}),accounts=await store.query(accountsSQL+" WHERE c.entity_id=? AND a.type_code IN ("+funding.accountTypes.map(()=>'?').join(',')+") AND a.system_key IS NULL ORDER BY a.id",[funding.entityId,...funding.accountTypes]);
const choices=accounts.filter(a=>a.state==='active'&&a.package_state==='active'&&Number(a.entity_active)===1&&(funding.claimsOnly||canDebitAccount(context,funding.entityId,a.id))).map(a=>({id:String(a.id),number:a.account_number,name:a.display_name,available:money(BigInt(a.balance_minor)-BigInt(a.reserved_minor))}));
return {[this.idField]:clan.id,name:clan.name,entityId:id,tier,revision,tariffVersion:CLAIM_TARIFF_VERSION,next,blocked,funding,targets:available,settlesAt:standardCycle(this.clock()).nextAt,accounts:choices};
}
async purchase(user,input,{revalidate=async()=>user}={}){
const keys=[this.idField,'sourceAccount','requestId','expectedRevision','targetTier','expectedUnlockMinor','tariffVersion','confirmed'];
if(!input||Object.keys(input).some(k=>!keys.includes(k))||!uuid(input[this.idField])||!uuid(input.requestId)||!/^\d{1,12}$/.test(input.sourceAccount||'')||!Number.isSafeInteger(input.expectedRevision)||input.expectedRevision<1||typeof input.targetTier!=='string'||!Number.isSafeInteger(input.expectedUnlockMinor)||input.expectedUnlockMinor<0||input.confirmed!==true)throw new BankError('Review and confirm the clan upgrade.');
const entity=entityId(this.kind,input[this.idField]),fingerprint=createHash('sha256').update(JSON.stringify([...(this.kind!=='clan'?[this.kind]:[]),user.id,input[this.idField],input.sourceAccount,input.expectedRevision,input.targetTier,input.expectedUnlockMinor,input.tariffVersion])).digest('hex');
const subject=await this.owner(user,input[this.idField]),subjectCharter=await this.readCharter(input[this.idField]);
await this.bank.query('INSERT INTO pb_entities(id,kind,external_key,display_name,active,created_at) VALUES(?,?,?,?,?,?) ON DUPLICATE KEY UPDATE display_name=VALUES(display_name)',[entity,this.kind,input[this.idField],subject.name,['original','royal'].includes(subjectCharter)?1:0,this.clock()]);
return this.bank.transaction(async tx=>{
for(const id of [entity,entityId('person',user.id)].sort())await tx.first('SELECT id FROM pb_entities WHERE id=? FOR UPDATE',[id]);
const fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed.',403);await this.owner(fresh,input[this.idField]);
const prior=await tx.first('SELECT * FROM pb_claim_purchases WHERE request_id=?',[input.requestId]);
if(prior){if(prior.actor_id!==user.id||prior.fingerprint!==fingerprint)throw new BankError('The request reference was already used.',409);return {ok:true,replayed:true,tier:prior.tier,revision:Number(prior.revision),reserved:money(prior.amount_minor),paymentState:'reserved'};}
const quote=await this.quote(fresh,input[this.idField],{store:tx,lock:true});
const targetTier=quote.targets.find(row=>row.code===input.targetTier);
if(quote.revision!==input.expectedRevision||!targetTier||input.tariffVersion!==quote.tariffVersion||targetTier.unlockMinor!==input.expectedUnlockMinor)throw new BankError('The upgrade quote changed. Refresh and review it again.',409);
if(!quote.accounts.some(a=>a.id===input.sourceAccount))throw new BankError('Choose an authorised account for this claim charter.',403);
const sourceMeta=await tx.first(accountsSQL+' WHERE a.id=?',[input.sourceAccount]);
if(!sourceMeta||sourceMeta.entity_id!==quote.funding.entityId)throw new BankError('The funding account changed.',409);
const taxMeta=await tx.first("SELECT id FROM pb_accounts WHERE system_key='sys_tax_treasury'");if(!taxMeta)throw new BankError('Tax treasury unavailable.',503);
const locked=await tx.query('SELECT * FROM pb_accounts WHERE id IN (?,?) ORDER BY id FOR UPDATE',[sourceMeta.id,taxMeta.id]),source=locked.find(a=>String(a.id)===input.sourceAccount),tax=locked.find(a=>String(a.id)===String(taxMeta.id));
const amount=BigInt(targetTier.unlockMinor);if(!source||!tax||source.state!=='active'||tax.state!=='active'||BigInt(source.balance_minor)-BigInt(source.reserved_minor)<amount)throw new BankError('Insufficient available funding or an account is unavailable.',409);
if(BigInt(tax.balance_minor)+amount>9223372036854775807n)throw new BankError('Tax treasury balance limit reached.',409);
const finalUser=await revalidate();if(!finalUser||finalUser.id!==user.id)throw new BankError('Your session changed.',403);await this.owner(finalUser,input[this.idField]);const finalRights=await this.authority(finalUser,{bank:tx}),freshFunding=await this.resolveFunding(this.central,await this.owner(finalUser,input[this.idField]),await this.readCharter(input[this.idField]));if(freshFunding.entityId!==quote.funding.entityId||freshFunding.kind!==quote.funding.kind)throw new BankError('The claim funding mandate changed.',409);if(!quote.funding.claimsOnly&&!canDebitAccount(finalRights,quote.funding.entityId,source.id))throw new BankError('Your clan payment authority changed.',403);
const now=this.clock(),due=standardCycle(now).nextAt,hash=createHash('sha256').update('claims-batch:'+source.id+':'+due).digest('hex'),batchId=hash.slice(0,8)+'-'+hash.slice(8,12)+'-5'+hash.slice(13,16)+'-a'+hash.slice(17,20)+'-'+hash.slice(20,32);
const batch=await tx.first('SELECT * FROM pb_orders WHERE id=? FOR UPDATE',[batchId]);
if(batch&&(batch.state!=='queued'||String(batch.source_id)!==String(source.id)||String(batch.target_id)!==String(tax.id)))throw new BankError('The settlement batch changed. Refresh.',409);
if(batch)await tx.query('UPDATE pb_orders SET amount_minor=amount_minor+? WHERE id=?',[String(amount),batchId]);
else{
await tx.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'claims','queued',?)",[batchId,user.id,source.id,tax.id,hash,String(amount),'Claim upgrades · four-hour settlement',now]);
await tx.query('INSERT INTO pb_claim_batches(order_id,entity_id,payer_entity_id,due_at) VALUES(?,?,?,?)',[batchId,entity,quote.funding.entityId,due]);
}
await tx.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'claimref','included',?)",[input.requestId,user.id,source.id,tax.id,fingerprint,String(amount),'Claim unlock '+claimDisplayName(quote.tier)+' → '+targetTier.displayName,now]);
await tx.query('INSERT INTO pb_claim_batch_items(request_id,order_id) VALUES(?,?)',[input.requestId,batchId]);
const itemCount=await tx.first('SELECT COUNT(*) total FROM pb_claim_batch_items WHERE order_id=?',[batchId]);
await tx.query('UPDATE pb_orders SET memo=? WHERE id=?',['Claim upgrades ('+itemCount.total+') · '+targetTier.displayName,batchId]);
await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor+? WHERE id=?',[String(amount),source.id]);
const revision=quote.revision+1,existing=await tx.first('SELECT entity_id FROM pb_claim_entitlements WHERE entity_id=?',[entity]);
if(existing)await tx.query('UPDATE pb_claim_entitlements SET tier=?,revision=?,updated_at=? WHERE entity_id=?',[targetTier.code,revision,this.clock(),entity]);
else await tx.query('INSERT INTO pb_claim_entitlements(entity_id,tier,revision,updated_at) VALUES(?,?,?,?)',[entity,targetTier.code,revision,this.clock()]);
await tx.query('INSERT INTO pb_claim_purchases(request_id,actor_id,entity_id,fingerprint,tier,revision,amount_minor,created_at) VALUES(?,?,?,?,?,?,?,?)',[input.requestId,user.id,entity,fingerprint,targetTier.code,revision,String(amount),this.clock()]);
return {ok:true,replayed:false,tier:targetTier.code,revision,reserved:money(amount),paymentState:'reserved',settlesAt:due};
});
}
}