Add Company CP, office decision menus and clan directory cards

This commit is contained in:
unimatrixgit 2026-11-16 05:40:07 +01:00
commit 3263573f2f
3 changed files with 754 additions and 36 deletions

View file

@ -0,0 +1,13 @@
import {identity} from './auth.mjs';
const uuid=/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i;
export function createCompanyWorkspace(db,{authenticate=request=>identity(request,db)}={}){return async request=>{
const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}});
if(request.method!=='GET')return reply({message:'Method not allowed.'},405);
const user=await authenticate(request);if(!user)return reply({message:'Sign in to open Company CP.'},401);
const params=new URL(request.url).searchParams,id=params.get('company');
if([...params.keys()].some(k=>k!=='company')||params.getAll('company').length>1||id!==null&&!uuid.test(id))return reply({message:'Choose a valid company.'},400);
const {results=[]}=await db.prepare('SELECT c.id,c.slug,c.name,c.description,c.status,c.founded_by,c.ceo_account_id,a.username ceo_name,f.username founder_name FROM corrino_companies c LEFT JOIN site_accounts a ON a.id=c.ceo_account_id LEFT JOIN site_accounts f ON f.id=c.founded_by WHERE c.founded_by=? OR c.ceo_account_id=? ORDER BY c.name LIMIT 100').bind(user.id,user.id).all();
const companies=results.map(({founded_by,ceo_account_id,...company})=>({...company,role:founded_by===user.id?'Founder':'CEO'}));
if(id&&!companies.some(c=>c.id===id))return reply({message:'This company is not available to your account.'},404);
return reply({companies,selected:id||companies[0]?.id||null});
};}

View file

@ -1,7 +1,11 @@
import {COMPANY_MENU} from '../control-panel/public/cp-v2/cp-v2-company-navigation.mjs';
import {POLITICAL_TABS} from '../control-panel/public/cp-v2/cp-v2-politics-navigation.mjs';
import {MAIN_MENU} from '../scripts/main-menu.mjs';
const asset='https://www.dunerealms.com/assets/';
export const BADGE_SCOPES={
corp:COMPANY_MENU.map(([id,label])=>({label,href:'https://corp.dunerealms.com/#company/'+id,artwork:asset+'guild.webp'})),
pol:POLITICAL_TABS.flatMap(tab=>tab.pages.map(([id,label])=>({label,href:'https://www.dunerealms.com/government.html#'+tab.id+'/'+id,artwork:asset+'seals/office-landsraad.png'}))),
header:MAIN_MENU.map(([label,href,artwork])=>({label,href,artwork:asset+artwork})),
cp:[['realm','My Realm','nav-account-v2.webp'],['bureau','Imperial Bureau','nav-staff-v2.webp'],['forge','DuneForge','nav-manual-v2.webp'],['politics','Realm & Politics','seals/office-landsraad.png'],['post','Imperial Post','nav-support-v2.webp'],['bank','Imperial Postbank','imperial-postbank-v2.png'],['market','CHOAM Exchange','nav-exchange-v2.webp']].map(([id,label,artwork])=>({label,href:'https://cp.dunerealms.com/#'+id,artwork:asset+artwork})),
cp:[['realm','My Realm','nav-account-v2.webp'],['bureau','Imperial Bureau','nav-staff-v2.webp'],['forge','DuneForge','nav-manual-v2.webp'],['post','Imperial Post','nav-support-v2.webp'],['bank','Imperial Postbank','imperial-postbank-v2.png'],['market','CHOAM Exchange','nav-exchange-v2.webp']].map(([id,label,artwork])=>({label,href:'https://cp.dunerealms.com/#'+id,artwork:asset+artwork})),
clan:[['clan','My Clan','nav-clan-v2.webp'],['quests','Quests','nav-manual-v2.webp'],['kits','Clan Tailor','items/office_water.png'],['events','Events','nav-home-v2.webp']].map(([id,label,artwork])=>({label,href:'https://clans.dunerealms.com/#'+id,artwork:asset+artwork}))
};

View file

@ -4,7 +4,7 @@ import {can} from './permissions.mjs';
import {canInspectAllBankAccounts} from './postbank-recipient-policy.mjs';
import {BADGE_SCOPES} from './menu-badge-catalogue.mjs';
const KEY='main_menu_badges';
export const DEFAULT_BADGES=Object.freeze({Roster:'NEW',Exchange:'UPDATE',Politics:'NEW',Clans:'NEW',CP:'UPDATE'});
export const DEFAULT_BADGES=Object.freeze({Roster:'NEW',Exchange:'UPDATE',Politics:'NEW',Clans:'NEW',Companies:'NEW',CP:'UPDATE'});
const json=(data,status=200,publicRead=false)=>Response.json(data,{status,headers:{'Cache-Control':'no-store',...(publicRead?{'Access-Control-Allow-Origin':'*'}:{})}});
export function validateMenuBadges(items,scope='header'){
const catalogue=BADGE_SCOPES[scope];if(!catalogue||!Array.isArray(items)||items.length!==catalogue.length)throw Error('Choose one badge for every menu item.');
@ -14,7 +14,7 @@ export function validateMenuBadges(items,scope='header'){
export async function readMenuBadges(db){
let row;try{row=await db.prepare('SELECT setting_value,updated_at FROM website_settings WHERE setting_key=?').bind(KEY).first();}catch{}
const scopes=Object.fromEntries(Object.entries(BADGE_SCOPES).map(([key,items])=>[key,items.map(item=>({...item,badge:key==='header'?DEFAULT_BADGES[item.label]||'':''}))]));
if(row){try{const stored=JSON.parse(row.setting_value);if(Array.isArray(stored))scopes.header=validateMenuBadges(stored);else for(const key of Object.keys(scopes))if(stored[key])scopes[key]=validateMenuBadges(stored[key],key);}catch{}}
if(row){try{const stored=JSON.parse(row.setting_value);const saved=Array.isArray(stored)?{header:stored}:stored;for(const key of Object.keys(scopes)){if(!Array.isArray(saved[key]))continue;const choices=new Map(saved[key].filter(x=>x&&typeof x.href==='string'&&['','NEW','UPDATE'].includes(x.badge)).map(x=>[x.href,x.badge]));scopes[key]=scopes[key].map(item=>({...item,badge:choices.has(item.href)?choices.get(item.href):item.badge}));}}catch{}}
return {items:scopes.header,scopes,revision:Number(row?.updated_at)||0};
}
export function createMenuBadges(db,settings={},dependencies={}){
@ -26,13 +26,13 @@ export function createMenuBadges(db,settings={},dependencies={}){
if(!['GET','PUT'].includes(request.method))return json({message:'Method not allowed'},405);
const user=await authenticate(request);if(!user)return json({message:'Sign in first.'},401);
const [editor,bigFour]=await Promise.all([allowed(user),workspaceAccess(user)]);if(!editor&&!bigFour)return json({message:'Website publication permission required.'},403);
const editableScopes=[...(editor||bigFour?['header']:[]),...(bigFour?['cp','clan']:[])];
const editableScopes=[...(editor||bigFour?['header']:[]),...(bigFour?['cp','clan','corp','pol']:[])];
if(request.method==='GET')return json({...await readMenuBadges(db),editableScopes});
if(request.headers.get('origin')!==new URL(settings.CP_ORIGIN||'https://cp.dunerealms.com').origin)return json({message:'Origin rejected'},403);
if(!request.headers.get('content-type')?.startsWith('application/json'))return json({message:'JSON required'},415);
const raw=await request.text();if(raw.length>16384)return json({message:'Request too large'},413);
let body,items,scope;try{body=JSON.parse(raw);scope=body.scope||'header';items=validateMenuBadges(body.items,scope);}catch{return json({message:'Invalid menu badge choices.'},400);}
if(!editableScopes.includes(scope))return json({message:'CP and Clan CP badges are reserved for the Big Four and the verified Owner alias.'},403);
if(!editableScopes.includes(scope))return json({message:'Workspace badges are reserved for the Big Four and the verified Owner alias.'},403);
const previous=await readMenuBadges(db);if(body.revision!==previous.revision)return json({message:'Badges changed elsewhere. Reload before saving.'},409);
const now=Math.max(Date.now(),previous.revision+1),scopes={...previous.scopes,[scope]:items},value=JSON.stringify(scopes);
let change;try{change=previous.revision?await db.prepare('UPDATE website_settings SET setting_value=?,updated_at=? WHERE setting_key=? AND updated_at=?').bind(value,now,KEY,previous.revision).run():await db.prepare('INSERT INTO website_settings(setting_key,setting_value,updated_at) VALUES(?,?,?)').bind(KEY,value,now).run();}catch(error){if(error.code==='ER_DUP_ENTRY'||String(error.message).includes('UNIQUE'))return json({message:'Badges changed elsewhere. Reload before saving.'},409);throw error;}