This commit is contained in:
xCyanGrizzly
2026-02-18 14:26:36 +01:00
commit 3a5726e82b
167 changed files with 104081 additions and 0 deletions

View File

@@ -0,0 +1,184 @@
"use client";
import { type ColumnDef } from "@tanstack/react-table";
import { MoreHorizontal, Pencil, Archive, Trash2, FlaskConical } from "lucide-react";
import { DataTableColumnHeader } from "@/components/shared/data-table-column-header";
import { StatusBadge, getStockStatus } from "@/components/shared/status-badge";
import { ColorSwatch } from "@/components/shared/color-swatch";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
export interface ResinRow {
id: string;
name: string;
brand: string;
resinType: string;
color: string;
colorHex: string;
bottleSize: number;
usedML: number;
cost: number | null;
purchaseDate: Date | null;
notes: string | null;
archived: boolean;
vendor: { id: string; name: string } | null;
location: { id: string; name: string } | null;
}
interface ResinColumnsProps {
onEdit: (resin: ResinRow) => void;
onArchive: (id: string) => void;
onDelete: (id: string) => void;
onLogUsage: (resin: ResinRow) => void;
lowStockThreshold: number;
}
export function getResinColumns({
onEdit,
onArchive,
onDelete,
onLogUsage,
lowStockThreshold,
}: ResinColumnsProps): ColumnDef<ResinRow, unknown>[] {
return [
{
id: "color",
header: "",
cell: ({ row }) => <ColorSwatch hex={row.original.colorHex} size="sm" />,
enableHiding: false,
size: 40,
},
{
accessorKey: "name",
header: ({ column }) => <DataTableColumnHeader column={column} title="Name" />,
cell: ({ row }) => {
const remaining = row.original.bottleSize - row.original.usedML;
const status = getStockStatus(
remaining,
row.original.bottleSize,
lowStockThreshold,
row.original.archived
);
return (
<div className="flex items-center gap-2">
<span className="font-medium">{row.original.name}</span>
<StatusBadge variant={status} />
</div>
);
},
enableHiding: false,
},
{
accessorKey: "brand",
header: ({ column }) => <DataTableColumnHeader column={column} title="Brand" />,
cell: ({ row }) => (
<span className="text-sm text-muted-foreground">{row.original.brand}</span>
),
},
{
accessorKey: "resinType",
header: ({ column }) => <DataTableColumnHeader column={column} title="Type" />,
cell: ({ row }) => (
<Badge variant="secondary" className="text-xs">
{row.original.resinType}
</Badge>
),
},
{
id: "remaining",
header: ({ column }) => <DataTableColumnHeader column={column} title="Remaining" />,
cell: ({ row }) => {
const remaining = row.original.bottleSize - row.original.usedML;
const percent =
row.original.bottleSize > 0
? (remaining / row.original.bottleSize) * 100
: 0;
const isLow = percent <= lowStockThreshold;
return (
<div className="flex items-center gap-2 min-w-[120px]">
<div className="flex-1 h-2 rounded-full bg-muted overflow-hidden">
<div
className={`h-full rounded-full transition-all ${
isLow ? "bg-orange-500" : "bg-primary"
}`}
style={{ width: `${Math.max(0, Math.min(100, percent))}%` }}
/>
</div>
<span className="text-xs text-muted-foreground w-16 text-right">
{remaining.toFixed(0)} ml
</span>
</div>
);
},
},
{
id: "location",
header: "Location",
cell: ({ row }) => (
<span className="text-sm text-muted-foreground">
{row.original.location?.name ?? "\u2014"}
</span>
),
},
{
id: "vendor",
header: "Vendor",
cell: ({ row }) => (
<span className="text-sm text-muted-foreground">
{row.original.vendor?.name ?? "\u2014"}
</span>
),
},
{
accessorKey: "cost",
header: ({ column }) => <DataTableColumnHeader column={column} title="Cost" />,
cell: ({ row }) => (
<span className="text-sm text-muted-foreground">
{row.original.cost != null ? `\u20AC${row.original.cost.toFixed(2)}` : "\u2014"}
</span>
),
},
{
id: "actions",
cell: ({ row }) => (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="h-8 w-8">
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => onEdit(row.original)}>
<Pencil className="mr-2 h-3.5 w-3.5" />
Edit
</DropdownMenuItem>
<DropdownMenuItem onClick={() => onLogUsage(row.original)}>
<FlaskConical className="mr-2 h-3.5 w-3.5" />
Log Usage
</DropdownMenuItem>
<DropdownMenuItem onClick={() => onArchive(row.original.id)}>
<Archive className="mr-2 h-3.5 w-3.5" />
{row.original.archived ? "Unarchive" : "Archive"}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => onDelete(row.original.id)}
className="text-destructive focus:text-destructive"
>
<Trash2 className="mr-2 h-3.5 w-3.5" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
),
enableHiding: false,
},
];
}

View File

@@ -0,0 +1,363 @@
"use client";
import { useTransition } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { toast } from "sonner";
import { resinSchema, type ResinInput } from "@/schemas/resin.schema";
import { RESIN_TYPES } from "@/lib/constants";
import { createResin, updateResin } from "../actions";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { ColorSwatch } from "@/components/shared/color-swatch";
import { CatalogBrowserButton } from "@/components/shared/catalog-browser-button";
import { AutocompleteInput } from "@/components/shared/autocomplete-input";
import type { CatalogItem } from "@/types/catalog.types";
interface ResinFormProps {
resin?: {
id: string;
name: string;
brand: string;
resinType: string;
color: string;
colorHex: string;
bottleSize: number;
usedML: number;
cost: number | null;
purchaseDate: Date | null;
notes: string | null;
vendorId: string | null;
locationId: string | null;
};
vendors: { id: string; name: string }[];
locations: { id: string; name: string }[];
onSuccess: () => void;
}
export function ResinForm({ resin, vendors, locations, onSuccess }: ResinFormProps) {
const [isPending, startTransition] = useTransition();
const isEditing = !!resin;
const form = useForm<ResinInput>({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
resolver: zodResolver(resinSchema) as any,
defaultValues: {
name: resin?.name ?? "",
brand: resin?.brand ?? "",
resinType: (resin?.resinType as ResinInput["resinType"]) ?? "Standard",
color: resin?.color ?? "",
colorHex: resin?.colorHex ?? "#000000",
bottleSize: resin?.bottleSize ?? 500,
usedML: resin?.usedML ?? 0,
cost: resin?.cost ?? undefined,
purchaseDate: resin?.purchaseDate
? new Date(resin.purchaseDate).toISOString().split("T")[0]
: "",
notes: resin?.notes ?? "",
vendorId: resin?.vendorId ?? "",
locationId: resin?.locationId ?? "",
},
});
const watchColorHex = form.watch("colorHex");
function handleCatalogSelect(item: CatalogItem) {
form.setValue("name", item.name);
form.setValue("brand", item.brand);
if (item.color) form.setValue("color", item.color);
if (item.colorHex) form.setValue("colorHex", item.colorHex);
if (item.resinType) {
const match = RESIN_TYPES.find(
(t) => t.toUpperCase() === item.resinType!.toUpperCase(),
);
if (match) form.setValue("resinType", match);
}
if (item.volume) form.setValue("bottleSize", item.volume);
if (item.price != null) form.setValue("cost", item.price);
}
function onSubmit(values: ResinInput) {
startTransition(async () => {
const result = isEditing
? await updateResin(resin!.id, values)
: await createResin(values);
if (!result.success) {
toast.error(result.error);
return;
}
toast.success(isEditing ? "Resin updated" : "Resin created");
form.reset();
onSuccess();
});
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
{!isEditing && (
<div className="flex items-center justify-between">
<p className="text-sm text-muted-foreground">
Auto-fill from product catalog
</p>
<CatalogBrowserButton type="resin" onSelect={handleCatalogSelect} />
</div>
)}
<div className="grid grid-cols-2 gap-4">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem className="col-span-2">
<FormLabel>Name</FormLabel>
<FormControl>
{!isEditing ? (
<AutocompleteInput
type="resin"
value={field.value}
onChange={field.onChange}
onSelectItem={handleCatalogSelect}
placeholder="Resin name — type to search catalog"
/>
) : (
<Input placeholder="Resin name" {...field} />
)}
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="brand"
render={({ field }) => (
<FormItem>
<FormLabel>Brand</FormLabel>
<FormControl>
<Input placeholder="Brand name" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="resinType"
render={({ field }) => (
<FormItem>
<FormLabel>Type</FormLabel>
<Select onValueChange={field.onChange} value={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select type" />
</SelectTrigger>
</FormControl>
<SelectContent>
{RESIN_TYPES.map((t) => (
<SelectItem key={t} value={t}>
{t}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="color"
render={({ field }) => (
<FormItem>
<FormLabel>Color Name</FormLabel>
<FormControl>
<Input placeholder="e.g. Clear Grey" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="colorHex"
render={({ field }) => (
<FormItem>
<FormLabel>Color Hex</FormLabel>
<div className="flex items-center gap-2">
<FormControl>
<Input placeholder="#000000" {...field} className="flex-1" />
</FormControl>
<input
type="color"
value={field.value}
onChange={(e) => field.onChange(e.target.value)}
className="h-9 w-9 cursor-pointer rounded border border-border bg-transparent p-0.5"
/>
<ColorSwatch hex={watchColorHex || "#000000"} size="md" />
</div>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="bottleSize"
render={({ field }) => (
<FormItem>
<FormLabel>Bottle Size (ml)</FormLabel>
<FormControl>
<Input type="number" step="1" min="0" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="usedML"
render={({ field }) => (
<FormItem>
<FormLabel>Used (ml)</FormLabel>
<FormControl>
<Input type="number" step="0.1" min="0" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="vendorId"
render={({ field }) => (
<FormItem>
<FormLabel>Vendor</FormLabel>
<Select
onValueChange={(val) => field.onChange(val === "none" ? "" : val)}
value={field.value || "none"}
>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select vendor" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="none">None</SelectItem>
{vendors.map((v) => (
<SelectItem key={v.id} value={v.id}>
{v.name}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="locationId"
render={({ field }) => (
<FormItem>
<FormLabel>Location</FormLabel>
<Select
onValueChange={(val) => field.onChange(val === "none" ? "" : val)}
value={field.value || "none"}
>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select location" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="none">None</SelectItem>
{locations.map((l) => (
<SelectItem key={l.id} value={l.id}>
{l.name}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="cost"
render={({ field }) => (
<FormItem>
<FormLabel>Cost</FormLabel>
<FormControl>
<Input type="number" step="0.01" min="0" placeholder="0.00" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="purchaseDate"
render={({ field }) => (
<FormItem>
<FormLabel>Purchase Date</FormLabel>
<FormControl>
<Input type="date" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="notes"
render={({ field }) => (
<FormItem className="col-span-2">
<FormLabel>Notes</FormLabel>
<FormControl>
<Textarea placeholder="Optional notes" rows={2} {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="flex justify-end gap-2">
<Button type="submit" disabled={isPending}>
{isPending ? "Saving..." : isEditing ? "Update" : "Create"}
</Button>
</div>
</form>
</Form>
);
}

View File

@@ -0,0 +1,50 @@
"use client";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { ScrollArea } from "@/components/ui/scroll-area";
import { ResinForm } from "./resin-form";
interface ResinModalProps {
open: boolean;
onOpenChange: (open: boolean) => void;
resin?: Parameters<typeof ResinForm>[0]["resin"];
vendors: { id: string; name: string }[];
locations: { id: string; name: string }[];
}
export function ResinModal({
open,
onOpenChange,
resin,
vendors,
locations,
}: ResinModalProps) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-2xl max-h-[90vh]">
<DialogHeader>
<DialogTitle>{resin ? "Edit Resin" : "Add Resin"}</DialogTitle>
<DialogDescription>
{resin
? "Update the resin details below."
: "Add a new resin bottle to your inventory."}
</DialogDescription>
</DialogHeader>
<ScrollArea className="max-h-[70vh] pr-4">
<ResinForm
resin={resin}
vendors={vendors}
locations={locations}
onSuccess={() => onOpenChange(false)}
/>
</ScrollArea>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,213 @@
"use client";
import { useState, useTransition, useCallback } from "react";
import { useRouter, usePathname, useSearchParams } from "next/navigation";
import { Plus, Search } from "lucide-react";
import { toast } from "sonner";
import { useDataTable } from "@/hooks/use-data-table";
import { RESIN_TYPES } from "@/lib/constants";
import { getResinColumns, type ResinRow } from "./resin-columns";
import { ResinModal } from "./resin-modal";
import { deleteResin, archiveResin, logResinUsage } from "../actions";
import { DataTable } from "@/components/shared/data-table";
import { DataTablePagination } from "@/components/shared/data-table-pagination";
import { DataTableViewOptions } from "@/components/shared/data-table-view-options";
import { DataTableFacetedFilter } from "@/components/shared/data-table-faceted-filter";
import { DeleteDialog } from "@/components/shared/delete-dialog";
import { UsageLogDialog } from "@/components/shared/usage-log-dialog";
import { PageHeader } from "@/components/shared/page-header";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
interface ResinTableProps {
data: ResinRow[];
pageCount: number;
totalCount: number;
vendors: { id: string; name: string }[];
locations: { id: string; name: string }[];
lowStockThreshold: number;
}
export function ResinTable({
data,
pageCount,
totalCount,
vendors,
locations,
lowStockThreshold,
}: ResinTableProps) {
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const [isPending, startTransition] = useTransition();
const [modalOpen, setModalOpen] = useState(false);
const [editResin, setEditResin] = useState<ResinRow | undefined>();
const [deleteId, setDeleteId] = useState<string | null>(null);
const [usageResin, setUsageResin] = useState<ResinRow | null>(null);
const [searchValue, setSearchValue] = useState(searchParams.get("search") ?? "");
const resinTypeFilter = new Set(searchParams.getAll("resinType"));
const vendorFilter = new Set(searchParams.getAll("vendor"));
const locationFilter = new Set(searchParams.getAll("location"));
const updateFilters = useCallback(
(key: string, values: Set<string>) => {
const params = new URLSearchParams(searchParams.toString());
params.delete(key);
values.forEach((v) => params.append(key, v));
params.set("page", "1");
router.push(`${pathname}?${params.toString()}`, { scroll: false });
},
[router, pathname, searchParams]
);
const updateSearch = (value: string) => {
setSearchValue(value);
const params = new URLSearchParams(searchParams.toString());
if (value) {
params.set("search", value);
params.set("page", "1");
} else {
params.delete("search");
}
router.push(`${pathname}?${params.toString()}`, { scroll: false });
};
const columns = getResinColumns({
onEdit: (resin) => {
setEditResin(resin);
setModalOpen(true);
},
onArchive: (id) => {
startTransition(async () => {
const result = await archiveResin(id);
if (result.success) toast.success("Resin updated");
else toast.error(result.error);
});
},
onDelete: (id) => setDeleteId(id),
onLogUsage: (resin) => setUsageResin(resin),
lowStockThreshold,
});
const { table } = useDataTable({ data, columns, pageCount });
const handleDelete = () => {
if (!deleteId) return;
startTransition(async () => {
const result = await deleteResin(deleteId);
if (result.success) {
toast.success("Resin deleted");
setDeleteId(null);
} else {
toast.error(result.error);
}
});
};
const resinTypeOptions = RESIN_TYPES.map((t) => ({ label: t, value: t }));
const vendorOptions = vendors.map((v) => ({ label: v.name, value: v.id }));
const locationOptions = locations.map((l) => ({ label: l.name, value: l.id }));
return (
<div className="space-y-4">
<PageHeader title="Resins" description="Manage your SLA resin inventory">
<Button
onClick={() => {
setEditResin(undefined);
setModalOpen(true);
}}
>
<Plus className="mr-2 h-4 w-4" />
Add Resin
</Button>
</PageHeader>
<div className="flex flex-wrap items-center gap-2">
<div className="relative flex-1 min-w-[200px] max-w-sm">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search resins..."
value={searchValue}
onChange={(e) => updateSearch(e.target.value)}
className="pl-9 h-9"
/>
</div>
<DataTableFacetedFilter
title="Type"
options={resinTypeOptions}
selectedValues={resinTypeFilter}
onSelectionChange={(values) => updateFilters("resinType", values)}
/>
<DataTableFacetedFilter
title="Vendor"
options={vendorOptions}
selectedValues={vendorFilter}
onSelectionChange={(values) => updateFilters("vendor", values)}
/>
<DataTableFacetedFilter
title="Location"
options={locationOptions}
selectedValues={locationFilter}
onSelectionChange={(values) => updateFilters("location", values)}
/>
<DataTableViewOptions table={table} />
</div>
<DataTable table={table} emptyMessage="No resins found. Add your first bottle!" />
<DataTablePagination table={table} totalCount={totalCount} />
<ResinModal
open={modalOpen}
onOpenChange={(open) => {
setModalOpen(open);
if (!open) setEditResin(undefined);
}}
resin={
editResin
? {
id: editResin.id,
name: editResin.name,
brand: editResin.brand,
resinType: editResin.resinType,
color: editResin.color,
colorHex: editResin.colorHex,
bottleSize: editResin.bottleSize,
usedML: editResin.usedML,
cost: editResin.cost,
purchaseDate: editResin.purchaseDate,
notes: editResin.notes,
vendorId: editResin.vendor?.id ?? null,
locationId: editResin.location?.id ?? null,
}
: undefined
}
vendors={vendors}
locations={locations}
/>
<DeleteDialog
open={!!deleteId}
onOpenChange={(open) => !open && setDeleteId(null)}
title="Delete Resin"
description="This will permanently delete this resin bottle and all its usage logs."
onConfirm={handleDelete}
isLoading={isPending}
/>
{usageResin && (
<UsageLogDialog
open={!!usageResin}
onOpenChange={(open) => !open && setUsageResin(null)}
itemName={usageResin.name}
unit="ml"
onSubmit={async (amount, notes) => {
const result = await logResinUsage(usageResin.id, { amount, notes });
return result;
}}
/>
)}
</div>
);
}

View File

@@ -0,0 +1,153 @@
"use server";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { resinSchema } from "@/schemas/resin.schema";
import { usageLogSchema } from "@/schemas/usage-log.schema";
import { revalidatePath } from "next/cache";
import type { ActionResult } from "@/types/api.types";
export async function createResin(input: unknown): Promise<ActionResult<{ id: string }>> {
const session = await auth();
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
const parsed = resinSchema.safeParse(input);
if (!parsed.success) return { success: false, error: "Validation failed" };
try {
const resin = await prisma.resin.create({
data: {
name: parsed.data.name,
brand: parsed.data.brand,
resinType: parsed.data.resinType,
color: parsed.data.color,
colorHex: parsed.data.colorHex,
bottleSize: parsed.data.bottleSize,
usedML: parsed.data.usedML,
purchaseDate: parsed.data.purchaseDate ? new Date(parsed.data.purchaseDate) : null,
cost: parsed.data.cost ?? null,
notes: parsed.data.notes || null,
vendorId: parsed.data.vendorId || null,
locationId: parsed.data.locationId || null,
userId: session.user.id,
},
});
revalidatePath("/resins");
revalidatePath("/dashboard");
return { success: true, data: { id: resin.id } };
} catch {
return { success: false, error: "Failed to create resin" };
}
}
export async function updateResin(id: string, input: unknown): Promise<ActionResult> {
const session = await auth();
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
const parsed = resinSchema.safeParse(input);
if (!parsed.success) return { success: false, error: "Validation failed" };
const existing = await prisma.resin.findFirst({ where: { id, userId: session.user.id } });
if (!existing) return { success: false, error: "Not found" };
try {
await prisma.resin.update({
where: { id },
data: {
name: parsed.data.name,
brand: parsed.data.brand,
resinType: parsed.data.resinType,
color: parsed.data.color,
colorHex: parsed.data.colorHex,
bottleSize: parsed.data.bottleSize,
usedML: parsed.data.usedML,
purchaseDate: parsed.data.purchaseDate ? new Date(parsed.data.purchaseDate) : null,
cost: parsed.data.cost ?? null,
notes: parsed.data.notes || null,
vendorId: parsed.data.vendorId || null,
locationId: parsed.data.locationId || null,
},
});
revalidatePath("/resins");
revalidatePath("/dashboard");
return { success: true, data: undefined };
} catch {
return { success: false, error: "Failed to update resin" };
}
}
export async function deleteResin(id: string): Promise<ActionResult> {
const session = await auth();
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
const existing = await prisma.resin.findFirst({ where: { id, userId: session.user.id } });
if (!existing) return { success: false, error: "Not found" };
try {
await prisma.resin.delete({ where: { id } });
revalidatePath("/resins");
revalidatePath("/dashboard");
return { success: true, data: undefined };
} catch {
return { success: false, error: "Failed to delete resin" };
}
}
export async function archiveResin(id: string): Promise<ActionResult> {
const session = await auth();
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
const existing = await prisma.resin.findFirst({ where: { id, userId: session.user.id } });
if (!existing) return { success: false, error: "Not found" };
try {
await prisma.resin.update({
where: { id },
data: { archived: !existing.archived },
});
revalidatePath("/resins");
revalidatePath("/dashboard");
return { success: true, data: undefined };
} catch {
return { success: false, error: "Failed to archive resin" };
}
}
export async function logResinUsage(resinId: string, input: unknown): Promise<ActionResult> {
const session = await auth();
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
const parsed = usageLogSchema.safeParse(input);
if (!parsed.success) return { success: false, error: "Validation failed" };
const existing = await prisma.resin.findFirst({ where: { id: resinId, userId: session.user.id } });
if (!existing) return { success: false, error: "Not found" };
try {
await prisma.$transaction([
prisma.usageLog.create({
data: {
itemType: "RESIN",
itemId: resinId,
resinId,
amount: parsed.data.amount,
unit: "ml",
notes: parsed.data.notes || null,
userId: session.user.id,
},
}),
prisma.resin.update({
where: { id: resinId },
data: { usedML: { increment: parsed.data.amount } },
}),
]);
revalidatePath("/resins");
revalidatePath("/dashboard");
return { success: true, data: undefined };
} catch {
return { success: false, error: "Failed to log usage" };
}
}

View File

@@ -0,0 +1,34 @@
import { Skeleton } from "@/components/ui/skeleton";
export default function ResinsLoading() {
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<div>
<Skeleton className="h-8 w-32" />
<Skeleton className="mt-1 h-4 w-56" />
</div>
<Skeleton className="h-9 w-28" />
</div>
<div className="flex flex-wrap items-center gap-2">
<Skeleton className="h-9 w-64" />
<Skeleton className="h-9 w-24" />
<Skeleton className="h-9 w-24" />
<Skeleton className="h-9 w-24" />
</div>
<div className="rounded-md border">
<div className="h-10 border-b bg-muted/50" />
{Array.from({ length: 5 }).map((_, i) => (
<div key={i} className="flex items-center gap-4 border-b px-4 py-2">
<Skeleton className="h-5 w-5 rounded" />
<Skeleton className="h-4 w-32" />
<Skeleton className="h-4 w-20" />
<Skeleton className="h-4 w-20" />
<Skeleton className="h-4 w-24" />
<Skeleton className="h-4 w-16" />
</div>
))}
</div>
</div>
);
}

View File

@@ -0,0 +1,44 @@
import { auth } from "@/lib/auth";
import { redirect } from "next/navigation";
import { getResins } from "@/data/resin.queries";
import { getVendorOptions } from "@/data/vendor.queries";
import { getLocationOptions } from "@/data/location.queries";
import { getUserSettings } from "@/data/settings.queries";
import { ResinTable } from "./_components/resin-table";
interface ResinsPageProps {
searchParams: Promise<Record<string, string | string[] | undefined>>;
}
export default async function ResinsPage({ searchParams }: ResinsPageProps) {
const session = await auth();
if (!session?.user?.id) redirect("/login");
const params = await searchParams;
const [resinsResult, vendors, locations, settings] = await Promise.all([
getResins(session.user.id, {
page: typeof params.page === "string" ? params.page : "1",
perPage: typeof params.perPage === "string" ? params.perPage : "20",
sort: typeof params.sort === "string" ? params.sort : undefined,
order: typeof params.order === "string" ? (params.order as "asc" | "desc") : undefined,
search: typeof params.search === "string" ? params.search : undefined,
resinType: params.resinType,
vendor: params.vendor,
location: params.location,
}),
getVendorOptions(session.user.id),
getLocationOptions(session.user.id),
getUserSettings(session.user.id),
]);
return (
<ResinTable
data={JSON.parse(JSON.stringify(resinsResult.data))}
pageCount={resinsResult.pageCount}
totalCount={resinsResult.totalCount}
vendors={vendors}
locations={locations}
lowStockThreshold={settings.lowStockThreshold}
/>
);
}