diff --git a/src/app/(frontend)/logistics/game-vehicles/[id]/page.tsx b/src/app/(frontend)/logistics/game-vehicles/[id]/page.tsx index 277d5c40..06a37957 100644 --- a/src/app/(frontend)/logistics/game-vehicles/[id]/page.tsx +++ b/src/app/(frontend)/logistics/game-vehicles/[id]/page.tsx @@ -71,11 +71,11 @@ export default async function GameVehicleDetailPage({ params }: GameVehicleDetai return (
- Back to Vehicles + Back to Garage
diff --git a/src/app/(frontend)/logistics/game-vehicles/page.tsx b/src/app/(frontend)/logistics/game-vehicles/page.tsx index f31f339a..1b20b4f7 100644 --- a/src/app/(frontend)/logistics/game-vehicles/page.tsx +++ b/src/app/(frontend)/logistics/game-vehicles/page.tsx @@ -1,126 +1,10 @@ -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"; +import { redirect } from "next/navigation"; -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 = { - 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 ( -
-
-
- -

Vehicles

-
-

- {vehicles.length} vehicle{vehicles.length !== 1 ? "s" : ""} deployed. -

-
- - {vehicles.length > 0 ? ( -
- {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 ( - - - -
- - - - - {vehicle.name} - - {vehicleType?.name ?? "Unknown type"} - - -
- - {vehicle.status === "in_transit" - ? "In Transit" - : vehicle.status.charAt(0).toUpperCase() + vehicle.status.slice(1)} - -
- -
-
-
-
20 ? "bg-green-500" : "bg-red-500" - }`} - style={{ - width: `${Math.min(100, fuelPercent)}%`, - }} - /> -
- - {vehicle.currentFuel?.toFixed(0)} /{" "} - {vehicleType?.fuel?.fuelCapacity ?? "?"} fuel - -
-
- HP: {vehicle.currentHealth} - {vehicleType?.fuel?.fuelType && - typeof vehicleType.fuel.fuelType === "object" && ( - {vehicleType.fuel.fuelType.name} - )} -
-
- - {vehicleType?.name ?? "Unknown type"} - - - ); - })} -
- ) : ( -
-

No vehicles deployed.

-
- )} -
- ); +/** + * 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"); } diff --git a/src/app/(frontend)/logistics/garage/actions.ts b/src/app/(frontend)/logistics/garage/actions.ts new file mode 100644 index 00000000..21a403de --- /dev/null +++ b/src/app/(frontend)/logistics/garage/actions.ts @@ -0,0 +1,455 @@ +"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 { + 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>, + user: User, +): Promise { + return hasPermission(payload, user, "game-vehicles:update"); +} + +const FORBIDDEN = + "Insufficient permissions. Vehicle logistics personnel can manage the garage."; + +async function loadVehicle(payload: Awaited>, 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>): { + 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) + : 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 { + 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 { + 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 { + 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 { + 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 { + 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))) { + 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, + }; + } +} diff --git a/src/app/(frontend)/logistics/garage/page.tsx b/src/app/(frontend)/logistics/garage/page.tsx new file mode 100644 index 00000000..e49af16a --- /dev/null +++ b/src/app/(frontend)/logistics/garage/page.tsx @@ -0,0 +1,196 @@ +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))) 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(); + 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 ( +
+
+

Garage

+

+ Vehicle bays across all accessible structures. Drag to rearrange parked + instances; use Dispatch and Store for real movement. +

+
+ ({ id: s.id, name: s.name ?? `Structure ${s.id}` }))} + reservation={ + options + ? { + canCreate: canCreateReservation, + options, + canManageLogistics, + currentUserId: user.id, + } + : null + } + /> +
+ ); +} diff --git a/src/components/command-palette/commands/navigation.ts b/src/components/command-palette/commands/navigation.ts index b16c282d..6c4601b2 100644 --- a/src/components/command-palette/commands/navigation.ts +++ b/src/components/command-palette/commands/navigation.ts @@ -218,11 +218,11 @@ export const navigationCommands: NavigationCommand[] = [ shortcut: "G T", }, { - id: "nav:deployed-vehicles", - label: "Deployed Vehicles", + id: "nav:garage", + label: "Garage", icon: Map, - href: "/logistics/game-vehicles", - keywords: ["active", "field"], + href: "/logistics/garage", + keywords: ["vehicle", "bay", "parked", "fleet"], requires: "logistics", }, { diff --git a/src/components/frontend/blocks/sidebarData.ts b/src/components/frontend/blocks/sidebarData.ts index 6a856789..72b0d9ec 100644 --- a/src/components/frontend/blocks/sidebarData.ts +++ b/src/components/frontend/blocks/sidebarData.ts @@ -129,8 +129,8 @@ export const sidebarData = { icon: Package, }, { - title: "Deployed Vehicles", - url: "/logistics/game-vehicles", + title: "Garage", + url: "/logistics/garage", icon: Car, }, { diff --git a/src/components/frontend/garage/GarageGrid.tsx b/src/components/frontend/garage/GarageGrid.tsx new file mode 100644 index 00000000..10288ca0 --- /dev/null +++ b/src/components/frontend/garage/GarageGrid.tsx @@ -0,0 +1,418 @@ +"use client"; + +import { 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); + return ( +
+ {item.thumbnailUrl ? ( + // eslint-disable-next-line @next/next/no-img-element + + ) : ( + + )} + + {item.name} + + {statusTint(item.status) && ( +
+ ); +} + +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 ( + + ); +} + +interface GarageGridProps { + gridWidth: number; + gridHeight: number; + items: GarageVehicleItem[]; + canEdit: boolean; + onMoveItem: ( + vehicleId: number, + gridX: number, + gridY: number, + rotated?: boolean, + ) => Promise; + onSelectItem: (item: GarageVehicleItem | null) => void; + selectedItem: GarageVehicleItem | null; +} + +export function GarageGrid({ + gridWidth, + gridHeight, + items, + canEdit, + onMoveItem, + onSelectItem, + selectedItem, +}: GarageGridProps) { + const [activeItem, setActiveItem] = useState(null); + const [hoverPosition, setHoverPosition] = useState<{ x: number; y: number } | null>(null); + const [pendingRotated, setPendingRotated] = useState(false); + const [cellSize, setCellSize] = useState(64); + const gridRef = useRef(null); + const containerRef = useRef(null); + + // Responsive cell size: fit the bay width into the container. + useEffect(() => { + const el = containerRef.current; + if (!el) return; + const observer = new ResizeObserver((entries) => { + const width = entries[0]?.contentRect.width ?? 0; + if (width > 0) { + setCellSize(Math.max(40, Math.min(96, Math.floor(width / 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(); + 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); + } + }; + + return ( + +
+
+
+
+ {Array.from({ length: gridHeight }).map((_, y) => + Array.from({ length: gridWidth }).map((__, x) => { + const key = `${x},${y}`; + return ( + + ); + }), + )} + {items.map((item) => ( + + ))} +
+
+
+
+ {items.length} parked + + bay {gridWidth} × {gridHeight} + + {canEdit && drag to move · R to rotate} +
+
+ + {activeItem ? ( +
+ +
+ ) : null} +
+
+ ); +} diff --git a/src/components/frontend/garage/GarageView.tsx b/src/components/frontend/garage/GarageView.tsx new file mode 100644 index 00000000..5a5321aa --- /dev/null +++ b/src/components/frontend/garage/GarageView.tsx @@ -0,0 +1,438 @@ +"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 = { + idle: "Idle", + assigned: "Assigned", + in_transit: "In transit", + damaged: "Damaged", + destroyed: "Destroyed", +}; + +function StatusBadge({ status }: { status: GarageVehicleItem["status"] }) { + return ( + + {STATUS_LABELS[status]} + + ); +} + +/** Dossier classification-strip header shared by garage + elsewhere sections. */ +function SectionHeader({ + kicker, + title, + action, +}: { + kicker: string; + title: string; + action?: React.ReactNode; +}) { + return ( +
+
+ + {kicker} + +

{title}

+
+ {action} +
+ ); +} + +function ReadoutCell({ label, value }: { label: string; value: string }) { + return ( +
+
{label}
+
{value}
+
+ ); +} + +function CornerBrackets() { + return ( +