MC/website/node/membership-recruitment.mjs

41 lines
6 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 {clanMemberLimit} from './clan-membership-policy.mjs';
import {connectionReader} from './clan-deeds.mjs';
import {readCompanyDeed} from './company-deeds.mjs';
// Shared request/decision transaction builder. Domain adapters retain their
// authority lock, membership storage and current capacity guard.
const sources=Object.freeze({clan:{requests:'site_clan_requests',column:'clan_id'},company:{requests:'site_company_requests',column:'company_id'}});
export class MembershipError extends Error{constructor(message,status=409){super(message);this.status=status;}}
export const companyMembership=(db,userId)=>db.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();
export function clanAcceptanceStatements({db,record,target,link,now}){return [
{async run(connection){const sql="SELECT c.active,COALESCE(ch.charter_kind,'basic') charter_kind,(SELECT COUNT(*) FROM site_clan_members m WHERE m.clan_id=c.id) member_count FROM site_clans c LEFT JOIN site_clan_charters ch ON ch.clan_id=c.id WHERE c.id=?";const current=connection?(await connection.execute(sql,[record.id]))[0][0]:await db.prepare(sql).bind(record.id).first();if(!current||!current.active)throw new MembershipError('The clan is unavailable.');const limit=clanMemberLimit(current.charter_kind);if(Number(current.member_count)>=limit)throw new MembershipError(`This clan has at most ${limit} members, including the owner. An outside Consort remains a member of their own clan.`);return {success:true,meta:{changes:0}};}},
db.prepare("INSERT INTO site_clan_members(user_id,minecraft_uuid,clan_id,clan_role,joined_at) VALUES(?,?,?,'member',?)").bind(target.user_id,link.minecraft_uuid,record.id,now),
db.prepare("UPDATE site_clan_requests SET status='withdrawn',updated_at=? WHERE user_id=? AND status='pending' AND clan_id<>?").bind(now,target.user_id,record.id)
];}
export function companyAcceptanceStatements({db,record,target,now}){return [
{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 companyMembership(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)
];}
export function changed(statement){return{async run(connection){const result=await statement.run(connection);if(result.meta.changes!==1)throw new MembershipError('The membership record changed. Refresh first.');return result;}};}
export async function membershipRequest({db,kind,user,record,body,now,hasMembership,lock,audit,integration}){
const source=sources[kind];if(!source)throw TypeError('Unknown membership domain');
if(hasMembership)throw new MembershipError('You already belong to a '+kind+'.');
const pending=await db.prepare(`SELECT COUNT(*) AS total FROM ${source.requests} WHERE user_id=? AND status='pending'`).bind(user.id).first();if(Number(pending.total)>=10)throw new MembershipError('Withdraw an existing request before applying to another '+kind+'.',429);
const prior=await db.prepare(`SELECT status FROM ${source.requests} WHERE ${source.column}=? AND user_id=?`).bind(record.id,user.id).first();if(prior?.status==='pending')throw new MembershipError('Your join request is already pending.');
if(body.jarvisListingId&&!integration)throw new MembershipError('The recruitment register is unavailable.',503);
const attachment=await integration?.request({user,record,body,now})||[];
return [lock(),db.prepare(`INSERT INTO ${source.requests}(${source.column},user_id,status,created_at,updated_at) VALUES(?,?,'pending',?,?) ON CONFLICT(${source.column},user_id) DO UPDATE SET status='pending',updated_at=excluded.updated_at,decided_by=NULL`).bind(record.id,user.id,now,now),...attachment,audit({})];
}
export async function membershipReview({db,kind,user,record,body,now,canReview,lock,audit,integration,access,accept}){
const source=sources[kind];if(!source)throw TypeError('Unknown membership domain');
if(!canReview)throw new MembershipError('Only this '+kind+'’s management can review requests.',403);
if(!['accept','decline'].includes(body.decision)||typeof body.target!=='string')throw new MembershipError('Choose a pending request and decision.',400);
const target=await db.prepare(`SELECT r.user_id,a.id,a.username,a.role FROM ${source.requests} r JOIN site_accounts a ON a.id=r.user_id WHERE r.${source.column}=? AND a.username=? AND r.status='pending'`).bind(record.id,body.target).first();if(!target)throw new MembershipError('Pending request not found.',404);
const statements=[lock(),changed(db.prepare(`UPDATE ${source.requests} SET status=?,updated_at=?,decided_by=? WHERE ${source.column}=? AND user_id=? AND status='pending'`).bind(body.decision==='accept'?'accepted':'declined',now,user.id,record.id,target.user_id))];
if(body.decision==='accept'){
const link=await db.prepare('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?').bind(target.user_id).first();if(!link)throw new MembershipError('The applicant must link Minecraft before acceptance.');
if(!(await access(target)).nodes.includes('web.menu.game'))throw new MembershipError('The applicant no longer has game account access.');
statements.push(...await accept({target,link}));
}
statements.push(...await integration?.review({record,target,decision:body.decision,now})||[],audit({target:body.target,decision:body.decision}));return statements;
}