1
0
Fork 0

Compare commits

...

13 commits

Author SHA1 Message Date
d5bbf86e04 v0.4.1 - coordinate grid, locker sync, item storage, NPC portraits/bio, eval window, flappy ambient layers, /announce role mention 2026-10-05 03:39:43 -04:00
3e9d54486f chore(ui): replace em-dash placeholders with hyphen in NPC readouts
The 'Goods' readout cell rendered an em-dash when the NPC was not a vendor;
dash-sanitize gate requires a plain hyphen on user-facing surfaces.
2026-10-05 03:39:23 -04:00
6959a5ca0d docs: remove stale AI compose changelog entry 2026-10-05 03:37:20 -04:00
9b6935314d feat(bot): auto-mention a role in /announce when unset
Adds DISCORD_ANNOUNCE_MENTION_ROLE_ID; when set, /announce without a message
(compose dialog) posts the announcement with that role mentioned. Documented
in config, env example and the bot design guide.
2026-10-05 03:37:15 -04:00
c626ca3ccc feat(minigames): add drifting clouds and V-flock ambient layers to flappy
Adds drifting cloud layers and a V-flock of ambient birds to the flappy
bird arena for a more lived-in feel, without affecting gameplay.
2026-10-05 03:37:07 -04:00
4b9d231ba5 chore(ui): drop grid-texture hover fade
Remove the hover-only brightening of the tactical dossier grid texture so it
keeps a constant opacity across EmploymentCard, CampaignCard, and the
operations surfaces (OperationSections, StrategicSummary, tokens).
2026-10-05 03:36:38 -04:00
665992a7ea feat(evaluations): mark mission evaluable after scheduled window
isMissionEvaluable now considers the full scheduled window (start +
estimated duration) rather than the start alone, so evaluation reminders
fire once a mission's window has genuinely closed. Extends the profile page,
the remindEvaluations command and the evaluationReminders service to match,
and adds integration tests. Updates the bot evaluation-reminders docs.
2026-10-05 03:36:12 -04:00
f4a0c8e378 chore(types): regenerate payload-types and generated schema 2026-10-05 03:29:34 -04:00
d530de315b chore(migrations): register grid, item storage and NPC migrations
Register 20261005_001212_add_map_grid_config,
20261005_051452_add_game_structure_item_storage and the two game-npc
migrations in the migration index, and normalize trailing commas on the
preceding entries.
2026-10-05 03:27:14 -04:00
755bd04875 feat(personnel): add NPC portraits and rich bio, redesign contact cards
Game NPCs gain an image upload and a Lexical rich-text bio (with data
migration that wraps existing plain text in a paragraph). NPC profile, card
and directory surface the portrait, a status-chip row and initials fallback;
contacts list and detail pages adopt the redesigned cards.
2026-10-05 03:22:11 -04:00
4755cb681a feat(game-structures): add item storage model with per-structure access control
New item storage (limited-arsenal stock) on game-structures: a unique
storageSlug identifying the structure to the game bridge, an Item Storage
Access group (anyone / specific roles / specific users) backed by
canAccessStructureStorage, a storedAssets array (asset, quantity, grid
position, rotation, per-instance attachments/skin/custom name) with a
storedAssetCount rollup, and a beforeChange hook that pushes a locker.apply
command to the game whenever web-originated stock changes. Migration
20261005_051452_add_game_structure_item_storage.
2026-10-05 03:19:32 -04:00
5963082f9d feat(arma-bridge): sync limited-arsenal locker stock with the game
New locker-sync bridge: web-originated storedAssets edits enqueue a
locker.apply command sent to the game, and game-side locker.sync merges
feed back into the member UI. Position/equipment layout is preserved across
merges. Adds the lockers service, LockerStorages + ArmaSyncEvents wiring and
integration tests. Docs in docs/arma-bridge/locker-sync.md.
2026-10-05 03:17:59 -04:00
12cb62b487 feat(map): add Arma-style coordinate grid config, overlay and mission-map wiring
Per-map grid config (gridEnabled, easting/northing origin, spacing, label
digits, over-lines) rides on the Maps collection and surfaces via
/api/map-features. Pure math in src/lib/map/grid.ts mirrors CfgWorlds Grid
(floor truncation, mod-10^digits wrapping, nested levels). GridLayer renders
hairlines + edge labels on the world map and mission planning maps, and
armaGridRef now delegates to gridRef. Migration 20261005_001212_add_map_grid_config.
2026-10-05 03:17:52 -04:00
54 changed files with 150324 additions and 286 deletions

View file

@ -67,6 +67,9 @@ APP_PORT=3000
# App updates: where /announce posts when no channel is given; also the
# channel preselected in the /announce compose dialog.
# DISCORD_ANNOUNCE_CHANNEL_ID=
# Optional: when set, /announce (no message, compose dialog) automatically
# mentions this role in the posted announcement. Leave unset to disable.
# DISCORD_ANNOUNCE_MENTION_ROLE_ID=
# DISCORD_STAFF_ROLE_IDS=
# DISCORD_ATTENDANCE_POLL_MS=
# DISCORD_NOTIFICATION_POLL_MS=

View file

@ -211,6 +211,7 @@ Leaflet world map at `/map` (top-level sidebar entry, whole unit views it). Full
- **Construction**: `src/lib/map/construction.ts`. Construction runs on timestamps: `maybeStartConstruction(payload, siteId, now)` is called at delivery time (shipment `completeShipment`, the structures `addResource`/`transferResource` actions via `addResourceInternal`, and `placeStructure` for materialless blueprints) and, when every blueprint material is stored, consumes them via `consumeStorage`, sets `constructionStartedAt`/`constructionCompletesAt` from the blueprint's `constructionDurationMinutes` (minutes, replacing the old tick-based `constructionTime`), and flips `awaiting_materials` to `building`. The game tick's `processConstructionTick` is a sweeper only: building sites past `constructionCompletesAt` flip to `complete` + `structure:construction-complete` (idempotent). Crew speed (slice 2): blueprint `constructionCrewRequired` gates start (`no_crew` with no labor) and scales duration by staffed fraction (floor 0.25); labor-classifications `buildEfficiency` weights each worker; `setLaborHeadcount` re-prices the remaining work via `applyCrewRateChange` (`src/lib/base/constructionSpeed.ts`). Default constructionStatus on game-structures is `complete` (backward compat). ConstructionPanel on the structure detail page shows required vs delivered + a timestamp-derived progress bar; map markers interpolate progress from the timestamps.
- **UI**: `/map` is a **picker screen** (grid of eligible map cards with basemap thumbnails, linking to `/map/[id]`); the map view itself is `/map/[id]` (`MapLoader` ssr:false + `src/components/frontend/map/MapClient.tsx`, single-map props, no switcher). CRS.Simple with y-flip (latlng = [-y, x]), image (ImageOverlay) or XYZ (TileLayer) basemap, layer toggles (structures/nodes/roads/zones/shipments/ranges), structure markers as status-colored pins (emerald building icon = operational, blue hammer = building, amber package = awaiting materials, with a progress bar under construction sites), popovers linking to `/logistics/structures/[id]`, shipment markers interpolated along `routePath` from `dispatchedAt`/`estimatedArrival`, refreshed by `useGameTick`. Feature data served by `GET /api/map-features?mapId=` (view surface, logged-in). Map labels: zone names render at the polygon centroid, road names render as curved SVG textPath labels following a Catmull-Rom smoothed road line every 400 screen px (max 12/road, flipped to a reversed path when the direction would render upside down or straight down, so vertical labels read bottom-to-top; dark casing stroke for contrast), structure names render as persistent labels with cluster priority (`labelVisible` + `labelPriority` on game-structures; winner = highest `labelPriority`, then stored mass, then id; cluster radius 56 screen px, so zooming in reveals suppressed labels). Road/zone stroke + fill colors, widths, dash styles, and opacities are editable in the authoring toolbar (`strokeColor`/`strokeWeight`/`strokeStyle` on roads; `fillColor`/`strokeColor`/`fillOpacity`/`strokeWeight` on zones; hex validated by `validateHexColor` in `src/lib/map/style.ts`, empty = per-type defaults). Pure label/styling math lives in `src/lib/map/style.ts` (`metersPerPx`, `roadLabelPoints`, `polygonCentroid`, `dashArrayFor`, `roadLabelShown`, `labelScreenAngle`; roads under 600 screen px render one straight midpoint label instead of curved text, since glyphs fold on tiny wiggly paths).
- **Authoring**: edit mode on `/map` (maps:*-gated) draws roads/zones/nodes, edits existing features (popup Edit loads geometry + attributes into the authoring toolbar; Save passes the feature id and requires `maps:update`), and deletes features (server actions in the same actions.ts). Drafts get vertex editing: draggable square handles per draft vertex (drag-end snaps), right-click deletes (min 2 road / 3 zone points), cyan midpoint handles insert a vertex; clicks and drags snap within 12 screen px to feature vertices and zone/road edges (closing segments included; vertices beat edges unless the edge is 2x closer) via pure `src/lib/map/snapping.ts` (`findSnap`, `closestPointOnSegment`, `segmentMidpoints`; `AuthoringSnapLayer` + `DraftHandles` in MapClient). `POST /api/map-import` imports a GeoJSON FeatureCollection (LineString to roads, Polygon to zones, Point to nodes; [x, y] positions used directly as map meters). Mapping table in `docs/map-system.md`.
- **Coordinate grid**: per-map Arma-style grid config on the Maps collection ("Coordinate Grid" group, admin panel): `gridEnabled` master switch, `gridOriginEasting`/`gridOriginNorthing` (meters from the west/south edges to the grid zero line; vanilla terrains use 0), `gridStartEasting`/`gridStartNorthing` (label numbers on the zero line), `gridSpacingMeters` (base cell, default 1000), `gridLabelDigits` (default 2), `gridNumbersOverLines` (Tanoa style: labels on lines instead of cell-centered). Pure math in `src/lib/map/grid.ts` (`gridConfigFromMapDoc`, `gridLevelFor` (power-of-ten ladder, 10x subdivision at close zoom: 1 km/2-digit -> 100 m/3 -> 10 m/4, chosen by on-screen cell size via `GRID_MIN_CELL_PX`), `gridLinesForBounds` (viewport lines + labels in map meters), `gridRef` (6/8-digit references)). Semantics mirror CfgWorlds Grid: floor truncation, labels wrap mod 10^digits with leading zeros (negatives wrap too), levels nest exactly (1 km cell "10" contains 100 m lines "100".."109"). `armaGridRef` (missionMarkers.ts) is a thin wrapper over `gridRef` with `DEFAULT_MAP_GRID`, which reproduces the legacy output. The config rides `MapConfig.grid` from `/api/map-features`; `GridLayer.tsx` (`src/components/frontend/map/`) renders hairlines + edge labels on the world map (Map Control "Grid" toggle) and mission planning maps (header "Grid" switch); both cursor readouts show the configured reference. Migration `20261005_001212_add_map_grid_config` (hand-trimmed; the .json snapshot intentionally covers the full current schema to repair missing sidecars on the three prior hand-written migrations).
- **GameRules**: `proximityThreshold` now means meters (default 1000; migration backfilled rows still at the old default 10). Both call sites (shipments/actions.ts, structures/actions.ts transferResource) use meters.
- **Tests**: `tests/int/map-system.int.spec.ts` (routing graph/snap/refusals, cross-map refusal, ground route + path snapshot, air straight-line, proximity, terrain/range validation, placeStructure happy/water/range cases, construction tick lifecycle, permission gating, label/styling helpers + save-action styling validation). Gotcha: Payload applies select `filterOptions` server-side, so test fixtures must use `approvalStatus: "in_progress"`.
@ -380,7 +381,7 @@ A Discord bot living in `src/bot/`, run as a standalone long-running process via
- **Env / run**: requires `DISCORD_TOKEN` and `DISCORD_GUILD_ID` (fail-fast on missing required vars in `src/bot/config.ts`); optional `DISCORD_OPS_CHANNEL_ID`, `DISCORD_ANNOUNCE_CHANNEL_ID`, `DISCORD_STAFF_ROLE_IDS`, `DISCORD_ATTENDANCE_POLL_MS` (default 60s), `DISCORD_NOTIFICATION_POLL_MS` (default 20s), `DISCORD_EVALUATION_POLL_MS` (default 60s), `DISCORD_IMMINENT_POLL_MS` (default 60s), `DISCORD_SIDE_OPS_CHANNEL_ID` (Friday open-slot notice channel), `DISCORD_COMMUNITY_ZEUS_ROLE_ID` (role ping for that notice), `DISCORD_SIDE_OPS_POLL_MS` (default 30 min), plus existing `APP_URL`. Logs through `payload.logger`.
- **Structure**: `commands/` — `ping`, `signup`, `link`, `announce`, `remindEvaluations`; `events/interactionCreate.ts` — routes `ptf-att:` RSVP buttons; `services/` — `missionEmbeds` (attendance embed lifecycle + reconcile loop), `notificationBridge` (poll → Discord DMs), `evaluationReminders` (post-mission evaluation reminder DMs), `imminentReminders` (pre-op thread + attendee pings), and `fridayOpsNotice` (weekly #side-ops ping when the upcoming Friday has no op, edited to credit the community claimer); `lib/` — `roles.ts` (`isStaff`), `resolve.ts` (discordId ↔ Payload user lookups). Command registration scope: `signup`/`link`/`ping` are **global** (DM-usable — guild-scoped commands never appear in DMs), `announce`/`remind-evaluations` are guild-only.
- **Evaluation reminders**: once a mission is evaluable (`Completed`, or `Scheduled`/`Active` past its start — same rule as `isMissionEvaluable`), the bot sends a one-shot DM (per user with a linked `discordId`) asking them to rate their leadership, plus a "rate your subordinates" section for leaders whose members RSVP'd yes. Links go to each ratee's profile page where the rating dialog lives. Recipient computation: `computeEvaluationReminderPlan` in `src/lib/evaluations/reminders.ts`; state marker: `evaluationRemindersSentAt` on Missions (one-shot, same pattern as `discordAttendanceSentAt`; withheld if the 40-DM/tick cap is hit — retries next tick). These DMs deliberately ignore `preferences.discord.enabled` (defaults false, not yet exposed in the web UI — honoring it would DM nobody). Staff can trigger manually via `/remind-evaluations` (optional `mission` option accepts an ID, name, or code name and re-sends even if the marker is set; omitted, it sweeps all pending missions and reports `{processed, sent}`).
- **Evaluation reminders**: once a mission is evaluable (`Completed`, or `Scheduled`/`Active` whose full scheduled window (start + estimated duration, default 240 min) has passed — same rule as `isMissionEvaluable`), the bot sends a one-shot DM (per user with a linked `discordId`) asking them to rate their leadership, plus a "rate your subordinates" section for leaders whose members RSVP'd yes. Links go to each ratee's profile page where the rating dialog lives. Recipient computation: `computeEvaluationReminderPlan` in `src/lib/evaluations/reminders.ts`; state marker: `evaluationRemindersSentAt` on Missions (one-shot, same pattern as `discordAttendanceSentAt`; withheld if the 40-DM/tick cap is hit — retries next tick). These DMs deliberately ignore `preferences.discord.enabled` (defaults false, not yet exposed in the web UI — honoring it would DM nobody). Staff can trigger manually via `/remind-evaluations` (optional `mission` option accepts an ID, name, or code name and re-sends even if the marker is set; omitted, it sweeps all pending missions and reports `{processed, sent}`).
- **Sign-up / linking (feature 1)**: `/signup` is **DM-only** (the temp password flows through the DM). Creates the Payload user with `username` = `discordUsername` = the caller's Discord username, plus `discordId`, `displayName`, `steamId`, and a random temp password. The ephemeral reply carries the password as the guaranteed delivery path; `interaction.user.send()` is a best-effort persistent copy, so a blocked DM never orphans the account. `/link` works in servers **and** DMs (credential-free, ephemeral reply only) — matches `discordUsername` → sets `discordId`.
- **DM gotcha**: a user with "Allow direct messages from server members" off in Discord privacy settings can neither receive the bot's DMs nor open a DM with the bot. The `/signup` rejection message explains how to enable it.
- **Attendance (feature 2)**: `mission-attendances` collection + `src/lib/attendance/` (single write path, emits `mission:attendance-change`). The bot posts RSVP embeds (Yes/Tentative/No) for future, `Scheduled`, `visibility: "unit"` missions into the ops channel; stores `discordMessageId` + `discordAttendanceHash` on the mission; reconciles hash changes every poll tick (web ↔ Discord two-way sync, loop-safe). Web UI: `MissionAttendance` component on the mission detail page. `bun run payload generate-mission` clones the next weekly main mission.
@ -457,7 +458,7 @@ The recipe (each piece is separable; use subsets, do not feel obliged to use all
4. **Military status language**: squared pill (`rounded-sm`) or plain colored text, uppercase relabels (e.g. Concept → Planning, In Progress → Active Deployment, Completed → Concluded). The status color renders as **text** (`text-blue-400` / `text-emerald-400` / `text-muted-foreground`); do not duplicate status in two places on one card.
5. **Readout footer**: a permanent (not hover-only) single-line bar (`border-t border-white/15 bg-black/60 py-1.5 backdrop-blur-sm`), cells `flex-1` separated by hairline `border-r border-white/15`, each cell a `font-mono text-xs tabular-nums text-white/80` value plus a 9px uppercase `text-white/50` label (e.g. `3 MSNS`, `4h 0m DURATION`). No owner/DIR cell unless the user wants it.
6. **Darkened cover imagery**: image at `opacity-15` (hover 25) under a heavy gradient (`from-black/85 via-black/60 to-black/25`) so text stays readable.
7. **Faint grid texture**: 1px white grid lines, 28px cells, `opacity-[0.04]` (hover 0.07), `motion-reduce` honored.
7. **Faint grid texture**: 1px white grid lines, 28px cells, `opacity-[0.04]`. Constant opacity: it does NOT brighten on hover (only borders/brackets/imagery highlight).
8. **One-shot glitch hover** (only with explicit user opt-in; it is extra motion): every layer fires instantly at 0% then decays; steps-based chaos only in the first ~15-20% of the animation; title/soft text restore to readable within ~25-35%; chromatic aberration via paired cyan/rose `text-shadow`; title shards are duplicated absolutely-positioned `aria-hidden` spans clipped by slanted `clip-path` polygons (cyan `#22d3ee`, rose `#f43f5e`, white); image tears use two ghost `<img>` copies clipped to horizontal bands so pieces shift but nothing ever disappears (never animate `opacity: inherit` on an image, it flashes to full brightness). Image band decay may run longer (2s) than text (1s). Everything is one-shot (no `infinite`) and fully disabled under `prefers-reduced-motion`.
Where it fits: large feature/hero cards, section headers, showcase surfaces. Where it does not: dense data UI, tables, forms, dialogs, buttons, or anything shadcn-styled (the shadcn rule above still governs those). Consistency rule: within one page, secondary surfaces stay conventional so the tactical surface stands out.

View file

@ -38,7 +38,6 @@ Personnel gets a real promotion pipeline, ops move through their lifecycle on th
- **Roll calls**: the Discord sign-up embed goes up three days before a Scheduled op starts and no longer fires for a side op that is still a draft. The old "Ready check" reminder is now a "Schedule check" that nudges creators to commit their op.
- **Arma catalog import**: staff tooling can pull inventory icons out of the game files and bring them into the asset catalog, so imported gear can carry proper artwork.
- **AI compose**: drafts now come from a faster model that keeps replies focused on the writing.
### Fixes

View file

@ -0,0 +1,145 @@
# Locker Sync Contract
Binding contract for limited-arsenal storage sync between the Arma 3 mods and
the web app. It covers **personal lockers** (web `locker-storages`, one per
member) and **structure item storage** (web `game-structures.storedAssets`,
e.g. the Superstructure). Implement exactly what is written here; do not
redesign while implementing.
## Overview
In-game, each storage is a limited ACE Arsenal: every item class has a finite
quantity. The game server is authoritative for what a player physically takes
or deposits in a session; the web app is authoritative for everything outside
the session (member UI edits, admin edits, future crafting/market flows). Two
existing bridge channels carry the data; **no new extension channels** (same
precedent as crate sync — the Python module is closed):
- **Events (mod to web)**: the `locker.*` event family, delivered through the
existing `flush_events` ingestion (`POST /api/arma/v1/events`).
- **Commands (web to mod)**: the `locker.*` command types, delivered through
the existing `pull_commands` / `ack_command` loop.
## Instance identity
An `instanceRef` string identifies one storage:
| Form | Meaning |
|---|---|
| `personal:<steamId>` | The personal locker of the member whose `users.steamId` matches. |
| `structure:<storageSlug>` | The `storedAssets` of the `game-structures` row with this `storageSlug` (e.g. `structure:superstructure`). |
- The mod NEVER embeds a server identifier in an instanceRef. The web resolves
the owning server authoritatively from the authenticated connection
(`eventId = ${serverId}:${event.id}`), exactly as in crate sync.
- `personal:` refs are derived from the opening player's UID at open time; the
same physical locker box serves every player with their own stock.
- `structure:` refs are bound to boxes by the TWWK Eden/Zeus module
(`StructureStorageSlug` argument). Only structures with a `storageSlug`
expose item storage to the game.
## Event family
Payloads are flat arrays (`fn_queueEvent` stores `[_id, _type, _payload,
serverTime]`, payload defaults to `[]`).
| Type | Payload | Meaning |
|---|---|---|
| `locker.sync` | `[instanceRef, [[itemClass, count], ...]]` | Full stock snapshot for one instance after a committed change. |
| `locker.request` | `[instanceRef]` | The game asks the web to push current state for this instance (mission start, player connect, availability refresh). |
`locker.sync` snapshot rules:
- TOP-LEVEL stock only: `[itemClass, count]` pairs, one per class, counts are
integers >= 0. Classes with count 0 MAY be included (explicit depletion) or
omitted (treated as unknown/absent, not as zero — see merge rules).
- Emitted after every committed stock mutation (take settlement, deposit,
Zeus/Eden edit, `locker.apply` application) while the bridge is enabled.
- Dedup is web-side by `eventId`; retried flushes never double-apply.
Snapshots are idempotent wholesale state, so re-application is safe.
## Web-side consumption rules
`locker.sync` merges into the instance's item array keyed by Arma class name:
- `personal:<steamId>`: resolve `users.steamId` → that user's `locker-storages`
row (created lazily if a linked user has none). Unlinked Steam IDs are
logged and skipped (same rule as money sync); the game keeps a session-only
stock for them.
- `structure:<storageSlug>`: resolve the `game-structures` row by `storageSlug`.
Unknown slug is logged and skipped.
- Merge per entry by `asset.className`:
- Existing web entry whose class appears in the snapshot → `quantity` set to
the snapshot count. **All web-managed metadata is preserved**: `gridX`,
`gridY`, `rotated`, and the `equipment` group (attachments, skin,
customName) are never touched by the merge.
- Snapshot class with no web entry → create the entry (asset resolved by
`className`; unknown classes are skipped with a warning) and **auto-place**
it in the next free grid cell (row-major scan, unrotated). Equipment left
empty.
- Web entry whose class is absent from the snapshot → left untouched
(absence is not deletion; the game only reports classes it tracks).
- `itemCount` keeps deriving from the array length via its existing hook.
- Every merged write links the raw `arma-sync-events` row as provenance where
the storage model supports it.
`locker.request` handling:
- Enqueue exactly one `locker.apply` command for the requesting server with
the web's current full snapshot for that instanceRef. Unknown/unlinked
instanceRefs enqueue nothing.
## Command envelope and schemas
Envelope: `[commandId, commandType, payload]` (what `fn_pollCommands` passes
and `fn_executeCommand` destructures), stored in `arma-commands`.
| Type | Payload | Effect |
|---|---|---|
| `locker.apply` | `[instanceRef, [[itemClass, count], ...]]` | Server replaces the instance's stock wholesale with the given pairs, pushes availability to clients, and acks. |
- The web enqueues `locker.apply` when: (a) a member/admin edits locker items
or structure `storedAssets` in the UI (afterChange hook), or (b) a
`locker.request` event arrives. Target server: the most recently heartbeated
game server (single-server assumption, same as crate UI flows).
- The mod-side handler is registered through the bridge's command-handler
registry (`ptf_bridge_fnc_registerCommandHandler`); the bridge mod itself
stays storage-agnostic.
- Unknown instanceRef → the mod acks FAILED with an error string; the command
is marked `failed` web-side and is not retried by the mod.
- Ack shape is the existing `[commandId, success, result, error]`; successful
acks carry the applied instanceRef in `result` for traceability.
- Echo guard: web writes that originate from a `locker.sync` merge mark
`req.context.lockerSyncOrigin = true`; the afterChange enqueue hook skips
such writes so a game-originated change never bounces back as a command.
## Failure rules
- Web event processors never throw: malformed payloads are logged and skipped;
one bad event never aborts the batch or rolls back raw-event ingestion.
- Duplicate eventIds are deduped (counted as duplicates, no double-apply).
- Bridge disabled/unreachable: the mod keeps full session-local stock; queued
`locker.sync` events flush when the bridge returns (queue cap drops oldest,
per existing bridge behavior).
- Game store is volatile per mission (like crate registry): on mission start
the mod emits `locker.request` for every bound structure instance and per
connecting player, and the web replies with `locker.apply`.
## Security
- All channels sit behind `requireArmaServer` (`ARMA_BRIDGE_API_KEY` +
`x-arma-server-id`); server identity is always derived from the connection.
- The `storageAccess` group on `game-structures` (anyone / faction / roles /
users) governs **web UI** visibility/editing of `storedAssets` only; it does
not constrain the bridge (server-to-server) or in-game physical access.
## Mod-side behavior (TWWK `twwk_arsenal`)
- Server store: `instanceRef → (className → count)` in missionNamespace.
- Availability: a class is in the ACE Arsenal virtual-item set iff count > 0
(shared instances: global `addVirtualItems`/`removeVirtualItems`; personal:
targeted per-player local set).
- Settlement: client snapshots gear on `ace_arsenal_displayOpened`, diffs on
`ace_arsenal_displayClosed`, server validates/clamps and commits; live
over-take into containers is clamped per `ace_arsenal_cargoChanged`.
- Deposits run through the same commit path with the sign flipped.

View file

@ -123,7 +123,7 @@ Dependency: `discord.js` ^14 (add to root `package.json`). Script: `"bot": "bun
### D. Evaluation reminders (post-mission)
- **Trigger**: a mission becomes evaluable (status `Completed`, or `Scheduled`/`Active` whose `classification.startDateTime` has fully passed — same rule as `isMissionEvaluable` in `src/lib/evaluations`). Poll loop every `DISCORD_EVALUATION_POLL_MS` (default 60s) queries evaluable missions with no `evaluationRemindersSentAt` marker (one-shot, same pattern as `discordAttendanceSentAt`).
- **Trigger**: a mission becomes evaluable (status `Completed`, or `Scheduled`/`Active` whose scheduled window (`classification.startDateTime` + `classification.estimatedDuration`, default 240 min) has fully passed — same rule as `isMissionEvaluable` in `src/lib/evaluations`). Poll loop every `DISCORD_EVALUATION_POLL_MS` (default 60s) queries evaluable missions with no `evaluationRemindersSentAt` marker (one-shot, same pattern as `discordAttendanceSentAt`).
- **Recipients** (`computeEvaluationReminderPlan` in `src/lib/evaluations/reminders.ts`): participants = users with a "yes" RSVP. Each participant is reminded to rate their direct leader(s); each leader of an assignment containing a participant is reminded to rate that participant (subordinate kind needs no RSVP). Self-pairs skipped; a user who is both gets one merged DM.
- **DM**: embed with "Rate your leadership" / "Rate your subordinates" sections, each line linking to the ratee's profile page (`APP_URL + /profile/<username>`) where the rating dialog lives. Best-effort: DM failures are logged and skipped, marker is set after the pass (cap 40 DMs/tick, 300ms between sends; overflow retries next tick before the marker is set).
- **Deliberate exception**: these DMs ignore `preferences.discord.enabled` (defaults false, not yet exposed in the web UI — honoring it would DM nobody). Dedicated unit-admin flow, not notification-stream forwarding.
@ -162,6 +162,7 @@ Dependency: `discord.js` ^14 (add to root `package.json`). Script: `"bot": "bun
| `DISCORD_IMMINENT_POLL_MS` | no | default 60000 |
| `DISCORD_SIDE_OPS_CHANNEL_ID` | no | #side-ops channel for the Friday open-slot notice |
| `DISCORD_COMMUNITY_ZEUS_ROLE_ID` | no | Community Zeus role ping (falls back to resolving the role by name) |
| `DISCORD_ANNOUNCE_MENTION_ROLE_ID` | no | Role auto-mentioned in `/announce` when called without a message (compose dialog). Unset disables it |
| `DISCORD_SIDE_OPS_POLL_MS` | no | default 1800000 (30 min) |
`APP_URL` already exists — used for login links in DMs.

View file

@ -1,6 +1,6 @@
{
"name": "polaris-task-force",
"version": "0.4.0",
"version": "0.4.1",
"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

@ -150,23 +150,24 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) {
const listings = listingsRes.docs as unknown as MarketListing[];
return (
<div className="grid gap-6 lg:grid-cols-2">
<div className="lg:col-span-2">
<NpcProfile npc={npc} listings={listings} />
</div>
<div className="px-5 pb-5 lg:col-start-2">
<EmploymentCard
employment={employment}
structures={structures}
canManage={canManage}
npcId={npc.id}
npcName={npc.name}
classifications={classifications}
hiringEnabled={Boolean(rules.staffHiringEnabled)}
hiringDisabledMessage={rules.staffHiringDisabledMessage ?? undefined}
currencyConfig={currencyConfig}
/>
</div>
<div className="p-5">
<NpcProfile
npc={npc}
listings={listings}
employmentSlot={
<EmploymentCard
employment={employment}
structures={structures}
canManage={canManage}
npcId={npc.id}
npcName={npc.name}
classifications={classifications}
hiringEnabled={Boolean(rules.staffHiringEnabled)}
hiringDisabledMessage={rules.staffHiringDisabledMessage ?? undefined}
currencyConfig={currencyConfig}
/>
}
/>
</div>
);
}

View file

@ -3,6 +3,11 @@ import { getPayload } from "payload";
import type { GameNpc } from "@/payload-types";
import { UsersIcon } from "lucide-react";
import { NpcDirectory } from "@/components/frontend/personnel/NpcDirectory";
import {
ClassificationStrip,
CornerBrackets,
DOSSIER,
} from "@/components/frontend/operations";
export const metadata = {
title: "Contacts: Polaris Task Force",
@ -19,15 +24,28 @@ export default async function ContactsPage() {
return (
<div className="flex flex-col gap-6 p-5">
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2">
<UsersIcon className="size-5 text-muted-foreground" />
<h1 className="text-lg font-semibold">Contacts</h1>
<header className="group relative overflow-hidden rounded-none border border-border/70 bg-card">
<div
aria-hidden="true"
className="pointer-events-none absolute inset-0 z-[5] opacity-[0.04]"
style={DOSSIER.gridTexture}
/>
<ClassificationStrip
left="Theater Contacts // Personnel"
right={`${npcs.length} Recorded`}
/>
<CornerBrackets />
<div className="relative z-10 flex items-center gap-3 px-5 py-4">
<UsersIcon className="size-5 shrink-0 text-white/50" />
<div className="flex flex-col gap-0.5">
<h1 className="text-xl font-bold tracking-tight text-white">Contacts</h1>
<p className="text-sm text-white/60">
{npcs.length} contact{npcs.length !== 1 ? "s" : ""} recorded in the theater of
operations.
</p>
</div>
</div>
<p className="text-sm text-muted-foreground">
{npcs.length} contact{npcs.length !== 1 ? "s" : ""} recorded in the theater of operations.
</p>
</div>
</header>
<NpcDirectory npcs={npcs} />
</div>

View file

@ -188,7 +188,7 @@ async function findEligibleEvaluationMissions(
depth: 0,
select: {
name: true,
classification: { startDateTime: true },
classification: { startDateTime: true, estimatedDuration: true },
ownershipAndStatus: { status: true },
},
overrideAccess: true,
@ -199,6 +199,7 @@ async function findEligibleEvaluationMissions(
isMissionEvaluable(
mission.ownershipAndStatus.status,
mission.classification.startDateTime,
mission.classification.estimatedDuration ?? null,
now,
),
)

View file

@ -3604,6 +3604,33 @@
pointer-events: none;
}
.map-grid-label-icon {
background: transparent;
border: none;
}
.map-grid-label {
color: rgb(255 255 255 / 85%);
font-family:
ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New",
monospace;
font-size: 10px;
letter-spacing: 0.05em;
white-space: nowrap;
/* Size to the text itself: inside the 0x0 divIcon container a block div
resolves to 0 width, which makes the percentage anchoring transform a
no-op and leaves the label hanging off the edge. */
width: max-content;
text-shadow:
0 0 3px rgb(0 0 0 / 90%),
0 0 1px rgb(0 0 0 / 90%);
pointer-events: none;
}
.leaflet-container .map-grid-label-icon {
pointer-events: none;
}
/* Radix floating panels (Select/DropdownMenu/Popover/Tooltip) portal to <body>
and would otherwise paint below the map page's high-z overlays (authoring
toolbar z-[1000], structure drawer z-[1200]). Pin every popper wrapper above

View file

@ -9,6 +9,7 @@ import {
isOperationalMember,
} from "@/lib/map/compounds";
import { isPointArray, type MapPoint } from "@/lib/map/points";
import { gridConfigFromMapDoc } from "@/lib/map/grid";
import type { MapFeaturesResponse, StructureFeature } from "@/lib/map/types";
export const dynamic = "force-dynamic";
@ -288,6 +289,7 @@ export async function GET(req: NextRequest) {
maxZoom: mapDoc.maxZoom ?? 12,
defaultZoom: mapDoc.defaultZoom ?? 2,
defaultCenter: [mapDoc.defaultCenterX ?? worldW / 2, mapDoc.defaultCenterY ?? worldH / 2],
grid: gridConfigFromMapDoc(mapDoc as unknown as Record<string, unknown>),
},
structures,
nodes,

View file

@ -46,8 +46,12 @@ const postAnnouncement = async (
channel: TextBasedChannelFields,
title: string,
message: string,
mentionRoleId?: string | null,
): Promise<void> => {
// The role mention has to live in `content`, not the embed description:
// Discord only pings on a mention in the message content, never inside an embed.
await channel.send({
content: mentionRoleId ? `<@&${mentionRoleId}>` : undefined,
embeds: [
new EmbedBuilder()
.setTitle(title || "Announcement")
@ -187,7 +191,12 @@ export const handleAnnounceModal = async (
return;
}
await postAnnouncement(channel as TextBasedChannelFields, title, message);
await postAnnouncement(
channel as TextBasedChannelFields,
title,
message,
botConfig.announceMentionRoleId,
);
const name = (channel as unknown as { name?: string | null }).name ?? resolvedId;
await interaction.reply(ephemeral(`Announcement posted to #${name}.`));

View file

@ -89,10 +89,11 @@ export const remindEvaluationsCommand: BotCommand = {
!isMissionEvaluable(
mission.ownershipAndStatus?.status ?? "",
mission.classification?.startDateTime ?? null,
mission.classification?.estimatedDuration ?? null,
)
) {
await interaction.editReply(
`**${missionLabel(mission)}** isn't evaluable yet: missions must be completed or past their scheduled start before reminders go out.`,
`**${missionLabel(mission)}** isn't evaluable yet: missions must be completed or past their scheduled window before reminders go out.`,
);
return;
}

View file

@ -7,6 +7,7 @@ export interface BotConfig {
staffRoleIds: string[];
sideOpsChannelId: string | null;
communityZeusRoleId: string | null;
announceMentionRoleId: string | null;
attendancePollMs: number;
notificationPollMs: number;
evaluationPollMs: number;
@ -52,6 +53,7 @@ export const botConfig: BotConfig = {
.filter((id) => id.length > 0),
sideOpsChannelId: optional("DISCORD_SIDE_OPS_CHANNEL_ID"),
communityZeusRoleId: optional("DISCORD_COMMUNITY_ZEUS_ROLE_ID"),
announceMentionRoleId: optional("DISCORD_ANNOUNCE_MENTION_ROLE_ID"),
attendancePollMs: pollMs("DISCORD_ATTENDANCE_POLL_MS", 60_000),
notificationPollMs: pollMs("DISCORD_NOTIFICATION_POLL_MS", 20_000),
evaluationPollMs: pollMs("DISCORD_EVALUATION_POLL_MS", 60_000),

View file

@ -186,6 +186,7 @@ export const reconcile = async (client: Client, payload: Payload): Promise<Recon
isMissionEvaluable(
mission.ownershipAndStatus?.status ?? "",
mission.classification?.startDateTime ?? null,
mission.classification?.estimatedDuration ?? null,
),
);
for (const mission of missions) {

View file

@ -25,6 +25,15 @@ export const GameNpcs: CollectionConfig = {
description: "The NPC's name as shown in-game and on the frontend.",
},
},
{
name: "image",
type: "upload",
relationTo: "media",
admin: {
description:
"Portrait/photo for this contact. Shown on the contacts directory and profile when set.",
},
},
{
name: "occupation",
type: "text",
@ -50,7 +59,7 @@ export const GameNpcs: CollectionConfig = {
},
{
name: "bio",
type: "textarea",
type: "richText",
admin: {
description: "A short background/profile for this NPC.",
},

View file

@ -1,11 +1,63 @@
import type { CollectionConfig } from "payload";
import { requirePermission } from "@/utils/access-control/hasPermission";
import type { CollectionConfig, PayloadRequest } from "payload";
import { requirePermission, hasPermission } from "@/utils/access-control/hasPermission";
import { emitGameEvent } from "@/utils/event-log/emit";
import { staffingDefaultsFromBlueprint } from "@/lib/base/staffingDefaults";
import { createStaffingFields } from "./staffingFields";
import { createProductionFields } from "./productionFields";
import { createModuleFields } from "./moduleFields";
import { productionDefaultsFromBlueprint } from "@/lib/base/productionDefaults";
import { enqueueLockerApplyForStructureDoc, isLockerSyncOrigin } from "@/lib/arma-bridge/lockers";
function relId(value: unknown): number | null {
if (typeof value === "number") return value;
if (value !== null && typeof value === "object" && "id" in (value as { id: unknown })) {
const id = (value as { id: unknown }).id;
return typeof id === "number" ? id : null;
}
return null;
}
/**
* Field-level gate for storedAssets (web UI only — bridge sync writes use
* overrideAccess and are unaffected). Admins with game-structures:update
* always pass; otherwise the structure's storageAccess mode decides:
* anyone / specific roles (matched against the user's roleDocs) / specific
* users. A "faction" mode is deliberately not offered yet: members have no
* faction linkage in the users/profiles model, so it could not be evaluated.
*/
async function canAccessStructureStorage({
req,
doc,
}: {
req: PayloadRequest;
doc?: Record<string, unknown> | null;
}): Promise<boolean> {
const user = req.user;
if (!user) return false;
if (await hasPermission(req.payload, user, "game-structures:update")) return true;
const access = (doc?.storageAccess ?? undefined) as
| { mode?: string; roles?: unknown; users?: unknown }
| undefined;
const mode = access?.mode ?? "anyone";
if (mode === "anyone") return true;
if (mode === "roles") {
const allowed = (Array.isArray(access?.roles) ? (access.roles as unknown[]) : [])
.map(relId)
.filter((v): v is number => v != null);
const userRoles = (Array.isArray((user as { roleDocs?: unknown }).roleDocs)
? ((user as { roleDocs: unknown[] }).roleDocs as unknown[])
: []
)
.map(relId)
.filter((v): v is number => v != null);
return allowed.length > 0 && userRoles.some((role) => allowed.includes(role));
}
if (mode === "users") {
const allowed = (Array.isArray(access?.users) ? (access.users as unknown[]) : []).map(relId);
return allowed.includes(user.id);
}
return false;
}
export const GameStructures: CollectionConfig = {
slug: "game-structures",
@ -80,6 +132,17 @@ export const GameStructures: CollectionConfig = {
},
});
},
// Locker sync (docs/arma-bridge/locker-sync.md): web-originated
// storedAssets edits push a locker.apply command to the game. Writes
// that came from a locker.sync merge are marked in req.context and
// skipped so they never echo back.
async ({ doc, previousDoc, req }) => {
if (isLockerSyncOrigin(req)) return;
const d = doc as Record<string, unknown>;
const prev = (previousDoc ?? {}) as Record<string, unknown>;
if (JSON.stringify(prev.storedAssets ?? []) === JSON.stringify(d.storedAssets ?? [])) return;
await enqueueLockerApplyForStructureDoc(req.payload, doc);
},
],
},
fields: [
@ -302,5 +365,176 @@ export const GameStructures: CollectionConfig = {
},
],
},
{
name: "storageSlug",
type: "text",
unique: true,
index: true,
validate: (value: unknown) =>
value == null ||
value === "" ||
(typeof value === "string" && /^[a-z0-9][a-z0-9-_]{1,63}$/.test(value)) ||
"2-64 chars: lowercase letters, digits, '-' and '_', starting with a letter or digit.",
admin: {
description:
"Slug identifying this structure's item storage to the game bridge (e.g. 'superstructure'). The in-game arsenal module binds to structure:<slug>. Empty = no item storage.",
},
},
{
name: "storageAccess",
type: "group",
label: "Item Storage Access",
admin: {
description:
"Who can see and edit this structure's item storage in the member UI. Bridge (game) sync is unaffected by these rules.",
},
fields: [
{
name: "mode",
type: "select",
// NOT required and no required parent: a required mode makes the
// whole storageAccess group required in generated create-data types,
// which breaks every existing game-structures create call site
// (Payload 3.88 draft-overload gotcha). Runtime treats empty as
// "anyone" (see canAccessStructureStorage).
defaultValue: "anyone",
options: [
{ label: "Anyone (all members)", value: "anyone" },
{ label: "Specific roles", value: "roles" },
{ label: "Specific users", value: "users" },
],
},
{
name: "roles",
type: "relationship",
relationTo: "roles",
hasMany: true,
admin: {
condition: (_data, siblingData) => siblingData?.mode === "roles",
description: "Members holding any of these roles (Role Assignments) can access the storage.",
},
},
{
name: "users",
type: "relationship",
relationTo: "users",
hasMany: true,
admin: {
condition: (_data, siblingData) => siblingData?.mode === "users",
description: "Only these members can access the storage.",
},
},
],
},
{
name: "storedAssets",
type: "array",
access: {
read: canAccessStructureStorage,
create: canAccessStructureStorage,
update: canAccessStructureStorage,
},
admin: {
description:
"Arma item storage (limited-arsenal stock). Synced with the game via locker.sync / locker.apply; grid position and equipment are managed from the member UI and preserved by sync merges.",
},
fields: [
{
name: "asset",
type: "relationship",
relationTo: "assets",
required: true,
},
{
name: "quantity",
type: "number",
required: true,
min: 1,
defaultValue: 1,
},
{
name: "gridX",
type: "number",
required: true,
min: 0,
defaultValue: 0,
admin: {
description: "Column position in the storage grid (0-indexed).",
},
},
{
name: "gridY",
type: "number",
required: true,
min: 0,
defaultValue: 0,
admin: {
description: "Row position in the storage grid (0-indexed).",
},
},
{
name: "rotated",
type: "checkbox",
defaultValue: false,
admin: {
description: "Whether this item is rotated 90 degrees (swaps width and height).",
},
},
{
name: "equipment",
type: "group",
label: "Equipment Customization",
admin: {
description:
"Per-instance customization for this item: installed attachments, applied skin, and a custom name. Managed from the member storage UI.",
},
fields: [
{
name: "attachments",
type: "array",
label: "Installed Attachments",
fields: [
{
name: "asset",
type: "relationship",
relationTo: "assets",
required: true,
},
],
},
{
name: "skin",
type: "relationship",
relationTo: "assets",
filterOptions: {
assetType: {
equals: "skin",
},
},
},
{
name: "customName",
type: "text",
},
],
},
],
},
{
name: "storedAssetCount",
type: "number",
admin: {
readOnly: true,
description: "Total number of distinct entries currently in item storage.",
},
hooks: {
beforeChange: [
({ data }) => {
const items = (data as { storedAssets?: unknown[] } | undefined)?.storedAssets;
return Array.isArray(items) ? items.length : 0;
},
],
},
},
],
};

View file

@ -1,5 +1,6 @@
import { CollectionConfig } from "payload";
import { requirePermission, hasPermission } from "@/utils/access-control/hasPermission";
import { enqueueLockerApplyForLockerDoc, isLockerSyncOrigin } from "@/lib/arma-bridge/lockers";
export const LockerStorages: CollectionConfig = {
slug: "locker-storages",
@ -8,6 +9,18 @@ export const LockerStorages: CollectionConfig = {
useAsTitle: "name",
defaultColumns: ["name", "ownerUser", "itemCount"],
},
hooks: {
afterChange: [
// Locker sync (docs/arma-bridge/locker-sync.md): web-originated item
// edits push a locker.apply command to the game. Writes that came from
// a locker.sync merge are marked in req.context and skipped.
async ({ doc, req, operation }) => {
if (operation !== "create" && operation !== "update") return;
if (isLockerSyncOrigin(req)) return;
await enqueueLockerApplyForLockerDoc(req.payload, doc);
},
],
},
access: {
read: async ({ req }) => {
if (!req.user) return false;

View file

@ -2,6 +2,7 @@ import { CollectionConfig } from "payload";
import { processPlayerKill } from "@/lib/arma-bridge/processSyncEvents";
import { processBoxEvent } from "@/lib/arma-bridge/crates";
import { processMoneyEvent } from "@/lib/arma-bridge/money";
import { processLockerEvent } from "@/lib/arma-bridge/lockers";
import { isOperationLedgerEnabled } from "@/lib/operations/rollout";
import { processOperationEvent } from "@/lib/operations/process";
@ -40,6 +41,15 @@ export const ArmaSyncEvents: CollectionConfig = {
// flushing). processMoneyEvent never throws.
await processMoneyEvent(req.payload, doc);
}
if (doc.type.startsWith("locker.")) {
// Awaited (same posture as box.*): locker writes join the raw-event
// transaction; processLockerEvent never throws.
try {
await processLockerEvent(req.payload, doc, req);
} catch (err) {
req.payload.logger.error(`[LockerSync] Failed to process locker event ${doc.eventId}: ${err}`);
}
}
},
],
},

View file

@ -208,5 +208,105 @@ export const Maps: CollectionConfig = {
},
],
},
{
label: "Coordinate Grid",
type: "group",
admin: {
description:
"Arma-style coordinate grid overlay + grid references. Set up to match the terrain's in-game grid (CfgWorlds Grid class).",
},
fields: [
{
name: "gridEnabled",
type: "checkbox",
label: "Enable Grid",
defaultValue: false,
admin: {
description:
"Show a coordinate grid on the world map and mission planning maps, and use it for grid reference readouts.",
},
},
{
name: "gridOriginEasting",
type: "number",
label: "Origin Easting (m)",
defaultValue: 0,
admin: {
condition: (_data, siblingData) => siblingData?.gridEnabled === true,
description:
"Meters from the west edge (in-game X) to the grid's zero line. Vanilla terrains use 0 (zero line on the west edge).",
},
},
{
name: "gridOriginNorthing",
type: "number",
label: "Origin Northing (m)",
defaultValue: 0,
admin: {
condition: (_data, siblingData) => siblingData?.gridEnabled === true,
description:
"Meters from the south edge (in-game Y) to the grid's zero line. Vanilla terrains use 0 (zero line on the south edge).",
},
},
{
name: "gridStartEasting",
type: "number",
label: "Starting Easting Number",
defaultValue: 0,
admin: {
condition: (_data, siblingData) => siblingData?.gridEnabled === true,
description:
"Number shown on the first easting line (at the origin). Applies at the base spacing and finer subdivisions.",
},
},
{
name: "gridStartNorthing",
type: "number",
label: "Starting Northing Number",
defaultValue: 0,
admin: {
condition: (_data, siblingData) => siblingData?.gridEnabled === true,
description:
"Number shown on the first northing line (at the origin). Applies at the base spacing and finer subdivisions.",
},
},
{
name: "gridSpacingMeters",
type: "number",
label: "Cell Spacing (m)",
defaultValue: 1000,
min: 1,
admin: {
condition: (_data, siblingData) => siblingData?.gridEnabled === true,
description:
"Base grid cell size in meters. The map subdivides 10x automatically as you zoom in, like the in-game map.",
},
},
{
name: "gridLabelDigits",
type: "number",
label: "Label Digits",
defaultValue: 2,
min: 1,
max: 6,
admin: {
condition: (_data, siblingData) => siblingData?.gridEnabled === true,
description:
"Digits shown per axis at the base spacing (Arma shows 2 at 1 km, 3 at 100 m). Numbers wrap at the digit width.",
},
},
{
name: "gridNumbersOverLines",
type: "checkbox",
label: "Numbers Over Lines",
defaultValue: false,
admin: {
condition: (_data, siblingData) => siblingData?.gridEnabled === true,
description:
"Draw labels on the grid lines instead of centered in the cells (Tanoa style).",
},
},
],
},
],
};

View file

@ -1,10 +1,11 @@
"use client";
import { BadgeCheckIcon } from "lucide-react";
import { Building2Icon } from "lucide-react";
import type { CurrencyConfig } from "@/lib/banking/format";
import { CurrencyAmount } from "@/components/frontend/banking/CurrencyAmount";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { StrategicSummary } from "@/components/frontend/operations";
import { HireStaffDialog } from "@/components/frontend/baseManagement/HireStaffDialog";
import { cn } from "@/lib/utils";
import type { LaborClassificationOption, StructureStaffingOption } from "@/lib/base";
interface EmploymentCardProps {
@ -24,6 +25,28 @@ interface EmploymentCardProps {
readonly currencyConfig: CurrencyConfig;
}
/** Squared tactical chip colors per staffing position type. */
const POSITION_TYPE_STYLES: Record<string, string> = {
labor: "border-amber-500/40 bg-amber-500/20 text-amber-400",
administrative: "border-blue-500/40 bg-blue-500/20 text-blue-400",
technical: "border-violet-500/40 bg-violet-500/20 text-violet-400",
other: "border-white/25 bg-white/10 text-white/70",
};
function PositionTypeChip({ type }: { type: string }) {
const style = POSITION_TYPE_STYLES[type] ?? POSITION_TYPE_STYLES.other;
return (
<span
className={cn(
"inline-flex items-center border px-1.5 py-px font-mono text-[9px] uppercase leading-none tracking-widest",
style,
)}
>
{type}
</span>
);
}
export function EmploymentCard({
employment,
structures,
@ -36,50 +59,46 @@ export function EmploymentCard({
currencyConfig,
}: EmploymentCardProps) {
return (
<Card>
<CardHeader className="gap-2">
<CardTitle className="flex items-center gap-2">
<BadgeCheckIcon className="size-4 text-muted-foreground" />
Employment
</CardTitle>
<CardDescription>Current base assignment and compensation.</CardDescription>
</CardHeader>
<CardContent>
{employment ? (
<div className="flex flex-col gap-2">
<p className="font-medium">{employment.positionTitle}</p>
<p className="text-sm text-muted-foreground">
{employment.positionType} · {employment.structureName}
</p>
<p className="font-mono text-sm tabular-nums">
<CurrencyAmount value={employment.salary} currency={currencyConfig} />/tick
</p>
<StrategicSummary classificationLeft="Employment" classificationRight="Base Assignment">
{employment ? (
<div className="flex flex-col gap-3">
<div className="flex flex-wrap items-center gap-2">
<p className="font-medium text-white/90">{employment.positionTitle}</p>
<PositionTypeChip type={employment.positionType} />
</div>
) : canManage && hiringEnabled ? (
<div className="flex flex-wrap items-center justify-between gap-3">
<p className="text-sm text-muted-foreground">Not currently employed.</p>
<HireStaffDialog
structures={structures}
npcs={[{ id: npcId, name: npcName ?? `NPC #${npcId}` }]}
fixedNpcId={npcId}
canManage={canManage}
classifications={classifications}
hiringEnabled={hiringEnabled}
hiringDisabledMessage={hiringDisabledMessage}
currencyConfig={currencyConfig}
/>
<div className="flex items-center gap-2 text-sm text-white/60">
<Building2Icon className="size-3.5 shrink-0 text-white/40" />
<span className="truncate">{employment.structureName}</span>
</div>
) : canManage ? (
<div className="flex flex-col gap-2">
<p className="text-sm text-muted-foreground">Not currently employed.</p>
<p className="text-sm text-muted-foreground">
{hiringDisabledMessage || "Staff hiring is currently disabled."}
</p>
<div className="flex items-center gap-1.5 font-mono text-sm tabular-nums text-white/90">
<CurrencyAmount value={employment.salary} currency={currencyConfig} />
<span>/tick</span>
</div>
) : (
<p className="text-sm text-muted-foreground">Not currently employed.</p>
)}
</CardContent>
</Card>
</div>
) : canManage && hiringEnabled ? (
<div className="flex flex-wrap items-center justify-between gap-3">
<p className="text-sm text-white/60">Not currently employed.</p>
<HireStaffDialog
structures={structures}
npcs={[{ id: npcId, name: npcName ?? `NPC #${npcId}` }]}
fixedNpcId={npcId}
canManage={canManage}
classifications={classifications}
hiringEnabled={hiringEnabled}
hiringDisabledMessage={hiringDisabledMessage}
currencyConfig={currencyConfig}
/>
</div>
) : canManage ? (
<div className="flex flex-col gap-2">
<p className="text-sm text-white/60">Not currently employed.</p>
<p className="text-sm text-white/50">
{hiringDisabledMessage || "Staff hiring is currently disabled."}
</p>
</div>
) : (
<p className="text-sm text-white/60">Not currently employed.</p>
)}
</StrategicSummary>
);
}

View file

@ -143,7 +143,7 @@ export function CampaignCard({ campaign, size = "lg" }: CampaignCardProps) {
{!isSmall && (
<div
aria-hidden="true"
className="pointer-events-none absolute inset-0 z-[5] opacity-[0.04] transition-opacity duration-500 group-hover:opacity-[0.07] motion-reduce:transition-none"
className="pointer-events-none absolute inset-0 z-[5] opacity-[0.04]"
style={{
backgroundImage:
"linear-gradient(to right, white 1px, transparent 1px), linear-gradient(to bottom, white 1px, transparent 1px)",
@ -166,7 +166,7 @@ export function CampaignCard({ campaign, size = "lg" }: CampaignCardProps) {
{!isSmall && (
<div
aria-hidden="true"
className="absolute inset-x-0 top-0 z-20 flex items-center justify-between border-b border-white/15 bg-black/50 px-3 py-1.5 backdrop-blur-sm"
className="absolute inset-x-0 top-0 z-20 flex items-center justify-between border-b border-white/15 bg-black/50 px-5 py-1.5 backdrop-blur-sm"
>
<span className="font-mono text-[9px] uppercase tracking-widest text-white/60">
Official // Unit Command

View file

@ -18,6 +18,8 @@ import {
import type { MapPoint } from "@/lib/map/points";
import { dashArrayFor, metersPerPx, splinePolyline } from "@/lib/map/style";
import type { MapFeaturesResponse } from "@/lib/map/types";
import type { MapGridConfig } from "@/lib/map/grid";
import { GridLayer } from "@/components/frontend/map/GridLayer";
import { markerBrushOf, resolveMarkerRgba, rgbaToHex } from "@/lib/arma-markers";
import {
areaOutline,
@ -38,12 +40,18 @@ export interface MissionMapCanvasProps {
canEdit: boolean;
showRoads: boolean;
showZones: boolean;
showGrid: boolean;
onSelect: (id: number | null) => void;
onCreate: (data: MissionMarkerData) => void;
/** persist=false for live drag previews, true on drag end. */
onChange: (marker: MissionMarker, persist: boolean) => void;
onCursor: (point: MapPoint | null) => void;
onLoaded: (info: { worldWidth: number; worldHeight: number; hasBasemap: boolean }) => void;
onLoaded: (info: {
worldWidth: number;
worldHeight: number;
hasBasemap: boolean;
grid: MapGridConfig;
}) => void;
}
const toLatLng = (p: MapPoint): [number, number] => [-p[1], p[0]];
@ -520,6 +528,7 @@ export function MissionMapCanvas({
canEdit,
showRoads,
showZones,
showGrid,
onSelect,
onCreate,
onChange,
@ -550,6 +559,7 @@ export function MissionMapCanvas({
(body.map.basemapMode === "image" && body.map.basemapImageUrl) ||
(body.map.basemapMode === "tiles" && body.map.tileUrlTemplate),
),
grid: body.map.grid,
});
})
.catch((e: unknown) => {
@ -669,6 +679,10 @@ export function MissionMapCanvas({
(mapConfig.basemapMode === "tiles" && mapConfig.tileUrlTemplate)
) && <Rectangle bounds={worldBounds} pathOptions={BASEMAP_FALLBACK} interactive={false} />}
{mapConfig?.grid.enabled && showGrid && (
<GridLayer config={mapConfig.grid} worldWidth={worldW} worldHeight={worldH} />
)}
{showZones &&
zonePolys.map(({ zone, positions, options }) => (
<Polygon key={`zone-${zone.id}`} positions={positions} pathOptions={options} />

View file

@ -24,12 +24,12 @@ import {
DEFAULT_MARKER_TYPE,
} from "@/lib/arma-markers";
import {
armaGridRef,
markersToSqf,
normalizeMarkerInput,
type MissionMarker,
type MissionMarkerData,
} from "@/lib/arma-markers/missionMarkers";
import { DEFAULT_MAP_GRID, gridRef, type MapGridConfig } from "@/lib/map/grid";
import type { MapPoint } from "@/lib/map/points";
import {
clearMissionMapMarkers,
@ -112,7 +112,9 @@ export function MissionPlanningMap({
const [cursor, setCursor] = useState<MapPoint | null>(null);
const [showRoads, setShowRoads] = useState(true);
const [showZones, setShowZones] = useState(true);
const [showGrid, setShowGrid] = useState(true);
const [world, setWorld] = useState({ width: map.worldWidth, height: map.worldHeight });
const [gridConfig, setGridConfig] = useState<MapGridConfig>(DEFAULT_MAP_GRID);
const [toggling, setToggling] = useState(false);
const timers = useRef(new Map<number, ReturnType<typeof setTimeout>>());
@ -278,8 +280,10 @@ export function MissionPlanningMap({
}, [enabled, canEdit, selectedId, tool, handleDelete]);
const handleLoaded = useCallback(
(info: { worldWidth: number; worldHeight: number }) =>
setWorld({ width: info.worldWidth, height: info.worldHeight }),
(info: { worldWidth: number; worldHeight: number; grid: MapGridConfig }) => {
setWorld({ width: info.worldWidth, height: info.worldHeight });
setGridConfig(info.grid);
},
[],
);
@ -362,6 +366,15 @@ export function MissionPlanningMap({
Planning map // {missionLabel}
</span>
<div className="flex shrink-0 items-center gap-3">
<label className="flex items-center gap-1.5">
<Switch size="sm" checked={showGrid} onCheckedChange={setShowGrid} id="plan-grid" />
<Label
htmlFor="plan-grid"
className="font-mono text-[9px] uppercase tracking-widest text-white/60"
>
Grid
</Label>
</label>
<label className="flex items-center gap-1.5">
<Switch size="sm" checked={showRoads} onCheckedChange={setShowRoads} id="plan-roads" />
<Label
@ -401,6 +414,7 @@ export function MissionPlanningMap({
canEdit={canEdit}
showRoads={showRoads}
showZones={showZones}
showGrid={showGrid}
onSelect={setSelectedId}
onCreate={(data) => void handleCreate(data)}
onChange={handleChange}
@ -469,7 +483,10 @@ export function MissionPlanningMap({
<ReadoutCell value={String(counts.icons)} label="Icons" />
<ReadoutCell value={String(counts.areas)} label="Areas" />
<ReadoutCell value={String(counts.lines)} label="Lines" />
<ReadoutCell value={cursor ? armaGridRef(cursor, world.height) : "--- ---"} label="Grid" />
<ReadoutCell
value={cursor ? gridRef(cursor, world.height, gridConfig) : "--- ---"}
label="Grid"
/>
<ReadoutCell
value={`${(Math.max(world.width, world.height) / 1000).toFixed(1)} km`}
label="World"

View file

@ -0,0 +1,208 @@
"use client";
import L from "leaflet";
import { Fragment, memo, useCallback, useEffect, useState } from "react";
import { Marker, Polyline, useMap, useMapEvents } from "react-leaflet";
import {
gridLinesForBounds,
type GridBounds,
type MapGridConfig,
} from "@/lib/map/grid";
import { metersPerPx } from "@/lib/map/style";
export interface GridLayerProps {
config: MapGridConfig;
worldWidth: number;
worldHeight: number;
}
// Layer styling is hoisted to module constants: react-leaflet re-applies
// pathOptions by reference, and a fresh object literal every render forces a
// canvas redraw that glitches mid-zoom-animation.
const GRID_CASING_PATH_OPTIONS: L.PathOptions = {
color: "#0f172a",
weight: 3,
opacity: 0.35,
interactive: false,
};
const GRID_HAIRLINE_PATH_OPTIONS: L.PathOptions = {
color: "#ffffff",
weight: 1,
opacity: 0.22,
interactive: false,
};
// Same slack the maps give maxBounds; viewport clamps stay inside it.
const BOUNDS_PAD_METERS = 2000;
type GridLabelAnchor = "top" | "bottom" | "left" | "right";
// The iconAnchor nudges the 0x0 icon off the viewport edge; the per-kind
// transform pins the matching corner of the text to it, so the glyph always
// sits just inside the map.
const GRID_LABEL_ICON_ANCHORS: Record<GridLabelAnchor, [number, number]> = {
top: [0, -2],
bottom: [0, 2],
left: [-2, 0],
right: [2, 0],
};
const GRID_LABEL_TRANSFORMS: Record<GridLabelAnchor, string> = {
top: "translate(-50%, 0)",
bottom: "translate(-50%, -100%)",
left: "translate(0, -50%)",
right: "translate(-100%, -50%)",
};
const gridLabelIconCache = new Map<string, L.DivIcon>();
function gridLabelIcon(value: string, anchor: GridLabelAnchor): L.DivIcon {
const key = `${value}:${anchor}`;
let icon = gridLabelIconCache.get(key);
if (!icon) {
icon = L.divIcon({
className: "map-grid-label-icon",
html: `<div class="map-grid-label" style="transform: ${GRID_LABEL_TRANSFORMS[anchor]}">${value}</div>`,
iconSize: [0, 0],
iconAnchor: GRID_LABEL_ICON_ANCHORS[anchor],
});
gridLabelIconCache.set(key, icon);
}
return icon;
}
interface GridLineRender {
key: string;
positions: [number, number][];
}
interface GridLabelRender {
key: string;
position: [number, number];
icon: L.DivIcon;
}
interface GridView {
verticalLines: GridLineRender[];
horizontalLines: GridLineRender[];
labels: GridLabelRender[];
}
/**
* Arma-style coordinate grid: hairlines over a dark casing plus edge labels.
* Geometry is recomputed on moveend/zoomend (and once on mount or config
* change), never on mousemove, so cursor tracking stays cheap. Line spans
* are padded by one cell past the viewport.
*/
export const GridLayer = memo(function GridLayer({
config,
worldWidth,
worldHeight,
}: GridLayerProps) {
const map = useMap();
const worldSize = Math.max(worldWidth, worldHeight);
const computeView = useCallback((): GridView => {
const raw = map.getBounds();
// Viewport bounds in map meters (lng = x, lat = -y), clamped to the
// max-bounds slack so a flung viewport stays in a sane range.
const clampX = (x: number): number =>
Math.min(worldWidth + BOUNDS_PAD_METERS, Math.max(-BOUNDS_PAD_METERS, x));
const clampY = (y: number): number =>
Math.min(worldHeight + BOUNDS_PAD_METERS, Math.max(-BOUNDS_PAD_METERS, y));
const bounds: GridBounds = {
minX: clampX(raw.getWest()),
maxX: clampX(raw.getEast()),
minY: clampY(-raw.getNorth()),
maxY: clampY(-raw.getSouth()),
};
const lineSet = gridLinesForBounds(
config,
worldHeight,
bounds,
metersPerPx(map.getZoom(), worldSize),
);
const pad = lineSet.level.spacing;
const verticalLines: GridLineRender[] = lineSet.verticalLines.map((x) => ({
key: `v-${x}`,
positions: [
[-(bounds.minY - pad), x],
[-(bounds.maxY + pad), x],
],
}));
const horizontalLines: GridLineRender[] = lineSet.horizontalLines.map((y) => ({
key: `h-${y}`,
positions: [
[-y, bounds.minX - pad],
[-y, bounds.maxX + pad],
],
}));
const labels: GridLabelRender[] = [
...lineSet.eastingLabels.flatMap((label): GridLabelRender[] => [
{
key: `e-t-${label.at}`,
position: [-bounds.minY, label.at],
icon: gridLabelIcon(label.value, "top"),
},
{
key: `e-b-${label.at}`,
position: [-bounds.maxY, label.at],
icon: gridLabelIcon(label.value, "bottom"),
},
]),
...lineSet.northingLabels.flatMap((label): GridLabelRender[] => [
{
key: `n-l-${label.at}`,
position: [-label.at, bounds.minX],
icon: gridLabelIcon(label.value, "left"),
},
{
key: `n-r-${label.at}`,
position: [-label.at, bounds.maxX],
icon: gridLabelIcon(label.value, "right"),
},
]),
];
return { verticalLines, horizontalLines, labels };
}, [map, config, worldWidth, worldHeight, worldSize]);
const [view, setView] = useState<GridView>(computeView);
// Recompute on mount and whenever the config (or world) changes; pan/zoom
// updates arrive through the map events below.
useEffect(() => {
setView(computeView());
}, [computeView]);
useMapEvents({
moveend: () => setView(computeView()),
zoomend: () => setView(computeView()),
});
return (
<>
{view.verticalLines.map((line) => (
<Fragment key={line.key}>
<Polyline positions={line.positions} pathOptions={GRID_CASING_PATH_OPTIONS} />
<Polyline positions={line.positions} pathOptions={GRID_HAIRLINE_PATH_OPTIONS} />
</Fragment>
))}
{view.horizontalLines.map((line) => (
<Fragment key={line.key}>
<Polyline positions={line.positions} pathOptions={GRID_CASING_PATH_OPTIONS} />
<Polyline positions={line.positions} pathOptions={GRID_HAIRLINE_PATH_OPTIONS} />
</Fragment>
))}
{view.labels.map((label) => (
<Marker
key={label.key}
position={label.position}
icon={label.icon}
interactive={false}
/>
))}
</>
);
});

View file

@ -46,6 +46,8 @@ import {
splinePolyline,
} from "@/lib/map/style";
import type { MapFeaturesResponse, ShipmentFeature, StructureFeature } from "@/lib/map/types";
import { gridRef, type MapGridConfig } from "@/lib/map/grid";
import { GridLayer } from "./GridLayer";
import { PlacementDialog } from "./PlacementDialog";
import { AuthoringToolbar, useMapAuthoring } from "./AuthoringToolbar";
import { StructureDetailDrawer } from "./StructureDetailDrawer";
@ -64,6 +66,7 @@ type LayerToggles = {
zones: boolean;
shipments: boolean;
ranges: boolean;
grid: boolean;
};
const STRUCTURE_STATUS: Record<string, { color: string; label: string }> = {
@ -353,7 +356,13 @@ function formatEta(estimatedArrival: string | null, nowMs: number): string | nul
return `ETA ${Math.floor(minutes / 60)}h ${minutes % 60}m`;
}
function MousePosition() {
function MousePosition({
grid,
worldHeight,
}: {
grid: MapGridConfig | null;
worldHeight: number;
}) {
const [position, setPosition] = useState<MapPoint | null>(null);
useMapEvents({
mousemove: (event) => {
@ -363,7 +372,11 @@ function MousePosition() {
});
return (
<div className="pointer-events-none absolute bottom-2 left-2 z-[1000] rounded border border-white/15 bg-black/70 px-2 py-1 font-mono text-[10px] text-white/80 backdrop-blur-sm">
{position ? `X ${position[0]} m, Y ${position[1]} m` : "\u00a0"}
{position
? grid
? `${gridRef(position, worldHeight, grid)} // X ${position[0]} m, Y ${position[1]} m`
: `X ${position[0]} m, Y ${position[1]} m`
: "\u00a0"}
</div>
);
}
@ -1162,6 +1175,7 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
zones: true,
shipments: true,
ranges: false,
grid: true,
});
const fetchingRef = useRef(false);
const [mode, setMode] = useState<"view" | "place" | "edit">("view");
@ -1314,6 +1328,7 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
setToggles((current) => ({ ...current, [key]: !current[key] }));
const layerToggleKeys: { key: keyof LayerToggles; label: string }[] = [
...(mapConfig?.grid.enabled ? [{ key: "grid" as const, label: "Grid" }] : []),
{ key: "structures", label: "Structures" },
{ key: "nodes", label: "Nodes" },
{ key: "roads", label: "Roads" },
@ -1371,6 +1386,10 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
<Rectangle bounds={worldBounds} pathOptions={BASEMAP_FALLBACK_PATH_OPTIONS} />
)}
{features && mapConfig?.grid.enabled && toggles.grid && (
<GridLayer config={mapConfig.grid} worldWidth={worldW} worldHeight={worldH} />
)}
{features && toggles.zones && (
<>
{zonePolys.map(({ zone, positions, options }) => (
@ -1602,7 +1621,10 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
/>
)}
<MousePosition />
<MousePosition
grid={mapConfig?.grid.enabled ? mapConfig.grid : null}
worldHeight={worldH}
/>
<MapAttribution prefix="Polaris Task Force // Arma 3 // Leaflet" />
<FitToViewport worldW={worldW} worldH={worldH} minZoomFloor={mapConfig?.minZoom ?? 0} />
{mapConfig && (

View file

@ -34,6 +34,17 @@ const STARS = Array.from({ length: 70 }, (_, i) => ({
r: (i % 3) + 0.5,
}));
const CLOUD_MARGIN = 90;
const CLOUD_SEEDS = Array.from({ length: 7 }, (_, i) => ({
x: ((i * 137) % (CANVAS_W + 160)) - 80,
y: 46 + ((i * 71) % 200),
s: 0.7 + ((i * 37) % 10) / 14,
v: 0.1 + ((i * 53) % 10) / 90,
}));
const FLOCK_MIN_DELAY = 840;
const FLOCK_MAX_DELAY = 2280;
const DAY_CYCLE_SECONDS = 60;
const DAY_SKY_TOP: [number, number, number] = [56, 189, 248];
@ -57,6 +68,21 @@ interface Pipe {
seed: number;
}
interface Cloud {
x: number;
y: number;
s: number;
v: number;
}
interface Flock {
x: number;
y: number;
v: number;
count: number;
t: number;
}
interface GameState {
birdY: number;
birdVy: number;
@ -66,6 +92,13 @@ interface GameState {
groundOffset: number;
runTime: number;
cycleT: number;
clouds: Cloud[];
flock: Flock | null;
flockTimer: number;
}
function makeClouds(): Cloud[] {
return CLOUD_SEEDS.map((c) => ({ ...c }));
}
function drawTopBuilding(ctx: CanvasRenderingContext2D, p: Pipe, light: number) {
@ -162,6 +195,46 @@ function drawObstacle(ctx: CanvasRenderingContext2D, p: Pipe, light: number) {
drawBuilding(ctx, p, light);
}
function drawCloud(ctx: CanvasRenderingContext2D, c: Cloud, light: number) {
ctx.save();
ctx.globalAlpha = 0.32 + 0.34 * light;
ctx.fillStyle = mix([30, 41, 59], [255, 255, 255], light);
const puffs = [
[0, 0, 26, 12],
[-19, 4, 16, 9],
[19, 3, 18, 10],
[3, -8, 15, 10],
];
for (const [dx, dy, rx, ry] of puffs) {
ctx.beginPath();
ctx.ellipse(c.x + dx * c.s, c.y + dy * c.s, rx * c.s, ry * c.s, 0, 0, Math.PI * 2);
ctx.fill();
}
ctx.restore();
}
function drawFlock(ctx: CanvasRenderingContext2D, f: Flock, light: number) {
const alpha = 0.12 + 0.5 * light;
if (alpha <= 0.05) return;
ctx.save();
ctx.strokeStyle = `rgba(15, 23, 42, ${alpha.toFixed(2)})`;
ctx.lineWidth = 1.4;
ctx.lineCap = "round";
for (let i = 0; i < f.count; i++) {
const side = i === 0 ? 0 : Math.ceil(i / 2);
const sign = i % 2 === 1 ? -1 : 1;
const bx = f.x + side * 9;
const by = f.y + sign * side * 5;
const flap = 0.35 + 0.65 * Math.abs(Math.sin(f.t * 0.18 + i * 1.3));
const w = 4.5;
ctx.beginPath();
ctx.moveTo(bx - w, by - w * 0.55 * flap);
ctx.quadraticCurveTo(bx, by + w * 0.35 * flap, bx + w, by - w * 0.55 * flap);
ctx.stroke();
}
ctx.restore();
}
function drawHelicopter(
ctx: CanvasRenderingContext2D,
y: number,
@ -349,6 +422,9 @@ export function FlappyBird({
groundOffset: 0,
runTime: 0,
cycleT: 0,
clouds: makeClouds(),
flock: null,
flockTimer: 480,
});
const submittingRef = useRef(false);
const statsRef = useRef<FlappyStats>(serverStats);
@ -381,6 +457,9 @@ export function FlappyBird({
g.groundOffset = 0;
g.runTime = 0;
g.cycleT = 0;
g.clouds = makeClouds();
g.flock = null;
g.flockTimer = 480;
setScore(0);
setPhaseSafe("ready");
}, [setPhaseSafe]);
@ -545,6 +624,32 @@ export function FlappyBird({
}
}
for (const c of g.clouds) {
c.x -= c.v * dt;
if (c.x < -CLOUD_MARGIN) {
c.x = CANVAS_W + CLOUD_MARGIN;
c.y = 46 + Math.random() * 200;
}
}
if (g.flock) {
g.flock.x -= g.flock.v * dt;
g.flock.t += dt;
if (g.flock.x < -90) g.flock = null;
} else {
g.flockTimer -= dt;
if (g.flockTimer <= 0) {
g.flock = {
x: CANVAS_W + 60,
y: 60 + Math.random() * 170,
v: 0.28 + Math.random() * 0.18,
count: 5 + 2 * Math.floor(Math.random() * 3),
t: Math.random() * 100,
};
g.flockTimer = FLOCK_MIN_DELAY + Math.random() * (FLOCK_MAX_DELAY - FLOCK_MIN_DELAY);
}
}
ctx.clearRect(0, 0, CANVAS_W, CANVAS_H);
const cycle = (g.cycleT / DAY_CYCLE_SECONDS) * Math.PI * 2;
@ -613,6 +718,9 @@ export function FlappyBird({
ctx.restore();
}
for (const c of g.clouds) drawCloud(ctx, c, light);
if (g.flock) drawFlock(ctx, g.flock, light);
for (const pipe of g.pipes) drawObstacle(ctx, pipe, light);
ctx.fillStyle = mix([11, 15, 20], [100, 116, 139], light);

View file

@ -21,14 +21,14 @@ function CardShell({
<section className="group relative overflow-hidden rounded-none border border-border/70 bg-card" data-slot="operation-card">
<div
aria-hidden="true"
className="pointer-events-none absolute inset-0 z-[5] opacity-[0.04] transition-opacity duration-500 group-hover:opacity-[0.07] motion-reduce:transition-none"
className="pointer-events-none absolute inset-0 z-[5] opacity-[0.04]"
style={DOSSIER.gridTexture}
/>
<CornerBrackets />
<header className={`${DOSSIER.strip} relative z-10`}>
<h2 className={DOSSIER.stripLabel}>{title}</h2>
</header>
<div className="relative z-10 p-3">{children}</div>
<div className="relative z-10 px-5 py-3">{children}</div>
</section>
);
}

View file

@ -39,13 +39,13 @@ export function StrategicSummary({
>
<div
aria-hidden="true"
className="pointer-events-none absolute inset-0 z-[5] opacity-[0.04] transition-opacity duration-500 group-hover:opacity-[0.07] motion-reduce:transition-none"
className="pointer-events-none absolute inset-0 z-[5] opacity-[0.04]"
style={DOSSIER.gridTexture}
/>
<CornerBrackets />
<div className="relative z-10 flex flex-col">
<ClassificationStrip left={classificationLeft} right={classificationRight} />
<div className="px-4 py-4">{children}</div>
<div className="px-5 py-4">{children}</div>
{readoutCells ? <LedgerRow cells={readoutCells} /> : null}
</div>
</div>

View file

@ -38,9 +38,9 @@ export function statusToneFor(status: string): StatusTone {
/** Shared dossier surface classes (classification strip, readouts, chips). */
export const DOSSIER = {
strip: "border-b border-white/15 bg-black/50 px-3 py-1.5 backdrop-blur-sm",
strip: "border-b border-white/15 bg-black/50 px-5 py-1.5 backdrop-blur-sm",
stripLabel: "font-mono text-[9px] uppercase tracking-widest text-white/60",
readout: "border-t border-white/15 bg-black/60 py-1.5 backdrop-blur-sm",
readout: "border-t border-white/15 bg-black/60 px-5 py-1.5 backdrop-blur-sm",
readoutValue: "font-mono text-xs tabular-nums text-white/80",
readoutLabel: "text-[9px] uppercase tracking-wider text-white/50",
chip: "border border-white/25 bg-black/40 px-1.5 py-0.5 font-mono text-[9px] uppercase tracking-widest text-white/70",

View file

@ -2,8 +2,10 @@
import Link from "next/link";
import type { GameNpc } from "@/payload-types";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { cn } from "@/lib/utils";
import { ClassificationStrip, CornerBrackets, DOSSIER, type ReadoutCell } from "@/components/frontend/operations";
import { NpcStatusChips } from "@/components/frontend/personnel/NpcStatusChips";
import { initialsOf } from "@/components/frontend/personnel/initials";
interface NpcCardProps {
readonly npc: GameNpc;
@ -12,40 +14,110 @@ interface NpcCardProps {
export function NpcCard({ npc }: NpcCardProps) {
const factionName =
typeof npc.faction === "object" && npc.faction !== null ? npc.faction.name : null;
const locationName =
typeof npc.location === "object" && npc.location !== null ? npc.location.name : null;
const vendorEnabled = npc.vendor?.enabled === true;
const goodsCount = (npc.vendor?.sells ?? []).length;
const imageUrl =
typeof npc.image === "object" && npc.image !== null ? (npc.image.url ?? null) : null;
const refCode = String(npc.id).padStart(3, "0");
const monogram = initialsOf(npc.name);
const readoutCells: ReadoutCell[] = [
{ label: "Faction", value: factionName ?? "Unaffiliated" },
{ label: "Station", value: locationName ?? "Unknown" },
{ label: "Goods", value: vendorEnabled ? goodsCount.toString() : "-", mono: true },
];
return (
<Link href={`/personnel/contacts/${npc.id}`} className="block h-full">
<Card className="h-full transition-colors hover:bg-accent/50">
<CardHeader className="gap-2">
<CardTitle className="text-base">{npc.name}</CardTitle>
<p className="text-sm text-muted-foreground">
{npc.occupation ?? "Occupation not recorded"}
</p>
<div className="flex flex-wrap items-center gap-1.5">
{npc.isInGame === true && (
<Badge variant="secondary" className="border-emerald-500/30 text-emerald-500">
In Game
</Badge>
)}
{npc.isGenerated === true && (
<Badge variant="outline" className="border-amber-500/40 text-amber-500">
Generated
</Badge>
)}
{npc.vendor?.enabled === true && (
<Badge variant="outline" className="border-violet-500/40 text-violet-500">
Vendor
</Badge>
)}
<Link
href={`/personnel/contacts/${npc.id}`}
aria-label={`Open contact ${npc.name}`}
className="block rounded-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
>
<article className="group relative flex aspect-[4/5] flex-col overflow-hidden rounded-none border border-border/70 bg-card transition-colors duration-300 hover:border-foreground/30 motion-reduce:transition-none">
<div className="relative z-20 shrink-0">
<ClassificationStrip left="Contact" right={`REF ${refCode}`} />
</div>
<div className="relative min-h-0 flex-1 overflow-hidden">
{imageUrl ? (
<img src={imageUrl} alt="" className="absolute inset-0 size-full object-cover" />
) : (
<>
<div className="absolute inset-0 bg-gradient-to-br from-muted/40 via-card to-black/40" />
<div className="absolute inset-0 flex items-center justify-center">
<span className="select-none font-mono text-[3rem] font-bold leading-none tracking-tighter text-white/[0.06] transition-opacity duration-500 group-hover:text-white/[0.1] motion-reduce:transition-none">
{monogram}
</span>
</div>
</>
)}
<div
aria-hidden="true"
className="absolute inset-0 bg-gradient-to-t from-black/85 via-black/55 to-black/25"
/>
<div className="relative z-10 flex h-full items-center justify-center px-3 text-center">
<div className="flex max-w-full flex-col items-center gap-1.5">
<h2
data-text={npc.name}
className="glitch-hover text-balance text-center text-sm font-bold leading-tight text-white drop-shadow-lg"
>
{npc.name}
<span aria-hidden="true" className="glitch-ghost glitch-shard-a">
{npc.name}
</span>
<span aria-hidden="true" className="glitch-ghost glitch-shard-b">
{npc.name}
</span>
<span aria-hidden="true" className="glitch-ghost glitch-shard-c">
{npc.name}
</span>
</h2>
<p className="glitch-soft line-clamp-1 max-w-full text-pretty text-[10px] text-white/60 drop-shadow">
{npc.occupation ?? "Occupation not recorded"}
</p>
<NpcStatusChips npc={npc} size="compact" className="mt-0.5 justify-center" />
</div>
</div>
</CardHeader>
<CardContent className="flex flex-col gap-2 text-sm">
<div className="flex items-center justify-between gap-3">
<span className="text-muted-foreground">Faction</span>
<span className="truncate text-right">{factionName ?? "Unaffiliated"}</span>
</div>
</CardContent>
</Card>
</div>
<div className="relative z-20 shrink-0">
<footer className="flex items-stretch border-t border-white/15 bg-black/60 px-1 py-1 backdrop-blur-sm">
{readoutCells.map((cell, index) => (
<div
key={cell.label}
className={cn(
"flex min-w-0 flex-1 flex-col items-center justify-center px-1",
index < readoutCells.length - 1 && "border-r border-white/15",
)}
>
<span
className={cn(
"w-full truncate text-center text-[10px] text-white/80",
cell.mono && "font-mono tabular-nums",
)}
>
{cell.value}
</span>
<span className="text-[7px] uppercase tracking-widest text-white/40">
{cell.label}
</span>
</div>
))}
</footer>
</div>
<div
aria-hidden="true"
className="pointer-events-none absolute inset-0 z-[5] opacity-[0.04]"
style={DOSSIER.gridTexture}
/>
<CornerBrackets />
</article>
</Link>
);
}

View file

@ -3,13 +3,12 @@
import { useMemo, useState } from "react";
import { SearchIcon } from "lucide-react";
import type { GameNpc } from "@/payload-types";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { cn } from "@/lib/utils";
import { NpcCard } from "@/components/frontend/personnel/NpcCard";
import { DOSSIER, NoticeState } from "@/components/frontend/operations";
interface NpcDirectoryProps {
readonly npcs: GameNpc[];
@ -94,30 +93,29 @@ export function NpcDirectory({ npcs }: NpcDirectoryProps) {
</fieldset>
</div>
<Badge variant="outline" className="w-fit">
<span className={cn("w-fit", DOSSIER.chip)}>
{filteredNpcs.length} of {npcs.length}
</Badge>
</span>
</div>
{filteredNpcs.length === 0 ? (
<Card>
<CardContent className="flex flex-col gap-1 p-6">
<p className="font-semibold">
{npcs.length === 0
? "No contacts have been added."
: hasFilters
? "No contacts match those filters."
: "No contacts found."}
</p>
<p className="text-sm text-muted-foreground">
{npcs.length === 0
? "NPC records will appear here as the theater develops."
: "Try a different search or clear one of the filters."}
</p>
</CardContent>
</Card>
<NoticeState
variant="empty"
message={
npcs.length === 0
? "No contacts have been added."
: hasFilters
? "No contacts match those filters."
: "No contacts found."
}
hint={
npcs.length === 0
? "NPC records will appear here as the theater develops."
: "Try a different search or clear one of the filters."
}
/>
) : (
<div className="grid grid-cols-1 gap-3 md:grid-cols-2 lg:grid-cols-3">
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
{filteredNpcs.map((npc) => (
<NpcCard key={npc.id} npc={npc} />
))}

View file

@ -1,53 +1,71 @@
"use client";
import { Fragment } from "react";
import { Fragment, type ComponentType, type ReactNode } from "react";
import Link from "next/link";
import { ArrowLeftIcon, MapPinIcon, ShieldIcon, StoreIcon } from "lucide-react";
import { RichText } from "@payloadcms/richtext-lexical/react";
import type { Asset, GameNpc, MarketListing } from "@/payload-types";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import {
ClassificationStrip,
CornerBrackets,
DOSSIER,
LedgerRow,
StrategicSummary,
type ReadoutCell,
} from "@/components/frontend/operations";
import { CurrencyAmount } from "@/components/frontend/banking/CurrencyAmount";
import { NpcStatusChips } from "@/components/frontend/personnel/NpcStatusChips";
import { initialsOf } from "@/components/frontend/personnel/initials";
interface NpcProfileProps {
readonly npc: GameNpc;
readonly listings: MarketListing[];
/** Interactive employment controls, rendered in the dossier's right column. */
readonly employmentSlot?: ReactNode;
}
function assetName(asset: number | Asset): string {
return typeof asset === "object" && asset !== null ? asset.name : `Asset #${asset}`;
}
function StatusBadges({ npc }: { npc: GameNpc }) {
function Field({
icon: Icon,
label,
value,
}: {
icon: ComponentType<{ className?: string }>;
label: string;
value: string;
}) {
return (
<div className="flex flex-wrap items-center gap-1.5">
{npc.isInGame === true && (
<Badge variant="secondary" className="border-emerald-500/30 text-emerald-500">
In Game
</Badge>
)}
{npc.isGenerated === true && (
<Badge variant="outline" className="border-amber-500/40 text-amber-500">
Generated
</Badge>
)}
{npc.vendor?.enabled === true && (
<Badge variant="outline" className="border-violet-500/40 text-violet-500">
Vendor
</Badge>
)}
<div className="flex items-start gap-3">
<Icon className="mt-0.5 size-4 shrink-0 text-white/40" />
<div className="flex flex-col gap-1">
<span className={DOSSIER.readoutLabel}>{label}</span>
<span className="text-sm text-white/90">{value}</span>
</div>
</div>
);
}
export function NpcProfile({ npc, listings }: NpcProfileProps) {
type LexicalData = Parameters<typeof RichText>[0]["data"];
/** Renders the NPC's Lexical richText bio, falling back to a placeholder when empty. */
function NpcBio({ bio }: { bio: GameNpc["bio"] }) {
const children = (bio as { root?: { children?: unknown[] } } | null | undefined)?.root?.children;
if (!bio || !Array.isArray(children) || children.length === 0) {
return <p className="text-sm text-white/60">No bio on file.</p>;
}
return (
<div className="lexical-content">
<RichText data={bio as LexicalData} />
</div>
);
}
export function NpcProfile({ npc, listings, employmentSlot }: NpcProfileProps) {
const faction = typeof npc.faction === "object" && npc.faction !== null ? npc.faction : null;
const location =
typeof npc.location === "object" && npc.location !== null ? npc.location : null;
@ -55,134 +73,171 @@ export function NpcProfile({ npc, listings }: NpcProfileProps) {
(asset): asset is Asset => typeof asset === "object" && asset !== null,
);
const vendorEnabled = npc.vendor?.enabled === true;
const priceModifier = npc.vendor?.priceModifier ?? 1;
const imageUrl =
typeof npc.image === "object" && npc.image !== null ? (npc.image.url ?? null) : null;
const refCode = String(npc.id).padStart(3, "0");
const monogram = initialsOf(npc.name);
const heroCells: ReadoutCell[] = [
{ label: "Faction", value: faction?.name ?? "Unaffiliated" },
{ label: "Station", value: location?.name ?? "Unknown" },
{ label: "Goods", value: vendorEnabled ? sellableAssets.length.toString() : "-", mono: true },
{ label: "Listings", value: listings.length.toString(), mono: true },
];
return (
<div className="flex flex-col gap-6 p-5">
<div className="flex flex-col gap-6">
<Link
href="/personnel/contacts"
className="inline-flex w-fit items-center gap-2 text-sm text-muted-foreground hover:text-foreground"
className="inline-flex w-fit items-center gap-2 font-mono text-xs uppercase tracking-widest text-white/50 transition-colors hover:text-white/90"
>
<ArrowLeftIcon className="size-4" />
<ArrowLeftIcon className="size-3.5" />
Back to Contacts
</Link>
<div className="flex flex-col gap-2">
<div className="flex flex-wrap items-center gap-3">
<h1 className="text-lg font-semibold">{npc.name}</h1>
<StatusBadges npc={npc} />
{/* Hero dossier */}
<section
data-slot="npc-dossier-hero"
className="group relative overflow-hidden rounded-none border border-border/70 bg-card"
>
<div aria-hidden="true" className="absolute inset-0">
{imageUrl ? (
<img src={imageUrl} alt="" className="absolute inset-0 size-full object-cover" />
) : (
<>
<div className="absolute inset-0 bg-gradient-to-br from-muted/40 via-card to-black/50" />
<div className="absolute inset-0 flex items-center justify-end">
<span className="select-none pr-6 font-mono text-[9rem] font-bold leading-none tracking-tighter text-white/[0.05] transition-opacity duration-500 group-hover:text-white/[0.08] motion-reduce:transition-none md:pr-12 md:text-[12rem]">
{monogram}
</span>
</div>
</>
)}
</div>
<p className="text-sm text-muted-foreground">
{npc.occupation ?? "Occupation not recorded"}
</p>
</div>
<div
aria-hidden="true"
className="absolute inset-0 bg-gradient-to-r from-black/75 via-black/40 to-transparent"
/>
<div
aria-hidden="true"
className="pointer-events-none absolute inset-0 z-[5] opacity-[0.04]"
style={DOSSIER.gridTexture}
/>
<ClassificationStrip left="Personnel File // Theater Contacts" right={`REF ${refCode}`} />
<CornerBrackets />
<div className="relative z-10 flex flex-col gap-3 px-6 py-10 md:py-14">
<h1
data-text={npc.name}
className="glitch-hover text-balance text-3xl font-bold tracking-tight text-white drop-shadow-lg"
>
{npc.name}
<span aria-hidden="true" className="glitch-ghost glitch-shard-a">
{npc.name}
</span>
<span aria-hidden="true" className="glitch-ghost glitch-shard-b">
{npc.name}
</span>
<span aria-hidden="true" className="glitch-ghost glitch-shard-c">
{npc.name}
</span>
</h1>
<p className="glitch-soft max-w-prose text-pretty text-sm uppercase tracking-wider text-white/60 drop-shadow">
{npc.occupation ?? "Occupation not recorded"}
</p>
<NpcStatusChips npc={npc} className="mt-1" />
</div>
<div className="relative z-10">
<LedgerRow cells={heroCells} />
</div>
</section>
<div className="grid gap-6 lg:grid-cols-2">
<div className="flex flex-col gap-6">
<Card>
<CardHeader className="gap-2">
<CardTitle>Bio</CardTitle>
<CardDescription>Background information on this contact.</CardDescription>
</CardHeader>
<CardContent>
<p className="whitespace-pre-wrap text-sm text-muted-foreground">
{npc.bio?.trim() || "No bio on file."}
</p>
</CardContent>
</Card>
<StrategicSummary classificationLeft="Bio" classificationRight="Personnel File">
<NpcBio bio={npc.bio} />
</StrategicSummary>
<Card>
<CardHeader className="gap-2">
<CardTitle>Assignment</CardTitle>
<CardDescription>Known affiliations and current station.</CardDescription>
</CardHeader>
<CardContent className="grid gap-4 sm:grid-cols-2">
<div className="flex items-start gap-3">
<MapPinIcon className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
<div className="flex flex-col gap-1">
<span className="text-xs uppercase tracking-wider text-muted-foreground">
Stationed at
</span>
<span className="text-sm">{location?.name ?? "Location unknown"}</span>
</div>
</div>
<div className="flex items-start gap-3">
<ShieldIcon className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
<div className="flex flex-col gap-1">
<span className="text-xs uppercase tracking-wider text-muted-foreground">
Faction
</span>
<span className="text-sm">{faction?.name ?? "Unaffiliated"}</span>
</div>
</div>
</CardContent>
</Card>
<StrategicSummary classificationLeft="Assignment" classificationRight="Affiliations">
<div className="grid gap-4 sm:grid-cols-2">
<Field
icon={MapPinIcon}
label="Stationed at"
value={location?.name ?? "Location unknown"}
/>
<Field
icon={ShieldIcon}
label="Faction"
value={faction?.name ?? "Unaffiliated"}
/>
</div>
</StrategicSummary>
</div>
<div className="flex flex-col gap-6">
{vendorEnabled && (
<Card>
<CardHeader className="gap-2">
<div className="flex items-center gap-2">
<StoreIcon className="size-4 text-muted-foreground" />
<CardTitle>Vendor information</CardTitle>
</div>
<CardDescription>Market preferences for this contact.</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<div className="flex items-center justify-between gap-3 text-sm">
<span className="text-muted-foreground">Price modifier</span>
<span className="font-mono tabular-nums">
×{(npc.vendor?.priceModifier ?? 1).toFixed(2)}
<StrategicSummary classificationLeft="Vendor" classificationRight="Market Preferences">
<div className="flex flex-col gap-4">
<div className="flex items-center justify-between gap-3">
<span className={`flex items-center gap-2 ${DOSSIER.readoutLabel}`}>
<StoreIcon className="size-3.5 text-white/40" />
Price modifier
</span>
<span className="font-mono text-sm tabular-nums text-white/90">
×{priceModifier.toFixed(2)}
</span>
</div>
<div className="flex flex-col gap-2">
<span className="text-xs uppercase tracking-wider text-muted-foreground">
Goods they sell
</span>
<span className={DOSSIER.readoutLabel}>Goods they sell</span>
{sellableAssets.length > 0 ? (
<div className="flex flex-wrap gap-1.5">
{sellableAssets.map((asset) => (
<Badge key={asset.id} variant="secondary" className="font-normal">
<span key={asset.id} className={DOSSIER.chip}>
{asset.name}
</Badge>
</span>
))}
</div>
) : (
<p className="text-sm text-muted-foreground">No goods assigned.</p>
<p className="text-sm text-white/60">No goods assigned.</p>
)}
</div>
</CardContent>
</Card>
</div>
</StrategicSummary>
)}
<Card>
<CardHeader className="flex-row items-start justify-between gap-3">
<div className="flex flex-col gap-2">
<CardTitle>Active Market Stock</CardTitle>
<CardDescription>{listings.length} active listing(s).</CardDescription>
<StrategicSummary
classificationLeft="Active Market Stock"
classificationRight={`${listings.length} Listing(s)`}
>
<div className="flex flex-col gap-3">
<div className="flex justify-end">
<Button asChild variant="outline" size="sm">
<Link href="/logistics/market">View market</Link>
</Button>
</div>
<Button asChild variant="outline" size="sm">
<Link href="/logistics/market">View market</Link>
</Button>
</CardHeader>
<CardContent>
{listings.length === 0 ? (
<p className="text-sm italic text-muted-foreground">No active stock.</p>
<p className="text-sm italic text-white/50">No active stock.</p>
) : (
<div className="flex flex-col">
{listings.map((listing, index) => (
<Fragment key={listing.id}>
{index > 0 && <Separator />}
{index > 0 && <Separator className="bg-white/10" />}
<div className="flex items-center justify-between gap-4 py-3 first:pt-0 last:pb-0">
<div className="min-w-0">
<p className="truncate text-sm font-semibold">
<p className="truncate text-sm font-semibold text-white/90">
{assetName(listing.asset)}
</p>
<p className="text-xs text-muted-foreground">
<p className="text-xs text-white/50">
{listing.quantity.toLocaleString()} available
</p>
</div>
<span className="shrink-0 text-sm font-semibold tabular-nums">
<span className="shrink-0 text-sm font-semibold tabular-nums text-white/90">
<CurrencyAmount value={listing.price} currency={listing.currency} />
</span>
</div>
@ -190,8 +245,12 @@ export function NpcProfile({ npc, listings }: NpcProfileProps) {
))}
</div>
)}
</CardContent>
</Card>
</div>
</StrategicSummary>
{employmentSlot ? (
<Fragment key="employment">{employmentSlot}</Fragment>
) : null}
</div>
</div>
</div>

View file

@ -0,0 +1,52 @@
"use client";
import type { GameNpc } from "@/payload-types";
import { cn } from "@/lib/utils";
const STATUS_CHIP: Record<string, string> = {
inGame: "border-emerald-500/40 bg-emerald-500/20 text-emerald-400",
generated: "border-amber-500/40 bg-amber-500/20 text-amber-400",
vendor: "border-violet-500/40 bg-violet-500/20 text-violet-400",
};
function Chip({
label,
tone,
size,
}: {
label: string;
tone: keyof typeof STATUS_CHIP;
size: "default" | "compact";
}) {
return (
<span
className={cn(
"inline-flex items-center border font-mono uppercase leading-none tracking-widest",
size === "compact" ? "px-1 py-px text-[8px]" : "px-1.5 py-0.5 text-[9px]",
STATUS_CHIP[tone],
)}
>
{label}
</span>
);
}
/** Squared tactical status chips shared by the contact card and profile. */
export function NpcStatusChips({
npc,
className,
size = "default",
}: {
npc: GameNpc;
className?: string;
size?: "default" | "compact";
}) {
const vendorEnabled = npc.vendor?.enabled === true;
return (
<div className={cn("flex flex-wrap items-center gap-1.5", className)}>
{npc.isInGame === true && <Chip label="In Game" tone="inGame" size={size} />}
{npc.isGenerated === true && <Chip label="Generated" tone="generated" size={size} />}
{vendorEnabled && <Chip label="Vendor" tone="vendor" size={size} />}
</div>
);
}

View file

@ -0,0 +1,13 @@
/**
* Deterministic two-letter monogram used as the tactical "file photo" backdrop
* on personnel dossier surfaces. Pure, client-safe.
*/
export function initialsOf(name: string): string {
const words = name
.split(/[\s-]+/)
.map((word) => word.replace(/[^A-Za-z0-9]/g, ""))
.filter(Boolean);
if (words.length === 0) return "??";
if (words.length === 1) return words[0].slice(0, 2).toUpperCase();
return (words[0][0] + words[words.length - 1][0]).toUpperCase();
}

View file

@ -0,0 +1,518 @@
import { randomBytes } from "crypto";
import type { Payload, PayloadRequest } from "payload";
import type { RawSyncEvent } from "@/lib/operations/types";
/**
* Limited-arsenal storage sync (Arma bridge) — contract: docs/arma-bridge/locker-sync.md.
*
* An `instanceRef` identifies one storage: `personal:<steamId>` (the member's
* locker-storages row) or `structure:<storageSlug>` (a game-structures row's
* storedAssets). The game sends `locker.sync` full snapshots after every
* committed stock change and `locker.request` when it needs web state; the web
* pushes `locker.apply` commands (full snapshots) on UI edits and on request.
*
* Merge rule: snapshots update asset+quantity only. Grid metadata (gridX,
* gridY, rotated, equipment) is web-managed and always preserved; entries the
* game does not know are left untouched; absence in a snapshot is NOT
* deletion. New game-side classes are auto-placed below the used grid rows.
*/
export interface LockerStockLine {
className: string;
count: number;
}
export type LockerInstanceRef =
| { kind: "personal"; steamId: string }
| { kind: "structure"; slug: string };
/** Hard cap on snapshot lines so a malformed event cannot build huge arrays. */
const MAX_STOCK_LINES = 1000;
const SLUG_PATTERN = /^[a-z0-9][a-z0-9-_]{1,63}$/;
export function formatInstanceRef(ref: LockerInstanceRef): string {
return ref.kind === "personal" ? `personal:${ref.steamId}` : `structure:${ref.slug}`;
}
export function parseInstanceRef(value: unknown): LockerInstanceRef | null {
if (typeof value !== "string") return null;
const sep = value.indexOf(":");
if (sep <= 0) return null;
const kind = value.slice(0, sep);
const key = value.slice(sep + 1).trim();
if (kind === "personal") {
if (key.length === 0 || key.length > 64) return null;
return { kind: "personal", steamId: key };
}
if (kind === "structure") {
if (!SLUG_PATTERN.test(key)) return null;
return { kind: "structure", slug: key };
}
return null;
}
/**
* Parses the snapshot half of a locker payload: [[itemClass, count], ...].
* Returns null only when the outer shape is not an array; individual bad
* lines are dropped (defensive, never-throws — same posture as crate sync).
*/
export function parseStockSnapshot(value: unknown): LockerStockLine[] | null {
if (!Array.isArray(value)) return null;
const lines: LockerStockLine[] = [];
for (const entry of value.slice(0, MAX_STOCK_LINES)) {
if (!Array.isArray(entry) || entry.length < 2) continue;
const className = entry[0];
const count = entry[1];
if (typeof className !== "string" || className.length === 0 || className.length > 200) continue;
if (typeof count !== "number" || !Number.isFinite(count)) continue;
lines.push({ className, count: Math.max(0, Math.round(count)) });
}
return lines;
}
function relId(value: unknown): number | null {
if (typeof value === "number") return value;
if (value !== null && typeof value === "object" && "id" in (value as { id: unknown })) {
const id = (value as { id: unknown }).id;
return typeof id === "number" ? id : null;
}
return null;
}
async function findUserIdBySteamId(payload: Payload, steamId: string): Promise<number | null> {
const users = await payload.find({
collection: "users",
where: { steamId: { equals: steamId } },
limit: 1,
depth: 0,
overrideAccess: true,
});
return users.docs[0]?.id ?? null;
}
/** The most recently heartbeated online server, per the locker-sync contract. */
export async function findLatestOnlineServerId(payload: Payload): Promise<number | null> {
const servers = await payload.find({
collection: "game-servers",
where: { status: { equals: "online" } },
sort: "-lastSeenAt",
limit: 1,
depth: 0,
overrideAccess: true,
});
return servers.docs[0]?.id ?? null;
}
/**
* Enqueues one `locker.apply` command. Targets the latest online server when
* no explicit server id is given. No-op (false) when no server is online —
* the game pulls state via locker.request when it next starts anyway.
*/
export async function enqueueLockerApply(
payload: Payload,
instanceRef: string,
stock: Array<[string, number]>,
serverId?: number,
): Promise<boolean> {
const target = serverId ?? (await findLatestOnlineServerId(payload));
if (target == null) {
payload.logger.warn(`[LockerSync] No online server; locker.apply for ${instanceRef} not enqueued`);
return false;
}
await payload.create({
collection: "arma-commands",
data: {
commandId: `locker-${randomBytes(12).toString("hex")}`,
server: target,
type: "locker.apply",
payload: [instanceRef, stock],
status: "queued",
},
overrideAccess: true,
depth: 0,
});
return true;
}
/**
* Converts a stored item array (locker-storages items / game-structures
* storedAssets) into [className, count] command pairs. Asset references are
* batch-resolved by id; entries without a resolvable className are skipped.
*/
export async function stockPairsFromItems(
payload: Payload,
items: unknown,
): Promise<Array<[string, number]>> {
if (!Array.isArray(items) || items.length === 0) return [];
const rows = items as Array<Record<string, unknown>>;
const assetIds = [
...new Set(rows.map((row) => relId(row.asset)).filter((v): v is number => v != null)),
];
if (assetIds.length === 0) return [];
const assets = await payload.find({
collection: "assets",
where: { id: { in: assetIds } },
limit: assetIds.length * 2,
depth: 0,
overrideAccess: true,
});
const classById = new Map<number, string>();
for (const asset of assets.docs) {
const className = (asset as { className?: unknown }).className;
if (typeof className === "string" && className.length > 0) classById.set(asset.id, className);
}
const pairs: Array<[string, number]> = [];
for (const row of rows) {
const assetId = relId(row.asset);
const className = assetId != null ? classById.get(assetId) : undefined;
const quantity = typeof row.quantity === "number" ? Math.round(row.quantity) : 0;
if (!className || quantity < 1) continue;
pairs.push([className, quantity]);
}
return pairs;
}
interface ExistingItemRow {
[key: string]: unknown;
}
/**
* Merges a game snapshot into a stored item array (contract merge rules):
* quantity updates in place for known classes (grid metadata preserved), new
* classes appended below the used rows, unknown-to-the-game entries untouched.
* Returns the new array (suitable as update `data.items` / `data.storedAssets`).
*/
export function mergeStockIntoItems(
existing: ExistingItemRow[],
snapshot: LockerStockLine[],
assetIdByClassName: Map<string, number>,
warn?: (message: string) => void,
): ExistingItemRow[] {
const merged = existing.map((row) => ({ ...row }));
const indexByClassName = new Map<string, number>();
merged.forEach((row, index) => {
if (typeof row.className === "string") indexByClassName.set(row.className, index);
});
let nextY =
merged.reduce((max, row) => {
const y = typeof row.gridY === "number" ? row.gridY : 0;
return Math.max(max, y);
}, -1) + 1;
for (const line of snapshot) {
const hit = indexByClassName.get(line.className);
if (hit !== undefined) {
merged[hit] = { ...merged[hit], quantity: line.count };
continue;
}
const assetId = assetIdByClassName.get(line.className);
if (assetId == null) {
warn?.(`[LockerSync] Snapshot class "${line.className}" has no matching asset; skipped`);
continue;
}
const row: ExistingItemRow = {
asset: assetId,
quantity: line.count,
gridX: 0,
gridY: nextY,
rotated: false,
className: line.className,
};
nextY += 1;
indexByClassName.set(line.className, merged.length);
merged.push(row);
}
return merged;
}
/**
* Resolves snapshot class names to asset ids (assets are keyed by className).
*/
async function findAssetIdsByClassName(
payload: Payload,
classNames: string[],
): Promise<Map<string, number>> {
const wanted = [...new Set(classNames)];
const map = new Map<string, number>();
if (wanted.length === 0) return map;
const assets = await payload.find({
collection: "assets",
where: { className: { in: wanted } },
limit: wanted.length * 2,
depth: 0,
overrideAccess: true,
});
for (const asset of assets.docs) {
const className = (asset as { className?: unknown }).className;
if (typeof className === "string") map.set(className, asset.id);
}
return map;
}
/** Marks the request so afterChange enqueue hooks skip game-originated writes. */
function markSyncOrigin(req: PayloadRequest | undefined): void {
if (!req) return;
req.context = { ...req.context, lockerSyncOrigin: true };
}
export function isLockerSyncOrigin(req: PayloadRequest): boolean {
return Boolean((req.context as Record<string, unknown> | undefined)?.lockerSyncOrigin);
}
/**
* Annotates stored rows with their asset className so mergeStockIntoItems can
* key by class. Stored rows reference assets by id; class names come from a
* batch lookup.
*/
async function annotateItemsWithClassName(
payload: Payload,
items: unknown,
): Promise<ExistingItemRow[]> {
if (!Array.isArray(items)) return [];
const rows = items as ExistingItemRow[];
const assetIds = [...new Set(rows.map((row) => relId(row.asset)).filter((v): v is number => v != null))];
if (assetIds.length === 0) return rows;
const assets = await payload.find({
collection: "assets",
where: { id: { in: assetIds } },
limit: assetIds.length * 2,
depth: 0,
overrideAccess: true,
});
const classById = new Map<number, string>();
for (const asset of assets.docs) {
const className = (asset as { className?: unknown }).className;
if (typeof className === "string") classById.set(asset.id, className);
}
return rows.map((row) => {
const assetId = relId(row.asset);
const className = assetId != null ? classById.get(assetId) : undefined;
return className ? { ...row, className } : row;
});
}
/**
* Consumes one `locker.*` raw sync event (contract: docs/arma-bridge/locker-sync.md).
* Never throws: malformed events are logged and skipped so raw-event ingestion
* is never rolled back by locker sync.
*/
export async function processLockerEvent(
payload: Payload,
raw: RawSyncEvent,
req?: PayloadRequest,
): Promise<void> {
try {
if (typeof raw.server !== "number") {
payload.logger.warn(`[LockerSync] Event ${raw.eventId} has no server; skipping (malformed)`);
return;
}
if (!Array.isArray(raw.payload)) {
payload.logger.warn(`[LockerSync] Event ${raw.eventId} payload is not an array; skipping`);
return;
}
const ref = parseInstanceRef(raw.payload[0]);
if (!ref) {
payload.logger.warn(`[LockerSync] Event ${raw.eventId} has a malformed instanceRef; skipping`);
return;
}
const refString = formatInstanceRef(ref);
if (raw.type === "locker.sync") {
const snapshot = parseStockSnapshot(raw.payload[1]);
if (!snapshot) {
payload.logger.warn(`[LockerSync] Event ${raw.eventId} has a malformed snapshot; skipping`);
return;
}
await applySnapshotToInstance(payload, ref, refString, snapshot, raw.eventId, req);
return;
}
if (raw.type === "locker.request") {
const stock = await currentStockForInstance(payload, ref);
if (stock === null) {
payload.logger.info(`[LockerSync] locker.request for unknown ${refString}; nothing enqueued`);
return;
}
await enqueueLockerApply(payload, refString, stock, raw.server);
return;
}
payload.logger.warn(`[LockerSync] Unknown locker event type "${raw.type}" for ${raw.eventId}; skipping`);
} catch (error) {
payload.logger.error(
`[LockerSync] Failed to process locker event ${raw.eventId}: ${error instanceof Error ? error.message : "unknown error"}`,
);
}
}
/**
* Applies one locker.sync snapshot to its instance. Returns after merging;
* all writes carry the sync-origin sentinel so afterChange hooks do not echo
* the change back to the game as a locker.apply command.
*/
async function applySnapshotToInstance(
payload: Payload,
ref: LockerInstanceRef,
refString: string,
snapshot: LockerStockLine[],
eventId: string,
req?: PayloadRequest,
): Promise<void> {
const assetIds = await findAssetIdsByClassName(
payload,
snapshot.map((line) => line.className),
);
markSyncOrigin(req);
if (ref.kind === "personal") {
const userId = await findUserIdBySteamId(payload, ref.steamId);
if (!userId) {
payload.logger.info(
`[LockerSync] Steam ID ${ref.steamId} is not linked to a user; session-only stock, event ${eventId} skipped`,
);
return;
}
const lockers = await payload.find({
collection: "locker-storages",
where: { ownerUser: { equals: userId } },
limit: 1,
depth: 0,
overrideAccess: true,
req,
});
const locker = lockers.docs[0];
if (!locker) {
// Linked user without a locker yet: create it from the snapshot.
const items = mergeStockIntoItems([], snapshot, assetIds, (m) => payload.logger.warn(m));
await payload.create({
collection: "locker-storages",
data: { name: "Personal Locker", ownerUser: userId, items: items as never },
overrideAccess: true,
depth: 0,
req,
});
return;
}
const existing = await annotateItemsWithClassName(payload, (locker as { items?: unknown }).items);
const merged = mergeStockIntoItems(existing, snapshot, assetIds, (m) => payload.logger.warn(m));
await payload.update({
collection: "locker-storages",
id: locker.id,
data: { items: merged as never },
overrideAccess: true,
depth: 0,
req,
});
return;
}
const structures = await payload.find({
collection: "game-structures",
where: { storageSlug: { equals: ref.slug } },
limit: 1,
depth: 0,
overrideAccess: true,
req,
});
const structure = structures.docs[0];
if (!structure) {
payload.logger.warn(`[LockerSync] No game-structure with storageSlug "${ref.slug}"; event ${eventId} skipped`);
return;
}
const existing = await annotateItemsWithClassName(
payload,
(structure as { storedAssets?: unknown }).storedAssets,
);
const merged = mergeStockIntoItems(existing, snapshot, assetIds, (m) => payload.logger.warn(m));
await payload.update({
collection: "game-structures",
id: structure.id,
data: { storedAssets: merged as never },
overrideAccess: true,
depth: 0,
req,
});
}
/**
* The web's current stock for an instance as [className, count] pairs.
* Null when the instance cannot be resolved (unknown slug / unlinked user);
* an EMPTY array is a valid, meaningful "known but empty" snapshot.
*/
async function currentStockForInstance(
payload: Payload,
ref: LockerInstanceRef,
): Promise<Array<[string, number]> | null> {
if (ref.kind === "personal") {
const userId = await findUserIdBySteamId(payload, ref.steamId);
if (!userId) return null;
const lockers = await payload.find({
collection: "locker-storages",
where: { ownerUser: { equals: userId } },
limit: 1,
depth: 0,
overrideAccess: true,
});
const locker = lockers.docs[0];
if (!locker) return [];
return stockPairsFromItems(payload, (locker as { items?: unknown }).items);
}
const structures = await payload.find({
collection: "game-structures",
where: { storageSlug: { equals: ref.slug } },
limit: 1,
depth: 0,
overrideAccess: true,
});
const structure = structures.docs[0];
if (!structure) return null;
return stockPairsFromItems(payload, (structure as { storedAssets?: unknown }).storedAssets);
}
/**
* afterChange helper for locker-storages: pushes the member's new stock to
* the game as locker.apply. Skips when the owner has no Steam ID (nothing to
* address) or when no server is online. Never throws — hook safety.
*/
export async function enqueueLockerApplyForLockerDoc(payload: Payload, doc: unknown): Promise<void> {
try {
const row = doc as { ownerUser?: unknown; items?: unknown };
const ownerId = relId(row.ownerUser);
if (ownerId == null) return;
const owner = await payload.findByID({
collection: "users",
id: ownerId,
depth: 0,
overrideAccess: true,
});
const steamId = (owner as { steamId?: unknown } | null)?.steamId;
if (typeof steamId !== "string" || steamId.length === 0) return;
const stock = await stockPairsFromItems(payload, row.items);
await enqueueLockerApply(payload, `personal:${steamId}`, stock);
} catch (error) {
payload.logger.error(
`[LockerSync] Failed to enqueue locker.apply for locker: ${error instanceof Error ? error.message : "unknown error"}`,
);
}
}
/**
* afterChange helper for game-structures: pushes storedAssets to the game as
* locker.apply when the structure exposes item storage (storageSlug set).
* Never throws — hook safety.
*/
export async function enqueueLockerApplyForStructureDoc(payload: Payload, doc: unknown): Promise<void> {
try {
const row = doc as { storageSlug?: unknown; storedAssets?: unknown };
const slug = typeof row.storageSlug === "string" ? row.storageSlug.trim() : "";
if (!slug) return;
const stock = await stockPairsFromItems(payload, row.storedAssets);
await enqueueLockerApply(payload, `structure:${slug}`, stock);
} catch (error) {
payload.logger.error(
`[LockerSync] Failed to enqueue locker.apply for structure: ${error instanceof Error ? error.message : "unknown error"}`,
);
}
}

View file

@ -11,6 +11,7 @@
* export flips y against the world height.
*/
import { isPointArray, type MapPoint } from "@/lib/map/points";
import { DEFAULT_MAP_GRID, gridRef } from "@/lib/map/grid";
import {
DEFAULT_MARKER_BRUSH,
DEFAULT_MARKER_COLOR,
@ -426,17 +427,11 @@ export function toArmaPosition(point: MapPoint, worldHeight: number): [number, n
/**
* Arma map grid reference (6 digits = 100 m squares, 8 digits = 10 m), the
* same numbers the in-game map shows: easting then northing, from the
* bottom-left origin. Off-world points clamp to the edge.
* bottom-left origin. Thin wrapper over gridRef with the default (vanilla)
* grid; off-world points wrap at the digit width like the in-game readout.
*/
export function armaGridRef(point: MapPoint, worldHeight: number, digits: 6 | 8 = 6): string {
const [x, y] = toArmaPosition(point, worldHeight);
const per = digits / 2;
const cell = 10 ** (5 - per);
const fmt = (value: number) =>
String(Math.max(0, Math.floor(value / cell)))
.padStart(per, "0")
.slice(-per);
return `${fmt(x)} ${fmt(y)}`;
return gridRef(point, worldHeight, DEFAULT_MAP_GRID, digits);
}
/**

View file

@ -5,6 +5,7 @@ import {
type PerformanceLevel,
type PerformanceLevelId,
} from "./levels";
import { missionEndTime } from "@/lib/intelligence/missionLifecycle";
type PayloadType = Awaited<ReturnType<typeof import("payload").getPayload>>;
@ -34,20 +35,22 @@ export const ANONYMITY_THRESHOLD = 3;
/**
* Pure eligibility check for whether a mission is "completed/past" enough to be
* evaluated. Draft statuses (Concept/Planning/Ready) and Cancelled are never
* eligible. Scheduled/Active missions become eligible once their scheduled start
* has passed.
* eligible. Scheduled/Active missions become eligible only once their scheduled
* window (start + estimated duration, defaulting to 240 minutes when missing —
* same rule as the mission-lifecycle auto-complete) has fully passed, so an op
* that just started is not treated as evaluable while it is still running.
*/
export function isMissionEvaluable(
status: string,
startDateTimeISO?: string | null,
estimatedDurationMinutes?: number | null,
now: Date = new Date(),
): boolean {
if (status === "Completed") return true;
if (status === "Scheduled" || status === "Active") {
if (!startDateTimeISO) return false;
const start = new Date(startDateTimeISO).getTime();
if (Number.isNaN(start)) return false;
return start < now.getTime();
const end = missionEndTime(startDateTimeISO ?? null, estimatedDurationMinutes ?? null);
if (!end) return false;
return end.getTime() <= now.getTime();
}
return false;
}
@ -158,14 +161,15 @@ export async function evaluateEligibility(
const mission = missions.docs[0] as
| {
ownershipAndStatus?: { status?: string };
classification?: { startDateTime?: string | null };
classification?: { startDateTime?: string | null; estimatedDuration?: number | null };
}
| undefined;
if (!mission) return { eligible: false, reason: "Mission not found." };
const status = mission.ownershipAndStatus?.status ?? "";
const startDateTime = mission.classification?.startDateTime;
if (!isMissionEvaluable(status, startDateTime)) {
const estimatedDuration = mission.classification?.estimatedDuration ?? null;
if (!isMissionEvaluable(status, startDateTime, estimatedDuration)) {
return { eligible: false, reason: "This mission is not completed or past yet." };
}

273
src/lib/map/grid.ts Normal file
View file

@ -0,0 +1,273 @@
/**
* Arma-style coordinate grid: per-map configuration, label math, zoom level
* selection, and grid references. Pure module (client-safe, no Payload).
*
* The model mirrors CfgWorlds `class Grid` on A3 terrains. Vanilla terrains
* place the grid zero line on the south-west world corner so labels equal raw
* world meters; the config below can shift that origin (placement), renumber
* the first line (starting numbers), and resize the base cell, so each map
* can reproduce its in-game grid exactly.
*
* Coordinate spaces: our maps store meters with origin top-left and y running
* south. Arma world coordinates run origin bottom-left, y north. Grid math
* happens in Arma space (y north); conversion is `armaY = worldHeight - mapY`.
*
* Label rules (verified against in-game anchors on Altis/Stratis/Malden/Tanoa):
* values are floor-truncated cell indices, wrapped modulo 10^digits and
* zero-padded (negative indices wrap the same way, e.g. -1 at 3 digits reads
* "999"). Zoom levels step by powers of ten and nest exactly: the 1 km cell
* labeled "10" contains the 100 m lines "100" through "109".
*/
import type { MapPoint } from "./points";
export interface MapGridConfig {
/** Master switch: overlay + configured grid references. */
enabled: boolean;
/** Arma-space meters from the west edge to the grid zero line (in-game X). */
originEasting: number;
/** Arma-space meters from the south edge to the grid zero line (in-game Y). */
originNorthing: number;
/** Label value shown on the zero line at the base spacing (eastings). */
startEasting: number;
/** Label value shown on the zero line at the base spacing (northings). */
startNorthing: number;
/** Base cell size in meters (Arma's 1 km level by default). */
spacingMeters: number;
/** Digits shown per axis at the base spacing (Arma shows 2 at 1 km). */
labelDigits: number;
/** Tanoa style: draw numbers over the lines instead of centered in cells. */
numbersOverLines: boolean;
}
/**
* Default grid: zero line on the south-west corner, 1 km base cells, numbers
* from zero. gridRef with these values reproduces the legacy armaGridRef
* output exactly (100 m cells at 6 digits, 10 m at 8).
*/
export const DEFAULT_MAP_GRID: MapGridConfig = {
enabled: false,
originEasting: 0,
originNorthing: 0,
startEasting: 0,
startNorthing: 0,
spacingMeters: 1000,
labelDigits: 2,
numbersOverLines: false,
};
function finite(value: unknown): value is number {
return typeof value === "number" && Number.isFinite(value);
}
function clampInt(value: number, min: number, max: number): number {
return Math.min(max, Math.max(min, Math.round(value)));
}
/** Coerce a maps collection row into a grid config, tolerating nulls. */
export function gridConfigFromMapDoc(doc: Record<string, unknown> | null | undefined): MapGridConfig {
const raw = doc ?? {};
const spacing = finite(raw.gridSpacingMeters) && raw.gridSpacingMeters >= 1
? raw.gridSpacingMeters
: DEFAULT_MAP_GRID.spacingMeters;
return {
enabled: raw.gridEnabled === true,
originEasting: finite(raw.gridOriginEasting) ? raw.gridOriginEasting : 0,
originNorthing: finite(raw.gridOriginNorthing) ? raw.gridOriginNorthing : 0,
startEasting: finite(raw.gridStartEasting) ? Math.trunc(raw.gridStartEasting) : 0,
startNorthing: finite(raw.gridStartNorthing) ? Math.trunc(raw.gridStartNorthing) : 0,
spacingMeters: spacing,
labelDigits: finite(raw.gridLabelDigits)
? clampInt(raw.gridLabelDigits, 1, 6)
: DEFAULT_MAP_GRID.labelDigits,
numbersOverLines: raw.gridNumbersOverLines === true,
};
}
/** Floor-modulo that wraps negatives into [0, modulus), matching Arma. */
function wrapMod(value: number, modulus: number): number {
return ((value % modulus) + modulus) % modulus;
}
/**
* Zero-padded label for a cell index at `digits` precision, wrapped modulo
* 10^digits with leading zeros ("7" at 3 digits reads "007", -1 reads "999").
*/
export function gridLabel(cellIndex: number, digits: number): string {
const modulus = 10 ** digits;
return String(wrapMod(Math.trunc(cellIndex), modulus)).padStart(digits, "0");
}
/**
* Cell index of an Arma-space coordinate at a given spacing, including the
* configured origin and starting-number offset. Starting numbers are defined
* at the base spacing and scale into finer levels (a base start of 5 reads
* "05" at 1 km and "050" at 100 m); at coarser-than-base levels the start
* contribution floors out and is ignored.
*/
function cellValue(armaCoord: number, origin: number, start: number, spacing: number, baseSpacing: number): number {
const index = Math.floor((armaCoord - origin) / spacing);
const scale = baseSpacing / spacing;
return index + (scale >= 1 ? Math.floor(start * scale) : 0);
}
export interface GridLevel {
/** Cell size of the active level in meters. */
spacing: number;
/** Label digits per axis at this level. */
digits: number;
}
/**
* On-screen cell size below which a finer level is chosen instead. Sized so a
* typical viewport shows roughly 15-40 lines, close to the in-game map.
*/
export const GRID_MIN_CELL_PX = 56;
/**
* Pick the zoom level for a meters-per-pixel scale. The ladder runs from
* 100x coarser to 100x finer than the base spacing in power-of-ten steps
* (with default config: 10 km/1 digit, 1 km/2, 100 m/3, 10 m/4, the A3
* ladder). The finest level whose on-screen cell stays readable wins; zooming
* out past the coarsest level just keeps it.
*/
export function gridLevelFor(metersPerPxValue: number, config: MapGridConfig): GridLevel {
const base = config.spacingMeters;
const levels: GridLevel[] = [];
for (let k = -2; k <= 2; k++) {
const digits = config.labelDigits + k;
if (digits < 1 || digits > 8) continue;
levels.push({ spacing: base / 10 ** k, digits });
}
if (levels.length === 0) return { spacing: base, digits: config.labelDigits };
// levels run coarse to fine; take the finest that still reads on screen.
let chosen = levels[0];
for (const level of levels) {
if (level.spacing / metersPerPxValue >= GRID_MIN_CELL_PX) chosen = level;
}
return chosen;
}
export interface GridLabel {
/** Line index (or cell index in cell-centered mode) this label shows. */
value: string;
/** Anchor position on the label's axis, in map meters. */
at: number;
}
export interface GridLineSet {
level: GridLevel;
/** Vertical line positions, map meters (x, measured from the west edge). */
verticalLines: number[];
/** Horizontal line positions, map meters (y, measured from the north edge). */
horizontalLines: number[];
/** Easting labels (top/bottom edges), x in map meters. */
eastingLabels: GridLabel[];
/** Northing labels (left/right edges), y in map meters. */
northingLabels: GridLabel[];
}
export interface GridBounds {
minX: number;
minY: number;
maxX: number;
maxY: number;
}
/**
* Lines and labels covering a viewport, in map meters (origin top-left, y
* south). Labels are cell-centered by default (Arma draws numbers between the
* lines) and sit on the lines when `numbersOverLines` is set (Tanoa style).
* Bounds are padded by one cell so labels do not pop while panning.
*/
export function gridLinesForBounds(
config: MapGridConfig,
worldHeight: number,
bounds: GridBounds,
metersPerPxValue: number,
): GridLineSet {
const level = gridLevelFor(metersPerPxValue, config);
const { spacing, digits } = level;
const pad = spacing;
const firstV = Math.floor((bounds.minX - config.originEasting - pad) / spacing);
const lastV = Math.ceil((bounds.maxX - config.originEasting + pad) / spacing);
const verticalLines: number[] = [];
const eastingLabels: GridLabel[] = [];
for (let k = firstV; k <= lastV; k++) {
const x = config.originEasting + k * spacing;
verticalLines.push(x);
if (x < bounds.minX - pad || x > bounds.maxX + pad) continue;
if (config.numbersOverLines) {
eastingLabels.push({ value: gridLabel(cellValue(x, config.originEasting, config.startEasting, spacing, config.spacingMeters), digits), at: x });
}
}
if (!config.numbersOverLines) {
for (let k = firstV; k <= lastV; k++) {
const center = config.originEasting + (k + 0.5) * spacing;
if (center < bounds.minX - pad || center > bounds.maxX + pad) continue;
eastingLabels.push({
value: gridLabel(
cellValue(config.originEasting + k * spacing, config.originEasting, config.startEasting, spacing, config.spacingMeters),
digits,
),
at: center,
});
}
}
// Arma-space northing of the viewport: map y runs south, so flip.
const armaMin = worldHeight - bounds.maxY;
const armaMax = worldHeight - bounds.minY;
const firstH = Math.floor((armaMin - config.originNorthing - pad) / spacing);
const lastH = Math.ceil((armaMax - config.originNorthing + pad) / spacing);
const horizontalLines: number[] = [];
const northingLabels: GridLabel[] = [];
for (let k = firstH; k <= lastH; k++) {
const armaY = config.originNorthing + k * spacing;
horizontalLines.push(worldHeight - armaY);
if (armaY < armaMin - pad || armaY > armaMax + pad) continue;
if (config.numbersOverLines) {
northingLabels.push({ value: gridLabel(cellValue(armaY, config.originNorthing, config.startNorthing, spacing, config.spacingMeters), digits), at: worldHeight - armaY });
}
}
if (!config.numbersOverLines) {
for (let k = firstH; k <= lastH; k++) {
const armaY = config.originNorthing + (k + 0.5) * spacing;
if (armaY < armaMin - pad || armaY > armaMax + pad) continue;
northingLabels.push({
value: gridLabel(
cellValue(config.originNorthing + k * spacing, config.originNorthing, config.startNorthing, spacing, config.spacingMeters),
digits,
),
at: worldHeight - armaY,
});
}
}
return { level, verticalLines, horizontalLines, eastingLabels, northingLabels };
}
/**
* Arma grid reference for a map-meter point: easting group then northing
* group, 6 digits (3+3, 100 m cells with default config) or 8 digits (4+4,
* 10 m). Values wrap at the digit width like the in-game readout. With
* DEFAULT_MAP_GRID this reproduces the legacy armaGridRef output for any
* in-world point.
*/
export function gridRef(
point: MapPoint,
worldHeight: number,
config: MapGridConfig = DEFAULT_MAP_GRID,
digits: 6 | 8 = 6,
): string {
const per = digits / 2;
// Precision relative to the base level: default config lands on 100 m at
// 6 digits and 10 m at 8, matching Arma's finest zoom classes.
const spacing = config.spacingMeters / 10 ** (per - config.labelDigits);
const armaX = point[0];
const armaY = worldHeight - point[1];
const easting = cellValue(armaX, config.originEasting, config.startEasting, spacing, config.spacingMeters);
const northing = cellValue(armaY, config.originNorthing, config.startNorthing, spacing, config.spacingMeters);
return `${gridLabel(easting, per)} ${gridLabel(northing, per)}`;
}

View file

@ -1,4 +1,5 @@
import type { MapPoint } from "./points";
import type { MapGridConfig } from "./grid";
export interface MapConfig {
id: number;
@ -12,6 +13,7 @@ export interface MapConfig {
maxZoom: number;
defaultZoom: number;
defaultCenter: MapPoint;
grid: MapGridConfig;
}
export interface RangeRequirementFeature {

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,35 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
/**
* Adds the per-map Arma-style coordinate grid config to the maps collection.
* Hand-trimmed: the generated diff also carried unrelated snapshot drift from
* earlier hand-written migrations missing their .json sidecars
* (mission_map_markers, ai plugin model enum, assets accessory enum value,
* payload_mcp_api_keys columns). Those objects already exist in every
* migrated database via their own migrations, so this migration applies only
* the maps grid columns. The committed .json snapshot is intentionally the
* full current schema so future diffs exclude that drift.
*/
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "maps" ADD COLUMN "grid_enabled" boolean DEFAULT false;
ALTER TABLE "maps" ADD COLUMN "grid_origin_easting" numeric DEFAULT 0;
ALTER TABLE "maps" ADD COLUMN "grid_origin_northing" numeric DEFAULT 0;
ALTER TABLE "maps" ADD COLUMN "grid_start_easting" numeric DEFAULT 0;
ALTER TABLE "maps" ADD COLUMN "grid_start_northing" numeric DEFAULT 0;
ALTER TABLE "maps" ADD COLUMN "grid_spacing_meters" numeric DEFAULT 1000;
ALTER TABLE "maps" ADD COLUMN "grid_label_digits" numeric DEFAULT 2;
ALTER TABLE "maps" ADD COLUMN "grid_numbers_over_lines" boolean DEFAULT false;`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "maps" DROP COLUMN "grid_enabled";
ALTER TABLE "maps" DROP COLUMN "grid_origin_easting";
ALTER TABLE "maps" DROP COLUMN "grid_origin_northing";
ALTER TABLE "maps" DROP COLUMN "grid_start_easting";
ALTER TABLE "maps" DROP COLUMN "grid_start_northing";
ALTER TABLE "maps" DROP COLUMN "grid_spacing_meters";
ALTER TABLE "maps" DROP COLUMN "grid_label_digits";
ALTER TABLE "maps" DROP COLUMN "grid_numbers_over_lines";`)
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,74 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
CREATE TYPE "public"."enum_game_structures_storage_access_mode" AS ENUM('anyone', 'roles', 'users');
CREATE TABLE "game_structures_stored_assets_equipment_attachments" (
"_order" integer NOT NULL,
"_parent_id" varchar NOT NULL,
"id" varchar PRIMARY KEY NOT NULL,
"asset_id" integer NOT NULL
);
CREATE TABLE "game_structures_stored_assets" (
"_order" integer NOT NULL,
"_parent_id" integer NOT NULL,
"id" varchar PRIMARY KEY NOT NULL,
"asset_id" integer NOT NULL,
"quantity" numeric DEFAULT 1 NOT NULL,
"grid_x" numeric DEFAULT 0 NOT NULL,
"grid_y" numeric DEFAULT 0 NOT NULL,
"rotated" boolean DEFAULT false,
"equipment_skin_id" integer,
"equipment_custom_name" varchar
);
CREATE TABLE "game_structures_rels" (
"id" serial PRIMARY KEY NOT NULL,
"order" integer,
"parent_id" integer NOT NULL,
"path" varchar NOT NULL,
"roles_id" integer,
"users_id" integer
);
ALTER TABLE "game_structures" ADD COLUMN "storage_slug" varchar;
ALTER TABLE "game_structures" ADD COLUMN "storage_access_mode" "enum_game_structures_storage_access_mode" DEFAULT 'anyone';
ALTER TABLE "game_structures" ADD COLUMN "stored_asset_count" numeric;
ALTER TABLE "game_structures_stored_assets_equipment_attachments" ADD CONSTRAINT "game_structures_stored_assets_equipment_attachments_asset_id_assets_id_fk" FOREIGN KEY ("asset_id") REFERENCES "public"."assets"("id") ON DELETE set null ON UPDATE no action;
ALTER TABLE "game_structures_stored_assets_equipment_attachments" ADD CONSTRAINT "game_structures_stored_assets_equipment_attachments_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."game_structures_stored_assets"("id") ON DELETE cascade ON UPDATE no action;
ALTER TABLE "game_structures_stored_assets" ADD CONSTRAINT "game_structures_stored_assets_asset_id_assets_id_fk" FOREIGN KEY ("asset_id") REFERENCES "public"."assets"("id") ON DELETE set null ON UPDATE no action;
ALTER TABLE "game_structures_stored_assets" ADD CONSTRAINT "game_structures_stored_assets_equipment_skin_id_assets_id_fk" FOREIGN KEY ("equipment_skin_id") REFERENCES "public"."assets"("id") ON DELETE set null ON UPDATE no action;
ALTER TABLE "game_structures_stored_assets" ADD CONSTRAINT "game_structures_stored_assets_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."game_structures"("id") ON DELETE cascade ON UPDATE no action;
ALTER TABLE "game_structures_rels" ADD CONSTRAINT "game_structures_rels_parent_fk" FOREIGN KEY ("parent_id") REFERENCES "public"."game_structures"("id") ON DELETE cascade ON UPDATE no action;
ALTER TABLE "game_structures_rels" ADD CONSTRAINT "game_structures_rels_roles_fk" FOREIGN KEY ("roles_id") REFERENCES "public"."roles"("id") ON DELETE cascade ON UPDATE no action;
ALTER TABLE "game_structures_rels" ADD CONSTRAINT "game_structures_rels_users_fk" FOREIGN KEY ("users_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;
CREATE INDEX "game_structures_stored_assets_equipment_attachments_order_idx" ON "game_structures_stored_assets_equipment_attachments" USING btree ("_order");
CREATE INDEX "game_structures_stored_assets_equipment_attachments_parent_id_idx" ON "game_structures_stored_assets_equipment_attachments" USING btree ("_parent_id");
CREATE INDEX "game_structures_stored_assets_equipment_attachments_asse_idx" ON "game_structures_stored_assets_equipment_attachments" USING btree ("asset_id");
CREATE INDEX "game_structures_stored_assets_order_idx" ON "game_structures_stored_assets" USING btree ("_order");
CREATE INDEX "game_structures_stored_assets_parent_id_idx" ON "game_structures_stored_assets" USING btree ("_parent_id");
CREATE INDEX "game_structures_stored_assets_asset_idx" ON "game_structures_stored_assets" USING btree ("asset_id");
CREATE INDEX "game_structures_stored_assets_equipment_equipment_skin_idx" ON "game_structures_stored_assets" USING btree ("equipment_skin_id");
CREATE INDEX "game_structures_rels_order_idx" ON "game_structures_rels" USING btree ("order");
CREATE INDEX "game_structures_rels_parent_idx" ON "game_structures_rels" USING btree ("parent_id");
CREATE INDEX "game_structures_rels_path_idx" ON "game_structures_rels" USING btree ("path");
CREATE INDEX "game_structures_rels_roles_id_idx" ON "game_structures_rels" USING btree ("roles_id");
CREATE INDEX "game_structures_rels_users_id_idx" ON "game_structures_rels" USING btree ("users_id");
CREATE UNIQUE INDEX "game_structures_storage_slug_idx" ON "game_structures" USING btree ("storage_slug");`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "game_structures_stored_assets_equipment_attachments" DISABLE ROW LEVEL SECURITY;
ALTER TABLE "game_structures_stored_assets" DISABLE ROW LEVEL SECURITY;
ALTER TABLE "game_structures_rels" DISABLE ROW LEVEL SECURITY;
DROP TABLE "game_structures_stored_assets_equipment_attachments" CASCADE;
DROP TABLE "game_structures_stored_assets" CASCADE;
DROP TABLE "game_structures_rels" CASCADE;
DROP INDEX "game_structures_storage_slug_idx";
ALTER TABLE "game_structures" DROP COLUMN "storage_slug";
ALTER TABLE "game_structures" DROP COLUMN "storage_access_mode";
ALTER TABLE "game_structures" DROP COLUMN "stored_asset_count";
DROP TYPE "public"."enum_game_structures_storage_access_mode";`)
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,57 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
/**
* Converts GameNpcs.bio from a plain-text column to a Lexical richText (jsonb)
* column. Existing plain-text bios are wrapped in a single Lexical paragraph
* so no data is lost; the `USING` clause is required because there is no
* implicit varchar -> jsonb cast.
*/
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "game_npcs"
ALTER COLUMN "bio" SET DATA TYPE jsonb
USING CASE
WHEN "bio" IS NULL THEN NULL
ELSE jsonb_build_object(
'root', jsonb_build_object(
'type', 'root',
'format', '',
'indent', 0,
'version', 1,
'direction', NULL,
'children', jsonb_build_array(
jsonb_build_object(
'type', 'paragraph',
'format', '',
'indent', 0,
'version', 1,
'direction', NULL,
'textStyle', '',
'textFormat', 0,
'children', jsonb_build_array(
jsonb_build_object(
'type', 'text',
'text', "bio",
'mode', 'normal',
'style', '',
'detail', 0,
'format', 0,
'version', 1
)
)
)
)
)
)
END;`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "game_npcs"
ALTER COLUMN "bio" SET DATA TYPE varchar
USING CASE
WHEN "bio" IS NULL THEN NULL
ELSE "bio" #>> '{root,children,0,children,0,text}'
END;`)
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,16 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "game_npcs" ADD COLUMN "image_id" integer;
ALTER TABLE "game_npcs" ADD CONSTRAINT "game_npcs_image_id_media_id_fk" FOREIGN KEY ("image_id") REFERENCES "public"."media"("id") ON DELETE set null ON UPDATE no action;
CREATE INDEX "game_npcs_image_idx" ON "game_npcs" USING btree ("image_id");`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "game_npcs" DROP CONSTRAINT "game_npcs_image_id_media_id_fk";
DROP INDEX "game_npcs_image_idx";
ALTER TABLE "game_npcs" DROP COLUMN "image_id";`)
}

View file

@ -102,6 +102,10 @@ import * as migration_20261002_031917_add_promotion_nominations_and_leadership_t
import * as migration_20261002_180000_add_asset_type_accessory from './20261002_180000_add_asset_type_accessory';
import * as migration_20261003_060154_change_ai_model_to_ornith from './20261003_060154_change_ai_model_to_ornith';
import * as migration_20261003_190000_add_mission_map_markers from './20261003_190000_add_mission_map_markers';
import * as migration_20261005_001212_add_map_grid_config from './20261005_001212_add_map_grid_config';
import * as migration_20261005_051452_add_game_structure_item_storage from './20261005_051452_add_game_structure_item_storage';
import * as migration_20261005_054132_add_game_npc_bio_richtext from './20261005_054132_add_game_npc_bio_richtext';
import * as migration_20261005_063613_add_game_npc_image from './20261005_063613_add_game_npc_image';
export const migrations = [
{
@ -607,21 +611,41 @@ export const migrations = [
{
up: migration_20261002_031917_add_promotion_nominations_and_leadership_transfers.up,
down: migration_20261002_031917_add_promotion_nominations_and_leadership_transfers.down,
name: '20261002_031917_add_promotion_nominations_and_leadership_transfers'
name: '20261002_031917_add_promotion_nominations_and_leadership_transfers',
},
{
up: migration_20261002_180000_add_asset_type_accessory.up,
down: migration_20261002_180000_add_asset_type_accessory.down,
name: '20261002_180000_add_asset_type_accessory'
name: '20261002_180000_add_asset_type_accessory',
},
{
up: migration_20261003_060154_change_ai_model_to_ornith.up,
down: migration_20261003_060154_change_ai_model_to_ornith.down,
name: '20261003_060154_change_ai_model_to_ornith'
name: '20261003_060154_change_ai_model_to_ornith',
},
{
up: migration_20261003_190000_add_mission_map_markers.up,
down: migration_20261003_190000_add_mission_map_markers.down,
name: '20261003_190000_add_mission_map_markers'
name: '20261003_190000_add_mission_map_markers',
},
{
up: migration_20261005_001212_add_map_grid_config.up,
down: migration_20261005_001212_add_map_grid_config.down,
name: '20261005_001212_add_map_grid_config',
},
{
up: migration_20261005_051452_add_game_structure_item_storage.up,
down: migration_20261005_051452_add_game_structure_item_storage.down,
name: '20261005_051452_add_game_structure_item_storage',
},
{
up: migration_20261005_054132_add_game_npc_bio_richtext.up,
down: migration_20261005_054132_add_game_npc_bio_richtext.down,
name: '20261005_054132_add_game_npc_bio_richtext',
},
{
up: migration_20261005_063613_add_game_npc_image.up,
down: migration_20261005_063613_add_game_npc_image.down,
name: '20261005_063613_add_game_npc_image'
},
];

View file

@ -59,6 +59,10 @@ export const enum_game_structures_construction_status = pgEnum(
"enum_game_structures_construction_status",
["awaiting_materials", "building", "complete"],
);
export const enum_game_structures_storage_access_mode = pgEnum(
"enum_game_structures_storage_access_mode",
["anyone", "roles", "users"],
);
export const enum_game_vehicles_status = pgEnum("enum_game_vehicles_status", [
"idle",
"assigned",
@ -1413,6 +1417,65 @@ export const game_structures_void_storage = pgTable(
],
);
export const game_structures_stored_assets_equipment_attachments = pgTable(
"game_structures_stored_assets_equipment_attachments",
{
_order: integer("_order").notNull(),
_parentID: varchar("_parent_id").notNull(),
id: varchar("id").primaryKey(),
asset: integer("asset_id")
.notNull()
.references(() => assets.id, {
onDelete: "set null",
}),
},
(columns) => [
index("game_structures_stored_assets_equipment_attachments_order_idx").on(columns._order),
index("game_structures_stored_assets_equipment_attachments_parent_id_idx").on(
columns._parentID,
),
index("game_structures_stored_assets_equipment_attachments_asse_idx").on(columns.asset),
foreignKey({
columns: [columns["_parentID"]],
foreignColumns: [game_structures_stored_assets.id],
name: "game_structures_stored_assets_equipment_attachments_parent_id_fk",
}).onDelete("cascade"),
],
);
export const game_structures_stored_assets = pgTable(
"game_structures_stored_assets",
{
_order: integer("_order").notNull(),
_parentID: integer("_parent_id").notNull(),
id: varchar("id").primaryKey(),
asset: integer("asset_id")
.notNull()
.references(() => assets.id, {
onDelete: "set null",
}),
quantity: numeric("quantity", { mode: "number" }).notNull().default(1),
gridX: numeric("grid_x", { mode: "number" }).notNull().default(0),
gridY: numeric("grid_y", { mode: "number" }).notNull().default(0),
rotated: boolean("rotated").default(false),
equipment_skin: integer("equipment_skin_id").references(() => assets.id, {
onDelete: "set null",
}),
equipment_customName: varchar("equipment_custom_name"),
},
(columns) => [
index("game_structures_stored_assets_order_idx").on(columns._order),
index("game_structures_stored_assets_parent_id_idx").on(columns._parentID),
index("game_structures_stored_assets_asset_idx").on(columns.asset),
index("game_structures_stored_assets_equipment_equipment_skin_idx").on(columns.equipment_skin),
foreignKey({
columns: [columns["_parentID"]],
foreignColumns: [game_structures.id],
name: "game_structures_stored_assets_parent_id_fk",
}).onDelete("cascade"),
],
);
export const game_structures = pgTable(
"game_structures",
{
@ -1458,6 +1521,10 @@ export const game_structures = pgTable(
onDelete: "set null",
},
),
storageSlug: varchar("storage_slug"),
storageAccess_mode:
enum_game_structures_storage_access_mode("storage_access_mode").default("anyone"),
storedAssetCount: numeric("stored_asset_count", { mode: "number" }),
updatedAt: timestamp("updated_at", { mode: "string", withTimezone: true, precision: 3 })
.defaultNow()
.notNull(),
@ -1470,11 +1537,46 @@ export const game_structures = pgTable(
index("game_structures_faction_idx").on(columns.faction),
index("game_structures_map_idx").on(columns.map),
index("game_structures_parent_structure_idx").on(columns.parentStructure),
uniqueIndex("game_structures_storage_slug_idx").on(columns.storageSlug),
index("game_structures_updated_at_idx").on(columns.updatedAt),
index("game_structures_created_at_idx").on(columns.createdAt),
],
);
export const game_structures_rels = pgTable(
"game_structures_rels",
{
id: serial("id").primaryKey(),
order: integer("order"),
parent: integer("parent_id").notNull(),
path: varchar("path").notNull(),
rolesID: integer("roles_id"),
usersID: integer("users_id"),
},
(columns) => [
index("game_structures_rels_order_idx").on(columns.order),
index("game_structures_rels_parent_idx").on(columns.parent),
index("game_structures_rels_path_idx").on(columns.path),
index("game_structures_rels_roles_id_idx").on(columns.rolesID),
index("game_structures_rels_users_id_idx").on(columns.usersID),
foreignKey({
columns: [columns["parent"]],
foreignColumns: [game_structures.id],
name: "game_structures_rels_parent_fk",
}).onDelete("cascade"),
foreignKey({
columns: [columns["rolesID"]],
foreignColumns: [roles.id],
name: "game_structures_rels_roles_fk",
}).onDelete("cascade"),
foreignKey({
columns: [columns["usersID"]],
foreignColumns: [users.id],
name: "game_structures_rels_users_fk",
}).onDelete("cascade"),
],
);
export const game_vehicles_stored_resources = pgTable(
"game_vehicles_stored_resources",
{
@ -1571,6 +1673,9 @@ export const game_npcs = pgTable(
{
id: serial("id").primaryKey(),
name: varchar("name").notNull(),
image: integer("image_id").references(() => media.id, {
onDelete: "set null",
}),
occupation: varchar("occupation"),
location: integer("location_id").references(() => game_structures.id, {
onDelete: "set null",
@ -1578,7 +1683,7 @@ export const game_npcs = pgTable(
faction: integer("faction_id").references(() => factions.id, {
onDelete: "set null",
}),
bio: varchar("bio"),
bio: jsonb("bio"),
isGenerated: boolean("is_generated").default(false),
isInGame: boolean("is_in_game").default(true),
vendor_enabled: boolean("vendor_enabled").default(false),
@ -1591,6 +1696,7 @@ export const game_npcs = pgTable(
.notNull(),
},
(columns) => [
index("game_npcs_image_idx").on(columns.image),
index("game_npcs_location_idx").on(columns.location),
index("game_npcs_faction_idx").on(columns.faction),
index("game_npcs_updated_at_idx").on(columns.updatedAt),
@ -5498,6 +5604,14 @@ export const maps = pgTable(
defaultCenterX: numeric("default_center_x", { mode: "number" }),
defaultCenterY: numeric("default_center_y", { mode: "number" }),
defaultZoom: numeric("default_zoom", { mode: "number" }).default(2),
gridEnabled: boolean("grid_enabled").default(false),
gridOriginEasting: numeric("grid_origin_easting", { mode: "number" }).default(0),
gridOriginNorthing: numeric("grid_origin_northing", { mode: "number" }).default(0),
gridStartEasting: numeric("grid_start_easting", { mode: "number" }).default(0),
gridStartNorthing: numeric("grid_start_northing", { mode: "number" }).default(0),
gridSpacingMeters: numeric("grid_spacing_meters", { mode: "number" }).default(1000),
gridLabelDigits: numeric("grid_label_digits", { mode: "number" }).default(2),
gridNumbersOverLines: boolean("grid_numbers_over_lines").default(false),
updatedAt: timestamp("updated_at", { mode: "string", withTimezone: true, precision: 3 })
.defaultNow()
.notNull(),
@ -8365,6 +8479,61 @@ export const relations_game_structures_void_storage = relations(
}),
}),
);
export const relations_game_structures_stored_assets_equipment_attachments = relations(
game_structures_stored_assets_equipment_attachments,
({ one }) => ({
_parentID: one(game_structures_stored_assets, {
fields: [game_structures_stored_assets_equipment_attachments._parentID],
references: [game_structures_stored_assets.id],
relationName: "equipment_attachments",
}),
asset: one(assets, {
fields: [game_structures_stored_assets_equipment_attachments.asset],
references: [assets.id],
relationName: "asset",
}),
}),
);
export const relations_game_structures_stored_assets = relations(
game_structures_stored_assets,
({ one, many }) => ({
_parentID: one(game_structures, {
fields: [game_structures_stored_assets._parentID],
references: [game_structures.id],
relationName: "storedAssets",
}),
asset: one(assets, {
fields: [game_structures_stored_assets.asset],
references: [assets.id],
relationName: "asset",
}),
equipment_attachments: many(game_structures_stored_assets_equipment_attachments, {
relationName: "equipment_attachments",
}),
equipment_skin: one(assets, {
fields: [game_structures_stored_assets.equipment_skin],
references: [assets.id],
relationName: "equipment_skin",
}),
}),
);
export const relations_game_structures_rels = relations(game_structures_rels, ({ one }) => ({
parent: one(game_structures, {
fields: [game_structures_rels.parent],
references: [game_structures.id],
relationName: "_rels",
}),
rolesID: one(roles, {
fields: [game_structures_rels.rolesID],
references: [roles.id],
relationName: "roles",
}),
usersID: one(users, {
fields: [game_structures_rels.usersID],
references: [users.id],
relationName: "users",
}),
}));
export const relations_game_structures = relations(game_structures, ({ one, many }) => ({
type: one(structures, {
fields: [game_structures.type],
@ -8407,6 +8576,12 @@ export const relations_game_structures = relations(game_structures, ({ one, many
voidStorage: many(game_structures_void_storage, {
relationName: "voidStorage",
}),
storedAssets: many(game_structures_stored_assets, {
relationName: "storedAssets",
}),
_rels: many(game_structures_rels, {
relationName: "_rels",
}),
}));
export const relations_game_vehicles_stored_resources = relations(
game_vehicles_stored_resources,
@ -8474,6 +8649,11 @@ export const relations_game_npcs_rels = relations(game_npcs_rels, ({ one }) => (
}),
}));
export const relations_game_npcs = relations(game_npcs, ({ one, many }) => ({
image: one(media, {
fields: [game_npcs.image],
references: [media.id],
relationName: "image",
}),
location: one(game_structures, {
fields: [game_npcs.location],
references: [game_structures.id],
@ -11246,6 +11426,7 @@ type DatabaseSchema = {
enum_announcements_paths_match_type: typeof enum_announcements_paths_match_type;
enum_game_structures_staff_positions_position_type: typeof enum_game_structures_staff_positions_position_type;
enum_game_structures_construction_status: typeof enum_game_structures_construction_status;
enum_game_structures_storage_access_mode: typeof enum_game_structures_storage_access_mode;
enum_game_vehicles_status: typeof enum_game_vehicles_status;
enum_npc_staffing_position_type: typeof enum_npc_staffing_position_type;
enum_npc_staffing_status: typeof enum_npc_staffing_status;
@ -11373,7 +11554,10 @@ type DatabaseSchema = {
game_structures_installed_modules: typeof game_structures_installed_modules;
game_structures_stored_resources: typeof game_structures_stored_resources;
game_structures_void_storage: typeof game_structures_void_storage;
game_structures_stored_assets_equipment_attachments: typeof game_structures_stored_assets_equipment_attachments;
game_structures_stored_assets: typeof game_structures_stored_assets;
game_structures: typeof game_structures;
game_structures_rels: typeof game_structures_rels;
game_vehicles_stored_resources: typeof game_vehicles_stored_resources;
game_vehicles_void_storage: typeof game_vehicles_void_storage;
game_vehicles: typeof game_vehicles;
@ -11566,6 +11750,9 @@ type DatabaseSchema = {
relations_game_structures_installed_modules: typeof relations_game_structures_installed_modules;
relations_game_structures_stored_resources: typeof relations_game_structures_stored_resources;
relations_game_structures_void_storage: typeof relations_game_structures_void_storage;
relations_game_structures_stored_assets_equipment_attachments: typeof relations_game_structures_stored_assets_equipment_attachments;
relations_game_structures_stored_assets: typeof relations_game_structures_stored_assets;
relations_game_structures_rels: typeof relations_game_structures_rels;
relations_game_structures: typeof relations_game_structures;
relations_game_vehicles_stored_resources: typeof relations_game_vehicles_stored_resources;
relations_game_vehicles_void_storage: typeof relations_game_vehicles_void_storage;

View file

@ -1113,6 +1113,63 @@ export interface GameStructure {
id?: string | null;
}[]
| null;
/**
* Slug identifying this structure's item storage to the game bridge (e.g. 'superstructure'). The in-game arsenal module binds to structure:<slug>. Empty = no item storage.
*/
storageSlug?: string | null;
/**
* Who can see and edit this structure's item storage in the member UI. Bridge (game) sync is unaffected by these rules.
*/
storageAccess?: {
mode?: ('anyone' | 'roles' | 'users') | null;
/**
* Members holding any of these roles (Role Assignments) can access the storage.
*/
roles?: (number | Role)[] | null;
/**
* Only these members can access the storage.
*/
users?: (number | User)[] | null;
};
/**
* Arma item storage (limited-arsenal stock). Synced with the game via locker.sync / locker.apply; grid position and equipment are managed from the member UI and preserved by sync merges.
*/
storedAssets?:
| {
asset: number | Asset;
quantity: number;
/**
* Column position in the storage grid (0-indexed).
*/
gridX: number;
/**
* Row position in the storage grid (0-indexed).
*/
gridY: number;
/**
* Whether this item is rotated 90 degrees (swaps width and height).
*/
rotated?: boolean | null;
/**
* Per-instance customization for this item: installed attachments, applied skin, and a custom name. Managed from the member storage UI.
*/
equipment?: {
attachments?:
| {
asset: number | Asset;
id?: string | null;
}[]
| null;
skin?: (number | null) | Asset;
customName?: string | null;
};
id?: string | null;
}[]
| null;
/**
* Total number of distinct entries currently in item storage.
*/
storedAssetCount?: number | null;
updatedAt: string;
createdAt: string;
}
@ -2205,6 +2262,38 @@ export interface Map {
*/
defaultCenterY?: number | null;
defaultZoom?: number | null;
/**
* Show a coordinate grid on the world map and mission planning maps, and use it for grid reference readouts.
*/
gridEnabled?: boolean | null;
/**
* Meters from the west edge (in-game X) to the grid's zero line. Vanilla terrains use 0 (zero line on the west edge).
*/
gridOriginEasting?: number | null;
/**
* Meters from the south edge (in-game Y) to the grid's zero line. Vanilla terrains use 0 (zero line on the south edge).
*/
gridOriginNorthing?: number | null;
/**
* Number shown on the first easting line (at the origin). Applies at the base spacing and finer subdivisions.
*/
gridStartEasting?: number | null;
/**
* Number shown on the first northing line (at the origin). Applies at the base spacing and finer subdivisions.
*/
gridStartNorthing?: number | null;
/**
* Base grid cell size in meters. The map subdivides 10x automatically as you zoom in, like the in-game map.
*/
gridSpacingMeters?: number | null;
/**
* Digits shown per axis at the base spacing (Arma shows 2 at 1 km, 3 at 100 m). Numbers wrap at the digit width.
*/
gridLabelDigits?: number | null;
/**
* Draw labels on the grid lines instead of centered in the cells (Tanoa style).
*/
gridNumbersOverLines?: boolean | null;
updatedAt: string;
createdAt: string;
}
@ -2275,6 +2364,10 @@ export interface GameNpc {
* The NPC's name as shown in-game and on the frontend.
*/
name: string;
/**
* Portrait/photo for this contact. Shown on the contacts directory and profile when set.
*/
image?: (number | null) | Media;
/**
* What this NPC does (e.g. 'Weapons Dealer', 'Field Medic').
*/
@ -2290,7 +2383,21 @@ export interface GameNpc {
/**
* A short background/profile for this NPC.
*/
bio?: string | null;
bio?: {
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;
} | null;
/**
* True for NPCs auto-created by the market tick to cover unstocked goods. They are placeholders until included in the game.
*/
@ -7426,6 +7533,37 @@ export interface GameStructuresSelect<T extends boolean = true> {
rotated?: T;
id?: T;
};
storageSlug?: T;
storageAccess?:
| T
| {
mode?: T;
roles?: T;
users?: T;
};
storedAssets?:
| T
| {
asset?: T;
quantity?: T;
gridX?: T;
gridY?: T;
rotated?: T;
equipment?:
| T
| {
attachments?:
| T
| {
asset?: T;
id?: T;
};
skin?: T;
customName?: T;
};
id?: T;
};
storedAssetCount?: T;
updatedAt?: T;
createdAt?: T;
}
@ -7470,6 +7608,7 @@ export interface GameVehiclesSelect<T extends boolean = true> {
*/
export interface GameNpcsSelect<T extends boolean = true> {
name?: T;
image?: T;
occupation?: T;
location?: T;
faction?: T;
@ -9023,6 +9162,14 @@ export interface MapsSelect<T extends boolean = true> {
defaultCenterX?: T;
defaultCenterY?: T;
defaultZoom?: T;
gridEnabled?: T;
gridOriginEasting?: T;
gridOriginNorthing?: T;
gridStartEasting?: T;
gridStartNorthing?: T;
gridSpacingMeters?: T;
gridLabelDigits?: T;
gridNumbersOverLines?: T;
updatedAt?: T;
createdAt?: T;
}

View file

@ -0,0 +1,453 @@
import { getPayload, Payload } from "payload";
import config from "@/payload.config";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import {
formatInstanceRef,
mergeStockIntoItems,
parseInstanceRef,
parseStockSnapshot,
processLockerEvent,
} from "@/lib/arma-bridge/lockers";
let payload: Payload;
const RUN = `locker-${Date.now().toString(36)}`;
const STEAM_ID = `${RUN}-steam-001`;
const UNLINKED = `${RUN}-steam-unlinked`;
const SLUG = `${RUN}-superstructure`;
const CLASS_A = "arifle_MX_F";
const CLASS_B = "ACE_bandage";
const LEXICAL_EMPTY = {
root: {
children: [{ text: "" }],
direction: null,
format: "" as const,
indent: 0,
type: "text",
version: 1,
},
};
let userId: number;
let assetAId: number;
let assetBId: number;
let resourceId: number;
let blueprintId: number;
let structureId: number;
let lockerId: number;
let serverId: number;
const commandIds: number[] = [];
let eventSeq = 0;
function lockerEvent(type: string, eventPayload: unknown[], server: number) {
eventSeq += 1;
return {
id: eventSeq,
eventId: `${RUN}:${eventSeq}`,
server,
type,
occurredAt: new Date().toISOString(),
payload: eventPayload,
};
}
async function findLockerApplyCommands(): Promise<{ id: number; payload: unknown }[]> {
const found = await payload.find({
collection: "arma-commands",
where: { type: { equals: "locker.apply" } },
limit: 100,
depth: 0,
overrideAccess: true,
});
return found.docs.map((doc) => ({ id: doc.id, payload: (doc as { payload?: unknown }).payload }));
}
async function lockerDoc() {
return (await payload.findByID({
collection: "locker-storages",
id: lockerId,
depth: 0,
overrideAccess: true,
})) as unknown as { items: Record<string, unknown>[]; itemCount: number };
}
describe("Arma locker sync", () => {
beforeAll(async () => {
const payloadConfig = await config;
payload = await getPayload({ config: payloadConfig });
const user = await payload.create({
collection: "users",
data: {
username: `${RUN}-player`,
discordUsername: `${RUN}-player-discord`,
displayName: `${RUN} Player`,
steamId: STEAM_ID,
password: "Test1234",
},
overrideAccess: true,
depth: 0,
});
userId = user.id;
for (const [className, name] of [
[CLASS_A, `${RUN} MX Rifle`],
[CLASS_B, `${RUN} Bandage`],
] as const) {
const asset = await payload.create({
collection: "assets",
data: {
name,
className,
assetType: className === CLASS_A ? "weapon" : "medical",
approvalStatus: "approved",
} as never,
draft: false,
overrideAccess: true,
depth: 0,
});
if (className === CLASS_A) assetAId = asset.id;
else assetBId = asset.id;
}
const resource = await payload.create({
collection: "resources",
data: {
name: `${RUN} Steel`,
codeName: `${RUN}-steel`,
approvalStatus: "in_progress",
type: "physical",
baseValue: 1,
rarity: "common",
unitOfMeasure: "kg",
massPerUnit: 1,
gridWidth: 1,
gridHeight: 1,
} as never,
overrideAccess: true,
depth: 0,
});
resourceId = resource.id;
const blueprint = await payload.create({
collection: "structures",
data: {
name: `${RUN} Superstructure`,
codeName: `${RUN}-superstructure`,
approvalStatus: "in_progress",
description: LEXICAL_EMPTY,
category: "logistics",
materials: [{ resource: resourceId, amount: 1 }],
constructionDurationMinutes: 1,
terrainType: "land",
maxHealth: 100,
} as never,
overrideAccess: true,
depth: 0,
});
blueprintId = blueprint.id;
const structure = await payload.create({
collection: "game-structures",
data: {
name: `${RUN} Superstructure`,
type: blueprintId,
constructionStatus: "complete",
storageSlug: SLUG,
} as never,
overrideAccess: true,
depth: 0,
});
structureId = structure.id;
});
afterAll(async () => {
for (const id of commandIds) {
await payload.delete({ collection: "arma-commands", id, overrideAccess: true }).catch(() => {});
}
if (lockerId) {
await payload.delete({ collection: "locker-storages", id: lockerId, overrideAccess: true }).catch(() => {});
}
if (structureId) {
await payload.delete({ collection: "game-structures", id: structureId, overrideAccess: true }).catch(() => {});
}
if (blueprintId) {
await payload.delete({ collection: "structures", id: blueprintId, overrideAccess: true }).catch(() => {});
}
if (resourceId) {
await payload.delete({ collection: "resources", id: resourceId, overrideAccess: true }).catch(() => {});
}
for (const id of [assetAId, assetBId]) {
if (id) await payload.delete({ collection: "assets", id, overrideAccess: true }).catch(() => {});
}
if (serverId) {
await payload.delete({ collection: "game-servers", id: serverId, overrideAccess: true }).catch(() => {});
}
if (userId) {
const profiles = await payload.find({
collection: "profiles",
where: { user: { equals: userId } },
depth: 0,
overrideAccess: true,
});
for (const profile of profiles.docs) {
await payload.delete({ collection: "profiles", id: profile.id, overrideAccess: true }).catch(() => {});
}
await payload.delete({ collection: "users", id: userId, overrideAccess: true }).catch(() => {});
}
});
describe("parseInstanceRef", () => {
it("parses personal and structure refs", () => {
expect(parseInstanceRef(`personal:${STEAM_ID}`)).toEqual({ kind: "personal", steamId: STEAM_ID });
expect(parseInstanceRef("structure:superstructure")).toEqual({
kind: "structure",
slug: "superstructure",
});
expect(formatInstanceRef({ kind: "personal", steamId: "abc" })).toBe("personal:abc");
});
it("rejects malformed refs", () => {
expect(parseInstanceRef(null)).toBeNull();
expect(parseInstanceRef("nope")).toBeNull();
expect(parseInstanceRef("personal:")).toBeNull();
expect(parseInstanceRef("structure:Bad Slug!")).toBeNull();
expect(parseInstanceRef("other:x")).toBeNull();
});
});
describe("parseStockSnapshot", () => {
it("parses [[class, count], ...] and clamps counts", () => {
expect(
parseStockSnapshot([
[CLASS_A, 3],
[CLASS_B, 2.6],
]),
).toEqual([
{ className: CLASS_A, count: 3 },
{ className: CLASS_B, count: 3 },
]);
});
it("returns null for non-arrays and drops bad lines", () => {
expect(parseStockSnapshot("nope")).toBeNull();
expect(parseStockSnapshot([[CLASS_A, "x"], ["", 1], [CLASS_B, 2]])).toEqual([
{ className: CLASS_B, count: 2 },
]);
});
});
describe("mergeStockIntoItems", () => {
it("preserves grid metadata, appends new classes, leaves unknown entries", () => {
const existing = [
{ asset: 1, quantity: 2, gridX: 3, gridY: 4, rotated: true, className: CLASS_A, equipment: { customName: "Frank's Karma" } },
{ asset: 9, quantity: 1, gridX: 0, gridY: 0, rotated: false, className: "other_class" },
];
const assetIds = new Map<string, number>([
[CLASS_A, 1],
[CLASS_B, 2],
]);
const merged = mergeStockIntoItems(
existing,
[
{ className: CLASS_A, count: 7 },
{ className: CLASS_B, count: 10 },
{ className: "no_such_asset", count: 1 },
],
assetIds,
);
expect(merged).toHaveLength(3);
expect(merged[0]).toMatchObject({ quantity: 7, gridX: 3, gridY: 4, rotated: true });
expect((merged[0].equipment as { customName: string }).customName).toBe("Frank's Karma");
expect(merged[1]).toMatchObject({ className: "other_class", quantity: 1 });
expect(merged[2]).toMatchObject({ asset: 2, quantity: 10, gridX: 0, gridY: 5, rotated: false });
});
});
describe("locker.sync (personal)", () => {
it("creates the linked user's locker from the first snapshot", async () => {
await expect(
processLockerEvent(payload, lockerEvent("locker.sync", [`personal:${STEAM_ID}`, [[CLASS_A, 2]]], 1)),
).resolves.toBeUndefined();
const lockers = await payload.find({
collection: "locker-storages",
where: { ownerUser: { equals: userId } },
limit: 1,
depth: 0,
overrideAccess: true,
});
expect(lockers.docs).toHaveLength(1);
lockerId = lockers.docs[0].id;
const doc = await lockerDoc();
expect(doc.itemCount).toBe(1);
expect(doc.items[0]).toMatchObject({ asset: assetAId, quantity: 2, gridX: 0, gridY: 0, rotated: false });
});
it("preserves web-managed grid metadata on later syncs", async () => {
await payload.update({
collection: "locker-storages",
id: lockerId,
data: {
items: [
{
asset: assetAId,
quantity: 2,
gridX: 3,
gridY: 4,
rotated: true,
equipment: { customName: "Frank's Karma" },
},
],
} as never,
overrideAccess: true,
depth: 0,
});
await processLockerEvent(
payload,
lockerEvent("locker.sync", [`personal:${STEAM_ID}`, [[CLASS_A, 7], [CLASS_B, 10]]], 1),
);
const doc = await lockerDoc();
expect(doc.itemCount).toBe(2);
const byAsset = new Map(doc.items.map((item) => [item.asset, item]));
expect(byAsset.get(assetAId)).toMatchObject({
quantity: 7,
gridX: 3,
gridY: 4,
rotated: true,
equipment: { customName: "Frank's Karma" },
});
expect(byAsset.get(assetBId)).toMatchObject({ quantity: 10, gridX: 0, gridY: 5, rotated: false });
});
it("treats absence as not-deletion and skips unknown classes", async () => {
await processLockerEvent(
payload,
lockerEvent("locker.sync", [`personal:${STEAM_ID}`, [[CLASS_A, 1], ["no_such_class", 3]]], 1),
);
const doc = await lockerDoc();
expect(doc.itemCount).toBe(2);
const byAsset = new Map(doc.items.map((item) => [item.asset, item]));
expect(byAsset.get(assetAId)).toMatchObject({ quantity: 1 });
expect(byAsset.get(assetBId)).toMatchObject({ quantity: 10 });
});
it("skips unlinked Steam IDs without creating anything", async () => {
const before = await payload.find({ collection: "locker-storages", limit: 100, depth: 0, overrideAccess: true });
await expect(
processLockerEvent(payload, lockerEvent("locker.sync", [`personal:${UNLINKED}`, [[CLASS_A, 5]]], 1)),
).resolves.toBeUndefined();
const after = await payload.find({ collection: "locker-storages", limit: 100, depth: 0, overrideAccess: true });
expect(after.totalDocs).toBe(before.totalDocs);
});
it("is idempotent for repeated snapshots", async () => {
const event = lockerEvent("locker.sync", [`personal:${STEAM_ID}`, [[CLASS_A, 1]]], 1);
await processLockerEvent(payload, event);
await processLockerEvent(payload, { ...event });
const doc = await lockerDoc();
expect(doc.itemCount).toBe(2);
});
});
describe("locker.sync (structure)", () => {
it("merges into game-structures storedAssets by storageSlug", async () => {
await processLockerEvent(
payload,
lockerEvent("locker.sync", [`structure:${SLUG}`, [[CLASS_A, 4]]], 1),
);
const structure = (await payload.findByID({
collection: "game-structures",
id: structureId,
depth: 0,
overrideAccess: true,
})) as unknown as { storedAssets: Record<string, unknown>[]; storedAssetCount: number };
expect(structure.storedAssetCount).toBe(1);
expect(structure.storedAssets[0]).toMatchObject({ asset: assetAId, quantity: 4 });
});
it("skips unknown slugs without throwing", async () => {
await expect(
processLockerEvent(payload, lockerEvent("locker.sync", [`structure:${RUN}-missing`, [[CLASS_A, 4]]], 1)),
).resolves.toBeUndefined();
});
});
describe("locker.request + locker.apply enqueue", () => {
it("enqueues exactly one locker.apply for the requesting server with current stock", async () => {
const server = await payload.create({
collection: "game-servers",
data: {
serverId: `${RUN}-srv`,
name: `${RUN} Test Server`,
status: "online",
lastSeenAt: new Date().toISOString(),
} as never,
overrideAccess: true,
depth: 0,
});
serverId = server.id;
await processLockerEvent(payload, lockerEvent("locker.request", [`personal:${STEAM_ID}`], serverId));
const commands = await findLockerApplyCommands();
commandIds.push(...commands.map((command) => command.id));
expect(commands).toHaveLength(1);
const [instanceRef, stock] = commands[0].payload as [string, [string, number][]];
expect(instanceRef).toBe(`personal:${STEAM_ID}`);
expect(stock).toContainEqual([CLASS_A, 1]);
expect(stock).toContainEqual([CLASS_B, 10]);
});
it("enqueues nothing for unknown instances", async () => {
await processLockerEvent(payload, lockerEvent("locker.request", [`structure:${RUN}-missing`], serverId));
const commands = await findLockerApplyCommands();
expect(commands).toHaveLength(1);
});
});
describe("echo guard", () => {
it("web-originated locker edits enqueue locker.apply; sync-origin writes do not", async () => {
const beforeCommands = await findLockerApplyCommands();
const beforeIds = new Set(beforeCommands.map((command) => command.id));
const doc = await lockerDoc();
await payload.update({
collection: "locker-storages",
id: lockerId,
data: {
items: doc.items.map((item) =>
item.asset === assetAId ? { ...item, quantity: 42 } : item,
),
} as never,
overrideAccess: true,
depth: 0,
});
const afterEdit = await findLockerApplyCommands();
const newCommands = afterEdit.filter((command) => !beforeIds.has(command.id));
commandIds.push(...newCommands.map((command) => command.id));
expect(newCommands).toHaveLength(1);
const [instanceRef, stock] = newCommands[0].payload as [string, [string, number][]];
expect(instanceRef).toBe(`personal:${STEAM_ID}`);
expect(stock).toContainEqual([CLASS_A, 42]);
const docAgain = await lockerDoc();
await payload.update({
collection: "locker-storages",
id: lockerId,
data: {
items: docAgain.items.map((item) =>
item.asset === assetAId ? { ...item, quantity: 43 } : item,
),
} as never,
context: { lockerSyncOrigin: true },
overrideAccess: true,
depth: 0,
});
const afterSyncWrite = await findLockerApplyCommands();
expect(afterSyncWrite.filter((command) => !beforeIds.has(command.id))).toHaveLength(1);
});
});
});

View file

@ -229,6 +229,9 @@ describe("Leadership evaluations", () => {
it("classifies mission statuses for evaluability (pure)", () => {
const past = new Date(Date.now() - 86_400_000).toISOString();
const future = new Date(Date.now() + 86_400_000).toISOString();
// A mission that just started: past its start but inside the default
// 240-minute window, so it is still running and not yet evaluable.
const justStarted = new Date(Date.now() - 60 * 60 * 1000).toISOString();
expect(isMissionEvaluable("Completed")).toBe(true);
expect(isMissionEvaluable("Scheduled", past)).toBe(true);
@ -238,6 +241,12 @@ describe("Leadership evaluations", () => {
expect(isMissionEvaluable("Cancelled", past)).toBe(false);
expect(isMissionEvaluable("Scheduled")).toBe(false);
expect(isMissionEvaluable("Scheduled", "not-a-date")).toBe(false);
// Still running: start has passed but the scheduled window has not.
expect(isMissionEvaluable("Active", justStarted)).toBe(false);
expect(isMissionEvaluable("Scheduled", justStarted)).toBe(false);
// Explicit duration: evaluable once start + duration has fully passed.
expect(isMissionEvaluable("Active", justStarted, 30)).toBe(true);
expect(isMissionEvaluable("Active", justStarted, 240)).toBe(false);
});
it("derives the evaluation kind from the rater/ratee/mission relationship", async () => {

View file

@ -0,0 +1,260 @@
import { describe, expect, it } from "vitest";
import { armaGridRef } from "@/lib/arma-markers/missionMarkers";
import {
DEFAULT_MAP_GRID,
GRID_MIN_CELL_PX,
gridConfigFromMapDoc,
gridLabel,
gridLevelFor,
gridLinesForBounds,
gridRef,
} from "@/lib/map/grid";
const WORLD = 8192;
const FULL_WORLD = { minX: 0, minY: 0, maxX: WORLD, maxY: WORLD };
describe("gridLabel", () => {
it("zero-pads to the digit width", () => {
expect(gridLabel(7, 3)).toBe("007");
expect(gridLabel(0, 2)).toBe("00");
expect(gridLabel(42, 4)).toBe("0042");
});
it("wraps at the digit width", () => {
expect(gridLabel(1234, 3)).toBe("234");
expect(gridLabel(100, 2)).toBe("00");
});
it("wraps negatives like Arma", () => {
expect(gridLabel(-1, 3)).toBe("999");
expect(gridLabel(-25, 2)).toBe("75");
});
it("truncates fractional input", () => {
expect(gridLabel(12.9, 2)).toBe("12");
expect(gridLabel(-1.5, 2)).toBe("99");
});
});
describe("gridLevelFor", () => {
it("walks the A3 ladder with the default config", () => {
expect(gridLevelFor(8, DEFAULT_MAP_GRID)).toEqual({ spacing: 1000, digits: 2 });
expect(gridLevelFor(0.5, DEFAULT_MAP_GRID)).toEqual({ spacing: 100, digits: 3 });
expect(gridLevelFor(0.0625, DEFAULT_MAP_GRID)).toEqual({ spacing: 10, digits: 4 });
// Far out: nothing finer reads, the coarsest level wins.
expect(gridLevelFor(64, DEFAULT_MAP_GRID)).toEqual({ spacing: 10000, digits: 1 });
});
it("keeps the coarsest level when zoomed out past every threshold", () => {
expect(gridLevelFor(1000, DEFAULT_MAP_GRID)).toEqual({ spacing: 10000, digits: 1 });
});
it("chooses a level exactly at GRID_MIN_CELL_PX and never a finer one below it", () => {
expect(GRID_MIN_CELL_PX).toBe(56);
// 5600 m base cells: at 100 m/px the base cell is exactly 56 px on screen.
const config = gridConfigFromMapDoc({ gridEnabled: true, gridSpacingMeters: 5600 });
expect(gridLevelFor(100, config)).toEqual({ spacing: 5600, digits: 2 });
// A hair further out the base cell drops under the threshold; the finer
// levels are smaller still, so the ladder falls back to the coarse level.
expect(gridLevelFor(101, config)).toEqual({ spacing: 56000, digits: 1 });
// Same crossing on the default ladder between mpp 1.7 and 2 (100 m cell
// sits at 58.8 px, then 50 px).
expect(gridLevelFor(1.7, DEFAULT_MAP_GRID)).toEqual({ spacing: 100, digits: 3 });
expect(gridLevelFor(2, DEFAULT_MAP_GRID)).toEqual({ spacing: 1000, digits: 2 });
});
});
describe("gridRef", () => {
it("reproduces the legacy armaGridRef output with DEFAULT_MAP_GRID", () => {
const point: [number, number] = [4567, WORLD - 1234];
expect(gridRef(point, WORLD, DEFAULT_MAP_GRID, 6)).toBe("045 012");
expect(gridRef(point, WORLD, DEFAULT_MAP_GRID, 8)).toBe("0456 0123");
// Default arguments land on the same 6-digit reference.
expect(gridRef(point, WORLD)).toBe("045 012");
});
it("armaGridRef still returns the legacy strings (it delegates to gridRef)", () => {
expect(armaGridRef([4567, WORLD - 1234], WORLD)).toBe("045 012");
expect(armaGridRef([4567, WORLD - 1234], WORLD, 8)).toBe("0456 0123");
});
it("uses 100 m cells at 6 digits and 10 m cells at 8", () => {
const point: [number, number] = [4567, WORLD - 1234];
const [e6, n6] = gridRef(point, WORLD, DEFAULT_MAP_GRID, 6).split(" ");
const [e8, n8] = gridRef(point, WORLD, DEFAULT_MAP_GRID, 8).split(" ");
// The 6-digit groups are the truncation of the 8-digit groups.
expect(e8.startsWith(e6)).toBe(true);
expect(n8.startsWith(n6)).toBe(true);
// 100 m granularity at 6 digits: 4599 stays, 4600 rolls over.
expect(gridRef([4599, WORLD - 1234], WORLD, DEFAULT_MAP_GRID, 6)).toBe("045 012");
expect(gridRef([4600, WORLD - 1234], WORLD, DEFAULT_MAP_GRID, 6)).toBe("046 012");
// 10 m granularity at 8 digits: 4569 stays, 4570 rolls over.
expect(gridRef([4569, WORLD - 1234], WORLD, DEFAULT_MAP_GRID, 8)).toBe("0456 0123");
expect(gridRef([4570, WORLD - 1234], WORLD, DEFAULT_MAP_GRID, 8)).toBe("0457 0123");
});
it("shifts the zero line with gridOriginEasting/gridOriginNorthing", () => {
const config = gridConfigFromMapDoc({
gridEnabled: true,
gridOriginEasting: 2000,
gridOriginNorthing: 3000,
});
// A point exactly on the configured origin reads zero at every precision.
const atOrigin: [number, number] = [2000, WORLD - 3000];
expect(gridRef(atOrigin, WORLD, config, 6)).toBe("000 000");
expect(gridRef(atOrigin, WORLD, config, 8)).toBe("0000 0000");
// The vanilla default would read raw meters at the same spot.
expect(gridRef(atOrigin, WORLD, DEFAULT_MAP_GRID, 6)).toBe("020 030");
});
it("reads the configured starting numbers on the origin line", () => {
const config = gridConfigFromMapDoc({
gridEnabled: true,
gridOriginEasting: 2000,
gridOriginNorthing: 3000,
gridStartEasting: 5,
gridStartNorthing: 7,
});
// Start numbers are defined at the base spacing and scale into finer
// levels: 5 at 1 km reads "050" at 100 m.
expect(gridRef([2000, WORLD - 3000], WORLD, config, 6)).toBe("050 070");
});
it("scales starting numbers across levels and keeps the nesting mod rule", () => {
const config = gridConfigFromMapDoc({ gridEnabled: true, gridStartEasting: 100 });
// Base level (1 km, 2 digits): the first cell east of the zero line adds
// the start value, then wraps to the digit width.
const set = gridLinesForBounds(config, WORLD, FULL_WORLD, 8);
expect(set.level).toEqual({ spacing: 1000, digits: 2 });
const baseLabel = set.eastingLabels.find((l) => l.at === 500);
expect(baseLabel?.value).toBe("00"); // 0 + 100, wrapped to 2 digits
// 100 m level (6-digit ref) at the zero line: 0 + 100*10 = 1000 -> "000".
const [easting6] = gridRef([0, WORLD - 1234], WORLD, config, 6).split(" ");
expect(easting6).toBe("000");
// Nesting: the finer label's trailing digits match the base label.
expect(easting6.slice(-2)).toBe(baseLabel?.value);
// 10 m level (8-digit ref): 0 + 100*100 = 10000 -> "0000".
expect(gridRef([0, WORLD - 1234], WORLD, config, 8).split(" ")[0]).toBe("0000");
});
it("wraps labels west of an origin that sits east of the point", () => {
const config = gridConfigFromMapDoc({ gridEnabled: true, gridOriginEasting: 5000 });
// x = 1000 lies 4000 m west of the zero line: -40 cells at 100 m.
expect(gridRef([1000, WORLD - 1000], WORLD, config, 6)).toBe("960 010");
// Base level: the cell holding x = 1000 is index -4, wrapped to "96".
const set = gridLinesForBounds(
config,
WORLD,
{ minX: 0, minY: 0, maxX: 2000, maxY: 2000 },
8,
);
expect(set.eastingLabels.find((l) => l.at === 1500)?.value).toBe("96");
});
});
describe("gridLinesForBounds", () => {
it("covers the viewport plus one padded cell of lines at the 1 km level", () => {
const set = gridLinesForBounds(DEFAULT_MAP_GRID, WORLD, FULL_WORLD, 8);
expect(set.level).toEqual({ spacing: 1000, digits: 2 });
// Lines span one padded cell past each edge; the east/south side ceils to
// the next line because 8192 is not cell-aligned.
expect(set.verticalLines).toEqual([
-1000, 0, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000,
]);
expect(set.horizontalLines).toEqual([
9192, 8192, 7192, 6192, 5192, 4192, 3192, 2192, 1192, 192, -808, -1808,
]);
});
it("centers easting labels in their cells by default", () => {
const set = gridLinesForBounds(DEFAULT_MAP_GRID, WORLD, FULL_WORLD, 8);
expect(set.eastingLabels).toHaveLength(10);
expect(set.eastingLabels[1]).toEqual({ value: "00", at: 500 });
expect(set.eastingLabels[2]).toEqual({ value: "01", at: 1500 });
// One padded cell west of the zero line wraps to "99".
expect(set.eastingLabels[0]).toEqual({ value: "99", at: -500 });
});
it("places northing labels in map space (y south) with the Arma y-flip", () => {
const set = gridLinesForBounds(DEFAULT_MAP_GRID, WORLD, FULL_WORLD, 8);
// Arma northing cell 0 centers 500 m above the south edge.
expect(set.northingLabels.find((l) => l.value === "00")?.at).toBe(WORLD - 500);
// Cell 7 centers at 7500 m Arma-north: map y = 8192 - 7500 = 692.
const seven = set.northingLabels.find((l) => l.value === "07");
expect(seven?.at).toBe(WORLD - 7500);
expect(seven?.at).toBe(692);
});
it("puts labels on the lines when numbersOverLines is set", () => {
const config = gridConfigFromMapDoc({ gridEnabled: true, gridNumbersOverLines: true });
const set = gridLinesForBounds(config, WORLD, FULL_WORLD, 8);
expect(set.eastingLabels.find((l) => l.at === 0)?.value).toBe("00");
expect(set.eastingLabels.find((l) => l.at === 1000)?.value).toBe("01");
expect(set.northingLabels.find((l) => l.at === WORLD)?.value).toBe("00");
// Every anchor is a line position, not a cell center.
expect(set.eastingLabels.every((l) => set.verticalLines.includes(l.at))).toBe(true);
expect(set.northingLabels.every((l) => set.horizontalLines.includes(l.at))).toBe(true);
});
it("extends lines and labels past the world edge, counting and wrapping", () => {
const set = gridLinesForBounds(DEFAULT_MAP_GRID, WORLD, FULL_WORLD, 8);
// Lines run past the east and south edges.
expect(set.verticalLines).toContain(9000);
expect(set.verticalLines).toContain(10000);
expect(set.horizontalLines).toContain(-808);
// Values keep counting past the east edge (cell 8 centered at 8500).
expect(set.eastingLabels.find((l) => l.at === 8500)?.value).toBe("08");
// Past the north edge (map y negative): northing cell 8 at y = -308.
expect(set.northingLabels.find((l) => l.at === -308)?.value).toBe("08");
// West of the zero line and south of the world the values wrap.
expect(set.eastingLabels.find((l) => l.at === -500)?.value).toBe("99");
expect(set.northingLabels.find((l) => l.at === WORLD + 500)?.value).toBe("99");
});
});
describe("gridConfigFromMapDoc", () => {
it("returns DEFAULT_MAP_GRID for null, undefined and empty docs", () => {
expect(gridConfigFromMapDoc(null)).toEqual(DEFAULT_MAP_GRID);
expect(gridConfigFromMapDoc(undefined)).toEqual(DEFAULT_MAP_GRID);
expect(gridConfigFromMapDoc({})).toEqual(DEFAULT_MAP_GRID);
});
it("tolerates null fields and falls back to defaults", () => {
const config = gridConfigFromMapDoc({
gridEnabled: null,
gridOriginEasting: null,
gridOriginNorthing: null,
gridStartEasting: null,
gridStartNorthing: null,
gridSpacingMeters: null,
gridLabelDigits: null,
gridNumbersOverLines: null,
});
expect(config).toEqual(DEFAULT_MAP_GRID);
});
it("falls back to 1000 m when gridSpacingMeters is 0 or missing", () => {
expect(gridConfigFromMapDoc({ gridSpacingMeters: 0 }).spacingMeters).toBe(1000);
expect(gridConfigFromMapDoc({}).spacingMeters).toBe(1000);
});
it("clamps gridLabelDigits to [1, 6]", () => {
expect(gridConfigFromMapDoc({ gridLabelDigits: 0 }).labelDigits).toBe(1);
expect(gridConfigFromMapDoc({ gridLabelDigits: -4 }).labelDigits).toBe(1);
expect(gridConfigFromMapDoc({ gridLabelDigits: 9 }).labelDigits).toBe(6);
expect(gridConfigFromMapDoc({ gridLabelDigits: 3 }).labelDigits).toBe(3);
});
it("truncates fractional starting numbers", () => {
expect(gridConfigFromMapDoc({ gridStartEasting: 3.9 }).startEasting).toBe(3);
expect(gridConfigFromMapDoc({ gridStartNorthing: -2.7 }).startNorthing).toBe(-2);
});
it("reads the boolean flags strictly", () => {
expect(gridConfigFromMapDoc({ gridEnabled: true }).enabled).toBe(true);
expect(gridConfigFromMapDoc({ gridEnabled: 1 }).enabled).toBe(false);
expect(gridConfigFromMapDoc({ gridNumbersOverLines: true }).numbersOverLines).toBe(true);
expect(gridConfigFromMapDoc({ gridNumbersOverLines: "yes" }).numbersOverLines).toBe(false);
});
});