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

53 lines
5.3 KiB
JavaScript

import {isClandestineInstitution} from './clandestine-identity.mjs';
// Corrino Group company registry foundation. No shares or financial transfers occur here.
import {recordInitialCompanyDeed} from './company-deeds.mjs';
import {clanMemberLimit} from './clan-membership-policy.mjs';
import {randomUUID} from 'node:crypto';
export const companyRegistrySchema=Object.freeze([
`CREATE TABLE IF NOT EXISTS corrino_companies (id CHAR(36) PRIMARY KEY, slug VARCHAR(64) NOT NULL UNIQUE, name VARCHAR(120) NOT NULL, description VARCHAR(1000) NOT NULL DEFAULT '', founded_by CHAR(36) NOT NULL, ceo_account_id CHAR(36) NULL, status VARCHAR(24) NOT NULL DEFAULT 'pending', created_at BIGINT NOT NULL, updated_at BIGINT NOT NULL, INDEX company_status(status,name)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
`CREATE TABLE IF NOT EXISTS corrino_company_events (id CHAR(36) PRIMARY KEY, company_id CHAR(36) NOT NULL, action VARCHAR(32) NOT NULL, actor_id CHAR(36) NOT NULL, details_json TEXT NULL, created_at BIGINT NOT NULL, INDEX company_event_history(company_id,created_at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
]);
export async function initializeCompanyRegistry(db){for(const sql of companyRegistrySchema)await db.prepare(sql).run();}
export function validateCompanyInput({slug,name,description=''}){
if(typeof slug!=='string'||!/^[a-z][a-z0-9-]{2,63}$/.test(slug)||typeof name!=='string'||!name.trim()||name.length>120||typeof description!=='string'||description.length>1000)throw new TypeError('Invalid company details');
return {slug,name:name.trim(),description:description.trim()};
}
// Caller must verify the actor has explicit company-management permission.
const accountIdPattern=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
// Transactional checks prevent registering nonexistent founders and stale CEO changes.
export async function registerCompany(db,{slug,name,description='',founderId,actorId,authorized=false}){
if(authorized!==true||![founderId,actorId].every(v=>typeof v==='string'&&accountIdPattern.test(v)))throw new Error('Company registration not authorized');
if(typeof db.transaction!=='function')throw new Error('Transactional database required');
const input=validateCompanyInput({slug,name,description}),id=randomUUID(),now=Date.now();
return db.transaction(async tx=>{
const founder=await tx.first('SELECT id FROM site_accounts WHERE id=?',[founderId]);
if(!founder)throw new Error('Founder account not found');
await tx.query('INSERT INTO corrino_companies(id,slug,name,description,founded_by,status,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?)',[id,input.slug,input.name,input.description,founderId,'pending',now,now]);
if(db.companyDeedsEnabled)await recordInitialCompanyDeed(tx,{id,founded_by:founderId},now);
await tx.query('INSERT INTO corrino_company_events(id,company_id,action,actor_id,details_json,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),id,'register',actorId,JSON.stringify({founderId}),now]);
return {id,status:'pending'};
});
}
export async function appointCompanyCeo(db,{companyId,ceoId,actorId,authorized=false}){
if(authorized!==true||![companyId,ceoId,actorId].every(v=>typeof v==='string'&&accountIdPattern.test(v)))throw new Error('CEO appointment not authorized');
if(isClandestineInstitution('company',companyId))throw new Error('Protected institution management requires its scoped key');
if(typeof db.transaction!=='function')throw new Error('Transactional database required');
return db.transaction(async tx=>{
const company=await tx.first('SELECT id,ceo_account_id FROM corrino_companies WHERE id=? FOR UPDATE',[companyId]);
if(!company)throw new Error('Company not found');
const account=await tx.first('SELECT id FROM site_accounts WHERE id=?',[ceoId]);
if(!account)throw new Error('CEO account not found');
if(company.ceo_account_id===ceoId)return {companyId,ceoId,changed:false};
if(db.companyDeedsEnabled){
const deed=await tx.first('SELECT charter_kind FROM site_company_deeds WHERE company_id=? FOR UPDATE',[companyId]);if(!deed)throw new Error('Company deed not found');
const count=await tx.first('SELECT COUNT(*) total FROM site_company_members WHERE company_id=?',[companyId]),member=await tx.first('SELECT user_id FROM site_company_members WHERE company_id=? AND user_id=?',[companyId,ceoId]);
if(Number(count.total)+(member?0:1)>clanMemberLimit(deed.charter_kind))throw new TypeError('The CEO must fit within the company membership limit.');
}
const now=Date.now();
await tx.query('UPDATE corrino_companies SET ceo_account_id=?,updated_at=? WHERE id=?',[ceoId,now,companyId]);
if(db.companyDeedsEnabled)await tx.query('UPDATE site_company_deeds SET version=version+1,updated_at=? WHERE company_id=?',[now,companyId]);
await tx.query('INSERT INTO corrino_company_events(id,company_id,action,actor_id,details_json,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),companyId,'appoint-ceo',actorId,JSON.stringify({ceoId,previousCeoId:company.ceo_account_id||null}),now]);
return {companyId,ceoId,changed:true};
});
}
export async function listPublicCompanies(db){const {results=[]}=await db.prepare("SELECT c.id,c.slug,c.name,c.description,a.username AS ceo FROM corrino_companies c LEFT JOIN site_accounts a ON a.id=c.ceo_account_id WHERE c.status='active' ORDER BY c.name").all();return results.filter(row=>!isClandestineInstitution('company',row.id));}