forked from unimatrix/web
Merge pull request '1.0.1.0 design: Codex management and clan Exchange' (#382) from design/item-codex-clan-exchange into main
This commit is contained in:
commit
b76ce21c08
49 changed files with 706 additions and 462 deletions
150
docs/design/DUNEREALM-ITEM-CODEX.md
Normal file
150
docs/design/DUNEREALM-ITEM-CODEX.md
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
# Dunerealm Item Codex — design agreement
|
||||
|
||||
Status: design implementation and CI publication authorised. New Codex backend
|
||||
operations remain placeholders until design approval.
|
||||
|
||||
The Dunerealm Item Codex is the shared repository for item/kit definitions,
|
||||
keys, entitlements, deeds and Writs. The existing key generator becomes its
|
||||
Keys & Entitlements module; Chancery handles Writ records and lifecycle.
|
||||
Dedicated typed tables and validated metadata, rather than one unstructured
|
||||
Writ table for everything. Existing bank, mail, clan and election services
|
||||
remain authoritative for their operations.
|
||||
|
||||
Exchange reads existing cargo listings and eligible public Codex records into
|
||||
one shared card model. Categories and sorting make items, jobs, quests, events,
|
||||
political positions and companies/deeds easy to find. Jobs may be clan,
|
||||
company or faction recruitment. Private diplomacy is displayed through its own
|
||||
inbox, not public listings. Mail provides notifications. New behaviour still
|
||||
requires a handler; metadata alone cannot enforce objectives or authority.
|
||||
|
||||
GUI proposal: compact starport heading; left category/filter column; prominent
|
||||
search; sort and grid/list controls; one card grid; My listings and Create
|
||||
listing actions; compact icon/explanation guide below the results. No separate
|
||||
illustrated Cargo/Company tabs, no repeated explanatory paragraphs on cards.
|
||||
Minecraft goods use actual item icons/renders. Existing deed/key artwork is
|
||||
reused. Five new scroll icons are recorded in EXCHANGE-ICON-SET-v1.json.
|
||||
Full visual proposal: exchange-gui-concept-v1.png.
|
||||
|
||||
Recruitment: Basic/Keyed/Royal proposed member caps 5/25/50. Vacancies cannot
|
||||
exceed actual remaining capacity. Basic recruitment is free (up to four open
|
||||
places when owner is the only member); other clans pay per advertised place
|
||||
from their organisational account. Apply creates a join request; accept or deny
|
||||
notifies the applicant through internal mail. Acceptance adds membership and
|
||||
closes that vacancy; denial leaves it available. Recheck capacity and eligibility
|
||||
on acceptance. Existing pending requests remain reviewable.
|
||||
|
||||
Optional Discord promotion proposal: a poster can opt into a separately priced
|
||||
Exchange News announcement. Administrators configure the fee, rather than the
|
||||
poster choosing their own price. Only public active listings qualify. Confirm
|
||||
payment, queue through the existing Discord delivery system, prevent duplicate
|
||||
posts and duplicate charges, retry delivery failures, and release/refund the
|
||||
promotion fee on permanent failure. No automatic announcement for every listing.
|
||||
|
||||
Workflow: agree on the images and interactions here, then implement the page
|
||||
and its backend together in a focused CI-reviewed change. Initial integration
|
||||
order: shared typed Codex/key metadata, Exchange adapter, clan recruitment flow;
|
||||
reuse the same foundation for later companies, factions, quests and politics.
|
||||
## Design batch: Codex Management and lifecycle contracts
|
||||
|
||||
Status: design implementation authorised. Backend operations stay disabled until approved.
|
||||
|
||||
Imperial Bureau > Management > Codex Management replaces the separate Item
|
||||
Management, Kit Management, Kit Publishing, Kit Claims and Exchange Management
|
||||
navigation entries. Legacy links resolve to the corresponding consolidated tab.
|
||||
Keep shop administration, honours/seal design, banks and personal reward registers.
|
||||
Reuse existing access nodes for visibility; backend department authority and Big 4.1
|
||||
checks must be resolved server-side before any operation is enabled.
|
||||
|
||||
Tabs: Keys & deeds, Issuance, Items & definitions, Kits, Publication, Delivery,
|
||||
Listings, History and Seasons. No pretend successful writes or live balances.
|
||||
|
||||
### Proposed API contract (not implemented endpoints)
|
||||
|
||||
- GET /api/codex/definitions?type=&query=&cursor= : public/authorised definitions.
|
||||
- GET /api/codex/instances?scope=owned|organisation|subclans&state=&cursor= :
|
||||
only authorised records, masked private codes, explicit pagination.
|
||||
- POST /api/codex/staff/issuances : definitionId, recipient, decisionRef, reason,
|
||||
optional expiresAt, idempotency key; server chooses environment, season,
|
||||
key version, instanceId and issuer. Staff issue proof is server-signed.
|
||||
- POST /api/codex/instances/:id/replace : reason, decisionRef, idempotency key;
|
||||
invalidate unused predecessor atomically, retain provenance and entitlement.
|
||||
- POST /api/codex/instances/:id/revoke : authorisation and immutable audit reason.
|
||||
- POST /api/codex/instances/:id/use : signed proof, action and idempotency key;
|
||||
atomic compare-and-consume, authority checks and effect in one transaction or
|
||||
durable idempotent handler. A copied game item is not a second entitlement.
|
||||
- POST /api/codex/instances/:id/transfer : recipient, expected revision and
|
||||
idempotency key; verify ownership, transferability and unused state atomically.
|
||||
- GET /api/codex/deliveries?state=&cursor= and POST /:id/retry : delivery ledger,
|
||||
safe retry with the original delivery identity, not minting a new item.
|
||||
- GET /api/codex/history?instanceId=&cursor= : authorised, secret-free audit view.
|
||||
- GET /api/codex/seasons and POST /api/codex/staff/signing-keys/rotate : privileged
|
||||
configuration only. Never return secret signing/encryption material to browsers.
|
||||
|
||||
Standard results: data plus nextCursor; errors carry code/message/requestId.
|
||||
401 unauthenticated, 403 unauthorised, 409 already-used/revision-conflict,
|
||||
422 invalid input, 503 dependency unavailable. No new endpoints are called by
|
||||
this design commit.
|
||||
|
||||
### Instance identity, seasons and natural rarity
|
||||
|
||||
Each instance has immutable instanceId, definitionId, issuedSeasonId, issuedAt,
|
||||
environmentId, optional testRunId, provenance (original/staff/replacement),
|
||||
signingKeyId, issuer, decisionRef, state and revision. Secret redemption material
|
||||
is separate from public display fields and never a substitute for authority.
|
||||
|
||||
Rotate the active signing key for a new season or isolated test. Retain prior
|
||||
verification keys and ledger records: unused S1 keys and items can remain valid
|
||||
and tradable in S2 when their type permits. Deeds carry over. Historical S1
|
||||
items (such as a sword) retain S1 origin; rarity emerges from actual remaining
|
||||
instances, not invented scarcity totals. Rotation alone does not revoke items.
|
||||
Tests use a separate namespace/ledger and cannot redeem into production.
|
||||
Signing ensures authenticity; encryption, if used for private secrets, has a
|
||||
separate versioned encryption key and rotation/migration policy.
|
||||
|
||||
Validate on use/redemption/transfer, without recurring inventory scans. Staff
|
||||
proof does not bypass duplicate protection. Copying metadata copies the same
|
||||
instance ID and cannot produce another successful consumption or delivery.
|
||||
Original key redemption can replace a staff seal on the deed without duplicating
|
||||
rights; preserve both events in history. Replacement retains original provenance.
|
||||
|
||||
### Clan presentation and entitlement policy
|
||||
|
||||
Dashboard tabs: Overview, People, Household, Activity. Settings tabs include Keys:
|
||||
unused owner/member upgrade keys plus subclans, masked until server-authorised
|
||||
access. A borrowed/traded key follows its type's transfer rules; a UI list never
|
||||
confers ownership. Basic/Keyed/Royal limits 5/25/50 derive from the deed.
|
||||
Basic receives four recruitment vacancies subject to actual free slots, and five
|
||||
shared promotion credits: one per Board post and one per Discord post. Both cost
|
||||
two. Credits may be earned from quests. Upgrades remove the Basic token limit;
|
||||
other promotions use configurable fees. Credits never bypass membership/authority.
|
||||
|
||||
### Immutable edition metadata
|
||||
|
||||
Issued instances include issuedSeasonId, releaseStage (alpha/beta/live) and
|
||||
releaseVersion (server release identity, initially Alpha 1.0.1.0), plus issuedAt.
|
||||
These are server-assigned and immutable: staff cannot backdate/regenerate an S1
|
||||
original. Regeneration creates a distinct current-stage/current-version instance
|
||||
and may reference the historical template. An exact lost-key replacement retains
|
||||
entitlement/provenance lineage but is explicitly a replacement, not a second
|
||||
historical collectible. Never increase historical original issuance counts.
|
||||
Display origin in item detail and filters when the backend supplies it; do not
|
||||
label unversioned legacy Minecraft listings as Alpha originals. Actual scarcity
|
||||
counts require the authoritative instance ledger.
|
||||
|
||||
Quality reuses existing Common / Uncommon / Rare / Very Rare / Legendary tiers.
|
||||
Quality is independent of immutable edition, season and actual surviving count.
|
||||
A Rare Netherite Shovel from an older Alpha release remains that edition; no
|
||||
promise of resale value or artificial rarity count is made.
|
||||
Issuer provenance also stores the issuing citizen and, where applicable, verified
|
||||
political deed/office and term references. A royal key issued by the first Emperor
|
||||
can retain that factual provenance without granting a second political entitlement.
|
||||
|
||||
### Persistent versus consumable items
|
||||
|
||||
Declare lifecycle as consumable, entitlement or persistent. Consuming a key is
|
||||
atomic and single-use. A persistent sword/shovel is not consumed on every swing:
|
||||
its uses validate the unique active custody/binding and current instance revision.
|
||||
The game bridge must enforce one active physical binding per persistent instance
|
||||
and reject conflicting copies on relevant use/transfer events. An ID or signature
|
||||
alone cannot distinguish bit-identical copies held by the same player; custody
|
||||
enforcement is required, without claiming inventory-wide periodic scans.
|
||||
41
docs/design/EXCHANGE-ICON-SET-v1.json
Normal file
41
docs/design/EXCHANGE-ICON-SET-v1.json
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
{
|
||||
"status": "design implementation",
|
||||
"assets": [
|
||||
{
|
||||
"type": "clan-recruitment",
|
||||
"file": "website/web/assets/exchange-clan-recruitment-v1.png",
|
||||
"prompt": "Emerald parchment, recruits, banner and crossed-swords seal",
|
||||
"style": "Transparent Minecraft voxel parchment with faceted gold fittings; no text",
|
||||
"generator": "built-in image_gen"
|
||||
},
|
||||
{
|
||||
"type": "company-jobs",
|
||||
"file": "website/web/assets/exchange-company-jobs-v1.png",
|
||||
"prompt": "Teal parchment, gear, quill and cargo motif",
|
||||
"style": "Transparent Minecraft voxel parchment with faceted gold fittings; no text",
|
||||
"generator": "built-in image_gen"
|
||||
},
|
||||
{
|
||||
"type": "faction-jobs",
|
||||
"file": "website/web/assets/exchange-faction-jobs-v1.png",
|
||||
"prompt": "Cobalt parchment, desert planet and faction pennants",
|
||||
"style": "Transparent Minecraft voxel parchment with faceted gold fittings; no text",
|
||||
"generator": "built-in image_gen"
|
||||
},
|
||||
{
|
||||
"type": "quests",
|
||||
"file": "website/web/assets/exchange-quests-v1.png",
|
||||
"prompt": "Amber parchment, map, route and compass",
|
||||
"style": "Transparent Minecraft voxel parchment with faceted gold fittings; no text",
|
||||
"generator": "built-in image_gen"
|
||||
},
|
||||
{
|
||||
"type": "political-positions",
|
||||
"file": "website/web/assets/exchange-political-positions-v1.png",
|
||||
"prompt": "Purple parchment, crown, ballot and sun seal",
|
||||
"style": "Transparent Minecraft voxel parchment with faceted gold fittings; no text",
|
||||
"generator": "built-in image_gen"
|
||||
}
|
||||
],
|
||||
"deliverySize": "256 x 256 transparent PNG; original generated sources retained outside repository"
|
||||
}
|
||||
31
docs/design/MINECRAFT-EXCHANGE-TEXTURES.json
Normal file
31
docs/design/MINECRAFT-EXCHANGE-TEXTURES.json
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
{
|
||||
"version": "1.21.4",
|
||||
"manifest": "https://piston-meta.mojang.com/v1/packages/87fcc1eec25874d12bca737d6579a247ce2d2746/1.21.4.json",
|
||||
"client": "https://piston-data.mojang.com/v1/objects/a7e5a6024bfd3cd614625aa05629adf760020304/client.jar",
|
||||
"sha1": "a7e5a6024bfd3cd614625aa05629adf760020304",
|
||||
"note": "Unmodified official item PNGs extracted from the SHA1-verified Mojang client jar. Minecraft assets belong to Mojang/Microsoft. Pixelated rendering; no generated replacements.",
|
||||
"files": [
|
||||
"apple.png",
|
||||
"bow.png",
|
||||
"coal.png",
|
||||
"cooked_cod.png",
|
||||
"copper_ingot.png",
|
||||
"diamond.png",
|
||||
"diamond_sword.png",
|
||||
"emerald.png",
|
||||
"ender_pearl.png",
|
||||
"fishing_rod.png",
|
||||
"golden_carrot.png",
|
||||
"gold_ingot.png",
|
||||
"iron_ingot.png",
|
||||
"iron_pickaxe.png",
|
||||
"lapis_lazuli.png",
|
||||
"netherite_scrap.png",
|
||||
"netherite_upgrade_smithing_template.png",
|
||||
"paper.png",
|
||||
"potato.png",
|
||||
"quartz.png",
|
||||
"redstone.png",
|
||||
"wheat.png"
|
||||
]
|
||||
}
|
||||
|
|
@ -1,24 +1,25 @@
|
|||
export {workspacesForSurface} from './cp-v2-surface.mjs';
|
||||
import {NATIVE_SERVICES,nativeServiceAccess} from './cp-v2-native-services.mjs';
|
||||
import {canSubmitDevRequest} from '../dev-request-access.mjs';
|
||||
const legacy={"account-authorisations":"web.bank.staff.view","tax-treasury":"web.bank.staff.manage","bank-dashboard":"web.bank.staff.view","company-finance":"web.bank.staff.view","loan-centre":"web.bank.personal.view","loan-administration":"web.bank.staff.view","electoral-roll":"web.menu.game","imperial-inbox":"web.mail.internal.view","faction-inbox":"web.mail.internal.view","staff-inbox":"web.mail.staff.view","clan-inbox":"web.mail.internal.view","council-motd":"web.menu.game","applications":"web.menu.game","formal-council":"web.menu.game","shared-inbox":"web.mail.internal.view","house-elections":"web.menu.game","imperial-elections":"web.menu.game","imperial-command":"web.menu.game","imperial-water":"web.menu.game","imperial-spice":"web.menu.game","discord-link":"web.menu.security","support-management":"web.tickets.admin","landsraad":"web.menu.game","hosting-control":"web.menu.security","user-management":"web.accounts.view","manual-seals":"web.accounts.assign","company-management":"web.accounts.assign","community-goals":"web.community.manage","marketplace-home":"web.menu.inventory","adventure-home":"web.menu.game","account-home":"web.menu.security","server-kits":"web.ranks.manage","kit-checkout":"web.menu.inventory","rewards-codes":"web.menu.rewards","transactions":"web.menu.inventory","kits-exchange":"web.menu.inventory","redeem-code":"web.menu.rewards","discovery-rewards":"web.quests.view","shop-settings":"web.menu.inventory","exchange-settings":"web.menu.inventory","shop-admin":"web.shop.support","exchange-settings-admin":"web.exchange.manage","user-home":null,"staff-home":null,"exchange":"web.menu.game","clans":"web.menu.game","imperial-atelier":"web.menu.game","personal-bank":"web.bank.personal.view","staff-bank":"web.bank.staff.view","clan-portal":"web.menu.game","clan-shops":"web.menu.game","clan-kits":"web.menu.game","clan-bank":"web.menu.game","clan-settings":"web.menu.game","clan-quests":"web.menu.game","clan-quests-player":"web.menu.game","clan-quests-clan":"web.menu.game","clan-quests-guild":"web.menu.game","quests":"web.quests.view","quests-admin":"web.quests.manage","game":"web.menu.game","webmail":"web.menu.security","git-admin":"web.git.admin","git-control":"web.menu.security","site-profile":"web.menu.security","planetary-inventory":"web.menu.inventory","rewards":"web.menu.rewards","security":"web.menu.security","server-operations":"web.menu.servers","staff":"web.menu.administration","permissions":"web.menu.permissions","game-permissions":"web.ranks.manage","items":"web.menu.items","staff-manual":"web.menu.staffmanual","luckperms":"web.menu.luckperms","tickets":"web.menu.tickets","staff-tickets":"web.tickets.staff","forum-admin":"web.menu.forum","exchange-admin":"web.menu.exchange","website-posts":"web.menu.posts","bans":"web.menu.bans","ban-evidence":"web.menu.bans","kit-publishing":"web.ranks.manage","kit-claims":"web.ranks.manage","company-management-v2":"web.accounts.assign","company-audit":"web.accounts.assign","seal-generator":"web.accounts.assign","bank-audit":"web.bank.staff.view","stock-admin":"web.exchange.manage","stock-surveillance":"web.exchange.manage","git-repositories":"web.menu.security","mail-admin":"web.menu.administration"};
|
||||
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==='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');
|
||||
if(workspace==='events')return has('web.menu.game');
|
||||
if(workspace==='politics')return has('web.menu.game');
|
||||
if(item.id==='menu-badges')return has('web.posts.publish');
|
||||
if(item.id==='website-posts')return has('web.menu.posts')&&has('web.posts.view');
|
||||
if(workspace==='forge'&&item.id.startsWith('dev-'))return canSubmitDevRequest(user);
|
||||
if(NATIVE_SERVICES[item.id])return nativeServiceAccess(user,NATIVE_SERVICES[item.id]);
|
||||
if(item.viewPermission&&has(item.viewPermission))return true;
|
||||
if(legacy[item.id])return has(legacy[item.id]);
|
||||
if(['bureau'].includes(workspace))return has('web.menu.administration');
|
||||
if(workspace==='bank')return has('web.bank.personal.view');
|
||||
return true;
|
||||
}
|
||||
export function accessibleCPMenu(menu,user){return {...menu,workspaces:menu.workspaces.map(w=>({...w,groups:w.groups.map(g=>({...g,items:g.items.filter(item=>visibleCPItem(user,w.id,item))})).filter(g=>g.items.length)})).filter(w=>w.groups.length)};}
|
||||
export {workspacesForSurface} from './cp-v2-surface.mjs';
|
||||
import {NATIVE_SERVICES,nativeServiceAccess} from './cp-v2-native-services.mjs';
|
||||
import {canSubmitDevRequest} from '../dev-request-access.mjs';
|
||||
const legacy={"account-authorisations":"web.bank.staff.view","tax-treasury":"web.bank.staff.manage","bank-dashboard":"web.bank.staff.view","company-finance":"web.bank.staff.view","loan-centre":"web.bank.personal.view","loan-administration":"web.bank.staff.view","electoral-roll":"web.menu.game","imperial-inbox":"web.mail.internal.view","faction-inbox":"web.mail.internal.view","staff-inbox":"web.mail.staff.view","clan-inbox":"web.mail.internal.view","council-motd":"web.menu.game","applications":"web.menu.game","formal-council":"web.menu.game","shared-inbox":"web.mail.internal.view","house-elections":"web.menu.game","imperial-elections":"web.menu.game","imperial-command":"web.menu.game","imperial-water":"web.menu.game","imperial-spice":"web.menu.game","discord-link":"web.menu.security","support-management":"web.tickets.admin","landsraad":"web.menu.game","hosting-control":"web.menu.security","user-management":"web.accounts.view","manual-seals":"web.accounts.assign","company-management":"web.accounts.assign","community-goals":"web.community.manage","marketplace-home":"web.menu.inventory","adventure-home":"web.menu.game","account-home":"web.menu.security","server-kits":"web.ranks.manage","kit-checkout":"web.menu.inventory","rewards-codes":"web.menu.rewards","transactions":"web.menu.inventory","kits-exchange":"web.menu.inventory","redeem-code":"web.menu.rewards","discovery-rewards":"web.quests.view","shop-settings":"web.menu.inventory","exchange-settings":"web.menu.inventory","shop-admin":"web.shop.support","exchange-settings-admin":"web.exchange.manage","user-home":null,"staff-home":null,"exchange":"web.menu.game","clans":"web.menu.game","imperial-atelier":"web.menu.game","personal-bank":"web.bank.personal.view","staff-bank":"web.bank.staff.view","clan-portal":"web.menu.game","clan-shops":"web.menu.game","clan-kits":"web.menu.game","clan-bank":"web.menu.game","clan-settings":"web.menu.game","clan-quests":"web.menu.game","clan-quests-player":"web.menu.game","clan-quests-clan":"web.menu.game","clan-quests-guild":"web.menu.game","quests":"web.quests.view","quests-admin":"web.quests.manage","game":"web.menu.game","webmail":"web.menu.security","git-admin":"web.git.admin","git-control":"web.menu.security","site-profile":"web.menu.security","planetary-inventory":"web.menu.inventory","rewards":"web.menu.rewards","security":"web.menu.security","server-operations":"web.menu.servers","staff":"web.menu.administration","permissions":"web.menu.permissions","game-permissions":"web.ranks.manage","items":"web.menu.items","staff-manual":"web.menu.staffmanual","luckperms":"web.menu.luckperms","tickets":"web.menu.tickets","staff-tickets":"web.tickets.staff","forum-admin":"web.menu.forum","exchange-admin":"web.menu.exchange","website-posts":"web.menu.posts","bans":"web.menu.bans","ban-evidence":"web.menu.bans","kit-publishing":"web.ranks.manage","kit-claims":"web.ranks.manage","company-management-v2":"web.accounts.assign","company-audit":"web.accounts.assign","seal-generator":"web.accounts.assign","bank-audit":"web.bank.staff.view","stock-admin":"web.exchange.manage","stock-surveillance":"web.exchange.manage","git-repositories":"web.menu.security","mail-admin":"web.menu.administration"};
|
||||
export function visibleCPItem(user,workspace,item){
|
||||
if(item.id==='codex-management')return ['web.menu.items','web.menu.exchange','web.ranks.manage','web.cp.v2.items.view','web.cp.v2.server.kits.view','web.cp.v2.kit.publishing.view','web.cp.v2.kit.claims.view','web.cp.v2.exchange.admin.view'].some(node=>user?.permissions?.includes(node)||user?.permissions?.includes(node.replace(/^web\./,'cp.')));
|
||||
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==='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');
|
||||
if(workspace==='events')return has('web.menu.game');
|
||||
if(workspace==='politics')return has('web.menu.game');
|
||||
if(item.id==='menu-badges')return has('web.posts.publish');
|
||||
if(item.id==='website-posts')return has('web.menu.posts')&&has('web.posts.view');
|
||||
if(workspace==='forge'&&item.id.startsWith('dev-'))return canSubmitDevRequest(user);
|
||||
if(NATIVE_SERVICES[item.id])return nativeServiceAccess(user,NATIVE_SERVICES[item.id]);
|
||||
if(item.viewPermission&&has(item.viewPermission))return true;
|
||||
if(legacy[item.id])return has(legacy[item.id]);
|
||||
if(['bureau'].includes(workspace))return has('web.menu.administration');
|
||||
if(workspace==='bank')return has('web.bank.personal.view');
|
||||
return true;
|
||||
}
|
||||
export function accessibleCPMenu(menu,user){return {...menu,workspaces:menu.workspaces.map(w=>({...w,groups:w.groups.map(g=>({...g,items:g.items.filter(item=>visibleCPItem(user,w.id,item))})).filter(g=>g.items.length)})).filter(w=>w.groups.length)};}
|
||||
|
|
|
|||
|
|
@ -1,22 +1,22 @@
|
|||
import {mountNativeService} from './cp-v2-native-services.mjs';
|
||||
import {createCPV2Page,element as el} from './cp-v2-page-template.mjs';
|
||||
// Presentation-only CHOAM workspace. No trading endpoints, invented prices or orders.
|
||||
const PAGES={
|
||||
'stock-overview':{title:'Market Overview',description:'CHOAM markets and exchange intelligence.',tabs:[['pulse','Market pulse','Market activity, trends and sector summaries'],['sectors','Market sectors','Industry categories and market participation'],['notices','Market notices','Official CHOAM exchange announcements']]},
|
||||
'stock-listings':{title:'Listed Enterprises',description:'Registered companies and exchange listings.',tabs:[['directory','Listing directory','Listed companies and market identifiers'],['profiles','Enterprise profiles','Issuer details and public disclosures'],['criteria','Listing requirements','Market eligibility and disclosure rules']]},
|
||||
'stock-quotes':{title:'Market Prices',description:'Future real-time Solari-denominated price information.',tabs:[['quotes','Price board','Current market quotes and trading sessions'],['charts','Price history','Historical charts and volume trends'],['reference','Market reference','Ticker symbols and trading units']]},
|
||||
'stock-portfolio':{title:'My Holdings',description:'Personal CHOAM investments and positions.',tabs:[['positions','My positions','Owned securities and investment positions'],['performance','Performance','Cost basis, returns and portfolio valuation'],['income','Investment income','Dividends and distributions']]},
|
||||
'stock-orders':{title:'Trading Floor',description:'Future authenticated market order service.',tabs:[['ticket','Order ticket','Buy and sell order entry with validation'],['open','Open orders','Pending orders, cancellations and execution status'],['rules','Trading rules','Market hours, limits and order safeguards']]},
|
||||
'stock-trades':{title:'Trade Ledger',description:'Personal market execution history and settlement.',tabs:[['executions','Trade executions','Completed market trades and references'],['settlement','Settlement','Trade settlement and Solari movements'],['records','Trade records','Exportable trade confirmations and account records']]},
|
||||
'stock-watchlist':{title:'Watchlist',description:'Personal market monitoring and saved enterprises.',tabs:[['saved','Saved enterprises','Followed tickers and watched companies'],['alerts','Price alerts','Future thresholds and watchlist notifications'],['discovery','Discover markets','Explore exchange sectors and listed issuers']]},
|
||||
'companies':{title:'My Companies',description:'Personal enterprise ownership and management.',tabs:[['holdings','My enterprises','Company ownership and membership records'],['management','Company management','Authorized enterprise administration'],['activity','Company activity','Enterprise updates and governance notices']]},
|
||||
'company-directory':{title:'Company Registry',description:'CHOAM registry of registered enterprises.',tabs:[['registry','Registered companies','Public enterprise directory and registration details'],['sectors','Enterprise sectors','Industry classifications and business activities'],['records','Registry records','Corporate registration and filing history']]},
|
||||
'company-profile':{title:'Corporate Profiles',description:'Enterprise identity and public corporate disclosures.',tabs:[['identity','Corporate identity','Company overview, emblem and officers'],['ownership','Ownership','Corporate ownership and capital structure'],['disclosures','Disclosures','Corporate reports and official filings']]},
|
||||
'stock-ipo':{title:'Listing Applications',description:'Future CHOAM market listing process.',tabs:[['apply','Apply for listing','New listing applications and eligibility'],['review','Application review','Authorized assessment and application progress'],['requirements','Listing requirements','Exchange rules and required disclosures']]},
|
||||
'stock-dividends':{title:'Dividends',description:'Future shareholder distributions and corporate dividends.',tabs:[['calendar','Dividend calendar','Declared and upcoming distribution dates'],['receipts','My distributions','Personal dividend entitlements and receipts'],['policy','Distribution policy','Company payout rules and authorizations']]},
|
||||
'stock-admin':{title:'Market Authority',description:'Restricted exchange operations and market governance.',tabs:[['operations','Exchange operations','Authorized market configuration and listing controls'],['approvals','Approval queue','Pending listings and official market decisions'],['policy','Market policy','Trading rules and administrative authorizations']]},
|
||||
'stock-surveillance':{title:'Market Surveillance',description:'Restricted CHOAM market integrity monitoring.',tabs:[['monitoring','Market monitoring','Suspicious trading and exchange activity signals'],['cases','Investigation cases','Authorized market integrity investigations'],['reports','Surveillance reports','Oversight reports and audit trails']]}
|
||||
};
|
||||
export function mountCHOAMPlaceholder(host,id){const spec=PAGES[id];if(!spec)throw Error('Unknown CHOAM page');const tabs=spec.tabs.map(([key,label,detail])=>{const content=el('div',undefined,'cp-v2-bank-placeholder');const image=el('img');image.src='https://www.dunerealms.com/assets/nav-exchange-v2.webp';image.alt='';image.width=82;image.height=82;content.append(image,el('h4',label),el('p',detail),el('p','V2 · PLANNED — market data and trading actions are not connected.','cp-v2-bank-status'));return{id:key,label,artwork:'nav-exchange-v2.webp',content}});const {root}=createCPV2Page({title:spec.title,description:spec.description,artwork:'nav-exchange-v2.webp',tabs});host.replaceChildren(root);return()=>root.remove()}
|
||||
|
||||
export function mountCommodityExchange(host,id,{fetcher=fetch}={}){if(!['commodity-listings','commodity-mine'].includes(id))throw Error('Unknown commodity workspace.');return mountNativeService(host,'exchange-listings',{fetcher,singleHeading:true,title:id==='commodity-mine'?'My Commodity Listings':'Commodity Exchange',initialTab:id==='commodity-mine'?'mine':undefined});}
|
||||
import {mountNativeService} from './cp-v2-native-services.mjs';
|
||||
import {createCPV2Page,element as el} from './cp-v2-page-template.mjs';
|
||||
// Presentation-only CHOAM workspace. No trading endpoints, invented prices or orders.
|
||||
const PAGES={
|
||||
'stock-overview':{title:'Market Overview',description:'CHOAM markets and exchange intelligence.',tabs:[['pulse','Market pulse','Market activity, trends and sector summaries'],['sectors','Market sectors','Industry categories and market participation'],['notices','Market notices','Official CHOAM exchange announcements']]},
|
||||
'stock-listings':{title:'Listed Enterprises',description:'Registered companies and exchange listings.',tabs:[['directory','Listing directory','Listed companies and market identifiers'],['profiles','Enterprise profiles','Issuer details and public disclosures'],['criteria','Listing requirements','Market eligibility and disclosure rules']]},
|
||||
'stock-quotes':{title:'Market Prices',description:'Future real-time Solari-denominated price information.',tabs:[['quotes','Price board','Current market quotes and trading sessions'],['charts','Price history','Historical charts and volume trends'],['reference','Market reference','Ticker symbols and trading units']]},
|
||||
'stock-portfolio':{title:'My Holdings',description:'Personal CHOAM investments and positions.',tabs:[['positions','My positions','Owned securities and investment positions'],['performance','Performance','Cost basis, returns and portfolio valuation'],['income','Investment income','Dividends and distributions']]},
|
||||
'stock-orders':{title:'Trading Floor',description:'Future authenticated market order service.',tabs:[['ticket','Order ticket','Buy and sell order entry with validation'],['open','Open orders','Pending orders, cancellations and execution status'],['rules','Trading rules','Market hours, limits and order safeguards']]},
|
||||
'stock-trades':{title:'Trade Ledger',description:'Personal market execution history and settlement.',tabs:[['executions','Trade executions','Completed market trades and references'],['settlement','Settlement','Trade settlement and Solari movements'],['records','Trade records','Exportable trade confirmations and account records']]},
|
||||
'stock-watchlist':{title:'Watchlist',description:'Personal market monitoring and saved enterprises.',tabs:[['saved','Saved enterprises','Followed tickers and watched companies'],['alerts','Price alerts','Future thresholds and watchlist notifications'],['discovery','Discover markets','Explore exchange sectors and listed issuers']]},
|
||||
'companies':{title:'My Companies',description:'Personal enterprise ownership and management.',tabs:[['holdings','My enterprises','Company ownership and membership records'],['management','Company management','Authorized enterprise administration'],['activity','Company activity','Enterprise updates and governance notices']]},
|
||||
'company-directory':{title:'Company Registry',description:'CHOAM registry of registered enterprises.',tabs:[['registry','Registered companies','Public enterprise directory and registration details'],['sectors','Enterprise sectors','Industry classifications and business activities'],['records','Registry records','Corporate registration and filing history']]},
|
||||
'company-profile':{title:'Corporate Profiles',description:'Enterprise identity and public corporate disclosures.',tabs:[['identity','Corporate identity','Company overview, emblem and officers'],['ownership','Ownership','Corporate ownership and capital structure'],['disclosures','Disclosures','Corporate reports and official filings']]},
|
||||
'stock-ipo':{title:'Listing Applications',description:'Future CHOAM market listing process.',tabs:[['apply','Apply for listing','New listing applications and eligibility'],['review','Application review','Authorized assessment and application progress'],['requirements','Listing requirements','Exchange rules and required disclosures']]},
|
||||
'stock-dividends':{title:'Dividends',description:'Future shareholder distributions and corporate dividends.',tabs:[['calendar','Dividend calendar','Declared and upcoming distribution dates'],['receipts','My distributions','Personal dividend entitlements and receipts'],['policy','Distribution policy','Company payout rules and authorizations']]},
|
||||
'stock-admin':{title:'Market Authority',description:'Restricted exchange operations and market governance.',tabs:[['operations','Exchange operations','Authorized market configuration and listing controls'],['approvals','Approval queue','Pending listings and official market decisions'],['policy','Market policy','Trading rules and administrative authorizations']]},
|
||||
'stock-surveillance':{title:'Market Surveillance',description:'Restricted CHOAM market integrity monitoring.',tabs:[['monitoring','Market monitoring','Suspicious trading and exchange activity signals'],['cases','Investigation cases','Authorized market integrity investigations'],['reports','Surveillance reports','Oversight reports and audit trails']]}
|
||||
};
|
||||
export function mountCHOAMPlaceholder(host,id){const spec=PAGES[id];if(!spec)throw Error('Unknown CHOAM page');const tabs=spec.tabs.map(([key,label,detail])=>{const content=el('div',undefined,'cp-v2-bank-placeholder');const image=el('img');image.src='https://www.dunerealms.com/assets/nav-exchange-v2.webp';image.alt='';image.width=82;image.height=82;content.append(image,el('h4',label),el('p',detail),el('p','V2 · PLANNED — market data and trading actions are not connected.','cp-v2-bank-status'));return{id:key,label,artwork:'nav-exchange-v2.webp',content}});const {root}=createCPV2Page({title:spec.title,description:spec.description,artwork:'nav-exchange-v2.webp',tabs});host.replaceChildren(root);return()=>root.remove()}
|
||||
|
||||
export function mountCommodityExchange(host,id,{fetcher=fetch}={}){let active=true,dispose=()=>{};import('./cp-v2-exchange-design.mjs').then(({mountExchangeDesign})=>{if(active)dispose=mountExchangeDesign(host,{context:'user',view:id==='commodity-mine'?'mine':'browse',fetcher});}).catch(()=>{if(active)host.textContent='Item exchange unavailable.';});return()=>{active=false;dispose();};}
|
||||
|
|
|
|||
|
|
@ -0,0 +1 @@
|
|||
.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}}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
import {organisationTabs} from '../organisation-tabs.mjs';
|
||||
const assets='https://www.dunerealms.com/assets/';
|
||||
const make=(tag,text,className)=>{const node=document.createElement(tag);if(text!==undefined)node.textContent=text;if(className)node.className=className;return node;};
|
||||
const TYPES=[['Clan upgrade','Silver charter','Upgrade a Basic clan','Original or staff issue'],['Company upgrade','Silver charter','Upgrade a Basic company','Original or staff issue'],['Royal appointment','Gold charter','Political appointment or authorised reward','Original or staff issue'],['Political office','Office deed','Appointment for a defined term','Political decision'],['Kit','Equipment seal','Single redemption of a defined kit','Kit service'],['Custom item','Item instance','Unique physical or redeemable item','Codex publication'],['Promotion credit','Dispatch seal','One Board or Discord publication','Reward or authorised grant']];
|
||||
function image(name){const img=make('img');img.src=assets+name;img.alt='';img.loading='lazy';return img;}
|
||||
function field(label,options){const wrapper=make('label',undefined,'codex-field');wrapper.append(make('span',label));let input;if(Array.isArray(options)){input=make('select');for(const option of options){const node=make('option',option);input.append(node);}}else{input=make(options==='message'?'textarea':'input');input.type='text';input.placeholder=options||'';}wrapper.append(input);return wrapper;}
|
||||
function locked(label){const button=make('button',label);button.type='button';button.disabled=true;button.title='Design preview: service connection pending';return button;}
|
||||
function table(headers,rows){const wrap=make('div',undefined,'codex-table-scroll'),table=make('table'),thead=make('thead'),head=make('tr'),body=make('tbody');for(const text of headers){const cell=make('th',text);cell.scope='col';head.append(cell);}thead.append(head);for(const cells of rows){const row=make('tr');for(const value of cells)row.append(make('td',value));body.append(row);}table.append(thead,body);wrap.append(table);return wrap;}
|
||||
function empty(headers,copy){const wrapper=table(headers,[]),row=make('tr'),cell=make('td',copy);cell.colSpan=headers.length;row.append(cell);wrapper.querySelector('tbody').append(row);return wrapper;}
|
||||
function box(title,copy){const node=make('article',undefined,'codex-management-box');node.append(make('h3',title));if(copy)node.append(make('p',copy));return node;}
|
||||
export function mountCodexManagement(host,{initial='keys'}={}){
|
||||
if(!document.querySelector('link[data-codex-management]')){const css=make('link');css.rel='stylesheet';css.href=new URL('./cp-v2-codex-management.css',import.meta.url).href;css.dataset.codexManagement='';document.head.append(css);}
|
||||
const root=make('section',undefined,'codex-management'),hero=make('header',undefined,'codex-management-hero');hero.append(image('exchange-quests-v1.png'));const heading=make('div');heading.append(make('small','IMPERIAL BUREAU · MANAGEMENT'),make('h2','Dunerealm Item Codex'),make('p','Issue, register and deliver the instruments of the realm.'));hero.append(heading);root.append(hero,make('p','Design preview · No live records are loaded. Issuing, replacing, transferring and delivery actions remain unavailable.','codex-preview-notice'));
|
||||
const disposers=[];let mounted=true;const groups=[];
|
||||
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 Codex 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 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 Codex 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});
|
||||
const delivery=box('Deliveries & claims','Track each delivery attempt against one instance. Retries retain the same delivery identity.');delivery.append(field('Delivery state',['All states','Queued','Processing','Delivered','Failed','Redeemed','Revoked']),empty(['Instance','Recipient','Method','State','Last attempt','Action'],'Delivery service not connected. No delivery totals are inferred.'),locked('Retry selected delivery'));groups.push({id:'delivery',title:'Delivery',content:delivery});
|
||||
const listings=box('Listings & distribution','One exchange for goods and eligible Codex instruments. Listings retain the record owner and instance reference.');listings.append(empty(['Listing','Type','Owner','Audience','State'],'Listing administration adapter pending.'),locked('Review listing'));retained(listings,'Open existing exchange controls','./cp-v2-exchange-authority.mjs','mountExchangeAuthority');groups.push({id:'listings',title:'Listings',content:listings});
|
||||
const history=box('History','Issuance, replacements, transfers, redemption and delivery attempts are recorded without exposing private key material.');history.append(field('Search history','Instance, issuer, recipient or decision'),empty(['Time','Instrument','Action','Actor','Reason','Result'],'Audit service not connected.'));groups.push({id:'history',title:'History',content:history});
|
||||
const seasons=box('Seasons & signing keys','Each season or isolated test run has its own signing-key version. Existing deeds and historical items retain their origin.');seasons.append(table(['Policy','Behaviour'],[['Origin','Season, Alpha/Beta/Live stage, release version and issue date stay attached to the instance.'],['Historical originals','Staff regeneration creates a new current-version instance; it never relabels the historical original.'],['Quality','Common, Uncommon, Rare, Very Rare and Legendary describe quality independently from edition age and actual scarcity.'],['Carry-over','Deeds persist. Unused older-season keys and rare items remain valid and transferable when their type permits.'],['Key rotation','New issues use the active signing key; historical signatures remain verifiable.'],['Test isolation','Test-run instances belong to their own namespace and cannot be redeemed in production.'],['Duplicate protection','Validate on use, redemption or transfer; atomic processing accepts an instance only once.']]),locked('Rotate active signing key'),locked('Create isolated test run'));groups.push({id:'seasons',title:'Seasons',content:seasons});
|
||||
root.append(organisationTabs(groups,{label:'Codex Management sections',initial}));host.replaceChildren(root);return()=>{mounted=false;for(const dispose of disposers)if(typeof dispose==='function')dispose();root.remove();};
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
34
website/control-panel/public/cp-v2/cp-v2-exchange-design.mjs
Normal file
34
website/control-panel/public/cp-v2/cp-v2-exchange-design.mjs
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import {organisationTabs} from '../organisation-tabs.mjs';
|
||||
const asset='https://www.dunerealms.com/assets/';
|
||||
const el=(tag,text,cls)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;if(cls)n.className=cls;return n;};
|
||||
const TYPES=[['all','All listings','nav-exchange-v2.webp','Everything in one register'],['items','Minecraft items','minecraft-items/diamond.png','Actual game goods'],['recruitment','Clan recruitment','exchange-clan-recruitment-v1.png','Join a household'],['company','Company jobs','exchange-company-jobs-v1.png','Commercial opportunities'],['faction','Faction jobs','exchange-faction-jobs-v1.png','Serve your faction'],['quests','Quests','exchange-quests-v1.png','Accept a task'],['events','Events','nav-home-v2.webp','Gatherings and campaigns'],['politics','Political positions','exchange-political-positions-v1.png','Public appointments'],['deeds','Companies & deeds','exchange-political-positions-v1.png','Transferable rights']];
|
||||
const SAMPLES=[{id:'preview-recruit',type:'recruitment',title:'A place beneath our banner',owner:'Example household',world:'Kaladam',price:0,description:'Recruitment example. No real vacancy or application is created.'},{id:'preview-quest',type:'quests',title:'Supplies for the next expedition',owner:'Example household',world:'Arrakduin',price:0,description:'Quest example. Objectives and rewards are not connected.'},{id:'preview-office',type:'politics',title:'An imperial appointment',owner:'Example office',world:'Kaiterhof',price:0,description:'Political example. Candidacy and election handling are deferred.'},{id:'preview-event',type:'events',title:'The caravan assembles',owner:'Example event',world:'Giedermark',price:0,description:'Event example. No event is scheduled.'}];
|
||||
const words=value=>String(value||'').replaceAll('_',' ').replace(/\b\w/g,c=>c.toUpperCase());
|
||||
function image(name,cls){const n=el('img',undefined,cls);n.src=asset+name;n.alt='';n.loading='lazy';return n;}
|
||||
function button(label,handler,disabled=false){const n=el('button',label);n.type='button';n.disabled=disabled;n.onclick=handler;return n;}
|
||||
function field(label,options){const box=el('label',undefined,'codex-exchange-field');box.append(el('span',label));const input=el(Array.isArray(options)?'select':options==='message'?'textarea':'input');if(Array.isArray(options))for(const text of options)input.append(el('option',text));else input.placeholder=options||'';box.append(input);return{box,input};}
|
||||
function empty(columns,message){const wrap=el('div',undefined,'codex-exchange-table'),table=el('table'),head=el('tr'),thead=el('thead'),body=el('tbody'),row=el('tr'),cell=el('td',message);for(const label of columns)head.append(el('th',label));thead.append(head);cell.colSpan=columns.length;row.append(cell);body.append(row);table.append(thead,body);wrap.append(table);return wrap;}
|
||||
export function mountExchangeDesign(host,{context='public',view='browse',fetcher=fetch}={}){
|
||||
if(!document.querySelector('link[data-codex-exchange]')){const css=el('link');css.rel='stylesheet';css.href=new URL('./cp-v2-exchange-design.css',import.meta.url).href;css.dataset.codexExchange='';document.head.append(css);}
|
||||
let active=true,rows=[],category=context==='user'?'items':'all',page=0,examples=false,clanKind='unknown';const controller=new AbortController();
|
||||
const root=el('section',undefined,'codex-exchange'),hero=el('header',undefined,'codex-exchange-hero'),copy=el('div');copy.append(el('small','STARPORT · DUNEREALM ITEM CODEX'),el('h2',context==='clan'?'Household Exchange':context==='user'?'Item Exchange':'The Exchange'),el('p','Find your next trade, calling or adventure.'));hero.append(image('nav-exchange-v2.webp'),copy);root.append(hero);
|
||||
const banner=el('p',context==='user'?'Minecraft goods use the existing listings service. Trading remains in game.':'Codex design preview · New listings, applications and promotions are not connected.','codex-exchange-notice');root.append(banner);
|
||||
const browse=el('div'),layout=el('div',undefined,'codex-exchange-layout'),aside=el('aside',undefined,'codex-exchange-categories'),main=el('div',undefined,'codex-exchange-main'),tools=el('div',undefined,'codex-exchange-tools');
|
||||
const search=field('Search','Items, opportunities, sellers or worlds');search.input.type='search';const sort=field('Sort',['Newest first','Price: low to high','Price: high to low','Title']);const quality=field('Quality',['All qualities','Common','Uncommon','Rare','Very Rare','Legendary']);const stage=field('Edition',['All stages','Alpha','Beta','Live']);const season=field('Season',['All seasons','Current season','Earlier seasons']);const preview=el('label',undefined,'codex-exchange-preview'),toggle=el('input');toggle.type='checkbox';preview.append(toggle,el('span','Show design examples'));toggle.onchange=()=>{examples=toggle.checked;page=0;render();};tools.append(search.box,sort.box,quality.box,stage.box,season.box);if(context!=='user')tools.append(preview);const status=el('p','Loading live Minecraft listings…','codex-exchange-status');status.setAttribute('role','status');const cards=el('div',undefined,'codex-exchange-cards'),pager=el('div',undefined,'codex-exchange-pager');main.append(tools,status,cards,pager);layout.append(aside,main);browse.append(layout);
|
||||
const categories=context==='user'?TYPES.filter(([id])=>id==='items'):TYPES;const buttons=[];for(const [id,title,art]of categories){const node=button(title,()=>{category=id;page=0;render();});node.prepend(image(art));node.setAttribute('aria-pressed',String(id===category));buttons.push([node,id]);aside.append(node);}
|
||||
const legend=el('details',undefined,'codex-exchange-legend');legend.append(el('summary','Codex symbols · What each listing means'));const icons=el('div');for(const [,title,art,description]of TYPES.slice(1)){const row=el('section');row.append(image(art),el('strong',title),el('span',description));icons.append(row);}legend.append(icons);browse.append(legend);
|
||||
const mine=el('div');mine.append(el('h3','My listings'),empty(['Artwork','Title','Type','Applications','Promotion','Status','Action'],'Codex listing records are not connected. No records or balances are inferred.'),button('Post a listing',()=>selectPost?.()));
|
||||
const post=el('div',undefined,'codex-exchange-form-grid'),form=el('form',undefined,'codex-exchange-form'),formTitle=el('h3',context==='user'?'List an item':'Post a listing');form.onsubmit=e=>e.preventDefault();form.append(formTitle);const kind=field('Listing type',context==='user'?['Minecraft item']:['Clan recruitment','Quest · Keyed required','Event · Keyed required','Contract · Keyed required']);if(context==='clan')for(const option of [...kind.input.options].slice(1))option.disabled=true;const title=field('Title','A clear title for your listing'),message=field('Message','message'),audience=field('Audience',['Public exchange','Clan only']),promotion=el('fieldset');promotion.append(el('legend','Promotion'));for(const text of ['Publish to Boards','Publish to Discord']){const label=el('label'),input=el('input');input.type='checkbox';label.append(input,el('span',text));promotion.append(label);}const outcome=el('p','Preview only · Nothing has been submitted.','codex-exchange-status');form.append(kind.box,title.box,message.box,audience.box,promotion,button('Preview listing',()=>{previewCard.replaceChildren(el('small','LOCAL PREVIEW · NOT PUBLISHED'),el('h3',title.input.value||'Your listing title'),el('p',message.input.value||'Your message will appear here.'),el('p',kind.input.value));outcome.textContent='Local preview updated. Publishing is unavailable until the Codex service is connected.';}),button(context==='user'?'Create through /exchange in game':'Publish listing',null,true),outcome);const previewCard=el('article',undefined,'codex-exchange-listing-preview');previewCard.append(image(context==='user'?'minecraft-items/diamond.png':'exchange-clan-recruitment-v1.png'),el('h3','Your next chapter'),el('p','Preview your listing before publication.'));post.append(form,previewCard);
|
||||
const applications=el('div');applications.append(el('h3','Applications'),empty(['Applicant','Listing','Received','Status','Review'],'Application service not connected. Existing clan join requests remain available from the dashboard.'),button('Accept application',null,true),button('Decline application',null,true));
|
||||
const promotions=el('div',undefined,'codex-exchange-promotion');promotions.append(el('h3','Promotions & delivery'),el('p','Basic: five initial shared credits. Each Board post costs one; each Discord post costs one. Choose any mix. Quest rewards may add credits. Keyed and Royal remove the Basic credit limit; configured promotion fees apply.'),empty(['Listing','Channel','Cost','State','Last attempt'],'Delivery history is not connected.'),el('p','Available credits: not connected. No charge is made in this preview.'));
|
||||
const eligibility=el('p','Checking your deed…','codex-exchange-eligibility');if(context==='clan')root.append(eligibility);
|
||||
let selectPost;const groups=[{id:'browse',title:'Browse',content:browse}];if(context!=='public'){groups.push({id:'mine',title:'My listings',content:mine},{id:'post',title:context==='user'?'Post an item':'Post a listing',content:post});if(context==='clan')groups.push({id:'applications',title:'Applications',content:applications},{id:'promotions',title:'Promotions',content:promotions});}const tabbed=organisationTabs(groups,{label:'Exchange sections',initial:view});selectPost=()=>tabbed.querySelector('[role=tab][aria-controls$="-post-panel"]')?.click();root.append(tabbed);
|
||||
const footer=el('footer',undefined,'codex-exchange-logistics');footer.append(el('span','Exchange logistics supplied by'),image('spost-logo-v1.svg'),el('small','part of'),image('corrino-group-v4.png'));root.append(footer);host.replaceChildren(root);
|
||||
function render(){for(const [node,id]of buttons)node.setAttribute('aria-pressed',String(id===category));let matches=[...rows,...(examples?SAMPLES.filter(row=>context!=='clan'||['recruitment','quests','events'].includes(row.type)):[])].filter(row=>(category==='all'||row.type===category)&&[row.title,row.owner,row.world].join(' ').toLowerCase().includes(search.input.value.toLowerCase()));if(season.input.selectedIndex>0||quality.input.selectedIndex>0||stage.input.selectedIndex>0)matches=[];matches.sort((a,b)=>sort.input.selectedIndex===1?a.price-b.price:sort.input.selectedIndex===2?b.price-a.price:sort.input.selectedIndex===3?a.title.localeCompare(b.title):Number(b.id)-Number(a.id)||0);page=Math.min(page,Math.max(0,Math.ceil(matches.length/8)-1));cards.replaceChildren();if(!matches.length)cards.append(el('p',season.input.selectedIndex||quality.input.selectedIndex||stage.input.selectedIndex?'Existing goods do not yet carry Codex edition and quality metadata. Matching records will appear after Codex integration.':'No matching listings. Design examples can be enabled separately.','codex-exchange-empty'));for(const row of matches.slice(page*8,page*8+8)){const sample=String(row.id).startsWith('preview-'),type=TYPES.find(([id])=>id===row.type),card=el('article',undefined,'codex-exchange-card');card.append(el('small',sample?'DESIGN EXAMPLE':type?.[1]||'ITEM'));const art=row.type==='items'?'minecraft-items/'+String(row.material).toLowerCase()+'.png':type?.[2],img=image(art,row.type==='items'?'minecraft-texture':undefined);img.onerror=()=>{img.remove();card.prepend(el('span','▧','codex-exchange-missing-icon'));};card.append(img,el('h3',row.title),el('p',row.owner+' · '+row.world),el('strong',row.type==='items'?row.price.toFixed(2)+' DM · '+row.quantity+' available':'View opportunity'),button(row.type==='items'?'View item':row.type==='recruitment'?'View vacancy':'View details',()=>detail(row,sample)));cards.append(card);}pager.replaceChildren(button('← Previous',()=>{page--;render();},page===0),el('span',(page+1)+' / '+Math.max(1,Math.ceil(matches.length/8))),button('Next →',()=>{page++;render();},(page+1)*8>=matches.length));}
|
||||
function detail(row,sample){const dialog=el('dialog',undefined,'codex-exchange-dialog');dialog.append(el('h3',row.title),el('p',row.description||row.owner+' · '+row.world),el('p',sample?'Design example. Applications and purchases are disabled.':'Trade in Minecraft: /exchange buy '+row.id),button('Close',()=>dialog.close()));dialog.onclose=()=>dialog.remove();root.append(dialog);dialog.showModal();}
|
||||
search.input.oninput=()=>{page=0;render();};sort.input.onchange=quality.input.onchange=stage.input.onchange=season.input.onchange=()=>{page=0;render();};
|
||||
async function load(){try{const response=await fetcher(context==='public'?'/api/exchange/listings':'/api/exchange/listings?view=all',{credentials:'same-origin',signal:controller.signal});if(!response.ok)throw Error('unavailable');const data=await response.json();const source=Array.isArray(data)?data:Array.isArray(data.listings)?data.listings:Array.isArray(data.items)?data.items:[];rows=source.filter(row=>Number.isFinite(Number(row.price))&&Number.isFinite(Number(row.quantity))&&/^[A-Za-z0-9_]+$/.test(row.material||'')&&/^\d+$/.test(String(row.id))).map(row=>({...row,type:'items',title:row.displayName||words(row.material),owner:row.seller||row.seller_name||'Player listing',world:words(row.origin),price:Number(row.price),quantity:Number(row.quantity)}));if(!active)return;status.textContent=rows.length+' live Minecraft listings · Codex opportunities pending connection.';render();}catch{if(!active)return;rows=[];status.textContent='Live listings are unavailable. Design examples stay separate and cannot be purchased.';render();}}
|
||||
if(context==='clan')Promise.resolve().then(async()=>{const response=await fetcher('/api/clans',{signal:controller.signal});if(!response.ok)throw Error();const data=await response.json(),clan=data.membership?.clan||data.clan||data.clans?.find(c=>c.role);if(!clan)throw Error();clanKind=clan.charterKind||clan.deed?.charterKind||'unknown';if(!active)return;const tier={basic:['Basic',5],original:['Keyed',25],royal:['Royal',50]}[clanKind];eligibility.textContent=tier?tier[0]+' deed · '+tier[1]+' members maximum · '+(clanKind==='basic'?'Free recruitment; other listing types unlock with an upgrade.':'Advanced listing types available after Codex integration.'):'Deed eligibility is not connected. Advanced listing types remain locked.';if(['original','royal'].includes(clanKind))for(const option of kind.input.options)option.disabled=false;}).catch(()=>{if(active)eligibility.textContent='Deed eligibility could not be confirmed. Advanced listing types remain locked.';});
|
||||
if(context==='user')Promise.resolve().then(async()=>{const response=await fetcher('/api/exchange/listings?view=mine',{signal:controller.signal,credentials:'same-origin'});if(!response.ok)throw Error();const data=await response.json();if(!active)return;const records=Array.isArray(data.listings)?data.listings:[];const table=empty(['Item','World','Quantity','Each · DM'],'No active item listings. List goods through /exchange in game.');if(records.length){const body=table.querySelector('tbody');body.replaceChildren();for(const item of records){const row=el('tr');for(const value of [item.displayName||words(item.material),words(item.origin),String(item.quantity),String(item.price)])row.append(el('td',value));body.append(row);}}mine.replaceChildren(el('h3','My item listings'),table,el('p',data.linked===false?'Link your Minecraft account to see your listings.':'Existing Minecraft listings · manage in game through /exchange.'));}).catch(()=>{if(active)mine.replaceChildren(el('h3','My item listings'),el('p','Your listings are unavailable. Refresh to retry.'));});
|
||||
render();load();return()=>{active=false;controller.abort();root.remove();};
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
import {mountExchangeDesign} from './cp-v2-exchange-design.mjs';
|
||||
import {mountPatronage} from './cp-v2-patronage.mjs';
|
||||
import {mountClaims} from './cp-v2-claims.mjs';
|
||||
import {mountClanBank} from './cp-v2-clan-bank.mjs';
|
||||
|
|
@ -5,7 +6,7 @@ import {element as el} from './cp-v2-page-template.mjs';
|
|||
import {mountNativeService} from './cp-v2-native-services.mjs';
|
||||
import {mountUserPage} from './cp-v2-user-pages.mjs';
|
||||
export function mountPlayWorkspace(host,workspace,id,options={}){
|
||||
if(workspace==='clan'){if(id==='clan-boards')return mountNativeService(host,'clan-boards',{...options,singleHeading:true});if(id==='clan-patronage')return mountPatronage(host);if(id==='clan-claims')return mountClaims(host,{kind:'clan',fetcher:options.fetcher||fetch,clanId:new URLSearchParams(location.hash.split('?')[1]||'').get('clientclan')||options.accountId||null});if(id==='clan-subhouses'){const panel=el('section',undefined,'claims-workspace');panel.append(el('h2','Subhouses'),el('p','Clan allegiance, independence and rebellion are coming soon. Subhouses retain their identity, land and local access; political powers and final authority belong to the ruling clan.'),el('strong','Coming soon'));for(const title of ['Buy Independence','Rebel']){const button=el('button',title);button.type='button';button.disabled=true;panel.append(button);}host.replaceChildren(panel);return()=>panel.remove();}if(id==='clan-bank')return mountClanBank(host,options);
|
||||
if(workspace==='clan'){if(['clan-shop','clan-listings','clan-post-listing'].includes(id))return mountExchangeDesign(host,{context:'clan',view:id==='clan-listings'?'mine':id==='clan-post-listing'?'post':'browse',fetcher:options.fetcher||fetch});if(id==='clan-boards')return mountNativeService(host,'clan-boards',{...options,singleHeading:true});if(id==='clan-patronage')return mountPatronage(host);if(id==='clan-claims')return mountClaims(host,{kind:'clan',fetcher:options.fetcher||fetch,clanId:new URLSearchParams(location.hash.split('?')[1]||'').get('clientclan')||options.accountId||null});if(id==='clan-subhouses'){const panel=el('section',undefined,'claims-workspace');panel.append(el('h2','Subhouses'),el('p','Clan allegiance, independence and rebellion are coming soon. Subhouses retain their identity, land and local access; political powers and final authority belong to the ruling clan.'),el('strong','Coming soon'));for(const title of ['Buy Independence','Rebel']){const button=el('button',title);button.type='button';button.disabled=true;panel.append(button);}host.replaceChildren(panel);return()=>panel.remove();}if(id==='clan-bank')return mountClanBank(host,options);
|
||||
const registry={'clan-overview':'overview','clan-roster':'roster','clan-requests':'requests','clan-settings':'settings','clan-directory':'directory'};
|
||||
if(registry[id])return mountNativeService(host,'clans',{...options,organisationId:options.accountId||new URLSearchParams(location.hash.split('?')[1]||'').get('clientclan')||undefined,singleHeading:true,initialTab:registry[id]});
|
||||
if(id==='clan-mail')return mountNativeService(host,'shared-inbox',{...options,singleHeading:true,initialTab:'clan-inbox'});
|
||||
|
|
|
|||
|
|
@ -1,49 +1,51 @@
|
|||
import {createCPV2Page,element as el} from './cp-v2-page-template.mjs';
|
||||
import {createUserAPI} from './cp-v2-user-api.mjs';
|
||||
export function questRows(data,{query='',status='',page=1}={}){
|
||||
if(typeof data?.linked!=='boolean'||!Array.isArray(data.quests))throw Error('Quest records could not be confirmed.');
|
||||
const filtered=data.quests.filter(row=>(!status||row.status===status)&&[row.title,row.description,row.status].join(' ').toLowerCase().includes(query.trim().toLowerCase())).sort((a,b)=>Number(b.assignedAt||0)-Number(a.assignedAt||0));
|
||||
const pages=Math.max(1,Math.ceil(filtered.length/12)),current=Math.max(1,Math.min(pages,Number.isSafeInteger(page)?page:1));
|
||||
return {rows:filtered.slice((current-1)*12,current*12),pages,page:current,total:filtered.length};
|
||||
}
|
||||
export function mountUserPage(host,id,{fetcher=fetch,initialTab,listingId}={}){
|
||||
let active=true,dispose=()=>{};const controller=new AbortController(),api=createUserAPI(fetcher,controller.signal);
|
||||
host.replaceChildren(el('p','Opening your user workspace…','cp-v2-news-status'));
|
||||
import {createCPV2Page,element as el} from './cp-v2-page-template.mjs';
|
||||
import {createUserAPI} from './cp-v2-user-api.mjs';
|
||||
export function questRows(data,{query='',status='',page=1}={}){
|
||||
if(typeof data?.linked!=='boolean'||!Array.isArray(data.quests))throw Error('Quest records could not be confirmed.');
|
||||
const filtered=data.quests.filter(row=>(!status||row.status===status)&&[row.title,row.description,row.status].join(' ').toLowerCase().includes(query.trim().toLowerCase())).sort((a,b)=>Number(b.assignedAt||0)-Number(a.assignedAt||0));
|
||||
const pages=Math.max(1,Math.ceil(filtered.length/12)),current=Math.max(1,Math.min(pages,Number.isSafeInteger(page)?page:1));
|
||||
return {rows:filtered.slice((current-1)*12,current*12),pages,page:current,total:filtered.length};
|
||||
}
|
||||
export function mountUserPage(host,id,{fetcher=fetch,initialTab,listingId}={}){
|
||||
let active=true,dispose=()=>{};const controller=new AbortController(),api=createUserAPI(fetcher,controller.signal);
|
||||
host.replaceChildren(el('p','Opening your user workspace…','cp-v2-news-status'));
|
||||
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(['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);}
|
||||
const inventory=el('div',undefined,'cp-v2-user-inventory');
|
||||
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(['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);
|
||||
box.append(el('h4','Community connection'),el('p','Loading your public Discord record…'));const data=await api.request('/api/account/profile');if(!active)return;box.replaceChildren(el('h4','Community connection'));
|
||||
const url=data.profile?.socials?.discord;let valid=false;try{const parsed=new URL(url);valid=parsed.protocol==='https:'&&!parsed.username&&!parsed.password&&['discord.com','discord.gg'].some(domain=>parsed.hostname===domain||parsed.hostname.endsWith('.'+domain));}catch{}
|
||||
if(valid){const link=el('a','Open your saved Discord link ↗');link.href=url;link.target='_blank';link.rel='noopener noreferrer';box.append(link);}else box.append(el('p','No Discord social link is saved.'));
|
||||
const edit=el('a','Edit social links');edit.href='#realm/site-profile';const unavailable=el('button','Verified account linking · not available');unavailable.type='button';unavailable.disabled=true;box.append(edit,el('p','Your saved social link is not a verified Discord account connection. The current API does not provide an account-linking service.'),unavailable);dispose=()=>root.remove();return;
|
||||
}
|
||||
throw Error('This user workspace has not been connected.');
|
||||
}
|
||||
function mountQuests(){
|
||||
let data=null,page=1,loading=false;
|
||||
const box=el('section'),status=el('p','Opening your quest record…'),tools=el('div',undefined,'cp-v2-company-actions'),search=el('input'),filter=el('select'),refresh=el('button','Refresh quests'),cards=el('div',undefined,'cp-v2-user-quests'),nav=el('nav',undefined,'cp-v2-company-actions');status.setAttribute('role','status');nav.setAttribute('aria-label','Quest history pages');search.type='search';search.placeholder='Search your quests';search.setAttribute('aria-label','Search your quests');filter.setAttribute('aria-label','Quest status');refresh.type='button';tools.append(search,filter,refresh);box.append(status,tools,cards,nav);
|
||||
const {root}=createCPV2Page({shellHost:host,title:'Contracts & Quests',description:'Your current assignments and retained quest history from the game engine.',artwork:'nav-manual-v2.webp',tabs:[{id:'quest-record',label:'Quest journal',content:box}]});host.replaceChildren(root);
|
||||
const date=value=>value?new Date(Number(value)).toLocaleString():'—';
|
||||
function render(){cards.replaceChildren();nav.replaceChildren();if(!data.linked){const link=el('a','Open Citizen Passport to link Minecraft');link.href='#realm/game';cards.append(el('p','Link your Minecraft identity to see your quests.'),link);return;}
|
||||
const result=questRows(data,{query:search.value,status:filter.value,page});page=result.page;for(const row of result.rows){const card=el('article');card.dataset.status=row.status;card.append(el('h4',row.title),el('p',row.description),el('strong',row.status),el('p','Assigned '+date(row.assignedAt)+' · Deadline '+date(row.deadlineAt)));if(row.completedAt)card.append(el('small','Completed '+date(row.completedAt)));cards.append(card);}if(!result.total)cards.append(el('p','No quests match this view. Assigned adventures will appear here.'));
|
||||
const previous=el('button','← Previous'),next=el('button','Next →');previous.type=next.type='button';previous.disabled=page<=1;next.disabled=page>=result.pages;previous.onclick=()=>{page--;render();};next.onclick=()=>{page++;render();};nav.append(previous,el('span','Page '+page+' of '+result.pages),next);
|
||||
}
|
||||
async function load(){if(loading)return;loading=true;refresh.disabled=true;try{const result=await api.request('/api/quests');if(!active)return;if(result.linked===false&&!result.quests)result.quests=[];questRows(result);data=result;const chosen=filter.value;filter.replaceChildren();for(const value of ['',...new Set(data.quests.map(row=>row.status))]){const option=el('option',value||'All statuses');option.value=value;filter.append(option);}filter.value=[...filter.children].some(row=>row.value===chosen)?chosen:'';render();status.textContent='Quest state confirmed by the game engine.';}catch(error){if(active){status.textContent=error.message;cards.replaceChildren();nav.replaceChildren();}}finally{loading=false;if(active)refresh.disabled=false;}}
|
||||
search.oninput=filter.onchange=()=>{page=1;if(data)render();};refresh.onclick=()=>void load();void load();dispose=()=>root.remove();
|
||||
}
|
||||
void mount().catch(error=>{if(active)host.replaceChildren(el('p',error.message,'cp-v2-news-status'));});
|
||||
return()=>{active=false;controller.abort();dispose();};
|
||||
}
|
||||
if(['item-exchange','item-listings','item-post'].includes(id)){const {mountExchangeDesign}=await import('./cp-v2-exchange-design.mjs');if(active)dispose=mountExchangeDesign(host,{context:'user',view:id==='item-listings'?'mine':id==='item-post'?'post':'browse',fetcher});return;}
|
||||
|
||||
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(['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);}
|
||||
const inventory=el('div',undefined,'cp-v2-user-inventory');
|
||||
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(['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);
|
||||
box.append(el('h4','Community connection'),el('p','Loading your public Discord record…'));const data=await api.request('/api/account/profile');if(!active)return;box.replaceChildren(el('h4','Community connection'));
|
||||
const url=data.profile?.socials?.discord;let valid=false;try{const parsed=new URL(url);valid=parsed.protocol==='https:'&&!parsed.username&&!parsed.password&&['discord.com','discord.gg'].some(domain=>parsed.hostname===domain||parsed.hostname.endsWith('.'+domain));}catch{}
|
||||
if(valid){const link=el('a','Open your saved Discord link ↗');link.href=url;link.target='_blank';link.rel='noopener noreferrer';box.append(link);}else box.append(el('p','No Discord social link is saved.'));
|
||||
const edit=el('a','Edit social links');edit.href='#realm/site-profile';const unavailable=el('button','Verified account linking · not available');unavailable.type='button';unavailable.disabled=true;box.append(edit,el('p','Your saved social link is not a verified Discord account connection. The current API does not provide an account-linking service.'),unavailable);dispose=()=>root.remove();return;
|
||||
}
|
||||
throw Error('This user workspace has not been connected.');
|
||||
}
|
||||
function mountQuests(){
|
||||
let data=null,page=1,loading=false;
|
||||
const box=el('section'),status=el('p','Opening your quest record…'),tools=el('div',undefined,'cp-v2-company-actions'),search=el('input'),filter=el('select'),refresh=el('button','Refresh quests'),cards=el('div',undefined,'cp-v2-user-quests'),nav=el('nav',undefined,'cp-v2-company-actions');status.setAttribute('role','status');nav.setAttribute('aria-label','Quest history pages');search.type='search';search.placeholder='Search your quests';search.setAttribute('aria-label','Search your quests');filter.setAttribute('aria-label','Quest status');refresh.type='button';tools.append(search,filter,refresh);box.append(status,tools,cards,nav);
|
||||
const {root}=createCPV2Page({shellHost:host,title:'Contracts & Quests',description:'Your current assignments and retained quest history from the game engine.',artwork:'nav-manual-v2.webp',tabs:[{id:'quest-record',label:'Quest journal',content:box}]});host.replaceChildren(root);
|
||||
const date=value=>value?new Date(Number(value)).toLocaleString():'—';
|
||||
function render(){cards.replaceChildren();nav.replaceChildren();if(!data.linked){const link=el('a','Open Citizen Passport to link Minecraft');link.href='#realm/game';cards.append(el('p','Link your Minecraft identity to see your quests.'),link);return;}
|
||||
const result=questRows(data,{query:search.value,status:filter.value,page});page=result.page;for(const row of result.rows){const card=el('article');card.dataset.status=row.status;card.append(el('h4',row.title),el('p',row.description),el('strong',row.status),el('p','Assigned '+date(row.assignedAt)+' · Deadline '+date(row.deadlineAt)));if(row.completedAt)card.append(el('small','Completed '+date(row.completedAt)));cards.append(card);}if(!result.total)cards.append(el('p','No quests match this view. Assigned adventures will appear here.'));
|
||||
const previous=el('button','← Previous'),next=el('button','Next →');previous.type=next.type='button';previous.disabled=page<=1;next.disabled=page>=result.pages;previous.onclick=()=>{page--;render();};next.onclick=()=>{page++;render();};nav.append(previous,el('span','Page '+page+' of '+result.pages),next);
|
||||
}
|
||||
async function load(){if(loading)return;loading=true;refresh.disabled=true;try{const result=await api.request('/api/quests');if(!active)return;if(result.linked===false&&!result.quests)result.quests=[];questRows(result);data=result;const chosen=filter.value;filter.replaceChildren();for(const value of ['',...new Set(data.quests.map(row=>row.status))]){const option=el('option',value||'All statuses');option.value=value;filter.append(option);}filter.value=[...filter.children].some(row=>row.value===chosen)?chosen:'';render();status.textContent='Quest state confirmed by the game engine.';}catch(error){if(active){status.textContent=error.message;cards.replaceChildren();nav.replaceChildren();}}finally{loading=false;if(active)refresh.disabled=false;}}
|
||||
search.oninput=filter.onchange=()=>{page=1;if(data)render();};refresh.onclick=()=>void load();void load();dispose=()=>root.remove();
|
||||
}
|
||||
void mount().catch(error=>{if(active)host.replaceChildren(el('p',error.message,'cp-v2-news-status'));});
|
||||
return()=>{active=false;controller.abort();dispose();};
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
|
|
@ -1,24 +1,25 @@
|
|||
import {claimDisplayName} from './cp-v2/cp-v2-claim-tariffs.mjs';
|
||||
import {claimTariffs} from './cp-v2/cp-v2-claim-tariffs.mjs';
|
||||
import {createActivityFeed} from './organisation-activity.mjs';
|
||||
// Shared presentation only. Callers supply verified records and existing navigation.
|
||||
const el=(tag,text,cls)=>{const node=document.createElement(tag);if(text!==undefined)node.textContent=text;if(cls)node.className=cls;return node;};
|
||||
const assets='https://www.dunerealms.com/assets/';
|
||||
export function createOrganisationDashboard({kind='clan',organisation,members=[],role,canReview=false,requests=[],onMembers,onRequests,loadMailbox,loadTreasury,loadClaims,activity=[],activityStatus}={}){
|
||||
if(!document.querySelector('link[data-organisation-dashboard]')){const css=el('link');css.rel='stylesheet';css.href=new URL('./organisation-dashboard.css',import.meta.url).href;css.dataset.organisationDashboard='';document.head.append(css);}
|
||||
const company=kind==='company',noun=company?'Company':'Clan',root=el('div',undefined,'organisation-dashboard');
|
||||
const backgrounds={'Members':'guild.webp','Applications':'political-small-council-v1.png','News & activity':'political-imperial-chamber-v1.png','Events':'clan-atelier-v1.webp','Treasury':'postbank-transfer-hall-v1.png','Land & claims':'guild.webp','Mailbox':'imperial-post-office-v1.png','Needs attention':'political-small-council-v1.png','Subhouses & subsidiaries':'clan-atelier-v1.webp'};
|
||||
function card(title,art,{pending=false}={}){const box=el('article',undefined,'organisation-dashboard-card'),header=el('header'),image=el('img');image.src=assets+art;image.alt='';image.width=image.height=48;box.dataset.dashboardCard=title.toLowerCase().replaceAll(/[^a-z]+/g,'-');box.style.setProperty('--dashboard-art','url("'+assets+(backgrounds[title]||'political-imperial-chamber-v1.png')+'")');header.append(image,el('h3',title));if(pending)header.append(el('span','Coming soon','organisation-dashboard-status'));box.append(header);root.append(box);return box;}
|
||||
function action(box,label,handler){const button=el('button',label);button.type='button';button.onclick=handler;box.append(button);}
|
||||
const welcome=card('Welcome to '+organisation.name,company?'clans/vaerkring-v1.png':'nav-clan-v2.webp');welcome.classList.add('organisation-dashboard-welcome');const emblem=welcome.querySelector('header img');if(organisation.emblem)emblem.src=organisation.emblem;welcome.append(el('small','YOUR '+noun.toUpperCase()+' · YOUR PEOPLE · YOUR NEXT CHAPTER'));const welcomeBoxes=el('div',undefined,'organisation-welcome-boxes');for(const [title,message] of [[noun+' description',organisation.description||'No introduction has been published yet.'],['Message of the day',organisation.motd||(role?'No message of the day has been published.':'The message of the day is visible to members.')]]){const box=el('section',undefined,'organisation-welcome-subbox');box.append(el('h4',title),el('p',message));welcomeBoxes.append(box);}welcome.append(welcomeBoxes,el('p','['+organisation.tag+'] · '+(organisation.homeworldName||'Homeworld not selected')+' · '+(organisation.titles?.[role]||{owner:noun+' owner',heir:'Heir',officer:'Officer',member:'Member'}[role]||'Visitor')));
|
||||
|
||||
const people=card('Members','nav-account-v2.webp'),faces=el('div',undefined,'organisation-dashboard-members');people.append(el('p',members.length+' '+(members.length===1?'member':'members')+' in the register'));
|
||||
for(const member of members.slice(0,8)){const link=el('a',undefined,'organisation-dashboard-member'),image=el('img'),copy=el('span');image.src='https://cp.dunerealms.com/api/avatars/face/roster/'+encodeURIComponent(member.username);image.alt='';image.width=image.height=44;image.loading='lazy';copy.append(el('strong',member.username),el('small',organisation.titles?.[member.clan_role||member.role]||({owner:noun+' owner',heir:'Heir',officer:'Officer',member:'Member'})[member.clan_role||member.role]||'Member'));link.href='https://www.dunerealms.com/people/'+encodeURIComponent(member.username);link.target='_top';link.append(image,copy);faces.append(link);}people.append(faces);if(onMembers)action(people,'View all members →',onMembers);
|
||||
const applications=card('Applications','nav-support-v2.webp');applications.append(el('p',canReview?(requests.length?requests.length+' '+(requests.length===1?'application awaits':'applications await')+' review.':'No applications are waiting for review.'):'Applications are reviewed by the owner and authorised officers.'));
|
||||
if(canReview){for(const request of requests.slice(0,3))applications.append(el('p',request.username,'organisation-dashboard-request'));if(onRequests)action(applications,'Review applications →',onRequests);}
|
||||
const news=card('News & activity','nav-manual-v2.webp');news.append(createActivityFeed(activity,{emptyMessage:activityStatus==='restricted'?'Activity is visible to organisation members.':activityStatus==='unavailable'?'Activity could not be loaded.':'No clan activity has been recorded yet.'}));
|
||||
for(const [title,art,message] of [['Events','nav-manual-full-v2.webp','Upcoming activities, dates and participation will appear here.'],['Treasury','imperial-postbank-v2.png','Available funds and the account reference will appear here once the authorised bank summary is connected.'],['Land & claims','clans/house-veyr-v1.png','Claims share one total chunk budget. Capacity upgrades will be performed ingame by right-clicking the Home Block.']]){const box=card(title,art,{pending:title==='Events'||title==='Land & claims'&&!loadClaims});box.append(el('p',message),el('small','Not connected yet · no records are shown.'));if(title==='Land & claims'){box.querySelectorAll('p,small').forEach(n=>n.remove());const note=el('p',loadClaims?'Checking your claim registry…':'Claims are not connected for this organisation yet.'),info=el('dl');box.append(note,info);if(loadClaims)Promise.resolve().then(loadClaims).then(view=>{if(!root.isConnected)return;if(view.state!=='connected')throw Error('unavailable');note.textContent='Your registered land and claim allowance.';for(const [label,value]of [['Estate rank',claimDisplayName(view.tier)],['Claimed chunks',view.usedChunks+' / '+view.capacity],['Available chunks',view.availableChunks],['Monthly upkeep',view.monthlyUpkeep]])info.append(el('dt',label),el('dd',String(value)));}).catch(()=>{if(root.isConnected)note.textContent='Claim records could not be loaded. Open Claims to refresh.';});const link=el('a','Open land & claims →');link.href=company?'https://corp.dunerealms.com/#company/company-claims':'https://clans.dunerealms.com/#clan/clan-claims';link.target='_top';box.append(link);}if(title==='Treasury'){const table=el('table');for(const [label,value] of [['Available funds','Not connected'],['Account','Authorised view required']]){const row=el('tr');row.append(el('th',label),el('td',value));table.append(row);}box.append(table);if(loadTreasury){box.querySelectorAll('p,small').forEach(n=>n.remove());table.replaceChildren();const note=el('p','Checking authorised clan funds…');box.append(note);Promise.resolve().then(loadTreasury).then(entity=>{if(!root.isConnected)return;note.textContent=entity.state==='not_activated'?'Clan banking has not been activated.':'Current accounts · Imperial Postbank';table.replaceChildren();for(const account of entity.accounts){const row=el('tr'),link=el('a',account.number);link.href='https://cp.dunerealms.com/#bank/bank-statements/'+encodeURIComponent(account.id);link.target='_top';const cell=el('td');cell.append(link);row.append(cell,el('td',account.available+' DM available'));table.append(row);}if(!entity.accounts.length&&entity.state!=='not_activated')note.textContent='No active current accounts are visible with your bank permissions.';}).catch(()=>{if(root.isConnected){table.replaceChildren();note.textContent='Clan funds could not be confirmed. Open Imperial Postbank to check your access.';}});}else{table.replaceChildren();box.querySelector('p').textContent='Clan funds are available only with authorised banking access.';}const bank=el('a','Open Imperial Postbank →');bank.href='https://cp.dunerealms.com/#bank/bank-overview';bank.target='_top';box.append(bank);}}
|
||||
const children=card('Subhouses & subsidiaries','clans/vaerkring-v1.png',{pending:true});children.append(el('p','Subordinate organisations will appear here. Claim rights and management pass to the mother organisation; upkeep and upgrade costs remain with the original organisation.'));const relations=el('table'),head=el('thead'),heading=el('tr');for(const label of ['Organisation','Type','Relationship']){const cell=el('th',label);cell.scope='col';heading.append(cell);}head.append(heading);const body=el('tbody'),row=el('tr'),empty=el('td','Hierarchy records are not connected yet.');empty.colSpan=3;row.append(empty);body.append(row);relations.append(head,body);children.append(relations);
|
||||
const mail=card('Mailbox','imperial-post-office-v1.png'),mailStatus=el('p',loadMailbox?'Checking unread clan mail…':'Clan mail is available to the owner and authorised officers.');mailStatus.setAttribute('role','status');mail.append(mailStatus);if(loadMailbox){const link=el('a','Open clan mailbox →');link.href='https://clans.dunerealms.com/#clan/clan-mail';link.target='_top';mail.append(link);Promise.resolve().then(loadMailbox).then(count=>{if(root.isConnected)mailStatus.textContent=Number.isSafeInteger(count)&&count>=0?'You have '+count+' unread '+(count===1?'message.':'messages.'):'Unread count is unavailable.';}).catch(()=>{if(root.isConnected)mailStatus.textContent='Mail service unavailable. Open the mailbox to retry.';});}
|
||||
const attention=card('Needs attention','nav-support-v2.webp');attention.append(el('p',canReview&&requests.length?requests.length+' pending '+(requests.length===1?'application needs':'applications need')+' your attention.':'No additional dashboard alerts are connected yet.'));if(canReview&&requests.length&&onRequests)action(attention,'Open pending applications →',onRequests);return root;
|
||||
}
|
||||
import {organisationTabs} from './organisation-tabs.mjs';
|
||||
import {claimDisplayName} from './cp-v2/cp-v2-claim-tariffs.mjs';
|
||||
import {claimTariffs} from './cp-v2/cp-v2-claim-tariffs.mjs';
|
||||
import {createActivityFeed} from './organisation-activity.mjs';
|
||||
// Shared presentation only. Callers supply verified records and existing navigation.
|
||||
const el=(tag,text,cls)=>{const node=document.createElement(tag);if(text!==undefined)node.textContent=text;if(cls)node.className=cls;return node;};
|
||||
const assets='https://www.dunerealms.com/assets/';
|
||||
export function createOrganisationDashboard({kind='clan',organisation,members=[],role,canReview=false,requests=[],onMembers,onRequests,loadMailbox,loadTreasury,loadClaims,activity=[],activityStatus}={}){
|
||||
if(!document.querySelector('link[data-organisation-dashboard]')){const css=el('link');css.rel='stylesheet';css.href=new URL('./organisation-dashboard.css',import.meta.url).href;css.dataset.organisationDashboard='';document.head.append(css);}
|
||||
const company=kind==='company',noun=company?'Company':'Clan',root=el('div',undefined,'organisation-dashboard');
|
||||
const backgrounds={'Members':'guild.webp','Applications':'political-small-council-v1.png','News & activity':'political-imperial-chamber-v1.png','Events':'clan-atelier-v1.webp','Treasury':'postbank-transfer-hall-v1.png','Land & claims':'guild.webp','Mailbox':'imperial-post-office-v1.png','Needs attention':'political-small-council-v1.png','Subhouses & subsidiaries':'clan-atelier-v1.webp'};
|
||||
function card(title,art,{pending=false}={}){const box=el('article',undefined,'organisation-dashboard-card'),header=el('header'),image=el('img');image.src=assets+art;image.alt='';image.width=image.height=48;box.dataset.dashboardCard=title.toLowerCase().replaceAll(/[^a-z]+/g,'-');box.style.setProperty('--dashboard-art','url("'+assets+(backgrounds[title]||'political-imperial-chamber-v1.png')+'")');header.append(image,el('h3',title));if(pending)header.append(el('span','Coming soon','organisation-dashboard-status'));box.append(header);root.append(box);return box;}
|
||||
function action(box,label,handler){const button=el('button',label);button.type='button';button.onclick=handler;box.append(button);}
|
||||
const welcome=card('Welcome to '+organisation.name,company?'clans/vaerkring-v1.png':'nav-clan-v2.webp');welcome.classList.add('organisation-dashboard-welcome');const emblem=welcome.querySelector('header img');if(organisation.emblem)emblem.src=organisation.emblem;welcome.append(el('small','YOUR '+noun.toUpperCase()+' · YOUR PEOPLE · YOUR NEXT CHAPTER'));const welcomeBoxes=el('div',undefined,'organisation-welcome-boxes');for(const [title,message] of [[noun+' description',organisation.description||'No introduction has been published yet.'],['Message of the day',organisation.motd||(role?'No message of the day has been published.':'The message of the day is visible to members.')]]){const box=el('section',undefined,'organisation-welcome-subbox');box.append(el('h4',title),el('p',message));welcomeBoxes.append(box);}welcome.append(welcomeBoxes,el('p','['+organisation.tag+'] · '+(organisation.homeworldName||'Homeworld not selected')+' · '+(organisation.titles?.[role]||{owner:noun+' owner',heir:'Heir',officer:'Officer',member:'Member'}[role]||'Visitor')));
|
||||
|
||||
const people=card('Members','nav-account-v2.webp'),faces=el('div',undefined,'organisation-dashboard-members');people.append(el('p',members.length+' '+(members.length===1?'member':'members')+' in the register'));
|
||||
for(const member of members.slice(0,8)){const link=el('a',undefined,'organisation-dashboard-member'),image=el('img'),copy=el('span');image.src='https://cp.dunerealms.com/api/avatars/face/roster/'+encodeURIComponent(member.username);image.alt='';image.width=image.height=44;image.loading='lazy';copy.append(el('strong',member.username),el('small',organisation.titles?.[member.clan_role||member.role]||({owner:noun+' owner',heir:'Heir',officer:'Officer',member:'Member'})[member.clan_role||member.role]||'Member'));link.href='https://www.dunerealms.com/people/'+encodeURIComponent(member.username);link.target='_top';link.append(image,copy);faces.append(link);}people.append(faces);if(onMembers)action(people,'View all members →',onMembers);
|
||||
const applications=card('Applications','nav-support-v2.webp');applications.append(el('p',canReview?(requests.length?requests.length+' '+(requests.length===1?'application awaits':'applications await')+' review.':'No applications are waiting for review.'):'Applications are reviewed by the owner and authorised officers.'));
|
||||
if(canReview){for(const request of requests.slice(0,3))applications.append(el('p',request.username,'organisation-dashboard-request'));if(onRequests)action(applications,'Review applications →',onRequests);}
|
||||
const news=card('News & activity','nav-manual-v2.webp');news.append(createActivityFeed(activity,{emptyMessage:activityStatus==='restricted'?'Activity is visible to organisation members.':activityStatus==='unavailable'?'Activity could not be loaded.':'No clan activity has been recorded yet.'}));
|
||||
for(const [title,art,message] of [['Events','nav-manual-full-v2.webp','Upcoming activities, dates and participation will appear here.'],['Treasury','imperial-postbank-v2.png','Available funds and the account reference will appear here once the authorised bank summary is connected.'],['Land & claims','clans/house-veyr-v1.png','Claims share one total chunk budget. Capacity upgrades will be performed ingame by right-clicking the Home Block.']]){const box=card(title,art,{pending:title==='Events'||title==='Land & claims'&&!loadClaims});box.append(el('p',message),el('small','Not connected yet · no records are shown.'));if(title==='Land & claims'){box.querySelectorAll('p,small').forEach(n=>n.remove());const note=el('p',loadClaims?'Checking your claim registry…':'Claims are not connected for this organisation yet.'),info=el('dl');box.append(note,info);if(loadClaims)Promise.resolve().then(loadClaims).then(view=>{if(!root.isConnected)return;if(view.state!=='connected')throw Error('unavailable');note.textContent='Your registered land and claim allowance.';for(const [label,value]of [['Estate rank',claimDisplayName(view.tier)],['Claimed chunks',view.usedChunks+' / '+view.capacity],['Available chunks',view.availableChunks],['Monthly upkeep',view.monthlyUpkeep]])info.append(el('dt',label),el('dd',String(value)));}).catch(()=>{if(root.isConnected)note.textContent='Claim records could not be loaded. Open Claims to refresh.';});const link=el('a','Open land & claims →');link.href=company?'https://corp.dunerealms.com/#company/company-claims':'https://clans.dunerealms.com/#clan/clan-claims';link.target='_top';box.append(link);}if(title==='Treasury'){const table=el('table');for(const [label,value] of [['Available funds','Not connected'],['Account','Authorised view required']]){const row=el('tr');row.append(el('th',label),el('td',value));table.append(row);}box.append(table);if(loadTreasury){box.querySelectorAll('p,small').forEach(n=>n.remove());table.replaceChildren();const note=el('p','Checking authorised clan funds…');box.append(note);Promise.resolve().then(loadTreasury).then(entity=>{if(!root.isConnected)return;note.textContent=entity.state==='not_activated'?'Clan banking has not been activated.':'Current accounts · Imperial Postbank';table.replaceChildren();for(const account of entity.accounts){const row=el('tr'),link=el('a',account.number);link.href='https://cp.dunerealms.com/#bank/bank-statements/'+encodeURIComponent(account.id);link.target='_top';const cell=el('td');cell.append(link);row.append(cell,el('td',account.available+' DM available'));table.append(row);}if(!entity.accounts.length&&entity.state!=='not_activated')note.textContent='No active current accounts are visible with your bank permissions.';}).catch(()=>{if(root.isConnected){table.replaceChildren();note.textContent='Clan funds could not be confirmed. Open Imperial Postbank to check your access.';}});}else{table.replaceChildren();box.querySelector('p').textContent='Clan funds are available only with authorised banking access.';}const bank=el('a','Open Imperial Postbank →');bank.href='https://cp.dunerealms.com/#bank/bank-overview';bank.target='_top';box.append(bank);}}
|
||||
const children=card('Subhouses & subsidiaries','clans/vaerkring-v1.png',{pending:true});children.append(el('p','Subordinate organisations will appear here. Claim rights and management pass to the mother organisation; upkeep and upgrade costs remain with the original organisation.'));const relations=el('table'),head=el('thead'),heading=el('tr');for(const label of ['Organisation','Type','Relationship']){const cell=el('th',label);cell.scope='col';heading.append(cell);}head.append(heading);const body=el('tbody'),row=el('tr'),empty=el('td','Hierarchy records are not connected yet.');empty.colSpan=3;row.append(empty);body.append(row);relations.append(head,body);children.append(relations);
|
||||
const mail=card('Mailbox','imperial-post-office-v1.png'),mailStatus=el('p',loadMailbox?'Checking unread clan mail…':'Clan mail is available to the owner and authorised officers.');mailStatus.setAttribute('role','status');mail.append(mailStatus);if(loadMailbox){const link=el('a','Open clan mailbox →');link.href='https://clans.dunerealms.com/#clan/clan-mail';link.target='_top';mail.append(link);Promise.resolve().then(loadMailbox).then(count=>{if(root.isConnected)mailStatus.textContent=Number.isSafeInteger(count)&&count>=0?'You have '+count+' unread '+(count===1?'message.':'messages.'):'Unread count is unavailable.';}).catch(()=>{if(root.isConnected)mailStatus.textContent='Mail service unavailable. Open the mailbox to retry.';});}
|
||||
const attention=card('Needs attention','nav-support-v2.webp');attention.append(el('p',canReview&&requests.length?requests.length+' pending '+(requests.length===1?'application needs':'applications need')+' your attention.':'No additional dashboard alerts are connected yet.'));if(canReview&&requests.length&&onRequests)action(attention,'Open pending applications →',onRequests);const groups=[['overview','Overview',['welcome','land-claims','needs-attention']],['people','People',['members','applications']],['household','Household',['treasury','mailbox','subhouses-subsidiaries']],['activity','Activity',['news-activity','events']]].map(([id,title,names])=>{const content=el('div',undefined,'organisation-dashboard');for(const node of [...root.children])if(names.includes(node.dataset.dashboardCard)||id==='overview'&&node.classList.contains('organisation-dashboard-welcome'))content.append(node);return{id,title,content};});root.classList.remove('organisation-dashboard');root.replaceChildren(organisationTabs(groups,{label:noun+' dashboard sections'}));return root;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
// Internal settings-page template. Adapters supply existing authorised forms.
|
||||
export function createOrganisationSettings(sections){
|
||||
if(!document.querySelector('link[data-organisation-settings]')){const css=document.createElement('link');css.rel='stylesheet';css.href=new URL('./organisation-settings.css',import.meta.url).href;css.dataset.organisationSettings='';document.head.append(css);}
|
||||
const root=document.createElement('div');root.className='organisation-settings-grid';
|
||||
for(const {title,description,content,pending=false,danger=false} of sections){const card=document.createElement('section');card.className='organisation-settings-card'+(danger?' organisation-settings-danger':'');const heading=document.createElement('h3');heading.textContent=title;card.append(heading);if(pending){const badge=document.createElement('span');badge.className='organisation-settings-status';badge.textContent='Coming soon';card.append(badge);}const copy=document.createElement('p');copy.textContent=description;card.append(copy);if(content){if(content.tagName==='FORM')content.querySelector(':scope > h3')?.remove();card.append(content);}root.append(card);}return root;
|
||||
}
|
||||
import {organisationTabs} from './organisation-tabs.mjs';
|
||||
// Internal settings-page template. Adapters supply existing authorised forms.
|
||||
export function createOrganisationSettings(sections){
|
||||
if(!document.querySelector('link[data-organisation-settings]')){const css=document.createElement('link');css.rel='stylesheet';css.href=new URL('./organisation-settings.css',import.meta.url).href;css.dataset.organisationSettings='';document.head.append(css);}
|
||||
const root=document.createElement('div');root.className='organisation-settings-grid';
|
||||
for(const {title,description,content,pending=false,danger=false} of sections){const card=document.createElement('section');card.className='organisation-settings-card'+(danger?' organisation-settings-danger':'');const heading=document.createElement('h3');heading.textContent=title;card.append(heading);if(pending){const badge=document.createElement('span');badge.className='organisation-settings-status';badge.textContent='Coming soon';card.append(badge);}const copy=document.createElement('p');copy.textContent=description;card.append(copy);if(content){if(content.tagName==='FORM')content.querySelector(':scope > h3')?.remove();card.append(content);}root.append(card);}
|
||||
const groups=[['identity','Identity',['Identity & homeworld','Clan emblem']],['messages','Messages',['Message of the day']],['leadership','Leadership',['Leadership & roles','Ownership deed & dynasty']],['charter','Charter',['Claim charter & capacity','Relations & subhouses']],['keys','Keys',[]],['archive','Archive',['Archive clan']]].map(([id,title,titles])=>{const content=document.createElement('div');content.className='organisation-settings-grid';for(const card of [...root.children])if(titles.includes(card.querySelector('h3')?.textContent))content.append(card);if(id==='keys'){const card=document.createElement('section');card.className='organisation-settings-card';const heading=document.createElement('h3');heading.textContent='Unused upgrade keys';const note=document.createElement('p');note.textContent='Owner and member upgrade rights, including subclans. Design preview: private keys and ownership checks are not connected.';const scroll=document.createElement('div');scroll.style.overflow='auto';const table=document.createElement('table');const head=document.createElement('tr');for(const label of ['Holder','Clan / subclan','Type','Purpose','Origin','Status']){const cell=document.createElement('th');cell.textContent=label;head.append(cell);}const thead=document.createElement('thead');thead.append(head);const body=document.createElement('tbody'),row=document.createElement('tr'),cell=document.createElement('td');cell.colSpan=6;cell.textContent='Authorised key register will appear here. No private member keys are loaded.';row.append(cell);body.append(row);table.append(thead,body);scroll.append(table);card.append(heading,note,scroll);content.append(card);}return{id,title,content};});
|
||||
if(root.children.length){groups[0].content.append(...root.children);}return organisationTabs(groups,{label:'Organisation settings sections'});
|
||||
}
|
||||
|
|
|
|||
1
website/control-panel/public/organisation-tabs.css
Normal file
1
website/control-panel/public/organisation-tabs.css
Normal file
|
|
@ -0,0 +1 @@
|
|||
.organisation-tabbed{min-width:0;width:100%}.organisation-tabs{display:flex;gap:8px;flex-wrap:wrap;padding:16px 18px;border-bottom:1px solid #7c7245;margin-bottom:18px}.organisation-tabs button{font:inherit;min-height:44px;padding:10px 17px;border:1px solid #7d875f;border-radius:8px;background:#142e28;color:#dfd6b5;cursor:pointer}.organisation-tabs button[aria-selected=true]{border-color:#e8c96c;color:#ffe5a1;background:linear-gradient(130deg,#395140,#223a31);box-shadow:inset 0 -3px #ccb365}.organisation-tabbed [role=tabpanel][hidden]{display:none!important}.organisation-tabbed [role=tabpanel]{min-width:0}.organisation-tabs button:focus-visible{outline:3px solid #91c8da;outline-offset:3px}@media(max-width:500px){.organisation-tabs{padding:10px;gap:6px}.organisation-tabs button{flex:1 1 auto;padding:10px}}
|
||||
9
website/control-panel/public/organisation-tabs.mjs
Normal file
9
website/control-panel/public/organisation-tabs.mjs
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
let sequence=0;
|
||||
export function organisationTabs(groups,{label='Workspace sections',initial}={}){
|
||||
const root=document.createElement('div');root.className='organisation-tabbed';
|
||||
if(!document.querySelector('link[data-organisation-tabs]')){const css=document.createElement('link');css.rel='stylesheet';css.href=new URL('./organisation-tabs.css',import.meta.url).href;css.dataset.organisationTabs='';document.head.append(css);}
|
||||
const nav=document.createElement('div');nav.className='organisation-tabs';nav.setAttribute('role','tablist');nav.setAttribute('aria-label',label);root.append(nav);const entries=[];const prefix='organisation-tabs-'+(++sequence);
|
||||
groups.forEach(({id,title,content},i)=>{const button=document.createElement('button'),panel=document.createElement('section');button.type='button';button.textContent=title;button.id=prefix+'-'+id;button.setAttribute('role','tab');button.setAttribute('aria-controls',button.id+'-panel');panel.id=button.id+'-panel';panel.setAttribute('role','tabpanel');panel.setAttribute('aria-labelledby',button.id);panel.tabIndex=0;panel.append(content);nav.append(button);root.append(panel);entries.push({id,button,panel});button.onclick=()=>select(id);button.onkeydown=e=>{let index;if(e.key==='ArrowRight')index=(i+1)%entries.length;if(e.key==='ArrowLeft')index=(i+entries.length-1)%entries.length;if(e.key==='Home')index=0;if(e.key==='End')index=entries.length-1;if(index!==undefined){e.preventDefault();select(entries[index].id);entries[index].button.focus();}};});
|
||||
function select(id){for(const entry of entries){const active=entry.id===id;entry.button.setAttribute('aria-selected',String(active));entry.button.tabIndex=active?0:-1;entry.panel.hidden=!active;}}
|
||||
select(entries.some(e=>e.id===initial)?initial:entries[0]?.id);return root;
|
||||
}
|
||||
|
|
@ -308,6 +308,8 @@ export function createPanel(db,settings={},dependencies={}){
|
|||
if(/^\/(?:v2|cp-v2)\/cp-v2-[a-z0-9-]+\.(?:mjs|css)$/.test(path)){
|
||||
try{const bytes=await readFile(new URL('./public/cp-v2/'+path.slice(path.lastIndexOf('/')+1),import.meta.url));return new Response(request.method==='HEAD'?null:bytes,{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'}});}catch(error){if(error.code==='ENOENT')return new Response('Not found',{status:404});throw error;}
|
||||
}
|
||||
if(['/v2/cp-v2-codex-management.mjs','/v2/cp-v2-codex-management.css','/v2/cp-v2-exchange-design.mjs','/v2/cp-v2-exchange-design.css'].includes(path))return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/'+path.slice(4),import.meta.url)),{headers:{'Content-Type':path.endsWith('.css')?'text/css; charset=utf-8':'text/javascript; charset=utf-8','Cache-Control':'no-store','Access-Control-Allow-Origin':'*'}});
|
||||
if(['/organisation-tabs.mjs','/organisation-tabs.css'].includes(path))return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/'+path.slice(1),import.meta.url)),{headers:{'Content-Type':path.endsWith('.css')?'text/css; charset=utf-8':'text/javascript; charset=utf-8','Cache-Control':'no-store','Access-Control-Allow-Origin':'*'}});
|
||||
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-code-redemption.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');
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
(()=>{const frame=document.getElementById('clan-workspace');if(!frame)return;frame.setAttribute('scrolling','no');frame.addEventListener('load',()=>frame.contentWindow?.postMessage({type:'dune-embed-measure'},'https://cp.dunerealms.com'));const cp='https://cp.dunerealms.com',legacy={'clans':'clan/clan-directory','clan-portal':'clan/clan-overview','clan-kits':'clan/clan-tailor','clan-shops':'clan/clan-shop','clan-bank':'clan/clan-bank','clan-settings':'clan/clan-settings','clan-quests':'clan/clan-quests'};
|
||||
const valid=value=>/^(?:clan\/(?:clan-(?:overview|roster|requests|settings|directory|boards|mail|bank|shop|tailor|quests|campaigns|claims|subhouses|patronage))|quests\/quests|kits\/kits-exchange|events\/events-calendar)$/.test(value);
|
||||
function show(){const raw=location.hash.slice(1),route=valid(raw)?raw:legacy[raw]||'clan/clan-overview',url=cp+'/clan-cp#'+route;if(frame.src!==url)frame.src=url;}window.addEventListener('hashchange',show);
|
||||
window.addEventListener('message',event=>{if(event.origin!==cp||event.source!==frame.contentWindow)return;if(event.data?.type==='dune-embed-size'&&Number.isFinite(event.data.height)&&event.data.height>=100&&event.data.height<=200000)frame.style.height=Math.ceil(event.data.height)+'px';if(event.data?.type==='dune-clan-route'){const route=event.data.workspace+'/'+event.data.page;if(valid(route))history.replaceState(null,'','#'+route);}});show();})();
|
||||
(()=>{const frame=document.getElementById('clan-workspace');if(!frame)return;frame.setAttribute('scrolling','no');frame.addEventListener('load',()=>frame.contentWindow?.postMessage({type:'dune-embed-measure'},'https://cp.dunerealms.com'));const cp='https://cp.dunerealms.com',legacy={'clans':'clan/clan-directory','clan-portal':'clan/clan-overview','clan-kits':'clan/clan-tailor','clan-shops':'clan/clan-shop','clan-bank':'clan/clan-bank','clan-settings':'clan/clan-settings','clan-quests':'clan/clan-quests'};
|
||||
const valid=value=>/^(?:clan\/(?:clan-(?:overview|roster|requests|settings|directory|boards|mail|bank|shop|listings|post-listing|tailor|quests|campaigns|claims|subhouses|patronage))|quests\/quests|kits\/kits-exchange|events\/events-calendar)$/.test(value);
|
||||
function show(){const raw=location.hash.slice(1),route=valid(raw)?raw:legacy[raw]||'clan/clan-overview',url=cp+'/clan-cp#'+route;if(frame.src!==url)frame.src=url;}window.addEventListener('hashchange',show);
|
||||
window.addEventListener('message',event=>{if(event.origin!==cp||event.source!==frame.contentWindow)return;if(event.data?.type==='dune-embed-size'&&Number.isFinite(event.data.height)&&event.data.height>=100&&event.data.height<=200000)frame.style.height=Math.ceil(event.data.height)+'px';if(event.data?.type==='dune-clan-route'){const route=event.data.workspace+'/'+event.data.page;if(valid(route))history.replaceState(null,'','#'+route);}});show();})();
|
||||
|
|
|
|||
|
|
@ -1,15 +1,15 @@
|
|||
import {readFile,mkdir,writeFile} from 'node:fs/promises';
|
||||
import {fileURLToPath} from 'node:url';
|
||||
import path from 'node:path';
|
||||
import {DESIGN_PAGES} from '../control-panel/public/cp-v2/cp-v2-design-catalog.mjs';
|
||||
const menuSource=await readFile(new URL('../control-panel/public/cp-v2/v2.js',import.meta.url),'utf8');
|
||||
const menu=JSON.parse(menuSource.slice('const menu='.length,menuSource.indexOf(';')));
|
||||
const oldSource=await readFile(new URL('../control-panel/public/pages.mjs',import.meta.url),'utf8'),start=oldSource.indexOf('const pages=')+'const pages='.length;
|
||||
const oldIds=new Set(Object.keys(JSON.parse(oldSource.slice(start,oldSource.indexOf(';',start)))));
|
||||
const oldLayout=await readFile(new URL('../control-panel/public/panel-layout.mjs',import.meta.url),'utf8');for(const match of oldLayout.matchAll(/item\([^,]+,'([^']+)'/g))oldIds.add(match[1]);
|
||||
for(const id of ['dev-panel','dev-queue','dev-approvals','dev-new','dev-archive'])oldIds.add(id);
|
||||
export const designAliases={'realm/company-directory':'realm/companies','realm/company-registration':'realm/companies','realm/company-profile':'realm/companies','realm/company-members':'realm/companies','realm/company-finance':'realm/companies','realm/company-permissions':'realm/companies','realm/company-applications':'realm/companies','market/company-directory':'market/companies','market/company-profile':'market/companies'};
|
||||
const implementedBankPages=new Set(['bank-authorisations','federal-reserve','dunemark-collection']);
|
||||
export function auditDesign(){return menu.workspaces.flatMap(w=>w.groups.flatMap(g=>g.items.map(item=>{const key=w.id+'/'+item.id,design=DESIGN_PAGES[key],preserved=['quests','kits'].includes(w.id)||w.id==='clan'&&!['clan-campaigns','clan-quests'].includes(item.id)||w.id==='bank'&&(item.id==='bank-information'||implementedBankPages.has(item.id))||w.id==='politics'||w.id==='market'&&['commodity-listings','commodity-mine'].includes(item.id)||w.id==='bureau'&&item.id!=='kit-claims'||w.id==='forge'&&['dev-panel','dev-queue','dev-approvals','dev-new','dev-archive','git-workspace','git-repositories','git-administration'].includes(item.id);return{workspace:w.label,group:g.label,key,title:item.label,existedInV1:oldIds.has(item.id),classification:w.id==='events'||['clan-campaigns','clan-quests'].includes(item.id)?'planned-placeholder':design?'new-design-only':preserved?'preserved-implemented':oldIds.has(item.id)?'v1-integration-next':'needs-design-spec',tabs:design?.tabs.map(t=>t.label)||[],fields:design?[...new Set(design.tabs.flatMap(t=>t.fields.map(f=>f.label)))]:[]};})));}
|
||||
export async function writeDesignAudit(destination){const rows=auditDesign(),summary={menus:rows.length,designed:rows.filter(r=>r.classification==='new-design-only').length,integrationNext:rows.filter(r=>r.classification==='v1-integration-next').length,preserved:rows.filter(r=>r.classification==='preserved-implemented').length,uncovered:rows.filter(r=>r.classification==='needs-design-spec').map(r=>r.key),featureTabs:Object.values(DESIGN_PAGES).reduce((n,p)=>n+p.tabs.length,0)};await mkdir(destination,{recursive:true});await writeFile(path.join(destination,'design-batch.json'),JSON.stringify({summary,rows,aliases:designAliases},null,2));const lines=['DUNEREALMS V2 — NEW PAGE DESIGN BATCH','Design only. No API integration or live business changes.','',JSON.stringify(summary,null,2),''];for(const workspace of menu.workspaces){lines.push(workspace.label);for(const r of rows.filter(r=>r.workspace===workspace.label)){lines.push(' '+r.title+' ['+r.classification+'] — '+r.key);if(r.tabs.length)lines.push(' Tabs: '+r.tabs.join(' | '));}lines.push('');}lines.push('COMPANY BOOKMARK ALIASES');for(const [from,to]of Object.entries(designAliases))lines.push(from+' -> '+to);await writeFile(path.join(destination,'design-batch.txt'),lines.join('\n'));return summary;}
|
||||
if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){const result=await writeDesignAudit(process.argv[2]||'output/cp-v2-design-batch');console.log(JSON.stringify(result));if(result.uncovered.length)process.exitCode=1;}
|
||||
import {readFile,mkdir,writeFile} from 'node:fs/promises';
|
||||
import {fileURLToPath} from 'node:url';
|
||||
import path from 'node:path';
|
||||
import {DESIGN_PAGES} from '../control-panel/public/cp-v2/cp-v2-design-catalog.mjs';
|
||||
const menuSource=await readFile(new URL('../control-panel/public/cp-v2/v2.js',import.meta.url),'utf8');
|
||||
const menu=JSON.parse(menuSource.slice('const menu='.length,menuSource.indexOf(';')));
|
||||
const oldSource=await readFile(new URL('../control-panel/public/pages.mjs',import.meta.url),'utf8'),start=oldSource.indexOf('const pages=')+'const pages='.length;
|
||||
const oldIds=new Set(Object.keys(JSON.parse(oldSource.slice(start,oldSource.indexOf(';',start)))));
|
||||
const oldLayout=await readFile(new URL('../control-panel/public/panel-layout.mjs',import.meta.url),'utf8');for(const match of oldLayout.matchAll(/item\([^,]+,'([^']+)'/g))oldIds.add(match[1]);
|
||||
for(const id of ['dev-panel','dev-queue','dev-approvals','dev-new','dev-archive'])oldIds.add(id);
|
||||
export const designAliases={'realm/company-directory':'realm/companies','realm/company-registration':'realm/companies','realm/company-profile':'realm/companies','realm/company-members':'realm/companies','realm/company-finance':'realm/companies','realm/company-permissions':'realm/companies','realm/company-applications':'realm/companies','market/company-directory':'market/companies','market/company-profile':'market/companies'};
|
||||
const implementedBankPages=new Set(['bank-authorisations','federal-reserve','dunemark-collection']);
|
||||
export function auditDesign(){return menu.workspaces.flatMap(w=>w.groups.flatMap(g=>g.items.map(item=>{const key=w.id+'/'+item.id,design=DESIGN_PAGES[key],preserved=w.id==='realm'&&['item-exchange','item-listings','item-post'].includes(item.id)||['quests','kits'].includes(w.id)||w.id==='clan'&&!['clan-campaigns','clan-quests'].includes(item.id)||w.id==='bank'&&(item.id==='bank-information'||implementedBankPages.has(item.id))||w.id==='politics'||w.id==='market'&&['commodity-listings','commodity-mine'].includes(item.id)||w.id==='bureau'&&item.id!=='kit-claims'||w.id==='forge'&&['dev-panel','dev-queue','dev-approvals','dev-new','dev-archive','git-workspace','git-repositories','git-administration'].includes(item.id);return{workspace:w.label,group:g.label,key,title:item.label,existedInV1:oldIds.has(item.id),classification:w.id==='events'||['clan-campaigns','clan-quests'].includes(item.id)?'planned-placeholder':design?'new-design-only':preserved?'preserved-implemented':oldIds.has(item.id)?'v1-integration-next':'needs-design-spec',tabs:design?.tabs.map(t=>t.label)||[],fields:design?[...new Set(design.tabs.flatMap(t=>t.fields.map(f=>f.label)))]:[]};})));}
|
||||
export async function writeDesignAudit(destination){const rows=auditDesign(),summary={menus:rows.length,designed:rows.filter(r=>r.classification==='new-design-only').length,integrationNext:rows.filter(r=>r.classification==='v1-integration-next').length,preserved:rows.filter(r=>r.classification==='preserved-implemented').length,uncovered:rows.filter(r=>r.classification==='needs-design-spec').map(r=>r.key),featureTabs:Object.values(DESIGN_PAGES).reduce((n,p)=>n+p.tabs.length,0)};await mkdir(destination,{recursive:true});await writeFile(path.join(destination,'design-batch.json'),JSON.stringify({summary,rows,aliases:designAliases},null,2));const lines=['DUNEREALMS V2 — NEW PAGE DESIGN BATCH','Design only. No API integration or live business changes.','',JSON.stringify(summary,null,2),''];for(const workspace of menu.workspaces){lines.push(workspace.label);for(const r of rows.filter(r=>r.workspace===workspace.label)){lines.push(' '+r.title+' ['+r.classification+'] — '+r.key);if(r.tabs.length)lines.push(' Tabs: '+r.tabs.join(' | '));}lines.push('');}lines.push('COMPANY BOOKMARK ALIASES');for(const [from,to]of Object.entries(designAliases))lines.push(from+' -> '+to);await writeFile(path.join(destination,'design-batch.txt'),lines.join('\n'));return summary;}
|
||||
if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){const result=await writeDesignAudit(process.argv[2]||'output/cp-v2-design-batch');console.log(JSON.stringify(result));if(result.uncovered.length)process.exitCode=1;}
|
||||
|
|
|
|||
|
|
@ -30,6 +30,12 @@ function preparePublicHtml(html){
|
|||
}
|
||||
return result;
|
||||
}
|
||||
// Publish the shared Exchange presentation on the public origin for strict CSP.
|
||||
for(const [source,target] of [['cp-v2/cp-v2-exchange-design.mjs','codex-exchange.js'],['cp-v2/cp-v2-exchange-design.css','codex-exchange.css'],['organisation-tabs.mjs','codex-tabs.js'],['organisation-tabs.css','codex-tabs.css']]){
|
||||
let content=readFileSync(path.join(root,'control-panel/public',source),'utf8');
|
||||
if(target.endsWith('.js'))content=content.replaceAll('../organisation-tabs.mjs','./codex-tabs.js').replaceAll('./organisation-tabs.css','./codex-tabs.css').replaceAll('./cp-v2-exchange-design.css','./codex-exchange.css');
|
||||
writeFileSync(path.join(web,target),content);
|
||||
}
|
||||
writeFileSync(path.join(web,'rates-and-charges.html'),bankRatesPage());
|
||||
let assetCount=0;let assetWriter=null;const types={'.html':'text/html; charset=utf-8','.css':'text/css; charset=utf-8','.js':'text/javascript; charset=utf-8','.json':'application/json; charset=utf-8','.webp':'image/webp','.png':'image/png','.mp4':'video/mp4','.zip':'application/zip','.svg':'image/svg+xml'};
|
||||
function collect(directory){for(const entry of readdirSync(directory).sort()){const p=path.join(directory,entry);if(statSync(p).isDirectory())collect(p);else{const relative=path.relative(web,p).split(path.sep).join('/');if(/^assets\/seals\/[^/]+-provenance\.txt$/.test(relative)||/^assets\/organisation-deed(?:s)?-[a-z0-9-]+\.png$/.test(relative))continue;const type=types[path.extname(entry)];if(!type)throw Error('Unexpected asset: '+entry);const bytes=readFileSync(p);const payload=relative.endsWith('.html')?Buffer.from(preparePublicHtml(bytes.toString('utf8'))):relative==='portal-navigation.js'?Buffer.from(withCanonicalMenu(withMenuBadges(bytes.toString('utf8')))):relative==='portal-navigation.css'?Buffer.concat([bytes,Buffer.from(HOUSE_STYLE_CSS)]):bytes;writeSync(assetWriter,JSON.stringify('/'+relative)+':['+JSON.stringify(type)+','+JSON.stringify(payload.toString('base64'))+'],');assetCount++}}}if(existsSync(dist)){const resolved=path.resolve(dist);if(resolved!==path.join(root,'dist'))throw Error('Invalid dist directory');rmSync(resolved,{recursive:true,force:true})}
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue

Staff