forked from unimatrix/web
Merge pull request 'Alpha 1.0.0.7 — The Great Migration' (#299) from dev/MC:dev/alpha-1.0.0.7-the-great-migration into main
This commit is contained in:
commit
5739f81c2d
70 changed files with 1513 additions and 46 deletions
|
|
@ -27,6 +27,20 @@ jobs:
|
|||
with:
|
||||
node-version: '22'
|
||||
|
||||
- name: Prepare publication comparison
|
||||
shell: bash
|
||||
env:
|
||||
REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
BEFORE=$(node -e 'const fs=require("fs");const p=process.env.GITHUB_EVENT_PATH;const e=p&&fs.existsSync(p)?JSON.parse(fs.readFileSync(p)):{};process.stdout.write(e.before||"");')
|
||||
if [[ ! "$BEFORE" =~ ^[0-9a-f]{40}$ || "$BEFORE" =~ ^0+$ ]]; then
|
||||
git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --deepen=1 https://www.dunerealms.com/git/unimatrix/MC.git "$GITHUB_SHA"
|
||||
BEFORE=$(git rev-parse HEAD^)
|
||||
else
|
||||
git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/MC.git "$BEFORE"
|
||||
fi
|
||||
node website/scripts/publication-changes.mjs "$BEFORE" "$GITHUB_SHA"
|
||||
|
||||
- name: Verify deployment policy
|
||||
run: node --test .forgejo/tests/web-deploy.test.mjs
|
||||
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ function refresh(view){const b=el('button','Refresh');b.type='button';b.onclick=
|
|||
function priceEditor(view){if(!data.canSetPrice)return;const form=el('form');form.className='clan-form';const label=el('label','Full clan kit price · Dunemarks'),price=el('input');price.type='number';price.min=1;price.max=1000000;price.required=true;price.value=data.priceDunemarks;label.append(price);const save=el('button','Set kit price');save.type='submit';save.dataset.duneAction='admin';form.append(label,save);form.onsubmit=async e=>{e.preventDefault();const g=generation;save.disabled=true;try{const r=await fetch('/api/clans/shop/price',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({priceDunemarks:Number(price.value)})});const d=await r.json();if(!r.ok)throw Error(d.message);if(g===generation)await load();}catch(e){if(g===generation)view.status.textContent=e.message;}finally{if(g===generation)save.disabled=false;}};view.body.append(form);}
|
||||
function renderShop(v){header(v,'shops','Clan shops','Equipment commissioned under your clan banner.','nav-exchange-full-v2.webp');const card=el('article');card.className='clan-shop-card';const image=el('img');image.src='https://www.dunerealms.com/assets/clan-atelier-v1.webp';image.alt='Illustrated desert stillsuit armour display';const copy=el('div');copy.append(el('span','UNCOMMON · FOUR-PIECE SET'),el('h3',data.blueprint?.name||'Clan stillsuit'),el('strong',data.priceDunemarks+' Dunemarks'),el('p','Paid from the buyer’s Dunemarks wallet. Physical spice is not used.'));if(data.blueprint){for(const line of data.blueprint.lore)copy.append(el('p',line));const swatch=el('span',data.blueprint.color);swatch.className='clan-kit-swatch';swatch.style.backgroundColor=data.blueprint.color;copy.append(swatch,el('p','Open the Clan Shop in game to confirm payment and receive your four armour pieces.'));}else copy.append(el('p','Your clan owner or an officer must save a kit design before members can purchase it.'));card.append(image,copy);v.body.append(card);priceEditor(v);}
|
||||
function renderKits(v){header(v,'kits','House Tailor','Commission your clan’s colours and write the lore carried into the desert.','items/office_water.png');const g=generation,mount=createHouseTailor({data,save:api,isCurrent:()=>g===generation&&mount.element.isConnected});v.body.append(mount.element);}
|
||||
function renderBank(v){header(v,'bank','Clan Treasury','Your clan’s Dunemarks treasury and recorded transactions.','dunemark-icon-64.png');v.body.classList.add('imperial-bank-view');const brand=el('img');brand.src='/assets/imperial-postbank-v2.png';brand.alt='Imperial Postbank · Part of Corrino Group';brand.className='imperial-bank-brand';brand.width=480;v.body.append(brand);refresh(v);if(!data.bankAvailable){v.body.append(el('p','The Dunemarks bank connection is temporarily unavailable.'));return;}const stats=el('div');stats.className='clan-stat-grid';const total=el('article');total.append(el('small','CLAN BALANCE · DUNEMARKS'),el('strong',data.bank.balanceDunemarks+' DM'));const access=el('article');access.append(el('small','YOUR BANK ACCESS'),el('strong',['owner','officer'].includes(data.clan.role)?'Officer':'Member'));stats.append(total,access);const account=el('article');account.className='imperial-account-card';account.append(el('small','CLAN ACCOUNT NUMBER'),el('strong',data.bank.accountNumber),el('p',data.clan.name));v.body.append(account,stats,el('p','Deposit and withdraw Dunemarks in game. Bank withdrawals require the clan owner or an officer. No physical spice is used.'),el('h3','Transaction ledger'));const scroll=el('div');scroll.className='clan-table-scroll';const table=el('table');table.className='clan-table';const head=el('tr');for(const t of ['Date','Entry','From account','To account','Dunemarks','Balance after'])head.append(el('th',t));table.append(head);for(const row of data.bank.ledger){const tr=el('tr');tr.append(el('td',new Date(Number(row.createdAt)).toLocaleString()),el('td',row.kind),el('td',row.amountDunemarks.startsWith('-')?data.bank.accountNumber:'Not recorded'),el('td',row.amountDunemarks.startsWith('-')?'Not recorded':data.bank.accountNumber),el('td',row.amountDunemarks),el('td',row.balanceDunemarks));table.append(tr);}scroll.append(table);v.body.append(scroll);if(!data.bank.ledger.length)v.body.append(el('p','No bank transactions recorded yet.'));}
|
||||
function renderBank(v){header(v,'bank','Clan Banking','Manage your authorised clan accounts in Imperial Postbank.','imperial-postbank-v2.png');const link=el('a','Open Imperial Postbank');link.href='https://cp.dunerealms.com/#bank/bank-overview';link.target='_top';v.body.append(link);}
|
||||
function questMenu(v,current){const nav=el('nav');nav.className='quest-submenu';nav.setAttribute('aria-label','Quest categories');for(const[id,label]of [['player','Player Quests'],['clan','Clan Quests'],['guild','Spacing Guild Quests']]){const a=el('a',label);if(data.member||id==='player')a.href='#clan-quests-'+id;else{a.setAttribute('aria-disabled','true');a.title='Join a clan to unlock this section.';}if(current===id)a.setAttribute('aria-current','page');nav.append(a);}v.body.append(nav);}
|
||||
function placeholders(v,kind){const labels={player:['Personal quest journal','Track your own objectives and plan your next crossing.'],clan:['Clan expedition ledger','Coordinate shared objectives and clan contributions.'],guild:['Spacing Guild contracts','Personal assignments and contracts undertaken by your clan.']};header(v,'quests',...labels[kind],'nav-manual-full-v2.webp');questMenu(v,kind);if(kind==='player'){const host=el('div');v.body.append(host);mountPersonalKitArc(host);return;}const banner=el('aside');banner.className='quest-preview-notice';banner.append(el('strong','LAYOUT PREVIEW'),el('p','Example planning material only. These entries are not active quests and grant no rewards.'));v.body.append(banner);if(kind==='player'){const live=el('a','Open your live quest journal');live.href='#quests';v.body.append(live);}const stats=el('div');stats.className='clan-stat-grid';for(const label of ['Active objectives','Completed journeys','Rewards ready']){const c=el('article');c.append(el('small',label),el('strong','—'));stats.append(c);}v.body.append(stats);const tools=el('nav');tools.className='quest-preview-filters';for(const label of ['Overview','In progress','Completed','Archived']){const b=el('button',label);b.type='button';b.disabled=true;tools.append(b);}v.body.append(tools);const cards=el('div');cards.className='quest-plan-grid';const examples=kind==='player'?[['Desert field training','Prepare a stillsuit, learn the safe routes and record a first expedition.','Personal objectives'],['A traveller’s provisions','Organise supplies before your next planetary crossing.','Personal checklist']]:kind==='clan'?[['Raise the clan banner','Plan a shared expedition and assign contributions to clan members.','Clan objectives'],['Caravan provisions','Review collective supplies and coordinate your clan’s next journey.','Member contributions']]:[['Personal Guild contract','A reserved place for individual travel and courier assignments.','Player contracts'],['Clan Guild charter','A reserved place for coordinated contracts undertaken under your clan banner.','Clan contracts']];for(const[title,description,scope]of examples){const card=el('article'),img=el('img');img.src='https://www.dunerealms.com/assets/'+(kind==='guild'?'guild.webp':'nav-manual-full-v2.webp');img.alt='';card.append(img,el('small','PLANNED · '+scope),el('h3',title),el('p',description),el('p','Objectives · — Progress · — Reward · Not configured'));const button=el('button','Details coming soon');button.type='button';button.disabled=true;card.append(button);cards.append(card);}v.body.append(cards);}
|
||||
async function render(id){const v=views[id];if(!v||!data)return;v.status.textContent='';if(!data.member&&!id.startsWith('clan-quests')){header(v,id.slice(5),'Join a clan','A verified clan membership is required for this page.');v.body.append(el('p','Your personal quest journal is available without a clan.'));const a=el('a','Open Player Quests');a.href='#clan-quests-player';v.body.append(a);return;}if(id==='clan-shops')renderShop(v);else if(id==='clan-kits')renderKits(v);else if(id==='clan-bank')renderBank(v);else if(id==='clan-settings'){header(v,'settings','Clan settings','Manage your banner, membership and leadership.');const mount=el('div');v.body.append(mount);if(!await mountOwnClanManagement(mount))mount.append(el('p','Clan management could not be loaded. Refresh to retry.'));}else if(id==='clan-portal'){header(v,'portal','Clan portal','Your clan’s operations, colours and shared journeys.');const cards=el('div');cards.className='clan-portal-grid';for(const[key,label,art]of entries.filter(x=>x[0]!=='portal')){const a=el('a');a.href='#clan-'+key;const image=el('img');image.src='https://www.dunerealms.com/assets/'+art;image.alt='';a.append(image,el('h3',label),el('p',{shops:'Commission a full clan stillsuit.',kits:'Design your clan colours and lore.',bank:'Inspect the Dunemarks balance and ledger.',settings:'Manage members and your banner.',quests:'Plan personal and clan journeys.'}[key]));cards.append(a);}v.body.append(cards);}else{let kind=id.split('-').at(-1);if(!['player','clan','guild'].includes(kind))kind='player';if(!data.member&&kind!=='player'){header(v,'quests','Clan membership required','Only Player Quests are available without a clan.','nav-manual-full-v2.webp');questMenu(v,'player');return;}placeholders(v,kind);}}
|
||||
|
|
|
|||
8
website/control-panel/public/cp-v2/citizen-directory.css
Normal file
8
website/control-panel/public/cp-v2/citizen-directory.css
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
.migration-directory{--md-gold:#dfc17a;--md-line:#66846b;--md-muted:#bacbbb;--md-bg:#102b22;--md-panel:#17382b;color:#f2e7c8;font:14px/1.5 system-ui,sans-serif;display:grid;gap:18px}
|
||||
.migration-directory [hidden]{display:none!important}.migration-directory h2,.migration-directory h3{margin:0;color:var(--md-gold);font-family:Georgia,serif}.migration-directory h2{font-size:24px}.migration-directory h3{font-size:19px}.migration-directory p{margin:0}.migration-directory button,.migration-directory input,.migration-directory select{font:inherit}.migration-directory button,.migration-directory a{color:var(--md-gold)}
|
||||
.migration-directory button{padding:9px 14px;background:#102b22;border:1px solid #a98b4c;border-radius:8px;cursor:pointer}.migration-directory button:hover{background:#284a34}.migration-directory button:disabled{opacity:.45;cursor:default}.migration-directory button:focus-visible,.migration-directory input:focus-visible,.migration-directory select:focus-visible{outline:2px solid var(--md-gold);outline-offset:3px}
|
||||
.migration-directory .md-tabs{display:flex;flex-wrap:wrap;gap:8px;margin:0 0 18px}.migration-directory .md-tabs button[aria-current=true]{background:#d5b867;color:#14271b;border-color:#f0db9d}.migration-directory .md-muted,.migration-directory small{color:var(--md-muted)}.migration-directory small{display:block}
|
||||
.migration-directory .md-tools{display:flex;align-items:end;flex-wrap:wrap;gap:12px;margin-bottom:18px}.migration-directory input,.migration-directory select{background:var(--md-bg);color:#f2e7c8;border:1px solid var(--md-line);border-radius:8px;padding:11px;min-width:0;max-width:100%;box-sizing:border-box}.migration-directory input[type=search]{flex:1 1 260px}.migration-directory .md-field{display:grid;gap:4px;flex:1 1 150px;color:var(--md-muted)}
|
||||
.migration-directory .md-table-wrap{overflow:auto;border:1px solid var(--md-line);border-radius:12px}.migration-directory .md-table{border-collapse:collapse;width:100%;table-layout:auto;background:var(--md-bg)}.migration-directory .md-table th{padding:12px;text-align:left;color:var(--md-gold);background:#244b39;font-size:12px;text-transform:uppercase;letter-spacing:.04em}.migration-directory .md-table td{padding:12px;border-top:1px solid #355741;vertical-align:middle;overflow-wrap:anywhere}.migration-directory .md-table tr:nth-child(even){background:#153528}.migration-directory .md-table td:first-child button{background:transparent;border:0;padding:0;text-align:left;font-weight:600}.migration-directory .md-table td:last-child{white-space:nowrap}.migration-directory .md-badge{display:inline-block;border:1px solid #778b61;border-radius:20px;padding:3px 10px;font-size:12px;color:#d7e9c9}
|
||||
.migration-directory .md-pager{display:flex;justify-content:end;align-items:center;gap:14px;margin-top:16px}.migration-directory .md-identity{display:flex;align-items:center;flex-wrap:wrap;gap:16px;margin:18px 0 22px;padding-bottom:20px;border-bottom:1px solid var(--md-line)}.migration-directory .md-identity img{object-fit:contain;border-radius:9px}.migration-directory .md-identity a{margin-left:auto}.migration-directory .md-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}.migration-directory .md-box{border:1px solid var(--md-line);border-radius:12px;background:linear-gradient(130deg,#1d4230,#102b22);padding:20px;display:grid;gap:14px;margin-bottom:18px}.migration-directory .md-detail{display:flex;justify-content:space-between;flex-wrap:wrap;gap:8px;padding:9px 0;border-bottom:1px solid #355741}.migration-directory .md-detail span{color:var(--md-muted)}.migration-directory .md-detail strong{overflow-wrap:anywhere}.migration-directory .md-assignment{border-left:3px solid #c7ad62;padding:8px 12px;background:#153326}.migration-directory .md-assignment strong{color:var(--md-gold)}.migration-directory .md-note{color:var(--md-muted);padding-top:12px}.migration-directory details{margin-top:12px}.migration-directory summary{color:var(--md-gold);cursor:pointer}.migration-directory .md-diagnostics{border-top:1px solid #476046;padding-top:16px}.migration-directory .md-diagnostics p{margin:12px 0}.migration-directory .md-status:empty{display:none}@media(max-width:850px){.migration-directory .md-grid{grid-template-columns:1fr}.migration-directory .md-table{min-width:650px}}
|
||||
.migration-directory .md-assignment-form{display:grid;gap:12px;margin-top:18px}.migration-directory textarea{font:inherit;background:#102b22;color:#f2e7c8;border:1px solid #66846b;border-radius:8px;padding:11px;box-sizing:border-box;width:100%}.migration-directory .md-policy-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:7px;margin-top:14px}.migration-directory .md-permission{display:flex;align-items:start;gap:10px;padding:10px;background:#153528;border-radius:8px;overflow-wrap:anywhere}.migration-directory .md-permission input{margin-top:5px}.migration-directory .md-permission strong{font-weight:500}.migration-directory .md-permission small{display:block}.migration-directory .md-permission[hidden]{display:none}@media(max-width:850px){.migration-directory .md-policy-grid{grid-template-columns:1fr}}
|
||||
123
website/control-panel/public/cp-v2/citizen-directory.mjs
Normal file
123
website/control-panel/public/cp-v2/citizen-directory.mjs
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
import {applyShellHeading} from './cp-v2-page-template.mjs';
|
||||
|
||||
const API='/api/admin/citizens';
|
||||
const element=(tag,value,cls)=>{const e=document.createElement(tag);if(value!==undefined)e.textContent=value;if(cls)e.className=cls;return e;};
|
||||
const button=(label,action)=>{const b=element('button',label);b.type='button';b.onclick=action;return b;};
|
||||
const date=value=>value?new Date(Number(value)).toLocaleDateString('en-GB'):'Not recorded';
|
||||
const roleDescription=a=>a.assignments.map(x=>x.scopeLabel+' · '+x.roleLabel).join(' / ');
|
||||
async function request(path,signal){const r=await fetch(path,{credentials:'same-origin',cache:'no-store',signal});const data=await r.json().catch(()=>({}));if(!r.ok)throw Error(data.message||'Directory unavailable.');return data;}
|
||||
async function send(body){const r=await fetch('/api/admin/organisation/assignments',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});const data=await r.json().catch(()=>({}));if(!r.ok)throw Error(data.message||'Assignment could not be saved.');return data;}
|
||||
|
||||
export function mountCitizenDirectory(host){
|
||||
const root=element('section',undefined,'migration-directory');
|
||||
const css=document.createElement('link');css.rel='stylesheet';css.href='/v2/citizen-directory.css';root.append(css);
|
||||
const view=element('div');const status=element('p','Loading directory…','md-status');status.setAttribute('role','status');
|
||||
const diagnostics=element('details',undefined,'md-diagnostics');diagnostics.append(element('summary','+ Workspace details'),element('p','Central account directory. Assignment catalogue preparation does not change existing permissions.'),button('Reload workspace',()=>load()));
|
||||
root.append(status,view,diagnostics);host.replaceChildren(root);
|
||||
let context='users',page=1,query='',filter='',department='',branch='',selected=null,tab='overview',disposed=false,controller,sequence=0,catalogue={departments:[]},assignmentData=null;
|
||||
let searchTimer;
|
||||
function heading(){applyShellHeading(host,{title:selected?(context==='staff'?'Manage Staff':'Manage User'):'Citizen Directory',description:selected?selected.displayName+' · '+selected.username:'Find a citizen, then manage their account or staff responsibilities.',artwork:context==='staff'?'nav-staff-v2.webp':'nav-account-v2.webp'});}
|
||||
function box(title){const section=element('section',undefined,'md-box');section.append(element('h3',title));return section;}
|
||||
function detail(label,value){const row=element('div',undefined,'md-detail');row.append(element('span',label),element('strong',String(value??'Not recorded')));return row;}
|
||||
function choices(label,items,value,onChange){const field=element('label',label,'md-field'),s=element('select');for(const [key,title]of items){const o=element('option',title);o.value=key;s.append(o);}s.value=value;s.onchange=()=>onChange(s.value);field.append(s);return field;}
|
||||
function badge(label){return element('span',label,'md-badge');}
|
||||
function assignments(){const panel=box(context==='staff'?'Staff assignments':'Memberships & offices');
|
||||
if(selected.assignments.length){for(const a of selected.assignments){const card=element('div',undefined,'md-assignment');card.append(element('strong',a.roleLabel),element('p',a.scopeLabel),badge(a.source||'Recorded assignment'));if(a.endsAt)card.append(element('small','Until '+date(a.endsAt)));panel.append(card);}}
|
||||
else panel.append(element('p',context==='staff'?'No new-model staff assignments have been activated for this account.':'No memberships or offices have been registered in the new assignment model yet. Existing memberships remain in their source systems.','md-muted'));
|
||||
panel.append(element('p','The new assignment register is being prepared. Recorded changes do not replace existing permissions until migration activation.','md-note'));
|
||||
return panel;
|
||||
}
|
||||
function scopeVersion(a){return Number(assignmentData.versions.find(v=>v.scope_type===a.scopeType&&v.scope_key===a.scopeKey)?.version||1);}
|
||||
async function loadAssignments(panel){
|
||||
const target=selected.id;panel.append(element('p','Loading assignment controls…','md-muted'));
|
||||
try{
|
||||
const data=await request('/api/admin/organisation/assignments?userId='+encodeURIComponent(target),controller?.signal);
|
||||
if(disposed||selected?.id!==target||context!=='staff'||tab!=='assignments'||!panel.isConnected)return;
|
||||
assignmentData=data;selected.assignments=data.assignments;panel.replaceChildren(element('h3','Staff assignments'),element('p',data.enforcement==='active'?'Function changes update central access and queue native synchronisation.':'Changes are audited in the new register. Live permission activation follows after the mapping is verified.','md-note'));
|
||||
const message=element('p','');message.setAttribute('role','status');
|
||||
for(const a of data.assignments){
|
||||
const row=element('div',undefined,'md-assignment');row.append(element('strong',a.roleLabel),element('p',a.scopeLabel),badge(a.source));
|
||||
if(a.editable){const revoke=button('Remove assignment',async()=>{
|
||||
const reason=prompt('Reason for removing '+a.roleLabel+' from '+selected.username+' (3–500 characters):');if(reason===null)return;
|
||||
if(!confirm('Remove '+a.roleLabel+' in '+a.scopeLabel+'?'))return;revoke.disabled=true;
|
||||
try{await send({action:'revoke',userId:target,assignmentId:a.id,version:a.version,scopeType:a.scopeType,scopeKey:a.scopeKey,role:a.role,scopeVersion:scopeVersion(a),reason});message.textContent='Assignment removal recorded.';await loadAssignments(panel);}catch(e){message.textContent=e.message;revoke.disabled=false;}
|
||||
});row.append(revoke);}else row.append(element('small',a.source==='manual'?'Outside your management scope.':'Automatic assignment — manage at its source.'));panel.append(row);
|
||||
}
|
||||
if(!data.assignments.length)panel.append(element('p','No new-model staff assignments recorded.','md-muted'));
|
||||
if(data.editable.length){
|
||||
const form=element('form',undefined,'md-assignment-form');const scope=element('select');scope.setAttribute('aria-label','Assignment scope');const role=element('select');role.setAttribute('aria-label','Role within scope');
|
||||
const unique=[...new Map(data.editable.map(s=>[s.type+':'+s.key,s])).values()];for(const s of unique){const o=element('option',s.label+' · '+s.type);o.value=s.type+':'+s.key;scope.append(o);}
|
||||
const updateRoles=()=>{role.replaceChildren();const[type,key]=scope.value.split(':');for(const s of data.editable.filter(s=>s.type===type&&s.key===key)){const o=element('option',s.role.replaceAll('_',' '));o.value=s.role;role.append(o);}};scope.onchange=updateRoles;updateRoles();
|
||||
const reason=element('textarea');reason.required=true;reason.minLength=3;reason.maxLength=500;reason.rows=2;reason.placeholder='Reason for the appointment';reason.setAttribute('aria-label','Reason for appointment');
|
||||
const save=button('Save assignment',()=>{});save.type='submit';
|
||||
for(const[label,input]of [['Department or branch',scope],['Role',role],['Reason',reason]]){const wrap=element('label',label,'md-field');wrap.append(input);form.append(wrap);}form.append(save);
|
||||
form.onsubmit=async e=>{e.preventDefault();if(!form.reportValidity())return;const[type,key]=scope.value.split(':');if(!confirm('Record '+role.selectedOptions[0].textContent+' for '+selected.username+'?'))return;save.disabled=true;
|
||||
try{const result=await send({action:'assign',userId:target,scopeType:type,scopeKey:key,role:role.value,scopeVersion:scopeVersion({scopeType:type,scopeKey:key}),reason:reason.value});await loadAssignments(panel);status.textContent=result.permissionsChanged?'Function assigned. Central access updated; native synchronisation queued.':'Assignment recorded; current live permissions remain unchanged.';}catch(error){message.textContent=error.message;save.disabled=false;}
|
||||
};panel.append(form);
|
||||
}else panel.append(element('p','You have no assignment-management authority in this register.','md-muted'));
|
||||
panel.append(message);
|
||||
}catch(e){if(e.name!=='AbortError'&&panel.isConnected)panel.append(element('p',e.message,'md-note'));}
|
||||
}
|
||||
async function loadActivity(panel){
|
||||
const target=selected.id,currentContext=context;
|
||||
try{const data=await request('/api/admin/organisation/activity?userId='+encodeURIComponent(target)+'&context='+context,controller?.signal);if(disposed||selected?.id!==target||context!==currentContext||tab!=='activity'||!panel.isConnected)return;
|
||||
if(!data.events.length)panel.append(element('p','No changes recorded in the new management register. Older account history remains preserved.','md-muted'));
|
||||
for(const event of data.events){const row=element('div',undefined,'md-assignment');row.append(element('strong',event.action+' · '+event.scope_key.replaceAll('_',' ')),element('p',event.reason),element('small',(event.actor||'System')+' · '+new Date(Number(event.created_at)).toLocaleString('en-GB')));panel.append(row);}
|
||||
}catch(e){if(e.name!=='AbortError'&&panel.isConnected)panel.append(element('p',e.message,'md-note'));}
|
||||
}
|
||||
async function loadAccessPreview(panel){
|
||||
const target=selected.id;panel.append(element('p','Checking the central role mapping…','md-muted'));
|
||||
try{const data=await request('/api/admin/organisation/effective?userId='+encodeURIComponent(target),controller?.signal);
|
||||
if(disposed||selected?.id!==target||context!=='staff'||tab!=='permissions'||!panel.isConnected)return;
|
||||
panel.replaceChildren(element('h3','Effective access preview'),element('p','Preparation only. These mapped permissions have not replaced live access.','md-note'));
|
||||
for(const source of data.sources){const row=element('details',undefined,'md-assignment');row.append(element('summary',source.scopeKey.replaceAll('_',' ')+' · '+source.role.replaceAll('_',' ')+' · '+source.nodes.length+' permissions'));for(const node of source.nodes)row.append(element('p',node,'md-muted'));panel.append(row);}
|
||||
panel.append(element('p',data.nodes.length+' unique permissions · '+data.missingPolicies.length+' missing policy mappings · '+data.blocked.length+' unsafe grants blocked.'));
|
||||
for(const missing of data.missingPolicies)panel.append(element('p','Mapping required: '+missing.scopeKey+' / '+missing.role,'md-note'));
|
||||
if(!data.sources.length&&!data.missingPolicies.length)panel.append(element('p','No active mapped staff functions. Existing live rights remain unchanged.'));
|
||||
}catch(e){if(e.name!=='AbortError'&&panel.isConnected)panel.replaceChildren(element('p',e.message,'md-note'));}
|
||||
}
|
||||
function renderAccount(){
|
||||
view.replaceChildren();heading();const back=button('← '+(context==='staff'?'Staff Directory':'User Directory'),()=>{selected=null;void load();});view.append(back);
|
||||
const hero=element('header',undefined,'md-identity');const avatar=element('img');avatar.alt='';avatar.width=56;avatar.height=56;avatar.src=selected.minecraftUuid?'/api/avatars/minecraft/'+encodeURIComponent(selected.minecraftUuid):'https://www.dunerealms.com/assets/nav-account-v2.webp';
|
||||
const names=element('div');names.append(element('h2',selected.displayName),element('p',selected.username,'md-muted'));const publicLink=element('a','View public profile →');publicLink.href='https://www.dunerealms.com/people/'+encodeURIComponent(selected.username);hero.append(avatar,names,badge(selected.status),publicLink);view.append(hero);
|
||||
const tabs=context==='staff'?[['overview','Overview'],['account','Account'],['assignments','Staff assignments'],['permissions','Access preview'],['honours','Seals & honours'],['activity','Activity']]:[['overview','Overview'],['account','Account'],['assignments','Memberships & offices'],['honours','Seals & honours'],['activity','Activity']];
|
||||
const nav=element('nav',undefined,'md-tabs');nav.setAttribute('aria-label','Manage '+(context==='staff'?'staff':'user'));for(const[key,label]of tabs){const b=button(label,()=>{tab=key;renderAccount();});b.setAttribute('aria-current',String(tab===key));nav.append(b);}view.append(nav);
|
||||
if(tab==='overview'){
|
||||
const grid=element('div',undefined,'md-grid'),identity=box('Account summary');identity.append(detail('Minecraft',selected.minecraftName||'Not linked'),detail('Joined',date(selected.createdAt)),detail('Status',selected.status));grid.append(identity,assignments());view.append(grid);
|
||||
if(context==='staff'&&selected.staffSources?.length){const source=box('Imported staff record');for(const row of selected.staffSources)source.append(detail('Source account',row.name),detail('Imported',date(row.importedAt)));source.append(element('p','Imported identity is evidence of the staff cohort, not a new permission grant.','md-muted'));view.append(source);}
|
||||
}else if(tab==='account'){
|
||||
const identity=box('Linked identity');identity.append(detail('Username',selected.username),detail('Display name',selected.displayName),detail('Minecraft',selected.minecraftName||'Not linked'),detail('Status',selected.status));const advanced=element('details');advanced.append(element('summary','+ Advanced account details'),detail('Account ID',selected.id),detail('Minecraft UUID',selected.minecraftUuid||'Not linked'));identity.append(advanced);view.append(identity);
|
||||
}else if(tab==='assignments'){const panel=assignments();view.append(panel);if(context==='staff')void loadAssignments(panel);}
|
||||
else if(tab==='permissions'&&context==='staff'){const panel=box('Effective access preview');view.append(panel);void loadAccessPreview(panel);}
|
||||
else if(tab==='honours'){const panel=box('Seals & honours');panel.append(element('p','Existing awards are preserved. The new seal ledger and compact award controls follow in the recognition batch.','md-muted'));panel.append(publicLink.cloneNode(true));view.append(panel);}
|
||||
else{const panel=box('Account activity');view.append(panel);void loadActivity(panel);}
|
||||
}
|
||||
function renderList(data){
|
||||
const restoreSearch=document.activeElement===view.querySelector('input[type="search"]');
|
||||
view.replaceChildren();heading();const nav=element('nav',undefined,'md-tabs');nav.setAttribute('aria-label','Directory type');for(const[key,label]of [['users','Users'],['staff','Staff']]){const b=button(label,()=>{if(context===key)return;context=key;page=1;department='';branch='';void load();});b.setAttribute('aria-current',String(context===key));nav.append(b);}view.append(nav);
|
||||
if(context==='staff')nav.append(button('Add staff member',()=>pickCandidate()));
|
||||
const toolbar=element('form',undefined,'md-tools');const search=element('input');search.type='search';search.value=query;search.placeholder='Name, Minecraft UUID or account ID';search.setAttribute('aria-label','Search all directory records');search.oninput=()=>{query=search.value;clearTimeout(searchTimer);searchTimer=setTimeout(()=>{page=1;void load();},350);};
|
||||
toolbar.onsubmit=e=>{e.preventDefault();clearTimeout(searchTimer);page=1;void load();};toolbar.append(search,choices('Status',[['','All statuses'],['active','Active'],['banned','Banned'],['deleted','Deleted']],filter,value=>{filter=value;page=1;void load();}));
|
||||
if(context==='staff'){
|
||||
toolbar.append(choices('Department',[['','All departments'],...catalogue.departments.map(d=>[d.key,d.label])],department,value=>{department=value;branch='';page=1;void load();}));
|
||||
const branches=catalogue.departments.filter(d=>!department||d.key===department).flatMap(d=>d.branches);
|
||||
toolbar.append(choices('Branch',[['','All branches'],...branches.map(b=>[b.key,b.label])],branch,value=>{branch=value;page=1;void load();}));
|
||||
}view.append(toolbar);if(restoreSearch){search.focus({preventScroll:true});search.setSelectionRange(search.value.length,search.value.length);}
|
||||
const wrap=element('div',undefined,'md-table-wrap'),table=element('table',undefined,'md-table'),head=element('thead'),tr=element('tr');
|
||||
for(const label of ['Citizen','Status',context==='staff'?'Functions':'Memberships & offices','Minecraft',''])tr.append(element('th',label));head.append(tr);table.append(head);const body=element('tbody');
|
||||
for(const a of data.accounts){const row=element('tr');const name=element('td');name.append(button(a.displayName,()=>open(a.id)),element('small',a.username));const state=element('td');state.append(badge(a.status));row.append(name,state,element('td',roleDescription(a)||(context==='staff'?'Awaiting migration':'Source integration pending'),'md-muted'),element('td',a.minecraftName||'Not linked'));const action=element('td');action.append(button('Manage →',()=>open(a.id)));row.append(action);body.append(row);}
|
||||
if(!data.accounts.length){const row=element('tr'),cell=element('td','No matching '+(context==='staff'?'staff accounts.':'users.'));cell.colSpan=5;row.append(cell);body.append(row);}table.append(body);wrap.append(table);view.append(wrap);
|
||||
const pager=element('div',undefined,'md-pager'),previous=button('Previous',()=>{page--;void load();}),next=button('Next',()=>{page++;void load();});previous.disabled=page===1;next.disabled=!data.hasMore;pager.append(previous,element('span','Page '+page),next);view.append(pager);
|
||||
if(context==='staff'&&(department||branch))view.append(element('p','Department and branch filters use new-model assignments. Imported accounts appear in All staff until their assignments are migrated.','md-note'));
|
||||
}
|
||||
function pickCandidate(){
|
||||
view.replaceChildren(button('← Staff Directory',()=>load()));const panel=box('Find a citizen to appoint'),form=element('form',undefined,'md-tools'),input=element('input'),find=button('Find citizen',()=>{}),results=element('div');input.type='search';input.required=true;input.minLength=3;input.maxLength=80;input.placeholder='Username or Minecraft identity';input.setAttribute('aria-label','Find a staff candidate');find.type='submit';form.append(input,find);panel.append(form,results);view.append(panel);
|
||||
form.onsubmit=async e=>{e.preventDefault();if(!form.reportValidity())return;find.disabled=true;results.replaceChildren(element('p','Finding citizens…'));
|
||||
try{const data=await request(API+'?context=users&q='+encodeURIComponent(input.value),controller?.signal);if(!panel.isConnected||disposed)return;results.replaceChildren();for(const account of data.accounts.filter(a=>a.status==='active')){const row=element('div',undefined,'md-detail');row.append(element('span',account.displayName+' · '+account.username),button('Manage staff assignments',async()=>{await open(account.id);if(selected?.id===account.id){tab='assignments';renderAccount();}}));results.append(row);}if(!results.children.length)results.append(element('p','No active citizens found.'));if(data.hasMore)results.append(element('p','Refine the name to narrow the results.','md-note'));}
|
||||
catch(error){if(panel.isConnected)results.replaceChildren(element('p',error.message));}finally{find.disabled=false;}
|
||||
};
|
||||
}
|
||||
async function open(id){controller?.abort();controller=new AbortController();const current=++sequence;status.textContent='Loading account…';try{const data=await request(API+'/'+encodeURIComponent(id)+'?context='+context,controller.signal);if(disposed||current!==sequence)return;selected=data.account;tab='overview';renderAccount();status.textContent='';}catch(e){if(!disposed&&e.name!=='AbortError')status.textContent=e.message;}}
|
||||
async function load(){controller?.abort();controller=new AbortController();const current=++sequence;status.textContent='Loading '+context+'…';try{if(context==='staff'&&!catalogue.departments.length)catalogue=await request(API+'/catalogue?context=staff',controller.signal);const params=new URLSearchParams({context,page:String(page),q:query,status:filter,department,branch});const data=await request(API+'?'+params,controller.signal);if(disposed||current!==sequence)return;selected=null;renderList(data);status.textContent=data.accounts.length+' records on this page · search covers the complete directory.';}catch(e){if(!disposed&&e.name!=='AbortError'){view.replaceChildren();status.textContent=e.message;}}}
|
||||
void load();return()=>{disposed=true;sequence++;clearTimeout(searchTimer);controller?.abort();root.remove();};
|
||||
}
|
||||
|
|
@ -12,7 +12,7 @@ import {createCPV2Page,element as el} from './cp-v2-page-template.mjs';
|
|||
import {mountReadRegister} from './cp-v2-read-register.mjs';
|
||||
import {BUREAU_READS} from './cp-v2-bureau-data.mjs';
|
||||
import {mountCompanyActions} from './cp-v2-company-actions.mjs';
|
||||
import {mountImperialRevenue} from './cp-v2-imperial-revenue.mjs';
|
||||
import {mountPostbankAdmin} from './cp-v2-postbank-admin.mjs';
|
||||
// Imperial Bureau pages not yet backed by verified V2 APIs. Never expose fake writes.
|
||||
const PAGES={"company-management":{"title":"Company Directorate","tabs":["Enterprise registry","Corporate governance","Company permissions"]},"company-management-v2":{"title":"Corporate Administration","tabs":["Company administration","Officer assignments","Corporate settings"]},"company-audit":{"title":"Corporate Audit","tabs":["Audit register","Corporate changes","Compliance reports"]},"staff-bank":{"title":"Imperial Revenue","tabs":["Revenue overview","Collections","Allocation controls"]},"server-kits":{"title":"Kit Directorate","tabs":["Kit catalogue","Kit administration","In-game delivery"]},"kit-publishing":{"title":"Kit Publications","tabs":["Publication queue","Published kits","Version history"]},"kit-claims":{"title":"Claim Registry","tabs":["Claim requests","Claim history","Delivery reconciliation"]},"exchange-admin":{"title":"Exchange Authority","tabs":["Exchange operations","Listing moderation","Trade oversight"]},"shop-admin":{"title":"Merchant Directorate","tabs":["Merchant directory","Shop approvals","Sales administration"]},"items":{"title":"Item Registry","tabs":["Item catalogue","Item definitions","Publishing queue"]},"website-posts":{"title":"Imperial Newsroom","tabs":["Newsroom drafts","Publication schedule","Published announcements"]},"staff-tickets":{"title":"Petition Office","tabs":["Incoming petitions","Assigned cases","Resolution history"]},"bans":{"title":"Tribunal","tabs":["Tribunal cases","Sanctions register","Appeal reviews"]},"ban-evidence":{"title":"Evidence Registry","tabs":["Evidence register","Case attachments","Chain of custody"]},"forum-admin":{"title":"Forum Wardens","tabs":["Forum reports","Moderation queue","Community rules"]},"quests-admin":{"title":"Campaign Directorate","tabs":["Campaign catalogue","Quest publishing","Participation reports"]},"community-goals":{"title":"Community Treasury","tabs":["Treasury goals","Contribution records","Funding oversight"]},"support-management":{"title":"Petition Administration","tabs":["Support queue","Staff assignments","Service reports"]},"server-operations":{"title":"Network Command","tabs":["Network overview","Server operations","Incident register"]},"hosting-control":{"title":"Hosting Command","tabs":["Infrastructure status","Hosting controls","Change approvals"]},"dev-approvals":{"title":"Development Approvals","tabs":["Approval queue","Change proposals","Decision history"]}};
|
||||
const artFor=id=>/kit|item|dev/.test(id)?'nav-manual-v2.webp':/bank|exchange|shop|revenue|treasury/.test(id)?'nav-exchange-v2.webp':'nav-staff-v2.webp';
|
||||
|
|
@ -101,6 +101,6 @@ export function mountBureauPlaceholder(host,id){
|
|||
if(id==='website-posts')return mountNewsroom(host);
|
||||
if(SERVICE_PAGES[id])return mountBureauServicePage(host,id);
|
||||
if(id==='company-management')return mountCompanyDirectorate(host);
|
||||
if(id==='staff-bank')return mountImperialRevenue(host);
|
||||
if(id==='staff-bank')return mountPostbankAdmin(host,'staff-bank');
|
||||
if(BUREAU_READS[id]){const spec=PAGES[id];return mountReadRegister(host,{title:spec.title,description:'Imperial Bureau · '+spec.title+' · Read-only preview',artwork:artFor(id),tabs:spec.tabs.map((label,index)=>({id:'area-'+(index+1),label,...BUREAU_READS[id][index]}))});}
|
||||
const spec=PAGES[id];if(!spec)throw Error('Unknown Bureau page');const artwork=artFor(id);const tabs=spec.tabs.map((label,index)=>{const content=el('section',undefined,'cp-v2-bank-placeholder');const image=el('img');image.src='https://www.dunerealms.com/assets/'+artwork;image.alt='';image.width=82;image.height=82;content.append(image,el('h4',label),el('p',label+' will be connected to its verified authorization and data service during V2 integration.'),el('p','V2 · PLANNED — no live data or administrative changes are available here.','cp-v2-bank-status'));return{id:'area-'+(index+1),label,artwork,content}});const {root}=createCPV2Page({title:spec.title,description:'Imperial Bureau · '+spec.title+' workspace.',artwork,tabs});host.replaceChildren(root);return()=>root.remove()}
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ export function mountPostbankAdmin(host,id,{fetcher=fetch}={}){
|
|||
const nav=el('nav',undefined,'pb-ledger-pagination'),previous=el('button','Previous'),next=el('button','Next');previous.type=next.type='button';previous.disabled=page===1;next.disabled=!data.hasMore;previous.onclick=()=>{page--;void load();};next.onclick=()=>{page++;void load();};nav.append(previous,el('span','Page '+page),next);frame.content.append(nav);frame.status.hidden=true;frame.diagnostics.textContent='Central API · Bank administration permission confirmed · '+new Date().toLocaleString('en-GB');
|
||||
}catch(error){if(active)message(error.message);}finally{busy=false;if(active)frame.reloadButton.disabled=false;}}
|
||||
function renderTreasuries(data,canManage,canIssueReserve){
|
||||
if(canManage){const allocations=el('a','Tax Treasury Payments');allocations.href='#bureau/tax-treasury';allocations.className='pb-primary-link';frame.content.append(allocations);}
|
||||
const managed=data.records.filter(a=>!a.system||a.canTransfer),automated=data.records.filter(a=>a.system&&!a.canTransfer),priority=a=>a.name==='Website Bank Treasury'?0:a.name==='In-game Bank Treasury'?1:a.name==='I.D. Taxes'?2:3;
|
||||
managed.sort((a,b)=>priority(a)-priority(b)||a.name.localeCompare(b.name));automated.sort((a,b)=>a.name.localeCompare(b.name));
|
||||
for(const [title,records,type,description]of [['Managed Accounts',managed,'managed','Bank reserves, the combined web/game tax treasury and staff accounts. Manual treasury transfers are limited to the website bank, in-game reserve and tax treasury.'],['System Accounts',automated,'system','Automated service accounts. Federal Imperial Reserve records capital issuance; P&O is a fictitious payroll issuer. Neither can make manual payments here.']]){
|
||||
|
|
|
|||
|
|
@ -12,7 +12,8 @@ export function mountUserPage(host,id,{fetcher=fetch,initialTab,listingId}={}){
|
|||
async function mount(){
|
||||
const loaders={game:['./cp-v2-passport.mjs','mountPassport'],'site-profile':['./cp-v2-personal-records.mjs','mountPersonalRecords'],security:['./cp-v2-security.mjs','mountSecurity'],'rewards-codes':['./cp-v2-rewards.mjs','mountRewards']};
|
||||
if(loaders[id]){const [path,key]=loaders[id],module=await import(path);if(active)dispose=module[key](host,{fetcher,initialTab});return;}
|
||||
if(['tickets','clans','shared-inbox','kits-exchange','personal-bank'].includes(id)){const {mountNativeService}=await import('./cp-v2-native-services.mjs');if(active)dispose=mountNativeService(host,id,{fetcher,singleHeading:true,initialTab,listingId});return;}
|
||||
if(['personal-bank','transactions'].includes(id)){const {mountBankPage}=await import('./cp-v2-bank-pages.mjs');if(active)dispose=mountBankPage(host,id==='transactions'?'bank-statements':'personal-bank',{fetcher});return;}
|
||||
if(['tickets','clans','shared-inbox','kits-exchange'].includes(id)){const {mountNativeService}=await import('./cp-v2-native-services.mjs');if(active)dispose=mountNativeService(host,id,{fetcher,singleHeading:true,initialTab,listingId});return;}
|
||||
if(id==='planetary-inventory'){
|
||||
const {mountInventory}=await import('/inventory/inventory-view.mjs');if(!active)return;
|
||||
if(!document.querySelector('link[data-v2-inventory]')){const css=el('link');css.rel='stylesheet';css.href='/inventory/inventory.css';css.dataset.v2Inventory='true';document.head.append(css);}
|
||||
|
|
@ -20,7 +21,7 @@ export function mountUserPage(host,id,{fetcher=fetch,initialTab,listingId}={}){
|
|||
const {root}=createCPV2Page({shellHost:host,title:'My Inventory',description:'Your saved planetary equipment and exchange history, connected to the existing game inventory service.',artwork:'nav-account-v2.webp',tabs:[{id:'inventory-record',label:'Equipment & ledger',content:inventory}]});host.replaceChildren(root);
|
||||
const view=mountInventory(inventory,{request:api.request,visibleTabs:['inventory','history'],title:'Saved inventory'});dispose=()=>{view.clear();root.remove();};return;
|
||||
}
|
||||
if(['transactions','shop-settings','exchange-settings'].includes(id)){const {mountUserCommerce}=await import('./cp-v2-user-commerce.mjs');if(active)dispose=mountUserCommerce(host,id,{fetcher});return;}
|
||||
if(['shop-settings','exchange-settings'].includes(id)){const {mountUserCommerce}=await import('./cp-v2-user-commerce.mjs');if(active)dispose=mountUserCommerce(host,id,{fetcher});return;}
|
||||
if(id==='quests'){mountQuests();return;}
|
||||
if(id==='discord-link'){
|
||||
const box=el('section',undefined,'cp-v2-personal-box'),{root}=createCPV2Page({shellHost:host,title:'Discord Link',description:'Your Discord community presence and account-linking availability.',artwork:'nav-discord-v2.webp',tabs:[{id:'discord-identity',label:'Discord identity',content:box}]});host.replaceChildren(root);
|
||||
|
|
|
|||
|
|
@ -0,0 +1,33 @@
|
|||
import {applyShellHeading} from './cp-v2-page-template.mjs';
|
||||
const el=(tag,value,cls)=>{const e=document.createElement(tag);if(value!==undefined)e.textContent=value;if(cls)e.className=cls;return e;};
|
||||
const roleNames={owner_ceo:'Owner & CEO',executive:'Executive',department_head:'Department Head',branch_lead:'Branch Lead',officer:'Officer'};
|
||||
const roles={organisation:['owner_ceo','executive'],department:['department_head'],branch:['branch_lead','officer']};
|
||||
const API='/api/admin/organisation/policies';
|
||||
export function mountOrganisationPermissions(host){
|
||||
let disposed=false,data,selection='branch:news_media',role='officer',dirty=false,busy=false;const controller=new AbortController();
|
||||
const root=el('section',undefined,'migration-directory');const css=el('link');css.rel='stylesheet';css.href='/v2/citizen-directory.css';
|
||||
const status=el('p','Loading the central permission matrix…');status.setAttribute('role','status');const content=el('div');root.append(css,status,content);host.replaceChildren(root);
|
||||
applyShellHeading(host,{title:'Imperial Permissions',description:'Map existing permissions to departments, branches and functions.',artwork:'nav-staff-v2.webp'});
|
||||
async function api(body){const r=await fetch(API,{credentials:'same-origin',cache:'no-store',signal:controller.signal,...(body?{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:{})});const d=await r.json().catch(()=>({}));if(!r.ok)throw Error(d.message||'Policy service unavailable.');return d;}
|
||||
function render(){
|
||||
content.replaceChildren();content.append(el('p','Preparation mode: saved mappings are versioned and audited. Current live permissions remain unchanged until the migration is activated.','md-note'));
|
||||
const tools=el('div',undefined,'md-tools'),scopes=el('select'),ranks=el('select');scopes.setAttribute('aria-label','Department or branch');ranks.setAttribute('aria-label','Function');
|
||||
for(const s of data.scopes){const o=el('option',s.label+' · '+s.type);o.value=s.type+':'+s.key;scopes.append(o);}scopes.value=selection;
|
||||
const [type,key]=selection.split(':');for(const value of roles[type]){const o=el('option',roleNames[value]);o.value=value;ranks.append(o);}if(!roles[type].includes(role))role=roles[type][0];ranks.value=role;
|
||||
const choose=callback=>{if(busy)return;if(dirty&&!confirm('Discard unsaved mapping changes?'))return;dirty=false;callback();render();};scopes.onchange=()=>choose(()=>{selection=scopes.value;});ranks.onchange=()=>choose(()=>{role=ranks.value;});tools.append(scopes,ranks);content.append(tools);
|
||||
const policy=data.policies.find(p=>p.scope_type===type&&p.scope_key===key&&p.role_key===role),chosen=new Set(policy?.nodes||[]);
|
||||
const heading=el('h3',roleNames[role]+' · '+data.scopes.find(s=>s.type===type&&s.key===key).label);content.append(heading);
|
||||
const search=el('input');search.type='search';search.placeholder='Find existing permission';search.setAttribute('aria-label','Filter permission catalogue');const assignedOnly=el('input');assignedOnly.type='checkbox';const assignedLabel=el('label','Show assigned only');assignedLabel.prepend(assignedOnly);const filters=el('div',undefined,'md-tools');filters.append(search,assignedLabel);content.append(filters);
|
||||
const matrix=el('div',undefined,'md-policy-grid');
|
||||
for(const item of data.catalogue){const option=el('label',undefined,'md-permission');const check=el('input');check.type='checkbox';check.checked=chosen.has(item.node);check.disabled=!data.canEdit;const label=el('span');label.append(el('strong',item.label),el('small',item.node));option.append(check,label);option.dataset.search=(item.node+' '+item.label).toLowerCase();check.onchange=()=>{dirty=true;check.checked?chosen.add(item.node):chosen.delete(item.node);count.textContent=chosen.size+' mapped permissions';filter();};matrix.append(option);}
|
||||
const filter=()=>{for(const row of matrix.children)row.hidden=!!search.value&&!row.dataset.search.includes(search.value.toLowerCase())||assignedOnly.checked&&!row.querySelector('input').checked;};search.oninput=filter;assignedOnly.onchange=filter;content.append(matrix);
|
||||
const count=el('p',chosen.size+' mapped permissions','md-note');const reason=el('textarea');reason.rows=2;reason.required=true;reason.minLength=3;reason.maxLength=500;reason.placeholder='Reason for this policy change';reason.setAttribute('aria-label','Reason for policy change');const save=el('button','Save policy mapping');save.type='submit';save.disabled=!data.canEdit;const form=el('form',undefined,'md-assignment-form');form.append(count,reason,save);content.append(form);
|
||||
form.onsubmit=async e=>{e.preventDefault();if(busy||!data.canEdit||!form.reportValidity()||!confirm('Save this mapping? Live activation is a separate migration step.'))return;busy=true;save.disabled=true;
|
||||
try{const version=Number(data.versions.find(v=>v.scope_type===type&&v.scope_key===key)?.version||1);await api({scopeType:type,scopeKey:key,role,nodes:[...chosen],scopeVersion:version,reason:reason.value});dirty=false;await load();status.textContent='Policy mapping saved and audited. Live permissions unchanged.';}catch(error){if(!disposed)status.textContent=error.message;}finally{busy=false;if(save.isConnected)save.disabled=!data.canEdit;}
|
||||
};
|
||||
if(!data.canEdit)content.append(el('p','Read-only mapping. Editing requires Executive or Dev service authority.','md-note'));
|
||||
const advanced=el('details');advanced.append(el('summary','+ Workspace details'),el('p','Central policy register · version '+(policy?.version||0)+' · no native rank editor or wildcard grants'));content.append(advanced);
|
||||
}
|
||||
async function load(){try{data=await api();if(disposed)return;render();status.textContent='';}catch(e){if(!disposed&&e.name!=='AbortError')status.textContent=e.message;}}
|
||||
void load();return()=>{disposed=true;controller.abort();root.remove();};
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
|
|
@ -118,8 +118,8 @@ function render(){
|
|||
const house=views['house-elections'].content;
|
||||
if(context?.faction){const name=context.faction[0].toUpperCase()+context.faction.slice(1);house.append(card(name+' · House chamber','Your faction was confirmed from your linked Minecraft account. The register below contains real candidatures for this chamber.','seals/office-house_leader.png'),renderVoting('house'));}
|
||||
else{const title=context?.linked===false?'Link your Minecraft account':context?'House not confirmed':'Checking your linked House';const box=card(title,context?.linked===false?'Link your Minecraft identity to enter the chamber belonging to the faction you chose in game.':'Your House has not been confirmed. Other House elections remain hidden.','seals/office-house_leader.png');box.append(artLink('Minecraft account','game','nav-clan-v2.webp'));house.append(box);}
|
||||
const council=views['formal-council'].content;if(context?.factionAccount){const treasury=card('House Treasury',context.factionAccount,'dunemark-icon-64.png');treasury.classList.add('imperial-account-card');const brand=el('img');brand.src='/assets/imperial-postbank-v2.png';brand.alt='Imperial Postbank · Part of Corrino Group';brand.className='imperial-bank-brand';brand.width=480;treasury.prepend(brand);council.append(treasury);}council.append(councilPreview(),rallyPreview(),revoltPreview(),warPreview(),inboxPreview());if(views['shared-inbox'].section.dataset.internalMail!=='true')views['shared-inbox'].content.append(el('p','Loading your private inbox…'));
|
||||
const councilLink=card('Faction Council','Banking, appointments, rallies, war requests and your shared inbox.','seals/office-house_leader.png');councilLink.append(artLink('Enter the council','formal-council','seals/office-house_leader.png'));landing.append(councilLink);
|
||||
const council=views['formal-council'].content;{const treasury=card('House Treasury','Manage your authorised House and office accounts in Imperial Postbank.','imperial-postbank-v2.png');const link=el('a','Open Imperial Postbank');link.href='https://cp.dunerealms.com/#bank/bank-overview';link.target='_top';treasury.append(link);council.append(treasury);}council.append(councilPreview(),rallyPreview(),revoltPreview(),warPreview(),inboxPreview());if(views['shared-inbox'].section.dataset.internalMail!=='true')views['shared-inbox'].content.append(el('p','Loading your private inbox…'));
|
||||
const councilLink=card('Faction Council','Appointments, rallies, war requests, your shared inbox and Imperial Postbank access.','seals/office-house_leader.png');councilLink.append(artLink('Enter the council','formal-council','seals/office-house_leader.png'));landing.append(councilLink);
|
||||
const lore=card('The Veiled Concord · Caitain','In the quiet courts of Caitain, the Concord keeps the promises that crowns forget. Its scholars train in memory, diplomacy and patient observation. Three woven paths surround a guiding star upon their seal: knowledge, restraint and accord. Their elected Reverent Mother speaks with the standing of a House leader, while an appointed Concord Sister tends the treasury. They may counsel another House toward war, but never declare it themselves.','seals/veiled-concord-v1.png');lore.classList.add('politics-concord');landing.append(lore);
|
||||
for(const key of ['house-elections','imperial-elections']){const note=views[key].section.querySelector('.politics-preview-note');if(note)note.textContent='ELECTION CHAMBER · Real candidates and definitive votes. Voting opens at the scheduled time.';}
|
||||
const imperial=views['imperial-elections'].content;imperial.append(renderVoting('imperial'));
|
||||
|
|
|
|||
|
|
@ -68,6 +68,9 @@ import {sharedErrorResponse} from '../node/shared-errors.mjs';
|
|||
import {initializeNews} from '../node/news.mjs';
|
||||
import {initializeStaffBureau} from '../node/staff-bureau-schema.mjs';
|
||||
import {createStaffBureauReadApi} from '../node/staff-bureau-read-api.mjs';
|
||||
import {initializeOrganisation} from '../node/organisation-model.mjs';
|
||||
import {createCitizenDirectory} from '../node/citizen-directory.mjs';
|
||||
import {createOrganisationManagement} from '../node/organisation-management.mjs';
|
||||
import {initializeRanks,initializeCommunityAccess,initializeQuestAccess,initializeBankAccess,can,accessFor} from '../node/permissions.mjs';
|
||||
import {createServer} from 'node:http';
|
||||
import {createV1PersonalBank} from './api-v1-personal-bank.mjs';
|
||||
|
|
@ -105,6 +108,8 @@ export function createPanel(db,settings={},dependencies={}){
|
|||
const honours=createHonourRoute(db,origin);const ranks=createRankAdmin(db,settings,origin);const badges=createBadgeAdmin(db,origin);const manualSeals=createManualSealRoute(db,origin);const sealCatalog=createSealCatalogAdmin(db,origin);const companyAdmin=createCompanyAdmin(db,origin);
|
||||
const manual=createStaffManual(db);
|
||||
const staffBureauRead=createStaffBureauReadApi(db);
|
||||
const citizenDirectory=createCitizenDirectory(db);
|
||||
const organisationManagement=createOrganisationManagement(db,{origin});
|
||||
const luckperms=createLuckPerms(db,settings,dependencies.luckperms);
|
||||
const servers=createServerControl(db,settings,dependencies.serverControl);
|
||||
const pool=dependencies.inventoryPool||{async query(){throw Error('Inventory database is not configured');}};
|
||||
|
|
@ -155,6 +160,8 @@ export function createPanel(db,settings={},dependencies={}){
|
|||
if(path==='/api/politics/applications')return electionApplications(request);
|
||||
if(path==='/api/politics/preview')return politicsPreview(request);
|
||||
if(path==='/api/admin/register-user')return adminRegistration(request);
|
||||
if(path==='/api/admin/citizens'||path.startsWith('/api/admin/citizens/'))return citizenDirectory(request);
|
||||
if(path.startsWith('/api/admin/organisation/'))return organisationManagement(request);
|
||||
if(path==='/api/account/email')return contactEmail(request);
|
||||
if(path.startsWith('/api/people/'))return memberProfiles(request);
|
||||
if(path==='/profile-login'&&request.method==='GET'){
|
||||
|
|
@ -244,6 +251,7 @@ export function createPanel(db,settings={},dependencies={}){
|
|||
if(path.startsWith('/assets/')&&sharedAssets.has(path.slice(8))){const file=path.slice(8);return new Response(request.method==='HEAD'?null:await readFile(new URL('../web/assets/'+file,import.meta.url)),{headers:{'Content-Type':file.endsWith('.svg')?'image/svg+xml':file.endsWith('.png')?'image/png':'image/webp','Cache-Control':'public, max-age=3600'}});}
|
||||
if(path==='/federal-reserve'||path==='/federal-reserve/')return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/reserve-ledger.html',import.meta.url)),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}});
|
||||
// V2 shell is public; private data and writes retain their authenticated API gates.
|
||||
if(['/v2/citizen-directory.mjs','/v2/citizen-directory.css','/v2/organisation-permissions.mjs'].includes(path))return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/'+path.slice('/v2/'.length),import.meta.url)),{headers:{'Content-Type':path.endsWith('.css')?'text/css; charset=utf-8':'text/javascript; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}});
|
||||
if(['/','/index.html','/v2','/v2/','/v2/cp-v2-politics-pages.mjs','/v2/cp-v2-auth.mjs','/v2/cp-v2-access.mjs','/v2/citizens-registry.mjs','/v2/cp-v2-page-template.mjs','/v2/imperial-permissions.mjs','/v2/honours-seals.mjs','/v2/cp-v2-planned-pages.mjs','/v2/cp-v2-choam-pages.mjs','/v2/cp-v2-bureau-pages.mjs','/v2/cp-v2-service-pages.mjs','/v2/cp-v2-newsroom.mjs','/v2/cp-v2-moderation.mjs','/v2/cp-v2-native-services.mjs','/v2/cp-v2-exchange-authority.mjs','/v2/cp-v2-crysknife.mjs','/v2/cp-v2-post-menu.mjs','/v2/cp-v2-postbank-foundation.mjs','/v2/cp-v2-postbank-payments.mjs','/v2/cp-v2-postbank-admin.mjs','/v2/cp-v2-authorisations.mjs','/v2/cp-v2-tax-treasury.mjs','/v2/cp-v2-reserve-ledger.mjs','/v2/cp-v2-reserve-entry.mjs','/v2/cp-v2-postbank-credit.mjs','/v2/cp-v2-postbank-beneficiaries.mjs','/v2/cp-v2-postbank-statement-archive.mjs','/v2/cp-v2-bank-pages.mjs','/v2/cp-v2-post-pages.mjs','/v2/cp-v2-rewards.mjs','/v2/cp-v2-user-commerce.mjs','/v2/cp-v2-user-pages.mjs','/v2/cp-v2-user-api.mjs','/v2/cp-v2-security.mjs','/v2/cp-v2-passport.mjs','/v2/cp-v2-personal-records.mjs','/v2/cp-v2-design-pages.mjs','/v2/cp-v2-design-catalog.mjs','/v2/cp-v2-forge-pages.mjs','/v2/cp-v2-hosting.mjs','/v2/cp-v2-community-treasury.mjs','/v2/cp-v2-item-register.mjs','/v2/cp-v2-kit-directorate.mjs','/v2/cp-v2-campaigns.mjs','/v2/cp-v2-imperial-revenue.mjs','/v2/cp-v2-read-register.mjs','/v2/cp-v2-bureau-data.mjs','/v2/cp-v2-company-actions.mjs','/v2/v2.css','/v2/v2.js'].includes(path)){
|
||||
const moduleFile=path.endsWith('.mjs')||path.endsWith('.js');
|
||||
const file=path.endsWith('.mjs')?path.slice('/v2/'.length):path.endsWith('.js')?'v2.js':path.endsWith('.css')?'v2.css':'index.html';
|
||||
|
|
@ -262,7 +270,7 @@ export async function startPanel(settings=process.env){
|
|||
inventoryPool.on('error',()=>console.error('Inventory database connection unavailable.'));
|
||||
}
|
||||
const bankDatabase=await openPostbankDatabase(settings);
|
||||
const db=await openDatabase(settings);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);const handle=createPanel(db,settings,{inventoryPool,bankDatabase}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com';
|
||||
const db=await openDatabase(settings);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);const handle=createPanel(db,settings,{inventoryPool,bankDatabase}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com';
|
||||
await initializeInternalMailAccess(db);const stopElectionClock=startElectionClock(db);const stopOfficeLedger=startOfficeLedger(db);
|
||||
const stopBanSync=startModerationSync(db,settings),stopInternalMail=startInternalMailSync(db),stopPostbankQueue=startPostbankQueue(db,bankDatabase,settings);
|
||||
const security={'X-Robots-Tag':'noindex, nofollow, noarchive','X-Content-Type-Options':'nosniff','Referrer-Policy':'no-referrer','Cache-Control':'no-store','Content-Security-Policy':"default-src 'self'; script-src 'self' https://www.dunerealms.com; style-src 'self' https://www.dunerealms.com https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; connect-src 'self' https://www.dunerealms.com; img-src 'self' data: https://www.dunerealms.com https://support.dunerealms.com; frame-src 'self' https://luckperms.net https://www.dunerealms.com https://support.dunerealms.com https://forums.dunerealms.com https://clans.dunerealms.com https://wiki.dunerealms.com; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'self' https://www.dunerealms.com https://dunerealms.com https://clans.dunerealms.com"};
|
||||
|
|
|
|||
106
website/docs/great-migration.md
Normal file
106
website/docs/great-migration.md
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
# Alpha 1.0.0.7 — The Great Migration
|
||||
|
||||
## Batch 1: central directory and contextual account views
|
||||
|
||||
The existing CP account tool mixes staff access, user memberships and recognition.
|
||||
The new directory separates Users and Staff while keeping one underlying account.
|
||||
|
||||
Review URL after this batch is deployed:
|
||||
`https://cp.dunerealms.com/?migration=1#bureau/user-management`.
|
||||
The regular URL continues to use the existing editor during this incremental batch.
|
||||
|
||||
Included:
|
||||
|
||||
- Central organisation vocabulary: two departments, nine branches, contextual roles.
|
||||
- Additive `org_assignments` storage, indexed by account and scope.
|
||||
- Read-only `/api/admin/citizens`, `/catalogue`, and `/:accountId` endpoints.
|
||||
- Server-side whole-directory search by account name, Minecraft name/UUID or ID,
|
||||
contextual staff filtering and 25-record pagination with an extra sentinel row.
|
||||
- Users, Manage User and Manage Staff views. User responses exclude staff scopes
|
||||
and staff provenance. Staff views retain imported source identity for review.
|
||||
- Existing account administration and all live permissions remain unchanged.
|
||||
|
||||
Not claimed complete in batch 1: assignment writes, permission activation/projection,
|
||||
native integration migration, the recognition editor and the audit timeline. Existing memberships have not
|
||||
yet been imported into `org_assignments`; an empty new-model list is not a claim
|
||||
that the citizen has no memberships in existing systems.
|
||||
|
||||
Validation: contextual disclosure, authentication and authorisation denials,
|
||||
SQL parameterisation/literal wildcard search, filter validation, schema no-grant
|
||||
behaviour, and pagination are covered by executable tests. No financial actions,
|
||||
player identities or live staff appointments are changed by this batch.
|
||||
|
||||
## Migration rules
|
||||
|
||||
Reuse the existing API, database adapter and integration adapters. Do not rewrite
|
||||
osTicket, MyBB or LuckPerms. Human ranks lose native user/group/permission editing
|
||||
capabilities; those writes originate centrally. Do not remove or lock the native
|
||||
modules. Dev retains existing service access, separate from the human organigram.
|
||||
|
||||
Official bank account management is reserved for the Big Four and Department Heads.
|
||||
Existing system-account restrictions remain. Staff ranks contain explicit job
|
||||
nodes, without wildcard or OP grants. Assignments may overlap and expire; their
|
||||
derived rights/seals must follow their lifecycle. Earned honours remain intact.
|
||||
|
||||
## Subsequent batches
|
||||
|
||||
1. Contextual assignment editor, audited changes and central policy matrix.
|
||||
2. Map current rights to the approved hierarchy and existing native adapters;
|
||||
synchronisation/revocation, visible failures and retry.
|
||||
3. Recognition, personal and function seals, signatures across connected systems.
|
||||
4. Public staff organigram + ordered bio cards; separate Crysknife Order gallery.
|
||||
5. Full public profile template preserving current features; verified Bedrock-name
|
||||
normalisation; Picard memorial restyle/link and Big-Four-only Deceased workflow.
|
||||
6. Access/lifecycle/privacy verification, release and combined .6/.7 announcement.
|
||||
|
||||
Do not change the public version banner or publish release news before .7 is done.
|
||||
|
||||
## Batch 2: audited assignment editor and policy preparation
|
||||
|
||||
Staff assignments can be recorded and revoked within the manager's scope. One
|
||||
lead per branch/department is enforced under a shared scope lock. A scope version
|
||||
prevents stale forms from overwriting another manager's work. Automatic records
|
||||
must be changed at their source. Service accounts stay outside human appointments.
|
||||
|
||||
The permission matrix at `?migration=1#bureau/permissions` maps registered existing
|
||||
nodes to each function. It rejects wildcard/OP/native-editor nodes and official
|
||||
bank management on ordinary branch roles. Policy writes and assignments share
|
||||
atomic audit and version checks. These are preparatory records: they do not yet
|
||||
replace live roles. No native backend code is rewritten.
|
||||
|
||||
An explicit operator-run `scripts/bootstrap-organisation-control.mjs --apply`
|
||||
pins the existing Big Four and Dev service by account ID for management authority.
|
||||
It is idempotent, checks the established Owner/Dev identities, refuses conflicting
|
||||
existing principals and does not run at application startup. Its audit clearly
|
||||
states that it does not activate live permission projection.
|
||||
|
||||
## Additional Owner-approved bank work
|
||||
|
||||
After the current management batch, add a staff Client Management context reusing
|
||||
Accounts & Payments components without generic Wire Transfers.
|
||||
|
||||
Add immediate Service Compensation from Payment Control, linked to the original
|
||||
posted payment, with reason, consent, actual actor and a distinct purple type
|
||||
badge in staff/customer histories and statements. Recover funds from the original
|
||||
recipient when possible; otherwise the bank bears the cost. Never erase the
|
||||
original payment or compensate its value more than once across retries/partials.
|
||||
|
||||
The shared budget is the available balance of a dedicated Compensation Reserve.
|
||||
A monthly standing instruction funds it from Website Bank Treasury, initially
|
||||
25,000 DM; unspent funds roll forward. Big Four and the bank CEO may change that
|
||||
standing instruction and transfer reserve funds in/out through Treasury Accounts.
|
||||
No extra Officer cap/counter, CEO override system, support ticket, approval flow,
|
||||
or four-hour compensation queue. Reuse existing posting/audit infrastructure.
|
||||
|
||||
Cash conversion is reserved for the future in-game GUI + central API in both
|
||||
directions. No cash web page, redeem code flow or game changes in this batch.
|
||||
|
||||
Effective-access preview: GET /api/admin/organisation/effective?userId=UUID requires web.ranks.manage and computes explicit new-model grants with provenance. Branch Leads inherit their own Officer policy. Missing policies and blocked unsafe grants are reported. Staff Directory has an Access preview tab; User context does not. Payroll requires a pinned Big Four control principal (Dev service exception), never an Executive title alone. No live rank mutation or native projection is activated by this endpoint.
|
||||
|
||||
Default policies now enumerate 22 function mappings (nine branches with Officer/Lead, two Department Heads, Owner/Executive). Native permission editors are excluded for humans; official bank management remains departmental/executive, payroll requires pinned control identity. bootstrap-organisation-policies.mjs defaults to a plan; explicit --apply --actor=UUID requires an active control principal, retains existing policies, versions each scope and audits inserts atomically. It stores preparation data only, with no legacy rank replacement, user appointments or native group projection.
|
||||
|
||||
Runtime integration: ORGANISATION_ACCESS_ENABLED=true opts the central database adapter into fresh, read-snapshot organisation access. The default remains disabled. Enabled accessFor replaces legacy staff/owner bypass with new explicit policies, preserves ordinary/VIP/Order membership, and keeps only the pinned exempt Dev service on its existing access path. Invalid policy data fails closed, never falls back to old admin grants. This switch must not be enabled before control baseline, assignments, policy coverage and native projections are reconciled. This source batch does not enable it in production. Public session exports the account's own active functions.
|
||||
|
||||
Native bridge integration: activated game sync sends stable permission-set groups through the existing revision-confirmed /permissions/teams bridge. Explicit canonical game nodes plus retained citizen gameplay perks are combined; wildcard/OP/LuckPerms editor grants and service identities are excluded. Duplicate verified UUIDs abort the projection. Unactivated game sync stays on its existing path. Native agent sync reuses the installed osTicket adapter and maps ticket department tags; active human payloads omit native administration flags while retaining business department access. Dev service payload is unchanged. No game server or native application code is rewritten or deployed by this source batch.
|
||||
|
||||
Approved appointments and public staff page: the migration plan resolves 14 existing people into 26 current functions, validates the existing Owner identity and rejects service accounts or conflicting leaders. It defaults to dry-run; explicit application is audited and idempotent. The redesigned staff.html uses the public publication allowlist, one biography card per person, an organigram with explicit vacancies and a separate Crysknife Order gallery. Canonical profile links are retained for Bedrock display names. Active function changes now atomically queue the existing native synchronization outbox; the public process starts its retry worker only in active mode. Forum SSO filters native privilege administration for central human identities while retaining the Dev service path. Existing native products are reused.
|
||||
78
website/node/citizen-directory.mjs
Normal file
78
website/node/citizen-directory.mjs
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
import {identity} from './auth.mjs';
|
||||
import {can} from './permissions.mjs';
|
||||
import {ORGANISATION,ASSIGNMENT_ROLES,STAFF_SCOPE_TYPES,assignmentLabel} from './organisation-model.mjs';
|
||||
|
||||
const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'no-store'}});
|
||||
const LEGACY_STAFF=['staff','corestaff','owners','official_account','web_net_admin','web_net_owner','web_network','network_admin','web_dev'];
|
||||
const STATUS_SQL="CASE WHEN a.password_hash='!deleted' THEN 'deleted' WHEN a.password_hash='!banned' THEN 'banned' ELSE 'active' END";
|
||||
const fields=`a.id,a.username,a.display_name,a.created_at,${STATUS_SQL} AS account_status,
|
||||
(SELECT l.minecraft_name FROM site_game_links l WHERE l.user_id=a.id LIMIT 1) AS minecraft_name,
|
||||
(SELECT l.minecraft_uuid FROM site_game_links l WHERE l.user_id=a.id LIMIT 1) AS minecraft_uuid`;
|
||||
const placeholders=LEGACY_STAFF.map(()=>'?').join(',');
|
||||
const activeStaff=`EXISTS (SELECT 1 FROM org_assignments o WHERE o.user_id=a.id AND o.scope_type IN ('organisation','department','branch') AND o.status='active' AND o.starts_at<=? AND (o.ends_at IS NULL OR o.ends_at>?))`;
|
||||
const importedStaff='EXISTS (SELECT 1 FROM staff_source_members s WHERE s.user_id=a.id)';
|
||||
const legacyStaff=`(a.role IN (${placeholders}) OR EXISTS (SELECT 1 FROM cp_account_ranks cr WHERE cr.user_id=a.id AND cr.rank_key IN (${placeholders})))`;
|
||||
|
||||
export function directoryFilters(url,now=Date.now()){
|
||||
const context=url.searchParams.get('context')||'users';
|
||||
if(!['users','staff'].includes(context))throw new Error('Invalid directory context.');
|
||||
const query=(url.searchParams.get('q')||'').trim();
|
||||
if(query.length>80)throw new Error('Search must be at most 80 characters.');
|
||||
const pageText=url.searchParams.get('page')||'1';
|
||||
if(!/^[1-9]\d{0,3}$/.test(pageText))throw new Error('Invalid page.');
|
||||
const status=url.searchParams.get('status')||'';
|
||||
if(status&&!['active','banned','deleted'].includes(status))throw new Error('Invalid status.');
|
||||
const department=url.searchParams.get('department')||'',branch=url.searchParams.get('branch')||'';
|
||||
if(context==='users'&&(department||branch))throw new Error('Staff filters require Staff context.');
|
||||
const dept=ORGANISATION.find(d=>d.key===department);
|
||||
if(department&&!dept)throw new Error('Invalid department.');
|
||||
if(branch&&!(dept?dept.branches:ORGANISATION.flatMap(d=>d.branches)).some(b=>b.key===branch))throw new Error('Invalid branch.');
|
||||
const where=[],values=[];
|
||||
if(context==='staff'){where.push(`(${activeStaff} OR ${importedStaff} OR ${legacyStaff})`);values.push(now,now,...LEGACY_STAFF,...LEGACY_STAFF);where.push('NOT EXISTS (SELECT 1 FROM site_account_policies service WHERE service.user_id=a.id AND service.game_link_exempt=1)');}
|
||||
if(query){where.push('(a.username LIKE ? OR a.id=? OR EXISTS (SELECT 1 FROM site_game_links gl WHERE gl.user_id=a.id AND (gl.minecraft_uuid=? OR gl.minecraft_name LIKE ?)))');const term='%'+query.replace(/[=%_]/g,c=>'='+c)+'%';values.push(term,query,query,term);where[where.length-1]=where.at(-1).replaceAll('LIKE ?',"LIKE ? ESCAPE '='");}
|
||||
if(status){where.push(STATUS_SQL+'=?');values.push(status);}
|
||||
if(department||branch){
|
||||
const keys=branch?[branch]:[department,...dept.branches.map(b=>b.key)];
|
||||
where.push(`EXISTS (SELECT 1 FROM org_assignments f WHERE f.user_id=a.id AND f.scope_type IN ('department','branch') AND f.scope_key IN (${keys.map(()=>'?')}) AND f.status='active' AND f.starts_at<=? AND (f.ends_at IS NULL OR f.ends_at>?))`);values.push(...keys,now,now);
|
||||
}
|
||||
return {context,page:Number(pageText),where:where.length?' WHERE '+where.join(' AND '):'',values};
|
||||
}
|
||||
function project(row){return {id:row.id,username:row.username,displayName:row.display_name||row.username,
|
||||
status:row.account_status,createdAt:Number(row.created_at),minecraftName:row.minecraft_name||null,minecraftUuid:row.minecraft_uuid||null};}
|
||||
|
||||
export function createCitizenDirectory(db,{authenticate=identity,authorize=can,clock=Date.now}={}){
|
||||
async function assignments(ids,context){
|
||||
if(!ids.length)return [];
|
||||
const scopeClause=context==='users'?"NOT IN ('organisation','department','branch')":"IN ('organisation','department','branch')";
|
||||
const now=clock();
|
||||
const {results}=await db.prepare(`SELECT id,user_id,scope_type,scope_key,role_key,source_kind,starts_at,ends_at,version FROM org_assignments WHERE user_id IN (${ids.map(()=>'?')}) AND scope_type ${scopeClause} AND status='active' AND starts_at<=? AND (ends_at IS NULL OR ends_at>?) ORDER BY scope_type,scope_key,role_key`).bind(...ids,now,now).all();
|
||||
return results;
|
||||
}
|
||||
return async request=>{
|
||||
if(request.method!=='GET')return reply({message:'This directory endpoint is read-only.'},405);
|
||||
const actor=await authenticate(request,db);if(!actor)return reply({message:'Sign in first.'},401);
|
||||
if(!await authorize(db,actor,'web.accounts.view'))return reply({message:'Account directory permission required.'},403);
|
||||
const url=new URL(request.url);let filter;try{filter=directoryFilters(url,clock());}catch(e){return reply({message:e.message},400);}
|
||||
if(url.pathname==='/api/admin/citizens/catalogue')return reply({departments:filter.context==='staff'?ORGANISATION:[],roles:Object.fromEntries(Object.entries(ASSIGNMENT_ROLES).filter(([key])=>STAFF_SCOPE_TYPES.includes(key)===(filter.context==='staff'))),assignmentMode:'preparing',permissionsChanged:false});
|
||||
const match=url.pathname.match(/^\/api\/admin\/citizens\/([0-9a-f-]{36})$/i);
|
||||
if(match){
|
||||
// Staff managers may open a human candidate before their first appointment.
|
||||
// The directory list remains staff-only; service accounts are never candidates.
|
||||
const candidateGuard=filter.context==='staff'?' AND NOT EXISTS (SELECT 1 FROM site_account_policies service WHERE service.user_id=a.id AND service.game_link_exempt=1)':'';
|
||||
const row=await db.prepare(`SELECT ${fields} FROM site_accounts a WHERE a.id=?${candidateGuard}`).bind(match[1]).first();
|
||||
if(!row)return reply({message:'Account not found.'},404);
|
||||
const current=await assignments([row.id],filter.context);
|
||||
const account={...project(row),assignments:current.map(assignmentLabel)};
|
||||
// Staff provenance and legacy staff ranks never leave the Staff view.
|
||||
if(filter.context==='staff'){
|
||||
const {results}=await db.prepare('SELECT source_name,source_ref,imported_at FROM staff_source_members WHERE user_id=? ORDER BY source_key').bind(row.id).all();
|
||||
account.staffSources=results.map(s=>({name:s.source_name,reference:s.source_ref,importedAt:Number(s.imported_at)}));
|
||||
}
|
||||
return reply({account,context:filter.context,assignmentMode:'preparing',permissionsChanged:false});
|
||||
}
|
||||
if(url.pathname!=='/api/admin/citizens')return reply({message:'Not found.'},404);
|
||||
const {results}=await db.prepare(`SELECT ${fields} FROM site_accounts a${filter.where} ORDER BY a.username,a.id LIMIT ? OFFSET ?`).bind(...filter.values,26,(filter.page-1)*25).all();
|
||||
const rows=results.slice(0,25),current=await assignments(rows.map(a=>a.id),filter.context);
|
||||
return reply({accounts:rows.map(row=>({...project(row),assignments:current.filter(a=>a.user_id===row.id).map(assignmentLabel)})),page:filter.page,pageSize:25,hasMore:results.length>25,context:filter.context,assignmentMode:'preparing'});
|
||||
};
|
||||
}
|
||||
|
|
@ -1,11 +1,22 @@
|
|||
import {projectOrganisationGameUsers} from './organisation-game-projection.mjs';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import {accessFor,rankFor} from './permissions.mjs';
|
||||
import {gameNodesForRank} from './game-ranks.mjs';
|
||||
import {accessFor,rankFor,NODES} from './permissions.mjs';
|
||||
import {gameNodesForRank,GAME_NODE_SET,BANK_MAP} from './game-ranks.mjs';
|
||||
export async function syncGamePermissions(db,{settings=process.env,fetcher=fetch,access=user=>accessFor(db,user)}={}){
|
||||
if((settings.SERVER_CONTROL_TOKEN||'').length<64)throw Error('Game permission bridge unavailable');
|
||||
if(db.organisationAccessEnabled){
|
||||
const {results:accounts}=await db.prepare("SELECT a.id,a.username,a.role,l.minecraft_uuid FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id WHERE a.password_hash NOT LIKE '!%' AND a.role<>'memorial' AND NOT EXISTS (SELECT 1 FROM site_account_policies p WHERE p.user_id=a.id AND p.game_link_exempt=1) ORDER BY a.id").all();
|
||||
const projection=await projectOrganisationGameUsers(accounts,{access,gameNodes:new Set([...GAME_NODE_SET,...Object.keys(NODES).filter(n=>/^(?:dune|duneess|duneprotect|dunelobby)\./.test(n))]),bankMap:BANK_MAP,citizenGameNodes:async keys=>{
|
||||
const nodes=[];for(const key of keys.filter(k=>!k.startsWith('org_'))){const rank=await rankFor(db,key);for(const node of(await gameNodesForRank(db,rank)).nodes)nodes.push(node);}return nodes;
|
||||
}});
|
||||
return deliverGamePermissions(projection,{settings,fetcher});
|
||||
}
|
||||
const {results:stored}=await db.prepare("SELECT rank_key FROM cp_ranks WHERE kind='access' AND rank_level>0 ORDER BY rank_key").all();const ranks=[];
|
||||
for(const row of stored){if(!/^[a-z][a-z0-9_]{2,29}$/.test(row.rank_key))throw Error('Rank cannot be projected to game');const rank=await rankFor(db,row.rank_key),game=await gameNodesForRank(db,rank);ranks.push({id:rank.key,permissions:Object.fromEntries(game.nodes.map(n=>[n,true]))});}
|
||||
const {results:accounts}=await db.prepare("SELECT a.id,a.username,a.role,l.minecraft_uuid FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id WHERE a.password_hash NOT LIKE '!%' AND a.role<>'memorial' ORDER BY a.id").all();const users=[];
|
||||
for(const user of accounts){if(!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(user.minecraft_uuid))throw Error('Invalid verified identity');const rights=await access(user);users.push({uuid:user.minecraft_uuid.toLowerCase(),ranks:rights.ranks});}
|
||||
return deliverGamePermissions({ranks,users},{settings,fetcher});
|
||||
}
|
||||
async function deliverGamePermissions({ranks,users},{settings,fetcher}){
|
||||
const revision=randomUUID(),r=await fetcher('http://127.0.0.1:15433/permissions/teams',{method:'POST',headers:{Authorization:'Bearer '+settings.SERVER_CONTROL_TOKEN,'Content-Type':'application/json'},body:JSON.stringify({revision,actor:'website-sync',ranks,users}),signal:AbortSignal.timeout(20000)});if(!r.ok)throw Error('Game permission synchronization unavailable');const d=await r.json();if(d.ok!==true||d.revision!==revision)throw Error('Game permission synchronization unconfirmed');
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,4 +5,4 @@ export const protectedStaffRanks=ranks=>Array.isArray(ranks)&&ranks.some(isOwner
|
|||
export function gameStaffSeals(ranks=[]){return [...GAME_STAFF_SEALS,...RECOGNITION.roles].filter(seal=>ranks.includes(seal.rank)||protectedStaffRanks(ranks));}
|
||||
export function managedRoleSeals(ranks=[]){return [...(ranks.includes('web_streamer')||protectedStaffRanks(ranks)?['rank-streamer']:[]),...(ranks.includes('web_dev')||protectedStaffRanks(ranks)?['rank-dev']:[]),...(ranks.includes('crysknife')?['rank-crysknife']:[]),...gameStaffSeals(ranks).map(s=>s.key)];}
|
||||
|
||||
export function currentStaffRanks(ranks=[]){return ranks.some(key=>DEFAULT_RANKS.some(r=>r.key===key&&(key.startsWith('web_')||key.startsWith('game_')||['staff','corestaff','owners','official_account','network_admin'].includes(key))));}
|
||||
export function currentStaffRanks(ranks=[]){return ranks.some(key=>['org_owner_ceo','org_executive','org_department_head','org_branch_lead','org_officer'].includes(key)||DEFAULT_RANKS.some(r=>r.key===key&&(key.startsWith('web_')||key.startsWith('game_')||['staff','corestaff','owners','official_account','network_admin'].includes(key))));}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import {nativeAgentIdentity} from './organisation-native-projection.mjs';
|
||||
import {communityBadgeVisible} from './community-badges.mjs';
|
||||
import {publicProfileFor} from './profile.mjs';
|
||||
import {badgesFor} from './community-badges.mjs';
|
||||
|
|
@ -43,7 +44,8 @@ export function createIntegrationSSO(db,settings={}){
|
|||
const access=await accessFor(db,user),link=await db.prepare('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?').bind(user.id).first();
|
||||
const age=await db.prepare('SELECT age_band FROM site_age_declarations WHERE user_id=?').bind(user.id).first();
|
||||
const policy=await db.prepare('SELECT service_uuid,game_link_exempt FROM site_account_policies WHERE user_id=?').bind(user.id).first();
|
||||
return json({id:user.id,username:user.username,displayName:user.display_name,publicProfile:await publicProfileFor(db,user.id,settings.CP_ORIGIN||'https://cp.dunerealms.com'),role:access.rank,ranks:access.ranks,rankLabel:access.label,rankLevel:access.level,communityBadges:(await badgesFor(db,user.id)).filter(k=>communityBadgeVisible(k,access.ranks)),linked:!!link?.minecraft_uuid,gameLinkExempt:!!policy?.service_uuid&&Number(policy.game_link_exempt)===1,forumAllowed:age?.age_band!=='under15',permissions:access.nodes,sessionRef});
|
||||
const native=nativeAgentIdentity(user,access);
|
||||
return json({id:user.id,username:user.username,displayName:user.display_name,publicProfile:await publicProfileFor(db,user.id,settings.CP_ORIGIN||'https://cp.dunerealms.com'),role:access.rank,ranks:access.ranks,rankLabel:access.label,rankLevel:access.level,communityBadges:(await badgesFor(db,user.id)).filter(k=>communityBadgeVisible(k,access.ranks)),linked:!!link?.minecraft_uuid,gameLinkExempt:!!policy?.service_uuid&&Number(policy.game_link_exempt)===1,forumAllowed:age?.age_band!=='under15',permissions:native.permissions,...(native.nativePermissionManagement===false?{nativePermissionManagement:false}:{}),sessionRef});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ export async function openDatabase(env) {
|
|||
catch(error){c.release();throw error;}
|
||||
}
|
||||
const db={
|
||||
organisationAccessEnabled:env.ORGANISATION_ACCESS_ENABLED==='true',
|
||||
async query(sql,values=[]) {const c=await connection();try{return (await c.execute(mysqlSql(sql),values))[0];}finally{c.release();}},
|
||||
prepare(sql) {
|
||||
let values=[];
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import {nativeAgentIdentity} from './organisation-native-projection.mjs';
|
||||
import {syncGamePermissions} from './game-permission-sync.mjs';
|
||||
import {spawn} from 'node:child_process';
|
||||
import {existsSync} from 'node:fs';
|
||||
|
|
@ -7,7 +8,7 @@ const native='/home/dunerealms/apps/integrations/osticket/sync-agents.php';
|
|||
export async function syncNativeAgents(db){
|
||||
if(!existsSync(native))return;
|
||||
const {results}=await db.prepare('SELECT id,username,role FROM site_accounts').all();
|
||||
const accounts=[];for(const user of results){const access=await accessFor(db,user);accounts.push({...user,role:access.rank,ranks:access.ranks,permissions:access.nodes});}
|
||||
const accounts=[];for(const user of results){const access=await accessFor(db,user);accounts.push(nativeAgentIdentity(user,access));}
|
||||
await new Promise((resolve,reject)=>{const child=spawn('/usr/bin/php',[native],{stdio:['pipe','ignore','pipe']});let error='';child.stderr.on('data',chunk=>{error+=chunk.toString().slice(0,1000)});const timer=setTimeout(()=>{child.kill();reject(Error('Native staff sync timed out'));},20000);child.once('error',reject);child.once('exit',code=>{clearTimeout(timer);code===0?resolve():reject(Error('Native staff sync failed'));});child.stdin.on('error',()=>{});child.stdin.end(JSON.stringify(accounts));});
|
||||
await syncNativeSeals(db);
|
||||
await syncGamePermissions(db);
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import{badgesFor,BADGES,communityBadgeVisible}from './community-badges.mjs';
|
|||
export function visibleCommunityBadges(keys,ranks){return keys.filter(key=>BADGES.includes(key)&&ranks.length>0&&communityBadgeVisible(key,ranks));}
|
||||
export function staffSealFor(account,manifest){
|
||||
const ranks=Array.isArray(account.ranks)?account.ranks:[account.role];
|
||||
const role=ranks.includes('owners')?'OWNER':ranks.includes('web_net_admin')?'MAINNETWORKADMIN':ranks.includes('corestaff')?'CORESTAFF':(ranks.includes('network_admin')||ranks.includes('network_admin'))?'NETWORKSTAFF':'';
|
||||
const role=(ranks.includes('owners')||ranks.includes('org_owner_ceo'))?'OWNER':ranks.includes('web_net_admin')?'MAINNETWORKADMIN':ranks.includes('corestaff')?'CORESTAFF':(ranks.includes('network_admin')||ranks.includes('network_admin'))?'NETWORKSTAFF':'';
|
||||
const named=kind=>Object.values(manifest).find(asset=>asset.role===kind&&asset.label?.toLowerCase()===account.username.toLowerCase())?.footer150||null;
|
||||
if(role&&named(role))return named(role);
|
||||
if(protectedStaffRanks(ranks)&&named('OWNER'))return named('OWNER');
|
||||
|
|
|
|||
|
|
@ -3,11 +3,8 @@ import {existsSync} from 'node:fs';
|
|||
import {syncNativeAgents} from './native-agents.mjs';
|
||||
|
||||
// One coalesced change event. Retrying this table never polls accounts or ranks.
|
||||
export const NATIVE_SYNC_SCHEMA=`CREATE TABLE IF NOT EXISTS native_sync_outbox (
|
||||
job_key VARCHAR(32) PRIMARY KEY, revision CHAR(36) NOT NULL, attempts INTEGER NOT NULL,
|
||||
next_attempt_at BIGINT NOT NULL, lease_token CHAR(36) NOT NULL, lease_until BIGINT NOT NULL,
|
||||
created_at BIGINT NOT NULL, last_error VARCHAR(80) NOT NULL
|
||||
)`;
|
||||
import {NATIVE_SYNC_SCHEMA} from './native-sync-schema.mjs';
|
||||
export {NATIVE_SYNC_SCHEMA} from './native-sync-schema.mjs';
|
||||
export async function initializeNativeSyncOutbox(db){await db.prepare(NATIVE_SYNC_SCHEMA).run();}
|
||||
export function nativeSyncChange(db,now=Date.now()){
|
||||
return db.prepare("INSERT INTO native_sync_outbox(job_key,revision,attempts,next_attempt_at,lease_token,lease_until,created_at,last_error) VALUES('memberships',?,0,0,'',0,?,'') ON CONFLICT(job_key) DO UPDATE SET revision=excluded.revision,attempts=0,next_attempt_at=0,created_at=excluded.created_at,last_error='' ").bind(randomUUID(),now);
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue

Staff