forked from unimatrix/web
Merge pull request 'Add dev-key batches and sealed economic history' (#407) from feature/progression-jarvis-backend-20261118 into main
This commit is contained in:
commit
54af90fb30
43 changed files with 611 additions and 25 deletions
14
AGENTS.md
14
AGENTS.md
|
|
@ -38,3 +38,17 @@ These are the user's default preferences for future DuneRealms work. Apply them
|
|||
- Place new features in the existing navigation structure when an item already exists. Avoid duplicate menus.
|
||||
- Use the established CP design, readable colors, gold framing, and appropriate original Dune/Minecraft-inspired artwork. Company CP uses the Vaerkring/Spacing Guild-inspired palette.
|
||||
- Clearly mark unfinished features as coming soon. Do not display invented records, offers, payments, or completed actions.
|
||||
|
||||
## J.A.R.V.I.S. data-operation workflow (2026-11-18)
|
||||
|
||||
- Use Git, reviewed batches and CI for changes to files, code, schemas and action implementations.
|
||||
- Perform supported user/domain data changes through validated J.A.R.V.I.S. actions and instruments. Do not use ad hoc SQL/manual database editing as an operational shortcut.
|
||||
- Special dev keys are server/CLI-only overrides bound to an exact action manifest, environment, authorised developer identity and short validity. Never expose their issuance, secrets or execution through website routes, dropdowns or web APIs, including Big 4 accounts.
|
||||
- An ordinary code is not authority. Revalidate identity, action scope and domain conditions on execution. Keep irreversible actions explicit in the manifest.
|
||||
- Record issuance ID/hash, actor, manifest hash, each result, failures and completion; never log a secret key. Enforce once-only execution and safe retries/rollback.
|
||||
- Existing supported data actions require no PR/deployment per execution. New action logic still requires tests, Git and publication.
|
||||
- Never call a verifier-only test a successful live operation. Report local, simulated, staged and executed states accurately.
|
||||
- Seasonal changes use an explicit versioned dev batch. Preserve/reset decisions are per-season configuration, not automatic consequences of every deploy.
|
||||
- Honour the approved reset exclusions: official/protected organisations and the owner's clan/company rosters; no broader reset unless explicitly requested. No Minecraft code or deployment in this web/backend batch.
|
||||
|
||||
Current priority: implement and test the server-only dev-key executor, starting with the authorised clan-reset batch. Keep special dev tools outside the website package.
|
||||
|
|
|
|||
|
|
@ -31,3 +31,45 @@ Perform a website-wide design consistency pass: buttons, colours, spacing, typog
|
|||
|
||||
## Official identities
|
||||
Jarvis receives original DuneRealms archivist lore, a dedicated avatar and clearly ceremonial company props; do not create a company or valid keys for those props. Requested permanent Emperor POL-clan archive membership must use the existing staff-key mechanism, not an officeholder term or AD rank. Keep the Emperor office unchanged. Preserve Patrick memorial identity without login/AD. Verify separate least-privilege Git collaboration and forum publication access for Jarvis; no broad staff permissions are implied.
|
||||
|
||||
## Approved addition — Imperial Reserve economy foundation (2026-11-18)
|
||||
|
||||
Implement within the existing Postbank / J.A.R.V.I.S. backend batch. Reuse existing ledger, pricing, savings, loan and P&O components; no stock exchange, portfolios, stock orders, Market Authority or Market Surveillance. Remove the separate CHOAM navigation entry; retain shared components needed elsewhere.
|
||||
|
||||
Reserve UI: preserve issued / returned / net issued / transaction totals. Add one central multi-series line graph with individually selectable money supply, system prices, savings rate, loan rate and staff-pay index. Period selection: 7D / 30D / 90D / 1Y. Normalise each series to 100 at period start; selected dates expose actual DM, annual rates and multipliers. Handle missing data and zero baselines explicitly. Do not fabricate historical snapshots. Show current policy and existing J.A.R.V.I.S. history. Approved visual reference: exec-59ddc479-5406-4280-8533-24d9cef41af4.png (concept values only).
|
||||
|
||||
Configurable starting formulas:
|
||||
- Economic index E = (current circulating money / reference circulating money)^0.25. Distinguish circulation from reserve balances and net issuance. Transfers to Tax do not burn money. This is monetary pressure, not measured consumer-price inflation.
|
||||
- Demand factor D = ((units sold + 10) / (units offered + 10))^0.15 over a seven-day window. Define consistent eligible inventory/cohort accounting before enabling this factor.
|
||||
- Target system price = base price * E * D; daily adjustment at most +/-5%, absolute range 50–200% of base. Player asking prices remain independent unless explicitly opted into dynamic pricing.
|
||||
- Annual savings rate = base savings rate + 5 percentage points * (E - 1), bounded by configured policy and account terms.
|
||||
- Annual loan rate = base loan rate + 10 percentage points * (E - 1), bounded by configured policy; new offers only. Existing contracts retain their agreed rates.
|
||||
- Target P&O staff pay = base pay * E; monthly adjustment at most +/-5%. Calculate from base pay, not recursively multiplying the previous indexed pay.
|
||||
|
||||
Persist versioned index snapshots, source observations, baseline, effective dates and tariff versions. Never apply a cadence step twice on retries. Freeze buyer/seller/Tax amounts in an accepted checkout quote; use existing settlement and tax policies, no invented additional charges. Display the agreed price and any quote expiry before confirmation; committed transactions retain their snapshot.
|
||||
|
||||
Future economic threshold events and political Decisions are deferred. The foundation should expose recorded observations for later use, without activating automatic event triggers now. No production publication is implied by this design acceptance.
|
||||
|
||||
## Authorised publication reset (2026-11-18)
|
||||
|
||||
User confirmed ALL DM balances, including system reserves, reset to zero at publication. Preserve financial audit consistency; reconcile pending orders, holds, payouts and auctions before applying. New issuance budget and a fresh reference baseline follow the reset. No zero-denominator index or historical test data baseline.
|
||||
|
||||
Delete non-official clans except the user's owned clan(s); retain official/protected organisations and Unimatrix-Artreides / Unicorp. Do not delete companies. Reset non-official retained clans and companies to Basic. Preserve user's memberships and official/protected memberships; other players may be clan/company-less. Clear home blocks, claims and related claim configuration, including retained entities. Use authoritative IDs and institution registry when constructing the reviewed manifest.
|
||||
|
||||
Clear non-kit Exchange test listings (including diamond, shovel and test postings), retain kits. User explicitly declined an Exchange-items backup. Preserve required financial audit records.
|
||||
|
||||
Reset USED clan and company founding entitlements as part of this publication. Preserve historical consumed-key records; use a reset-generation replacement entitlement for accounts without a retained corresponding entity. Do not reactivate old secrets or grant duplicate live founding entitlements to retained owners. Apply once under a recorded reset ID, not at each deploy/startup. This must explicitly integrate with the existing lifetime-original grant uniqueness rule before execution.
|
||||
|
||||
## Approved J.A.R.V.I.S. key icon family (2026-11-18)
|
||||
|
||||
Approved concept sheet: artwork/jarvis-key-family-lore-approved-v1.png. Built-in image generation produced the original family, then an approved lore-rich revision. Prompt direction: thirty coherent tangible Minecraft-inspired gold keys and sealed data rods, emerald background; clan/sietch architecture, trade mechanisms, imperial office symbols, gold-capped archival rods. These are item icons, not seals or medallions. This is a design reference, not a ready-to-use transparent sprite atlas. Produce individual clean assets before UI integration; reuse one image per instrument type, never per secret instance. Existing and planned types share scale, perspective, material treatment and silhouette language. Planned artwork does not imply an implemented entitlement.
|
||||
|
||||
Normal key family covers founding, upgrades, subentities, offices, delegation, parent links, transfers, quests, milestones, XP corrections, seasonal XP reserve, economic snapshots, bank corrections, Rihla, events, promotions, private acquisitions, kits, items and repairs. Economic snapshots are immutable archival instruments; chart values read their sealed records, with corrections in linked new records.
|
||||
|
||||
DEV batch/reset rod artwork belongs ONLY in developer documentation and CLI/server tooling. Never ship these special keys, their secret material or generator options through website assets, dropdowns or web APIs. Explicit developer authority is required outside the web surface. Record ID/hash, actor, approved manifest and per-step results, never the secret. Domain changes including resets and corrections follow validated J.A.R.V.I.S. operations rather than manual database edits.
|
||||
|
||||
## News editor addition — approved 2026-11-18
|
||||
|
||||
Extend the existing Imperial Bureau news editor, not a separate CMS/CP. Add accessible rich editing: headings, bold/italic, lists, links, image upload/insertion with alt text/caption and alignment/size controls, preview, draft save and existing publication actions. Preserve existing author, category, permissions, optimistic version checks and Boards/Discord delivery identities. Sanitise structured/rich content on the server; allowlisted markup only, no scripts/event handlers/unsafe URLs. Existing plain-text posts remain readable without migration loss. Provide appropriate plain-text/forum/Discord projections from the same source. No unsafe raw HTML paste or unsupported formatting claims.
|
||||
|
||||
Immediate content request: user has created the first live dev-key batch news draft and wants the approved key-family artwork inserted, while retaining draft status so the user publishes it. Publication is no longer authorised as an automatic next step. Do not expose secret key material; public instrument reference 621a99a4-3f40-4123-8d8e-70a80ecdaa6c is permitted. The existing browser-control route is unavailable; image insertion has not been performed and requires a supported authenticated editing path. Do not work around this using an ad hoc manual database change.
|
||||
|
|
|
|||
BIN
docs/design/artwork/jarvis-key-family-lore-approved-v1.png
Normal file
BIN
docs/design/artwork/jarvis-key-family-lore-approved-v1.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.3 MiB |
37
tools/jarvis-dev-clan-reset-cli.mjs
Normal file
37
tools/jarvis-dev-clan-reset-cli.mjs
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
// Installed outside the website. No HTTP entry point and no arbitrary SQL/action.
|
||||
import {createRequire} from 'node:module';
|
||||
import {randomBytes} from 'node:crypto';
|
||||
import {createDevKeyAuthority} from './jarvis-dev-key.mjs';
|
||||
import {clanResetManifest,executeClanReset} from './jarvis-dev-clan-reset.mjs';
|
||||
const BATCH='clan-reset-20261118-v1';
|
||||
if(process.getuid?.()!==0)throw Error('Run the installed CLI with explicit server administrator authority');
|
||||
if(process.argv.length!==3||!['--plan','--apply'].includes(process.argv[2]))throw Error('Choose --plan or --apply');
|
||||
process.loadEnvFile('/home/dunerealms/.config/dunerealms.env');
|
||||
const require=createRequire('/home/dunerealms/apps/dunerealms/current/node/mysql.mjs'),mysql=require('mysql2/promise');
|
||||
const db=await mysql.createConnection({host:process.env.DB_HOST||'127.0.0.1',port:Number(process.env.DB_PORT||3306),user:process.env.DB_USER,password:process.env.DB_PASSWORD,database:process.env.DB_NAME,supportBigNumbers:true,bigNumberStrings:true,multipleStatements:false});
|
||||
const tx={query:async(sql,args=[])=>{const [rows]=await db.execute(sql,args);return rows;},first:async(sql,args=[])=>{const [rows]=await db.execute(sql,args);return rows[0]||null;}};
|
||||
let locked=false,started=false;
|
||||
try{
|
||||
const lock=await tx.first("SELECT GET_LOCK('jarvis-dev-clan-reset',10) acquired");if(Number(lock.acquired)!==1)throw Error('Another clan reset is running');locked=true;
|
||||
await db.beginTransaction();started=true;
|
||||
const prior=await tx.first("SELECT id FROM account_audit WHERE action='dev-clan-reset-complete' AND details LIKE ?",['%'+BATCH+'%']);
|
||||
if(prior){await db.rollback();started=false;console.log(JSON.stringify({batchId:BATCH,state:'already-completed',replayed:true}));}
|
||||
else{
|
||||
const manifest=await clanResetManifest(tx,'unimatrix999');
|
||||
const names=await tx.query('SELECT id,name FROM site_clans WHERE active=1 ORDER BY id');
|
||||
console.log(JSON.stringify({batchId:BATCH,state:'planned',retained:names.filter(c=>manifest.retainClanIds.includes(c.id)),archive:names.filter(c=>manifest.deleteClanIds.includes(c.id))}));
|
||||
if(process.argv[2]==='--plan'){await db.rollback();started=false;}
|
||||
else{
|
||||
const actor={id:'server-root'},authority=createDevKeyAuthority({secret:randomBytes(32).toString('hex'),environment:'production',authorize:async a=>process.getuid()===0&&a.id===actor.id});
|
||||
const issued=await authority.issue(actor,manifest),record=await authority.verify(actor,issued.key,manifest);
|
||||
// Record the receipt without ever printing the bearer key or signing secret.
|
||||
await tx.query('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[issued.record.id,manifest.ownerId,'dev-key-issued',JSON.stringify({...issued.audit,batchId:BATCH}),Date.now()]);
|
||||
const result=await executeClanReset(tx,{record,expectedManifest:manifest,batchId:BATCH});
|
||||
const after=await clanResetManifest(tx,'unimatrix999');
|
||||
if(after.deleteClanIds.length)throw Error('Reset verification failed');
|
||||
await db.commit();started=false;
|
||||
console.log(JSON.stringify({batchId:BATCH,keyId:record.id,state:'completed',...result,companiesChanged:false,balancesChanged:false}));
|
||||
}
|
||||
}
|
||||
}catch(error){if(started)await db.rollback();console.error(JSON.stringify({batchId:BATCH,state:'failed',reason:'Reset failed; transaction rolled back',code:error.code||error.name}));process.exitCode=1;}
|
||||
finally{if(locked)await tx.query("SELECT RELEASE_LOCK('jarvis-dev-clan-reset')");await db.end();}
|
||||
39
tools/jarvis-dev-clan-reset.mjs
Normal file
39
tools/jarvis-dev-clan-reset.mjs
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
// CLI-only domain handler. Uses the existing archive semantics: inactive clan,
|
||||
// removed roster and closed requests; financial/history rows are not erased.
|
||||
import {createHash,randomUUID} from 'node:crypto';
|
||||
const digest=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
||||
export async function clanResetManifest(tx,ownerUsername){
|
||||
const owner=await tx.first('SELECT id,username FROM site_accounts WHERE username=? FOR UPDATE',[ownerUsername]);
|
||||
if(!owner)throw Error('Preserved owner not found');
|
||||
const clans=await tx.query('SELECT id,name,owner_id,active,version FROM site_clans ORDER BY id FOR UPDATE');
|
||||
const institutions=await tx.query('SELECT clan_id,institution_key FROM site_clan_institutions ORDER BY clan_id FOR UPDATE');
|
||||
const members=await tx.query('SELECT user_id,clan_id,clan_role FROM site_clan_members ORDER BY user_id FOR UPDATE');
|
||||
const protectedIds=new Set(institutions.map(i=>i.clan_id));
|
||||
const active=clans.filter(c=>Number(c.active)===1),keep=active.filter(c=>protectedIds.has(c.id)||c.owner_id===owner.id);
|
||||
if(!keep.some(c=>c.owner_id===owner.id))throw Error('Preserved owner clan is missing');
|
||||
return {action:'clan-reset',state:'planned',ownerId:owner.id,
|
||||
retainClanIds:keep.map(c=>c.id),deleteClanIds:active.filter(c=>!keep.some(k=>k.id===c.id)).map(c=>c.id),
|
||||
inventoryHash:digest({clans,institutions,members}),preserveOwnerMembers:true,
|
||||
scope:'clans-only-existing-archive-flow',companiesChanged:false,balancesChanged:false};
|
||||
}
|
||||
export async function executeClanReset(tx,{record,expectedManifest,batchId,now=Date.now()}){
|
||||
if(record.manifestHash==null||JSON.stringify(record.manifest)!==JSON.stringify(expectedManifest)){
|
||||
// Key manifests are canonicalised; compare the actual scope and inventory,
|
||||
// independent of JSON property order.
|
||||
const actual=record.manifest;
|
||||
if(!actual||Object.keys(actual).sort().join()!==Object.keys(expectedManifest).sort().join()||Object.keys(expectedManifest).some(k=>JSON.stringify(actual[k])!==JSON.stringify(expectedManifest[k])))throw Error('Reset manifest mismatch');
|
||||
}
|
||||
const prior=await tx.first("SELECT id FROM account_audit WHERE action='dev-clan-reset-complete' AND details LIKE ? FOR UPDATE",['%'+batchId+'%']);
|
||||
if(prior)return {replayed:true,archived:0};
|
||||
let archived=0;
|
||||
for(const id of expectedManifest.deleteClanIds){
|
||||
const changed=await tx.query('UPDATE site_clans SET active=0,version=version+1,updated_at=? WHERE id=? AND active=1',[now,id]);
|
||||
if(changed.affectedRows!==1)throw Error('Clan inventory changed');
|
||||
await tx.query('DELETE FROM site_clan_members WHERE clan_id=?',[id]);
|
||||
await tx.query("UPDATE site_clan_requests SET status='closed',updated_at=? WHERE clan_id=? AND status='pending'",[now,id]);
|
||||
await tx.query('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),expectedManifest.ownerId,'dev-clan-reset-step',JSON.stringify({batchId,keyId:record.id,executor:record.actorId,clanId:id,action:'archive'}),now]);
|
||||
archived++;
|
||||
}
|
||||
await tx.query('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),expectedManifest.ownerId,'dev-clan-reset-complete',JSON.stringify({batchId,keyId:record.id,manifestHash:record.manifestHash,archived,retained:expectedManifest.retainClanIds}),now]);
|
||||
return {replayed:false,archived,retained:expectedManifest.retainClanIds};
|
||||
}
|
||||
36
tools/jarvis-dev-key.mjs
Normal file
36
tools/jarvis-dev-key.mjs
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
// Server/CLI only. Never import this module into website code or expose it by API.
|
||||
import {createHmac,createHash,randomUUID,timingSafeEqual} from 'node:crypto';
|
||||
const hash=value=>createHash('sha256').update(value).digest('hex');
|
||||
const canonical=value=>{
|
||||
if(value===null||typeof value==='boolean'||typeof value==='string')return JSON.stringify(value);
|
||||
if(typeof value==='number'&&Number.isSafeInteger(value))return String(value);
|
||||
if(Array.isArray(value))return '['+value.map(canonical).join(',')+']';
|
||||
if(value&&Object.getPrototypeOf(value)===Object.prototype)return '{'+Object.keys(value).sort().map(k=>JSON.stringify(k)+':'+canonical(value[k])).join(',')+'}';
|
||||
throw TypeError('Invalid batch manifest');
|
||||
};
|
||||
export function createDevKeyAuthority({secret,environment,authorize,clock=Date.now}){
|
||||
if(typeof secret!=='string'||!/^\w+$/.test(environment||'')||!/^[a-f0-9]{64}$/i.test(secret)||typeof authorize!=='function')throw TypeError('Developer authority configuration required');
|
||||
const sign=payload=>createHmac('sha256',Buffer.from(secret,'hex')).update(payload).digest('hex');
|
||||
const allowed=async actor=>{if(!actor?.id||!await authorize(actor))throw Error('Developer access required');};
|
||||
return Object.freeze({
|
||||
async issue(actor,manifest,{ttlMs=600000}={}){
|
||||
await allowed(actor);
|
||||
if(!Number.isSafeInteger(ttlMs)||ttlMs<1||ttlMs>900000||manifest?.action!=='clan-reset'||manifest.state!=='planned')throw TypeError('Invalid developer batch');
|
||||
const now=clock(),record={id:randomUUID(),environment,actorId:actor.id,issuedAt:now,expiresAt:now+ttlMs,manifestHash:hash(canonical(manifest)),manifest:JSON.parse(canonical(manifest))};
|
||||
const payload=Buffer.from(canonical(record)).toString('base64url');
|
||||
const key='DEV-BATCH.'+payload+'.'+sign(payload);
|
||||
return {key,record,audit:{id:record.id,actorId:actor.id,environment,manifestHash:record.manifestHash,keyHash:hash(key),issuedAt:now,expiresAt:record.expiresAt}};
|
||||
},
|
||||
async verify(actor,key,expectedManifest){
|
||||
await allowed(actor);
|
||||
if(typeof key!=='string'||key.length>65536)throw Error('Invalid developer key');
|
||||
const parts=key.split('.');if(parts.length!==3||parts[0]!=='DEV-BATCH'||!/^[a-f0-9]{64}$/.test(parts[2]))throw Error('Invalid developer key');
|
||||
const wanted=Buffer.from(sign(parts[1]),'hex'),given=Buffer.from(parts[2],'hex');
|
||||
if(!timingSafeEqual(wanted,given))throw Error('Invalid developer key');
|
||||
let record;try{record=JSON.parse(Buffer.from(parts[1],'base64url').toString());}catch{throw Error('Invalid developer key');}
|
||||
if(record.environment!==environment||record.actorId!==actor.id||record.expiresAt<=clock()||record.issuedAt>clock()||record.expiresAt-record.issuedAt>900000)throw Error('Developer key unavailable');
|
||||
if(record.manifestHash!==hash(canonical(record.manifest))||record.manifestHash!==hash(canonical(expectedManifest)))throw Error('Batch manifest changed');
|
||||
return record;
|
||||
}
|
||||
});
|
||||
}
|
||||
30
tools/package-dev-clan-reset.mjs
Normal file
30
tools/package-dev-clan-reset.mjs
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
// Packages only the reviewed fixed-purpose CLI; excludes website code/secrets.
|
||||
import {readFileSync,writeFileSync} from 'node:fs';import {createHash} from 'node:crypto';
|
||||
const files=Object.fromEntries(['jarvis-dev-key.mjs','jarvis-dev-clan-reset.mjs','jarvis-dev-clan-reset-cli.mjs'].map(name=>{const bytes=readFileSync(new URL(name,import.meta.url));return [name,{data:bytes.toString('base64'),sha256:createHash('sha256').update(bytes).digest('hex')}];}));
|
||||
const output=process.argv[2];if(!output)throw Error('Output path required');
|
||||
writeFileSync(output,`#!/usr/bin/python3
|
||||
import os,sys,json,base64,hashlib,subprocess,stat
|
||||
if os.geteuid()!=0: raise SystemExit('Run with server administrator authority')
|
||||
if len(sys.argv)!=2 or sys.argv[1] not in ('--plan','--apply'): raise SystemExit('Use --plan or --apply')
|
||||
files=json.loads(${JSON.stringify(JSON.stringify(files))})
|
||||
target='/usr/local/libexec/dunerealms-dev/keytest-20261118'
|
||||
for directory in ['/usr/local/libexec','/usr/local/libexec/dunerealms-dev',target]:
|
||||
if os.path.lexists(directory):
|
||||
st=os.lstat(directory)
|
||||
if not stat.S_ISDIR(st.st_mode) or st.st_uid!=0 or st.st_mode & 0o022: raise SystemExit('Unsafe installation directory')
|
||||
else: os.mkdir(directory,0o755)
|
||||
for name,item in files.items():
|
||||
data=base64.b64decode(item['data'])
|
||||
if hashlib.sha256(data).hexdigest()!=item['sha256']: raise SystemExit('Package hash mismatch')
|
||||
dest=os.path.join(target,name)
|
||||
if os.path.islink(dest): raise SystemExit('Unsafe installation target')
|
||||
temporary=dest+'.install-'+str(os.getpid())
|
||||
fd=os.open(temporary,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600)
|
||||
with os.fdopen(fd,'wb') as out:
|
||||
out.write(data);out.flush();os.fsync(out.fileno())
|
||||
os.chmod(temporary,0o644);os.replace(temporary,dest)
|
||||
node='/home/dunerealms/.nvm/versions/node/v22.23.3/bin/node'
|
||||
for name in files: subprocess.run([node,'--check',os.path.join(target,name)],check=True)
|
||||
raise SystemExit(subprocess.run([node,os.path.join(target,'jarvis-dev-clan-reset-cli.mjs'),sys.argv[1]]).returncode)
|
||||
`);
|
||||
console.log(JSON.stringify({output,files:Object.keys(files),containsSecrets:false}));
|
||||
|
|
@ -33,7 +33,7 @@ export function createOrganisationPortraitTree(organisation,{kind='company'}={})
|
|||
if(index===2&&!politics&&!group.rows.length)continue;
|
||||
const section=el('section',undefined,'dynasty-interior '+(index===0?'dynasty-family':'dynasty-council')),grid=el('div',undefined,'dynasty-council-grid');section.append(el('h3',group.title));
|
||||
if(!group.rows.length)grid.append(el('p',index===0?'Position vacant.':'No current appointments.'));
|
||||
for(const member of group.rows){const card=el('article',undefined,'dynasty-player'),portrait=el('div',undefined,'dynasty-portrait'),face=el('img'),link=el('a',member.name||member.username);face.src='https://cp.dunerealms.com/api/avatars/face/roster/'+encodeURIComponent(member.username);face.alt=member.username+' Minecraft portrait';face.width=face.height=96;face.loading='lazy';portrait.append(face);link.href='https://www.dunerealms.com/'+(member.memorial?'memorial/'+encodeURIComponent(member.memorial):'people/'+encodeURIComponent(member.username));card.append(el('small',member.title||member.role||'Member'),portrait,link,el('small','@'+member.username));if(member.expiresAt)card.append(el('small','Term ends '+new Date(member.expiresAt).toLocaleDateString('en-GB')));grid.append(card);}section.append(grid);root.append(section);
|
||||
for(const member of group.rows){const card=el('article',undefined,'dynasty-player'),portrait=el('div',undefined,'dynasty-portrait'),face=el('img'),link=el('a',member.name||member.username);face.src=member.memorial==='patrick-stewart'?'https://cp.dunerealms.com/api/avatars/memorial/patrick-stewart':'https://cp.dunerealms.com/api/avatars/face/roster/'+encodeURIComponent(member.username);face.alt=member.username+' Minecraft portrait';face.width=face.height=96;face.loading='lazy';portrait.append(face);link.href='https://www.dunerealms.com/'+(member.memorial?'memorial/'+encodeURIComponent(member.memorial):'people/'+encodeURIComponent(member.username));card.append(el('small',member.title||member.role||'Member'),portrait,link,el('small','@'+member.username));if(member.expiresAt)card.append(el('small','Term ends '+new Date(member.expiresAt).toLocaleDateString('en-GB')));grid.append(card);}section.append(grid);root.append(section);
|
||||
}
|
||||
root.dataset.structure=politics?'office-deeds':'company-board';return root;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
// Shared syntax only: a readable edition is never proof of ownership or authority.
|
||||
const legacy=/^(STAFF-COM|STAFF-POL|CLAN-SUB|COM-SUB|POL-CLAN|CLAN|COM|POL)-([A-F0-9]{48})$/;
|
||||
const versioned=/^(STAFF-COM|STAFF-POL|CLAN-SUB|COM-SUB|POL-CLAN|CLAN|COM|POL)-(ALPHA|BETA|LIVE)-((?:0|[1-9]\d{0,2})(?:\.(?:0|[1-9]\d{0,2})){3})-(S\d{2,4})-([A-F0-9]{8}(?:-[A-F0-9]{8}){5})$/;
|
||||
const legacy=/^(ECO-SNAP|STAFF-LINK|STAFF-COM|STAFF-POL|XFR|CLAN-SUB|COM-SUB|POL-CLAN|QST|QSM|CLAN|COM|POL)-([A-F0-9]{48})$/;
|
||||
const versioned=/^(ECO-SNAP|STAFF-LINK|STAFF-COM|STAFF-POL|XFR|CLAN-SUB|COM-SUB|POL-CLAN|QST|QSM|CLAN|COM|POL)-(ALPHA|BETA|LIVE)-((?:0|[1-9]\d{0,2})(?:\.(?:0|[1-9]\d{0,2})){3})-(S\d{2,4})-([A-F0-9]{8}(?:-[A-F0-9]{8}){5})$/;
|
||||
export function parseOrganisationCode(value){
|
||||
if(typeof value!=='string'||value.length>128)throw new TypeError('Invalid organisation code');
|
||||
const code=value.trim().toUpperCase(),old=code.match(legacy);
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ export function visibleCPItem(user,workspace,item){
|
|||
if(workspace==='bank'&&item.id==='federal-reserve')return true;
|
||||
if(!user||!Array.isArray(user.permissions))return false;
|
||||
const has=node=>user.permissions.includes(node)||user.permissions.includes(node.replace(/^web\./,'cp.'));
|
||||
if(workspace==='bank'&&item.staffOnly)return has(item.viewPermission)||has('web.bank.staff.view')||has('web.bank.staff.manage');
|
||||
if(workspace==='clan')return has('web.menu.game')&&(item.id!=='clan-mail'||has('web.mail.internal.view'));
|
||||
if(workspace==='quests')return has('web.quests.view');
|
||||
if(workspace==='kits')return has('web.menu.inventory');
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
.codex-management{color:#e8e4d1;min-width:0}.codex-management-hero{display:flex;align-items:center;gap:22px;padding:22px;border-bottom:1px solid #9d854c;background:linear-gradient(100deg,#153b32eb,#122e29e8),url(https://www.dunerealms.com/assets/guild.webp) center/cover}.codex-management-hero>img{width:84px;height:84px;object-fit:contain}.codex-management h2,.codex-management h3{color:#eed495;font-family:Georgia,serif}.codex-management h2{font-size:clamp(25px,3vw,38px);margin:8px 0}.codex-management small{letter-spacing:.13em;color:#c5ad72}.codex-preview-notice{margin:18px;padding:12px 16px;border-left:3px solid #bd9e57;background:#223b34;line-height:1.6}.codex-management-grid{display:grid;grid-template-columns:minmax(0,1.5fr) minmax(250px,1fr);gap:18px}.codex-management [role=tabpanel]{padding:0 18px 18px}.codex-management-box{min-width:0;border:1px solid #7d794f;border-radius:12px;padding:20px;background:linear-gradient(130deg,#1b3d32f5,#122d27f5)}.codex-management-box h3{margin-top:0;font-size:23px}.codex-management p{line-height:1.65}.codex-table-scroll{overflow:auto;max-width:100%;margin:16px 0}.codex-management table{width:100%;border-collapse:collapse;font-size:14px}.codex-management th{text-align:left;color:#efd598;background:#263f35}.codex-management td,.codex-management th{padding:12px;border-bottom:1px solid #526649;vertical-align:top}.codex-field{display:grid;gap:8px;margin:15px 0;font-size:14px}.codex-field>span{color:#d3c28e}.codex-field input,.codex-field select,.codex-field textarea{box-sizing:border-box;width:100%;min-width:0;padding:12px;border:1px solid #667b61;border-radius:6px;background:#102a24;color:#eee6cf;font:inherit}.codex-management button:disabled{padding:12px 16px;margin:6px 8px 6px 0;border:1px solid #68745a;border-radius:7px;background:#263c32;color:#b5b59f;cursor:not-allowed}.codex-seal-note{padding:12px;border-left:2px solid #aa9259;margin:14px 0;background:#142e27}.codex-seal-note strong{color:#e4c67d}.codex-seal-note p{margin-bottom:0}@media(max-width:900px){.codex-management-grid{grid-template-columns:minmax(0,1fr)}}@media(max-width:500px){.codex-management-hero{padding:14px;gap:12px}.codex-management-hero>img{width:60px;height:60px}.codex-management [role=tabpanel]{padding:0 10px 10px}.codex-management-box{padding:14px}}
|
||||
|
||||
.codex-live-register nav{display:flex;align-items:center;flex-wrap:wrap;gap:12px}.codex-live-register nav button{padding:10px 16px;border:1px solid #a48b4d;border-radius:7px;background:#18372d;color:#eed594;cursor:pointer}.codex-live-register td{overflow-wrap:anywhere}
|
||||
.jarvis-generator{display:grid;gap:18px}.jarvis-generator .codex-preview-notice{margin:0}.jarvis-generator-fields{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:0 16px}.jarvis-generator-summary{display:grid;grid-template-columns:minmax(90px,1fr) minmax(0,1.4fr);gap:0;margin:20px 0}.jarvis-generator-summary dt,.jarvis-generator-summary dd{margin:0;padding:10px 0;border-bottom:1px solid #526649;overflow-wrap:anywhere}.jarvis-generator-summary dt{color:#d3c28e}.jarvis-generator-consent{display:flex;align-items:center;gap:10px;margin:20px 0}.jarvis-generator-badge{display:inline-block;padding:3px 12px;border:1px solid #7d794f;border-radius:20px}.jarvis-generator [hidden]{display:none}.jarvis-generator aside{position:relative;overflow:hidden;padding-bottom:72px}.jarvis-archive-box{position:absolute;bottom:18px;right:24px;width:19px;height:34px;background:linear-gradient(#d7d9bf 0 4%,#102b57 4% 24%,#b3c9ce 24% 44%,#1b4272 44%);border:2px solid #102948;box-shadow:3px 3px 0 #09213a;opacity:.55;transform:rotate(-6deg)}.jarvis-archive-box:before{content:'';position:absolute;width:5px;height:5px;left:6px;top:-7px;background:#cadfd4;border:1px solid #18345a}.jarvis-archive-box:after{content:'';position:absolute;left:8px;top:7px;height:23px;border-left:2px solid #18345a}@media(max-width:600px){.jarvis-generator-fields{grid-template-columns:minmax(0,1fr)}}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import {createKeyGeneratorDesign} from './cp-v2-key-generator.mjs';
|
||||
import {mountProgressionDesign} from './cp-v2-progression.mjs';
|
||||
import {showInvalidKey} from './cp-v2-key-validation.mjs';
|
||||
import {createJarvisRegister} from './cp-v2-jarvis-register.mjs';
|
||||
|
|
@ -18,7 +19,7 @@ export function mountCodexManagement(host,{initial='keys',fetcher=fetch}={}){
|
|||
function retained(content,label,path,name,args=[]){const node=make('details',undefined,'codex-retained-service'),summary=make('summary',label),host=make('div');let started=false;summary.onclick=()=>{if(started)return;started=true;import(path).then(module=>{if(mounted)disposers.push(module[name](host,...args));}).catch(()=>{if(mounted)host.textContent='Existing service unavailable. Reload to retry.';});};node.append(summary,host);content.append(node);}
|
||||
|
||||
const keys=make('div',undefined,'codex-management-grid'),matrix=box('Keys & deeds','A common register, with the authority of each instrument kept distinct.');matrix.append(table(['Instrument','Seal','Purpose','Source'],TYPES));keys.append(matrix);const provenance=box('The mark of origin','Original keys carry an original seal. Authorised staff issues carry a staff seal.');for(const [title,copy] of [['Original seal','An original key may replace a staff-issued upgrade without granting duplicate rights.'],['Staff seal','Each issue records the issuer, reason and a server-signed issue proof.'],['Replacement','A replacement invalidates the unused predecessor and retains its original provenance.']]){const row=make('section',undefined,'codex-seal-note');row.append(make('strong',title),make('p',copy));provenance.append(row);}keys.append(provenance);groups.push({id:'keys',title:'Keys & deeds',content:keys});
|
||||
const issuance=make('div',undefined,'codex-management-grid'),issue=box('Issue an instrument','Staff issuance uses the same generator and lifecycle as original keys.');const form=make('form',undefined,'codex-management-form');form.onsubmit=e=>e.preventDefault();form.append(field('Instrument',TYPES.map(row=>row[0])),field('Quality',['Common','Uncommon','Rare','Very Rare','Legendary']),field('Recipient','Citizen or organisation'),field('Issue reason',['Support resolution','Event reward','Authorised grant']),field('Season','Current season · supplied by server'),field('Validity','Optional expiry'),field('Reason / decision reference','Required audit reference'),locked('Generate key'));issue.append(form);const replace=box('Replace or revoke','Select an existing unused instance. No second entitlement is created.');replace.append(field('Instance ID','Unique J.A.R.V.I.S. instance'),field('Reason','Required audit reason'),locked('Replace key'),locked('Revoke unused key'));issuance.append(issue,replace);groups.push({id:'issuance',title:'Issuance',content:issuance});
|
||||
const issuance=createKeyGeneratorDesign();const replace=box('Replace or revoke','Select an existing unused instance. No second entitlement is created.');replace.append(field('Instance ID','Unique J.A.R.V.I.S. instance'),field('Reason','Required audit reason'),locked('Replace key'),locked('Revoke unused key'));issuance.append(replace);groups.push({id:'issuance',title:'Issuance',content:issuance});
|
||||
const definitions=box('Items & definitions','Definitions describe a type; every issued item receives its own unique instance ID.');definitions.append(field('Search definitions','Name, type or definition ID'),empty(['Artwork','Definition','Type','Quality','Revision','State'],'Definition service not connected.'),locked('Create definition'));retained(definitions,'Open existing item catalogue','./cp-v2-item-register.mjs','mountItemRegister');groups.push({id:'items',title:'Items & definitions',content:definitions});
|
||||
const kits=box('Kits','Kit definitions, equipment and redeemable kit instances share the J.A.R.V.I.S. catalogue.');kits.append(empty(['Kit','Revision','Contents','Availability'],'Kit catalogue adapter pending.'),locked('Define kit'));retained(kits,'Open existing kit service','./cp-v2-kit-directorate.mjs','mountKitDirectorate',['server-kits']);groups.push({id:'kits',title:'Kits',content:kits});
|
||||
const publication=box('Publication','Review versions and their distribution channels before publication.');publication.append(empty(['Definition','Revision','Approval','Channels','State'],'Publication queue is not connected.'),locked('Publish approved revision'));retained(publication,'Open existing publication service','./cp-v2-kit-directorate.mjs','mountKitDirectorate',['kit-publishing']);groups.push({id:'publication',title:'Publication',content:publication});
|
||||
|
|
|
|||
|
|
@ -0,0 +1 @@
|
|||
.pb-economy-chart{min-width:0;margin:24px 0;padding:20px;border:1px solid #a58e55;border-radius:14px;background:linear-gradient(125deg,#193d30,#0c2923);color:#e8e4ce}.pb-economy-chart header{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px}.pb-economy-chart h3{margin:0;color:#efd58d;font:600 24px Georgia,serif}.pb-economy-chart nav,.pb-economy-legend{display:flex;flex-wrap:wrap;gap:8px}.pb-economy-legend{margin:18px 0}.pb-economy-chart button{padding:7px 12px;border:1px solid #8e8053;border-radius:6px;color:inherit;background:#102e25;cursor:pointer}.pb-economy-chart button[aria-pressed=true]{background:#435638}.pb-economy-chart button[aria-pressed=false]{opacity:.65}.pb-economy-chart svg{display:block;width:100%;height:auto;min-height:170px}.pb-economy-chart label{display:grid;gap:8px;margin-top:16px}.pb-economy-chart select{box-sizing:border-box;max-width:100%;width:100%;padding:10px;border:1px solid #8e8053;border-radius:6px;color:inherit;background:#102e25}.pb-economy-values{display:grid;grid-template-columns:minmax(100px,1fr) minmax(0,2fr);gap:0}.pb-economy-values dt,.pb-economy-values dd{margin:0;padding:8px;border-bottom:1px solid #435a42;overflow-wrap:anywhere}.pb-economy-values dt{color:#d1bd83}.pb-economy-chart [hidden]{display:none}@media(max-width:500px){.pb-economy-chart{padding:12px}.pb-economy-chart h3{font-size:21px}.pb-economy-values{font-size:13px}}
|
||||
36
website/control-panel/public/cp-v2/cp-v2-economy-chart.mjs
Normal file
36
website/control-panel/public/cp-v2/cp-v2-economy-chart.mjs
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
import {element as el} from './cp-v2-page-template.mjs';
|
||||
export const ECONOMY_SERIES=[['circulatingMinor','Money supply','#e8c86c','DM'],['priceIndexMicros','System prices','#efaa49','index'],['savingsBps','Savings rate','#a5dfc9','rate'],['loanBps','Loan rate','#d98aa5','rate'],['payIndexMicros','Staff pay index','#85bde5','index']];
|
||||
export function normalisedEconomicSeries(records,field){
|
||||
const valid=v=>Number.isSafeInteger(v)&&v>=0,first=records.find(r=>valid(r[field]));
|
||||
if(!first||first[field]===0)return [];
|
||||
return records.map((r,i)=>valid(r[field])?{i,value:r[field]/first[field]*100}:null);
|
||||
}
|
||||
const actual=(v,unit)=>v==null?'Not recorded':unit==='DM'?(v/100).toLocaleString('en-GB',{minimumFractionDigits:2,maximumFractionDigits:2})+' DM':unit==='rate'?(v/100).toFixed(2)+'% p.a.':(v/1000000).toFixed(3)+'×';
|
||||
const date=t=>new Date(t).toLocaleString('en-GB',{timeZone:'Europe/Brussels',dateStyle:'medium',timeStyle:'short'});
|
||||
const svgEl=(tag,attrs={})=>{const n=document.createElementNS('http://www.w3.org/2000/svg',tag);for(const [k,v]of Object.entries(attrs))n.setAttribute(k,String(v));return n;};
|
||||
export function mountEconomyChart(host,{fetcher=fetch}={}){
|
||||
if(!document.querySelector('link[data-economy-chart]')){const css=el('link');css.rel='stylesheet';css.href=new URL('./cp-v2-economy-chart.css',import.meta.url).href;css.dataset.economyChart='';document.head.append(css);}
|
||||
const root=el('section',undefined,'pb-economy-chart'),header=el('header'),periods=el('nav'),legend=el('div',undefined,'pb-economy-legend'),message=el('p'),plot=el('div'),selection=el('label'),selector=el('select'),details=el('dl',undefined,'pb-economy-values');
|
||||
periods.setAttribute('aria-label','Economic observation period');message.setAttribute('role','status');selection.append(el('span','Observation'),selector);selector.setAttribute('aria-label','Select economic observation');
|
||||
header.append(el('h3','Economic trends'),periods);root.append(header,legend,message,plot,selection,details,el('p','Lines start at index 100 for comparison. Select an observation for actual values. Missing or zero-baseline series are not plotted.','pb-muted'));host.append(root);
|
||||
let active=true,period='30D',records=[],selected=0,request=null;const visible=new Set(ECONOMY_SERIES.map(s=>s[0]));
|
||||
function showDetails(){details.replaceChildren();const r=records[selected];if(!r)return;for(const [field,label,,unit]of ECONOMY_SERIES)details.append(el('dt',label),el('dd',actual(r[field],unit)));details.append(el('dt','Snapshot'),el('dd',r.id));}
|
||||
function draw(){plot.replaceChildren();if(!records.length)return;
|
||||
const sets=ECONOMY_SERIES.filter(s=>visible.has(s[0])).map(s=>({s,points:normalisedEconomicSeries(records,s[0])})),values=sets.flatMap(s=>s.points.filter(Boolean).map(p=>p.value));
|
||||
if(!values.length){plot.append(el('p','No selected series has a positive baseline. Recorded values remain available below.'));return;}
|
||||
const lo=Math.min(90,...values),hi=Math.max(110,...values),x=i=>60+i/Math.max(1,records.length-1)*800,y=v=>240-(v-lo)/(hi-lo)*210,svg=svgEl('svg',{viewBox:'0 0 900 290',role:'img','aria-label':'Economic line graph; each series starts at index 100'});
|
||||
for(let i=0;i<=4;i++){const v=lo+(hi-lo)*i/4;svg.append(svgEl('line',{x1:60,x2:860,y1:y(v),y2:y(v),stroke:'#61745c','stroke-opacity':'.4'}));const t=svgEl('text',{x:50,y:y(v)+4,'text-anchor':'end',fill:'#dedcc7','font-size':12});t.textContent=v.toFixed(0);svg.append(t);}
|
||||
for(const {s,points}of sets){let d='';for(const p of points){if(!p)continue;d+=(points[p.i-1]?'L':'M')+x(p.i)+','+y(p.value)+' ';}svg.append(svgEl('path',{d,fill:'none',stroke:s[2],'stroke-width':2.5}));for(const p of points.filter(Boolean))svg.append(svgEl('circle',{cx:x(p.i),cy:y(p.value),r:p.i===selected?4:2,fill:s[2]}));}
|
||||
svg.append(svgEl('line',{x1:x(selected),x2:x(selected),y1:20,y2:245,stroke:'#efe3ba','stroke-dasharray':'4 4'}));
|
||||
for(const i of [...new Set([0,Math.floor((records.length-1)/2),records.length-1])]){const t=svgEl('text',{x:x(i),y:273,'text-anchor':'middle',fill:'#dedcc7','font-size':12});t.textContent=new Date(records[i].observedAt).toLocaleDateString('en-GB',{timeZone:'Europe/Brussels',day:'2-digit',month:'short'});svg.append(t);}plot.append(svg);
|
||||
}
|
||||
for(const [field,label,color]of ECONOMY_SERIES){const b=el('button',label);b.type='button';b.style.borderColor=color;b.setAttribute('aria-pressed','true');b.onclick=()=>{visible.has(field)?visible.delete(field):visible.add(field);b.setAttribute('aria-pressed',String(visible.has(field)));draw();};legend.append(b);}
|
||||
for(const value of ['7D','30D','90D','1Y']){const b=el('button',value);b.type='button';b.dataset.period=value;b.onclick=()=>{period=value;void load();};periods.append(b);}
|
||||
selector.onchange=()=>{selected=Number(selector.value);draw();showDetails();};
|
||||
async function load(){request?.abort();const abort=new AbortController();request=abort;message.hidden=false;message.textContent='Loading sealed economic observations…';for(const b of periods.children)b.setAttribute('aria-pressed',String(b.dataset.period===period));
|
||||
try{const response=await fetcher('/api/bank/public/economy?period='+period,{credentials:'omit',signal:AbortSignal.any([abort.signal,AbortSignal.timeout(15000)])}),data=await response.json();if(!response.ok)throw Error(data.message||'Economic observations unavailable.');if(!active||abort.signal.aborted)return;
|
||||
records=data.records||[];selected=Math.max(0,records.length-1);selector.replaceChildren(...records.map((r,i)=>{const o=el('option',date(r.observedAt));o.value=String(i);return o;}));selector.value=String(selected);selection.hidden=!records.length;message.hidden=!!records.length;message.textContent='Economic history begins after the new budget and first sealed observation. No historical data has been invented.';draw();showDetails();
|
||||
}catch(e){if(active&&!abort.signal.aborted){records=[];plot.replaceChildren();details.replaceChildren();selection.hidden=true;message.textContent=e.message;}}
|
||||
}
|
||||
void load();return()=>{active=false;request?.abort();root.remove();};
|
||||
}
|
||||
33
website/control-panel/public/cp-v2/cp-v2-key-generator.mjs
Normal file
33
website/control-panel/public/cp-v2/cp-v2-key-generator.mjs
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
// Design catalogue only. These choices confer no issuing or execution authority.
|
||||
export const KEY_GENERATOR_COMPONENTS=[
|
||||
['Progression & XP',['XP compensation','Season XP transfer','Quest reward'],['XP amount','Ban / support ticket']],
|
||||
['Keys & deeds',['Clan upgrade','Company upgrade','Royal upgrade','Parent relation'],['Organisation / deed reference']],
|
||||
['Bank',['Service compensation'],['Original payment ID','Amount · DM']],
|
||||
['Offices',['Appointment','Delegation','Membership'],['Office deed','Role','Term end']],
|
||||
['Events',['Event instrument','Event reward'],['Event reference']],
|
||||
['Items & kits',['Kit entitlement','Item entitlement','Repair entitlement'],['Definition reference','Quantity','Quality']],
|
||||
['Exchange',['Promotion credit','Private acquisition'],['Listing / dossier reference']],
|
||||
['Rihla',['Transfer instrument'],['Transfer reference']]
|
||||
];
|
||||
const el=(tag,text,cls)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;if(cls)n.className=cls;return n;};
|
||||
function field(name,choices){const label=el('label',undefined,'codex-field'),input=el(choices?'select':'input');label.append(el('span',name));input.setAttribute('aria-label',name);if(choices)for(const text of choices)input.append(el('option',text));else{input.type='text';input.placeholder=name;}label.append(input);return {label,input};}
|
||||
export function createKeyGeneratorDesign(){
|
||||
const root=el('section',undefined,'jarvis-generator'),notice=el('p','Design preview · no key is generated and no account is changed.','codex-preview-notice');
|
||||
const layout=el('div',undefined,'codex-management-grid'),form=el('form',undefined,'codex-management-box jarvis-generator-form'),preview=el('aside',undefined,'codex-management-box');
|
||||
form.onsubmit=e=>e.preventDefault();form.append(el('h3','Issue an instrument'));
|
||||
const component=field('Component',KEY_GENERATOR_COMPONENTS.map(c=>c[0])),action=field('Action',[]),recipient=field('Recipient'),dynamic=el('div',undefined,'jarvis-generator-fields');
|
||||
const reason=field('Issue reason',['Support resolution','Event reward','Authorised grant']),audit=field('Reason / decision reference'),season=field('Season'),validity=field('Validity',['Until redeemed','Defined expiry']),expiry=field('Expires at');
|
||||
season.input.value='Current season · supplied by server';season.input.readOnly=true;expiry.input.type='datetime-local';expiry.label.hidden=true;
|
||||
const pairs=el('div',undefined,'jarvis-generator-fields');pairs.append(component.label,action.label);form.append(pairs,recipient.label,dynamic,reason.label,audit.label,season.label,validity.label,expiry.label);
|
||||
const consent=el('label',undefined,'jarvis-generator-consent'),check=el('input');check.type='checkbox';consent.append(check,el('span','I verified the recipient and supporting record.'));
|
||||
const generate=el('button','Generate key');generate.type='submit';generate.disabled=true;generate.title='Design preview · issuance adapter pending';form.append(consent,generate);
|
||||
preview.append(el('h3','Instrument preview'),el('p','Preview · not issued','jarvis-generator-badge'));
|
||||
const details=el('dl',undefined,'jarvis-generator-summary'),status=el('p','Authority and conditions are checked by the server on issue and redemption.');
|
||||
const copy=el('button','Copy key');copy.type='button';copy.disabled=true;preview.append(details,copy,el('p','Available after generation.'),el('h3','Validation'),status);
|
||||
const decor=el('span',undefined,'jarvis-archive-box');decor.setAttribute('aria-hidden','true');preview.append(decor);
|
||||
let inputs=[];
|
||||
function refresh(){details.replaceChildren();for(const [name,value]of [['Component',component.input.value],['Action',action.input.value],['Recipient',recipient.input.value||'Select recipient'],...inputs.map(f=>[f.input.getAttribute('aria-label'),f.input.value||'—']),['Usage','Once']])details.append(el('dt',name),el('dd',value));}
|
||||
function changeComponent(){const definition=KEY_GENERATOR_COMPONENTS.find(c=>c[0]===component.input.value);action.input.replaceChildren(...definition[1].map(t=>el('option',t)));inputs=definition[2].map(name=>field(name,name==='Quality'?['Common','Uncommon','Rare','Very Rare','Legendary']:undefined));dynamic.replaceChildren(...inputs.map(f=>f.label));for(const f of inputs)f.input.oninput=refresh;refresh();}
|
||||
component.input.onchange=changeComponent;action.input.onchange=refresh;recipient.input.oninput=refresh;validity.input.onchange=()=>{expiry.label.hidden=validity.input.value!=='Defined expiry';};changeComponent();
|
||||
layout.append(form,preview);root.append(notice,layout);return root;
|
||||
}
|
||||
|
|
@ -1,13 +1,14 @@
|
|||
export const ORGANISATION_MENU_GROUPS=Object.freeze([
|
||||
['Your organisation',[['overview','Dashboard'],['settings','Settings'],['missions','Missions & Decisions']]],
|
||||
['Organisation affairs',[['boards','Boards'],['events','Events'],['elections','Elections'],['naibs','Council of Naibs'],['advertising','Advertising'],['commerce','Exchange'],['jobs','Office vacancies'],['tailor','Tailor']]],
|
||||
['Estates & relations',[['claims','Claims'],['subsidiaries','Subhouses'],['directory','Directory'],['projects','Expeditions'],['campaigns','Campaigns']]]
|
||||
['Organisation affairs',[['boards','Boards'],['events','Events'],['elections','Elections'],['naibs','Council of Naibs']]],
|
||||
['Exchange & recruitment',[['commerce','Exchange'],['jobs','Office vacancies'],['advertising','Advertising'],['tailor','Tailor']]],
|
||||
['Estates & relations',[['claims','Claims'],['subsidiaries','Subhouses'],['directory','Directory']]]
|
||||
]);
|
||||
export function organisationPage(hash=''){
|
||||
if(typeof hash!=='string'||hash.length>300)return null;
|
||||
const page=hash.replace(/^#/,'').split('/').at(-1),aliases={'politics-overview':'overview','dashboard':'overview','company-claims':'claims'};
|
||||
if(Object.hasOwn(aliases,page))return aliases[page];
|
||||
return [...ORGANISATION_MENU_GROUPS.flatMap(([,items])=>items.map(([id])=>id)),'people','applications','mail'].includes(page)?page:null;
|
||||
return [...ORGANISATION_MENU_GROUPS.flatMap(([,items])=>items.map(([id])=>id)),'people','applications','mail','projects','campaigns'].includes(page)?page:null;
|
||||
}
|
||||
export function organisationMenuItems(kind){
|
||||
if(!['company','politics'].includes(kind))throw TypeError('Unknown organisation workspace');
|
||||
|
|
|
|||
|
|
@ -34,7 +34,7 @@ export function startOrganisationCP(kind){
|
|||
function pending(host,title,copy){const box=el('section',undefined,'organisation-settings-card');box.append(el('h3',title),el('p',copy));host.append(box);}
|
||||
function render(){
|
||||
if(!ready||stopped)return;dispose();dispose=()=>{};const turn=++generation,record=records.find(r=>r.id===selected),page=route()||'overview';
|
||||
left.replaceChildren(el('div',company?'YOUR COMPANY':'YOUR POLITICAL HOUSE','side-hero'));right.replaceChildren(el('div',company?'COMPANY DIRECTORY':'POLITICAL HOUSES','side-hero'));portals.replaceChildren();portals.hidden=false;portals.classList.remove('organisation-switcher');const tiles=el('div',undefined,'organisation-portals');for(const [id,title,art,href] of [['overview',company?'My Company':'My Political House',record?.emblem||fallback],['missions','Missions & Decisions','nav-manual-v2.webp'],['tailor','Kits',company?'minecraft-items/iron_pickaxe.png':'items/office_water.png','https://www.dunerealms.com/exchange.html?type=kits-'+(company?'clan':'office')],['campaigns','Events',company?'nav-home-v2.webp':'seals/emperor-v1.png']]){const a=el('a',undefined,'organisation-portal');a.href=href||'#'+prefix+'/'+id;if(href)a.target='_top';a.append(image(art),el('strong',title));if(id===page)a.setAttribute('aria-current','page');tiles.append(a);}portals.append(tiles);
|
||||
left.replaceChildren(el('div',company?'YOUR COMPANY':'YOUR POLITICAL HOUSE','side-hero'));right.replaceChildren(el('div',company?'COMPANY DIRECTORY':'POLITICAL HOUSES','side-hero'));portals.replaceChildren();portals.hidden=true;portals.classList.remove('organisation-switcher');const tiles=el('div',undefined,'organisation-portals');for(const [id,title,art,href] of [['overview',company?'My Company':'My Political House',record?.emblem||fallback],['missions','Missions & Decisions','nav-manual-v2.webp'],['tailor','Kits',company?'minecraft-items/iron_pickaxe.png':'items/office_water.png','https://www.dunerealms.com/exchange.html?type=kits-'+(company?'clan':'office')],['campaigns','Events',company?'nav-home-v2.webp':'seals/emperor-v1.png']]){const a=el('a',undefined,'organisation-portal');a.href=href||'#'+prefix+'/'+id;if(href)a.target='_top';a.append(image(art),el('strong',title));if(id===page)a.setAttribute('aria-current','page');tiles.append(a);}portals.append(tiles);
|
||||
const label=el('label',company?'Your companies':'Political Houses'),select=el('select');select.setAttribute('aria-label',company?'Choose your company':'Choose a political House');for(const r of records){const option=el('option',r.name);option.value=r.id;select.append(option);}if(!records.length){const option=el('option','No verified organisation available');option.value='';select.append(option);}select.value=selected||'';select.disabled=!records.length;select.onchange=()=>{selected=select.value;const u=new URL(location.href);u.searchParams.set(company?'company':'office',selected);history.replaceState(null,'',u);render();};label.append(select);const selector=el('div',undefined,'organisation-switcher');selector.append(image(record?.emblem||fallback),label);selector.classList.add('organisation-sidebar-switcher');
|
||||
for(let i=0;i<groups.length;i++){const [heading,items]=groups[i],host=i<2?left:right,block=el('section',undefined,'category-block'),links=el('div',undefined,'category-links');block.append(el('div',heading,'category-heading'));for(const[id,title]of items){if(company&&['jobs','naibs'].includes(id))continue;const a=el('a',title==='Subhouses'&&company?'Subsidiaries':title,'navitem');a.href='#'+prefix+'/'+id;a.dataset.menuHref=(company?outer+'/':outer+'/government.html')+a.getAttribute('href');if(id===page)a.setAttribute('aria-current','page');links.append(a);}block.append(links);host.append(block);}left.append(selector);
|
||||
const hero=el('header',undefined,'hero organisation-workspace-hero'),copy=el('div');copy.append(el('small',company?'SPACING GUILD · COMMERCIAL AFFAIRS':'IMPERIAL HOUSES · OFFICE DEEDS'),el('h1',record?.name||noun+' Dashboard'),el('p',company?'Your enterprise, its people and its next chapter.':'Protected Houses · membership follows current office deeds.'));hero.append(image(record?.emblem||fallback),copy);
|
||||
|
|
|
|||
|
|
@ -1,14 +1,15 @@
|
|||
import {element as el,createCPV2ContentPage} from './cp-v2-page-template.mjs';
|
||||
import {mountEconomyChart} from './cp-v2-economy-chart.mjs';
|
||||
const format=n=>n?.match(/.{1,4}/g)?.join(' ')||'—';
|
||||
export function mountReserveLedger(host,{fetcher=fetch}={}){
|
||||
const abort=new AbortController();let active=true,busy=false,page=1;
|
||||
const abort=new AbortController();let active=true,busy=false,page=1,disposeChart=()=>{};
|
||||
const frame=createCPV2ContentPage({host,title:'Federal Reserve Ledger',description:'A public record of DM issuance, returns and every Federal Imperial Reserve transaction.',reload:()=>void load()});
|
||||
async function load(){if(busy)return;busy=true;frame.status.hidden=false;frame.status.textContent='Loading the public reserve ledger…';try{const response=await fetcher('/api/bank/public/reserve-ledger?page='+page,{credentials:'omit',signal:AbortSignal.any([abort.signal,AbortSignal.timeout(15000)])}),data=await response.json();if(!response.ok)throw Error(data.message||'Reserve ledger unavailable.');if(!active)return;frame.content.replaceChildren();
|
||||
const metrics=el('div',undefined,'pb-admin-metrics');for(const [label,value]of [['DM issued',data.totals.issued],['DM returned',data.totals.returned],['Net DM issued',data.totals.netIssued],['Transactions',String(data.totals.transactions)]]){const box=el('section');box.append(el('small',label),el('strong',value));metrics.append(box);}frame.content.append(metrics);
|
||||
async function load(){if(busy)return;busy=true;frame.status.hidden=false;frame.status.textContent='Loading the public reserve ledger…';try{const response=await fetcher('/api/bank/public/reserve-ledger?page='+page,{credentials:'omit',signal:AbortSignal.any([abort.signal,AbortSignal.timeout(15000)])}),data=await response.json();if(!response.ok)throw Error(data.message||'Reserve ledger unavailable.');if(!active)return;disposeChart();frame.content.replaceChildren();
|
||||
const metrics=el('div',undefined,'pb-admin-metrics');for(const [label,value]of [['DM issued',data.totals.issued],['DM returned',data.totals.returned],['Net DM issued',data.totals.netIssued],['Transactions',String(data.totals.transactions)]]){const box=el('section');box.append(el('small',label),el('strong',value));metrics.append(box);}frame.content.append(metrics);disposeChart=mountEconomyChart(frame.content,{fetcher});
|
||||
const info=el('section',undefined,'pb-reserve-information');info.append(el('strong',data.account.name),el('code',format(data.account.number)),el('p','The reserve is an issuance ledger. Its negative accounting balance represents net DM issued, rather than an ordinary spending balance. All counterparties and transaction references are public.'));const share=el('a','Open public page ↗');share.href='/federal-reserve';info.append(share);frame.content.append(info);
|
||||
const wrap=el('div',undefined,'pb-ledger-scroll'),table=el('table',undefined,'pb-ledger'),head=el('thead'),headrow=el('tr'),body=el('tbody');for(const h of ['Date','Reference','From','To','Amount · DM','Movement','Reserve balance after'])headrow.append(el('th',h));head.append(headrow);table.append(head,body);wrap.append(table);
|
||||
for(const r of data.records){const row=el('tr');row.dataset.direction=r.direction==='returned'?'credit':'debit';const reference=el('td',r.reference,'pb-ledger-reference'),details=el('details');details.append(el('summary','+ Payment details'),el('code',r.paymentId),el('p','State: '+r.state),el('p','Submitted: '+new Date(r.createdAt).toLocaleString('en-GB',{timeZone:'Europe/Brussels'})));reference.append(details);const party=p=>{const c=el('td');c.append(el('strong',p.name),el('code',format(p.number)));return c;};row.append(el('td',new Date(r.postedAt||r.createdAt).toLocaleString('en-GB',{timeZone:'Europe/Brussels'})),reference,party(r.from),party(r.to),el('td',r.amount,'pb-ledger-amount'),el('td',r.direction==='issued'?'Issued':'Returned'),el('td',r.reserveBalanceAfter));body.append(row);}
|
||||
frame.content.append(wrap);if(!data.records.length)frame.content.append(el('p','No reserve transactions have been posted.'));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+' of '+data.totalPages),next);frame.content.append(nav,el('p','DM is DuneRealms game currency. Displayed times: Europe/Brussels. Updated '+new Date(data.asOf).toLocaleString('en-GB',{timeZone:'Europe/Brussels'})+'.','pb-muted'));frame.status.hidden=true;frame.diagnostics.textContent='Public read-only reserve ledger · 25 transactions per page · No sign-in required.';
|
||||
}catch(error){if(active)frame.status.textContent=error.message;}finally{busy=false;}}
|
||||
void load();return()=>{active=false;abort.abort();frame.root.remove();};
|
||||
void load();return()=>{active=false;disposeChart();abort.abort();frame.root.remove();};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,2 +1,2 @@
|
|||
export const clanWorkspaces=new Set(['clan','quests','kits','events']);
|
||||
export function workspacesForSurface(workspaces,clanSurface){return workspaces.filter(w=>w.id!=='politics'&&clanSurface===clanWorkspaces.has(w.id));}
|
||||
export function workspacesForSurface(workspaces,clanSurface){return workspaces.filter(w=>w.id!=='politics'&&(['quests','events'].includes(w.id)||clanSurface===clanWorkspaces.has(w.id)));}
|
||||
|
|
|
|||
|
|
@ -275,3 +275,6 @@
|
|||
|
||||
/* Rihla: external stylesheet so production CSP can apply the layout. */
|
||||
.rihla-page,.rihla-page .pb-content{box-sizing:border-box;width:100%;max-width:100%;min-width:0}.rihla-page .pb-content{display:grid;grid-template-columns:minmax(0,1fr);gap:16px}.card:has(.rihla-page),#content:has(.rihla-page){min-width:0;max-width:100%}.rihla-page .pb-box{box-sizing:border-box;min-width:0;max-width:100%;margin:0;padding:20px;overflow-wrap:anywhere}.rihla-page .rihla-brand{width:min(100%,520px);aspect-ratio:1536/650;padding:0;overflow:hidden;justify-self:center;border:1px solid #b89a55;border-radius:12px;background:#faf6ed}.rihla-page .rihla-brand>img{display:block;width:100%;max-width:100%;height:auto;max-height:none;margin:0}.rihla-page h4{margin:0 0 12px;font-size:1.15rem;overflow-wrap:anywhere}.rihla-page p{line-height:1.6;max-width:85ch}.rihla-page .pb-ledger-scroll{width:100%;max-width:100%;overflow-x:auto;margin-top:16px}.rihla-page .pb-ledger{width:100%;min-width:580px;table-layout:fixed}.rihla-page .pb-ledger th,.rihla-page .pb-ledger td{padding:12px;white-space:normal;overflow-wrap:anywhere}.rihla-page .pb-ledger-pagination{display:flex;gap:10px;flex-wrap:wrap;margin-top:16px}.rihla-page .pb-ledger-pagination button{min-height:40px;padding:8px 16px}.rihla-page .pb-muted{font:14px/1.6 system-ui,sans-serif}@media(max-width:650px){.rihla-page .pb-box{padding:14px}.rihla-page .rihla-brand{padding:0}.rihla-page h4{font-size:1rem}}
|
||||
|
||||
/* Navigation is in the side menus; remove the duplicated portal row on every CP. */
|
||||
#portals[hidden]{display:none!important}.cp-workspace-switch{display:grid;gap:8px;padding:12px;color:#ead49a}.cp-workspace-switch select{width:100%;min-width:0;padding:10px;border:1px solid #b29a5e;border-radius:8px;background:#102820;color:#f0dfb4;font:inherit}
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue

Staff