web/website/control-panel/public/panel.js

97 lines
22 KiB
JavaScript

const ownerRank=key=>['owners','official_account','web_net_admin','web_net_owner'].includes(key);
let mode='login',session=null;const $=id=>document.getElementById(id),notice=message=>{$('notice').textContent=message;};
if(new URLSearchParams(location.search).get('embedded')==='1')document.body.classList.add('embedded');
async function api(path,body){const response=await fetch('/api/'+path,{method:body===undefined?'GET':'POST',headers:{'Content-Type':'application/json'},...(body===undefined?{}:{body:JSON.stringify(body)}),cache:'no-store'});const data=await response.json();if(!response.ok)throw Error(data.message||'Please try again later.');return data;}
function el(tag,text){const node=document.createElement(tag);if(text!==undefined)node.textContent=text;return node;}
async function action(button,work){button.disabled=true;notice('');try{await work();}catch(error){notice(error.message);}finally{button.disabled=false;}}
for(const next of ['login','register'])$(next+'-tab').onclick=()=>{mode=next;$('registration-age').hidden=next!=='register';$('registration-age').disabled=next!=='register';for(const tab of ['login','register'])$(tab+'-tab').setAttribute('aria-pressed',String(tab===next));$('auth-submit').textContent=next==='login'?'Sign in':'Create account';$('auth-form').elements.password.autocomplete=next==='login'?'current-password':'new-password';notice('');};
$('auth-form').onsubmit=event=>{event.preventDefault();action($('auth-submit'),async()=>{await api('auth/'+mode,Object.fromEntries(new FormData(event.target)));event.target.reset();await load();});};
$('logout').onclick=()=>action($('logout'),async()=>{await api('auth/logout',{});location.reload();});
async function linking(){const data=await api('game-link');$('identity').replaceChildren();$('game-status').textContent=data.linked?'Your Minecraft account is verified.':'No verified Minecraft UUID linked.';$('unlink-game').hidden=!data.linked;$('link-game').hidden=data.linked;if(data.linked){$('link-command').textContent='';for(const [label,value]of [['Player',data.link.minecraft_name],['Minecraft UUID',data.link.minecraft_uuid],['Eligible since',new Date(Number(data.link.first_linked_at)).toLocaleString()]])$('identity').append(el('dt',label),el('dd',value));}}
$('link-game').onclick=()=>action($('link-game'),async()=>{const data=await api('game-link',{});$('link-command').textContent=data.command;notice('Enter this command yourself in game within 10 minutes.');});
$('check-link').onclick=()=>action($('check-link'),async()=>{await linking();await rewards();});
$('unlink-game').onclick=()=>{if(confirm('Unlink this website account? UUID eligibility and previous claims will be retained to prevent duplicate rewards.'))action($('unlink-game'),async()=>{await api('game-link/unlink',{});await linking();await rewards();});};
let rewardRequest=0;async function rewards(){const token=++rewardRequest,actor=session?.id||session?.username,identity=document.getElementById("identity").textContent;const data=await api('community/rewards');if(token!==rewardRequest||actor!==(session?.id||session?.username)||identity!==document.getElementById("identity").textContent)return;for(const [id,rows]of [['available',data.available],['history',data.history]]){const root=$(id);root.replaceChildren();if(!rows.length)root.append(el('p',data.linked?'No '+(id==='available'?'unused earned codes yet.':'claims yet.'):'Link your Minecraft account to see rewards.'));for(const row of rows){const card=el('article');card.className='reward';card.append(el('h3',row.month==='season-tavren-ii'?'Tavren II Aedrecht · Season reward':row.month+' community reward'),el('p',row.reward_amount+' in-game Dunemarks'));if(row.personal_code&&row.delivery_ready===false){card.append(el('p','Season reward earned. In-game code redemption is being prepared; your reward remains reserved.'));}else if(row.personal_code){if(row.month==='season-tavren-ii')card.append(el('p','Redeem this command while playing on Arrakduin. One claim per verified Minecraft UUID.'));const command='/communitycode '+row.personal_code;card.append(el('code',command));const copy=el('button','Copy command');copy.onclick=()=>action(copy,async()=>{await navigator.clipboard.writeText(command);notice('Command copied.');});card.append(el('p'),copy);}else card.append(el('p','Claimed '+new Date(Number(row.delivered_at)).toLocaleString()));root.append(card);}}}
$('refresh-rewards').onclick=()=>action($('refresh-rewards'),rewards);
$('password-form').onsubmit=event=>{event.preventDefault();action(event.target.querySelector('button'),async()=>{await api('auth/password',Object.fromEntries(new FormData(event.target)));event.target.reset();notice('Password changed. Other sessions have been signed out.');});};
async function campaigns(){const data=await api('community/campaigns');$('campaigns').replaceChildren();for(const row of data.campaigns){const card=el('article');card.className='reward';card.append(el('h3',row.month),el('p',new Intl.NumberFormat(undefined,{style:'currency',currency:'EUR'}).format(row.received_cents/100)+' / '+new Intl.NumberFormat(undefined,{style:'currency',currency:'EUR'}).format(row.target_cents/100)),el('p',row.reward_amount+' Dunemarks per UUID · '+(row.reached_at?'Goal reached':'Not reached')));$('campaigns').append(card);}}
for(const [form,endpoint]of [['campaign-form','community/campaigns'],['total-form','community/verify-total']])$(form).onsubmit=event=>{event.preventDefault();action(event.target.querySelector('button'),async()=>{const data=Object.fromEntries(new FormData(event.target));for(const key of ['targetCents','rewardAmount','receivedCents'])if(key in data)data[key]=Number(data[key]);if(!confirm(endpoint.endsWith('verify-total')?'Confirm that this total is verified against payment records? Reaching the target unlocks rewards.':'Create this goal? The target and reward cannot be edited afterward.'))return;await api(endpoint,data);notice('Saved.');await campaigns();});};
async function load(){const data=await api('auth/session');session=data.user;document.querySelector('.account-summary').textContent=data.authenticated?'Signed in as '+data.user.username+' · '+data.user.rankLabel:'Your dunerealms.com account';$('auth').hidden=data.authenticated;$('dashboard').hidden=!data.authenticated;$('logout').hidden=!data.authenticated;$('welcome').textContent=data.authenticated?'Welcome, '+data.user.username+'.':'Welcome, traveller.';window.dispatchEvent(new CustomEvent('dune:session',{detail:session}));if(data.authenticated){const returnTo=new URLSearchParams(location.search).get('return_to');if((returnTo?.startsWith('/sso/authorize?')||/^\/memorial-login\?slug=[a-z0-9-]{3,64}$/.test(returnTo||'')||/^\/profile-login\?username=[a-z0-9_]{3,32}$/.test(returnTo||''))&&!/[\\\\\r\n]/.test(returnTo)){location.replace(returnTo);return;}const has=node=>data.user.permissions.includes(node);$('staff').hidden=!has('web.menu.administration');$('staff-tab').hidden=!has('web.menu.administration');const work=[];if(has('web.menu.game'))work.push(linking());if(has('web.menu.rewards'))work.push(rewards());if(has('web.menu.servers'))work.push(serverControls());if(has('web.community.manage'))work.push(campaigns());if(has('web.accounts.view'))work.push(accounts());await Promise.allSettled(work);}}
async function accounts(){
const [data,catalog]=await Promise.all([api('admin/accounts'),api('ranks').catch(()=>({ranks:[]}))]);
const host=$('accounts');host.replaceChildren();host.className='account-admin';
const labels=new Map(catalog.ranks.map(r=>[r.key,r.label]));
const labelFor=key=>labels.get(key)||({owners:'Owner',corestaff:'Corestaff',user:'User',vip:'VIP',game_admin:'Administrator',game_mod:'Moderator',web_legal:'Legal Team',web_sales:'Sales Team'}[key])||key.replace(/^(web|game)_/,'').replaceAll('_',' ').replace(/\b\w/g,c=>c.toUpperCase());
const keysFor=row=>row.ranks?.length?row.ranks:[row.role];
const regular=row=>keysFor(row).every(key=>['user','vip','patron_caravan','patron_guild','patron_grand'].includes(key));
const tools=el('form');tools.className='account-admin-toolbar';
const searchLabel=el('label','Find an account'),search=el('input');search.type='search';search.placeholder='Website or Minecraft name, UUID';search.setAttribute('aria-label','Search accounts');searchLabel.append(search);
const filterLabel=el('label','Website rank'),filter=el('select');filter.setAttribute('aria-label','Filter by website rank');const all=el('option','All ranks');all.value='';filter.append(all);
for(const key of [...new Set(data.accounts.flatMap(keysFor))].sort((a,b)=>labelFor(a).localeCompare(labelFor(b)))){const o=el('option',labelFor(key));o.value=key;filter.append(o);}filterLabel.append(filter);
const archiveLabel=el('label','Show removed accounts'),archiveFilter=el('input');archiveFilter.type='checkbox';archiveLabel.prepend(archiveFilter);tools.append(archiveLabel);archiveFilter.onchange=()=>render();
const go=el('button','Search');go.type='submit';go.className='account-admin-search';const reset=el('button','Reset');reset.type='button';reset.className='account-admin-secondary';tools.append(searchLabel,filterLabel,go,reset);
const summary=el('div');summary.className='account-admin-summary';summary.setAttribute('aria-live','polite');
const scroll=el('div');scroll.className='account-admin-scroll';const table=el('table');table.className='account-admin-table';
const caption=el('caption','Website accounts and their verified Minecraft identities');caption.className='account-admin-sr';table.append(caption);
const head=el('thead'),heading=el('tr');for(const title of ['Website account','Minecraft identity','Website ranks','Actions']){const th=el('th',title);th.scope='col';heading.append(th);}head.append(heading);const body=el('tbody');table.append(head,body);scroll.append(table);
const editor=el('div');editor.className='account-admin-editor';editor.hidden=true;const footnote=el('p','Showing the latest '+data.accounts.length+' loaded accounts (up to 200). Search and filters apply to this list.');footnote.className='account-admin-footnote';host.append(tools,summary,scroll,footnote,editor);
const copyText=async(button,value)=>action(button,async()=>{await navigator.clipboard.writeText(value);notice('Minecraft UUID copied.');});
function render(){
editor._closeEditor?.();body.replaceChildren();const q=search.value.trim().toLowerCase();const rows=data.accounts.filter(row=>(archiveFilter.checked||!row.archived)&&(!filter.value||keysFor(row).includes(filter.value))&&[row.username,row.minecraft_name,row.minecraft_uuid].some(value=>String(value||'').toLowerCase().includes(q)));
summary.replaceChildren();for(const [value,label]of[[rows.length,'shown'],[rows.filter(row=>row.minecraft_uuid).length,'Minecraft linked'],[rows.filter(row=>!row.minecraft_uuid).length,'not linked']]){const chip=el('span');chip.append(el('strong',String(value)),el('span',label));summary.append(chip);}
if(!rows.length){const tr=el('tr'),td=el('td','No accounts match your search.');td.colSpan=4;td.className='account-admin-empty';tr.append(td);body.append(tr);return;}
for(const row of rows){
const tr=el('tr'),name=el('td'),game=el('td'),ranks=el('td'),actions=el('td');
const identity=el('div');identity.className='account-admin-identity';const avatar=el('span');avatar.className='account-admin-avatar'+(row.minecraft_uuid?' account-admin-avatar--skin':'');const image=el('img');image.src='/api/avatars/roster/'+encodeURIComponent(row.username);image.alt='';image.loading='lazy';image.decoding='async';avatar.append(image);const text=el('div');text.append(el('strong',row.username));if(row.archived)text.append(el('small','Removed account')); if(row.username===session?.username){const own=el('small','Your account');own.className='account-admin-muted';text.append(own);}identity.append(avatar,text);name.append(identity);
const player=el('strong',row.minecraft_name||'Not linked');game.append(player);if(row.minecraft_uuid){const details=el('details');details.className='account-admin-uuid';details.append(el('summary','UUID details'),el('code',row.minecraft_uuid));const copy=el('button','Copy UUID');copy.type='button';copy.onclick=()=>copyText(copy,row.minecraft_uuid);details.append(copy);game.append(details);}else game.append(el('small','Awaiting account link'));
const chips=el('div');chips.className='account-admin-rank-chips';for(const key of keysFor(row)){const chip=el('span',labelFor(key));chip.className='account-admin-rank-chip'+(key==='owners'?' account-admin-rank-chip--owner':'');chip.title=key;chips.append(chip);}ranks.append(chips);
const actionRow=el('div');actionRow.className='account-admin-actions';if(!row.archived){const profileLink=el('a','View profile');profileLink.href='https://www.dunerealms.com/people/'+encodeURIComponent(row.username);profileLink.target='_blank';profileLink.rel='noopener';actionRow.append(profileLink);}const protectedRank=keysFor(row).some(ownerRank)||!ownerRank(session?.rank)&&Number(row.rankLevel)>=Number(session?.rankLevel);
if(session?.permissions?.includes('web.accounts.assign')&&!protectedRank){const edit=el('button','Edit ranks');edit.type='button';edit.className='account-admin-primary';edit.setAttribute('aria-label','Edit ranks for '+row.username);edit.onclick=()=>assignRank(editor,row,edit);actionRow.append(edit);}else{const protectedLabel=el('span','Protected rank');protectedLabel.className='account-admin-protected';actionRow.append(protectedLabel);}
const more=el('details');more.className='account-admin-more';more.append(el('summary','More'));const menu=el('div');menu.className='account-admin-more-menu';
if(session?.permissions?.includes('web.ranks.manage')&&regular(row)){const seals=el('button','Edit community seals');seals.type='button';seals.onclick=()=>{more.open=false;editBadges(editor,row,seals);};menu.append(seals);}else if(!regular(row)){const managed=el('p','Staff seals follow assigned ranks.');managed.className='account-admin-muted';menu.append(managed);}
if(session?.permissions?.includes('web.accounts.revoke')&&(!protectedRank||row.username===session?.username||ownerRank(session?.rank))){const revoke=el('button','Sign out sessions');revoke.type='button';revoke.className='account-admin-danger';revoke.onclick=()=>{more.open=false;if(confirm('Sign out all current sessions for '+row.username+'?'))action(revoke,async()=>{await api('admin/revoke-sessions',{userId:row.id});notice('Sessions revoked for '+row.username+'.');});};menu.append(revoke);}
if(ownerRank(session?.rank)&&!protectedRank&&row.username!==session?.username){const remove=el('button',row.archived?'Restore account':'Delete account');remove.type='button';remove.className='account-admin-danger';remove.onclick=()=>{const confirmed=prompt((row.archived?'Restore ':'Disable and archive ')+row.username+'? Receipts and audit records are retained. Type the exact username.');if(confirmed===null)return;action(remove,async()=>{const saved=await api('admin/'+(row.archived?'restore-account':'archive-account'),{userId:row.id,confirmation:confirmed});notice(saved.message);await accounts();});};menu.append(remove);}
if(session?.permissions?.includes('web.accounts.assign')&&keysFor(row).includes('crysknife')&&!row.archived){const award=el('button','Edit honour citation');award.type='button';award.onclick=()=>editHonour(editor,row,award);menu.append(award);}
if(menu.childNodes.length){more.append(menu);actionRow.append(more);}actions.append(actionRow);tr.append(name,game,ranks,actions);body.append(tr);
}
}
tools.onsubmit=event=>{event.preventDefault();render();};filter.onchange=render;reset.onclick=()=>{search.value='';filter.value='';render();};render();
}
$('refresh-accounts').onclick=()=>action($('refresh-accounts'),accounts);
load().catch(error=>notice(error.message));
// Embedded parent receives only layout information, never credentials, UUIDs or reward codes.
new ResizeObserver(()=>{if(parent!==window)for(const origin of ['https://www.dunerealms.com','https://dunerealms.com'])parent.postMessage({type:'dunerealms-account-height',height:document.documentElement.scrollHeight},origin);}).observe(document.body);
async function serverControls(){let allowed=false;try{await api('servers');allowed=true;}catch{}$('servers-tab').hidden=!allowed;$('server-operations').hidden=!allowed;const frame=$('server-controls-frame');if(allowed&&!frame.getAttribute('src'))frame.src='/servers?embedded=1';if(!allowed)frame.removeAttribute('src');}
window.addEventListener('message',event=>{const frame=$('server-controls-frame');if(event.origin!==location.origin||event.source!==frame.contentWindow||event.data?.type!=='dune-server-panel-height')return;const height=event.data.height;if(Number.isFinite(height))frame.style.height=Math.max(700,Math.min(4000,height))+'px';});
async function assignRank(host,row,button){
host._closeEditor?.();button.disabled=true;host.hidden=false;host.replaceChildren();
host._closeEditor=()=>{host.replaceChildren();host.hidden=true;button.disabled=false;};
const heading=el('h3','Website ranks · '+row.username);host.append(heading,el('p','Choose all ranks this account should hold. Website permissions combine across the selected ranks. Saving signs out previous sessions.'));
try{
const data=await api('ranks'),box=el('fieldset');box.className='account-admin-rank-picker';box.append(el('legend','Assigned ranks'));
for(const [key,title]of Object.entries(data.sections||{players:'Players',website:'Website staff',game:'Game staff',legacy:'Custom ranks'})){
const group=el('div');group.className='account-admin-rank-group';group.append(el('h4',title));
for(const rank of data.ranks.filter(rank=>(rank.section||'legacy')===key&&rank.kind==='access'&&(session.rank==='owners'||rank.level<session.rankLevel))){const label=el('label'),input=el('input');input.type='checkbox';input.value=rank.key;input.checked=(row.ranks||[row.role]).includes(rank.key);const text=el('span',rank.label);text.append(el('small',rank.key));label.append(input,text);group.append(label);}
if(group.childNodes.length>1)box.append(group);
}
const controls=el('div');controls.className='account-admin-editor-actions';const save=el('button','Save ranks');save.type='button';save.className='account-admin-primary';save.onclick=()=>action(save,async()=>{const ranks=[...box.querySelectorAll('input:checked')].map(input=>input.value);if(!ranks.length){notice('Select at least one website rank.');return;}const saved=await api('ranks/assign',{userId:row.id,ranks});notice('Ranks saved for '+row.username+'; previous sessions revoked.'+(saved.nativeSyncPending?' Team and signature update queued for retry.':''));await accounts();});const cancel=el('button','Cancel');cancel.type='button';cancel.onclick=()=>host._closeEditor();controls.append(save,cancel);host.append(box,controls);heading.tabIndex=-1;heading.focus({preventScroll:true});host.scrollIntoView({behavior:'smooth',block:'nearest'});
}catch(error){notice(error.message);host._closeEditor();}
}
async function editBadges(host,row,button){
if(!(row.ranks||[row.role]).every(rank=>['user','vip','patron_caravan','patron_guild','patron_grand'].includes(rank))){notice('Staff seals follow assigned ranks. Community recognition seals are for regular users only.');return;}
host._closeEditor?.();button.disabled=true;host.hidden=false;host.replaceChildren();host._closeEditor=()=>{host.replaceChildren();host.hidden=true;button.disabled=false;};
const heading=el('h3','Community seals · '+row.username),box=el('fieldset');box.className='account-admin-seal-picker';box.append(el('legend','Earned recognition'));
for(const [key,title]of [['alpha-tester','Alpha Tester'],['beta-tester','Beta Tester'],['launch-contributor','Launch Contributor'],['season-tavren-ii','Tavren II Aedrecht season']]){const label=el('label'),input=el('input');input.type='checkbox';input.value=key;input.checked=row.communityBadges?.includes(key);label.append(input,el('span',title));box.append(label);}
const controls=el('div');controls.className='account-admin-editor-actions';const save=el('button','Save seals');save.type='button';save.className='account-admin-primary';save.onclick=()=>action(save,async()=>{const saved=await api('badges',{userId:row.id,badges:[...box.querySelectorAll('input:checked')].map(input=>input.value)});if(saved.nativeSyncPending)notice('Seals saved; signature update queued for retry.');notice('Community seals updated for '+row.username+'.');await accounts();});const cancel=el('button','Cancel');cancel.type='button';cancel.onclick=()=>host._closeEditor();controls.append(save,cancel);host.append(heading,el('p','Dedicated Tester and VIP are earned automatically by regular users holding Alpha, Beta and Launch seals.'),box,controls);heading.tabIndex=-1;heading.focus({preventScroll:true});host.scrollIntoView({behavior:'smooth',block:'nearest'});
}
async function editHonour(host,row,button){
host._closeEditor?.();host.hidden=false;host.replaceChildren();button.disabled=true;host._closeEditor=()=>{host.hidden=true;host.replaceChildren();button.disabled=false;};
try{const response=await fetch('/api/ranks/honour?userId='+encodeURIComponent(row.id),{cache:'no-store'}),data=await response.json();if(!response.ok)throw Error(data.message);const label=el('label','Award citation · up to 20 lines'),text=el('textarea');text.rows=8;text.maxLength=2000;text.value=data.honour.citation;text.style.width='100%';label.append(text);const save=el('button','Save citation'),cancel=el('button','Cancel');save.type=cancel.type='button';save.onclick=()=>action(save,async()=>{await api('ranks/honour',{userId:row.id,citation:text.value,version:data.honour.version});notice('Honour citation saved.');host._closeEditor();});cancel.onclick=host._closeEditor;host.append(el('h3','Holy Order of The Crysknife · '+row.username),el('p','This appears on the public profile beneath the seal. Line breaks are preserved. The recipient cannot edit this award through their profile editor.'),label,save,cancel);text.focus();host.scrollIntoView({block:'nearest'});}catch(e){notice(e.message);host._closeEditor();}
}