1
0
Fork 0

Compare commits

..

No commits in common. "35a88ccd8f74f1fcd91b9ccfa634b20c29938184" and "8f91bfedbd7d50ee756b73692d0fdeb4f907825a" have entirely different histories.

35 changed files with 161 additions and 45024 deletions

View file

@ -1,26 +1,5 @@
# Changelog
# v0.10.0
The Garage replaces the Deployed Vehicles list: every structure with a vehicle bay now has a grid where parked vehicles can be arranged, rotated, dispatched, and stored.
### Features
- **Garage.** Structures whose blueprint defines a vehicle bay expose a garage grid at /logistics/garage. Drag parked vehicles between cells, press R to rotate, and use Dispatch and Store for real movement in and out of the bay. The old Deployed Vehicles page redirects here.
- **Elsewhere section.** Deployed vehicles that do not fit a bay, or sit at structures without one, are listed under Elsewhere so nothing goes missing.
- **Bridge sync.** The Arma bridge now handles garage deposit, withdraw, and bay sync events, keeping the grid aligned with what is actually parked in the game world.
- **Vehicle library picker.** Vehicle templates can now be filled from imported Arma vehicle records, pulling in the thumbnail plus mass and category defaults.
### Improvements
- **Rotated thumbnails.** A vehicle's silhouette now turns with its card and keeps its full size, so orientation reads at a glance.
### Fixes
- Rotating an item mid-drag no longer collapses the drag preview to a square in the locker, storage, and garage grids.
---
# v0.9.2
Journals now earn contribution XP, alongside a few journal, editor, and navigation fixes.

View file

@ -1,8 +0,0 @@
# LESSONS.md — Polaris Task Force
Distilled rules for future sessions. Format per `lesson-capture` skill: trigger, rule, rationale.
## 2026-10-13 — New (frontend) pages must own their page padding
- **Type**: correction
- **Lesson**: Every page under `src/app/(frontend)/` renders its content inside a root wrapper that includes `p-5` (convention: `<div className="p-5 flex flex-col gap-6">`, add `max-w-*` when the page wants a width cap). The `(frontend)` layout provides the sidebar/header shell but NO content padding, so a page root without `p-5` renders flush against the header and sidebar. Copy the wrapper from a sibling page (e.g. `logistics/page.tsx`) when creating a new route.
- **Why**: The Garage page shipped with `flex flex-col gap-6` and no padding; user had to annotate it in the browser ("contents touching the header and sidebar"). ~55 existing pages already follow the `p-5` convention, so the omission is obvious the moment you compare siblings.

View file

@ -1,138 +0,0 @@
# Garage Sync Contract
Binding contract for vehicle-garage sync between the Arma 3 addon and the web
app. It covers **structure vehicle bays** (the Garage view at
`/logistics/garage`): parking, dispatching, and state (fuel/damage) of specific
vehicle **instances**. Implement exactly what is written here; do not redesign
while implementing.
## Overview
The Garage is a grid inventory of vehicle instances parked in structure vehicle
bays. The web app owns placement (grid cells are pure web bookkeeping, never
sent to the game); the game owns physical existence. Every physical vehicle
instance carries a `bridgeUid` assigned by the addon so two identical trucks are
distinguishable and fuel/damage stay honest per instance.
**Authority and physical despawn policy.** Until the addon ships, the garage is
**web-authoritative**: dispatch/store only change web state and enqueue commands
that no client consumes yet. Once the addon implements this contract:
- `garage.dispatch` means the physical object must **despawn from the bay**. The
unit relocates through game logic (cargo plane, sea port, scenario start),
never by driving out of the garage cell.
- `garage.store` means the addon must **spawn (or relocate) the instance at this
garage** with the given fuel and damage.
- `garage.apply` is a full reconciliation of the bay: spawn missing entries,
update existing ones, and despawn bay objects whose `bridgeUid` is absent
from the list.
- Cell coordinates are never transmitted. A web-side drag that only rearranges
cells must not produce any game-side movement.
## Instance identity
| Ref | Meaning |
|---|---|
| `garage:<storageSlug>` | One structure's vehicle bay. `<storageSlug>` is the structure's existing `storageSlug` field (the same slug the arsenal module binds to via `structure:<slug>`). No separate garage slug exists (assumption A1). |
A vehicle instance is identified on the wire by its `bridgeUid`: an opaque
addon-assigned string (1-64 chars, `[A-Za-z0-9_-]+`), stable for the lifetime of
the physical object and persisted across missions if the object persists. The
web claims unknown instances by classname match against unassigned vehicles at
that structure (first-tag-wins, provenance logged); otherwise it creates a new
`game-vehicles` row.
`fuel` is a fraction of tank capacity (0..1). `damage` is a fraction of total
damage (0 = intact, 1 = destroyed). Both are clamped by the web; out-of-range or
non-finite values fall back to 0.
## Event family
Payloads are flat arrays (`fn_queueEvent` stores `[_id, _type, _payload,
serverTime]`, payload defaults to `[]`). Events ride the existing
`POST /api/arma/v1/events` flush; dedup is by the unique `eventId`
(`<serverId>:<localId>`), so retries are no-ops.
| Type | Payload | Meaning |
|---|---|---|
| `garage.deposit` | `[garageRef, bridgeUid, classname, fuel, damage]` | An instance entered the bay and is parked. |
| `garage.withdraw` | `[garageRef, bridgeUid, classname, fuel, damage]` | A known instance physically left the bay (driven out, destroyed in place, deleted). |
| `garage.sync` | `[garageRef, [[bridgeUid, classname, fuel, damage], ...]]` | Full snapshot of instances currently parked in the bay. |
| `garage.request` | `[garageRef]` | The game asks the web to push current state for this garage (mission start, garage module load). |
## Web-side consumption rules
Processed from the `arma-sync-events` afterChange router (`src/lib/arma-bridge/garages.ts`):
1. **Claim or create.** Resolve `bridgeUid` to a `game-vehicles` row. Unknown
uid: claim the oldest untagged (null `bridgeUid`) instance whose populated
template `classname` matches, at the structure named by `garageRef`
(first-tag-wins; the claim is logged with the event id as provenance). No
candidate: create a new `game-vehicles` instance from the template matching
`classname`; unknown classnames are skipped with a warning.
2. **State merge.** Apply `fuel` (scaled to the template's `fuelCapacity`) and
`damage` (scaled to the template's `maxHealth`). `damage >= 1` sets status
`destroyed`; recovery below 1 clears `destroyed`/`damaged` back to `idle`.
Statuses `assigned` and `in_transit` are never overwritten by sync.
3. **Placement.** Deposit/sync entries without a cell are auto-placed row-major
into free bay cells. Cells already set on web rows are **preserved**; sync
never moves parked vehicles. A snapshot line for an unknown-to-the-game row
updates state only; absence from a snapshot is **not** deletion or
withdrawal.
4. **Withdraw.** Clears the instance's bay cells and `deployedAt`, sets status
`in_transit` (unless destroyed), keeps `bridgeUid`.
5. **Echo guard.** All writes made while processing garage events run with
`req.context.garageSyncOrigin = true`. Garage commands (`garage.apply`,
`garage.dispatch`, `garage.store`) are enqueued only by explicit user
actions, so sync-originated writes never bounce back as commands.
6. Processors **never throw**: malformed payloads log a warning and return;
unexpected errors are caught and logged so event ingestion cannot roll back.
## Command envelope and schemas
Envelope: `[commandId, commandType, payload]` (what `fn_pollCommands` passes
and `fn_executeCommand` destructures), stored in `arma-commands` and pulled via
`GET /api/arma/v1/commands/pull`. Commands target the most recently heartbeated
online game server (single-server assumption, same as locker sync).
| Type | Payload | Effect |
|---|---|---|
| `garage.apply` | `[garageRef, [[bridgeUid, classname, fuel, damage], ...]]` | Full state push for the bay; the addon reconciles as described above. Sent in response to `garage.request`. |
| `garage.dispatch` | `[garageRef, bridgeUid, classname, fuel, damage]` | Despawn this instance from the bay; it is now in transit (web cleared its cell and location). |
| `garage.store` | `[garageRef, bridgeUid, classname, fuel, damage]` | Spawn/relocate this instance into this garage bay. |
Instances without a `bridgeUid` (never seen by the game) produce no commands;
their dispatch/store stays web-only.
## Failure rules
- Unknown `garageRef` slug: warn and skip the event.
- Malformed payload shape (not an array, bad ref, non-string uid, non-finite
numbers): warn and skip the whole event, never partially apply.
- Snapshot arrays are capped at 200 lines; longer snapshots are truncated with
a warning.
- Commands are fire-and-forget: no online server means the enqueue is skipped
with a warning (the web state is already committed).
- Duplicate `eventId` deliveries are dropped by the unique index before the
processor runs.
## Security
- Server identity always comes from the authenticated bridge connection
(`x-arma-bridge-key` + `x-arma-server-id`), never from event payloads.
- Events are read-only inserts for the bridge; the addon cannot call
`arma-commands` directly, only pull/ack them.
- Classnames and uids are treated as opaque strings; they are length-capped and
never interpolated into queries beyond Payload's parameterized `where`.
## Mod-side behavior (garage module)
- Assign each tracked physical vehicle a `bridgeUid` on spawn; persist it on the
object (e.g. `setVariable`) and reuse it in every event.
- Emit `garage.deposit` when an instance parks in a bay zone, `garage.withdraw`
when it leaves or dies, and batch `garage.sync` after any committed change to
bay contents (same flush cadence as locker sync).
- On module load / mission start, emit `garage.request` per configured bay and
apply the returned `garage.apply` snapshot.
- Ack every executed command through the existing commands ack route; failed
executions ack with `success: false` and an error string.

View file

@ -1,6 +1,6 @@
{
"name": "polaris-task-force",
"version": "0.10.0",
"version": "0.9.2",
"description": "Web app for the Arma 3 unit Polaris Task Force. Uses Next.js for client- and server-side rendering, with a Postgres database and some other neat libraries.",
"license": "MIT",
"type": "module",
@ -21,7 +21,6 @@
"payload": "cross-env NODE_OPTIONS=--no-deprecation payload",
"migrate": "bun run src/scripts/run-migrations.ts",
"mcp:key": "bun run src/tools/cli/create-mcp-key.ts",
"garage:backfill": "bun run src/tools/cli/backfillGaragePlacement.ts",
"db": "cross-env NODE_OPTIONS=--no-deprecation pnpm drizzle-kit",
"start": "cross-env NODE_OPTIONS=--no-deprecation next start",
"staging": "cross-env NODE_ENV=test NODE_OPTIONS=--no-deprecation next start",

View file

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

View file

@ -1,10 +1,126 @@
import { redirect } from "next/navigation";
import config from "@payload-config";
import { getPayload } from "payload";
import type { GameVehicle, Vehicle } from "@/payload-types";
import { TruckIcon } from "lucide-react";
import Link from "next/link";
import {
Item,
ItemContent,
ItemDescription,
ItemHeader,
ItemMedia,
ItemTitle,
} from "@/components/ui/item";
/**
* D8: the Deployed Vehicles list was replaced by the Garage. The URL is kept
* alive so bookmarks and old links keep working; detail pages remain at
* /logistics/game-vehicles/[id].
*/
export default function GameVehiclesPage() {
redirect("/logistics/garage");
export const metadata = {
title: "Vehicles: Polaris Task Force",
};
export default async function GameVehiclesPage() {
const payload = await getPayload({ config });
const vehiclesRes = await payload.find({
collection: "game-vehicles",
limit: 500,
depth: 2,
});
const vehicles = vehiclesRes.docs as unknown as (GameVehicle & {
type: Vehicle;
})[];
const statusColors: Record<string, string> = {
idle: "bg-emerald-500/20 text-emerald-400",
assigned: "bg-blue-500/20 text-blue-400",
in_transit: "bg-amber-500/20 text-amber-400",
damaged: "bg-red-500/20 text-red-400",
destroyed: "bg-red-500/20 text-red-400",
};
return (
<div className="p-5 flex flex-col gap-6">
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2">
<TruckIcon className="size-5 text-muted-foreground" />
<h1 className="text-lg font-semibold">Vehicles</h1>
</div>
<p className="text-sm text-muted-foreground">
{vehicles.length} vehicle{vehicles.length !== 1 ? "s" : ""} deployed.
</p>
</div>
{vehicles.length > 0 ? (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
{vehicles.map((vehicle) => {
const vehicleType = typeof vehicle.type === "object" ? vehicle.type : null;
const fuelPercent = vehicleType?.fuel?.fuelCapacity
? (vehicle.currentFuel / vehicleType.fuel.fuelCapacity) * 100
: 0;
return (
<Link key={vehicle.id} href={`/logistics/game-vehicles/${vehicle.id}`}>
<Item
variant="outline"
className="cursor-pointer group transition-all duration-200 hover:scale-[1.01] hover:[box-shadow:inset_0_2px_8px_rgba(255,255,255,0.33)]"
>
<ItemHeader>
<div className="flex items-center gap-2">
<ItemMedia variant="icon">
<TruckIcon />
</ItemMedia>
<ItemTitle className="flex flex-col">
<span>{vehicle.name}</span>
<span className="text-xs font-normal text-muted-foreground">
{vehicleType?.name ?? "Unknown type"}
</span>
</ItemTitle>
</div>
<span
className={`text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded ${statusColors[vehicle.status] ?? "bg-muted text-muted-foreground"}`}
>
{vehicle.status === "in_transit"
? "In Transit"
: vehicle.status.charAt(0).toUpperCase() + vehicle.status.slice(1)}
</span>
</ItemHeader>
<ItemContent>
<div className="flex flex-col gap-2 w-full">
<div className="flex items-center gap-2">
<div className="flex-1 h-1.5 bg-border rounded-full overflow-hidden">
<div
className={`h-full rounded-full transition-all ${
fuelPercent > 20 ? "bg-green-500" : "bg-red-500"
}`}
style={{
width: `${Math.min(100, fuelPercent)}%`,
}}
/>
</div>
<span className="text-[10px] font-mono text-muted-foreground">
{vehicle.currentFuel?.toFixed(0)} /{" "}
{vehicleType?.fuel?.fuelCapacity ?? "?"} fuel
</span>
</div>
<div className="flex items-center justify-between text-xs text-muted-foreground">
<span>HP: {vehicle.currentHealth}</span>
{vehicleType?.fuel?.fuelType &&
typeof vehicleType.fuel.fuelType === "object" && (
<span>{vehicleType.fuel.fuelType.name}</span>
)}
</div>
</div>
</ItemContent>
<ItemDescription>{vehicleType?.name ?? "Unknown type"}</ItemDescription>
</Item>
</Link>
);
})}
</div>
) : (
<div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
<p className="text-sm">No vehicles deployed.</p>
</div>
)}
</div>
);
}

View file

@ -1,455 +0,0 @@
"use server";
import config from "@payload-config";
import { getPayload } from "payload";
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
import type { User } from "@/payload-types";
import { hasPermission } from "@/utils/access-control/hasPermission";
import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
import { canUserAccessStructureStorage } from "@/collections/game/GameStructures";
import { activeReservedVehicleIds } from "@/lib/operations/reservationOptions";
import {
autoArrangeGarageItems,
findGarageEmptySpot,
getGarageBayDimensions,
getVehicleFootprint,
isGaragePlacementValid,
parkedVehiclesToGridItems,
} from "@/lib/garage";
import {
enqueueGarageDispatch,
enqueueGarageStore,
garageInstanceLine,
} from "@/lib/arma-bridge/garages";
interface ActionResult<T = undefined> {
success: boolean;
error?: string;
data?: T;
}
async function authenticate() {
const payloadConfig = await config;
const payload = await getPayload({ config: payloadConfig });
const { headers } = await import("next/headers");
const hdrs = await headers();
const { user } = await payload.auth({
headers: hdrs,
canSetHeaders: false,
});
if (!isPayloadUser(user)) {
throw new Error("Unauthorized");
}
return { payload, user };
}
/**
* SECURITY (D6): all garage mutations require game-vehicles:update and are
* enforced HERE. Payload field-level access cannot see the parent structure's
* storageAccess gate and silently strips instead of rejecting, so placement
* fields stay open at the field level and every write path is this file.
*/
async function canEditGarage(
payload: Awaited<ReturnType<typeof getPayload>>,
user: User,
): Promise<boolean> {
return hasPermission(payload, user, "game-vehicles:update");
}
const FORBIDDEN =
"Insufficient permissions. Vehicle logistics personnel can manage the garage.";
async function loadVehicle(payload: Awaited<ReturnType<typeof getPayload>>, vehicleId: number) {
return payload.findByID({
collection: "game-vehicles",
id: vehicleId,
depth: 2,
overrideAccess: true,
});
}
/** Resolve a vehicle's current garage structure + bay, or an error message. */
function resolveBay(vehicle: Awaited<ReturnType<typeof loadVehicle>>): {
structureId: number;
structureName: string;
bay: { width: number; height: number };
} {
const structure =
vehicle.deployedAt && typeof vehicle.deployedAt === "object"
? (vehicle.deployedAt as { id: number; name: string; type?: unknown })
: null;
const blueprint =
structure && structure.type && typeof structure.type === "object"
? (structure.type as Record<string, unknown>)
: null;
const bay = getGarageBayDimensions(blueprint as never);
if (!structure || !bay) {
throw new Error("This vehicle is not parked at a structure with a vehicle bay.");
}
return { structureId: structure.id, structureName: structure.name, bay };
}
export async function moveGarageItem(
vehicleId: number,
gridX: number,
gridY: number,
rotated?: boolean,
): Promise<ActionResult> {
try {
const { payload, user } = await authenticate();
if (!(await canEditGarage(payload, user))) return { success: false, error: FORBIDDEN };
const vehicle = await loadVehicle(payload, vehicleId);
const { structureId, bay } = resolveBay(vehicle);
const template = typeof vehicle.type === "object" ? (vehicle.type as never) : null;
const nextRotated = rotated ?? Boolean(vehicle.garageRotated);
const fp = getVehicleFootprint(template, nextRotated);
const { docs } = await payload.find({
collection: "game-vehicles",
where: { deployedAt: { equals: structureId } },
depth: 1,
limit: 1000,
overrideAccess: true,
});
const items = parkedVehiclesToGridItems(docs as never);
if (
!isGaragePlacementValid(
items,
String(vehicle.id),
gridX,
gridY,
fp.width,
fp.height,
bay.width,
bay.height,
)
) {
return { success: false, error: "That spot is occupied or out of bounds." };
}
await payload.update({
collection: "game-vehicles",
id: vehicle.id,
data: { garageGridX: gridX, garageGridY: gridY, garageRotated: nextRotated },
overrideAccess: true,
depth: 0,
});
await emitGameEvent(payload, {
type: EventTypes.GarageMove,
message: `Moved vehicle "${vehicle.name}" to cell (${gridX}, ${gridY})`,
actor: user.id,
structure: structureId,
targetCollection: "game-vehicles",
targetId: vehicle.id,
data: { gridX, gridY, rotated: nextRotated },
});
return { success: true };
} catch (e) {
const message = e instanceof Error ? e.message : "Unknown error";
return {
success: false,
error: message === "Unauthorized" ? "You must be logged in." : message,
};
}
}
export async function rotateGarageItem(vehicleId: number): Promise<ActionResult> {
try {
const { payload, user } = await authenticate();
if (!(await canEditGarage(payload, user))) return { success: false, error: FORBIDDEN };
const vehicle = await loadVehicle(payload, vehicleId);
const { structureId, bay } = resolveBay(vehicle);
if (vehicle.garageGridX == null || vehicle.garageGridY == null) {
return { success: false, error: "This vehicle is not parked on a bay cell." };
}
const template = typeof vehicle.type === "object" ? (vehicle.type as never) : null;
const nextRotated = !vehicle.garageRotated;
const fp = getVehicleFootprint(template, nextRotated);
const { docs } = await payload.find({
collection: "game-vehicles",
where: { deployedAt: { equals: structureId } },
depth: 1,
limit: 1000,
overrideAccess: true,
});
const items = parkedVehiclesToGridItems(docs as never);
if (
!isGaragePlacementValid(
items,
String(vehicle.id),
vehicle.garageGridX,
vehicle.garageGridY,
fp.width,
fp.height,
bay.width,
bay.height,
)
) {
return { success: false, error: "No room to rotate here; move it first." };
}
await payload.update({
collection: "game-vehicles",
id: vehicle.id,
data: { garageRotated: nextRotated },
overrideAccess: true,
depth: 0,
});
await emitGameEvent(payload, {
type: EventTypes.GarageRotate,
message: `${nextRotated ? "Rotated" : "Straightened"} vehicle "${vehicle.name}"`,
actor: user.id,
structure: structureId,
targetCollection: "game-vehicles",
targetId: vehicle.id,
data: { rotated: nextRotated },
});
return { success: true };
} catch (e) {
const message = e instanceof Error ? e.message : "Unknown error";
return {
success: false,
error: message === "Unauthorized" ? "You must be logged in." : message,
};
}
}
export async function autoArrangeGarage(structureId: number): Promise<ActionResult> {
try {
const { payload, user } = await authenticate();
if (!(await canEditGarage(payload, user))) return { success: false, error: FORBIDDEN };
const structure = await payload.findByID({
collection: "game-structures",
id: structureId,
depth: 1,
overrideAccess: true,
});
const bay = getGarageBayDimensions(
typeof structure.type === "object" ? (structure.type as never) : null,
);
if (!bay) return { success: false, error: "This structure has no vehicle bay." };
const { docs } = await payload.find({
collection: "game-vehicles",
where: { deployedAt: { equals: structureId } },
depth: 1,
limit: 1000,
overrideAccess: true,
});
const items = parkedVehiclesToGridItems(docs as never);
if (items.length === 0) return { success: true };
const { placed, overflow } = autoArrangeGarageItems(items, bay.width, bay.height);
for (const p of placed) {
await payload.update({
collection: "game-vehicles",
id: Number(p.id),
data: { garageGridX: p.gridX, garageGridY: p.gridY },
overrideAccess: true,
depth: 0,
});
}
// Vehicles that no longer fit stay unplaced and surface in Elsewhere.
for (const id of overflow) {
await payload.update({
collection: "game-vehicles",
id: Number(id),
data: { garageGridX: null, garageGridY: null },
overrideAccess: true,
depth: 0,
});
}
await emitGameEvent(payload, {
type: EventTypes.GarageAutoArrange,
message: `Auto-arranged the vehicle bay at "${structure.name}" (${placed.length} placed, ${overflow.length} overflow)`,
actor: user.id,
structure: structureId,
targetCollection: "game-structures",
targetId: structureId,
data: { placed: placed.length, overflow: overflow.length },
});
return { success: true, data: undefined };
} catch (e) {
const message = e instanceof Error ? e.message : "Unknown error";
return {
success: false,
error: message === "Unauthorized" ? "You must be logged in." : message,
};
}
}
export async function dispatchVehicle(vehicleId: number): Promise<ActionResult> {
try {
const { payload, user } = await authenticate();
if (!(await canEditGarage(payload, user))) return { success: false, error: FORBIDDEN };
const vehicle = await loadVehicle(payload, vehicleId);
if (vehicle.status !== "idle") {
return {
success: false,
error:
vehicle.status === "destroyed"
? "Destroyed vehicles cannot be dispatched."
: "Only idle vehicles can be dispatched.",
};
}
const reserved = await activeReservedVehicleIds(payload);
if (reserved.has(vehicle.id)) {
return {
success: false,
error: "This vehicle is reserved for an operation; release the reservation first.",
};
}
const structure =
vehicle.deployedAt && typeof vehicle.deployedAt === "object"
? (vehicle.deployedAt as { id: number; name: string; storageSlug?: string | null })
: null;
const template = typeof vehicle.type === "object" ? (vehicle.type as never) : null;
const line = garageInstanceLine(vehicle as never, template);
const slug = structure?.storageSlug?.trim();
await payload.update({
collection: "game-vehicles",
id: vehicle.id,
data: {
status: "in_transit",
garageGridX: null,
garageGridY: null,
garageRotated: false,
deployedAt: null,
},
overrideAccess: true,
depth: 0,
});
// Fire-and-forget per the contract: web state is already committed.
if (line && slug) {
try {
await enqueueGarageDispatch(payload, slug, line);
} catch {
/* command enqueue failures never roll back the dispatch */
}
}
await emitGameEvent(payload, {
type: EventTypes.GarageDispatch,
message: `Dispatched vehicle "${vehicle.name}"${structure ? ` from "${structure.name}"` : ""}`,
actor: user.id,
...(structure ? { structure: structure.id } : {}),
targetCollection: "game-vehicles",
targetId: vehicle.id,
data: { fromStructure: structure?.name ?? null },
});
return { success: true };
} catch (e) {
const message = e instanceof Error ? e.message : "Unknown error";
return {
success: false,
error: message === "Unauthorized" ? "You must be logged in." : message,
};
}
}
export async function storeVehicle(
vehicleId: number,
targetStructureId: number,
): Promise<ActionResult> {
try {
const { payload, user } = await authenticate();
if (!(await canEditGarage(payload, user))) return { success: false, error: FORBIDDEN };
const vehicle = await loadVehicle(payload, vehicleId);
if (vehicle.status === "destroyed") {
return { success: false, error: "Destroyed vehicles cannot be stored." };
}
const target = await payload.findByID({
collection: "game-structures",
id: targetStructureId,
depth: 1,
overrideAccess: true,
});
// D5: the target's storageAccess gate applies to storing, same knob as
// item storage.
if (!(await canUserAccessStructureStorage(payload, user, target as unknown as Record<string, unknown>))) {
return { success: false, error: "You do not have access to this structure's storage." };
}
const bay = getGarageBayDimensions(
typeof target.type === "object" ? (target.type as never) : null,
);
if (!bay) return { success: false, error: "That structure has no vehicle bay." };
const { docs } = await payload.find({
collection: "game-vehicles",
where: { deployedAt: { equals: targetStructureId } },
depth: 1,
limit: 1000,
overrideAccess: true,
});
const items = parkedVehiclesToGridItems(docs as never);
const template = typeof vehicle.type === "object" ? (vehicle.type as never) : null;
const fp = getVehicleFootprint(template, false);
const spot = findGarageEmptySpot(items, fp.width, fp.height, bay.width, bay.height);
if (!spot) {
return { success: false, error: `No free bay space at "${target.name}".` };
}
const line = garageInstanceLine(vehicle as never, template);
const slug = target.storageSlug?.trim();
await payload.update({
collection: "game-vehicles",
id: vehicle.id,
data: {
// D7: storing parks the vehicle. Destroyed instances are rejected
// above (A4), so a stored vehicle always returns to idle.
status: "idle",
deployedAt: targetStructureId,
garageGridX: spot.x,
garageGridY: spot.y,
garageRotated: false,
},
overrideAccess: true,
depth: 0,
});
if (line && slug) {
try {
await enqueueGarageStore(payload, slug, line);
} catch {
/* command enqueue failures never roll back the store */
}
}
await emitGameEvent(payload, {
type: EventTypes.GarageStore,
message: `Stored vehicle "${vehicle.name}" in "${target.name}"`,
actor: user.id,
structure: targetStructureId,
targetCollection: "game-vehicles",
targetId: vehicle.id,
data: { cell: `${spot.x},${spot.y}` },
});
return { success: true };
} catch (e) {
const message = e instanceof Error ? e.message : "Unknown error";
return {
success: false,
error: message === "Unauthorized" ? "You must be logged in." : message,
};
}
}

View file

@ -1,196 +0,0 @@
import type { GameStructure, GameVehicle } from "@/payload-types";
import type { Metadata } from "next";
import { getPayload } from "payload";
import config from "@payload-config";
import { headers as nextHeaders } from "next/headers";
import { redirect } from "next/navigation";
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
import { hasPermission } from "@/utils/access-control/hasPermission";
import { hasLogisticsQualification } from "@/utils/access-control/hasLogisticsQualification";
import { listReservationOptions, reservedVehiclesByOperation } from "@/lib/operations/reservationOptions";
import { canUserAccessStructureStorage } from "@/collections/game/GameStructures";
import { getGarageBayDimensions } from "@/lib/garage";
import { GarageView, type ElsewhereGroup, type GarageSectionData } from "@/components/frontend/garage/GarageView";
import type { GarageVehicleItem } from "@/components/frontend/garage/GarageGrid";
export const metadata: Metadata = {
title: "Garage",
};
/**
* Garage (D8): replaces the old "Deployed Vehicles" list. Server component:
* resolves visible garage-bearing structures (blueprint bay + storageAccess),
* partitions vehicle instances into grid items vs. "Elsewhere" groups, and
* hands everything to the client GarageView.
*/
function pct(current: number | null | undefined, max: number | null | undefined): number | null {
if (current == null || max == null || max <= 0) return null;
return Math.max(0, Math.min(100, Math.round((current / max) * 100)));
}
export default async function GaragePage() {
const payload = await getPayload({ config });
const { user: authUser } = await payload.auth({
headers: await nextHeaders(),
canSetHeaders: false,
});
const user = isPayloadUser(authUser) ? authUser : null;
if (!user) redirect("/login");
const [structuresRes, vehiclesRes, reservedMap] = await Promise.all([
payload.find({ collection: "game-structures", depth: 1, limit: 1000 }),
payload.find({ collection: "game-vehicles", depth: 2, limit: 1000 }),
reservedVehiclesByOperation(payload),
]);
// Structures with a blueprint vehicle bay that the viewer may access (D5).
const garages: GameStructure[] = [];
for (const structure of structuresRes.docs) {
const blueprint = typeof structure.type === "object" ? structure.type : null;
if (!getGarageBayDimensions(blueprint)) continue;
if (!(await canUserAccessStructureStorage(payload, user, structure as unknown as Record<string, unknown>))) continue;
garages.push(structure);
}
const visibleIds = new Set(garages.map((s) => s.id));
const canEdit = await hasPermission(payload, user, "game-vehicles:update");
const toGridItem = (vehicle: GameVehicle): GarageVehicleItem | null => {
const template = typeof vehicle.type === "object" ? vehicle.type : null;
if (
vehicle.garageGridX == null ||
vehicle.garageGridY == null ||
!template ||
template.id == null
) {
return null;
}
const image = template.image && typeof template.image === "object" ? template.image : null;
return {
id: vehicle.id,
name: vehicle.name ?? template.name ?? "Unnamed vehicle",
status: vehicle.status,
gridX: vehicle.garageGridX,
gridY: vehicle.garageGridY,
rotated: Boolean(vehicle.garageRotated),
width: template.garageWidth ?? 1,
height: template.garageHeight ?? 1,
thumbnailUrl: image?.url ?? null,
fuelPct: pct(vehicle.currentFuel, template.fuel?.fuelCapacity),
healthPct: pct(vehicle.currentHealth, template.maxHealth),
reservedFor: reservedMap.get(vehicle.id) ?? null,
};
};
const sections: GarageSectionData[] = garages.map((structure) => {
const bay = getGarageBayDimensions(
typeof structure.type === "object" ? structure.type : null,
)!;
return {
structureId: structure.id,
structureName: structure.name ?? `Structure ${structure.id}`,
bayWidth: bay.width,
bayHeight: bay.height,
vehicles: [],
};
});
const sectionByStructure = new Map(sections.map((s) => [s.structureId, s]));
const onGrid = new Set<number>();
for (const vehicle of vehiclesRes.docs) {
const structureId =
vehicle.deployedAt && typeof vehicle.deployedAt === "object"
? vehicle.deployedAt.id
: vehicle.deployedAt;
if (structureId == null || !visibleIds.has(Number(structureId))) continue;
const item = toGridItem(vehicle);
if (!item) continue;
sectionByStructure.get(Number(structureId))?.vehicles.push(item);
onGrid.add(vehicle.id);
}
// Elsewhere (D9): everything not rendered on a grid. Vehicles parked at
// garages this viewer cannot access stay hidden entirely (access control).
const elsewhereVehicles = vehiclesRes.docs.filter((vehicle) => {
if (onGrid.has(vehicle.id)) return false;
const structureId =
vehicle.deployedAt && typeof vehicle.deployedAt === "object"
? vehicle.deployedAt.id
: vehicle.deployedAt;
if (structureId != null && !visibleIds.has(Number(structureId))) {
const hidden = structuresRes.docs.find((s) => s.id === Number(structureId));
const blueprint = hidden && typeof hidden.type === "object" ? hidden.type : null;
if (getGarageBayDimensions(blueprint)) return false;
}
return true;
});
const toElsewhere = (vehicle: GameVehicle) => ({
id: vehicle.id,
name: vehicle.name ?? "Unnamed vehicle",
status: vehicle.status,
locationName:
vehicle.deployedAt && typeof vehicle.deployedAt === "object"
? (vehicle.deployedAt.name ?? null)
: null,
reservedFor: reservedMap.get(vehicle.id) ?? null,
});
const elsewhere: ElsewhereGroup[] = [
{
key: "transit",
label: "In transit",
hint: "dispatched, awaiting game-side arrival",
vehicles: elsewhereVehicles.filter((v) => v.status === "in_transit").map(toElsewhere),
},
{
key: "wrecks",
label: "Wrecks & damaged",
hint: "off-grid casualties",
vehicles: elsewhereVehicles
.filter((v) => v.status === "destroyed" || v.status === "damaged")
.map(toElsewhere),
},
{
key: "unplaced",
label: "Unplaced",
hint: "idle or assigned without a bay cell",
vehicles: elsewhereVehicles
.filter((v) => v.status !== "in_transit" && v.status !== "destroyed" && v.status !== "damaged")
.map(toElsewhere),
},
];
const canCreateReservation = await hasPermission(payload, user, "operation-reservations:create");
const canManageLogistics = await hasLogisticsQualification(payload, user);
const options = canCreateReservation ? await listReservationOptions(payload, user) : null;
return (
<div className="p-5 flex flex-col gap-6">
<div className="flex flex-col gap-1">
<h1 className="text-2xl font-semibold tracking-tight">Garage</h1>
<p className="text-sm text-muted-foreground">
Vehicle bays across all accessible structures. Drag to rearrange parked
instances; use Dispatch and Store for real movement.
</p>
</div>
<GarageView
garages={sections}
elsewhere={elsewhere}
canEdit={canEdit}
storeTargets={garages.map((s) => ({ id: s.id, name: s.name ?? `Structure ${s.id}` }))}
reservation={
options
? {
canCreate: canCreateReservation,
options,
canManageLogistics,
currentUserId: user.id,
}
: null
}
/>
</div>
);
}

View file

@ -34,7 +34,6 @@ import { default as default_701da9bef3b3cc3d8567adf41fa08aa3 } from '@/component
import { default as default_4b88a624e9f0b376cffcc6814d459adb } from '@/components/admin/assignments/AssignmentMembersField'
import { default as default_0edde40a6ccd30c893b1227360f69360 } from '@/components/static/TickDurationDescription'
import { default as default_2d468cc5cf0b647ffca3201592c20825 } from '@/components/static/WarningMessage'
import { default as default_8e873aa39584420378774e6c9c4ac54b } from '@/components/admin/VehicleLibraryPicker'
import { AudioPreviewField as AudioPreviewField_6bccef9bf4ea41ed573ab9f36fa579b2 } from '@/components/admin/voiceover/AudioPreviewField'
import { default as default_7fa52484aec46e988e9cfb5e86c0c759 } from '@/components/admin/narrative-flow/NarrativeFlowEditor'
import { default as default_b7f86fb8e028bca592f57e6d387a0380 } from '@/components/admin/minigames/PeriodCloseControl'
@ -90,7 +89,6 @@ export const importMap = {
"@/components/admin/assignments/AssignmentMembersField#default": default_4b88a624e9f0b376cffcc6814d459adb,
"@/components/static/TickDurationDescription#default": default_0edde40a6ccd30c893b1227360f69360,
"@/components/static/WarningMessage#default": default_2d468cc5cf0b647ffca3201592c20825,
"@/components/admin/VehicleLibraryPicker#default": default_8e873aa39584420378774e6c9c4ac54b,
"@/components/admin/voiceover/AudioPreviewField#AudioPreviewField": AudioPreviewField_6bccef9bf4ea41ed573ab9f36fa579b2,
"@/components/admin/narrative-flow/NarrativeFlowEditor#default": default_7fa52484aec46e988e9cfb5e86c0c759,
"@/components/admin/minigames/PeriodCloseControl#default": default_b7f86fb8e028bca592f57e6d387a0380,

View file

@ -18,17 +18,23 @@ function relId(value: unknown): number | null {
}
/**
* Request-independent core of the structure storage gate. Field-level access
* (below) and server actions / pages that must evaluate the same rule without
* a PayloadRequest (e.g. the Garage view) both call this.
* Field-level gate for storedAssets (web UI only — bridge sync writes use
* overrideAccess and are unaffected). Admins with game-structures:update
* always pass; otherwise the structure's storageAccess mode decides:
* anyone / specific roles (matched against the user's roleDocs) / specific
* users. A "faction" mode is deliberately not offered yet: members have no
* faction linkage in the users/profiles model, so it could not be evaluated.
*/
export async function canUserAccessStructureStorage(
payload: Parameters<typeof hasPermission>[0],
user: { id: number | string; roleDocs?: unknown } | null | undefined,
doc?: Record<string, unknown> | null,
): Promise<boolean> {
async function canAccessStructureStorage({
req,
doc,
}: {
req: PayloadRequest;
doc?: Record<string, unknown> | null;
}): Promise<boolean> {
const user = req.user;
if (!user) return false;
if (await hasPermission(payload, user, "game-structures:update")) return true;
if (await hasPermission(req.payload, user, "game-structures:update")) return true;
const access = (doc?.storageAccess ?? undefined) as
| { mode?: string; roles?: unknown; users?: unknown }
| undefined;
@ -48,29 +54,11 @@ export async function canUserAccessStructureStorage(
}
if (mode === "users") {
const allowed = (Array.isArray(access?.users) ? (access.users as unknown[]) : []).map(relId);
return allowed.some((id) => id != null && String(id) === String(user.id));
return allowed.includes(user.id);
}
return false;
}
/**
* Field-level gate for storedAssets (web UI only; bridge sync writes use
* overrideAccess and are unaffected). Admins with game-structures:update
* always pass; otherwise the structure's storageAccess mode decides:
* anyone / specific roles (matched against the user's roleDocs) / specific
* users. A "faction" mode is deliberately not offered yet: members have no
* faction linkage in the users/profiles model, so it could not be evaluated.
*/
async function canAccessStructureStorage({
req,
doc,
}: {
req: PayloadRequest;
doc?: Record<string, unknown> | null;
}): Promise<boolean> {
return canUserAccessStructureStorage(req.payload, req.user, doc);
}
export const GameStructures: CollectionConfig = {
slug: "game-structures",
admin: {

View file

@ -39,42 +39,6 @@ export const GameVehicles: CollectionConfig = {
description: "The structure where this vehicle is currently stationed. Null if in transit.",
},
},
{
name: "garageGridX",
type: "number",
min: 0,
admin: {
description:
"Column position in the deployed structure's Garage vehicle bay (0-indexed). Null = not parked in a bay cell.",
},
},
{
name: "garageGridY",
type: "number",
min: 0,
admin: {
description:
"Row position in the deployed structure's Garage vehicle bay (0-indexed). Null = not parked in a bay cell.",
},
},
{
name: "garageRotated",
type: "checkbox",
defaultValue: false,
admin: {
description: "Whether this vehicle is rotated 90 degrees in the garage bay (swaps width and height).",
},
},
{
name: "bridgeUid",
type: "text",
unique: true,
index: true,
admin: {
description:
"Per-instance identity assigned by the Arma bridge (docs/arma-bridge/garage-sync.md). Two identical vehicles are told apart by this tag. Null = never seen by the game.",
},
},
{
name: "faction",
type: "relationship",

View file

@ -671,30 +671,6 @@ export const Structures: CollectionConfig = {
},
],
},
{
// Named group on purpose: an unnamed group would flatten its
// xSize/ySize onto the document and collide with the top-level
// storage slot dimensions above.
name: "vehicleBay",
label: "Vehicle Bay Dimensions",
type: "group",
admin: {
description:
"Grid capacity for the Garage view. Structures whose blueprint defines a bay with both dimensions greater than zero expose a garage grid holding parked vehicle instances. Empty = no vehicle storage.",
},
fields: [
{
name: "xSize",
type: "number",
label: "Columns (X)",
},
{
name: "ySize",
type: "number",
label: "Rows (Y)",
},
],
},
{
name: "allowedStorage",
type: "array",

View file

@ -19,17 +19,6 @@ export const Vehicles: CollectionConfig = {
delete: requireLogisticsPermission("vehicles:delete"),
},
fields: [
{
// D11b: searchable imported-library picker (name, classname, thumbnail)
// that copies an imported entry into this form on click.
name: "libraryPicker",
type: "ui",
admin: {
components: {
Field: "@/components/admin/VehicleLibraryPicker",
},
},
},
{
label: "Identity",
type: "group",
@ -284,28 +273,6 @@ export const Vehicles: CollectionConfig = {
},
],
},
{
label: "Garage Footprint",
type: "group",
admin: {
description:
"Cells this vehicle's type occupies in a structure's Garage vehicle bay (width = columns, height = rows). Unset defaults to 1x1. Independent of the display-only storage grid dimensions above.",
},
fields: [
{
name: "garageWidth",
type: "number",
label: "Garage Width (cells)",
min: 1,
},
{
name: "garageHeight",
type: "number",
label: "Garage Height (cells)",
min: 1,
},
],
},
{
label: "Cargo Capacity",
type: "group",

View file

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

View file

@ -1,135 +0,0 @@
"use client";
import { useEffect, useState } from "react";
import { SearchIcon, TruckIcon } from "lucide-react";
import { toast, useField } from "@payloadcms/ui";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
/**
* Imported library picker for vehicle templates (D11b). Searches the vehicles
* collection (the rows importArmaLibrary maintains) by display name or
* classname with thumbnails, and copies the chosen entry's name + classname
* into the open document so officers never hand-type classnames. Applies only
* on explicit click; nothing is written automatically.
*/
interface LibraryEntry {
id: number;
name?: string | null;
classname?: string | null;
transportMode?: string | null;
image?: { id?: number; url?: string | null } | string | number | null;
}
export function VehicleLibraryPicker() {
const nameField = useField<string>({ path: "name" });
const classnameField = useField<string>({ path: "classname" });
const imageField = useField<unknown>({ path: "image" });
const [query, setQuery] = useState("");
const [results, setResults] = useState<LibraryEntry[]>([]);
const [searching, setSearching] = useState(false);
useEffect(() => {
const q = query.trim();
if (q.length < 2) {
setResults([]);
return;
}
let cancelled = false;
setSearching(true);
const where = encodeURIComponent(
JSON.stringify({ or: [{ name: { like: q } }, { classname: { like: q } }] }),
);
const timer = setTimeout(async () => {
try {
const res = await fetch(`/api/vehicles?where=${where}&limit=12&depth=1`, {
credentials: "include",
});
const json = (await res.json()) as { docs?: LibraryEntry[] };
if (!cancelled) setResults(Array.isArray(json.docs) ? json.docs : []);
} catch {
if (!cancelled) setResults([]);
} finally {
if (!cancelled) setSearching(false);
}
}, 250);
return () => {
cancelled = true;
clearTimeout(timer);
};
}, [query]);
function apply(entry: LibraryEntry) {
nameField.setValue(entry.name ?? "");
classnameField.setValue(entry.classname ?? "");
// Fill the thumbnail only when this template has none yet.
if (imageField.value == null && entry.image != null && entry.image !== "") {
const mediaId =
typeof entry.image === "object" ? entry.image.id : Number(entry.image);
if (mediaId != null && Number.isFinite(Number(mediaId))) {
imageField.setValue(Number(mediaId));
}
}
toast.success(`Loaded ${entry.name || entry.classname} into this template.`);
}
return (
<div className="border border-border rounded-lg p-4 flex flex-col gap-3">
<div className="flex items-center justify-between gap-2">
<h3 className="text-sm font-semibold">Imported library</h3>
<span className="text-xs text-[var(--theme-elevation-500)]">
Search imported Arma vehicle templates and copy them into this form
</span>
</div>
<div className="relative">
<SearchIcon className="size-4 absolute left-2.5 top-1/2 -translate-y-1/2 text-[var(--theme-elevation-500)]" />
<Input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search by name or classname (2+ characters)..."
className="pl-8"
/>
</div>
{searching && <p className="text-xs text-[var(--theme-elevation-500)]">Searching...</p>}
{!searching && query.trim().length >= 2 && results.length === 0 && (
<p className="text-xs text-[var(--theme-elevation-500)]">
Nothing found. Run the catalog import to add it first.
</p>
)}
{results.length > 0 && (
<ul className="max-h-64 overflow-auto divide-y divide-[var(--theme-border-color)] border border-[var(--theme-border-color)] rounded-md">
{results.map((entry) => {
const image = entry.image && typeof entry.image === "object" ? entry.image : null;
return (
<li key={entry.id} className="flex items-center gap-3 px-3 py-2">
{image?.url ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={image.url}
alt=""
className="size-10 rounded object-contain bg-[var(--theme-elevation-100)] shrink-0"
/>
) : (
<TruckIcon className="size-5 shrink-0 text-[var(--theme-elevation-500)]" />
)}
<div className="min-w-0 flex-1">
<div className="truncate text-sm">{entry.name || "(unnamed)"}</div>
<div className="truncate font-mono text-xs text-[var(--theme-elevation-500)]">
{entry.classname}
{entry.transportMode ? ` · ${entry.transportMode}` : ""}
</div>
</div>
<Button type="button" size="sm" variant="outline" onClick={() => apply(entry)}>
Use
</Button>
</li>
);
})}
</ul>
)}
</div>
);
}
export default VehicleLibraryPicker;

View file

@ -218,11 +218,11 @@ export const navigationCommands: NavigationCommand[] = [
shortcut: "G T",
},
{
id: "nav:garage",
label: "Garage",
id: "nav:deployed-vehicles",
label: "Deployed Vehicles",
icon: Map,
href: "/logistics/garage",
keywords: ["vehicle", "bay", "parked", "fleet"],
href: "/logistics/game-vehicles",
keywords: ["active", "field"],
requires: "logistics",
},
{

View file

@ -129,8 +129,8 @@ export const sidebarData = {
icon: Package,
},
{
title: "Garage",
url: "/logistics/garage",
title: "Deployed Vehicles",
url: "/logistics/game-vehicles",
icon: Car,
},
{

View file

@ -1,467 +0,0 @@
"use client";
import { type CSSProperties, useEffect, useMemo, useRef, useState } from "react";
import {
DndContext,
type DragEndEvent,
type DragMoveEvent,
type DragStartEvent,
DragOverlay,
PointerSensor,
useSensor,
useSensors,
} from "@dnd-kit/core";
import { CSS } from "@dnd-kit/utilities";
import { useDraggable } from "@dnd-kit/core";
import { ShieldAlert, Truck as TruckIcon } from "lucide-react";
import { GridCell } from "@/components/frontend/storage/GridCell";
import { cn } from "@/lib/utils";
/**
* Garage vehicle bay grid. Modeled on storage/InventoryGrid and
* locker/LockerGrid (dnd-kit, hover cell preview, R-to-rotate), but items are
* vehicle instances with per-template footprints. Dragging ONLY rearranges
* cells (server action moveGarageItem); real game movement is the explicit
* Dispatch/Store actions in GarageView. Dense data UI: plain shadcn + site
* dark theme, no dossier styling (D12).
*/
export interface GarageVehicleItem {
/** game-vehicles instance id. */
id: number;
name: string;
status: "idle" | "assigned" | "in_transit" | "damaged" | "destroyed";
gridX: number;
gridY: number;
rotated: boolean;
/** Template footprint at rotation 0. */
width: number;
height: number;
thumbnailUrl: string | null;
fuelPct: number | null;
healthPct: number | null;
/** Operation label when actively reserved ("Reserved for op X" badge). */
reservedFor?: string | null;
}
function footprint(item: { width: number; height: number; rotated: boolean }) {
return item.rotated
? { width: item.height, height: item.width }
: { width: item.width, height: item.height };
}
function cellsOf(x: number, y: number, w: number, h: number): string[] {
const cells: string[] = [];
for (let dx = 0; dx < w; dx++) {
for (let dy = 0; dy < h; dy++) {
cells.push(`${x + dx},${y + dy}`);
}
}
return cells;
}
function isPlacementValid(
items: GarageVehicleItem[],
excludeId: number,
x: number,
y: number,
w: number,
h: number,
gridWidth: number,
gridHeight: number,
): boolean {
if (x < 0 || y < 0 || x + w > gridWidth || y + h > gridHeight) return false;
const target = new Set(cellsOf(x, y, w, h));
for (const item of items) {
if (item.id === excludeId) continue;
const fp = footprint(item);
for (const cell of cellsOf(item.gridX, item.gridY, fp.width, fp.height)) {
if (target.has(cell)) return false;
}
}
return true;
}
/** Status tinting for the vehicle face (A4: destroyed stays visible, tinted). */
function statusTint(status: GarageVehicleItem["status"]): string | null {
switch (status) {
case "destroyed":
return "bg-red-500/40";
case "damaged":
return "bg-amber-500/30";
case "in_transit":
return "bg-sky-500/20";
default:
return null;
}
}
export function VehicleFace({
item,
cellSize,
dragging,
}: {
item: GarageVehicleItem;
cellSize: number;
dragging?: boolean;
}) {
const fp = footprint(item);
const cardW = fp.width * cellSize - 2;
const cardH = fp.height * cellSize - 2;
// Thumbnail caps are applied PRE-rotation, so for rotated cards the long
// edge must be capped by the card's HEIGHT (it becomes vertical after the
// 90deg turn) and vice versa. Pixel math, since % would resolve against
// the wrong axis of the already-rotated card. The rotated image is taken
// out of flow and anchored to the card centre so the 90deg turn happens
// around the card's middle (an in-flow image would rotate around its own
// top-biased box and clip against the card edge).
const thumbStyle: CSSProperties = item.rotated
? {
position: "absolute",
left: "50%",
top: "50%",
width: Math.floor(cardH * 0.85),
height: Math.floor(cardW * 0.85),
objectFit: "contain",
transform: "translate(-50%, -50%) rotate(90deg)",
}
: {
maxWidth: Math.floor(cardW * 0.85),
maxHeight: Math.floor(cardH * 0.55),
};
return (
<div
className={cn(
"relative flex h-full w-full flex-col items-center justify-center gap-0.5 overflow-hidden rounded-md border p-1 text-center transition-shadow",
"border-border/70 bg-muted/40",
item.status === "destroyed" && "border-red-500/50 grayscale",
item.status === "damaged" && "border-amber-500/50",
item.reservedFor && "ring-1 ring-sky-400/60",
dragging && "shadow-lg",
)}
style={{ width: cardW, height: cardH }}
title={
item.reservedFor ? `${item.name} (reserved for ${item.reservedFor})` : item.name
}
>
{item.thumbnailUrl ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={item.thumbnailUrl}
alt=""
className="pointer-events-none object-contain opacity-85"
style={thumbStyle}
/>
) : (
<TruckIcon className="size-5 opacity-70" />
)}
<span className="line-clamp-2 text-[9px] leading-tight text-foreground/90">
{item.name}
</span>
{statusTint(item.status) && (
<span
aria-hidden="true"
className={cn("pointer-events-none absolute inset-0", statusTint(item.status))}
/>
)}
{item.status === "destroyed" && (
<ShieldAlert className="absolute right-0.5 top-0.5 size-3 text-red-400" aria-label="Destroyed" />
)}
{item.reservedFor ? (
<span className="absolute left-0.5 top-0.5 rounded-sm bg-sky-500/90 px-1 font-mono text-[8px] font-semibold uppercase tracking-wide text-white">
OP
</span>
) : null}
</div>
);
}
function DraggableVehicle({
item,
cellSize,
selected,
onSelect,
}: {
item: GarageVehicleItem;
cellSize: number;
selected: boolean;
onSelect: (item: GarageVehicleItem) => void;
}) {
const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({
id: `garage-item-${item.id}`,
data: { item },
});
const didDrag = useRef(false);
useEffect(() => {
if (isDragging) didDrag.current = true;
}, [isDragging]);
const fp = footprint(item);
return (
<button
ref={setNodeRef}
type="button"
{...listeners}
{...attributes}
onClick={() => {
if (!didDrag.current) onSelect(item);
didDrag.current = false;
}}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
onSelect(item);
}
}}
className={cn(
"absolute cursor-grab rounded-md transition-[left,top] duration-150 ease-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",
selected && "ring-2 ring-primary",
)}
style={{
left: item.gridX * cellSize,
top: item.gridY * cellSize,
width: fp.width * cellSize - 2,
height: fp.height * cellSize - 2,
zIndex: 10,
transform: CSS.Translate.toString(transform),
opacity: isDragging ? 0 : 1,
}}
aria-label={`${item.name}, ${item.status}`}
>
<VehicleFace item={item} cellSize={cellSize} />
</button>
);
}
interface GarageGridProps {
gridWidth: number;
gridHeight: number;
items: GarageVehicleItem[];
canEdit: boolean;
onMoveItem: (
vehicleId: number,
gridX: number,
gridY: number,
rotated?: boolean,
) => Promise<void>;
onSelectItem: (item: GarageVehicleItem | null) => void;
selectedItem: GarageVehicleItem | null;
}
export function GarageGrid({
gridWidth,
gridHeight,
items,
canEdit,
onMoveItem,
onSelectItem,
selectedItem,
}: GarageGridProps) {
const [activeItem, setActiveItem] = useState<GarageVehicleItem | null>(null);
const [hoverPosition, setHoverPosition] = useState<{ x: number; y: number } | null>(null);
const [pendingRotated, setPendingRotated] = useState(false);
const [cellSize, setCellSize] = useState(64);
const gridRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
// Chrome between the measured wrapper and the grid: the inventory frame's
// p-2 padding (8+8) plus its 1px borders (1+1).
const FRAME_CHROME_PX = 18;
// Responsive cell size: always fit the bay width into the container (the
// grid must never overflow, so no scrollbar can appear). The small floor is
// a legibility guard only; realistic containers never reach it.
useEffect(() => {
const el = containerRef.current;
if (!el) return;
const observer = new ResizeObserver((entries) => {
const width = entries[0]?.contentRect.width ?? 0;
if (width > FRAME_CHROME_PX) {
setCellSize(
Math.max(24, Math.min(96, Math.floor((width - FRAME_CHROME_PX) / gridWidth))),
);
}
});
observer.observe(el);
return () => observer.disconnect();
}, [gridWidth]);
// R rotates the dragged vehicle while dragging (same gesture as locker).
useEffect(() => {
if (!activeItem) return;
const handler = (e: KeyboardEvent) => {
if (e.key === "r" || e.key === "R") {
e.preventDefault();
setPendingRotated((prev) => !prev);
}
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [activeItem]);
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }));
const occupiedCells = useMemo(() => {
const set = new Set<string>();
for (const item of items) {
const fp = footprint(item);
for (const cell of cellsOf(item.gridX, item.gridY, fp.width, fp.height)) {
set.add(cell);
}
}
return set;
}, [items]);
const hoverInfo = useMemo(() => {
if (!activeItem || !hoverPosition) return null;
const w = pendingRotated ? activeItem.height : activeItem.width;
const h = pendingRotated ? activeItem.width : activeItem.height;
const valid = isPlacementValid(
items,
activeItem.id,
hoverPosition.x,
hoverPosition.y,
w,
h,
gridWidth,
gridHeight,
);
return { cells: new Set(cellsOf(hoverPosition.x, hoverPosition.y, w, h)), valid };
}, [activeItem, hoverPosition, pendingRotated, items, gridWidth, gridHeight]);
const handleDragStart = (event: DragStartEvent) => {
const item = event.active.data.current?.item as GarageVehicleItem | undefined;
if (!item) return;
setActiveItem(item);
setPendingRotated(item.rotated ?? false);
setHoverPosition(null);
};
const handleDragMove = (event: DragMoveEvent) => {
if (!activeItem) return;
const dx = Math.round(event.delta.x / cellSize);
const dy = Math.round(event.delta.y / cellSize);
const x = activeItem.gridX + dx;
const y = activeItem.gridY + dy;
const w = pendingRotated ? activeItem.height : activeItem.width;
const h = pendingRotated ? activeItem.width : activeItem.height;
if (x < 0 || y < 0 || x + w > gridWidth || y + h > gridHeight) {
setHoverPosition(null);
return;
}
setHoverPosition({ x, y });
};
const handleDragEnd = (event: DragEndEvent) => {
const item = activeItem;
setActiveItem(null);
setHoverPosition(null);
if (!item || !canEdit) return;
// Derive the target cell from the drag translation (pointer-anchored math
// like InventoryGrid: original cell + rounded delta).
const dx = Math.round(event.delta.x / cellSize);
const dy = Math.round(event.delta.y / cellSize);
const targetX = item.gridX + dx;
const targetY = item.gridY + dy;
if (dx === 0 && dy === 0) {
if (pendingRotated === item.rotated) return;
void onMoveItem(item.id, item.gridX, item.gridY, pendingRotated);
return;
}
const w = pendingRotated ? item.height : item.width;
const h = pendingRotated ? item.width : item.height;
if (
isPlacementValid(items, item.id, targetX, targetY, w, h, gridWidth, gridHeight)
) {
void onMoveItem(item.id, targetX, targetY, pendingRotated);
}
};
// Drag preview must track mid-drag rotation: dnd-kit pins the overlay
// container to the activator rect captured at drag start, so we override
// its width/height via the style prop (spread after the pinned rect).
const overlayFp = activeItem
? {
width: pendingRotated ? activeItem.height : activeItem.width,
height: pendingRotated ? activeItem.width : activeItem.height,
}
: null;
return (
<DndContext
sensors={sensors}
onDragStart={handleDragStart}
onDragMove={handleDragMove}
onDragEnd={handleDragEnd}
>
<div className="flex flex-col gap-2">
<div ref={containerRef} className="min-w-0 max-w-full overflow-hidden">
<div
className="inventory-frame relative rounded border border-border bg-card/80 p-2 shadow-sm"
role="region"
aria-label="Garage vehicle bay"
tabIndex={0}
>
<div
ref={gridRef}
className="relative grid bg-background/10"
style={{
gridTemplateColumns: `repeat(${gridWidth}, ${cellSize}px)`,
gridTemplateRows: `repeat(${gridHeight}, ${cellSize}px)`,
}}
>
{Array.from({ length: gridHeight }).map((_, y) =>
Array.from({ length: gridWidth }).map((__, x) => {
const key = `${x},${y}`;
return (
<GridCell
key={key}
x={x}
y={y}
cellSize={cellSize}
isOccupied={occupiedCells.has(key)}
isDropTarget={!!activeItem}
isHovered={hoverInfo !== null && hoverInfo.cells.has(key)}
isInvalidDrop={hoverInfo !== null && !hoverInfo.valid}
/>
);
}),
)}
{items.map((item) => (
<DraggableVehicle
key={item.id}
item={item}
cellSize={cellSize}
selected={selectedItem?.id === item.id}
onSelect={onSelectItem}
/>
))}
</div>
</div>
</div>
<div className="metadata-strip flex items-center gap-4 font-mono text-[10px] uppercase tracking-wider text-muted-foreground">
<span>{items.length} parked</span>
<span>
bay {gridWidth} &times; {gridHeight}
</span>
{canEdit && <span className="ml-auto normal-case">drag to move &middot; R to rotate</span>}
</div>
</div>
<DragOverlay
dropAnimation={null}
style={
overlayFp
? { width: overlayFp.width * cellSize, height: overlayFp.height * cellSize }
: undefined
}
>
{activeItem ? (
<div className="h-full w-full rounded-md border border-primary/50 bg-card/95 shadow-xl">
<VehicleFace item={{ ...activeItem, rotated: pendingRotated }} cellSize={cellSize} dragging />
</div>
) : null}
</DragOverlay>
</DndContext>
);
}

View file

@ -1,438 +0,0 @@
"use client";
import { useState, useTransition } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { RotateCwIcon, SendIcon, WarehouseIcon, Wand2Icon, XIcon } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { CreateReservationDialog } from "@/components/frontend/operations/reservations/CreateReservationDialog";
import type { ReservationOptions } from "@/lib/operations/reservationOptions";
import {
autoArrangeGarage,
dispatchVehicle,
moveGarageItem,
rotateGarageItem,
storeVehicle,
} from "@/app/(frontend)/logistics/garage/actions";
import { GarageGrid, type GarageVehicleItem } from "./GarageGrid";
import { cn } from "@/lib/utils";
/**
* Garage overview: one grid per accessible structure whose blueprint defines
* a vehicle bay, plus an "Elsewhere" section for instances that are not on a
* grid (in transit, wrecks at non-garage sites, unplaced). Section headers use
* the tactical dossier style (D12); the grids themselves stay plain shadcn.
*/
export interface GarageSectionData {
structureId: number;
structureName: string;
bayWidth: number;
bayHeight: number;
vehicles: GarageVehicleItem[];
}
export interface ElsewhereVehicle {
id: number;
name: string;
status: GarageVehicleItem["status"];
locationName: string | null;
reservedFor: string | null;
}
export interface ElsewhereGroup {
key: string;
label: string;
hint: string;
vehicles: ElsewhereVehicle[];
}
export interface GarageReservationProps {
canCreate: boolean;
options: ReservationOptions;
canManageLogistics: boolean;
currentUserId: number;
}
interface GarageViewProps {
garages: GarageSectionData[];
elsewhere: ElsewhereGroup[];
canEdit: boolean;
/** Structures with a vehicle bay the viewer may store into. */
storeTargets: { id: number; name: string }[];
reservation: GarageReservationProps | null;
}
const STATUS_LABELS: Record<GarageVehicleItem["status"], string> = {
idle: "Idle",
assigned: "Assigned",
in_transit: "In transit",
damaged: "Damaged",
destroyed: "Destroyed",
};
function StatusBadge({ status }: { status: GarageVehicleItem["status"] }) {
return (
<Badge
variant="outline"
className={cn(
"font-mono text-[9px] uppercase tracking-wider",
status === "destroyed" && "border-red-500/50 text-red-400",
status === "damaged" && "border-amber-500/50 text-amber-400",
status === "in_transit" && "border-sky-500/50 text-sky-400",
status === "idle" && "text-muted-foreground",
)}
>
{STATUS_LABELS[status]}
</Badge>
);
}
/** Dossier classification-strip header shared by garage + elsewhere sections. */
function SectionHeader({
kicker,
title,
action,
}: {
kicker: string;
title: string;
action?: React.ReactNode;
}) {
return (
<header className="relative flex items-center justify-between gap-3 border-b border-white/15 bg-black/50 px-4 py-2.5 backdrop-blur-sm">
<div className="flex min-w-0 flex-col">
<span className="font-mono text-[9px] uppercase tracking-widest text-white/60">
{kicker}
</span>
<h2 className="truncate font-semibold uppercase tracking-wide">{title}</h2>
</div>
{action}
</header>
);
}
function ReadoutCell({ label, value }: { label: string; value: string }) {
return (
<div className="flex-1 border-r border-white/15 px-3 last:border-r-0">
<div className="font-mono text-[9px] uppercase tracking-widest text-white/50">{label}</div>
<div className="font-mono text-xs tabular-nums text-white/80">{value}</div>
</div>
);
}
function CornerBrackets() {
return (
<span aria-hidden="true" className="pointer-events-none absolute inset-2 z-10">
<span className="absolute left-0 top-0 size-3 border-l border-t border-white/25" />
<span className="absolute right-0 top-0 size-3 border-r border-t border-white/25" />
<span className="absolute bottom-0 left-0 size-3 border-b border-l border-white/25" />
<span className="absolute bottom-0 right-0 size-3 border-b border-r border-white/25" />
</span>
);
}
type SelectedVehicle = GarageVehicleItem & { structureId: number };
export function GarageView({
garages,
elsewhere,
canEdit,
storeTargets,
reservation,
}: GarageViewProps) {
const router = useRouter();
const [isPending, startTransition] = useTransition();
const [selected, setSelected] = useState<SelectedVehicle | null>(null);
const [storeOpen, setStoreOpen] = useState(false);
const [storeTarget, setStoreTarget] = useState<string>("");
const run = (label: string, fn: () => Promise<{ success: boolean; error?: string }>) => {
startTransition(async () => {
const result = await fn();
if (!result.success) {
toast.error(result.error ?? `${label} failed.`);
return;
}
toast.success(`${label}.`);
setSelected(null);
router.refresh();
});
};
const handleMove = async (id: number, gridX: number, gridY: number, rotated?: boolean) => {
if (!canEdit) return;
startTransition(async () => {
const result = await moveGarageItem(id, gridX, gridY, rotated);
if (!result.success) toast.error(result.error ?? "Move failed.");
else router.refresh();
});
};
const otherTargets = storeTargets.filter((t) => t.id !== selected?.structureId);
return (
<div className="flex flex-col gap-8">
{garages.length === 0 && (
<div className="border border-border/60 bg-card/40 p-6 text-sm text-muted-foreground">
No structures with vehicle bays are available yet. Define Vehicle Bay
Dimensions on a structure blueprint to open a garage.
</div>
)}
{garages.map((garage) => {
const occupiedCells = garage.vehicles.reduce(
(sum, v) => sum + v.width * v.height,
0,
);
const capacity = garage.bayWidth * garage.bayHeight;
return (
<section
key={garage.structureId}
className="relative border border-white/15 bg-card/30"
>
<CornerBrackets />
<SectionHeader
kicker={`Vehicle bay // structure ${garage.structureId}`}
title={garage.structureName}
action={
canEdit ? (
<Button
variant="outline"
size="sm"
disabled={isPending}
onClick={() =>
run("Bay auto-arranged", () => autoArrangeGarage(garage.structureId))
}
>
<Wand2Icon className="size-4" />
Auto-arrange
</Button>
) : undefined
}
/>
<div className="p-4">
<GarageGrid
gridWidth={garage.bayWidth}
gridHeight={garage.bayHeight}
items={garage.vehicles}
canEdit={canEdit}
selectedItem={selected?.structureId === garage.structureId ? selected : null}
onSelectItem={(item) =>
setSelected(item ? { ...item, structureId: garage.structureId } : null)
}
onMoveItem={handleMove}
/>
{selected && selected.structureId === garage.structureId && (
<div className="mt-4 flex flex-wrap items-center gap-3 border border-border/60 bg-muted/30 p-3">
<div className="flex min-w-0 flex-col gap-1">
<div className="flex items-center gap-2">
<span className="truncate text-sm font-medium">{selected.name}</span>
<StatusBadge status={selected.status} />
{selected.reservedFor && (
<Badge variant="secondary" className="bg-sky-500/15 text-[9px] uppercase">
Reserved for {selected.reservedFor}
</Badge>
)}
</div>
<span className="font-mono text-[10px] uppercase tracking-wider text-muted-foreground">
cell {selected.gridX},{selected.gridY} &middot;{" "}
{selected.rotated ? `${selected.height}x${selected.width}` : `${selected.width}x${selected.height}`} ft
{selected.fuelPct != null && ` · fuel ${selected.fuelPct}%`}
{selected.healthPct != null && ` · health ${selected.healthPct}%`}
</span>
</div>
<div className="ml-auto flex flex-wrap items-center gap-2">
{canEdit && (
<>
<Button
variant="outline"
size="sm"
disabled={isPending || selected.status === "destroyed"}
onClick={() => run("Vehicle rotated", () => rotateGarageItem(selected.id))}
>
<RotateCwIcon className="size-4" />
Rotate
</Button>
<Button
size="sm"
disabled={
isPending ||
selected.status !== "idle" ||
Boolean(selected.reservedFor)
}
title={
selected.reservedFor
? "Release the operation reservation first"
: undefined
}
onClick={() => run("Vehicle dispatched", () => dispatchVehicle(selected.id))}
>
<SendIcon className="size-4" />
Dispatch
</Button>
<Button
variant="secondary"
size="sm"
disabled={
isPending ||
selected.status === "destroyed" ||
otherTargets.length === 0
}
onClick={() => {
setStoreTarget("");
setStoreOpen(true);
}}
>
<WarehouseIcon className="size-4" />
Store
</Button>
</>
)}
{reservation?.canCreate && (
<CreateReservationDialog
key={`reserve-${selected.id}`}
options={reservation.options}
canManageLogistics={reservation.canManageLogistics}
currentUserId={reservation.currentUserId}
canCreate={reservation.canCreate}
initialVehicleIds={[selected.id]}
triggerLabel="Reserve"
/>
)}
<Button asChild variant="ghost" size="sm">
<Link href={`/logistics/game-vehicles/${selected.id}`}>Details</Link>
</Button>
<Button
variant="ghost"
size="icon"
aria-label="Deselect"
onClick={() => setSelected(null)}
>
<XIcon className="size-4" />
</Button>
</div>
</div>
)}
</div>
<footer className="flex border-t border-white/15 bg-black/60 py-1.5">
<ReadoutCell label="Parked" value={`${garage.vehicles.length}`} />
<ReadoutCell label="Bay cells" value={`${occupiedCells}/${capacity}`} />
<ReadoutCell
label="Damaged"
value={`${garage.vehicles.filter((v) => v.status === "damaged").length}`}
/>
<ReadoutCell
label="Destroyed"
value={`${garage.vehicles.filter((v) => v.status === "destroyed").length}`}
/>
</footer>
</section>
);
})}
{elsewhere.some((g) => g.vehicles.length > 0) && (
<section className="relative border border-white/15 bg-card/30">
<CornerBrackets />
<SectionHeader kicker="Fleet // off-grid" title="Elsewhere" />
<div className="flex flex-col gap-4 p-4">
{elsewhere.map((group) =>
group.vehicles.length === 0 ? null : (
<div key={group.key} className="flex flex-col gap-2">
<div className="flex items-baseline gap-2">
<h3 className="font-mono text-[10px] uppercase tracking-widest text-muted-foreground">
{group.label}
</h3>
<span className="text-xs text-muted-foreground/70">{group.hint}</span>
</div>
<ul className="divide-y divide-border/50 border border-border/60">
{group.vehicles.map((v) => (
<li key={v.id} className="flex items-center gap-3 px-3 py-2">
<Link
href={`/logistics/game-vehicles/${v.id}`}
className="truncate text-sm hover:underline"
>
{v.name}
</Link>
<StatusBadge status={v.status} />
{v.reservedFor && (
<Badge variant="secondary" className="bg-sky-500/15 text-[9px] uppercase">
Reserved for {v.reservedFor}
</Badge>
)}
<span className="ml-auto shrink-0 font-mono text-[10px] uppercase tracking-wider text-muted-foreground">
{v.locationName ?? "Unassigned"}
</span>
</li>
))}
</ul>
</div>
),
)}
</div>
</section>
)}
<Dialog open={storeOpen} onOpenChange={setStoreOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Store vehicle</DialogTitle>
<DialogDescription>
Park {selected?.name ?? "the vehicle"} in another garage bay. The instance is
marked idle and a deposit command is queued for the game server.
</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-2">
<Label htmlFor="store-target">Target garage</Label>
<Select value={storeTarget} onValueChange={setStoreTarget}>
<SelectTrigger id="store-target">
<SelectValue placeholder="Choose a structure" />
</SelectTrigger>
<SelectContent>
{otherTargets.map((t) => (
<SelectItem key={t.id} value={String(t.id)}>
{t.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setStoreOpen(false)}>
Cancel
</Button>
<Button
disabled={!storeTarget || isPending || !selected}
onClick={() => {
if (!selected) return;
const target = Number(storeTarget);
setStoreOpen(false);
run("Vehicle stored", () => storeVehicle(selected.id, target));
}}
>
Store
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}

View file

@ -544,13 +544,6 @@ export function LockerGrid({
onSelectItem(null);
}, [onSelectItem]);
// Drag preview must track mid-drag rotation: dnd-kit pins the overlay
// container to the activator rect captured at drag start, so we override
// its width/height via the style prop (spread after the pinned rect).
const overlayFp = activeItem
? getLockerItemFootprint(activeItem.asset, pendingRotated)
: null;
return (
<DndContext
sensors={sensors}
@ -642,16 +635,9 @@ export function LockerGrid({
</div>
{/* Tactical drag overlay */}
<DragOverlay
dropAnimation={null}
style={
overlayFp
? { width: overlayFp.width * cellSize, height: overlayFp.height * cellSize }
: undefined
}
>
<DragOverlay dropAnimation={null}>
{activeItem && (
<div className="h-full w-full rounded-sm border border-primary/50 bg-card shadow-lg ring-2 ring-primary/40">
<div className="rounded-sm border border-primary/50 bg-card shadow-lg ring-2 ring-primary/40">
<LockerItemFace
asset={activeItem.asset}
quantity={activeItem.quantity}

View file

@ -35,10 +35,6 @@ interface CreateReservationDialogProps {
currentUserId: number;
/** Trigger only renders for users who hold operation-reservations:create. */
canCreate: boolean;
/** Pre-select vehicles (e.g. "Reserve for operation" from the garage). */
initialVehicleIds?: number[];
/** Override the trigger button text. */
triggerLabel?: string;
}
interface CargoLine {
@ -124,8 +120,6 @@ export function CreateReservationDialog({
canManageLogistics,
currentUserId,
canCreate,
initialVehicleIds,
triggerLabel,
}: CreateReservationDialogProps) {
const router = useRouter();
const [open, setOpen] = useState(false);
@ -133,7 +127,7 @@ export function CreateReservationDialog({
const [operationId, setOperationId] = useState("");
const [missionId, setMissionId] = useState("");
const [personnel, setPersonnel] = useState<number[]>([]);
const [vehicles, setVehicles] = useState<number[]>(initialVehicleIds ?? []);
const [vehicles, setVehicles] = useState<number[]>([]);
const [originId, setOriginId] = useState("");
const [destinationId, setDestinationId] = useState("");
const [cargoLines, setCargoLines] = useState<CargoLine[]>([]);
@ -182,7 +176,7 @@ export function CreateReservationDialog({
setOperationId("");
setMissionId("");
setPersonnel([]);
setVehicles(initialVehicleIds ?? []);
setVehicles([]);
setOriginId("");
setDestinationId("");
setCargoLines([]);
@ -279,7 +273,7 @@ export function CreateReservationDialog({
<DialogTrigger asChild>
<Button size="sm">
<PlusIcon className="size-4" />
{triggerLabel ?? "New Reservation"}
New Reservation
</Button>
</DialogTrigger>
) : null}

View file

@ -353,20 +353,7 @@ export function InventoryGrid({
</div>
</div>
<DragOverlay
dropAnimation={null}
style={
activeItem
? (() => {
// dnd-kit pins the overlay container to the activator rect
// from drag start; override width/height so mid-drag rotation
// resizes the preview (style is spread after the pinned rect).
const fp = getItemFootprint(activeItem.resource as Resource, pendingRotated);
return { width: fp.width * cellSize - 2, height: fp.height * cellSize - 2 };
})()
: undefined
}
>
<DragOverlay dropAnimation={null}>
{activeItem && (
<DragOverlayContent item={activeItem} cellSize={cellSize} rotated={pendingRotated} />
)}

View file

@ -1,543 +0,0 @@
import { randomBytes } from "crypto";
import type { Payload, PayloadRequest } from "payload";
import type { GameStructure, GameVehicle, Structure, Vehicle } from "@/payload-types";
import type { RawSyncEvent } from "@/lib/operations/types";
import { findLatestOnlineServerId } from "./lockers";
import {
findGarageEmptySpot,
getGarageBayDimensions,
garageRelId,
parkedVehiclesToGridItems,
parseGarageInstanceRef,
type GarageGridItem,
} from "@/lib/garage";
/**
* Garage sync bridge processor (docs/arma-bridge/garage-sync.md).
*
* Instance refs are `garage:<storageSlug>` (the structure's existing item
* storage slug, assumption A1). Events carry per-instance identity via the
* addon-assigned `bridgeUid` plus fuel/damage fractions; the web claims
* unknown instances by classname match against untagged vehicles at that
* structure (first-tag-wins, provenance logged) or creates new game-vehicles
* rows. Grid cells are web bookkeeping: deposits auto-place row-major into
* free bay cells, and sync never moves already-parked vehicles.
*
* Merge rules mirror locker sync: snapshots update state only, absence is NOT
* deletion, grid metadata is preserved, and processors never throw so event
* ingestion cannot roll back.
*/
export interface GarageInstanceLine {
bridgeUid: string;
classname: string;
/** Fraction of tank capacity, 0..1. */
fuel: number;
/** Fraction of total damage, 0..1 (1 = destroyed). */
damage: number;
}
const MAX_SNAPSHOT_LINES = 200;
const UID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
const CLASSNAME_MAX = 200;
function clamp01(value: unknown): number {
const n = typeof value === "number" ? value : Number(value);
if (!Number.isFinite(n)) return 0;
return Math.min(1, Math.max(0, n));
}
/** Parse `[bridgeUid, classname, fuel, damage]`; null when malformed. */
export function parseInstanceLine(value: unknown): GarageInstanceLine | null {
if (!Array.isArray(value) || value.length < 2) return null;
const [uid, classname, fuel, damage] = value as unknown[];
if (typeof uid !== "string" || !UID_PATTERN.test(uid)) return null;
if (typeof classname !== "string" || classname.length === 0 || classname.length > CLASSNAME_MAX) {
return null;
}
if (value.length > 2 && !Number.isFinite(Number(fuel))) return null;
if (value.length > 3 && !Number.isFinite(Number(damage))) return null;
return {
bridgeUid: uid,
classname,
fuel: clamp01(fuel),
damage: clamp01(damage),
};
}
/** Parse a snapshot array of instance lines; null when the shape is invalid. */
export function parseGarageSnapshot(value: unknown): GarageInstanceLine[] | null {
if (!Array.isArray(value)) return null;
const lines: GarageInstanceLine[] = [];
for (const entry of value.slice(0, MAX_SNAPSHOT_LINES)) {
const line = parseInstanceLine(entry);
if (!line) return null;
lines.push(line);
}
return lines;
}
/** Marks the request so garage writes never echo back as commands. */
function markGarageSyncOrigin(req: PayloadRequest | undefined): void {
if (!req) return;
req.context = { ...req.context, garageSyncOrigin: true };
}
export function isGarageSyncOrigin(req: PayloadRequest): boolean {
return Boolean((req.context as Record<string, unknown> | undefined)?.garageSyncOrigin);
}
// ── Command enqueue (web -> mod) ──────────────────────────────────────────
async function enqueueGarageCommand(
payload: Payload,
type: string,
commandPayload: unknown[],
serverId?: number,
): Promise<boolean> {
const target = serverId ?? (await findLatestOnlineServerId(payload));
if (target == null) {
payload.logger.warn(
`[GarageSync] No online server; ${type} command not enqueued`,
);
return false;
}
await payload.create({
collection: "arma-commands",
data: {
commandId: `garage-${randomBytes(12).toString("hex")}`,
server: target,
type,
payload: commandPayload,
status: "queued",
},
overrideAccess: true,
depth: 0,
});
return true;
}
/** Build the wire line for a web-side instance; null when it has no game identity. */
export function garageInstanceLine(
vehicle: GameVehicle,
template: Vehicle | null | undefined,
): GarageInstanceLine | null {
if (!vehicle.bridgeUid) return null;
const classname = template?.classname?.trim();
if (!classname) return null;
const capacity = template?.fuel?.fuelCapacity ?? 0;
const fuel = capacity > 0 ? clamp01((vehicle.currentFuel ?? 0) / capacity) : 0;
const maxHealth = template?.maxHealth ?? 0;
const damage =
vehicle.status === "destroyed"
? 1
: maxHealth > 0
? clamp01(1 - (vehicle.currentHealth ?? 0) / maxHealth)
: 0;
return { bridgeUid: vehicle.bridgeUid, classname, fuel, damage };
}
/** Enqueue `garage.dispatch` (despawn from bay; instance now in transit). */
export async function enqueueGarageDispatch(
payload: Payload,
slug: string,
line: GarageInstanceLine,
): Promise<boolean> {
return enqueueGarageCommand(payload, "garage.dispatch", [
`garage:${slug}`,
line.bridgeUid,
line.classname,
line.fuel,
line.damage,
]);
}
/** Enqueue `garage.store` (spawn/relocate the instance into this bay). */
export async function enqueueGarageStore(
payload: Payload,
slug: string,
line: GarageInstanceLine,
): Promise<boolean> {
return enqueueGarageCommand(payload, "garage.store", [
`garage:${slug}`,
line.bridgeUid,
line.classname,
line.fuel,
line.damage,
]);
}
/** Enqueue a full `garage.apply` state push for one bay. */
export async function enqueueGarageApply(
payload: Payload,
slug: string,
lines: Array<[string, string, number, number]>,
serverId?: number,
): Promise<boolean> {
return enqueueGarageCommand(payload, "garage.apply", [`garage:${slug}`, lines], serverId);
}
// ── Event processing (mod -> web) ─────────────────────────────────────────
function statusFromDamage(
damage: number,
currentStatus: GameVehicle["status"],
): GameVehicle["status"] {
if (damage >= 1) return "destroyed";
if (currentStatus === "destroyed" || currentStatus === "damaged") return "idle";
return currentStatus;
}
async function findStructureBySlug(
payload: Payload,
slug: string,
req?: PayloadRequest,
): Promise<(GameStructure & { type?: Structure | null }) | null> {
const found = await payload.find({
collection: "game-structures",
where: { storageSlug: { equals: slug } },
depth: 1,
limit: 1,
overrideAccess: true,
req,
});
return (found.docs[0] as (GameStructure & { type?: Structure | null }) | undefined) ?? null;
}
/**
* Resolve a wire instance to a game-vehicles row: existing bridgeUid match,
* else claim an untagged classname match at this structure (first-tag-wins),
* else create a new instance from the template. Null when the classname is
* unknown to the vehicles templates.
*/
async function resolveInstance(
payload: Payload,
structureId: number,
line: GarageInstanceLine,
eventId: string,
req?: PayloadRequest,
): Promise<GameVehicle | null> {
const tagged = await payload.find({
collection: "game-vehicles",
where: { bridgeUid: { equals: line.bridgeUid } },
depth: 1,
limit: 1,
overrideAccess: true,
req,
});
if (tagged.docs[0]) return tagged.docs[0];
const untagged = await payload.find({
collection: "game-vehicles",
where: {
and: [
{ bridgeUid: { exists: false } },
{ deployedAt: { equals: structureId } },
{ "type.classname": { equals: line.classname } },
],
},
depth: 1,
limit: 1,
sort: "createdAt",
overrideAccess: true,
req,
});
const claim = untagged.docs[0];
if (claim) {
payload.logger.info(
`[GarageSync] Claimed vehicle ${claim.id} as bridgeUid ${line.bridgeUid} ` +
`(classname ${line.classname}, structure ${structureId}, provenance event ${eventId})`,
);
return payload.update({
collection: "game-vehicles",
id: claim.id,
data: { bridgeUid: line.bridgeUid },
depth: 1,
overrideAccess: true,
req,
});
}
const templates = await payload.find({
collection: "vehicles",
where: { classname: { equals: line.classname } },
depth: 0,
limit: 1,
overrideAccess: true,
req,
});
const template = templates.docs[0];
if (!template) {
payload.logger.warn(
`[GarageSync] Classname "${line.classname}" has no vehicle template; instance ${line.bridgeUid} skipped (event ${eventId})`,
);
return null;
}
const capacity = template.fuel?.fuelCapacity ?? 100;
const maxHealth = template.maxHealth ?? 100;
return payload.create({
collection: "game-vehicles",
data: {
name: template.name,
type: template.id,
deployedAt: structureId,
status: line.damage >= 1 ? "destroyed" : "idle",
currentFuel: Math.round(line.fuel * capacity),
currentHealth: Math.round((1 - line.damage) * maxHealth),
bridgeUid: line.bridgeUid,
},
depth: 1,
overrideAccess: true,
req,
});
}
/** Row-major auto-place an unplaced instance into the bay; null when full. */
async function autoPlaceIntoBay(
payload: Payload,
structure: GameStructure & { type?: Structure | null },
vehicle: GameVehicle & { type?: Vehicle | null },
req?: PayloadRequest,
): Promise<{ x: number; y: number } | null> {
const bay = getGarageBayDimensions(structure.type ?? null);
if (!bay) return null;
const { docs } = await payload.find({
collection: "game-vehicles",
where: { deployedAt: { equals: structure.id } },
depth: 1,
limit: 1000,
overrideAccess: true,
req,
});
const others = parkedVehiclesToGridItems(
(docs as Array<GameVehicle & { type?: unknown }>).filter((v) => v.id !== vehicle.id),
);
const template = typeof vehicle.type === "object" ? vehicle.type : null;
const fp = {
width: Math.max(1, Math.floor(template?.garageWidth ?? 1)),
height: Math.max(1, Math.floor(template?.garageHeight ?? 1)),
};
return findGarageEmptySpot(others, fp.width, fp.height, bay.width, bay.height);
}
async function applyDeposit(
payload: Payload,
structure: GameStructure & { type?: Structure | null },
line: GarageInstanceLine,
eventId: string,
req?: PayloadRequest,
): Promise<void> {
const instance = await resolveInstance(payload, structure.id, line, eventId, req);
if (!instance) return;
const template = typeof instance.type === "object" ? instance.type : null;
const capacity = template?.fuel?.fuelCapacity ?? 100;
const maxHealth = template?.maxHealth ?? 100;
const data: Record<string, unknown> = {
deployedAt: structure.id,
currentFuel: Math.round(line.fuel * capacity),
currentHealth: Math.round((1 - line.damage) * maxHealth),
};
const nextStatus = statusFromDamage(line.damage, instance.status);
if (nextStatus !== instance.status) data.status = nextStatus;
else if (instance.status === "in_transit") data.status = "idle";
if (instance.garageGridX == null || instance.garageGridY == null) {
const spot = await autoPlaceIntoBay(
payload,
structure,
instance as GameVehicle & { type?: Vehicle | null },
req,
);
if (spot) {
data.garageGridX = spot.x;
data.garageGridY = spot.y;
} else {
payload.logger.warn(
`[GarageSync] Bay full at structure ${structure.id}; vehicle ${instance.id} parked off-grid (event ${eventId})`,
);
}
}
await payload.update({
collection: "game-vehicles",
id: instance.id,
data: data as never,
depth: 0,
overrideAccess: true,
req,
});
}
async function applyWithdraw(
payload: Payload,
line: GarageInstanceLine,
eventId: string,
req?: PayloadRequest,
): Promise<void> {
const found = await payload.find({
collection: "game-vehicles",
where: { bridgeUid: { equals: line.bridgeUid } },
depth: 1,
limit: 1,
overrideAccess: true,
req,
});
const instance = found.docs[0];
if (!instance) {
payload.logger.warn(
`[GarageSync] garage.withdraw for unknown bridgeUid ${line.bridgeUid} (event ${eventId}); skipped`,
);
return;
}
const template = typeof instance.type === "object" ? instance.type : null;
const capacity = template?.fuel?.fuelCapacity ?? 100;
const maxHealth = template?.maxHealth ?? 100;
const destroyed = line.damage >= 1;
await payload.update({
collection: "game-vehicles",
id: instance.id,
data: {
garageGridX: null,
garageGridY: null,
garageRotated: false,
deployedAt: null,
currentFuel: Math.round(line.fuel * capacity),
currentHealth: Math.round((1 - line.damage) * maxHealth),
status: destroyed ? "destroyed" : instance.status === "assigned" ? "assigned" : "in_transit",
} as never,
depth: 0,
overrideAccess: true,
req,
});
}
async function handleRequest(
payload: Payload,
structure: GameStructure & { type?: Structure | null },
raw: RawSyncEvent,
req?: PayloadRequest,
): Promise<void> {
const { docs } = await payload.find({
collection: "game-vehicles",
where: {
and: [{ deployedAt: { equals: structure.id } }, { bridgeUid: { exists: true } }],
},
depth: 1,
limit: 1000,
overrideAccess: true,
req,
});
const lines: Array<[string, string, number, number]> = [];
for (const vehicle of docs as Array<GameVehicle & { type?: Vehicle }>) {
if (vehicle.garageGridX == null || vehicle.garageGridY == null) continue;
const line = garageInstanceLine(vehicle, vehicle.type);
if (!line) continue;
lines.push([line.bridgeUid, line.classname, line.fuel, line.damage]);
}
const slug = structure.storageSlug?.trim();
if (!slug) return;
await enqueueGarageApply(payload, slug, lines, typeof raw.server === "number" ? raw.server : undefined);
}
/**
* Router entry for `garage.*` events (wired from the arma-sync-events
* afterChange hook). Never throws.
*/
export async function processGarageEvent(
payload: Payload,
raw: RawSyncEvent,
req?: PayloadRequest,
): Promise<void> {
try {
if (typeof raw.server !== "number") {
payload.logger.warn(`[GarageSync] Garage event ${raw.eventId} has no server; skipped`);
return;
}
if (!Array.isArray(raw.payload)) {
payload.logger.warn(`[GarageSync] Malformed garage event payload ${raw.eventId}; skipped`);
return;
}
const ref = parseGarageInstanceRef(raw.payload[0]);
if (!ref) {
payload.logger.warn(`[GarageSync] Invalid garage instance ref on event ${raw.eventId}; skipped`);
return;
}
const structure = await findStructureBySlug(payload, ref.slug, req);
if (!structure) {
payload.logger.warn(
`[GarageSync] Unknown garage ref "garage:${ref.slug}" on event ${raw.eventId}; skipped`,
);
return;
}
if (!getGarageBayDimensions(structure.type ?? null)) {
payload.logger.warn(
`[GarageSync] Structure ${structure.id} ("${ref.slug}") has no vehicle bay; skipping event ${raw.eventId}`,
);
return;
}
markGarageSyncOrigin(req);
if (raw.type === "garage.deposit" || raw.type === "garage.withdraw") {
const line = parseInstanceLine(raw.payload.slice(1));
if (!line) {
payload.logger.warn(`[GarageSync] Malformed ${raw.type} payload ${raw.eventId}; skipped`);
return;
}
if (raw.type === "garage.deposit") {
await applyDeposit(payload, structure, line, raw.eventId, req);
} else {
await applyWithdraw(payload, line, raw.eventId, req);
}
return;
}
if (raw.type === "garage.sync") {
if (Array.isArray(raw.payload[1]) && raw.payload[1].length > MAX_SNAPSHOT_LINES) {
payload.logger.warn(
`[GarageSync] Snapshot for garage:${ref.slug} truncated to ${MAX_SNAPSHOT_LINES} lines (event ${raw.eventId})`,
);
}
const lines = parseGarageSnapshot(raw.payload[1]);
if (!lines) {
payload.logger.warn(`[GarageSync] Malformed garage.sync snapshot ${raw.eventId}; skipped`);
return;
}
for (const line of lines) {
await applyDeposit(payload, structure, line, raw.eventId, req);
}
return;
}
if (raw.type === "garage.request") {
await handleRequest(payload, structure, raw, req);
return;
}
payload.logger.warn(`[GarageSync] Unknown garage event type "${raw.type}" (${raw.eventId})`);
} catch (error) {
payload.logger.error(`[GarageSync] Failed to process garage event ${raw.eventId}: ${error}`);
}
}
/** Parked instances at a structure that the game can reconcile (used by tests/actions). */
export async function parkedTaggedVehicles(
payload: Payload,
structureId: number,
): Promise<Array<GameVehicle & { type?: Vehicle }>> {
const { docs } = await payload.find({
collection: "game-vehicles",
where: { deployedAt: { equals: structureId } },
depth: 1,
limit: 1000,
overrideAccess: true,
});
return (docs as Array<GameVehicle & { type?: Vehicle }>).filter(
(v) => v.bridgeUid && v.garageGridX != null && v.garageGridY != null,
);
}
export type { GarageGridItem };
export { garageRelId };

View file

@ -12,8 +12,8 @@
* - For "vehicle" records `extra` is the transport mode ("air" | "sea" |
* "ground"; anything else -> "ground").
* - For "magazine" records `extra` is the round count (magazine roundCapacity).
* - `mass` imports into `vehicles.maxMass` for vehicle records (physical mass
* from the export); asset records do not carry a matching field.
* - `mass` is accepted for contract completeness; no collection field maps to
* it yet, so it is not imported.
*
* Legacy field aliases (`class`, `category`, `name`) are still accepted.
*
@ -56,7 +56,7 @@ export interface CatalogRecord {
picture?: string;
mod?: string;
description?: string;
/** Vehicles only: physical mass, imported into maxMass. */
/** Accepted by the contract; no collection field maps to it (not imported). */
mass?: number;
/** Transport mode for vehicles, round count for magazines, otherwise "". */
extra?: number | string;
@ -82,8 +82,6 @@ export interface ImportPlan {
assetType: AssetType | "vehicle";
/** Vehicles only. */
transportMode: TransportMode;
/** Vehicles only: physical mass from the export (written to maxMass). */
mass?: number;
/** Magazines only: round count from `extra`. */
roundCapacity?: number;
/** Weapons only: compatibility references (classnames), linked in a second pass. */
@ -183,20 +181,6 @@ function transportModeFromExtra(extra: number | string | undefined): TransportMo
return "ground";
}
/**
* Default Vehicles.category derived from the transport mode. Only applied
* when a template has no category yet; officers refine it by hand (the export
* carries no doctrine classification).
*/
export function defaultCategoryForTransport(mode: TransportMode): "utility" | "transport" {
return mode === "ground" ? "utility" : "transport";
}
/** Positive finite mass from a catalog record, undefined otherwise. */
function positiveMass(mass: number | undefined): number | undefined {
return typeof mass === "number" && Number.isFinite(mass) && mass > 0 ? mass : undefined;
}
/**
* Plan one catalog record (pure — no filesystem or database access).
* Returns undefined for records without a usable classname.
@ -212,7 +196,6 @@ export function planRecord(rec: CatalogRecord, lookups: PlanLookups = {}): Impor
const pictureRef = lookupIcon(lookups.icons, className) || String(rec.picture ?? "").trim();
if (rawType === "vehicle" || (!ASSET_TYPE_SET.has(rawType) && looksLikeVehicle(className, rawType))) {
const mass = positiveMass(rec.mass);
return {
kind: "vehicle",
className,
@ -220,7 +203,6 @@ export function planRecord(rec: CatalogRecord, lookups: PlanLookups = {}): Impor
description,
assetType: "vehicle",
transportMode: transportModeFromExtra(rec.extra),
...(mass !== undefined ? { mass } : {}),
mod,
pictureRef,
media: { paaPath: "", pngPath: "", screenshotPath: "" },
@ -502,15 +484,9 @@ async function upsertVehicle(payload: Payload, plan: ImportPlan, fuelId: number
transportMode: plan.transportMode,
};
if (plan.description) data.description = plaintextToLexical(plan.description);
// Physical mass is pure game data: refresh it on every import.
if (plan.mass !== undefined) data.maxMass = plan.mass;
const imagePath = planImagePath(plan);
// Same rule as assets: fill an empty image, never replace one that is set.
const current = existing.docs[0] as unknown as { image?: unknown; category?: unknown };
// Category default only fills templates nobody has classified yet.
if (!Array.isArray(current.category) || current.category.length === 0) {
data.category = [defaultCategoryForTransport(plan.transportMode)];
}
const current = existing.docs[0] as unknown as { image?: unknown };
if (imagePath && !current.image) {
const media = await resolveMedia(payload, imagePath);
if (media) data.image = media.id;
@ -526,8 +502,6 @@ async function upsertVehicle(payload: Payload, plan: ImportPlan, fuelId: number
classname: plan.className,
fuel: { fuelType: fuelId, fuelCapacity: 100, fuelConsumptionRate: 1 },
transportMode: plan.transportMode,
category: [defaultCategoryForTransport(plan.transportMode)],
...(plan.mass !== undefined ? { maxMass: plan.mass } : {}),
...(plan.description ? { description: plaintextToLexical(plan.description) } : {}),
...(mediaId !== undefined ? { image: mediaId } : {}),
};

View file

@ -1,222 +0,0 @@
import type { GameStructure, GameVehicle, Structure, Vehicle } from "@/payload-types";
/**
* Garage grid geometry for vehicle bays.
*
* Clones the proven shape of src/lib/logistics.ts (footprint / occupancy /
* placement validity / auto-arrange) for vehicle instances parked in a
* structure's vehicle bay. Vehicles never stack; rotation swaps width and
* height. Footprints come from the vehicle template's dedicated
* garageWidth/garageHeight fields (default 1x1 when unset).
*/
export type GridDimensions = { width: number; height: number };
export type GarageGridItem = {
/** Stable client identity: String(gameVehicleId). */
id: string;
vehicleId: number;
gridX: number;
gridY: number;
rotated: boolean;
template: Vehicle;
};
/**
* Resolve a blueprint's vehicle bay dimensions. Returns null when the
* blueprint defines no usable bay (either dimension missing or <= 0).
*/
export function getGarageBayDimensions(blueprint: Structure | null | undefined): GridDimensions | null {
const x = blueprint?.vehicleBay?.xSize ?? 0;
const y = blueprint?.vehicleBay?.ySize ?? 0;
if (!x || !y || x <= 0 || y <= 0) return null;
return { width: Math.floor(x), height: Math.floor(y) };
}
/** True when a game structure's populated blueprint exposes a vehicle bay. */
export function structureHasVehicleBay(
structure: (GameStructure & { type?: Structure | null }) | null | undefined,
): boolean {
return getGarageBayDimensions(structure?.type ?? null) !== null;
}
/**
* Get the effective footprint of a vehicle in the bay, accounting for
* rotation. Falls back to 1x1 when the template has no garage dimensions.
*/
export function getVehicleFootprint(template: Vehicle | null | undefined, rotated: boolean): GridDimensions {
const w = Math.max(1, Math.floor(template?.garageWidth ?? 1));
const h = Math.max(1, Math.floor(template?.garageHeight ?? 1));
return rotated ? { width: h, height: w } : { width: w, height: h };
}
/**
* Get the cells occupied by a footprint as an array of "x,y" strings.
*/
export function getGarageOccupiedCells(
gridX: number,
gridY: number,
width: number,
height: number,
): string[] {
const cells: string[] = [];
for (let dx = 0; dx < width; dx++) {
for (let dy = 0; dy < height; dy++) {
cells.push(`${gridX + dx},${gridY + dy}`);
}
}
return cells;
}
/**
* Check whether placing a vehicle at (targetX, targetY) would overlap any
* other parked vehicle or leave the bay. Returns true if VALID.
*/
export function isGaragePlacementValid(
items: GarageGridItem[],
excludeId: string | null,
targetX: number,
targetY: number,
width: number,
height: number,
bayWidth: number,
bayHeight: number,
): boolean {
if (targetX < 0 || targetY < 0) return false;
if (targetX + width > bayWidth || targetY + height > bayHeight) return false;
const targetCells = new Set(getGarageOccupiedCells(targetX, targetY, width, height));
for (const item of items) {
if (item.id === excludeId) continue;
const fp = getVehicleFootprint(item.template, item.rotated);
const occupied = getGarageOccupiedCells(item.gridX, item.gridY, fp.width, fp.height);
for (const cell of occupied) {
if (targetCells.has(cell)) return false;
}
}
return true;
}
/**
* Find the first available spot for a footprint, scanning left-to-right,
* top-to-bottom (row-major). Returns {x, y} or null when the bay is full.
*/
export function findGarageEmptySpot(
items: GarageGridItem[],
width: number,
height: number,
bayWidth: number,
bayHeight: number,
): { x: number; y: number } | null {
for (let y = 0; y <= bayHeight - height; y++) {
for (let x = 0; x <= bayWidth - width; x++) {
if (isGaragePlacementValid(items, null, x, y, width, height, bayWidth, bayHeight)) {
return { x, y };
}
}
}
return null;
}
/**
* Auto-arrange all parked vehicles into the bay (row-major greedy repack in
* input order). Vehicles that no longer fit are returned in `overflow` and
* should stay unplaced (they surface in the Elsewhere section instead).
*/
export function autoArrangeGarageItems(
items: GarageGridItem[],
bayWidth: number,
bayHeight: number,
): { placed: Array<{ id: string; gridX: number; gridY: number }>; overflow: string[] } {
const placed: Array<GarageGridItem> = [];
const result: Array<{ id: string; gridX: number; gridY: number }> = [];
const overflow: string[] = [];
for (const item of items) {
const fp = getVehicleFootprint(item.template, item.rotated);
const spot = findGarageEmptySpot(placed, fp.width, fp.height, bayWidth, bayHeight);
if (spot) {
const moved = { ...item, gridX: spot.x, gridY: spot.y };
placed.push(moved);
result.push({ id: item.id, gridX: spot.x, gridY: spot.y });
} else {
overflow.push(item.id);
}
}
return { placed: result, overflow };
}
/**
* Get the number of bay cells occupied vs total.
*/
export function getGarageGridOccupancy(
items: GarageGridItem[],
bayWidth: number,
bayHeight: number,
): { used: number; total: number } {
const occupied = new Set<string>();
for (const item of items) {
const fp = getVehicleFootprint(item.template, item.rotated);
const cells = getGarageOccupiedCells(item.gridX, item.gridY, fp.width, fp.height);
for (const c of cells) occupied.add(c);
}
return { used: occupied.size, total: bayWidth * bayHeight };
}
function relId(value: unknown): number | null {
if (typeof value === "number") return value;
if (value !== null && typeof value === "object" && "id" in (value as { id: unknown })) {
const id = (value as { id: unknown }).id;
return typeof id === "number" ? id : null;
}
return null;
}
/**
* Convert populated game-vehicles rows into grid items, keeping only the
* instances actually parked on bay cells (garageGridX/garageGridY set) whose
* template is populated.
*/
export function parkedVehiclesToGridItems(
vehicles: Array<GameVehicle & { type?: Vehicle | number | null }>,
): GarageGridItem[] {
const items: GarageGridItem[] = [];
for (const vehicle of vehicles) {
if (vehicle.garageGridX == null || vehicle.garageGridY == null) continue;
const template = typeof vehicle.type === "object" ? vehicle.type : null;
if (!template) continue;
items.push({
id: String(vehicle.id),
vehicleId: vehicle.id,
gridX: vehicle.garageGridX,
gridY: vehicle.garageGridY,
rotated: vehicle.garageRotated ?? false,
template,
});
}
return items;
}
/** Instance ref used on the bridge wire: `garage:<storageSlug>` (A1). */
export function formatGarageInstanceRef(slug: string): string {
return `garage:${slug}`;
}
/** Parse a `garage:<storageSlug>` instance ref; null when malformed. */
export function parseGarageInstanceRef(value: unknown): { slug: string } | null {
if (typeof value !== "string") return null;
const separator = value.indexOf(":");
if (separator <= 0) return null;
if (value.slice(0, separator) !== "garage") return null;
const slug = value.slice(separator + 1);
if (!/^[a-z0-9][a-z0-9-_]{1,63}$/.test(slug)) return null;
return { slug };
}
/** Numeric id of a possibly-populated relationship, or null. */
export function garageRelId(value: unknown): number | null {
return relId(value);
}

View file

@ -129,7 +129,7 @@ function fuelPercent(vehicle: Depth0Vehicle): number {
return Math.round((current / capacity) * 100);
}
export async function activeReservedVehicleIds(
async function activeReservedVehicleIds(
payload: PayloadType,
): Promise<Set<number>> {
const res = await payload
@ -155,44 +155,6 @@ export async function activeReservedVehicleIds(
return ids;
}
/**
* Map of game-vehicle id -> human label of the operation it is actively
* reserved for ("Reserved for op X" badges on garage vehicle faces).
* First reservation wins; mission name preferred over the free-text
* operationId. Shares semantics with activeReservedVehicleIds: only
* status === "reserved" counts as active.
*/
export async function reservedVehiclesByOperation(
payload: PayloadType,
): Promise<Map<number, string>> {
const res = await payload
.find({
collection: "operation-reservations",
where: { status: { equals: "reserved" } },
limit: 1000,
depth: 1,
overrideAccess: true,
})
.catch(() => ({ docs: [] as unknown[] }));
const map = new Map<number, string>();
for (const doc of res.docs) {
const row = doc as {
operationId?: string;
mission?: { name?: string } | number | null;
vehicles?: { vehicle: number | { id: number } }[] | null;
};
const missionName =
row.mission && typeof row.mission === "object" ? row.mission.name : undefined;
const label = missionName?.trim() || row.operationId || "an operation";
for (const entry of row.vehicles ?? []) {
const ref = entry.vehicle;
const id = typeof ref === "object" && ref ? ref.id : ref;
if (typeof id === "number" && !map.has(id)) map.set(id, label);
}
}
return map;
}
async function fetchBudgetAccounts(
payload: PayloadType,
userId: number | null,

File diff suppressed because it is too large Load diff

View file

@ -1,27 +0,0 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "game_vehicles" ADD COLUMN "garage_grid_x" numeric;
ALTER TABLE "game_vehicles" ADD COLUMN "garage_grid_y" numeric;
ALTER TABLE "game_vehicles" ADD COLUMN "garage_rotated" boolean DEFAULT false;
ALTER TABLE "game_vehicles" ADD COLUMN "bridge_uid" varchar;
ALTER TABLE "vehicles" ADD COLUMN "garage_width" numeric;
ALTER TABLE "vehicles" ADD COLUMN "garage_height" numeric;
ALTER TABLE "structures" ADD COLUMN "vehicle_bay_x_size" numeric;
ALTER TABLE "structures" ADD COLUMN "vehicle_bay_y_size" numeric;
CREATE UNIQUE INDEX "game_vehicles_bridge_uid_idx" ON "game_vehicles" USING btree ("bridge_uid");`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
DROP INDEX "game_vehicles_bridge_uid_idx";
ALTER TABLE "game_vehicles" DROP COLUMN "garage_grid_x";
ALTER TABLE "game_vehicles" DROP COLUMN "garage_grid_y";
ALTER TABLE "game_vehicles" DROP COLUMN "garage_rotated";
ALTER TABLE "game_vehicles" DROP COLUMN "bridge_uid";
ALTER TABLE "vehicles" DROP COLUMN "garage_width";
ALTER TABLE "vehicles" DROP COLUMN "garage_height";
ALTER TABLE "structures" DROP COLUMN "vehicle_bay_x_size";
ALTER TABLE "structures" DROP COLUMN "vehicle_bay_y_size";`)
}

View file

@ -133,7 +133,6 @@ import * as migration_20261012_181310_add_journals_collection from './20261012_1
import * as migration_20261012_182016_add_journals_event_target from './20261012_182016_add_journals_event_target';
import * as migration_20261012_185409_add_award_rules_automation from './20261012_185409_add_award_rules_automation';
import * as migration_20261013_183041_add_journal_contribution_type from './20261013_183041_add_journal_contribution_type';
import * as migration_20261013_184745_add_garage_fields from './20261013_184745_add_garage_fields';
export const migrations = [
{
@ -809,11 +808,6 @@ export const migrations = [
{
up: migration_20261013_183041_add_journal_contribution_type.up,
down: migration_20261013_183041_add_journal_contribution_type.down,
name: '20261013_183041_add_journal_contribution_type',
},
{
up: migration_20261013_184745_add_garage_fields.up,
down: migration_20261013_184745_add_garage_fields.down,
name: '20261013_184745_add_garage_fields'
name: '20261013_183041_add_journal_contribution_type'
},
];

View file

@ -1542,13 +1542,6 @@ export interface Structure {
restrictToAllowed?: boolean | null;
xSize?: number | null;
ySize?: number | null;
/**
* Grid capacity for the Garage view. Structures whose blueprint defines a bay with both dimensions greater than zero expose a garage grid holding parked vehicle instances. Empty = no vehicle storage.
*/
vehicleBay?: {
xSize?: number | null;
ySize?: number | null;
};
allowedStorage?:
| {
item?:
@ -2141,8 +2134,6 @@ export interface Vehicle {
transportMode: 'ground' | 'air' | 'sea';
width?: number | null;
height?: number | null;
garageWidth?: number | null;
garageHeight?: number | null;
maxMass?: number | null;
/**
* The number of ACE cargo slots this vehicle has by default.
@ -2422,22 +2413,6 @@ export interface GameVehicle {
* The structure where this vehicle is currently stationed. Null if in transit.
*/
deployedAt?: (number | null) | GameStructure;
/**
* Column position in the deployed structure's Garage vehicle bay (0-indexed). Null = not parked in a bay cell.
*/
garageGridX?: number | null;
/**
* Row position in the deployed structure's Garage vehicle bay (0-indexed). Null = not parked in a bay cell.
*/
garageGridY?: number | null;
/**
* Whether this vehicle is rotated 90 degrees in the garage bay (swaps width and height).
*/
garageRotated?: boolean | null;
/**
* Per-instance identity assigned by the Arma bridge (docs/arma-bridge/garage-sync.md). Two identical vehicles are told apart by this tag. Null = never seen by the game.
*/
bridgeUid?: string | null;
/**
* The faction that owns this vehicle.
*/
@ -8815,10 +8790,6 @@ export interface GameVehiclesSelect<T extends boolean = true> {
name?: T;
type?: T;
deployedAt?: T;
garageGridX?: T;
garageGridY?: T;
garageRotated?: T;
bridgeUid?: T;
faction?: T;
status?: T;
currentFuel?: T;
@ -9957,8 +9928,6 @@ export interface VehiclesSelect<T extends boolean = true> {
transportMode?: T;
width?: T;
height?: T;
garageWidth?: T;
garageHeight?: T;
maxMass?: T;
aceCargoSlots?: T;
allowedVirtualCargo?:
@ -10112,12 +10081,6 @@ export interface StructuresSelect<T extends boolean = true> {
restrictToAllowed?: T;
xSize?: T;
ySize?: T;
vehicleBay?:
| T
| {
xSize?: T;
ySize?: T;
};
allowedStorage?:
| T
| {

View file

@ -1,181 +0,0 @@
#!/usr/bin/env bun
/**
* backfillGaragePlacement.ts - seed garage bay placement for existing vehicles.
*
* Row-major auto-places existing IDLE game-vehicles whose deployedAt structure
* has a vehicle bay (blueprint vehicleBay.xSize/ySize > 0) into free bay cells.
* Anything that does not fit stays unplaced (null cells) and shows up in the
* Garage "Elsewhere" section. Mirrors the locker sync auto-placement posture:
* never moves vehicles that already have a cell, never touches non-idle or
* non-garaged vehicles.
*
* Usage (targets the DATABASE_URI from .env, same as other local tooling):
* bun run garage:backfill --dry-run # report only, no writes
* bun run garage:backfill # apply
*/
import { getPayload } from "payload";
import type { Payload } from "payload";
import type { GameStructure, GameVehicle, Structure } from "@/payload-types";
import {
getGarageBayDimensions,
getVehicleFootprint,
isGaragePlacementValid,
type GarageGridItem,
} from "@/lib/garage";
const DRY_RUN = process.argv.includes("--dry-run") || process.argv.includes("-n");
function log(msg: string) {
console.log(`[garage-backfill] ${msg}`);
}
async function main() {
const payloadConfig = await (await import("@payload-config")).default;
const payload: Payload = await getPayload({ config: payloadConfig });
// Structures whose blueprint exposes a vehicle bay.
const { docs: blueprints } = await payload.find({
collection: "structures",
depth: 0,
limit: 1000,
overrideAccess: true,
});
const bayBlueprintIds = new Map<number, { width: number; height: number }>();
for (const bp of blueprints as Structure[]) {
const bay = getGarageBayDimensions(bp);
if (bay) bayBlueprintIds.set(bp.id, bay);
}
if (bayBlueprintIds.size === 0) {
log("No structure blueprints define a vehicle bay. Nothing to do.");
return;
}
const { docs: structures } = await payload.find({
collection: "game-structures",
depth: 0,
limit: 1000,
overrideAccess: true,
where: {
type: { in: Array.from(bayBlueprintIds.keys()) },
},
});
if (structures.length === 0) {
log("No built structures use a blueprint with a vehicle bay. Nothing to do.");
return;
}
let totalPlaced = 0;
let totalOverflow = 0;
for (const structure of structures as GameStructure[]) {
const bay = bayBlueprintIds.get(
typeof structure.type === "object" ? (structure.type as Structure).id : (structure.type as number),
);
if (!bay) continue;
const { docs: vehicles } = await payload.find({
collection: "game-vehicles",
depth: 1, // populate type (template) for footprints
limit: 1000,
overrideAccess: true,
where: { deployedAt: { equals: structure.id } },
});
const rows = vehicles as Array<GameVehicle & { type?: unknown }>;
// Occupancy from vehicles already parked on cells (never moved).
const occupied: GarageGridItem[] = [];
for (const v of rows) {
if (v.garageGridX == null || v.garageGridY == null) continue;
const template = typeof v.type === "object" ? (v.type as never) : null;
if (!template) continue;
occupied.push({
id: String(v.id),
vehicleId: v.id,
gridX: v.garageGridX,
gridY: v.garageGridY,
rotated: v.garageRotated ?? false,
template,
});
}
// Idle, unplaced candidates, in stable order.
const candidates = rows.filter(
(v) => v.status === "idle" && v.garageGridX == null && v.garageGridY == null,
);
if (candidates.length === 0) continue;
const placements: Array<{ id: number; gridX: number; gridY: number }> = [];
const working = [...occupied];
let overflow = 0;
for (const candidate of candidates) {
const template = typeof candidate.type === "object" ? (candidate.type as never) : null;
if (!template) {
overflow += 1;
continue;
}
const fp = getVehicleFootprint(template as never, false);
let spot: { x: number; y: number } | null = null;
outer: for (let y = 0; y <= bay.height - fp.height; y++) {
for (let x = 0; x <= bay.width - fp.width; x++) {
if (
isGaragePlacementValid(working, null, x, y, fp.width, fp.height, bay.width, bay.height)
) {
spot = { x, y };
break outer;
}
}
}
if (!spot) {
overflow += 1;
continue;
}
working.push({
id: String(candidate.id),
vehicleId: candidate.id,
gridX: spot.x,
gridY: spot.y,
rotated: false,
template: template as never,
});
placements.push({ id: candidate.id, gridX: spot.x, gridY: spot.y });
}
if (placements.length > 0 || overflow > 0) {
log(
`Structure "${structure.name}" (bay ${bay.width}x${bay.height}): ` +
`${placements.length} to place, ${overflow} overflow (stays unplaced).`,
);
}
for (const p of placements) {
if (DRY_RUN) {
log(` dry-run: vehicle ${p.id} -> cell (${p.gridX}, ${p.gridY})`);
} else {
await payload.update({
collection: "game-vehicles",
id: p.id,
data: { garageGridX: p.gridX, garageGridY: p.gridY, garageRotated: false },
overrideAccess: true,
depth: 0,
});
}
}
totalPlaced += placements.length;
totalOverflow += overflow;
}
log(
`${DRY_RUN ? "Dry run complete. Would place" : "Placed"} ${totalPlaced} vehicle(s); ` +
`${totalOverflow} left unplaced (Elsewhere).`,
);
}
main()
.then(() => process.exit(0))
.catch((err) => {
console.error("[garage-backfill] Failed:", err);
process.exit(1);
});

View file

@ -245,13 +245,6 @@ export const EventTypes = {
ProductionToggled: "production:toggled",
StructureModuleInstall: "structure:module-install",
StructureModuleUninstall: "structure:module-uninstall",
// Garage (vehicle bay grid)
GarageMove: "garage:move",
GarageRotate: "garage:rotate",
GarageAutoArrange: "garage:auto-arrange",
GarageDispatch: "garage:dispatch",
GarageStore: "garage:store",
} as const;
export type EventType = (typeof EventTypes)[keyof typeof EventTypes];

View file

@ -1,229 +0,0 @@
import { expect, test } from "@playwright/test";
import type { Payload } from "payload";
import { bootstrapTestDatabase, resolveTestDatabaseUri } from "../test-db";
/**
* Garage surface: grid of parked vehicles per bay structure, Elsewhere for
* off-grid instances, drag-to-rearrange persisting through the server action,
* and the legacy /logistics/game-vehicles redirect.
*
* NOTE: exercises the real dev server under the dev-server protocol (the
* webServer env points DATABASE_URI at the dedicated test database).
*/
const RUN = `e2e-garage-${Date.now().toString(36)}`;
const STRUCTURE_NAME = `${RUN} Motor Pool`;
const PARKED_NAME = `${RUN} Parked HEMTT`;
const UNPLACED_NAME = `${RUN} Stray Truck`;
const LEXICAL_EMPTY = {
root: {
children: [{ text: "" }],
direction: null,
format: "" as const,
indent: 0,
type: "text",
version: 1,
},
};
let payload: Payload;
const cleanupIds: Array<{ collection: string; id: number }> = [];
async function seed() {
process.env.DATABASE_URI = resolveTestDatabaseUri();
const { getPayload } = await import("payload");
const { default: config } = await import("@payload-config");
payload = await getPayload({ config });
const resource = await payload.create({
collection: "resources",
data: {
name: `${RUN} Fuel`,
codeName: `${RUN}-fuel`,
approvalStatus: "in_progress",
type: "physical",
baseValue: 1,
rarity: "common",
unitOfMeasure: "L",
massPerUnit: 1,
gridWidth: 1,
gridHeight: 1,
} as never,
overrideAccess: true,
depth: 0,
});
cleanupIds.push({ collection: "resources", id: resource.id });
const blueprint = await payload.create({
collection: "structures",
data: {
name: `${RUN} Blueprint`,
codeName: RUN,
approvalStatus: "in_progress",
description: LEXICAL_EMPTY,
category: "logistics",
materials: [{ resource: resource.id, amount: 1 }],
constructionDurationMinutes: 1,
terrainType: "land",
maxHealth: 100,
vehicleBay: { xSize: 4, ySize: 3 },
} as never,
overrideAccess: true,
depth: 0,
});
cleanupIds.push({ collection: "structures", id: blueprint.id });
const structure = await payload.create({
collection: "game-structures",
data: {
name: STRUCTURE_NAME,
type: blueprint.id,
constructionStatus: "complete",
storageSlug: `${RUN}-pool`,
} as never,
overrideAccess: true,
depth: 0,
});
cleanupIds.push({ collection: "game-structures", id: structure.id });
const template = await payload.create({
collection: "vehicles",
data: {
name: `${RUN} HEMTT`,
classname: `${RUN}-hemtt`,
approvalStatus: "approved",
garageWidth: 2,
garageHeight: 1,
maxHealth: 100,
fuel: { fuelType: resource.id, fuelCapacity: 100, fuelConsumptionRate: 1 },
} as never,
draft: false,
overrideAccess: true,
depth: 0,
});
cleanupIds.push({ collection: "vehicles", id: template.id });
const parked = await payload.create({
collection: "game-vehicles",
data: {
name: PARKED_NAME,
type: template.id,
deployedAt: structure.id,
status: "idle",
currentFuel: 80,
currentHealth: 100,
garageGridX: 0,
garageGridY: 0,
} as never,
overrideAccess: true,
depth: 0,
});
cleanupIds.push({ collection: "game-vehicles", id: parked.id });
const stray = await payload.create({
collection: "game-vehicles",
data: {
name: UNPLACED_NAME,
type: template.id,
deployedAt: structure.id,
status: "idle",
currentFuel: 40,
currentHealth: 100,
} as never,
overrideAccess: true,
depth: 0,
});
cleanupIds.push({ collection: "game-vehicles", id: stray.id });
return { parkedId: parked.id };
}
async function login(page: import("@playwright/test").Page) {
await page.goto("/login");
await page.getByLabel("Username").fill("dev");
await page.getByLabel("Password").fill("Test123");
await page.getByRole("button", { name: "Log in" }).click();
await page.waitForURL((url) => !url.pathname.startsWith("/login"), { timeout: 30_000 });
}
test.describe("Garage", () => {
let parkedId: number;
test.beforeAll(async () => {
await bootstrapTestDatabase();
const seeded = await seed();
parkedId = seeded.parkedId;
});
test.afterAll(async () => {
if (!payload) return;
for (const { collection, id } of cleanupIds) {
await payload.delete({ collection, id, overrideAccess: true } as never).catch(() => {});
}
});
test("guests never see the garage", async ({ page }) => {
await page.goto("/logistics/garage");
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Polaris Task Force");
});
test("renders the bay grid, Elsewhere, and redirects the legacy route", async ({ page }) => {
await login(page);
await page.goto("/logistics/garage");
await expect(page.getByRole("heading", { name: "Garage" })).toBeVisible();
await expect(page.getByRole("heading", { name: STRUCTURE_NAME })).toBeVisible();
await expect(page.getByRole("button", { name: new RegExp(PARKED_NAME) })).toBeVisible();
// Elsewhere lists the unplaced instance.
await expect(page.getByRole("heading", { name: "Elsewhere" })).toBeVisible();
await expect(page.getByRole("link", { name: UNPLACED_NAME })).toBeVisible();
// Sidebar entry renamed (D8).
await expect(page.getByRole("link", { name: "Garage" }).first()).toBeVisible();
// Legacy list URL redirects to the garage.
await page.goto("/logistics/game-vehicles");
await page.waitForURL((url) => url.pathname === "/logistics/garage", { timeout: 30_000 });
});
test("dragging a vehicle persists its new cell", async ({ page }) => {
await login(page);
await page.goto("/logistics/garage");
const face = page.getByRole("button", { name: new RegExp(PARKED_NAME) });
await expect(face).toBeVisible();
const box = await face.boundingBox();
expect(box).not.toBeNull();
// Drag one grid step right (the bay is otherwise empty, so any single
// cell shift lands on a free spot regardless of the responsive cell size).
const step = Math.max(12, Math.floor((box!.width / 2) - 4));
await page.mouse.move(box!.x + box!.width / 2, box!.y + box!.height / 2);
await page.mouse.down();
await page.mouse.move(box!.x + box!.width / 2 + step, box!.y + box!.height / 2, { steps: 8 });
await page.mouse.move(box!.x + box!.width / 2 + step + 6, box!.y + box!.height / 2, { steps: 4 });
await page.mouse.up();
// The move goes through the server action; poll the test DB for it.
await expect
.poll(
async () => {
const doc = await payload.findByID({
collection: "game-vehicles",
id: parkedId,
depth: 0,
overrideAccess: true,
});
return doc.garageGridX;
},
{ timeout: 20_000, message: "expected garageGridX to change after the drag" },
)
.toBeGreaterThan(0);
// And it survives a reload.
await page.reload();
await expect(face).toBeVisible();
});
});

View file

@ -1,406 +0,0 @@
import { getPayload, Payload } from "payload";
import config from "@/payload.config";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { GameVehicle } from "@/payload-types";
import { processGarageEvent } from "@/lib/arma-bridge/garages";
let payload: Payload;
const RUN = `garagebr-${Date.now().toString(36)}`;
const SLUG = `${RUN}-motorpool`;
const CLASSNAME = `${RUN}-truck`;
const UID_PARKED = `${RUN}-uid-parked`;
const UID_UNTAGGED = `${RUN}-uid-claim`;
const LEXICAL_EMPTY = {
root: {
children: [{ text: "" }],
direction: null,
format: "" as const,
indent: 0,
type: "text",
version: 1,
},
};
let resourceId: number;
let blueprintId: number;
let structureId: number;
let templateId: number;
let serverId: number;
let parkedId: number;
let untaggedId: number;
const vehicleIds: number[] = [];
const commandIds: number[] = [];
const eventIds: number[] = [];
let eventSeq = 0;
function garageEvent(type: string, eventPayload: unknown[], server: number) {
eventSeq += 1;
return {
id: eventSeq,
eventId: `${RUN}:${eventSeq}`,
server,
type,
occurredAt: new Date().toISOString(),
payload: eventPayload,
};
}
async function vehicleDoc(id: number) {
return (await payload.findByID({
collection: "game-vehicles",
id,
depth: 0,
overrideAccess: true,
})) as GameVehicle;
}
async function findVehicleByUid(uid: string): Promise<GameVehicle | null> {
const found = await payload.find({
collection: "game-vehicles",
where: { bridgeUid: { equals: uid } },
limit: 1,
depth: 0,
overrideAccess: true,
});
return (found.docs[0] as GameVehicle | undefined) ?? null;
}
async function findGarageCommands(type: string) {
const found = await payload.find({
collection: "arma-commands",
where: { type: { equals: type } },
limit: 100,
depth: 0,
overrideAccess: true,
});
return found.docs.filter(
(doc) =>
Array.isArray((doc as { payload?: unknown }).payload) &&
String((doc as { payload: unknown[] }).payload[0]).includes(SLUG),
);
}
describe("Arma garage sync", () => {
beforeAll(async () => {
const payloadConfig = await config;
payload = await getPayload({ config: payloadConfig });
const resource = await payload.create({
collection: "resources",
data: {
name: `${RUN} Fuel`,
codeName: `${RUN}-fuel`,
approvalStatus: "in_progress",
type: "physical",
baseValue: 1,
rarity: "common",
unitOfMeasure: "L",
massPerUnit: 1,
gridWidth: 1,
gridHeight: 1,
} as never,
overrideAccess: true,
depth: 0,
});
resourceId = resource.id;
const blueprint = await payload.create({
collection: "structures",
data: {
name: `${RUN} Motor Pool Blueprint`,
codeName: `${RUN}-mp`,
approvalStatus: "in_progress",
description: LEXICAL_EMPTY,
category: "logistics",
materials: [{ resource: resourceId, amount: 1 }],
constructionDurationMinutes: 1,
terrainType: "land",
maxHealth: 100,
vehicleBay: { xSize: 4, ySize: 3 },
} as never,
overrideAccess: true,
depth: 0,
});
blueprintId = blueprint.id;
const structure = await payload.create({
collection: "game-structures",
data: {
name: `${RUN} Motor Pool`,
type: blueprintId,
constructionStatus: "complete",
storageSlug: SLUG,
} as never,
overrideAccess: true,
depth: 0,
});
structureId = structure.id;
const template = await payload.create({
collection: "vehicles",
data: {
name: `${RUN} Truck Template`,
classname: CLASSNAME,
approvalStatus: "approved",
garageWidth: 2,
garageHeight: 1,
maxHealth: 100,
fuel: { fuelType: resourceId, fuelCapacity: 100, fuelConsumptionRate: 1 },
} as never,
draft: false,
overrideAccess: true,
depth: 0,
});
templateId = template.id;
const parked = await payload.create({
collection: "game-vehicles",
data: {
name: `${RUN} Parked Truck`,
type: templateId,
deployedAt: structureId,
status: "idle",
bridgeUid: UID_PARKED,
garageGridX: 0,
garageGridY: 0,
currentFuel: 80,
currentHealth: 100,
} as never,
overrideAccess: true,
depth: 0,
});
parkedId = parked.id;
vehicleIds.push(parkedId);
// Untagged instance at the same structure: claim-by-classname target.
const untagged = await payload.create({
collection: "game-vehicles",
data: {
name: `${RUN} Untagged Truck`,
type: templateId,
deployedAt: structureId,
status: "idle",
currentFuel: 100,
currentHealth: 100,
} as never,
overrideAccess: true,
depth: 0,
});
untaggedId = untagged.id;
vehicleIds.push(untaggedId);
const server = await payload.create({
collection: "game-servers",
data: { serverId: `${RUN}-srv`, name: `${RUN} Server`, status: "online" },
overrideAccess: true,
depth: 0,
});
serverId = server.id;
});
afterAll(async () => {
if (!payload) return;
for (const id of commandIds) {
await payload.delete({ collection: "arma-commands", id, overrideAccess: true }).catch(() => {});
}
for (const id of eventIds) {
await payload.delete({ collection: "arma-sync-events", id, overrideAccess: true }).catch(() => {});
}
for (const id of vehicleIds) {
await payload.delete({ collection: "game-vehicles", id, overrideAccess: true }).catch(() => {});
}
if (templateId) {
await payload.delete({ collection: "vehicles", id: templateId, overrideAccess: true }).catch(() => {});
}
if (structureId) {
await payload.delete({ collection: "game-structures", id: structureId, overrideAccess: true }).catch(() => {});
}
if (blueprintId) {
await payload.delete({ collection: "structures", id: blueprintId, overrideAccess: true }).catch(() => {});
}
if (resourceId) {
await payload.delete({ collection: "resources", id: resourceId, overrideAccess: true }).catch(() => {});
}
if (serverId) {
await payload.delete({ collection: "game-servers", id: serverId, overrideAccess: true }).catch(() => {});
}
});
describe("garage.deposit", () => {
it("applies fuel/damage to a known instance and preserves its cell", async () => {
await expect(
processGarageEvent(payload, garageEvent("garage.deposit", [`garage:${SLUG}`, UID_PARKED, CLASSNAME, 0.5, 0.25], 1)),
).resolves.toBeUndefined();
const doc = await vehicleDoc(parkedId);
expect(doc.currentFuel).toBe(50);
expect(doc.currentHealth).toBe(75);
expect(doc.garageGridX).toBe(0);
expect(doc.garageGridY).toBe(0);
expect(doc.status).toBe("idle");
});
it("claims an untagged classname match at the structure (first-tag-wins)", async () => {
await processGarageEvent(
payload,
garageEvent("garage.deposit", [`garage:${SLUG}`, UID_UNTAGGED, CLASSNAME, 1, 0], 1),
);
const doc = await vehicleDoc(untaggedId);
expect(doc.bridgeUid).toBe(UID_UNTAGGED);
// Row-major auto-place: (0,0) is taken by the parked truck, so a 2x1
// lands at (2,0).
expect(doc.garageGridX).toBe(2);
expect(doc.garageGridY).toBe(0);
expect(doc.status).toBe("idle");
});
it("creates a new instance for an unknown uid with a known template", async () => {
const uid = `${RUN}-uid-created`;
await processGarageEvent(
payload,
garageEvent("garage.deposit", [`garage:${SLUG}`, uid, CLASSNAME, 0.4, 0], 1),
);
const created = await findVehicleByUid(uid);
expect(created).not.toBeNull();
vehicleIds.push(created!.id);
expect(created!.status).toBe("idle");
expect(created!.currentFuel).toBe(40);
expect(Number(typeof created!.deployedAt === "object" ? created!.deployedAt?.id : created!.deployedAt)).toBe(
structureId,
);
});
it("skips unknown classnames without creating anything", async () => {
const before = await payload.count({
collection: "game-vehicles",
where: { bridgeUid: { exists: true } },
overrideAccess: true,
});
await expect(
processGarageEvent(
payload,
garageEvent("garage.deposit", [`garage:${SLUG}`, `${RUN}-uid-ghost`, "no_such_class", 1, 0], 1),
),
).resolves.toBeUndefined();
const after = await payload.count({
collection: "game-vehicles",
where: { bridgeUid: { exists: true } },
overrideAccess: true,
});
expect(after.totalDocs).toBe(before.totalDocs);
});
it("marks full damage as destroyed", async () => {
await processGarageEvent(
payload,
garageEvent("garage.deposit", [`garage:${SLUG}`, UID_UNTAGGED, CLASSNAME, 0.1, 1], 1),
);
const doc = await vehicleDoc(untaggedId);
expect(doc.status).toBe("destroyed");
expect(doc.currentHealth).toBe(0);
});
});
describe("garage.withdraw", () => {
it("clears cells and deployedAt and sets in_transit", async () => {
await processGarageEvent(
payload,
garageEvent("garage.withdraw", [`garage:${SLUG}`, UID_PARKED, CLASSNAME, 0.4, 0], 1),
);
const doc = await vehicleDoc(parkedId);
expect(doc.garageGridX).toBeNull();
expect(doc.garageGridY).toBeNull();
expect(doc.deployedAt).toBeNull();
expect(doc.status).toBe("in_transit");
expect(doc.bridgeUid).toBe(UID_PARKED);
});
it("skips unknown bridgeUids without throwing", async () => {
await expect(
processGarageEvent(
payload,
garageEvent("garage.withdraw", [`garage:${SLUG}`, `${RUN}-uid-nope`, CLASSNAME, 1, 0], 1),
),
).resolves.toBeUndefined();
});
});
describe("garage.sync snapshot", () => {
it("applies every line and is idempotent (absence is not deletion)", async () => {
const uid = `${RUN}-uid-sync`;
const snapshot = [
[`garage:${SLUG}`, [
[uid, CLASSNAME, 0.9, 0],
[UID_UNTAGGED, CLASSNAME, 0.1, 1],
]],
];
await processGarageEvent(payload, garageEvent("garage.sync", snapshot[0], 1));
const created = await findVehicleByUid(uid);
expect(created).not.toBeNull();
vehicleIds.push(created!.id);
// Re-apply the same snapshot: no duplicates, state unchanged.
await processGarageEvent(payload, garageEvent("garage.sync", snapshot[0], 1));
const found = await payload.find({
collection: "game-vehicles",
where: { bridgeUid: { equals: uid } },
limit: 5,
depth: 0,
overrideAccess: true,
});
expect(found.totalDocs).toBe(1);
// UID_PARKED was absent from the snapshot but keeps its row.
expect((await vehicleDoc(parkedId)).bridgeUid).toBe(UID_PARKED);
});
});
describe("garage.request -> garage.apply", () => {
it("enqueues one apply command with the parked tagged instances", async () => {
await processGarageEvent(payload, garageEvent("garage.request", [`garage:${SLUG}`], serverId));
const commands = await findGarageCommands("garage.apply");
expect(commands).toHaveLength(1);
commandIds.push(Number(commands[0].id));
const [ref, lines] = commands[0].payload as [string, Array<[string, string, number, number]>];
expect(ref).toBe(`garage:${SLUG}`);
const uids = lines.map((line) => line[0]);
expect(uids).toContain(UID_UNTAGGED);
expect(uids).not.toContain(UID_PARKED); // withdrawn, no longer parked
expect(commands[0].server).toBe(serverId);
});
});
describe("router wiring + malformed input", () => {
it("processes a real arma-sync-events row of type garage.deposit", async () => {
const uid = `${RUN}-uid-router`;
const raw = await payload.create({
collection: "arma-sync-events",
data: {
eventId: `${RUN}-router`,
server: serverId,
type: "garage.deposit",
occurredAt: new Date().toISOString(),
payload: [`garage:${SLUG}`, uid, CLASSNAME, 1, 0],
} as never,
overrideAccess: true,
depth: 0,
});
eventIds.push(raw.id);
const created = await findVehicleByUid(uid);
expect(created).not.toBeNull();
vehicleIds.push(created!.id);
});
it("never throws on malformed payloads or unknown refs", async () => {
await expect(processGarageEvent(payload, garageEvent("garage.deposit", [], 1))).resolves.toBeUndefined();
await expect(
processGarageEvent(payload, garageEvent("garage.sync", ["bogus-ref", []], 1)),
).resolves.toBeUndefined();
await expect(
processGarageEvent(payload, garageEvent("garage.sync", [`garage:${RUN}-missing`, []], 1)),
).resolves.toBeUndefined();
await expect(
processGarageEvent(payload, { ...garageEvent("garage.sync", [], 1), payload: "nope" as never }),
).resolves.toBeUndefined();
});
});
});

View file

@ -1,524 +0,0 @@
import { getPayload, Payload } from "payload";
import config from "@/payload.config";
import { afterAll, beforeAll, describe, expect, it, vi, type MockInstance } from "vitest";
import type { GameVehicle, User } from "@/payload-types";
import {
autoArrangeGarageItems,
findGarageEmptySpot,
formatGarageInstanceRef,
getVehicleFootprint,
isGaragePlacementValid,
parseGarageInstanceRef,
type GarageGridItem,
} from "@/lib/garage";
import { canUserAccessStructureStorage } from "@/collections/game/GameStructures";
import {
dispatchVehicle,
moveGarageItem,
rotateGarageItem,
storeVehicle,
} from "@/app/(frontend)/logistics/garage/actions";
// Mock next/headers so the actions' authenticate() can run outside a request.
vi.mock("next/headers", () => ({
headers: async () => new Headers(),
}));
let payload: Payload;
let authSpy: MockInstance;
const RUN = `garage-${Date.now().toString(36)}`;
const SLUG_A = `${RUN}-bay-a`;
const CLASSNAME = `${RUN}-truck`;
const LEXICAL_EMPTY = {
root: {
children: [{ text: "" }],
direction: null,
format: "" as const,
indent: 0,
type: "text",
version: 1,
},
};
// ---------------------------------------------------------------------------
// Fixture tracking for cleanup
// ---------------------------------------------------------------------------
const userIds: number[] = [];
const roleIds: number[] = [];
const vehicleIds: number[] = [];
const commandIds: number[] = [];
const reservationIds: number[] = [];
let resourceId: number;
let blueprintAId: number;
let blueprintBId: number;
let structureAId: number;
let structureBId: number;
let templateId: number;
let serverId: number;
let officerUser: User;
let plainUser: User;
function item(id: string, gridX: number, gridY: number, w: number, h: number, rotated = false): GarageGridItem {
return {
id,
vehicleId: Number(id),
gridX,
gridY,
rotated,
template: { garageWidth: w, garageHeight: h } as GarageGridItem["template"],
};
}
async function makeUser(label: string, roleDocIds?: number[]): Promise<User> {
const user = (await payload.create({
collection: "users",
data: {
username: `${RUN}-${label}`,
discordUsername: `${RUN}-${label}-discord`,
displayName: `${RUN} ${label}`,
steamId: `${RUN}-steam-${label}`,
password: "Test1234",
roles: ["user"],
...(roleDocIds && roleDocIds.length > 0 ? { roleDocs: roleDocIds } : {}),
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
userIds.push(user.id);
return user;
}
async function makeVehicle(data: Record<string, unknown>): Promise<GameVehicle> {
const vehicle = (await payload.create({
collection: "game-vehicles",
data: {
name: `${RUN} Truck`,
type: templateId,
status: "idle",
currentFuel: 100,
currentHealth: 100,
...data,
} as never,
overrideAccess: true,
depth: 0,
})) as unknown as GameVehicle;
vehicleIds.push(vehicle.id);
return vehicle;
}
async function vehicleDoc(id: number) {
return payload.findByID({ collection: "game-vehicles", id, depth: 0, overrideAccess: true });
}
// ---------------------------------------------------------------------------
// Setup / teardown
// ---------------------------------------------------------------------------
beforeAll(async () => {
const payloadConfig = await config;
payload = await getPayload({ config: payloadConfig });
authSpy = vi.spyOn(payload, "auth");
const garageRole = await payload.create({
collection: "roles",
data: {
name: `${RUN} Garage Officer`,
slug: `${RUN}-garage-officer`,
permissions: ["game-vehicles:update"],
} as never,
overrideAccess: true,
depth: 0,
});
roleIds.push(garageRole.id);
officerUser = await makeUser("officer", [garageRole.id]);
plainUser = await makeUser("plain");
const resource = await payload.create({
collection: "resources",
data: {
name: `${RUN} Fuel`,
codeName: `${RUN}-fuel`,
approvalStatus: "in_progress",
type: "physical",
baseValue: 1,
rarity: "common",
unitOfMeasure: "L",
massPerUnit: 1,
gridWidth: 1,
gridHeight: 1,
} as never,
overrideAccess: true,
depth: 0,
});
resourceId = resource.id;
const blueprints = await Promise.all(
[4, 2].map((baySize, i) =>
payload.create({
collection: "structures",
data: {
name: `${RUN} Depot ${i}`,
codeName: `${RUN}-depot-${i}`,
approvalStatus: "in_progress",
description: LEXICAL_EMPTY,
category: "logistics",
materials: [{ resource: resourceId, amount: 1 }],
constructionDurationMinutes: 1,
terrainType: "land",
maxHealth: 100,
vehicleBay: i === 0 ? { xSize: 4, ySize: 4 } : { xSize: baySize, ySize: 2 },
} as never,
overrideAccess: true,
depth: 0,
}),
),
);
blueprintAId = blueprints[0].id;
blueprintBId = blueprints[1].id;
const structureA = await payload.create({
collection: "game-structures",
data: {
name: `${RUN} Motor Pool`,
type: blueprintAId,
constructionStatus: "complete",
storageSlug: SLUG_A,
} as never,
overrideAccess: true,
depth: 0,
});
structureAId = structureA.id;
const structureB = await payload.create({
collection: "game-structures",
data: {
name: `${RUN} Restricted Depot`,
type: blueprintBId,
constructionStatus: "complete",
storageSlug: `${RUN}-bay-b`,
storageAccess: { mode: "users", users: [plainUser.id] },
} as never,
overrideAccess: true,
depth: 0,
});
structureBId = structureB.id;
const template = await payload.create({
collection: "vehicles",
data: {
name: `${RUN} Truck Template`,
classname: CLASSNAME,
approvalStatus: "approved",
garageWidth: 2,
garageHeight: 1,
maxHealth: 100,
fuel: { fuelType: resourceId, fuelCapacity: 100, fuelConsumptionRate: 1 },
} as never,
draft: false,
overrideAccess: true,
depth: 0,
});
templateId = template.id;
const server = await payload.create({
collection: "game-servers",
data: { serverId: `${RUN}-srv`, name: `${RUN} Server`, status: "online" },
overrideAccess: true,
depth: 0,
});
serverId = server.id;
});
afterAll(async () => {
if (!payload) return;
for (const id of commandIds) {
await payload.delete({ collection: "arma-commands", id, overrideAccess: true }).catch(() => {});
}
for (const id of reservationIds) {
await payload
.delete({ collection: "operation-reservations", id, overrideAccess: true })
.catch(() => {});
}
for (const id of vehicleIds) {
await payload.delete({ collection: "game-vehicles", id, overrideAccess: true }).catch(() => {});
}
if (templateId) {
await payload.delete({ collection: "vehicles", id: templateId, overrideAccess: true }).catch(() => {});
}
for (const id of [structureAId, structureBId]) {
if (id) await payload.delete({ collection: "game-structures", id, overrideAccess: true }).catch(() => {});
}
for (const id of [blueprintAId, blueprintBId]) {
if (id) await payload.delete({ collection: "structures", id, overrideAccess: true }).catch(() => {});
}
if (resourceId) {
await payload.delete({ collection: "resources", id: resourceId, overrideAccess: true }).catch(() => {});
}
for (const id of userIds) {
const profiles = await payload
.find({ collection: "profiles", where: { user: { equals: id } }, depth: 0, overrideAccess: true })
.catch(() => ({ docs: [] as { id: number }[] }));
for (const profile of profiles.docs) {
await payload.delete({ collection: "profiles", id: profile.id, overrideAccess: true }).catch(() => {});
}
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
}
for (const id of roleIds) {
await payload.delete({ collection: "roles", id, overrideAccess: true }).catch(() => {});
}
if (serverId) {
await payload.delete({ collection: "game-servers", id: serverId, overrideAccess: true }).catch(() => {});
}
});
// ---------------------------------------------------------------------------
// Pure geometry
// ---------------------------------------------------------------------------
describe("garage geometry", () => {
it("footprint swaps width/height when rotated and defaults to 1x1", () => {
const fp = getVehicleFootprint({ garageWidth: 3, garageHeight: 2 } as never, true);
expect(fp).toEqual({ width: 2, height: 3 });
expect(getVehicleFootprint(null, false)).toEqual({ width: 1, height: 1 });
});
it("rejects overlapping and out-of-bounds placements", () => {
const items = [item("1", 0, 0, 2, 1)];
expect(isGaragePlacementValid(items, "1", 2, 0, 2, 1, 4, 3)).toBe(true);
expect(isGaragePlacementValid(items, null, 1, 0, 2, 1, 4, 3)).toBe(false);
expect(isGaragePlacementValid(items, null, 3, 0, 2, 1, 4, 3)).toBe(false);
expect(isGaragePlacementValid(items, null, 0, 3, 1, 1, 4, 3)).toBe(false);
});
it("finds empty spots row-major and reports overflow on auto-arrange", () => {
const items = [item("1", 0, 0, 2, 1)];
expect(findGarageEmptySpot(items, 1, 1, 4, 2)).toEqual({ x: 2, y: 0 });
const packed = [item("1", 0, 0, 2, 1), item("2", 2, 0, 2, 1)];
expect(findGarageEmptySpot(packed, 2, 1, 4, 1)).toBeNull();
const arranged = autoArrangeGarageItems(
[item("1", 3, 2, 2, 1), item("2", 0, 0, 2, 1), item("3", 1, 1, 2, 1)],
3,
1,
);
expect(arranged.placed).toHaveLength(1);
expect(arranged.overflow).toEqual(["2", "3"]);
});
it("parses and formats garage instance refs (A1)", () => {
expect(formatGarageInstanceRef("motor-pool")).toBe("garage:motor-pool");
expect(parseGarageInstanceRef("garage:motor_pool")).toEqual({ slug: "motor_pool" });
expect(parseGarageInstanceRef("locker:x")).toBeNull();
expect(parseGarageInstanceRef("garage:")).toBeNull();
expect(parseGarageInstanceRef(null)).toBeNull();
});
});
// ---------------------------------------------------------------------------
// storageAccess gating modes (D5)
// ---------------------------------------------------------------------------
describe("canUserAccessStructureStorage", () => {
it("honors anyone, users and roles modes", async () => {
const structureA = await payload.findByID({
collection: "game-structures",
id: structureAId,
depth: 0,
overrideAccess: true,
});
await expect(
canUserAccessStructureStorage(payload, officerUser, structureA as unknown as Record<string, unknown>),
).resolves.toBe(true);
const structureB = await payload.findByID({
collection: "game-structures",
id: structureBId,
depth: 0,
overrideAccess: true,
});
await expect(
canUserAccessStructureStorage(payload, plainUser, structureB as unknown as Record<string, unknown>),
).resolves.toBe(true);
await expect(
canUserAccessStructureStorage(payload, officerUser, structureB as unknown as Record<string, unknown>),
).resolves.toBe(false);
const restrictedRole = await payload.create({
collection: "roles",
data: { name: `${RUN} Depot Crew`, slug: `${RUN}-depot-crew` },
overrideAccess: true,
depth: 0,
});
roleIds.push(restrictedRole.id);
await payload.update({
collection: "game-structures",
id: structureBId,
data: { storageAccess: { mode: "roles", roles: [restrictedRole.id] } } as never,
overrideAccess: true,
depth: 0,
});
const crewUser = await makeUser("crew", [restrictedRole.id]);
const structureBRoles = await payload.findByID({
collection: "game-structures",
id: structureBId,
depth: 0,
overrideAccess: true,
});
await expect(
canUserAccessStructureStorage(payload, crewUser, structureBRoles as unknown as Record<string, unknown>),
).resolves.toBe(true);
await expect(
canUserAccessStructureStorage(payload, plainUser, structureBRoles as unknown as Record<string, unknown>),
).resolves.toBe(false);
});
});
// ---------------------------------------------------------------------------
// Server actions (D6/D7)
// ---------------------------------------------------------------------------
describe("garage server actions", () => {
let vehicle1: GameVehicle; // parked at (0,0)
let vehicle2: GameVehicle; // parked at (2,0)
let vehicle3: GameVehicle; // off-map, for store
let wreck: GameVehicle; // destroyed at (2,2)
let tagged: GameVehicle; // bridgeUid-tagged at (2,1)? placed after moves
beforeAll(async () => {
vehicle1 = await makeVehicle({ deployedAt: structureAId, garageGridX: 0, garageGridY: 0 });
vehicle2 = await makeVehicle({ deployedAt: structureAId, garageGridX: 2, garageGridY: 0 });
vehicle3 = await makeVehicle({ status: "in_transit" });
wreck = await makeVehicle({
status: "destroyed",
deployedAt: structureAId,
garageGridX: 2,
garageGridY: 2,
});
tagged = await makeVehicle({
deployedAt: structureAId,
garageGridX: 0,
garageGridY: 1,
bridgeUid: `${RUN}-uid-5`,
currentFuel: 50,
currentHealth: 100,
});
});
it("rejects users without game-vehicles:update (D6)", async () => {
authSpy.mockResolvedValue({ user: plainUser } as never);
const result = await moveGarageItem(vehicle1.id, 1, 1);
expect(result.success).toBe(false);
expect(result.error).toMatch(/Insufficient permissions/);
});
it("moves a vehicle to a free cell and persists it", async () => {
authSpy.mockResolvedValue({ user: officerUser } as never);
const result = await moveGarageItem(vehicle1.id, 0, 2);
expect(result.success).toBe(true);
const doc = await vehicleDoc(vehicle1.id);
expect(doc.garageGridX).toBe(0);
expect(doc.garageGridY).toBe(2);
});
it("rejects overlapping and out-of-bounds moves", async () => {
authSpy.mockResolvedValue({ user: officerUser } as never);
const overlap = await moveGarageItem(vehicle1.id, 1, 0); // hits vehicle2 at (2,0)
expect(overlap.success).toBe(false);
expect(overlap.error).toMatch(/occupied or out of bounds/i);
const oob = await moveGarageItem(vehicle1.id, 3, 0); // 2-wide truck past x=3
expect(oob.success).toBe(false);
});
it("rotates a parked vehicle in place", async () => {
authSpy.mockResolvedValue({ user: officerUser } as never);
const before = await vehicleDoc(vehicle1.id);
const result = await rotateGarageItem(vehicle1.id);
expect(result.success).toBe(true);
const after = await vehicleDoc(vehicle1.id);
expect(Boolean(after.garageRotated)).toBe(!Boolean(before.garageRotated));
});
it("dispatches an idle tagged vehicle: clears cells + deployedAt, queues garage.dispatch", async () => {
authSpy.mockResolvedValue({ user: officerUser } as never);
const result = await dispatchVehicle(tagged.id);
expect(result.success).toBe(true);
const doc = await vehicleDoc(tagged.id);
expect(doc.status).toBe("in_transit");
expect(doc.garageGridX).toBeNull();
expect(doc.deployedAt).toBeNull();
const commands = await payload.find({
collection: "arma-commands",
where: { type: { equals: "garage.dispatch" } },
limit: 10,
depth: 0,
overrideAccess: true,
});
const command = commands.docs.find(
(c) => Array.isArray(c.payload) && String(c.payload[0]).includes(SLUG_A),
);
expect(command).toBeDefined();
commandIds.push(Number(command!.id));
expect(command!.payload).toEqual([`garage:${SLUG_A}`, `${RUN}-uid-5`, CLASSNAME, 0.5, 0]);
});
it("refuses to dispatch destroyed or reserved vehicles (A4/D10)", async () => {
authSpy.mockResolvedValue({ user: officerUser } as never);
const destroyed = await dispatchVehicle(wreck.id);
expect(destroyed.success).toBe(false);
expect(destroyed.error).toMatch(/Destroyed/);
const reservation = await payload.create({
collection: "operation-reservations",
data: {
reservationKey: `${RUN}-op`,
operationId: `${RUN}-operation`,
status: "reserved",
vehicles: [{ vehicle: vehicle1.id }],
} as never,
overrideAccess: true,
depth: 0,
});
reservationIds.push(reservation.id);
const reserved = await dispatchVehicle(vehicle1.id);
expect(reserved.success).toBe(false);
expect(reserved.error).toMatch(/reserved/i);
});
it("stores a vehicle into the first free row-major cell and queues garage.store", async () => {
authSpy.mockResolvedValue({ user: officerUser } as never);
// Occupied now: vehicle2 (2,0 2x1), wreck (2,2 2x1), vehicle1 rotated at (0,2).
const result = await storeVehicle(vehicle3.id, structureAId);
expect(result.success).toBe(true);
const doc = await vehicleDoc(vehicle3.id);
expect(doc.status).toBe("idle");
expect(doc.garageGridX).toBe(0);
expect(doc.garageGridY).toBe(0);
expect(Number(typeof doc.deployedAt === "object" ? doc.deployedAt?.id : doc.deployedAt)).toBe(
structureAId,
);
// vehicle3 has no bridgeUid, so no garage.store command is queued.
const commands = await payload.find({
collection: "arma-commands",
where: { type: { equals: "garage.store" } },
limit: 10,
depth: 0,
overrideAccess: true,
});
expect(
commands.docs.filter((c) => Array.isArray(c.payload) && String(c.payload[0]).includes(SLUG_A)),
).toHaveLength(0);
});
it("refuses to store destroyed vehicles and respects the target storageAccess gate", async () => {
authSpy.mockResolvedValue({ user: officerUser } as never);
const destroyed = await storeVehicle(wreck.id, structureAId);
expect(destroyed.success).toBe(false);
expect(destroyed.error).toMatch(/Destroyed/);
// structureB is users-restricted to plainUser; the officer passes the
// permission check but fails the storage gate (D5).
const gated = await storeVehicle(vehicle3.id, structureBId);
expect(gated.success).toBe(false);
expect(gated.error).toMatch(/access/i);
});
});