web/website/node/company-admin.mjs
2026-11-27 23:43:05 +00:00

40 lines
4 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 {registerCompany,appointCompanyCeo} from './company-registry.mjs';
const respond=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'no-store'}});
export function accountPrefixPattern(query){return query.replaceAll('!','!!').replaceAll('%','!%').replaceAll('_','!_')+'%';}
export function createCompanyAdmin(db,origin,{authenticate=identity,authorize=accessFor,register=registerCompany,appoint=appointCompanyCeo}={}){return async request=>{
const actor=await authenticate(request,db);if(!actor)return respond({message:'Sign in first'},401);
if(request.method==='GET'){
const rights=await authorize(db,actor);
if(!rights?.nodes?.includes('web.accounts.assign'))return respond({message:'Company management permission required'},403);
const url=new URL(request.url),query=(url.searchParams.get('account')||'').trim();
if(['registry','events'].includes(url.searchParams.get('view'))){
const pageText=url.searchParams.get('page')||'1';
if(!/^[1-9][0-9]{0,5}$/.test(pageText))return respond({message:'Invalid page'},400);
const page=Number(pageText),limit=50;
try{
if(url.searchParams.get('view')==='events'){
const {results=[]}=await db.prepare(`SELECT e.id,e.company_id,c.name AS company,e.action,a.username AS actor,e.created_at FROM corrino_company_events e LEFT JOIN corrino_companies c ON c.id=e.company_id LEFT JOIN site_accounts a ON a.id=e.actor_id ORDER BY e.created_at DESC,e.id DESC LIMIT ? OFFSET ?`).bind(limit+1,(page-1)*limit).all();
return respond({events:results.slice(0,limit),page,hasMore:results.length>limit});
}
const {results=[]}=await db.prepare(`SELECT c.id,c.slug,c.name,c.description,c.status,c.founded_by,c.ceo_account_id,c.created_at,c.updated_at,f.username AS founder,a.username AS ceo FROM corrino_companies c LEFT JOIN site_accounts f ON f.id=c.founded_by LEFT JOIN site_accounts a ON a.id=c.ceo_account_id ORDER BY c.name,c.id LIMIT ? OFFSET ?`).bind(limit+1,(page-1)*limit).all();
return respond({companies:results.slice(0,limit),page,hasMore:results.length>limit,access:{node:'web.accounts.assign',allowed:true},companyRolesAvailable:false});
}catch{return respond({message:'Company registry is temporarily unavailable'},503);}
}
if(url.searchParams.has('view'))return respond({message:'Unknown company view'},400);
if(query.length<3||query.length>32||!/^[a-zA-Z0-9_]+$/.test(query))return respond({message:'Enter a valid account username (3–32 characters)'},400);
const {results}=await db.prepare("SELECT id,username FROM site_accounts WHERE username LIKE ? ESCAPE '!' AND password_hash NOT IN ('!deleted','!banned') ORDER BY username LIMIT 12").bind(accountPrefixPattern(query)).all();
return respond({accounts:results});
}
if(request.method!=='POST')return respond({message:'Method not allowed'},405);
if(request.headers.get('origin')!==origin)return respond({message:'Origin rejected'},403);
const rights=await authorize(db,actor);
if(!rights?.nodes?.includes('web.accounts.assign'))return respond({message:'Company management permission required'},403);
let body;try{body=await request.json();}catch{return respond({message:'Invalid JSON'},400);}
if(!body||typeof body!=='object'||Array.isArray(body))return respond({message:'Invalid payload'},400);
const action=body.action;if(!['register','appoint-ceo'].includes(action))return respond({message:'Unknown company action'},400);
try{if(action==='register'){const result=await register(db,{slug:body.slug,name:body.name,description:body.description,founderId:body.founderId,actorId:actor.id,authorized:true});return respond(result,201);}
const result=await appoint(db,{companyId:body.companyId,ceoId:body.ceoId,actorId:actor.id,authorized:true});return respond(result);
}catch(error){if(error instanceof TypeError||/not found|not authorized/i.test(error.message||''))return respond({message:error.message},400);if(error.code==='ER_DUP_ENTRY')return respond({message:'Company slug already registered'},409);throw error;}
};}