Fix focused clan dashboard and connect reusable activity and treasury views

This commit is contained in:
unimatrixgit 2026-11-16 13:50:53 +01:00
commit 2879231782
10 changed files with 78 additions and 9 deletions

View file

@ -1,3 +1,4 @@
import {readClanActivity} from '../node/clan-activity.mjs';
import {CLAN_INSTITUTION_SCHEMA,institutionalClanDenial} from './clan-institutions.mjs';
import {clanEmblemUrl,CLAN_EMBLEM_SCHEMA} from './clan-emblems.mjs';
import {randomUUID} from 'node:crypto';
@ -43,7 +44,9 @@ export function createClans(db,{origin='https://cp.dunerealms.com',authenticate=
const {results:members}=await db.prepare("SELECT a.username,m.clan_role,m.joined_at FROM site_clan_members m JOIN site_accounts a ON a.id=m.user_id WHERE m.clan_id=? ORDER BY CASE m.clan_role WHEN 'owner' THEN 0 WHEN 'officer' THEN 1 ELSE 2 END,a.username").bind(record.id).all();
const role=own?.clan_id===record.id?own.clan_role:null,canReview=linked&&!record.institution&&['owner','officer'].includes(role);
const requests=canReview?(await db.prepare("SELECT a.username,r.created_at FROM site_clan_requests r JOIN site_accounts a ON a.id=r.user_id WHERE r.clan_id=? AND r.status='pending' ORDER BY r.created_at,a.username").bind(record.id).all()).results:[];
return json({clan:publicClan(record),members,requests,role,canReview,canManage:linked&&role==='owner'&&!record.institution,linked});
let activity=[],activityStatus=role?'available':'restricted';
if(role){try{activity=await readClanActivity(db,record.id);}catch{activityStatus='unavailable';}}
return json({clan:publicClan(record),members,requests,role,canReview,canManage:linked&&role==='owner'&&!record.institution,linked,activity,activityStatus});
}
if(request.headers.get('origin')!==origin)return json({message:'Request origin rejected.'},403);
let body;try{body=await request.json();}catch{return json({message:'Invalid request.'},400);}

View file

@ -0,0 +1,12 @@
// Read adapters for existing authorised services. No payment or membership writes.
export function projectClanTreasury(view,clanId){
const entity=Array.isArray(view?.entities)?view.entities.find(e=>e.kind==='clan'&&e.clanId===clanId):null;
if(!entity)throw Error('Clan bank access unavailable');
const accounts=(entity.accounts||[]).filter(a=>a.state==='active'&&a.type==='105').map(a=>{
if(typeof a.id!=='string'||!a.id||!/^DR\d{14}$/.test(a.number||'')||typeof a.available!=='string'||!/^-?\d+\.\d{2}$/.test(a.available))throw Error('Clan funds were not confirmed');
return {id:a.id,number:a.number,available:a.available};
});return {state:entity.state,accounts};
}
async function read(fetcher,path,body){const response=await fetcher(path,{method:body?'POST':'GET',credentials:'same-origin',cache:'no-store',signal:AbortSignal.timeout(10000),...(body?{headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:{})});if(!response.ok)throw Error('Service unavailable');return response.json();}
export async function loadClanTreasury(clanId,{fetcher=fetch}={}){return projectClanTreasury(await read(fetcher,'/api/bank/overview'),clanId);}
export async function loadClanMail({fetcher=fetch}={}){const result=await read(fetcher,'/api/internal-mail/messages/list',{scope:'clan',folder:'INBOX',offset:0,limit:1,unread:true});if(!Number.isSafeInteger(result.total)||result.total<0)throw Error('Unread count unavailable');return result.total;}

View file

@ -1,9 +1,10 @@
import {loadClanTreasury,loadClanMail} from './clan-dashboard-data.mjs';
import {createOrganisationDashboard} from './organisation-dashboard.mjs';
const el=(tag,text)=>{const node=document.createElement(tag);if(text!==undefined)node.textContent=text;return node;};
export function organiseClanProfile(host,data,{initialView='overview'}={}){
const nav=el('nav');nav.className='clan-profile-tabs';nav.setAttribute('aria-label','Clan profile sections');
const dedicated=new URL(location.href).searchParams.get('own')==='1';if(dedicated){const back=host.querySelector(':scope > button');if(back)back.hidden=true;}const nav=el('nav');nav.className='clan-profile-tabs';nav.setAttribute('aria-label','Clan profile sections');
const panels=new Map(),overview=el('section'),roster=el('section'),grid=el('div');overview.className='clan-profile-overview';grid.className='clan-roster-cards';
overview.append(createOrganisationDashboard({kind:'clan',organisation:data.clan,members:data.members,role:data.role,canReview:data.canReview,requests:data.requests||[],loadMailbox:data.role&&['owner','officer'].includes(data.role)?async()=>{const r=await fetch('/api/internal-mail/messages/list',{method:'POST',credentials:'same-origin',cache:'no-store',headers:{'Content-Type':'application/json'},body:JSON.stringify({scope:'clan',folder:'INBOX',offset:0,limit:1,unread:true}),signal:AbortSignal.timeout(10000)});if(!r.ok)throw Error('Mail unavailable');const result=await r.json();return result.total;}:undefined,onMembers:()=>select('roster'),onRequests:()=>select('requests')}));
overview.append(createOrganisationDashboard({kind:'clan',organisation:data.clan,members:data.members,role:data.role,canReview:data.canReview,requests:data.requests||[],activity:data.activity||[],activityStatus:data.activityStatus,loadTreasury:data.role?()=>loadClanTreasury(data.clan.id):undefined,loadMailbox:['owner','officer'].includes(data.role)?()=>loadClanMail():undefined,onMembers:()=>select('roster'),onRequests:()=>select('requests')}));
for(const node of [...host.children]){if(node.matches('img.clan-emblem,h3,span.clan-role')||node.tagName==='DIV'&&node.textContent==='['+data.clan.tag+']')node.remove();}const introduction=host.querySelector(':scope > p');if(introduction&&introduction.textContent===(data.clan.description||'No clan introduction yet.'))introduction.remove();
panels.set('overview',{label:'Overview',panel:overview});panels.set('roster',{label:'Roster',panel:roster});
const table=host.querySelector('.clan-table-scroll'),rows=[...(table?.querySelectorAll('tbody tr')||[])];
@ -15,6 +16,6 @@ export function organiseClanProfile(host,data,{initialView='overview'}={}){
const requests=host.querySelector('.clan-requests');if(requests)panels.set('requests',{label:'Join requests',panel:requests});
const settingsNodes=[...host.querySelectorAll('[data-clan-settings]')];if(settingsNodes.length){const settings=el('section');for(const node of settingsNodes)settings.append(node);panels.set('settings',{label:'Banner & leadership',panel:settings});}
for(const [id,value]of panels){value.panel.classList.add('clan-profile-panel');value.panel.dataset.clanPanel=id;const button=el('button',value.label);button.type='button';button.onclick=()=>select(id);value.button=button;nav.append(button);}
function select(id){for(const [key,{panel,button}]of panels){panel.hidden=key!==id;button.setAttribute('aria-current',key===id?'page':'false');}}
function select(id){nav.hidden=dedicated;for(const [key,{panel,button}]of panels){panel.hidden=key!==id;button.setAttribute('aria-current',key===id?'page':'false');}}
host.append(nav);for(const {panel}of panels.values())host.append(panel);select(panels.has(initialView)?initialView:'overview');
}

View file

@ -17,7 +17,7 @@ if(dashboard&&nav){dashboard.append(section);const link=el('a',clanPortalEmbedde
async function api(path='',body){const response=await fetch('/api/clans'+path,{method:body?'POST':'GET',headers:body?{'Content-Type':'application/json'}:{},...(body?{body:JSON.stringify(body)}:{}),cache:'no-store'});const data=await response.json();if(!response.ok){const error=new Error(data.message||'The clan request could not be completed.');error.status=response.status;throw error;}return data;}
function button(label,action,className=''){const node=el('button',label);node.type='button';node.className=className;node.onclick=action;return node;}
function badge(role){const node=el('span',role==='owner'?'Clan owner':role==='officer'?'Officer':'Member');node.className='clan-role clan-role-'+role;return node;}
function showDirectory(){if(details.parentElement!==section){section.insertBefore(details,scope);location.hash='#clans';}navigation++;gate.invalidate('detail');selected=null;details.hidden=true;directory.hidden=false;toolbar.hidden=false;renderDirectory();}
function showDirectory(){section.classList.remove('clan-focused-workspace');summary.hidden=false;count.hidden=false;if(details.parentElement!==section){section.insertBefore(details,scope);location.hash='#clans';}navigation++;gate.invalidate('detail');selected=null;details.hidden=true;directory.hidden=false;toolbar.hidden=false;renderDirectory();}
async function mutate(button,body,show=true){
const token=gate.begin('mutation');if(!token||!allowed)return false;const originalNavigation=navigation;
button.disabled=true;notice.textContent='Saving clan changes…';
@ -45,7 +45,7 @@ async function load(){const token=gate.begin('directory');if(!allowed||!token)re
if(state.applications.length){const applications=el('aside');applications.className='clan-callout';applications.append(el('h3','Your pending join requests'));for(const request of state.applications)applications.append(button('['+request.tag+'] '+request.name,()=>showClan(request.clan_id)));summary.append(applications);}
renderDirectory();if(!selected&&new URL(location.href).searchParams.get("own")==="1"&&state.membership)selected=state.membership.clan_id;if(selected){await showClan(selected,false);if(!gate.current(token))return false;}return true;
}catch(error){if(gate.current(token))notice.textContent=error.message;return false;}finally{if(gate.current(token))refresh.disabled=false;}}
async function showClan(id,userNavigation=true){const token=gate.begin('detail');if(!allowed||!token||!state)return false;if(userNavigation)navigation++;selected=id;try{const data=await api('/'+encodeURIComponent(id));if(!gate.current(token)||selected!==id||!state)return false;const clan=data.clan;directory.hidden=true;toolbar.hidden=true;details.hidden=false;details.replaceChildren();details.append(button('← Clan directory',showDirectory),clanEmblem(clan),el('div','['+clan.tag+']'),el('h3',clan.name),el('p',clan.description||'No clan introduction yet.'));
async function showClan(id,userNavigation=true){const token=gate.begin('detail');if(!allowed||!token||!state)return false;if(userNavigation)navigation++;selected=id;try{const data=await api('/'+encodeURIComponent(id));if(!gate.current(token)||selected!==id||!state)return false;const clan=data.clan;const focused=new URL(location.href).searchParams.get('own')==='1'&&state.membership?.clan_id===id;section.classList.toggle('clan-focused-workspace',focused);summary.hidden=focused;count.hidden=focused;directory.hidden=true;toolbar.hidden=true;details.hidden=false;details.replaceChildren();details.append(button('← Clan directory',showDirectory),clanEmblem(clan),el('div','['+clan.tag+']'),el('h3',clan.name),el('p',clan.description||'No clan introduction yet.'));
const context={clanId:clan.id,version:Number(clan.version)};if(data.role)details.append(badge(data.role));
if(clan.institution){details.append(el('p','Protected institution · '+clan.institution.memberLimit+' player places. Recruitment and management follow the institution charter.'));}if(!data.role&&!state.membership&&!clan.institution){const pending=state.applications.some(request=>request.clan_id===id);const join=button(pending?'Withdraw join request':'Request to join',()=>mutate(join,{...context,action:pending?'withdraw':'request'}));join.disabled=!data.linked&&!pending;details.append(join,el('p',pending?'Your request is waiting for a clan owner or officer.':'An owner or officer reviews requests before membership is granted.'));}
const table=el('table');table.className='clan-table';const head=el('thead'),tr=el('tr');for(const title of ['Clan member','Role','Joined',...(data.canManage?['Manage']:[])])tr.append(el('th',title));head.append(tr);table.append(head);const tbody=el('tbody');

View file

@ -0,0 +1,10 @@
// Shared display contract for clan, company and political activity adapters.
export function createActivityFeed(items=[],{emptyMessage='No activity has been recorded yet.'}={}){
const list=document.createElement('ol');list.className='organisation-activity-feed';
for(const item of items.slice(0,5)){
if(typeof item.title!=='string'||typeof item.message!=='string'||!Number.isFinite(item.createdAt))continue;
const row=document.createElement('li'),title=document.createElement('strong'),message=document.createElement('p'),time=document.createElement('time');
title.textContent=item.title;message.textContent=item.message;const date=new Date(item.createdAt);if(!Number.isFinite(date.getTime()))continue;time.dateTime=date.toISOString();time.textContent=date.toLocaleString('en-GB',{dateStyle:'medium',timeStyle:'short'});row.append(title,message,time);list.append(row);
}
if(!list.children.length){const empty=document.createElement('li');empty.textContent=emptyMessage;list.append(empty);}return list;
}

View file

@ -1,3 +1,5 @@
.organisation-dashboard{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:20px;margin:20px 0;color:#dbe3d3}.organisation-dashboard-card{min-width:0;border:1px solid #9b8b50;border-radius:15px;padding:24px;background:linear-gradient(125deg,#1c4033f5,#102b24f0);box-shadow:inset 0 0 0 4px #c7a85b0c}.organisation-dashboard-card>header{display:flex;align-items:center;flex-wrap:wrap;gap:12px;border-bottom:1px solid #b49b5140;padding-bottom:14px;margin-bottom:16px}.organisation-dashboard-card>header img{width:48px;height:48px;object-fit:contain}.organisation-dashboard-card h3{font:700 22px Georgia,serif;color:#ecd394;margin:0;flex:1}.organisation-dashboard-card p{line-height:1.65}.organisation-dashboard-card small{color:#b9c9b7;line-height:1.5}.organisation-dashboard-status{border:1px solid #ad9652;border-radius:20px;padding:5px 9px;font-size:11px;color:#dcc48a}.organisation-dashboard-welcome{grid-column:1/-1;background:linear-gradient(95deg,#0e2a23f5,#173b2fc7),url('https://www.dunerealms.com/assets/political-imperial-chamber-v1.png') center/cover}.organisation-dashboard-welcome>small{letter-spacing:.13em;color:#d6bd78}.organisation-dashboard-members{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin:18px 0}.organisation-dashboard-member{display:flex;gap:11px;align-items:center;min-width:0;text-decoration:none;color:#ead7a2!important;padding:10px;background:#0b241b80;border:1px solid #8b875c55;border-radius:9px}.organisation-dashboard-member img{width:44px;height:44px;border-radius:6px;image-rendering:pixelated}.organisation-dashboard-member span{min-width:0}.organisation-dashboard-member strong{display:block;overflow-wrap:anywhere;font-size:13px}.organisation-dashboard-member small{display:block;font-size:11px}.organisation-dashboard-request{padding:10px;border-left:2px solid #bd9f54;background:#153b2c}.organisation-dashboard-card button{margin-top:10px}@media(max-width:760px){.organisation-dashboard{grid-template-columns:minmax(0,1fr);gap:14px}.organisation-dashboard-card{padding:18px}.organisation-dashboard-card h3{font-size:20px}}@media(max-width:400px){.organisation-dashboard-members{grid-template-columns:minmax(0,1fr)}}
.clan-profile-overview>.organisation-dashboard{grid-column:1/-1}.clan-profile-overview .organisation-dashboard-card small{margin-bottom:0;text-transform:none;letter-spacing:normal}.clan-profile-overview .organisation-dashboard-member strong{font:700 13px Arial,sans-serif}.organisation-dashboard-welcome>header{flex-direction:column;align-items:center;text-align:center}.organisation-dashboard-welcome>header img{width:150px;height:150px;filter:drop-shadow(0 6px 10px #0005)}.organisation-dashboard-welcome>header h3{font-size:30px}.organisation-dashboard-welcome>p{white-space:pre-line}.organisation-dashboard-welcome>small{display:block;margin-top:16px!important}
.organisation-dashboard-card table{width:100%;border-collapse:collapse;margin-top:18px;font-size:13px}.organisation-dashboard-card th,.organisation-dashboard-card td{text-align:left;padding:11px 8px;border-bottom:1px solid #b49b5140}.organisation-dashboard-card th{color:#d8c185;font-weight:400}
.clan-focused-workspace>.clan-scope{display:none}.clan-focused-workspace>.clan-notice:empty{display:none}.clan-focused-workspace .clan-details{margin:0;padding:0}.clan-center .organisation-dashboard-card>header{display:flex!important;align-items:center;justify-content:flex-start;position:static!important;width:auto!important;min-height:0!important;height:auto!important;background:transparent!important;margin:0 0 16px;padding:0 0 14px;border:0;border-bottom:1px solid #b49b5140;box-shadow:none;gap:12px}.clan-center .organisation-dashboard-welcome>header{flex-direction:column!important;text-align:center;align-items:center!important}.clan-center .organisation-dashboard-welcome>header img{width:150px!important;height:150px!important;object-fit:contain}.clan-center .organisation-dashboard{grid-column:1/-1;width:100%;box-sizing:border-box}.clan-center .organisation-dashboard-card{box-sizing:border-box}.clan-center .organisation-dashboard-card h3{margin:0!important;line-height:1.2}
.organisation-activity-feed{list-style:none;padding:0;margin:0}.organisation-activity-feed li{padding:14px 0;border-bottom:1px solid #b49b5138}.organisation-activity-feed strong{display:block;font:700 15px Arial,sans-serif!important;color:#ead29a}.organisation-activity-feed p{margin:7px 0}.organisation-activity-feed time{font-size:11px;color:#aebdac}

View file

@ -1,7 +1,8 @@
import {createActivityFeed} from './organisation-activity.mjs';
// Shared presentation only. Callers supply verified records and existing navigation.
const el=(tag,text,cls)=>{const node=document.createElement(tag);if(text!==undefined)node.textContent=text;if(cls)node.className=cls;return node;};
const assets='https://www.dunerealms.com/assets/';
export function createOrganisationDashboard({kind='clan',organisation,members=[],role,canReview=false,requests=[],onMembers,onRequests,loadMailbox}={}){
export function createOrganisationDashboard({kind='clan',organisation,members=[],role,canReview=false,requests=[],onMembers,onRequests,loadMailbox,loadTreasury,activity=[],activityStatus}={}){
if(!document.querySelector('link[data-organisation-dashboard]')){const css=el('link');css.rel='stylesheet';css.href=new URL('./organisation-dashboard.css',import.meta.url).href;css.dataset.organisationDashboard='';document.head.append(css);}
const company=kind==='company',noun=company?'Company':'Clan',root=el('div',undefined,'organisation-dashboard');
function card(title,art,{pending=false}={}){const box=el('article',undefined,'organisation-dashboard-card'),header=el('header'),image=el('img');image.src=assets+art;image.alt='';image.width=image.height=48;header.append(image,el('h3',title));if(pending)header.append(el('span','Coming soon','organisation-dashboard-status'));box.append(header);root.append(box);return box;}
@ -11,7 +12,8 @@ export function createOrganisationDashboard({kind='clan',organisation,members=[]
for(const member of members.slice(0,8)){const link=el('a',undefined,'organisation-dashboard-member'),image=el('img'),copy=el('span');image.src='https://cp.dunerealms.com/api/avatars/face/roster/'+encodeURIComponent(member.username);image.alt='';image.width=image.height=44;image.loading='lazy';copy.append(el('strong',member.username),el('small',({owner:noun+' owner',officer:'Officer',member:'Member'})[member.clan_role||member.role]||'Member'));link.href='https://www.dunerealms.com/people/'+encodeURIComponent(member.username);link.target='_top';link.append(image,copy);faces.append(link);}people.append(faces);if(onMembers)action(people,'View all members →',onMembers);
const applications=card('Applications','nav-support-v2.webp');applications.append(el('p',canReview?(requests.length?requests.length+' '+(requests.length===1?'application awaits':'applications await')+' review.':'No applications are waiting for review.'):'Applications are reviewed by the owner and authorised officers.'));
if(canReview){for(const request of requests.slice(0,3))applications.append(el('p',request.username,'organisation-dashboard-request'));if(onRequests)action(applications,'Review applications →',onRequests);}
for(const [title,art,message] of [['News','nav-manual-v2.webp','Announcements and updates from your '+noun.toLowerCase()+' will appear here.'],['Events','nav-manual-full-v2.webp','Upcoming activities, dates and participation will appear here.'],['Treasury','imperial-postbank-v2.png','Available funds and the account reference will appear here once the authorised bank summary is connected.'],['Land & claims','clans/house-veyr-v1.png','Territory, estate anchors and claim summaries will appear here.']]){const box=card(title,art,{pending:true});box.append(el('p',message),el('small','Not connected yet · no records are shown.'));if(title==='Treasury'){const table=el('table');for(const [label,value] of [['Available funds','Not connected'],['Account','Authorised view required']]){const row=el('tr');row.append(el('th',label),el('td',value));table.append(row);}box.append(table);}}
const news=card('News & activity','nav-manual-v2.webp');news.append(createActivityFeed(activity,{emptyMessage:activityStatus==='restricted'?'Activity is visible to organisation members.':activityStatus==='unavailable'?'Activity could not be loaded.':'No clan activity has been recorded yet.'}));
for(const [title,art,message] of [['Events','nav-manual-full-v2.webp','Upcoming activities, dates and participation will appear here.'],['Treasury','imperial-postbank-v2.png','Available funds and the account reference will appear here once the authorised bank summary is connected.'],['Land & claims','clans/house-veyr-v1.png','Territory, estate anchors and claim summaries will appear here.']]){const box=card(title,art,{pending:title==='Treasury'?false:true});box.append(el('p',message),el('small','Not connected yet · no records are shown.'));if(title==='Treasury'){const table=el('table');for(const [label,value] of [['Available funds','Not connected'],['Account','Authorised view required']]){const row=el('tr');row.append(el('th',label),el('td',value));table.append(row);}box.append(table);if(loadTreasury){box.querySelectorAll('p,small').forEach(n=>n.remove());table.replaceChildren();const note=el('p','Checking authorised clan funds…');box.append(note);Promise.resolve().then(loadTreasury).then(entity=>{if(!root.isConnected)return;note.textContent=entity.state==='not_activated'?'Clan banking has not been activated.':'Current accounts · Imperial Postbank';table.replaceChildren();for(const account of entity.accounts){const row=el('tr'),link=el('a',account.number);link.href='https://cp.dunerealms.com/#bank/bank-statements/'+encodeURIComponent(account.id);link.target='_top';const cell=el('td');cell.append(link);row.append(cell,el('td',account.available+' DM available'));table.append(row);}if(!entity.accounts.length&&entity.state!=='not_activated')note.textContent='No active current accounts are visible with your bank permissions.';}).catch(()=>{if(root.isConnected){table.replaceChildren();note.textContent='Clan funds could not be confirmed. Open Imperial Postbank to check your access.';}});}else{table.replaceChildren();box.querySelector('p').textContent='Clan funds are available only with authorised banking access.';}const bank=el('a','Open Imperial Postbank →');bank.href='https://cp.dunerealms.com/#bank/bank-overview';bank.target='_top';box.append(bank);}}
const mail=card('Mailbox','imperial-post-office-v1.png'),mailStatus=el('p',loadMailbox?'Checking unread clan mail…':'Clan mail is available to the owner and authorised officers.');mailStatus.setAttribute('role','status');mail.append(mailStatus);if(loadMailbox){const link=el('a','Open clan mailbox →');link.href='https://clans.dunerealms.com/#clan/clan-mail';link.target='_top';mail.append(link);Promise.resolve().then(loadMailbox).then(count=>{if(root.isConnected)mailStatus.textContent=Number.isSafeInteger(count)&&count>=0?'You have '+count+' unread '+(count===1?'message.':'messages.'):'Unread count is unavailable.';}).catch(()=>{if(root.isConnected)mailStatus.textContent='Mail service unavailable. Open the mailbox to retry.';});}
const attention=card('Needs attention','nav-support-v2.webp');attention.append(el('p',canReview&&requests.length?requests.length+' pending '+(requests.length===1?'application needs':'applications need')+' your attention.':'No additional dashboard alerts are connected yet.'));if(canReview&&requests.length&&onRequests)action(attention,'Open pending applications →',onRequests);return root;
}

View file

@ -291,7 +291,7 @@ export function createPanel(db,settings={},dependencies={}){
return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/'+file,import.meta.url)),{headers:{'Content-Type':moduleFile?'text/javascript; charset=utf-8':file.endsWith('.css')?'text/css; charset=utf-8':'text/html; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}});
}
const file=path==='/'?'index.html':path==='/servers'?'servers.html':path.slice(1);
if(!['user-service.html','user-service-entry.mjs','user-service.css','kit-receipt-status.mjs','clan-center.html','clan-center-entry.mjs','clan-center.css','bank-transfer-view.mjs','bank-dashboard.mjs','mail-service-ui.mjs','mail-workspace.css','hosting-control.mjs','internal-mail.mjs','internal-mail.css','election-voting-view.mjs','imperial-charters-view.mjs','proclamations-view.mjs','electoral-roll-view.mjs','election-applications-view.mjs','election-rules.mjs','political-catalog.mjs','menu-ribbons.mjs','council-preview.mjs','politics.mjs','crysknife.mjs','x-news-draft.mjs','terms.html','admin-registration.mjs','mail-signature.mjs','webmail.mjs','git-control.mjs','git-control.css','site-profile.mjs','site-profile.css','servers.html','servers.js','servers.css','pages.mjs','user-page-hero.mjs','commerce-settings.mjs','shop-management.mjs','center-portals.mjs','panel-layout.mjs','embed-size.mjs','dev-request-access.mjs','center-portals.css','overview.mjs','overview.css','page-groups.mjs','ban-register.mjs','moderation-form-response.mjs','ban-record-cards.css','ban-evidence.mjs','ban-evidence.css','ranks.mjs','ranks.css','staff-manual.mjs','luckperms.mjs','community-admin.mjs','native-community.mjs','exchange.mjs','exchange.css','clans.mjs','clan-shop.mjs','house-tailor.mjs','banking.mjs','banking.css','game-ranks.mjs','upgrade-shop.mjs','kit-generator.mjs','kit-design-model.mjs','kit-equipment-editor.mjs','kit-texture-preview.mjs','kit-generator.css','kit-market.mjs','kit-market.css','kit-cart.mjs','imperial-atelier.mjs','quests.mjs','quests.css','clans.css','clan-request-gate.mjs','clan-directory-model.mjs','clan-profile-panels.mjs','organisation-dashboard.mjs','organisation-dashboard.css','quest-rewards.mjs','quest-rewards.css','inventory/inventory-view.mjs','inventory/inventory-mount.mjs','inventory/inventory.css'].includes(file))return new Response('Not found',{status:404});
if(!['user-service.html','user-service-entry.mjs','user-service.css','kit-receipt-status.mjs','clan-center.html','clan-center-entry.mjs','clan-center.css','bank-transfer-view.mjs','bank-dashboard.mjs','mail-service-ui.mjs','mail-workspace.css','hosting-control.mjs','internal-mail.mjs','internal-mail.css','election-voting-view.mjs','imperial-charters-view.mjs','proclamations-view.mjs','electoral-roll-view.mjs','election-applications-view.mjs','election-rules.mjs','political-catalog.mjs','menu-ribbons.mjs','council-preview.mjs','politics.mjs','crysknife.mjs','x-news-draft.mjs','terms.html','admin-registration.mjs','mail-signature.mjs','webmail.mjs','git-control.mjs','git-control.css','site-profile.mjs','site-profile.css','servers.html','servers.js','servers.css','pages.mjs','user-page-hero.mjs','commerce-settings.mjs','shop-management.mjs','center-portals.mjs','panel-layout.mjs','embed-size.mjs','dev-request-access.mjs','center-portals.css','overview.mjs','overview.css','page-groups.mjs','ban-register.mjs','moderation-form-response.mjs','ban-record-cards.css','ban-evidence.mjs','ban-evidence.css','ranks.mjs','ranks.css','staff-manual.mjs','luckperms.mjs','community-admin.mjs','native-community.mjs','exchange.mjs','exchange.css','clans.mjs','clan-shop.mjs','house-tailor.mjs','banking.mjs','banking.css','game-ranks.mjs','upgrade-shop.mjs','kit-generator.mjs','kit-design-model.mjs','kit-equipment-editor.mjs','kit-texture-preview.mjs','kit-generator.css','kit-market.mjs','kit-market.css','kit-cart.mjs','imperial-atelier.mjs','quests.mjs','quests.css','clans.css','clan-request-gate.mjs','clan-directory-model.mjs','clan-profile-panels.mjs','organisation-dashboard.mjs','organisation-dashboard.css','organisation-activity.mjs','clan-dashboard-data.mjs','quest-rewards.mjs','quest-rewards.css','inventory/inventory-view.mjs','inventory/inventory-mount.mjs','inventory/inventory.css'].includes(file))return new Response('Not found',{status:404});
return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/'+file,import.meta.url)),{headers:{'Content-Type':types[file.slice(file.lastIndexOf('.'))],'Cache-Control':'no-store'}});
};
}

View file

@ -0,0 +1,23 @@
const name=value=>typeof value==='string'&&/^[a-z0-9_]{3,32}$/i.test(value)?value:null;
// Deliberately project a small member-visible subset, never the raw audit payload.
export function projectClanActivity(rows,clanId){
const items=[];
for(const row of rows){let detail;try{detail=JSON.parse(row.details);}catch{continue;}
if(detail?.clanId!==clanId||!Number.isFinite(Number(row.created_at)))continue;
const actor=name(row.actor_name),target=name(detail.target);let title,message;
if(row.action==='clan-create'){title='A new banner';message=(actor||'The founder')+' established the clan.';}
else if(row.action==='clan-review'&&detail.decision==='accept'&&target){title='Member joined';message=target+' joined the clan.';}
else if(row.action==='clan-leave'&&actor){title='Member left';message=actor+' left the clan.';}
else if(row.action==='clan-remove'&&target){title='Membership ended';message=target+' is no longer a clan member.';}
else if(row.action==='clan-role'&&target&&['officer','member'].includes(detail.role)){title='Role updated';message=target+' is now '+(detail.role==='officer'?'an officer.':'a member.');}
else if(row.action==='clan-transfer'&&target){title='Leadership changed';message=target+' became the clan owner.';}
else if(row.action==='clan-edit'){title='Banner updated';message='The clan details were updated.';}
else continue;
items.push({title,message,createdAt:Number(row.created_at)});
}
return items.slice(0,5);
}
export async function readClanActivity(db,clanId){
const rows=await db.prepare("SELECT e.action,e.details,e.created_at,a.username AS actor_name FROM account_audit e LEFT JOIN site_accounts a ON a.id=e.actor_id WHERE e.action IN ('clan-create','clan-review','clan-leave','clan-remove','clan-role','clan-transfer','clan-edit') AND e.details LIKE ? ORDER BY e.created_at DESC,e.id DESC LIMIT 30").bind('%"clanId":"'+clanId+'"%').all();
return projectClanActivity(rows.results||[],clanId);
}

View file

@ -0,0 +1,16 @@
import test from 'node:test';import assert from 'node:assert/strict';
import {projectClanTreasury,loadClanMail} from '../control-panel/public/clan-dashboard-data.mjs';
import {projectClanActivity} from '../node/clan-activity.mjs';
test('treasury never substitutes another clan, personal funds or blocked accounts',()=>{
const account={id:'a',number:'DR00105123456789',type:'105',state:'active',available:'12.34'};
const view={entities:[{kind:'person',clanId:'ours',accounts:[account]},{kind:'clan',clanId:'other',accounts:[account]},{kind:'clan',clanId:'ours',state:'active',accounts:[account,{...account,id:'blocked',type:'106'},{...account,id:'closed',state:'closed'}]}]};
assert.deepEqual(projectClanTreasury(view,'ours'),{state:'active',accounts:[{id:'a',number:account.number,available:'12.34'}]});assert.throws(()=>projectClanTreasury(view,'missing'));assert.throws(()=>projectClanTreasury({entities:[{kind:'clan',clanId:'ours',accounts:[{...account,available:1234}]}]},'ours'));
});
test('clan activity projects only scoped public events and never raw audit/private requests',()=>{
const make=(action,detail={},extra={})=>({action,actor_name:'Captain',details:JSON.stringify({clanId:'ours',secret:'never expose',...detail}),created_at:100,...extra});
const data=projectClanActivity([make('clan-review',{target:'NewMember',decision:'accept'}),make('clan-review',{target:'Hidden',decision:'decline'}),make('clan-request'),make('clan-leave'),make('clan-role',{target:'Officer',role:'officer'}),make('clan-remove',{target:'Other',clanId:'other'}),make('clan-edit',{}, {details:'broken'})],'ours');
assert.equal(data.length,3);assert.equal(data[0].message,'NewMember joined the clan.');assert.equal(data[1].message,'Captain left the clan.');assert.doesNotMatch(JSON.stringify(data),/never expose|Hidden|actor_id|details/);
});
test('mail summary uses existing authorised clan scope without opening or marking messages read',async()=>{
let options;assert.equal(await loadClanMail({fetcher:async(path,opts)=>{assert.equal(path,'/api/internal-mail/messages/list');options=opts;return Response.json({total:3});}}),3);assert.deepEqual(JSON.parse(options.body),{scope:'clan',folder:'INBOX',offset:0,limit:1,unread:true});assert.equal(options.credentials,'same-origin');await assert.rejects(loadClanMail({fetcher:async()=>Response.json({total:-1})}));
});