forked from unimatrix/web
Unify deed titles, character identity and household specialist appointments
This commit is contained in:
parent
8a894faa31
commit
4a16f5c083
10 changed files with 244 additions and 95 deletions
|
|
@ -1,8 +1,11 @@
|
|||
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,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 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,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({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;
|
||||
}
|
||||
|
|
@ -12,15 +15,17 @@ export function clanHierarchyRoot(rows,id){
|
|||
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){
|
||||
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.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();
|
||||
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.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,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 {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;
|
||||
return {clan,root,kind,keyed,owner,heir,consort,candidates,consortCandidates:members,version:Number(clan.deed_version||1)};
|
||||
if(includePolitics)for(const person of [owner,heir,consort])if(person)person.politicalIdentity=await readPoliticalIdentity(db,person);
|
||||
const arms=candidates.find(m=>m.id===clan.arms_account_id&&Number(m.joined_at)===Number(clan.arms_joined_at))||null;
|
||||
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,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;return {canManage:!deed.clan.institution_key&&(deed.owner?.id===userId||mother.owner?.id===userId||mother.heir?.id===userId),isOwner:deed.owner?.id===userId,deed};}catch(error){if(error instanceof DeedError)return {canManage:false,isOwner:false};throw error;}
|
||||
|
|
@ -32,8 +37,8 @@ export function clanDeedGuard(db,userId,clanId){return {async run(connection){
|
|||
return {success:true,meta:{changes:1}};
|
||||
}};}
|
||||
export function publicDeed(deed){
|
||||
const person=member=>member?{username:member.username,clanId:member.clan_id}:null;
|
||||
return {clanId:deed.clan.id,kind:deed.kind,version:deed.version,ruler:person(deed.owner),heir:person(deed.heir),consort:person(deed.consort),parentClanId:deed.clan.parent_clan_id||null};
|
||||
const person=member=>member?{username:member.username,characterName:member.display_name?.trim()||member.username,clanId:member.clan_id,politicalIdentity:member.politicalIdentity}:null;
|
||||
return {clanId:deed.clan.id,kind:deed.kind,version:deed.version,ruler:person(deed.owner),heir:person(deed.heir),consort:person(deed.consort),arms:person(deed.arms),parentClanId:deed.clan.parent_clan_id||null};
|
||||
}
|
||||
export async function clanDeedOperators(db){
|
||||
if(!db.clanDeedsEnabled)return new Map();
|
||||
|
|
@ -42,23 +47,27 @@ export async function clanDeedOperators(db){
|
|||
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);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'].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);
|
||||
if(!input||Object.keys(input).some(k=>!['role','candidate','version','confirmed'].includes(k))||!['heir','consort','arms'].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)throw new DeedError('Protected institution appointments follow their franchise.',403);
|
||||
if(initial.clan.institution_key&&input.role!=='arms')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(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=input.role==='heir'?'heir_account_id':'consort_account_id',now=Date.now();
|
||||
if(input.role!=='arms'&&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'})[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||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(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+'=?,'+(input.role==='heir'?'heir_joined_at':'consort_joined_at')+'=?,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;
|
||||
if(current.owner?.id!==user.id||current.version!==input.version||current.root!==clanId||current.clan.institution_key&&input.role!=='arms'||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(input.role!=='arms'&&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'})[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};
|
||||
}
|
||||
|
|
|
|||
27
website/node/member-holdings.mjs
Normal file
27
website/node/member-holdings.mjs
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import {readPoliticalIdentity} from './political-identity.mjs';
|
||||
import {clanHierarchyRoot} from './clan-deeds.mjs';
|
||||
import {clanTitles} from '../control-panel/public/clan-titles.mjs';
|
||||
import {dynasticAddress} from '../control-panel/public/dynastic-address.mjs';
|
||||
const missing=e=>/no such table|doesn't exist|unknown column|no such column/i.test(e.message||'');
|
||||
// A public ownership projection, not a bank/mandate or permission source.
|
||||
export async function memberHoldings(db,target){
|
||||
const result={state:'available',clansState:'available',companiesState:'available',clans:[],companies:[],appointments:[],deeds:[],subhouses:[],address:null};let clans;
|
||||
try{clans=(await db.prepare('SELECT c.id,c.name,c.tag,c.home_world,c.owner_id,i.institution_key,d.parent_clan_id,d.heir_account_id,d.heir_joined_at,d.consort_account_id,d.consort_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 LEFT JOIN site_clan_institutions i ON i.clan_id=c.id WHERE c.active=1 ORDER BY c.name_key LIMIT 501').all()).results;if(clans.length>500)throw Error('Public clan register exceeds its current view.');}catch(error){if(!missing(error))throw error;clans=[];result.state='partial';result.clansState='unavailable';}
|
||||
const current=await db.prepare('SELECT 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 WHERE m.user_id=?').bind(target.id).first();
|
||||
const politicalIdentity=await readPoliticalIdentity(db,target);
|
||||
const rank=[],owned=new Set();
|
||||
for(const c of clans){const kind=c.charter_kind||'basic',record={id:c.id,name:c.name,tag:c.tag,kind,url:'https://www.dunerealms.com/clans/'+encodeURIComponent(c.tag),emblem:'https://cp.dunerealms.com/api/clan-emblems/'+encodeURIComponent(c.id)};let role=null;
|
||||
if(c.owner_id===target.id){result.clans.push(record);result.deeds.push(record);owned.add(c.id);role='ruler';}
|
||||
else if(c.heir_account_id===target.id&&['original','royal'].includes(kind)&¤t&&Number(current.joined_at)===Number(c.heir_joined_at)&&clanHierarchyRoot(clans,current.clan_id)===clanHierarchyRoot(clans,c.id))role='heir';
|
||||
else if(c.consort_account_id===target.id&¤t&&Number(current.joined_at)===Number(c.consort_joined_at))role='consort';
|
||||
if(role){const address=dynasticAddress({username:target.username,characterName:target.display_name,politicalIdentity}, {name:c.name,institution:c.institution_key},clanTitles({home_world:c.home_world,charterKind:kind,institution:c.institution_key}),role);result.appointments.push({...record,role,address});rank.push({address,score:({royal:30,original:20,basic:10})[kind]+({ruler:3,heir:2,consort:1})[role]});}
|
||||
}
|
||||
for(const c of clans)if(c.parent_clan_id&&owned.has(c.parent_clan_id))result.subhouses.push({id:c.id,name:c.name,tag:c.tag,parentClanId:c.parent_clan_id,url:'https://www.dunerealms.com/clans/'+encodeURIComponent(c.tag),emblem:'https://cp.dunerealms.com/api/clan-emblems/'+encodeURIComponent(c.id)});
|
||||
result.address=rank.sort((a,b)=>b.score-a.score)[0]?.address||null;
|
||||
try{
|
||||
const {results}=await db.prepare("SELECT c.id,c.name,c.slug,c.founded_by,(SELECT COALESCE(SUM(p.quantity),0) FROM corrino_share_positions p JOIN corrino_share_classes s ON s.id=p.share_class_id WHERE s.company_id=c.id AND p.account_id=?) owned_shares,(SELECT COALESCE(SUM(s.issued_shares),0) FROM corrino_share_classes s WHERE s.company_id=c.id) issued_shares FROM corrino_companies c WHERE c.status='active' AND (c.founded_by=? OR EXISTS(SELECT 1 FROM corrino_share_positions p JOIN corrino_share_classes s ON s.id=p.share_class_id WHERE s.company_id=c.id AND p.account_id=? AND p.quantity>0)) ORDER BY c.name LIMIT 101").bind(target.id,target.id,target.id).all();
|
||||
if(results.length>100)throw Error('Public company register exceeds its current view.');
|
||||
result.companies=results.filter(c=>BigInt(c.owned_shares)>0n||c.founded_by===target.id&&BigInt(c.issued_shares)===0n).map(c=>({id:c.id,name:c.name,url:'https://corp.dunerealms.com/#company/company-overview/'+encodeURIComponent(c.id),basis:BigInt(c.owned_shares)>0n?'Shareholder':'Registered founder'}));
|
||||
}catch(error){if(!missing(error))throw error;result.state='partial';result.companiesState='unavailable';}
|
||||
return result;
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
import {memberHoldings} from './member-holdings.mjs';
|
||||
import {gameStaffSeals,protectedStaffRanks} from './game-staff-seals.mjs';
|
||||
import {AWARD_LABELS,AWARD_FILES} from './recognition.mjs';
|
||||
import {politicalSeals} from './political-heraldry.mjs';
|
||||
|
|
@ -74,7 +75,8 @@ export async function memberProfileData(db,target,settings={}){
|
|||
if(office&&Number(office.expires_at)>Date.now()/1000){const known={emperor:'Emperor',house_leader:'Faction leader',specerhuis:'Specerhuis',welvaart:'House of Water',guild_staff:'Vaerkring',landsraad:'Landsraad'};for(const key of JSON.parse(office.roles_json||'[]'))if(known[key])add('office-'+key,known[key],'https://forums.dunerealms.com/assets/seals/office-'+key+'.png','Political offices');}
|
||||
const memorial=await optional(()=>db.prepare("SELECT m.slug FROM site_memorials m LEFT JOIN site_life_status l ON l.user_id=m.user_id WHERE m.user_id=? AND (l.status IS NULL OR l.status='deceased')").bind(target.id).first(),null);
|
||||
const clan=await optional(()=>db.prepare('SELECT c.id,c.name,c.tag,c.description,m.clan_role,m.joined_at,(SELECT COUNT(*) FROM site_clan_members n WHERE n.clan_id=c.id) AS member_count FROM site_clan_members m JOIN site_clans c ON c.id=m.clan_id WHERE m.user_id=? AND c.active=1').bind(target.id).first(),undefined);
|
||||
return{politicalOffices,personnelNumber:await personnelNumberFor(db,target.id),showcase,memorial:memorial?'/memorial/'+memorial.slug:null,personalSeal:namedPersonal?medals.find(m=>m.key==='personal-role'):null,username:target.username,displayName:target.display_name,joinedAt:Number(target.created_at),functions:access.organisation?.assignments||[],avatar:'https://cp.dunerealms.com/api/avatars/face/member/'+encodeURIComponent(target.username),avatarMode:'image',bio:publicProfile.bio,publicInfo:publicProfile.publicInfo,socials:publicProfile.socials,ranks,medals,forum:await publicForumFor(db,target.id),support:{status:staff?(stats?'available':'unavailable'):'not-staff',closed:stats?.totalClosed??null,departments:stats?.departments||{}},quests:{status:'placeholder',completed:null,active:null},clan:clan===undefined?{status:'unavailable'}:clan?{status:'member',emblem:'https://cp.dunerealms.com/api/clan-emblems/'+clan.id,name:clan.name,tag:clan.tag,description:clan.description,role:clan.clan_role,joinedAt:Number(clan.joined_at),members:Math.max(0,Number(clan.member_count))}:{status:'none'}};
|
||||
const holdings=await optional(()=>memberHoldings(db,target),{state:'unavailable',clans:[],companies:[],appointments:[],deeds:[],subhouses:[],address:null});
|
||||
return{holdings,characterName:target.display_name||target.username,politicalOffices,personnelNumber:await personnelNumberFor(db,target.id),showcase,memorial:memorial?'/memorial/'+memorial.slug:null,personalSeal:namedPersonal?medals.find(m=>m.key==='personal-role'):null,username:target.username,displayName:target.display_name,joinedAt:Number(target.created_at),functions:access.organisation?.assignments||[],avatar:'https://cp.dunerealms.com/api/avatars/face/member/'+encodeURIComponent(target.username),avatarMode:'image',bio:publicProfile.bio,publicInfo:publicProfile.publicInfo,socials:publicProfile.socials,ranks,medals,forum:await publicForumFor(db,target.id),support:{status:staff?(stats?'available':'unavailable'):'not-staff',closed:stats?.totalClosed??null,departments:stats?.departments||{}},quests:{status:'placeholder',completed:null,active:null},clan:clan===undefined?{status:'unavailable'}:clan?{status:'member',emblem:'https://cp.dunerealms.com/api/clan-emblems/'+clan.id,name:clan.name,tag:clan.tag,description:clan.description,role:clan.clan_role,joinedAt:Number(clan.joined_at),members:Math.max(0,Number(clan.member_count))}:{status:'none'}};
|
||||
}
|
||||
export function createMemberProfiles(db,settings={}){return async request=>{
|
||||
const from=request.headers.get('origin');if(from&&from!==origin)return json({message:'Origin rejected.'},403);
|
||||
|
|
|
|||
13
website/node/political-identity.mjs
Normal file
13
website/node/political-identity.mjs
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import {memberPoliticalOffices} from './member-political-offices.mjs';
|
||||
// Read projections only: the active office deed and the historical register are
|
||||
// separate sources. Neither a historical honour nor a title grants permissions.
|
||||
export async function readPoliticalIdentity(db,target,{clock=Date.now}={}){
|
||||
const offices=await memberPoliticalOffices(db,target,{clock});
|
||||
const poldeeds={status:offices.status,records:offices.records};
|
||||
let register={status:'available',recognitions:[]};
|
||||
try{
|
||||
const {results}=await db.prepare(`SELECT DISTINCT t.office,t.kind,t.faction FROM political_election_honours h JOIN political_office_terms t ON t.id=h.term_id AND t.player_uuid=h.player_uuid AND t.kind=h.kind AND t.faction=h.faction WHERE t.user_id=? AND t.outcome='winner' AND t.streak>=3 AND h.earned_at<=?`).bind(target.id,clock()).all();
|
||||
register.recognitions=results.map(r=>({office:r.office,kind:r.kind,faction:r.faction,title:'Ter Electus'}));
|
||||
}catch{register={status:'unavailable',recognitions:[]};}
|
||||
return {poldeeds,register};
|
||||
}
|
||||
|
|
@ -1,42 +1,42 @@
|
|||
import {publicGitFor} from './git-public.mjs';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import {mkdir,writeFile} from 'node:fs/promises';
|
||||
import {resolve,join} from 'node:path';
|
||||
import {identity} from './auth.mjs';
|
||||
import {avatarForAccount} from './avatar.mjs';
|
||||
import {json} from './game-link.mjs';
|
||||
import {evidenceMime} from '../control-panel/evidence.mjs';
|
||||
import {syncNativeProfile} from './native-profiles.mjs';
|
||||
import {honoursFor} from './honours.mjs';
|
||||
import {personnelNumberFor} from './personnel-numbers.mjs';
|
||||
export const SOCIAL_DOMAINS={website:[],discord:['discord.com','discord.gg'],youtube:['youtube.com','youtu.be'],twitch:['twitch.tv'],twitter:['twitter.com','x.com'],facebook:['facebook.com','fb.com'],github:['github.com'],dunehub:[],instagram:['instagram.com'],tiktok:['tiktok.com']};
|
||||
export function normalizeSocials(input={}){
|
||||
const socials={};for(const [key,domains]of Object.entries(SOCIAL_DOMAINS)){
|
||||
const value=input?.[key];if(!value)continue;if(typeof value!=='string')throw Error('Invalid social link');
|
||||
const url=new URL(value.trim());if(url.protocol!=='https:'||url.username||url.password||url.href.length>500||url.port&&url.port!=='443'||domains.length&&!domains.some(d=>url.hostname===d||url.hostname.endsWith('.'+d)))throw Error('Invalid social link');
|
||||
socials[key]=url.href;
|
||||
}return socials;
|
||||
}
|
||||
export async function publicProfileFor(db,userId,origin='https://cp.dunerealms.com'){
|
||||
const row=await db.prepare('SELECT bio,public_info,socials_json FROM site_profiles WHERE user_id=?').bind(userId).first();
|
||||
let socials={};try{socials=normalizeSocials(JSON.parse(row?.socials_json||'{}'));}catch{}
|
||||
const avatar=await avatarForAccount(db,userId);
|
||||
const git=await publicGitFor(db,userId);delete socials.dunehub;if(git)socials.dunehub=git.profileUrl;
|
||||
const account=await db.prepare('SELECT id,role FROM site_accounts WHERE id=?').bind(userId).first();
|
||||
return{honours:account?await honoursFor(db,account):[],bio:row?.bio||'',publicInfo:row?.public_info||'',socials,git,avatar:{...avatar,url:new URL(avatar.url,origin).href}};
|
||||
}
|
||||
export function createProfile(db,settings,origin){return async request=>{
|
||||
const user=await identity(request,db);if(!user)return json({message:'Sign in first'},401);const path=new URL(request.url).pathname;
|
||||
if(request.method==='GET'){const profile=await db.prepare('SELECT * FROM site_profiles WHERE user_id=?').bind(user.id).first();const account=await db.prepare('SELECT username,display_name FROM site_accounts WHERE id=?').bind(user.id).first();return json({profile:{...account,personnelNumber:await personnelNumberFor(db,user.id),honours:await honoursFor(db,user),bio:profile?.bio||'',birthday:profile?.birthday||'',publicBirthday:!!profile?.public_birthday,publicInfo:profile?.public_info||'',socials:JSON.parse(profile?.socials_json||'{}'),git:await publicGitFor(db,user.id),avatar:await avatarForAccount(db,user.id)}});}
|
||||
if(request.method!=='POST'||request.headers.get('origin')!==origin)return json({message:'Origin rejected'},403);
|
||||
if(path==='/api/account/avatar'){
|
||||
if(!settings.AVATAR_DIR)return json({message:'Avatar uploads are not configured'},503);let form;try{form=await request.formData();}catch{return json({message:'Invalid upload'},400);}const file=form.get('file');if(!file||typeof file.arrayBuffer!=='function'||file.size<1||file.size>2*1024*1024)return json({message:'Upload a PNG, JPEG or WebP avatar up to 2 MB'},400);const bytes=Buffer.from(await file.arrayBuffer()),mime=evidenceMime(bytes,file.name);if(!mime?.startsWith('image/'))return json({message:'Use PNG, JPEG or WebP'},400);const id=randomUUID();await mkdir(resolve(settings.AVATAR_DIR),{recursive:true,mode:0o700});await writeFile(join(resolve(settings.AVATAR_DIR),id+'.bin'),bytes,{flag:'wx',mode:0o600});await db.prepare('INSERT INTO site_profiles(user_id,socials_json,avatar_key,avatar_mime,updated_at) VALUES(?,?,?,?,?) ON CONFLICT(user_id) DO UPDATE SET avatar_key=excluded.avatar_key,avatar_mime=excluded.avatar_mime,updated_at=excluded.updated_at').bind(user.id,'{}',id,mime,Date.now()).run();return json({ok:true,avatar:await avatarForAccount(db,user.id)});
|
||||
}
|
||||
let body;try{body=await request.json();}catch{return json({message:'Invalid request'},400);}if(path==='/api/account/avatar/remove'){await db.prepare('UPDATE site_profiles SET avatar_key=NULL,avatar_mime=NULL,updated_at=? WHERE user_id=?').bind(Date.now(),user.id).run();return json({ok:true});}
|
||||
if(path!=='/api/account/profile')return json({message:'Not found'},404);
|
||||
if(typeof body.displayName!=='string'||body.displayName.trim().length<2||body.displayName.length>40||typeof body.bio!=='string'||body.bio.length>1000||typeof body.publicInfo!=='string'||body.publicInfo.length>500)return json({message:'Check your display name, bio and public information lengths'},400);
|
||||
const birthday=body.birthday||null;if(birthday&&(!/^\d{4}-\d{2}-\d{2}$/.test(birthday)||!Number.isFinite(Date.parse(birthday))||Date.parse(birthday)>Date.now()))return json({message:'Choose a valid birthday'},400);
|
||||
let socials;try{socials=normalizeSocials(body.socials);}catch{return json({message:'Use HTTPS links to the matching social service, without login details.'},400);}
|
||||
await db.batch([db.prepare('UPDATE site_accounts SET display_name=? WHERE id=?').bind(body.displayName.trim(),user.id),db.prepare('INSERT INTO site_profiles(user_id,bio,birthday,public_birthday,public_info,socials_json,updated_at) VALUES(?,?,?,?,?,?,?) ON CONFLICT(user_id) DO UPDATE SET bio=excluded.bio,birthday=excluded.birthday,public_birthday=excluded.public_birthday,public_info=excluded.public_info,socials_json=excluded.socials_json,updated_at=excluded.updated_at').bind(user.id,body.bio,birthday,body.publicBirthday?1:0,body.publicInfo,JSON.stringify(socials),Date.now())]);
|
||||
const profile=await publicProfileFor(db,user.id,origin);await syncNativeProfile({id:user.id,username:user.username,displayName:body.displayName.trim(),publicProfile:profile});return json({ok:true});
|
||||
};}
|
||||
import {publicGitFor} from './git-public.mjs';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import {mkdir,writeFile} from 'node:fs/promises';
|
||||
import {resolve,join} from 'node:path';
|
||||
import {identity} from './auth.mjs';
|
||||
import {avatarForAccount} from './avatar.mjs';
|
||||
import {json} from './game-link.mjs';
|
||||
import {evidenceMime} from '../control-panel/evidence.mjs';
|
||||
import {syncNativeProfile} from './native-profiles.mjs';
|
||||
import {honoursFor} from './honours.mjs';
|
||||
import {personnelNumberFor} from './personnel-numbers.mjs';
|
||||
export const SOCIAL_DOMAINS={website:[],discord:['discord.com','discord.gg'],youtube:['youtube.com','youtu.be'],twitch:['twitch.tv'],twitter:['twitter.com','x.com'],facebook:['facebook.com','fb.com'],github:['github.com'],dunehub:[],instagram:['instagram.com'],tiktok:['tiktok.com']};
|
||||
export function normalizeSocials(input={}){
|
||||
const socials={};for(const [key,domains]of Object.entries(SOCIAL_DOMAINS)){
|
||||
const value=input?.[key];if(!value)continue;if(typeof value!=='string')throw Error('Invalid social link');
|
||||
const url=new URL(value.trim());if(url.protocol!=='https:'||url.username||url.password||url.href.length>500||url.port&&url.port!=='443'||domains.length&&!domains.some(d=>url.hostname===d||url.hostname.endsWith('.'+d)))throw Error('Invalid social link');
|
||||
socials[key]=url.href;
|
||||
}return socials;
|
||||
}
|
||||
export async function publicProfileFor(db,userId,origin='https://cp.dunerealms.com'){
|
||||
const row=await db.prepare('SELECT bio,public_info,socials_json FROM site_profiles WHERE user_id=?').bind(userId).first();
|
||||
let socials={};try{socials=normalizeSocials(JSON.parse(row?.socials_json||'{}'));}catch{}
|
||||
const avatar=await avatarForAccount(db,userId);
|
||||
const git=await publicGitFor(db,userId);delete socials.dunehub;if(git)socials.dunehub=git.profileUrl;
|
||||
const account=await db.prepare('SELECT id,role FROM site_accounts WHERE id=?').bind(userId).first();
|
||||
return{honours:account?await honoursFor(db,account):[],bio:row?.bio||'',publicInfo:row?.public_info||'',socials,git,avatar:{...avatar,url:new URL(avatar.url,origin).href}};
|
||||
}
|
||||
export function createProfile(db,settings,origin){return async request=>{
|
||||
const user=await identity(request,db);if(!user)return json({message:'Sign in first'},401);const path=new URL(request.url).pathname;
|
||||
if(request.method==='GET'){const profile=await db.prepare('SELECT * FROM site_profiles WHERE user_id=?').bind(user.id).first();const account=await db.prepare('SELECT username,display_name FROM site_accounts WHERE id=?').bind(user.id).first();return json({profile:{...account,personnelNumber:await personnelNumberFor(db,user.id),honours:await honoursFor(db,user),bio:profile?.bio||'',birthday:profile?.birthday||'',publicBirthday:!!profile?.public_birthday,publicInfo:profile?.public_info||'',socials:JSON.parse(profile?.socials_json||'{}'),git:await publicGitFor(db,user.id),avatar:await avatarForAccount(db,user.id)}});}
|
||||
if(request.method!=='POST'||request.headers.get('origin')!==origin)return json({message:'Origin rejected'},403);
|
||||
if(path==='/api/account/avatar'){
|
||||
if(!settings.AVATAR_DIR)return json({message:'Avatar uploads are not configured'},503);let form;try{form=await request.formData();}catch{return json({message:'Invalid upload'},400);}const file=form.get('file');if(!file||typeof file.arrayBuffer!=='function'||file.size<1||file.size>2*1024*1024)return json({message:'Upload a PNG, JPEG or WebP avatar up to 2 MB'},400);const bytes=Buffer.from(await file.arrayBuffer()),mime=evidenceMime(bytes,file.name);if(!mime?.startsWith('image/'))return json({message:'Use PNG, JPEG or WebP'},400);const id=randomUUID();await mkdir(resolve(settings.AVATAR_DIR),{recursive:true,mode:0o700});await writeFile(join(resolve(settings.AVATAR_DIR),id+'.bin'),bytes,{flag:'wx',mode:0o600});await db.prepare('INSERT INTO site_profiles(user_id,socials_json,avatar_key,avatar_mime,updated_at) VALUES(?,?,?,?,?) ON CONFLICT(user_id) DO UPDATE SET avatar_key=excluded.avatar_key,avatar_mime=excluded.avatar_mime,updated_at=excluded.updated_at').bind(user.id,'{}',id,mime,Date.now()).run();return json({ok:true,avatar:await avatarForAccount(db,user.id)});
|
||||
}
|
||||
let body;try{body=await request.json();}catch{return json({message:'Invalid request'},400);}if(path==='/api/account/avatar/remove'){await db.prepare('UPDATE site_profiles SET avatar_key=NULL,avatar_mime=NULL,updated_at=? WHERE user_id=?').bind(Date.now(),user.id).run();return json({ok:true});}
|
||||
if(path!=='/api/account/profile')return json({message:'Not found'},404);
|
||||
if(typeof body.displayName!=='string'||body.displayName.trim().length<2||body.displayName.length>40||typeof body.bio!=='string'||body.bio.length>1000||typeof body.publicInfo!=='string'||body.publicInfo.length>500)return json({message:'Check your character name, bio and public information lengths'},400);
|
||||
const birthday=body.birthday||null;if(birthday&&(!/^\d{4}-\d{2}-\d{2}$/.test(birthday)||!Number.isFinite(Date.parse(birthday))||Date.parse(birthday)>Date.now()))return json({message:'Choose a valid birthday'},400);
|
||||
let socials;try{socials=normalizeSocials(body.socials);}catch{return json({message:'Use HTTPS links to the matching social service, without login details.'},400);}
|
||||
await db.batch([db.prepare('UPDATE site_accounts SET display_name=? WHERE id=?').bind(body.displayName.trim(),user.id),db.prepare('INSERT INTO site_profiles(user_id,bio,birthday,public_birthday,public_info,socials_json,updated_at) VALUES(?,?,?,?,?,?,?) ON CONFLICT(user_id) DO UPDATE SET bio=excluded.bio,birthday=excluded.birthday,public_birthday=excluded.public_birthday,public_info=excluded.public_info,socials_json=excluded.socials_json,updated_at=excluded.updated_at').bind(user.id,body.bio,birthday,body.publicBirthday?1:0,body.publicInfo,JSON.stringify(socials),Date.now())]);
|
||||
const profile=await publicProfileFor(db,user.id,origin);await syncNativeProfile({id:user.id,username:user.username,displayName:body.displayName.trim(),publicProfile:profile});return json({ok:true});
|
||||
};}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ export function createPublicClans(db){return async request=>{
|
|||
if(!['GET','HEAD'].includes(request.method))return reply({message:'Method not allowed.'},405);
|
||||
if(!/^[A-Z0-9]{2,6}$/i.test(tag)||url.search)return reply({message:'Clan not found.'},404);
|
||||
const row=await db.prepare('SELECT id FROM site_clans WHERE tag=? AND active=1').bind(tag.toUpperCase()).first();if(!row)return reply({message:'Clan not found.'},404);
|
||||
try{const deed=await readClanDeed(db,row.id),clan=deed.clan,count=await db.prepare('SELECT COUNT(*) total FROM site_clan_members WHERE clan_id=?').bind(clan.id).first();
|
||||
try{const deed=await readClanDeed(db,row.id,{includePolitics:true}),clan=deed.clan,count=await db.prepare('SELECT COUNT(*) total FROM site_clan_members WHERE clan_id=?').bind(clan.id).first();
|
||||
const result={clan:{id:clan.id,name:clan.name,tag:clan.tag,description:clan.description,homeWorld:clan.home_world,createdAt:Number(clan.created_at),memberCount:Number(count.total),emblem:clanEmblemUrl(clan.id)},members:deed.candidates.filter(m=>m.clan_id===clan.id).map(m=>({username:m.username,title:m.clan_role==='owner'?clanTitles({home_world:clan.home_world,charterKind:deed.kind,institution:clan.institution_key}).owner:m.clan_role==='officer'?'Officer':'Member'})),deed:publicDeed(deed),titles:clanTitles({home_world:clan.home_world,charterKind:deed.kind,institution:clan.institution_key})};
|
||||
return request.method==='HEAD'?new Response(null,{headers:{'Cache-Control':'no-store'}}):reply(result);
|
||||
}catch(error){if(error instanceof DeedError)return reply({message:error.message},error.status);throw error;}
|
||||
|
|
|
|||
|
|
@ -2,3 +2,5 @@
|
|||
|
||||
.profile-clan-emblem{display:block;width:110px;height:110px;object-fit:contain;margin:0 auto 18px;filter:drop-shadow(0 4px 8px #0005)}
|
||||
.profile-political-offices{border:3px double #c7a05a;background:linear-gradient(120deg,#4b252c,#261e22);box-shadow:inset 0 0 0 3px #d5ad6114}.profile-political-office-list{display:grid;gap:16px}.profile-political-office{display:flex;align-items:center;gap:24px;padding:20px;border:1px solid #b8975688;border-radius:10px;background:#f6eddd0a;min-width:0}.profile-political-office>img{width:96px;height:96px;object-fit:contain;flex-shrink:0;filter:drop-shadow(0 4px 8px #0005)}.profile-political-office small{color:#d4ba82;letter-spacing:.08em;text-transform:uppercase}.profile-political-office h3{margin:7px 0 10px}.profile-political-office strong{color:#edd7a0;font-size:13px}.profile-political-office p{margin:8px 0 0;font-size:12px}@media(max-width:520px){.profile-political-office{align-items:flex-start;flex-direction:column;gap:14px;padding:16px}.profile-political-office>img{width:80px;height:80px}}
|
||||
|
||||
#passport-title{line-height:1.2;font-size:clamp(1.6rem,3.7vw,2.8rem);overflow-wrap:break-word}.profile-header-clan-logo{display:block;width:88px;height:88px;object-fit:contain;filter:drop-shadow(0 4px 7px #0006)}.profile-holdings{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}.profile-holding-box{padding:22px;min-width:0;border:1px solid #947b43;border-radius:13px;background:linear-gradient(120deg,#213d31ec,#102922f7)}.profile-holding-box h3{font-family:Georgia,serif;color:#e7cc86;margin-top:0}.profile-holding-link{display:flex;align-items:center;gap:14px;padding:10px 0;line-height:1.5;overflow-wrap:anywhere}.profile-holding-link img{width:48px;height:48px;object-fit:contain;flex:none}.profile-holding-box>small{display:block;color:#b7c9b8}@media(max-width:650px){.profile-holdings{grid-template-columns:1fr}}
|
||||
|
|
|
|||
|
|
@ -7,5 +7,6 @@
|
|||
<section id="personal-seal-panel" class="profile-panel personal-seal-panel" hidden><div><p class="eyebrow">PERSONAL RECOGNITION</p><h2>Personal seal</h2><p>Issued in this member’s name.</p></div><div id="personal-seal"></div></section>
|
||||
<section id="order-panel" class="profile-panel profile-order" hidden><img src="/assets/seals/order-crysknife-v1.png" alt="Holy Order of the Crysknife" width="120" height="120"><div><p class="eyebrow">SERVICE BEYOND OFFICE</p><h2>Holy Order of the Crysknife</h2><p>Order membership recognises service to DuneRealms and is separate from staff authority.</p></div></section>
|
||||
<section class="profile-panel"><p class="eyebrow">SERVICE & RECOGNITION</p><h2 id="recognition-title">Seals & earned awards</h2><p id="recognition-description" class="muted">Current function seals and recorded community achievements.</p><div id="seals" class="profile-award-groups"></div></section>
|
||||
<section id="holdings-panel" class="profile-panel"><p class="eyebrow">HOUSEHOLD & ENTERPRISE</p><h2>Leadership & holdings</h2><div id="holdings" class="profile-holdings"></div></section>
|
||||
<section class="profile-panel"><p class="eyebrow">AROUND THE REALMS</p><h2>Community activity</h2><div id="community" class="profile-community"></div></section>
|
||||
</main><footer><a href="/">DuneRealms</a><nav><a href="https://support.dunerealms.com/">Support</a><a href="/rates-and-charges.html">Rates & Charges</a></nav></footer></body></html>
|
||||
|
|
|
|||
|
|
@ -12,9 +12,11 @@ function renderPoliticalOffices(host,data){
|
|||
return true;
|
||||
}
|
||||
function render(p){
|
||||
document.title=(p.displayName||p.username)+' | DuneRealms';text('passport-title',p.displayName||p.username);text('handle','@'+p.username+(p.personnelNumber?' · '+p.personnelNumber:''));text('status',p.showcase?'Verified official DuneRealms account':'DuneRealms community member');if(p.showcase){text('recognition-title','Seal & award showcase');text('recognition-description','The general DuneRealms catalogue. Personal seals and the Holy Order of the Crysknife are excluded.');}text('joined',p.joinedAt?new Date(p.joinedAt).toLocaleDateString('en-GB'):null);text('clan',p.clan?.status==='member'?p.clan.name:'No clan listed');text('forum',p.forum?.status==='linked'?p.forum.username:'Not linked');
|
||||
document.title=(p.displayName||p.username)+' | DuneRealms';text('passport-title',p.holdings?.address||p.characterName||p.displayName||p.username);text('handle','@'+p.username+(p.personnelNumber?' · '+p.personnelNumber:''));text('status',p.showcase?'Verified official DuneRealms account':'DuneRealms community member');if(p.showcase){text('recognition-title','Seal & award showcase');text('recognition-description','The general DuneRealms catalogue. Personal seals and the Holy Order of the Crysknife are excluded.');}text('joined',p.joinedAt?new Date(p.joinedAt).toLocaleDateString('en-GB'):null);text('clan',p.clan?.status==='member'?p.clan.name:'No clan listed');if(p.clan?.status==='member'){const link=el('a'),logo=el('img');link.href='https://www.dunerealms.com/clans/'+encodeURIComponent(p.clan.tag);link.title=p.clan.name;link.setAttribute('aria-label','Open '+p.clan.name+' public clan page');logo.src=p.clan.emblem;logo.alt=p.clan.name;logo.width=logo.height=88;logo.className='profile-header-clan-logo';link.append(logo);$('clan').replaceChildren(link);}
|
||||
text('forum',p.forum?.status==='linked'?p.forum.username:'Not linked');
|
||||
if(typeof p.avatar==='string'&&/^https:\/\/cp\.dunerealms\.com\/api\/avatars\//.test(p.avatar)){$('avatar').src=p.avatar;$('avatar').hidden=false;}
|
||||
for(const rank of p.ranks||[]){if(rank.label==='Unknown rank')continue;const chip=el('span',rank.label,'chip');chip.dataset.staff=String(rank.key.startsWith('org_'));$('ranks').append(chip);}
|
||||
const holdingHost=$('holdings');if(holdingHost){holdingHost.replaceChildren();const h=p.holdings||{};for(const [title,rows]of [['Leader of · Clans',h.clans],['Owner of · Companies',h.companies],['Registered deeds',h.deeds],['Daughter clans',h.subhouses]]){const box=el('article',null,'profile-holding-box');box.append(el('h3',title));for(const record of rows||[]){const link=el('a',record.name,'profile-holding-link');link.href=record.url+(title==='Registered deeds'?'#ownership-deed':'');if(record.emblem){const logo=el('img');logo.src=record.emblem;logo.alt='';logo.width=logo.height=48;link.prepend(logo);}box.append(link);if(record.basis)box.append(el('small',record.basis));}if(!rows?.length)box.append(el('p',h.state==='unavailable'||(title.includes('Companies')?h.companiesState:h.clansState)==='unavailable'?'Register temporarily unavailable.':'No records in this register.','muted'));holdingHost.append(box);}if(h.appointments?.length){const box=el('article',null,'profile-holding-box');box.append(el('h3','Dynastic appointments'));for(const appointment of h.appointments){const link=el('a',appointment.address,'profile-holding-link');link.href=appointment.url;box.append(link);}holdingHost.append(box);}}
|
||||
const functions=p.functions||[];
|
||||
for(const f of functions){const card=el('article',null,'profile-function');card.append(el('strong',f.roleLabel),el('span',f.scopeLabel));$('department').append(card);}
|
||||
if(!functions.length)$('department').append(el('p','No staff functions listed.','muted'));
|
||||
|
|
|
|||
|
|
@ -55,9 +55,9 @@ export function createApplication(db,settings={}) {
|
|||
if(Object.hasOwn(publicModeration,url.pathname))return request.method==='GET'?publicModeration[url.pathname]():new Response('Method not allowed',{status:405});
|
||||
if(url.pathname.startsWith('/memorial/')||['/memorial.css','/memorial.js'].includes(url.pathname))return memorials(request);
|
||||
if(url.pathname.startsWith('/api/public/clans/'))return publicClans(request);
|
||||
if(/^\/clans\/[a-z0-9]{2,6}\/?$/i.test(url.pathname)||['/clan-public.css','/clan-public.js','/clan-dynasty.js','/clan-dynasty.css','/dune-date.js'].includes(url.pathname)){
|
||||
if(/^\/clans\/[a-z0-9]{2,6}\/?$/i.test(url.pathname)||['/clan-public.css','/clan-public.js','/clan-dynasty.js','/dynastic-address.mjs','/clan-dynasty.css','/dune-date.js'].includes(url.pathname)){
|
||||
if(!['GET','HEAD'].includes(request.method))return new Response('Method not allowed',{status:405});
|
||||
const asset=url.pathname.startsWith('/clans/')?'clan.html':url.pathname.slice(1),shared={'clan-dynasty.js':'clan-dynasty.mjs','clan-dynasty.css':'clan-dynasty.css','dune-date.js':'dune-date.mjs'};
|
||||
const asset=url.pathname.startsWith('/clans/')?'clan.html':url.pathname.slice(1),shared={'dynastic-address.mjs':'dynastic-address.mjs','clan-dynasty.js':'clan-dynasty.mjs','clan-dynasty.css':'clan-dynasty.css','dune-date.js':'dune-date.mjs'};
|
||||
const content=request.method==='HEAD'?null:await readFile(shared[asset]?new URL('../control-panel/public/'+shared[asset],import.meta.url):new URL(asset,root));
|
||||
return new Response(asset==='clan.html'&&content?content.toString().replace('<!--SHARED_HEADER-->',SHARED_HEADER):content,{headers:{...security,'Content-Type':(asset.endsWith('.html')?'text/html':asset.endsWith('.css')?'text/css':'text/javascript')+'; charset=utf-8','Cache-Control':'no-store'}});
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff