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

87 lines
14 KiB
JavaScript

import {entityControllers,entityParent} from './entity-relations.mjs';
import {readCharacterPreferences} from './character-preferences.mjs';
import {readPoliticalIdentity} from './political-identity.mjs';
import {normalisePalette} from '../control-panel/public/organisation-palette-model.mjs';
import {randomUUID} from 'node:crypto';
import {readClanCharter} from './clan-charters.mjs';
export const CLAN_DEED_SCHEMA=`CREATE TABLE IF NOT EXISTS site_clan_deeds (clan_id CHAR(36) PRIMARY KEY,parent_clan_id CHAR(36) NULL,heir_account_id CHAR(36) NULL,consort_account_id CHAR(36) NULL,heir_joined_at BIGINT NULL,consort_joined_at BIGINT NULL,envoy_account_id CHAR(36) NULL,envoy_joined_at BIGINT NULL,arms_account_id CHAR(36) NULL,arms_joined_at BIGINT NULL,claims_use_mother INTEGER NOT NULL DEFAULT 0,primary_color CHAR(7) NULL,secondary_color CHAR(7) NULL,trim_color CHAR(7) NULL,version INTEGER NOT NULL DEFAULT 1,updated_at BIGINT NOT NULL,FOREIGN KEY(clan_id) REFERENCES site_clans(id),FOREIGN KEY(parent_clan_id) REFERENCES site_clans(id),FOREIGN KEY(heir_account_id) REFERENCES site_accounts(id),FOREIGN KEY(consort_account_id) REFERENCES site_accounts(id))`;
export async function initializeClanDeeds(db,{mysql=true}={}){
await db.prepare(CLAN_DEED_SCHEMA+(mysql?' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4':'')).run();
if(mysql)for(const [column,type]of Object.entries({envoy_account_id:'CHAR(36) NULL',envoy_joined_at:'BIGINT NULL',arms_account_id:'CHAR(36) NULL',arms_joined_at:'BIGINT NULL',claims_use_mother:'INTEGER NOT NULL DEFAULT 0',primary_color:'CHAR(7) NULL',secondary_color:'CHAR(7) NULL',trim_color:'CHAR(7) NULL'})){const found=await db.prepare("SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='site_clan_deeds' AND COLUMN_NAME=?").bind(column).first();if(!found)try{await db.prepare('ALTER TABLE site_clan_deeds ADD COLUMN '+column+' '+type).run();}catch(error){if(error.errno!==1060&&error.code!=='ER_DUP_FIELDNAME')throw error;}}
await db.prepare('INSERT INTO site_clan_deeds(clan_id,updated_at) SELECT c.id,? FROM site_clans c WHERE c.active=1 AND NOT EXISTS(SELECT 1 FROM site_clan_deeds d WHERE d.clan_id=c.id)').bind(Date.now()).run();
db.clanDeedsEnabled=true;
}
export class DeedError extends Error{constructor(message,status=409){super(message);this.status=status;}}
export function clanHierarchyRoot(rows,id){
const map=new Map(rows.map(r=>[r.id,r]));let current=map.get(id),seen=new Set();
while(current){if(seen.has(current.id)||seen.size>=128)throw new DeedError('The clan hierarchy requires review.');seen.add(current.id);if(!current.parent_clan_id)return current.id;current=map.get(current.parent_clan_id);}
throw new DeedError('The clan hierarchy is unavailable.');
}
export async function readClanDeed(db,clanId,{includePolitics=false}={}){
const clan=await db.prepare('SELECT c.id,c.name,c.tag,c.description,c.home_world,c.owner_id,c.version,c.created_at,i.institution_key,d.parent_clan_id,d.heir_account_id,d.consort_account_id,d.heir_joined_at,d.consort_joined_at,d.envoy_account_id,d.envoy_joined_at,d.arms_account_id,d.arms_joined_at,d.claims_use_mother,d.primary_color,d.secondary_color,d.trim_color,d.version deed_version FROM site_clans c LEFT JOIN site_clan_deeds d ON d.clan_id=c.id LEFT JOIN site_clan_institutions i ON i.clan_id=c.id WHERE c.id=? AND c.active=1').bind(clanId).first();
if(!clan)throw new DeedError('Clan not found.',404);
const {results:hierarchy}=await db.prepare('SELECT c.id,d.parent_clan_id FROM site_clans c LEFT JOIN site_clan_deeds d ON d.clan_id=c.id WHERE c.active=1 LIMIT 501').all();if(hierarchy.length>500)throw new DeedError('The hierarchy requires a larger registry view.');
const root=clanHierarchyRoot(hierarchy,clan.id),kind=await readClanCharter(db,clanId),eligible=new Set(hierarchy.filter(c=>clanHierarchyRoot(hierarchy,c.id)===root).map(c=>c.id));
const {results:members}=await db.prepare("SELECT a.id,a.username,a.display_name,m.clan_id,m.clan_role,m.joined_at FROM site_clan_members m JOIN site_accounts a ON a.id=m.user_id JOIN site_game_links l ON l.user_id=m.user_id AND l.minecraft_uuid=m.minecraft_uuid JOIN site_clans c ON c.id=m.clan_id WHERE c.active=1 ORDER BY a.username LIMIT 5001").all();if(members.length>5000)throw new DeedError('The member registry requires review.');
const candidates=members.filter(m=>eligible.has(m.clan_id)),owner=candidates.find(m=>m.id===clan.owner_id),keyed=['original','royal'].includes(kind);
const heir=keyed?candidates.find(m=>m.id===clan.heir_account_id&&m.id!==clan.owner_id&&Number(m.joined_at)===Number(clan.heir_joined_at))||null:null,consort=members.find(m=>m.id===clan.consort_account_id&&m.id!==clan.owner_id&&Number(m.joined_at)===Number(clan.consort_joined_at))||null;
if(includePolitics)for(const person of [owner,heir,consort])if(person){person.politicalIdentity=await readPoliticalIdentity(db,person);person.characterGender=(await readCharacterPreferences(db,person.id)).ownerDefault;}
const envoy=candidates.find(m=>m.id===clan.envoy_account_id&&Number(m.joined_at)===Number(clan.envoy_joined_at))||null;
const arms=candidates.find(m=>m.id===clan.arms_account_id&&Number(m.joined_at)===Number(clan.arms_joined_at))||null;
const presentation=includePolitics?await readCharacterPreferences(db,clan.owner_id):{ownerDefault:'male',consortPortrait:'female',heirDefault:'male'};
const colors=normalisePalette(clan.primary_color&&clan.secondary_color&&clan.trim_color?{primary:clan.primary_color,secondary:clan.secondary_color,trim:clan.trim_color}:undefined,clan.institution_key||clan.home_world);return {clan,root,kind,keyed,owner,heir,consort,arms,envoy,presentation,colors,candidates,consortCandidates:members,version:Number(clan.deed_version||1)};
}
export async function clanDeedAuthority(db,userId,clanId){
try{const deed=await readClanDeed(db,clanId),mother=deed.root!==clanId?await readClanDeed(db,deed.root):deed,relation=db.companyDeedsEnabled?await entityParent(db,'clan',clanId):null,typedControllers=db.companyDeedsEnabled?await entityControllers(db,'clan',clanId):[],parentControllerIds=[...new Set([...(deed.root!==clanId?[mother.owner?.id,mother.heir?.id]:[]),...typedControllers].filter(Boolean))],hasParent=!!(relation||deed.clan.parent_clan_id);return {canManage:!deed.clan.institution_key&&(deed.owner?.id===userId||mother.owner?.id===userId||mother.heir?.id===userId||typedControllers.includes(userId)),isOwner:deed.owner?.id===userId,hasParent,parentControllerIds,deed};}catch(error){if(error instanceof DeedError)return {canManage:false,isOwner:false};throw error;}
}
export function connectionReader(db,connection){return connection?{clanDeedsEnabled:db.clanDeedsEnabled,companyDeedsEnabled:db.companyDeedsEnabled,prepare(sql){let values=[];return {bind(...args){values=args;return this;},async first(){return (await connection.execute(sql,values))[0][0]||null;},async all(){return {results:(await connection.execute(sql,values))[0]};}};}}:db;}
export function clanDeedGuard(db,userId,clanId){return {async run(connection){
if(connection)await connection.execute('SELECT id FROM site_clans WHERE id=? FOR UPDATE',[clanId]);
if(!(await clanDeedAuthority(connectionReader(db,connection),userId,clanId)).canManage)throw new DeedError('Clan deed authority changed.',403);
return {success:true,meta:{changes:1}};
}};}
export function publicDeed(deed){
const person=member=>member?{username:member.username,characterName:member.display_name?.trim()||member.username,characterGender:member.characterGender,clanId:member.clan_id,politicalIdentity:member.politicalIdentity}:null;
return {clanId:deed.clan.id,kind:deed.kind,version:deed.version,ownerDefault:deed.presentation?.ownerDefault||'male',consortPortrait:deed.presentation?.consortPortrait||'female',heirDefault:deed.presentation?.heirDefault||'male',ruler:person(deed.owner),heir:person(deed.heir),consort:person(deed.consort),arms:person(deed.arms),envoy:person(deed.envoy),parentClanId:deed.clan.parent_clan_id||null};
}
export async function clanDeedOperators(db){
if(!db.clanDeedsEnabled)return new Map();
const {results:clans}=await db.prepare('SELECT c.id,c.owner_id,d.parent_clan_id,d.heir_account_id,d.heir_joined_at,ch.charter_kind FROM site_clans c LEFT JOIN site_clan_deeds d ON d.clan_id=c.id LEFT JOIN site_clan_charters ch ON ch.clan_id=c.id WHERE c.active=1 LIMIT 501').all();if(clans.length>500)throw new DeedError('The deed registry requires review.');
const {results:members}=await db.prepare('SELECT m.user_id,m.clan_id,m.joined_at FROM site_clan_members m JOIN site_game_links l ON l.user_id=m.user_id AND l.minecraft_uuid=m.minecraft_uuid').all(),map=new Map(clans.map(c=>[c.id,c])),result=new Map();
for(const clan of clans){const root=map.get(clanHierarchyRoot(clans,clan.id)),operators=new Set([clan.owner_id,root.owner_id]);const heir=members.find(m=>m.user_id===root.heir_account_id&&Number(m.joined_at)===Number(root.heir_joined_at));if(heir&&['original','royal'].includes(root.charter_kind)&&clanHierarchyRoot(clans,heir.clan_id)===root.id)operators.add(heir.user_id);if(db.companyDeedsEnabled)for(const userId of await entityControllers(db,'clan',clan.id))operators.add(userId);result.set(clan.id,[...operators]);}return result;
}
export async function appointClanDynasty(db,user,clanId,input){
if(!input||Object.keys(input).some(k=>!['role','candidate','version','confirmed'].includes(k))||!['heir','consort','arms','envoy'].includes(input.role)||input.confirmed!==true||!Number.isSafeInteger(input.version)||input.version<1||input.candidate!==null&&typeof input.candidate!=='string')throw new DeedError('Choose and confirm a current appointment.',400);
const initial=await readClanDeed(db,clanId);if(initial.owner?.id!==user.id)throw new DeedError('Only the registered Ruler can appoint a dynastic role.',403);
if(initial.root!==clanId)throw new DeedError('Dynastic appointments are managed by the mother clan.',403);
if(input.role==='heir'&&!initial.keyed)throw new DeedError('A Keyed or Royal charter is required for an Heir.',403);
if(initial.clan.institution_key&&!['arms','envoy'].includes(input.role))throw new DeedError('Protected institution appointments follow their franchise.',403);
const chosen=input.candidate===null?null:(input.role==='consort'?initial.consortCandidates:initial.candidates).find(m=>m.username===input.candidate&&m.id!==user.id);if(input.candidate!==null&&!chosen)throw new DeedError('Choose an eligible current member for this dynastic role.',400);
if(!['arms','envoy'].includes(input.role)&&chosen&&(input.role==='heir'?initial.consort?.id:initial.heir?.id)===chosen.id)throw new DeedError('Heir and Consort must be different people.',400);
const column=({heir:'heir_account_id',consort:'consort_account_id',arms:'arms_account_id',envoy:'envoy_account_id'})[input.role],now=Date.now();
// Lock the owner clan first. Every later deed/relationship writer uses the
// same clan version lock; membership and appointments are re-read in this tx.
await db.batch([{async run(connection){
const scoped=connection?{prepare(sql){let values=[];return {bind(...args){values=args;return this;},async first(){return (await connection.execute(sql,values))[0][0]||null;},async all(){return {results:(await connection.execute(sql,values))[0]};}};}}:db;
if(connection)await connection.execute('SELECT id FROM site_clans WHERE id=? FOR UPDATE',[clanId]);
const current=await readClanDeed(scoped,clanId),candidate=chosen?(input.role==='consort'?current.consortCandidates:current.candidates).find(m=>m.id===chosen.id):null;
if(current.owner?.id!==user.id||current.version!==input.version||current.root!==clanId||current.clan.institution_key&&!['arms','envoy'].includes(input.role)||input.role==='heir'&&!current.keyed||chosen&&!candidate)throw new DeedError('The deed or clan eligibility changed. Refresh first.');
const other=input.role==='heir'?current.consort:current.heir;if(!['arms','envoy'].includes(input.role)&&candidate&&other?.id===candidate.id)throw new DeedError('The dynastic appointments changed. Refresh first.');
const result=await db.prepare('UPDATE site_clan_deeds SET '+column+'=?,'+({heir:'heir_joined_at',consort:'consort_joined_at',arms:'arms_joined_at',envoy:'envoy_joined_at'})[input.role]+'=?,version=version+1,updated_at=? WHERE clan_id=? AND version=?').bind(candidate?.id||null,candidate?Number(candidate.joined_at):null,now,clanId,input.version).run(connection);if(result.meta.changes!==1)throw new DeedError('The deed changed. Refresh first.');return result;
}},db.prepare('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)').bind(randomUUID(),user.id,'clan-dynasty-appointment',JSON.stringify({clanId,role:input.role,candidate:chosen?.username||null}),now)]);
return {ok:true};
}
export async function clanKitAuthority(db,userId,clanId){
const deed=await readClanDeed(db,clanId),management=await clanDeedAuthority(db,userId,clanId);
return {canGenerate:management.canManage||deed.arms?.id===userId,progression:deed.kind,appointment:deed.arms?.id===userId?'arms':null};
}
// Organisation election authority only. Personal ballots always remain bound to
// their authenticated voter; this projection is not an owner impersonation token.
export async function clanElectionAuthority(db,userId,clanId){
const deed=await readClanDeed(db,clanId),management=await clanDeedAuthority(db,userId,clanId);
return {canManageClanElections:management.hasParent?management.parentControllerIds.includes(userId):management.canManage||deed.envoy?.id===userId,canCastOthersPersonalVotes:false,appointment:deed.envoy?.id===userId?'envoy':null};
}
export async function clanWarAuthority(db,userId,clanId){
const deed=await readClanDeed(db,clanId),management=await clanDeedAuthority(db,userId,clanId);
return {canManageWar:management.canManage||deed.arms?.id===userId,appointment:deed.arms?.id===userId?'arms':null};
}