1
0
Fork 0

Compare commits

...

13 commits

Author SHA1 Message Date
2f81cc9ede v0.13.1 - add extraction review, vehicle cargo blacklist, brass ribbon devices 2026-10-27 02:16:03 -04:00
80f71dc917 fix(map-objectives): read Playwright request failure via errorText 2026-10-27 02:13:44 -04:00
3bef63af33 feat(map-objectives): superuser-authored strategic objectives on mission maps
Add a superuser-authored objective layer (defend, assault, secure, etc.)
shown as labelled map markers on both the world map and mission planning
map, with per-layer toggles on the planning map.

- collection: MapObjectives (map_objectives table, enums, FKs)
- lib: objectives service + objectiveTypes + permissions + event emit
- actions/api: create/update/delete objectives server actions
- UI: feature-layer toggles, objective picker dialog, world/plan markers,
  SQF export, dossier dialog integration
- generated: regenerate payload schema + types for map_objectives
- tests: 10 integration specs + e2e spec
- docs: CHANGELOG, map-system, AGENTS guides
2026-10-27 02:12:31 -04:00
245e70f3f2 feat(awards): brass-emboss ribbon devices, swap arrow for valor V 2026-10-27 01:47:10 -04:00
7430251adf feat(awards): render ribbon devices as vectors with tier-driven auto-layout
Introduce RibbonArt, a single shared SVG renderer used by both the production viewer and admin/studio preview so they can no longer diverge. Devices are now vector glyphs (star/oak leaf/campaign clasp/arrow up) instead of Unicode text, laid out as one centered cluster that shrinks to fit. Device count derives from advancement tier using the service-star convention (tier N shows N-1, cap 6; bare ribbon at tier 1 or for non-tiered awards). Legacy per-device x/y positions are stored but ignored, so no schema change. Designers add/remove/reorder device types and preview tiers.
2026-10-26 22:21:10 -04:00
f32afc6421 feat(logistics): restyle vehicle catalog cards in tactical dossier style
VehicleCard gains classification strip, corner brackets, squared corners, darkened cover imagery, faint grid texture and a permanent readout footer (matching CampaignCard). Fixes pre-existing defects: description rendered twice, category colors disagreed with the detail page, and stat accessors read nonexistent nested fields hidden by an 'as any' cast (now typed against Vehicle). Category color/label maps unified into src/lib/vehicles/categories.ts shared by card and detail pages.
2026-10-26 22:20:54 -04:00
acf47a75ea feat(operations): gate logistics extractions behind an officer review screen
Logistics operation-extraction effects now park as pending_action instead of auto-settling. Officers visit Operations > Extractions to keep, scrap, or expel each line; only kept lines deposit into HQ. A capacity failure leaves the effect retryable (pending_action) so a full HQ can free space and re-resolve. Adds resolveLogisticsExtraction/listPendingExtractions actions + ExtractionReview UI + tests.
2026-10-26 22:20:14 -04:00
40b074a693 feat(vehicles): add per-vehicle disallowed-cargo blacklist enforced at shipment
Vehicles gain a virtual-block disallowedCargo array (asset/vehicle/resource item + optional amount cap, 0 forbids outright). createShipment consults findDisallowedCargo() before deducting any origin stock and rejects matching cargo lines cleanly. Includes Payload migration + 7 integration tests.
2026-10-26 22:17:21 -04:00
02ef9f4954 feat(bot): add staff-only /debug command for previewing and reposting bot messages 2026-10-26 18:07:05 -04:00
6263730d9c refactor(bot): export render and send helpers for debug reuse 2026-10-26 18:07:05 -04:00
282b313cd5 fix(modlists): send modlist files as downloads instead of inline views 2026-10-26 18:07:05 -04:00
134c403b38 chore: regenerate db-schema (syncs payload-generated-schema.ts to current DB) 2026-10-26 03:39:40 -04:00
1fdb6bf872 feat(vehicles): add 'static' and 'drone' vehicle categories 2026-10-26 03:39:38 -04:00
94 changed files with 142257 additions and 591 deletions

View file

@ -1,5 +1,25 @@
# Changelog
# v0.13.1
Officers now review logistics extractions before they reach HQ, vehicle cards show their stats, and ribbon devices are brass-embossed with a Valor "V" in place of the arrow.
### Features
- **Extraction review.** Logistics extractions wait for an officer decision on a new Extractions page. Each line can be kept, scrapped, or expelled before anything reaches HQ storage. If HQ is full, the extraction stays pending so the officer can drop a line and retry.
- **Vehicle cargo blacklist.** Each vehicle can list items it may not carry on virtual shipments. A matching shipment is rejected before any stock is deducted.
- **Ribbon devices.** Devices are brass-embossed vectors and centered automatically. The number shown follows the award's advancement tier. The arrow is replaced by the Valor "V" device.
- **Vehicle catalog.** Vehicle cards use the dossier style, with a registry strip, category pills, and a readout footer.
- **Vehicle categories.** Added "static" and "drone" categories.
### Fixes
- **Vehicles.** Card stats (integrity, road speed, materials, build time) now show; they were always empty before. Category colors and labels now match between the card grid and the detail page.
- **Modlist downloads.** Modlist files download instead of opening inline.
- **Ribbon remove buttons.** The remove buttons now show a multiplication sign instead of a raw escape code.
---
# v0.13.0
Leadership ratings now follow the unit's rank structure instead of squad assignments.

View file

@ -286,7 +286,35 @@ Those markers belong to the one mission and never appear on `/map`.
`worldSizeWidth`/`worldSizeHeight` must match the terrain's real size for
exported markers to land in the right place in-game.
- The base layers come from `GET /api/map-features?mapId=<id>&layers=base`,
which skips the structure, node and shipment queries.
which skips the structure, node and shipment queries until a reference layer
is switched on in the Layers popover (structures are on by default, so the
full feed normally loads).
- Objectives (below) are always included in the feed, independent of
`layers=base`.
- Icons, colors and brushes come from the game config via
`bun run markers:arma`. See the "Mission Planning Map" section in AGENTS.md
for the full wiring.
## Strategic objectives
`map-objectives` holds Arma-style command markers that belong to a terrain map
and are shared by every mission planned on it, so the command picture stays
consistent between the world map and mission planning maps.
- Fields: `map` (required), `name` (the designation shown under the marker,
e.g. `OBJ ALPHA`), `description`, `markerType` (CfgMarkers class, default
`mil_objective`), `status` (`active` / `secured` / `failed`), `redacted`,
`position` ([x, y] meters), `createdBy`.
- Status drives the colour: `active` = `ColorRed`, `secured` = `ColorGreen`,
`failed` = `ColorGrey`. There is no free colour picker on purpose.
- Writes require the superuser tier (`system:admin-access`). Every logged-in
user reads objectives, but `redacted` rows are stripped for anyone without
the tier; superusers see them dimmed with a `REDACTED` tag so they can stage
an objective before revealing it.
- Creation, status flips, reveals and deletes emit `map:objective-*` events
targeting `map-objectives`.
- Authoring is available on both surfaces: `/map/[id]` ("Add objective" in Map
Control) and a mission's planning map (Layers popover, superusers only).
Deleting a map removes its objectives through the Maps `beforeDelete` hook,
because the relationship is NOT NULL.

View file

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

@ -52,6 +52,7 @@ import {
listMissionMarkers,
planningMapDelegateIds,
} from "@/lib/intelligence/missionMap";
import { listMapObjectives } from "@/lib/map/objectives";
interface MissionDetailPageProps {
params: Promise<{ id: string }>;
@ -280,9 +281,16 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro
const canCuratePlan = canControlSideOp && !planLocked;
const canDelegate = canManage && !planLocked;
const canEditPlan = (canControlSideOp || isPlanDelegate) && !planLocked;
const canManageObjectives = currentUser
? await hasPermission(payload, currentUser, "system:admin-access")
: false;
const planningMapEnabled = mission.classification.planningMapEnabled === true;
const planMarkers =
map && planningMapEnabled ? await listMissionMarkers(payload, mission.id) : [];
const planObjectives =
map && (planningMapEnabled || canEditPlan)
? await listMapObjectives(payload, map.id, { includeRedacted: canManageObjectives })
: [];
const showPlanningMap = map !== null && (planningMapEnabled || canEditPlan);
let planningUsers: PlanningUserOption[] = [];
@ -470,6 +478,7 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro
enabled={planningMapEnabled}
canEdit={canEditPlan}
canCurate={canCuratePlan}
canManageObjectives={canManageObjectives}
locked={planLocked}
map={{
id: map.id,
@ -478,6 +487,7 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro
worldHeight: Number(map.worldSizeHeight ?? 8192),
}}
initialMarkers={planMarkers}
initialObjectives={planObjectives}
/>
)}
{/* Attendance sits right under the hero on stacked (below-xl) layouts */}

View file

@ -8,6 +8,7 @@ import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
import { calculateDistance } from "@/lib/distance";
import { calculateFuelCost, calculateTransitTime, getVehicleEffectiveSpeed } from "@/lib/shipping";
import { findDisallowedCargo } from "@/lib/shipping/cargo";
import { checkStorageDeposit, storageViolationMessage } from "@/lib/storageRules";
import { effectiveMaxMass } from "@/lib/base/modules";
import { buildRoadGraph, findRoute } from "@/lib/map/routing";
@ -213,6 +214,18 @@ export async function createShipment(params: {
};
}
// Reject cargo the vehicle template is not permitted to carry. Checked
// before any origin stock is deducted so a blacklisted manifest never
// mutates state. `disallowedCargo` lives on the Vehicle template; amount 0
// forbids an item entirely, a positive amount caps it.
const disallowed = findDisallowedCargo(vehicleType.disallowedCargo, cargo);
if (disallowed) {
return {
success: false,
error: `Vehicle "${vehicleType.name}" may not carry ${disallowed.relationTo} #${disallowed.itemId}${disallowed.cap > 0 ? ` (over its ${disallowed.cap} cap)` : ""}.`,
};
}
// Validate cargo exists at origin
const storedResources = origin.storedResources ?? [];
for (const cargoItem of cargo) {

View file

@ -5,7 +5,15 @@ import type { Vehicle } from "@/payload-types";
import { VehicleCard } from "@/components/frontend/logistics/VehicleCard";
import { VehicleFilters } from "@/components/frontend/logistics/VehicleFilters";
const categories = ["civilian", "utility", "transport", "weaponized", "military"];
const categories = [
"civilian",
"utility",
"transport",
"drone",
"weaponized",
"static",
"military",
];
export function VehiclesList({ vehicles }: { vehicles: Vehicle[] }) {
const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
@ -21,9 +29,9 @@ export function VehiclesList({ vehicles }: { vehicles: Vehicle[] }) {
<>
<VehicleFilters categories={categories} onFilterChange={setSelectedCategory} />
{filtered.length > 0 ? (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{filtered.map((vehicle) => (
<VehicleCard key={vehicle.id} vehicle={vehicle as any} />
<VehicleCard key={vehicle.id} vehicle={vehicle} />
))}
</div>
) : (

View file

@ -5,6 +5,7 @@ import Link from "next/link";
import type { Resource, Structure, Technology } from "@/payload-types";
import { RichText } from "@payloadcms/richtext-lexical/react";
import { convertLexicalToPlaintext } from "@payloadcms/richtext-lexical/plaintext";
import { categoryLabel, categoryPillClasses } from "@/lib/vehicles/categories";
import {
ArrowLeftIcon,
BoxIcon,
@ -29,14 +30,6 @@ interface VehicleDetailPageProps {
params: Promise<{ id: string }>;
}
const categoryColors: Record<string, string> = {
civilian: "bg-muted text-muted-foreground",
utility: "bg-blue-500/20 text-blue-400",
transport: "bg-green-500/20 text-green-400",
weaponized: "bg-red-500/20 text-red-400",
military: "bg-amber-500/20 text-amber-400",
};
const armorColors: Record<string, string> = {
none: "bg-muted text-muted-foreground",
light: "bg-green-500/20 text-green-400",
@ -104,9 +97,9 @@ export default async function VehicleDetailPage({ params }: VehicleDetailPagePro
{(vehicle.category ?? []).map((cat) => (
<span
key={cat}
className={`text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded ${categoryColors[cat] ?? "bg-muted text-muted-foreground"}`}
className={`text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded ${categoryPillClasses(cat)}`}
>
{cat}
{categoryLabel(cat)}
</span>
))}
</div>

View file

@ -31,17 +31,19 @@ export default async function MapViewPage({ params }: MapViewPageProps) {
if (!map) notFound();
const [canPlace, canAuthorRoads, canAuthorZones, canAuthorNodes] = await Promise.all([
user
? Promise.all([
hasPermission(payload, user, "maps:place"),
hasLogisticsQualification(payload, user),
]).then(([place, logistics]) => place && logistics)
: Promise.resolve(false),
user ? hasPermission(payload, user, "map-roads:author") : Promise.resolve(false),
user ? hasPermission(payload, user, "map-zones:author") : Promise.resolve(false),
user ? hasPermission(payload, user, "resource-nodes:author") : Promise.resolve(false),
]);
const [canPlace, canAuthorRoads, canAuthorZones, canAuthorNodes, canManageObjectives] =
await Promise.all([
user
? Promise.all([
hasPermission(payload, user, "maps:place"),
hasLogisticsQualification(payload, user),
]).then(([place, logistics]) => place && logistics)
: Promise.resolve(false),
user ? hasPermission(payload, user, "map-roads:author") : Promise.resolve(false),
user ? hasPermission(payload, user, "map-zones:author") : Promise.resolve(false),
user ? hasPermission(payload, user, "resource-nodes:author") : Promise.resolve(false),
user ? hasPermission(payload, user, "system:admin-access") : Promise.resolve(false),
]);
// Inactive maps stay reachable for editors previewing them, but are hidden
// from everyone else.
@ -67,6 +69,7 @@ export default async function MapViewPage({ params }: MapViewPageProps) {
map={{ id: map.id, name: map.name }}
canAuthor={{ roads: canAuthorRoads, zones: canAuthorZones, nodes: canAuthorNodes }}
canPlace={canPlace}
canManageObjectives={canManageObjectives}
/>
</div>
);

View file

@ -0,0 +1,146 @@
"use server";
import config from "@payload-config";
import { getPayload } from "payload";
import { hasPermission } from "@/utils/access-control/hasPermission";
import {
createMapObjective,
deleteMapObjective,
listMapObjectives,
objectiveFromDoc,
updateMapObjective,
type MapObjectiveDoc,
} from "@/lib/map/objectives";
import type { MapObjectiveStatus } from "@/lib/map/objectiveTypes";
import type { MapObjectiveFeature } from "@/lib/map/types";
export interface ActionResult<T = undefined> {
success: boolean;
error?: string;
data?: T;
}
async function authenticate() {
const payloadConfig = await config;
const payload = await getPayload({ config: payloadConfig });
const { headers } = await import("next/headers");
const hdrs = await headers();
const { user } = await payload.auth({ headers: hdrs, canSetHeaders: false });
if (!user) {
throw new Error("Unauthorized");
}
return { payload, user };
}
/** Objectives are managed by the superuser tier only (admin + superuser roles). */
async function authorizedActor() {
const { payload, user } = await authenticate();
if (!(await hasPermission(payload, user, "system:admin-access"))) {
throw new Error("Only superusers can manage strategic objectives.");
}
return { payload, user };
}
function failure(error: unknown): { success: false; error: string } {
const message = error instanceof Error ? error.message : "Unknown error";
return message === "Unauthorized"
? { success: false, error: "You must be logged in." }
: { success: false, error: message };
}
/** Create (no id, needs mapId) or update (id) one objective. */
export async function saveMapObjective(input: {
mapId?: number;
id?: number | null;
objective: unknown;
}): Promise<ActionResult<MapObjectiveFeature>> {
try {
const { payload, user } = await authorizedActor();
if (input.id) {
const objective = await updateMapObjective(payload, input.id, input.objective);
return { success: true, data: objective };
}
if (!input.mapId) return { success: false, error: "Map is required." };
const objective = await createMapObjective(
payload,
input.mapId,
input.objective,
Number(user.id),
);
return { success: true, data: objective };
} catch (error) {
return failure(error);
}
}
/** Status flips from the map popup (active / secured / failed). */
export async function setMapObjectiveStatus(input: {
id: number;
status: MapObjectiveStatus;
}): Promise<ActionResult<MapObjectiveFeature>> {
try {
const { payload } = await authorizedActor();
const existing = await payload
.findByID({ collection: "map-objectives", id: input.id, depth: 0, overrideAccess: true })
.catch(() => null);
const current = existing ? objectiveFromDoc(existing as unknown as MapObjectiveDoc) : null;
if (!current) return { success: false, error: "Objective not found." };
const objective = await updateMapObjective(payload, input.id, {
...current,
status: input.status,
});
return { success: true, data: objective };
} catch (error) {
return failure(error);
}
}
/** Reveal or hide an objective from players. */
export async function setMapObjectiveRedacted(input: {
id: number;
redacted: boolean;
}): Promise<ActionResult<MapObjectiveFeature>> {
try {
const { payload } = await authorizedActor();
const existing = await payload
.findByID({ collection: "map-objectives", id: input.id, depth: 0, overrideAccess: true })
.catch(() => null);
const current = existing ? objectiveFromDoc(existing as unknown as MapObjectiveDoc) : null;
if (!current) return { success: false, error: "Objective not found." };
const objective = await updateMapObjective(payload, input.id, {
...current,
redacted: Boolean(input.redacted),
});
return { success: true, data: objective };
} catch (error) {
return failure(error);
}
}
export async function removeMapObjective(input: { id: number }): Promise<ActionResult> {
try {
const { payload } = await authorizedActor();
await deleteMapObjective(payload, input.id);
return { success: true };
} catch (error) {
return failure(error);
}
}
/** Read path for the planning map's background refresh (any mission viewer). */
export async function getMapObjectives(input: {
mapId: number;
}): Promise<ActionResult<MapObjectiveFeature[]>> {
try {
const { payload, user } = await authenticate();
const includeRedacted = await hasPermission(payload, user, "system:admin-access");
return {
success: true,
data: await listMapObjectives(payload, input.mapId, { includeRedacted }),
};
} catch (error) {
return failure(error);
}
}

View file

@ -4,8 +4,13 @@ import config from "@payload-config";
import { getPayload } from "payload";
import { headers as nextHeaders } from "next/headers";
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
import { hasPermission } from "@/utils/access-control/hasPermission";
import { replayOperationEvent } from "@/lib/operations/reconcile";
import { backfillOperationEvents } from "@/lib/operations/rollout";
import { listPendingExtractions } from "@/lib/operations/surfaceQuery";
import { resolveLogisticsExtraction } from "@/lib/operations/settlementExtraction";
import type { ExtractionDecisions } from "@/lib/operations/settlementTypes";
import type { PendingExtraction } from "@/lib/operations/surfaceQuery";
export interface ActionResult<T> {
success: boolean;
@ -46,3 +51,47 @@ export async function reconcileBackfill(): Promise<ActionResult<{ processed: num
return { success: false, error: e instanceof Error ? e.message : "Unknown error" };
}
}
/**
* Pending-extraction review queue: logistics extractions parked as
* `pending_action` awaiting an officer's keep / scrap / expel decision before
* they deposit at HQ. Read is access-controlled (any logged-in user sees what
* they may read); the queue is officer-facing in practice.
*/
export async function getPendingExtractions(): Promise<ActionResult<{ extractions: PendingExtraction[]; total: number }>> {
try {
const { payload, user } = await authenticate();
if (!user) return { success: false, error: "Authentication required." };
const result = await listPendingExtractions(payload, { id: user.id });
return { success: true, data: result };
} catch (e) {
return { success: false, error: e instanceof Error ? e.message : "Unknown error" };
}
}
/**
* Officer resolution of a gated logistics extraction. `decisions` is a
* per-line [{ relationTo, id, decision }] array (decision: keep | scrap |
* expel); pass `null` to keep every line. Kept lines deposit at HQ; scrap/expel
* lines are held back. A capacity failure leaves the effect parked for a retry.
*/
export async function resolveExtraction(
effectId: number,
decisions: ExtractionDecisions | null,
): Promise<ActionResult<{ status?: string; kept?: number; heldBack?: number }>> {
try {
const { payload, user } = await authenticate();
if (!user) return { success: false, error: "Authentication required." };
if (!(await hasPermission(payload, user, "operation-readiness:read"))) {
return { success: false, error: "Insufficient permissions." };
}
const result = await resolveLogisticsExtraction(payload, effectId, decisions);
if (!result.success) return { success: false, error: result.error ?? "Resolution failed." };
return {
success: true,
data: { status: "applied" },
};
} catch (e) {
return { success: false, error: e instanceof Error ? e.message : "Unknown error" };
}
}

View file

@ -0,0 +1,56 @@
import config from "@payload-config";
import { getPayload } from "payload";
import { headers as nextHeaders } from "next/headers";
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
import { getPendingExtractions } from "@/app/(frontend)/operations/actions";
import { ExtractionReview, PageShell, OperationsRealtimeRefresher } from "@/components/frontend/operations";
import type { PendingExtraction } from "@/lib/operations/surfaceQuery";
export const metadata = {
title: "Pending Extractions // Operations Review",
};
export default async function PendingExtractionsPage() {
const payload = await getPayload({ config });
const { user: authUser } = await payload.auth({
headers: await nextHeaders(),
canSetHeaders: false,
});
const user = isPayloadUser(authUser) ? authUser : null;
// Fetch inside a try so a transient failure shows a clean state, not a crash.
let extractions: PendingExtraction[] = [];
let error: string | null = null;
if (user) {
const res = await getPendingExtractions();
if (res.success) extractions = res.data?.extractions ?? [];
else error = res.error ?? "Failed to load pending extractions.";
} else {
error = "Sign in to review pending extractions.";
}
return (
<div className="mx-auto flex w-full max-w-[96rem] flex-col gap-6 px-4 py-6">
<OperationsRealtimeRefresher />
<PageShell
title="Pending extractions"
meta="EXTRACTION RETURNS // REVIEW & DEPOSIT"
dataTour="page-header-extractions"
>
<p className="max-w-2xl text-sm text-white/70">
Logistics extractions are parked here until an officer reviews them. Choose to deposit
each line at HQ or hold it back. Kept lines deposit on resolve; capacity is re-checked
then, so drop lines to fit a full HQ and retry.
</p>
</PageShell>
{error ? (
<div role="alert" className="rounded-lg border border-rose-500/30 bg-rose-500/10 px-4 py-3 text-sm text-rose-300">
{error}
</div>
) : null}
<ExtractionReview extractions={extractions} />
</div>
);
}

View file

@ -3976,6 +3976,37 @@
outline-offset: 3px;
}
/* Strategic objectives: persistent designation plate under the Arma glyph. */
.leaflet-container .objective-marker-label {
background: transparent;
border: none;
box-shadow: none;
padding: 0;
}
.leaflet-container .objective-marker-label::before {
display: none;
}
.objective-marker-name {
display: block;
width: max-content;
max-width: 220px;
transform: translateX(-50%);
padding: 1px 4px;
background: rgb(0 0 0 / 45%);
border: 1px solid rgb(255 255 255 / 20%);
font-family: var(--font-mono, ui-monospace, monospace);
font-size: 9px;
font-weight: 600;
letter-spacing: 0.12em;
line-height: 1.4;
text-transform: uppercase;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.leaflet-container .mission-map-handle {
background: transparent;
border: none;

View file

@ -11,6 +11,8 @@ import {
import { isPointArray, type MapPoint } from "@/lib/map/points";
import { gridConfigFromMapDoc } from "@/lib/map/grid";
import type { MapFeaturesResponse, StructureFeature } from "@/lib/map/types";
import { listMapObjectives } from "@/lib/map/objectives";
import { hasPermission } from "@/utils/access-control/hasPermission";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
@ -71,56 +73,61 @@ export async function GET(req: NextRequest) {
const worldH = Number(mapDoc.worldSizeHeight ?? 8192);
// layers=base: basemap + roads + zones only (mission planning maps). Skips
// the logistics queries (structures/nodes/shipments) entirely.
// the logistics queries (structures/nodes/shipments) entirely. Objectives are
// cheap and belong to every surface, so they are always included.
const baseOnly = req.nextUrl.searchParams.get("layers") === "base";
const includeRedacted = await hasPermission(payload, user, "system:admin-access");
const none = { docs: [] as never[] };
const [structuresRes, nodesRes, roadsRes, zonesRes, shipmentsRes] = await Promise.all([
baseOnly
? none
: payload.find({
collection: "game-structures",
where: { map: { equals: mapId } },
depth: 2,
limit: 1000,
overrideAccess: true,
}),
baseOnly
? none
: payload.find({
collection: "resource-nodes",
where: { map: { equals: mapId } },
depth: 1,
limit: 5000,
overrideAccess: true,
}),
payload.find({
collection: "map-roads",
where: { map: { equals: mapId } },
depth: 0,
limit: 5000,
overrideAccess: true,
}),
payload.find({
collection: "map-zones",
where: { map: { equals: mapId } },
depth: 1,
limit: 5000,
overrideAccess: true,
}),
baseOnly
? none
: payload.find({
collection: "shipments",
where: {
and: [{ map: { equals: mapId } }, { status: { in: ["dispatched", "in_transit"] } }],
},
depth: 2,
limit: 200,
sort: "-dispatchedAt",
overrideAccess: true,
}),
]);
const [structuresRes, nodesRes, roadsRes, zonesRes, shipmentsRes, objectives] = await Promise.all(
[
baseOnly
? none
: payload.find({
collection: "game-structures",
where: { map: { equals: mapId } },
depth: 2,
limit: 1000,
overrideAccess: true,
}),
baseOnly
? none
: payload.find({
collection: "resource-nodes",
where: { map: { equals: mapId } },
depth: 1,
limit: 5000,
overrideAccess: true,
}),
payload.find({
collection: "map-roads",
where: { map: { equals: mapId } },
depth: 0,
limit: 5000,
overrideAccess: true,
}),
payload.find({
collection: "map-zones",
where: { map: { equals: mapId } },
depth: 1,
limit: 5000,
overrideAccess: true,
}),
baseOnly
? none
: payload.find({
collection: "shipments",
where: {
and: [{ map: { equals: mapId } }, { status: { in: ["dispatched", "in_transit"] } }],
},
depth: 2,
limit: 200,
sort: "-dispatchedAt",
overrideAccess: true,
}),
listMapObjectives(payload, mapId, { includeRedacted }),
],
);
const structures: StructureFeature[] = [];
for (const doc of structuresRes.docs) {
@ -296,6 +303,7 @@ export async function GET(req: NextRequest) {
roads,
zones,
shipments,
objectives,
};
return NextResponse.json(response);

View file

@ -8,7 +8,7 @@ Standalone long-running process (`bun run bot`). Imports `@payload-config` direc
## Env
Required: `DISCORD_TOKEN`, `DISCORD_GUILD_ID` (fail-fast on missing vars in `config.ts`). Optional: `DISCORD_OPS_CHANNEL_ID`, `DISCORD_ANNOUNCE_CHANNEL_ID`, `DISCORD_CHANGELOG_CHANNEL_ID` (dedicated #releases channel for `/changelog`; falls back to the announce channel), `DISCORD_STAFF_ROLE_IDS`, `DISCORD_SIDE_OPS_CHANNEL_ID` (Friday open-slot notice channel), `DISCORD_COMMUNITY_ZEUS_ROLE_ID` (role ping for that notice), `DISCORD_NPC_EVENT_CHANNEL_ID` (NPC dispatch channel for dialogue events; unset disables posting), `APP_URL`, plus poll intervals `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_POLL_MS` (default 30 min), `DISCORD_PRESENCE_POLL_MS` (default 30s), `DISCORD_NPC_EVENT_POLL_MS` (default 60s). Logs through `payload.logger`.
Required: `DISCORD_TOKEN`, `DISCORD_GUILD_ID` (fail-fast on missing vars in `config.ts`). Optional: `DISCORD_OPS_CHANNEL_ID`, `DISCORD_ANNOUNCE_CHANNEL_ID`, `DISCORD_CHANGELOG_CHANNEL_ID` (dedicated #releases channel for `/changelog`; falls back to the announce channel), `DISCORD_STAFF_ROLE_IDS`, `DISCORD_SIDE_OPS_CHANNEL_ID` (Friday open-slot notice channel), `DISCORD_COMMUNITY_ZEUS_ROLE_ID` (role ping for that notice), `DISCORD_NPC_EVENT_CHANNEL_ID` (NPC dispatch channel for dialogue events; unset disables posting), `DISCORD_DEBUG_CHANNEL_ID` (sandbox channel for `/debug run ... mode:sandbox`; unset disables sandbox), `APP_URL`, plus poll intervals `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_POLL_MS` (default 30 min), `DISCORD_PRESENCE_POLL_MS` (default 30s), `DISCORD_NPC_EVENT_POLL_MS` (default 60s). Logs through `payload.logger`.
## Structure
@ -27,6 +27,7 @@ bot/
remindEvaluations.ts # /remind-evaluations (guild-only, staff only, manual evaluation-reminder trigger)
rollcall.ts # /rollcall (guild-only, staff only, force-send/refresh a roll-call)
discordPresence.ts # /discord-presence (guild-only, discord:rp:update; view/edit/clear the bot's Rich Presence via a prefilled modal)
debug.ts # /debug (guild-only, staff only; list | run preview|sandbox|live | inspect | delete, see "Feature flow: debug")
events/
interactionCreate.ts # Routes ptf-att: RSVP button interactions
@ -46,6 +47,7 @@ bot/
discordPresence.ts # Poll the discord-presence Global → reconcile the bot's live Rich Presence (in-memory last-applied diff)
lib/
debugActions.ts # /debug action registry: each action builds the production message and sends it live
roles.ts # isStaff check
resolve.ts # discordId ↔ Payload user lookups
transferMessaging.ts # Transfer embed builders + delivery keys
@ -65,6 +67,19 @@ bot/
`/changelog` (guild-only, staff only) posts a `CHANGELOG.md` release entry to the releases channel (`DISCORD_CHANGELOG_CHANNEL_ID`, falling back to `DISCORD_ANNOUNCE_CHANNEL_ID`). `/changelog` targets the newest entry; `/changelog v0.4.0` targets a specific version (for catching up on missed posts); `/changelog v0.3.0..v0.5.0` targets a range (inclusive slice, output oldest-to-newest). Either range end is open (`v0.3.0..` to the latest, `..v0.5.0` from the oldest) and a reversed range is normalized. **Edit mode** (`edit=true`): instead of posting, opens a modal prefilled with the target entry's raw markdown so staff can make last-minute copy tweaks right in Discord; submit renders the edited text through the same pipeline and posts it. One-shot by design: the edit shapes only the post about to happen, `CHANGELOG.md` (baked into the deployed image) is never written back. Single-version targets only (ranges are rejected ephemerally), entries over the 4000-char modal input cap refuse edit mode with a pointer to the file. The modal must be the first response, so the edit path checks staff and shows the modal WITHOUT deferring (same pattern as `/announce`); submits route through `bot/index.ts` on the `ptf-changelog-edit:` custom-id prefix and re-check staff. Rendering lives in `bot/lib/changelogRender.ts` (pure, no Discord/Payload deps): entries are split on `# vX.Y.Z` headers, `### ` sections become Discord markdown headings (`### `, the deepest level Discord renders), bullets become `•`, and entries over Discord's 4096-char limit are split across messages at section boundaries. The command reads `CHANGELOG.md` from the repo root relative to the file (works from the deploy server) and posts each version as its own amber embed, the first message of each version carrying the `Changelog vX.Y.Z` title and multi-message versions adding a page footer. Ranges spanning more than `WIDE_RANGE_THRESHOLD` (10) versions post an ephemeral warning but proceed. Idempotency ("don't repost") is intentionally out of scope for the manual command; the same rendering can be reused by a future automatic trigger.
## Feature flow: debug
`/debug` (guild-only, `isStaff`) re-renders or re-sends bot messages through the production render and send code, so a test exercises what actually ships. Subcommands: `list`, `run action target mode`, `inspect action target`, `delete action target`.
- **preview** (default): ephemeral. Shows the exact embed, with buttons stripped. Writes nothing.
- **sandbox**: posts to `DISCORD_DEBUG_CHANNEL_ID` with mentions suppressed. Writes nothing. Refused with a message when that env var is unset.
- **live**: posts to the real channel after a Confirm button (30s timeout). Supported by `rollcall` (`method=edit` edits the stored message in place, `method=repost` posts fresh and links it), `modlist`, `npc-dispatch`, `achievement`, and `changelog` (posts to the releases channel). Live posts do not change one-shot markers or hashes except through the rollcall path.
- **delete**: removes the tracked message after Confirm and clears its stored id. Keeps the one-shot markers, so a deleted message is not reposted automatically.
Preview-only actions (no live send): `imminent` (live thread pings would reach attendees), `ready-reminders`, `friday-notice` (a live post would create a real dedup token), `evaluations` (shows the first recipient's DM with a recipient count), `notification`, and `transfer`. Preview omits buttons, so debug output never exposes a live decision control.
Actions live in `bot/lib/debugActions.ts`. Each `build` receives the client and returns the message the production path sends. The render helpers they reuse are exported from `services/missionEmbeds.ts`, `services/npcEventAnnouncements.ts`, `services/imminentReminders.ts`, `services/readyReminders.ts`, `services/evaluationReminders.ts`, `services/notificationBridge.ts`, `services/fridayOpsNotice.ts`, `services/transferDelivery.ts`, and `commands/changelog.ts`.
## Feature flow: attendance
Bot posts RSVP embeds (Yes/Tentative/No) for future, Scheduled, visibility:"unit" missions into ops channel. Stores `discordMessageId` + `discordAttendanceHash` on mission. Reconciles hash changes every poll tick (web ↔ Discord two-way sync, loop-safe). The embed title links to the mission page, a mission summary sits under the title (truncated to 300 characters with an ellipsis), and an "Open the op" field carries the URL; `attendanceHash` includes an embed schema version so layout-only changes re-render live roll-calls once (idempotent). Web UI: `MissionAttendance` component. Weekly main missions are cloned by `bun run payload generate-mission` (a payload bin, see `src/scripts/AGENTS.md`). Staff can force one outside the lead-time window with `/rollcall [mission]` (ID, name, or code name; omit to target the next upcoming Scheduled unit op): `forceRollCall` in `missionEmbeds.ts` re-renders the live message or posts a fresh one (even after a manual deletion), bypassing only the 3-day gate; target lookup/validation lives in `src/lib/intelligence/rollCall.ts`.

View file

@ -30,7 +30,7 @@ import {
// CHANGELOG.md sits at the repo root; resolve it relative to this file so the
// path is correct regardless of the process working directory.
const CHANGELOG_PATH = path.resolve(
export const CHANGELOG_PATH = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
"../../../CHANGELOG.md",
);
@ -80,21 +80,27 @@ const resolveChannel = async (guild: Guild): Promise<TextBasedChannelFields | nu
* Post one version's messages as amber embeds. The first carries the version
* title; multi-message versions add a page footer so order stays clear.
*/
const postVersion = async (
export const renderVersionEmbeds = (version: string, messages: string[]): EmbedBuilder[] => {
const total = messages.length;
return messages.map((message, i) => {
const embed = new EmbedBuilder()
.setTitle(`Changelog v${version}`)
.setColor(ANNOUNCE_COLOR)
.setDescription(message);
if (total > 1) {
embed.setFooter({ text: `Page ${i + 1}/${total}` });
}
return embed;
});
};
export const postVersion = async (
channel: TextBasedChannelFields,
version: string,
messages: string[],
): Promise<number> => {
const total = messages.length;
let posted = 0;
for (let i = 0; i < messages.length; i += 1) {
const embed = new EmbedBuilder()
.setTitle(`Changelog v${version}`)
.setColor(ANNOUNCE_COLOR)
.setDescription(messages[i]);
if (total > 1) {
embed.setFooter({ text: `Page ${i + 1}/${total}` });
}
for (const embed of renderVersionEmbeds(version, messages)) {
await channel.send({ embeds: [embed] });
posted += 1;
}

316
src/bot/commands/debug.ts Normal file
View file

@ -0,0 +1,316 @@
import {
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
ComponentType,
MessageFlags,
SlashCommandBuilder,
type ChatInputCommandInteraction,
type Client,
} from "discord.js";
import type { Payload } from "payload";
import type { BotCommand } from "./index";
import { botConfig } from "@/bot/config";
import { isStaff } from "@/bot/lib/roles";
import {
debugActions,
findDebugAction,
type DebugAction,
type DebugMode,
type OutboundMessage,
} from "@/bot/lib/debugActions";
const CONFIRM_TIMEOUT_MS = 30_000;
const actionChoices = debugActions.map((action) => ({ name: action.name, value: action.name }));
const formatError = (error: unknown): string =>
error instanceof Error ? error.message : "Unknown error";
const stripComponents = (message: OutboundMessage): OutboundMessage => ({
content: message.content,
embeds: message.embeds,
files: message.files,
});
/**
* Asks for a button press before a live change. Returns true only when the
* caller clicks Confirm within the timeout; anything else cancels.
*/
const confirmLive = async (
interaction: ChatInputCommandInteraction,
prompt: string,
): Promise<boolean> => {
const confirm = new ButtonBuilder()
.setCustomId(`ptf-debug-confirm:${interaction.id}`)
.setStyle(ButtonStyle.Danger)
.setLabel("Confirm");
const cancel = new ButtonBuilder()
.setCustomId(`ptf-debug-cancel:${interaction.id}`)
.setStyle(ButtonStyle.Secondary)
.setLabel("Cancel");
const row = new ActionRowBuilder<ButtonBuilder>().addComponents(confirm, cancel);
const reply = await interaction.editReply({ content: prompt, components: [row] });
try {
const press = await reply.awaitMessageComponent({
componentType: ComponentType.Button,
filter: (press) => press.user.id === interaction.user.id,
time: CONFIRM_TIMEOUT_MS,
});
await press.update({ content: "Working...", components: [] });
return press.customId === `ptf-debug-confirm:${interaction.id}`;
} catch {
await interaction.editReply({ content: "Timed out. Nothing was changed.", components: [] });
return false;
}
};
const runPreview = async (
interaction: ChatInputCommandInteraction,
payload: Payload,
client: Client,
action: DebugAction,
target: string | undefined,
): Promise<void> => {
const message = stripComponents(await action.build(client, payload, target));
const header = `Preview of \`${action.name}\`. Nothing was posted or stored. Buttons are omitted in debug output.`;
await interaction.editReply({
content: message.content ? `${header}\n\n${message.content}` : header,
embeds: message.embeds,
files: message.files,
});
};
const runSandbox = async (
interaction: ChatInputCommandInteraction,
payload: Payload,
client: Client,
action: DebugAction,
target: string | undefined,
): Promise<void> => {
const debugChannelId = botConfig.debugChannelId;
if (!debugChannelId) {
await interaction.editReply(
"Sandbox is disabled because DISCORD_DEBUG_CHANNEL_ID is not set. Use preview or live.",
);
return;
}
const message = stripComponents(await action.build(client, payload, target));
const channel = await client.channels.fetch(debugChannelId);
if (!channel || !("send" in channel)) {
throw new Error(`Debug channel ${debugChannelId} is not a text channel.`);
}
await (
channel as unknown as {
send(options: OutboundMessage & { allowedMentions: { parse: never[] } }): Promise<unknown>;
}
).send({
content: message.content,
embeds: message.embeds,
files: message.files,
allowedMentions: { parse: [] },
});
await interaction.editReply(
`Sent a sandbox copy of \`${action.name}\` to <#${debugChannelId}>. Nothing stored changed.`,
);
};
const runLive = async (
interaction: ChatInputCommandInteraction,
payload: Payload,
client: Client,
action: DebugAction,
target: string | undefined,
method: "edit" | "repost" | undefined,
): Promise<void> => {
if (!action.live) {
await interaction.editReply(
`\`${action.name}\` has no live mode. Use preview or sandbox instead.`,
);
return;
}
const confirmed = await confirmLive(
interaction,
`This posts \`${action.name}\` to the **real** channel and may update stored state. Confirm?`,
);
if (!confirmed) {
await interaction.editReply({
content: `Cancelled. Nothing was posted for \`${action.name}\`.`,
components: [],
});
return;
}
const result = await action.live(client, payload, target, { method });
await interaction.editReply({ content: result, components: [] });
};
const runDelete = async (
interaction: ChatInputCommandInteraction,
payload: Payload,
client: Client,
action: DebugAction,
target: string | undefined,
): Promise<void> => {
if (!action.remove) {
await interaction.editReply(`\`${action.name}\` has no tracked message to delete.`);
return;
}
const confirmed = await confirmLive(
interaction,
`This **deletes** the tracked \`${action.name}\` message from the real channel. Confirm?`,
);
if (!confirmed) {
await interaction.editReply({ content: "Cancelled. Nothing was deleted.", components: [] });
return;
}
const result = await action.remove(client, payload, target);
await interaction.editReply({ content: result, components: [] });
};
const runList = (): string =>
debugActions
.map((action) => {
const modes = ["preview", action.live ? "live" : null, "sandbox"]
.filter(Boolean)
.join(", ");
return `**${action.name}**: ${action.description}\n target: ${action.targetHint}\n modes: ${modes}`;
})
.join("\n\n");
const requireAction = (name: string): DebugAction => {
const action = findDebugAction(name);
if (!action) throw new Error(`Unknown debug action "${name}".`);
return action;
};
export const debugCommand: BotCommand = {
builder: new SlashCommandBuilder()
.setName("debug")
.setDescription("Preview, sandbox, or live-repost bot messages (staff only)")
.addSubcommand((sub) =>
sub.setName("list").setDescription("List the debuggable bot actions"),
)
.addSubcommand((sub) =>
sub
.setName("run")
.setDescription("Render or send a bot message for a target")
.addStringOption((option) =>
option
.setName("action")
.setDescription("Which bot message to run")
.setRequired(true)
.addChoices(...actionChoices),
)
.addStringOption((option) =>
option
.setName("target")
.setDescription("Mission ID/name/code name, or the record ID the action expects"),
)
.addStringOption((option) =>
option
.setName("mode")
.setDescription("preview (default, ephemeral), sandbox (debug channel), or live (real)")
.addChoices(
{ name: "preview", value: "preview" },
{ name: "sandbox", value: "sandbox" },
{ name: "live", value: "live" },
),
)
.addStringOption((option) =>
option
.setName("method")
.setDescription("Live roll-call only: edit the existing message, or repost a fresh one")
.addChoices(
{ name: "edit", value: "edit" },
{ name: "repost", value: "repost" },
),
),
)
.addSubcommand((sub) =>
sub
.setName("inspect")
.setDescription("Show the stored bot-side state for a target")
.addStringOption((option) =>
option
.setName("action")
.setDescription("Which bot message")
.setRequired(true)
.addChoices(...actionChoices),
)
.addStringOption((option) => option.setName("target").setDescription("Target")),
)
.addSubcommand((sub) =>
sub
.setName("delete")
.setDescription("Delete a tracked bot message (live, with confirmation)")
.addStringOption((option) =>
option
.setName("action")
.setDescription("Which bot message")
.setRequired(true)
.addChoices(...actionChoices),
)
.addStringOption((option) => option.setName("target").setDescription("Target")),
) as SlashCommandBuilder,
execute: async (interaction, payload) => {
if (!interaction.inGuild() || !interaction.guild) {
await interaction.reply({
content: "This command only works in a server.",
flags: MessageFlags.Ephemeral,
});
return;
}
const member = await interaction.guild.members.fetch(interaction.user.id);
if (!(await isStaff(member, payload))) {
await interaction.reply({
content: "You don't have permission to use debug.",
flags: MessageFlags.Ephemeral,
});
return;
}
const subcommand = interaction.options.getSubcommand();
if (subcommand === "list") {
await interaction.reply({ content: runList(), flags: MessageFlags.Ephemeral });
return;
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const client = interaction.client as Client;
const actionName = interaction.options.getString("action", true);
const target = interaction.options.getString("target")?.trim() || undefined;
try {
const action = requireAction(actionName);
if (subcommand === "run") {
const mode = (interaction.options.getString("mode") ?? "preview") as DebugMode;
const method = interaction.options.getString("method") as "edit" | "repost" | null;
if (mode === "preview") await runPreview(interaction, payload, client, action, target);
else if (mode === "sandbox") await runSandbox(interaction, payload, client, action, target);
else await runLive(interaction, payload, client, action, target, method ?? undefined);
return;
}
if (subcommand === "inspect") {
if (!action.inspect) {
await interaction.editReply(`\`${action.name}\` has no stored state to inspect.`);
return;
}
const state = await action.inspect(payload, target);
await interaction.editReply(
"```json\n" + JSON.stringify(state, null, 2) + "\n```",
);
return;
}
if (subcommand === "delete") {
await runDelete(interaction, payload, client, action, target);
}
} catch (error) {
await interaction.editReply(`Debug failed: ${formatError(error)}`);
}
},
};

View file

@ -8,6 +8,7 @@ import { changelogCommand } from "./changelog";
import { remindEvaluationsCommand } from "./remindEvaluations";
import { rollCallCommand } from "./rollcall";
import { discordPresenceCommand } from "./discordPresence";
import { debugCommand } from "./debug";
export interface BotCommand {
builder: SlashCommandBuilder;
@ -29,4 +30,5 @@ export const commands: BotCommand[] = [
remindEvaluationsCommand,
rollCallCommand,
discordPresenceCommand,
debugCommand,
];

View file

@ -10,6 +10,7 @@ export interface BotConfig {
changelogChannelId: string | null;
announceMentionRoleId: string | null;
npcEventChannelId: string | null;
debugChannelId: string | null;
attendancePollMs: number;
notificationPollMs: number;
evaluationPollMs: number;
@ -61,6 +62,7 @@ export const botConfig: BotConfig = {
changelogChannelId: optional("DISCORD_CHANGELOG_CHANNEL_ID"),
announceMentionRoleId: optional("DISCORD_ANNOUNCE_MENTION_ROLE_ID"),
npcEventChannelId: optional("DISCORD_NPC_EVENT_CHANNEL_ID"),
debugChannelId: optional("DISCORD_DEBUG_CHANNEL_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),

431
src/bot/lib/debugActions.ts Normal file
View file

@ -0,0 +1,431 @@
import {
AttachmentBuilder,
EmbedBuilder,
type ActionRowBuilder,
type ButtonBuilder,
type Client,
type TextBasedChannelFields,
} from "discord.js";
import { readFileSync } from "node:fs";
import type { Payload } from "payload";
import { botConfig } from "@/bot/config";
import {
CHANGELOG_PATH,
postVersion,
renderVersionEmbeds,
} from "@/bot/commands/changelog";
import {
buildModlistMessage,
buildRollCallMessage,
forceRollCall,
postEmbed,
postModlistMessage,
resolveModlist,
} from "@/bot/services/missionEmbeds";
import { buildEmbed as buildNpcEmbed } from "@/bot/services/npcEventAnnouncements";
import { renderReminderEmbed as renderImminentEmbed } from "@/bot/services/imminentReminders";
import { renderReminderEmbed as renderReadyEmbed } from "@/bot/services/readyReminders";
import { renderReminderEmbed as renderEvaluationEmbed } from "@/bot/services/evaluationReminders";
import { renderNotificationEmbed } from "@/bot/services/notificationBridge";
import {
getSideOpsChannel,
renderNotice,
resolveZeusRoleId,
} from "@/bot/services/fridayOpsNotice";
import { contextFor } from "@/bot/services/transferDelivery";
import { requestEmbed, transferDecisionRow } from "@/bot/lib/transferMessaging";
import { resolveChangelog } from "@/bot/lib/changelogRender";
import {
achievementWindowLabel,
groupAchievementsForAnnouncement,
renderAchievementAnnouncement,
type AchievementAnnouncementRow,
} from "@/bot/lib/achievementRender";
import { computeEvaluationReminderPlan } from "@/lib/evaluations/reminders";
import { getNextUpcomingScheduledMission, resolveMissionByRef } from "@/lib/intelligence/rollCall";
import type {
AssignmentTransfer,
GameEventLog,
Mission,
UserNotification,
} from "@/payload-types";
export type DebugMode = "preview" | "sandbox" | "live";
/** The exact message a production path would send, before any send happens. */
export interface OutboundMessage {
content?: string;
embeds: EmbedBuilder[];
components?: ActionRowBuilder<ButtonBuilder>[];
files?: AttachmentBuilder[];
}
export interface LiveOptions {
/** Roll-call only: edit the live message in place, or post a fresh one. */
method?: "edit" | "repost";
}
export interface DebugAction {
name: string;
description: string;
/** Hint for the target argument, shown by /debug list. */
targetHint: string;
/** Builds the message the production path would send for this target. */
build: (client: Client, payload: Payload, target: string | undefined) => Promise<OutboundMessage>;
/** Sends for real through the production channel. Omit when live is unsupported. */
live?: (
client: Client,
payload: Payload,
target: string | undefined,
options: LiveOptions,
) => Promise<string>;
/** Inspects the stored bot-side state for the target. */
inspect?: (payload: Payload, target: string | undefined) => Promise<Record<string, unknown>>;
/** Deletes the tracked bot message and clears its stored id. Live only. */
remove?: (client: Client, payload: Payload, target: string | undefined) => Promise<string>;
}
const requireChannel = (id: string | null, envName: string): string => {
if (!id) throw new Error(`${envName} is not set.`);
return id;
};
interface SendableChannel {
send(options: { content?: string; embeds: EmbedBuilder[] }): Promise<unknown>;
}
const textChannel = async (client: Client, channelId: string): Promise<SendableChannel> => {
const channel = await client.channels.fetch(channelId);
if (!channel || !("send" in channel)) {
throw new Error(`Channel ${channelId} is not a text channel.`);
}
return channel as unknown as SendableChannel;
};
interface MessageChannel {
messages: { fetch(id: string): Promise<{ delete(): Promise<unknown> }> };
}
const fetchTrackedMessage = async (client: Client, channelId: string, messageId: string) => {
const channel = await client.channels.fetch(channelId);
if (!channel || !("messages" in channel)) {
throw new Error(`Channel ${channelId} is not a text channel.`);
}
return (channel as unknown as MessageChannel).messages.fetch(messageId);
};
const resolveMission = async (payload: Payload, target: string | undefined): Promise<Mission> => {
if (target?.trim()) {
const resolved = await resolveMissionByRef(payload, target.trim());
if (resolved.error || !resolved.mission) {
throw new Error(resolved.error ?? `No mission matches "${target}".`);
}
return resolved.mission;
}
const next = await getNextUpcomingScheduledMission(payload);
if (!next) throw new Error("No upcoming Scheduled mission found. Pass a mission target.");
return next;
};
const parseId = (target: string | undefined, label: string): number => {
const id = Number(target?.trim());
if (!Number.isInteger(id) || id <= 0) {
throw new Error(`Pass the ${label} ID as the target.`);
}
return id;
};
const loadEventLog = (payload: Payload, id: number): Promise<GameEventLog> =>
payload.findByID({
collection: "game-event-logs",
id,
depth: 0,
overrideAccess: true,
}) as Promise<GameEventLog>;
const achievementGroupFor = async (payload: Payload, id: number) => {
const anchor = (await payload.findByID({
collection: "achievements",
id,
depth: 1,
overrideAccess: true,
})) as unknown as AchievementAnnouncementRow;
const res = await payload.find({
collection: "achievements",
where: {
and: [
{ window: { equals: anchor.window } },
{ windowStart: { equals: anchor.windowStart } },
],
},
depth: 1,
limit: 100,
overrideAccess: true,
});
const group = groupAchievementsForAnnouncement(
res.docs as unknown as AchievementAnnouncementRow[],
)[0];
if (!group) {
throw new Error(
`No achievements found for window ${achievementWindowLabel(anchor.window, anchor.windowStart, anchor.windowEnd)}.`,
);
}
return group;
};
const achievementEmbed = (group: Awaited<ReturnType<typeof achievementGroupFor>>): EmbedBuilder => {
const rendered = renderAchievementAnnouncement(group);
return new EmbedBuilder()
.setTitle(rendered.title)
.setDescription(rendered.description)
.setColor(rendered.color)
.addFields(rendered.fields);
};
const changelogTarget = (version: string | undefined) => {
const content = readFileSync(CHANGELOG_PATH, "utf8");
const resolved = resolveChangelog(content, version);
if (!resolved.found || resolved.messages.length === 0 || !resolved.version) {
throw new Error(
version ? `No changelog entry found for version ${version}.` : "The changelog has no entries.",
);
}
return { version: resolved.version, messages: resolved.messages };
};
export const debugActions: DebugAction[] = [
{
name: "rollcall",
description: "Live roll-call embed with RSVP buttons",
targetHint: "mission ID, name, or code name (omit for next upcoming op)",
build: async (_client, payload, target) => {
const mission = await resolveMission(payload, target);
const message = await buildRollCallMessage(payload, mission);
return { embeds: message.embeds, components: message.components };
},
live: async (client, payload, target, options) => {
const mission = await resolveMission(payload, target);
if (options.method === "repost") {
const opsChannelId = requireChannel(botConfig.opsChannelId, "DISCORD_OPS_CHANNEL_ID");
await postEmbed(client, payload, opsChannelId, mission);
return `Posted a fresh roll-call for **${mission.name}** in the ops channel and linked it.`;
}
const result = await forceRollCall(client, payload, mission);
return result === "updated"
? `Edited the live roll-call for **${mission.name}** in place.`
: `No live roll-call existed, so posted a fresh one for **${mission.name}**.`;
},
inspect: async (payload, target) => {
const mission = await resolveMission(payload, target);
return {
mission: `#${mission.id} ${mission.name}`,
discordMessageId: mission.discordMessageId ?? null,
discordAttendanceSentAt: mission.discordAttendanceSentAt ?? null,
discordAttendanceHash: mission.discordAttendanceHash ? "set" : null,
discordModlistHash: mission.discordModlistHash ? "set" : null,
imminentReminderSentAt: mission.imminentReminderSentAt ?? null,
evaluationRemindersSentAt: mission.evaluationRemindersSentAt ?? null,
};
},
remove: async (client, payload, target) => {
const mission = await resolveMission(payload, target);
if (!mission.discordMessageId) throw new Error("No live roll-call is stored for this mission.");
const message = await fetchTrackedMessage(
client,
requireChannel(botConfig.opsChannelId, "DISCORD_OPS_CHANNEL_ID"),
mission.discordMessageId,
);
await message.delete();
await payload.update({
collection: "missions",
id: mission.id,
data: { discordMessageId: null, discordAttendanceHash: null },
overrideAccess: true,
});
return `Deleted the roll-call message for **${mission.name}**. The one-shot marker is kept, so it will not repost on its own.`;
},
},
{
name: "modlist",
description: "Modlist attachment or download-link message",
targetHint: "mission ID, name, or code name",
build: async (_client, payload, target) => {
const mission = await resolveMission(payload, target);
const modlist = await resolveModlist(payload, mission);
if (!modlist) throw new Error(`${mission.name} has no modlist attached.`);
return buildModlistMessage(payload, mission, modlist, "new");
},
live: async (client, payload, target) => {
const mission = await resolveMission(payload, target);
const modlist = await resolveModlist(payload, mission);
if (!modlist) throw new Error(`${mission.name} has no modlist attached.`);
const opsChannelId = requireChannel(botConfig.opsChannelId, "DISCORD_OPS_CHANNEL_ID");
await postModlistMessage(client, payload, opsChannelId, mission, modlist, "new");
return `Posted the modlist message for **${mission.name}**. Stored markers were not changed.`;
},
},
{
name: "npc-dispatch",
description: "NPC dispatch embed for a dialogue event",
targetHint: "game event log ID",
build: async (_client, payload, target) => {
const doc = await loadEventLog(payload, parseId(target, "game event log"));
return { embeds: [buildNpcEmbed(doc)] };
},
live: async (client, payload, target) => {
const doc = await loadEventLog(payload, parseId(target, "game event log"));
const channel = await textChannel(
client,
requireChannel(botConfig.npcEventChannelId, "DISCORD_NPC_EVENT_CHANNEL_ID"),
);
await channel.send({ embeds: [buildNpcEmbed(doc)] });
return `Posted a copy of NPC dispatch event #${doc.id}. Its discordAnnouncedAt stamp was not changed.`;
},
inspect: async (payload, target) => {
const doc = await loadEventLog(payload, parseId(target, "game event log"));
return {
event: `#${doc.id}`,
discordRequested: doc.discordRequested ?? false,
discordAnnouncedAt: doc.discordAnnouncedAt ?? null,
discordMessageId: doc.discordMessageId ?? null,
};
},
remove: async (client, payload, target) => {
const doc = await loadEventLog(payload, parseId(target, "game event log"));
if (!doc.discordMessageId) throw new Error("No dispatch message is stored for this event.");
const message = await fetchTrackedMessage(
client,
requireChannel(botConfig.npcEventChannelId, "DISCORD_NPC_EVENT_CHANNEL_ID"),
doc.discordMessageId,
);
await message.delete();
await payload.update({
collection: "game-event-logs",
id: doc.id,
data: { discordMessageId: null },
overrideAccess: true,
depth: 0,
});
return `Deleted the dispatch message for event #${doc.id}. discordAnnouncedAt is kept, so it will not repost.`;
},
},
{
name: "achievement",
description: "Minigame results embed for an award window",
targetHint: "any achievement ID in the window",
build: async (_client, payload, target) => {
const group = await achievementGroupFor(payload, parseId(target, "achievement"));
return { embeds: [achievementEmbed(group)] };
},
live: async (client, payload, target) => {
const group = await achievementGroupFor(payload, parseId(target, "achievement"));
const channel = await textChannel(
client,
requireChannel(botConfig.announceChannelId, "DISCORD_ANNOUNCE_CHANNEL_ID"),
);
await channel.send({ embeds: [achievementEmbed(group)] });
return `Posted a copy of the results for "${group.label}". announcedAt was not changed.`;
},
},
{
name: "imminent",
description: "Imminent-op reminder embed (live thread pings are not offered)",
targetHint: "mission ID, name, or code name",
build: async (_client, payload, target) => {
const mission = await resolveMission(payload, target);
return { embeds: [renderImminentEmbed(mission)] };
},
},
{
name: "ready-reminders",
description: "Schedule-check DM to the op creator (preview only)",
targetHint: "mission ID, name, or code name",
build: async (_client, payload, target) => {
const mission = await resolveMission(payload, target);
return { embeds: [renderReadyEmbed(mission, new Date())] };
},
},
{
name: "friday-notice",
description: "Friday open-slot notice for #side-ops (sandbox only; live would fool the dedup token)",
targetHint: "none",
build: async (client, _payload, _target) => {
const zeusRoleId = await resolveZeusRoleId(client);
return { content: renderNotice(zeusRoleId), embeds: [] };
},
},
{
name: "changelog",
description: "Release notes for one CHANGELOG.md version (live posts to #releases)",
targetHint: "version, e.g. 0.4.0 (omit for latest)",
build: async (_client, _payload, target) => {
const { version, messages } = changelogTarget(target?.trim().replace(/^v/i, ""));
return { embeds: renderVersionEmbeds(version, messages) };
},
live: async (client, _payload, target) => {
const { version, messages } = changelogTarget(target?.trim().replace(/^v/i, ""));
const channelId = requireChannel(
botConfig.changelogChannelId ?? botConfig.announceChannelId,
"DISCORD_CHANGELOG_CHANNEL_ID",
);
const channel = await client.channels.fetch(channelId);
if (!channel || !("send" in channel)) {
throw new Error(`Releases channel ${channelId} is not a text channel.`);
}
const posted = await postVersion(channel as TextBasedChannelFields, version, messages);
return `Posted **Changelog v${version}** to the releases channel (${posted} message(s)).`;
},
},
{
name: "evaluations",
description: "Evaluation reminder DM (preview only; shows first recipient)",
targetHint: "mission ID, name, or code name",
build: async (_client, payload, target) => {
const mission = await resolveMission(payload, target);
const plan = await computeEvaluationReminderPlan(payload, mission.id);
const recipients = plan.recipients.filter((r) => r.discordId);
const first = recipients[0];
if (!first) throw new Error("No recipients with a linked Discord account.");
return {
content: `${recipients.length} recipient(s) would be DMed. Showing the first (user #${first.userId}).`,
embeds: [
renderEvaluationEmbed(mission, first.rateLeaders, first.rateSubordinates, botConfig.appUrl),
],
};
},
},
{
name: "notification",
description: "Notification bridge DM (preview only)",
targetHint: "user-notification ID",
build: async (_client, payload, target) => {
const doc = (await payload.findByID({
collection: "user-notifications",
id: parseId(target, "user-notification"),
depth: 0,
overrideAccess: true,
})) as unknown as UserNotification;
return { embeds: [renderNotificationEmbed(doc)] };
},
},
{
name: "transfer",
description: "Transfer approval request DM (preview only)",
targetHint: "assignment-transfer request ID",
build: async (_client, payload, target) => {
const doc = (await payload.findByID({
collection: "assignment-transfers",
id: parseId(target, "transfer request"),
depth: 0,
overrideAccess: true,
})) as unknown as AssignmentTransfer;
return {
embeds: [requestEmbed(await contextFor(payload, doc))],
components: [transferDecisionRow(doc.id)],
};
},
},
];
export const findDebugAction = (name: string): DebugAction | undefined =>
debugActions.find((action) => action.name === name);

View file

@ -66,7 +66,7 @@ const formatLinks = (links: ReminderLink[], appUrl: string): string => {
return lines.join("\n").slice(0, 1024) || "-";
};
const renderReminderEmbed = (
export const renderReminderEmbed = (
mission: Mission,
rateLeaders: ReminderLink[],
rateSubordinates: ReminderLink[],

View file

@ -30,11 +30,14 @@ let reconcileRunning = false;
const errorMessage = (error: unknown): string =>
error instanceof Error ? error.message : "Unknown error";
type SideOpsChannel = TextBasedChannelFields & {
export type SideOpsChannel = TextBasedChannelFields & {
messages: { fetch(options: { limit: number }): Promise<Collection<string, Message>> };
};
const getSideOpsChannel = async (client: Client, channelId: string): Promise<SideOpsChannel> => {
export const getSideOpsChannel = async (
client: Client,
channelId: string,
): Promise<SideOpsChannel> => {
const channel = await client.channels.fetch(channelId);
if (!channel || !("send" in channel) || !("messages" in channel)) {
throw new Error(`[Bot] Side-ops channel ${channelId} is not a text channel.`);
@ -43,16 +46,16 @@ const getSideOpsChannel = async (client: Client, channelId: string): Promise<Sid
};
/** Configured role ID wins; otherwise resolve the role by name in the guild. */
const resolveZeusRoleId = async (client: Client): Promise<string | null> => {
export const resolveZeusRoleId = async (client: Client): Promise<string | null> => {
if (botConfig.communityZeusRoleId) return botConfig.communityZeusRoleId;
const guild = await client.guilds.fetch(botConfig.guildId);
const role = guild.roles.cache.find((role) => role.name === SIDE_OPS_NOTICE_ROLE_NAME);
return role?.id ?? null;
};
const renderNotice = (zeusRoleId: string | null): string => {
export const renderNotice = (zeusRoleId: string | null, now = new Date()): string => {
const mention = zeusRoleId ? `<@&${zeusRoleId}> ` : "";
const { epoch } = upcomingFridayRange(new Date());
const { epoch } = upcomingFridayRange(now);
return (
`${mention}The Friday op slot (<t:${epoch}:D>) is still open, and you are welcome to host an op: ` +
`schedule one via the Friday Ops calendar at ${botConfig.appUrl}/intelligence/missions/calendar. ` +
@ -67,7 +70,7 @@ const CLAIM_LINE_PATTERN =
const creditedNameOf = (content: string): string | null =>
content.match(CLAIM_LINE_PATTERN)?.[1] ?? null;
const findNoticeMessage = async (
export const findNoticeMessage = async (
channel: SideOpsChannel,
token: string,
): Promise<Message | null> => {

View file

@ -26,7 +26,7 @@ let reconcileRunning = false;
const errorMessage = (error: unknown): string =>
error instanceof Error ? error.message : "Unknown error";
const renderReminderEmbed = (mission: Mission): EmbedBuilder => {
export const renderReminderEmbed = (mission: Mission): EmbedBuilder => {
const startUnix = Math.floor(new Date(mission.classification.startDateTime).getTime() / 1000);
return new EmbedBuilder()
.setTitle(`⏰ Op starting soon: ${missionTitle(mission)}`)
@ -38,7 +38,7 @@ const renderReminderEmbed = (mission: Mission): EmbedBuilder => {
});
};
const mentionsFor = (users: User[]): string[] =>
export const mentionsFor = (users: User[]): string[] =>
users
.filter((user) => user.discordId)
.map((user) => `<@${user.discordId as string}>`);

View file

@ -213,7 +213,7 @@ export const renderCancelledEmbed = (mission: Mission): EmbedBuilder =>
.setDescription("This operation has been cancelled.")
.setColor(CANCELLED_COLOR);
const renderCancelledNoticeEmbed = (mission: Mission): EmbedBuilder =>
export const renderCancelledNoticeEmbed = (mission: Mission): EmbedBuilder =>
new EmbedBuilder()
.setTitle(`Cancelled: ${missionTitle(mission)}`)
.setDescription(
@ -223,7 +223,7 @@ const renderCancelledNoticeEmbed = (mission: Mission): EmbedBuilder =>
.setColor(CANCELLED_COLOR)
.setTimestamp();
const renderRescheduledEmbed = (mission: Mission, rollCallDueUnix: number | null): EmbedBuilder => {
export const renderRescheduledEmbed = (mission: Mission, rollCallDueUnix: number | null): EmbedBuilder => {
const startUnix = Math.floor(new Date(mission.classification.startDateTime).getTime() / 1000);
return new EmbedBuilder()
.setTitle(`Rescheduled: ${missionTitle(mission)}`)
@ -255,7 +255,7 @@ export const buildAttendanceRow = (missionId: number): ActionRowBuilder<ButtonBu
.setLabel("❌ No"),
);
const getOpsChannel = async (
export const getOpsChannel = async (
client: Client,
opsChannelId: string,
): Promise<TextBasedChannelFields> => {
@ -266,7 +266,18 @@ const getOpsChannel = async (
return channel as unknown as TextBasedChannelFields;
};
const postEmbed = async (
export const buildRollCallMessage = async (
payload: Payload,
mission: Mission,
): Promise<{ embeds: EmbedBuilder[]; components: ActionRowBuilder<ButtonBuilder>[] }> => {
const summary = await getMissionAttendance(payload, mission.id);
return {
embeds: [renderAttendanceEmbed(mission, summary)],
components: [buildAttendanceRow(mission.id)],
};
};
export const postEmbed = async (
client: Client,
payload: Payload,
opsChannelId: string,
@ -301,7 +312,7 @@ const postEmbed = async (
});
};
interface ModlistInfo {
export interface ModlistInfo {
id: number;
name: string;
filename: string;
@ -310,7 +321,7 @@ interface ModlistInfo {
updatedAt: string;
}
const resolveModlist = async (payload: Payload, mission: Mission): Promise<ModlistInfo | null> => {
export const resolveModlist = async (payload: Payload, mission: Mission): Promise<ModlistInfo | null> => {
const raw = mission.gameDetails.gameSetup?.requiredMods;
if (raw == null || typeof raw === "number") return null;
const modlist = raw as ModList;
@ -337,7 +348,7 @@ const modlistHash = (modlist: ModlistInfo): string =>
updatedAt: modlist.updatedAt,
});
const renderModlistEmbed = (
export const renderModlistEmbed = (
mission: Mission,
modlist: ModlistInfo,
kind: "new" | "updated",
@ -354,15 +365,12 @@ const renderModlistEmbed = (
return embed;
};
const postModlistMessage = async (
client: Client,
export const buildModlistMessage = async (
payload: Payload,
opsChannelId: string,
mission: Mission,
modlist: ModlistInfo,
kind: "new" | "updated",
): Promise<void> => {
const channel = await getOpsChannel(client, opsChannelId);
): Promise<{ embeds: EmbedBuilder[]; files?: AttachmentBuilder[] }> => {
const embed = renderModlistEmbed(mission, modlist, kind);
let files: AttachmentBuilder[] | undefined;
@ -389,7 +397,19 @@ const postModlistMessage = async (
embed.addFields({ name: "Download", value: `${botConfig.appUrl}${modlist.url}` });
}
await channel.send({ embeds: [embed], files });
return { embeds: [embed], files };
};
export const postModlistMessage = async (
client: Client,
payload: Payload,
opsChannelId: string,
mission: Mission,
modlist: ModlistInfo,
kind: "new" | "updated",
): Promise<void> => {
const channel = await getOpsChannel(client, opsChannelId);
await channel.send(await buildModlistMessage(payload, mission, modlist, kind));
};
/**

View file

@ -43,6 +43,16 @@ const eligibleForDm = (owner: User, type?: string | null): boolean => {
return true;
};
export const renderNotificationEmbed = (notification: UserNotification): EmbedBuilder =>
new EmbedBuilder()
.setTitle(notification.title)
.setDescription(notification.message ?? null)
.setColor(EMBED_COLOR)
.addFields({
name: "Link",
value: `${botConfig.appUrl}${notification.link ?? ""}`,
});
const poll = async (client: Client, payload: Payload): Promise<void> => {
try {
if (cursor === null) {
@ -76,18 +86,7 @@ const poll = async (client: Client, payload: Payload): Promise<void> => {
if (!eligibleForDm(owner, notification.type)) continue;
const target = await client.users.fetch(owner.discordId as string);
await target.send({
embeds: [
new EmbedBuilder()
.setTitle(notification.title)
.setDescription(notification.message ?? null)
.setColor(EMBED_COLOR)
.addFields({
name: "Link",
value: `${botConfig.appUrl}${notification.link ?? ""}`,
}),
],
});
await target.send({ embeds: [renderNotificationEmbed(notification)] });
sent++;
if (sent < MAX_SENDS_PER_TICK) await sleep(SEND_DELAY_MS);
} catch {

View file

@ -30,7 +30,7 @@ let running = false;
const errorMessage = (error: unknown): string =>
error instanceof Error ? error.message : "Unknown error";
const buildEmbed = (doc: GameEventLog): EmbedBuilder => {
export const buildEmbed = (doc: GameEventLog): EmbedBuilder => {
const epoch = Math.floor(new Date(doc.timestamp).getTime() / 1000);
const embed = new EmbedBuilder()
.setTitle("NPC Dispatch")

View file

@ -38,7 +38,7 @@ const errorMessage = (error: unknown): string =>
const creatorIdOf = (mission: Mission): number | null =>
typeof mission.createdBy === "object" ? (mission.createdBy?.id ?? null) : (mission.createdBy ?? null);
const renderReminderEmbed = (mission: Mission, now: Date): EmbedBuilder => {
export const renderReminderEmbed = (mission: Mission, now: Date): EmbedBuilder => {
const days = daysUntil(mission.classification.startDateTime, now);
const when = days === 0 ? "today" : days === 1 ? "tomorrow" : `in ${days} days`;
return new EmbedBuilder()

View file

@ -35,7 +35,7 @@ const fetchUser = (payload: Payload, id: number): Promise<User> =>
const fetchAssignment = (payload: Payload, id: number): Promise<Assignment> =>
payload.findByID({ collection: "assignments", id, depth: 0, overrideAccess: true });
const contextFor = async (
export const contextFor = async (
payload: Payload,
doc: AssignmentTransfer,
): Promise<TransferContext> => {

View file

@ -28,7 +28,7 @@ collections/
# GameVehicles, GameNpcs, GameHardResources, GameEventLogs,
# NpcStaffing, LaborClassifications (+ shared staffingFields.ts factory)
server/ 5 files # MissionFiles, ModLists, GameServers, ArmaCommands, ArmaSyncEvents
world/ 5 files # Maps (basemap config), MapRoads/MapZones/ResourceNodes (map features), NarrativeEvents
world/ 6 files # Maps (basemap config), MapRoads/MapZones/ResourceNodes (map features), MapObjectives (superuser strategic objectives), NarrativeEvents
projects/ 4 files # Projects, Labels, Releases, Sprints (Jira-like)
tickets/ 2 files # Tickets (Lexical rich text; `archived` hides from all front-ends, admin panel only), TicketVotes
wiki/ 3 files # WikiPages, WikiRevisions, WikiTemplates

View file

@ -36,6 +36,7 @@ const TARGET_COLLECTIONS = [
{ label: "Wiki Templates", value: "wiki-templates" },
{ label: "Survey Submissions", value: "form-submissions" },
{ label: "Mission Map Markers", value: "mission-map-markers" },
{ label: "Map Objectives", value: "map-objectives" },
{ label: "Contribution Entries", value: "contribution-entries" },
{ label: "Game Servers", value: "game-servers" },
{ label: "Assignment Transfers", value: "assignment-transfers" },
@ -190,7 +191,8 @@ export const GameEventLogs: CollectionConfig = {
type: "date",
admin: {
readOnly: true,
description: "Set by the bot when the dispatch posts. Empty with a request above means queued or retrying.",
description:
"Set by the bot when the dispatch posts. Empty with a request above means queued or retrying.",
},
},
{

View file

@ -109,10 +109,18 @@ export const Vehicles: CollectionConfig = {
label: "Transport",
value: "transport",
},
{
label: "Drone",
value: "drone",
},
{
label: "Weaponized",
value: "weaponized",
},
{
label: "Static",
value: "static",
},
{
label: "Military",
value: "military",
@ -357,6 +365,32 @@ export const Vehicles: CollectionConfig = {
},
],
},
{
name: "disallowedCargo",
label: "Disallowed Virtual Cargo",
type: "array",
admin: {
description:
"Items this vehicle may NOT carry when used virtually (e.g., during deliveries, moving troops). A shipment using this vehicle is rejected before its cargo is deducted if any cargo line matches.",
},
fields: [
{
name: "item",
type: "relationship",
relationTo: ["assets", "vehicles", "resources"],
required: true,
},
{
name: "amount",
type: "number",
defaultValue: 0,
admin: {
description:
"Optional cap. Leave at 0 to forbid the item entirely; set a positive number to allow up to that amount only.",
},
},
],
},
],
},
],

View file

@ -81,10 +81,22 @@ export const OperationEffects: CollectionConfig = {
options: [
{ label: "Applied", value: "applied" },
{ label: "Pending", value: "pending" },
{
label: "Awaiting Action",
value: "pending_action",
},
{ label: "Failed", value: "failed" },
{ label: "Reversed", value: "reversed" },
],
},
{
name: "decisions",
type: "json",
admin: {
description:
"Per-item officer resolution for a gated extraction: [{ relationTo, id, decision }]. decision is keep (deposit), scrap, or expel (hold back). Absent = not yet reviewed.",
},
},
{ name: "payload", type: "json" },
{
name: "reversalOf",

View file

@ -45,5 +45,12 @@ export const ModLists: CollectionConfig = {
// "Invalid MIME type: application/xml". The document itself is stored
// with the text/html mimetype the action passes.
mimeTypes: ["text/html", "application/xml"],
// Payload streams uploads inline by default, so the browser renders the
// preset HTML instead of saving it. Force a download for every link to the
// file (the Discord modlist embed and the web UI both use this URL).
modifyResponseHeaders: ({ headers }) => {
headers.set("Content-Disposition", "attachment");
return headers;
},
},
};

View file

@ -0,0 +1,207 @@
import type { CollectionConfig } from "payload";
import { hasPermission, requirePermission } from "@/utils/access-control/hasPermission";
import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
import { validatePosition } from "@/lib/map/points";
import {
DEFAULT_OBJECTIVE_MARKER_TYPE,
MAP_OBJECTIVE_STATUSES,
OBJECTIVE_STATUS_META,
objectiveStatusLabel,
} from "@/lib/map/objectiveTypes";
/** Payload's loose doc shape inside hooks (avoids a generated-types dependency). */
interface ObjectiveHookDoc {
id: number;
map?: number | { id: number } | null;
name?: string | null;
status?: string | null;
redacted?: boolean | null;
}
function mapIdOf(doc: ObjectiveHookDoc): number | null {
const value = doc.map;
if (typeof value === "number") return value;
if (value && typeof value === "object") return value.id;
return null;
}
/**
* Strategic objectives: Arma-style command markers that belong to a terrain
* map and are visible to every mission planned on it.
*
* - Read: any logged-in user, except `redacted` rows which Payload filters out
* for anyone without the superuser tier.
* - Write: `system:admin-access` only (built-in admin role + superuser roles).
* Division roles are never granted this tier.
*
* Frontend authoring flows through `src/app/(frontend)/map/actions.ts`; this
* collection-level gate governs the REST API and the admin panel.
*/
export const MapObjectives: CollectionConfig = {
slug: "map-objectives",
admin: {
group: "World",
useAsTitle: "name",
defaultColumns: ["name", "map", "status", "redacted", "position"],
description:
"Strategic objectives shown on the world map and mission planning maps. Superuser-authored.",
},
access: {
read: async ({ req }) => {
if (!req.user) return false;
if (await hasPermission(req.payload, req.user, "system:admin-access")) return true;
return { redacted: { equals: false } };
},
create: requirePermission("system:admin-access"),
update: requirePermission("system:admin-access"),
delete: requirePermission("system:admin-access"),
},
hooks: {
afterChange: [
async ({ doc, previousDoc, operation, req }) => {
const current = doc as unknown as ObjectiveHookDoc;
const previous = previousDoc as unknown as ObjectiveHookDoc | undefined;
const mapId = mapIdOf(current) ?? (previous ? mapIdOf(previous) : null);
if (!mapId) return;
const name = current.name ?? previous?.name ?? `Objective #${current.id}`;
const actor = req.user?.id;
if (operation === "create") {
await emitGameEvent(req.payload, {
type: EventTypes.MapObjectiveCreate,
message: `Added objective ${name}`,
actor,
targetCollection: "map-objectives",
targetId: current.id,
data: { mapId, objectiveId: current.id },
});
return;
}
if (previous && previous.status !== current.status) {
await emitGameEvent(req.payload, {
type: EventTypes.MapObjectiveStatus,
message: `Objective ${name} is now ${objectiveStatusLabel(current.status).toLowerCase()}`,
actor,
targetCollection: "map-objectives",
targetId: current.id,
data: { mapId, objectiveId: current.id, status: current.status },
});
return;
}
if (previous && previous.redacted !== current.redacted) {
await emitGameEvent(req.payload, {
type: EventTypes.MapObjectiveReveal,
message: `${current.redacted ? "Hid" : "Revealed"} objective ${name}`,
actor,
targetCollection: "map-objectives",
targetId: current.id,
data: { mapId, objectiveId: current.id, redacted: current.redacted },
});
return;
}
await emitGameEvent(req.payload, {
type: EventTypes.MapObjectiveUpdate,
message: `Updated objective ${name}`,
actor,
targetCollection: "map-objectives",
targetId: current.id,
data: { mapId, objectiveId: current.id },
});
},
],
afterDelete: [
async ({ doc, req }) => {
const deleted = doc as unknown as ObjectiveHookDoc;
const mapId = mapIdOf(deleted);
await emitGameEvent(req.payload, {
type: EventTypes.MapObjectiveDelete,
message: `Removed objective ${deleted.name ?? `#${deleted.id}`}`,
actor: req.user?.id,
targetCollection: "map-objectives",
targetId: deleted.id,
data: mapId ? { mapId, objectiveId: deleted.id } : { objectiveId: deleted.id },
});
},
],
},
fields: [
{
name: "name",
type: "text",
required: true,
maxLength: 80,
admin: {
description: 'Map label, e.g. "OBJ ALPHA". Shown under the marker on every map.',
},
},
{
name: "description",
type: "textarea",
maxLength: 500,
admin: {
description: "Planning note shown in the marker popup.",
},
},
{
name: "map",
type: "relationship",
relationTo: "maps",
required: true,
index: true,
},
{
name: "markerType",
type: "text",
defaultValue: DEFAULT_OBJECTIVE_MARKER_TYPE,
admin: {
description: "CfgMarkers class name, e.g. mil_objective, o_objective, hd_objective.",
},
},
{
name: "status",
type: "select",
required: true,
defaultValue: "active",
options: MAP_OBJECTIVE_STATUSES.map((status) => ({
label: OBJECTIVE_STATUS_META[status].label,
value: status,
})),
admin: {
description:
"Drives the marker colour: red for active, green for secured, grey for failed.",
},
},
{
name: "redacted",
type: "checkbox",
label: "Redacted",
defaultValue: false,
admin: {
description:
"Hidden from everyone except superusers (and drawn dimmed for them) until revealed.",
},
},
{
name: "position",
type: "json",
required: true,
validate: validatePosition,
admin: {
description: "[x, y] in map meters (origin top-left, y south).",
},
},
{
name: "createdBy",
type: "relationship",
relationTo: "users",
admin: {
readOnly: true,
position: "sidebar",
},
},
],
};

View file

@ -13,6 +13,31 @@ export const Maps: CollectionConfig = {
delete: requirePermission("maps:delete"),
read: requirePermission("maps:read"),
},
hooks: {
beforeDelete: [
// Strategic objectives belong to exactly one map. Their FK is NOT NULL
// (required), so the default ON DELETE SET NULL would make the map
// delete fail; remove them first, inside the same request.
async ({ id, req }) => {
const objectives = await req.payload.find({
collection: "map-objectives",
where: { map: { equals: id } },
depth: 0,
pagination: false,
overrideAccess: true,
req,
});
for (const objective of objectives.docs) {
await req.payload.delete({
collection: "map-objectives",
id: objective.id,
overrideAccess: true,
req,
});
}
},
],
},
fields: [
{
name: "name",

View file

@ -52,7 +52,7 @@ export default function RibbonDesigner() {
Configure the ribbon colors, stripes, and device attachments for this award.
</p>
<RibbonPreview design={design} />
<RibbonPreview design={design} allowTierPreview />
<button
type="button"

View file

@ -0,0 +1,243 @@
/**
* THE single ribbon renderer, shared by production (`RibbonViewer`), the admin
* `RibbonDesigner`, and the member-facing `RibbonStudio`. Drawing stripes,
* the fabric overlay, and the devices lives here so an author's preview is
* pixel-identical to what grantees see.
*
* Devices are inline vector shapes (no Unicode glyphs, no font dependency) and
* their count and placement are derived, never positioned by hand:
*
* - `resolveDisplayedDeviceTypes(design, tier)` maps an advancement tier to a
* device count using the service-star convention: tier 1 is the bare award,
* each higher tier adds one device (capped at `MAX_TIER_DEVICES`). Non-tiered
* ribbons keep the device set authored in the designer.
* - `computeDeviceSlots(...)` lays the devices out as one centered cluster on
* the ribbon face, evenly spaced and shrunk to fit narrow ribbons.
*/
import type { ReactNode } from "react";
import { RIBBON_CONSTANTS, DEFAULT_RIBBON } from "./constants";
import type { DeviceType, RibbonDesign } from "./types";
export const MAX_TIER_DEVICES = 6;
const DEFAULT_DEVICE_TYPE: DeviceType = "star";
// ─── Tier-driven device resolution ──────────────────────────────────
/**
* Resolve which device glyphs to display for a design at a given advancement
* tier. Pass `tier >= 2` to use the tier mapping (tier N shows N - 1 devices,
* cycling through the authored device types, defaulting to star when none are
* authored). Pass `undefined`/`null`/`1` to render exactly what was authored.
*/
export function resolveDisplayedDeviceTypes(
design: RibbonDesign | null | undefined,
tier?: number | null,
): DeviceType[] {
const authored = Array.isArray(design?.devices) ? design.devices.map((d) => d.type) : [];
// Derive from tier only for genuine upgrades (tier >= 2). Missing, invalid,
// or base tiers render exactly what was authored.
const effectiveTier = typeof tier === "number" && Number.isFinite(tier) ? Math.floor(tier) : null;
if (effectiveTier === null || effectiveTier < 2) return authored;
// Service-star convention: the base tier carries no devices; each upgrade
// adds one. The first award of a series is therefore a bare ribbon and tier
// N reads as "awarded N times". Capped at MAX_TIER_DEVICES clusters.
const slots = Math.min(effectiveTier - 1, MAX_TIER_DEVICES);
return Array.from({ length: slots }, (_, i) => authored[i % authored.length] ?? DEFAULT_DEVICE_TYPE);
}
// ─── Centered auto-layout ───────────────────────────────────────────
export interface DeviceSlot {
cx: number;
cy: number;
size: number;
}
/**
* Lay out `count` devices as a single centered cluster on a `width x height`
* SVG canvas. Devices are evenly spaced and vertically centered; the whole
* cluster shrinks to fit within 80% of the ribbon width for high counts.
*/
export function computeDeviceSlots(
count: number,
width: number,
height: number,
): DeviceSlot[] {
if (count <= 0) return [];
const maxGroupWidth = width * 0.8;
const idealSize = Math.min(height * 0.34, 30);
// Pitch is 1.55 device-sizes center-to-center (size + a half-size gap), so
// the cluster spans `1 + 1.55 * (count - 1)` sizes (center-to-center gaps
// plus one device width); shrink uniformly when that exceeds the face.
const GAP_RATIO = 0.55;
const PITCH_RATIO = 1 + GAP_RATIO;
const spanInSizes = 1 + PITCH_RATIO * (count - 1);
const size = Math.max(6, Math.min(idealSize, maxGroupWidth / spanInSizes));
const spacing = size * PITCH_RATIO;
const total = (count - 1) * spacing;
const startX = width / 2 - total / 2;
const cy = height / 2;
return Array.from({ length: count }, (_, i) => ({ cx: startX + i * spacing, cy, size }));
}
// ─── Vector device shapes (authored in a 0..100 unit space) ─────────
const DEVICE_SHAPES: Record<DeviceType, string> = {
star: "M50 2 L60.6 35.4 L95.7 35.2 L67.1 55.6 L78.2 88.8 L50 68 L21.8 88.8 L32.9 55.6 L4.3 35.2 L39.4 35.4 Z",
oakLeaf:
"M50 88 Q68 90 80 80 Q72 74 64 72 Q86 70 92 52 Q78 50 66 50 Q84 40 80 22 Q70 26 60 30 Q56 18 50 4 Q44 18 40 30 Q30 26 20 22 Q16 40 34 50 Q22 50 8 52 Q14 70 32 72 Q24 74 20 80 Q32 90 50 88 Z",
valor: "M10 12 L30 12 L50 66 L70 12 L90 12 L56 92 L44 92 Z",
campaignClasp: "M12 32 L88 32 L88 68 L12 68 Z",
};
const BRASS_OUTLINE = "#3b2208";
/**
* Brass device body shared by every device type. Built for legibility at
* ribbon scale (~24px): a brass gradient with a dark outline carries the
* silhouette. Offset highlight/shadow layers blur together when small, so the
* emboss is expressed through the gradient and outline instead. The gradient
* id is static: every instance defines the identical gradient, so duplicates
* are harmless, and RibbonArt stays hook-free for server components.
*/
function BrassShape({ d, children }: { d: string; children?: ReactNode }) {
return (
<g transform="translate(-50 -50)">
<defs>
<linearGradient id="ptf-brass" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stopColor="#f7dc8f" />
<stop offset="55%" stopColor="#c8913a" />
<stop offset="100%" stopColor="#8a5a1c" />
</linearGradient>
</defs>
<path d={d} fill="url(#ptf-brass)" stroke={BRASS_OUTLINE} strokeWidth={5} strokeLinejoin="round" />
{children}
</g>
);
}
function DeviceShape({ type }: { type: DeviceType }) {
const d = DEVICE_SHAPES[type] ?? DEVICE_SHAPES.star;
if (type === "oakLeaf") {
// Leaf rotated and given an engraved midrib plus a brass stem at the
// bottom right, so it reads as a sprig rather than a flat blob.
return (
<g transform="rotate(-35)">
<BrassShape d={d}>
<path d="M50 86 L50 94" fill="none" stroke={BRASS_OUTLINE} strokeWidth={11} strokeLinecap="round" />
<path d="M50 86 L50 94" fill="none" stroke="#c8913a" strokeWidth={5} strokeLinecap="round" />
<path d="M50 84 L50 16" fill="none" stroke={BRASS_OUTLINE} strokeWidth={4} strokeLinecap="round" />
</BrassShape>
</g>
);
}
return <BrassShape d={d} />;
}
/**
* A device icon at `px` size, usable outside the ribbon SVG (editors, chips).
* Shapes are authored around the origin (see `DeviceShape`).
*/
export function DeviceGlyph({
type,
px = 14,
className,
}: {
type: DeviceType;
px?: number;
className?: string;
}) {
return (
<svg
viewBox="-56 -56 112 112"
width={px}
height={px}
aria-hidden="true"
className={className}
style={{ display: "inline-block", verticalAlign: "-2px" }}
>
<DeviceShape type={type} />
</svg>
);
}
// ─── Shared renderer ────────────────────────────────────────────────
export interface RibbonArtProps {
design: RibbonDesign | null | undefined;
/** Advancement tier of the award being rendered; drives device count. */
tier?: number | null;
/** Fabric texture overlay (present in both preview and production). */
showOverlay?: boolean;
/** Additional class names on the <svg> root (sizing, borders). */
className?: string;
maxHeight?: number;
}
/**
* Render a ribbon (stripes + overlay + vector devices) at the canonical
* `RIBBON_WIDTH x PREVIEW_HEIGHT` viewBox, scaled responsively by CSS. The
* devices shown come from `resolveDisplayedDeviceTypes(design, tier)` and are
* auto-laid-out by `computeDeviceSlots`, so this component owns all layout.
*/
export function RibbonArt({
design,
tier,
showOverlay = true,
className,
maxHeight,
}: RibbonArtProps) {
const resolved: RibbonDesign =
design && typeof design === "object" && Array.isArray(design.stripes) ? design : DEFAULT_RIBBON;
const { stripes, mirrored } = resolved;
if (stripes.length === 0) return null;
const displayStripes = mirrored ? [...stripes, ...stripes.slice(0, -1).reverse()] : stripes;
const totalWeight = displayStripes.reduce((sum, s) => sum + s.width, 0);
const viewWidth = RIBBON_CONSTANTS.RIBBON_WIDTH;
const viewHeight = RIBBON_CONSTANTS.PREVIEW_HEIGHT;
const deviceTypes = resolveDisplayedDeviceTypes(resolved, tier);
const slots = computeDeviceSlots(deviceTypes.length, viewWidth, viewHeight);
let stripeX = 0;
const stripeRects = displayStripes.map((stripe, i) => {
const w = (stripe.width / totalWeight) * viewWidth;
const el = <rect key={i} x={stripeX} y={0} width={w} height={viewHeight} fill={stripe.color} />;
stripeX += w;
return el;
});
return (
<svg
viewBox={`0 0 ${viewWidth} ${viewHeight}`}
className={className}
style={maxHeight ? { maxHeight } : undefined}
>
<rect x={0} y={0} width={viewWidth} height={viewHeight} rx={2} fill="#18181b" />
{stripeRects}
{showOverlay && (
<image href="/images/ribbon-overlay.png" className="mix-blend-multiply w-full" />
)}
{slots.map((slot, i) => (
<g
key={i}
data-device={deviceTypes[i]}
transform={`translate(${slot.cx} ${slot.cy}) scale(${slot.size / 100})`}
>
{/* Emboss: offset dark drop-shadow beneath the gold shape */}
<g style={{ pointerEvents: "none", color: "rgba(12, 10, 4, 0.55)" }} transform="translate(3 4)">
<DeviceShape type={deviceTypes[i]} />
</g>
<g style={{ pointerEvents: "none" }} color="#facc15">
<DeviceShape type={deviceTypes[i]} />
</g>
</g>
))}
</svg>
);
}

View file

@ -40,7 +40,7 @@ export const MILITARY_COLORS: { name: string; hex: string }[] = [
export const RIBBON_DEVICE_INFO: Record<DeviceType, { label: string; symbol: string }> = {
star: { label: "Star", symbol: "\u2605" },
oakLeaf: { label: "Oak Leaf", symbol: "\u{1F333}" },
arrowUp: { label: "Arrow", symbol: "\u2191" },
valor: { label: "Valor (V)", symbol: "V" },
campaignClasp: { label: "Clasp", symbol: "\u2015" },
};

View file

@ -1,61 +1,59 @@
"use client";
import { RIBBON_CONSTANTS, RIBBON_DEVICE_INFO } from "./constants";
import { useState } from "react";
import { RIBBON_DEVICE_INFO } from "./constants";
import { DeviceGlyph, MAX_TIER_DEVICES, RibbonArt } from "./RibbonArt";
import type { Device, DeviceType, RibbonDesign, Stripe } from "./types";
const { RIBBON_ASPECT, RIBBON_WIDTH, PREVIEW_HEIGHT } = RIBBON_CONSTANTS;
// ─── Preview ────────────────────────────────────────────────────────
export function RibbonPreview({ design }: { design: RibbonDesign }) {
const { stripes, devices, mirrored } = design;
if (stripes.length === 0) return null;
const displayStripes = mirrored ? [...stripes, ...stripes.slice(0, -1).reverse()] : stripes;
const totalWeight = displayStripes.reduce((sum, s) => sum + s.width, 0);
const viewWidth = RIBBON_WIDTH;
const viewHeight = PREVIEW_HEIGHT;
/**
* Design-time ribbon preview: the same `RibbonArt` used on the live site, so
* authors see exactly what grantees get (devices included, auto-laid-out).
* Pass `tier` to preview one fixed tier. With `allowTierPreview`, a small
* selector simulates tiers 1..MAX+1: tier 1 renders the authored device set,
* each higher tier derives its cluster count (N - 1 devices), matching the
* service-star convention applied at render time.
*/
export function RibbonPreview({
design,
tier,
allowTierPreview,
}: {
design: RibbonDesign;
tier?: number | null;
allowTierPreview?: boolean;
}) {
const [simulatedTier, setSimulatedTier] = useState(1);
const effectiveTier = allowTierPreview ? simulatedTier : tier;
return (
<svg
viewBox={`0 0 ${viewWidth} ${viewHeight}`}
className="w-full h-auto rounded border border-zinc-700 bg-zinc-950"
style={{ maxHeight: 140 }}
>
<rect x={0} y={0} width={viewWidth} height={viewHeight} rx={2} fill="#18181b" />
{(() => {
let x = 0;
return displayStripes.map((stripe, i) => {
const w = (stripe.width / totalWeight) * viewWidth;
const el = <rect key={i} x={x} y={0} width={w} height={viewHeight} fill={stripe.color} />;
x += w;
return el;
});
})()}
{devices.map((device) => {
const info = RIBBON_DEVICE_INFO[device.type];
const cx = (device.position / 100) * viewWidth;
const cy = (device.positionY / 100) * viewHeight;
const fontSize = Math.min(viewHeight * 0.45, 24);
return (
<text
key={device.id}
x={cx}
y={cy}
textAnchor="middle"
dominantBaseline="central"
fill="#facc15"
fontSize={fontSize}
fontFamily="serif"
style={{ pointerEvents: "none" }}
>
{info.symbol}
</text>
);
})}
</svg>
<div className="flex flex-col gap-2">
<RibbonArt
design={design}
tier={effectiveTier}
className="w-full h-auto rounded border border-zinc-700 bg-zinc-950"
maxHeight={140}
/>
{allowTierPreview && (
<label className="flex items-center gap-2 text-[11px] text-zinc-400">
<span className="uppercase tracking-wider">Preview tier</span>
<input
type="range"
min={1}
max={MAX_TIER_DEVICES + 1}
value={simulatedTier}
onChange={(e) => setSimulatedTier(Number(e.target.value))}
className="flex-1 h-1 accent-amber-500"
/>
<span className="font-mono w-16 text-right">
{simulatedTier === 1
? "as authored"
: `${Math.min(simulatedTier - 1, MAX_TIER_DEVICES)} devices`}
</span>
</label>
)}
</div>
);
}
@ -123,7 +121,7 @@ export function StripeEditor({
onClick={() => removeStripe(idx)}
className="py-1 text-zinc-500 hover:text-red-400 text-sm cursor-pointer"
>
\u00D7
{"\u00D7"}
</button>
</div>
))}
@ -133,6 +131,12 @@ export function StripeEditor({
// ─── Device Editor ──────────────────────────────────────────────────
/**
* Devices are added/removed as an ordered set; their placement on the ribbon
* is computed automatically (centered cluster, tier-driven count when the
* award belongs to an advancement series). The legacy per-device X/Y sliders
* are gone because layout is derived, and stored positions are ignored.
*/
export function DeviceEditor({
devices,
onChange,
@ -143,12 +147,21 @@ export function DeviceEditor({
const addDevice = (type: DeviceType) =>
onChange([...devices, { id: crypto.randomUUID(), type, position: 50, positionY: 50 }]);
const removeDevice = (id: string) => onChange(devices.filter((d) => d.id !== id));
const updateDevice = (id: string, patch: Partial<Device>) =>
onChange(devices.map((d) => (d.id === id ? { ...d, ...patch } : d)));
const moveDevice = (idx: number, delta: number) => {
const next = [...devices];
const target = idx + delta;
if (target < 0 || target >= next.length) return;
[next[idx], next[target]] = [next[target], next[idx]];
onChange(next);
};
return (
<div className="flex flex-col gap-2">
<span className="text-xs font-medium text-zinc-400 uppercase tracking-wider">Devices</span>
<p className="text-[10px] text-zinc-500">
Devices arrange themselves centered on the ribbon. For awards in an
advancement series, the tier sets how many show (tier N displays N&nbsp;-&nbsp;1).
</p>
<div className="flex flex-wrap gap-1.5">
{(Object.keys(RIBBON_DEVICE_INFO) as DeviceType[]).map((type) => {
const info = RIBBON_DEVICE_INFO[type];
@ -157,58 +170,51 @@ export function DeviceEditor({
key={type}
type="button"
onClick={() => addDevice(type)}
className="text-[11px] px-2 py-1 rounded bg-zinc-800 border border-zinc-700 text-zinc-300 hover:bg-zinc-700 transition-colors cursor-pointer"
className="text-[11px] px-2 py-1 rounded bg-zinc-800 border border-zinc-700 text-zinc-300 hover:bg-zinc-700 transition-colors cursor-pointer inline-flex items-center gap-1.5 text-yellow-400 [&_span]:text-zinc-300"
>
{info.symbol} {info.label}
<DeviceGlyph type={type} px={12} /> <span>{info.label}</span>
</button>
);
})}
</div>
{devices.length > 0 && (
<div className="flex flex-col gap-1.5">
{devices.map((device) => {
{devices.map((device, idx) => {
const info = RIBBON_DEVICE_INFO[device.type];
return (
<div
key={device.id}
className="flex items-center gap-2 bg-zinc-900 rounded px-2 py-1.5"
className="flex items-center gap-2 bg-zinc-900 rounded px-2 py-1.5 text-yellow-400"
>
<span className="text-sm">{info.symbol}</span>
<span className="font-mono text-[10px] text-zinc-500 w-4">{idx + 1}</span>
<DeviceGlyph type={device.type} px={14} />
<span className="text-[11px] text-zinc-400">{info.label}</span>
<div className="flex items-center gap-1.5 flex-1">
<label className="text-[10px] text-zinc-500 shrink-0">X</label>
<input
type="range"
min={0}
max={100}
value={device.position}
onChange={(e) => updateDevice(device.id, { position: Number(e.target.value) })}
className="flex-1 h-1 accent-zinc-400"
/>
<span className="text-[10px] text-zinc-500 font-mono w-5 text-right">
{device.position}
</span>
</div>
<div className="flex items-center gap-1.5 flex-1">
<label className="text-[10px] text-zinc-500 shrink-0">Y</label>
<input
type="range"
min={0}
max={100}
value={device.positionY}
onChange={(e) => updateDevice(device.id, { positionY: Number(e.target.value) })}
className="flex-1 h-1 accent-zinc-400"
/>
<span className="text-[10px] text-zinc-500 font-mono w-5 text-right">
{device.positionY}
</span>
</div>
<div className="flex-1" />
<button
type="button"
onClick={() => removeDevice(device.id)}
className="py-1 text-zinc-500 hover:text-red-400 text-sm cursor-pointer"
aria-label={`Move ${info.label} earlier`}
onClick={() => moveDevice(idx, -1)}
disabled={idx === 0}
className="px-1 text-zinc-500 hover:text-zinc-200 disabled:opacity-30 cursor-pointer"
>
\u00D7
↑
</button>
<button
type="button"
aria-label={`Move ${info.label} later`}
onClick={() => moveDevice(idx, 1)}
disabled={idx === devices.length - 1}
className="px-1 text-zinc-500 hover:text-zinc-200 disabled:opacity-30 cursor-pointer"
>
↓
</button>
<button
type="button"
aria-label={`Remove ${info.label}`}
onClick={() => removeDevice(device.id)}
className="px-1 py-1 text-zinc-500 hover:text-red-400 text-sm cursor-pointer"
>
{"\u00D7"}
</button>
</div>
);

View file

@ -1,6 +1,6 @@
// ─── Types ──────────────────────────────────────────────────────────
export type DeviceType = "star" | "oakLeaf" | "arrowUp" | "campaignClasp";
export type DeviceType = "star" | "oakLeaf" | "valor" | "campaignClasp";
export type Device = {
id: string;

View file

@ -71,6 +71,7 @@ export default function AwardCard(props: {
<RibbonViewer
ribbonDesign={props.award.ribbonDesign as RibbonDesign}
showRibbonOnly={true}
tier={props.award.advancement?.tier ?? null}
/>
)}
<div className="flex items-center gap-2.5">

View file

@ -87,6 +87,7 @@ export function AwardListingCard({
<RibbonViewer
ribbonDesign={award.ribbonDesign as RibbonDesign}
showRibbonOnly={false}
tier={award.advancement?.tier ?? null}
/>
</div>
) : awardImage?.url ? (

View file

@ -75,7 +75,11 @@ export function AwardPickerDialog({
{award.type === "ribbon" && award.ribbonDesign ? (
<div className="flex h-16 w-full items-center justify-center">
<div className="w-32 max-w-full">
<RibbonViewer ribbonDesign={award.ribbonDesign as RibbonDesign} showRibbonOnly />
<RibbonViewer
ribbonDesign={award.ribbonDesign as RibbonDesign}
showRibbonOnly
tier={award.advancement?.tier ?? null}
/>
</div>
</div>
) : (

View file

@ -63,7 +63,7 @@ export const RibbonRack = ({ awards }: { awards: Award[] }) => {
return (
<Tooltip key={key}>
<TooltipTrigger className="w-[6.375rem] max-w-full h-[1.6875rem] hover:scale-110 shadow-black shadow-xs hover:shadow-xl transition-transform">
<RibbonViewer ribbonDesign={ribbon} showRibbonOnly />
<RibbonViewer ribbonDesign={ribbon} showRibbonOnly tier={award.advancement?.tier ?? null} />
</TooltipTrigger>
<TooltipContent>
<div className="flex flex-col gap-1">

View file

@ -1,15 +1,26 @@
"use client";
import {
RIBBON_DEVICE_INFO,
RIBBON_CONSTANTS,
DEFAULT_RIBBON,
} from "@/components/awards/ribbonDesign/constants";
import { DEFAULT_RIBBON } from "@/components/awards/ribbonDesign/constants";
import { RibbonArt } from "@/components/awards/ribbonDesign/RibbonArt";
import type { RibbonDesign } from "@/components/awards/ribbonDesign/types";
import { useState } from "react";
import { cn } from "@/lib/utils";
export const RibbonViewer = ({ ribbonDesign, showRibbonOnly }: { ribbonDesign: RibbonDesign, showRibbonOnly?: boolean }) => {
/**
* Production ribbon renderer. Thin wrapper around the shared `RibbonArt` so
* the live site and the admin/studio previews cannot drift apart. Pass an
* award's `advancement.tier` to let the device cluster derive its count from
* the tier (service-star convention); omit it to show the authored devices.
*/
export const RibbonViewer = ({
ribbonDesign,
showRibbonOnly,
tier,
}: {
ribbonDesign: RibbonDesign;
showRibbonOnly?: boolean;
tier?: number | null;
}) => {
const initial: RibbonDesign =
ribbonDesign && typeof ribbonDesign === "object" && Array.isArray((ribbonDesign as RibbonDesign).stripes)
? (ribbonDesign as RibbonDesign)
@ -17,57 +28,13 @@ export const RibbonViewer = ({ ribbonDesign, showRibbonOnly }: { ribbonDesign: R
const [design] = useState<RibbonDesign>(initial);
const { stripes, devices, mirrored } = design;
if (stripes.length === 0) return null;
const displayStripes = mirrored ? [...stripes, ...stripes.slice(0, -1).reverse()] : stripes;
const totalWeight = displayStripes.reduce((sum, s) => sum + s.width, 0);
const viewWidth = RIBBON_CONSTANTS.RIBBON_WIDTH;
const viewHeight = RIBBON_CONSTANTS.PREVIEW_HEIGHT;
return (
<svg
viewBox={`0 0 ${viewWidth} ${viewHeight}`}
<RibbonArt
design={design}
tier={tier}
className={cn("h-auto max-h-20", {
"w-full rounded border border-zinc-700 bg-zinc-950": !showRibbonOnly
} )}
>
<rect x={0} y={0} width={viewWidth} height={viewHeight} rx={2} fill="#18181b" />
{(() => {
let x = 0;
return displayStripes.map((stripe, i) => {
const w = (stripe.width / totalWeight) * viewWidth;
const el = <rect key={i} x={x} y={0} width={w} height={viewHeight} fill={stripe.color} />;
x += w;
return el;
});
})()}
<image href="/images/ribbon-overlay.png" className="mix-blend-multiply w-full" />
{devices.map((device) => {
const info = RIBBON_DEVICE_INFO[device.type];
const cx = (device.position / 100) * viewWidth;
const cy = (device.positionY / 100) * viewHeight;
const fontSize = Math.min(viewHeight * 0.45, 24);
return (
<text
key={device.id}
x={cx}
y={cy}
textAnchor="middle"
dominantBaseline="central"
fill="#facc15"
fontSize={fontSize}
fontFamily="serif"
style={{ pointerEvents: "none" }}
className="text-shadow-sm text-shadow-black"
>
{info.symbol}
</text>
);
"w-full rounded border border-zinc-700 bg-zinc-950": !showRibbonOnly,
})}
</svg>
/>
);
};

View file

@ -114,7 +114,7 @@ export function RibbonStudio() {
<div className="flex min-w-0 flex-col gap-5">
<div className="flex flex-col gap-2">
<Label>Preview</Label>
<RibbonPreview design={design} />
<RibbonPreview design={design} allowTierPreview />
</div>
<StripeEditor
stripes={design.stripes}

View file

@ -99,6 +99,11 @@ export const sidebarData = {
url: "/operations/reservations",
icon: ClipboardList,
},
{
title: "Extractions",
url: "/operations/extractions",
icon: ClipboardCheck,
},
],
navLogistics: [
{

View file

@ -36,7 +36,7 @@ import {
type MissionMarker,
} from "@/lib/arma-markers/missionMarkers";
import { cn } from "@/lib/utils";
import { MarkerTypePicker } from "./MarkerTypePicker";
import { MarkerTypePicker } from "@/components/frontend/markers/MarkerTypePicker";
import type { MarkerStyle, PlanTool } from "./types";
const TOOLS: { value: PlanTool; label: string; icon: typeof MapPinIcon; hint: string }[] = [

View file

@ -19,7 +19,15 @@ 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 type { MapObjectiveFeature } from "@/lib/map/types";
import { GridLayer } from "@/components/frontend/map/GridLayer";
import { ObjectiveLayer } from "@/components/frontend/map/objectives/ObjectiveLayer";
import {
NodeReferenceLayer,
RangeReferenceLayer,
ShipmentReferenceLayer,
StructureReferenceLayer,
} from "./PlanningFeatureLayers";
import { markerBrushOf, resolveMarkerRgba, rgbaToHex } from "@/lib/arma-markers";
import {
areaOutline,
@ -28,24 +36,37 @@ import {
type MissionMarker,
type MissionMarkerData,
} from "@/lib/arma-markers/missionMarkers";
import { markerDivIcon } from "./markerIcon";
import { markerDivIcon } from "@/components/frontend/markers/markerIcon";
import type { MarkerStyle, PlanTool } from "./types";
export interface MissionMapCanvasProps {
mapId: number;
markers: MissionMarker[];
objectives: MapObjectiveFeature[];
selectedId: number | null;
tool: PlanTool;
style: MarkerStyle;
canEdit: boolean;
/** Superuser tier: objectives are editable from this canvas too. */
canManageObjectives: boolean;
/** Armed objective placement mode: the next map click picks a position. */
objectiveArmed: boolean;
showRoads: boolean;
showZones: boolean;
showGrid: boolean;
showStructures: boolean;
showNodes: boolean;
showShipments: boolean;
showRanges: 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;
onObjectivePlace: (point: MapPoint) => void;
onEditObjective: (objective: MapObjectiveFeature) => void;
onObjectiveUpdated: (objective: MapObjectiveFeature) => void;
onObjectiveDeleted: (id: number) => void;
onLoaded: (info: {
worldWidth: number;
worldHeight: number;
@ -519,29 +540,54 @@ function LineHandles({
);
}
/** Objective placement: the next map click picks the marker position. */
function ObjectivePlaceHandler({ onPick }: { onPick: (point: MapPoint) => void }) {
useMapEvents({
click: (event) => {
onPick([Math.round(event.latlng.lng), Math.round(-event.latlng.lat)]);
},
});
return null;
}
export function MissionMapCanvas({
mapId,
markers,
objectives,
selectedId,
tool,
style,
canEdit,
canManageObjectives,
objectiveArmed,
showRoads,
showZones,
showGrid,
showStructures,
showNodes,
showShipments,
showRanges,
onSelect,
onCreate,
onChange,
onCursor,
onObjectivePlace,
onEditObjective,
onObjectiveUpdated,
onObjectiveDeleted,
onLoaded,
}: MissionMapCanvasProps) {
const [features, setFeatures] = useState<MapFeaturesResponse | null>(null);
const [error, setError] = useState<string | null>(null);
const layerClickAt = useRef(0);
// Reference layers (structures/nodes/shipments/ranges) need the heavy
// logistics queries; base-only keeps the planning map fast until asked.
const includeLogistics = showStructures || showNodes || showShipments || showRanges;
useEffect(() => {
let cancelled = false;
fetch(`/api/map-features?mapId=${mapId}&layers=base`, { cache: "no-store" })
const suffix = includeLogistics ? "" : "&layers=base";
fetch(`/api/map-features?mapId=${mapId}${suffix}`, { cache: "no-store" })
.then(async (response) => {
if (!response.ok) {
const body = (await response.json().catch(() => null)) as { error?: string } | null;
@ -568,7 +614,7 @@ export function MissionMapCanvas({
return () => {
cancelled = true;
};
}, [mapId, onLoaded]);
}, [mapId, onLoaded, includeLogistics]);
const mapConfig = features?.map ?? null;
const worldW = mapConfig?.worldSizeWidth ?? 8192;
@ -692,6 +738,11 @@ export function MissionMapCanvas({
<Polyline key={`road-${road.id}`} positions={positions} pathOptions={options} />
))}
{features && showStructures && <StructureReferenceLayer structures={features.structures} />}
{features && showNodes && <NodeReferenceLayer nodes={features.nodes} />}
{features && showShipments && <ShipmentReferenceLayer shipments={features.shipments} />}
{features && showRanges && <RangeReferenceLayer structures={features.structures} />}
{markers.map((marker) => {
if (marker.shape === "rectangle" || marker.shape === "ellipse") {
return (
@ -764,6 +815,16 @@ export function MissionMapCanvas({
<LineHandles marker={selected} onChange={onChange} />
)}
<ObjectiveLayer
objectives={objectives}
canManage={canManageObjectives}
onEdit={onEditObjective}
onUpdated={onObjectiveUpdated}
onDeleted={onObjectiveDeleted}
/>
{objectiveArmed && <ObjectivePlaceHandler onPick={onObjectivePlace} />}
<PlanInteractions
tool={tool}
canEdit={canEdit}

View file

@ -3,10 +3,17 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { ClipboardCopyIcon, EraserIcon, MapIcon, PowerOffIcon } from "lucide-react";
import {
ClipboardCopyIcon,
EraserIcon,
LayersIcon,
MapIcon,
PowerOffIcon,
TargetIcon,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import {
AlertDialog,
AlertDialogAction,
@ -31,6 +38,10 @@ import {
} from "@/lib/arma-markers/missionMarkers";
import { DEFAULT_MAP_GRID, gridRef, type MapGridConfig } from "@/lib/map/grid";
import type { MapPoint } from "@/lib/map/points";
import type { MapObjectiveFeature } from "@/lib/map/types";
import { getMapObjectives } from "@/app/(frontend)/map/actions";
import { objectiveToMarker } from "@/components/frontend/map/objectives/objectiveVisuals";
import { ObjectiveDialog } from "@/components/frontend/map/objectives/ObjectiveDialog";
import {
clearMissionMapMarkers,
deleteMissionMapMarker,
@ -50,14 +61,68 @@ export interface MissionPlanningMapProps {
canEdit: boolean;
/** Can manage the map itself: toggle it, clear all markers. Defaults to canEdit. */
canCurate?: boolean;
/** Superuser tier: may author strategic objectives from this map too. */
canManageObjectives?: boolean;
/** True once the mission is terminal: the map is frozen read-only. */
locked?: boolean;
map: { id: number; name: string; worldWidth: number; worldHeight: number };
initialMarkers: MissionMarker[];
/** Objectives for this mission's map, already filtered for the viewer. */
initialObjectives?: MapObjectiveFeature[];
}
const SAVE_DEBOUNCE_MS = 400;
const POLL_MS = 30_000;
const LAYERS_KEY = "ptf:plan-layers:v1";
type PlanLayers = {
grid: boolean;
roads: boolean;
zones: boolean;
objectives: boolean;
structures: boolean;
nodes: boolean;
shipments: boolean;
ranges: boolean;
};
const DEFAULT_LAYERS: PlanLayers = {
grid: true,
roads: true,
zones: true,
objectives: true,
structures: false,
nodes: false,
shipments: false,
ranges: false,
};
const LAYER_ROWS: { key: keyof PlanLayers; label: string }[] = [
{ key: "objectives", label: "Objectives" },
{ key: "structures", label: "Structures" },
{ key: "nodes", label: "Resource nodes" },
{ key: "shipments", label: "Shipments" },
{ key: "ranges", label: "Ranges" },
{ key: "grid", label: "Grid" },
{ key: "roads", label: "Roads" },
{ key: "zones", label: "Zones" },
];
function readStoredLayers(): PlanLayers {
if (typeof window === "undefined") return DEFAULT_LAYERS;
try {
const raw = window.localStorage.getItem(LAYERS_KEY);
if (!raw) return DEFAULT_LAYERS;
const parsed = JSON.parse(raw) as Record<string, unknown>;
const next = { ...DEFAULT_LAYERS };
for (const key of Object.keys(DEFAULT_LAYERS) as (keyof PlanLayers)[]) {
if (typeof parsed[key] === "boolean") next[key] = parsed[key] as boolean;
}
return next;
} catch {
return DEFAULT_LAYERS;
}
}
const DEFAULT_STYLE: MarkerStyle = {
markerType: DEFAULT_MARKER_TYPE,
@ -107,22 +172,28 @@ export function MissionPlanningMap({
enabled,
canEdit,
canCurate = canEdit,
canManageObjectives = false,
locked = false,
map,
initialMarkers,
initialObjectives = [],
}: MissionPlanningMapProps) {
const router = useRouter();
const [markers, setMarkers] = useState<MissionMarker[]>(initialMarkers);
const [objectives, setObjectives] = useState<MapObjectiveFeature[]>(initialObjectives);
const [selectedId, setSelectedId] = useState<number | null>(null);
const [tool, setTool] = useState<PlanTool>("select");
const [style, setStyle] = useState<MarkerStyle>(DEFAULT_STYLE);
const [cursor, setCursor] = useState<MapPoint | null>(null);
const [showRoads, setShowRoads] = useState(true);
const [showZones, setShowZones] = useState(true);
const [showGrid, setShowGrid] = useState(true);
const [layers, setLayers] = useState<PlanLayers>(DEFAULT_LAYERS);
const [world, setWorld] = useState({ width: map.worldWidth, height: map.worldHeight });
const [gridConfig, setGridConfig] = useState<MapGridConfig>(DEFAULT_MAP_GRID);
const [toggling, setToggling] = useState(false);
// Objective authoring (superuser tier only).
const [objectiveArmed, setObjectiveArmed] = useState(false);
const [objectiveDialogOpen, setObjectiveDialogOpen] = useState(false);
const [objectivePoint, setObjectivePoint] = useState<MapPoint | null>(null);
const [editingObjective, setEditingObjective] = useState<MapObjectiveFeature | null>(null);
const timers = useRef(new Map<number, ReturnType<typeof setTimeout>>());
const inflight = useRef(new Map<number, Promise<unknown>>());
@ -137,6 +208,24 @@ export function MissionPlanningMap({
}
}, [missionId]);
const refreshObjectives = useCallback(async () => {
const result = await getMapObjectives({ mapId: map.id });
if (result.success && result.data) setObjectives(result.data);
}, [map.id]);
// Layer choices survive reloads: planning sessions tend to repeat.
useEffect(() => {
setLayers(readStoredLayers());
}, []);
useEffect(() => {
try {
window.localStorage.setItem(LAYERS_KEY, JSON.stringify(layers));
} catch {
// Private mode / blocked storage: layer choices simply do not persist.
}
}, [layers]);
// Background refresh picks up other editors' changes, but never while a
// local edit is pending (it would snap the marker back mid-edit).
useEffect(() => {
@ -148,10 +237,11 @@ export function MissionPlanningMap({
document.visibilityState === "visible"
) {
void refresh();
void refreshObjectives();
}
}, POLL_MS);
return () => clearInterval(timer);
}, [enabled, refresh]);
}, [enabled, refresh, refreshObjectives]);
useEffect(() => {
const pending = timers.current;
@ -308,8 +398,15 @@ export function MissionPlanningMap({
const exportSqf = async () => {
try {
await navigator.clipboard.writeText(markersToSqf(markers, world.height));
toast.success(`Copied ${markers.length} markers as SQF.`, {
const exportMarkers: MissionMarker[] = [
...markers,
...objectives.map((objective) => ({
...objectiveToMarker(objective),
text: objective.name,
})),
];
await navigator.clipboard.writeText(markersToSqf(exportMarkers, world.height));
toast.success(`Copied ${exportMarkers.length} markers as SQF.`, {
description: "Paste into the debug console or an init script.",
});
} catch {
@ -334,8 +431,9 @@ export function MissionPlanningMap({
areas: markers.filter((marker) => marker.shape === "rectangle" || marker.shape === "ellipse")
.length,
lines: markers.filter((marker) => marker.shape === "polyline").length,
objectives: objectives.length,
}),
[markers],
[markers, objectives],
);
const selected = markers.find((marker) => marker.id === selectedId) ?? null;
const ref = String((missionId * 37) % 1000).padStart(3, "0");
@ -373,33 +471,58 @@ 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
htmlFor="plan-roads"
className="font-mono text-[9px] uppercase tracking-widest text-white/60"
>
Roads
</Label>
</label>
<label className="flex items-center gap-1.5">
<Switch size="sm" checked={showZones} onCheckedChange={setShowZones} id="plan-zones" />
<Label
htmlFor="plan-zones"
className="font-mono text-[9px] uppercase tracking-widest text-white/60"
>
Zones
</Label>
</label>
<Popover>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-6 gap-1 px-2 font-mono text-[9px] uppercase tracking-widest text-white/60 hover:text-white"
>
<LayersIcon className="size-3" />
Layers
</Button>
</PopoverTrigger>
<PopoverContent align="end" className="w-52 p-2">
<div className="flex flex-col gap-1.5">
{LAYER_ROWS.map(({ key, label }) => (
<label key={key} className="flex items-center justify-between gap-2">
<span className="font-mono text-[10px] uppercase tracking-widest text-white/70">
{label}
</span>
<Switch
size="sm"
checked={layers[key]}
onCheckedChange={(checked) =>
setLayers((current) => ({ ...current, [key]: checked }))
}
/>
</label>
))}
</div>
{canManageObjectives && (
<div className="mt-2 border-t border-white/10 pt-2">
<Button
size="sm"
variant={objectiveArmed ? "secondary" : "outline"}
className="h-7 w-full justify-start gap-1.5 text-xs"
onClick={() => {
setObjectiveArmed((current) => !current);
setTool("select");
setSelectedId(null);
}}
>
<TargetIcon className="size-3.5" />
{objectiveArmed ? "Cancel placement" : "Add objective"}
</Button>
{objectiveArmed && (
<p className="mt-1.5 text-[10px] leading-snug text-muted-foreground">
Click the map to place the objective marker.
</p>
)}
</div>
)}
</PopoverContent>
</Popover>
<span className="hidden font-mono text-[9px] uppercase tracking-widest text-white/60 sm:inline">
{map.name} // REF {ref}
</span>
@ -409,23 +532,49 @@ export function MissionPlanningMap({
<div className="flex flex-col lg:h-[620px] lg:flex-row">
<div
className="map-host relative h-[480px] min-w-0 flex-1 lg:h-full"
data-mode={canEdit && tool !== "select" ? "crosshair" : undefined}
data-mode={(canEdit && tool !== "select") || objectiveArmed ? "crosshair" : undefined}
>
<Corners />
<MissionMapLoader
mapId={map.id}
markers={markers}
objectives={objectives}
selectedId={selectedId}
tool={canEdit ? tool : "select"}
style={style}
canEdit={canEdit}
showRoads={showRoads}
showZones={showZones}
showGrid={showGrid}
canManageObjectives={canManageObjectives}
objectiveArmed={objectiveArmed}
showRoads={layers.roads}
showZones={layers.zones}
showGrid={layers.grid}
showStructures={layers.structures}
showNodes={layers.nodes}
showShipments={layers.shipments}
showRanges={layers.ranges}
onSelect={setSelectedId}
onCreate={(data) => void handleCreate(data)}
onChange={handleChange}
onCursor={setCursor}
onObjectivePlace={(point) => {
setEditingObjective(null);
setObjectivePoint(point);
setObjectiveDialogOpen(true);
setObjectiveArmed(false);
}}
onEditObjective={(objective) => {
setEditingObjective(objective);
setObjectivePoint(null);
setObjectiveDialogOpen(true);
}}
onObjectiveUpdated={(objective) =>
setObjectives((list) =>
list.map((entry) => (entry.id === objective.id ? objective : entry)),
)
}
onObjectiveDeleted={(id) =>
setObjectives((list) => list.filter((entry) => entry.id !== id))
}
onLoaded={handleLoaded}
/>
</div>
@ -450,38 +599,38 @@ export function MissionPlanningMap({
{canCurate && (
<>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="outline" size="sm" disabled={markers.length === 0}>
<EraserIcon />
Clear all
<AlertDialogTrigger asChild>
<Button variant="outline" size="sm" disabled={markers.length === 0}>
<EraserIcon />
Clear all
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Clear the planning map?</AlertDialogTitle>
<AlertDialogDescription>
This removes all {markers.length} markers from this mission. It cannot be
undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={() => void clearAll()}>
Clear markers
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<Button
variant="ghost"
size="sm"
onClick={() => void toggleEnabled(false)}
disabled={toggling}
title="Hide the planning map from the mission page (markers are kept)"
>
<PowerOffIcon />
Disable
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Clear the planning map?</AlertDialogTitle>
<AlertDialogDescription>
This removes all {markers.length} markers from this mission. It cannot be
undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={() => void clearAll()}>
Clear markers
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<Button
variant="ghost"
size="sm"
onClick={() => void toggleEnabled(false)}
disabled={toggling}
title="Hide the planning map from the mission page (markers are kept)"
>
<PowerOffIcon />
Disable
</Button>
</>
)}
</div>
@ -500,6 +649,7 @@ 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={String(counts.objectives)} label="Objectives" />
<ReadoutCell
value={cursor ? gridRef(cursor, world.height, gridConfig) : "--- ---"}
label="Grid"
@ -514,7 +664,7 @@ export function MissionPlanningMap({
size="sm"
className="h-6 px-2 font-mono text-[10px] uppercase tracking-widest text-white/70"
onClick={() => void exportSqf()}
disabled={markers.length === 0}
disabled={markers.length === 0 && objectives.length === 0}
title="Copy a createMarker script that recreates this plan in Arma 3"
>
<ClipboardCopyIcon className="size-3" />
@ -522,6 +672,29 @@ export function MissionPlanningMap({
</Button>
</div>
</div>
{canManageObjectives && (
<ObjectiveDialog
open={objectiveDialogOpen}
onOpenChange={(open) => {
setObjectiveDialogOpen(open);
if (!open) {
setObjectivePoint(null);
setEditingObjective(null);
}
}}
mapId={map.id}
objective={editingObjective}
position={objectivePoint}
onSaved={(objective, created) =>
setObjectives((list) =>
created
? [...list, objective]
: list.map((entry) => (entry.id === objective.id ? objective : entry)),
)
}
/>
)}
</section>
);
}

View file

@ -0,0 +1,252 @@
"use client";
import Link from "next/link";
import type * as L from "leaflet";
import { Circle, Marker, Polyline, Popup, Tooltip } from "react-leaflet";
import { Button } from "@/components/ui/button";
import {
STRUCTURE_STATUS,
nodeIconFor,
shipmentIcon,
structureStatusIcon,
toLatLng,
} from "@/components/frontend/map/mapIcons";
import { interpolateAlong, type MapPoint } from "@/lib/map/points";
import { splinePolyline } from "@/lib/map/style";
import type { NodeFeature, ShipmentFeature, StructureFeature } from "@/lib/map/types";
const RANGE_RESOURCE_PATH: L.PathOptions = {
color: "#2dd4bf",
dashArray: "4 4",
fillOpacity: 0.03,
weight: 1,
};
const RANGE_STRUCTURE_PATH: L.PathOptions = {
color: "#a78bfa",
dashArray: "4 4",
fillOpacity: 0.03,
weight: 1,
};
const SHIPMENT_PATH: L.PathOptions = {
color: "#22d3ee",
weight: 2,
dashArray: "6 6",
opacity: 0.8,
};
function tonnes(kg: number): string {
return `${Math.round(kg / 100) / 10} t`;
}
/**
* Compact reference layers for mission planning maps. The planning surface is
* read-only for logistics: pins, names and links back to the owning record,
* without the world map's authoring/ribbon machinery.
*/
export function StructureReferenceLayer({ structures }: { structures: StructureFeature[] }) {
return (
<>
{structures.map((structure) => {
const statusKey = structure.constructionStatus ?? "complete";
const label = STRUCTURE_STATUS[statusKey]?.label ?? "Structure";
return (
<Marker
key={`plan-structure-${structure.id}`}
position={toLatLng(structure.point)}
icon={structureStatusIcon(statusKey)}
>
<Tooltip direction="top" offset={[0, -12]} opacity={1} className="map-tooltip-dossier">
<div className="map-tooltip-name">{structure.name}</div>
<div className="map-tooltip-meta">
{label}
{structure.storageCapacityKg != null
? ` // ${tonnes(structure.storageUsedKg)} / ${tonnes(structure.storageCapacityKg)}`
: ""}
</div>
</Tooltip>
<Popup>
<div className="min-w-52 text-sm">
<div className="font-semibold">{structure.name}</div>
<div className="text-xs text-white/60">{label}</div>
{structure.blueprintName && (
<div className="text-xs text-white/60">{structure.blueprintName}</div>
)}
{structure.storageCapacityKg != null && (
<div className="text-xs text-white/60">
Storage {tonnes(structure.storageUsedKg)} /{" "}
{tonnes(structure.storageCapacityKg)}
</div>
)}
{structure.factionName && (
<div className="text-xs text-white/60">Faction {structure.factionName}</div>
)}
<div className="mt-2 border-t border-white/15 pt-2">
<Button asChild size="sm" variant="outline" className="h-7 w-full px-2 text-xs">
<Link href={`/logistics/structures/${structure.id}`}>Open structure</Link>
</Button>
</div>
</div>
</Popup>
</Marker>
);
})}
</>
);
}
export function NodeReferenceLayer({ nodes }: { nodes: NodeFeature[] }) {
return (
<>
{nodes.map((node) => (
<Marker
key={`plan-node-${node.id}`}
position={toLatLng(node.point)}
icon={nodeIconFor(node.icon)}
>
<Tooltip direction="top" offset={[0, -10]} opacity={1} className="map-tooltip-dossier">
<div className="map-tooltip-name">{node.name}</div>
{node.resources.length > 0 && (
<div className="map-tooltip-meta">
{node.resources.map((entry) => entry.name).join(", ")}
</div>
)}
</Tooltip>
<Popup>
<div className="min-w-44 text-sm">
<div className="font-semibold">{node.name}</div>
{node.resources.length > 0 ? (
<div className="text-xs text-white/60">
Resources: {node.resources.map((entry) => entry.name).join(", ")}
</div>
) : (
<div className="text-xs text-white/60">Plain marker node</div>
)}
{node.richness != null && node.resources.length > 0 && (
<div className="text-xs text-white/60">Richness {node.richness}</div>
)}
{node.description && <p className="mt-1 text-xs text-white/70">{node.description}</p>}
</div>
</Popup>
</Marker>
))}
</>
);
}
function shipmentPoint(shipment: ShipmentFeature): {
point: MapPoint;
bearing: number;
} | null {
const path = shipment.routePath;
if (!path || path.length < 2) return null;
const start = shipment.dispatchedAt ? new Date(shipment.dispatchedAt).getTime() : NaN;
const end = shipment.estimatedArrival ? new Date(shipment.estimatedArrival).getTime() : NaN;
const now = Date.now();
const fraction =
Number.isFinite(start) && Number.isFinite(end) && end > start
? Math.min(1, Math.max(0, (now - start) / (end - start)))
: 0.5;
return interpolateAlong(path, fraction);
}
export function ShipmentReferenceLayer({ shipments }: { shipments: ShipmentFeature[] }) {
return (
<>
{shipments.map((shipment) => {
const path = shipment.routePath;
const position = shipmentPoint(shipment);
return (
<FragmentizedShipment
key={`plan-shipment-${shipment.id}`}
shipment={shipment}
path={path}
position={position}
/>
);
})}
</>
);
}
function FragmentizedShipment({
shipment,
path,
position,
}: {
shipment: ShipmentFeature;
path: MapPoint[] | null;
position: { point: MapPoint; bearing: number } | null;
}) {
return (
<>
{path && path.length > 1 && (
<Polyline
positions={splinePolyline(path).map(toLatLng)}
pathOptions={SHIPMENT_PATH}
interactive={false}
/>
)}
{position && (
<Marker position={toLatLng(position.point)} icon={shipmentIcon(position.bearing)}>
<Tooltip direction="top" offset={[0, -14]} opacity={1} className="map-tooltip-dossier">
<div className="map-tooltip-name">{shipment.name ?? `Shipment #${shipment.id}`}</div>
<div className="map-tooltip-meta">
{shipment.originName ?? "unknown"} to {shipment.destinationName ?? "unknown"}
</div>
</Tooltip>
<Popup>
<div className="min-w-48 text-sm">
<div className="font-semibold">{shipment.name ?? `Shipment #${shipment.id}`}</div>
<div className="text-xs capitalize text-white/60">{shipment.status}</div>
<div className="text-xs text-white/60">
{shipment.originName ?? "unknown"} to {shipment.destinationName ?? "unknown"}
</div>
{shipment.vehicleName && (
<div className="text-xs text-white/60">Vehicle {shipment.vehicleName}</div>
)}
<div className="mt-2 border-t border-white/15 pt-2">
<Button asChild size="sm" variant="outline" className="h-7 w-full px-2 text-xs">
<Link href={`/logistics/shipments/${shipment.id}`}>Open shipment</Link>
</Button>
</div>
</div>
</Popup>
</Marker>
)}
</>
);
}
/** Resource/structure range circles for structures on this map. */
export function RangeReferenceLayer({ structures }: { structures: StructureFeature[] }) {
return (
<>
{structures.flatMap((structure) =>
[
...structure.resourcesInRange.map((requirement) => ({
kind: "resource" as const,
range: requirement.range ?? 0,
})),
...structure.structuresInRange.map((requirement) => ({
kind: "structure" as const,
range: requirement.range ?? 0,
})),
]
.filter((requirement) => requirement.range > 0)
.map((requirement, index) => (
<Circle
key={`plan-range-${structure.id}-${requirement.kind}-${index}`}
center={toLatLng(structure.point)}
radius={requirement.range}
interactive={false}
pathOptions={
requirement.kind === "resource" ? RANGE_RESOURCE_PATH : RANGE_STRUCTURE_PATH
}
/>
)),
)}
</>
);
}

View file

@ -1,151 +1,159 @@
"use client";
import Link from "next/link";
import {
Item,
ItemContent,
ItemDescription,
ItemHeader,
ItemMedia,
ItemTitle,
} from "@/components/ui/item";
import { convertLexicalToPlaintext } from "@payloadcms/richtext-lexical/plaintext";
import { ChevronRightIcon, HeartIcon, TimerIcon, TruckIcon } from "lucide-react";
import { ChevronRightIcon } from "lucide-react";
import type { Vehicle } from "@/payload-types";
import { cn } from "@/lib/utils";
import { categoryLabel, categoryPillClasses } from "@/lib/vehicles/categories";
interface VehicleCardProps {
vehicle: {
id: number;
name: string;
classname?: string | null;
category?: string[] | null;
description?: {
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;
image?: { url: string } | number | null;
construction?: {
materials?: { resource: { name: string } | number; amount: number }[];
constructionTime?: number;
};
combat?: {
maxHealth?: number;
maxSpeedOnRoad?: number;
};
};
vehicle: Vehicle;
}
const categoryColors: Record<string, string> = {
civilian: "bg-stone-500/20 text-stone-400",
utility: "bg-emerald-500/20 text-emerald-400",
transport: "bg-blue-500/20 text-blue-400",
weaponized: "bg-red-500/20 text-red-400",
military: "bg-amber-500/20 text-amber-400",
};
const categoryLabels: Record<string, string> = {
civilian: "Civilian",
utility: "Utility",
transport: "Transport",
weaponized: "Weaponized",
military: "Military",
};
/**
* Tactical dossier vehicle card (Battlefield-style registry tile): squared
* corners, classification strip, corner brackets, darkened cover imagery,
* faint grid, and a permanent readout footer. The reference implementation is
* CampaignCard (`intelligence/CampaignCard.tsx`); per its convention this card
* omits the opt-in glitch motion, keeping the treatment calm for a data grid.
*/
export function VehicleCard({ vehicle }: VehicleCardProps) {
const image = vehicle.image && typeof vehicle.image === "object" ? vehicle.image : null;
const imageUrl =
vehicle.image && typeof vehicle.image === "object" ? (vehicle.image.url ?? null) : null;
const description = vehicle.description
? convertLexicalToPlaintext({ data: vehicle.description })
: null;
const truncatedDescription =
description && description.length > 150 ? description.slice(0, 150) + "…" : description;
description && description.length > 160 ? description.slice(0, 160) + "…" : description;
const materialCount = vehicle.construction?.materials?.length ?? 0;
const constructionTime = vehicle.construction?.constructionTime;
const maxHealth = vehicle.combat?.maxHealth;
const maxSpeed = vehicle.combat?.maxSpeedOnRoad;
const categories = vehicle.category ?? [];
// Vehicle stats are flat on the document (Payload tabs flatten into the
// parent), which the previous nested access got wrong and `as any` hid.
const materialCount = vehicle.materials?.length ?? 0;
const constructionTime = vehicle.constructionTime ?? null;
const maxHealth = vehicle.maxHealth ?? null;
const maxSpeed = vehicle.maxSpeedOnRoad ?? null;
const refCode = String(vehicle.id).padStart(3, "0");
const stripLabel =
categories.length > 0
? categories.map((c) => c.toUpperCase()).slice(0, 2).join(" / ")
: "UNCLASSIFIED";
const readoutCells = [
maxHealth != null && { label: "Integrity", value: maxHealth.toLocaleString() },
maxSpeed != null && { label: "Road", value: `${maxSpeed} km/h` },
materialCount > 0 && { label: "Mats", value: String(materialCount) },
constructionTime != null && {
label: "Build",
value: `${constructionTime} tick${constructionTime !== 1 ? "s" : ""}`,
},
].filter(Boolean) as { label: string; value: string }[];
return (
<Link href={`/logistics/vehicles/${vehicle.id}`}>
<Item
variant="outline"
className="cursor-pointer group transition-all duration-200 hover:scale-[1.01] hover:[box-shadow:inset_0_2px_8px_rgba(255,255,255,0.33)]"
>
<ItemHeader>
<div className="flex items-center gap-2">
{image ? (
<ItemMedia variant="image">
<img src={image.url} alt={vehicle.name} className="size-full object-cover" />
</ItemMedia>
) : (
<ItemMedia variant="icon">
<TruckIcon />
</ItemMedia>
)}
<ItemTitle className="flex flex-col">
{vehicle.classname && (
<span className="font-mono text-xs text-muted-foreground">{vehicle.classname}</span>
)}
<span>{vehicle.name}</span>
</ItemTitle>
</div>
<div className="flex items-center gap-2">
{vehicle.category?.map((cat) => (
<Link
href={`/logistics/vehicles/${vehicle.id}`}
aria-label={`Open vehicle ${vehicle.name}`}
className="block rounded-lg 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 min-h-[10rem] flex-col overflow-hidden rounded-none border border-border/70 bg-card transition-colors duration-300 hover:border-foreground/30">
{/* Darkened cover imagery with gradient scrim */}
<div aria-hidden="true" className="absolute inset-0">
{imageUrl ? (
<img
src={imageUrl}
alt=""
className="absolute inset-0 size-full object-cover opacity-15 transition-opacity duration-500 ease-out group-hover:opacity-25 motion-reduce:transition-none"
/>
) : (
<div className="absolute inset-0 bg-gradient-to-br from-muted to-muted/50 opacity-30" />
)}
<div className="absolute inset-0 bg-gradient-to-t from-black/85 via-black/60 to-black/25" />
</div>
{/* Faint grid texture, constant opacity */}
<div
aria-hidden="true"
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)",
backgroundSize: "28px 28px",
}}
/>
{/* Classification strip */}
<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-5 py-1.5 backdrop-blur-sm"
>
<span className="font-mono text-[9px] uppercase tracking-widest text-white/60">
Vehicle Registry // {stripLabel}
</span>
<span className="font-mono text-[9px] uppercase tracking-widest text-white/60">
REF {refCode}
</span>
</div>
{/* Corner brackets, brightening on hover */}
<div aria-hidden="true" className="pointer-events-none absolute inset-2 z-30">
<span className="absolute left-0 top-0 size-3 border-l border-t border-white/25 transition-colors duration-300 group-hover:border-white/60 motion-reduce:transition-none" />
<span className="absolute right-0 top-0 size-3 border-r border-t border-white/25 transition-colors duration-300 group-hover:border-white/60 motion-reduce:transition-none" />
<span className="absolute bottom-0 left-0 size-3 border-b border-l border-white/25 transition-colors duration-300 group-hover:border-white/60 motion-reduce:transition-none" />
<span className="absolute bottom-0 right-0 size-3 border-b border-r border-white/25 transition-colors duration-300 group-hover:border-white/60 motion-reduce:transition-none" />
</div>
{/* Body */}
<div className="relative z-10 flex flex-1 flex-col gap-1.5 px-5 pb-3 pt-8">
<div className="flex flex-wrap items-center gap-1.5">
{categories.map((cat) => (
<span
key={cat}
className={`text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded ${categoryColors[cat] ?? "bg-muted text-muted-foreground"}`}
className={cn(
"rounded-sm px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-widest",
categoryPillClasses(cat),
)}
>
{categoryLabels[cat] ?? cat}
{categoryLabel(cat)}
</span>
))}
</div>
</ItemHeader>
<ItemContent>
<div className="flex flex-col gap-3 w-full">
{truncatedDescription && (
<p className="text-sm text-muted-foreground line-clamp-2">{truncatedDescription}</p>
)}
<div className="flex flex-wrap items-center gap-x-4 gap-y-1.5 text-xs text-muted-foreground">
{materialCount > 0 && (
<span className="flex items-center gap-1">
{materialCount} material{materialCount !== 1 ? "s" : ""}
{constructionTime != null && (
<>
, <TimerIcon className="size-3" />
{constructionTime} tick{constructionTime !== 1 ? "s" : ""}
</>
)}
</span>
)}
{maxHealth != null && (
<span className="flex items-center gap-1">
<HeartIcon className="size-3" />
{maxHealth.toLocaleString()} HP
</span>
)}
{maxSpeed != null && (
<span className="flex items-center gap-1">
<TruckIcon className="size-3" />
{maxSpeed} km/h
</span>
{vehicle.classname && (
<p className="font-mono text-[10px] uppercase tracking-widest text-white/50">
{vehicle.classname}
</p>
)}
<h3 className="text-balance text-lg font-bold leading-snug text-white drop-shadow">
{vehicle.name}
</h3>
{truncatedDescription && (
<p className="line-clamp-2 max-w-prose text-pretty text-xs leading-relaxed text-white/60 drop-shadow">
{truncatedDescription}
</p>
)}
</div>
{/* Permanent readout footer */}
<div className="relative z-10 mt-auto flex items-stretch border-t border-white/15 bg-black/60 backdrop-blur-sm">
{readoutCells.map((cell, i) => (
<div
key={cell.label}
className={cn(
"flex-1 px-3 py-1.5",
i !== readoutCells.length - 1 && "border-r border-white/15",
)}
>
<p className="font-mono text-xs tabular-nums text-white/80">{cell.value}</p>
<p className="text-[9px] uppercase tracking-wider text-white/50">{cell.label}</p>
</div>
</div>
</ItemContent>
<ItemDescription>{truncatedDescription ?? vehicle.classname ?? "Vehicle"}</ItemDescription>
<span className="text-xs text-muted-foreground group-hover:text-primary transition-colors flex items-center gap-1">
View details <ChevronRightIcon className="size-3" />
</span>
</Item>
))}
<span className="flex items-center gap-1 py-1.5 pl-3 pr-4 font-mono text-[9px] uppercase tracking-widest text-white/40 transition-colors group-hover:text-white/70 motion-reduce:transition-none">
Open
<ChevronRightIcon className="size-3" />
</span>
</div>
</article>
</Link>
);
}

View file

@ -12,7 +12,9 @@ const categoryLabels: Record<string, string> = {
civilian: "Civilian",
utility: "Utility",
transport: "Transport",
drone: "Drone",
weaponized: "Weaponized",
static: "Static",
military: "Military",
};

View file

@ -19,7 +19,7 @@ import {
useMapEvents,
} from "react-leaflet";
import Link from "next/link";
import { Hammer, Pencil, RefreshCw } from "lucide-react";
import { Hammer, Pencil, RefreshCw, Target } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useGameTick } from "@/hooks/useGameTick";
import {
@ -51,15 +51,29 @@ import { GridLayer } from "./GridLayer";
import { PlacementDialog } from "./PlacementDialog";
import { AuthoringToolbar, useMapAuthoring } from "./AuthoringToolbar";
import { StructureDetailDrawer } from "./StructureDetailDrawer";
import { nodeIconOption } from "@/lib/map/nodeIcons";
import {
STRUCTURE_STATUS,
STRUCTURE_SVG_PATHS,
dossierSvg,
escapeHtml,
nodeIconFor,
shipmentIcon,
toLatLng,
} from "./mapIcons";
import { ObjectiveLayer } from "./objectives/ObjectiveLayer";
import { ObjectiveDialog } from "./objectives/ObjectiveDialog";
import type { MapObjectiveFeature } from "@/lib/map/types";
export interface MapClientProps {
map: { id: number; name: string };
canAuthor: { roads: boolean; zones: boolean; nodes: boolean };
canPlace: boolean;
/** Superuser tier: may add, move, retitle and reveal strategic objectives. */
canManageObjectives: boolean;
}
type LayerToggles = {
objectives: boolean;
structures: boolean;
nodes: boolean;
roads: boolean;
@ -69,12 +83,6 @@ type LayerToggles = {
grid: boolean;
};
const STRUCTURE_STATUS: Record<string, { color: string; label: string }> = {
complete: { color: "#34d399", label: "Operational" },
building: { color: "#60a5fa", label: "Building" },
awaiting_materials: { color: "#fbbf24", label: "Awaiting materials" },
};
// 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.
@ -146,14 +154,6 @@ const RIBBON_HEIGHT_PX = 32;
const RIBBON_GAP_PX = 6;
const RIBBON_PIN_HALF_PX = STRUCTURE_PIN_SIZES.lg / 2;
function escapeHtml(text: string): string {
return text
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;");
}
const zoneLabelIconCache = new Map<string, L.DivIcon>();
function zoneLabelIcon(name: string): L.DivIcon {
@ -245,65 +245,6 @@ function roadLabelSvgIcon(
});
}
const toLatLng = (p: MapPoint): [number, number] => [-p[1], p[0]];
const NODE_SVG_PATH = '<path d="m8 3 4 8 5-5 5 15H2L8 3z"/>';
const SHIPMENT_SVG_PATH = '<polygon points="3 11 22 2 13 21 11 13 3 11"/>';
const STRUCTURE_SVG_PATHS: Record<string, string> = {
complete:
'<path d="M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z"/><path d="M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2"/><path d="M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"/><path d="M10 6h4"/><path d="M10 10h4"/><path d="M10 14h4"/><path d="M10 18h4"/>',
building:
'<path d="m15 12-8.373 8.373a1 1 0 1 1-3-3L12 9"/><path d="m18 15 4-4"/><path d="m21.5 11.5-1.914-1.914A2 2 0 0 1 19 8.172V7l-2.26-2.26a6 6 0 0 0-4.202-1.756L9 2.96l.92.829A6.018 6.018 0 0 1 12 8.02V10l2 2h1.172a2 2 0 0 1 1.414.586L18.5 14.5"/>',
awaiting_materials:
'<path d="M16.5 9.4 7.55 4.24"/><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.29 7 12 12 20.71 7"/><line x1="12" x2="12" y1="22" y2="12"/>',
};
function dossierSvg(paths: string, color: string, bearingDeg?: number, size = 13): string {
const rotate = bearingDeg != null ? ` transform="rotate(${bearingDeg} 12 12)"` : "";
return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="${color}" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"${rotate}>${paths}</svg>`;
}
const nodeIconCache = new Map<string, L.DivIcon>();
function nodeIconFor(icon: string | null | undefined): L.DivIcon {
const key = icon ?? "marker";
let cached = nodeIconCache.get(key);
if (!cached) {
const option = nodeIconOption(key);
cached = L.divIcon({
className: "map-structure-icon",
html: `<div class="map-structure-pin map-pin-sm" style="border-color:#22d3ee">${dossierSvg(option.path, "#22d3ee")}</div>`,
iconSize: [20, 20],
iconAnchor: [10, 10],
});
nodeIconCache.set(key, cached);
}
return cached;
}
const shipmentIconCache = new Map<number, L.DivIcon>();
function shipmentIcon(bearing: number): L.DivIcon {
const bucket = Math.round(bearing / 5) * 5;
let icon = shipmentIconCache.get(bucket);
if (!icon) {
icon = L.divIcon({
className: "map-structure-icon",
html: `<div class="map-structure-pin" style="border-color:#22d3ee">${dossierSvg(
SHIPMENT_SVG_PATH,
"#22d3ee",
bucket,
)}</div>`,
iconSize: [26, 26],
iconAnchor: [13, 13],
});
shipmentIconCache.set(bucket, icon);
}
return icon;
}
const structureIconCache = new Map<string, L.DivIcon>();
interface StructureRibbon {
@ -356,13 +297,7 @@ function formatEta(estimatedArrival: string | null, nowMs: number): string | nul
return `ETA ${Math.floor(minutes / 60)}h ${minutes % 60}m`;
}
function MousePosition({
grid,
worldHeight,
}: {
grid: MapGridConfig | null;
worldHeight: number;
}) {
function MousePosition({ grid, worldHeight }: { grid: MapGridConfig | null; worldHeight: number }) {
const [position, setPosition] = useState<MapPoint | null>(null);
useMapEvents({
mousemove: (event) => {
@ -1163,12 +1098,13 @@ function ShipmentLayer({ shipments }: { shipments: ShipmentFeature[] }) {
);
}
export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
export function MapClient({ map, canAuthor, canPlace, canManageObjectives }: MapClientProps) {
const canEdit = canAuthor.roads || canAuthor.zones || canAuthor.nodes;
const selectedMapId = map.id;
const [features, setFeatures] = useState<MapFeaturesResponse | null>(null);
const [error, setError] = useState<string | null>(null);
const [toggles, setToggles] = useState<LayerToggles>({
objectives: true,
structures: true,
nodes: true,
roads: true,
@ -1181,6 +1117,11 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
const [mode, setMode] = useState<"view" | "place" | "edit">("view");
const [pendingPoint, setPendingPoint] = useState<MapPoint | null>(null);
const [previewId, setPreviewId] = useState<number | null>(null);
// Strategic objective authoring (superuser tier only).
const [objectiveArmed, setObjectiveArmed] = useState(false);
const [objectiveDialogOpen, setObjectiveDialogOpen] = useState(false);
const [objectivePoint, setObjectivePoint] = useState<MapPoint | null>(null);
const [editingObjective, setEditingObjective] = useState<MapObjectiveFeature | null>(null);
const fetchFeatures = useCallback(async (mapId: number) => {
if (fetchingRef.current) return;
@ -1329,6 +1270,7 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
const layerToggleKeys: { key: keyof LayerToggles; label: string }[] = [
...(mapConfig?.grid.enabled ? [{ key: "grid" as const, label: "Grid" }] : []),
{ key: "objectives", label: "Objectives" },
{ key: "structures", label: "Structures" },
{ key: "nodes", label: "Nodes" },
{ key: "roads", label: "Roads" },
@ -1340,7 +1282,9 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
return (
<div
className="map-host group relative min-h-0 flex-1"
data-mode={mode === "place" || authoring.kind != null ? "crosshair" : undefined}
data-mode={
mode === "place" || authoring.kind != null || objectiveArmed ? "crosshair" : undefined
}
>
<span
aria-hidden
@ -1621,6 +1565,40 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
/>
)}
{features && toggles.objectives && (
<ObjectiveLayer
objectives={features.objectives}
canManage={canManageObjectives}
onEdit={(objective) => {
setEditingObjective(objective);
setObjectivePoint(null);
setObjectiveDialogOpen(true);
}}
onUpdated={(objective) =>
setFeatures((current) =>
current
? {
...current,
objectives: current.objectives.map((entry) =>
entry.id === objective.id ? objective : entry,
),
}
: current,
)
}
onDeleted={(id) =>
setFeatures((current) =>
current
? {
...current,
objectives: current.objectives.filter((entry) => entry.id !== id),
}
: current,
)
}
/>
)}
<MousePosition
grid={mapConfig?.grid.enabled ? mapConfig.grid : null}
worldHeight={worldH}
@ -1631,6 +1609,16 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
<DefaultView key={mapConfig.id} center={center} zoom={mapConfig.defaultZoom ?? 2} />
)}
{mode === "place" && <ClickHandler onPick={setPendingPoint} />}
{objectiveArmed && (
<ClickHandler
onPick={(point) => {
setEditingObjective(null);
setObjectivePoint(point);
setObjectiveDialogOpen(true);
setObjectiveArmed(false);
}}
/>
)}
{mode === "edit" && authoring.kind != null && (
<AuthoringSnapLayer
targets={snapTargets}
@ -1717,6 +1705,7 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
setMode((current) => (current === "place" ? "view" : "place"));
authoring.setKind(null);
setPendingPoint(null);
setObjectiveArmed(false);
}}
>
<Hammer className="size-3.5" />
@ -1724,6 +1713,23 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
</Button>
)}
{canManageObjectives && (
<Button
size="sm"
variant={objectiveArmed ? "secondary" : "outline"}
className="h-8 px-2.5 text-xs"
onClick={() => {
setObjectiveArmed((current) => !current);
setMode("view");
authoring.setKind(null);
setPendingPoint(null);
}}
>
<Target className="size-3.5" />
{objectiveArmed ? "Cancel objective" : "Add objective"}
</Button>
)}
{canEdit && (
<Button
size="sm"
@ -1772,6 +1778,23 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
/>
)}
{canManageObjectives && (
<ObjectiveDialog
open={objectiveDialogOpen}
onOpenChange={(open) => {
setObjectiveDialogOpen(open);
if (!open) {
setObjectivePoint(null);
setEditingObjective(null);
}
}}
mapId={selectedMapId}
objective={editingObjective}
position={objectivePoint}
onSaved={() => void refetchFeatures()}
/>
)}
{previewId != null && (
<StructureDetailDrawer structureId={previewId} onClose={() => setPreviewId(null)} />
)}

View file

@ -0,0 +1,107 @@
/**
* Shared Leaflet icon helpers for map surfaces (world map + mission planning
* maps). Extracted from MapClient so both render the same pin language.
*
* Pure client module: imports Leaflet only.
*/
import L from "leaflet";
import type { MapPoint } from "@/lib/map/points";
import { nodeIconOption } from "@/lib/map/nodeIcons";
export const toLatLng = (p: MapPoint): [number, number] => [-p[1], p[0]];
export function escapeHtml(text: string): string {
return text
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;");
}
export const STRUCTURE_STATUS: Record<string, { color: string; label: string }> = {
complete: { color: "#34d399", label: "Operational" },
building: { color: "#60a5fa", label: "Building" },
awaiting_materials: { color: "#fbbf24", label: "Awaiting materials" },
};
export const NODE_SVG_PATH = '<path d="m8 3 4 8 5-5 5 15H2L8 3z"/>';
export const SHIPMENT_SVG_PATH = '<polygon points="3 11 22 2 13 21 11 13 3 11"/>';
export const STRUCTURE_SVG_PATHS: Record<string, string> = {
complete:
'<path d="M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z"/><path d="M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2"/><path d="M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"/><path d="M10 6h4"/><path d="M10 10h4"/><path d="M10 14h4"/><path d="M10 18h4"/>',
building:
'<path d="m15 12-8.373 8.373a1 1 0 1 1-3-3L12 9"/><path d="m18 15 4-4"/><path d="m21.5 11.5-1.914-1.914A2 2 0 0 1 19 8.172V7l-2.26-2.26a6 6 0 0 0-4.202-1.756L9 2.96l.92.829A6.018 6.018 0 0 1 12 8.02V10l2 2h1.172a2 2 0 0 1 1.414.586L18.5 14.5"/>',
awaiting_materials:
'<path d="M16.5 9.4 7.55 4.24"/><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.29 7 12 12 20.71 7"/><line x1="12" x2="12" y1="22" y2="12"/>',
};
export function dossierSvg(paths: string, color: string, bearingDeg?: number, size = 13): string {
const rotate = bearingDeg != null ? ` transform="rotate(${bearingDeg} 12 12)"` : "";
return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="${color}" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"${rotate}>${paths}</svg>`;
}
const nodeIconCache = new Map<string, L.DivIcon>();
export function nodeIconFor(icon: string | null | undefined): L.DivIcon {
const key = icon ?? "marker";
let cached = nodeIconCache.get(key);
if (!cached) {
const option = nodeIconOption(key);
cached = L.divIcon({
className: "map-structure-icon",
html: `<div class="map-structure-pin map-pin-sm" style="border-color:#22d3ee">${dossierSvg(option.path, "#22d3ee")}</div>`,
iconSize: [20, 20],
iconAnchor: [10, 10],
});
nodeIconCache.set(key, cached);
}
return cached;
}
const shipmentIconCache = new Map<number, L.DivIcon>();
export function shipmentIcon(bearing: number): L.DivIcon {
const bucket = Math.round(bearing / 5) * 5;
let icon = shipmentIconCache.get(bucket);
if (!icon) {
icon = L.divIcon({
className: "map-structure-icon",
html: `<div class="map-structure-pin" style="border-color:#22d3ee">${dossierSvg(
SHIPMENT_SVG_PATH,
"#22d3ee",
bucket,
)}</div>`,
iconSize: [26, 26],
iconAnchor: [13, 13],
});
shipmentIconCache.set(bucket, icon);
}
return icon;
}
const structureStatusIconCache = new Map<string, L.DivIcon>();
/**
* Compact status pin for surfaces that show structures as reference only
* (mission planning maps). The world map uses its richer ribboned variant.
*/
export function structureStatusIcon(statusKey: string | null | undefined): L.DivIcon {
const key = statusKey && STRUCTURE_STATUS[statusKey] ? statusKey : "complete";
let icon = structureStatusIconCache.get(key);
if (!icon) {
const meta = STRUCTURE_STATUS[key];
icon = L.divIcon({
className: "map-structure-icon",
html: `<div class="map-structure-pin map-pin-sm" style="border-color:${meta.color}">${dossierSvg(
STRUCTURE_SVG_PATHS[key] ?? STRUCTURE_SVG_PATHS.complete,
meta.color,
)}</div>`,
iconSize: [20, 20],
iconAnchor: [10, 10],
});
structureStatusIconCache.set(key, icon);
}
return icon;
}

View file

@ -0,0 +1,274 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { MarkerTypePicker } from "@/components/frontend/markers/MarkerTypePicker";
import {
DEFAULT_OBJECTIVE_MARKER_TYPE,
MAP_OBJECTIVE_STATUSES,
OBJECTIVE_STATUS_META,
MAX_OBJECTIVE_DESCRIPTION,
MAX_OBJECTIVE_NAME,
type MapObjectiveStatus,
} from "@/lib/map/objectiveTypes";
import type { MapObjectiveFeature } from "@/lib/map/types";
import type { MapPoint } from "@/lib/map/points";
import { saveMapObjective } from "@/app/(frontend)/map/actions";
import { objectiveHex } from "./objectiveVisuals";
export interface ObjectiveDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
mapId: number;
/** Existing objective when editing, null when creating. */
objective: MapObjectiveFeature | null;
/** Placement point for a new objective (ignored when editing). */
position: MapPoint | null;
onSaved: (objective: MapObjectiveFeature, created: boolean) => void;
}
interface Draft {
name: string;
description: string;
markerType: string;
status: MapObjectiveStatus;
redacted: boolean;
}
const EMPTY_DRAFT: Draft = {
name: "",
description: "",
markerType: DEFAULT_OBJECTIVE_MARKER_TYPE,
status: "active",
redacted: false,
};
function Corners() {
const base = "pointer-events-none absolute size-3 border-white/25";
return (
<>
<span aria-hidden className={`${base} left-2 top-2 border-l border-t`} />
<span aria-hidden className={`${base} right-2 top-2 border-r border-t`} />
<span aria-hidden className={`${base} bottom-2 left-2 border-b border-l`} />
<span aria-hidden className={`${base} bottom-2 right-2 border-b border-r`} />
</>
);
}
function FieldLabel({ children }: { children: React.ReactNode }) {
return (
<span className="font-mono text-[9px] uppercase tracking-widest text-white/60">{children}</span>
);
}
/**
* Superuser authoring dialog for strategic objectives (tactical dossier
* surface: classification strip, corner brackets, mono labels). Used by both
* the world map and mission planning maps.
*/
export function ObjectiveDialog({
open,
onOpenChange,
mapId,
objective,
position,
onSaved,
}: ObjectiveDialogProps) {
const [draft, setDraft] = useState<Draft>(EMPTY_DRAFT);
const [saving, setSaving] = useState(false);
useEffect(() => {
if (!open) return;
setDraft(
objective
? {
name: objective.name,
description: objective.description ?? "",
markerType: objective.markerType,
status: objective.status,
redacted: objective.redacted,
}
: EMPTY_DRAFT,
);
}, [open, objective]);
const point = objective?.position ?? position;
const swatch = useMemo(() => objectiveHex(draft.status), [draft.status]);
const canSave = draft.name.trim().length > 0 && point !== null && !saving;
const submit = async () => {
if (!point) {
toast.error("Pick a position on the map first.");
return;
}
setSaving(true);
try {
const result = await saveMapObjective({
mapId,
id: objective?.id ?? null,
objective: {
name: draft.name,
description: draft.description,
markerType: draft.markerType,
status: draft.status,
redacted: draft.redacted,
position: point,
},
});
if (!result.success || !result.data) {
toast.error(result.error ?? "Failed to save the objective.");
return;
}
onSaved(result.data, !objective);
toast.success(objective ? `Updated ${result.data.name}.` : `Added ${result.data.name}.`);
onOpenChange(false);
} finally {
setSaving(false);
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="gap-0 overflow-hidden rounded-none border-white/15 bg-background p-0 sm:max-w-lg">
<div className="flex items-center justify-between gap-3 border-b border-white/15 bg-black/50 px-3 py-1.5">
<span className="font-mono text-[9px] uppercase tracking-widest text-white/60">
Objective control // {objective ? "amend" : "new"}
</span>
<span className="font-mono text-[9px] uppercase tracking-widest text-white/60">
{objective ? `REF ${String(objective.id).padStart(3, "0")}` : "REF ---"}
</span>
</div>
<div className="relative flex flex-col gap-4 p-5">
<Corners />
<DialogHeader>
<DialogTitle className="text-lg">
{objective ? "Amend objective" : "Mark objective"}
</DialogTitle>
<DialogDescription className="text-xs">
Objectives are visible on the world map and every mission planned on it.
</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-1.5">
<FieldLabel>Designation</FieldLabel>
<Input
autoFocus
value={draft.name}
maxLength={MAX_OBJECTIVE_NAME}
placeholder="OBJ ALPHA"
onChange={(event) =>
setDraft((current) => ({ ...current, name: event.target.value }))
}
/>
</div>
<div className="flex flex-col gap-1.5">
<FieldLabel>Notes</FieldLabel>
<Textarea
value={draft.description}
maxLength={MAX_OBJECTIVE_DESCRIPTION}
rows={2}
placeholder="What is here, and what taking it achieves."
onChange={(event) =>
setDraft((current) => ({ ...current, description: event.target.value }))
}
/>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="flex flex-col gap-1.5">
<FieldLabel>Marker</FieldLabel>
<MarkerTypePicker
value={draft.markerType}
color={OBJECTIVE_STATUS_META[draft.status].color}
onChange={(markerType) => setDraft((current) => ({ ...current, markerType }))}
/>
</div>
<div className="flex flex-col gap-1.5">
<FieldLabel>Status</FieldLabel>
<ToggleGroup
type="single"
variant="outline"
size="sm"
value={draft.status}
onValueChange={(value) =>
value &&
setDraft((current) => ({ ...current, status: value as MapObjectiveStatus }))
}
className="w-full"
>
{MAP_OBJECTIVE_STATUSES.map((status) => (
<ToggleGroupItem key={status} value={status} className="flex-1 text-xs">
<span
aria-hidden
className="mr-1.5 inline-block size-2"
style={{ backgroundColor: objectiveHex(status) }}
/>
{OBJECTIVE_STATUS_META[status].label}
</ToggleGroupItem>
))}
</ToggleGroup>
<span className="text-xs text-muted-foreground">
{OBJECTIVE_STATUS_META[draft.status].description}
</span>
</div>
</div>
<div className="flex items-center justify-between gap-3 border-t border-white/10 pt-3">
<div className="flex flex-col">
<Label htmlFor="objective-redacted" className="text-sm">
Redacted
</Label>
<span className="text-xs text-muted-foreground">
Hidden from players until revealed. Superusers see it dimmed.
</span>
</div>
<Switch
id="objective-redacted"
checked={draft.redacted}
onCheckedChange={(redacted) => setDraft((current) => ({ ...current, redacted }))}
/>
</div>
<div className="flex items-center justify-between gap-3 border-t border-white/10 pt-3 font-mono text-[10px] uppercase tracking-widest text-white/50">
<span className="flex items-center gap-2">
<span
aria-hidden
className="inline-block size-2"
style={{ backgroundColor: swatch }}
/>
{OBJECTIVE_STATUS_META[draft.status].color}
</span>
<span>
{point ? `${Math.round(point[0])} / ${Math.round(point[1])} M` : "NO POSITION"}
</span>
</div>
</div>
<DialogFooter className="border-t border-white/15 bg-black/40 px-5 py-3 sm:justify-end">
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button type="button" disabled={!canSave} onClick={() => void submit()}>
{saving ? "Saving..." : objective ? "Save objective" : "Deploy objective"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View file

@ -0,0 +1,231 @@
"use client";
import { useState } from "react";
import { Marker, Popup, Tooltip } from "react-leaflet";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { markerDivIcon } from "@/components/frontend/markers/markerIcon";
import type { MapPoint } from "@/lib/map/points";
import type { MapObjectiveFeature } from "@/lib/map/types";
import {
MAP_OBJECTIVE_STATUSES,
OBJECTIVE_STATUS_META,
objectiveStatusLabel,
} from "@/lib/map/objectiveTypes";
import {
removeMapObjective,
saveMapObjective,
setMapObjectiveRedacted,
setMapObjectiveStatus,
} from "@/app/(frontend)/map/actions";
import { objectiveHex, objectiveToMarker } from "./objectiveVisuals";
const toLatLng = (point: MapPoint): [number, number] => [-point[1], point[0]];
export interface ObjectiveLayerProps {
objectives: MapObjectiveFeature[];
/** Superusers may drag markers and use the popup actions. */
canManage: boolean;
onEdit: (objective: MapObjectiveFeature) => void;
/** Fired after any successful mutation so the parent can reconcile state. */
onUpdated: (objective: MapObjectiveFeature) => void;
onDeleted: (id: number) => void;
}
/**
* Read-only Arma-style objective markers shared by the world map and mission
* planning maps. Superusers additionally get status/reveal/edit/delete actions
* and drag-to-move; everyone else sees the command picture only.
*/
export function ObjectiveLayer({
objectives,
canManage,
onEdit,
onUpdated,
onDeleted,
}: ObjectiveLayerProps) {
const [busyId, setBusyId] = useState<number | null>(null);
// Two-step delete: Leaflet popups are a bad host for a nested AlertDialog
// portal, so the button itself flips into a confirmation.
const [confirmId, setConfirmId] = useState<number | null>(null);
const apply = async (
objective: MapObjectiveFeature,
run: () => Promise<{ success: boolean; error?: string; data?: MapObjectiveFeature }>,
) => {
setBusyId(objective.id);
try {
const result = await run();
if (!result.success || !result.data) {
toast.error(result.error ?? "Failed to update the objective.");
return;
}
onUpdated(result.data);
} finally {
setBusyId(null);
}
};
const move = async (objective: MapObjectiveFeature, position: MapPoint) => {
const rounded: MapPoint = [
Math.round(position[0] * 100) / 100,
Math.round(position[1] * 100) / 100,
];
const result = await updateMapObjectiveForMove(objective, rounded);
if (!result.success || !result.data) {
toast.error(result.error ?? "Failed to move the objective.");
return;
}
onUpdated(result.data);
};
const remove = async (objective: MapObjectiveFeature) => {
setBusyId(objective.id);
try {
const result = await removeMapObjective({ id: objective.id });
if (!result.success) {
toast.error(result.error ?? "Failed to remove the objective.");
return;
}
onDeleted(objective.id);
toast.success(`Removed ${objective.name}.`);
} finally {
setBusyId(null);
}
};
return (
<>
{objectives.map((objective) => {
const hex = objectiveHex(objective.status);
const marker = objectiveToMarker(objective);
return (
<Marker
key={`objective-${objective.id}`}
position={toLatLng(objective.position)}
icon={markerDivIcon(marker, false)}
draggable={canManage}
eventHandlers={
canManage
? {
dragend: (event) => {
const latlng = event.target.getLatLng();
void move(objective, [latlng.lng, -latlng.lat]);
},
popupclose: () => setConfirmId(null),
}
: undefined
}
>
<Tooltip
permanent
direction="bottom"
offset={[0, 12]}
interactive={false}
className="objective-marker-label"
>
<span className="objective-marker-name" style={{ color: hex }}>
{objective.name}
{objective.redacted ? " // REDACTED" : ""}
</span>
</Tooltip>
<Popup>
<div className="min-w-56 text-sm">
<div className="font-semibold">{objective.name}</div>
<div className="mt-0.5 text-xs uppercase tracking-wide" style={{ color: hex }}>
{objectiveStatusLabel(objective.status)}
{objective.redacted ? " // REDACTED" : ""}
</div>
{objective.description && (
<p className="mt-1 text-xs text-white/70">{objective.description}</p>
)}
{canManage && (
<div className="mt-2 flex flex-col gap-2 border-t border-white/15 pt-2">
<div className="flex flex-wrap gap-1">
{MAP_OBJECTIVE_STATUSES.map((status) => (
<Button
key={status}
type="button"
size="sm"
variant={objective.status === status ? "secondary" : "outline"}
className="h-6 px-1.5 text-[10px] uppercase"
disabled={busyId === objective.id}
onClick={() =>
void apply(objective, () =>
setMapObjectiveStatus({ id: objective.id, status }),
)
}
>
{OBJECTIVE_STATUS_META[status].label}
</Button>
))}
</div>
<div className="flex flex-wrap gap-1">
<Button
type="button"
size="sm"
variant="outline"
className="h-6 px-1.5 text-[10px] uppercase"
disabled={busyId === objective.id}
onClick={() => onEdit(objective)}
>
Edit
</Button>
<Button
type="button"
size="sm"
variant="outline"
className="h-6 px-1.5 text-[10px] uppercase"
disabled={busyId === objective.id}
onClick={() =>
void apply(objective, () =>
setMapObjectiveRedacted({
id: objective.id,
redacted: !objective.redacted,
}),
)
}
>
{objective.redacted ? "Reveal" : "Hide"}
</Button>
<Button
type="button"
size="sm"
variant="outline"
className="h-6 px-1.5 text-[10px] uppercase text-red-400"
disabled={busyId === objective.id}
onClick={() => {
if (confirmId === objective.id) {
void remove(objective);
return;
}
setConfirmId(objective.id);
}}
>
{confirmId === objective.id ? "Confirm" : "Delete"}
</Button>
</div>
</div>
)}
</div>
</Popup>
</Marker>
);
})}
</>
);
}
/**
* Drag updates go through the full save action so position validation (world
* bounds) runs server-side, exactly like a dialog edit.
*/
async function updateMapObjectiveForMove(
objective: MapObjectiveFeature,
position: MapPoint,
): Promise<{ success: boolean; error?: string; data?: MapObjectiveFeature }> {
return saveMapObjective({
id: objective.id,
objective: { ...objective, position },
});
}

View file

@ -0,0 +1,35 @@
import { resolveMarkerRgba, rgbaToHex } from "@/lib/arma-markers";
import type { MissionMarkerData } from "@/lib/arma-markers/missionMarkers";
import {
OBJECTIVE_ICON_SCALE,
objectiveStatusColor,
type MapObjectiveStatus,
} from "@/lib/map/objectiveTypes";
import type { MapObjectiveFeature } from "@/lib/map/types";
/** Hex colour an objective renders with (status-driven, like Arma marker colours). */
export function objectiveHex(status: MapObjectiveStatus | string | null | undefined): string {
return rgbaToHex(resolveMarkerRgba(objectiveStatusColor(status)));
}
/**
* Objective as an Arma marker, for the shared mission-marker icon renderer.
* The id is negative so it never collides with a real planning-marker id.
*/
export function objectiveToMarker(objective: MapObjectiveFeature): MissionMarkerData & {
id: number;
} {
return {
id: -objective.id,
shape: "icon",
markerType: objective.markerType,
color: objectiveStatusColor(objective.status),
brush: null,
text: "",
position: objective.position,
size: [OBJECTIVE_ICON_SCALE, OBJECTIVE_ICON_SCALE],
direction: 0,
alpha: objective.redacted ? 0.55 : 1,
points: [],
};
}

View file

@ -0,0 +1,191 @@
"use client";
import { useState } from "react";
import { CornerBrackets } from "./CornerBrackets";
import { DOSSIER, STATUS_TONE_CLASSES } from "./tokens";
import { resolveExtraction } from "@/app/(frontend)/operations/actions";
import type { PendingExtraction } from "@/lib/operations/surfaceQuery";
import type { ExtractionLineDecision } from "@/lib/operations/settlementTypes";
/**
* Officer review surface for gated logistics extractions. Each parked effect
* renders as a dossier card: the HQ it will deposit to, the manifest lines
* (resource + quantity), and a keep / scrap / expel toggle per line. Resolving
* deposits the kept lines at HQ and settles the linked reservation; the card
* removes itself on success.
*
* `keep` deposits at HQ, `scrap` / `expel` hold the line back. A line may be
* resolved to `keep` even when the HQ is full: capacity is re-checked at
* resolve time, so the officer can drop lines to fit and retry.
*/
const DECISIONS = ["keep", "scrap", "expel"] as const;
type Decision = (typeof DECISIONS)[number];
const DECISION_TONE: Record<Decision, string> = {
keep: STATUS_TONE_CLASSES.success,
scrap: STATUS_TONE_CLASSES.warning,
expel: STATUS_TONE_CLASSES.danger,
};
const DECISION_LABEL: Record<Decision, string> = {
keep: "Deposit",
scrap: "Scrap",
expel: "Hold back",
};
export function ExtractionReview({
extractions,
}: {
extractions: PendingExtraction[];
}) {
const [remaining, setRemaining] = useState<PendingExtraction[]>(extractions);
const [decisions, setDecisions] = useState<Record<number, Record<number, Decision>>>(
() => Object.fromEntries(remaining.map((ex) => [ex.id, defaultLines(ex.lines)])),
);
const [submitting, setSubmitting] = useState<number | null>(null);
const [notice, setNotice] = useState<{ tone: "success" | "danger"; text: string } | null>(null);
function defaultLines(lines: PendingExtraction["lines"]): Record<number, Decision> {
const map: Record<number, Decision> = {};
for (const line of lines) map[line.resourceId] = "keep";
return map;
}
function setDecision(effectId: number, resourceId: number, decision: Decision) {
setDecisions((prev) => ({
...prev,
[effectId]: { ...prev[effectId], [resourceId]: decision },
}));
}
async function handleResolve(ex: PendingExtraction) {
setSubmitting(ex.id);
setNotice(null);
try {
const lineDecisions: ExtractionLineDecision[] = ex.lines.map((line) => ({
relationTo: "resources",
id: line.resourceId,
decision: decisions[ex.id]?.[line.resourceId] ?? "keep",
}));
const result = await resolveExtraction(ex.id, lineDecisions);
if (!result.success) {
setNotice({ tone: "danger", text: result.error ?? "Resolution failed." });
return;
}
setRemaining((prev) => prev.filter((other) => other.id !== ex.id));
setNotice({ tone: "success", text: "Extraction resolved and deposited to HQ." });
} catch (e) {
setNotice({
tone: "danger",
text: e instanceof Error ? e.message : "Unexpected error.",
});
} finally {
setSubmitting(null);
}
}
if (remaining.length === 0) {
return (
<div className="mx-auto flex w-full max-w-3xl flex-col gap-4">
<div className="rounded-lg border border-white/10 bg-card/60 px-6 py-12 text-center">
<p className="text-sm font-medium text-white/80">No extractions awaiting review</p>
<p className="mt-1.5 text-xs text-muted-foreground">
Logistics extractions are parked here until an officer reviews them.
</p>
</div>
</div>
);
}
return (
<div className="mx-auto flex w-full max-w-3xl flex-col gap-5">
{notice ? (
<div
role="alert"
className={`rounded-md border px-4 py-3 text-sm ${STATUS_TONE_CLASSES[notice.tone]}`}
>
{notice.text}
</div>
) : null}
{remaining.map((ex) => {
const lineDecisions = decisions[ex.id] ?? {};
const kept = ex.lines.filter((l) => lineDecisions[l.resourceId] === "keep").length;
const held = ex.lines.length - kept;
return (
<article
key={ex.id}
aria-label={`Extraction ${ex.operationId}`}
className="relative overflow-hidden rounded-lg border border-white/10 bg-card/70"
>
<CornerBrackets />
<header className="flex items-baseline justify-between gap-3 border-b border-white/10 px-5 py-3">
<div className="min-w-0">
<p className="truncate font-mono text-sm font-semibold tracking-wide text-white/90">
{ex.operationId}
</p>
<p className="mt-0.5 font-mono text-[11px] text-white/50">
{ex.hqName ? `HQ: ${ex.hqName}` : "HQ: unknown"} · {new Date(ex.occurredAt).toLocaleString()}
</p>
</div>
<span
className="shrink-0 rounded border border-amber-500/30 bg-amber-500/10 px-2 py-0.5 font-mono text-[10px] uppercase tracking-widest text-amber-300"
data-slot="pending-badge"
>
Awaiting review
</span>
</header>
<div className="divide-y divide-white/5">
{ex.lines.map((line) => {
const current = lineDecisions[line.resourceId] ?? "keep";
return (
<div key={line.resourceId} className="flex items-center justify-between gap-4 px-5 py-3">
<div className="min-w-0">
<p className="truncate text-sm text-white/85">{line.resourceName}</p>
<p className="font-mono text-xs text-white/45">+{line.amount}</p>
</div>
<div className="flex shrink-0 items-center gap-1" role="group">
{DECISIONS.map((d) => (
<button
key={d}
type="button"
onClick={() => setDecision(ex.id, line.resourceId, d)}
aria-pressed={current === d}
className={`rounded px-2.5 py-1 font-mono text-[10px] uppercase tracking-wide transition ${
current === d
? DECISION_TONE[d]
: "border border-white/10 bg-black/30 text-white/40 hover:text-white/60"
}`}
>
{DECISION_LABEL[d]}
</button>
))}
</div>
</div>
);
})}
</div>
<div className="flex items-center justify-between border-t border-white/10 px-5 py-3">
<span className="font-mono text-[11px] text-white/50">
{kept} deposit / {held} held back
</span>
<button
type="button"
onClick={() => handleResolve(ex)}
disabled={submitting !== null}
aria-busy={submitting === ex.id}
className="inline-flex items-center gap-2 rounded border border-white/15 bg-white/10 px-4 py-1.5 text-xs font-medium text-white transition hover:bg-white/20 disabled:cursor-not-allowed disabled:opacity-50"
>
{submitting === ex.id ? "Resolving…" : "Resolve"}
</button>
</div>
</article>
);
})}
</div>
);
}
export { DOSSIER };

View file

@ -19,3 +19,4 @@ export {
export { LedgerTable, type LedgerTableFilters } from "./LedgerTable";
export { AarView } from "./AarView";
export { ReconcilePanel, type ReconcilableEvent } from "./ReconcilePanel";
export { ExtractionReview } from "./ExtractionReview";

View file

@ -9,5 +9,5 @@ Optional per-mission planning layer: the mission's own map (`classification.map`
- **Catalog lib** (`src/lib/arma-markers/`, pure, client-safe): `index.ts` (case-insensitive `markerTypeOf`/`markerColorOf`/`markerBrushOf`, `resolveMarkerRgba` where color `Default` = the type's own config color, `markerTypesByCategory`), `missionMarkers.ts` (marker model mirroring Arma: shape icon/rectangle/ellipse/polyline + type/color/brush/text/size/direction/alpha/points; `normalizeMarkerInput` validation; `areaOutline` (direction = degrees clockwise from north, size = half-extents like `markerSize`); `hatchSegments` for pattern brushes; `armaGridRef`; `markersToSqf` export, y flipped against world height).
- **Collection**: `mission-map-markers` (`src/collections/intelligence/MissionMapMarkers.ts`, permission group "Mission Map Markers", REST access permission-gated). Missions gained `classification.planningMapEnabled` (opt-in) and a `beforeDelete` hook that removes the mission's markers (the FK is NOT NULL, so Payload's default ON DELETE SET NULL would fail the delete). Migration `20261003_190000_add_mission_map_markers` (hand-written; matches the generated schema).
- **Rules**: read = anyone who can read the mission (user-scoped `findByID`). Two edit tiers in `src/lib/intelligence/missionMap.ts`: **curators** (`missions:update` or the mission's `createdBy`) manage the whole plan (toggle, clear, edit/delete any marker); **delegates** (`classification.planningMapDelegates`, set per mission by `missions:update` holders via `setMissionPlanningDelegates`) may place markers and edit/delete only their own. The map locks for everyone (`isMissionPlanLocked`) once status is Completed/Cancelled. Placing a marker queues 2 contribution XP that grants only if the marker survives to completion (see `src/lib/contributions/AGENTS.md`). Service `src/lib/intelligence/missionMap.ts`; server actions `src/app/(frontend)/intelligence/missions/mapActions.ts` (`setMissionPlanningMap`, `setMissionPlanningDelegates`, `getMissionMapMarkers`, `saveMissionMapMarker`, `deleteMissionMapMarker`, `clearMissionMapMarkers`; events `mission:planning-map-toggle` / `mission:planning-delegates` / `mission:map-marker-*` / `mission:map-markers-clear`, target `missions`). Max 1000 markers per mission.
- **UI**: `src/components/frontend/intelligence/missionMap/` (tactical dossier section above the mission detail grid). `MissionPlanningMap` (state, debounced per-marker saves, 30s background refresh, Delete/Escape keys, SQF copy, Arma grid readout), `MissionMapCanvas` (Leaflet, basemap + roads/zones via `GET /api/map-features?mapId=&layers=base`, which skips structures/nodes/shipments), `MarkerToolPanel` (tools, type picker, colors, brush, text, scale/size, direction, opacity), `markerIcon.ts` + `iconStyle.ts` (icons render as texture MULTIPLIED by the marker color and masked by the texture alpha, exactly like Arma: white glyphs take the color, flags keep theirs). Editors see an "Enable planning map" card until it is on; non-editors see nothing until enabled.
- **UI**: `src/components/frontend/intelligence/missionMap/` (tactical dossier section above the mission detail grid). `MissionPlanningMap` (state, debounced per-marker saves, 30s background refresh of markers **and** the map's shared objectives, Delete/Escape keys, SQF copy that includes visible objectives, Arma grid readout, Layers popover persisted in localStorage: objectives/structures/nodes/shipments/ranges plus grid/roads/zones), `MissionMapCanvas` (Leaflet, basemap + roads/zones via `GET /api/map-features?mapId=&layers=base`, which skips structures/nodes/shipments until one of those reference layers is switched on; then the full feed loads), `PlanningFeatureLayers` (read-only structure/node/shipment/range reference markers with links back to the owning records), `MarkerToolPanel` (tools, type picker, colors, brush, text, scale/size, direction, opacity), `markerIcon.ts` + `iconStyle.ts` (icons render as texture MULTIPLIED by the marker color and masked by the texture alpha, exactly like Arma: white glyphs take the color, flags keep theirs; both moved to the shared `src/components/frontend/markers/` folder alongside `MarkerTypePicker`). Editors see an "Enable planning map" card until it is on; non-editors see nothing until enabled. Superusers (`system:admin-access`) can also place and amend the map's strategic objectives from the planning map through the shared `ObjectiveDialog` / `ObjectiveLayer`, independently of mission-marker curation.
- **Gotchas**: leaflet click/dblclick/mousedown/mouseup fire faster than React re-renders, so draft line vertices and the area drag start live in refs (state only drives the preview). URLs inside divIcon HTML must use single quotes (`url('...')`): a double quote ends the `style` attribute and the glyph silently disappears. Radix Select keeps `pointer-events: none` on `<body>` briefly after closing (affects scripted drags right after choosing a brush). Tests: `tests/int/mission-map.int.spec.ts`, `tests/e2e/mission-planning-map.e2e.spec.ts`.

View file

@ -43,7 +43,7 @@ export function validateRibbonDesign(design: unknown): RibbonValidationResult {
return { ok: false, error: "Must have at most 6 devices" };
}
const validDeviceTypes = ["star", "oakLeaf", "arrowUp", "campaignClasp"];
const validDeviceTypes = ["star", "oakLeaf", "valor", "campaignClasp"];
for (let i = 0; i < devices.length; i++) {
const device = devices[i];
if (!device || typeof device !== "object") {

View file

@ -5,13 +5,14 @@
Leaflet world map at `/map` (top-level sidebar entry, whole unit views it). Full docs: `docs/map-system.md`.
- **Strategic objectives** (`src/collections/world/MapObjectives.ts`, slug `map-objectives`): Arma-style command markers owned by a terrain map and shared by every mission planned on it (`name`, `description`, `markerType` CfgMarkers class default `mil_objective`, `status` active/secured/failed, `redacted`, `position` JSON [x, y], `createdBy`). Writes require `system:admin-access` (admin + superuser roles only); reads are open to logged-in users, with `redacted` rows stripped for anyone without the tier. Status drives the colour (`ColorRed` / `ColorGreen` / `ColorGrey`). Maps `beforeDelete` removes the map's objectives (NOT NULL FK; same trap as mission markers). Hooks emit `map:objective-created` / `-updated` / `-status` / `-reveal` / `-deleted` targeting `map-objectives`. Service `src/lib/map/objectives.ts`; pure constants `src/lib/map/objectiveTypes.ts`; actions `src/app/(frontend)/map/actions.ts` (`saveMapObjective`, `setMapObjectiveStatus`, `setMapObjectiveRedacted`, `removeMapObjective`, `getMapObjectives`). `GET /api/map-features` always returns `objectives` (redacted included only for superusers).
- **Collections** (`src/collections/world/`): `maps` (redesigned: `worldSizeWidth`/`worldSizeHeight` meters, `basemapMode` select `image`/`tiles`, `basemapImage` upload, `tileUrlTemplate`, zoom defaults, `isActive`, `worldMap` checkbox (opt-in "World Map Entry", default false; existing active maps backfilled true), optional `campaign` relationship, optional intel fields: `description`, `weather` freeform text (colored by keyword match on picker cards), `latitude`/`longitude` real-world reference, `easeOfAccess` select (easy/moderate/difficult), `factionControl` relationship; picker cards show weather/ease/faction stats + a truncated description), `map-roads` (name, description, map rel, surface select, `speedMultiplier`, strokeColor/strokeWeight/strokeStyle/labelVisible (tri-state: unset = auto, paved labels always, dirt/trail only at close zoom via `roadLabelShown` in style.ts, 4 m/px threshold), `points` JSON array of [x, y] meters), `map-zones` (name, description, type select water/land/territory/border/other (territory/border are informational political boundaries, other is for generic areas like named compounds; none gate placement, only water does; default fills amber 0.1 / violet 0.06 / slate 0.08), fillColor/strokeColor/fillOpacity/strokeWeight/labelVisible, polygon points JSON), `resource-nodes` (`resources` hasMany rel OPTIONAL (empty = plain marker node: placement's resourcesInRange never matches it), `icon` select from the shared set in `src/lib/map/nodeIcons.ts` (marker/droplet/trees/mountain/flag/star/skull/home/anchor/fuel; rendered on the map + picked in the authoring toolbar and admin), `position` JSON [x, y], richness, name, description). Feature collections read: any logged-in user; write: `maps:*` permissions. World Map screen eligibility (`src/lib/map/screen.ts`): `worldMap && isActive && (no campaign or campaignMode != custom)` — mission-only / side-op maps (flag off, or tied to a custom campaign) never appear on the screen but stay attachable to missions. Admin-panel visibility needs `<slug>:read` + `admin:<slug>:manage` ("Map Features" permission group).
- **Coordinates**: real meters, per-map Cartesian grid, origin top-left, y runs south (Arma convention). JSON geometry for map features; `game-structures.coordinates` keeps its PostGIS point but stores meters (`validate: () => true` overrides Payload's geographic lng/lat validation; meters are not degrees).
- **Routing**: `src/lib/map/routing.ts` (pure) builds a graph from road polylines (1 m vertex epsilon; shared vertex = junction), Dijkstra weighted by `length / speedMultiplier`; origin/destination snap to the nearest vertex within 1000 m; no connected route refuses ground shipments with a clear error. Air/sea (`vehicles.transportMode`) go straight-line. Distance = geometric route length in meters; `routePath` JSON snapshot on shipments (auto-return reverses it). Speed math converts meters to km once in `calculateTransitTime`; fuel stays `meters x rate`.
- **Placement**: `src/lib/map/placement.ts` (pure: terrain point-in-polygon, resourcesInRange vs multi-resource nodes OR resource-bearing zones at the site, structuresInRange) + `placeStructure` action (`src/app/(frontend)/logistics/map/actions.ts`, hasLogisticsQualification gate, emits `structure:placed`). Map UI placement mode for logistics-qualified users (click to place, dialog with blueprint/name/faction, client pre-validation + server enforcement). Water zones block land blueprints; water blueprints need a water zone; no zones = everything allowed.
- **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).
- **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 (objectives/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`. Objective markers render through the shared `src/components/frontend/map/objectives/` layer (Arma glyph + persistent designation plate); superusers get an "Add objective" toolbar mode, drag-to-move and status/reveal/edit/delete popup actions, and author through the dossier-styled `ObjectiveDialog`. 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"`.
- **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), `tests/int/map-objectives.int.spec.ts` (superuser gate, redaction filtering, status/reveal/delete events, world-bounds validation, map-delete cascade). Gotcha: Payload applies select `filterOptions` server-side, so test fixtures must use `approvalStatus: "in_progress"`.

View file

@ -0,0 +1,52 @@
/**
* Strategic objective constants (pure, client-safe).
*
* Objectives are Arma-style command markers that belong to a terrain map and
* are authored by superusers. Their colour is derived from the lifecycle
* status rather than picked freely, so the map always reads consistently:
* red = still to be taken, green = secured, grey = failed.
*/
export const MAP_OBJECTIVE_STATUSES = ["active", "secured", "failed"] as const;
export type MapObjectiveStatus = (typeof MAP_OBJECTIVE_STATUSES)[number];
/** Arma's own objective glyph (`mil_objective`, a circled star). */
export const DEFAULT_OBJECTIVE_MARKER_TYPE = "mil_objective";
export const MAX_OBJECTIVE_NAME = 80;
export const MAX_OBJECTIVE_DESCRIPTION = 500;
/** Icon scale multiplier (Arma markerSize) applied to every objective marker. */
export const OBJECTIVE_ICON_SCALE = 1.5;
export const OBJECTIVE_STATUS_META: Record<
MapObjectiveStatus,
{ label: string; /** CfgMarkerColors class */ color: string; description: string }
> = {
active: {
label: "Active",
color: "ColorRed",
description: "Objective is still to be taken.",
},
secured: {
label: "Secured",
color: "ColorGreen",
description: "Objective has been secured by friendly forces.",
},
failed: {
label: "Failed",
color: "ColorGrey",
description: "Objective was lost or is no longer achievable.",
},
};
export function isMapObjectiveStatus(value: unknown): value is MapObjectiveStatus {
return typeof value === "string" && (MAP_OBJECTIVE_STATUSES as readonly string[]).includes(value);
}
/** CfgMarkerColors class for a status (falls back to the active colour). */
export function objectiveStatusColor(status: string | null | undefined): string {
return OBJECTIVE_STATUS_META[isMapObjectiveStatus(status) ? status : "active"].color;
}
export function objectiveStatusLabel(status: string | null | undefined): string {
return OBJECTIVE_STATUS_META[isMapObjectiveStatus(status) ? status : "active"].label;
}

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

@ -0,0 +1,273 @@
/**
* Strategic objective service (Payload-dependent).
*
* Objectives are Arma-style command markers that belong to a terrain map, are
* shared by every mission planned on that map, and are authored by superusers
* only. Reads are open to any logged-in user, except rows flagged `redacted`,
* which are stripped for everyone without the superuser tier.
*
* All frontend writes flow through `src/app/(frontend)/map/actions.ts`, which
* gates on `system:admin-access` before calling in here.
*/
import type { Payload, Where } from "payload";
import { markerTypeOf } from "@/lib/arma-markers";
import { isPointArray, type MapPoint } from "./points";
import {
DEFAULT_OBJECTIVE_MARKER_TYPE,
MAX_OBJECTIVE_DESCRIPTION,
MAX_OBJECTIVE_NAME,
isMapObjectiveStatus,
type MapObjectiveStatus,
} from "./objectiveTypes";
import type { MapObjectiveFeature } from "./types";
/** Same slack the planning map gives its markers: objectives may sit just off-world. */
const WORLD_MARGIN = 2000;
export interface ObjectiveWorld {
width: number;
height: number;
}
/**
* Flat column shape for reads. Deliberately local (like `MissionMapMarkerDoc`)
* so this module does not depend on a regenerated `payload-types.ts`.
*/
export interface MapObjectiveDoc {
id: number;
map: number | { id: number } | null;
name?: string | null;
description?: string | null;
markerType?: string | null;
status?: string | null;
redacted?: boolean | null;
position?: unknown;
}
export interface MapObjectiveInput {
name: string;
description: string | null;
markerType: string;
status: MapObjectiveStatus;
redacted: boolean;
position: MapPoint;
}
export function objectiveWorldSize(map: {
worldSizeWidth?: number | null;
worldSizeHeight?: number | null;
}): ObjectiveWorld {
return {
width: Number(map.worldSizeWidth ?? 8192),
height: Number(map.worldSizeHeight ?? 8192),
};
}
function inWorld(point: MapPoint, world: ObjectiveWorld): boolean {
return (
point[0] >= -WORLD_MARGIN &&
point[0] <= world.width + WORLD_MARGIN &&
point[1] >= -WORLD_MARGIN &&
point[1] <= world.height + WORLD_MARGIN
);
}
/** One line, trimmed, capped. Objective names are map labels, not prose. */
export function sanitizeObjectiveName(value: unknown): string {
if (typeof value !== "string") return "";
return value
.replace(/[\r\n\t]+/g, " ")
.trim()
.slice(0, MAX_OBJECTIVE_NAME);
}
export function sanitizeObjectiveDescription(value: unknown): string {
if (typeof value !== "string") return "";
return value.replace(/\r\n/g, "\n").trim().slice(0, MAX_OBJECTIVE_DESCRIPTION);
}
/**
* Coerce a stored row into the client feature model. Bad geometry yields null
* so one broken row never blanks the layer.
*/
export function objectiveFromDoc(doc: MapObjectiveDoc): MapObjectiveFeature | null {
if (!isPointArray([doc.position])) return null;
const position = doc.position as MapPoint;
const status: MapObjectiveStatus = isMapObjectiveStatus(doc.status) ? doc.status : "active";
const markerType = markerTypeOf(doc.markerType)?.className ?? DEFAULT_OBJECTIVE_MARKER_TYPE;
return {
id: doc.id,
name: sanitizeObjectiveName(doc.name) || `Objective #${doc.id}`,
description: doc.description?.trim() || null,
markerType,
status,
redacted: doc.redacted === true,
position: [Math.round(position[0] * 100) / 100, Math.round(position[1] * 100) / 100],
};
}
/** Validate and normalize untrusted objective input (server-side gate). */
export function normalizeObjectiveInput(
input: unknown,
world: ObjectiveWorld,
): { ok: true; data: MapObjectiveInput } | { ok: false; error: string } {
if (!input || typeof input !== "object") return { ok: false, error: "Invalid objective." };
const raw = input as Record<string, unknown>;
const name = sanitizeObjectiveName(raw.name);
if (!name) return { ok: false, error: "Objective name is required." };
const status = raw.status ?? "active";
if (!isMapObjectiveStatus(status)) return { ok: false, error: "Unknown objective status." };
const typeClass =
typeof raw.markerType === "string" && raw.markerType
? raw.markerType
: DEFAULT_OBJECTIVE_MARKER_TYPE;
const type = markerTypeOf(typeClass);
if (!type) return { ok: false, error: `Unknown marker type "${typeClass}".` };
if (!isPointArray([raw.position])) return { ok: false, error: "Objective position is required." };
const position = (raw.position as MapPoint).map(
(value) => Math.round(value * 100) / 100,
) as MapPoint;
if (!inWorld(position, world)) return { ok: false, error: "Objective must be on the map." };
return {
ok: true,
data: {
name,
description: sanitizeObjectiveDescription(raw.description) || null,
markerType: type.className,
status,
redacted: raw.redacted === true,
position,
},
};
}
/** Objectives for one map. Redacted rows are opt-in (superuser surfaces only). */
export async function listMapObjectives(
payload: Payload,
mapId: number,
options: { includeRedacted?: boolean } = {},
): Promise<MapObjectiveFeature[]> {
if (!Number.isInteger(mapId) || mapId <= 0) return [];
const where: Where = options.includeRedacted
? { map: { equals: mapId } }
: {
and: [{ map: { equals: mapId } }, { redacted: { not_equals: true } }],
};
const result = await payload.find({
collection: "map-objectives",
where,
sort: "id",
depth: 0,
limit: 500,
pagination: false,
overrideAccess: true,
});
return result.docs
.map((doc) => objectiveFromDoc(doc as unknown as MapObjectiveDoc))
.filter((objective): objective is MapObjectiveFeature => objective !== null);
}
async function loadMapWorld(payload: Payload, mapId: number): Promise<ObjectiveWorld | null> {
const map = await payload
.findByID({ collection: "maps", id: mapId, depth: 0, overrideAccess: true })
.catch(() => null);
return map ? objectiveWorldSize(map) : null;
}
export async function createMapObjective(
payload: Payload,
mapId: number,
input: unknown,
actorId: number | null,
): Promise<MapObjectiveFeature> {
const world = await loadMapWorld(payload, mapId);
if (!world) throw new Error("Map not found.");
const normalized = normalizeObjectiveInput(input, world);
if (!normalized.ok) throw new Error(normalized.error);
const { data } = normalized;
const doc = await payload.create({
collection: "map-objectives",
data: {
map: mapId,
name: data.name,
description: data.description,
markerType: data.markerType,
status: data.status,
redacted: data.redacted,
position: data.position,
createdBy: actorId,
},
overrideAccess: true,
});
const objective = objectiveFromDoc(doc as unknown as MapObjectiveDoc);
if (!objective) throw new Error("Failed to save objective.");
return objective;
}
export async function updateMapObjective(
payload: Payload,
objectiveId: number,
input: unknown,
): Promise<MapObjectiveFeature> {
const existing = await payload
.findByID({ collection: "map-objectives", id: objectiveId, depth: 0, overrideAccess: true })
.catch(() => null);
if (!existing) throw new Error("Objective not found.");
const doc = existing as unknown as MapObjectiveDoc;
const mapId = typeof doc.map === "object" && doc.map !== null ? doc.map.id : doc.map;
if (!mapId) throw new Error("Objective has no map.");
const world = await loadMapWorld(payload, mapId);
if (!world) throw new Error("Map not found.");
const normalized = normalizeObjectiveInput(input, world);
if (!normalized.ok) throw new Error(normalized.error);
const { data } = normalized;
const updated = await payload.update({
collection: "map-objectives",
id: objectiveId,
data: {
name: data.name,
description: data.description,
markerType: data.markerType,
status: data.status,
redacted: data.redacted,
position: data.position,
},
overrideAccess: true,
});
const objective = objectiveFromDoc(updated as unknown as MapObjectiveDoc);
if (!objective) throw new Error("Failed to save objective.");
return objective;
}
export async function deleteMapObjective(payload: Payload, objectiveId: number): Promise<void> {
const existing = await payload
.findByID({ collection: "map-objectives", id: objectiveId, depth: 0, overrideAccess: true })
.catch(() => null);
if (!existing) throw new Error("Objective not found.");
await payload.delete({ collection: "map-objectives", id: objectiveId, overrideAccess: true });
}
/** Remove every objective on a map (Maps `beforeDelete` cleanup). */
export async function clearMapObjectives(payload: Payload, mapId: number): Promise<number> {
const result = await payload.find({
collection: "map-objectives",
where: { map: { equals: mapId } },
depth: 0,
limit: 1000,
pagination: false,
overrideAccess: true,
select: {},
});
for (const doc of result.docs) {
await payload.delete({ collection: "map-objectives", id: doc.id, overrideAccess: true });
}
return result.docs.length;
}

View file

@ -1,5 +1,6 @@
import type { MapPoint } from "./points";
import type { MapGridConfig } from "./grid";
import type { MapObjectiveStatus } from "./objectiveTypes";
export interface MapConfig {
id: number;
@ -96,6 +97,18 @@ export interface ShipmentFeature {
vehicleName: string | null;
}
export interface MapObjectiveFeature {
id: number;
name: string;
description: string | null;
/** CfgMarkers class, e.g. mil_objective. */
markerType: string;
status: MapObjectiveStatus;
/** Hidden from non-superusers until revealed. */
redacted: boolean;
position: MapPoint;
}
export interface MapFeaturesResponse {
map: MapConfig;
structures: StructureFeature[];
@ -103,4 +116,5 @@ export interface MapFeaturesResponse {
roads: RoadFeature[];
zones: ZoneFeature[];
shipments: ShipmentFeature[];
objectives: MapObjectiveFeature[];
}

View file

@ -43,15 +43,20 @@ export async function applyOperationEffect(
)) as unknown as OperationEffect | null;
if (!effect) return null;
if (effect.status === "applied" || effect.status === "reversed") return effect;
// pending_action is terminal for the auto-dispatcher: the extraction gate
// parked this effect for officer review; applyOperationEffect must not
// overwrite it with "applied".
if (effect.status === "pending_action") return effect;
try {
const note = await dispatchEffect(payload, effect, req);
const { note, status = "applied" } = await dispatchEffect(payload, effect, req);
const applied = status === "applied";
return (await payload.update({
collection: "operation-effects",
id: effect.id,
data: {
status: "applied",
appliedAt: new Date().toISOString(),
status,
appliedAt: applied ? new Date().toISOString() : null,
reconciliationNotes: note ?? null,
},
overrideAccess: true,
@ -73,22 +78,24 @@ export async function applyOperationEffect(
}
}
type DispatchResult = { note?: string | null; status?: "applied" | "pending_action" };
async function dispatchEffect(
payload: Payload,
effect: OperationEffect,
req?: PayloadRequest,
): Promise<string | null> {
): Promise<DispatchResult> {
switch (effect.effectType) {
case "operation.started":
return null;
return { note: null };
case "operation.objective-updated":
return handleObjective(payload, effect);
return { note: await handleObjective(payload, effect) };
case "operation.extraction-recorded":
return handleExtraction(payload, effect, req);
return await handleExtraction(payload, effect, req);
case "operation.inventory-recorded":
return handleInventoryLoss(payload, effect, req);
return { note: await handleInventoryLoss(payload, effect, req) };
case "operation.ended":
return handleOperationEnd(payload, effect, req);
return { note: await handleOperationEnd(payload, effect, req) };
default:
throw new SettlementFailure("internal-error", `Unknown effect type "${effect.effectType}".`);
}

View file

@ -24,13 +24,26 @@ import {
parsePlayerLine,
} from "./settlementParse";
import { SettlementFailure } from "./settlementTypes";
import type { ExtractionPayloadV1, LogisticsExtractionLine } from "./settlementTypes";
import type {
ExtractionDecision,
ExtractionDecisions,
ExtractionPayloadV1,
LogisticsExtractionLine,
} from "./settlementTypes";
/**
* Extraction settlement: converts a validated extraction effect into one
* provenance-linked HQ deposit (logistics) or personal-locker credit
* (player). Both paths preflight the whole manifest before any write, so a
* rejected effect never leaves a partial deposit or credit behind.
*
* Logistics extraction gate: a validated logistics extraction no longer
* auto-deposits. Instead `handleExtraction` resolves the manifest's resources
* (so an unresolved reference fails at emit) and parks the effect as
* `pending_action` for officer review. The officer resolves it later via
* `resolveLogisticsExtraction`, which deposits the kept lines and settles the
* linked reservation. Scrap/expel lines are held back (no deposit). Player
* extractions still auto-apply, since they credit a personal locker.
*/
type AuditUser = Parameters<typeof addResourceInternal>[1];
@ -53,7 +66,7 @@ export async function handleExtraction(
payload: Payload,
effect: OperationEffect,
req?: PayloadRequest,
): Promise<string | null> {
): Promise<{ note?: string | null; status: "applied" | "pending_action" }> {
const parsed = parseExtractionPayload(effect.payload);
if (!parsed.ok) throw new SettlementFailure(parsed.code, parsed.message);
const ext = parsed.value;
@ -66,19 +79,140 @@ export async function handleExtraction(
}
// Record-only extraction (legacy `{ player }` shape): AAR evidence, no
// inventory movement.
if (!ext.kind) return null;
if (!ext.kind) return { status: "applied" };
const rawLines = ext.items ?? [];
if (ext.kind === "logistics") {
await settleLogisticsExtraction(payload, ext, rawLines, req);
} else {
await settlePlayerExtraction(payload, effect, ext, rawLines, req);
// Gate instead of deposit: resolve the manifest, then park for officer
// review. The linked reservation is settled at resolve time, not here.
await gateLogisticsExtraction(payload, ext, effect, req);
return { status: "pending_action" };
}
await settlePlayerExtraction(payload, effect, ext, ext.items ?? [], req);
if (ext.reservationKey) {
return await settleLinkedReservation(payload, ext, effect.id, req);
return { note: await settleLinkedReservation(payload, ext, effect.id, req), status: "applied" };
}
return null;
return { status: "applied" };
}
/**
* Extraction gate for logistics deposits. Resolves every manifest resource so
* an unresolved reference fails here (at emit), matching player-extraction
* behavior, then parks the effect as `pending_action` instead of depositing.
* Capacity is intentionally checked at resolve time so an officer can drop
* lines (scrap/expel) to fit a full HQ.
*/
async function gateLogisticsExtraction(
payload: Payload,
ext: ExtractionPayloadV1,
effect: OperationEffect,
req?: PayloadRequest,
): Promise<void> {
for (const raw of ext.items ?? []) {
const line = parseLogisticsLine(raw);
if (!line.ok) throw new SettlementFailure(line.code, line.message);
const resource = await findByIdOrNull(payload, "resources", line.value.resourceId, req);
if (!resource) {
throw new SettlementFailure(
"unresolved-asset",
`Resource #${line.value.resourceId} does not exist.`,
);
}
}
await payload.update({
collection: "operation-effects",
id: effect.id,
data: { status: "pending_action", decisions: null },
overrideAccess: true,
depth: 0,
req,
});
}
/**
* Officer resolution of a gated logistics extraction. Applies the decisions
* (keep deposits, scrap/expel hold back), deposits the kept lines at HQ, and
* settles the linked reservation. A capacity/full-store failure at resolve
* marks the effect `failed` and leaves nothing half-deposited.
*/
export async function resolveLogisticsExtraction(
payload: Payload,
effectId: number,
decisions: ExtractionDecisions | null,
req?: PayloadRequest,
): Promise<{ success: boolean; error?: string }> {
const rawEffect = await findByIdOrNull(payload, "operation-effects", effectId, req);
const effect = rawEffect as unknown as OperationEffect | null;
if (!effect) return { success: false, error: "Effect not found." };
if (effect.effectType !== "operation.extraction-recorded") {
return { success: false, error: "Effect is not an extraction." };
}
if (effect.status !== "pending_action") {
return { success: false, error: `Effect is not awaiting action (status: ${effect.status}).` };
}
const parsed = parseExtractionPayload(effect.payload);
if (!parsed.ok) return { success: false, error: parsed.message };
const ext = parsed.value;
if (ext.kind !== "logistics") {
return { success: false, error: "Only logistics extractions are gated." };
}
// Map decisions by resource id, then keep every line not scrap/expel. A line
// not named in the decisions array defaults to keep.
const decisionById = new Map<number, ExtractionDecision>();
for (const d of decisions ?? []) decisionById.set(d.id, d.decision);
const keptRaw: unknown[] = [];
for (const raw of ext.items ?? []) {
const line = parseLogisticsLine(raw);
if (!line.ok) continue;
const decision = decisionById.get(line.value.resourceId);
if (decision === "scrap" || decision === "expel") continue;
keptRaw.push(raw);
}
try {
await settleLogisticsExtraction(payload, ext, keptRaw, req);
if (ext.reservationKey) {
await settleLinkedReservation(payload, ext, effect.id, req);
}
} catch (error) {
const code = error instanceof SettlementFailure ? error.code : "internal-error";
const message = error instanceof Error ? error.message : "unknown error";
// Leave the effect pending_action so the officer can retry — drop a line
// or free HQ space and resolve again. A capacity/storage failure is
// recoverable, unlike an unresolved asset (which fails at the gate).
await payload.update({
collection: "operation-effects",
id: effect.id,
data: {
status: "pending_action",
decisions,
reconciliationNotes: `${code}: ${message}`,
},
overrideAccess: true,
depth: 0,
req,
});
return { success: false, error: message };
}
await payload.update({
collection: "operation-effects",
id: effect.id,
data: {
status: "applied",
decisions,
appliedAt: new Date().toISOString(),
reconciliationNotes: null,
},
overrideAccess: true,
depth: 0,
req,
});
return { success: true };
}
async function settleLogisticsExtraction(

View file

@ -91,6 +91,28 @@ export interface LogisticsExtractionLine {
amount: number;
}
/**
* Officer resolution for a gated logistics extraction line:
* - keep: deposit the line at HQ (the default; lines not named here keep)
* - scrap / expel: hold the line back (no deposit), recorded for reporting
*/
export type ExtractionDecision = "keep" | "scrap" | "expel";
/** One officer decision for a single extraction line. */
export interface ExtractionLineDecision {
relationTo: "resources" | "assets" | "vehicles";
id: number;
decision: ExtractionDecision;
}
/**
* The officer's decisions on a gated logistics extraction effect.
* Absent (null) means unreviewed: the effect is parked for officer review.
* Once resolved this is an array; an empty array means "keep everything".
* Each line not named here defaults to "keep".
*/
export type ExtractionDecisions = ExtractionLineDecision[];
export interface PlayerExtractionLine {
assetId: number;
quantity: number;

View file

@ -264,3 +264,139 @@ export async function getOperationAar(
reservations,
};
}
/**
* Pending-extraction review queue. Every logistics extraction is gated: its
* effect parks as `pending_action` before it deposits at HQ, so a logistics
* officer reviews the manifest and decides keep / scrap / expel per line via
* `resolveLogisticsExtraction`. This surface lists those parked effects with
* the manifest resolved to human-readable lines; no raw payload JSON leaks.
*
* The queue is permission-gated like the rest of the ledger: a viewer without
* `operation-ledger:read` reads through access control and sees only what they
* are allowed to.
*/
export interface PendingExtractionLine {
resourceId: number;
resourceName: string;
amount: number;
}
export interface PendingExtraction {
id: number;
effectKey: string;
operationId: string;
occurredAt: string;
hqStructureId: number | null;
hqName: string | null;
notes: string | null;
lines: PendingExtractionLine[];
}
export interface PendingExtractionResult {
extractions: PendingExtraction[];
total: number;
}
export async function listPendingExtractions(
payload: PayloadType,
user: SurfaceUser,
): Promise<PendingExtractionResult> {
const found = await payload.find({
collection: "operation-effects",
where: {
and: [
{ status: { equals: "pending_action" } },
{ effectType: { equals: "operation.extraction-recorded" } },
],
},
sort: "-createdAt",
limit: 100,
depth: 0,
user: user ?? undefined,
});
// Collect every resource id and HQ id so we can resolve names in two batched
// queries instead of one per line.
const resourceIds: number[] = [];
const hqIds: number[] = [];
const rows = found.docs.map((doc) => {
const effect = doc as unknown as {
id: number;
effectKey: string;
operationId: string;
createdAt: string;
reconciliationNotes: string | null;
payload: Record<string, unknown>;
};
const manifest = effect.payload ?? {};
const items = Array.isArray(manifest["items"])
? (manifest["items"] as Array<Record<string, unknown>>)
: [];
const lines = items
.map((it) => {
const resourceId = it["resourceId"] as number;
if (typeof resourceId === "number") resourceIds.push(resourceId);
return {
resourceId,
amount: typeof it["amount"] === "number" ? it["amount"] : 0,
};
})
.filter((line) => typeof line.resourceId === "number");
const hqId = manifest["hqStructureId"] as number;
if (typeof hqId === "number") hqIds.push(hqId);
return { effect, lines };
});
const [resourceRows, hqRows] = await Promise.all([
resourceIds.length
? payload.find({
collection: "resources",
where: { id: { in: resourceIds } },
limit: resourceIds.length,
depth: 0,
})
: { docs: [] },
hqIds.length
? payload.find({
collection: "game-structures",
where: { id: { in: hqIds } },
limit: hqIds.length,
depth: 0,
})
: { docs: [] },
]);
const resourceNames = new Map(
resourceRows.docs.map((r) => {
const row = r as { id: number; name: string };
return [row.id, row.name] as const;
}),
);
const hqNames = new Map(
hqRows.docs.map((r) => {
const row = r as { id: number; name: string };
return [row.id, row.name] as const;
}),
);
const extractions: PendingExtraction[] = rows.map(({ effect, lines }) => {
const hqId = (effect.payload["hqStructureId"] as number) ?? null;
return {
id: effect.id,
effectKey: effect.effectKey,
operationId: effect.operationId,
occurredAt: effect.createdAt,
hqStructureId: hqId,
hqName: hqId != null ? hqNames.get(hqId) ?? null : null,
notes: effect.reconciliationNotes,
lines: lines.map((line) => ({
resourceId: line.resourceId,
resourceName: resourceNames.get(line.resourceId) ?? `Resource #${line.resourceId}`,
amount: line.amount,
})),
};
});
return { extractions, total: extractions.length };
}

75
src/lib/shipping/cargo.ts Normal file
View file

@ -0,0 +1,75 @@
/**
* Pure helpers for vehicle virtual-cargo rules.
*
* Kept free of Payload/DB access so the enforcement seam in
* `createShipment` can be reasoned about (and unit-tested) in isolation.
*/
/** A shipment cargo line, as passed to `createShipment`. */
export interface CargoLine {
relationTo: string;
value: number | { id: number } | null;
amount: number;
}
/** A single entry on a vehicle template's `disallowedCargo` array. */
export interface DisallowedCargoEntry {
item: { relationTo: string; value: number | { id: number } } | number | null;
amount?: number | null;
}
/**
* Resolve a disallowed-cargo entry's item to a comparable `(relationTo, id)`
* pair, tolerating the raw relationship shape stored on the vehicle template.
*/
function normalizedItem(entry: DisallowedCargoEntry): { relationTo: string; id: number } | null {
const item = entry.item;
if (!item || typeof item !== "object") return null;
const relationTo = item.relationTo;
const raw = (item as { value?: number | { id?: number } | null }).value;
const id = typeof raw === "number" ? raw : raw?.id;
if (relationTo == null || id == null) return null;
return { relationTo, id };
}
export interface DisallowedMatch {
relationTo: string;
itemId: number;
/** Amount the entry permits (0 = full ban). */
cap: number;
}
/**
* Return the first cargo line that a vehicle template forbids, or `null` when
* the cargo is permitted.
*
* A line matches a `disallowedCargo` entry when the `(relationTo, itemId)` pair
* is equal. An entry with `amount === 0` (the default) forbids the item
* entirely; an entry with `amount > 0` only forbids quantities above that cap.
*/
export function findDisallowedCargo(
disallowedCargo: DisallowedCargoEntry[] | null | undefined,
cargo: CargoLine[],
): DisallowedMatch | null {
if (!disallowedCargo || disallowedCargo.length === 0 || !cargo.length) return null;
for (const line of cargo) {
const itemId =
typeof line.value === "number" ? line.value : (line.value as { id: number } | null)?.id;
if (itemId == null) continue;
const match = disallowedCargo.find((entry) => {
const resolved = normalizedItem(entry);
return resolved && resolved.relationTo === line.relationTo && resolved.id === itemId;
});
if (!match) continue;
const cap = match.amount ?? 0;
if (cap === 0 || line.amount > cap) {
return { relationTo: line.relationTo, itemId, cap };
}
}
return null;
}

View file

@ -0,0 +1,33 @@
/**
* Single source of truth for vehicle category presentation. The card grid and
* the detail page both read from here so colors and labels never drift apart.
*/
export const VEHICLE_CATEGORY_LABELS: Record<string, string> = {
civilian: "Civilian",
utility: "Utility",
transport: "Transport",
drone: "Drone",
weaponized: "Weaponized",
static: "Static",
military: "Military",
};
/** Pill classes (Tailwind): -500/20 background with matching -400 text. */
export const VEHICLE_CATEGORY_COLORS: Record<string, string> = {
civilian: "bg-stone-500/20 text-stone-400",
utility: "bg-emerald-500/20 text-emerald-400",
transport: "bg-blue-500/20 text-blue-400",
drone: "bg-violet-500/20 text-violet-400",
weaponized: "bg-red-500/20 text-red-400",
static: "bg-slate-500/20 text-slate-400",
military: "bg-amber-500/20 text-amber-400",
};
export function categoryPillClasses(category: string): string {
return VEHICLE_CATEGORY_COLORS[category] ?? "bg-muted text-muted-foreground";
}
export function categoryLabel(category: string): string {
return VEHICLE_CATEGORY_LABELS[category] ?? category;
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,15 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TYPE "public"."enum_vehicles_category" ADD VALUE 'drone' BEFORE 'weaponized';
ALTER TYPE "public"."enum_vehicles_category" ADD VALUE 'static' BEFORE 'military';`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "vehicles_category" ALTER COLUMN "value" SET DATA TYPE text;
DROP TYPE "public"."enum_vehicles_category";
CREATE TYPE "public"."enum_vehicles_category" AS ENUM('civilian', 'utility', 'transport', 'weaponized', 'military');
ALTER TABLE "vehicles_category" ALTER COLUMN "value" SET DATA TYPE "public"."enum_vehicles_category" USING "value"::"public"."enum_vehicles_category";`)
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,20 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
CREATE TABLE "vehicles_disallowed_cargo" (
"_order" integer NOT NULL,
"_parent_id" integer NOT NULL,
"id" varchar PRIMARY KEY NOT NULL,
"amount" numeric DEFAULT 0
);
ALTER TABLE "vehicles_disallowed_cargo" ADD CONSTRAINT "vehicles_disallowed_cargo_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."vehicles"("id") ON DELETE cascade ON UPDATE no action;
CREATE INDEX "vehicles_disallowed_cargo_order_idx" ON "vehicles_disallowed_cargo" USING btree ("_order");
CREATE INDEX "vehicles_disallowed_cargo_parent_id_idx" ON "vehicles_disallowed_cargo" USING btree ("_parent_id");`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
DROP TABLE "vehicles_disallowed_cargo" CASCADE;`)
}

File diff suppressed because one or more lines are too long

View file

@ -148,6 +148,9 @@ import * as migration_20261020_191433_add_interior_module_effect_types from './2
import * as migration_20261020_200000_add_interior_asset_outputs_flag from './20261020_200000_add_interior_asset_outputs_flag';
import * as migration_20261020_201242_add_room_fixture_blocks_station from './20261020_201242_add_room_fixture_blocks_station';
import * as migration_20261022_170228_add_vehicle_mod_field from './20261022_170228_add_vehicle_mod_field';
import * as migration_20261026_073228_add_vehicle_category_static_and_drone from './20261026_073228_add_vehicle_category_static_and_drone';
import * as migration_20261026_195910_add_vehicle_disallowed_cargo_field from './20261026_195910_add_vehicle_disallowed_cargo_field';
import * as migration_20261026_205453_add_operation_effects_pending_action_and_decisions from './20261026_205453_add_operation_effects_pending_action_and_decisions';
export const migrations = [
{
@ -898,6 +901,21 @@ export const migrations = [
{
up: migration_20261022_170228_add_vehicle_mod_field.up,
down: migration_20261022_170228_add_vehicle_mod_field.down,
name: '20261022_170228_add_vehicle_mod_field'
name: '20261022_170228_add_vehicle_mod_field',
},
{
up: migration_20261026_073228_add_vehicle_category_static_and_drone.up,
down: migration_20261026_073228_add_vehicle_category_static_and_drone.down,
name: '20261026_073228_add_vehicle_category_static_and_drone',
},
{
up: migration_20261026_195910_add_vehicle_disallowed_cargo_field.up,
down: migration_20261026_195910_add_vehicle_disallowed_cargo_field.down,
name: '20261026_195910_add_vehicle_disallowed_cargo_field',
},
{
up: migration_20261026_205453_add_operation_effects_pending_action_and_decisions.up,
down: migration_20261026_205453_add_operation_effects_pending_action_and_decisions.down,
name: '20261026_205453_add_operation_effects_pending_action_and_decisions'
},
];

File diff suppressed because it is too large Load diff

View file

@ -137,6 +137,7 @@ export interface Config {
maps: Map;
'map-roads': MapRoad;
'map-zones': MapZone;
'map-objectives': MapObjective;
'resource-nodes': ResourceNode;
'narrative-events': NarrativeEvent;
'story-beats': StoryBeat;
@ -250,6 +251,7 @@ export interface Config {
maps: MapsSelect<false> | MapsSelect<true>;
'map-roads': MapRoadsSelect<false> | MapRoadsSelect<true>;
'map-zones': MapZonesSelect<false> | MapZonesSelect<true>;
'map-objectives': MapObjectivesSelect<false> | MapObjectivesSelect<true>;
'resource-nodes': ResourceNodesSelect<false> | ResourceNodesSelect<true>;
'narrative-events': NarrativeEventsSelect<false> | NarrativeEventsSelect<true>;
'story-beats': StoryBeatsSelect<false> | StoryBeatsSelect<true>;
@ -899,6 +901,8 @@ export interface Role {
| 'resource-nodes:read'
| 'resource-nodes:author'
| 'admin:resource-nodes:manage'
| 'map-objectives:read'
| 'admin:map-objectives:manage'
| 'narrative-events:create'
| 'narrative-events:read'
| 'narrative-events:update'
@ -2421,7 +2425,7 @@ export interface Vehicle {
[k: string]: unknown;
} | null;
image?: (number | null) | Media;
category?: ('civilian' | 'utility' | 'transport' | 'weaponized' | 'military')[] | null;
category?: ('civilian' | 'utility' | 'transport' | 'drone' | 'weaponized' | 'static' | 'military')[] | null;
/**
* Fuel configuration for this vehicle. Defines what fuel type it uses, how much it can hold, and how fast it consumes fuel.
*/
@ -2518,6 +2522,31 @@ export interface Vehicle {
id?: string | null;
}[]
| null;
/**
* Items this vehicle may NOT carry when used virtually (e.g., during deliveries, moving troops). A shipment using this vehicle is rejected before its cargo is deducted if any cargo line matches.
*/
disallowedCargo?:
| {
item:
| {
relationTo: 'assets';
value: number | Asset;
}
| {
relationTo: 'vehicles';
value: number | Vehicle;
}
| {
relationTo: 'resources';
value: number | Resource;
};
/**
* Optional cap. Leave at 0 to forbid the item entirely; set a positive number to allow up to that amount only.
*/
amount?: number | null;
id?: string | null;
}[]
| null;
maxHealth?: number | null;
armorRating?: ('none' | 'light' | 'medium' | 'heavy' | 'composite') | null;
maxSpeedOnRoad?: number | null;
@ -3399,6 +3428,8 @@ export interface GameEventLog {
| 'resource-nodes:read'
| 'resource-nodes:author'
| 'admin:resource-nodes:manage'
| 'map-objectives:read'
| 'admin:map-objectives:manage'
| 'narrative-events:create'
| 'narrative-events:read'
| 'narrative-events:update'
@ -3575,6 +3606,7 @@ export interface GameEventLog {
| 'wiki-templates'
| 'form-submissions'
| 'mission-map-markers'
| 'map-objectives'
| 'contribution-entries'
| 'game-servers'
| 'assignment-transfers'
@ -6018,6 +6050,51 @@ export interface MapZone {
updatedAt: string;
createdAt: string;
}
/**
* Strategic objectives shown on the world map and mission planning maps. Superuser-authored.
*
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "map-objectives".
*/
export interface MapObjective {
id: number;
/**
* Map label, e.g. "OBJ ALPHA". Shown under the marker on every map.
*/
name: string;
/**
* Planning note shown in the marker popup.
*/
description?: string | null;
map: number | Map;
/**
* CfgMarkers class name, e.g. mil_objective, o_objective, hd_objective.
*/
markerType?: string | null;
/**
* Drives the marker colour: red for active, green for secured, grey for failed.
*/
status: 'active' | 'secured' | 'failed';
/**
* Hidden from everyone except superusers (and drawn dimmed for them) until revealed.
*/
redacted?: boolean | null;
/**
* [x, y] in map meters (origin top-left, y south).
*/
position:
| {
[k: string]: unknown;
}
| unknown[]
| string
| number
| boolean
| null;
createdBy?: (number | null) | User;
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "resource-nodes".
@ -6455,7 +6532,19 @@ export interface OperationEffect {
| 'operation.objective-updated'
| 'operation.extraction-recorded'
| 'operation.inventory-recorded';
status: 'applied' | 'pending' | 'failed' | 'reversed';
status: 'applied' | 'pending' | 'pending_action' | 'failed' | 'reversed';
/**
* Per-item officer resolution for a gated extraction: [{ relationTo, id, decision }]. decision is keep (deposit), scrap, or expel (hold back). Absent = not yet reviewed.
*/
decisions?:
| {
[k: string]: unknown;
}
| unknown[]
| string
| number
| boolean
| null;
payload?:
| {
[k: string]: unknown;
@ -8457,6 +8546,24 @@ export interface PayloadMcpApiKey {
*/
delete?: boolean | null;
};
mapObjectives?: {
/**
* Allow clients to find map-objectives.
*/
find?: boolean | null;
/**
* Allow clients to create map-objectives.
*/
create?: boolean | null;
/**
* Allow clients to update map-objectives.
*/
update?: boolean | null;
/**
* Allow clients to delete map-objectives.
*/
delete?: boolean | null;
};
resourceNodes?: {
/**
* Allow clients to find resource-nodes.
@ -9232,6 +9339,10 @@ export interface PayloadLockedDocument {
relationTo: 'map-zones';
value: number | MapZone;
} | null)
| ({
relationTo: 'map-objectives';
value: number | MapObjective;
} | null)
| ({
relationTo: 'resource-nodes';
value: number | ResourceNode;
@ -10930,6 +11041,13 @@ export interface VehiclesSelect<T extends boolean = true> {
amount?: T;
id?: T;
};
disallowedCargo?:
| T
| {
item?: T;
amount?: T;
id?: T;
};
maxHealth?: T;
armorRating?: T;
maxSpeedOnRoad?: T;
@ -11706,6 +11824,22 @@ export interface MapZonesSelect<T extends boolean = true> {
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "map-objectives_select".
*/
export interface MapObjectivesSelect<T extends boolean = true> {
name?: T;
description?: T;
map?: T;
markerType?: T;
status?: T;
redacted?: T;
position?: T;
createdBy?: T;
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "resource-nodes_select".
@ -11939,6 +12073,7 @@ export interface OperationEffectsSelect<T extends boolean = true> {
effectKey?: T;
effectType?: T;
status?: T;
decisions?: T;
payload?: T;
reversalOf?: T;
reversedBy?: T;
@ -12937,6 +13072,14 @@ export interface PayloadMcpApiKeysSelect<T extends boolean = true> {
update?: T;
delete?: T;
};
mapObjectives?:
| T
| {
find?: T;
create?: T;
update?: T;
delete?: T;
};
resourceNodes?:
| T
| {

View file

@ -22,6 +22,7 @@ import { MissionMapMarkers } from "@/collections/intelligence/MissionMapMarkers"
import { Maps } from "@/collections/world/Maps";
import { MapRoads } from "@/collections/world/MapRoads";
import { MapZones } from "@/collections/world/MapZones";
import { MapObjectives } from "@/collections/world/MapObjectives";
import { ResourceNodes } from "@/collections/world/ResourceNodes";
import { Campaigns } from "@/collections/intelligence/Campaigns";
import { Qualifications } from "@/collections/users/Qualifications";
@ -398,6 +399,7 @@ const collections = [
Maps,
MapRoads,
MapZones,
MapObjectives,
ResourceNodes,
NarrativeEvents,

View file

@ -34,7 +34,12 @@ export interface PermissionGroup {
export const PERMISSION_GROUPS: PermissionGroup[] = [
{
group: "System",
permissions: [{ value: "system:admin-access", label: "Superuser Tier (user management, notification oversight, final approval states)" }],
permissions: [
{
value: "system:admin-access",
label: "Superuser Tier (user management, notification oversight, final approval states)",
},
],
},
// ---- Media ---------------------------------------------------------------
@ -586,6 +591,14 @@ export const PERMISSION_GROUPS: PermissionGroup[] = [
{ value: "resource-nodes:read", label: "Read Resource Nodes" },
{ value: "resource-nodes:author", label: "Author Resource Nodes" },
{ value: "admin:resource-nodes:manage", label: "Manage Resource Nodes Admin Page" },
{
value: "map-objectives:read",
label: "Read Strategic Objectives (writes need the Superuser Tier)",
},
{
value: "admin:map-objectives:manage",
label: "Manage Strategic Objectives Admin Page",
},
],
},
{
@ -1144,6 +1157,8 @@ export const ALL_PERMISSION_VALUES = PERMISSION_GROUPS.flatMap((g) =>
"resource-nodes:read",
"resource-nodes:author",
"admin:resource-nodes:manage",
"map-objectives:read",
"admin:map-objectives:manage",
"narrative-events:create",
"narrative-events:read",
"narrative-events:update",

View file

@ -57,6 +57,7 @@ interface GameEventInput {
| "reinforcement-pools"
| "form-submissions"
| "mission-map-markers"
| "map-objectives"
| "contribution-entries"
| "journals"
| "awards";

View file

@ -178,6 +178,13 @@ export const EventTypes = {
MissionMapMarkersClear: "mission:map-markers-clear",
MissionPlanningDelegates: "mission:planning-delegates",
// Strategic objectives (world map + planning maps)
MapObjectiveCreate: "map:objective-created",
MapObjectiveUpdate: "map:objective-updated",
MapObjectiveStatus: "map:objective-status",
MapObjectiveReveal: "map:objective-reveal",
MapObjectiveDelete: "map:objective-deleted",
// Contributions / XP
ContributionQueued: "contribution:queue",
ContributionGranted: "contribution:grant",

View file

@ -0,0 +1,126 @@
import { expect, test, type Page } from "@playwright/test";
/**
* Strategic objectives: a superuser authors a map objective through the REST
* gate and both surfaces render it (world map and the mission planning map of
* a mission on the same terrain). Seeds its own map + mission through
* cookie-authed REST (the e2e dev user carries a superuser role).
*/
test.describe("Strategic objectives", () => {
let mapId: number | null = null;
let missionId: number | null = null;
async function login(page: Page) {
const res = await page.request.post("/api/users/login", {
data: { username: "dev", password: "Test123" },
});
expect(res.ok(), `login failed: ${res.status()}`).toBe(true);
}
async function createObjective(
page: Page,
data: Record<string, unknown>,
): Promise<{ id: number }> {
const res = await page.request.post("/api/map-objectives", {
data: { map: mapId, markerType: "mil_objective", status: "active", ...data },
});
expect(res.ok(), await res.text()).toBe(true);
return (await res.json()).doc as { id: number };
}
test.afterAll(async ({ browser }) => {
const p = await browser.newPage().catch(() => null);
if (!p) return;
await login(p);
if (missionId) await p.request.delete(`/api/missions/${missionId}`);
// Objectives are removed by the maps beforeDelete hook.
if (mapId) await p.request.delete(`/api/maps/${mapId}`);
await p.close();
});
test("renders on the world map and the mission planning map", async ({ page }) => {
await login(page);
await page.addInitScript(() => window.localStorage.setItem("ptf:tours:opted-out", "1"));
page.on("console", (msg) => {
if (msg.type() === "error") console.log("[CONSOLE ERROR]", msg.text());
});
page.on("pageerror", (err) => console.log("[PAGE ERROR]", err.message));
page.on("requestfailed", (req) =>
console.log("[REQUEST FAILED]", req.url(), req.failure()?.errorText ?? ""),
);
const mapRes = await page.request.post("/api/maps", {
data: {
name: "E2E Objective Map",
worldSizeWidth: 8192,
worldSizeHeight: 8192,
basemapMode: "image",
isActive: true,
worldMap: true,
},
});
expect(mapRes.ok(), await mapRes.text()).toBe(true);
mapId = (await mapRes.json()).doc.id;
const meRes = await page.request.get("/api/users/me");
const meId = (await meRes.json()).user.id as number;
const missionRes = await page.request.post("/api/missions", {
data: {
name: "E2E Objective Op",
codeName: "E2E-OBJ",
summary: "Objective layer e2e mission",
operationType: "main",
classification: {
map: mapId,
missionType: "PvE",
startDateTime: new Date(Date.now() + 3 * 86_400_000).toISOString(),
estimatedDuration: 60,
planningMapEnabled: true,
},
ownershipAndStatus: { authors: [meId], status: "Scheduled", visibility: "unit" },
briefing: [],
gameDetails: { serverDetails: { serverIp: "127.0.0.1", serverPort: 2302 } },
missionRoles: { maxPlayers: 32, providedRoles: [] },
},
});
expect(missionRes.ok(), await missionRes.text()).toBe(true);
missionId = (await missionRes.json()).doc.id;
// REST create also exercises the superuser write gate.
await createObjective(page, {
name: "OBJ ALPHA",
description: "Take the ridge",
status: "active",
position: [4096, 4096],
});
await createObjective(page, {
name: "OBJ BRAVO",
status: "secured",
redacted: true,
position: [3000, 3500],
});
await page.goto(`/map/${mapId}`);
await expect(page.locator(".objective-marker-name", { hasText: "OBJ ALPHA" })).toBeVisible({
timeout: 60_000,
});
// Superusers see redacted objectives, flagged.
await expect(
page.locator(".objective-marker-name", { hasText: "OBJ BRAVO // REDACTED" }),
).toBeVisible();
await page.goto(`/intelligence/missions/${missionId}`);
const section = page.locator("section[aria-label='Mission planning map']");
await expect(section).toBeVisible({ timeout: 60_000 });
await expect(section.locator(".objective-marker-name", { hasText: "OBJ ALPHA" })).toBeVisible({
timeout: 60_000,
});
await expect(
section.locator(".objective-marker-name", { hasText: "OBJ BRAVO // REDACTED" }),
).toBeVisible();
// The export path is covered by the unit tests; no clipboard in headless.
await section.screenshot({ path: "test-results/mission-planning-objectives.png" });
});
});

View file

@ -0,0 +1,298 @@
import { getTestPayload } from "../helpers/get-test-payload";
import type { Payload } from "payload";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { User } from "@/payload-types";
import {
clearMapObjectives,
createMapObjective,
deleteMapObjective,
listMapObjectives,
normalizeObjectiveInput,
objectiveFromDoc,
objectiveWorldSize,
updateMapObjective,
} from "@/lib/map/objectives";
import {
DEFAULT_OBJECTIVE_MARKER_TYPE,
OBJECTIVE_STATUS_META,
objectiveStatusColor,
} from "@/lib/map/objectiveTypes";
import { hasPermission } from "@/utils/access-control/hasPermission";
const WORLD = { width: 8192, height: 8192 };
describe("Objective validation", () => {
it("normalizes a minimal objective and applies defaults", () => {
const result = normalizeObjectiveInput(
{ name: " OBJ\nALPHA ", position: [500.123, 900], description: " Take the ridge. " },
WORLD,
);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.data.name).toBe("OBJ ALPHA");
expect(result.data.position).toEqual([500.12, 900]);
expect(result.data.markerType).toBe(DEFAULT_OBJECTIVE_MARKER_TYPE);
expect(result.data.status).toBe("active");
expect(result.data.redacted).toBe(false);
expect(result.data.description).toBe("Take the ridge.");
});
it("rejects missing names, unknown types, bad status and off-world points", () => {
expect(normalizeObjectiveInput({ position: [1, 1] }, WORLD)).toMatchObject({ ok: false });
expect(normalizeObjectiveInput({ name: " ", position: [1, 1] }, WORLD)).toMatchObject({
ok: false,
});
expect(
normalizeObjectiveInput({ name: "OBJ", markerType: "not_a_marker", position: [1, 1] }, WORLD),
).toMatchObject({ ok: false });
expect(
normalizeObjectiveInput({ name: "OBJ", status: "nuked", position: [1, 1] }, WORLD),
).toMatchObject({ ok: false });
expect(normalizeObjectiveInput({ name: "OBJ", position: "here" }, WORLD)).toMatchObject({
ok: false,
});
expect(normalizeObjectiveInput({ name: "OBJ", position: [99999, 1] }, WORLD)).toMatchObject({
ok: false,
});
});
it("keeps markers just off-world (same margin as planning markers)", () => {
const result = normalizeObjectiveInput({ name: "EDGE", position: [-1500, 8300] }, WORLD);
expect(result.ok).toBe(true);
});
it("coerces stored rows and drops broken geometry", () => {
expect(objectiveFromDoc({ id: 1, map: 2, position: "bad" })).toBeNull();
expect(
objectiveFromDoc({ id: 2, map: 2, name: "OBJ BRAVO", position: [10, 20], status: "bogus" }),
).toMatchObject({
name: "OBJ BRAVO",
status: "active",
markerType: DEFAULT_OBJECTIVE_MARKER_TYPE,
});
});
it("maps status to Arma marker colours", () => {
expect(objectiveStatusColor("active")).toBe("ColorRed");
expect(objectiveStatusColor("secured")).toBe("ColorGreen");
expect(objectiveStatusColor("failed")).toBe("ColorGrey");
expect(objectiveStatusColor("unknown")).toBe("ColorRed");
expect(OBJECTIVE_STATUS_META.secured.label).toBe("Secured");
});
it("reads world size with the same defaults as the map config", () => {
expect(objectiveWorldSize({ worldSizeWidth: 4096, worldSizeHeight: 2048 })).toEqual({
width: 4096,
height: 2048,
});
expect(objectiveWorldSize({})).toEqual({ width: 8192, height: 8192 });
});
});
describe("Map objective service", () => {
let payload: Payload;
const RUN = `obj-${Date.now().toString(36)}`;
let mapId: number;
let superRoleId: number;
let superuser: User;
let player: User;
const userIds: number[] = [];
const makeUser = async (username: string, roleDocs: number[] = []): Promise<User> => {
const user = (await payload.create({
collection: "users",
data: {
username,
discordUsername: username,
displayName: "OBJECTIVE TEST",
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles: ["user"],
roleDocs,
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
userIds.push(user.id);
return user;
};
const makeMap = async (label: string): Promise<number> => {
const map = await payload.create({
collection: "maps",
data: {
name: `${RUN} ${label}`,
worldSizeWidth: 4096,
worldSizeHeight: 4096,
basemapMode: "image",
},
overrideAccess: true,
depth: 0,
});
return map.id;
};
beforeAll(async () => {
payload = await getTestPayload();
mapId = await makeMap("Map");
const role = await payload.create({
collection: "roles",
data: {
name: `${RUN}-super`,
slug: `${RUN}-super`,
isSuperuser: true,
permissions: ["system:admin-access"],
},
overrideAccess: true,
depth: 0,
});
superRoleId = role.id;
superuser = await makeUser(`${RUN}-super`, [superRoleId]);
player = await makeUser(`${RUN}-player`);
});
afterAll(async () => {
if (!payload) return;
await payload.delete({ collection: "maps", id: mapId, overrideAccess: true }).catch(() => {});
for (const id of userIds) {
for (const collection of ["bank-accounts", "profiles"] as const) {
const field = collection === "bank-accounts" ? "ownerUser" : "user";
const docs = await payload
.find({ collection, where: { [field]: { equals: id } }, depth: 0, overrideAccess: true })
.catch(() => null);
for (const doc of docs?.docs ?? []) {
await payload.delete({ collection, id: doc.id, overrideAccess: true }).catch(() => {});
}
}
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
}
await payload
.delete({ collection: "roles", id: superRoleId, overrideAccess: true })
.catch(() => {});
});
it("gates writes behind the superuser tier", async () => {
expect(await hasPermission(payload, superuser, "system:admin-access")).toBe(true);
expect(await hasPermission(payload, player, "system:admin-access")).toBe(false);
});
it("creates, updates, filters redacted rows and deletes", async () => {
const visible = await createMapObjective(
payload,
mapId,
{ name: "OBJ ALPHA", position: [500, 600], description: "Ridge line" },
superuser.id,
);
expect(visible).toMatchObject({
name: "OBJ ALPHA",
status: "active",
redacted: false,
markerType: DEFAULT_OBJECTIVE_MARKER_TYPE,
position: [500, 600],
});
const hidden = await createMapObjective(
payload,
mapId,
{ name: "OBJ BRAVO", position: [800, 900], redacted: true },
superuser.id,
);
// Player-facing list hides redacted rows; the superuser list keeps them.
expect((await listMapObjectives(payload, mapId)).map((o) => o.id)).toEqual([visible.id]);
expect(
(await listMapObjectives(payload, mapId, { includeRedacted: true })).map((o) => o.id),
).toEqual([visible.id, hidden.id]);
const secured = await updateMapObjective(payload, visible.id, {
...visible,
status: "secured",
});
expect(secured.status).toBe("secured");
expect((await listMapObjectives(payload, mapId))[0].status).toBe("secured");
await expect(
updateMapObjective(payload, visible.id, { ...visible, position: [99999, 1] }),
).rejects.toThrow("on the map");
await expect(updateMapObjective(payload, -1, visible)).rejects.toThrow("not found");
await deleteMapObjective(payload, hidden.id);
expect(
(await listMapObjectives(payload, mapId, { includeRedacted: true })).map((o) => o.id),
).toEqual([visible.id]);
expect(await clearMapObjectives(payload, mapId)).toBe(1);
expect(await listMapObjectives(payload, mapId, { includeRedacted: true })).toEqual([]);
});
it("emits create, status and reveal events targeting the objective", async () => {
const objective = await createMapObjective(
payload,
mapId,
{ name: "OBJ CHARLIE", position: [100, 100], redacted: true },
superuser.id,
);
await updateMapObjective(payload, objective.id, { ...objective, status: "failed" });
await updateMapObjective(payload, objective.id, {
...objective,
status: "failed",
redacted: false,
});
const events = await payload.find({
collection: "game-event-logs",
where: {
and: [
{ targetCollection: { equals: "map-objectives" } },
{ targetId: { equals: objective.id } },
],
},
sort: "id",
depth: 0,
limit: 20,
pagination: false,
overrideAccess: true,
});
const types = events.docs.map((event) => event.type);
expect(types).toContain("map:objective-created");
expect(types).toContain("map:objective-status");
expect(types).toContain("map:objective-reveal");
await deleteMapObjective(payload, objective.id);
const after = await payload.find({
collection: "game-event-logs",
where: {
and: [
{ targetCollection: { equals: "map-objectives" } },
{ targetId: { equals: objective.id } },
{ type: { equals: "map:objective-deleted" } },
],
},
depth: 0,
limit: 1,
overrideAccess: true,
});
expect(after.docs).toHaveLength(1);
});
it("removes a map's objectives when the map is deleted", async () => {
const doomedMapId = await makeMap("Doomed");
await createMapObjective(
payload,
doomedMapId,
{ name: "OBJ DOOMED", position: [10, 10] },
superuser.id,
);
await payload.delete({ collection: "maps", id: doomedMapId, overrideAccess: true });
const remaining = await payload.find({
collection: "map-objectives",
where: { map: { equals: doomedMapId } },
depth: 0,
limit: 1,
overrideAccess: true,
});
expect(remaining.docs).toHaveLength(0);
});
});

View file

@ -2,6 +2,7 @@ import { getTestPayload } from "../helpers/get-test-payload";
import { Payload } from "payload";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { applyEconomyEffect, DEFAULT_ECONOMY_CAPS } from "@/lib/operations/economy";
import { resolveLogisticsExtraction } from "@/lib/operations/settlementExtraction";
import { ECONOMY_NOTE_PREFIX, type EconomyRecord } from "@/lib/operations/economyConfig";
import { resetMarketStateDocs } from "@/lib/economy/consumption";
import { applyTransaction, ensurePersonalAccount } from "@/lib/banking";
@ -148,7 +149,13 @@ async function hookExtraction(
expect(effects.docs).toHaveLength(1);
const effect = effects.docs[0] as { id: number; status: string };
opEffectIds.push(effect.id);
expect(effect.status).toBe("applied");
// A player extraction applies immediately; a logistics extraction is gated
// and parks as pending_action. Resolve it (keep all) so the returned effect
// is the applied, market-feeding one the adapter expects.
if (effect.status === "pending_action") {
const resolved = await resolveLogisticsExtraction(payload, effect.id, null);
expect(resolved.success).toBe(true);
}
return { effectId: effect.id, eventId: sync.eventId as string };
}

View file

@ -0,0 +1,242 @@
import { getTestPayload } from "../helpers/get-test-payload";
import { Payload } from "payload";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { listPendingExtractions } from "@/lib/operations/surfaceQuery";
import type { Structure } from "@/payload-types";
let payload: Payload;
const RUN = `extractions-surf-${Date.now().toString(36)}`;
const userIds: number[] = [];
const resourceIds: number[] = [];
const structureIds: number[] = [];
const blueprintIds: number[] = [];
const effectIds: number[] = [];
let serverId: number;
let mapId: number;
let resourceA: number;
let resourceB: number;
let superUserId: number;
let plainUserId: number;
async function makeUser(label: string): Promise<number> {
const user = await payload.create({
collection: "users",
data: {
username: `${RUN}-${label}`,
discordUsername: `${RUN}-${label}-discord`,
steamId: `${RUN}-steam-${label}`,
password: "Test1234",
displayName: `${RUN} ${label}`,
},
overrideAccess: true,
depth: 0,
});
userIds.push(user.id);
return user.id;
}
async function makeResource(label: string): Promise<number> {
const resource = await payload.create({
collection: "resources",
data: {
name: `${RUN} ${label}`,
codeName: `${RUN}-${label}`,
approvalStatus: "in_progress",
type: "physical",
baseValue: 1,
rarity: "common",
unitOfMeasure: "kg",
massPerUnit: 1,
gridWidth: 1,
gridHeight: 1,
},
overrideAccess: true,
depth: 0,
});
resourceIds.push(resource.id);
return resource.id;
}
async function makeHq(label: string, blueprintId: number): Promise<number> {
const structure = await payload.create({
collection: "game-structures",
data: {
name: `${RUN} ${label}`,
type: blueprintId,
map: mapId,
coordinates: [100, 100],
constructionStatus: "complete",
storedResources: [],
},
overrideAccess: true,
depth: 0,
});
structureIds.push(structure.id);
return structure.id;
}
/**
* Emit a real logistics extraction sync event; the pipeline derives the
* operation-event + extraction-recorded effect and parks it as `pending_action`.
* Returns the created effect.
*/
async function emitExtraction(
label: string,
operationId: string,
hqId: number,
resourceId: number,
amount: number,
): Promise<number> {
const syncDoc = await payload.create({
collection: "arma-sync-events",
data: {
eventId: `${RUN}-${label}`,
server: serverId,
type: "operation.extraction",
occurredAt: new Date().toISOString(),
payload: {
operationId,
version: 1,
actorId: null,
kind: "logistics",
hqStructureId: hqId,
items: [{ resourceId, amount }],
},
},
overrideAccess: true,
depth: 0,
});
const opEvents = await payload.find({
collection: "operation-events",
where: { sourceEvent: { equals: syncDoc.id } },
limit: 1,
depth: 0,
overrideAccess: true,
});
const effects = await payload.find({
collection: "operation-effects",
where: { operationEvent: { equals: opEvents.docs[0].id } },
limit: 1,
depth: 0,
overrideAccess: true,
});
const effectId = effects.docs[0].id as number;
effectIds.push(effectId);
return effectId;
}
beforeAll(async () => {
payload = await getTestPayload();
superUserId = await makeUser("admin");
plainUserId = await makeUser("soldier");
const server = await payload.create({
collection: "game-servers",
data: { serverId: `${RUN}-srv`, name: `${RUN} Server`, status: "online" },
overrideAccess: true,
depth: 0,
});
serverId = server.id;
const map = await payload.create({
collection: "maps",
data: { name: `${RUN} Map`, worldSizeWidth: 4096, worldSizeHeight: 4096, basemapMode: "image" },
overrideAccess: true,
depth: 0,
});
mapId = map.id;
resourceA = await makeResource("Ammo");
resourceB = await makeResource("Fuel");
const blueprint = await payload.create({
collection: "structures",
data: {
name: `${RUN} HQ Depot`,
codeName: `${RUN}-hq-depot`,
approvalStatus: "in_progress",
description: { root: { children: [{ text: "" }], direction: "ltr", format: "" }, version: 1 } as unknown as Structure["description"],
category: "logistics",
materials: [{ resource: resourceA, amount: 1 }],
constructionDurationMinutes: 1,
terrainType: "land",
maxHealth: 100,
},
overrideAccess: true,
depth: 0,
});
blueprintIds.push(blueprint.id);
const hq = await makeHq("HQ", blueprint.id);
// Two parked logistics extractions awaiting an officer's decision.
await emitExtraction(`${RUN}-evt-keep`, `${RUN}-op-keep`, hq, resourceA, 25);
await emitExtraction(`${RUN}-evt-hold`, `${RUN}-op-hold`, hq, resourceB, 40);
// A third logistics extraction that the officer already resolved (applied)
// must NOT surface as pending.
const doneEffectId = await emitExtraction(`${RUN}-evt-done`, `${RUN}-op-done`, hq, resourceA, 10);
await payload.update({
collection: "operation-effects",
id: doneEffectId,
data: { status: "applied", appliedAt: new Date().toISOString() },
overrideAccess: true,
depth: 0,
});
});
afterAll(async () => {
if (!payload) return;
for (const id of effectIds) {
await payload.delete({ collection: "operation-effects", id, overrideAccess: true }).catch(() => {});
}
for (const id of structureIds) {
await payload.delete({ collection: "game-structures", id, overrideAccess: true }).catch(() => {});
}
for (const id of blueprintIds) {
await payload.delete({ collection: "structures", id, overrideAccess: true }).catch(() => {});
}
for (const id of resourceIds) {
await payload.delete({ collection: "resources", id, overrideAccess: true }).catch(() => {});
}
await payload.delete({ collection: "maps", id: mapId, overrideAccess: true }).catch(() => {});
await payload.delete({ collection: "game-servers", id: serverId, overrideAccess: true }).catch(() => {});
for (const id of userIds) {
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
}
});
describe("listPendingExtractions surface", () => {
it("returns only pending_action extractions with resolved resource and HQ names", async () => {
const result = await listPendingExtractions(payload, { id: superUserId });
expect(result.total).toBe(2);
expect(result.extractions).toHaveLength(2);
const byOp = Object.fromEntries(result.extractions.map((ex) => [ex.operationId, ex]));
expect(byOp[`${RUN}-op-keep`]).toBeDefined();
expect(byOp[`${RUN}-op-hold`]).toBeDefined();
expect(byOp[`${RUN}-op-done`]).toBeUndefined();
const keep = byOp[`${RUN}-op-keep`];
expect(keep?.hqName).toContain("HQ");
expect(keep?.hqStructureId).toBeGreaterThan(0);
expect(keep?.lines).toEqual([
{ resourceId: resourceA, resourceName: `${RUN} Ammo`, amount: 25 },
]);
expect(keep?.notes).toBeNull();
const hold = byOp[`${RUN}-op-hold`];
expect(hold?.lines).toEqual([
{ resourceId: resourceB, resourceName: `${RUN} Fuel`, amount: 40 },
]);
});
it("opens the queue to any authenticated viewer (read is access-controlled open)", async () => {
const forSoldier = await listPendingExtractions(payload, { id: plainUserId });
expect(forSoldier.total).toBe(2);
expect(forSoldier.extractions.length).toBe(2);
});
});

View file

@ -2,6 +2,7 @@ import { getTestPayload } from "../helpers/get-test-payload";
import { Payload } from "payload";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { processOperationEvent } from "@/lib/operations/process";
import { resolveLogisticsExtraction } from "@/lib/operations/settlementExtraction";
import { reserveOperationAssets, type SettlementRecord } from "@/lib/operations/allocation";
import { ensureLockerStorage, getLockerGridDimensions } from "@/lib/locker";
import type { GameStructure, LockerStorage, OperationReservation, Structure } from "@/payload-types";
@ -493,8 +494,27 @@ describe("Operation settlement", () => {
expect(effects).toHaveLength(1);
const effect = effects[0];
expect(effect.effectType).toBe("operation.extraction-recorded");
expect(effect.status).toBe("applied");
expect(effect.appliedAt).toBeTruthy();
// Gated: the logistics extraction parks for officer review instead of
// auto-depositing. Nothing is deposited and the reservation is untouched.
expect(effect.status).toBe("pending_action");
expect(effect.appliedAt).toBeNull();
expect(effect.decisions).toBeNull();
expect(await storedAmountAt(hqId, resourceAId)).toBe(0);
expect((await findReservation(reservationKey))?.status).not.toBe("settled");
// The officer resolves it keeping everything (decisions = null => keep all).
const resolved = await resolveLogisticsExtraction(payload, effect.id, null);
expect(resolved.success).toBe(true);
// Re-read: the effect is now applied after the officer's resolution.
const afterResolve = await payload.findByID({
collection: "operation-effects",
id: effect.id,
depth: 0,
overrideAccess: true,
});
expect((afterResolve as unknown as typeof effect).status).toBe("applied");
// Exactly one deposit: 25 units at the designated HQ, none at the origin.
expect(await storedAmountAt(hqId, resourceAId)).toBe(25);
@ -602,7 +622,19 @@ describe("Operation settlement", () => {
const effects = await effectsForOperation(operationId);
expect(effects).toHaveLength(1);
expect(effects[0].status).toBe("applied");
expect(effects[0].status).toBe("pending_action");
// Gated: an officer resolves the parked extraction, which then deposits.
const resolved = await resolveLogisticsExtraction(payload, effects[0].id, null);
expect(resolved.success).toBe(true);
const afterResolve = await payload.findByID({
collection: "operation-effects",
id: effects[0].id,
depth: 0,
overrideAccess: true,
});
expect((afterResolve as unknown as { status: string }).status).toBe("applied");
expect(await storedAmountAt(hqId, resourceAId)).toBe(10);
});
@ -666,8 +698,23 @@ describe("Operation settlement", () => {
const effects = await effectsForOperation(operationId);
expect(effects).toHaveLength(1);
expect(effects[0].status).toBe("failed");
expect(effects[0].reconciliationNotes).toContain("hq-capacity");
// Gated: the effect parks for officer review (assets resolved) before it can
// fail on capacity. Only after the officer resolves does the full HQ surface.
expect(effects[0].status).toBe("pending_action");
expect(await storedAmountAt(hqId, resourceAId)).toBe(0);
const resolved = await resolveLogisticsExtraction(payload, effects[0].id, null);
expect(resolved.success).toBe(false);
// Still pending (recoverable): the officer can retry once HQ frees up.
const afterResolve = await payload.findByID({
collection: "operation-effects",
id: effects[0].id,
depth: 0,
overrideAccess: true,
});
expect((afterResolve as unknown as { status: string }).status).toBe("pending_action");
expect((afterResolve as unknown as { reconciliationNotes: string }).reconciliationNotes).toContain("hq-capacity");
expect(await storedAmountAt(hqId, resourceAId)).toBe(0);
});
@ -777,6 +824,10 @@ describe("Operation settlement", () => {
consumed: { cargo: [{ resourceId: resourceAId, amount: 6 }] },
});
// Officer reviews and keeps the extracted cargo before the mission fails.
const extractEffects = await effectsForOperation(operationId);
await resolveLogisticsExtraction(payload, extractEffects[0].id, null);
await emitRawEvent(`${RUN}-evt-fail-end`, "operation.end", {
operationId,
version: 1,
@ -819,6 +870,146 @@ describe("Operation settlement", () => {
expect(freshExtraction.reversedBy).toBeNull();
});
async function makeSecondResource(): Promise<number> {
const resource = await payload.create({
collection: "resources",
data: {
name: `${RUN} Scrap Ore`,
codeName: `${RUN}-scrap-ore`,
approvalStatus: "in_progress",
type: "physical",
baseValue: 1,
rarity: "common",
unitOfMeasure: "kg",
massPerUnit: 1,
gridWidth: 1,
gridHeight: 1,
},
overrideAccess: true,
depth: 0,
});
resourceIds.push(resource.id);
return resource.id;
}
it("holds back scrap/expel lines and deposits only the kept lines on resolve", async () => {
const secondResourceId = await makeSecondResource();
const operationId = `${RUN}-op-scrap`;
const hqId = await makeStructure("hq-scrap", hqBlueprintId);
await emitRawEvent(`${RUN}-evt-scrap`, "operation.extraction", {
operationId,
version: 1,
actorId: extractorId,
kind: "logistics",
hqStructureId: hqId,
items: [
{ resourceId: resourceAId, amount: 20 },
{ resourceId: secondResourceId, amount: 30 },
],
});
const effect = (await effectsForOperation(operationId))[0];
expect(effect.status).toBe("pending_action");
// Keep resourceA, scrap the second resource.
const decisions = [
{ relationTo: "resources" as const, id: secondResourceId, decision: "scrap" as const },
];
const resolved = await resolveLogisticsExtraction(payload, effect.id, decisions);
expect(resolved.success).toBe(true);
// Only the kept line deposits; the scraped line is held back entirely.
expect(await storedAmountAt(hqId, resourceAId)).toBe(20);
expect(await storedAmountAt(hqId, secondResourceId)).toBe(0);
const afterResolve = await payload.findByID({
collection: "operation-effects",
id: effect.id,
depth: 0,
overrideAccess: true,
});
expect((afterResolve as unknown as { status: string }).status).toBe("applied");
expect((afterResolve as unknown as { decisions: unknown }).decisions).toEqual(decisions);
});
it("lets the officer make room on a full HQ by expelling a line", async () => {
const secondResourceId = await makeSecondResource();
const operationId = `${RUN}-op-fit`;
// cappedBlueprintId caps at 5 mass; pre-stock 3 so a kept line of 1 fits.
const hqId = await makeStructure("hq-fit", cappedBlueprintId);
await payload.update({
collection: "game-structures",
id: hqId,
depth: 0,
overrideAccess: true,
data: {
storedResources: [
{ resource: resourceAId, amount: 3, gridX: 0, gridY: 0, rotated: false },
],
},
});
await emitRawEvent(`${RUN}-evt-fit`, "operation.extraction", {
operationId,
version: 1,
actorId: extractorId,
kind: "logistics",
hqStructureId: hqId,
items: [
{ resourceId: resourceAId, amount: 10 },
{ resourceId: secondResourceId, amount: 1 },
],
});
const effect = (await effectsForOperation(operationId))[0];
// Keeping everything overflows the cap -> resolve fails but stays pending
// (retryable) so the officer can retry after freeing room.
const keepAll = await resolveLogisticsExtraction(payload, effect.id, null);
expect(keepAll.success).toBe(false);
const afterKeepAll = await payload.findByID({
collection: "operation-effects",
id: effect.id,
depth: 0,
overrideAccess: true,
});
expect((afterKeepAll as unknown as { status: string }).status).toBe("pending_action");
expect(
(afterKeepAll as unknown as { reconciliationNotes: string }).reconciliationNotes,
).toContain("hq-capacity");
// Expel the big resourceA line so the small line fits (3 + 1 = 5 <= cap).
const decisions = [{ relationTo: "resources" as const, id: resourceAId, decision: "expel" as const }];
const resolved = await resolveLogisticsExtraction(payload, effect.id, decisions);
expect(resolved.success).toBe(true);
// resourceA is held back (unchanged); only the kept secondResource deposits.
expect(await storedAmountAt(hqId, resourceAId)).toBe(3);
expect(await storedAmountAt(hqId, secondResourceId)).toBe(1);
});
it("rejects resolving an effect that is no longer awaiting action", async () => {
const operationId = `${RUN}-op-status`;
const hqId = await makeStructure("hq-status", hqBlueprintId);
await emitRawEvent(`${RUN}-evt-status`, "operation.extraction", {
operationId,
version: 1,
actorId: extractorId,
kind: "logistics",
hqStructureId: hqId,
items: [{ resourceId: resourceAId, amount: 5 }],
});
const effect = (await effectsForOperation(operationId))[0];
const ok = await resolveLogisticsExtraction(payload, effect.id, null);
expect(ok.success).toBe(true);
const again = await resolveLogisticsExtraction(payload, effect.id, null);
expect(again.success).toBe(false);
expect(again.error).toMatch(/not awaiting action/i);
});
it("updates the AAR for an objective-only operation without touching inventory", async () => {
const operationId = `${RUN}-op-obj`;
const hqId = await makeStructure("hq-obj", hqBlueprintId);

View file

@ -0,0 +1,147 @@
// @vitest-environment jsdom
import { createElement as h } from "react";
import { afterEach, describe, expect, it } from "vitest";
import { cleanup, render } from "@testing-library/react";
import {
RibbonArt,
computeDeviceSlots,
resolveDisplayedDeviceTypes,
MAX_TIER_DEVICES,
} from "@/components/awards/ribbonDesign/RibbonArt";
import type { RibbonDesign } from "@/components/awards/ribbonDesign/types";
afterEach(cleanup);
const design = (deviceTypes: string[]): RibbonDesign => ({
stripes: [
{ color: "#b91c1c", width: 50 },
{ color: "#1e3a5f", width: 50 },
],
devices: deviceTypes.map((type, i) => ({
id: `dev-${i}`,
// Cast to satisfy the union; tests only use valid types or assert fallback.
type: type as RibbonDesign["devices"][number]["type"],
position: 17 + i * 11,
positionY: 83,
})),
mirrored: false,
});
describe("resolveDisplayedDeviceTypes (tier-driven count)", () => {
const authored = ["star", "oakLeaf"] as const;
it("shows exactly the authored set for base, missing, and invalid tiers", () => {
for (const tier of [undefined, null, 1, 0, -2, Number.NaN]) {
expect(resolveDisplayedDeviceTypes(design([...authored]), tier)).toEqual(["star", "oakLeaf"]);
}
});
it("maps tier N to N-1 devices using the service-star convention", () => {
const d = design([...authored]);
expect(resolveDisplayedDeviceTypes(d, 2)).toEqual(["star"]);
expect(resolveDisplayedDeviceTypes(d, 3)).toEqual(["star", "oakLeaf"]);
expect(resolveDisplayedDeviceTypes(d, 4)).toEqual(["star", "oakLeaf", "star"]);
});
it("caps the derived cluster at MAX_TIER_DEVICES", () => {
const result = resolveDisplayedDeviceTypes(design([...authored]), 99);
expect(result).toHaveLength(MAX_TIER_DEVICES);
});
it("defaults to stars when a tiered series authored no devices", () => {
const result = resolveDisplayedDeviceTypes(design([]), 3);
expect(result).toEqual(["star", "star"]);
});
});
describe("computeDeviceSlots (centered auto-layout)", () => {
const W = 366;
const H = 80;
it("returns no slots for zero/negative counts", () => {
expect(computeDeviceSlots(0, W, H)).toEqual([]);
expect(computeDeviceSlots(-3, W, H)).toEqual([]);
});
it("centers a single device on the ribbon face", () => {
const [slot] = computeDeviceSlots(1, W, H);
expect(slot.cx).toBeCloseTo(W / 2, 6);
expect(slot.cy).toBeCloseTo(H / 2, 6);
expect(slot.size).toBeGreaterThan(0);
});
it("places N devices as an evenly spaced, centered cluster", () => {
const slots = computeDeviceSlots(4, W, H);
expect(slots).toHaveLength(4);
const spacings = slots.slice(1).map((s, i) => s.cx - slots[i].cx);
spacings.forEach((gap) => expect(gap).toBeCloseTo(spacings[0], 6));
// Symmetric about the centerline.
const meanCx = slots.reduce((sum, s) => sum + s.cx, 0) / slots.length;
expect(meanCx).toBeCloseTo(W / 2, 6);
// All vertically centered.
for (const slot of slots) expect(slot.cy).toBeCloseTo(H / 2, 6);
});
it("shrinks and keeps the cluster inside the face when crowded", () => {
// A tall, narrow canvas makes ideal sizing overflow at high counts, which
// exercises the uniform shrink path (compare like-for-like canvas).
const NARROW_W = 100;
const TALL_H = 200;
const few = computeDeviceSlots(1, NARROW_W, TALL_H);
const many = computeDeviceSlots(MAX_TIER_DEVICES, NARROW_W, TALL_H);
expect(many[many.length - 1].size).toBeLessThan(few[0].size);
const span =
many[many.length - 1].cx + many[many.length - 1].size / 2 - (many[0].cx - many[0].size / 2);
expect(span).toBeLessThanOrEqual(NARROW_W * 0.8 + 1e-6);
});
});
describe("RibbonArt rendering", () => {
it("renders vector device groups (no Unicode text elements) with tier counts", () => {
const { container } = render(h(RibbonArt, { design: design(["star", "oakLeaf"]), tier: 3 }));
const devices = container.querySelectorAll("[data-device]");
expect(devices).toHaveLength(2);
expect(Array.from(devices).map((d) => d.getAttribute("data-device"))).toEqual([
"star",
"oakLeaf",
]);
// Glyphs are inline paths now; no <text> nodes and no emoji fallbacks.
expect(container.querySelectorAll("text")).toHaveLength(0);
expect(container.querySelectorAll("path").length).toBeGreaterThan(0);
});
it("keeps preview identical to production by drawing the fabric overlay once", () => {
const { container } = render(h(RibbonArt, { design: design([]), tier: 1 }));
expect(container.querySelectorAll("image[href='/images/ribbon-overlay.png']")).toHaveLength(1);
});
it("drops the overlay when showOverlay is false", () => {
const { container } = render(h(RibbonArt, { design: design([]), showOverlay: false }));
expect(container.querySelector("image")).toBeNull();
});
it("renders mirrored designs with stripes doubled", () => {
const mirrored: RibbonDesign = { ...design(["star"]), mirrored: true };
const { container } = render(h(RibbonArt, { design: mirrored }));
// mirrored doubles every stripe band; two colors -> four rects over base bg
const rects = container.querySelectorAll("rect");
expect(rects.length).toBeGreaterThanOrEqual(4);
});
it("returns null for an explicitly stripe-less design and falls back for an absent one", () => {
// Matches legacy RibbonViewer/RibbonPreview behavior: a valid object with
// no stripes draws nothing...
const { container: empty } = render(
h(RibbonArt, { design: { stripes: [], devices: [], mirrored: false } }),
);
expect(empty.querySelector("svg")).toBeNull();
// ...while an unusable value falls back to DEFAULT_RIBBON and still renders.
const { container: fallback } = render(h(RibbonArt, { design: undefined }));
expect(fallback.querySelector("svg")).not.toBeNull();
});
});

View file

@ -0,0 +1,362 @@
import { getTestPayload } from "../helpers/get-test-payload";
import { afterAll, beforeAll, describe, expect, it, vi, type MockInstance } from "vitest";
import type { Payload } from "payload";
import type {
GameStructure,
GameVehicle,
Resource,
Role,
User,
Vehicle,
} from "@/payload-types";
import { createShipment } from "@/app/(frontend)/logistics/shipments/actions";
import { findDisallowedCargo, type CargoLine } from "@/lib/shipping/cargo";
// Mock next/headers so createShipment's authenticate() can run outside a request.
vi.mock("next/headers", () => ({ headers: async () => new Headers() }));
const RUN = `cargo-blacklist-${Date.now().toString(36)}`;
let payload: Payload;
let authSpy: MockInstance;
const mapIds: number[] = [];
const resourceIds: number[] = [];
const structureIds: number[] = [];
const vehicleTypeIds: number[] = [];
const userIds: number[] = [];
let mapId: number;
let resourceId: number;
let originId: number;
let destinationId: number;
let blacklistTypeId: number;
let cleanTypeId: number;
let commandUser: User;
const LEXICAL_EMPTY = {
root: {
children: [{ text: "" }],
direction: null,
format: "" as const,
indent: 0,
type: "text",
version: 1,
},
};
function relId(value: unknown): number {
return typeof value === "object" && value !== null
? (value as { id: number }).id
: (value as number);
}
// ---------------------------------------------------------------------------
// Pure unit tests for the matching logic (no DB required)
// ---------------------------------------------------------------------------
describe("findDisallowedCargo (pure)", () => {
const cargo = (value: number, amount = 5): CargoLine[] => [
{ relationTo: "resources", value, amount },
];
it("returns null when there is no blacklist", () => {
expect(findDisallowedCargo(null, cargo(1))).toBeNull();
expect(findDisallowedCargo([], cargo(1))).toBeNull();
});
it("forbids an item entirely when the cap is 0", () => {
expect(
findDisallowedCargo([{ item: { relationTo: "resources", value: 7 }, amount: 0 }], cargo(7)),
).toEqual({ relationTo: "resources", itemId: 7, cap: 0 });
});
it("allows quantity at or below the cap and forbids the excess", () => {
const atCap: CargoLine[] = [{ relationTo: "resources", value: 7, amount: 3 }];
expect(
findDisallowedCargo([{ item: { relationTo: "resources", value: 7 }, amount: 3 }], atCap),
).toBeNull();
const overCap: CargoLine[] = [{ relationTo: "resources", value: 7, amount: 4 }];
expect(
findDisallowedCargo([{ item: { relationTo: "resources", value: 7 }, amount: 3 }], overCap),
).toEqual({ relationTo: "resources", itemId: 7, cap: 3 });
});
it("matches by relationTo and id, ignoring unrelated entries", () => {
const twoLines: CargoLine[] = [
{ relationTo: "resources", value: 7, amount: 5 },
{ relationTo: "assets", value: 9, amount: 5 },
];
// Same id, wrong relationTo -> no match.
expect(
findDisallowedCargo([{ item: { relationTo: "vehicles", value: 7 }, amount: 0 }], twoLines),
).toBeNull();
// The asset line is blacklisted -> matches only that line.
expect(
findDisallowedCargo([{ item: { relationTo: "assets", value: 9 }, amount: 0 }], twoLines),
).toEqual({ relationTo: "assets", itemId: 9, cap: 0 });
});
it("tolerates a stored relationship shape (item.value as { id })", () => {
expect(
findDisallowedCargo(
[{ item: { relationTo: "resources", value: { id: 12 } }, amount: 0 }],
cargo(12),
),
).toEqual({ relationTo: "resources", itemId: 12, cap: 0 });
});
});
// ---------------------------------------------------------------------------
// createShipment enforcement (integration)
// ---------------------------------------------------------------------------
describe("createShipment vehicle cargo blacklist", () => {
beforeAll(async () => {
payload = await getTestPayload();
authSpy = vi.spyOn(payload, "auth");
const role = (await payload.create({
collection: "roles",
data: { name: `${RUN} Cmd`, slug: `${RUN}-cmd`, isSuperuser: true },
overrideAccess: true,
depth: 0,
})) as unknown as Role;
userIds.push(role.id);
commandUser = (await payload.create({
collection: "users",
data: {
username: `${RUN}-cmd`,
displayName: `${RUN} Cmd`,
discordUsername: `${RUN}-cmd`,
steamId: `${RUN}-steam`,
password: "Test1234",
roles: ["user"],
roleDocs: [role.id],
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
userIds.push(commandUser.id);
authSpy.mockResolvedValue({ user: commandUser });
const map = (await payload.create({
collection: "maps",
data: {
name: `${RUN} Map`,
worldSizeWidth: 20480,
worldSizeHeight: 20480,
basemapMode: "tiles",
tileUrlTemplate: "http://localhost/{z}/{x}/{y}.png",
isActive: false,
},
overrideAccess: true,
depth: 0,
})) as unknown as { id: number };
mapId = map.id;
mapIds.push(mapId);
const fuel = (await payload.create({
collection: "resources",
data: {
name: `${RUN} Diesel`,
codeName: `${RUN}-diesel`,
approvalStatus: "in_progress",
type: "physical",
baseValue: 1,
rarity: "common",
unitOfMeasure: "kg",
massPerUnit: 1,
gridWidth: 1,
gridHeight: 1,
},
overrideAccess: true,
depth: 0,
})) as unknown as Resource;
resourceId = fuel.id;
resourceIds.push(resourceId);
// A second resource, used to prove the clean vehicle blacklist targets a
// specific item (FK requires the referenced resource to exist).
const otherResource = (await payload.create({
collection: "resources",
data: {
name: `${RUN} Gravel`,
codeName: `${RUN}-gravel`,
approvalStatus: "in_progress",
type: "physical",
baseValue: 1,
rarity: "common",
unitOfMeasure: "kg",
massPerUnit: 1,
gridWidth: 1,
gridHeight: 1,
},
overrideAccess: true,
depth: 0,
})) as unknown as Resource;
const otherResourceId = otherResource.id;
resourceIds.push(otherResourceId);
const blueprint = (await payload.create({
collection: "structures",
data: {
name: `${RUN} Depot`,
codeName: `${RUN}-depot`,
approvalStatus: "in_progress",
description: LEXICAL_EMPTY as unknown as never,
category: "logistics",
materials: [{ resource: resourceId, amount: 1 }],
constructionDurationMinutes: 60,
terrainType: "land",
maxHealth: 100,
},
overrideAccess: true,
depth: 0,
})) as unknown as { id: number };
const origin = (await payload.create({
collection: "game-structures",
data: { name: `${RUN} Origin`, type: blueprint.id, map: mapId, coordinates: [2000, 2000] },
overrideAccess: true,
depth: 0,
})) as unknown as GameStructure;
originId = origin.id;
structureIds.push(originId);
const destination = (await payload.create({
collection: "game-structures",
data: { name: `${RUN} Destination`, type: blueprint.id, map: mapId, coordinates: [18000, 18000] },
overrideAccess: true,
depth: 0,
})) as unknown as GameStructure;
destinationId = destination.id;
structureIds.push(destinationId);
// Vehicle template that forbids the fuel resource entirely.
const blacklistType = (await payload.create({
collection: "vehicles",
data: {
name: `${RUN} Banned`,
approvalStatus: "in_progress",
transportMode: "air",
maxSpeedOnRoad: 60,
fuel: { fuelType: resourceId, fuelCapacity: 100000, fuelConsumptionRate: 0.01 },
disallowedCargo: [{ item: { relationTo: "resources", value: resourceId }, amount: 0 }],
},
overrideAccess: true,
depth: 0,
})) as unknown as Vehicle;
blacklistTypeId = blacklistType.id;
vehicleTypeIds.push(blacklistTypeId);
// Vehicle template that forbids a *different* resource, so the fuel is allowed.
const cleanType = (await payload.create({
collection: "vehicles",
data: {
name: `${RUN} Clean`,
approvalStatus: "in_progress",
transportMode: "air",
maxSpeedOnRoad: 60,
fuel: { fuelType: resourceId, fuelCapacity: 100000, fuelConsumptionRate: 0.01 },
disallowedCargo: [{ item: { relationTo: "resources", value: otherResourceId }, amount: 0 }],
},
overrideAccess: true,
depth: 0,
})) as unknown as Vehicle;
cleanTypeId = cleanType.id;
vehicleTypeIds.push(cleanTypeId);
});
afterAll(async () => {
for (const id of vehicleTypeIds)
await payload.delete({ collection: "vehicles", id, overrideAccess: true }).catch(() => {});
for (const id of structureIds)
await payload.delete({ collection: "game-structures", id, overrideAccess: true }).catch(() => {});
for (const id of resourceIds)
await payload.delete({ collection: "resources", id, overrideAccess: true }).catch(() => {});
for (const id of mapIds)
await payload.delete({ collection: "maps", id, overrideAccess: true }).catch(() => {});
for (const id of userIds)
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
});
const makeGameVehicle = async (typeId: number, atOriginId: number): Promise<GameVehicle> =>
(await payload.create({
collection: "game-vehicles",
data: {
name: `GV ${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
type: typeId,
deployedAt: atOriginId,
status: "idle",
currentFuel: 100000,
currentHealth: 100,
},
overrideAccess: true,
depth: 0,
})) as unknown as GameVehicle;
const resourceCargo = (value: number, amount = 10) =>
[{ relationTo: "resources" as const, value, amount }];
it("rejects a shipment whose vehicle may not carry the cargo (before anything is deducted)", async () => {
const vehicle = await makeGameVehicle(blacklistTypeId, originId);
const result = await createShipment({
originId,
destinationId,
vehicleId: vehicle.id,
cargo: resourceCargo(resourceId, 10),
});
expect(result.success).toBe(false);
expect(result.error).toMatch(/may not carry/i);
expect(result.error).toContain(String(resourceId));
// Nothing was deducted and no shipment was created: the vehicle is untouched.
const after = (await payload.findByID({
collection: "game-vehicles",
id: vehicle.id,
depth: 0,
overrideAccess: true,
})) as unknown as GameVehicle;
expect(after.status).toBe("idle");
expect(relId(after.deployedAt)).toBe(originId);
});
it("allows a shipment when the cargo is not blacklisted", async () => {
const vehicle = await makeGameVehicle(cleanTypeId, originId);
// Seed the origin with the cargo so the origin-stock and destination checks pass.
await payload.update({
collection: "game-structures",
id: originId,
data: {
storedResources: [
{ resource: resourceId, amount: 100, gridX: 0, gridY: 0, rotated: false },
],
},
overrideAccess: true,
});
const result = await createShipment({
originId,
destinationId,
vehicleId: vehicle.id,
cargo: resourceCargo(resourceId, 10),
});
expect(result.success).toBe(true);
const after = (await payload.findByID({
collection: "game-vehicles",
id: vehicle.id,
depth: 0,
overrideAccess: true,
})) as unknown as GameVehicle;
expect(after.status).toBe("in_transit");
});
});