1
0
Fork 0

Compare commits

..

21 commits

Author SHA1 Message Date
9dea9d1e36 v0.9.0 - add journals, automatic awards, and a customizable dashboard 2026-10-13 11:32:37 -04:00
9c074b5af6 docs: add v0.9.0 changelog entry 2026-10-13 11:32:27 -04:00
8d5aa081ba fix(bot): read open-ended changelog ranges in the newest direction
CHANGELOG.md is newest-first, but resolveChangelogRange treated its two
range ends as a closed min/max index pair. A range with only a starting
version ("0.6.0..") therefore resolved to the oldest entries through
0.6.0 instead of 0.6.0 and everything newer, so the release-notes command
announced the wrong set of releases.

Resolve each open end toward the direction it opens: "X.." runs from the
newest entry down to X, "..X" runs from X to the oldest entry, and a
closed range still normalizes to min/max. Adds a regression test against
the shipped file.
2026-10-13 11:18:24 -04:00
e1cfdd3329 feat(dashboard): apply the tactical dossier style to the remaining widgets
Wallet, Negotiations, My Tickets, Notifications, Upcoming Missions,
Active Campaigns and Recent Events were still conventional shadcn Item
cards while Service Summary, Mission Briefing and Situation Report already
used the dossier primitives. Wrap them in the shared TacticalFrame so the
whole dashboard reads as one board:

- classification strip naming the domain (Logistics // Banking,
  Helpdesk // Tickets, and so on), with a REF code on the wallet
- squared corners, corner brackets and the faint grid texture
- an inner header row of icon + uppercase title + action link, matching
  the Service Summary widget
- squared (rounded-sm, bordered) status pills for tickets and campaigns
- a ReadoutFooter on the wallet (account id + status) via the shared
  ReadoutFooter primitive

Empty and self-hiding states are preserved, and the wallet's no-account
path still returns the conventional MyWalletCard CTA. Also drops a dead
CLOSING_STATUSES import from MyTickets.
2026-10-13 11:08:56 -04:00
2a264a4530 test(audit): support exact route filtering in the mobile audit
AUDIT_ROUTE_FILTER now accepts "=/route" for an exact match in addition to
the existing substring match, so a single route such as the dashboard can be
audited on its own without pulling in every route that contains the filter.
2026-10-13 10:38:45 -04:00
9bfe43ad71 fix(dashboard): drop the mission widget header row
The Operations // Last Mission widget carried a header row whose left side
repeated the mission code name already shown on the card below, and after
that duplication was removed the row held only a lone right-aligned
"View all" link floating in an empty band. Remove the row entirely: the
frame strip names the section and the mission card carries its own
"View details" affordance.
2026-10-13 10:38:45 -04:00
3b3bba5d54 test(audit): refresh baseline after the final mobile gate
Full 390x844 pass on a fresh dev server: 68/68 routes ok, zero findings in
every violation class (overflow, grid, hoverOnly, tapTarget), leaving only
the review tiers (611 marginal, 6 WCAG-exempt inline links, 1 informational
hidden-on-mobile) plus the banking hydration fix.
2026-10-12 23:04:29 -04:00
6be2af2f86 fix(banking): render currency emblem inline to stop the hydration mismatch
CurrencyAmount returned a div, but callers place it inside p and span
(wallet hero balance, account cards, unit funds), which is invalid nesting:
the browser's parser closes the p early, so server and client markup differ
and React reports a hydration error on the banking pages. An inline-flex
span renders identically in all four call sites and is valid in each.
2026-10-12 23:04:29 -04:00
5765492494 test(audit): measure effective tap targets and report violation tiers
Raw element boxes overstated violations, so the check now measures what a
user actually taps, and reports the tiers separately (violation under
24px, marginal 24-39px, inline-exempt):

- effective target is the wrapping label, or label[for] for small
  checkables only. Verified in the browser that clicking a label toggles
  its Radix Switch (label rows are 84px tall); a Select's 14px caption
  label is not charged because its 36px trigger is the real target
- stretched-link cards (after:absolute inset-0) are measured on the
  positioned ancestor, not the 18px anchor inside
- sr-only proxy controls (under 8px) and input[type=range] are excluded
  (a slider's thumb is the target, not the 4px track)
- display:inline anchors in prose get the WCAG 2.5.8 inline exception and
  are reported as tapTargetInlineText
- refreshed baseline: 0 violations, 573 marginal, 6 inline, 1 hidden
2026-10-12 22:17:58 -04:00
9c3870cf79 fix(mobile): meet the 24px tap-target floor across the app
Session A measured 159 targets under the WCAG 2.5.8 minimum on 42 routes;
this brings that to zero. Mostly one-line spacing changes: small caption
labels and text links were 14-21px tall because shadcn Label/Button use
leading-none and bare text links carry no vertical padding.

- shared Dialog close button: p-1 with right-3/top-3 so the 24px hit box
  keeps the icon where it was
- tour card: Skip all tours (13 routes), All boards on standings cards (6)
- detail pages: 27 Back links, journals All journals, wiki category
  links, voiceover card titles, factions batch link
- dashboard: 7 View all / View full record links
- account preferences: mute rows min-h-6, radio and tours labels, plus
  contacts filter labels and the campaigns show-completed label
- ribbon studio: mirror label and stripe/module remove buttons
- helpdesk ticket titles, radio tick-sound label
2026-10-12 22:17:51 -04:00
61535aba58 test(audit): correct mobile viewport emulation and grid heuristic
The harness was measuring against a viewport Chromium had already widened:
with isMobile true it grows the layout viewport to fit overflowing content,
so scrollWidth > innerWidth could never fire and real overflows were masked.
hasTouch alone gives (pointer: coarse) while keeping the 390px viewport
fixed, which is what surfaced the remaining resources overflow.

- grid class: flag only grids that overflow a non-scrolling container;
  drop the narrow-track rule (it flagged intentional icon columns) and
  skip min-w-max boards, which scroll by design
- structures detail now resolves from game-structures (the page's
  collection), so the previous phantom 404 is gone
- refreshed baseline: overflow, grid and hoverOnly all at zero
2026-10-12 20:17:27 -04:00
55f6598569 fix(mobile): resolve horizontal overflow and touch-only affordances
Mobile audit (390x844) found overflow on 6 routes; all now clean.

- Tabs: TabsList is inline-flex and widened the page when several tabs
  were present (roster doc 639px, helpdesk 510px). It now scrolls
  (max-w-full + overflow-x-auto); TabsContent gets min-w-0 and the roster
  Tabs min-w-0 so the org tree's own scroller can clip instead of the
  page growing
- Item: ItemHeader/ItemFooter had flex-basis 100% with min-width auto, so
  a long title forced the card wider instead of shrinking. Shared min-w-0
- ResourceCard: the description rendered twice (once inside ItemContent,
  once as ItemDescription) and both fought for one flex line, crushing
  the content column to 27px. Single description, full-width rows,
  truncating title (min-w-0 + items-stretch so nowrap spans can clip),
  shrink-0 badges
- awards/design: stripe row wraps instead of exceeding the viewport
- leaderboards: flappy table and the shared StandingsTable scroll
  horizontally rather than widening the page
- blackjack: explicit grid-cols-1 (minmax(0,1fr)) so the arena's implicit
  track cannot outgrow the viewport
- campaigns: card readout was revealed only on hover, unreachable on
  touch; now always visible on coarse pointers and hover-revealed only
  on pointer-fine
2026-10-12 20:17:21 -04:00
d016075481 test(audit): add mobile layout audit harness with 390x844 baseline
Pass 2 Session A: scripted Playwright audit over all frontend routes at
mobile viewport, classifying overflow, dialog, grid, hoverOnly,
hiddenMobile, tapTarget (<24px WCAG violation) and tapTargetMarginal
(24-39px review tier) findings.

- resolves dynamic route ids from REST, skips unresolvable ones instead
  of navigating literal bracket URLs
- blocks the realtime SSE stream, uses domcontentloaded, retries 5xx and
  errors once, and aborts if the dev server dies mid-run
- AUDIT_ROUTE_FILTER for targeted re-audits (writes filtered files so
  the baseline report is never clobbered)
- markdown report clusters findings into cross-route pattern groups;
  Sessions B-D fix per class and re-run this as the regression gate
- includes the initial baseline report (159 tap violations, 24 overflow
  findings on 6 routes, 4 cramped grids, 1 hover-only, 1 hidden-on-mobile)
2026-10-12 18:36:43 -04:00
25df38cdd3 fix(sidebar): match Banking and Market nav icons to their page headers
Banking used TrendingUp and Market used ShoppingBag in the sidebar while
the pages render Landmark and Store respectively; adopt the page icons
2026-10-12 16:21:05 -04:00
e987952a9b feat(awards): polish Award Automation admin view styling
- Replace hand-rolled buttons with @payloadcms/ui Button (secondary dry
  run, primary apply) since the admin bundle has no Tailwind for shadcn
- Real spacing values throughout: Payload defines no --spacing-* vars,
  so gaps used to collapse to zero; use px literals and var(--base)
- Framed panels with theme-elevation borders, uppercase table headers,
  stats strip with collapsed line boxes so small caps sit evenly inside
  the card padding
2026-10-12 15:27:12 -04:00
db9248244d feat(awards): add award automation platform
- award-rules collection: metric/operator/value threshold rules linked to
  awards, with auto-retire-lower-tiers and once-per-series flags, active
  toggle, and award-rules:* permissions
- src/lib/awards/metrics.ts: pure metric resolvers (years of service from
  dossier.enlistmentDate with account-age fallback, account age, missions
  attended, total XP) plus operator comparison, unit tested
- evaluateAwardRules() sweeper: idempotent, dry-run capable; grants land as
  profile rows with awardedBy null so the existing afterChange hook sends
  award:granted notifications; upgrades replace the lower series tier in
  place preserving the original date; emits award:rule-granted events
- award-tick payload bin for daily evaluation + admin Award Automation
  view with Evaluate now (dry run) preview and Apply grants
- seedYearsOfServiceRules.ts wires the four years-of-service ribbons into
  one advancement series and creates their rules (idempotent, dev seeded)
- migration add_award_rules_automation (table + awards event target enum)
2026-10-12 15:11:38 -04:00
8a7d79c369 feat(journals): member-authored journal entries with author-owned publishing
- New Journals collection (Chronicle group): title, Lexical body, status
  draft/published, optional in-world date and mission link; authors read,
  edit, and delete their own entries at any status while every logged-in
  user reads published ones; journals:* staff permissions bypass ownership
  and gate the admin page (registered in the permission registry)
- /journals list with compose dialog and /journals/[id] reader reusing the
  Chronicle typography; edit/delete controls for authors and staff; drafts
  carry the DraftBadge and stay invisible to everyone but their author
- Server actions create/update/delete with ownership checks, publish-time
  journal:created and journal:deleted feed events (journals added to the
  GameEventLogs target collection enum via migration)
- Sidebar entry under Chronicle, command palette destination, admin panel
  icon; excerpt extractor as a pure module (src/lib/journals/excerpt.ts)
- Access-control integration spec covers draft privacy, publish visibility,
  non-author write blocking, and staff override (5 tests)
2026-10-12 14:39:48 -04:00
3604c1d146 feat(sidebar): pin Platform section to top during reorder
- normalizeSidebarOrder moves pinned sections (Platform) to the front, so
  even hand-crafted stored orders cannot displace it; enforced server-side
  in updateSidebarOrder via the same helper
- Customize mode renders Platform statically with a pin marker instead of
  a drag grip; only the remaining sections are sortable
- Spec updated: user order preserved after the pinned head, new pinning test
2026-10-12 14:02:21 -04:00
0ca35ec251 feat(sidebar): add server-persisted section reorder with customize mode
- preferences.display.sidebarOrder json field on Users + named migration
  add_sidebar_order_preference + regenerated types
- New pure helper src/lib/sidebar/order.ts (section ids, labels, default
  order, normalizeSidebarOrder) modeled on lib/dashboard/layout.ts, with
  tests/int/sidebar-order.int.spec.ts covering fallback/dupes/missing ids
- AppSidebar renders sections from the normalized order; feature-flagged-off
  sections skip their slot and keep stored positions
- Customize mode: dnd-kit sortable grips on group headers, save-on-drop via
  new updateSidebarOrder action, Reset clears the preference, Done exits;
  hidden while the sidebar is collapsed
- updateSidebarOrder sanitizes server-side and rewrites full preferences
- Fix sibling clobbering: saveDashboardLayout now preserves sidebarOrder,
  and updatePreferences now preserves both sidebarOrder and dashboard.layout
2026-10-12 13:46:48 -04:00
8fb97fdd1c feat(dashboard): demo tactical dossier styling on hero widgets
- New shared TacticalFrame/ReadoutFooter primitives (classification strip,
  corner brackets, faint grid texture, mono readout bar) following the
  campaign-card recipe; each piece separable per widget
- ProfileSummary: full frame + service-record readout footer (XP/level/rank/assignments)
- MissionBriefing: frame + codename line, inner MissionCard kept conventional
- QuickStats: hairline-separated situation-report readout bar
- Dense widgets (events, tickets, notifications, wallet, negotiations) stay
  shadcn so the tactical surfaces stand out
2026-10-12 13:26:21 -04:00
3219142f88 feat(admin): add icons to sidebar nav and dashboard collections grid
- New shared slug-to-icon map (collection-icons.ts) covering all collections,
  globals, plugin collections, and the custom tech-tree entry, with fallbacks
- TechTreeNavClient renders a lucide icon before every nav link label
- Custom 'collections' dashboard widget replaces Payload's stock CollectionCards
  grid with an icon-bearing variant (same permission filtering, group headers,
  create shortcuts, and global lock indicators)
2026-10-12 13:20:50 -04:00
104 changed files with 171085 additions and 415 deletions

3
.gitignore vendored
View file

@ -56,3 +56,6 @@ yarn-debug.log*
yarn-error.log*
.yarn/install-state.gz
.zinc
# Transient targeted-audit output (baseline report is committed)
tests/audit/mobile-audit-filtered.*

View file

@ -1,5 +1,33 @@
# Changelog
# v0.9.0
Personal journals, automatic awards and a dashboard you can rearrange arrive together, and every dashboard widget now wears the "tactical dossier" look.
### Features
- **Journals.** You can now write your own journal entries and publish them yourself. Compose from the Chronicle section, keep an entry private as a draft, then publish it for the unit to read. An entry stays yours to edit or delete, and publishing one posts it to the event log.
- **Automatic awards.** Awards can now be granted automatically by rule, and each grant is announced in the event log.
- **Customizable dashboard and sidebar.** You can now arrange the dashboard yourself: move a widget between the main area and the sidebar, widen one to full width, and drag the sidebar sections into the order you want. Your layout is saved to your account.
### Improvements
- **Tactical dashboard.** Every dashboard widget now uses the "tactical dossier" styling: a classification strip, corner brackets, squared corners and a faint grid texture. Service Summary, Mission Briefing and Situation Report already looked that way; the rest now match.
- **Mobile layout pass.** Every page was audited and repaired at phone size. Pages no longer scroll sideways, layouts stay inside the screen, hover-only controls are reachable by touch, and small controls meet a 24px tap-target floor.
- **Nav icons.** The Banking and Market sidebar icons now match the headers on their pages.
### Fixes
- The mission code name appeared twice in the "Operations // Last Mission" widget; it now appears once, on the mission card.
- A markup mismatch in the wallet and account views could make the currency emblem render inconsistently on the first load; it now renders inline.
- Various bug fixes and improvements.
---
# v0.8.14
The Discord bot now shows a live activity status on its profile.

View file

@ -1,6 +1,6 @@
{
"name": "polaris-task-force",
"version": "0.8.14",
"version": "0.9.0",
"description": "Web app for the Arma 3 unit Polaris Task Force. Uses Next.js for client- and server-side rendering, with a Postgres database and some other neat libraries.",
"license": "MIT",
"type": "module",

View file

@ -222,6 +222,16 @@ export async function updatePreferences(input: {
(MUTEABLE_NOTIFICATION_VALUES as readonly string[]).includes(t),
);
// Read the stored user first so preference groups this form does not own
// (sidebar order, dashboard layout) survive the full-preferences write.
const fullUser = await payload.findByID({
collection: "users",
id: userId,
depth: 0,
overrideAccess: true,
});
const stored = fullUser.preferences ?? {};
await payload.update({
collection: "users",
id: userId,
@ -234,11 +244,15 @@ export async function updatePreferences(input: {
showBackgroundTexture: input.showBackgroundTexture,
leadOrActual: input.leadOrActual,
xpDisplayMini: input.xpDisplayMini,
sidebarOrder: stored.display?.sidebarOrder ?? null,
},
discord: {
enabled: input.discordEnabled,
mutedTypes: discordMutedTypes,
},
dashboard: {
layout: stored.dashboard?.layout ?? null,
},
},
},
overrideAccess: true,

View file

@ -4,6 +4,7 @@ import config from "@payload-config";
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
import { getPayload } from "payload";
import { normalizeDashboardLayout } from "@/lib/dashboard/layout";
import { normalizeSidebarOrder } from "@/lib/sidebar/order";
export interface ActionResult<T = undefined> {
success: boolean;
@ -60,6 +61,7 @@ export async function saveDashboardLayout(
showBackgroundTexture: preferences.display?.showBackgroundTexture ?? true,
leadOrActual: preferences.display?.leadOrActual ?? "lead",
xpDisplayMini: preferences.display?.xpDisplayMini ?? false,
sidebarOrder: preferences.display?.sidebarOrder ?? null,
},
discord: {
enabled: preferences.discord?.enabled ?? false,
@ -80,3 +82,62 @@ export async function saveDashboardLayout(
return { success: false, error: message };
}
}
/**
* Persists the sidebar section order. Pass `null` to reset back to the
* default order (clears the stored preference). Like saveDashboardLayout,
* the full preferences object is rewritten so sibling groups survive, and
* the order itself is sanitized server-side.
*/
export async function updateSidebarOrder(order: unknown): Promise<ActionResult<boolean>> {
try {
const { payload, user } = await authenticate();
const userId = user.id as number;
const normalized = order === null || order === undefined ? null : normalizeSidebarOrder(order);
const fullUser = await payload.findByID({
collection: "users",
id: userId,
depth: 0,
overrideAccess: true,
});
const preferences = fullUser.preferences ?? {};
await payload.update({
collection: "users",
id: userId,
data: {
preferences: {
notifications: {
mutedAll: preferences.notifications?.mutedAll ?? false,
mutedTypes: preferences.notifications?.mutedTypes ?? [],
},
display: {
showCallsign: preferences.display?.showCallsign ?? false,
showVersionOverlay: preferences.display?.showVersionOverlay ?? true,
showBackgroundTexture: preferences.display?.showBackgroundTexture ?? true,
leadOrActual: preferences.display?.leadOrActual ?? "lead",
xpDisplayMini: preferences.display?.xpDisplayMini ?? false,
sidebarOrder: normalized,
},
discord: {
enabled: preferences.discord?.enabled ?? false,
mutedTypes: preferences.discord?.mutedTypes ?? [],
},
dashboard: {
layout: preferences.dashboard?.layout ?? null,
},
},
},
overrideAccess: true,
});
return { success: true, data: true };
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
if (message === "Unauthorized") {
return { success: false, error: "You must be logged in." };
}
return { success: false, error: message };
}
}

View file

@ -68,7 +68,7 @@ export default async function TicketPage({ params }: TicketPageProps) {
<div className="flex flex-col gap-3">
<Link
href="/helpdesk"
className="flex w-fit items-center gap-1 text-sm text-muted-foreground transition-colors hover:text-primary"
className="flex w-fit items-center gap-1 py-1 text-sm text-muted-foreground transition-colors hover:text-primary"
>
<ArrowLeftIcon className="size-3" />
Helpdesk

View file

@ -144,7 +144,7 @@ export default async function CampaignDetailPage({ params }: CampaignDetailPageP
<div className="absolute top-0 left-0 px-5 pt-5 pb-3 z-10">
<Link
href="/intelligence/campaigns"
className="flex w-fit items-center gap-1 text-sm text-muted-foreground transition-colors hover:text-primary"
className="flex w-fit items-center gap-1 py-1 text-sm text-muted-foreground transition-colors hover:text-primary"
>
<ArrowLeftIcon className="size-3" />
Back to Campaigns
@ -335,7 +335,7 @@ export default async function CampaignDetailPage({ params }: CampaignDetailPageP
</div>
<Link
href="/intelligence/factions"
className="text-xs text-muted-foreground hover:text-primary transition-colors"
className="py-1 text-xs text-muted-foreground hover:text-primary transition-colors"
>
View all
</Link>

View file

@ -164,7 +164,7 @@ export default async function FactionDetailPage({ params }: FactionDetailPagePro
<div className="absolute top-0 left-0 px-5 pt-5 pb-3 z-10">
<Link
href="/intelligence/factions"
className="flex w-fit items-center gap-1 text-sm text-muted-foreground transition-colors hover:text-primary"
className="flex w-fit items-center gap-1 py-1 text-sm text-muted-foreground transition-colors hover:text-primary"
>
<ArrowLeftIcon className="size-3" />
Back to Factions
@ -262,7 +262,7 @@ export default async function FactionDetailPage({ params }: FactionDetailPagePro
<div className="flex items-center justify-between gap-2">
<Link
href={`/intelligence/factions/${target.id}`}
className="flex items-center gap-2 text-sm font-medium hover:text-primary transition-colors"
className="flex items-center gap-2 py-1 text-sm font-medium hover:text-primary transition-colors"
>
<ShieldIcon className="size-4 text-muted-foreground" />
<span>{target.name}</span>
@ -357,7 +357,7 @@ export default async function FactionDetailPage({ params }: FactionDetailPagePro
</div>
<Link
href={`/logistics/banking/${bankAccount.id}`}
className="text-xs text-muted-foreground hover:text-primary transition-colors"
className="py-1 text-xs text-muted-foreground hover:text-primary transition-colors"
>
View
</Link>

View file

@ -335,7 +335,7 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro
<div className="absolute top-0 left-0 z-20 px-5 pt-5 pb-3">
<Link
href="/intelligence/missions"
className="flex w-fit items-center gap-1 text-sm text-muted-foreground transition-colors hover:text-primary"
className="flex w-fit items-center gap-1 py-1 text-sm text-muted-foreground transition-colors hover:text-primary"
>
<ArrowLeftIcon className="size-3" />
Back to Missions
@ -616,7 +616,7 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro
</div>
<Link
href={`/intelligence/campaigns/${campaign.id}`}
className="text-xs text-muted-foreground hover:text-primary transition-colors"
className="py-1 text-xs text-muted-foreground hover:text-primary transition-colors"
>
View
</Link>

View file

@ -0,0 +1,146 @@
import config from "@payload-config";
import { getPayload } from "payload";
import { headers as nextHeaders } from "next/headers";
import Link from "next/link";
import { notFound } from "next/navigation";
import { RichText } from "@payloadcms/richtext-lexical/react";
import { ArrowLeftIcon } from "lucide-react";
import type { Journal, Mission, User } from "@/payload-types";
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
import { hasPermission } from "@/utils/access-control/hasPermission";
import { cn } from "@/lib/utils";
import { BEAT_BODY_CLASSES } from "@/lib/story/richtextClasses";
import { DraftBadge } from "@/components/frontend/story/DraftBadge";
import { JournalDetailControls } from "@/components/frontend/journals/JournalDetailControls";
import type { JournalDraft, MissionOption } from "@/components/frontend/journals/JournalFormDialog";
export const metadata = {
title: "Journal Entry",
};
const DATE_FORMAT = new Intl.DateTimeFormat("en-US", {
year: "numeric",
month: "long",
day: "numeric",
});
function authorName(author: number | User): string {
if (typeof author === "number") return "Unknown operator";
return author.displayName || author.username || "Unknown operator";
}
export default async function JournalDetailPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
const journalId = Number(id);
if (!Number.isInteger(journalId) || journalId <= 0) notFound();
const payloadConfig = await config;
const payload = await getPayload({ config: payloadConfig });
const headers = await nextHeaders();
const { user } = await payload.auth({ headers, canSetHeaders: false });
if (!isPayloadUser(user)) return null;
// Read access is enforced by the collection: drafts of other authors throw
// here and fall through to notFound().
let journal: Journal | null = null;
try {
journal = (await payload.findByID({
collection: "journals",
id: journalId,
depth: 1,
overrideAccess: false,
user,
})) as Journal;
} catch {
journal = null;
}
if (!journal) notFound();
const authorId =
typeof journal.author === "number" ? journal.author : journal.author?.id ?? null;
const isAuthor = authorId !== null && authorId === user.id;
const [canUpdate, canDelete] = await Promise.all([
hasPermission(payload, user, "journals:update"),
hasPermission(payload, user, "journals:delete"),
]);
const canEdit = canUpdate || isAuthor;
const canDeleteEntry = canDelete || isAuthor;
const mission =
journal.mission && typeof journal.mission !== "number" ? (journal.mission as Mission) : null;
const dateSource = journal.occurredAt ?? journal.createdAt;
const isDraft = journal.status !== "published";
const missionsResult = await payload.find({
collection: "missions",
limit: 200,
depth: 0,
sort: "-id",
select: { name: true, codeName: true },
overrideAccess: false,
user,
});
const missionOptions: MissionOption[] = (missionsResult.docs as Mission[]).map((m) => ({
id: m.id,
label: m.codeName ? `${m.codeName} · ${m.name}` : m.name,
}));
const draft: JournalDraft = {
id: journal.id,
title: journal.title,
status: journal.status,
occurredAt: journal.occurredAt ? journal.occurredAt.slice(0, 10) : "",
missionId: mission?.id ?? null,
body: JSON.parse(JSON.stringify(journal.body)) as Record<string, unknown>,
};
return (
<div className="mx-auto max-w-3xl px-4 py-10">
<Link
href="/journals"
className="inline-flex items-center gap-1.5 py-1 text-sm text-muted-foreground transition-colors hover:text-foreground"
>
<ArrowLeftIcon className="size-4" />
All journals
</Link>
<header className="mt-4 flex flex-wrap items-start justify-between gap-4">
<div className="min-w-0">
<div className="flex items-center gap-2">
{isDraft && <DraftBadge />}
{mission && (
<span className="rounded border border-border px-2 py-0.5 text-xs text-muted-foreground">
{mission.codeName ? `${mission.codeName} · ${mission.name}` : mission.name}
</span>
)}
</div>
<h1 className="mt-2 font-serif text-3xl font-bold leading-tight">{journal.title}</h1>
<div className="mt-2 flex flex-wrap items-center gap-3 text-xs text-muted-foreground">
<span>{authorName(journal.author)}</span>
{dateSource && (
<>
<span className="text-border">|</span>
<span>{DATE_FORMAT.format(new Date(dateSource))}</span>
</>
)}
</div>
</div>
<JournalDetailControls
draft={draft}
missions={missionOptions}
canEdit={canEdit}
canDelete={canDeleteEntry}
/>
</header>
<article className={cn("mt-8", BEAT_BODY_CLASSES)}>
<RichText data={journal.body} />
</article>
</div>
);
}

View file

@ -0,0 +1,186 @@
"use server";
import config from "@payload-config";
import { getPayload } from "payload";
import { revalidatePath } from "next/cache";
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
import { hasPermission } from "@/utils/access-control/hasPermission";
import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
import type { Journal } from "@/payload-types";
export interface ActionResult<T = undefined> {
success: boolean;
error?: string;
data?: T;
}
async function authenticate() {
const payloadConfig = await config;
const payload = await getPayload({ config: payloadConfig });
const { headers } = await import("next/headers");
const hdrs = await headers();
const { user } = await payload.auth({ headers: hdrs, canSetHeaders: false });
if (!isPayloadUser(user)) {
throw new Error("Unauthorized");
}
return { payload, user };
}
export interface JournalInput {
title: string;
body: unknown;
status: "draft" | "published";
occurredAt?: string | null;
mission?: number | null;
}
function validate(input: JournalInput): string | null {
if (!input.title || input.title.trim().length === 0) return "Title is required.";
if (input.title.trim().length > 200) return "Title must be 200 characters or fewer.";
if (input.status !== "draft" && input.status !== "published") return "Invalid status.";
const root = (input.body as { root?: { children?: unknown[] } } | null)?.root;
if (!root || !Array.isArray(root.children) || root.children.length === 0) {
return "Entry body is required.";
}
return null;
}
const toNullableId = (value: number | null | undefined): number | null =>
typeof value === "number" ? value : null;
export async function createJournal(input: JournalInput): Promise<ActionResult<number>> {
try {
const { payload, user } = await authenticate();
const error = validate(input);
if (error) return { success: false, error };
const doc = await payload.create({
collection: "journals",
data: {
title: input.title.trim(),
author: user.id,
status: input.status,
occurredAt: input.occurredAt ?? null,
mission: toNullableId(input.mission),
body: input.body as Journal["body"],
},
overrideAccess: true,
depth: 0,
});
if (input.status === "published") {
const who = user.displayName || user.username || "Someone";
await emitGameEvent(payload, {
type: EventTypes.JournalCreated,
message: `${who} published a journal entry: "${doc.title}"`,
actor: user.id,
targetCollection: "journals",
targetId: doc.id,
});
}
revalidatePath("/journals");
return { success: true, data: doc.id };
} catch (e) {
const message = e instanceof Error ? e.message : "Unknown error";
return { success: false, error: message === "Unauthorized" ? "You must be logged in." : message };
}
}
/**
* Authors edit their own entries; journals:update staff may edit any entry.
* Publishing (draft -> published) emits the journal:created feed event so
* drafts stay silent until their author publishes them.
*/
export async function updateJournal(
id: number,
input: JournalInput,
): Promise<ActionResult<number>> {
try {
const { payload, user } = await authenticate();
const error = validate(input);
if (error) return { success: false, error };
const existing = await payload.findByID({
collection: "journals",
id,
depth: 0,
overrideAccess: true,
});
const authorId = typeof existing.author === "number" ? existing.author : existing.author?.id;
const isStaff = await hasPermission(payload, user, "journals:update");
if (!isStaff && authorId !== user.id) {
return { success: false, error: "You can only edit your own journal entries." };
}
await payload.update({
collection: "journals",
id,
data: {
title: input.title.trim(),
status: input.status,
occurredAt: input.occurredAt ?? null,
mission: toNullableId(input.mission),
body: input.body as Journal["body"],
},
overrideAccess: true,
depth: 0,
});
if (existing.status === "draft" && input.status === "published") {
const who = user.displayName || user.username || "Someone";
await emitGameEvent(payload, {
type: EventTypes.JournalCreated,
message: `${who} published a journal entry: "${input.title.trim()}"`,
actor: user.id,
targetCollection: "journals",
targetId: id,
});
}
revalidatePath("/journals");
revalidatePath(`/journals/${id}`);
return { success: true, data: id };
} catch (e) {
const message = e instanceof Error ? e.message : "Unknown error";
return { success: false, error: message === "Unauthorized" ? "You must be logged in." : message };
}
}
export async function deleteJournal(id: number): Promise<ActionResult> {
try {
const { payload, user } = await authenticate();
const existing = await payload.findByID({
collection: "journals",
id,
depth: 0,
overrideAccess: true,
});
const authorId = typeof existing.author === "number" ? existing.author : existing.author?.id;
const isStaff = await hasPermission(payload, user, "journals:delete");
if (!isStaff && authorId !== user.id) {
return { success: false, error: "You can only delete your own journal entries." };
}
await payload.delete({ collection: "journals", id, overrideAccess: true });
const who = user.displayName || user.username || "Someone";
await emitGameEvent(payload, {
type: EventTypes.JournalDeleted,
message: `${who} removed the journal entry "${existing.title}"`,
actor: user.id,
targetCollection: "journals",
targetId: id,
});
revalidatePath("/journals");
return { success: true };
} catch (e) {
const message = e instanceof Error ? e.message : "Unknown error";
return { success: false, error: message === "Unauthorized" ? "You must be logged in." : message };
}
}

View file

@ -0,0 +1,87 @@
import config from "@payload-config";
import { getPayload } from "payload";
import { headers as nextHeaders } from "next/headers";
import type { Journal, Mission, User } from "@/payload-types";
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
import { extractExcerpt } from "@/lib/journals/excerpt";
import { JournalsList, type JournalCard } from "@/components/frontend/journals/JournalsList";
import type { MissionOption } from "@/components/frontend/journals/JournalFormDialog";
export const metadata = {
title: "Journals",
};
const DATE_FORMAT = new Intl.DateTimeFormat("en-US", {
year: "numeric",
month: "long",
day: "numeric",
});
function missionLabel(mission: Mission): string {
return mission.codeName ? `${mission.codeName} · ${mission.name}` : mission.name;
}
function authorName(author: number | User): string {
if (typeof author === "number") return "Unknown operator";
return author.displayName || author.username || "Unknown operator";
}
export default async function JournalsPage() {
const payloadConfig = await config;
const payload = await getPayload({ config: payloadConfig });
const headers = await nextHeaders();
const { user } = await payload.auth({ headers, canSetHeaders: false });
if (!isPayloadUser(user)) return null;
// The collection's read access already limits non-staff to published docs
// plus their own drafts; the explicit filter keeps authors' drafts first-
// class in their list without needing a staff permission.
const journalsResult = await payload.find({
collection: "journals",
where: {
or: [{ status: { equals: "published" } }, { author: { equals: user.id } }],
},
sort: "-createdAt",
limit: 100,
depth: 1,
overrideAccess: false,
user,
});
const missionsResult = await payload.find({
collection: "missions",
limit: 200,
depth: 0,
sort: "-id",
select: { name: true, codeName: true },
overrideAccess: false,
user,
});
const cards: JournalCard[] = (journalsResult.docs as Journal[]).map((journal) => {
const mission =
journal.mission && typeof journal.mission !== "number" ? (journal.mission as Mission) : null;
const dateSource = journal.occurredAt ?? journal.createdAt;
return {
id: journal.id,
title: journal.title,
status: journal.status,
authorName: authorName(journal.author),
dateLabel: dateSource ? DATE_FORMAT.format(new Date(dateSource)) : null,
missionLabel: mission ? missionLabel(mission) : null,
excerpt: extractExcerpt(journal.body),
};
});
const missionOptions: MissionOption[] = (missionsResult.docs as Mission[]).map((mission) => ({
id: mission.id,
label: missionLabel(mission),
}));
return (
<div className="mx-auto max-w-6xl px-4 py-10">
<JournalsList journals={cards} missions={missionOptions} />
</div>
);
}

View file

@ -72,7 +72,7 @@ export default async function GameVehicleDetailPage({ params }: GameVehicleDetai
<div className="p-5 flex flex-col gap-6 max-w-7xl">
<Link
href="/logistics/game-vehicles"
className="text-sm text-muted-foreground hover:text-primary transition-colors flex items-center gap-1 w-fit"
className="py-1 text-sm text-muted-foreground hover:text-primary transition-colors flex items-center gap-1 w-fit"
>
<ArrowLeftIcon className="size-3" />
Back to Vehicles

View file

@ -109,7 +109,7 @@ export default async function ResourceDetailPage({ params }: ResourceDetailPageP
<div className="p-5 flex flex-col gap-6 max-w-7xl">
<Link
href="/logistics/resources"
className="text-sm text-muted-foreground hover:text-primary transition-colors flex items-center gap-1 w-fit"
className="py-1 text-sm text-muted-foreground hover:text-primary transition-colors flex items-center gap-1 w-fit"
>
<ArrowLeftIcon className="size-3" />
Back to Resources

View file

@ -98,7 +98,7 @@ export default async function ShipmentDetailPage({ params }: ShipmentDetailPageP
<div className="p-5 flex flex-col gap-6 max-w-7xl">
<Link
href="/logistics/shipments"
className="text-sm text-muted-foreground hover:text-primary transition-colors flex items-center gap-1 w-fit"
className="py-1 text-sm text-muted-foreground hover:text-primary transition-colors flex items-center gap-1 w-fit"
>
<ArrowLeftIcon className="size-3" />
Back to Shipments

View file

@ -340,7 +340,7 @@ export default async function StructureDetailPage({ params }: StructureDetailPag
<Link
href="/logistics"
className="relative z-10 text-sm text-muted-foreground hover:text-primary transition-colors flex items-center gap-1 w-fit"
className="relative z-10 py-1 text-sm text-muted-foreground hover:text-primary transition-colors flex items-center gap-1 w-fit"
>
<ArrowLeftIcon className="size-3" />
Back to Structures

View file

@ -88,7 +88,7 @@ export default async function VehicleDetailPage({ params }: VehicleDetailPagePro
<div className="p-5 flex flex-col gap-6 max-w-7xl">
<Link
href="/logistics/vehicles"
className="text-sm text-muted-foreground hover:text-primary transition-colors flex items-center gap-1 w-fit"
className="py-1 text-sm text-muted-foreground hover:text-primary transition-colors flex items-center gap-1 w-fit"
>
<ArrowLeftIcon className="size-3" />
Back to Vehicles

View file

@ -469,7 +469,7 @@ export default async function ProfilePage({ params }: ProfilePageProps) {
<div className="p-5 flex flex-col gap-6 max-w-7xl">
<Link
href="/"
className="text-sm text-muted-foreground hover:text-primary transition-colors flex items-center gap-1 w-fit"
className="py-1 text-sm text-muted-foreground hover:text-primary transition-colors flex items-center gap-1 w-fit"
>
<ArrowLeftIcon className="size-3" />
Back

View file

@ -123,7 +123,7 @@ export default async function SurveyDetailPage({
<div className="flex flex-col gap-3">
<Link
href="/surveys"
className="flex w-fit items-center gap-1 text-sm text-muted-foreground transition-colors hover:text-primary"
className="flex w-fit items-center gap-1 py-1 text-sm text-muted-foreground transition-colors hover:text-primary"
>
<ArrowLeftIcon className="size-3" />
Surveys

View file

@ -43,7 +43,7 @@ export default async function VoiceoverScriptPage({
<div className="flex min-w-0 flex-col gap-6 p-5">
<Link
href="/voiceover"
className="flex w-fit items-center gap-1 text-sm text-muted-foreground transition-colors hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
className="flex w-fit items-center gap-1 py-1 text-sm text-muted-foreground transition-colors hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<ArrowLeftIcon className="size-3" />
Voiceover scripts

View file

@ -111,7 +111,7 @@ function ScriptCard({ script }: { readonly script: VoiceoverScriptView }) {
{isRecordable || isDraft ? (
<Link
href={`/voiceover/${script.id}`}
className="rounded-sm outline-none transition-colors hover:text-primary focus-visible:ring-2 focus-visible:ring-ring"
className="inline-block rounded-sm py-1 outline-none transition-colors hover:text-primary focus-visible:ring-2 focus-visible:ring-ring"
>
{script.title}
</Link>

View file

@ -61,7 +61,7 @@ export default async function EditWikiPage({
<div className="flex flex-col gap-6 p-5">
<Link
href={`/wiki/${page.slug}`}
className="flex w-fit items-center gap-1 text-sm text-muted-foreground transition-colors hover:text-primary"
className="flex w-fit items-center gap-1 py-1 text-sm text-muted-foreground transition-colors hover:text-primary"
>
<ArrowLeftIcon className="size-3" />
Back to page
@ -81,7 +81,7 @@ export default async function EditWikiPage({
<div className="flex flex-col gap-6 p-5">
<Link
href={`/wiki/${page.slug}`}
className="flex w-fit items-center gap-1 text-sm text-muted-foreground transition-colors hover:text-primary"
className="flex w-fit items-center gap-1 py-1 text-sm text-muted-foreground transition-colors hover:text-primary"
>
<ArrowLeftIcon className="size-3" />
Back to page
@ -128,7 +128,7 @@ export default async function EditWikiPage({
<div className="flex flex-col gap-3">
<Link
href={`/wiki/${page.slug}`}
className="flex w-fit items-center gap-1 text-sm text-muted-foreground transition-colors hover:text-primary"
className="flex w-fit items-center gap-1 py-1 text-sm text-muted-foreground transition-colors hover:text-primary"
>
<ArrowLeftIcon className="size-3" />
Back to page

View file

@ -66,7 +66,7 @@ export default async function WikiHistoryPage({
<div className="flex flex-col gap-6 p-5">
<Link
href="/wiki"
className="flex w-fit items-center gap-1 text-sm text-muted-foreground transition-colors hover:text-primary"
className="flex w-fit items-center gap-1 py-1 text-sm text-muted-foreground transition-colors hover:text-primary"
>
<ArrowLeftIcon className="size-3" />
Wiki
@ -103,7 +103,7 @@ export default async function WikiHistoryPage({
<div className="flex flex-col gap-3">
<Link
href={`/wiki/${page.slug}`}
className="flex w-fit items-center gap-1 text-sm text-muted-foreground transition-colors hover:text-primary"
className="flex w-fit items-center gap-1 py-1 text-sm text-muted-foreground transition-colors hover:text-primary"
>
<ArrowLeftIcon className="size-3" />
Back to page

View file

@ -83,7 +83,7 @@ export default async function WikiDetailPage({
<div className="flex flex-col gap-6 p-5">
<Link
href="/wiki"
className="flex w-fit items-center gap-1 text-sm text-muted-foreground transition-colors hover:text-primary"
className="flex w-fit items-center gap-1 py-1 text-sm text-muted-foreground transition-colors hover:text-primary"
>
<ArrowLeftIcon className="size-3" />
Wiki
@ -124,7 +124,7 @@ export default async function WikiDetailPage({
<div className="flex flex-col gap-6 p-5">
<Link
href="/wiki"
className="flex w-fit items-center gap-1 text-sm text-muted-foreground transition-colors hover:text-primary"
className="flex w-fit items-center gap-1 py-1 text-sm text-muted-foreground transition-colors hover:text-primary"
>
<ArrowLeftIcon className="size-3" />
Wiki
@ -158,7 +158,7 @@ export default async function WikiDetailPage({
<div className="flex flex-col gap-3">
<Link
href="/wiki"
className="flex w-fit items-center gap-1 text-sm text-muted-foreground transition-colors hover:text-primary"
className="flex w-fit items-center gap-1 py-1 text-sm text-muted-foreground transition-colors hover:text-primary"
>
<ArrowLeftIcon className="size-3" />
Wiki
@ -201,7 +201,7 @@ export default async function WikiDetailPage({
<div className="flex flex-col gap-3">
<Link
href="/wiki"
className="flex w-fit items-center gap-1 text-sm text-muted-foreground transition-colors hover:text-primary"
className="flex w-fit items-center gap-1 py-1 text-sm text-muted-foreground transition-colors hover:text-primary"
>
<ArrowLeftIcon className="size-3" />
Wiki

View file

@ -45,7 +45,7 @@ export default async function WikiCategoryPage({
<div className="flex flex-col gap-3">
<Link
href="/wiki"
className="flex w-fit items-center gap-1 text-sm text-muted-foreground transition-colors hover:text-primary"
className="flex w-fit items-center gap-1 py-1 text-sm text-muted-foreground transition-colors hover:text-primary"
>
<ArrowLeftIcon className="size-3" />
Wiki

View file

@ -69,7 +69,7 @@ export default async function NewWikiPage({
<div className="flex flex-col gap-3">
<Link
href="/wiki"
className="flex w-fit items-center gap-1 text-sm text-muted-foreground transition-colors hover:text-primary"
className="flex w-fit items-center gap-1 py-1 text-sm text-muted-foreground transition-colors hover:text-primary"
>
<ArrowLeftIcon className="size-3" />
Wiki

View file

@ -30,6 +30,7 @@ import { default as default_513af5ed43d616d133e530d8c94232f8 } from '@/component
import { default as default_d9c22b951ac6762f436db59b889da382 } from '@/components/admin/awards/CommendationColorField'
import { default as default_c3ea68702b5e5f8f2f98055e01c43c8d } from '@/components/admin/awards/RibbonDesigner'
import { default as default_2f2033acccb3be245f1a85f7b4271dac } from '@/components/admin/awards/MedalDesigner'
import { default as default_701da9bef3b3cc3d8567adf41fa08aa3 } from '@/components/admin/awards/AwardAutomationView'
import { default as default_4b88a624e9f0b376cffcc6814d459adb } from '@/components/admin/assignments/AssignmentMembersField'
import { default as default_0edde40a6ccd30c893b1227360f69360 } from '@/components/static/TickDurationDescription'
import { default as default_2d468cc5cf0b647ffca3201592c20825 } from '@/components/static/WarningMessage'
@ -47,6 +48,7 @@ import { default as default_05548cb43495e62d80b80ec4d9f0f7e9 } from '@/component
import { default as default_459d6b6f5ead73c736013da63a5ace3f } from '@/components/static/GoToFrontendLink'
import { InstructionsProvider as InstructionsProvider_4490b89d4413c1ffaecdacfe72efaf73 } from '@ai-stack/payloadcms/client'
import { default as default_2b34d0df0cf91f4442ca2cd62ae7cd94 } from '@/components/admin/tech-tree/TechTreeView'
import { default as default_f3a799acf91e60a0d7a8ec121a8f5690 } from '@/components/admin/dashboard/CollectionCards'
import { CollectionCards as CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } from '@payloadcms/next/rsc'
/** @type import('payload').ImportMap */
@ -83,6 +85,7 @@ export const importMap = {
"@/components/admin/awards/CommendationColorField#default": default_d9c22b951ac6762f436db59b889da382,
"@/components/admin/awards/RibbonDesigner#default": default_c3ea68702b5e5f8f2f98055e01c43c8d,
"@/components/admin/awards/MedalDesigner#default": default_2f2033acccb3be245f1a85f7b4271dac,
"@/components/admin/awards/AwardAutomationView#default": default_701da9bef3b3cc3d8567adf41fa08aa3,
"@/components/admin/assignments/AssignmentMembersField#default": default_4b88a624e9f0b376cffcc6814d459adb,
"@/components/static/TickDurationDescription#default": default_0edde40a6ccd30c893b1227360f69360,
"@/components/static/WarningMessage#default": default_2d468cc5cf0b647ffca3201592c20825,
@ -100,5 +103,6 @@ export const importMap = {
"@/components/static/GoToFrontendLink#default": default_459d6b6f5ead73c736013da63a5ace3f,
"@ai-stack/payloadcms/client#InstructionsProvider": InstructionsProvider_4490b89d4413c1ffaecdacfe72efaf73,
"@/components/admin/tech-tree/TechTreeView#default": default_2b34d0df0cf91f4442ca2cd62ae7cd94,
"@/components/admin/dashboard/CollectionCards#default": default_f3a799acf91e60a0d7a8ec121a8f5690,
"@payloadcms/next/rsc#CollectionCards": CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1
}

View file

@ -284,14 +284,33 @@ export function resolveChangelogRange(
if (!from && !to) return { found: false, versions: [], messages: [] };
const idxFrom = from ? entries.findIndex((entry) => entry.version === from) : 0;
const idxTo = to ? entries.findIndex((entry) => entry.version === to) : entries.length - 1;
if (idxFrom === -1 || idxTo === -1) {
return { found: false, versions: [], messages: [] };
const indexOf = (version: string): number =>
entries.findIndex((entry) => entry.version === version);
// The file is newest-first, so a LOWER index is a NEWER version. "from.." opens
// toward the newest (index 0); "..to" opens toward the oldest (the last index).
let start: number;
let end: number;
if (from && to) {
const a = indexOf(from);
const b = indexOf(to);
if (a === -1 || b === -1) return { found: false, versions: [], messages: [] };
start = Math.min(a, b);
end = Math.max(a, b);
} else if (from) {
// "a.." = a and everything newer, up to the newest entry.
const a = indexOf(from);
if (a === -1) return { found: false, versions: [], messages: [] };
start = 0;
end = a;
} else {
// "..b" = the oldest entry through b.
const b = indexOf(to as string);
if (b === -1) return { found: false, versions: [], messages: [] };
start = b;
end = entries.length - 1;
}
const start = Math.min(idxFrom, idxTo);
const end = Math.max(idxFrom, idxTo);
const slice = entries
.slice(start, end + 1)
.sort((a, b) => compareVersions(a.version, b.version));

View file

@ -40,6 +40,8 @@ const TARGET_COLLECTIONS = [
{ label: "Voice Scripts", value: "voice-scripts" },
{ label: "Voice Submissions", value: "voice-submissions" },
{ label: "Chronicle Entries", value: "story-beats" },
{ label: "Journals", value: "journals" },
{ label: "Awards", value: "awards" },
{ label: "Chronicle Entry States", value: "story-beat-states" },
{ label: "Custom Minefields", value: "custom-minefields" },
{ label: "Custom Minefield Scores", value: "custom-minefield-scores" },

View file

@ -0,0 +1,108 @@
import type { CollectionConfig, Where } from "payload";
import { FixedToolbarFeature, lexicalEditor } from "@payloadcms/richtext-lexical";
import { hasPermission } from "@/utils/access-control/hasPermission";
/**
* Member-authored journal entries. Authors publish their own work directly
* (no staff review): authors can read/edit/delete their own entries at any
* status; every logged-in user reads published entries; staff with
* journals:read see everything through the admin panel.
*/
export const Journals: CollectionConfig = {
slug: "journals",
labels: {
singular: "Journal Entry",
plural: "Journals",
},
admin: {
group: "Chronicle",
useAsTitle: "title",
defaultColumns: ["title", "author", "status", "occurredAt", "createdAt"],
listSearchableFields: ["title", "body"],
description:
"Member-written journals. Drafts are visible to their author and staff only; published entries are readable by any logged-in user on /journals.",
},
access: {
read: async ({ req }): Promise<boolean | Where> => {
if (!req.user) return false;
if (await hasPermission(req.payload, req.user, "journals:read")) return true;
return {
or: [{ author: { equals: req.user.id } }, { status: { equals: "published" } }],
};
},
create: ({ req }) => Boolean(req.user),
update: async ({ req }): Promise<boolean | Where> => {
if (!req.user) return false;
if (await hasPermission(req.payload, req.user, "journals:update")) return true;
return { author: { equals: req.user.id } };
},
delete: async ({ req }): Promise<boolean | Where> => {
if (!req.user) return false;
if (await hasPermission(req.payload, req.user, "journals:delete")) return true;
return { author: { equals: req.user.id } };
},
},
fields: [
{
name: "title",
type: "text",
required: true,
},
{
name: "author",
type: "relationship",
relationTo: "users",
required: true,
defaultValue: ({ user }) => user?.id,
// Ownership is not transferable by authors; only journals:update staff
// may reassign an entry (Payload silently strips the field otherwise).
access: {
update: async ({ req }) =>
Boolean(req.user) && (await hasPermission(req.payload, req.user!, "journals:update")),
},
admin: {
description: "Owning member. Authors can always edit their own entries.",
},
},
{
name: "status",
type: "select",
required: true,
defaultValue: "draft",
index: true,
options: [
{ label: "Draft", value: "draft" },
{ label: "Published", value: "published" },
],
admin: {
description: "Authors publish directly; no staff review is required.",
},
},
{
name: "occurredAt",
type: "date",
admin: {
description: "Optional in-world date shown with the entry. Does not affect list order.",
},
},
{
name: "mission",
type: "relationship",
relationTo: "missions",
admin: {
description: "Optional mission this entry relates to. Entries may stand alone.",
},
},
{
name: "body",
type: "richText",
required: true,
editor: lexicalEditor({
features: ({ defaultFeatures }) => [...defaultFeatures, FixedToolbarFeature()],
}),
admin: {
description: "Rich text body of the entry, rendered on /journals with the Lexical renderer.",
},
},
],
};

View file

@ -0,0 +1,112 @@
import type { CollectionConfig } from "payload";
import { requirePermission } from "@/utils/access-control/hasPermission";
import { AWARD_METRICS, METRIC_LABELS, METRIC_OPERATORS, OPERATOR_LABELS } from "@/lib/awards/metrics";
/**
* Declarative grant rules evaluated by the award automation sweeper
* (src/lib/awards/automation.ts). Each rule says: when a member's metric
* passes `<operator> <value>`, grant them the linked award automatically.
*/
export const AwardRules: CollectionConfig = {
slug: "award-rules",
labels: {
singular: "Award Rule",
plural: "Award Rules",
},
admin: {
group: "Users",
useAsTitle: "label",
defaultColumns: ["label", "award", "metric", "operator", "value", "active"],
description:
"Automation rules that grant awards when a member's metric crosses a threshold. Evaluated by the daily award tick and the Evaluate Now view.",
components: {
views: {
awardAutomation: {
Component: "@/components/admin/awards/AwardAutomationView",
path: "/award-automation",
exact: true,
},
},
},
},
access: {
read: requirePermission("award-rules:read"),
create: requirePermission("award-rules:create"),
update: requirePermission("award-rules:update"),
delete: requirePermission("award-rules:delete"),
},
fields: [
{
name: "label",
type: "text",
required: true,
admin: {
description:
'Short rule name shown in previews and feed events (e.g. "2 years of service").',
},
},
{
name: "award",
type: "relationship",
relationTo: "awards",
required: true,
admin: {
description: "The award granted when the rule fires.",
},
},
{
name: "metric",
type: "select",
required: true,
options: AWARD_METRICS.map((metric) => ({ label: METRIC_LABELS[metric], value: metric })),
},
{
name: "operator",
type: "select",
required: true,
defaultValue: "gte",
options: METRIC_OPERATORS.map((operator) => ({
label: OPERATOR_LABELS[operator],
value: operator,
})),
},
{
name: "value",
type: "number",
required: true,
min: 0,
admin: {
description:
"Threshold compared against the metric (years for time-based metrics, counts otherwise).",
},
},
{
name: "autoRetireLowerTiers",
type: "checkbox",
defaultValue: false,
admin: {
description:
"For awards in an advancement series: replace any lower tier the member already holds with this award, preserving their original award date.",
condition: (_, siblingData) => Boolean(siblingData?.award),
},
},
{
name: "oncePerSeries",
type: "checkbox",
defaultValue: false,
admin: {
description:
"Skip members who already hold any award in this award's advancement series (use instead of auto-retire when tiers must not stack or upgrade).",
condition: (_, siblingData) => Boolean(siblingData?.award),
},
},
{
name: "active",
type: "checkbox",
defaultValue: true,
admin: {
description: "Inactive rules are ignored by the sweeper.",
},
},
],
};

View file

@ -312,6 +312,14 @@ export const Users: CollectionConfig = {
type: "checkbox",
defaultValue: true,
},
{
name: "sidebarOrder",
label: "Sidebar section order (managed by the sidebar)",
type: "json",
admin: {
description: "Ordered sidebar section ids, saved by the sidebar customize mode",
},
},
],
},
{

View file

@ -0,0 +1,209 @@
"use client";
import * as React from "react";
import { Button } from "@payloadcms/ui";
import { runAwardEvaluation, applyAwardGrants } from "@/lib/awards/automationActions";
import type { EvaluationResult } from "@/lib/awards/automation";
const panelStyle: React.CSSProperties = {
border: "1px solid var(--theme-elevation-150)",
borderRadius: "3px",
background: "var(--theme-elevation-50)",
};
/**
* Admin view (award-rules collection): preview which members currently
* qualify under the active rules, then apply the grants. Both actions are
* idempotent; the sweeper skips members who already hold the award.
*/
export default function AwardAutomationView() {
const [result, setResult] = React.useState<EvaluationResult | null>(null);
const [busy, setBusy] = React.useState<"preview" | "apply" | null>(null);
const [error, setError] = React.useState<string | null>(null);
const runPreview = async () => {
setBusy("preview");
setError(null);
const res = await runAwardEvaluation();
setBusy(null);
if (!res.success) {
setError(res.error);
return;
}
setResult(res.result);
};
const runApply = async () => {
setBusy("apply");
setError(null);
const res = await applyAwardGrants();
setBusy(null);
if (!res.success) {
setError(res.error);
return;
}
setResult(res.result);
};
const grantCount = result ? result.plans.filter((p) => p.kind === "grant").length : 0;
const upgradeCount = result ? result.plans.filter((p) => p.kind === "upgrade").length : 0;
return (
<div
style={{
padding: "var(--base) var(--base) calc(var(--base) * 2)",
maxWidth: "72rem",
display: "flex",
flexDirection: "column",
gap: "24px",
}}
>
<header style={{ display: "flex", flexDirection: "column", gap: "8px" }}>
<h1 style={{ margin: 0 }}>Award Automation</h1>
<p style={{ margin: 0, color: "var(--theme-elevation-600)", maxWidth: "44rem" }}>
Evaluate every active award rule against all members. Preview first: nothing is written
until you apply. Applying is safe to repeat, members who already hold an award are
skipped.
</p>
</header>
<div style={{ display: "flex", gap: "12px" }}>
<Button buttonStyle="secondary" onClick={runPreview} disabled={busy !== null}>
{busy === "preview" ? "Evaluating..." : "Evaluate now (dry run)"}
</Button>
<Button
buttonStyle="primary"
onClick={runApply}
disabled={busy !== null || !result || result.plans.length === 0}
>
{busy === "apply" ? "Applying..." : "Apply grants"}
</Button>
</div>
{error && (
<p
style={{
margin: 0,
padding: "8px 12px",
color: "var(--theme-error-500)",
...panelStyle,
borderColor: "var(--theme-error-200)",
}}
>
{error}
</p>
)}
{result && (
<section style={{ display: "flex", flexDirection: "column", gap: "24px" }}>
<div
style={{
display: "flex",
flexWrap: "wrap",
gap: "var(--base)",
padding: "16px 20px",
...panelStyle,
}}
>
{[
{ label: "Mode", value: result.dryRun ? "Dry run" : "Applied" },
{ label: "Rules evaluated", value: String(result.rulesEvaluated) },
{ label: "Members checked", value: String(result.membersChecked) },
{
label: result.dryRun ? "Would grant" : "Granted",
value: String(result.dryRun ? grantCount : result.granted),
},
{
label: result.dryRun ? "Would upgrade" : "Upgraded",
value: String(result.dryRun ? upgradeCount : result.upgraded),
},
{ label: "Skipped", value: String(result.skips.length) },
].map((stat) => (
<div
key={stat.label}
style={{ display: "flex", flexDirection: "column", gap: "2px", minWidth: "7rem" }}
>
<span
style={{
fontSize: "0.625rem",
lineHeight: 1,
textTransform: "uppercase",
letterSpacing: "0.04em",
color: "var(--theme-elevation-500)",
}}
>
{stat.label}
</span>
<span style={{ fontSize: "1.25rem", lineHeight: 1.1 }}>{stat.value}</span>
</div>
))}
</div>
{result.plans.length > 0 ? (
<div style={{ overflowX: "auto", ...panelStyle }}>
<table style={{ width: "100%", borderCollapse: "collapse" }}>
<thead>
<tr style={{ borderBottom: "1px solid var(--theme-elevation-150)" }}>
{["Member", "Rule", "Award", "Metric value", "Action"].map((col) => (
<th
key={col}
style={{
textAlign: "left",
padding: "12px 16px",
fontSize: "0.625rem",
lineHeight: 1,
textTransform: "uppercase",
letterSpacing: "0.04em",
color: "var(--theme-elevation-500)",
fontWeight: 600,
}}
>
{col}
</th>
))}
</tr>
</thead>
<tbody>
{result.plans.map((plan, i) => (
<tr
key={`${plan.ruleId}-${plan.userId}-${i}`}
style={{ borderBottom: "1px solid var(--theme-elevation-100)" }}
>
{[
plan.username,
plan.ruleLabel,
plan.awardName,
plan.metricValue.toFixed(2),
plan.kind === "upgrade"
? `Upgrade (retires award #${plan.replacesAwardId})`
: "Grant",
].map((cell, j) => (
<td
key={j}
style={{ padding: "12px 16px", verticalAlign: "top" }}
>
{cell}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
) : (
<p
style={{
margin: 0,
padding: "20px",
color: "var(--theme-elevation-600)",
...panelStyle,
}}
>
No members currently qualify for anything new.
</p>
)}
</section>
)}
</div>
);
}

View file

@ -0,0 +1,288 @@
import type { LucideIcon } from "lucide-react";
import {
Activity,
Archive,
ArrowLeftRight,
AudioWaveform,
Award,
Backpack,
BadgeCheck,
Bell,
BookOpen,
BookOpenText,
Bomb,
BookmarkCheck,
Bot,
Boxes,
Brain,
Building2,
CalendarCheck,
CalendarClock,
CalendarDays,
Car,
CarFront,
FastForward,
ClipboardCheck,
ClipboardList,
Crosshair,
Cpu,
Dices,
FileAudio,
FileText,
Filter,
Flag,
Flame,
Folder,
FolderTree,
FormInput,
Gamepad2,
Gauge,
Gem,
GitCompare,
Globe,
Handshake,
HardHat,
History,
Hexagon,
Image as ImageIcon,
Inbox,
Joystick,
Kanban,
KeyRound,
Landmark,
LayoutGrid,
LayoutTemplate,
LifeBuoy,
LineChart,
ListChecks,
ListOrdered,
Map as MapIcon,
MapPin,
Medal,
Megaphone,
MessageSquareText,
Mic,
Mountain,
Network,
NotebookText,
Package,
PackageOpen,
Radio,
RadioTower,
Radar,
Receipt,
Ribbon,
Rocket,
Route,
Scale,
ScrollText,
Server,
Settings2,
ShieldCheck,
ShieldHalf,
ShoppingBag,
ShoppingCart,
SlidersHorizontal,
Sparkles,
Star,
Swords,
Tags,
Target,
Terminal,
ThumbsUp,
Ticket,
TrendingUp,
Trophy,
Truck,
UserCheck,
UserCog,
UserRound,
Users,
UsersRound,
WandSparkles,
Warehouse,
Workflow,
Zap,
} from "lucide-react";
/**
* Single source of truth for admin-panel icons, keyed by collection/global
* slug (plus the custom `tech-tree` nav entry). Consumed by the admin sidebar
* (TechTreeNavClient) and the dashboard collections grid widget so both
* surfaces always agree. New collections fall back to `fallbackCollectionIcon`
* until they are added here.
*/
export const collectionIcons: Record<string, LucideIcon> = {
// Announcements
announcements: Megaphone,
// Media
media: ImageIcon,
// Game
"game-event-logs": History,
"game-hard-resources": Gem,
"game-npcs": Bot,
"game-structures": Building2,
"game-vehicles": Car,
"labor-classifications": HardHat,
"npc-dialogues": MessageSquareText,
"npc-staffing": UserCog,
"player-flags": Flag,
"reinforcement-pools": UsersRound,
// Users
"assignment-transfers": ArrowLeftRight,
assignments: Network,
awards: Award,
"contribution-entries": Sparkles,
evaluations: ClipboardCheck,
experience: Star,
"leadership-transfers": Handshake,
profiles: UserRound,
"promotion-nominations": TrendingUp,
qualifications: BadgeCheck,
ranks: Medal,
roles: ShieldCheck,
"user-notifications": Bell,
users: Users,
// Intelligence
campaigns: Swords,
factions: ShieldHalf,
"mission-attendances": ClipboardList,
"mission-map-markers": MapPin,
"mission-role-signups": UserCheck,
missions: Crosshair,
"tech-categories": FolderTree,
technologies: Cpu,
// Logistics
assets: Boxes,
resources: Package,
shipments: Truck,
structures: Warehouse,
vehicles: CarFront,
// Banking
"bank-accounts": Landmark,
"bank-transactions": Receipt,
"ledger-entries": NotebookText,
// Locker
loadouts: Backpack,
"locker-storages": Archive,
// Market
"market-listings": ShoppingBag,
"market-negotiations": Scale,
"market-state": LineChart,
// Voiceover
"voice-scripts": FileAudio,
"voice-submissions": AudioWaveform,
// Helpdesk
"ticket-votes": ThumbsUp,
tickets: LifeBuoy,
// Wiki
"wiki-pages": BookOpen,
"wiki-revisions": GitCompare,
"wiki-templates": LayoutTemplate,
// Projects
labels: Tags,
projects: Kanban,
releases: Rocket,
sprints: FastForward,
// World
"map-roads": Route,
"map-zones": Hexagon,
maps: MapIcon,
"narrative-events": BookOpenText,
"resource-nodes": Mountain,
// Story (Chronicle)
"story-beat-states": BookmarkCheck,
"story-beats": ScrollText,
journals: NotebookText,
"award-rules": Zap,
"story-voiceovers": Mic,
// Server
"arma-commands": Terminal,
"arma-sync-events": RadioTower,
"game-servers": Server,
"mission-files": FileText,
"mod-lists": ListChecks,
"respawn-tickets": Ticket,
"supply-boxes": PackageOpen,
// Operations
"operation-effects": Zap,
"operation-events": CalendarDays,
"operation-readiness": Gauge,
"operation-reservations": CalendarCheck,
"zone-pressure": Flame,
// Minigames
achievements: Trophy,
"custom-minefield-scores": Target,
"custom-minefields": Bomb,
"custom-radio-test-scores": ListOrdered,
"custom-radio-tests": Radio,
"minigame-entries": Gamepad2,
"minigame-periods": CalendarClock,
minigames: Dices,
// Globals
"discord-presence": Activity,
"game-rules": Settings2,
"minigame-rules": SlidersHorizontal,
shims: Filter,
// Custom admin views (nav entries that are not Payload entities)
"tech-tree": Workflow,
// Plugin collections
forms: FormInput,
"form-submissions": Inbox,
"payload-mcp-api-keys": KeyRound,
"plugin-ai-instructions": WandSparkles,
};
/** Icons for the admin nav/dashboard groups, keyed by group label. */
export const groupIcons: Record<string, LucideIcon> = {
Announcements: Megaphone,
Awards: Medal,
Banking: Landmark,
Chronicle: ScrollText,
Contributions: Sparkles,
Game: Joystick,
Helpdesk: LifeBuoy,
Intelligence: Brain,
Locker: Backpack,
Logistics: Truck,
Market: ShoppingCart,
Minigames: Gamepad2,
Operations: Radar,
Projects: Kanban,
Server: Server,
Users: Users,
Voiceover: Mic,
Wiki: BookOpenText,
World: Globe,
};
export const fallbackCollectionIcon: LucideIcon = LayoutGrid;
export const fallbackGroupIcon: LucideIcon = Folder;
export function getCollectionIcon(slug: string): LucideIcon {
return collectionIcons[slug] ?? fallbackCollectionIcon;
}
export function getGroupIcon(label: string): LucideIcon {
return groupIcons[label] ?? fallbackGroupIcon;
}

View file

@ -0,0 +1,161 @@
import { Locked } from "@payloadcms/ui/elements/Locked";
import { EntityType, groupNavItems } from "@payloadcms/ui/shared";
import { getGlobalData } from "@payloadcms/ui/utilities/getGlobalData";
import { getVisibleEntities } from "@payloadcms/ui/utilities/getVisibleEntities";
import { getAccessResults } from "payload";
import { formatAdminURL } from "payload/shared";
import type { EntityToGroup } from "@payloadcms/ui/shared";
import type { ClientUser, PayloadRequest, SanitizedPermissions } from "payload";
import React from "react";
import { getCollectionIcon, getGroupIcon } from "@/components/admin/collection-icons";
/**
* Replacement for Payload's built-in `collections` dashboard widget
* (`@payloadcms/next/rsc#CollectionCards`), registered under the same slug in
* `payload.config.ts` (admin.dashboard.widgets). Payload appends its default
* widget AFTER user widgets, and the dashboard resolves widgets by first
* match, so this component takes over the grid.
*
* Behavior mirrors the stock widget: entities are filtered by read permission
* and visibility, grouped by admin group, globals show their document lock,
* and collections with create permission get a "+" shortcut. Adds lucide
* icons per entity and per group from the shared collection-icons map.
*/
type WidgetProps = {
permissions?: SanitizedPermissions;
req: PayloadRequest;
};
function asLabel(label: unknown): string {
return typeof label === "string" ? label : String(label);
}
export const PolarisCollectionCards = async ({ permissions, req }: WidgetProps) => {
if (!req?.payload?.config) {
return null;
}
const { i18n, payload, user } = req;
const { admin: adminRoute } = payload.config.routes;
// The dashboard passes resolved permissions; recompute only when a render
// path did not provide them.
const resolvedPermissions = permissions ?? ((await getAccessResults({ req })) as SanitizedPermissions);
const visibleEntities = getVisibleEntities({ req });
const globalData = await getGlobalData(req);
const collections = payload.config.collections.filter(
(collection) =>
resolvedPermissions?.collections?.[collection.slug]?.read &&
visibleEntities.collections.includes(collection.slug),
);
const globals = payload.config.globals.filter(
(global) =>
resolvedPermissions?.globals?.[global.slug]?.read &&
visibleEntities.globals.includes(global.slug),
);
const navGroups = groupNavItems(
[
...collections.map(
(collection): EntityToGroup => ({ type: EntityType.collection, entity: collection }),
),
...globals.map((global): EntityToGroup => ({ type: EntityType.global, entity: global })),
],
resolvedPermissions,
i18n,
);
return (
<div className="flex w-full flex-col gap-6 py-2">
{navGroups.map(({ entities, label }, groupIndex) => {
const GroupIcon = getGroupIcon(label);
return (
<section className="flex flex-col gap-3" key={groupIndex}>
<h2 className="m-0 flex items-center gap-2 text-sm font-semibold text-[var(--theme-text-color)]">
<GroupIcon aria-hidden className="size-4 shrink-0 opacity-60" />
{label}
</h2>
<ul className="m-0 grid list-none grid-cols-[repeat(auto-fill,minmax(220px,1fr))] gap-3 p-0">
{entities.map(({ slug, type }, entityIndex) => {
let title: string;
let href: string;
let createHREF: string | undefined;
let hasCreatePermission = false;
let isLocked = false;
let userEditing: ClientUser | null = null;
if (type === EntityType.collection) {
const collection = payload.config.collections.find((c) => c.slug === slug)!;
title = asLabel(collection.labels.plural);
href = formatAdminURL({ adminRoute, path: `/collections/${slug}` });
createHREF = formatAdminURL({ adminRoute, path: `/collections/${slug}/create` });
hasCreatePermission = Boolean(resolvedPermissions?.collections?.[slug]?.create);
} else {
const global = payload.config.globals.find((g) => g.slug === slug)!;
title = asLabel(global.label);
href = formatAdminURL({ adminRoute, path: `/globals/${slug}` });
const globalLockData = globalData.find((g) => g.slug === slug);
if (globalLockData) {
isLocked = Boolean(globalLockData.data._isLocked);
userEditing =
typeof globalLockData.data._userEditing === "object"
? (globalLockData.data._userEditing as ClientUser)
: null;
const lockDuration = globalLockData.lockDuration ?? 0;
const lastEditedAt = new Date(globalLockData.data._lastEditedAt).getTime();
if (Date.now() > lastEditedAt + lockDuration * 1000) {
isLocked = false;
userEditing = null;
}
}
}
const Icon = getCollectionIcon(slug);
const showLocked = isLocked && user?.id !== userEditing?.id;
return (
<li className="relative" key={entityIndex}>
<a
aria-label={`Show all ${title}`}
className="group flex h-full items-center gap-3 rounded-lg border border-[var(--theme-border-color)] bg-[var(--theme-input-bg)] p-4 no-underline transition-[border-color,box-shadow] hover:border-[var(--theme-success)] hover:shadow-[inset_0_0_0_1px_var(--theme-success)]"
href={href}
id={`card-${slug}`}
>
<span className="flex size-9 shrink-0 items-center justify-center rounded-md border border-[var(--theme-border-color)] bg-[var(--theme-elevation-50)] text-[var(--theme-elevation-700)]">
<Icon aria-hidden className="size-4" />
</span>
<h3 className="m-0 min-w-0 flex-1 truncate text-sm font-medium text-[var(--theme-text-color)]">
{title}
</h3>
</a>
{showLocked && userEditing ? (
<span className="absolute right-3 top-1/2 -translate-y-1/2">
<Locked user={userEditing} />
</span>
) : null}
{!showLocked && hasCreatePermission && createHREF ? (
<a
aria-label={`Create new ${title}`}
className="absolute right-3 top-1/2 z-10 flex size-7 -translate-y-1/2 items-center justify-center rounded-full border border-[var(--theme-border-color)] bg-[var(--theme-bg)] text-lg leading-none text-[var(--theme-elevation-600)] opacity-70 transition-opacity hover:opacity-100"
href={createHREF}
>
+
</a>
) : null}
</li>
);
})}
</ul>
</section>
);
})}
</div>
);
};
export default PolarisCollectionCards;

View file

@ -6,6 +6,8 @@ import { usePathname } from "next/navigation.js";
import { formatAdminURL } from "payload/shared";
import React, { Fragment } from "react";
import { getCollectionIcon } from "@/components/admin/collection-icons";
/**
* A nav entity: either a standard Payload entity (collection/global) or a
* custom view entry injected by TechTreeNav (type "custom", href given).
@ -72,9 +74,15 @@ export const TechTreeNavClient = ({ groups, navPreferences }: Props) => {
pathname === href ||
(pathname.startsWith(href) && ["/", undefined].includes(pathname[href.length]));
const Icon = getCollectionIcon(slug);
const Label = (
<Fragment>
{isActive && <div className={`${baseClass}__link-indicator`} />}
<Icon
aria-hidden
className={`me-2 size-3.5 shrink-0 ${isActive ? "opacity-100" : "opacity-60"}`}
/>
<span className={`${baseClass}__link-label`}>
{typeof entityLabel === "string" ? entityLabel : String(entityLabel)}
</span>

View file

@ -87,7 +87,7 @@ export function StripeEditor({
</button>
</div>
{stripes.map((stripe, idx) => (
<div key={idx} className="flex items-center gap-2 bg-zinc-900 rounded px-2 py-1.5">
<div key={idx} className="flex flex-wrap items-center gap-2 bg-zinc-900 rounded px-2 py-1.5">
<input
type="color"
value={stripe.color}
@ -121,7 +121,7 @@ export function StripeEditor({
<button
type="button"
onClick={() => removeStripe(idx)}
className="text-zinc-500 hover:text-red-400 text-sm cursor-pointer"
className="py-1 text-zinc-500 hover:text-red-400 text-sm cursor-pointer"
>
\u00D7
</button>
@ -206,7 +206,7 @@ export function DeviceEditor({
<button
type="button"
onClick={() => removeDevice(device.id)}
className="text-zinc-500 hover:text-red-400 text-sm cursor-pointer"
className="py-1 text-zinc-500 hover:text-red-400 text-sm cursor-pointer"
>
\u00D7
</button>

View file

@ -21,6 +21,7 @@ import {
Search,
Award,
Mic,
NotebookText,
PlaneTakeoff,
Radio,
Bomb,
@ -380,6 +381,13 @@ export const navigationCommands: NavigationCommand[] = [
href: "/story",
keywords: ["lore", "narrative", "story", "history", "beats"],
},
{
id: "nav:journals",
label: "Journals",
icon: NotebookText,
href: "/journals",
keywords: ["writing", "member stories", "after action", "memories", "diary"],
},
{
id: "nav:surveys",
label: "Surveys",

View file

@ -176,11 +176,15 @@ export function PreferencesForm({
>
<div className="flex items-center gap-2">
<RadioGroupItem id="leadOrActual-lead" value="lead" />
<Label htmlFor="leadOrActual-lead">Lead</Label>
<Label htmlFor="leadOrActual-lead" className="py-1.5">
Lead
</Label>
</div>
<div className="flex items-center gap-2">
<RadioGroupItem id="leadOrActual-actual" value="actual" />
<Label htmlFor="leadOrActual-actual">Actual</Label>
<Label htmlFor="leadOrActual-actual" className="py-1.5">
Actual
</Label>
</div>
</RadioGroup>
</div>
@ -218,7 +222,7 @@ export function PreferencesForm({
<Label
key={notificationType.value}
htmlFor={id}
className="flex items-center justify-between gap-4 text-sm font-normal"
className="flex min-h-6 items-center justify-between gap-4 text-sm font-normal"
>
<span>{notificationType.label}</span>
<Switch
@ -272,7 +276,7 @@ export function PreferencesForm({
<Label
key={notificationType.value}
htmlFor={id}
className="flex items-center justify-between gap-4 text-sm font-normal"
className="flex min-h-6 items-center justify-between gap-4 text-sm font-normal"
>
<span>Mute {notificationType.label.toLowerCase()}</span>
<Switch

View file

@ -22,7 +22,7 @@ export function ToursPreference() {
return (
<div className="flex items-center justify-between gap-4">
<div className="flex flex-col gap-0.5">
<Label htmlFor="tours-autostart" className="text-sm">
<Label htmlFor="tours-autostart" className="py-0.5 text-sm">
Auto-start page tours
</Label>
<p className="text-xs text-muted-foreground">

View file

@ -101,7 +101,9 @@ export function RibbonStudio() {
}
/>
<div className="flex flex-col gap-1">
<Label htmlFor="ribbon-mirrored">Mirror stripe pattern</Label>
<Label htmlFor="ribbon-mirrored" className="py-1.5">
Mirror stripe pattern
</Label>
<p className="text-xs text-muted-foreground">
Reflect the pattern across the center for a balanced ribbon.
</p>

View file

@ -44,7 +44,7 @@ export function AccountDetail({
<div className="flex flex-col gap-6">
<Link
href="/logistics/banking"
className="text-sm text-muted-foreground hover:text-primary transition-colors flex items-center gap-1 w-fit"
className="py-1 text-sm text-muted-foreground hover:text-primary transition-colors flex items-center gap-1 w-fit"
>
<ArrowLeftIcon className="size-3" />
Back to Banking

View file

@ -19,9 +19,12 @@ export function CurrencyAmount({
const showSymbol =
currency != null && typeof currency === "object" && isCurrencyConfig(currency) && !!currency.symbol;
return (
<div className="flex items-center gap-1.5">
// Inline-flex <span>, not <div>: callers render this inside <p>/<span>
// (wallet hero, account cards), where a block element is invalid nesting
// and triggers a hydration mismatch.
<span className="inline-flex items-center gap-1.5">
<CurrencySymbol currency={currency} />
<span>{formatAmount(value, currency, showSymbol ? { hideLabel: true } : undefined)}</span>
</div>
</span>
);
}

View file

@ -11,7 +11,31 @@ import {
Minimize,
ScrollText,
SparkleIcon,
CheckIcon,
GripVerticalIcon,
PinIcon,
RotateCcwIcon,
SlidersHorizontalIcon,
} from "lucide-react";
import {
DndContext,
KeyboardSensor,
PointerSensor,
closestCenter,
useSensor,
useSensors,
} from "@dnd-kit/core";
import type { DragEndEvent } from "@dnd-kit/core";
import {
SortableContext,
arrayMove,
sortableKeyboardCoordinates,
useSortable,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { toast } from "sonner";
import { useRouter } from "next/navigation";
import { NavCore } from "@/components/frontend/blocks/NavCore";
import { NavMinigames } from "@/components/frontend/blocks/NavMinigames";
@ -24,7 +48,9 @@ import {
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
useSidebar,
} from "@/components/ui/sidebar";
import { Button } from "@/components/ui/button";
import Image from "next/image";
import Link from "next/link";
import XPDisplay from "@/components/frontend/blocks/XPDisplay";
@ -33,8 +59,17 @@ import type { User } from "@/payload-types";
import { Progress } from "@/components/ui/progress";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { updatePreferences } from "@/app/(frontend)/account/actions";
import { updateSidebarOrder } from "@/app/(frontend)/actions";
import { sidebarData } from "@/components/frontend/blocks/sidebarData";
import type { RegistryGame } from "@/lib/minigames/registry";
import {
DEFAULT_SIDEBAR_ORDER,
PINNED_SIDEBAR_SECTION_IDS,
SIDEBAR_SECTION_LABELS,
normalizeSidebarOrder,
type SidebarSectionId,
} from "@/lib/sidebar/order";
import { cn } from "@/lib/utils";
const data = {
navMain: [
@ -97,6 +132,8 @@ export function AppSidebar({
preferences?: NonNullable<User["preferences"]>;
minigameNav?: RegistryGame[];
} & React.ComponentProps<typeof Sidebar>) {
const router = useRouter();
const { state: sidebarState } = useSidebar();
const [isMiniMode, setIsMiniMode] = React.useState<boolean>(
preferences?.display?.xpDisplayMini ?? false,
);
@ -107,6 +144,25 @@ export function AppSidebar({
setIsMiniMode(savedXpDisplayMini);
}, [savedXpDisplayMini]);
// Section order: normalized from the stored preference, kept in local state
// while dragging and persisted on every drop (same flow as the dashboard).
const savedSidebarOrder = React.useMemo(
() => normalizeSidebarOrder(preferences?.display?.sidebarOrder),
[preferences],
);
const [sectionOrder, setSectionOrder] =
React.useState<SidebarSectionId[]>(savedSidebarOrder);
const [isReordering, setIsReordering] = React.useState(false);
const [savingOrder, setSavingOrder] = React.useState(false);
React.useEffect(() => {
setSectionOrder(savedSidebarOrder);
}, [savedSidebarOrder]);
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
);
const handleToggleXPMode = React.useCallback(async () => {
try {
await updatePreferences({
@ -139,6 +195,80 @@ export function AppSidebar({
);
const filteredNavHelpdesk = helpdeskEnabled ? data.navHelpdesk : [];
const sectionNodes: Record<SidebarSectionId, React.ReactNode> = {
platform: <NavCore label={SIDEBAR_SECTION_LABELS.platform} items={data.navMain} />,
map: <NavCore label={SIDEBAR_SECTION_LABELS.map} items={data.navMap} />,
intelligence: hasIntelligence ? (
<NavCore label={SIDEBAR_SECTION_LABELS.intelligence} items={data.navIntelligence} />
) : null,
operations: <NavCore label={SIDEBAR_SECTION_LABELS.operations} items={data.navOperations} />,
infrastructure: hasLogistics ? (
<NavCore
label={SIDEBAR_SECTION_LABELS.infrastructure}
items={filteredNavLogistics}
expandDefaultOpen={hasLogistics}
/>
) : null,
chronicle: <NavCore label={SIDEBAR_SECTION_LABELS.chronicle} items={data.navStory} />,
surveys: <NavCore label={SIDEBAR_SECTION_LABELS.surveys} items={data.navSurveys} />,
helpdesk: <NavCore label={SIDEBAR_SECTION_LABELS.helpdesk} items={filteredNavHelpdesk} />,
commerce: <NavCore label={SIDEBAR_SECTION_LABELS.commerce} items={data.navCommerce} />,
personal: <NavCore label={SIDEBAR_SECTION_LABELS.personal} items={data.navPersonal} />,
};
// Feature-flagged-off sections skip their slot entirely; hidden ids keep
// their stored positions so re-enabling a flag restores the user's layout.
const visibleOrder = sectionOrder.filter((id) => sectionNodes[id] !== null);
// Pinned sections (Platform) always render first and are not draggable.
const pinnedVisible = visibleOrder.filter((id) =>
PINNED_SIDEBAR_SECTION_IDS.includes(id),
);
const sortableOrder = visibleOrder.filter(
(id) => !PINNED_SIDEBAR_SECTION_IDS.includes(id),
);
const persistOrder = React.useCallback(
async (order: SidebarSectionId[] | null) => {
setSavingOrder(true);
const result = await updateSidebarOrder(order);
setSavingOrder(false);
if (!result.success) {
toast.error(result.error ?? "Failed to save sidebar order");
}
router.refresh();
},
[router],
);
const handleDragEnd = React.useCallback(
(event: DragEndEvent) => {
const { active, over } = event;
if (!over || active.id === over.id) return;
const from = sortableOrder.indexOf(active.id as SidebarSectionId);
const to = sortableOrder.indexOf(over.id as SidebarSectionId);
if (from < 0 || to < 0) return;
const reorderedSortable = arrayMove(sortableOrder, from, to);
// Pinned sections stay on top; hidden (feature-flagged) sections are
// re-inserted at their original indices.
const merged: SidebarSectionId[] = [...pinnedVisible, ...reorderedSortable];
const hiddenIds = sectionOrder.filter((id) => !visibleOrder.includes(id));
hiddenIds.forEach((id) => {
const originalIndex = sectionOrder.indexOf(id);
merged.splice(Math.min(originalIndex, merged.length), 0, id);
});
setSectionOrder(merged);
void persistOrder(merged);
},
[persistOrder, pinnedVisible, sectionOrder, sortableOrder, visibleOrder],
);
const handleResetOrder = React.useCallback(() => {
setSectionOrder([...DEFAULT_SIDEBAR_ORDER]);
void persistOrder(null);
}, [persistOrder]);
return (
<Sidebar variant="inset" {...props}>
<SidebarHeader>
@ -167,21 +297,76 @@ export function AppSidebar({
</SidebarMenu>
</SidebarHeader>
<SidebarContent className="overflow-hidden">
<div className="flex items-center justify-end gap-1 px-3 pt-1 group-data-[collapsible=icon]:hidden">
{isReordering ? (
<>
<Button
size="sm"
variant="ghost"
className="h-7 gap-1 px-2 text-xs text-muted-foreground"
disabled={savingOrder}
onClick={handleResetOrder}
>
<RotateCcwIcon className="size-3.5" />
Reset
</Button>
<Button
size="sm"
variant="ghost"
className="h-7 gap-1 px-2 text-xs"
disabled={savingOrder}
onClick={() => setIsReordering(false)}
>
<CheckIcon className="size-3.5" />
Done
</Button>
</>
) : (
sidebarState !== "collapsed" && (
<Button
size="sm"
variant="ghost"
className="h-7 gap-1 px-2 text-xs text-muted-foreground"
onClick={() => setIsReordering(true)}
>
<SlidersHorizontalIcon className="size-3.5" />
Customize
</Button>
)
)}
</div>
<div className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto group-data-[collapsible=icon]:overflow-hidden">
<NavCore label="Platform" items={data.navMain} />
<NavCore label="Map" items={data.navMap} />
{hasIntelligence && (
<NavCore label="Intelligence" items={data.navIntelligence} />
{isReordering ? (
<>
{pinnedVisible.map((id) => (
<div key={id} className="relative">
<span
aria-hidden="true"
title="Pinned to top"
className="absolute right-1 top-0 flex size-6 items-center justify-center text-muted-foreground/60"
>
<PinIcon className="size-3.5" />
</span>
{sectionNodes[id]}
</div>
))}
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}
>
<SortableContext items={sortableOrder} strategy={verticalListSortingStrategy}>
{sortableOrder.map((id) => (
<SortableSection key={id} id={id}>
{sectionNodes[id]}
</SortableSection>
))}
</SortableContext>
</DndContext>
</>
) : (
visibleOrder.map((id) => <React.Fragment key={id}>{sectionNodes[id]}</React.Fragment>)
)}
<NavCore label="Operations" items={data.navOperations} />
{hasLogistics && (
<NavCore label="Infrastructure" items={filteredNavLogistics} expandDefaultOpen={hasLogistics} />
)}
<NavCore label="Chronicle" items={data.navStory} />
<NavCore label="Surveys" items={data.navSurveys} />
<NavCore label="Helpdesk" items={filteredNavHelpdesk} />
<NavCore label="Commerce" items={data.navCommerce} />
<NavCore label="Personal" items={data.navPersonal} />
{/*<NavProjects projects={data.projects} />*/}
</div>
<hr />
@ -247,3 +432,32 @@ export function AppSidebar({
</Sidebar>
);
}
/**
* Drag wrapper for one sidebar section in customize mode. The grip floats
* over the group label row; sections stay expanded so labels guide placement.
*/
function SortableSection({ id, children }: { id: SidebarSectionId; children: React.ReactNode }) {
const { attributes, listeners, setNodeRef, setActivatorNodeRef, transform, transition, isDragging } =
useSortable({ id });
return (
<div
ref={setNodeRef}
style={{ transform: CSS.Transform.toString(transform), transition }}
className={cn("relative", isDragging && "z-20 opacity-80")}
>
<button
ref={setActivatorNodeRef}
type="button"
aria-label={`Reorder ${SIDEBAR_SECTION_LABELS[id]} section`}
{...attributes}
{...listeners}
className="absolute right-1 top-0 z-30 flex size-6 cursor-grab touch-none items-center justify-center rounded-sm text-muted-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:cursor-grabbing"
>
<GripVerticalIcon className="size-4" />
</button>
<div className={cn(isDragging && "rounded-md bg-sidebar-accent/40")}>{children}</div>
</div>
);
}

View file

@ -12,16 +12,17 @@ import {
Crosshair,
Flag,
Kanban,
Landmark,
LifeBuoy,
Medal,
Map,
NotebookText,
Package,
Radar,
ScrollText,
Search,
ShoppingBag,
Store,
Swords,
TrendingUp,
Trophy,
Truck,
UserCog,
@ -167,12 +168,12 @@ export const sidebarData = {
{
title: "Banking",
url: "/logistics/banking",
icon: TrendingUp,
icon: Landmark,
},
{
title: "Market",
url: "/logistics/market",
icon: ShoppingBag,
icon: Store,
},
],
navPersonal: [
@ -203,6 +204,11 @@ export const sidebarData = {
url: "/story",
icon: ScrollText,
},
{
title: "Journals",
url: "/journals",
icon: NotebookText,
},
],
navSurveys: [
{

View file

@ -1,6 +1,6 @@
import Link from "next/link";
import { Item, ItemContent, ItemHeader, ItemTitle } from "@/components/ui/item";
import { ChevronRightIcon, FlagIcon } from "lucide-react";
import { TacticalFrame } from "./tactical";
interface CampaignEntry {
id: number;
@ -14,73 +14,67 @@ interface ActiveCampaignsProps {
}
const statusColors: Record<string, string> = {
inProgress: "bg-blue-500/20 text-blue-400",
concept: "bg-muted text-muted-foreground",
onHold: "bg-amber-500/20 text-amber-400",
inProgress: "bg-blue-500/15 text-blue-400 border-blue-500/30",
concept: "bg-muted text-muted-foreground border-border",
onHold: "bg-amber-500/15 text-amber-400 border-amber-500/30",
};
export function ActiveCampaigns({ campaigns }: ActiveCampaignsProps) {
if (campaigns.length === 0) {
return (
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<FlagIcon className="size-4 text-muted-foreground" />
<ItemTitle>Active Campaigns</ItemTitle>
</div>
</ItemHeader>
<ItemContent>
<p className="text-sm text-muted-foreground italic">No active campaigns.</p>
</ItemContent>
</Item>
);
}
const statusLabel = (status: string): string =>
status === "inProgress" ? "Active" : status === "onHold" ? "On Hold" : status;
export function ActiveCampaigns({ campaigns }: ActiveCampaignsProps) {
return (
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<FlagIcon className="size-4 text-muted-foreground" />
<ItemTitle>Active Campaigns</ItemTitle>
<TacticalFrame classification="Intelligence // Campaigns">
<div className="flex items-center justify-between gap-2 px-4 pt-3">
<div className="flex min-w-0 items-center gap-2">
<FlagIcon className="size-4 shrink-0 text-muted-foreground" />
<h3 className="truncate text-sm font-semibold uppercase tracking-wide">
Active Campaigns
</h3>
</div>
<Link
href="/intelligence/campaigns"
className="text-xs text-muted-foreground hover:text-primary transition-colors"
>
View all
</Link>
</ItemHeader>
<ItemContent>
<div className="flex flex-col gap-2">
{campaigns.map((campaign) => (
<Link
key={campaign.id}
href={`/intelligence/campaigns/${campaign.id}`}
className="flex items-center gap-3 p-2 rounded-md hover:bg-muted/50 transition-colors group"
>
<FlagIcon className="size-4 text-muted-foreground shrink-0" />
<div className="flex flex-col gap-0.5 min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="text-sm font-medium truncate group-hover:text-primary transition-colors">
{campaign.name}
</span>
<span
className={`text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded shrink-0 ${statusColors[campaign.status] ?? "bg-muted text-muted-foreground"}`}
>
{campaign.status === "inProgress"
? "Active"
: campaign.status === "onHold"
? "On Hold"
: campaign.status}
</span>
{campaigns.length > 0 && (
<Link
href="/intelligence/campaigns"
className="shrink-0 py-1 text-xs text-muted-foreground transition-colors hover:text-primary"
>
View all
</Link>
)}
</div>
<div className="p-4 pt-3">
{campaigns.length === 0 ? (
<p className="text-sm italic text-muted-foreground">No active campaigns.</p>
) : (
<div className="flex flex-col gap-1">
{campaigns.map((campaign) => (
<Link
key={campaign.id}
href={`/intelligence/campaigns/${campaign.id}`}
className="group flex items-center gap-3 rounded-sm p-2 transition-colors hover:bg-muted/50"
>
<FlagIcon className="size-4 shrink-0 text-muted-foreground" />
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
<div className="flex items-center gap-2">
<span className="truncate text-sm font-medium transition-colors group-hover:text-primary">
{campaign.name}
</span>
<span
className={`shrink-0 rounded-sm border px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wider ${
statusColors[campaign.status] ?? "bg-muted text-muted-foreground border-border"
}`}
>
{statusLabel(campaign.status)}
</span>
</div>
<span className="truncate text-xs text-muted-foreground">{campaign.summary}</span>
</div>
<span className="text-xs text-muted-foreground truncate">{campaign.summary}</span>
</div>
<ChevronRightIcon className="size-3 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity shrink-0" />
</Link>
))}
</div>
</ItemContent>
</Item>
<ChevronRightIcon className="size-3 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100" />
</Link>
))}
</div>
)}
</div>
</TacticalFrame>
);
}

View file

@ -1,10 +1,8 @@
import Link from "next/link";
import { Item, ItemContent, ItemHeader, ItemTitle } from "@/components/ui/item";
import {
MissionCard,
type MissionCardProps,
} from "@/components/frontend/intelligence/MissionCard";
import { CrosshairIcon } from "lucide-react";
import { TacticalFrame, refCodeFrom } from "./tactical";
interface MissionBriefingProps {
readonly mission: MissionCardProps["mission"] | null;
@ -13,26 +11,19 @@ interface MissionBriefingProps {
export function MissionBriefing({ mission, heading = "Next Mission" }: MissionBriefingProps) {
return (
<Item variant="outline" className="items-start content-start">
<ItemHeader>
<div className="flex items-center gap-2">
<CrosshairIcon className="size-4 text-muted-foreground" />
<ItemTitle>{heading}</ItemTitle>
</div>
<Link
href="/intelligence/missions"
className="text-xs text-muted-foreground transition-colors hover:text-primary"
>
View all
</Link>
</ItemHeader>
<ItemContent>
<TacticalFrame
classification={`Operations // ${heading}`}
refCode={mission ? `REF ${refCodeFrom(mission.id)}` : undefined}
>
{/* No separate header row: the frame strip names the section and the
mission card carries its own "View details" affordance. */}
<div className="p-4">
{mission ? (
<MissionCard mission={mission} showFullDetails />
) : (
<p className="text-sm text-muted-foreground italic">No missions currently scheduled.</p>
)}
</ItemContent>
</Item>
</div>
</TacticalFrame>
);
}

View file

@ -1,12 +1,8 @@
import Link from "next/link";
import type { Ticket } from "@/payload-types";
import { Item, ItemContent, ItemHeader, ItemTitle } from "@/components/ui/item";
import { ChevronRightIcon, LifeBuoyIcon } from "lucide-react";
import {
CLOSING_STATUSES,
STATUS_STYLES,
statusLabel,
} from "@/lib/tickets/ticketMeta";
import { STATUS_STYLES, statusLabel } from "@/lib/tickets/ticketMeta";
import { TacticalFrame } from "./tactical";
interface MyTicketsProps {
readonly tickets: Ticket[];
@ -28,23 +24,26 @@ function timeAgo(dateStr: string): string {
export function MyTickets({ tickets, openCount }: MyTicketsProps) {
return (
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<LifeBuoyIcon className="size-4 text-muted-foreground" />
<ItemTitle>My Tickets</ItemTitle>
<TacticalFrame classification="Helpdesk // Tickets">
<div className="flex items-center justify-between gap-2 px-4 pt-3">
<div className="flex min-w-0 items-center gap-2">
<LifeBuoyIcon className="size-4 shrink-0 text-muted-foreground" />
<h3 className="truncate text-sm font-semibold uppercase tracking-wide">My Tickets</h3>
{openCount > 0 && (
<span className="text-xs text-muted-foreground">{openCount} open</span>
<span className="shrink-0 text-xs text-muted-foreground">{openCount} open</span>
)}
</div>
<Link
href="/helpdesk"
className="text-xs text-muted-foreground transition-colors hover:text-primary"
>
View all
</Link>
</ItemHeader>
<ItemContent>
{tickets.length > 0 && (
<Link
href="/helpdesk"
className="shrink-0 py-1 text-xs text-muted-foreground transition-colors hover:text-primary"
>
View all
</Link>
)}
</div>
<div className="p-4 pt-3">
{tickets.length === 0 ? (
<p className="text-sm italic text-muted-foreground">No tickets yet.</p>
) : (
@ -53,10 +52,10 @@ export function MyTickets({ tickets, openCount }: MyTicketsProps) {
<Link
key={ticket.id}
href={`/helpdesk/${ticket.id}`}
className="group flex items-center gap-3 rounded-md p-2 transition-colors hover:bg-muted/50"
className="group flex items-center gap-3 rounded-sm p-2 transition-colors hover:bg-muted/50"
>
<span
className={`shrink-0 rounded border px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wider ${STATUS_STYLES[ticket.status]}`}
className={`shrink-0 rounded-sm border px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wider ${STATUS_STYLES[ticket.status]}`}
>
{statusLabel(ticket.status)}
</span>
@ -73,7 +72,7 @@ export function MyTickets({ tickets, openCount }: MyTicketsProps) {
))}
</div>
)}
</ItemContent>
</Item>
</div>
</TacticalFrame>
);
}

View file

@ -1,9 +1,9 @@
import Link from "next/link";
import type { MarketListing, MarketNegotiation } from "@/payload-types";
import { Item, ItemContent, ItemHeader, ItemTitle } from "@/components/ui/item";
import { ChevronRightIcon, HandshakeIcon } from "lucide-react";
import type { CurrencyConfig } from "@/lib/banking/format";
import { CurrencyAmount } from "@/components/frontend/banking/CurrencyAmount";
import { TacticalFrame } from "./tactical";
interface OpenNegotiationsProps {
readonly negotiations: MarketNegotiation[];
@ -40,21 +40,24 @@ export function OpenNegotiations({
const fmt = (n: number) => <CurrencyAmount value={n} currency={currencyConfig} />;
return (
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<HandshakeIcon className="size-4 text-muted-foreground" />
<ItemTitle>Negotiations</ItemTitle>
<span className="text-xs text-muted-foreground">{negotiations.length} open</span>
<TacticalFrame classification="Logistics // Market">
<div className="flex items-center justify-between gap-2 px-4 pt-3">
<div className="flex min-w-0 items-center gap-2">
<HandshakeIcon className="size-4 shrink-0 text-muted-foreground" />
<h3 className="truncate text-sm font-semibold uppercase tracking-wide">Negotiations</h3>
<span className="shrink-0 text-xs text-muted-foreground">
{negotiations.length} open
</span>
</div>
<Link
href="/logistics/market"
className="text-xs text-muted-foreground transition-colors hover:text-primary"
className="shrink-0 py-1 text-xs text-muted-foreground transition-colors hover:text-primary"
>
Market
</Link>
</ItemHeader>
<ItemContent>
</div>
<div className="p-4 pt-3">
<div className="flex flex-col gap-1">
{negotiations.map((negotiation) => {
const listing = listingOf(negotiation);
@ -68,7 +71,7 @@ export function OpenNegotiations({
<Link
key={negotiation.id}
href="/logistics/market"
className="group flex items-center gap-3 rounded-md p-2 transition-colors hover:bg-muted/50"
className="group flex items-center gap-3 rounded-sm p-2 transition-colors hover:bg-muted/50"
>
<HandshakeIcon className="size-4 shrink-0 text-muted-foreground" />
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
@ -90,7 +93,7 @@ export function OpenNegotiations({
);
})}
</div>
</ItemContent>
</Item>
</div>
</TacticalFrame>
);
}

View file

@ -1,8 +1,8 @@
import Link from "next/link";
import type { Assignment, Rank } from "@/payload-types";
import type { ResolvedLevel } from "@/utils/xp/resolveLevel";
import { Item, ItemContent, ItemHeader, ItemTitle } from "@/components/ui/item";
import { UserIcon } from "lucide-react";
import { ReadoutFooter, TacticalFrame, refCodeFrom } from "./tactical";
interface ProfileSummaryProps {
displayName: string;
@ -19,21 +19,35 @@ export function ProfileSummary({
xpLevel,
assignments,
}: ProfileSummaryProps) {
const footerCells = [
{ label: "XP", value: xpLevel.xp.toLocaleString() },
{ label: "Level", value: xpLevel.levelName },
{ label: "Rank", value: rank.abbreviation || "-" },
{ label: "Assignments", value: String(assignments.length) },
];
return (
<Item variant="outline" className="items-start content-start">
<ItemHeader>
<div className="flex items-center gap-2">
<UserIcon className="size-4 text-muted-foreground" />
<ItemTitle>Service Summary</ItemTitle>
<TacticalFrame
classification="Personnel // Service Record"
refCode={`REF ${refCodeFrom(username)}`}
footer={<ReadoutFooter cells={footerCells} />}
>
<div className="flex items-center justify-between gap-2 px-4 pt-3">
<div className="flex min-w-0 items-center gap-2">
<UserIcon className="size-4 shrink-0 text-muted-foreground" />
<h3 className="truncate text-sm font-semibold uppercase tracking-wide">
Service Summary
</h3>
</div>
<Link
href={`/profile/${username}`}
className="text-xs text-muted-foreground hover:text-primary transition-colors"
className="shrink-0 py-1 text-xs text-muted-foreground transition-colors hover:text-primary"
>
View full record
</Link>
</ItemHeader>
<ItemContent className="flex flex-col gap-4">
</div>
<div className="flex flex-col gap-4 p-4 pt-3">
<div className="flex items-start gap-4">
{rank.insigniaUrl && (
<img
@ -43,7 +57,7 @@ export function ProfileSummary({
/>
)}
<div className="flex flex-col gap-1 min-w-0">
<h3 className="text-lg font-bold tracking-tight uppercase">{displayName}</h3>
<h4 className="text-lg font-bold tracking-tight uppercase">{displayName}</h4>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<span className="font-medium text-foreground">{rank.name}</span>
<span className="text-border">|</span>
@ -71,7 +85,7 @@ export function ProfileSummary({
{assignments.map((a) => (
<span
key={a.name}
className="text-xs font-mono bg-muted border border-border px-2.5 py-1 rounded-md"
className="text-xs font-mono bg-muted border border-border px-2.5 py-1 rounded-sm"
>
{a.callsign ? `[${a.callsign}] ` : ""}
{a.name}
@ -80,7 +94,7 @@ export function ProfileSummary({
))}
</div>
)}
</ItemContent>
</Item>
</div>
</TacticalFrame>
);
}

View file

@ -1,5 +1,6 @@
import { Item, ItemContent, ItemDescription, ItemMedia, ItemTitle } from "@/components/ui/item";
import type { LucideIcon } from "lucide-react";
import { Building2Icon, CrosshairIcon, ShieldIcon, UsersIcon } from "lucide-react";
import { TacticalFrame } from "./tactical";
interface QuickStatsProps {
activeCampaigns: number;
@ -9,6 +10,12 @@ interface QuickStatsProps {
totalMembers: number;
}
interface StatCell {
label: string;
value: number;
icon: LucideIcon;
}
export function QuickStats({
activeCampaigns,
totalMissions,
@ -16,63 +23,30 @@ export function QuickStats({
totalFactions,
totalMembers,
}: QuickStatsProps) {
const cells: StatCell[] = [
{ label: "Campaigns", value: activeCampaigns, icon: CrosshairIcon },
{ label: "Missions", value: totalMissions, icon: CrosshairIcon },
{ label: "Structures", value: totalStructures, icon: Building2Icon },
{ label: "Factions", value: totalFactions, icon: ShieldIcon },
{ label: "Operators", value: totalMembers, icon: UsersIcon },
];
return (
<div className="grid grid-cols-2 md:grid-cols-3 2xl:grid-cols-5 gap-3">
<Item variant="muted" size="sm">
<ItemMedia variant="icon">
<CrosshairIcon />
</ItemMedia>
<ItemContent>
<ItemTitle className="whitespace-nowrap">Active Campaigns</ItemTitle>
<ItemDescription className="text-2xl font-semibold text-foreground leading-none">
{activeCampaigns}
</ItemDescription>
</ItemContent>
</Item>
<Item variant="muted" size="sm">
<ItemMedia variant="icon">
<CrosshairIcon />
</ItemMedia>
<ItemContent>
<ItemTitle className="whitespace-nowrap">Total Missions</ItemTitle>
<ItemDescription className="text-2xl font-semibold text-foreground leading-none">
{totalMissions}
</ItemDescription>
</ItemContent>
</Item>
<Item variant="muted" size="sm">
<ItemMedia variant="icon">
<Building2Icon />
</ItemMedia>
<ItemContent>
<ItemTitle className="whitespace-nowrap">Structures</ItemTitle>
<ItemDescription className="text-2xl font-semibold text-foreground leading-none">
{totalStructures}
</ItemDescription>
</ItemContent>
</Item>
<Item variant="muted" size="sm">
<ItemMedia variant="icon">
<ShieldIcon />
</ItemMedia>
<ItemContent>
<ItemTitle className="whitespace-nowrap">Factions</ItemTitle>
<ItemDescription className="text-2xl font-semibold text-foreground leading-none">
{totalFactions}
</ItemDescription>
</ItemContent>
</Item>
<Item variant="muted" size="sm">
<ItemMedia variant="icon">
<UsersIcon />
</ItemMedia>
<ItemContent>
<ItemTitle className="whitespace-nowrap">Operators</ItemTitle>
<ItemDescription className="text-2xl font-semibold text-foreground leading-none">
{totalMembers}
</ItemDescription>
</ItemContent>
</Item>
</div>
<TacticalFrame classification="Theater // Situation Report" brackets={false}>
{/* gap-px over a white/10 backdrop renders hairline separators in both directions */}
<div className="grid grid-cols-2 gap-px bg-white/10 sm:grid-cols-3 2xl:grid-cols-5">
{cells.map((cell) => (
<div key={cell.label} className="flex flex-col gap-1 bg-card px-4 py-3">
<span className="font-mono text-xl leading-none tabular-nums text-foreground">
{cell.value.toLocaleString()}
</span>
<span className="flex items-center gap-1.5 text-[9px] uppercase tracking-widest text-muted-foreground">
<cell.icon aria-hidden="true" className="size-3 opacity-60" />
{cell.label}
</span>
</div>
))}
</div>
</TacticalFrame>
);
}

View file

@ -1,7 +1,7 @@
import type { GameStructure, User } from "@/payload-types";
import { Item, ItemContent, ItemHeader, ItemTitle } from "@/components/ui/item";
import { BookOpenTextIcon, LockIcon, ScrollTextIcon } from "lucide-react";
import { formatType } from "@/utils/event-log/formatType";
import { TacticalFrame } from "./tactical";
interface EventEntry {
id: number;
@ -33,75 +33,64 @@ function timeAgo(dateStr: string): string {
}
export function RecentEvents({ events, currentUserId }: RecentEventsProps) {
if (events.length === 0) {
return (
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<ScrollTextIcon className="size-4 text-muted-foreground" />
<ItemTitle>Recent Events</ItemTitle>
</div>
</ItemHeader>
<ItemContent>
<p className="text-sm text-muted-foreground italic">No recent events recorded.</p>
</ItemContent>
</Item>
);
}
return (
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<ScrollTextIcon className="size-4 text-muted-foreground" />
<ItemTitle>Recent Events</ItemTitle>
<TacticalFrame classification="Event Log // Recent">
<div className="flex items-center justify-between gap-2 px-4 pt-3">
<div className="flex min-w-0 items-center gap-2">
<ScrollTextIcon className="size-4 shrink-0 text-muted-foreground" />
<h3 className="truncate text-sm font-semibold uppercase tracking-wide">Recent Events</h3>
</div>
</ItemHeader>
<ItemContent>
<div className="flex flex-col">
{events.map((event, index) => {
const actor =
typeof event.actor === "object" && event.actor !== null
? (event.actor as User)
: null;
const actorId = actor?.id ?? (typeof event.actor === "number" ? event.actor : null);
const isYou = actorId != null && actorId === currentUserId;
const actorName = actor?.displayName ?? actor?.username ?? null;
const actorLabel = isYou ? "You" : actorName;
const isNarrative = event.system === false;
</div>
return (
<div key={event.id}>
<div
className={`flex items-start gap-3 py-2 text-sm ${isNarrative ? "pl-3 border-l-2 border-amber-500/40" : ""}`}
>
{isNarrative && (
<BookOpenTextIcon className="size-4 text-amber-400 shrink-0 mt-0.5" />
)}
<div className="flex-1 min-w-0 flex flex-col gap-0.5">
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<span className="tabular-nums shrink-0">{timeAgo(event.timestamp)}</span>
{actorLabel && (
<span className={`font-medium ${isYou ? "text-foreground" : ""}`}>
{actorLabel}
</span>
)}
<span className="capitalize">{formatType(event.type)}</span>
{event.visibility === "restricted" && (
<LockIcon className="size-3 text-amber-400 shrink-0" />
)}
<div className="p-4 pt-3">
{events.length === 0 ? (
<p className="text-sm italic text-muted-foreground">No recent events recorded.</p>
) : (
<div className="flex flex-col">
{events.map((event, index) => {
const actor =
typeof event.actor === "object" && event.actor !== null
? (event.actor as User)
: null;
const actorId = actor?.id ?? (typeof event.actor === "number" ? event.actor : null);
const isYou = actorId != null && actorId === currentUserId;
const actorName = actor?.displayName ?? actor?.username ?? null;
const actorLabel = isYou ? "You" : actorName;
const isNarrative = event.system === false;
return (
<div key={event.id}>
<div
className={`flex items-start gap-3 py-2 text-sm ${isNarrative ? "border-l-2 border-amber-500/40 pl-3" : ""}`}
>
{isNarrative && (
<BookOpenTextIcon className="mt-0.5 size-4 shrink-0 text-amber-400" />
)}
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<span className="shrink-0 tabular-nums">{timeAgo(event.timestamp)}</span>
{actorLabel && (
<span className={`font-medium ${isYou ? "text-foreground" : ""}`}>
{actorLabel}
</span>
)}
<span className="capitalize">{formatType(event.type)}</span>
{event.visibility === "restricted" && (
<LockIcon className="size-3 shrink-0 text-amber-400" />
)}
</div>
<span className={`min-w-0 ${isNarrative ? "text-amber-100/90" : ""}`}>
{event.message}
</span>
</div>
<span className={`min-w-0 ${isNarrative ? "text-amber-100/90" : ""}`}>
{event.message}
</span>
</div>
{index < events.length - 1 && <div className="border-t border-border" />}
</div>
{index < events.length - 1 && <div className="border-t border-border" />}
</div>
);
})}
</div>
</ItemContent>
</Item>
);
})}
</div>
)}
</div>
</TacticalFrame>
);
}

View file

@ -1,8 +1,8 @@
import Link from "next/link";
import type { UserNotification } from "@/payload-types";
import { Item, ItemContent, ItemHeader, ItemTitle } from "@/components/ui/item";
import { BellIcon } from "lucide-react";
import { MarkNotificationReadButton } from "@/components/frontend/dashboard/MarkNotificationReadButton";
import { TacticalFrame } from "./tactical";
interface RecentNotificationsProps {
readonly notifications: UserNotification[];
@ -31,30 +31,31 @@ export function RecentNotifications({
if (notifications.length === 0) return null;
return (
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<BellIcon className="size-4 text-muted-foreground" />
<ItemTitle>Notifications</ItemTitle>
<TacticalFrame classification="Comms // Notifications">
<div className="flex items-center justify-between gap-2 px-4 pt-3">
<div className="flex min-w-0 items-center gap-2">
<BellIcon className="size-4 shrink-0 text-muted-foreground" />
<h3 className="truncate text-sm font-semibold uppercase tracking-wide">Notifications</h3>
{unreadCount > 0 && (
<span className="text-xs text-muted-foreground">{unreadCount} unread</span>
<span className="shrink-0 text-xs text-muted-foreground">{unreadCount} unread</span>
)}
</div>
<Link
href="/notifications"
className="text-xs text-muted-foreground transition-colors hover:text-primary"
className="shrink-0 py-1 text-xs text-muted-foreground transition-colors hover:text-primary"
>
Inbox
</Link>
</ItemHeader>
<ItemContent>
</div>
<div className="p-4 pt-3">
<div className="flex flex-col gap-1">
{notifications.map((notification) => {
const unread = !notification.read;
return (
<div
key={notification.id}
className="group flex items-start gap-1 rounded-md p-2 transition-colors hover:bg-muted/50"
className="group flex items-start gap-1 rounded-sm p-2 transition-colors hover:bg-muted/50"
>
<Link
href={notification.link ?? "/notifications"}
@ -93,7 +94,7 @@ export function RecentNotifications({
);
})}
</div>
</ItemContent>
</Item>
</div>
</TacticalFrame>
);
}

View file

@ -1,53 +1,46 @@
import Link from "next/link";
import { Item, ItemContent, ItemHeader, ItemTitle } from "@/components/ui/item";
import {
MissionCard,
type MissionCardProps,
} from "@/components/frontend/intelligence/MissionCard";
import { CrosshairIcon } from "lucide-react";
import { TacticalFrame } from "./tactical";
interface UpcomingMissionsProps {
readonly missions: MissionCardProps["mission"][];
}
export function UpcomingMissions({ missions }: UpcomingMissionsProps) {
if (missions.length === 0) {
return (
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<CrosshairIcon className="size-4 text-muted-foreground" />
<ItemTitle>Upcoming Missions</ItemTitle>
</div>
</ItemHeader>
<ItemContent>
<p className="text-sm text-muted-foreground italic">No missions scheduled.</p>
</ItemContent>
</Item>
);
}
return (
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<CrosshairIcon className="size-4 text-muted-foreground" />
<ItemTitle>Upcoming Missions</ItemTitle>
<TacticalFrame classification="Operations // Upcoming">
<div className="flex items-center justify-between gap-2 px-4 pt-3">
<div className="flex min-w-0 items-center gap-2">
<CrosshairIcon className="size-4 shrink-0 text-muted-foreground" />
<h3 className="truncate text-sm font-semibold uppercase tracking-wide">
Upcoming Missions
</h3>
</div>
<Link
href="/intelligence/missions"
className="text-xs text-muted-foreground transition-colors hover:text-primary"
>
View all
</Link>
</ItemHeader>
<ItemContent>
<div className="flex flex-col gap-2">
{missions.map((mission) => (
<MissionCard key={mission.id} mission={mission} showFullDetails={false} />
))}
</div>
</ItemContent>
</Item>
{missions.length > 0 && (
<Link
href="/intelligence/missions"
className="shrink-0 py-1 text-xs text-muted-foreground transition-colors hover:text-primary"
>
View all
</Link>
)}
</div>
<div className="p-4 pt-3">
{missions.length === 0 ? (
<p className="text-sm italic text-muted-foreground">No missions scheduled.</p>
) : (
<div className="flex flex-col gap-2">
{missions.map((mission) => (
<MissionCard key={mission.id} mission={mission} showFullDetails={false} />
))}
</div>
)}
</div>
</TacticalFrame>
);
}

View file

@ -1,10 +1,10 @@
import Link from "next/link";
import type { BankAccount } from "@/payload-types";
import { Item, ItemContent, ItemHeader, ItemTitle } from "@/components/ui/item";
import { WalletIcon } from "lucide-react";
import type { CurrencyConfig } from "@/lib/banking/format";
import { CurrencyAmount } from "@/components/frontend/banking/CurrencyAmount";
import { MyWalletCard } from "@/components/frontend/banking/MyWalletCard";
import { ReadoutFooter, TacticalFrame, refCodeFrom } from "./tactical";
interface WalletWidgetProps {
readonly account: BankAccount | null;
@ -12,25 +12,36 @@ interface WalletWidgetProps {
}
export function WalletWidget({ account, currencyConfig }: WalletWidgetProps) {
// No account yet: the call-to-action card owns its own conventional styling.
if (!account) {
return <MyWalletCard />;
}
const footerCells = [
{ label: "Acct", value: `#${account.id}` },
{ label: "Status", value: account.status ?? "open" },
];
return (
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<WalletIcon className="size-4 text-muted-foreground" />
<ItemTitle>Wallet</ItemTitle>
<TacticalFrame
classification="Logistics // Banking"
refCode={`REF ${refCodeFrom(account.id)}`}
footer={<ReadoutFooter cells={footerCells} />}
>
<div className="flex items-center justify-between gap-2 px-4 pt-3">
<div className="flex min-w-0 items-center gap-2">
<WalletIcon className="size-4 shrink-0 text-muted-foreground" />
<h3 className="truncate text-sm font-semibold uppercase tracking-wide">Wallet</h3>
</div>
<Link
href="/logistics/banking"
className="text-xs text-muted-foreground transition-colors hover:text-primary"
className="shrink-0 py-1 text-xs text-muted-foreground transition-colors hover:text-primary"
>
Banking
</Link>
</ItemHeader>
<ItemContent>
</div>
<div className="p-4 pt-3">
<Link
href={`/logistics/banking/${account.id}`}
className="group flex items-center justify-between gap-3"
@ -48,7 +59,7 @@ export function WalletWidget({ account, currencyConfig }: WalletWidgetProps) {
<CurrencyAmount value={account.balance ?? 0} currency={currencyConfig} />
</span>
</Link>
</ItemContent>
</Item>
</div>
</TacticalFrame>
);
}

View file

@ -0,0 +1,118 @@
import type { ReactNode } from "react";
import { cn } from "@/lib/utils";
/**
* Shared tactical "dossier" primitives for dashboard hero widgets, following
* the recipe in src/components/frontend/AGENTS.md (reference implementation:
* CampaignCard). Each piece is separable: frames can take just the strip, or
* brackets, or a readout footer. Dense widgets stay conventional shadcn so
* these surfaces stand out.
*/
/** Deterministic 3-digit reference code derived from a seed (id, username...). */
export function refCodeFrom(seed: string | number): string {
const value = String(seed);
let hash = 5381;
for (let i = 0; i < value.length; i += 1) {
hash = ((hash << 5) + hash + value.charCodeAt(i)) >>> 0;
}
return String(hash % 1000).padStart(3, "0");
}
interface TacticalFrameProps {
/** Left classification-strip label, e.g. "Personnel // Service Record". */
classification: string;
/** Right strip label, e.g. "REF 042". Omit to hide. */
refCode?: string;
children: ReactNode;
/** Optional permanent readout bar pinned to the bottom edge. */
footer?: ReactNode;
/** Corner brackets, default on. Turn off for bar-shaped surfaces. */
brackets?: boolean;
className?: string;
}
export function TacticalFrame({
classification,
refCode,
children,
footer,
brackets = true,
className,
}: TacticalFrameProps) {
return (
<div
className={cn(
"group relative flex min-w-0 flex-col overflow-hidden rounded-none border border-border/70 bg-card transition-colors duration-300 hover:border-foreground/30",
className,
)}
>
{/* Faint grid texture: constant opacity, never brightens on hover. */}
<div
aria-hidden="true"
className="pointer-events-none absolute inset-0 opacity-[0.04]"
style={{
backgroundImage:
"linear-gradient(to right, white 1px, transparent 1px), linear-gradient(to bottom, white 1px, transparent 1px)",
backgroundSize: "28px 28px",
}}
/>
<div
aria-hidden="true"
className="relative z-20 flex items-center justify-between gap-2 border-b border-white/15 bg-black/50 px-4 py-1.5 backdrop-blur-sm"
>
<span className="truncate font-mono text-[9px] uppercase tracking-widest text-white/60">
{classification}
</span>
{refCode ? (
<span className="shrink-0 font-mono text-[9px] uppercase tracking-widest text-white/60">
{refCode}
</span>
) : null}
</div>
{brackets ? (
<div aria-hidden="true" className="pointer-events-none absolute inset-2 z-30">
<span className="absolute left-0 top-0 size-3 border-l border-t border-white/25 transition-colors duration-300 group-hover:border-white/60" />
<span className="absolute right-0 top-0 size-3 border-r border-t border-white/25 transition-colors duration-300 group-hover:border-white/60" />
<span className="absolute bottom-0 left-0 size-3 border-b border-l border-white/25 transition-colors duration-300 group-hover:border-white/60" />
<span className="absolute bottom-0 right-0 size-3 border-b border-r border-white/25 transition-colors duration-300 group-hover:border-white/60" />
</div>
) : null}
<div className="relative z-10 flex min-w-0 flex-1 flex-col">{children}</div>
{footer ? <div className="relative z-20 mt-auto">{footer}</div> : null}
</div>
);
}
export interface ReadoutCell {
label: string;
value: string;
}
/** Permanent single-line readout bar (hairline-separated mono cells). */
export function ReadoutFooter({ cells }: { cells: ReadoutCell[] }) {
return (
<div className="flex items-stretch border-t border-white/15 bg-black/60 px-2 py-1.5 backdrop-blur-sm">
{cells.map((cell, index) => (
<div
key={cell.label}
className={cn(
"flex min-w-0 flex-1 items-center justify-center gap-1.5 px-1",
index < cells.length - 1 && "border-r border-white/15",
)}
>
<span className="truncate font-mono text-xs tabular-nums text-white/80">
{cell.value}
</span>
<span className="shrink-0 text-[9px] uppercase tracking-wider text-white/50">
{cell.label}
</span>
</div>
))}
</div>
);
}

View file

@ -56,7 +56,7 @@ export function TicketCard({ ticket, voteSummary }: TicketCardProps) {
</ItemHeader>
<ItemContent className="w-full min-w-0 flex-1 gap-3">
<ItemTitle className="line-clamp-2 min-w-0 max-w-full text-base font-semibold">
<Link href={`/helpdesk/${ticket.id}`} className="hover:underline">
<Link href={`/helpdesk/${ticket.id}`} className="py-1 hover:underline">
{ticket.title}
</Link>
</ItemTitle>

View file

@ -243,7 +243,9 @@ export function CampaignCard({ campaign, size = "lg" }: CampaignCardProps) {
</div>
{isSmall ? (
<footer className="absolute inset-x-0 bottom-0 z-20 flex translate-y-4 items-center bg-black/60 px-2 py-2.5 opacity-0 backdrop-blur-sm transition-all duration-300 ease-out group-hover:translate-y-0 group-hover:opacity-100 motion-reduce:transition-none">
// Touch devices never hover: keep the readout permanently visible on
// coarse pointers and reserve the slide-in reveal for mice.
<footer className="absolute inset-x-0 bottom-0 z-20 flex translate-y-0 items-center bg-black/60 px-2 py-2.5 opacity-100 backdrop-blur-sm transition-all duration-300 ease-out pointer-fine:translate-y-4 pointer-fine:opacity-0 pointer-fine:group-hover:translate-y-0 pointer-fine:group-hover:opacity-100 motion-reduce:transition-none">
<div className="flex min-w-0 flex-1 items-center justify-center gap-1.5 border-r border-white/15 text-xs text-white/80">
<CrosshairIcon aria-hidden="true" className="size-3.5 shrink-0 text-white/60" />
<span className="sr-only">Missions</span>

View file

@ -48,7 +48,7 @@ export function CampaignsList({ campaigns }: CampaignsListProps) {
/>
<label
htmlFor="show-completed-campaigns"
className="cursor-pointer select-none text-sm text-muted-foreground"
className="cursor-pointer select-none px-1 py-1.5 text-sm text-muted-foreground"
>
Show completed
</label>

View file

@ -0,0 +1,108 @@
"use client";
import * as React from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Loader2Icon, PencilIcon, Trash2Icon } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { deleteJournal } from "@/app/(frontend)/journals/actions";
import { JournalFormDialog, type MissionOption } from "./JournalFormDialog";
import type { JournalDraft } from "./JournalFormDialog";
interface JournalDetailControlsProps {
draft: JournalDraft;
missions: MissionOption[];
canEdit: boolean;
canDelete: boolean;
}
/** Author/staff controls on the /journals/[id] reader page. */
export function JournalDetailControls({
draft,
missions,
canEdit,
canDelete,
}: JournalDetailControlsProps) {
const router = useRouter();
const [editing, setEditing] = React.useState(false);
const [deleting, setDeleting] = React.useState(false);
if (!canEdit && !canDelete) return null;
const handleDelete = async () => {
if (typeof draft.id !== "number") return;
setDeleting(true);
const result = await deleteJournal(draft.id);
setDeleting(false);
if (!result.success) {
toast.error(result.error ?? "Failed to delete entry");
return;
}
toast.success("Entry deleted");
router.push("/journals");
router.refresh();
};
return (
<div className="flex items-center gap-2">
{canEdit && (
<>
<Button variant="outline" size="sm" onClick={() => setEditing(true)}>
<PencilIcon className="mr-2 size-3.5" />
Edit
</Button>
<JournalFormDialog
open={editing}
onOpenChange={setEditing}
missions={missions}
draft={draft}
/>
</>
)}
{canDelete && (
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="outline" size="sm" className="text-destructive hover:text-destructive">
<Trash2Icon className="mr-2 size-3.5" />
Delete
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete this journal entry?</AlertDialogTitle>
<AlertDialogDescription>
"{draft.title}" will be permanently removed. This cannot be undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={(e) => {
e.preventDefault();
void handleDelete();
}}
disabled={deleting}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{deleting && <Loader2Icon className="mr-2 size-4 animate-spin" />}
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)}
</div>
);
}

View file

@ -0,0 +1,203 @@
"use client";
import * as React from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Loader2Icon } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
LexicalRichTextEditor,
type LexicalJson,
} from "@/components/frontend/intelligence/LexicalRichTextEditor";
import { createJournal, updateJournal } from "@/app/(frontend)/journals/actions";
export interface MissionOption {
id: number;
label: string;
}
export interface JournalDraft {
id?: number;
title: string;
status: "draft" | "published";
/** yyyy-MM-dd or "" */
occurredAt: string;
missionId: number | null;
body: LexicalJson | null;
}
export const EMPTY_JOURNAL_DRAFT: JournalDraft = {
title: "",
status: "draft",
occurredAt: "",
missionId: null,
body: null,
};
interface JournalFormDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
missions: MissionOption[];
draft: JournalDraft;
}
/** Compose/edit dialog shared by the /journals list and the entry reader. */
export function JournalFormDialog({
open,
onOpenChange,
missions,
draft,
}: JournalFormDialogProps) {
const router = useRouter();
const isEdit = typeof draft.id === "number";
const [title, setTitle] = React.useState(draft.title);
const [status, setStatus] = React.useState<"draft" | "published">(draft.status);
const [occurredAt, setOccurredAt] = React.useState(draft.occurredAt);
const [missionId, setMissionId] = React.useState<string>(
draft.missionId === null ? "none" : String(draft.missionId),
);
const [body, setBody] = React.useState<LexicalJson | null>(draft.body);
const [saving, setSaving] = React.useState(false);
// Re-seed the form whenever a different entry (or a fresh compose) opens.
React.useEffect(() => {
if (!open) return;
setTitle(draft.title);
setStatus(draft.status);
setOccurredAt(draft.occurredAt);
setMissionId(draft.missionId === null ? "none" : String(draft.missionId));
setBody(draft.body);
}, [open, draft]);
const handleSubmit = async () => {
setSaving(true);
const input = {
title,
status,
occurredAt: occurredAt ? new Date(occurredAt).toISOString() : null,
mission: missionId === "none" ? null : Number(missionId),
body,
};
const result = isEdit
? await updateJournal(draft.id as number, input)
: await createJournal(input);
setSaving(false);
if (!result.success) {
toast.error(result.error ?? "Failed to save entry");
return;
}
toast.success(isEdit ? "Entry updated" : "Entry saved");
onOpenChange(false);
router.refresh();
if (!isEdit && result.data) {
router.push(`/journals/${result.data}`);
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-2xl">
<DialogHeader>
<DialogTitle>{isEdit ? "Edit journal entry" : "Write a journal entry"}</DialogTitle>
<DialogDescription>
Drafts are private to you. Publishing makes the entry readable by every operator on
Journals.
</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-1.5">
<Label htmlFor="journal-title">Title</Label>
<Input
id="journal-title"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="After-action reflections, deployment diaries..."
maxLength={200}
/>
</div>
<div className="grid gap-4 sm:grid-cols-3">
<div className="flex flex-col gap-1.5">
<Label>Status</Label>
<Select value={status} onValueChange={(v) => setStatus(v as "draft" | "published")}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="draft">Draft (private)</SelectItem>
<SelectItem value="published">Published</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="journal-date">In-world date</Label>
<Input
id="journal-date"
type="date"
value={occurredAt}
onChange={(e) => setOccurredAt(e.target.value)}
/>
</div>
<div className="flex flex-col gap-1.5">
<Label>Related mission</Label>
<Select value={missionId} onValueChange={setMissionId}>
<SelectTrigger>
<SelectValue placeholder="None" />
</SelectTrigger>
<SelectContent>
<SelectItem value="none">None</SelectItem>
{missions.map((m) => (
<SelectItem key={m.id} value={String(m.id)}>
{m.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div className="flex flex-col gap-1.5">
<Label>Entry</Label>
<LexicalRichTextEditor
key={`${draft.id ?? "new"}-${open ? "open" : "closed"}`}
value={body}
onChange={setBody}
placeholder="Write your entry here..."
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>
Cancel
</Button>
<Button onClick={handleSubmit} disabled={saving || !title.trim()}>
{saving && <Loader2Icon className="mr-2 size-4 animate-spin" />}
{isEdit ? "Save changes" : "Save entry"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View file

@ -0,0 +1,107 @@
"use client";
import * as React from "react";
import Link from "next/link";
import { NotebookTextIcon, PenLineIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent } from "@/components/ui/card";
import { DraftBadge } from "@/components/frontend/story/DraftBadge";
import {
EMPTY_JOURNAL_DRAFT,
JournalFormDialog,
type MissionOption,
} from "./JournalFormDialog";
export interface JournalCard {
id: number;
title: string;
status: "draft" | "published";
authorName: string;
dateLabel: string | null;
missionLabel: string | null;
excerpt: string;
}
interface JournalsListProps {
journals: JournalCard[];
missions: MissionOption[];
}
export function JournalsList({ journals, missions }: JournalsListProps) {
const [composing, setComposing] = React.useState(false);
return (
<div className="flex flex-col gap-6">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<p className="text-xs uppercase tracking-[0.3em] text-muted-foreground">
Member Journals
</p>
<h1 className="mt-1 font-serif text-3xl font-bold">Journals</h1>
<p className="mt-1 max-w-xl text-sm text-muted-foreground">
First-person accounts from the unit: after-action notes, deployment diaries, and
everything in between. Write your own at any time; publish when you are happy with it.
</p>
</div>
<Button onClick={() => setComposing(true)}>
<PenLineIcon className="mr-2 size-4" />
Write entry
</Button>
</div>
{journals.length === 0 ? (
<Card>
<CardContent className="flex flex-col items-center gap-3 py-12 text-center">
<NotebookTextIcon className="size-8 text-muted-foreground" />
<p className="text-muted-foreground">
No journal entries yet. Be the first to write one.
</p>
</CardContent>
</Card>
) : (
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
{journals.map((journal) => (
<Link key={journal.id} href={`/journals/${journal.id}`} className="group">
<Card className="h-full transition-colors group-hover:border-primary/50">
<CardContent className="flex h-full flex-col gap-2 p-5">
<div className="flex items-center gap-2">
{journal.status === "draft" && <DraftBadge />}
{journal.missionLabel && (
<Badge variant="secondary" className="max-w-[60%] truncate text-[10px]">
{journal.missionLabel}
</Badge>
)}
</div>
<h2 className="font-serif text-lg font-semibold leading-snug line-clamp-2">
{journal.title}
</h2>
{journal.excerpt && (
<p className="text-sm text-muted-foreground line-clamp-3">{journal.excerpt}</p>
)}
<div className="mt-auto flex items-center gap-2 pt-2 text-xs text-muted-foreground">
<span className="truncate">{journal.authorName}</span>
{journal.dateLabel && (
<>
<span className="text-border">|</span>
<span className="shrink-0">{journal.dateLabel}</span>
</>
)}
</div>
</CardContent>
</Card>
</Link>
))}
</div>
)}
<JournalFormDialog
open={composing}
onOpenChange={setComposing}
missions={missions}
draft={EMPTY_JOURNAL_DRAFT}
/>
</div>
);
}

View file

@ -100,7 +100,7 @@ export function ResourceCard({ resource }: ResourceCardProps) {
className="cursor-pointer group transition-all duration-200 hover:scale-[1.01] hover:[box-shadow:inset_0_2px_8px_rgba(255,255,255,0.33)]"
>
<ItemHeader>
<div className="flex items-center gap-2">
<div className="flex min-w-0 items-center gap-2">
{icon ? (
<ItemMedia variant="image">
<img src={icon.url} alt={resource.name} className="size-full object-cover" />
@ -115,12 +115,14 @@ export function ResourceCard({ resource }: ResourceCardProps) {
) : (
<ItemMedia variant="icon">{typeIcons[resource.type]}</ItemMedia>
)}
<ItemTitle className="flex flex-col">
<span className="font-mono text-xs text-muted-foreground">{resource.codeName}</span>
<span>{resource.name}</span>
<ItemTitle className="flex min-w-0 flex-col items-stretch">
<span className="min-w-0 truncate font-mono text-xs text-muted-foreground">
{resource.codeName}
</span>
<span className="min-w-0 truncate">{resource.name}</span>
</ItemTitle>
</div>
<div className="flex items-center gap-2">
<div className="flex shrink-0 items-center gap-2">
<span
className={`text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded ${typeColors[resource.type] ?? "bg-muted text-muted-foreground"}`}
>
@ -135,9 +137,6 @@ export function ResourceCard({ resource }: ResourceCardProps) {
</ItemHeader>
<ItemContent>
<div className="flex flex-col gap-3 w-full">
{truncatedDescription && (
<p className="text-sm text-muted-foreground line-clamp-2">{truncatedDescription}</p>
)}
<div className="flex flex-wrap items-center gap-x-4 gap-y-1.5 text-xs text-muted-foreground">
<span className="flex items-center gap-1 font-medium text-foreground">
{resource.baseValue.toLocaleString()} credits
@ -155,10 +154,10 @@ export function ResourceCard({ resource }: ResourceCardProps) {
</div>
</div>
</ItemContent>
<ItemDescription>
<ItemDescription className="basis-full">
{truncatedDescription ?? `${resource.type} resource (${resource.unitOfMeasure})`}
</ItemDescription>
<span className="text-xs text-muted-foreground group-hover:text-primary transition-colors flex items-center gap-1">
<span className="basis-full text-xs text-muted-foreground group-hover:text-primary transition-colors flex items-center gap-1">
View details <ChevronRightIcon className="size-3" />
</span>
</Item>

View file

@ -75,7 +75,7 @@ export function PeriodStandingsCard({
</button>
<Link
href={`/minigames/leaderboards?game=${gameKey}`}
className="ml-auto pr-1 text-xs text-muted-foreground hover:text-foreground"
className="ml-auto py-1 pr-1 text-xs text-muted-foreground hover:text-foreground"
>
All boards
</Link>

View file

@ -40,7 +40,8 @@ export function StandingsTable({
}
return (
<table className={cn("w-full text-sm", className)}>
<div className="overflow-x-auto">
<table className={cn("w-full text-sm", className)}>
<thead>
<tr className="text-left text-xs uppercase tracking-wider text-muted-foreground">
<th className="px-4 py-2 font-medium">#</th>
@ -73,6 +74,7 @@ export function StandingsTable({
);
})}
</tbody>
</table>
</table>
</div>
);
}

View file

@ -299,7 +299,7 @@ export function BlackjackArena({
</p>
)}
<div className="grid min-w-0 gap-6 xl:grid-cols-[minmax(0,1fr)_minmax(22rem,28rem)]">
<div className="grid grid-cols-1 min-w-0 gap-6 xl:grid-cols-[minmax(0,1fr)_minmax(22rem,28rem)]">
<section className="min-w-0">
{view === "lobby" ? (
<BlackjackLobby

View file

@ -137,7 +137,8 @@ export function FlappyLeaderboard({ refreshKey = 0, currentUserId, activePilots
No pilots on the board yet. Be the first to pass a pipe!
</p>
) : (
<table className="w-full text-sm">
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="text-left text-xs uppercase tracking-wider text-muted-foreground">
<th className="px-4 py-2 font-medium">#</th>
@ -191,6 +192,7 @@ export function FlappyLeaderboard({ refreshKey = 0, currentUserId, activePilots
))}
</tbody>
</table>
</div>
)}
</div>
);

View file

@ -632,7 +632,7 @@ export function RadioTraffic({
)}
<div className="mt-3 flex items-center justify-between">
<label htmlFor="radio-tick-sound" title="Only plays during Watch mode countdowns" className="flex cursor-pointer items-center gap-1.5 text-xs text-muted-foreground">
<label htmlFor="radio-tick-sound" title="Only plays during Watch mode countdowns" className="flex min-h-6 cursor-pointer items-center gap-1.5 text-xs text-muted-foreground">
<Volume2 className="size-3.5" /> Countdown tick sound
</label>
<Switch id="radio-tick-sound" checked={tickSoundEnabled} onCheckedChange={handleTickSoundChange} />

View file

@ -71,7 +71,7 @@ export function NpcDirectory({ npcs }: NpcDirectoryProps) {
checked={inGameOnly}
onCheckedChange={(checked) => setInGameOnly(checked === true)}
/>
<Label htmlFor="npc-in-game-only" className="cursor-pointer text-sm font-normal">
<Label htmlFor="npc-in-game-only" className="cursor-pointer py-1.5 text-sm font-normal">
In-game only
</Label>
</div>
@ -86,7 +86,7 @@ export function NpcDirectory({ npcs }: NpcDirectoryProps) {
checked={vendorsOnly}
onCheckedChange={(checked) => setVendorsOnly(checked === true)}
/>
<Label htmlFor="npc-vendors-only" className="cursor-pointer text-sm font-normal">
<Label htmlFor="npc-vendors-only" className="cursor-pointer py-1.5 text-sm font-normal">
Vendors only
</Label>
</div>

View file

@ -599,7 +599,7 @@ export function RosterView({
return (
<RosterViewerContext.Provider value={viewer}>
<RosterDisplayContext.Provider value={leadOrActual}>
<Tabs defaultValue="org">
<Tabs defaultValue="org" className="min-w-0">
<TabsList variant="line">
<TabsTrigger value="org" className="gap-1.5">
<NetworkIcon className="size-3" />

View file

@ -183,7 +183,7 @@ export function GuidedTour({ tour, gates, onDismiss, onSkipAll }: GuidedTourProp
<Button
variant="link"
size="sm"
className="h-auto p-0 text-xs text-muted-foreground"
className="h-auto min-h-6 px-0 text-xs text-muted-foreground"
onClick={onSkipAll}
>
Skip all tours on this device

View file

@ -251,7 +251,7 @@ export function WikiIndex({ pages, isModerator }: WikiIndexProps) {
<h2 className="group/cat flex items-baseline gap-2 px-1 text-xs font-semibold tracking-wider text-muted-foreground uppercase">
<Link
href={`/wiki/category/${group.category}`}
className="inline-flex items-center gap-1 transition-colors hover:text-foreground"
className="inline-flex items-center gap-1 py-1 transition-colors hover:text-foreground"
>
{group.category}
<ArrowRightIcon

View file

@ -47,7 +47,7 @@ const DialogContent = React.forwardRef<
>
{children}
{showCloseButton && (
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<DialogPrimitive.Close className="absolute right-3 top-3 rounded-sm p-1 opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>

View file

@ -142,7 +142,9 @@ function ItemHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="item-header"
className={cn("flex basis-full items-center justify-between gap-2", className)}
// min-w-0 lets long titles shrink instead of forcing the card (and page)
// wider than its container; children opt into truncation.
className={cn("flex min-w-0 basis-full items-center justify-between gap-2", className)}
{...props}
/>
);
@ -152,7 +154,7 @@ function ItemFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="item-footer"
className={cn("flex basis-full items-center justify-between gap-2", className)}
className={cn("flex min-w-0 basis-full items-center justify-between gap-2", className)}
{...props}
/>
);

View file

@ -9,7 +9,9 @@ import { cn } from "@/lib/utils";
const Tabs = TabsPrimitive.Root;
const tabsListVariants = cva(
"inline-flex items-center justify-center text-muted-foreground",
// max-w-full + overflow-x-auto keep multi-tab lists from widening the page
// on narrow screens: they scroll horizontally instead.
"inline-flex max-w-full items-center justify-center overflow-x-auto text-muted-foreground [scrollbar-width:none]",
{
variants: {
variant: {
@ -62,7 +64,7 @@ const TabsContent = React.forwardRef<
<TabsPrimitive.Content
ref={ref}
className={cn(
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
"mt-2 min-w-0 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
className,
)}
{...props}

View file

@ -0,0 +1,334 @@
import type { Payload } from "payload";
import type { Award, AwardRule, Profile } from "@/payload-types";
import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
import type { AwardGrantEntry } from "@/lib/awards";
import { getAwardsByIds, heldTierOfSeries } from "@/lib/awards/grant";
import {
qualifiesForRule,
resolveMetricValue,
sumProgressionXp,
type MemberFacts,
} from "@/lib/awards/metrics";
/** A single row in `profile.progression.awards` plus automation bookkeeping. */
type MutableGrantEntry = AwardGrantEntry & {
upgradedFrom?: number | null;
upgradedAt?: string | null;
};
export interface AutomationPlan {
ruleId: number;
ruleLabel: string;
userId: number;
username: string;
awardId: number;
awardName: string;
metricValue: number;
/** "upgrade" replaces a lower tier of the same series; "grant" appends. */
kind: "grant" | "upgrade";
/** For upgrades: the award id being replaced (auto-retire). */
replacesAwardId?: number;
}
export interface AutomationSkip {
ruleId: number;
userId: number;
reason: string;
}
export interface EvaluationResult {
dryRun: boolean;
rulesEvaluated: number;
membersChecked: number;
plans: AutomationPlan[];
skips: AutomationSkip[];
granted: number;
upgraded: number;
}
interface ProgressionShape {
awards?: MutableGrantEntry[] | null;
[key: string]: unknown;
}
function refId(ref: number | { id?: number } | null | undefined): number | null {
if (typeof ref === "number") return ref;
if (ref && typeof ref.id === "number") return ref.id;
return null;
}
function entryAwardId(entry: MutableGrantEntry): number | null {
return refId(entry.award);
}
async function paginate<T>(
run: (page: number) => Promise<{ docs: T[]; hasNextPage: boolean }>,
): Promise<T[]> {
const all: T[] = [];
let page = 1;
for (;;) {
const res = await run(page);
all.push(...res.docs);
if (!res.hasNextPage) break;
page += 1;
}
return all;
}
/**
* Evaluate every active award rule against every member profile and (unless
* dry-run) apply the resulting grants. Idempotent: members who already hold
* the award (or a higher series tier, or any series tier under oncePerSeries)
* are skipped, so re-running never double-grants. Grants land as ordinary
* profile rows with `awardedBy: null`, which the Profiles afterChange hook
* turns into award:granted notifications exactly like manual admin grants.
*/
export async function evaluateAwardRules(
payload: Payload,
options: { dryRun?: boolean; ruleIds?: number[] } = {},
): Promise<EvaluationResult> {
const dryRun = options.dryRun ?? false;
const now = new Date();
const rulesResult = await payload.find({
collection: "award-rules",
where: {
...(options.ruleIds?.length ? { id: { in: options.ruleIds } } : {}),
active: { equals: true },
},
depth: 1,
limit: 200,
overrideAccess: true,
});
const rules = rulesResult.docs.filter((rule): rule is AwardRule & { award: Award } =>
Boolean(rule.award && typeof rule.award !== "number"),
);
const profiles = await paginate((page) =>
payload.find({
collection: "profiles",
depth: 0,
limit: 500,
page,
overrideAccess: true,
}),
);
const users = await paginate((page) =>
payload.find({
collection: "users",
select: { username: true, displayName: true, createdAt: true },
depth: 0,
limit: 500,
page,
overrideAccess: true,
}),
);
const userById = new Map(users.map((user) => [user.id, user]));
// Missions attended = mission-attendances rows with response "yes".
const attendances = await paginate((page) =>
payload.find({
collection: "mission-attendances",
where: { response: { equals: "yes" } },
select: { user: true },
depth: 0,
limit: 1000,
page,
overrideAccess: true,
}),
);
const attendanceCounts = new Map<number, number>();
for (const row of attendances) {
const userId = refId(row.user as number | { id?: number });
if (userId !== null) {
attendanceCounts.set(userId, (attendanceCounts.get(userId) ?? 0) + 1);
}
}
// Every award referenced by any grant row on any profile, so series/tier
// lookups stay in-memory. One batch up front; plans mutate working copies
// only, so the set never grows mid-run.
const referencedAwardIds = new Set<number>();
for (const profile of profiles) {
for (const entry of (profile.progression as ProgressionShape | undefined)?.awards ?? []) {
const id = entryAwardId(entry);
if (id !== null) referencedAwardIds.add(id);
}
}
for (const rule of rules) referencedAwardIds.add((rule.award as Award).id);
const allAwards = await getAwardsByIds(payload, [...referencedAwardIds]);
const awardById = new Map(allAwards.map((award) => [award.id, award]));
// Working copies so multiple rules against the same profile compose within
// one run (e.g. tier 1 grants, then tier 2 upgrades it) and stay idempotent.
const workingAwards = new Map<number, MutableGrantEntry[]>();
const dirtyProfiles = new Map<number, Profile>();
const plans: AutomationPlan[] = [];
const skips: AutomationSkip[] = [];
// Evaluate lower tiers first so an upgrade chain resolves in one pass.
const orderedRules = [...rules].sort(
(a, b) =>
((a.award as Award).advancement?.tier ?? 0) - ((b.award as Award).advancement?.tier ?? 0),
);
for (const rule of orderedRules) {
const award = rule.award as Award;
for (const profile of profiles) {
const userId = refId(profile.user as number | { id?: number });
if (userId === null) continue;
const user = userById.get(userId);
if (!user) continue;
const facts: MemberFacts = {
enlistmentDate: profile.dossier?.enlistmentDate ?? null,
accountCreatedAt: user.createdAt,
missionsAttended: attendanceCounts.get(userId) ?? 0,
xpTotal: sumProgressionXp(profile.progression),
};
if (!qualifiesForRule(rule, facts, now)) continue;
let current = workingAwards.get(profile.id);
if (!current) {
current = [
...(((profile.progression as ProgressionShape | undefined)?.awards ?? []) as MutableGrantEntry[]),
];
workingAwards.set(profile.id, current);
}
const heldIds = current
.map(entryAwardId)
.filter((id): id is number => id !== null);
// Already holds this exact award: nothing to do, ever.
if (heldIds.includes(award.id)) {
skips.push({ ruleId: rule.id, userId, reason: "already-held" });
continue;
}
const seriesKey = award.advancement?.seriesKey;
const targetTier = award.advancement?.tier ?? null;
let heldSeriesTier: { tier: number; entry: MutableGrantEntry; awardId: number } | null =
null;
if (seriesKey) {
for (const entry of current) {
const heldAwardId = entryAwardId(entry);
if (heldAwardId === null) continue;
const heldAward = awardById.get(heldAwardId);
if (!heldAward) continue;
const tier = heldTierOfSeries(heldAward, seriesKey);
if (tier !== null) {
heldSeriesTier = { tier, entry, awardId: heldAwardId };
break;
}
}
}
if (heldSeriesTier && targetTier !== null) {
if (heldSeriesTier.tier >= targetTier) {
skips.push({ ruleId: rule.id, userId, reason: "higher-or-equal-tier-held" });
continue;
}
if (!rule.autoRetireLowerTiers) {
skips.push({
ruleId: rule.id,
userId,
reason: rule.oncePerSeries ? "once-per-series" : "series-tier-held",
});
continue;
}
// Auto-retire: replace the lower tier in place, preserving the date
// the member first earned the series (mirrors the manual upgrade).
const index = current.indexOf(heldSeriesTier.entry);
current[index] = {
...heldSeriesTier.entry,
award: award.id,
awardedBy: null,
awardReason: rule.label,
upgradedFrom: heldSeriesTier.awardId,
upgradedAt: now.toISOString(),
};
plans.push({
ruleId: rule.id,
ruleLabel: rule.label,
userId,
username: user.displayName || user.username || String(userId),
awardId: award.id,
awardName: award.name,
metricValue: resolveMetricValue(rule.metric, facts, now),
kind: "upgrade",
replacesAwardId: heldSeriesTier.awardId,
});
dirtyProfiles.set(profile.id, profile);
continue;
}
if (rule.oncePerSeries && heldSeriesTier) {
skips.push({ ruleId: rule.id, userId, reason: "once-per-series" });
continue;
}
current.push({
award: award.id,
awardedBy: null,
awardedAt: now.toISOString(),
awardReason: rule.label,
});
plans.push({
ruleId: rule.id,
ruleLabel: rule.label,
userId,
username: user.displayName || user.username || String(userId),
awardId: award.id,
awardName: award.name,
metricValue: resolveMetricValue(rule.metric, facts, now),
kind: "grant",
});
dirtyProfiles.set(profile.id, profile);
}
}
let granted = 0;
let upgraded = 0;
if (!dryRun) {
for (const profile of dirtyProfiles.values()) {
const awards = workingAwards.get(profile.id) ?? [];
await payload.update({
collection: "profiles",
id: profile.id,
data: {
progression: {
...((profile.progression as ProgressionShape | undefined) ?? {}),
awards,
},
} as unknown as Partial<Profile>,
overrideAccess: true,
});
}
for (const plan of plans) {
if (plan.kind === "upgrade") upgraded += 1;
else granted += 1;
await emitGameEvent(payload, {
type: EventTypes.AwardRuleGranted,
message: `${plan.username} automatically received "${plan.awardName}" (${plan.ruleLabel})`,
targetCollection: "awards",
targetId: plan.awardId,
data: { ruleId: plan.ruleId, kind: plan.kind },
});
}
}
return {
dryRun,
rulesEvaluated: orderedRules.length,
membersChecked: profiles.length,
plans,
skips,
granted,
upgraded,
};
}

View file

@ -0,0 +1,60 @@
"use server";
import config from "@payload-config";
import { getPayload } from "payload";
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
import { hasPermission } from "@/utils/access-control/hasPermission";
import { evaluateAwardRules, type EvaluationResult } from "@/lib/awards/automation";
async function authorizeEvaluation() {
const payloadConfig = await config;
const payload = await getPayload({ config: payloadConfig });
const { headers } = await import("next/headers");
const hdrs = await headers();
const { user } = await payload.auth({ headers: hdrs, canSetHeaders: false });
if (!isPayloadUser(user)) {
return { ok: false as const, error: "You must be logged in." };
}
if (!(await hasPermission(payload, user, "award-rules:update"))) {
return { ok: false as const, error: "Missing award-rules:update permission." };
}
return { ok: true as const, payload };
}
/**
* Server actions behind the admin Award Automation view. Both require
* award-rules:update; the dry run is the who-qualifies preview and the apply
* run performs the actual grants (idempotent either way).
*/
export async function runAwardEvaluation(): Promise<
{ success: true; result: EvaluationResult } | { success: false; error: string }
> {
try {
const auth = await authorizeEvaluation();
if (!auth.ok) return { success: false, error: auth.error };
const result = await evaluateAwardRules(auth.payload, { dryRun: true });
return { success: true, result };
} catch (e) {
return {
success: false,
error: e instanceof Error ? e.message : "Unknown error",
};
}
}
export async function applyAwardGrants(): Promise<
{ success: true; result: EvaluationResult } | { success: false; error: string }
> {
try {
const auth = await authorizeEvaluation();
if (!auth.ok) return { success: false, error: auth.error };
const result = await evaluateAwardRules(auth.payload, { dryRun: false });
return { success: true, result };
} catch (e) {
return {
success: false,
error: e instanceof Error ? e.message : "Unknown error",
};
}
}

112
src/lib/awards/metrics.ts Normal file
View file

@ -0,0 +1,112 @@
/**
* Award automation metric resolvers. Pure module (no Payload import): the
* sweeper gathers raw `MemberFacts` per profile, and everything derived from
* them (metric values, threshold comparisons) is computed here so it is unit
* testable without a database.
*/
export const AWARD_METRICS = [
"yearsOfService",
"accountAge",
"missionsAttended",
"xpTotal",
] as const;
export type AwardMetric = (typeof AWARD_METRICS)[number];
export const METRIC_LABELS: Record<AwardMetric, string> = {
yearsOfService: "Years of Service",
accountAge: "Account Age (years)",
missionsAttended: "Missions Attended",
xpTotal: "Total XP",
};
export const METRIC_OPERATORS = ["gte", "gt"] as const;
export type MetricOperator = (typeof METRIC_OPERATORS)[number];
export const OPERATOR_LABELS: Record<MetricOperator, string> = {
gte: "at least",
gt: "more than",
};
/** Raw facts the sweeper collects per member; all metrics derive from these. */
export interface MemberFacts {
/** profile.dossier.enlistmentDate when set; account age is the fallback. */
enlistmentDate: string | null;
/** users.createdAt */
accountCreatedAt: string;
/** Count of mission-attendances rows with response "yes". */
missionsAttended: number;
/** Sum of every progression xpEarned bucket (minigames, voiceover, contributions). */
xpTotal: number;
}
const MS_PER_YEAR = 365.25 * 24 * 60 * 60 * 1000;
/** Whole-and-fractional years between a date and `now`, clamped at 0. */
export function yearsBetween(from: string | Date | null | undefined, now: Date): number {
if (!from) return 0;
const t = typeof from === "string" ? Date.parse(from) : from.getTime();
if (!Number.isFinite(t)) return 0;
return Math.max(0, (now.getTime() - t) / MS_PER_YEAR);
}
export function resolveMetricValue(metric: AwardMetric, facts: MemberFacts, now: Date): number {
switch (metric) {
case "yearsOfService":
// Enlistment date is the service clock; accounts without one age from
// registration so long-standing members are never unfairly gated out.
return yearsBetween(facts.enlistmentDate ?? facts.accountCreatedAt, now);
case "accountAge":
return yearsBetween(facts.accountCreatedAt, now);
case "missionsAttended":
return facts.missionsAttended;
case "xpTotal":
return facts.xpTotal;
}
}
export function applyOperator(operator: MetricOperator, actual: number, threshold: number): boolean {
return operator === "gt" ? actual > threshold : actual >= threshold;
}
export interface RuleThreshold {
metric: AwardMetric;
operator: MetricOperator;
value: number;
}
export function qualifiesForRule(rule: RuleThreshold, facts: MemberFacts, now: Date): boolean {
const actual = resolveMetricValue(rule.metric, facts, now);
return applyOperator(rule.operator, actual, rule.value);
}
interface XpBucketLike {
xpEarned?: number | null;
}
interface ProgressionLike {
minigames?: Record<string, XpBucketLike | null | undefined> | null;
voiceover?: XpBucketLike | null;
contributions?: XpBucketLike | null;
}
function bucketXp(bucket: XpBucketLike | null | undefined): number {
const value = bucket?.xpEarned;
return typeof value === "number" && Number.isFinite(value) ? value : 0;
}
/**
* Total XP across every progression bucket, mirroring the virtual `xp` field
* on Profiles (minigame buckets + voiceover + contributions). Accepts the raw
* progression group so it can run depth-0 without the virtual hook.
*/
export function sumProgressionXp(progression: unknown): number {
const p = progression as ProgressionLike | null | undefined;
if (!p) return 0;
let total = bucketXp(p.voiceover) + bucketXp(p.contributions);
for (const bucket of Object.values(p.minigames ?? {})) {
total += bucketXp(bucket);
}
return total;
}

View file

@ -0,0 +1,36 @@
/**
* Plain-text excerpt extraction from Lexical document JSON. Pure module so
* list pages and tests can use it without React or Payload.
*/
interface LexicalNodeLike {
type?: string;
text?: string;
children?: LexicalNodeLike[];
}
function collectText(node: LexicalNodeLike, parts: string[], limit: number): boolean {
if (node.type === "text" && typeof node.text === "string") {
parts.push(node.text);
return parts.join("").length >= limit;
}
for (const child of node.children ?? []) {
if (collectText(child, parts, limit)) return true;
}
return false;
}
/**
* Flattens the first `maxLength` characters of visible text out of a Lexical
* editor state. Returns "" for empty/invalid input.
*/
export function extractExcerpt(body: unknown, maxLength = 180): string {
const root = (body as { root?: LexicalNodeLike } | null)?.root;
if (!root || !Array.isArray(root.children)) return "";
const parts: string[] = [];
collectText(root, parts, maxLength);
const text = parts.join("").replace(/\s+/g, " ").trim();
if (text.length <= maxLength) return text;
return `${text.slice(0, maxLength - 1).trimEnd()}…`;
}

74
src/lib/sidebar/order.ts Normal file
View file

@ -0,0 +1,74 @@
/**
* Sidebar section registry and order vocabulary. Pure module (no React, no
* Payload import) so both the sidebar client component and server actions can
* use it. Modeled on src/lib/dashboard/layout.ts.
*/
export const SIDEBAR_SECTION_IDS = [
"platform",
"map",
"intelligence",
"operations",
"infrastructure",
"chronicle",
"surveys",
"helpdesk",
"commerce",
"personal",
] as const;
export type SidebarSectionId = (typeof SIDEBAR_SECTION_IDS)[number];
export const DEFAULT_SIDEBAR_ORDER: readonly SidebarSectionId[] = [...SIDEBAR_SECTION_IDS];
export const SIDEBAR_SECTION_LABELS: Record<SidebarSectionId, string> = {
platform: "Platform",
map: "Map",
intelligence: "Intelligence",
operations: "Operations",
infrastructure: "Infrastructure",
chronicle: "Chronicle",
surveys: "Surveys",
helpdesk: "Helpdesk",
commerce: "Commerce",
personal: "Personal",
};
export function isSidebarSectionId(value: unknown): value is SidebarSectionId {
return (
typeof value === "string" && (SIDEBAR_SECTION_IDS as readonly string[]).includes(value)
);
}
/** Sections that always render first and cannot be reordered by users. */
export const PINNED_SIDEBAR_SECTION_IDS: readonly SidebarSectionId[] = ["platform"];
/**
* Sanitizes an arbitrary stored order into a valid full section list: drops
* unknown/duplicate ids, keeps known ones in the user's order, appends any
* missing sections at the end in default order, and moves pinned sections
* (Platform) to the front. Non-array input falls back to the default order.
*/
export function normalizeSidebarOrder(raw: unknown): SidebarSectionId[] {
if (!Array.isArray(raw)) {
return [...DEFAULT_SIDEBAR_ORDER];
}
const seen = new Set<SidebarSectionId>();
const ordered: SidebarSectionId[] = [];
for (const entry of raw) {
if (isSidebarSectionId(entry) && !seen.has(entry)) {
seen.add(entry);
ordered.push(entry);
}
}
for (const id of DEFAULT_SIDEBAR_ORDER) {
if (!seen.has(id)) {
ordered.push(id);
}
}
const pinned = PINNED_SIDEBAR_SECTION_IDS.filter((id) => ordered.includes(id));
const rest = ordered.filter((id) => !PINNED_SIDEBAR_SECTION_IDS.includes(id));
return [...pinned, ...rest];
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,11 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "users" ADD COLUMN "preferences_display_sidebar_order" jsonb;`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "users" DROP COLUMN "preferences_display_sidebar_order";`)
}

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,14 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TYPE "public"."enum_game_event_logs_target_collection" ADD VALUE 'journals' BEFORE 'story-beat-states';`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "game_event_logs" ALTER COLUMN "target_collection" SET DATA TYPE text;
DROP TYPE "public"."enum_game_event_logs_target_collection";
CREATE TYPE "public"."enum_game_event_logs_target_collection" AS ENUM('game-structures', 'game-vehicles', 'game-npcs', 'npc-staffing', 'structures', 'resources', 'assets', 'vehicles', 'factions', 'missions', 'campaigns', 'users', 'technologies', 'maps', 'shipments', 'bank-accounts', 'bank-transactions', 'ledger-entries', 'locker-storages', 'loadouts', 'market-listings', 'market-negotiations', 'market-state', 'evaluations', 'tickets', 'wiki-pages', 'wiki-revisions', 'wiki-templates', 'form-submissions', 'mission-map-markers', 'contribution-entries', 'game-servers', 'assignment-transfers', 'voice-scripts', 'voice-submissions', 'story-beats', 'story-beat-states', 'custom-minefields', 'custom-minefield-scores', 'custom-radio-tests', 'custom-radio-test-scores', 'ribbon-submissions', 'promotion-nominations', 'leadership-transfers', 'player-flags', 'reinforcement-pools');
ALTER TABLE "game_event_logs" ALTER COLUMN "target_collection" SET DATA TYPE "public"."enum_game_event_logs_target_collection" USING "target_collection"::"public"."enum_game_event_logs_target_collection";`)
}

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -128,6 +128,10 @@ import * as migration_20261012_014741_add_call_for_fire_versus from './20261012_
import * as migration_20261012_015000_seed_call_for_fire_versus_registry from './20261012_015000_seed_call_for_fire_versus_registry';
import * as migration_20261012_030000_update_call_for_fire_versus_wording from './20261012_030000_update_call_for_fire_versus_wording';
import * as migration_20261012_134242_add_discord_presence_global from './20261012_134242_add_discord_presence_global';
import * as migration_20261012_173511_add_sidebar_order_preference from './20261012_173511_add_sidebar_order_preference';
import * as migration_20261012_181310_add_journals_collection from './20261012_181310_add_journals_collection';
import * as migration_20261012_182016_add_journals_event_target from './20261012_182016_add_journals_event_target';
import * as migration_20261012_185409_add_award_rules_automation from './20261012_185409_add_award_rules_automation';
export const migrations = [
{
@ -778,6 +782,26 @@ export const migrations = [
{
up: migration_20261012_134242_add_discord_presence_global.up,
down: migration_20261012_134242_add_discord_presence_global.down,
name: '20261012_134242_add_discord_presence_global'
name: '20261012_134242_add_discord_presence_global',
},
{
up: migration_20261012_173511_add_sidebar_order_preference.up,
down: migration_20261012_173511_add_sidebar_order_preference.down,
name: '20261012_173511_add_sidebar_order_preference',
},
{
up: migration_20261012_181310_add_journals_collection.up,
down: migration_20261012_181310_add_journals_collection.down,
name: '20261012_181310_add_journals_collection',
},
{
up: migration_20261012_182016_add_journals_event_target.up,
down: migration_20261012_182016_add_journals_event_target.down,
name: '20261012_182016_add_journals_event_target',
},
{
up: migration_20261012_185409_add_award_rules_automation.up,
down: migration_20261012_185409_add_award_rules_automation.down,
name: '20261012_185409_add_award_rules_automation'
},
];

View file

@ -85,6 +85,7 @@ export interface Config {
ranks: Rank;
profiles: Profile;
awards: Award;
'award-rules': AwardRule;
qualifications: Qualification;
assignments: Assignment;
'assignment-transfers': AssignmentTransfer;
@ -135,6 +136,7 @@ export interface Config {
'story-beats': StoryBeat;
'story-beat-states': StoryBeatState;
'story-voiceovers': StoryVoiceover;
journals: Journal;
'mission-files': MissionFile;
'mod-lists': ModList;
'game-servers': GameServer;
@ -190,6 +192,7 @@ export interface Config {
ranks: RanksSelect<false> | RanksSelect<true>;
profiles: ProfilesSelect<false> | ProfilesSelect<true>;
awards: AwardsSelect<false> | AwardsSelect<true>;
'award-rules': AwardRulesSelect<false> | AwardRulesSelect<true>;
qualifications: QualificationsSelect<false> | QualificationsSelect<true>;
assignments: AssignmentsSelect<false> | AssignmentsSelect<true>;
'assignment-transfers': AssignmentTransfersSelect<false> | AssignmentTransfersSelect<true>;
@ -240,6 +243,7 @@ export interface Config {
'story-beats': StoryBeatsSelect<false> | StoryBeatsSelect<true>;
'story-beat-states': StoryBeatStatesSelect<false> | StoryBeatStatesSelect<true>;
'story-voiceovers': StoryVoiceoversSelect<false> | StoryVoiceoversSelect<true>;
journals: JournalsSelect<false> | JournalsSelect<true>;
'mission-files': MissionFilesSelect<false> | MissionFilesSelect<true>;
'mod-lists': ModListsSelect<false> | ModListsSelect<true>;
'game-servers': GameServersSelect<false> | GameServersSelect<true>;
@ -504,6 +508,18 @@ export interface User {
showVersionOverlay?: boolean | null;
xpDisplayMini?: boolean | null;
showBackgroundTexture?: boolean | null;
/**
* Ordered sidebar section ids, saved by the sidebar customize mode
*/
sidebarOrder?:
| {
[k: string]: unknown;
}
| unknown[]
| string
| number
| boolean
| null;
};
discord?: {
enabled?: boolean | null;
@ -628,6 +644,16 @@ export interface Role {
| 'awards:update'
| 'awards:delete'
| 'admin:awards:manage'
| 'journals:create'
| 'journals:read'
| 'journals:update'
| 'journals:delete'
| 'admin:journals:manage'
| 'award-rules:create'
| 'award-rules:read'
| 'award-rules:update'
| 'award-rules:delete'
| 'admin:award-rules:manage'
| 'qualifications:create'
| 'qualifications:read'
| 'qualifications:update'
@ -2739,6 +2765,16 @@ export interface GameEventLog {
| 'awards:update'
| 'awards:delete'
| 'admin:awards:manage'
| 'journals:create'
| 'journals:read'
| 'journals:update'
| 'journals:delete'
| 'admin:journals:manage'
| 'award-rules:create'
| 'award-rules:read'
| 'award-rules:update'
| 'award-rules:delete'
| 'admin:award-rules:manage'
| 'qualifications:create'
| 'qualifications:read'
| 'qualifications:update'
@ -3130,6 +3166,8 @@ export interface GameEventLog {
| 'voice-scripts'
| 'voice-submissions'
| 'story-beats'
| 'journals'
| 'awards'
| 'story-beat-states'
| 'custom-minefields'
| 'custom-minefield-scores'
@ -3505,6 +3543,43 @@ export interface Qualification {
updatedAt: string;
createdAt: string;
}
/**
* Automation rules that grant awards when a member's metric crosses a threshold. Evaluated by the daily award tick and the Evaluate Now view.
*
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "award-rules".
*/
export interface AwardRule {
id: number;
/**
* Short rule name shown in previews and feed events (e.g. "2 years of service").
*/
label: string;
/**
* The award granted when the rule fires.
*/
award: number | Award;
metric: 'yearsOfService' | 'accountAge' | 'missionsAttended' | 'xpTotal';
operator: 'gte' | 'gt';
/**
* Threshold compared against the metric (years for time-based metrics, counts otherwise).
*/
value: number;
/**
* For awards in an advancement series: replace any lower tier the member already holds with this award, preserving their original award date.
*/
autoRetireLowerTiers?: boolean | null;
/**
* Skip members who already hold any award in this award's advancement series (use instead of auto-retire when tiers must not stack or upgrade).
*/
oncePerSeries?: boolean | null;
/**
* Inactive rules are ignored by the sweeper.
*/
active?: boolean | null;
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "assignment-transfers".
@ -5450,6 +5525,52 @@ export interface StoryBeatState {
updatedAt: string;
createdAt: string;
}
/**
* Member-written journals. Drafts are visible to their author and staff only; published entries are readable by any logged-in user on /journals.
*
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "journals".
*/
export interface Journal {
id: number;
title: string;
/**
* Owning member. Authors can always edit their own entries.
*/
author: number | User;
/**
* Authors publish directly; no staff review is required.
*/
status: 'draft' | 'published';
/**
* Optional in-world date shown with the entry. Does not affect list order.
*/
occurredAt?: string | null;
/**
* Optional mission this entry relates to. Entries may stand alone.
*/
mission?: (number | null) | Mission;
/**
* Rich text body of the entry, rendered on /journals with the Lexical renderer.
*/
body: {
root: {
type: string;
children: {
type: any;
version: number;
[k: string]: unknown;
}[];
direction: ('ltr' | 'rtl') | null;
format: 'left' | 'start' | 'center' | 'right' | 'end' | 'justify' | '';
indent: number;
version: number;
};
[k: string]: unknown;
};
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "game-servers".
@ -6725,6 +6846,24 @@ export interface PayloadMcpApiKey {
*/
delete?: boolean | null;
};
awardRules?: {
/**
* Allow clients to find award-rules.
*/
find?: boolean | null;
/**
* Allow clients to create award-rules.
*/
create?: boolean | null;
/**
* Allow clients to update award-rules.
*/
update?: boolean | null;
/**
* Allow clients to delete award-rules.
*/
delete?: boolean | null;
};
qualifications?: {
/**
* Allow clients to find qualifications.
@ -7625,6 +7764,24 @@ export interface PayloadMcpApiKey {
*/
delete?: boolean | null;
};
journals?: {
/**
* Allow clients to find journals.
*/
find?: boolean | null;
/**
* Allow clients to create journals.
*/
create?: boolean | null;
/**
* Allow clients to update journals.
*/
update?: boolean | null;
/**
* Allow clients to delete journals.
*/
delete?: boolean | null;
};
missionFiles?: {
/**
* Allow clients to find mission-files.
@ -8084,6 +8241,10 @@ export interface PayloadLockedDocument {
relationTo: 'awards';
value: number | Award;
} | null)
| ({
relationTo: 'award-rules';
value: number | AwardRule;
} | null)
| ({
relationTo: 'qualifications';
value: number | Qualification;
@ -8284,6 +8445,10 @@ export interface PayloadLockedDocument {
relationTo: 'story-voiceovers';
value: number | StoryVoiceover;
} | null)
| ({
relationTo: 'journals';
value: number | Journal;
} | null)
| ({
relationTo: 'mission-files';
value: number | MissionFile;
@ -8814,6 +8979,7 @@ export interface UsersSelect<T extends boolean = true> {
showVersionOverlay?: T;
xpDisplayMini?: T;
showBackgroundTexture?: T;
sidebarOrder?: T;
};
discord?:
| T
@ -9078,6 +9244,22 @@ export interface AwardsSelect<T extends boolean = true> {
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "award-rules_select".
*/
export interface AwardRulesSelect<T extends boolean = true> {
label?: T;
award?: T;
metric?: T;
operator?: T;
value?: T;
autoRetireLowerTiers?: T;
oncePerSeries?: T;
active?: T;
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "qualifications_select".
@ -10466,6 +10648,20 @@ export interface StoryVoiceoversSelect<T extends boolean = true> {
focalX?: T;
focalY?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "journals_select".
*/
export interface JournalsSelect<T extends boolean = true> {
title?: T;
author?: T;
status?: T;
occurredAt?: T;
mission?: T;
body?: T;
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "mission-files_select".
@ -11189,6 +11385,14 @@ export interface PayloadMcpApiKeysSelect<T extends boolean = true> {
update?: T;
delete?: T;
};
awardRules?:
| T
| {
find?: T;
create?: T;
update?: T;
delete?: T;
};
qualifications?:
| T
| {
@ -11589,6 +11793,14 @@ export interface PayloadMcpApiKeysSelect<T extends boolean = true> {
update?: T;
delete?: T;
};
journals?:
| T
| {
find?: T;
create?: T;
update?: T;
delete?: T;
};
missionFiles?:
| T
| {

View file

@ -11,6 +11,7 @@ import nodemailer from "nodemailer";
import { Users } from "@/collections/users/Users";
import { Roles } from "@/collections/users/Roles";
import { Awards } from "@/collections/users/Awards";
import { AwardRules } from "@/collections/users/AwardRules";
import { Media } from "@/collections/Media";
import { Ranks } from "@/collections/users/Ranks";
import { Profiles } from "@/collections/users/Profiles";
@ -83,6 +84,7 @@ import { Sprints } from "@/collections/projects/Sprints";
import { Releases } from "@/collections/projects/Releases";
import { Labels } from "@/collections/projects/Labels";
import { StoryBeats } from "@/collections/story/StoryBeats";
import { Journals } from "@/collections/story/Journals";
import { StoryBeatStates } from "@/collections/story/StoryBeatStates";
import { Voiceovers } from "@/collections/story/Voiceovers";
import { Shims } from "@/collections/Shims";
@ -289,6 +291,7 @@ const collections = [
Ranks,
Profiles,
Awards,
AwardRules,
Qualifications,
Assignments,
AssignmentTransfers,
@ -361,6 +364,7 @@ const collections = [
StoryBeats,
StoryBeatStates,
Voiceovers,
Journals,
// Server
MissionFiles,
@ -445,6 +449,18 @@ export default buildConfig({
],
},
// Overrides the built-in collection-cards grid on the admin dashboard
// (Payload appends its default `collections` widget after user widgets and
// resolves by first match). Same grid + permissions, plus lucide icons.
dashboard: {
widgets: [
{
slug: "collections",
Component: "@/components/admin/dashboard/CollectionCards",
minWidth: "full",
},
],
},
components: {
beforeDashboard: ["@/components/static/BeforeDashboardText"],
header: ["@/components/static/VersionOverlay"],
@ -513,6 +529,10 @@ export default buildConfig({
scriptPath: path.resolve(dirname, "scripts/periodTick.ts"),
key: "period-tick",
},
{
scriptPath: path.resolve(dirname, "scripts/awardTick.ts"),
key: "award-tick",
},
{
scriptPath: path.resolve(dirname, "scripts/generateNextMission.ts"),
key: "generate-mission",

View file

@ -102,6 +102,26 @@ export const PERMISSION_GROUPS: PermissionGroup[] = [
{ value: "admin:awards:manage", label: "Manage Admin Page" },
],
},
{
group: "Journals",
permissions: [
{ value: "journals:create", label: "Create" },
{ value: "journals:read", label: "Read (staff: all entries incl. drafts)" },
{ value: "journals:update", label: "Update (staff: any entry)" },
{ value: "journals:delete", label: "Delete (staff: any entry)" },
{ value: "admin:journals:manage", label: "Manage Admin Page" },
],
},
{
group: "Award Rules",
permissions: [
{ value: "award-rules:create", label: "Create" },
{ value: "award-rules:read", label: "Read" },
{ value: "award-rules:update", label: "Update (also runs Evaluate Now / Apply)" },
{ value: "award-rules:delete", label: "Delete" },
{ value: "admin:award-rules:manage", label: "Manage Admin Page" },
],
},
{
group: "Qualifications",
permissions: [
@ -846,6 +866,16 @@ export const ALL_PERMISSION_VALUES = PERMISSION_GROUPS.flatMap((g) =>
"awards:update",
"awards:delete",
"admin:awards:manage",
"journals:create",
"journals:read",
"journals:update",
"journals:delete",
"admin:journals:manage",
"award-rules:create",
"award-rules:read",
"award-rules:update",
"award-rules:delete",
"admin:award-rules:manage",
"qualifications:create",
"qualifications:read",
"qualifications:update",

23
src/scripts/awardTick.ts Normal file
View file

@ -0,0 +1,23 @@
import type { SanitizedConfig } from "payload";
import { getPayload } from "payload";
import { evaluateAwardRules } from "@/lib/awards/automation";
import { createBinLogger, errorMessage } from "./lib/binFileLogger";
export const script = async (config: SanitizedConfig) => {
const payload = await getPayload({ config });
const log = createBinLogger("award-tick", payload.logger);
try {
log.info("[Award Tick] Evaluating award rules...");
const result = await evaluateAwardRules(payload);
log.info(
`[Award Tick] Complete. Rules ${result.rulesEvaluated}; members ${result.membersChecked}; granted ${result.granted}; upgraded ${result.upgraded}; skipped ${result.skips.length}.`,
);
process.exit(0);
} catch (error) {
log.error(
`[Award Tick] Fatal: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`,
);
process.exit(1);
}
};

View file

@ -0,0 +1,150 @@
/**
* Seeds the years-of-service advancement series and its automation rules.
*
* - Wires the existing "First/Two/Three/Five Years of Service" ribbons into
* one advancement series (seriesKey "years-of-service", tier = years).
* - Creates one active award-rule per ribbon: yearsOfService >= <years>,
* auto-retiring the lower tier so anniversaries upgrade the member's ribbon
* in place instead of stacking.
*
* Idempotent: re-running updates nothing that already exists. Pass
* --create-missing to create the ribbons first (local dev databases only;
* production already has them).
*
* Usage: bun src/tools/seed/seedYearsOfServiceRules.ts [--create-missing]
*/
import { getPayload } from "payload";
import config from "@payload-config";
import type { Award } from "@/payload-types";
const SERIES_KEY = "years-of-service";
const PLAN: ReadonlyArray<{ name: string; tier: number; threshold: number }> = [
{ name: "First Year of Service", tier: 1, threshold: 1 },
{ name: "Two Years of Service", tier: 2, threshold: 2 },
{ name: "Three Years of Service", tier: 3, threshold: 3 },
{ name: "Five Years of Service", tier: 5, threshold: 5 },
];
function richText(text: string) {
return {
root: {
type: "root" as const,
format: "" as const,
indent: 0,
version: 1,
children: [
{
type: "paragraph" as const,
format: "" as const,
indent: 0,
version: 1,
direction: "ltr" as const,
children: [
{
type: "text" as const,
format: 0,
style: "",
mode: "normal" as const,
text,
version: 1,
},
],
},
],
direction: "ltr" as const,
},
};
}
async function main() {
const payload = await getPayload({ config });
const createMissing = process.argv.includes("--create-missing");
for (const entry of PLAN) {
const found = await payload.find({
collection: "awards",
where: { name: { equals: entry.name } },
limit: 1,
depth: 0,
overrideAccess: true,
});
let award = found.docs[0] as Award | undefined;
if (!award && createMissing) {
award = (await payload.create({
collection: "awards",
data: {
name: entry.name,
description: richText(`Awarded for ${entry.threshold} full years of service.`),
type: "ribbon",
},
overrideAccess: true,
depth: 0,
})) as unknown as Award;
payload.logger.info(`Created ribbon "${entry.name}"`);
}
if (!award) {
payload.logger.warn(`Ribbon "${entry.name}" not found; skipping.`);
continue;
}
if (award.advancement?.seriesKey !== SERIES_KEY || award.advancement?.tier !== entry.tier) {
await payload.update({
collection: "awards",
id: award.id,
data: { advancement: { seriesKey: SERIES_KEY, tier: entry.tier } },
overrideAccess: true,
depth: 0,
});
payload.logger.info(
`Wired "${entry.name}" into series ${SERIES_KEY} at tier ${entry.tier}`,
);
}
const label = `Auto: ${entry.name.toLowerCase()}`;
const existingRule = await payload.find({
collection: "award-rules",
where: { label: { equals: label } },
limit: 1,
depth: 0,
overrideAccess: true,
});
if (existingRule.docs.length > 0) {
payload.logger.info(`Rule "${label}" already exists; skipping.`);
continue;
}
await payload.create({
collection: "award-rules",
data: {
label,
award: award.id,
metric: "yearsOfService",
operator: "gte",
value: entry.threshold,
autoRetireLowerTiers: entry.tier > 1,
oncePerSeries: false,
active: true,
},
overrideAccess: true,
depth: 0,
});
payload.logger.info(
`Created rule "${label}" (yearsOfService >= ${entry.threshold}${
entry.tier > 1 ? ", auto-retire lower tiers" : ""
})`,
);
}
payload.logger.info("Years-of-service rules seed complete.");
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

View file

@ -55,7 +55,9 @@ interface GameEventInput {
| "reinforcement-pools"
| "form-submissions"
| "mission-map-markers"
| "contribution-entries";
| "contribution-entries"
| "journals"
| "awards";
targetId?: number;
data?: Record<string, unknown>;
/**

View file

@ -208,6 +208,14 @@ export const EventTypes = {
StoryBeatRead: "story:beat-read",
StoryBeatReact: "story:beat-react",
// Journals
JournalCreated: "journal:created",
JournalUpdated: "journal:updated",
JournalDeleted: "journal:deleted",
// Award automation
AwardRuleGranted: "award:rule-granted",
// Projects
ProjectCreate: "project:create",
ProjectUpdate: "project:update",

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,591 @@
# Mobile audit (390x844) - 2026-10-13T03:01:26.663Z
Base: http://localhost:3000 | routes audited: 78 (ok: 68)
| Pattern class | Routes affected | Findings |
|---|---|---|
| tapTargetMarginal | 68 | 611 |
| hiddenMobile | 1 | 1 |
| tapTargetInlineText | 1 | 6 |
## tapTargetMarginal: pattern clusters
| Selector shape | Findings | Routes | Example |
|---|---|---|---|
| `button.inline-flex.items-center.justify-center` | 363 | 68 | 28x28px "Toggle Sidebar" |
| `a.flex.w-fit.items-center` | 10 | 10 | 42x28px "Wiki" |
| `input.flex.h-9.w-full` | 15 | 9 | 300x36px |
| `a.inline-flex.items-center.justify-center` | 7 | 6 | 111x32px "Design a ribbon" |
| `button.rounded-md.px-2.5.py-1` | 12 | 6 | 82x24px "This period" |
| `a.ml-auto.py-1.pr-1` | 6 | 6 | 60x24px "All boards" |
| `button.flex.h-9.items-center` | 8 | 4 | 160x36px "All rarities" |
| `a.py-1.text-sm.text-muted-foreground` | 4 | 4 | 50x28px "Back" |
| `button.flex.items-center.justify-between` | 6 | 3 | 176x32px "All targets" |
| `label.text-sm.font-medium.leading-none` | 3 | 2 | 33x26px (via label[for]) |
| `label.peer-disabled:cursor-not-allowed.peer-disabled:opacity` | 27 | 2 | 226x24px (via label) "Mute market offers" |
| `input.flex.h-9.rounded-md` | 3 | 2 | 144x36px "From date" |
## hiddenMobile: pattern clusters
| Selector shape | Findings | Routes | Example |
|---|---|---|---|
| `span.hidden.font-mono.text-[10px]` | 1 | 1 | hidden on mobile (md:/lg: reveal) |
## tapTargetInlineText: pattern clusters
| Selector shape | Findings | Routes | Example |
|---|---|---|---|
| `a.font-medium.text-primary.underline` | 6 | 1 | 61x19px "The Map" |
---
# Per-route detail
## tapTargetMarginal
### /
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 32x32px "Replay page tour" `div.ml-auto.flex.items-center > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 24x24px "Close tour" `div.mb-2.flex.items-start > button.inline-flex.items-center.justify-center`
- 48x32px "Skip" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 50x32px "Next" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 155x24px "Skip all tours on this device" `div.mt-2.border-t.border-border/60 > button.inline-flex.items-center.justify-center`
- 112x32px "Customize" `div.flex.flex-wrap.items-center > button.inline-flex.items-center.justify-center`
- ...and 5 more
### /account
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 300x36px `div.flex.flex-col.gap-2 > input#displayName.flex.h-9.w-full`
- 65x36px "Save" `div > button.inline-flex.items-center.justify-center`
- 144x32px "Request transfer" `div.flex.flex-wrap.items-start > button.inline-flex.items-center.justify-center`
- 300x36px `div.flex.flex-col.gap-2 > input#currentPassword.flex.h-9.w-full`
- 300x36px `div.flex.flex-col.gap-2 > input#newPassword.flex.h-9.w-full`
- 300x36px `div.flex.flex-col.gap-2 > input#confirmPassword.flex.h-9.w-full`
- ...and 32 more
### /awards
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 32x32px "Replay page tour" `div.ml-auto.flex.items-center > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 24x24px "Close tour" `div.mb-2.flex.items-start > button.inline-flex.items-center.justify-center`
- 48x32px "Skip" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 50x32px "Next" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 155x24px "Skip all tours on this device" `div.mt-2.border-t.border-border/60 > button.inline-flex.items-center.justify-center`
- 111x32px "Design a ribbon" `div.flex.flex-wrap.items-center > a.inline-flex.items-center.justify-center`
### /awards/design
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 300x36px `div.flex.flex-col.gap-1.5 > input#ribbon-name.flex.h-9.w-full`
- 246x26px (via label[for]) `div.flex.flex-col.gap-1 > label.text-sm.font-medium.leading-none`
- 82x38px "+ Add Stripe" `div.flex.items-center.justify-between > button.text-[11px].px-2.py-0.5`
- 28x28px `div.flex.flex-wrap.items-center > input.size-7.rounded.cursor-pointer`
- 48x28px "\u00D7" `div.flex.flex-wrap.items-center > button.py-1.text-zinc-500.hover:text-red-400`
- 149x36px "Submit for review" `div.flex.flex-wrap.items-center > button.inline-flex.items-center.justify-center`
### /awards/review
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 32x32px "Replay page tour" `div.ml-auto.flex.items-center > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 24x24px "Close tour" `div.mb-2.flex.items-start > button.inline-flex.items-center.justify-center`
- 48x32px "Skip" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 50x32px "Next" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 155x24px "Skip all tours on this device" `div.mt-2.border-t.border-border/60 > button.inline-flex.items-center.justify-center`
- 111x32px "Design a ribbon" `div.flex.flex-wrap.items-center > a.inline-flex.items-center.justify-center`
- ...and 1 more
### /contributions
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
### /events
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 32x32px "Replay page tour" `div.ml-auto.flex.items-center > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 24x24px "Close tour" `div.mb-2.flex.items-start > button.inline-flex.items-center.justify-center`
- 48x32px "Skip" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 53x32px "Done" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 155x24px "Skip all tours on this device" `div.mt-2.border-t.border-border/60 > button.inline-flex.items-center.justify-center`
- 320x36px `div.relative.w-full.max-w-xs > input.flex.h-9.w-full`
- ...and 9 more
### /helpdesk
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 110x32px "New ticket" `div.flex.flex-wrap.items-end > button.inline-flex.items-center.justify-center`
- 65x28px "All17" `div.inline-flex.items-center.overflow-x-auto > button#radix-_R_1l5esnf939etb_-trigger-all.inline-flex.items-center.justify-center`
- 84x28px "Open14" `div.inline-flex.items-center.overflow-x-auto > button#radix-_R_1l5esnf939etb_-trigger-open.inline-flex.items-center.justify-center`
- 107x28px "Resolved2" `div.inline-flex.items-center.overflow-x-auto > button#radix-_R_1l5esnf939etb_-trigger-resolved.inline-flex.items-center.justify-center`
- 89x28px "Closed1" `div.inline-flex.items-center.overflow-x-auto > button#radix-_R_1l5esnf939etb_-trigger-closed.inline-flex.items-center.justify-center`
- 125x28px "Unassigned5" `div.inline-flex.items-center.overflow-x-auto > button#radix-_R_1l5esnf939etb_-trigger-unassigned.inline-flex.items-center.justify-center`
- ...and 17 more
### /intelligence
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
### /intelligence/campaigns
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 148x32px "Create campaign" `div.flex.flex-col.gap-1 > button.inline-flex.items-center.justify-center`
- 117x32px (via label[for]) "Show completed campaigns" `div.flex.items-center.justify-end > label.cursor-pointer.select-none.px-1`
### /intelligence/factions
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
### /intelligence/missions
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 38x28px "All" `div.flex.flex-wrap.gap-1.5 > button.inline-flex.items-center.justify-center`
- 111x28px "Building Blocks" `div.flex.flex-wrap.gap-1.5 > button.inline-flex.items-center.justify-center`
- 133x28px "Operation Dubrava" `div.flex.flex-wrap.gap-1.5 > button.inline-flex.items-center.justify-center`
- 139x28px "The World We Knew" `div.flex.flex-wrap.gap-1.5 > button.inline-flex.items-center.justify-center`
- 143x28px "The End of All Things" `div.flex.flex-wrap.gap-1.5 > button.inline-flex.items-center.justify-center`
- 54x28px "Main" `div.flex.flex-wrap.gap-1.5 > button.inline-flex.items-center.justify-center`
- ...and 9 more
### /intelligence/missions/calendar
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 32x32px "Replay page tour" `div.ml-auto.flex.items-center > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 24x24px "Close tour" `div.mb-2.flex.items-start > button.inline-flex.items-center.justify-center`
- 48x32px "Skip" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 53x32px "Done" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 155x24px "Skip all tours on this device" `div.mt-2.border-t.border-border/60 > button.inline-flex.items-center.justify-center`
- 103x32px "Schedule" `div.flex.min-w-0.basis-full > button.inline-flex.items-center.justify-center`
### /journals
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 139x36px "Write entry" `div.flex.flex-wrap.items-center > button.inline-flex.items-center.justify-center`
### /locker
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 32x32px "Replay page tour" `div.ml-auto.flex.items-center > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 24x24px "Close tour" `div.mb-2.flex.items-start > button.inline-flex.items-center.justify-center`
- 48x32px "Skip" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 53x32px "Done" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 155x24px "Skip all tours on this device" `div.mt-2.border-t.border-border/60 > button.inline-flex.items-center.justify-center`
- 114x38px "WARDROBE" `div.inline-flex.max-w-full.items-center > button#radix-_R_55esnf939etb_-trigger-wardrobe.inline-flex.items-center.justify-center`
- ...and 9 more
### /logistics
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 32x32px "Replay page tour" `div.ml-auto.flex.items-center > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 73x26px "Logistics" `div.flex.items-center.gap-1.5 > button.text-xs.px-2.5.py-1`
- 65x26px "Military" `div.flex.items-center.gap-1.5 > button.text-xs.px-2.5.py-1`
- 62x26px "Civilian" `div.flex.items-center.gap-1.5 > button.text-xs.px-2.5.py-1`
### /logistics/banking
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 32x32px "Replay page tour" `div.ml-auto.flex.items-center > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 24x24px "Close tour" `div.mb-2.flex.items-start > button.inline-flex.items-center.justify-center`
- 48x32px "Skip" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 50x32px "Next" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 155x24px "Skip all tours on this device" `div.mt-2.border-t.border-border/60 > button.inline-flex.items-center.justify-center`
- 101x32px "Deposit" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- ...and 4 more
### /logistics/game-vehicles
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
### /logistics/market
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 32x32px "Replay page tour" `div.ml-auto.flex.items-center > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 24x24px "Close tour" `div.mb-2.flex.items-start > button.inline-flex.items-center.justify-center`
- 48x32px "Skip" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 53x32px "Done" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 155x24px "Skip all tours on this device" `div.mt-2.border-t.border-border/60 > button.inline-flex.items-center.justify-center`
- 264x36px `div.relative > input.flex.h-9.w-full`
- ...and 3 more
### /logistics/resources
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
### /logistics/shipments
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 32x32px "Replay page tour" `div.ml-auto.flex.items-center > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 24x24px "Close tour" `div.mb-2.flex.items-start > button.inline-flex.items-center.justify-center`
- 48x32px "Skip" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 50x32px "Next" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 155x24px "Skip all tours on this device" `div.mt-2.border-t.border-border/60 > button.inline-flex.items-center.justify-center`
- 38x28px "All" `div.flex.flex-wrap.gap-1.5 > button.inline-flex.items-center.justify-center`
- ...and 4 more
### /logistics/supply-boxes
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
### /logistics/vehicles
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 38x32px "All" `div.flex.flex-wrap.gap-2 > button.inline-flex.items-center.justify-center`
- 68x32px "Civilian" `div.flex.flex-wrap.gap-2 > button.inline-flex.items-center.justify-center`
- 60x32px "Utility" `div.flex.flex-wrap.gap-2 > button.inline-flex.items-center.justify-center`
- 80x32px "Transport" `div.flex.flex-wrap.gap-2 > button.inline-flex.items-center.justify-center`
- 96x32px "Weaponized" `div.flex.flex-wrap.gap-2 > button.inline-flex.items-center.justify-center`
- 70x32px "Military" `div.flex.flex-wrap.gap-2 > button.inline-flex.items-center.justify-center`
### /map
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 32x32px "Replay page tour" `div.ml-auto.flex.items-center > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 24x24px "Close tour" `div.mb-2.flex.items-start > button.inline-flex.items-center.justify-center`
- 48x32px "Skip" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 50x32px "Next" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 155x24px "Skip all tours on this device" `div.mt-2.border-t.border-border/60 > button.inline-flex.items-center.justify-center`
### /notifications
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
### /operations
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 32x32px "Replay page tour" `div.ml-auto.flex.items-center > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 24x24px "Close tour" `div.mb-2.flex.items-start > button.inline-flex.items-center.justify-center`
- 48x32px "Skip" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 53x32px "Done" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 155x24px "Skip all tours on this device" `div.mt-2.border-t.border-border/60 > button.inline-flex.items-center.justify-center`
### /operations/ledger
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 32x32px "Replay page tour" `div.ml-auto.flex.items-center > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 24x24px "Close tour" `div.mb-2.flex.items-start > button.inline-flex.items-center.justify-center`
- 48x32px "Skip" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 53x32px "Done" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 155x24px "Skip all tours on this device" `div.mt-2.border-t.border-border/60 > button.inline-flex.items-center.justify-center`
### /operations/reservations
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 101x28px "AllReservedSettledCancelledExp" `div.flex.flex-col.gap-1 > select#reservation-status.border.border-white/15.bg-black/40`
- 256x26px `div.flex.flex-col.gap-1 > input#reservation-operation.w-64.border.border-white/15`
- 35x32px "Clear" `form.flex.flex-wrap.items-end > a.font-mono.text-[10px].uppercase`
- 358x32px "New Reservation" `div.mx-auto.flex.w-full > button.inline-flex.items-center.justify-center`
### /personnel/contacts
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 264x36px "Search contacts by name or occ" `div.relative > input#npc-search.flex.h-9.rounded-md`
- 86x32px (via label[for]) `div.flex.items-center.gap-2 > label.peer-disabled:cursor-not-allowed.peer-disabled:opacity-70.cursor-pointer`
- 83x32px (via label[for]) `div.flex.items-center.gap-2 > label.peer-disabled:cursor-not-allowed.peer-disabled:opacity-70.cursor-pointer`
### /personnel/promotions
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
### /personnel/statistics
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
### /projects
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 131x32px "Create project" `div.flex.flex-wrap.items-end > button.inline-flex.items-center.justify-center`
- 350x36px "Search projects" `div.relative.w-full.lg:max-w-xs > input.flex.h-9.w-full`
### /projects/search
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 350x36px "Search tickets" `div.relative.w-full.lg:max-w-md > input.flex.h-9.w-full`
- 160x36px "All statuses" `div.flex.flex-wrap.gap-2 > button.flex.h-9.items-center`
- 150x36px "All types" `div.flex.flex-wrap.gap-2 > button.flex.h-9.items-center`
### /roster
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 32x32px "Replay page tour" `div.ml-auto.flex.items-center > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 24x24px "Close tour" `div.mb-2.flex.items-start > button.inline-flex.items-center.justify-center`
- 48x32px "Skip" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 53x32px "Done" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 155x24px "Skip all tours on this device" `div.mt-2.border-t.border-border/60 > button.inline-flex.items-center.justify-center`
- 115x38px "Org Chart" `div.inline-flex.max-w-full.items-center > button#radix-_R_55esnf939etb_-trigger-org.inline-flex.items-center.justify-center`
- ...and 4 more
### /story
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 162x36px "Immersive view" `div.mt-5.flex.flex-wrap > button.inline-flex.items-center.justify-center`
- 128x36px "Book view" `div.mt-5.flex.flex-wrap > button.inline-flex.items-center.justify-center`
- 28x28px "Play narration: What Makes Us " `div.flex.items-center.gap-2.5 > button.inline-flex.items-center.justify-center`
- 56x32px "2" `div.mt-5.flex.flex-wrap > button.inline-flex.items-center.justify-center`
- 56x32px "0" `div.mt-5.flex.flex-wrap > button.inline-flex.items-center.justify-center`
- 28x28px "Play narration: Little Green L" `div.flex.items-center.gap-2.5 > button.inline-flex.items-center.justify-center`
- ...and 1 more
### /surveys
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
### /transfers
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
### /voiceover
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 109x24px "Kestrel: Arrival" `div.font-semibold.leading-none.tracking-tight > a.inline-block.rounded-sm.py-1`
- 300x36px "Record a take" `div.p-6.pt-0.flex > a.inline-flex.items-center.justify-center`
- 110x24px "Practice Script" `div.font-semibold.leading-none.tracking-tight > a.inline-block.rounded-sm.py-1`
### /wiki
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 32x32px "Replay page tour" `div.ml-auto.flex.items-center > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 24x24px "Close tour" `div.mb-2.flex.items-start > button.inline-flex.items-center.justify-center`
- 48x32px "Skip" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 53x32px "Done" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 155x24px "Skip all tours on this device" `div.mt-2.border-t.border-border/60 > button.inline-flex.items-center.justify-center`
- 350x36px "Search wiki pages" `div.relative.min-w-56.flex-1 > input.flex.h-9.w-full`
- ...and 12 more
### /wiki/new
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 42x28px "Wiki" `div.flex.flex-col.gap-3 > a.flex.w-fit.items-center`
- 350x36px `div.flex.flex-col.gap-1.5 > input#wiki-title.flex.h-9.w-full`
- 350x36px "Meta" `div.flex.flex-col.gap-1.5 > button#wiki-category.flex.h-9.w-full`
- 350x36px `div.flex.flex-col.gap-1.5 > input#wiki-tags.flex.h-9.w-full`
- 350x36px `div.flex.flex-col.gap-1.5 > input#wiki-summary.flex.h-9.w-full`
- 127x32px "Insert wikilink" `div.flex.flex-wrap.items-center > button.inline-flex.items-center.justify-center`
- ...and 24 more
### /minigames/blackjack
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 117x32px "House rules" `div.flex.flex-wrap.items-center > button.inline-flex.items-center.justify-center`
- 36x36px "Refresh blackjack tables" `div.flex.shrink-0.gap-2 > button.inline-flex.items-center.justify-center`
- 138x36px "Create table" `div.flex.shrink-0.gap-2 > button.inline-flex.items-center.justify-center`
### /minigames/call-for-fire
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 149x32px "Begin fire mission" `div.flex.flex-wrap.items-center > button.inline-flex.items-center.justify-center`
- 32x32px "-50" `div.flex.items-center.gap-1 > button.inline-flex.items-center.justify-center`
- 218x32px `div.flex.items-center.gap-1 > input#cff-range.flex.w-full.rounded-md`
- 32x32px "+50" `div.flex.items-center.gap-1 > button.inline-flex.items-center.justify-center`
- 218x32px `div.flex.items-center.gap-1 > input#cff-deflection.flex.w-full.rounded-md`
- 290x36px "Fire mission" `form.flex.flex-col.gap-3 > button.inline-flex.items-center.justify-center`
- ...and 4 more
### /minigames/call-for-fire-versus
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 95x32px "Refresh" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 101x32px "New duel" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
### /minigames/eod
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 26x26px "row 1 col 1 hidden" `div.grid.min-w-max.grid-cols-[repeat(var(--board-cols),var(--cell-size))] > button.flex.size-[var(--cell-size)].items-center`
- 26x26px "row 1 col 2 hidden" `div.grid.min-w-max.grid-cols-[repeat(var(--board-cols),var(--cell-size))] > button.flex.size-[var(--cell-size)].items-center`
- 26x26px "row 1 col 3 hidden" `div.grid.min-w-max.grid-cols-[repeat(var(--board-cols),var(--cell-size))] > button.flex.size-[var(--cell-size)].items-center`
- 26x26px "row 1 col 4 hidden" `div.grid.min-w-max.grid-cols-[repeat(var(--board-cols),var(--cell-size))] > button.flex.size-[var(--cell-size)].items-center`
- 26x26px "row 1 col 5 hidden" `div.grid.min-w-max.grid-cols-[repeat(var(--board-cols),var(--cell-size))] > button.flex.size-[var(--cell-size)].items-center`
- 26x26px "row 1 col 6 hidden" `div.grid.min-w-max.grid-cols-[repeat(var(--board-cols),var(--cell-size))] > button.flex.size-[var(--cell-size)].items-center`
- ...and 88 more
### /minigames/eod/custom
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
### /minigames/flappy
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 82x24px "This period" `div.flex.items-center.gap-1 > button.rounded-md.px-2.5.py-1`
- 67x24px "All-Time" `div.flex.items-center.gap-1 > button.rounded-md.px-2.5.py-1`
- 60x24px "All boards" `div.flex.items-center.gap-1 > a.ml-auto.py-1.pr-1`
### /minigames/leaderboards
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 350x36px "Current period · Oct 12 to Oct" `div.flex.flex-wrap.items-center > button.flex.h-9.items-center`
- 149x28px "Flight Simulator" `div.max-w-full.items-center.overflow-x-auto > button#radix-_r_8_-trigger-flappy.inline-flex.items-center.justify-center`
- 176x28px "Minefield Clearance" `div.max-w-full.items-center.overflow-x-auto > button#radix-_r_8_-trigger-eod.inline-flex.items-center.justify-center`
- 128x28px "Radio Traffic" `div.max-w-full.items-center.overflow-x-auto > button#radix-_r_8_-trigger-radio.inline-flex.items-center.justify-center`
- 177x28px "Qualification Course" `div.max-w-full.items-center.overflow-x-auto > button#radix-_r_8_-trigger-qualification.inline-flex.items-center.justify-center`
- 140x28px "OPORD Recall" `div.max-w-full.items-center.overflow-x-auto > button#radix-_r_8_-trigger-opord.inline-flex.items-center.justify-center`
- ...and 1 more
### /minigames/opord
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 82x24px "This period" `div.flex.items-center.gap-1 > button.rounded-md.px-2.5.py-1`
- 67x24px "All-Time" `div.flex.items-center.gap-1 > button.rounded-md.px-2.5.py-1`
- 60x24px "All boards" `div.flex.items-center.gap-1 > a.ml-auto.py-1.pr-1`
### /minigames/poker
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 118x32px "How to play" `div.flex.flex-wrap.items-center > button.inline-flex.items-center.justify-center`
- 36x36px "Refresh poker tables" `div.flex.shrink-0.gap-2 > button.inline-flex.items-center.justify-center`
- 138x36px "Create table" `div.flex.shrink-0.gap-2 > button.inline-flex.items-center.justify-center`
### /minigames/qualification
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 36x36px "Crosshair settings" `div.flex.items-center.gap-1.5 > button.inline-flex.items-center.justify-center`
- 181x36px "Begin Qualification" `div.absolute.inset-0.flex > button.inline-flex.items-center.justify-center`
- 82x24px "This period" `div.flex.items-center.gap-1 > button.rounded-md.px-2.5.py-1`
- 67x24px "All-Time" `div.flex.items-center.gap-1 > button.rounded-md.px-2.5.py-1`
- 60x24px "All boards" `div.flex.items-center.gap-1 > a.ml-auto.py-1.pr-1`
### /minigames/radio
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 147x24px (via label[for]) `div.mt-3.flex.items-center > label.flex.min-h-6.cursor-pointer`
- 154x32px "Sprint · 10 messages" `div.mt-3.grid.grid-cols-2 > button.inline-flex.items-center.justify-center`
- 154x32px "Watch · 60 seconds" `div.mt-3.grid.grid-cols-2 > button.inline-flex.items-center.justify-center`
- 130x36px "Start intercept" `div.flex.flex-col.items-center > button.inline-flex.items-center.justify-center`
- 77x24px "Top Score" `div#radio-traffic-leaderboard-tabs.max-w-full.items-center.justify-center > button#radix-_R_16qatpesnf939etb_-trigger-score.inline-flex.items-center.justify-center`
- 77x24px "Top Accuracy" `div#radio-traffic-leaderboard-tabs.max-w-full.items-center.justify-center > button#radix-_R_16qatpesnf939etb_-trigger-accuracy.inline-flex.items-center.justify-center`
- ...and 5 more
### /minigames/radio/custom
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
### /helpdesk/17
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 77x28px "Helpdesk" `div.flex.flex-col.gap-3 > a.flex.w-fit.items-center`
- 58x32px "0upvotes" `div.flex.flex-wrap.items-center > button.inline-flex.items-center.justify-center`
- 252x36px "In Review" `div.flex.gap-2 > button#ticket-status.flex.h-9.w-full`
- 56x32px "Apply" `div.flex.gap-2 > button.inline-flex.items-center.justify-center`
- 252x36px "J. Fraley (jason)" `div.flex.gap-2 > button#ticket-assignee.flex.h-9.w-full`
- 134x32px "Archive ticket" `div.flex.flex-wrap.items-center > button.inline-flex.items-center.justify-center`
- ...and 1 more
### /journals/1
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 94x28px "All journals" `div.mx-auto.max-w-3xl.px-4 > a.inline-flex.items-center.gap-1.5`
- 80x32px "Edit" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 95x32px "Delete" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
### /profile/dev
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 50x28px "Back" `div.p-5.flex.flex-col > a.py-1.text-sm.text-muted-foreground`
- 70x32px "Edit" `div.flex.min-w-0.basis-full > button.inline-flex.items-center.justify-center`
- 122x32px "Grant Award" `div.flex.flex-wrap.items-center > button.inline-flex.items-center.justify-center`
- 159x32px "Request promotion" `div.flex.items-center.justify-between > button.inline-flex.items-center.justify-center`
### /intelligence/factions/3
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_r_20_.inline-flex.items-center.justify-center`
- 126x28px "Back to Factions" `div.absolute.top-0.left-0 > a.flex.w-fit.items-center`
- 165x28px "Batch 41-7 (POLARIS)" `div.flex.items-center.justify-between > a.flex.items-center.gap-2`
### /intelligence/campaigns/4
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 143x28px "Back to Campaigns" `div.absolute.top-0.left-0 > a.flex.w-fit.items-center`
- 316x34px "ConceptIn ProgressOn HoldCompl" `div.flex.min-w-0.flex-1 > select.w-full.rounded-md.border`
### /intelligence/missions/11
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 126x28px "Back to Missions" `div.absolute.top-0.left-0 > a.flex.w-fit.items-center`
### /voiceover/2
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 127x28px "Voiceover scripts" `div.flex.min-w-0.flex-col > a.flex.w-fit.items-center`
- 340x36px "Go back" `div.flex.flex-col-reverse.sm:flex-row > button.inline-flex.items-center.justify-center`
- 340x36px "I understand" `div.flex.flex-col-reverse.sm:flex-row > button.inline-flex.items-center.justify-center`
### /map/6
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 30x30px "+" `div.leaflet-control-zoom.leaflet-bar.leaflet-control > a.leaflet-control-zoom-in`
- 30x30px "−" `div.leaflet-control-zoom.leaflet-bar.leaflet-control > a.leaflet-control-zoom-out`
- 82x32px "Structures" `div.flex.flex-wrap.items-center > button.inline-flex.items-center.justify-center`
- 56x32px "Nodes" `div.flex.flex-wrap.items-center > button.inline-flex.items-center.justify-center`
- 55x32px "Roads" `div.flex.flex-wrap.items-center > button.inline-flex.items-center.justify-center`
- 54x32px "Zones" `div.flex.flex-wrap.items-center > button.inline-flex.items-center.justify-center`
- ...and 5 more
### /logistics/structures/1
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 138x28px "Back to Structures" `header.relative.flex.flex-col > a.relative.z-10.py-1`
- 102x32px "Manage" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 48x32px "Fire" `div.flex.items-center.gap-3 > button.inline-flex.items-center.justify-center`
- 132x32px "Auto-Arrange" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 40x32px `div.flex.items-center.gap-1 > button.inline-flex.items-center.justify-center`
- 42x32px `div.flex.items-center.gap-1 > button.inline-flex.items-center.justify-center`
### /logistics/banking/30
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 123x28px "Back to Banking" `div.flex.flex-col.gap-6 > a.py-1.text-sm.text-muted-foreground`
- 101x32px "Deposit" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 111x32px "Withdraw" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
- 111x32px "Transfer" `div.flex.items-center.gap-2 > button.inline-flex.items-center.justify-center`
### /logistics/resources/89
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 138x28px "Back to Resources" `div.p-5.flex.flex-col > a.py-1.text-sm.text-muted-foreground`
### /logistics/vehicles/1902
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 125x28px "Back to Vehicles" `div.p-5.flex.flex-col > a.py-1.text-sm.text-muted-foreground`
### /wiki/welcome-to-the-unit
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 42x28px "Wiki" `div.flex.flex-col.gap-3 > a.flex.w-fit.items-center`
- 72x32px "Edit" `div.flex.flex-wrap.justify-end > a.inline-flex.items-center.justify-center`
- 92x32px "History" `div.flex.flex-wrap.justify-end > a.inline-flex.items-center.justify-center`
- 78x32px "Lock" `div.flex.flex-wrap.justify-end > button.inline-flex.items-center.justify-center`
- 85x32px "Delete" `div.flex.flex-wrap.justify-end > button.inline-flex.items-center.justify-center`
### /wiki/welcome-to-the-unit/history
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 103x28px "Back to page" `div.flex.flex-col.gap-3 > a.flex.w-fit.items-center`
### /wiki/welcome-to-the-unit/edit
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 103x28px "Back to page" `div.flex.flex-col.gap-6 > a.flex.w-fit.items-center`
### /wiki/category/Documentation
- 28x28px "Toggle Sidebar" `header.flex.h-16.shrink-0 > button.inline-flex.items-center.justify-center`
- 36x36px "No unread notifications" `div.ml-auto.flex.items-center > button#radix-_R_2gp39etb_.inline-flex.items-center.justify-center`
- 42x28px "Wiki" `div.flex.flex-col.gap-3 > a.flex.w-fit.items-center`
- 117x26px "documentation7" `div.flex.flex-wrap.gap-1.5 > a.inline-flex.items-center.gap-1.5`
- 89x38px "documentation" `div.flex.shrink-0.flex-wrap > a.relative.z-10.rounded-sm`
## hiddenMobile
### /locker
- hidden on mobile (md:/lg: reveal) `div.flex.shrink-0.items-center > span.hidden.font-mono.text-[10px]`
## tapTargetInlineText
### /wiki/welcome-to-the-unit
- 61x19px "The Map" `li > a.font-medium.text-primary.underline`
- 76x19px "Shipments" `li > a.font-medium.text-primary.underline`
- 198x19px "Logistics and Storage Rules" `li > a.font-medium.text-primary.underline`
- 131x19px "Base Management" `li > a.font-medium.text-primary.underline`
- 57x19px "Banking" `li > a.font-medium.text-primary.underline`
- 167x19px "Market and Negotiation" `li > a.font-medium.text-primary.underline`

551
tests/audit/mobile-audit.ts Normal file
View file

@ -0,0 +1,551 @@
/**
* Pass 2 Session A - mobile layout audit.
*
* Walks every frontend route at 390x844 against a running dev server and
* classifies issues into pattern classes:
* overflow horizontal scroll / elements crossing the viewport edge
* dialog dialogs/panels taller than the viewport
* grid multi-track grids that are cramped at mobile width
* hoverOnly affordances revealed only via (group-)hover
* hiddenMobile content gated behind md:/lg: breakpoints (invisible on mobile)
* tapTarget interactive elements under 24px (WCAG 2.5.8 violation)
* tapTargetMarginal interactive elements 24-39px (review tier)
*
* Usage: bun run tests/audit/mobile-audit.ts
* Env: AUDIT_BASE_URL (default http://localhost:3000)
* AUDIT_USER / AUDIT_PASS (default dev / Test123)
* AUDIT_ROUTE_FILTER (substring match, or "=/route" for an exact match)
* E2E_BROWSER_PATH (browser executable override)
*
* Outputs tests/audit/mobile-audit-report.json (regression gate artifact for
* Sessions B-D) and mobile-audit-report.md (human issue matrix).
*/
import { chromium, type BrowserContext, type Page } from "@playwright/test";
import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
const BASE_URL = process.env.AUDIT_BASE_URL ?? "http://localhost:3000";
const USER = process.env.AUDIT_USER ?? "dev";
const PASS = process.env.AUDIT_PASS ?? "Test123";
const VIEWPORT = { width: 390, height: 844 };
const OUT_DIR = join(__dirname);
// Optional substring filter for targeted re-audits (Sessions B-D). When set,
// reports go to mobile-audit-filtered.{json,md} so the baseline is untouched.
const ROUTE_FILTER = process.env.AUDIT_ROUTE_FILTER ?? "";
let authToken: string | null = null;
type Issue = { kind: string; detail: string; selector?: string; size?: string };
type RouteResult = {
route: string;
url: string;
status: "ok" | "skipped" | "error";
httpStatus?: number;
note?: string;
issues: Issue[];
};
/** Static routes, straight from the filesystem. */
const STATIC_ROUTES = [
"/", "/account", "/awards", "/awards/design", "/awards/review",
"/contributions", "/events", "/helpdesk", "/intelligence",
"/intelligence/campaigns", "/intelligence/factions",
"/intelligence/missions", "/intelligence/missions/calendar",
"/journals", "/locker", "/logistics", "/logistics/banking",
"/logistics/game-vehicles", "/logistics/market", "/logistics/resources",
"/logistics/shipments", "/logistics/supply-boxes", "/logistics/vehicles",
"/map", "/notifications",
"/operations", "/operations/ledger", "/operations/reservations",
"/personnel/contacts", "/personnel/promotions", "/personnel/statistics",
"/projects", "/projects/search", "/roster", "/story",
"/surveys", "/transfers", "/voiceover", "/wiki", "/wiki/new",
"/minigames/blackjack", "/minigames/call-for-fire",
"/minigames/call-for-fire-versus", "/minigames/eod", "/minigames/eod/custom",
"/minigames/flappy", "/minigames/leaderboards", "/minigames/opord",
"/minigames/poker", "/minigames/qualification", "/minigames/radio",
"/minigames/radio/custom",
];
/**
* Dynamic routes: template -> REST collection to resolve a real doc from the
* dev DB, plus the field substituted into the path. `null` collection means
* the route is skipped if no candidate resolves.
*/
const DYNAMIC_ROUTES: { template: string; collection: string | null; field: string; fallback?: string }[] = [
{ template: "/helpdesk/[id]", collection: "tickets", field: "id" },
{ template: "/journals/[id]", collection: "journals", field: "id" },
{ template: "/surveys/[id]", collection: "forms", field: "id" },
{ template: "/profile/[username]", collection: null, field: "", fallback: USER },
{ template: "/operations/[operationId]", collection: "operations", field: "id" },
{ template: "/operations/reservations/[id]", collection: "operation-reservations", field: "id" },
{ template: "/intelligence/factions/[id]", collection: "factions", field: "id" },
{ template: "/intelligence/campaigns/[id]", collection: "campaigns", field: "id" },
{ template: "/intelligence/missions/[id]", collection: "missions", field: "id" },
{ template: "/projects/[key]", collection: "projects", field: "key", fallback: "" },
{ template: "/voiceover/[id]", collection: "voice-scripts", field: "id" },
{ template: "/map/[id]", collection: "maps", field: "id" },
{ template: "/personnel/contacts/[id]", collection: "contacts", field: "id" },
{ template: "/logistics/supply-boxes/[id]", collection: "supply-boxes", field: "id" },
{ template: "/logistics/structures/[id]", collection: "game-structures", field: "id" },
{ template: "/logistics/banking/[id]", collection: "bank-accounts", field: "id" },
{ template: "/logistics/resources/[id]", collection: "resources", field: "id" },
{ template: "/logistics/shipments/[id]", collection: "shipments", field: "id" },
{ template: "/logistics/game-vehicles/[id]", collection: "game-vehicles", field: "id" },
{ template: "/logistics/vehicles/[id]", collection: "vehicles", field: "id" },
{ template: "/minigames/eod/custom/[id]", collection: "custom-minefields", field: "id" },
{ template: "/minigames/radio/custom/[id]", collection: "custom-radio-tests", field: "id" },
];
/** Wiki routes need a slug/category instead of an id. */
const WIKI_ROUTES = [
{ template: "/wiki/[slug]", suffix: "" },
{ template: "/wiki/[slug]", suffix: "/history" },
{ template: "/wiki/[slug]", suffix: "/edit" },
];
async function resolveDoc(collection: string): Promise<Record<string, unknown> | null> {
try {
const res = await fetch(`${BASE_URL}/api/${collection}?limit=1&sort=-createdAt`, {
headers: authToken ? { Cookie: `payload-token=${authToken}` } : {},
});
if (!res.ok) return null;
const body = (await res.json()) as { docs?: Record<string, unknown>[] };
return body.docs?.[0] ?? null;
} catch {
return null;
}
}
/** Runs inside the page; returns raw issue records. */
async function collectIssues(): Promise<Issue[]> {
const issues: Issue[] = [];
const vw = window.innerWidth;
const vh = window.innerHeight;
const path = (el: Element): string => {
const parts: string[] = [el.tagName.toLowerCase()];
if (el.id) parts.push("#" + el.id);
const cls = typeof el.className === "string" ? el.className.split(/\s+/).filter(Boolean).slice(0, 3) : [];
if (cls.length) parts.push("." + cls.join("."));
const parent = el.parentElement;
return (parent ? path(parent).split(" > ").pop() + " > " : "") + parts.join("");
};
// 1. Horizontal overflow
const docW = document.documentElement.scrollWidth;
if (docW > vw + 1) {
issues.push({ kind: "overflow", detail: `document scrollWidth ${docW}px > ${vw}px` });
const offenders: { el: Element; over: number }[] = [];
for (const el of Array.from(document.querySelectorAll("body *"))) {
const rect = el.getBoundingClientRect();
if (rect.width < 8 || rect.height < 2) continue;
const style = getComputedStyle(el);
if (style.position === "fixed") continue;
const over = Math.max(rect.right - vw, -rect.left);
if (over > 4) offenders.push({ el, over });
}
offenders.sort((a, b) => b.over - a.over);
for (const o of offenders.slice(0, 4)) {
issues.push({
kind: "overflow",
detail: `crosses edge by ${Math.round(o.over)}px`,
selector: path(o.el),
});
}
}
// 2. Dialogs taller than viewport
for (const dlg of Array.from(document.querySelectorAll('[role="dialog"],[role="alertdialog"]'))) {
const rect = dlg.getBoundingClientRect();
if (rect.height > vh + 1 || rect.bottom > vh + 1) {
issues.push({
kind: "dialog",
detail: `height ${Math.round(rect.height)}px > viewport ${vh}px`,
selector: path(dlg),
});
}
}
// 3. Grids that overflow a container which cannot scroll. Wide-by-design
// layouts (min-w-max boards) and grids inside scroll containers are
// intentional, and narrow icon tracks are not cramped layouts.
const hasScrollAncestor = (el: Element): boolean => {
let node = el.parentElement;
while (node && node !== document.body) {
if (/(auto|scroll)/.test(getComputedStyle(node).overflowX)) return true;
node = node.parentElement;
}
return false;
};
for (const el of Array.from(document.querySelectorAll("*"))) {
const style = getComputedStyle(el);
if (style.display !== "grid") continue;
const tracks = style.gridTemplateColumns.split(" ").filter(Boolean);
if (tracks.length < 2) continue;
const rect = el.getBoundingClientRect();
if (rect.width < 40) continue;
if (style.minWidth === "max-content" || hasScrollAncestor(el)) continue;
const overflowing = el.scrollWidth > el.clientWidth + 1 || rect.right > vw + 4;
if (overflowing) {
issues.push({
kind: "grid",
detail: `${tracks.length}-track grid overflows its container (${Math.round(rect.width)}px wide)`,
selector: path(el),
});
}
}
// 4. Hover-only affordances (invisible until hover/group-hover)
for (const el of Array.from(document.querySelectorAll('[class*="group-hover:"],[class*="hover:opacity"],[class*="hover:visible"],[class*="hover:block"],[class*="hover:flex"]'))) {
const style = getComputedStyle(el);
const cls: string = typeof el.className === "string" ? el.className : "";
const revealsOpacity = /(?:group-)?hover:opacity-\d/.test(cls) && parseFloat(style.opacity) < 0.05;
const revealsDisplay = /(?:group-)?hover:(block|flex)/.test(cls) && style.display === "none";
if (revealsOpacity || revealsDisplay) {
issues.push({ kind: "hoverOnly", detail: "affordance only visible on hover", selector: path(el) });
}
}
// 5. Content hidden at mobile behind md:/lg: reveal utilities. shadcn's
// Sidebar ships desktop-only scaffolding (peer spacer + fixed container)
// and Tailwind `peer` helpers are styling aids, never user content.
for (const el of Array.from(document.querySelectorAll('[class*="md:block"],[class*="md:flex"],[class*="lg:block"],[class*="lg:flex"],[class*="md:inline"],[class*="lg:inline"]'))) {
const cls: string = typeof el.className === "string" ? el.className : "";
if (!/(?:^|\s)hidden(?=\s|$)/.test(cls)) continue;
if (el.closest(".peer") || el.closest("aside")) continue;
const style = getComputedStyle(el);
if (style.display !== "none") continue;
issues.push({ kind: "hiddenMobile", detail: "hidden on mobile (md:/lg: reveal)", selector: path(el) });
}
// 6. Tap targets: WCAG 2.5.8 floor is 24px; 24-39px is a marginal tier for
// review (shadcn defaults live there). The measured box is the EFFECTIVE
// target: a control wrapped in (or labelled by) a <label> is tapped via that
// label, and visually-hidden inputs (1x1 sr-only selects) are driven by a
// styled trigger, so neither counts. Range inputs are excluded: the thumb is
// the target and the element box is only the track.
const interactive = 'a,button,[role="button"],[role="tab"],input:not([type="hidden"]):not([type="range"]),select';
const effectiveTarget = (el: Element): { box: Element; via: string } => {
const wrapping = el.closest("label");
if (wrapping) return { box: wrapping, via: "label" };
// label[for] is the target only for small checkable controls, where the
// label is the intended tap surface. For selects/inputs/large buttons the
// control itself is the target; its 14px caption label is not charged.
const tag = el.tagName.toLowerCase();
const type = (el.getAttribute("type") || "").toLowerCase();
const role = el.getAttribute("role") || "";
const smallCheckable =
(tag === "input" && (type === "checkbox" || type === "radio")) ||
role === "switch" ||
role === "checkbox" ||
role === "radio";
const id = el.getAttribute("id");
if (id && smallCheckable) {
const forLabel = document.querySelector(`label[for="${CSS.escape(id)}"]`);
if (forLabel) return { box: forLabel, via: "label[for]" };
}
return { box: el, via: "" };
};
// A "stretched link" (a.after:absolute inset-0) makes the whole card the
// target; the anchor box is only the text. Charge the positioned ancestor.
const stretchedCard = (el: Element): Element | null => {
if (el.tagName.toLowerCase() !== "a") return null;
const after = getComputedStyle(el, "::after");
if (after.position !== "absolute") return null;
if (!["top", "right", "bottom", "left"].every((s) => after.getPropertyValue(s) === "0px")) return null;
let node = el.parentElement;
while (node && node !== document.body) {
const pos = getComputedStyle(node).position;
if (pos === "relative" || pos === "absolute") return node;
node = node.parentElement;
}
return null;
};
for (const el of Array.from(document.querySelectorAll(interactive))) {
const own = el.getBoundingClientRect();
if (own.width === 0 || own.height === 0) continue;
const style = getComputedStyle(el);
if (style.visibility === "hidden" || style.opacity === "0") continue;
// Visually hidden control (sr-only clip, 1x1 proxy element): skip.
if (own.width < 8 || own.height < 8) continue;
const card = stretchedCard(el);
const { box, via } = card ? { box: card, via: "card overlay" } : effectiveTarget(el);
const rect = box.getBoundingClientRect();
const minSide = Math.min(rect.width, rect.height);
if (minSide >= 40) continue;
// WCAG 2.5.8 exempts targets inline in a sentence: an inline anchor with
// prose text beside it in the same block is sized by the surrounding
// line-height. Standalone inline links (list rows, header links) do not
// qualify and stay violations.
const inlineInSentence = (() => {
if (el.tagName.toLowerCase() !== "a") return false;
if (getComputedStyle(el).display !== "inline") return false;
// Inline links inside prose blocks (rendered content) are sized by the
// surrounding line-height, which is the 2.5.8 inline exception.
if (el.closest("p, li, td, th, blockquote, figcaption")) return true;
const parent = el.parentElement;
if (!parent) return false;
return Array.from(parent.childNodes).some(
(node) => node !== el && node.nodeType === 3 && (node.textContent ?? "").trim().length > 0,
);
})();
const kind = inlineInSentence ? "tapTargetInlineText" : minSide < 24 ? "tapTarget" : "tapTargetMarginal";
const label = (el.textContent || el.getAttribute("aria-label") || el.getAttribute("title") || "").trim().slice(0, 30);
issues.push({
kind,
detail: `${Math.round(rect.width)}x${Math.round(rect.height)}px${via ? ` (via ${via})` : ""}${label ? ` "${label}"` : ""}`,
selector: path(box === el ? el : box),
});
}
return issues;
}
async function auditRoute(context: BrowserContext, route: string): Promise<RouteResult> {
const url = `${BASE_URL}${route}`;
const page: Page = await context.newPage();
try {
// The realtime SSE stream never finishes and competes for the per-host
// connection cap; it adds nothing to a layout audit.
await page.route("**/api/realtime**", (r) => r.abort());
const res = await page.goto(url, { waitUntil: "domcontentloaded", timeout: 60_000 });
const httpStatus = res?.status();
// Let client components render.
await page.waitForTimeout(2000);
if (httpStatus && httpStatus >= 400) {
return { route, url, status: "skipped", httpStatus, note: `HTTP ${httpStatus}`, issues: [] };
}
const issues = await page.evaluate(collectIssues);
return { route, url, status: "ok", httpStatus, issues };
} catch (err) {
return { route, url, status: "error", note: String(err).slice(0, 200), issues: [] };
} finally {
await page.close();
}
}
async function main() {
// Fail fast if the server dies mid-audit instead of retrying every route.
let consecutiveConnectionFailures = 0;
const serverAlive = async (): Promise<boolean> => {
try {
const res = await fetch(`${BASE_URL}/api/version`, { signal: AbortSignal.timeout(5000) });
return res.ok;
} catch {
return false;
}
};
const browser = await chromium.launch({
executablePath: process.env.E2E_BROWSER_PATH || undefined,
headless: true,
});
const context = await browser.newContext({
viewport: VIEWPORT,
// hasTouch gives (pointer: coarse) so touch-only affordances are judged as
// a phone user sees them. isMobile must stay FALSE: it makes Chromium
// widen the layout viewport to fit overflowing content, which hides the
// very overflows this audit exists to catch (innerWidth silently becomes
// the content width, so scrollWidth > innerWidth never fires).
hasTouch: true,
isMobile: false,
deviceScaleFactor: 2,
});
// Authenticate via REST so gated routes render the app shell instead of the
// landing page. Playwright's request context is flaky under Bun, so use the
// global fetch and inject the resulting cookie into the browser context.
const login = await fetch(`${BASE_URL}/api/users/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: USER, password: PASS }),
});
if (!login.ok) {
console.error(`Login failed (${login.status}). Is the dev server up at ${BASE_URL}?`);
await browser.close();
process.exit(1);
}
const loginBody = (await login.json()) as { token?: string };
if (!loginBody.token) {
console.error("Login response had no token; cannot authenticate the audit context.");
await browser.close();
process.exit(1);
}
authToken = loginBody.token;
await context.addCookies([{ name: "payload-token", value: authToken, url: BASE_URL }]);
const routes: string[] = [...STATIC_ROUTES];
const results: RouteResult[] = [];
for (const dyn of DYNAMIC_ROUTES) {
let value = dyn.fallback ?? null;
if (!value && dyn.collection) {
const doc = await resolveDoc(dyn.collection);
if (doc) {
const raw = (doc as Record<string, unknown>)[dyn.field] ?? doc.id;
if (raw != null) value = String(raw);
}
}
if (!value) {
// Navigating to the literal bracket URL would render a bogus page;
// record an explicit skip instead.
results.push({
route: dyn.template,
url: "-",
status: "skipped",
note: dyn.collection ? `no resolvable doc in dev DB (${dyn.collection})` : "unresolved",
issues: [],
});
continue;
}
routes.push(dyn.template.replace(/\[[^\]]+\]/, value));
}
const wikiDoc = await resolveDoc("wiki-pages");
for (const w of WIKI_ROUTES) {
const slug = wikiDoc?.slug ? String(wikiDoc.slug) : null;
if (!slug) {
results.push({
route: w.template + w.suffix,
url: "-",
status: "skipped",
note: "no wiki page in dev DB",
issues: [],
});
continue;
}
routes.push(w.template.replace("[slug]", slug) + w.suffix);
}
const category = wikiDoc?.category ? String((wikiDoc.category as { category?: string }).category ?? wikiDoc.category) : "general";
routes.push(`/wiki/category/${encodeURIComponent(category || "general")}`);
console.log(`Auditing ${routes.length} routes at ${VIEWPORT.width}x${VIEWPORT.height} against ${BASE_URL}`);
const auditedRoutes = ROUTE_FILTER
? routes.filter((r) =>
ROUTE_FILTER.startsWith("=") ? r === ROUTE_FILTER.slice(1) : r.includes(ROUTE_FILTER),
)
: routes;
if (ROUTE_FILTER) {
// Targeted run: drop pre-seeded skips that did not match the filter.
results.length = 0;
}
if (ROUTE_FILTER) console.log(`Filter "${ROUTE_FILTER}" matched ${auditedRoutes.length} route(s)`);
for (const route of auditedRoutes) {
let result = await auditRoute(context, route);
// Cold-compile can transiently 5xx or stall on first visit; retry once.
if (result.status === "skipped" && (result.httpStatus === 500 || result.httpStatus === 503)) {
console.log(` ~ ${route} returned ${result.httpStatus}, retrying once`);
result = await auditRoute(context, route);
} else if (result.status === "error") {
console.log(` ~ ${route} errored (${(result.note ?? "").slice(0, 60)}), retrying once`);
result = await auditRoute(context, route);
}
if (result.status === "error" && /CONNECTION_REFUSED|CONNECTION_RESET|ECONNREFUSED/.test(result.note ?? "")) {
consecutiveConnectionFailures += 1;
if (consecutiveConnectionFailures >= 2 && !(await serverAlive())) {
console.error("\nDev server stopped responding mid-audit. Restart it and re-run; results are incomplete.");
await browser.close();
process.exit(1);
}
} else {
consecutiveConnectionFailures = 0;
}
const counts = result.issues.reduce<Record<string, number>>((acc, i) => {
acc[i.kind] = (acc[i.kind] ?? 0) + 1;
return acc;
}, {});
console.log(
`${result.status === "ok" ? "✓" : result.status === "skipped" ? "–" : "✗"} ${route} [${result.status}]${result.note ? ` (${result.note})` : ""} ${Object.entries(counts).map(([k, v]) => `${k}:${v}`).join(" ")}`,
);
results.push(result);
}
// Dedupe identical issues per route (same kind+selector repeats across children).
for (const r of results) {
const seen = new Set<string>();
r.issues = r.issues.filter((i) => {
const key = `${i.kind}|${i.selector ?? ""}|${i.detail}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
const byKind: Record<string, { route: string; issue: Issue }[]> = {};
for (const r of results) {
for (const issue of r.issues) {
(byKind[issue.kind] ??= []).push({ route: r.route, issue });
}
}
const summary = Object.fromEntries(
Object.entries(byKind).map(([kind, list]) => [kind, { routes: new Set(list.map((l) => l.route)).size, findings: list.length }]),
);
const report = {
generatedAt: new Date().toISOString(),
baseUrl: BASE_URL,
viewport: VIEWPORT,
routesAudited: results.length,
routesOk: results.filter((r) => r.status === "ok").length,
summary,
results,
};
const suffix = ROUTE_FILTER ? "filtered" : "report";
writeFileSync(join(OUT_DIR, `mobile-audit-${suffix}.json`), JSON.stringify(report, null, 2));
let md = `# Mobile audit (${VIEWPORT.width}x${VIEWPORT.height}) - ${new Date().toISOString()}\n\n`;
md += `Base: ${BASE_URL} | routes audited: ${results.length} (ok: ${report.routesOk})\n\n`;
md += `| Pattern class | Routes affected | Findings |\n|---|---|---|\n`;
for (const [kind, s] of Object.entries(summary)) md += `| ${kind} | ${s.routes} | ${s.findings} |\n`;
// Cross-route clustering: same selector shape recurring across routes is
// one fixable pattern, not N findings. Sessions B-D work per cluster.
const signature = (selector?: string): string => {
if (!selector) return "(document)";
const last = selector.split(" > ").pop() ?? selector;
return last.replace(/#[a-zA-Z0-9_-]+/g, "").slice(0, 60);
};
for (const [kind, list] of Object.entries(byKind)) {
const clusters = new Map<string, { count: number; routes: Set<string>; example: string }>();
for (const item of list) {
const key = signature(item.issue.selector);
const c = clusters.get(key) ?? { count: 0, routes: new Set<string>(), example: item.issue.detail };
c.count += 1;
c.routes.add(item.route);
clusters.set(key, c);
}
const sorted = [...clusters.entries()].sort((a, b) => b[1].routes.size - a[1].routes.size);
md += `\n## ${kind}: pattern clusters\n\n| Selector shape | Findings | Routes | Example |\n|---|---|---|---|\n`;
for (const [sig, c] of sorted.slice(0, 12)) {
md += `| \`${sig}\` | ${c.count} | ${c.routes.size} | ${c.example.slice(0, 50)} |\n`;
}
}
md += `\n---\n\n# Per-route detail\n`;
for (const [kind, list] of Object.entries(byKind)) {
md += `\n## ${kind}\n\n`;
const byRoute = new Map<string, Issue[]>();
for (const item of list) {
const arr = byRoute.get(item.route) ?? [];
arr.push(item.issue);
byRoute.set(item.route, arr);
}
for (const [route, issues] of byRoute) {
md += `### ${route}\n`;
for (const i of issues.slice(0, 8)) md += `- ${i.detail}${i.selector ? ` \`${i.selector}\`` : ""}\n`;
if (issues.length > 8) md += `- ...and ${issues.length - 8} more\n`;
md += "\n";
}
}
mkdirSync(dirname(join(OUT_DIR, `mobile-audit-${suffix}.md`)), { recursive: true });
writeFileSync(join(OUT_DIR, `mobile-audit-${suffix}.md`), md);
console.log(`\nSummary: ${JSON.stringify(summary)}`);
console.log(`Wrote tests/audit/mobile-audit-${suffix}.json and .md`);
await browser.close();
}
main().catch((err) => {
console.error(err);
process.exit(1);
});

View file

@ -0,0 +1,250 @@
import { getPayload, Payload } from "payload";
import config from "@/payload.config";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { Award, Profile, User } from "@/payload-types";
import { evaluateAwardRules } from "@/lib/awards/automation";
import type { AwardMetric, MetricOperator } from "@/lib/awards/metrics";
const RUN = `awardauto-${Date.now().toString(36)}`;
const YEAR_MS = 365.25 * 24 * 60 * 60 * 1000;
function richText(text: string) {
return {
root: {
type: "root",
format: "" as const,
indent: 0,
version: 1,
children: [
{
type: "paragraph",
format: "" as const,
indent: 0,
version: 1,
children: [
{ type: "text", format: 0, style: "", mode: "normal" as const, text, version: 1 },
],
direction: "ltr" as const,
},
],
direction: "ltr" as const,
},
};
}
describe("Award automation sweeper", () => {
let payload: Payload;
let medalId: number;
let tier1Id: number;
let tier2Id: number;
let tier3Id: number;
let veteranId: number;
let rookieId: number;
let ruleIds: number[] = [];
async function makeAward(name: string, seriesTier?: number): Promise<number> {
const created = (await payload.create({
collection: "awards",
data: {
name,
description: richText(`${RUN} test award`),
type: seriesTier ? "ribbon" : "medal",
...(seriesTier
? { advancement: { seriesKey: `${RUN}-yos`, tier: seriesTier } }
: {}),
},
overrideAccess: true,
depth: 0,
})) as unknown as Award;
return created.id;
}
async function makeUser(username: string): Promise<number> {
const user = (await payload.create({
collection: "users",
data: {
username: `${RUN}-${username}`,
discordUsername: `${RUN}-${username}-dc`,
displayName: `${RUN} ${username}`,
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
const profiles = await payload.find({
collection: "profiles",
where: { user: { equals: user.id } },
limit: 1,
depth: 0,
overrideAccess: true,
});
if (!profiles.docs[0]) throw new Error(`profile not auto-created for ${username}`);
return profiles.docs[0].id;
}
async function makeRule(rule: {
label: string;
award: number;
metric: AwardMetric;
operator?: MetricOperator;
value: number;
autoRetireLowerTiers?: boolean;
oncePerSeries?: boolean;
active?: boolean;
}): Promise<number> {
const created = await payload.create({
collection: "award-rules",
data: {
label: rule.label,
award: rule.award,
metric: rule.metric,
operator: rule.operator ?? "gte",
value: rule.value,
autoRetireLowerTiers: rule.autoRetireLowerTiers ?? false,
oncePerSeries: rule.oncePerSeries ?? false,
active: rule.active ?? true,
},
overrideAccess: true,
depth: 0,
});
ruleIds.push(created.id);
return created.id;
}
async function profileAwards(profileId: number) {
const profile = (await payload.findByID({
collection: "profiles",
id: profileId,
depth: 0,
overrideAccess: true,
})) as Profile;
return profile.progression?.awards ?? [];
}
beforeAll(async () => {
const payloadConfig = await config;
payload = await getPayload({ config: payloadConfig });
medalId = await makeAward(`${RUN} Merit Medal`);
tier1Id = await makeAward(`${RUN} YOS Bronze`, 1);
tier2Id = await makeAward(`${RUN} YOS Silver`, 2);
tier3Id = await makeAward(`${RUN} YOS Gold`, 3);
const veteranProfileId = await makeUser("veteran");
veteranId = veteranProfileId;
const rookieProfileId = await makeUser("rookie");
rookieId = rookieProfileId;
// Veteran: enlisted 3 years ago, 150 contribution XP.
await payload.update({
collection: "profiles",
id: veteranProfileId,
data: {
dossier: { enlistmentDate: new Date(Date.now() - 3 * YEAR_MS).toISOString() },
progression: { contributions: { xpEarned: 150 } },
} as unknown as Partial<Profile>,
overrideAccess: true,
depth: 0,
});
// Rookie: enlisted 6 months ago, 10 XP.
await payload.update({
collection: "profiles",
id: rookieProfileId,
data: {
dossier: { enlistmentDate: new Date(Date.now() - 0.5 * YEAR_MS).toISOString() },
progression: { contributions: { xpEarned: 10 } },
} as unknown as Partial<Profile>,
overrideAccess: true,
depth: 0,
});
await makeRule({ label: "100 XP medal", award: medalId, metric: "xpTotal", value: 100 });
await makeRule({ label: "1 year", award: tier1Id, metric: "yearsOfService", value: 1 });
await makeRule({
label: "2 years",
award: tier2Id,
metric: "yearsOfService",
value: 2,
autoRetireLowerTiers: true,
});
await makeRule({
label: "gold once",
award: tier3Id,
metric: "xpTotal",
value: 100,
oncePerSeries: true,
});
await makeRule({
label: "inactive rule",
award: medalId,
metric: "xpTotal",
value: 1,
active: false,
});
});
afterAll(async () => {
for (const id of ruleIds) {
await payload.delete({ collection: "award-rules", id, overrideAccess: true }).catch(() => {});
}
});
it("dry run plans grants and upgrades without writing anything", async () => {
const result = await evaluateAwardRules(payload, { dryRun: true });
expect(result.dryRun).toBe(true);
expect(result.rulesEvaluated).toBe(4); // inactive rule excluded
const veteranPlans = result.plans.filter((p) => p.userId === veteranId);
expect(veteranPlans.map((p) => p.awardId).sort()).toEqual(
[medalId, tier1Id, tier2Id].sort(),
);
const upgradePlan = result.plans.find((p) => p.kind === "upgrade");
expect(upgradePlan?.awardId).toBe(tier2Id);
expect(upgradePlan?.replacesAwardId).toBe(tier1Id);
// oncePerSeries blocks the gold ribbon because the veteran holds the series.
expect(result.skips.some((s) => s.reason === "once-per-series")).toBe(true);
// Nothing written on a dry run.
expect(await profileAwards(veteranId)).toHaveLength(0);
expect(await profileAwards(rookieId)).toHaveLength(0);
});
it("apply writes grants and upgrades, then is idempotent", async () => {
const applied = await evaluateAwardRules(payload);
expect(applied.granted).toBe(2); // medal + tier 1
expect(applied.upgraded).toBe(1); // tier 1 -> tier 2 in place
const veteranAwards = await profileAwards(veteranId);
expect(veteranAwards).toHaveLength(2);
const medalEntry = veteranAwards.find((e) => e.award === medalId);
expect(medalEntry?.awardedBy).toBeNull();
const seriesEntry = veteranAwards.find((e) => e.award === tier2Id);
expect(seriesEntry?.upgradedFrom).toBe(tier1Id);
expect(seriesEntry?.awardedAt).toBeTruthy();
// Rookie never qualifies.
expect(await profileAwards(rookieId)).toHaveLength(0);
// Second run: nothing new to grant.
const rerun = await evaluateAwardRules(payload);
expect(rerun.plans).toHaveLength(0);
expect(rerun.skips.some((s) => s.reason === "already-held")).toBe(true);
expect(await profileAwards(veteranId)).toHaveLength(2);
});
it("emits award:rule-granted game events for applied plans", async () => {
const events = await payload.find({
collection: "game-event-logs",
where: { type: { equals: "award:rule-granted" } },
limit: 50,
depth: 0,
overrideAccess: true,
});
const messages = events.docs.map((doc) => doc.message).join("\n");
expect(messages).toContain("Merit Medal");
expect(messages).toContain("YOS Silver");
});
});

Some files were not shown because too many files have changed in this diff Show more