1
0
Fork 0
polaris-task-force/src/lib/map/objectives.ts
Z8MB1E 3bef63af33 feat(map-objectives): superuser-authored strategic objectives on mission maps
Add a superuser-authored objective layer (defend, assault, secure, etc.)
shown as labelled map markers on both the world map and mission planning
map, with per-layer toggles on the planning map.

- collection: MapObjectives (map_objectives table, enums, FKs)
- lib: objectives service + objectiveTypes + permissions + event emit
- actions/api: create/update/delete objectives server actions
- UI: feature-layer toggles, objective picker dialog, world/plan markers,
  SQF export, dossier dialog integration
- generated: regenerate payload schema + types for map_objectives
- tests: 10 integration specs + e2e spec
- docs: CHANGELOG, map-system, AGENTS guides
2026-10-27 02:12:31 -04:00

273 lines
9 KiB
TypeScript

/**
* 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;
}