feat(realm): reuse shared MOTD settings for Company and Politics

This commit is contained in:
unimatrix 2026-11-17 19:58:41 +00:00
commit 323c4d67f9
2 changed files with 127 additions and 13 deletions

View file

@ -9,11 +9,14 @@ export async function initializeNews(db){
for(const [key,label] of Object.entries(NEWS_CATEGORIES))await db.prepare('INSERT INTO website_post_categories(category_key,label,artwork) VALUES(?,?,?) ON CONFLICT(category_key) DO UPDATE SET label=excluded.label').bind(key,label,'assets/news-'+(key==='unis_blog'?'news':key)+'.png').run();
// Only published release records become posts. Pending work never becomes a release announcement.
let releases=[];try{const file=JSON.parse(await readFile(new URL('../scripts/changelog.json',import.meta.url),'utf8'));releases=Array.isArray(file)?file:file.releases||[];}catch{}
// Requested official news is distinct from the development patchnote bundles.
let announcements=[];try{announcements=JSON.parse(await readFile(new URL('../scripts/news-announcements.json',import.meta.url),'utf8'));}catch{}
if(Array.isArray(announcements))for(const item of announcements)if(/^[a-z0-9-]{1,80}$/.test(item.id||'')&&typeof item.title==='string'&&typeof item.body==='string')releases.push({sourceKey:'announcement:'+item.id,category:'news',publishedAt:item.publishedAt,title:item.title,synopsis:item.body});
for(const release of releases){
const key='release:'+String(release.version).slice(0,100),existing=await db.prepare('SELECT id FROM website_posts WHERE source_key=?').bind(key).first();if(existing)continue;
const key=release.sourceKey||'release:'+String(release.version).slice(0,100),existing=await db.prepare('SELECT id FROM website_posts WHERE source_key=?').bind(key).first();if(existing)continue;
const date=Date.parse(release.publishedAt||release.date);if(!Number.isFinite(date)||date>Date.now())continue;
const body=[release.synopsis,...(release.tasks||[]).flatMap(t=>[t.title,...(t.changes||[]).map(x=>'• '+x)])].filter(Boolean).join('\n\n').slice(0,12000);
await db.prepare('INSERT INTO website_posts(id,source_key,category,title,body,status,author_id,created_at,updated_at,published_at,version) VALUES(?,?,?,?,?,?,?,?,?,?,1) ON CONFLICT(source_key) DO UPDATE SET source_key=excluded.source_key').bind(randomUUID(),key,'changelogs',String(release.title||release.version).slice(0,120),body,'published',OFFICIAL_ACCOUNT.id,date,date,date).run();
await db.prepare('INSERT INTO website_posts(id,source_key,category,title,body,status,author_id,created_at,updated_at,published_at,version) VALUES(?,?,?,?,?,?,?,?,?,?,1) ON CONFLICT(source_key) DO UPDATE SET source_key=excluded.source_key').bind(randomUUID(),key,release.category||'changelogs',String(release.title||release.version).slice(0,120),body,'published',OFFICIAL_ACCOUNT.id,date,date,date).run();
}
}
export async function forumLinks(db,posts){try{if(!posts.length)return posts;const{results}=await db.prepare('SELECT post_id,thread_id FROM forum_news_delivery WHERE post_id IN ('+posts.map(()=>'?').join(',')+") AND thread_id>0 AND state='sent'").bind(...posts.map(p=>p.id)).all();const links=new Map(results.filter(r=>Number.isSafeInteger(Number(r.thread_id))&&Number(r.thread_id)>0).map(r=>[r.post_id,'https://forums.dunerealms.com/showthread.php?tid='+Number(r.thread_id)]));return posts.map(p=>({...p,forum_url:links.get(p.id)||null}));}catch{return posts.map(p=>({...p,forum_url:null}));}}

View file

@ -0,0 +1,51 @@
import {randomUUID} from 'node:crypto';
import {identity} from './auth.mjs';
import {accessFor} from './permissions.mjs';
import {PUBLIC_OFFICES} from './public-government.mjs';
import {validateMotd} from './organisation-motd.mjs';
const uuid=/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i;
const failure=(message,status)=>Object.assign(Error(message),{status});
export function createOrganisationSettingsRoute(db,{origin='https://cp.dunerealms.com',authenticate=r=>identity(r,db),access=u=>accessFor(db,u),clock=Date.now}={}){return async request=>{
const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}}),url=new URL(request.url),match=/^\/api\/organisations\/(company|politics)\/([a-z0-9_-]{1,36})\/settings$/i.exec(url.pathname);
if(!match||url.search)return reply({message:'Settings not found.'},404);
if(!['GET','POST'].includes(request.method))return reply({message:'Method not allowed.'},405);
const user=await authenticate(request);if(!user)return reply({message:'Sign in to manage organisation settings.'},401);
if(!(await access(user)).nodes.includes('web.menu.game'))return reply({message:'Game account access required.'},403);
const [,kind,id]=match;if(kind==='company'&&!uuid.test(id)||kind==='politics'&&!PUBLIC_OFFICES.some(o=>o.key===id))return reply({message:'Organisation not found.'},404);
if(request.method==='POST'&&request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403);
try{
let input;if(request.method==='POST'){const text=await request.text();if(text.length>6000)throw failure('Settings request too large.',413);try{input=JSON.parse(text);}catch{throw failure('Invalid settings.',400);}if(!input||!['motd','identity'].includes(input.action)||!Number.isSafeInteger(input.revision)||input.revision<0)throw failure('Refresh and review the current settings.',400);}
return await db.transaction(async tx=>{
const fresh=await authenticate(request);if(fresh?.id!==user.id)throw failure('Your session changed.',403);
let organisation;
if(kind==='company'){
organisation=await tx.first("SELECT id,name,description,updated_at,founded_by,ceo_account_id FROM corrino_companies WHERE id=? AND status IN ('active','pending') FOR UPDATE",[id]);
if(!organisation||![organisation.founded_by,organisation.ceo_account_id].includes(user.id))throw failure('Company management authority required.',403);
}else{
const office=PUBLIC_OFFICES.find(o=>o.key===id),kinds=office.kind==='bene'?['bene','house']:office.kind==='guild'?['guild','court']:[office.kind],now=clock();
const terms=await tx.query("SELECT user_id,kind FROM political_office_terms WHERE faction=? AND office=? AND outcome='winner' AND starts_at<=? AND expires_at>? FOR UPDATE",[office.faction,office.office,now,now]);
const valid=terms.filter(t=>kinds.includes(t.kind));if(valid.length!==1||valid[0].user_id!==user.id)throw failure('A current unambiguous office deed is required.',403);
organisation={name:office.scope,description:office.description,updated_at:0};
}
const message=await tx.first('SELECT message,updated_at FROM organisation_motd WHERE organisation_kind=? AND organisation_id=? FOR UPDATE',[kind,id]);
if(input){
if(input.action==='identity'){
if(kind!=='company')throw failure('Protected office identity follows the office register.',403);
const name=typeof input.name==='string'?input.name.trim():'',description=typeof input.description==='string'?input.description.trim():'';
if(!name||name.length>120||description.length>1000||/[\x00-\x1f\x7f]/.test(name)||/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(description))throw failure('Enter a name up to 120 characters and description up to 1,000.',400);
if(input.revision!==Number(organisation.updated_at))throw failure('The identity changed. Refresh before saving.',409);
const now=Math.max(clock(),Number(organisation.updated_at)+1);await tx.query('UPDATE corrino_companies SET name=?,description=?,updated_at=? WHERE id=?',[name,description,now,id]);organisation={...organisation,name,description,updated_at:now};
}else{
if(input.revision!==Number(message?.updated_at||0))throw failure('The message changed. Refresh before saving.',409);
let text;try{text=validateMotd(input.message);}catch(e){throw failure(e.message,400);}
const now=Math.max(clock(),Number(message?.updated_at||0)+1);
await tx.query('INSERT INTO organisation_motd(organisation_kind,organisation_id,message,updated_by,updated_at) VALUES(?,?,?,?,?) ON DUPLICATE KEY UPDATE message=VALUES(message),updated_by=VALUES(updated_by),updated_at=VALUES(updated_at)',[kind,id,text,user.id,now]);
await tx.query('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),user.id,'organisation-motd',JSON.stringify({kind,id}),now]);
return reply({name:organisation.name,description:organisation.description,identityRevision:Number(organisation.updated_at),motd:text,motdRevision:now,canEditIdentity:kind==='company'});
}
}
if(input)await tx.query('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),user.id,'organisation-identity',JSON.stringify({kind,id}),clock()]);
return reply({name:organisation.name,description:organisation.description,identityRevision:Number(organisation.updated_at),motd:message?.message||'',motdRevision:Number(message?.updated_at||0),canEditIdentity:kind==='company'});
});
}catch(error){return reply({message:error.status?error.message:'Organisation settings are temporarily unavailable.'},error.status||503);}
};}