web/website/node/company-claims.mjs

55 lines
8.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {identity} from './auth.mjs';import {accessFor} from './permissions.mjs';
import {readPassiveOrder,passiveOrderAuthority} from './political-passive-orders.mjs';
import {readCompanyDeed,companyDeedView,companyId} from './company-deeds.mjs';
import {readClaimRegistry,webClanClaimSnapshot} from './claim-registry.mjs';
import {PostbankClaimProducts} from './postbank-claim-products.mjs';import {BankError} from './postbank-service.mjs';
import {entityId} from './postbank-authority.mjs';
import {projectClaimRegistry} from '../control-panel/claim-overview.mjs';import {createClaimUpgrades} from '../control-panel/claim-upgrades.mjs';
import {CLAN_HOMEWORLDS} from '../control-panel/clans.mjs';
const uuid=companyId;
function reader(tx){return{prepare(sql){let values=[];return{bind(...args){values=args;return this;},first:()=>tx.first(sql,values),all:async()=>({results:await tx.query(sql,values)})};}};}
export function createCompanyClaims(db,bank,authority,settings={},deps={}){
const clock=deps.clock||Date.now,authenticate=deps.authenticate||(r=>identity(r,db)),access=deps.access||(u=>accessFor(db,u)),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com';
const owner=async(user,id)=>{if(!uuid(id))throw new BankError('Choose a valid company.');const deed=await readCompanyDeed(db,id),view=companyDeedView(deed,user.id),link=await db.prepare('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?').bind(user.id).first();if(!view.canManage||deed.company.status!=='active'||!uuid(link?.minecraft_uuid))throw new BankError('Current linked company management is required.',403);return{id,name:deed.company.name,owner_id:deed.company.owner_account_id};};
const resolveFunding=async(_db,company,charter)=>['original','royal'].includes(charter)?{kind:'company',entityId:entityId('company',company.id),name:company.name,companyId:company.id,accountTypes:['105'],claimsOnly:false}:{kind:'person',entityId:entityId('person',company.owner_id),name:'Company owner’s personal account',ownerId:company.owner_id,accountTypes:['102','108'],claimsOnly:false};
const products=bank?new PostbankClaimProducts(db,bank,authority,{clock,domain:{kind:'company',owner,resolveFunding},readCharter:async id=>(await readCompanyDeed(db,id)).company.charter_kind}):null;
const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}});
const handle=mode=>async request=>{
const url=new URL(request.url);if(request.method!==(mode==='overview'?'GET':'POST'))return reply({message:'Method not allowed.'},405);
const user=await authenticate(request);if(!user)return reply({message:'Sign in to open Company claims.'},401);if(!(await access(user)).nodes.includes('web.menu.game'))return reply({message:'Game account access required.'},403);
try{
if(mode==='overview'){
const ids=url.searchParams.getAll('companyId');if([...url.searchParams.keys()].some(k=>k!=='companyId')||ids.length!==1||!uuid(ids[0]))throw new BankError('Choose a valid company.');
const id=ids[0],order=await readPassiveOrder(db,id);
if(order){
const permission=await passiveOrderAuthority(db,user,id,{clock});
if(!permission?.member)throw new BankError('Current Order membership is required for its civic records.',403);
const record=await readClaimRegistry(db,'company',id),claims=projectClaimRegistry({id},record,{kind:'company'});
return reply({company:{id,name:order.name,homeWorld:claims.homeBlock?.worldName||null},claims,canUpgrade:false,canRegisterHome:false,worlds:[],subhouses:{state:'connected',items:[]},passive:true});
}
const deed=await readCompanyDeed(db,id),view=companyDeedView(deed,user.id);if(deed.company.status!=='active')throw new BankError('Company claims are unavailable.',404);
let record=await readClaimRegistry(db,'company',id);if(record&&!products)throw new BankError('The company claim treasury is unavailable.',503);if(record&&products){const entitlement=await products.entitlement(id);if(entitlement)record={...record,tier:entitlement.tier};}
const link=await db.prepare('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?').bind(user.id).first(),claims=projectClaimRegistry({id},record,{kind:'company'});
return reply({company:{id,name:view.name,homeWorld:claims.homeBlock?.worldName||null},claims,canUpgrade:!!products&&!!record&&view.canManage&&uuid(link?.minecraft_uuid),canRegisterHome:!record&&view.canManage&&uuid(link?.minecraft_uuid),worlds:CLAN_HOMEWORLDS.map(({key,name})=>({key,name})),subhouses:{state:'not_connected',items:[]},simulation:false});
}
if(url.search||request.headers.get('origin')!==origin)throw new BankError('Request origin rejected.',403);
if(!/^application\/json(?:\s*;|$)/i.test(request.headers.get('content-type')||''))throw new BankError('JSON required.',415);
const raw=await request.text();if(raw.length>4096)throw new BankError('Request too large.',413);let input;try{input=JSON.parse(raw);}catch{throw new BankError('Invalid Home Block instruction.');}
if(!input||Object.keys(input).some(k=>!['companyId','worldKey','requestId','confirmed'].includes(k))||!uuid(input.companyId)||!uuid(input.requestId)||input.confirmed!==true||!CLAN_HOMEWORLDS.some(w=>w.key===input.worldKey))throw new BankError('Choose and confirm the company homeworld.');
const fresh=await authenticate(request);if(fresh?.id!==user.id||!(await access(fresh)).nodes.includes('web.menu.game'))throw new BankError('Your session changed.',403);await owner(fresh,input.companyId);
return await db.transaction(async tx=>{
await tx.first('SELECT id FROM corrino_companies WHERE id=? FOR UPDATE',[input.companyId]);await tx.first('SELECT company_id FROM site_company_deeds WHERE company_id=? FOR UPDATE',[input.companyId]);
const deed=await readCompanyDeed(reader(tx),input.companyId);if(!companyDeedView(deed,user.id).canManage||deed.company.status!=='active')throw new BankError('Company authority changed.',403);
const prior=await tx.first('SELECT company_id,actor_id,action,details_json FROM corrino_company_events WHERE id=?',[input.requestId]);if(prior&&(prior.company_id!==input.companyId||prior.actor_id!==user.id||prior.action!=='home-block-registered'||JSON.parse(prior.details_json).worldKey!==input.worldKey))throw new BankError('The instruction reference was already used.',409);
const existing=await tx.first("SELECT snapshot_json FROM site_claim_registry WHERE organisation_kind='company' AND organisation_id=? FOR UPDATE",[input.companyId]);
if(existing){const snapshot=JSON.parse(existing.snapshot_json),world=CLAN_HOMEWORLDS.find(w=>w.key===input.worldKey);if(snapshot.homeBlock?.worldName!==world.name)throw new BankError('The Company Home Block already defines another homeworld.',409);return reply({ok:true,replayed:true,companyId:input.companyId});}
if(prior)throw new BankError('The historical Home Block registration requires review.',409);
const ownerLink=await tx.first('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?',[deed.company.owner_account_id]);if(!uuid(ownerLink?.minecraft_uuid))throw new BankError('The registered owner must link Minecraft before a Home Block can be registered.',409);
const links=await tx.query('SELECT minecraft_uuid FROM site_game_links WHERE user_id IN ('+deed.members.map(()=>'?').join(',')+')',deed.members.map(m=>m.id)),snapshot=webClanClaimSnapshot({id:input.companyId,name:deed.company.name,home_world:input.worldKey,owner_uuid:ownerLink.minecraft_uuid,member_uuids:links.map(l=>l.minecraft_uuid)},{kind:'company'}),now=clock();
await tx.query("INSERT INTO site_claim_registry(organisation_kind,organisation_id,snapshot_json,revision,updated_at) VALUES('company',?,?,1,?)",[input.companyId,JSON.stringify(snapshot),now]);
await tx.query('INSERT INTO corrino_company_events(id,company_id,action,actor_id,details_json,created_at) VALUES(?,?,?,?,?,?)',[input.requestId,input.companyId,'home-block-registered',user.id,JSON.stringify({worldKey:input.worldKey,homeBlockId:snapshot.homeBlock.id}),now]);return reply({ok:true,replayed:false,companyId:input.companyId},201);
});
}catch(error){return reply({message:error.status?error.message:'Company claims could not be confirmed.'},error.status||503);}
};
return{products,overview:handle('overview'),homeBlock:handle('home-block'),upgrades:createClaimUpgrades(db,products,settings,{authenticate,access,idField:'companyId',path:'/api/v1/company-claims/upgrades'})};
}