feat: add list+create+close UI for MaintenanceRecord

Mirrors assignments/page.tsx's per-row close mini-form pattern; targetStatus
select reuses the closed AssetItemStatus set client-side, same precedent as
licenses page's licenseType select.
This commit is contained in:
toanhoang
2026-08-04 10:23:50 -04:00
parent 651ff2d626
commit 74e78322b4
2 changed files with 416 additions and 0 deletions
+415
View File
@@ -0,0 +1,415 @@
"use client";
import { useState, type FormEvent } from "react";
import { useApiList } from "@/hooks/use-api-list";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
// Shape returned by GET /api/maintenance-records — snake_case per this
// repo's API-boundary convention (see src/lib/maintenance-records.ts's
// toRecord()). An "open" record is one where end_date is null.
interface MaintenanceRecordRecord {
id: string;
asset_item_id: string;
type: "repair" | "warranty" | "preventive";
vendor_id: string | null;
issue_description: string;
resolution_notes: string | null;
start_date: string;
end_date: string | null;
created_at: string;
}
// Shape returned by GET /api/assets — only the field used to populate the
// assetItemId <Select> here (see src/app/assets/page.tsx's AssetItemRecord
// for the full shape).
interface AssetItemRecord {
id: string;
serial_number: string;
}
// Shape returned by GET /api/vendors — only the field used to populate the
// vendorId <Select> here (see src/app/vendors/page.tsx's VendorRecord for
// the full shape).
interface VendorRecord {
id: string;
name: string;
}
// The 4 AssetItemStatus enum values, reused verbatim as the targetStatus
// <Select>'s option list — mirrors src/lib/maintenance-records.ts's own
// assetItemStatusValues constant (not re-derived from an API call, this is
// a closed set already known client-side, same precedent as licenses
// page's licenseType/perpetual|subscription <Select>).
const ASSET_ITEM_STATUS_VALUES = ["in_stock", "assigned", "repair", "retired"] as const;
// Radix <Select.Item> can't take an empty-string value, so "no vendor" is
// represented by this sentinel in the form state and translated to "omit
// the key" on submit — same pattern as licenses page's
// NO_PURCHASE_ORDER_VALUE / employees page's NO_MANAGER_VALUE.
const NO_VENDOR_VALUE = "none";
function todayDateString(): string {
return new Date().toISOString().slice(0, 10);
}
export default function MaintenanceRecordsPage() {
const {
data: maintenanceRecords,
loading,
error,
refetch,
} = useApiList<MaintenanceRecordRecord>("/api/maintenance-records");
const { data: assetItems } = useApiList<AssetItemRecord>("/api/assets");
const { data: vendors } = useApiList<VendorRecord>("/api/vendors");
const [assetItemId, setAssetItemId] = useState("");
const [type, setType] = useState("");
const [vendorId, setVendorId] = useState(NO_VENDOR_VALUE);
const [issueDescription, setIssueDescription] = useState("");
const [startDate, setStartDate] = useState("");
const [submitting, setSubmitting] = useState(false);
const [submitError, setSubmitError] = useState<string | null>(null);
// Per-row close mini-form state, keyed by maintenance record id — kept as
// separate maps (rather than one nested-object map) to keep each field's
// setter a plain string setter, same shape as returnErrors/returningId on
// assignments/page.tsx which this page mirrors.
const [closeEndDate, setCloseEndDate] = useState<Record<string, string>>({});
const [closeResolutionNotes, setCloseResolutionNotes] = useState<Record<string, string>>({});
const [closeTargetStatus, setCloseTargetStatus] = useState<Record<string, string>>({});
const [closeErrors, setCloseErrors] = useState<Record<string, string>>({});
const [closingId, setClosingId] = useState<string | null>(null);
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setSubmitError(null);
setSubmitting(true);
try {
const response = await fetch("/api/maintenance-records", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
assetItemId,
type,
issueDescription,
startDate,
// Omit the key entirely when left unselected, rather than sending
// null — matches licenses page's purchaseOrderId pattern.
...(vendorId !== NO_VENDOR_VALUE ? { vendorId } : {}),
}),
});
let body: unknown;
try {
body = await response.json();
} catch {
body = null;
}
if (!response.ok) {
const message =
body !== null &&
typeof body === "object" &&
"error" in body &&
typeof (body as { error: unknown }).error === "string"
? (body as { error: string }).error
: "Request failed";
setSubmitError(message);
return;
}
setAssetItemId("");
setType("");
setVendorId(NO_VENDOR_VALUE);
setIssueDescription("");
setStartDate("");
refetch();
} catch {
setSubmitError("Request failed");
} finally {
setSubmitting(false);
}
}
async function handleClose(id: string) {
setClosingId(id);
setCloseErrors((previous) => {
const next = { ...previous };
delete next[id];
return next;
});
const endDate = closeEndDate[id] ?? todayDateString();
const resolutionNotes = closeResolutionNotes[id] ?? "";
const targetStatus = closeTargetStatus[id] ?? "";
try {
// PATCH /api/maintenance-records/[id]'s body is
// `{endDate, resolutionNotes?, targetStatus}` — see src/lib/
// maintenance-records.ts's validateCloseMaintenanceRecordInput().
// Unlike Assignment's returnedAt, targetStatus is REQUIRED and never
// defaulted server-side, so it's always sent here (an empty string
// if unselected, which the server rejects with a clean 400 message
// surfaced below, same as any other validation failure).
const response = await fetch(`/api/maintenance-records/${id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
endDate,
targetStatus,
...(resolutionNotes.trim() !== "" ? { resolutionNotes } : {}),
}),
});
let body: unknown;
try {
body = await response.json();
} catch {
body = null;
}
if (!response.ok) {
const message =
body !== null &&
typeof body === "object" &&
"error" in body &&
typeof (body as { error: unknown }).error === "string"
? (body as { error: string }).error
: "Request failed";
setCloseErrors((previous) => ({ ...previous, [id]: message }));
return;
}
setCloseEndDate((previous) => {
const next = { ...previous };
delete next[id];
return next;
});
setCloseResolutionNotes((previous) => {
const next = { ...previous };
delete next[id];
return next;
});
setCloseTargetStatus((previous) => {
const next = { ...previous };
delete next[id];
return next;
});
refetch();
} catch {
setCloseErrors((previous) => ({ ...previous, [id]: "Request failed" }));
} finally {
setClosingId(null);
}
}
return (
<div className="flex flex-col gap-8 p-6">
<h1 className="text-xl font-semibold">Maintenance Records</h1>
<section className="flex flex-col gap-3">
{loading ? (
<p className="text-sm text-muted-foreground">Loading...</p>
) : error ? (
<p className="text-sm text-destructive">{error}</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>ID</TableHead>
<TableHead>Asset Item ID</TableHead>
<TableHead>Type</TableHead>
<TableHead>Vendor ID</TableHead>
<TableHead>Issue Description</TableHead>
<TableHead>Resolution Notes</TableHead>
<TableHead>Start Date</TableHead>
<TableHead>End Date</TableHead>
<TableHead>Created At</TableHead>
<TableHead>Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{maintenanceRecords.map((record) => (
<TableRow key={record.id}>
<TableCell>{record.id}</TableCell>
<TableCell>{record.asset_item_id}</TableCell>
<TableCell>{record.type}</TableCell>
<TableCell>{record.vendor_id ?? "-"}</TableCell>
<TableCell>{record.issue_description}</TableCell>
<TableCell>{record.resolution_notes ?? "-"}</TableCell>
<TableCell>{record.start_date}</TableCell>
<TableCell>{record.end_date ?? "-"}</TableCell>
<TableCell>{record.created_at}</TableCell>
<TableCell>
{record.end_date === null ? (
<div className="flex w-56 flex-col gap-1">
<Input
type="date"
aria-label="End date"
value={closeEndDate[record.id] ?? todayDateString()}
onChange={(event) =>
setCloseEndDate((previous) => ({
...previous,
[record.id]: event.target.value,
}))
}
/>
<Input
type="text"
placeholder="Resolution notes (optional)"
value={closeResolutionNotes[record.id] ?? ""}
onChange={(event) =>
setCloseResolutionNotes((previous) => ({
...previous,
[record.id]: event.target.value,
}))
}
/>
<Select
value={closeTargetStatus[record.id] ?? ""}
onValueChange={(value) =>
setCloseTargetStatus((previous) => ({
...previous,
[record.id]: value,
}))
}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="Target status" />
</SelectTrigger>
<SelectContent>
{ASSET_ITEM_STATUS_VALUES.map((status) => (
<SelectItem key={status} value={status}>
{status}
</SelectItem>
))}
</SelectContent>
</Select>
<Button
type="button"
size="sm"
variant="outline"
disabled={closingId === record.id}
onClick={() => handleClose(record.id)}
>
{closingId === record.id ? "Closing..." : "Close"}
</Button>
{closeErrors[record.id] ? (
<p className="text-xs text-destructive">
{closeErrors[record.id]}
</p>
) : null}
</div>
) : (
"-"
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</section>
<section className="flex max-w-sm flex-col gap-4">
<h2 className="text-lg font-semibold">New Maintenance Record</h2>
<form className="flex flex-col gap-4" onSubmit={handleSubmit}>
<div className="flex flex-col gap-2">
<Label htmlFor="assetItemId">Asset Item</Label>
<Select value={assetItemId} onValueChange={setAssetItemId} required>
<SelectTrigger id="assetItemId" className="w-full">
<SelectValue placeholder="Select an asset item" />
</SelectTrigger>
<SelectContent>
{assetItems.map((assetItem) => (
<SelectItem key={assetItem.id} value={assetItem.id}>
{assetItem.serial_number}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="type">Type</Label>
<Select value={type} onValueChange={setType} required>
<SelectTrigger id="type" className="w-full">
<SelectValue placeholder="Select a type" />
</SelectTrigger>
<SelectContent>
<SelectItem value="repair">repair</SelectItem>
<SelectItem value="warranty">warranty</SelectItem>
<SelectItem value="preventive">preventive</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="vendorId">Vendor (optional)</Label>
<Select value={vendorId} onValueChange={setVendorId}>
<SelectTrigger id="vendorId" className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value={NO_VENDOR_VALUE}>None</SelectItem>
{vendors.map((vendor) => (
<SelectItem key={vendor.id} value={vendor.id}>
{vendor.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="issueDescription">Issue Description</Label>
<Textarea
id="issueDescription"
value={issueDescription}
onChange={(event) => setIssueDescription(event.target.value)}
required
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="startDate">Start Date</Label>
<Input
id="startDate"
type="date"
value={startDate}
onChange={(event) => setStartDate(event.target.value)}
required
/>
</div>
{submitError ? <p className="text-sm text-destructive">{submitError}</p> : null}
<Button type="submit" disabled={submitting}>
{submitting ? "Creating..." : "Create Maintenance Record"}
</Button>
</form>
</section>
</div>
);
}
+1
View File
@@ -21,6 +21,7 @@ const ENTITY_LINKS = [
{ href: "/purchase-orders", label: "Purchase Orders" }, { href: "/purchase-orders", label: "Purchase Orders" },
{ href: "/requests", label: "Requests" }, { href: "/requests", label: "Requests" },
{ href: "/assignments", label: "Assignments" }, { href: "/assignments", label: "Assignments" },
{ href: "/maintenance-records", label: "Maintenance Records" },
] as const; ] as const;
export function Nav() { export function Nav() {