web/website/node/company-recruitment.mjs

50 lines
6.9 KiB
JavaScript

import {randomUUID} from 'node:crypto';
import {identity} from './auth.mjs';import {accessFor} from './permissions.mjs';
import {companyId,readCompanyDeed,companyDeedView} from './company-deeds.mjs';
import {connectionReader} from './clan-deeds.mjs';
import {membershipRequest,membershipReview,MembershipError,changed} from './membership-recruitment.mjs';
import {JarvisError} from './jarvis-listings.mjs';
export function createCompanyRecruitment(db,{origin='https://cp.dunerealms.com',authenticate=r=>identity(r,db),access=u=>accessFor(db,u),requestIntegration=null,clock=Date.now}={}){
const membership=async(reader,userId)=>(await reader.prepare("SELECT c.id FROM corrino_companies c WHERE c.status='active' AND NOT EXISTS(SELECT 1 FROM site_company_institutions i WHERE i.company_id=c.id) AND (c.ceo_account_id=? OR EXISTS(SELECT 1 FROM site_company_members m WHERE m.company_id=c.id AND m.user_id=?)) LIMIT 1").bind(userId,userId).first());
return async request=>{
const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}});
if(request.method!=='POST')return reply({message:'Method not allowed.'},405);
const user=await authenticate(request);if(!user)return reply({message:'Sign in to manage company applications.'},401);
if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403);
if(!(await access(user)).nodes.includes('web.menu.game'))return reply({message:'Game account access required.'},403);
try{
const raw=await request.text();if(raw.length>6000)throw new MembershipError('Request too large.',413);let body;try{body=JSON.parse(raw);}catch{throw new MembershipError('Invalid request.',400);}
if(!body||!['request','review','withdraw','leave','remove'].includes(body.action)||!companyId(body.companyId)||!Number.isSafeInteger(body.version)||body.version<1)throw new MembershipError('Choose a current company record.',400);
const fresh=await authenticate(request);if(fresh?.id!==user.id||!(await access(fresh)).nodes.includes('web.menu.game'))throw new MembershipError('Your session changed.',403);
if(!await db.prepare('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?').bind(user.id).first())throw new MembershipError('Link your Minecraft account first.');
const deed=await readCompanyDeed(db,body.companyId),record=deed.company,now=clock();if(record.status!=='active')throw new MembershipError('This company is unavailable.');
if(record.institution_key)throw new MembershipError('Protected company membership follows its Order automatically.',403);
const canReview=[record.owner_account_id,record.ceo_account_id,...(deed.controllers||[])].includes(user.id);
const lock=()=>({async run(connection){
if(connection){await connection.execute('SELECT id FROM site_accounts WHERE id=? FOR UPDATE',[user.id]);await connection.execute('SELECT id FROM corrino_companies WHERE id=? FOR UPDATE',[record.id]);await connection.execute('SELECT company_id FROM site_company_deeds WHERE company_id=? FOR UPDATE',[record.id]);}
const reader=connectionReader(db,connection),current=await readCompanyDeed(reader,record.id);if(current.company.status!=='active'||current.version!==body.version)throw new MembershipError('The company changed. Refresh first.');
if(['review','remove'].includes(body.action)&&![current.company.owner_account_id,current.company.ceo_account_id,...(current.controllers||[])].includes(user.id))throw new MembershipError('Company management authority changed.',403);
if(body.action==='leave'&&[current.company.owner_account_id,current.company.ceo_account_id].includes(user.id))throw new MembershipError('Transfer the deed or change the CEO appointment before leaving.');
if(body.action==='request'&&await membership(reader,user.id))throw new MembershipError('You already belong to a company.');
return changed(db.prepare('UPDATE site_company_deeds SET version=version+1,updated_at=? WHERE company_id=? AND version=?').bind(now,record.id,body.version)).run(connection);
}});
const audit=details=>db.prepare('INSERT INTO corrino_company_events(id,company_id,action,actor_id,details_json,created_at) VALUES(?,?,?,?,?,?)').bind(randomUUID(),record.id,'membership-'+body.action,user.id,JSON.stringify(details),now);
if(body.action==='request')await db.batch(await membershipRequest({db,kind:'company',user,record,body,now,hasMembership:!!await membership(db,user.id),lock,audit,integration:requestIntegration}));
else if(body.action==='withdraw')await db.batch([lock(),changed(db.prepare("UPDATE site_company_requests SET status='withdrawn',updated_at=? WHERE company_id=? AND user_id=? AND status='pending'").bind(now,record.id,user.id)),...requestIntegration?.withdraw({user,record,now})||[],audit({})]);
else if(body.action==='leave'||body.action==='remove'){
if(body.action==='remove'&&!canReview)throw new MembershipError('Company management authority required.',403);
const target=body.action==='leave'?{id:user.id,username:user.username}:deed.members.find(m=>m.username===body.target);if(!target)throw new MembershipError('Choose a current company member.',404);
const guard={async run(connection){const current=await readCompanyDeed(connectionReader(db,connection),record.id);if([current.company.owner_account_id,current.company.ceo_account_id].includes(target.id))throw new MembershipError('The deed owner and current CEO cannot be removed through member controls.');return{meta:{changes:0}};}};
await db.batch([lock(),guard,changed(db.prepare('DELETE FROM site_company_members WHERE company_id=? AND user_id=?').bind(record.id,target.id)),audit({target:target.username})]);
}
else{
await db.batch(await membershipReview({db,kind:'company',user,record,body,now,canReview,lock,audit,integration:requestIntegration,access,accept:async({target})=>[
{async run(connection){if(connection)await connection.execute('SELECT id FROM site_accounts WHERE id=? FOR UPDATE',[target.user_id]);const reader=connectionReader(db,connection),current=await readCompanyDeed(reader,record.id);if(current.memberCount>=current.memberLimit)throw new MembershipError('The company membership limit has been reached.');if(await membership(reader,target.user_id))throw new MembershipError('The applicant already belongs to a company.');return{meta:{changes:0}};}},
db.prepare('INSERT INTO site_company_members(company_id,user_id,joined_at) VALUES(?,?,?)').bind(record.id,target.user_id,now),
db.prepare("UPDATE site_company_requests SET status='withdrawn',updated_at=? WHERE user_id=? AND company_id<>? AND status='pending'").bind(now,target.user_id,record.id)
]}));await requestIntegration?.afterReview?.().catch(()=>console.error('Company recruitment completion pending reconciliation'));
}
return reply({ok:true,companyId:record.id});
}catch(error){if(error instanceof MembershipError||error instanceof JarvisError)return reply({message:error.message},error.status);return reply({message:'The company application could not be confirmed.'},error.status||503);}
};
}