1
0
Fork 0
polaris-task-force/src/components/frontend/operations/reservations/CreateReservationDialog.tsx

541 lines
19 KiB
TypeScript

"use client";
import { useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { Check, ChevronDown, PlusIcon, TrashIcon } from "lucide-react";
import { Combobox, type ComboboxOption } from "@/components/ui/combobox";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import type { ReservationOptions } from "@/lib/operations/reservationOptions";
import { createReservation } from "@/app/(frontend)/operations/reservations/actions";
interface CreateReservationDialogProps {
options: ReservationOptions;
canManageLogistics: boolean;
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 {
resourceId: string;
amount: string;
}
/**
* Searchable multi-value picker built on the same Command/Popover primitives as
* the site Combobox, which is single-value only. Selections persist in a number
* array; the popover stays as wide as the trigger.
*/
function MultiSelect({
label,
options,
selected,
onChange,
disabled,
placeholder = "None selected",
}: {
label: string;
options: ComboboxOption[];
selected: number[];
onChange: (value: number[]) => void;
disabled?: boolean;
placeholder?: string;
}) {
const [open, setOpen] = useState(false);
const selectedLabels = useMemo(
() => options.filter((o) => selected.includes(Number(o.value))).map((o) => o.label),
[options, selected],
);
return (
<Popover open={open} onOpenChange={(next) => !disabled && setOpen(next)}>
<PopoverTrigger
disabled={disabled}
role="combobox"
aria-expanded={open}
className="flex h-9 w-full items-center justify-between gap-2 rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50"
>
<span className="truncate text-left flex-1">
{selectedLabels.length > 0 ? selectedLabels.join(", ") : placeholder}
</span>
<ChevronDown className="size-4 shrink-0 opacity-50" aria-hidden />
</PopoverTrigger>
<PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0" align="start">
<Command shouldFilter>
<CommandInput placeholder="Search..." />
<CommandList className="max-h-64">
<CommandEmpty>Nothing found.</CommandEmpty>
<CommandGroup>
{options.map((option) => {
const value = Number(option.value);
const isSelected = selected.includes(value);
return (
<CommandItem
key={option.value}
value={option.value}
onSelect={() => {
onChange(
isSelected
? selected.filter((v) => v !== value)
: [...selected, value].sort((a, b) => a - b),
);
}}
>
<Checkbox checked={isSelected} />
<span className="ml-2 min-w-0 block truncate">{option.label}</span>
</CommandItem>
);
})}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
}
export function CreateReservationDialog({
options,
canManageLogistics,
currentUserId,
canCreate,
initialVehicleIds,
triggerLabel,
}: CreateReservationDialogProps) {
const router = useRouter();
const [open, setOpen] = useState(false);
const [reservationKey, setReservationKey] = useState("");
const [operationId, setOperationId] = useState("");
const [missionId, setMissionId] = useState("");
const [personnel, setPersonnel] = useState<number[]>([]);
const [vehicles, setVehicles] = useState<number[]>(initialVehicleIds ?? []);
const [originId, setOriginId] = useState("");
const [destinationId, setDestinationId] = useState("");
const [cargoLines, setCargoLines] = useState<CargoLine[]>([]);
const [budgetAccountId, setBudgetAccountId] = useState("");
const [budgetAmount, setBudgetAmount] = useState("");
const [expiresAt, setExpiresAt] = useState("");
const [error, setError] = useState<string | null>(null);
const [submitting, setSubmitting] = useState(false);
const missionOptions: ComboboxOption[] = options.upcomingMissions.map((m) => ({
value: String(m.id),
label: m.name + (m.codeName ? ` (${m.codeName})` : ""),
}));
const vehicleOptions: ComboboxOption[] = options.vehicles.map((v) => ({
value: String(v.id),
label: v.name,
hint: `${v.fuelPct}% fuel`,
}));
const rosterOptions: ComboboxOption[] = options.rosterUsers.map((u) => ({
value: String(u.id),
label: u.displayName,
}));
const originOptions: ComboboxOption[] = options.originStructures.map((s) => ({
value: String(s.id),
label: s.name,
}));
const destinationOptions: ComboboxOption[] = options.destinationStructures.map((s) => ({
value: String(s.id),
label: s.name,
}));
const budgetOptions: ComboboxOption[] = options.budgetAccounts.map((a) => ({
value: String(a.id),
label: a.name,
hint: a.type,
}));
const originStock = originId ? options.stockByOrigin[originId] ?? [] : [];
function reset() {
setReservationKey("");
setOperationId("");
setMissionId("");
setPersonnel([]);
setVehicles(initialVehicleIds ?? []);
setOriginId("");
setDestinationId("");
setCargoLines([]);
setBudgetAccountId("");
setBudgetAmount("");
setExpiresAt("");
setError(null);
}
function updateCargo(index: number, patch: Partial<CargoLine>) {
setCargoLines((lines) =>
lines.map((line, i) => (i === index ? { ...line, ...patch } : line)),
);
}
function addCargoLine() {
setCargoLines((lines) => [...lines, { resourceId: "", amount: "" }]);
}
function removeCargoLine(index: number) {
setCargoLines((lines) => lines.filter((_, i) => i !== index));
}
/**
* Client-side sanity checks only. The server action re-validates every limit
* and is the source of truth; these give the form immediate feedback before
* the request goes out.
*/
function clientErrors(): string[] {
const errors: string[] = [];
if (!reservationKey.trim()) errors.push("A reservation key is required.");
if (!operationId.trim()) errors.push("An operation id is required.");
for (const [i, line] of cargoLines.entries()) {
const amount = Number(line.amount);
if (line.resourceId && (!Number.isInteger(amount) || amount <= 0)) {
errors.push(`Cargo amount on line ${i + 1} must be a positive integer.`);
}
}
if (cargoLines.some((l) => l.resourceId) && !originId) {
errors.push("An origin structure is required when cargo is reserved.");
}
if (budgetAmount && (!Number.isInteger(Number(budgetAmount)) || Number(budgetAmount) <= 0)) {
errors.push("Budget amount must be a positive integer.");
}
return errors;
}
async function handleSubmit() {
const problems = clientErrors();
if (problems.length > 0) {
setError(problems.join(" "));
return;
}
setSubmitting(true);
setError(null);
const result = await createReservation({
reservationKey: reservationKey.trim(),
operationId: operationId.trim(),
actorId: currentUserId,
...(missionId ? { missionId: Number(missionId) } : {}),
...(personnel.length ? { personnel: personnel.map((id) => ({ userId: id })) } : {}),
...(vehicles.length ? { vehicleIds: [...vehicles] } : {}),
...(cargoLines
.filter((l) => l.resourceId && Number(l.amount) > 0)
.length
? {
cargo: cargoLines
.filter((l) => l.resourceId && Number(l.amount) > 0)
.map((l) => ({ resourceId: Number(l.resourceId), amount: Number(l.amount) })),
}
: {}),
...(budgetAmount ? { budget: { accountId: Number(budgetAccountId), amount: Number(budgetAmount) } } : {}),
...(originId ? { originId: Number(originId) } : {}),
...(destinationId ? { destinationId: Number(destinationId) } : {}),
...(expiresAt ? { expiresAt: new Date(expiresAt).toISOString() } : {}),
});
if (result.success) {
setOpen(false);
reset();
router.refresh();
} else {
// Surface the engine's error string verbatim; the server action never
// rewords the allocation-rejected message.
setError(result.error ?? "Failed to create reservation.");
setSubmitting(false);
}
}
return (
<Dialog open={open} onOpenChange={(next) => { setOpen(next); if (!next) reset(); }}>
{canCreate ? (
<DialogTrigger asChild>
<Button size="sm">
<PlusIcon className="size-4" />
{triggerLabel ?? "New Reservation"}
</Button>
</DialogTrigger>
) : null}
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>Reserve Operation Assets</DialogTitle>
<DialogDescription>
earmark people, vehicles, cargo, and treasury budget against an operation. Capacity and
funds are enforced server-side.
</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-4">
<div className="flex gap-3">
<div className="flex flex-1 flex-col gap-1.5">
<Label htmlFor="reservationKey">Reservation key</Label>
<Input
id="reservationKey"
value={reservationKey}
onChange={(e) => setReservationKey(e.target.value)}
placeholder="e.g. op-24-alpha"
/>
</div>
<div className="flex flex-1 flex-col gap-1.5">
<Label htmlFor="operationId">Operation id</Label>
<Input
id="operationId"
value={operationId}
onChange={(e) => setOperationId(e.target.value)}
placeholder="e.g. operation-id"
/>
</div>
</div>
<div className="flex flex-col gap-1.5">
<Label>Mission (optional)</Label>
<Combobox
value={missionId}
onValueChange={setMissionId}
placeholder="Attach to a mission"
searchPlaceholder="Search missions..."
emptyMessage="No upcoming unit missions."
options={missionOptions}
/>
</div>
<div className="flex flex-col gap-1.5">
<Label>Personnel (optional)</Label>
<MultiSelect
label="Personnel"
options={rosterOptions}
selected={personnel}
onChange={setPersonnel}
placeholder="Select unit members"
/>
</div>
{!canManageLogistics ? (
<SectionGated hint="Logistics qualification required to reserve vehicles and cargo.">
<Label>Vehicles</Label>
<MultiSelect
label="Vehicles"
options={vehicleOptions}
selected={vehicles}
onChange={setVehicles}
disabled
placeholder="Request logistics access to reserve vehicles"
/>
</SectionGated>
) : (
<div className="flex flex-col gap-1.5">
<Label>Vehicles (optional)</Label>
<MultiSelect
label="Vehicles"
options={vehicleOptions}
selected={vehicles}
onChange={setVehicles}
placeholder="Select idle vehicles"
/>
</div>
)}
<div className="flex flex-col gap-1.5">
<Label htmlFor="origin">Origin structure (when reserving cargo)</Label>
<Combobox
id="origin"
value={originId}
onValueChange={setOriginId}
placeholder="No origin"
searchPlaceholder="Search structures..."
emptyMessage="No operational structures."
options={originOptions}
/>
</div>
{canManageLogistics ? (
<SectionGated>
<div className="flex items-center justify-between">
<Label>Cargo lines</Label>
<Button type="button" variant="ghost" size="sm" onClick={addCargoLine}>
<PlusIcon className="size-4" />
Add line
</Button>
</div>
{cargoLines.length === 0 ? (
<p className="text-xs text-muted-foreground">No cargo reserved.</p>
) : (
<div className="flex flex-col gap-2">
{cargoLines.map((line, index) => (
<div key={index} className="flex items-end gap-2">
<div className="flex flex-1 flex-col gap-1.5">
<Label htmlFor={`resource-${index}`}>Resource</Label>
{originStock.length > 0 ? (
<Combobox
value={line.resourceId}
onValueChange={(v) => updateCargo(index, { resourceId: v })}
searchPlaceholder="Search resources..."
emptyMessage="Nothing stored at this origin."
options={originStock.map((s) => ({
value: String(s.resourceId),
label: s.resourceName,
hint: `${s.amount.toLocaleString()} available`,
}))}
/>
) : (
<p className="text-xs text-muted-foreground">
Select an origin to choose resources.
</p>
)}
</div>
<div className="flex w-24 flex-col gap-1.5">
<Label htmlFor={`amount-${index}`}>Amount</Label>
<Input
id={`amount-${index}`}
type="number"
min={1}
value={line.amount}
onChange={(e) => updateCargo(index, { amount: e.target.value })}
/>
</div>
<Button
type="button"
variant="ghost"
size="icon"
className="shrink-0"
onClick={() => removeCargoLine(index)}
aria-label="Remove cargo line"
>
<TrashIcon className="size-4" />
</Button>
</div>
))}
</div>
)}
</SectionGated>
) : (
<SectionGated hint="Logistics qualification required to reserve cargo.">
<Label>Cargo lines</Label>
<p className="text-xs text-muted-foreground">Disabled until logistics access is granted.</p>
</SectionGated>
)}
<div className="flex flex-col gap-1.5">
<Label htmlFor="destination">Destination structure (optional)</Label>
<Combobox
id="destination"
value={destinationId}
onValueChange={setDestinationId}
placeholder="No destination"
searchPlaceholder="Search structures..."
emptyMessage="No operational structures."
options={destinationOptions}
/>
</div>
{canManageLogistics ? (
<div className="flex gap-3">
<div className="flex flex-1 flex-col gap-1.5">
<Label htmlFor="budgetAccount">Budget account (optional)</Label>
<Combobox
value={budgetAccountId}
onValueChange={setBudgetAccountId}
placeholder="No budget"
searchPlaceholder="Search accounts..."
emptyMessage="No accounts available."
options={budgetOptions}
/>
</div>
<div className="flex w-40 flex-col gap-1.5">
<Label htmlFor="budgetAmount">Amount</Label>
<Input
id="budgetAmount"
type="number"
min={1}
value={budgetAmount}
onChange={(e) => setBudgetAmount(e.target.value)}
/>
</div>
</div>
) : (
<SectionGated hint="Logistics qualification required to allocate budget.">
<Label htmlFor="budgetAccount">Budget account (optional)</Label>
<Combobox
id="budgetAccount"
value={budgetAccountId}
onValueChange={setBudgetAccountId}
placeholder="No budget"
searchPlaceholder="Search accounts..."
emptyMessage="No accounts available."
options={budgetOptions}
disabled
/>
</SectionGated>
)}
<div className="flex flex-col gap-1.5">
<Label htmlFor="expiresAt">Expiry (optional)</Label>
<Input
id="expiresAt"
type="datetime-local"
value={expiresAt}
onChange={(e) => setExpiresAt(e.target.value)}
/>
</div>
{error && <p className="text-sm text-red-400" role="alert">{error}</p>}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setOpen(false)}>
Cancel
</Button>
<Button onClick={handleSubmit} disabled={submitting}>
{submitting ? "Reserving..." : "Reserve assets"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
/**
* Wrapper that disables a form section for users without logistics access and
* shows why. UX-only gating; the server action is the source of truth.
*/
function SectionGated({
hint,
children,
}: {
hint?: string;
children: React.ReactNode;
}) {
return (
<div className="rounded-md border border-dashed border-border/60 px-3 py-2 opacity-60">
{hint ? <p className="mb-2 text-xs text-amber-300">{hint}</p> : null}
<div className="pointer-events-none">{children}</div>
</div>
);
}