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
This commit is contained in:
parent
245e70f3f2
commit
3bef63af33
33 changed files with 2858 additions and 225 deletions
20
CHANGELOG.md
20
CHANGELOG.md
|
|
@ -1,5 +1,25 @@
|
||||||
# Changelog
|
# 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
|
# v0.13.0
|
||||||
|
|
||||||
Leadership ratings now follow the unit's rank structure instead of squad assignments.
|
Leadership ratings now follow the unit's rank structure instead of squad assignments.
|
||||||
|
|
|
||||||
|
|
@ -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
|
`worldSizeWidth`/`worldSizeHeight` must match the terrain's real size for
|
||||||
exported markers to land in the right place in-game.
|
exported markers to land in the right place in-game.
|
||||||
- The base layers come from `GET /api/map-features?mapId=<id>&layers=base`,
|
- 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
|
- Icons, colors and brushes come from the game config via
|
||||||
`bun run markers:arma`. See the "Mission Planning Map" section in AGENTS.md
|
`bun run markers:arma`. See the "Mission Planning Map" section in AGENTS.md
|
||||||
for the full wiring.
|
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.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -52,6 +52,7 @@ import {
|
||||||
listMissionMarkers,
|
listMissionMarkers,
|
||||||
planningMapDelegateIds,
|
planningMapDelegateIds,
|
||||||
} from "@/lib/intelligence/missionMap";
|
} from "@/lib/intelligence/missionMap";
|
||||||
|
import { listMapObjectives } from "@/lib/map/objectives";
|
||||||
|
|
||||||
interface MissionDetailPageProps {
|
interface MissionDetailPageProps {
|
||||||
params: Promise<{ id: string }>;
|
params: Promise<{ id: string }>;
|
||||||
|
|
@ -280,9 +281,16 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro
|
||||||
const canCuratePlan = canControlSideOp && !planLocked;
|
const canCuratePlan = canControlSideOp && !planLocked;
|
||||||
const canDelegate = canManage && !planLocked;
|
const canDelegate = canManage && !planLocked;
|
||||||
const canEditPlan = (canControlSideOp || isPlanDelegate) && !planLocked;
|
const canEditPlan = (canControlSideOp || isPlanDelegate) && !planLocked;
|
||||||
|
const canManageObjectives = currentUser
|
||||||
|
? await hasPermission(payload, currentUser, "system:admin-access")
|
||||||
|
: false;
|
||||||
const planningMapEnabled = mission.classification.planningMapEnabled === true;
|
const planningMapEnabled = mission.classification.planningMapEnabled === true;
|
||||||
const planMarkers =
|
const planMarkers =
|
||||||
map && planningMapEnabled ? await listMissionMarkers(payload, mission.id) : [];
|
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);
|
const showPlanningMap = map !== null && (planningMapEnabled || canEditPlan);
|
||||||
|
|
||||||
let planningUsers: PlanningUserOption[] = [];
|
let planningUsers: PlanningUserOption[] = [];
|
||||||
|
|
@ -470,6 +478,7 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro
|
||||||
enabled={planningMapEnabled}
|
enabled={planningMapEnabled}
|
||||||
canEdit={canEditPlan}
|
canEdit={canEditPlan}
|
||||||
canCurate={canCuratePlan}
|
canCurate={canCuratePlan}
|
||||||
|
canManageObjectives={canManageObjectives}
|
||||||
locked={planLocked}
|
locked={planLocked}
|
||||||
map={{
|
map={{
|
||||||
id: map.id,
|
id: map.id,
|
||||||
|
|
@ -478,6 +487,7 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro
|
||||||
worldHeight: Number(map.worldSizeHeight ?? 8192),
|
worldHeight: Number(map.worldSizeHeight ?? 8192),
|
||||||
}}
|
}}
|
||||||
initialMarkers={planMarkers}
|
initialMarkers={planMarkers}
|
||||||
|
initialObjectives={planObjectives}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{/* Attendance sits right under the hero on stacked (below-xl) layouts */}
|
{/* Attendance sits right under the hero on stacked (below-xl) layouts */}
|
||||||
|
|
|
||||||
|
|
@ -31,17 +31,19 @@ export default async function MapViewPage({ params }: MapViewPageProps) {
|
||||||
|
|
||||||
if (!map) notFound();
|
if (!map) notFound();
|
||||||
|
|
||||||
const [canPlace, canAuthorRoads, canAuthorZones, canAuthorNodes] = await Promise.all([
|
const [canPlace, canAuthorRoads, canAuthorZones, canAuthorNodes, canManageObjectives] =
|
||||||
user
|
await Promise.all([
|
||||||
? Promise.all([
|
user
|
||||||
hasPermission(payload, user, "maps:place"),
|
? Promise.all([
|
||||||
hasLogisticsQualification(payload, user),
|
hasPermission(payload, user, "maps:place"),
|
||||||
]).then(([place, logistics]) => place && logistics)
|
hasLogisticsQualification(payload, user),
|
||||||
: Promise.resolve(false),
|
]).then(([place, logistics]) => place && logistics)
|
||||||
user ? hasPermission(payload, user, "map-roads:author") : Promise.resolve(false),
|
: Promise.resolve(false),
|
||||||
user ? hasPermission(payload, user, "map-zones:author") : Promise.resolve(false),
|
user ? hasPermission(payload, user, "map-roads:author") : Promise.resolve(false),
|
||||||
user ? hasPermission(payload, user, "resource-nodes: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
|
// Inactive maps stay reachable for editors previewing them, but are hidden
|
||||||
// from everyone else.
|
// from everyone else.
|
||||||
|
|
@ -67,6 +69,7 @@ export default async function MapViewPage({ params }: MapViewPageProps) {
|
||||||
map={{ id: map.id, name: map.name }}
|
map={{ id: map.id, name: map.name }}
|
||||||
canAuthor={{ roads: canAuthorRoads, zones: canAuthorZones, nodes: canAuthorNodes }}
|
canAuthor={{ roads: canAuthorRoads, zones: canAuthorZones, nodes: canAuthorNodes }}
|
||||||
canPlace={canPlace}
|
canPlace={canPlace}
|
||||||
|
canManageObjectives={canManageObjectives}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|
|
||||||
146
src/app/(frontend)/map/actions.ts
Normal file
146
src/app/(frontend)/map/actions.ts
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -3976,6 +3976,37 @@
|
||||||
outline-offset: 3px;
|
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 {
|
.leaflet-container .mission-map-handle {
|
||||||
background: transparent;
|
background: transparent;
|
||||||
border: none;
|
border: none;
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,8 @@ import {
|
||||||
import { isPointArray, type MapPoint } from "@/lib/map/points";
|
import { isPointArray, type MapPoint } from "@/lib/map/points";
|
||||||
import { gridConfigFromMapDoc } from "@/lib/map/grid";
|
import { gridConfigFromMapDoc } from "@/lib/map/grid";
|
||||||
import type { MapFeaturesResponse, StructureFeature } from "@/lib/map/types";
|
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 dynamic = "force-dynamic";
|
||||||
export const runtime = "nodejs";
|
export const runtime = "nodejs";
|
||||||
|
|
@ -71,56 +73,61 @@ export async function GET(req: NextRequest) {
|
||||||
const worldH = Number(mapDoc.worldSizeHeight ?? 8192);
|
const worldH = Number(mapDoc.worldSizeHeight ?? 8192);
|
||||||
|
|
||||||
// layers=base: basemap + roads + zones only (mission planning maps). Skips
|
// 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 baseOnly = req.nextUrl.searchParams.get("layers") === "base";
|
||||||
|
const includeRedacted = await hasPermission(payload, user, "system:admin-access");
|
||||||
const none = { docs: [] as never[] };
|
const none = { docs: [] as never[] };
|
||||||
|
|
||||||
const [structuresRes, nodesRes, roadsRes, zonesRes, shipmentsRes] = await Promise.all([
|
const [structuresRes, nodesRes, roadsRes, zonesRes, shipmentsRes, objectives] = await Promise.all(
|
||||||
baseOnly
|
[
|
||||||
? none
|
baseOnly
|
||||||
: payload.find({
|
? none
|
||||||
collection: "game-structures",
|
: payload.find({
|
||||||
where: { map: { equals: mapId } },
|
collection: "game-structures",
|
||||||
depth: 2,
|
where: { map: { equals: mapId } },
|
||||||
limit: 1000,
|
depth: 2,
|
||||||
overrideAccess: true,
|
limit: 1000,
|
||||||
}),
|
overrideAccess: true,
|
||||||
baseOnly
|
}),
|
||||||
? none
|
baseOnly
|
||||||
: payload.find({
|
? none
|
||||||
collection: "resource-nodes",
|
: payload.find({
|
||||||
where: { map: { equals: mapId } },
|
collection: "resource-nodes",
|
||||||
depth: 1,
|
where: { map: { equals: mapId } },
|
||||||
limit: 5000,
|
depth: 1,
|
||||||
overrideAccess: true,
|
limit: 5000,
|
||||||
}),
|
overrideAccess: true,
|
||||||
payload.find({
|
}),
|
||||||
collection: "map-roads",
|
payload.find({
|
||||||
where: { map: { equals: mapId } },
|
collection: "map-roads",
|
||||||
depth: 0,
|
where: { map: { equals: mapId } },
|
||||||
limit: 5000,
|
depth: 0,
|
||||||
overrideAccess: true,
|
limit: 5000,
|
||||||
}),
|
overrideAccess: true,
|
||||||
payload.find({
|
}),
|
||||||
collection: "map-zones",
|
payload.find({
|
||||||
where: { map: { equals: mapId } },
|
collection: "map-zones",
|
||||||
depth: 1,
|
where: { map: { equals: mapId } },
|
||||||
limit: 5000,
|
depth: 1,
|
||||||
overrideAccess: true,
|
limit: 5000,
|
||||||
}),
|
overrideAccess: true,
|
||||||
baseOnly
|
}),
|
||||||
? none
|
baseOnly
|
||||||
: payload.find({
|
? none
|
||||||
collection: "shipments",
|
: payload.find({
|
||||||
where: {
|
collection: "shipments",
|
||||||
and: [{ map: { equals: mapId } }, { status: { in: ["dispatched", "in_transit"] } }],
|
where: {
|
||||||
},
|
and: [{ map: { equals: mapId } }, { status: { in: ["dispatched", "in_transit"] } }],
|
||||||
depth: 2,
|
},
|
||||||
limit: 200,
|
depth: 2,
|
||||||
sort: "-dispatchedAt",
|
limit: 200,
|
||||||
overrideAccess: true,
|
sort: "-dispatchedAt",
|
||||||
}),
|
overrideAccess: true,
|
||||||
]);
|
}),
|
||||||
|
listMapObjectives(payload, mapId, { includeRedacted }),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
const structures: StructureFeature[] = [];
|
const structures: StructureFeature[] = [];
|
||||||
for (const doc of structuresRes.docs) {
|
for (const doc of structuresRes.docs) {
|
||||||
|
|
@ -296,6 +303,7 @@ export async function GET(req: NextRequest) {
|
||||||
roads,
|
roads,
|
||||||
zones,
|
zones,
|
||||||
shipments,
|
shipments,
|
||||||
|
objectives,
|
||||||
};
|
};
|
||||||
|
|
||||||
return NextResponse.json(response);
|
return NextResponse.json(response);
|
||||||
|
|
|
||||||
|
|
@ -28,7 +28,7 @@ collections/
|
||||||
# GameVehicles, GameNpcs, GameHardResources, GameEventLogs,
|
# GameVehicles, GameNpcs, GameHardResources, GameEventLogs,
|
||||||
# NpcStaffing, LaborClassifications (+ shared staffingFields.ts factory)
|
# NpcStaffing, LaborClassifications (+ shared staffingFields.ts factory)
|
||||||
server/ 5 files # MissionFiles, ModLists, GameServers, ArmaCommands, ArmaSyncEvents
|
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)
|
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
|
tickets/ 2 files # Tickets (Lexical rich text; `archived` hides from all front-ends, admin panel only), TicketVotes
|
||||||
wiki/ 3 files # WikiPages, WikiRevisions, WikiTemplates
|
wiki/ 3 files # WikiPages, WikiRevisions, WikiTemplates
|
||||||
|
|
|
||||||
|
|
@ -36,6 +36,7 @@ const TARGET_COLLECTIONS = [
|
||||||
{ label: "Wiki Templates", value: "wiki-templates" },
|
{ label: "Wiki Templates", value: "wiki-templates" },
|
||||||
{ label: "Survey Submissions", value: "form-submissions" },
|
{ label: "Survey Submissions", value: "form-submissions" },
|
||||||
{ label: "Mission Map Markers", value: "mission-map-markers" },
|
{ label: "Mission Map Markers", value: "mission-map-markers" },
|
||||||
|
{ label: "Map Objectives", value: "map-objectives" },
|
||||||
{ label: "Contribution Entries", value: "contribution-entries" },
|
{ label: "Contribution Entries", value: "contribution-entries" },
|
||||||
{ label: "Game Servers", value: "game-servers" },
|
{ label: "Game Servers", value: "game-servers" },
|
||||||
{ label: "Assignment Transfers", value: "assignment-transfers" },
|
{ label: "Assignment Transfers", value: "assignment-transfers" },
|
||||||
|
|
@ -190,7 +191,8 @@ export const GameEventLogs: CollectionConfig = {
|
||||||
type: "date",
|
type: "date",
|
||||||
admin: {
|
admin: {
|
||||||
readOnly: true,
|
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.",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|
|
||||||
207
src/collections/world/MapObjectives.ts
Normal file
207
src/collections/world/MapObjectives.ts
Normal 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",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
@ -13,6 +13,31 @@ export const Maps: CollectionConfig = {
|
||||||
delete: requirePermission("maps:delete"),
|
delete: requirePermission("maps:delete"),
|
||||||
read: requirePermission("maps:read"),
|
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: [
|
fields: [
|
||||||
{
|
{
|
||||||
name: "name",
|
name: "name",
|
||||||
|
|
|
||||||
|
|
@ -36,7 +36,7 @@ import {
|
||||||
type MissionMarker,
|
type MissionMarker,
|
||||||
} from "@/lib/arma-markers/missionMarkers";
|
} from "@/lib/arma-markers/missionMarkers";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { MarkerTypePicker } from "./MarkerTypePicker";
|
import { MarkerTypePicker } from "@/components/frontend/markers/MarkerTypePicker";
|
||||||
import type { MarkerStyle, PlanTool } from "./types";
|
import type { MarkerStyle, PlanTool } from "./types";
|
||||||
|
|
||||||
const TOOLS: { value: PlanTool; label: string; icon: typeof MapPinIcon; hint: string }[] = [
|
const TOOLS: { value: PlanTool; label: string; icon: typeof MapPinIcon; hint: string }[] = [
|
||||||
|
|
|
||||||
|
|
@ -19,7 +19,15 @@ import type { MapPoint } from "@/lib/map/points";
|
||||||
import { dashArrayFor, metersPerPx, splinePolyline } from "@/lib/map/style";
|
import { dashArrayFor, metersPerPx, splinePolyline } from "@/lib/map/style";
|
||||||
import type { MapFeaturesResponse } from "@/lib/map/types";
|
import type { MapFeaturesResponse } from "@/lib/map/types";
|
||||||
import type { MapGridConfig } from "@/lib/map/grid";
|
import type { MapGridConfig } from "@/lib/map/grid";
|
||||||
|
import type { MapObjectiveFeature } from "@/lib/map/types";
|
||||||
import { GridLayer } from "@/components/frontend/map/GridLayer";
|
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 { markerBrushOf, resolveMarkerRgba, rgbaToHex } from "@/lib/arma-markers";
|
||||||
import {
|
import {
|
||||||
areaOutline,
|
areaOutline,
|
||||||
|
|
@ -28,24 +36,37 @@ import {
|
||||||
type MissionMarker,
|
type MissionMarker,
|
||||||
type MissionMarkerData,
|
type MissionMarkerData,
|
||||||
} from "@/lib/arma-markers/missionMarkers";
|
} from "@/lib/arma-markers/missionMarkers";
|
||||||
import { markerDivIcon } from "./markerIcon";
|
import { markerDivIcon } from "@/components/frontend/markers/markerIcon";
|
||||||
import type { MarkerStyle, PlanTool } from "./types";
|
import type { MarkerStyle, PlanTool } from "./types";
|
||||||
|
|
||||||
export interface MissionMapCanvasProps {
|
export interface MissionMapCanvasProps {
|
||||||
mapId: number;
|
mapId: number;
|
||||||
markers: MissionMarker[];
|
markers: MissionMarker[];
|
||||||
|
objectives: MapObjectiveFeature[];
|
||||||
selectedId: number | null;
|
selectedId: number | null;
|
||||||
tool: PlanTool;
|
tool: PlanTool;
|
||||||
style: MarkerStyle;
|
style: MarkerStyle;
|
||||||
canEdit: boolean;
|
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;
|
showRoads: boolean;
|
||||||
showZones: boolean;
|
showZones: boolean;
|
||||||
showGrid: boolean;
|
showGrid: boolean;
|
||||||
|
showStructures: boolean;
|
||||||
|
showNodes: boolean;
|
||||||
|
showShipments: boolean;
|
||||||
|
showRanges: boolean;
|
||||||
onSelect: (id: number | null) => void;
|
onSelect: (id: number | null) => void;
|
||||||
onCreate: (data: MissionMarkerData) => void;
|
onCreate: (data: MissionMarkerData) => void;
|
||||||
/** persist=false for live drag previews, true on drag end. */
|
/** persist=false for live drag previews, true on drag end. */
|
||||||
onChange: (marker: MissionMarker, persist: boolean) => void;
|
onChange: (marker: MissionMarker, persist: boolean) => void;
|
||||||
onCursor: (point: MapPoint | null) => void;
|
onCursor: (point: MapPoint | null) => void;
|
||||||
|
onObjectivePlace: (point: MapPoint) => void;
|
||||||
|
onEditObjective: (objective: MapObjectiveFeature) => void;
|
||||||
|
onObjectiveUpdated: (objective: MapObjectiveFeature) => void;
|
||||||
|
onObjectiveDeleted: (id: number) => void;
|
||||||
onLoaded: (info: {
|
onLoaded: (info: {
|
||||||
worldWidth: number;
|
worldWidth: number;
|
||||||
worldHeight: 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({
|
export function MissionMapCanvas({
|
||||||
mapId,
|
mapId,
|
||||||
markers,
|
markers,
|
||||||
|
objectives,
|
||||||
selectedId,
|
selectedId,
|
||||||
tool,
|
tool,
|
||||||
style,
|
style,
|
||||||
canEdit,
|
canEdit,
|
||||||
|
canManageObjectives,
|
||||||
|
objectiveArmed,
|
||||||
showRoads,
|
showRoads,
|
||||||
showZones,
|
showZones,
|
||||||
showGrid,
|
showGrid,
|
||||||
|
showStructures,
|
||||||
|
showNodes,
|
||||||
|
showShipments,
|
||||||
|
showRanges,
|
||||||
onSelect,
|
onSelect,
|
||||||
onCreate,
|
onCreate,
|
||||||
onChange,
|
onChange,
|
||||||
onCursor,
|
onCursor,
|
||||||
|
onObjectivePlace,
|
||||||
|
onEditObjective,
|
||||||
|
onObjectiveUpdated,
|
||||||
|
onObjectiveDeleted,
|
||||||
onLoaded,
|
onLoaded,
|
||||||
}: MissionMapCanvasProps) {
|
}: MissionMapCanvasProps) {
|
||||||
const [features, setFeatures] = useState<MapFeaturesResponse | null>(null);
|
const [features, setFeatures] = useState<MapFeaturesResponse | null>(null);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const layerClickAt = useRef(0);
|
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(() => {
|
useEffect(() => {
|
||||||
let cancelled = false;
|
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) => {
|
.then(async (response) => {
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const body = (await response.json().catch(() => null)) as { error?: string } | null;
|
const body = (await response.json().catch(() => null)) as { error?: string } | null;
|
||||||
|
|
@ -568,7 +614,7 @@ export function MissionMapCanvas({
|
||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
};
|
};
|
||||||
}, [mapId, onLoaded]);
|
}, [mapId, onLoaded, includeLogistics]);
|
||||||
|
|
||||||
const mapConfig = features?.map ?? null;
|
const mapConfig = features?.map ?? null;
|
||||||
const worldW = mapConfig?.worldSizeWidth ?? 8192;
|
const worldW = mapConfig?.worldSizeWidth ?? 8192;
|
||||||
|
|
@ -692,6 +738,11 @@ export function MissionMapCanvas({
|
||||||
<Polyline key={`road-${road.id}`} positions={positions} pathOptions={options} />
|
<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) => {
|
{markers.map((marker) => {
|
||||||
if (marker.shape === "rectangle" || marker.shape === "ellipse") {
|
if (marker.shape === "rectangle" || marker.shape === "ellipse") {
|
||||||
return (
|
return (
|
||||||
|
|
@ -764,6 +815,16 @@ export function MissionMapCanvas({
|
||||||
<LineHandles marker={selected} onChange={onChange} />
|
<LineHandles marker={selected} onChange={onChange} />
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<ObjectiveLayer
|
||||||
|
objectives={objectives}
|
||||||
|
canManage={canManageObjectives}
|
||||||
|
onEdit={onEditObjective}
|
||||||
|
onUpdated={onObjectiveUpdated}
|
||||||
|
onDeleted={onObjectiveDeleted}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{objectiveArmed && <ObjectivePlaceHandler onPick={onObjectivePlace} />}
|
||||||
|
|
||||||
<PlanInteractions
|
<PlanInteractions
|
||||||
tool={tool}
|
tool={tool}
|
||||||
canEdit={canEdit}
|
canEdit={canEdit}
|
||||||
|
|
|
||||||
|
|
@ -3,10 +3,17 @@
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { toast } from "sonner";
|
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 { Button } from "@/components/ui/button";
|
||||||
import { Switch } from "@/components/ui/switch";
|
import { Switch } from "@/components/ui/switch";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||||
import {
|
import {
|
||||||
AlertDialog,
|
AlertDialog,
|
||||||
AlertDialogAction,
|
AlertDialogAction,
|
||||||
|
|
@ -31,6 +38,10 @@ import {
|
||||||
} from "@/lib/arma-markers/missionMarkers";
|
} from "@/lib/arma-markers/missionMarkers";
|
||||||
import { DEFAULT_MAP_GRID, gridRef, type MapGridConfig } from "@/lib/map/grid";
|
import { DEFAULT_MAP_GRID, gridRef, type MapGridConfig } from "@/lib/map/grid";
|
||||||
import type { MapPoint } from "@/lib/map/points";
|
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 {
|
import {
|
||||||
clearMissionMapMarkers,
|
clearMissionMapMarkers,
|
||||||
deleteMissionMapMarker,
|
deleteMissionMapMarker,
|
||||||
|
|
@ -50,14 +61,68 @@ export interface MissionPlanningMapProps {
|
||||||
canEdit: boolean;
|
canEdit: boolean;
|
||||||
/** Can manage the map itself: toggle it, clear all markers. Defaults to canEdit. */
|
/** Can manage the map itself: toggle it, clear all markers. Defaults to canEdit. */
|
||||||
canCurate?: boolean;
|
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. */
|
/** True once the mission is terminal: the map is frozen read-only. */
|
||||||
locked?: boolean;
|
locked?: boolean;
|
||||||
map: { id: number; name: string; worldWidth: number; worldHeight: number };
|
map: { id: number; name: string; worldWidth: number; worldHeight: number };
|
||||||
initialMarkers: MissionMarker[];
|
initialMarkers: MissionMarker[];
|
||||||
|
/** Objectives for this mission's map, already filtered for the viewer. */
|
||||||
|
initialObjectives?: MapObjectiveFeature[];
|
||||||
}
|
}
|
||||||
|
|
||||||
const SAVE_DEBOUNCE_MS = 400;
|
const SAVE_DEBOUNCE_MS = 400;
|
||||||
const POLL_MS = 30_000;
|
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 = {
|
const DEFAULT_STYLE: MarkerStyle = {
|
||||||
markerType: DEFAULT_MARKER_TYPE,
|
markerType: DEFAULT_MARKER_TYPE,
|
||||||
|
|
@ -107,22 +172,28 @@ export function MissionPlanningMap({
|
||||||
enabled,
|
enabled,
|
||||||
canEdit,
|
canEdit,
|
||||||
canCurate = canEdit,
|
canCurate = canEdit,
|
||||||
|
canManageObjectives = false,
|
||||||
locked = false,
|
locked = false,
|
||||||
map,
|
map,
|
||||||
initialMarkers,
|
initialMarkers,
|
||||||
|
initialObjectives = [],
|
||||||
}: MissionPlanningMapProps) {
|
}: MissionPlanningMapProps) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [markers, setMarkers] = useState<MissionMarker[]>(initialMarkers);
|
const [markers, setMarkers] = useState<MissionMarker[]>(initialMarkers);
|
||||||
|
const [objectives, setObjectives] = useState<MapObjectiveFeature[]>(initialObjectives);
|
||||||
const [selectedId, setSelectedId] = useState<number | null>(null);
|
const [selectedId, setSelectedId] = useState<number | null>(null);
|
||||||
const [tool, setTool] = useState<PlanTool>("select");
|
const [tool, setTool] = useState<PlanTool>("select");
|
||||||
const [style, setStyle] = useState<MarkerStyle>(DEFAULT_STYLE);
|
const [style, setStyle] = useState<MarkerStyle>(DEFAULT_STYLE);
|
||||||
const [cursor, setCursor] = useState<MapPoint | null>(null);
|
const [cursor, setCursor] = useState<MapPoint | null>(null);
|
||||||
const [showRoads, setShowRoads] = useState(true);
|
const [layers, setLayers] = useState<PlanLayers>(DEFAULT_LAYERS);
|
||||||
const [showZones, setShowZones] = useState(true);
|
|
||||||
const [showGrid, setShowGrid] = useState(true);
|
|
||||||
const [world, setWorld] = useState({ width: map.worldWidth, height: map.worldHeight });
|
const [world, setWorld] = useState({ width: map.worldWidth, height: map.worldHeight });
|
||||||
const [gridConfig, setGridConfig] = useState<MapGridConfig>(DEFAULT_MAP_GRID);
|
const [gridConfig, setGridConfig] = useState<MapGridConfig>(DEFAULT_MAP_GRID);
|
||||||
const [toggling, setToggling] = useState(false);
|
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 timers = useRef(new Map<number, ReturnType<typeof setTimeout>>());
|
||||||
const inflight = useRef(new Map<number, Promise<unknown>>());
|
const inflight = useRef(new Map<number, Promise<unknown>>());
|
||||||
|
|
@ -137,6 +208,24 @@ export function MissionPlanningMap({
|
||||||
}
|
}
|
||||||
}, [missionId]);
|
}, [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
|
// Background refresh picks up other editors' changes, but never while a
|
||||||
// local edit is pending (it would snap the marker back mid-edit).
|
// local edit is pending (it would snap the marker back mid-edit).
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|
@ -148,10 +237,11 @@ export function MissionPlanningMap({
|
||||||
document.visibilityState === "visible"
|
document.visibilityState === "visible"
|
||||||
) {
|
) {
|
||||||
void refresh();
|
void refresh();
|
||||||
|
void refreshObjectives();
|
||||||
}
|
}
|
||||||
}, POLL_MS);
|
}, POLL_MS);
|
||||||
return () => clearInterval(timer);
|
return () => clearInterval(timer);
|
||||||
}, [enabled, refresh]);
|
}, [enabled, refresh, refreshObjectives]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const pending = timers.current;
|
const pending = timers.current;
|
||||||
|
|
@ -308,8 +398,15 @@ export function MissionPlanningMap({
|
||||||
|
|
||||||
const exportSqf = async () => {
|
const exportSqf = async () => {
|
||||||
try {
|
try {
|
||||||
await navigator.clipboard.writeText(markersToSqf(markers, world.height));
|
const exportMarkers: MissionMarker[] = [
|
||||||
toast.success(`Copied ${markers.length} markers as SQF.`, {
|
...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.",
|
description: "Paste into the debug console or an init script.",
|
||||||
});
|
});
|
||||||
} catch {
|
} catch {
|
||||||
|
|
@ -334,8 +431,9 @@ export function MissionPlanningMap({
|
||||||
areas: markers.filter((marker) => marker.shape === "rectangle" || marker.shape === "ellipse")
|
areas: markers.filter((marker) => marker.shape === "rectangle" || marker.shape === "ellipse")
|
||||||
.length,
|
.length,
|
||||||
lines: markers.filter((marker) => marker.shape === "polyline").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 selected = markers.find((marker) => marker.id === selectedId) ?? null;
|
||||||
const ref = String((missionId * 37) % 1000).padStart(3, "0");
|
const ref = String((missionId * 37) % 1000).padStart(3, "0");
|
||||||
|
|
@ -373,33 +471,58 @@ export function MissionPlanningMap({
|
||||||
Planning map // {missionLabel}
|
Planning map // {missionLabel}
|
||||||
</span>
|
</span>
|
||||||
<div className="flex shrink-0 items-center gap-3">
|
<div className="flex shrink-0 items-center gap-3">
|
||||||
<label className="flex items-center gap-1.5">
|
<Popover>
|
||||||
<Switch size="sm" checked={showGrid} onCheckedChange={setShowGrid} id="plan-grid" />
|
<PopoverTrigger asChild>
|
||||||
<Label
|
<Button
|
||||||
htmlFor="plan-grid"
|
variant="ghost"
|
||||||
className="font-mono text-[9px] uppercase tracking-widest text-white/60"
|
size="sm"
|
||||||
>
|
className="h-6 gap-1 px-2 font-mono text-[9px] uppercase tracking-widest text-white/60 hover:text-white"
|
||||||
Grid
|
>
|
||||||
</Label>
|
<LayersIcon className="size-3" />
|
||||||
</label>
|
Layers
|
||||||
<label className="flex items-center gap-1.5">
|
</Button>
|
||||||
<Switch size="sm" checked={showRoads} onCheckedChange={setShowRoads} id="plan-roads" />
|
</PopoverTrigger>
|
||||||
<Label
|
<PopoverContent align="end" className="w-52 p-2">
|
||||||
htmlFor="plan-roads"
|
<div className="flex flex-col gap-1.5">
|
||||||
className="font-mono text-[9px] uppercase tracking-widest text-white/60"
|
{LAYER_ROWS.map(({ key, label }) => (
|
||||||
>
|
<label key={key} className="flex items-center justify-between gap-2">
|
||||||
Roads
|
<span className="font-mono text-[10px] uppercase tracking-widest text-white/70">
|
||||||
</Label>
|
{label}
|
||||||
</label>
|
</span>
|
||||||
<label className="flex items-center gap-1.5">
|
<Switch
|
||||||
<Switch size="sm" checked={showZones} onCheckedChange={setShowZones} id="plan-zones" />
|
size="sm"
|
||||||
<Label
|
checked={layers[key]}
|
||||||
htmlFor="plan-zones"
|
onCheckedChange={(checked) =>
|
||||||
className="font-mono text-[9px] uppercase tracking-widest text-white/60"
|
setLayers((current) => ({ ...current, [key]: checked }))
|
||||||
>
|
}
|
||||||
Zones
|
/>
|
||||||
</Label>
|
</label>
|
||||||
</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">
|
<span className="hidden font-mono text-[9px] uppercase tracking-widest text-white/60 sm:inline">
|
||||||
{map.name} // REF {ref}
|
{map.name} // REF {ref}
|
||||||
</span>
|
</span>
|
||||||
|
|
@ -409,23 +532,49 @@ export function MissionPlanningMap({
|
||||||
<div className="flex flex-col lg:h-[620px] lg:flex-row">
|
<div className="flex flex-col lg:h-[620px] lg:flex-row">
|
||||||
<div
|
<div
|
||||||
className="map-host relative h-[480px] min-w-0 flex-1 lg:h-full"
|
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 />
|
<Corners />
|
||||||
<MissionMapLoader
|
<MissionMapLoader
|
||||||
mapId={map.id}
|
mapId={map.id}
|
||||||
markers={markers}
|
markers={markers}
|
||||||
|
objectives={objectives}
|
||||||
selectedId={selectedId}
|
selectedId={selectedId}
|
||||||
tool={canEdit ? tool : "select"}
|
tool={canEdit ? tool : "select"}
|
||||||
style={style}
|
style={style}
|
||||||
canEdit={canEdit}
|
canEdit={canEdit}
|
||||||
showRoads={showRoads}
|
canManageObjectives={canManageObjectives}
|
||||||
showZones={showZones}
|
objectiveArmed={objectiveArmed}
|
||||||
showGrid={showGrid}
|
showRoads={layers.roads}
|
||||||
|
showZones={layers.zones}
|
||||||
|
showGrid={layers.grid}
|
||||||
|
showStructures={layers.structures}
|
||||||
|
showNodes={layers.nodes}
|
||||||
|
showShipments={layers.shipments}
|
||||||
|
showRanges={layers.ranges}
|
||||||
onSelect={setSelectedId}
|
onSelect={setSelectedId}
|
||||||
onCreate={(data) => void handleCreate(data)}
|
onCreate={(data) => void handleCreate(data)}
|
||||||
onChange={handleChange}
|
onChange={handleChange}
|
||||||
onCursor={setCursor}
|
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}
|
onLoaded={handleLoaded}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -450,38 +599,38 @@ export function MissionPlanningMap({
|
||||||
{canCurate && (
|
{canCurate && (
|
||||||
<>
|
<>
|
||||||
<AlertDialog>
|
<AlertDialog>
|
||||||
<AlertDialogTrigger asChild>
|
<AlertDialogTrigger asChild>
|
||||||
<Button variant="outline" size="sm" disabled={markers.length === 0}>
|
<Button variant="outline" size="sm" disabled={markers.length === 0}>
|
||||||
<EraserIcon />
|
<EraserIcon />
|
||||||
Clear all
|
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>
|
</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>
|
</div>
|
||||||
|
|
@ -500,6 +649,7 @@ export function MissionPlanningMap({
|
||||||
<ReadoutCell value={String(counts.icons)} label="Icons" />
|
<ReadoutCell value={String(counts.icons)} label="Icons" />
|
||||||
<ReadoutCell value={String(counts.areas)} label="Areas" />
|
<ReadoutCell value={String(counts.areas)} label="Areas" />
|
||||||
<ReadoutCell value={String(counts.lines)} label="Lines" />
|
<ReadoutCell value={String(counts.lines)} label="Lines" />
|
||||||
|
<ReadoutCell value={String(counts.objectives)} label="Objectives" />
|
||||||
<ReadoutCell
|
<ReadoutCell
|
||||||
value={cursor ? gridRef(cursor, world.height, gridConfig) : "--- ---"}
|
value={cursor ? gridRef(cursor, world.height, gridConfig) : "--- ---"}
|
||||||
label="Grid"
|
label="Grid"
|
||||||
|
|
@ -514,7 +664,7 @@ export function MissionPlanningMap({
|
||||||
size="sm"
|
size="sm"
|
||||||
className="h-6 px-2 font-mono text-[10px] uppercase tracking-widest text-white/70"
|
className="h-6 px-2 font-mono text-[10px] uppercase tracking-widest text-white/70"
|
||||||
onClick={() => void exportSqf()}
|
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"
|
title="Copy a createMarker script that recreates this plan in Arma 3"
|
||||||
>
|
>
|
||||||
<ClipboardCopyIcon className="size-3" />
|
<ClipboardCopyIcon className="size-3" />
|
||||||
|
|
@ -522,6 +672,29 @@ export function MissionPlanningMap({
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</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>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)),
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -19,7 +19,7 @@ import {
|
||||||
useMapEvents,
|
useMapEvents,
|
||||||
} from "react-leaflet";
|
} from "react-leaflet";
|
||||||
import Link from "next/link";
|
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 { Button } from "@/components/ui/button";
|
||||||
import { useGameTick } from "@/hooks/useGameTick";
|
import { useGameTick } from "@/hooks/useGameTick";
|
||||||
import {
|
import {
|
||||||
|
|
@ -51,15 +51,29 @@ import { GridLayer } from "./GridLayer";
|
||||||
import { PlacementDialog } from "./PlacementDialog";
|
import { PlacementDialog } from "./PlacementDialog";
|
||||||
import { AuthoringToolbar, useMapAuthoring } from "./AuthoringToolbar";
|
import { AuthoringToolbar, useMapAuthoring } from "./AuthoringToolbar";
|
||||||
import { StructureDetailDrawer } from "./StructureDetailDrawer";
|
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 {
|
export interface MapClientProps {
|
||||||
map: { id: number; name: string };
|
map: { id: number; name: string };
|
||||||
canAuthor: { roads: boolean; zones: boolean; nodes: boolean };
|
canAuthor: { roads: boolean; zones: boolean; nodes: boolean };
|
||||||
canPlace: boolean;
|
canPlace: boolean;
|
||||||
|
/** Superuser tier: may add, move, retitle and reveal strategic objectives. */
|
||||||
|
canManageObjectives: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
type LayerToggles = {
|
type LayerToggles = {
|
||||||
|
objectives: boolean;
|
||||||
structures: boolean;
|
structures: boolean;
|
||||||
nodes: boolean;
|
nodes: boolean;
|
||||||
roads: boolean;
|
roads: boolean;
|
||||||
|
|
@ -69,12 +83,6 @@ type LayerToggles = {
|
||||||
grid: boolean;
|
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
|
// Layer styling is hoisted to module constants: react-leaflet re-applies
|
||||||
// pathOptions by reference, and a fresh object literal every render forces a
|
// pathOptions by reference, and a fresh object literal every render forces a
|
||||||
// canvas redraw that glitches mid-zoom-animation.
|
// canvas redraw that glitches mid-zoom-animation.
|
||||||
|
|
@ -146,14 +154,6 @@ const RIBBON_HEIGHT_PX = 32;
|
||||||
const RIBBON_GAP_PX = 6;
|
const RIBBON_GAP_PX = 6;
|
||||||
const RIBBON_PIN_HALF_PX = STRUCTURE_PIN_SIZES.lg / 2;
|
const RIBBON_PIN_HALF_PX = STRUCTURE_PIN_SIZES.lg / 2;
|
||||||
|
|
||||||
function escapeHtml(text: string): string {
|
|
||||||
return text
|
|
||||||
.replaceAll("&", "&")
|
|
||||||
.replaceAll("<", "<")
|
|
||||||
.replaceAll(">", ">")
|
|
||||||
.replaceAll('"', """);
|
|
||||||
}
|
|
||||||
|
|
||||||
const zoneLabelIconCache = new Map<string, L.DivIcon>();
|
const zoneLabelIconCache = new Map<string, L.DivIcon>();
|
||||||
|
|
||||||
function zoneLabelIcon(name: 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>();
|
const structureIconCache = new Map<string, L.DivIcon>();
|
||||||
|
|
||||||
interface StructureRibbon {
|
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`;
|
return `ETA ${Math.floor(minutes / 60)}h ${minutes % 60}m`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function MousePosition({
|
function MousePosition({ grid, worldHeight }: { grid: MapGridConfig | null; worldHeight: number }) {
|
||||||
grid,
|
|
||||||
worldHeight,
|
|
||||||
}: {
|
|
||||||
grid: MapGridConfig | null;
|
|
||||||
worldHeight: number;
|
|
||||||
}) {
|
|
||||||
const [position, setPosition] = useState<MapPoint | null>(null);
|
const [position, setPosition] = useState<MapPoint | null>(null);
|
||||||
useMapEvents({
|
useMapEvents({
|
||||||
mousemove: (event) => {
|
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 canEdit = canAuthor.roads || canAuthor.zones || canAuthor.nodes;
|
||||||
const selectedMapId = map.id;
|
const selectedMapId = map.id;
|
||||||
const [features, setFeatures] = useState<MapFeaturesResponse | null>(null);
|
const [features, setFeatures] = useState<MapFeaturesResponse | null>(null);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [toggles, setToggles] = useState<LayerToggles>({
|
const [toggles, setToggles] = useState<LayerToggles>({
|
||||||
|
objectives: true,
|
||||||
structures: true,
|
structures: true,
|
||||||
nodes: true,
|
nodes: true,
|
||||||
roads: true,
|
roads: true,
|
||||||
|
|
@ -1181,6 +1117,11 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
|
||||||
const [mode, setMode] = useState<"view" | "place" | "edit">("view");
|
const [mode, setMode] = useState<"view" | "place" | "edit">("view");
|
||||||
const [pendingPoint, setPendingPoint] = useState<MapPoint | null>(null);
|
const [pendingPoint, setPendingPoint] = useState<MapPoint | null>(null);
|
||||||
const [previewId, setPreviewId] = useState<number | 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) => {
|
const fetchFeatures = useCallback(async (mapId: number) => {
|
||||||
if (fetchingRef.current) return;
|
if (fetchingRef.current) return;
|
||||||
|
|
@ -1329,6 +1270,7 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
|
||||||
|
|
||||||
const layerToggleKeys: { key: keyof LayerToggles; label: string }[] = [
|
const layerToggleKeys: { key: keyof LayerToggles; label: string }[] = [
|
||||||
...(mapConfig?.grid.enabled ? [{ key: "grid" as const, label: "Grid" }] : []),
|
...(mapConfig?.grid.enabled ? [{ key: "grid" as const, label: "Grid" }] : []),
|
||||||
|
{ key: "objectives", label: "Objectives" },
|
||||||
{ key: "structures", label: "Structures" },
|
{ key: "structures", label: "Structures" },
|
||||||
{ key: "nodes", label: "Nodes" },
|
{ key: "nodes", label: "Nodes" },
|
||||||
{ key: "roads", label: "Roads" },
|
{ key: "roads", label: "Roads" },
|
||||||
|
|
@ -1340,7 +1282,9 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className="map-host group relative min-h-0 flex-1"
|
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
|
<span
|
||||||
aria-hidden
|
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
|
<MousePosition
|
||||||
grid={mapConfig?.grid.enabled ? mapConfig.grid : null}
|
grid={mapConfig?.grid.enabled ? mapConfig.grid : null}
|
||||||
worldHeight={worldH}
|
worldHeight={worldH}
|
||||||
|
|
@ -1631,6 +1609,16 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
|
||||||
<DefaultView key={mapConfig.id} center={center} zoom={mapConfig.defaultZoom ?? 2} />
|
<DefaultView key={mapConfig.id} center={center} zoom={mapConfig.defaultZoom ?? 2} />
|
||||||
)}
|
)}
|
||||||
{mode === "place" && <ClickHandler onPick={setPendingPoint} />}
|
{mode === "place" && <ClickHandler onPick={setPendingPoint} />}
|
||||||
|
{objectiveArmed && (
|
||||||
|
<ClickHandler
|
||||||
|
onPick={(point) => {
|
||||||
|
setEditingObjective(null);
|
||||||
|
setObjectivePoint(point);
|
||||||
|
setObjectiveDialogOpen(true);
|
||||||
|
setObjectiveArmed(false);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
{mode === "edit" && authoring.kind != null && (
|
{mode === "edit" && authoring.kind != null && (
|
||||||
<AuthoringSnapLayer
|
<AuthoringSnapLayer
|
||||||
targets={snapTargets}
|
targets={snapTargets}
|
||||||
|
|
@ -1717,6 +1705,7 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
|
||||||
setMode((current) => (current === "place" ? "view" : "place"));
|
setMode((current) => (current === "place" ? "view" : "place"));
|
||||||
authoring.setKind(null);
|
authoring.setKind(null);
|
||||||
setPendingPoint(null);
|
setPendingPoint(null);
|
||||||
|
setObjectiveArmed(false);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Hammer className="size-3.5" />
|
<Hammer className="size-3.5" />
|
||||||
|
|
@ -1724,6 +1713,23 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
|
||||||
</Button>
|
</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 && (
|
{canEdit && (
|
||||||
<Button
|
<Button
|
||||||
size="sm"
|
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 && (
|
{previewId != null && (
|
||||||
<StructureDetailDrawer structureId={previewId} onClose={() => setPreviewId(null)} />
|
<StructureDetailDrawer structureId={previewId} onClose={() => setPreviewId(null)} />
|
||||||
)}
|
)}
|
||||||
|
|
|
||||||
107
src/components/frontend/map/mapIcons.ts
Normal file
107
src/components/frontend/map/mapIcons.ts
Normal 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("&", "&")
|
||||||
|
.replaceAll("<", "<")
|
||||||
|
.replaceAll(">", ">")
|
||||||
|
.replaceAll('"', """);
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
274
src/components/frontend/map/objectives/ObjectiveDialog.tsx
Normal file
274
src/components/frontend/map/objectives/ObjectiveDialog.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
231
src/components/frontend/map/objectives/ObjectiveLayer.tsx
Normal file
231
src/components/frontend/map/objectives/ObjectiveLayer.tsx
Normal 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 },
|
||||||
|
});
|
||||||
|
}
|
||||||
35
src/components/frontend/map/objectives/objectiveVisuals.ts
Normal file
35
src/components/frontend/map/objectives/objectiveVisuals.ts
Normal 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: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
@ -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).
|
- **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).
|
- **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.
|
- **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`.
|
- **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`.
|
||||||
|
|
|
||||||
|
|
@ -5,13 +5,14 @@
|
||||||
|
|
||||||
Leaflet world map at `/map` (top-level sidebar entry, whole unit views it). Full docs: `docs/map-system.md`.
|
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).
|
- **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).
|
- **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`.
|
- **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.
|
- **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.
|
- **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`.
|
- **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).
|
- **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.
|
- **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"`.
|
||||||
|
|
|
||||||
52
src/lib/map/objectiveTypes.ts
Normal file
52
src/lib/map/objectiveTypes.ts
Normal 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
273
src/lib/map/objectives.ts
Normal 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;
|
||||||
|
}
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import type { MapPoint } from "./points";
|
import type { MapPoint } from "./points";
|
||||||
import type { MapGridConfig } from "./grid";
|
import type { MapGridConfig } from "./grid";
|
||||||
|
import type { MapObjectiveStatus } from "./objectiveTypes";
|
||||||
|
|
||||||
export interface MapConfig {
|
export interface MapConfig {
|
||||||
id: number;
|
id: number;
|
||||||
|
|
@ -96,6 +97,18 @@ export interface ShipmentFeature {
|
||||||
vehicleName: string | null;
|
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 {
|
export interface MapFeaturesResponse {
|
||||||
map: MapConfig;
|
map: MapConfig;
|
||||||
structures: StructureFeature[];
|
structures: StructureFeature[];
|
||||||
|
|
@ -103,4 +116,5 @@ export interface MapFeaturesResponse {
|
||||||
roads: RoadFeature[];
|
roads: RoadFeature[];
|
||||||
zones: ZoneFeature[];
|
zones: ZoneFeature[];
|
||||||
shipments: ShipmentFeature[];
|
shipments: ShipmentFeature[];
|
||||||
|
objectives: MapObjectiveFeature[];
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -371,6 +371,8 @@ export const enum_game_event_logs_required_permissions = pgEnum(
|
||||||
"resource-nodes:read",
|
"resource-nodes:read",
|
||||||
"resource-nodes:author",
|
"resource-nodes:author",
|
||||||
"admin:resource-nodes:manage",
|
"admin:resource-nodes:manage",
|
||||||
|
"map-objectives:read",
|
||||||
|
"admin:map-objectives:manage",
|
||||||
"narrative-events:create",
|
"narrative-events:create",
|
||||||
"narrative-events:read",
|
"narrative-events:read",
|
||||||
"narrative-events:update",
|
"narrative-events:update",
|
||||||
|
|
@ -544,6 +546,7 @@ export const enum_game_event_logs_target_collection = pgEnum(
|
||||||
"wiki-templates",
|
"wiki-templates",
|
||||||
"form-submissions",
|
"form-submissions",
|
||||||
"mission-map-markers",
|
"mission-map-markers",
|
||||||
|
"map-objectives",
|
||||||
"contribution-entries",
|
"contribution-entries",
|
||||||
"game-servers",
|
"game-servers",
|
||||||
"assignment-transfers",
|
"assignment-transfers",
|
||||||
|
|
@ -928,6 +931,8 @@ export const enum_roles_permissions = pgEnum("enum_roles_permissions", [
|
||||||
"resource-nodes:read",
|
"resource-nodes:read",
|
||||||
"resource-nodes:author",
|
"resource-nodes:author",
|
||||||
"admin:resource-nodes:manage",
|
"admin:resource-nodes:manage",
|
||||||
|
"map-objectives:read",
|
||||||
|
"admin:map-objectives:manage",
|
||||||
"narrative-events:create",
|
"narrative-events:create",
|
||||||
"narrative-events:read",
|
"narrative-events:read",
|
||||||
"narrative-events:update",
|
"narrative-events:update",
|
||||||
|
|
@ -1587,6 +1592,11 @@ export const enum_map_zones_type = pgEnum("enum_map_zones_type", [
|
||||||
"border",
|
"border",
|
||||||
"other",
|
"other",
|
||||||
]);
|
]);
|
||||||
|
export const enum_map_objectives_status = pgEnum("enum_map_objectives_status", [
|
||||||
|
"active",
|
||||||
|
"secured",
|
||||||
|
"failed",
|
||||||
|
]);
|
||||||
export const enum_resource_nodes_icon = pgEnum("enum_resource_nodes_icon", [
|
export const enum_resource_nodes_icon = pgEnum("enum_resource_nodes_icon", [
|
||||||
"marker",
|
"marker",
|
||||||
"droplet",
|
"droplet",
|
||||||
|
|
@ -1635,6 +1645,7 @@ export const enum_operation_effects_effect_type = pgEnum("enum_operation_effects
|
||||||
export const enum_operation_effects_status = pgEnum("enum_operation_effects_status", [
|
export const enum_operation_effects_status = pgEnum("enum_operation_effects_status", [
|
||||||
"applied",
|
"applied",
|
||||||
"pending",
|
"pending",
|
||||||
|
"pending_action",
|
||||||
"failed",
|
"failed",
|
||||||
"reversed",
|
"reversed",
|
||||||
]);
|
]);
|
||||||
|
|
@ -5438,6 +5449,25 @@ export const vehicles_allowed_virtual_cargo = pgTable(
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
export const vehicles_disallowed_cargo = pgTable(
|
||||||
|
"vehicles_disallowed_cargo",
|
||||||
|
{
|
||||||
|
_order: integer("_order").notNull(),
|
||||||
|
_parentID: integer("_parent_id").notNull(),
|
||||||
|
id: varchar("id").primaryKey(),
|
||||||
|
amount: numeric("amount", { mode: "number" }).default(0),
|
||||||
|
},
|
||||||
|
(columns) => [
|
||||||
|
index("vehicles_disallowed_cargo_order_idx").on(columns._order),
|
||||||
|
index("vehicles_disallowed_cargo_parent_id_idx").on(columns._parentID),
|
||||||
|
foreignKey({
|
||||||
|
columns: [columns["_parentID"]],
|
||||||
|
foreignColumns: [vehicles.id],
|
||||||
|
name: "vehicles_disallowed_cargo_parent_id_fk",
|
||||||
|
}).onDelete("cascade"),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
export const vehicles_pylons = pgTable(
|
export const vehicles_pylons = pgTable(
|
||||||
"vehicles_pylons",
|
"vehicles_pylons",
|
||||||
{
|
{
|
||||||
|
|
@ -7404,6 +7434,39 @@ export const map_zones_rels = pgTable(
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
export const map_objectives = pgTable(
|
||||||
|
"map_objectives",
|
||||||
|
{
|
||||||
|
id: serial("id").primaryKey(),
|
||||||
|
name: varchar("name").notNull(),
|
||||||
|
description: varchar("description"),
|
||||||
|
map: integer("map_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => maps.id, {
|
||||||
|
onDelete: "set null",
|
||||||
|
}),
|
||||||
|
markerType: varchar("marker_type").default("mil_objective"),
|
||||||
|
status: enum_map_objectives_status("status").notNull().default("active"),
|
||||||
|
redacted: boolean("redacted").default(false),
|
||||||
|
position: jsonb("position").notNull(),
|
||||||
|
createdBy: integer("created_by_id").references(() => users.id, {
|
||||||
|
onDelete: "set null",
|
||||||
|
}),
|
||||||
|
updatedAt: timestamp("updated_at", { mode: "string", withTimezone: true, precision: 3 })
|
||||||
|
.defaultNow()
|
||||||
|
.notNull(),
|
||||||
|
createdAt: timestamp("created_at", { mode: "string", withTimezone: true, precision: 3 })
|
||||||
|
.defaultNow()
|
||||||
|
.notNull(),
|
||||||
|
},
|
||||||
|
(columns) => [
|
||||||
|
index("map_objectives_map_idx").on(columns.map),
|
||||||
|
index("map_objectives_created_by_idx").on(columns.createdBy),
|
||||||
|
index("map_objectives_updated_at_idx").on(columns.updatedAt),
|
||||||
|
index("map_objectives_created_at_idx").on(columns.createdAt),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
export const resource_nodes = pgTable(
|
export const resource_nodes = pgTable(
|
||||||
"resource_nodes",
|
"resource_nodes",
|
||||||
{
|
{
|
||||||
|
|
@ -7897,6 +7960,7 @@ export const operation_effects = pgTable(
|
||||||
effectKey: varchar("effect_key").notNull(),
|
effectKey: varchar("effect_key").notNull(),
|
||||||
effectType: enum_operation_effects_effect_type("effect_type").notNull(),
|
effectType: enum_operation_effects_effect_type("effect_type").notNull(),
|
||||||
status: enum_operation_effects_status("status").notNull().default("applied"),
|
status: enum_operation_effects_status("status").notNull().default("applied"),
|
||||||
|
decisions: jsonb("decisions"),
|
||||||
payload: jsonb("payload"),
|
payload: jsonb("payload"),
|
||||||
reversalOf: integer("reversal_of_id").references((): AnyPgColumn => operation_effects.id, {
|
reversalOf: integer("reversal_of_id").references((): AnyPgColumn => operation_effects.id, {
|
||||||
onDelete: "set null",
|
onDelete: "set null",
|
||||||
|
|
@ -9209,6 +9273,10 @@ export const payload_mcp_api_keys = pgTable(
|
||||||
mapZones_create: boolean("map_zones_create").default(false),
|
mapZones_create: boolean("map_zones_create").default(false),
|
||||||
mapZones_update: boolean("map_zones_update").default(false),
|
mapZones_update: boolean("map_zones_update").default(false),
|
||||||
mapZones_delete: boolean("map_zones_delete").default(false),
|
mapZones_delete: boolean("map_zones_delete").default(false),
|
||||||
|
mapObjectives_find: boolean("map_objectives_find").default(false),
|
||||||
|
mapObjectives_create: boolean("map_objectives_create").default(false),
|
||||||
|
mapObjectives_update: boolean("map_objectives_update").default(false),
|
||||||
|
mapObjectives_delete: boolean("map_objectives_delete").default(false),
|
||||||
resourceNodes_find: boolean("resource_nodes_find").default(false),
|
resourceNodes_find: boolean("resource_nodes_find").default(false),
|
||||||
resourceNodes_create: boolean("resource_nodes_create").default(false),
|
resourceNodes_create: boolean("resource_nodes_create").default(false),
|
||||||
resourceNodes_update: boolean("resource_nodes_update").default(false),
|
resourceNodes_update: boolean("resource_nodes_update").default(false),
|
||||||
|
|
@ -9435,6 +9503,7 @@ export const payload_locked_documents_rels = pgTable(
|
||||||
mapsID: integer("maps_id"),
|
mapsID: integer("maps_id"),
|
||||||
"map-roadsID": integer("map_roads_id"),
|
"map-roadsID": integer("map_roads_id"),
|
||||||
"map-zonesID": integer("map_zones_id"),
|
"map-zonesID": integer("map_zones_id"),
|
||||||
|
"map-objectivesID": integer("map_objectives_id"),
|
||||||
"resource-nodesID": integer("resource_nodes_id"),
|
"resource-nodesID": integer("resource_nodes_id"),
|
||||||
"narrative-eventsID": integer("narrative_events_id"),
|
"narrative-eventsID": integer("narrative_events_id"),
|
||||||
"story-beatsID": integer("story_beats_id"),
|
"story-beatsID": integer("story_beats_id"),
|
||||||
|
|
@ -9573,6 +9642,7 @@ export const payload_locked_documents_rels = pgTable(
|
||||||
index("payload_locked_documents_rels_maps_id_idx").on(columns.mapsID),
|
index("payload_locked_documents_rels_maps_id_idx").on(columns.mapsID),
|
||||||
index("payload_locked_documents_rels_map_roads_id_idx").on(columns["map-roadsID"]),
|
index("payload_locked_documents_rels_map_roads_id_idx").on(columns["map-roadsID"]),
|
||||||
index("payload_locked_documents_rels_map_zones_id_idx").on(columns["map-zonesID"]),
|
index("payload_locked_documents_rels_map_zones_id_idx").on(columns["map-zonesID"]),
|
||||||
|
index("payload_locked_documents_rels_map_objectives_id_idx").on(columns["map-objectivesID"]),
|
||||||
index("payload_locked_documents_rels_resource_nodes_id_idx").on(columns["resource-nodesID"]),
|
index("payload_locked_documents_rels_resource_nodes_id_idx").on(columns["resource-nodesID"]),
|
||||||
index("payload_locked_documents_rels_narrative_events_id_idx").on(
|
index("payload_locked_documents_rels_narrative_events_id_idx").on(
|
||||||
columns["narrative-eventsID"],
|
columns["narrative-eventsID"],
|
||||||
|
|
@ -9987,6 +10057,11 @@ export const payload_locked_documents_rels = pgTable(
|
||||||
foreignColumns: [map_zones.id],
|
foreignColumns: [map_zones.id],
|
||||||
name: "payload_locked_documents_rels_map_zones_fk",
|
name: "payload_locked_documents_rels_map_zones_fk",
|
||||||
}).onDelete("cascade"),
|
}).onDelete("cascade"),
|
||||||
|
foreignKey({
|
||||||
|
columns: [columns["map-objectivesID"]],
|
||||||
|
foreignColumns: [map_objectives.id],
|
||||||
|
name: "payload_locked_documents_rels_map_objectives_fk",
|
||||||
|
}).onDelete("cascade"),
|
||||||
foreignKey({
|
foreignKey({
|
||||||
columns: [columns["resource-nodesID"]],
|
columns: [columns["resource-nodesID"]],
|
||||||
foreignColumns: [resource_nodes.id],
|
foreignColumns: [resource_nodes.id],
|
||||||
|
|
@ -11932,6 +12007,16 @@ export const relations_vehicles_allowed_virtual_cargo = relations(
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
export const relations_vehicles_disallowed_cargo = relations(
|
||||||
|
vehicles_disallowed_cargo,
|
||||||
|
({ one }) => ({
|
||||||
|
_parentID: one(vehicles, {
|
||||||
|
fields: [vehicles_disallowed_cargo._parentID],
|
||||||
|
references: [vehicles.id],
|
||||||
|
relationName: "disallowedCargo",
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
);
|
||||||
export const relations_vehicles_pylons = relations(vehicles_pylons, ({ one }) => ({
|
export const relations_vehicles_pylons = relations(vehicles_pylons, ({ one }) => ({
|
||||||
_parentID: one(vehicles, {
|
_parentID: one(vehicles, {
|
||||||
fields: [vehicles_pylons._parentID],
|
fields: [vehicles_pylons._parentID],
|
||||||
|
|
@ -11997,6 +12082,9 @@ export const relations_vehicles = relations(vehicles, ({ one, many }) => ({
|
||||||
allowedVirtualCargo: many(vehicles_allowed_virtual_cargo, {
|
allowedVirtualCargo: many(vehicles_allowed_virtual_cargo, {
|
||||||
relationName: "allowedVirtualCargo",
|
relationName: "allowedVirtualCargo",
|
||||||
}),
|
}),
|
||||||
|
disallowedCargo: many(vehicles_disallowed_cargo, {
|
||||||
|
relationName: "disallowedCargo",
|
||||||
|
}),
|
||||||
pylons: many(vehicles_pylons, {
|
pylons: many(vehicles_pylons, {
|
||||||
relationName: "pylons",
|
relationName: "pylons",
|
||||||
}),
|
}),
|
||||||
|
|
@ -12926,6 +13014,18 @@ export const relations_map_zones = relations(map_zones, ({ one, many }) => ({
|
||||||
relationName: "_rels",
|
relationName: "_rels",
|
||||||
}),
|
}),
|
||||||
}));
|
}));
|
||||||
|
export const relations_map_objectives = relations(map_objectives, ({ one }) => ({
|
||||||
|
map: one(maps, {
|
||||||
|
fields: [map_objectives.map],
|
||||||
|
references: [maps.id],
|
||||||
|
relationName: "map",
|
||||||
|
}),
|
||||||
|
createdBy: one(users, {
|
||||||
|
fields: [map_objectives.createdBy],
|
||||||
|
references: [users.id],
|
||||||
|
relationName: "createdBy",
|
||||||
|
}),
|
||||||
|
}));
|
||||||
export const relations_resource_nodes_rels = relations(resource_nodes_rels, ({ one }) => ({
|
export const relations_resource_nodes_rels = relations(resource_nodes_rels, ({ one }) => ({
|
||||||
parent: one(resource_nodes, {
|
parent: one(resource_nodes, {
|
||||||
fields: [resource_nodes_rels.parent],
|
fields: [resource_nodes_rels.parent],
|
||||||
|
|
@ -13837,6 +13937,11 @@ export const relations_payload_locked_documents_rels = relations(
|
||||||
references: [map_zones.id],
|
references: [map_zones.id],
|
||||||
relationName: "map-zones",
|
relationName: "map-zones",
|
||||||
}),
|
}),
|
||||||
|
"map-objectivesID": one(map_objectives, {
|
||||||
|
fields: [payload_locked_documents_rels["map-objectivesID"]],
|
||||||
|
references: [map_objectives.id],
|
||||||
|
relationName: "map-objectives",
|
||||||
|
}),
|
||||||
"resource-nodesID": one(resource_nodes, {
|
"resource-nodesID": one(resource_nodes, {
|
||||||
fields: [payload_locked_documents_rels["resource-nodesID"]],
|
fields: [payload_locked_documents_rels["resource-nodesID"]],
|
||||||
references: [resource_nodes.id],
|
references: [resource_nodes.id],
|
||||||
|
|
@ -14227,6 +14332,7 @@ type DatabaseSchema = {
|
||||||
enum_map_roads_surface: typeof enum_map_roads_surface;
|
enum_map_roads_surface: typeof enum_map_roads_surface;
|
||||||
enum_map_roads_stroke_style: typeof enum_map_roads_stroke_style;
|
enum_map_roads_stroke_style: typeof enum_map_roads_stroke_style;
|
||||||
enum_map_zones_type: typeof enum_map_zones_type;
|
enum_map_zones_type: typeof enum_map_zones_type;
|
||||||
|
enum_map_objectives_status: typeof enum_map_objectives_status;
|
||||||
enum_resource_nodes_icon: typeof enum_resource_nodes_icon;
|
enum_resource_nodes_icon: typeof enum_resource_nodes_icon;
|
||||||
enum_narrative_events_triggers_type: typeof enum_narrative_events_triggers_type;
|
enum_narrative_events_triggers_type: typeof enum_narrative_events_triggers_type;
|
||||||
enum_story_beats_status: typeof enum_story_beats_status;
|
enum_story_beats_status: typeof enum_story_beats_status;
|
||||||
|
|
@ -14364,6 +14470,7 @@ type DatabaseSchema = {
|
||||||
vehicles_scrap_returns: typeof vehicles_scrap_returns;
|
vehicles_scrap_returns: typeof vehicles_scrap_returns;
|
||||||
vehicles_upkeep_costs: typeof vehicles_upkeep_costs;
|
vehicles_upkeep_costs: typeof vehicles_upkeep_costs;
|
||||||
vehicles_allowed_virtual_cargo: typeof vehicles_allowed_virtual_cargo;
|
vehicles_allowed_virtual_cargo: typeof vehicles_allowed_virtual_cargo;
|
||||||
|
vehicles_disallowed_cargo: typeof vehicles_disallowed_cargo;
|
||||||
vehicles_pylons: typeof vehicles_pylons;
|
vehicles_pylons: typeof vehicles_pylons;
|
||||||
vehicles: typeof vehicles;
|
vehicles: typeof vehicles;
|
||||||
vehicles_rels: typeof vehicles_rels;
|
vehicles_rels: typeof vehicles_rels;
|
||||||
|
|
@ -14426,6 +14533,7 @@ type DatabaseSchema = {
|
||||||
map_roads: typeof map_roads;
|
map_roads: typeof map_roads;
|
||||||
map_zones: typeof map_zones;
|
map_zones: typeof map_zones;
|
||||||
map_zones_rels: typeof map_zones_rels;
|
map_zones_rels: typeof map_zones_rels;
|
||||||
|
map_objectives: typeof map_objectives;
|
||||||
resource_nodes: typeof resource_nodes;
|
resource_nodes: typeof resource_nodes;
|
||||||
resource_nodes_rels: typeof resource_nodes_rels;
|
resource_nodes_rels: typeof resource_nodes_rels;
|
||||||
narrative_events: typeof narrative_events;
|
narrative_events: typeof narrative_events;
|
||||||
|
|
@ -14599,6 +14707,7 @@ type DatabaseSchema = {
|
||||||
relations_vehicles_scrap_returns: typeof relations_vehicles_scrap_returns;
|
relations_vehicles_scrap_returns: typeof relations_vehicles_scrap_returns;
|
||||||
relations_vehicles_upkeep_costs: typeof relations_vehicles_upkeep_costs;
|
relations_vehicles_upkeep_costs: typeof relations_vehicles_upkeep_costs;
|
||||||
relations_vehicles_allowed_virtual_cargo: typeof relations_vehicles_allowed_virtual_cargo;
|
relations_vehicles_allowed_virtual_cargo: typeof relations_vehicles_allowed_virtual_cargo;
|
||||||
|
relations_vehicles_disallowed_cargo: typeof relations_vehicles_disallowed_cargo;
|
||||||
relations_vehicles_pylons: typeof relations_vehicles_pylons;
|
relations_vehicles_pylons: typeof relations_vehicles_pylons;
|
||||||
relations_vehicles_rels: typeof relations_vehicles_rels;
|
relations_vehicles_rels: typeof relations_vehicles_rels;
|
||||||
relations_vehicles: typeof relations_vehicles;
|
relations_vehicles: typeof relations_vehicles;
|
||||||
|
|
@ -14661,6 +14770,7 @@ type DatabaseSchema = {
|
||||||
relations_map_roads: typeof relations_map_roads;
|
relations_map_roads: typeof relations_map_roads;
|
||||||
relations_map_zones_rels: typeof relations_map_zones_rels;
|
relations_map_zones_rels: typeof relations_map_zones_rels;
|
||||||
relations_map_zones: typeof relations_map_zones;
|
relations_map_zones: typeof relations_map_zones;
|
||||||
|
relations_map_objectives: typeof relations_map_objectives;
|
||||||
relations_resource_nodes_rels: typeof relations_resource_nodes_rels;
|
relations_resource_nodes_rels: typeof relations_resource_nodes_rels;
|
||||||
relations_resource_nodes: typeof relations_resource_nodes;
|
relations_resource_nodes: typeof relations_resource_nodes;
|
||||||
relations_narrative_events: typeof relations_narrative_events;
|
relations_narrative_events: typeof relations_narrative_events;
|
||||||
|
|
|
||||||
|
|
@ -137,6 +137,7 @@ export interface Config {
|
||||||
maps: Map;
|
maps: Map;
|
||||||
'map-roads': MapRoad;
|
'map-roads': MapRoad;
|
||||||
'map-zones': MapZone;
|
'map-zones': MapZone;
|
||||||
|
'map-objectives': MapObjective;
|
||||||
'resource-nodes': ResourceNode;
|
'resource-nodes': ResourceNode;
|
||||||
'narrative-events': NarrativeEvent;
|
'narrative-events': NarrativeEvent;
|
||||||
'story-beats': StoryBeat;
|
'story-beats': StoryBeat;
|
||||||
|
|
@ -250,6 +251,7 @@ export interface Config {
|
||||||
maps: MapsSelect<false> | MapsSelect<true>;
|
maps: MapsSelect<false> | MapsSelect<true>;
|
||||||
'map-roads': MapRoadsSelect<false> | MapRoadsSelect<true>;
|
'map-roads': MapRoadsSelect<false> | MapRoadsSelect<true>;
|
||||||
'map-zones': MapZonesSelect<false> | MapZonesSelect<true>;
|
'map-zones': MapZonesSelect<false> | MapZonesSelect<true>;
|
||||||
|
'map-objectives': MapObjectivesSelect<false> | MapObjectivesSelect<true>;
|
||||||
'resource-nodes': ResourceNodesSelect<false> | ResourceNodesSelect<true>;
|
'resource-nodes': ResourceNodesSelect<false> | ResourceNodesSelect<true>;
|
||||||
'narrative-events': NarrativeEventsSelect<false> | NarrativeEventsSelect<true>;
|
'narrative-events': NarrativeEventsSelect<false> | NarrativeEventsSelect<true>;
|
||||||
'story-beats': StoryBeatsSelect<false> | StoryBeatsSelect<true>;
|
'story-beats': StoryBeatsSelect<false> | StoryBeatsSelect<true>;
|
||||||
|
|
@ -899,6 +901,8 @@ export interface Role {
|
||||||
| 'resource-nodes:read'
|
| 'resource-nodes:read'
|
||||||
| 'resource-nodes:author'
|
| 'resource-nodes:author'
|
||||||
| 'admin:resource-nodes:manage'
|
| 'admin:resource-nodes:manage'
|
||||||
|
| 'map-objectives:read'
|
||||||
|
| 'admin:map-objectives:manage'
|
||||||
| 'narrative-events:create'
|
| 'narrative-events:create'
|
||||||
| 'narrative-events:read'
|
| 'narrative-events:read'
|
||||||
| 'narrative-events:update'
|
| 'narrative-events:update'
|
||||||
|
|
@ -3424,6 +3428,8 @@ export interface GameEventLog {
|
||||||
| 'resource-nodes:read'
|
| 'resource-nodes:read'
|
||||||
| 'resource-nodes:author'
|
| 'resource-nodes:author'
|
||||||
| 'admin:resource-nodes:manage'
|
| 'admin:resource-nodes:manage'
|
||||||
|
| 'map-objectives:read'
|
||||||
|
| 'admin:map-objectives:manage'
|
||||||
| 'narrative-events:create'
|
| 'narrative-events:create'
|
||||||
| 'narrative-events:read'
|
| 'narrative-events:read'
|
||||||
| 'narrative-events:update'
|
| 'narrative-events:update'
|
||||||
|
|
@ -3600,6 +3606,7 @@ export interface GameEventLog {
|
||||||
| 'wiki-templates'
|
| 'wiki-templates'
|
||||||
| 'form-submissions'
|
| 'form-submissions'
|
||||||
| 'mission-map-markers'
|
| 'mission-map-markers'
|
||||||
|
| 'map-objectives'
|
||||||
| 'contribution-entries'
|
| 'contribution-entries'
|
||||||
| 'game-servers'
|
| 'game-servers'
|
||||||
| 'assignment-transfers'
|
| 'assignment-transfers'
|
||||||
|
|
@ -6043,6 +6050,51 @@ export interface MapZone {
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
createdAt: 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
|
* This interface was referenced by `Config`'s JSON-Schema
|
||||||
* via the `definition` "resource-nodes".
|
* via the `definition` "resource-nodes".
|
||||||
|
|
@ -8494,6 +8546,24 @@ export interface PayloadMcpApiKey {
|
||||||
*/
|
*/
|
||||||
delete?: boolean | null;
|
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?: {
|
resourceNodes?: {
|
||||||
/**
|
/**
|
||||||
* Allow clients to find resource-nodes.
|
* Allow clients to find resource-nodes.
|
||||||
|
|
@ -9269,6 +9339,10 @@ export interface PayloadLockedDocument {
|
||||||
relationTo: 'map-zones';
|
relationTo: 'map-zones';
|
||||||
value: number | MapZone;
|
value: number | MapZone;
|
||||||
} | null)
|
} | null)
|
||||||
|
| ({
|
||||||
|
relationTo: 'map-objectives';
|
||||||
|
value: number | MapObjective;
|
||||||
|
} | null)
|
||||||
| ({
|
| ({
|
||||||
relationTo: 'resource-nodes';
|
relationTo: 'resource-nodes';
|
||||||
value: number | ResourceNode;
|
value: number | ResourceNode;
|
||||||
|
|
@ -11750,6 +11824,22 @@ export interface MapZonesSelect<T extends boolean = true> {
|
||||||
updatedAt?: T;
|
updatedAt?: T;
|
||||||
createdAt?: 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
|
* This interface was referenced by `Config`'s JSON-Schema
|
||||||
* via the `definition` "resource-nodes_select".
|
* via the `definition` "resource-nodes_select".
|
||||||
|
|
@ -12982,6 +13072,14 @@ export interface PayloadMcpApiKeysSelect<T extends boolean = true> {
|
||||||
update?: T;
|
update?: T;
|
||||||
delete?: T;
|
delete?: T;
|
||||||
};
|
};
|
||||||
|
mapObjectives?:
|
||||||
|
| T
|
||||||
|
| {
|
||||||
|
find?: T;
|
||||||
|
create?: T;
|
||||||
|
update?: T;
|
||||||
|
delete?: T;
|
||||||
|
};
|
||||||
resourceNodes?:
|
resourceNodes?:
|
||||||
| T
|
| T
|
||||||
| {
|
| {
|
||||||
|
|
|
||||||
|
|
@ -22,6 +22,7 @@ import { MissionMapMarkers } from "@/collections/intelligence/MissionMapMarkers"
|
||||||
import { Maps } from "@/collections/world/Maps";
|
import { Maps } from "@/collections/world/Maps";
|
||||||
import { MapRoads } from "@/collections/world/MapRoads";
|
import { MapRoads } from "@/collections/world/MapRoads";
|
||||||
import { MapZones } from "@/collections/world/MapZones";
|
import { MapZones } from "@/collections/world/MapZones";
|
||||||
|
import { MapObjectives } from "@/collections/world/MapObjectives";
|
||||||
import { ResourceNodes } from "@/collections/world/ResourceNodes";
|
import { ResourceNodes } from "@/collections/world/ResourceNodes";
|
||||||
import { Campaigns } from "@/collections/intelligence/Campaigns";
|
import { Campaigns } from "@/collections/intelligence/Campaigns";
|
||||||
import { Qualifications } from "@/collections/users/Qualifications";
|
import { Qualifications } from "@/collections/users/Qualifications";
|
||||||
|
|
@ -398,6 +399,7 @@ const collections = [
|
||||||
Maps,
|
Maps,
|
||||||
MapRoads,
|
MapRoads,
|
||||||
MapZones,
|
MapZones,
|
||||||
|
MapObjectives,
|
||||||
ResourceNodes,
|
ResourceNodes,
|
||||||
NarrativeEvents,
|
NarrativeEvents,
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -34,7 +34,12 @@ export interface PermissionGroup {
|
||||||
export const PERMISSION_GROUPS: PermissionGroup[] = [
|
export const PERMISSION_GROUPS: PermissionGroup[] = [
|
||||||
{
|
{
|
||||||
group: "System",
|
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 ---------------------------------------------------------------
|
// ---- Media ---------------------------------------------------------------
|
||||||
|
|
@ -586,6 +591,14 @@ export const PERMISSION_GROUPS: PermissionGroup[] = [
|
||||||
{ value: "resource-nodes:read", label: "Read Resource Nodes" },
|
{ value: "resource-nodes:read", label: "Read Resource Nodes" },
|
||||||
{ value: "resource-nodes:author", label: "Author Resource Nodes" },
|
{ value: "resource-nodes:author", label: "Author Resource Nodes" },
|
||||||
{ value: "admin:resource-nodes:manage", label: "Manage Resource Nodes Admin Page" },
|
{ 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:read",
|
||||||
"resource-nodes:author",
|
"resource-nodes:author",
|
||||||
"admin:resource-nodes:manage",
|
"admin:resource-nodes:manage",
|
||||||
|
"map-objectives:read",
|
||||||
|
"admin:map-objectives:manage",
|
||||||
"narrative-events:create",
|
"narrative-events:create",
|
||||||
"narrative-events:read",
|
"narrative-events:read",
|
||||||
"narrative-events:update",
|
"narrative-events:update",
|
||||||
|
|
|
||||||
|
|
@ -57,6 +57,7 @@ interface GameEventInput {
|
||||||
| "reinforcement-pools"
|
| "reinforcement-pools"
|
||||||
| "form-submissions"
|
| "form-submissions"
|
||||||
| "mission-map-markers"
|
| "mission-map-markers"
|
||||||
|
| "map-objectives"
|
||||||
| "contribution-entries"
|
| "contribution-entries"
|
||||||
| "journals"
|
| "journals"
|
||||||
| "awards";
|
| "awards";
|
||||||
|
|
|
||||||
|
|
@ -178,6 +178,13 @@ export const EventTypes = {
|
||||||
MissionMapMarkersClear: "mission:map-markers-clear",
|
MissionMapMarkersClear: "mission:map-markers-clear",
|
||||||
MissionPlanningDelegates: "mission:planning-delegates",
|
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
|
// Contributions / XP
|
||||||
ContributionQueued: "contribution:queue",
|
ContributionQueued: "contribution:queue",
|
||||||
ContributionGranted: "contribution:grant",
|
ContributionGranted: "contribution:grant",
|
||||||
|
|
|
||||||
126
tests/e2e/map-objectives.e2e.spec.ts
Normal file
126
tests/e2e/map-objectives.e2e.spec.ts
Normal 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()?.text ?? ""),
|
||||||
|
);
|
||||||
|
|
||||||
|
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" });
|
||||||
|
});
|
||||||
|
});
|
||||||
298
tests/int/map-objectives.int.spec.ts
Normal file
298
tests/int/map-objectives.int.spec.ts
Normal 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);
|
||||||
|
});
|
||||||
|
});
|
||||||
Loading…
Reference in a new issue