feat: add basic list+create UI for AssetCategoryAttributeDef, AssetModel, PurchaseOrder

This commit is contained in:
toanhoang
2026-08-03 07:09:42 -04:00
parent 4bcd4da11b
commit e471ae9c90
3 changed files with 736 additions and 0 deletions
@@ -0,0 +1,256 @@
"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 {
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/asset-category-attribute-defs — snake_case per
// this repo's API-boundary convention (see
// src/lib/asset-category-attribute-defs.ts's toRecord()).
interface AssetCategoryAttributeDefRecord {
id: string;
category_id: string;
key: string;
label: string;
data_type: "string" | "number" | "boolean" | "date";
required: boolean;
sort_order: number;
created_at: string;
}
// Shape returned by GET /api/asset-categories — snake_case per
// src/lib/asset-categories.ts's toRecord(). Only used here to populate the
// categoryId <Select> options.
interface AssetCategoryRecord {
id: string;
name: string;
value_group: "high_value" | "low_value";
created_at: string;
}
// Fixed 4-value set — mirrors src/lib/asset-category-attribute-defs.ts's
// dataType z.enum() literal values exactly.
const DATA_TYPE_OPTIONS = ["string", "number", "boolean", "date"] as const;
export default function AssetCategoryAttributeDefsPage() {
const {
data: attributeDefs,
loading,
error,
refetch,
} = useApiList<AssetCategoryAttributeDefRecord>("/api/asset-category-attribute-defs");
const { data: assetCategories } = useApiList<AssetCategoryRecord>("/api/asset-categories");
const [categoryId, setCategoryId] = useState("");
const [key, setKey] = useState("");
const [label, setLabel] = useState("");
const [dataType, setDataType] = useState<(typeof DATA_TYPE_OPTIONS)[number]>("string");
const [required, setRequired] = useState(false);
const [sortOrder, setSortOrder] = useState("0");
const [submitting, setSubmitting] = useState(false);
const [submitError, setSubmitError] = useState<string | null>(null);
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setSubmitting(true);
setSubmitError(null);
try {
const response = await fetch("/api/asset-category-attribute-defs", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
categoryId,
key,
label,
dataType,
required,
sortOrder: Number(sortOrder),
}),
});
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;
}
setCategoryId("");
setKey("");
setLabel("");
setDataType("string");
setRequired(false);
setSortOrder("0");
refetch();
} catch {
setSubmitError("Request failed");
} finally {
setSubmitting(false);
}
}
return (
<div className="flex flex-col gap-8 p-6">
<h1 className="text-xl font-semibold">Asset Category Attribute Defs</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>Category ID</TableHead>
<TableHead>Key</TableHead>
<TableHead>Label</TableHead>
<TableHead>Data Type</TableHead>
<TableHead>Required</TableHead>
<TableHead>Sort Order</TableHead>
<TableHead>Created At</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{attributeDefs.map((attributeDef) => (
<TableRow key={attributeDef.id}>
<TableCell>{attributeDef.id}</TableCell>
<TableCell>{attributeDef.category_id}</TableCell>
<TableCell>{attributeDef.key}</TableCell>
<TableCell>{attributeDef.label}</TableCell>
<TableCell>{attributeDef.data_type}</TableCell>
<TableCell>{attributeDef.required ? "Yes" : "No"}</TableCell>
<TableCell>{attributeDef.sort_order}</TableCell>
<TableCell>{attributeDef.created_at}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</section>
<section className="flex max-w-sm flex-col gap-4">
<h2 className="text-lg font-semibold">New Asset Category Attribute Def</h2>
<form className="flex flex-col gap-4" onSubmit={handleSubmit}>
<div className="flex flex-col gap-2">
<Label htmlFor="categoryId">Category</Label>
<Select value={categoryId} onValueChange={setCategoryId}>
<SelectTrigger id="categoryId" className="w-full">
<SelectValue placeholder="Select a category" />
</SelectTrigger>
<SelectContent>
{assetCategories.map((assetCategory) => (
<SelectItem key={assetCategory.id} value={assetCategory.id}>
{assetCategory.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="key">Key</Label>
<Input
id="key"
value={key}
onChange={(event) => setKey(event.target.value)}
required
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="label">Label</Label>
<Input
id="label"
value={label}
onChange={(event) => setLabel(event.target.value)}
required
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="dataType">Data Type</Label>
<Select
value={dataType}
onValueChange={(value) =>
setDataType(value as (typeof DATA_TYPE_OPTIONS)[number])
}
>
<SelectTrigger id="dataType" className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
{DATA_TYPE_OPTIONS.map((option) => (
<SelectItem key={option} value={option}>
{option}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex items-center gap-2">
<input
id="required"
type="checkbox"
checked={required}
onChange={(event) => setRequired(event.target.checked)}
className="h-4 w-4"
/>
<Label htmlFor="required">Required</Label>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="sortOrder">Sort Order</Label>
<Input
id="sortOrder"
type="number"
value={sortOrder}
onChange={(event) => setSortOrder(event.target.value)}
required
/>
</div>
{submitError ? <p className="text-sm text-destructive">{submitError}</p> : null}
<Button type="submit" disabled={submitting}>
{submitting ? "Creating..." : "Create Attribute Def"}
</Button>
</form>
</section>
</div>
);
}
+222
View File
@@ -0,0 +1,222 @@
"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/asset-models — snake_case per this repo's
// API-boundary convention (see src/lib/asset-models.ts's toRecord()).
interface AssetModelRecord {
id: string;
category_id: string;
manufacturer: string;
name: string;
specs: Record<string, unknown>;
created_at: string;
}
// Shape returned by GET /api/asset-categories — used only to populate the
// categoryId <Select> here, not rendered as its own table. Deliberately NOT
// filtered to valueGroup=high_value client-side: the server
// (createAssetModel() in src/lib/asset-models.ts) enforces that rule and
// returns a clear {error} message if violated, which this page surfaces
// verbatim via submitError instead of duplicating the rule client-side.
interface AssetCategoryRecord {
id: string;
name: string;
value_group: "high_value" | "low_value";
created_at: string;
}
const DEFAULT_SPECS_TEXT = "{}";
export default function AssetModelsPage() {
const {
data: assetModels,
loading,
error,
refetch,
} = useApiList<AssetModelRecord>("/api/asset-models");
const { data: assetCategories } = useApiList<AssetCategoryRecord>(
"/api/asset-categories"
);
const [categoryId, setCategoryId] = useState("");
const [manufacturer, setManufacturer] = useState("");
const [name, setName] = useState("");
const [specsText, setSpecsText] = useState(DEFAULT_SPECS_TEXT);
const [submitting, setSubmitting] = useState(false);
const [submitError, setSubmitError] = useState<string | null>(null);
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setSubmitting(true);
setSubmitError(null);
// specs is parsed client-side first — if it's not valid JSON, fail
// locally without calling the API at all (per task scope).
let specs: unknown;
try {
specs = JSON.parse(specsText);
} catch {
setSubmitError("Invalid JSON");
setSubmitting(false);
return;
}
try {
const response = await fetch("/api/asset-models", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ categoryId, manufacturer, name, specs }),
});
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;
}
setCategoryId("");
setManufacturer("");
setName("");
setSpecsText(DEFAULT_SPECS_TEXT);
refetch();
} catch {
setSubmitError("Request failed");
} finally {
setSubmitting(false);
}
}
return (
<div className="flex flex-col gap-8 p-6">
<h1 className="text-xl font-semibold">Asset Models</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>Category ID</TableHead>
<TableHead>Manufacturer</TableHead>
<TableHead>Name</TableHead>
<TableHead>Specs</TableHead>
<TableHead>Created At</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{assetModels.map((assetModel) => (
<TableRow key={assetModel.id}>
<TableCell>{assetModel.id}</TableCell>
<TableCell>{assetModel.category_id}</TableCell>
<TableCell>{assetModel.manufacturer}</TableCell>
<TableCell>{assetModel.name}</TableCell>
<TableCell>{JSON.stringify(assetModel.specs)}</TableCell>
<TableCell>{assetModel.created_at}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</section>
<section className="flex max-w-sm flex-col gap-4">
<h2 className="text-lg font-semibold">New Asset Model</h2>
<form className="flex flex-col gap-4" onSubmit={handleSubmit}>
<div className="flex flex-col gap-2">
<Label htmlFor="categoryId">Category</Label>
<Select value={categoryId} onValueChange={setCategoryId}>
<SelectTrigger id="categoryId" className="w-full">
<SelectValue placeholder="Select a category" />
</SelectTrigger>
<SelectContent>
{assetCategories.map((assetCategory) => (
<SelectItem key={assetCategory.id} value={assetCategory.id}>
{assetCategory.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="manufacturer">Manufacturer</Label>
<Input
id="manufacturer"
value={manufacturer}
onChange={(event) => setManufacturer(event.target.value)}
required
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="name">Name</Label>
<Input
id="name"
value={name}
onChange={(event) => setName(event.target.value)}
required
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="specs">Specs (JSON)</Label>
<Textarea
id="specs"
value={specsText}
onChange={(event) => setSpecsText(event.target.value)}
rows={6}
/>
</div>
{submitError ? (
<p className="text-sm text-destructive">{submitError}</p>
) : null}
<Button type="submit" disabled={submitting}>
{submitting ? "Creating..." : "Create Asset Model"}
</Button>
</form>
</section>
</div>
);
}
+258
View File
@@ -0,0 +1,258 @@
"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 {
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/purchase-orders — snake_case per this repo's
// API-boundary convention (see src/lib/purchase-orders.ts's toRecord()).
interface PurchaseOrderRecord {
id: string;
vendor_id: string;
order_date: string;
expected_date: string;
received_at: string | null;
received_by: string | null;
created_at: string;
}
// Shape returned by GET /api/vendors — only the fields used to populate the
// vendorId <Select> (see src/app/vendors/page.tsx's VendorRecord for the
// full shape).
interface VendorRecord {
id: string;
name: string;
}
// Shape returned by GET /api/employees — only the fields used to populate
// the receivedById <Select> (see src/app/employees/page.tsx's
// EmployeeRecord for the full shape).
interface EmployeeRecord {
id: string;
name: string;
}
// Radix <Select.Item> can't take an empty-string value, so "not received
// yet" is represented by this sentinel in the form state and translated to
// "omit the key" on submit — same pattern as employees page's
// NO_MANAGER_VALUE.
const NOT_RECEIVED_VALUE = "none";
export default function PurchaseOrdersPage() {
const {
data: purchaseOrders,
loading,
error,
refetch,
} = useApiList<PurchaseOrderRecord>("/api/purchase-orders");
const { data: vendors } = useApiList<VendorRecord>("/api/vendors");
const { data: employees } = useApiList<EmployeeRecord>("/api/employees");
const [vendorId, setVendorId] = useState("");
const [orderDate, setOrderDate] = useState("");
const [expectedDate, setExpectedDate] = useState("");
const [receivedAt, setReceivedAt] = useState("");
const [receivedById, setReceivedById] = useState(NOT_RECEIVED_VALUE);
const [submitting, setSubmitting] = useState(false);
const [submitError, setSubmitError] = useState<string | null>(null);
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setSubmitError(null);
// Mirror the server's .refine(): receivedAt/receivedById must both be
// empty or both be filled (src/lib/purchase-orders.ts's
// createPurchaseOrderSchema). Server is still the source of truth if
// this check somehow disagrees with it.
const hasReceivedAt = receivedAt.trim() !== "";
const hasReceivedById = receivedById !== NOT_RECEIVED_VALUE;
if (hasReceivedAt !== hasReceivedById) {
setSubmitError("receivedAt and receivedById must both be set or both be unset");
return;
}
setSubmitting(true);
try {
const response = await fetch("/api/purchase-orders", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
vendorId,
orderDate,
expectedDate,
// Omit both keys entirely when left empty, rather than sending
// null — matches the create-form pattern used on other pages
// (e.g. employees page's managerId).
...(hasReceivedAt ? { receivedAt } : {}),
...(hasReceivedById ? { receivedById } : {}),
}),
});
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;
}
setVendorId("");
setOrderDate("");
setExpectedDate("");
setReceivedAt("");
setReceivedById(NOT_RECEIVED_VALUE);
refetch();
} catch {
setSubmitError("Request failed");
} finally {
setSubmitting(false);
}
}
return (
<div className="flex flex-col gap-8 p-6">
<h1 className="text-xl font-semibold">Purchase Orders</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>Vendor ID</TableHead>
<TableHead>Order Date</TableHead>
<TableHead>Expected Date</TableHead>
<TableHead>Received At</TableHead>
<TableHead>Received By</TableHead>
<TableHead>Created At</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{purchaseOrders.map((purchaseOrder) => (
<TableRow key={purchaseOrder.id}>
<TableCell>{purchaseOrder.id}</TableCell>
<TableCell>{purchaseOrder.vendor_id}</TableCell>
<TableCell>{purchaseOrder.order_date}</TableCell>
<TableCell>{purchaseOrder.expected_date}</TableCell>
<TableCell>{purchaseOrder.received_at ?? "-"}</TableCell>
<TableCell>{purchaseOrder.received_by ?? "-"}</TableCell>
<TableCell>{purchaseOrder.created_at}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</section>
<section className="flex max-w-sm flex-col gap-4">
<h2 className="text-lg font-semibold">New Purchase Order</h2>
<form className="flex flex-col gap-4" onSubmit={handleSubmit}>
<div className="flex flex-col gap-2">
<Label htmlFor="vendorId">Vendor</Label>
<Select value={vendorId} onValueChange={setVendorId} required>
<SelectTrigger id="vendorId" className="w-full">
<SelectValue placeholder="Select a vendor" />
</SelectTrigger>
<SelectContent>
{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="orderDate">Order Date</Label>
<Input
id="orderDate"
type="date"
value={orderDate}
onChange={(event) => setOrderDate(event.target.value)}
required
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="expectedDate">Expected Date</Label>
<Input
id="expectedDate"
type="date"
value={expectedDate}
onChange={(event) => setExpectedDate(event.target.value)}
required
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="receivedAt">Received At (optional)</Label>
<Input
id="receivedAt"
type="date"
value={receivedAt}
onChange={(event) => setReceivedAt(event.target.value)}
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="receivedById">Received By (optional)</Label>
<Select value={receivedById} onValueChange={setReceivedById}>
<SelectTrigger id="receivedById" className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value={NOT_RECEIVED_VALUE}>Not received</SelectItem>
{employees.map((employee) => (
<SelectItem key={employee.id} value={employee.id}>
{employee.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{submitError ? <p className="text-sm text-destructive">{submitError}</p> : null}
<Button type="submit" disabled={submitting}>
{submitting ? "Creating..." : "Create Purchase Order"}
</Button>
</form>
</section>
</div>
);
}