mirror of
https://github.com/xCyanGrizzly/DragonsStash.git
synced 2026-05-11 06:11:15 +00:00
Init
This commit is contained in:
43
src/app/(app)/dashboard/loading.tsx
Normal file
43
src/app/(app)/dashboard/loading.tsx
Normal file
@@ -0,0 +1,43 @@
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
|
||||
export default function DashboardLoading() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
{Array.from({ length: 4 }).map((_, i) => (
|
||||
<Card key={i} className="border-border">
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-3 w-20" />
|
||||
<Skeleton className="h-7 w-16" />
|
||||
<Skeleton className="h-3 w-24" />
|
||||
</div>
|
||||
<Skeleton className="h-10 w-10 rounded-md" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
<div className="grid gap-6 lg:grid-cols-2">
|
||||
<Card className="border-border">
|
||||
<CardContent className="p-6 space-y-4">
|
||||
<Skeleton className="h-5 w-32" />
|
||||
{Array.from({ length: 3 }).map((_, i) => (
|
||||
<Skeleton key={i} className="h-10 w-full" />
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card className="border-border">
|
||||
<CardContent className="p-6 space-y-4">
|
||||
<Skeleton className="h-5 w-32" />
|
||||
{Array.from({ length: 3 }).map((_, i) => (
|
||||
<Skeleton key={i} className="h-10 w-full" />
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
126
src/app/(app)/dashboard/page.tsx
Normal file
126
src/app/(app)/dashboard/page.tsx
Normal file
@@ -0,0 +1,126 @@
|
||||
import { auth } from "@/lib/auth";
|
||||
import { redirect } from "next/navigation";
|
||||
import { getDashboardStats } from "@/data/dashboard.queries";
|
||||
import { getUserSettings } from "@/data/settings.queries";
|
||||
import { Package, DollarSign, AlertTriangle, Activity } from "lucide-react";
|
||||
import { StatCard } from "@/components/shared/stat-card";
|
||||
import { ColorSwatch } from "@/components/shared/color-swatch";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
export default async function DashboardPage() {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) redirect("/login");
|
||||
|
||||
const settings = await getUserSettings(session.user.id);
|
||||
const stats = await getDashboardStats(session.user.id, settings.lowStockThreshold);
|
||||
|
||||
const currencyFormatter = new Intl.NumberFormat("en-US", {
|
||||
style: "currency",
|
||||
currency: settings.currency,
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Stats Grid */}
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<StatCard
|
||||
title="Total Items"
|
||||
value={stats.totalItems}
|
||||
icon={Package}
|
||||
description="Filaments, resins & paints"
|
||||
/>
|
||||
<StatCard
|
||||
title="Inventory Value"
|
||||
value={currencyFormatter.format(stats.inventoryValue)}
|
||||
icon={DollarSign}
|
||||
description="Total purchase cost"
|
||||
/>
|
||||
<StatCard
|
||||
title="Low Stock"
|
||||
value={stats.lowStockCount}
|
||||
icon={AlertTriangle}
|
||||
description={`Below ${settings.lowStockThreshold}% remaining`}
|
||||
iconClassName={stats.lowStockCount > 0 ? "text-orange-400" : undefined}
|
||||
/>
|
||||
<StatCard
|
||||
title="Recent Activity"
|
||||
value={stats.recentActivityCount}
|
||||
icon={Activity}
|
||||
description="Usage logs in last 24h"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6 lg:grid-cols-2">
|
||||
{/* Low Stock Alerts */}
|
||||
<Card className="border-border">
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-base">Low Stock Alerts</CardTitle>
|
||||
<CardDescription>Items below {settings.lowStockThreshold}% remaining</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{stats.lowStockItems.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">All items are well stocked.</p>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{stats.lowStockItems.map((item) => (
|
||||
<div key={`${item.type}-${item.id}`} className="flex items-center gap-3">
|
||||
<ColorSwatch hex={item.colorHex} size="sm" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium truncate">{item.name}</p>
|
||||
<p className="text-xs text-muted-foreground capitalize">{item.type}</p>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="text-sm font-medium text-orange-400">
|
||||
{Math.round(item.remaining)}
|
||||
{item.type === "filament" ? "g" : "ml"}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">{Math.round(item.percent)}% left</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Recent Usage */}
|
||||
<Card className="border-border">
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-base">Recent Usage</CardTitle>
|
||||
<CardDescription>Latest consumption log entries</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{stats.recentUsage.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No usage logged yet.</p>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{stats.recentUsage.map((log) => (
|
||||
<div key={log.id} className="flex items-center gap-3">
|
||||
<Badge variant="outline" className="text-[10px] shrink-0">
|
||||
{log.itemType}
|
||||
</Badge>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium truncate">{log.itemName}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{log.notes || "No notes"}
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-right shrink-0">
|
||||
<p className="text-sm font-medium">
|
||||
-{log.amount}{log.unit}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{new Date(log.createdAt).toLocaleDateString()}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
193
src/app/(app)/filaments/_components/filament-columns.tsx
Normal file
193
src/app/(app)/filaments/_components/filament-columns.tsx
Normal file
@@ -0,0 +1,193 @@
|
||||
"use client";
|
||||
|
||||
import { type ColumnDef } from "@tanstack/react-table";
|
||||
import { MoreHorizontal, Pencil, Archive, Trash2, Plus } 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 FilamentRow {
|
||||
id: string;
|
||||
name: string;
|
||||
brand: string;
|
||||
material: string;
|
||||
color: string;
|
||||
colorHex: string;
|
||||
spoolWeight: number;
|
||||
usedWeight: number;
|
||||
cost: number | null;
|
||||
purchaseDate: Date | null;
|
||||
archived: boolean;
|
||||
vendor: { id: string; name: string } | null;
|
||||
location: { id: string; name: string } | null;
|
||||
tags: { tag: { id: string; name: string } }[];
|
||||
}
|
||||
|
||||
interface FilamentColumnsProps {
|
||||
onEdit: (filament: FilamentRow) => void;
|
||||
onArchive: (id: string) => void;
|
||||
onDelete: (id: string) => void;
|
||||
onLogUsage: (filament: FilamentRow) => void;
|
||||
lowStockThreshold: number;
|
||||
}
|
||||
|
||||
export function getFilamentColumns({
|
||||
onEdit,
|
||||
onArchive,
|
||||
onDelete,
|
||||
onLogUsage,
|
||||
lowStockThreshold,
|
||||
}: FilamentColumnsProps): ColumnDef<FilamentRow, unknown>[] {
|
||||
return [
|
||||
{
|
||||
id: "colorPreview",
|
||||
header: "",
|
||||
cell: ({ row }) => <ColorSwatch hex={row.original.colorHex} size="sm" />,
|
||||
enableHiding: false,
|
||||
enableSorting: false,
|
||||
size: 40,
|
||||
},
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: ({ column }) => <DataTableColumnHeader column={column} title="Name" />,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium">{row.original.name}</span>
|
||||
{row.original.archived && <StatusBadge variant="archived" />}
|
||||
</div>
|
||||
),
|
||||
enableHiding: false,
|
||||
},
|
||||
{
|
||||
accessorKey: "brand",
|
||||
header: ({ column }) => <DataTableColumnHeader column={column} title="Brand" />,
|
||||
cell: ({ row }) => <span className="text-sm">{row.original.brand}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "material",
|
||||
header: ({ column }) => <DataTableColumnHeader column={column} title="Material" />,
|
||||
cell: ({ row }) => (
|
||||
<Badge variant="secondary" className="text-[10px]">
|
||||
{row.original.material}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "remaining",
|
||||
header: ({ column }) => <DataTableColumnHeader column={column} title="Remaining" />,
|
||||
cell: ({ row }) => {
|
||||
const remaining = row.original.spoolWeight - row.original.usedWeight;
|
||||
const percent = row.original.spoolWeight > 0
|
||||
? Math.round((remaining / row.original.spoolWeight) * 100)
|
||||
: 0;
|
||||
const status = getStockStatus(remaining, row.original.spoolWeight, lowStockThreshold, row.original.archived);
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="h-1.5 w-16 rounded-full bg-muted">
|
||||
<div
|
||||
className={`h-full rounded-full ${
|
||||
status === "lowStock" || status === "empty"
|
||||
? "bg-orange-500"
|
||||
: "bg-emerald-500"
|
||||
}`}
|
||||
style={{ width: `${Math.max(0, Math.min(100, percent))}%` }}
|
||||
/>
|
||||
</div>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{Math.round(remaining)}g ({percent}%)
|
||||
</span>
|
||||
{(status === "lowStock" || status === "empty") && !row.original.archived && (
|
||||
<StatusBadge variant={status} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
accessorFn: (row) => row.spoolWeight - row.usedWeight,
|
||||
},
|
||||
{
|
||||
id: "location",
|
||||
header: ({ column }) => <DataTableColumnHeader column={column} title="Location" />,
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{row.original.location?.name || "—"}
|
||||
</span>
|
||||
),
|
||||
accessorFn: (row) => row.location?.name,
|
||||
},
|
||||
{
|
||||
id: "vendor",
|
||||
header: ({ column }) => <DataTableColumnHeader column={column} title="Vendor" />,
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{row.original.vendor?.name || "—"}
|
||||
</span>
|
||||
),
|
||||
accessorFn: (row) => row.vendor?.name,
|
||||
},
|
||||
{
|
||||
accessorKey: "cost",
|
||||
header: ({ column }) => <DataTableColumnHeader column={column} title="Cost" />,
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm">
|
||||
{row.original.cost != null ? `$${row.original.cost.toFixed(2)}` : "—"}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "purchaseDate",
|
||||
header: ({ column }) => <DataTableColumnHeader column={column} title="Purchased" />,
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{row.original.purchaseDate
|
||||
? new Date(row.original.purchaseDate).toLocaleDateString()
|
||||
: "—"}
|
||||
</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)}>
|
||||
<Plus 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,
|
||||
},
|
||||
];
|
||||
}
|
||||
361
src/app/(app)/filaments/_components/filament-form.tsx
Normal file
361
src/app/(app)/filaments/_components/filament-form.tsx
Normal file
@@ -0,0 +1,361 @@
|
||||
"use client";
|
||||
|
||||
import { useTransition } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { toast } from "sonner";
|
||||
import { filamentSchema, type FilamentInput } from "@/schemas/filament.schema";
|
||||
import { MATERIALS } from "@/lib/constants";
|
||||
import { createFilament, updateFilament } 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 FilamentFormProps {
|
||||
filament?: {
|
||||
id: string;
|
||||
name: string;
|
||||
brand: string;
|
||||
material: string;
|
||||
color: string;
|
||||
colorHex: string;
|
||||
diameter: number;
|
||||
spoolWeight: number;
|
||||
usedWeight: number;
|
||||
emptySpoolWeight: 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 FilamentForm({ filament, vendors, locations, onSuccess }: FilamentFormProps) {
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const isEditing = !!filament;
|
||||
|
||||
const form = useForm<FilamentInput>({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
resolver: zodResolver(filamentSchema) as any,
|
||||
defaultValues: {
|
||||
name: filament?.name ?? "",
|
||||
brand: filament?.brand ?? "",
|
||||
material: (filament?.material as FilamentInput["material"]) ?? "PLA",
|
||||
color: filament?.color ?? "",
|
||||
colorHex: filament?.colorHex ?? "#000000",
|
||||
diameter: filament?.diameter ?? 1.75,
|
||||
spoolWeight: filament?.spoolWeight ?? 1000,
|
||||
usedWeight: filament?.usedWeight ?? 0,
|
||||
emptySpoolWeight: filament?.emptySpoolWeight ?? 0,
|
||||
cost: filament?.cost ?? undefined,
|
||||
purchaseDate: filament?.purchaseDate
|
||||
? new Date(filament.purchaseDate).toISOString().split("T")[0]
|
||||
: "",
|
||||
notes: filament?.notes ?? "",
|
||||
vendorId: filament?.vendorId ?? "",
|
||||
locationId: filament?.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.material) {
|
||||
const match = MATERIALS.find(
|
||||
(m) => m.toUpperCase() === item.material!.toUpperCase(),
|
||||
);
|
||||
if (match) form.setValue("material", match);
|
||||
}
|
||||
if (item.weight) form.setValue("spoolWeight", item.weight);
|
||||
if (item.price != null) form.setValue("cost", item.price);
|
||||
}
|
||||
|
||||
function onSubmit(values: FilamentInput) {
|
||||
startTransition(async () => {
|
||||
const result = isEditing
|
||||
? await updateFilament(filament!.id, values)
|
||||
: await createFilament(values);
|
||||
|
||||
if (!result.success) {
|
||||
toast.error(result.error);
|
||||
return;
|
||||
}
|
||||
|
||||
toast.success(isEditing ? "Filament updated" : "Filament 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="filament" 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="filament"
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
onSelectItem={handleCatalogSelect}
|
||||
placeholder="Filament name — type to search catalog"
|
||||
/>
|
||||
) : (
|
||||
<Input placeholder="Filament 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="material"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Material</FormLabel>
|
||||
<Select onValueChange={field.onChange} value={field.value}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select material" />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{MATERIALS.map((m) => (
|
||||
<SelectItem key={m} value={m}>{m}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="color"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Color Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="e.g. Galaxy Black" {...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="spoolWeight"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Spool Weight (g)</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="number" step="1" min="0" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="usedWeight"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Used Weight (g)</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>
|
||||
);
|
||||
}
|
||||
48
src/app/(app)/filaments/_components/filament-modal.tsx
Normal file
48
src/app/(app)/filaments/_components/filament-modal.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { FilamentForm } from "./filament-form";
|
||||
|
||||
interface FilamentModalProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
filament?: Parameters<typeof FilamentForm>[0]["filament"];
|
||||
vendors: { id: string; name: string }[];
|
||||
locations: { id: string; name: string }[];
|
||||
}
|
||||
|
||||
export function FilamentModal({
|
||||
open,
|
||||
onOpenChange,
|
||||
filament,
|
||||
vendors,
|
||||
locations,
|
||||
}: FilamentModalProps) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-2xl max-h-[90vh]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{filament ? "Edit Filament" : "Add Filament"}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{filament ? "Update the filament details below." : "Add a new filament spool to your inventory."}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<ScrollArea className="max-h-[70vh] pr-4">
|
||||
<FilamentForm
|
||||
filament={filament}
|
||||
vendors={vendors}
|
||||
locations={locations}
|
||||
onSuccess={() => onOpenChange(false)}
|
||||
/>
|
||||
</ScrollArea>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
216
src/app/(app)/filaments/_components/filament-table.tsx
Normal file
216
src/app/(app)/filaments/_components/filament-table.tsx
Normal file
@@ -0,0 +1,216 @@
|
||||
"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 { MATERIALS } from "@/lib/constants";
|
||||
import { getFilamentColumns, type FilamentRow } from "./filament-columns";
|
||||
import { FilamentModal } from "./filament-modal";
|
||||
import { deleteFilament, archiveFilament, logFilamentUsage } 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 FilamentTableProps {
|
||||
data: FilamentRow[];
|
||||
pageCount: number;
|
||||
totalCount: number;
|
||||
vendors: { id: string; name: string }[];
|
||||
locations: { id: string; name: string }[];
|
||||
lowStockThreshold: number;
|
||||
}
|
||||
|
||||
export function FilamentTable({
|
||||
data,
|
||||
pageCount,
|
||||
totalCount,
|
||||
vendors,
|
||||
locations,
|
||||
lowStockThreshold,
|
||||
}: FilamentTableProps) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [editFilament, setEditFilament] = useState<FilamentRow | undefined>();
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||
const [usageFilament, setUsageFilament] = useState<FilamentRow | null>(null);
|
||||
const [searchValue, setSearchValue] = useState(searchParams.get("search") ?? "");
|
||||
|
||||
// Filter state from URL
|
||||
const materialFilter = new Set(searchParams.getAll("material"));
|
||||
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 = getFilamentColumns({
|
||||
onEdit: (filament) => {
|
||||
setEditFilament(filament);
|
||||
setModalOpen(true);
|
||||
},
|
||||
onArchive: (id) => {
|
||||
startTransition(async () => {
|
||||
const result = await archiveFilament(id);
|
||||
if (result.success) toast.success("Filament updated");
|
||||
else toast.error(result.error);
|
||||
});
|
||||
},
|
||||
onDelete: (id) => setDeleteId(id),
|
||||
onLogUsage: (filament) => setUsageFilament(filament),
|
||||
lowStockThreshold,
|
||||
});
|
||||
|
||||
const { table } = useDataTable({ data, columns, pageCount });
|
||||
|
||||
const handleDelete = () => {
|
||||
if (!deleteId) return;
|
||||
startTransition(async () => {
|
||||
const result = await deleteFilament(deleteId);
|
||||
if (result.success) {
|
||||
toast.success("Filament deleted");
|
||||
setDeleteId(null);
|
||||
} else {
|
||||
toast.error(result.error);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const materialOptions = MATERIALS.map((m) => ({ label: m, value: m }));
|
||||
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="Filaments" description="Manage your 3D printing filament inventory">
|
||||
<Button
|
||||
onClick={() => {
|
||||
setEditFilament(undefined);
|
||||
setModalOpen(true);
|
||||
}}
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Add Filament
|
||||
</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 filaments..."
|
||||
value={searchValue}
|
||||
onChange={(e) => updateSearch(e.target.value)}
|
||||
className="pl-9 h-9"
|
||||
/>
|
||||
</div>
|
||||
<DataTableFacetedFilter
|
||||
title="Material"
|
||||
options={materialOptions}
|
||||
selectedValues={materialFilter}
|
||||
onSelectionChange={(values) => updateFilters("material", 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 filaments found. Add your first spool!" />
|
||||
<DataTablePagination table={table} totalCount={totalCount} />
|
||||
|
||||
<FilamentModal
|
||||
open={modalOpen}
|
||||
onOpenChange={(open) => {
|
||||
setModalOpen(open);
|
||||
if (!open) setEditFilament(undefined);
|
||||
}}
|
||||
filament={
|
||||
editFilament
|
||||
? {
|
||||
id: editFilament.id,
|
||||
name: editFilament.name,
|
||||
brand: editFilament.brand,
|
||||
material: editFilament.material,
|
||||
color: editFilament.color,
|
||||
colorHex: editFilament.colorHex,
|
||||
diameter: 1.75,
|
||||
spoolWeight: editFilament.spoolWeight,
|
||||
usedWeight: editFilament.usedWeight,
|
||||
emptySpoolWeight: 0,
|
||||
cost: editFilament.cost,
|
||||
purchaseDate: editFilament.purchaseDate,
|
||||
notes: null,
|
||||
vendorId: editFilament.vendor?.id ?? null,
|
||||
locationId: editFilament.location?.id ?? null,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
vendors={vendors}
|
||||
locations={locations}
|
||||
/>
|
||||
|
||||
<DeleteDialog
|
||||
open={!!deleteId}
|
||||
onOpenChange={(open) => !open && setDeleteId(null)}
|
||||
title="Delete Filament"
|
||||
description="This will permanently delete this filament spool and all its usage logs."
|
||||
onConfirm={handleDelete}
|
||||
isLoading={isPending}
|
||||
/>
|
||||
|
||||
{usageFilament && (
|
||||
<UsageLogDialog
|
||||
open={!!usageFilament}
|
||||
onOpenChange={(open) => !open && setUsageFilament(null)}
|
||||
itemName={usageFilament.name}
|
||||
unit="g"
|
||||
onSubmit={async (amount, notes) => {
|
||||
const result = await logFilamentUsage(usageFilament.id, { amount, notes });
|
||||
return result;
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
168
src/app/(app)/filaments/actions.ts
Normal file
168
src/app/(app)/filaments/actions.ts
Normal file
@@ -0,0 +1,168 @@
|
||||
"use server";
|
||||
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { filamentSchema } from "@/schemas/filament.schema";
|
||||
import { usageLogSchema } from "@/schemas/usage-log.schema";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import type { ActionResult } from "@/types/api.types";
|
||||
|
||||
export async function createFilament(input: unknown): Promise<ActionResult<{ id: string }>> {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
|
||||
|
||||
const parsed = filamentSchema.safeParse(input);
|
||||
if (!parsed.success) {
|
||||
return { success: false, error: "Validation failed" };
|
||||
}
|
||||
|
||||
try {
|
||||
const filament = await prisma.filament.create({
|
||||
data: {
|
||||
name: parsed.data.name,
|
||||
brand: parsed.data.brand,
|
||||
material: parsed.data.material,
|
||||
color: parsed.data.color,
|
||||
colorHex: parsed.data.colorHex,
|
||||
diameter: parsed.data.diameter,
|
||||
spoolWeight: parsed.data.spoolWeight,
|
||||
usedWeight: parsed.data.usedWeight,
|
||||
emptySpoolWeight: parsed.data.emptySpoolWeight,
|
||||
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("/filaments");
|
||||
revalidatePath("/dashboard");
|
||||
return { success: true, data: { id: filament.id } };
|
||||
} catch {
|
||||
return { success: false, error: "Failed to create filament" };
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateFilament(id: string, input: unknown): Promise<ActionResult> {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
|
||||
|
||||
const parsed = filamentSchema.safeParse(input);
|
||||
if (!parsed.success) {
|
||||
return { success: false, error: "Validation failed" };
|
||||
}
|
||||
|
||||
const existing = await prisma.filament.findFirst({ where: { id, userId: session.user.id } });
|
||||
if (!existing) return { success: false, error: "Not found" };
|
||||
|
||||
try {
|
||||
await prisma.filament.update({
|
||||
where: { id },
|
||||
data: {
|
||||
name: parsed.data.name,
|
||||
brand: parsed.data.brand,
|
||||
material: parsed.data.material,
|
||||
color: parsed.data.color,
|
||||
colorHex: parsed.data.colorHex,
|
||||
diameter: parsed.data.diameter,
|
||||
spoolWeight: parsed.data.spoolWeight,
|
||||
usedWeight: parsed.data.usedWeight,
|
||||
emptySpoolWeight: parsed.data.emptySpoolWeight,
|
||||
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("/filaments");
|
||||
revalidatePath("/dashboard");
|
||||
return { success: true, data: undefined };
|
||||
} catch {
|
||||
return { success: false, error: "Failed to update filament" };
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteFilament(id: string): Promise<ActionResult> {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
|
||||
|
||||
const existing = await prisma.filament.findFirst({ where: { id, userId: session.user.id } });
|
||||
if (!existing) return { success: false, error: "Not found" };
|
||||
|
||||
try {
|
||||
await prisma.filament.delete({ where: { id } });
|
||||
revalidatePath("/filaments");
|
||||
revalidatePath("/dashboard");
|
||||
return { success: true, data: undefined };
|
||||
} catch {
|
||||
return { success: false, error: "Failed to delete filament" };
|
||||
}
|
||||
}
|
||||
|
||||
export async function archiveFilament(id: string): Promise<ActionResult> {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
|
||||
|
||||
const existing = await prisma.filament.findFirst({ where: { id, userId: session.user.id } });
|
||||
if (!existing) return { success: false, error: "Not found" };
|
||||
|
||||
try {
|
||||
await prisma.filament.update({
|
||||
where: { id },
|
||||
data: { archived: !existing.archived },
|
||||
});
|
||||
revalidatePath("/filaments");
|
||||
revalidatePath("/dashboard");
|
||||
return { success: true, data: undefined };
|
||||
} catch {
|
||||
return { success: false, error: "Failed to archive filament" };
|
||||
}
|
||||
}
|
||||
|
||||
export async function logFilamentUsage(
|
||||
filamentId: 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.filament.findFirst({
|
||||
where: { id: filamentId, userId: session.user.id },
|
||||
});
|
||||
if (!existing) return { success: false, error: "Not found" };
|
||||
|
||||
try {
|
||||
await prisma.$transaction([
|
||||
prisma.usageLog.create({
|
||||
data: {
|
||||
itemType: "FILAMENT",
|
||||
itemId: filamentId,
|
||||
filamentId,
|
||||
amount: parsed.data.amount,
|
||||
unit: "g",
|
||||
notes: parsed.data.notes || null,
|
||||
userId: session.user.id,
|
||||
},
|
||||
}),
|
||||
prisma.filament.update({
|
||||
where: { id: filamentId },
|
||||
data: { usedWeight: { increment: parsed.data.amount } },
|
||||
}),
|
||||
]);
|
||||
|
||||
revalidatePath("/filaments");
|
||||
revalidatePath("/dashboard");
|
||||
return { success: true, data: undefined };
|
||||
} catch {
|
||||
return { success: false, error: "Failed to log usage" };
|
||||
}
|
||||
}
|
||||
24
src/app/(app)/filaments/loading.tsx
Normal file
24
src/app/(app)/filaments/loading.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
|
||||
export default function FilamentsLoading() {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<Skeleton className="h-8 w-40" />
|
||||
<Skeleton className="h-9 w-32" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-9 w-64" />
|
||||
<Skeleton className="h-8 w-24" />
|
||||
<Skeleton className="h-8 w-24" />
|
||||
<Skeleton className="h-8 w-24" />
|
||||
</div>
|
||||
<Skeleton className="h-10 w-full" />
|
||||
<div className="space-y-2">
|
||||
{Array.from({ length: 8 }).map((_, i) => (
|
||||
<Skeleton key={i} className="h-10 w-full" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
36
src/app/(app)/filaments/page.tsx
Normal file
36
src/app/(app)/filaments/page.tsx
Normal file
@@ -0,0 +1,36 @@
|
||||
import { auth } from "@/lib/auth";
|
||||
import { redirect } from "next/navigation";
|
||||
import { getFilaments } from "@/data/filament.queries";
|
||||
import { getVendorOptions } from "@/data/vendor.queries";
|
||||
import { getLocationOptions } from "@/data/location.queries";
|
||||
import { getUserSettings } from "@/data/settings.queries";
|
||||
import type { DataTableSearchParams } from "@/types/table.types";
|
||||
import { FilamentTable } from "./_components/filament-table";
|
||||
|
||||
interface Props {
|
||||
searchParams: Promise<DataTableSearchParams>;
|
||||
}
|
||||
|
||||
export default async function FilamentsPage({ searchParams }: Props) {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) redirect("/login");
|
||||
|
||||
const params = await searchParams;
|
||||
const [result, vendors, locations, settings] = await Promise.all([
|
||||
getFilaments(session.user.id, params),
|
||||
getVendorOptions(session.user.id),
|
||||
getLocationOptions(session.user.id),
|
||||
getUserSettings(session.user.id),
|
||||
]);
|
||||
|
||||
return (
|
||||
<FilamentTable
|
||||
data={JSON.parse(JSON.stringify(result.data))}
|
||||
pageCount={result.pageCount}
|
||||
totalCount={result.totalCount}
|
||||
vendors={vendors}
|
||||
locations={locations}
|
||||
lowStockThreshold={settings.lowStockThreshold}
|
||||
/>
|
||||
);
|
||||
}
|
||||
16
src/app/(app)/layout.tsx
Normal file
16
src/app/(app)/layout.tsx
Normal file
@@ -0,0 +1,16 @@
|
||||
import { Sidebar } from "@/components/layout/sidebar";
|
||||
import { Header } from "@/components/layout/header";
|
||||
|
||||
export default function AppLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex h-screen overflow-hidden">
|
||||
<div className="hidden lg:block">
|
||||
<Sidebar />
|
||||
</div>
|
||||
<div className="flex flex-1 flex-col overflow-hidden">
|
||||
<Header />
|
||||
<main className="flex-1 overflow-y-auto p-4 lg:p-6">{children}</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
109
src/app/(app)/locations/_components/location-columns.tsx
Normal file
109
src/app/(app)/locations/_components/location-columns.tsx
Normal file
@@ -0,0 +1,109 @@
|
||||
"use client";
|
||||
|
||||
import { type ColumnDef } from "@tanstack/react-table";
|
||||
import { MoreHorizontal, Pencil, Archive, Trash2 } from "lucide-react";
|
||||
import { DataTableColumnHeader } from "@/components/shared/data-table-column-header";
|
||||
import { StatusBadge } from "@/components/shared/status-badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
|
||||
export interface LocationRow {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
archived: boolean;
|
||||
createdAt: Date;
|
||||
_count: { filaments: number; resins: number; paints: number };
|
||||
}
|
||||
|
||||
interface LocationColumnsProps {
|
||||
onEdit: (location: LocationRow) => void;
|
||||
onArchive: (id: string) => void;
|
||||
onDelete: (id: string) => void;
|
||||
}
|
||||
|
||||
export function getLocationColumns({
|
||||
onEdit,
|
||||
onArchive,
|
||||
onDelete,
|
||||
}: LocationColumnsProps): ColumnDef<LocationRow, unknown>[] {
|
||||
return [
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: ({ column }) => <DataTableColumnHeader column={column} title="Name" />,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium">{row.original.name}</span>
|
||||
{row.original.archived && <StatusBadge variant="archived" />}
|
||||
</div>
|
||||
),
|
||||
enableHiding: false,
|
||||
},
|
||||
{
|
||||
accessorKey: "description",
|
||||
header: ({ column }) => <DataTableColumnHeader column={column} title="Description" />,
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-muted-foreground truncate max-w-[300px] block">
|
||||
{row.original.description || "\u2014"}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "items",
|
||||
header: "Items",
|
||||
cell: ({ row }) => {
|
||||
const c = row.original._count;
|
||||
const total = c.filaments + c.resins + c.paints;
|
||||
return (
|
||||
<span className="text-sm text-muted-foreground">{total}</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "createdAt",
|
||||
header: ({ column }) => <DataTableColumnHeader column={column} title="Created" />,
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{new Date(row.original.createdAt).toLocaleDateString()}
|
||||
</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={() => 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,
|
||||
},
|
||||
];
|
||||
}
|
||||
94
src/app/(app)/locations/_components/location-form.tsx
Normal file
94
src/app/(app)/locations/_components/location-form.tsx
Normal file
@@ -0,0 +1,94 @@
|
||||
"use client";
|
||||
|
||||
import { useTransition } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { toast } from "sonner";
|
||||
import { locationSchema, type LocationInput } from "@/schemas/location.schema";
|
||||
import { createLocation, updateLocation } from "../actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
|
||||
interface LocationFormProps {
|
||||
location?: { id: string; name: string; description: string | null };
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
export function LocationForm({ location, onSuccess }: LocationFormProps) {
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const isEditing = !!location;
|
||||
|
||||
const form = useForm<LocationInput>({
|
||||
resolver: zodResolver(locationSchema),
|
||||
defaultValues: {
|
||||
name: location?.name ?? "",
|
||||
description: location?.description ?? "",
|
||||
},
|
||||
});
|
||||
|
||||
function onSubmit(values: LocationInput) {
|
||||
startTransition(async () => {
|
||||
const result = isEditing
|
||||
? await updateLocation(location!.id, values)
|
||||
: await createLocation(values);
|
||||
|
||||
if (!result.success) {
|
||||
toast.error(result.error);
|
||||
return;
|
||||
}
|
||||
|
||||
toast.success(isEditing ? "Location updated" : "Location created");
|
||||
form.reset();
|
||||
onSuccess();
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Location name" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="description"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Description</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea placeholder="Optional description" rows={3} {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button type="submit" disabled={isPending}>
|
||||
{isPending ? "Saving..." : isEditing ? "Update" : "Create"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
34
src/app/(app)/locations/_components/location-modal.tsx
Normal file
34
src/app/(app)/locations/_components/location-modal.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { LocationForm } from "./location-form";
|
||||
|
||||
interface LocationModalProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
location?: { id: string; name: string; description: string | null };
|
||||
}
|
||||
|
||||
export function LocationModal({ open, onOpenChange, location }: LocationModalProps) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{location ? "Edit Location" : "Add Location"}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{location
|
||||
? "Update the location details below."
|
||||
: "Add a new storage location."}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<LocationForm location={location} onSuccess={() => onOpenChange(false)} />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
127
src/app/(app)/locations/_components/location-table.tsx
Normal file
127
src/app/(app)/locations/_components/location-table.tsx
Normal file
@@ -0,0 +1,127 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useTransition } 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 { getLocationColumns, type LocationRow } from "./location-columns";
|
||||
import { LocationModal } from "./location-modal";
|
||||
import { deleteLocation, archiveLocation } 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 { DeleteDialog } from "@/components/shared/delete-dialog";
|
||||
import { PageHeader } from "@/components/shared/page-header";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
|
||||
interface LocationTableProps {
|
||||
data: LocationRow[];
|
||||
pageCount: number;
|
||||
totalCount: number;
|
||||
}
|
||||
|
||||
export function LocationTable({ data, pageCount, totalCount }: LocationTableProps) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [editLocation, setEditLocation] = useState<LocationRow | undefined>();
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||
const [searchValue, setSearchValue] = useState(searchParams.get("search") ?? "");
|
||||
|
||||
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 = getLocationColumns({
|
||||
onEdit: (location) => {
|
||||
setEditLocation(location);
|
||||
setModalOpen(true);
|
||||
},
|
||||
onArchive: (id) => {
|
||||
startTransition(async () => {
|
||||
const result = await archiveLocation(id);
|
||||
if (result.success) toast.success("Location updated");
|
||||
else toast.error(result.error);
|
||||
});
|
||||
},
|
||||
onDelete: (id) => setDeleteId(id),
|
||||
});
|
||||
|
||||
const { table } = useDataTable({ data, columns, pageCount });
|
||||
|
||||
const handleDelete = () => {
|
||||
if (!deleteId) return;
|
||||
startTransition(async () => {
|
||||
const result = await deleteLocation(deleteId);
|
||||
if (result.success) {
|
||||
toast.success("Location deleted");
|
||||
setDeleteId(null);
|
||||
} else {
|
||||
toast.error(result.error);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<PageHeader title="Locations" description="Manage your storage locations">
|
||||
<Button
|
||||
onClick={() => {
|
||||
setEditLocation(undefined);
|
||||
setModalOpen(true);
|
||||
}}
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Add Location
|
||||
</Button>
|
||||
</PageHeader>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="relative flex-1 max-w-sm">
|
||||
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search locations..."
|
||||
value={searchValue}
|
||||
onChange={(e) => updateSearch(e.target.value)}
|
||||
className="pl-9 h-9"
|
||||
/>
|
||||
</div>
|
||||
<DataTableViewOptions table={table} />
|
||||
</div>
|
||||
|
||||
<DataTable table={table} emptyMessage="No locations found. Add your first location!" />
|
||||
<DataTablePagination table={table} totalCount={totalCount} />
|
||||
|
||||
<LocationModal
|
||||
open={modalOpen}
|
||||
onOpenChange={(open) => {
|
||||
setModalOpen(open);
|
||||
if (!open) setEditLocation(undefined);
|
||||
}}
|
||||
location={editLocation}
|
||||
/>
|
||||
|
||||
<DeleteDialog
|
||||
open={!!deleteId}
|
||||
onOpenChange={(open) => !open && setDeleteId(null)}
|
||||
title="Delete Location"
|
||||
description="This will permanently delete this location. Items stored here will be unlinked."
|
||||
onConfirm={handleDelete}
|
||||
isLoading={isPending}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
95
src/app/(app)/locations/actions.ts
Normal file
95
src/app/(app)/locations/actions.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
"use server";
|
||||
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { locationSchema } from "@/schemas/location.schema";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import type { ActionResult } from "@/types/api.types";
|
||||
|
||||
export async function createLocation(input: unknown): Promise<ActionResult<{ id: string }>> {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
|
||||
|
||||
const parsed = locationSchema.safeParse(input);
|
||||
if (!parsed.success) {
|
||||
return { success: false, error: "Validation failed" };
|
||||
}
|
||||
|
||||
try {
|
||||
const location = await prisma.location.create({
|
||||
data: {
|
||||
...parsed.data,
|
||||
description: parsed.data.description || null,
|
||||
userId: session.user.id,
|
||||
},
|
||||
});
|
||||
|
||||
revalidatePath("/locations");
|
||||
return { success: true, data: { id: location.id } };
|
||||
} catch {
|
||||
return { success: false, error: "Failed to create location" };
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateLocation(id: string, input: unknown): Promise<ActionResult> {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
|
||||
|
||||
const parsed = locationSchema.safeParse(input);
|
||||
if (!parsed.success) {
|
||||
return { success: false, error: "Validation failed" };
|
||||
}
|
||||
|
||||
const existing = await prisma.location.findFirst({ where: { id, userId: session.user.id } });
|
||||
if (!existing) return { success: false, error: "Not found" };
|
||||
|
||||
try {
|
||||
await prisma.location.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...parsed.data,
|
||||
description: parsed.data.description || null,
|
||||
},
|
||||
});
|
||||
|
||||
revalidatePath("/locations");
|
||||
return { success: true, data: undefined };
|
||||
} catch {
|
||||
return { success: false, error: "Failed to update location" };
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteLocation(id: string): Promise<ActionResult> {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
|
||||
|
||||
const existing = await prisma.location.findFirst({ where: { id, userId: session.user.id } });
|
||||
if (!existing) return { success: false, error: "Not found" };
|
||||
|
||||
try {
|
||||
await prisma.location.delete({ where: { id } });
|
||||
revalidatePath("/locations");
|
||||
return { success: true, data: undefined };
|
||||
} catch {
|
||||
return { success: false, error: "Failed to delete location" };
|
||||
}
|
||||
}
|
||||
|
||||
export async function archiveLocation(id: string): Promise<ActionResult> {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
|
||||
|
||||
const existing = await prisma.location.findFirst({ where: { id, userId: session.user.id } });
|
||||
if (!existing) return { success: false, error: "Not found" };
|
||||
|
||||
try {
|
||||
await prisma.location.update({
|
||||
where: { id },
|
||||
data: { archived: !existing.archived },
|
||||
});
|
||||
revalidatePath("/locations");
|
||||
return { success: true, data: undefined };
|
||||
} catch {
|
||||
return { success: false, error: "Failed to archive location" };
|
||||
}
|
||||
}
|
||||
30
src/app/(app)/locations/loading.tsx
Normal file
30
src/app/(app)/locations/loading.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
|
||||
export default function LocationsLoading() {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<Skeleton className="h-8 w-40" />
|
||||
<Skeleton className="mt-1 h-4 w-60" />
|
||||
</div>
|
||||
<Skeleton className="h-9 w-32" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-9 w-64" />
|
||||
<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-4 w-32" />
|
||||
<Skeleton className="h-4 w-48" />
|
||||
<Skeleton className="h-4 w-16" />
|
||||
<Skeleton className="h-4 w-24" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
30
src/app/(app)/locations/page.tsx
Normal file
30
src/app/(app)/locations/page.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
import { auth } from "@/lib/auth";
|
||||
import { redirect } from "next/navigation";
|
||||
import { getLocations } from "@/data/location.queries";
|
||||
import { LocationTable } from "./_components/location-table";
|
||||
|
||||
interface LocationsPageProps {
|
||||
searchParams: Promise<Record<string, string | string[] | undefined>>;
|
||||
}
|
||||
|
||||
export default async function LocationsPage({ searchParams }: LocationsPageProps) {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) redirect("/login");
|
||||
|
||||
const params = await searchParams;
|
||||
const { data, pageCount, totalCount } = await getLocations(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,
|
||||
});
|
||||
|
||||
return (
|
||||
<LocationTable
|
||||
data={JSON.parse(JSON.stringify(data))}
|
||||
pageCount={pageCount}
|
||||
totalCount={totalCount}
|
||||
/>
|
||||
);
|
||||
}
|
||||
190
src/app/(app)/paints/_components/paint-columns.tsx
Normal file
190
src/app/(app)/paints/_components/paint-columns.tsx
Normal file
@@ -0,0 +1,190 @@
|
||||
"use client";
|
||||
|
||||
import { type ColumnDef } from "@tanstack/react-table";
|
||||
import { MoreHorizontal, Pencil, Archive, Trash2, Droplet } 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 PaintRow {
|
||||
id: string;
|
||||
name: string;
|
||||
brand: string;
|
||||
line: string | null;
|
||||
color: string;
|
||||
colorHex: string;
|
||||
finish: string;
|
||||
volumeML: 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 PaintColumnsProps {
|
||||
onEdit: (paint: PaintRow) => void;
|
||||
onArchive: (id: string) => void;
|
||||
onDelete: (id: string) => void;
|
||||
onLogUsage: (paint: PaintRow) => void;
|
||||
lowStockThreshold: number;
|
||||
}
|
||||
|
||||
export function getPaintColumns({
|
||||
onEdit,
|
||||
onArchive,
|
||||
onDelete,
|
||||
onLogUsage,
|
||||
lowStockThreshold,
|
||||
}: PaintColumnsProps): ColumnDef<PaintRow, 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.volumeML - row.original.usedML;
|
||||
const status = getStockStatus(
|
||||
remaining,
|
||||
row.original.volumeML,
|
||||
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 }) => (
|
||||
<div className="flex flex-col">
|
||||
<span className="text-sm">{row.original.brand}</span>
|
||||
{row.original.line && (
|
||||
<span className="text-xs text-muted-foreground">{row.original.line}</span>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "finish",
|
||||
header: ({ column }) => <DataTableColumnHeader column={column} title="Finish" />,
|
||||
cell: ({ row }) => (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{row.original.finish}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "remaining",
|
||||
header: ({ column }) => <DataTableColumnHeader column={column} title="Remaining" />,
|
||||
cell: ({ row }) => {
|
||||
const remaining = row.original.volumeML - row.original.usedML;
|
||||
const percent =
|
||||
row.original.volumeML > 0
|
||||
? (remaining / row.original.volumeML) * 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-14 text-right">
|
||||
{remaining.toFixed(1)} 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)}>
|
||||
<Droplet 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,
|
||||
},
|
||||
];
|
||||
}
|
||||
380
src/app/(app)/paints/_components/paint-form.tsx
Normal file
380
src/app/(app)/paints/_components/paint-form.tsx
Normal file
@@ -0,0 +1,380 @@
|
||||
"use client";
|
||||
|
||||
import { useTransition } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { toast } from "sonner";
|
||||
import { paintSchema, type PaintInput } from "@/schemas/paint.schema";
|
||||
import { PAINT_FINISHES } from "@/lib/constants";
|
||||
import { createPaint, updatePaint } 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 PaintFormProps {
|
||||
paint?: {
|
||||
id: string;
|
||||
name: string;
|
||||
brand: string;
|
||||
line: string | null;
|
||||
color: string;
|
||||
colorHex: string;
|
||||
finish: string;
|
||||
volumeML: 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 PaintForm({ paint, vendors, locations, onSuccess }: PaintFormProps) {
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const isEditing = !!paint;
|
||||
|
||||
const form = useForm<PaintInput>({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
resolver: zodResolver(paintSchema) as any,
|
||||
defaultValues: {
|
||||
name: paint?.name ?? "",
|
||||
brand: paint?.brand ?? "",
|
||||
line: paint?.line ?? "",
|
||||
color: paint?.color ?? "",
|
||||
colorHex: paint?.colorHex ?? "#000000",
|
||||
finish: (paint?.finish as PaintInput["finish"]) ?? "Matte",
|
||||
volumeML: paint?.volumeML ?? 17,
|
||||
usedML: paint?.usedML ?? 0,
|
||||
cost: paint?.cost ?? undefined,
|
||||
purchaseDate: paint?.purchaseDate
|
||||
? new Date(paint.purchaseDate).toISOString().split("T")[0]
|
||||
: "",
|
||||
notes: paint?.notes ?? "",
|
||||
vendorId: paint?.vendorId ?? "",
|
||||
locationId: paint?.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.line) form.setValue("line", item.line);
|
||||
if (item.finish) {
|
||||
const match = PAINT_FINISHES.find(
|
||||
(f) => f.toUpperCase() === item.finish!.toUpperCase(),
|
||||
);
|
||||
if (match) form.setValue("finish", match);
|
||||
}
|
||||
if (item.volume) form.setValue("volumeML", item.volume);
|
||||
if (item.price != null) form.setValue("cost", item.price);
|
||||
}
|
||||
|
||||
function onSubmit(values: PaintInput) {
|
||||
startTransition(async () => {
|
||||
const result = isEditing
|
||||
? await updatePaint(paint!.id, values)
|
||||
: await createPaint(values);
|
||||
|
||||
if (!result.success) {
|
||||
toast.error(result.error);
|
||||
return;
|
||||
}
|
||||
|
||||
toast.success(isEditing ? "Paint updated" : "Paint 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="paint" 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="paint"
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
onSelectItem={handleCatalogSelect}
|
||||
placeholder="Paint name — type to search catalog"
|
||||
/>
|
||||
) : (
|
||||
<Input placeholder="Paint 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="line"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Product Line</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="e.g. Base, Layer, Contrast" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="finish"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Finish</FormLabel>
|
||||
<Select onValueChange={field.onChange} value={field.value}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select finish" />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{PAINT_FINISHES.map((f) => (
|
||||
<SelectItem key={f} value={f}>
|
||||
{f}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="color"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Color Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="e.g. Retributor Armour" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="colorHex"
|
||||
render={({ field }) => (
|
||||
<FormItem className="col-span-2">
|
||||
<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="volumeML"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Volume (ml)</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="number" step="0.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>
|
||||
);
|
||||
}
|
||||
50
src/app/(app)/paints/_components/paint-modal.tsx
Normal file
50
src/app/(app)/paints/_components/paint-modal.tsx
Normal 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 { PaintForm } from "./paint-form";
|
||||
|
||||
interface PaintModalProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
paint?: Parameters<typeof PaintForm>[0]["paint"];
|
||||
vendors: { id: string; name: string }[];
|
||||
locations: { id: string; name: string }[];
|
||||
}
|
||||
|
||||
export function PaintModal({
|
||||
open,
|
||||
onOpenChange,
|
||||
paint,
|
||||
vendors,
|
||||
locations,
|
||||
}: PaintModalProps) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-2xl max-h-[90vh]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{paint ? "Edit Paint" : "Add Paint"}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{paint
|
||||
? "Update the paint details below."
|
||||
: "Add a new paint to your inventory."}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<ScrollArea className="max-h-[70vh] pr-4">
|
||||
<PaintForm
|
||||
paint={paint}
|
||||
vendors={vendors}
|
||||
locations={locations}
|
||||
onSuccess={() => onOpenChange(false)}
|
||||
/>
|
||||
</ScrollArea>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
214
src/app/(app)/paints/_components/paint-table.tsx
Normal file
214
src/app/(app)/paints/_components/paint-table.tsx
Normal file
@@ -0,0 +1,214 @@
|
||||
"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 { PAINT_FINISHES } from "@/lib/constants";
|
||||
import { getPaintColumns, type PaintRow } from "./paint-columns";
|
||||
import { PaintModal } from "./paint-modal";
|
||||
import { deletePaint, archivePaint, logPaintUsage } 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 PaintTableProps {
|
||||
data: PaintRow[];
|
||||
pageCount: number;
|
||||
totalCount: number;
|
||||
vendors: { id: string; name: string }[];
|
||||
locations: { id: string; name: string }[];
|
||||
lowStockThreshold: number;
|
||||
}
|
||||
|
||||
export function PaintTable({
|
||||
data,
|
||||
pageCount,
|
||||
totalCount,
|
||||
vendors,
|
||||
locations,
|
||||
lowStockThreshold,
|
||||
}: PaintTableProps) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [editPaint, setEditPaint] = useState<PaintRow | undefined>();
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||
const [usagePaint, setUsagePaint] = useState<PaintRow | null>(null);
|
||||
const [searchValue, setSearchValue] = useState(searchParams.get("search") ?? "");
|
||||
|
||||
const finishFilter = new Set(searchParams.getAll("finish"));
|
||||
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 = getPaintColumns({
|
||||
onEdit: (paint) => {
|
||||
setEditPaint(paint);
|
||||
setModalOpen(true);
|
||||
},
|
||||
onArchive: (id) => {
|
||||
startTransition(async () => {
|
||||
const result = await archivePaint(id);
|
||||
if (result.success) toast.success("Paint updated");
|
||||
else toast.error(result.error);
|
||||
});
|
||||
},
|
||||
onDelete: (id) => setDeleteId(id),
|
||||
onLogUsage: (paint) => setUsagePaint(paint),
|
||||
lowStockThreshold,
|
||||
});
|
||||
|
||||
const { table } = useDataTable({ data, columns, pageCount });
|
||||
|
||||
const handleDelete = () => {
|
||||
if (!deleteId) return;
|
||||
startTransition(async () => {
|
||||
const result = await deletePaint(deleteId);
|
||||
if (result.success) {
|
||||
toast.success("Paint deleted");
|
||||
setDeleteId(null);
|
||||
} else {
|
||||
toast.error(result.error);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const finishOptions = PAINT_FINISHES.map((f) => ({ label: f, value: f }));
|
||||
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="Paints" description="Manage your miniature paint collection">
|
||||
<Button
|
||||
onClick={() => {
|
||||
setEditPaint(undefined);
|
||||
setModalOpen(true);
|
||||
}}
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Add Paint
|
||||
</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 paints..."
|
||||
value={searchValue}
|
||||
onChange={(e) => updateSearch(e.target.value)}
|
||||
className="pl-9 h-9"
|
||||
/>
|
||||
</div>
|
||||
<DataTableFacetedFilter
|
||||
title="Finish"
|
||||
options={finishOptions}
|
||||
selectedValues={finishFilter}
|
||||
onSelectionChange={(values) => updateFilters("finish", 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 paints found. Add your first paint!" />
|
||||
<DataTablePagination table={table} totalCount={totalCount} />
|
||||
|
||||
<PaintModal
|
||||
open={modalOpen}
|
||||
onOpenChange={(open) => {
|
||||
setModalOpen(open);
|
||||
if (!open) setEditPaint(undefined);
|
||||
}}
|
||||
paint={
|
||||
editPaint
|
||||
? {
|
||||
id: editPaint.id,
|
||||
name: editPaint.name,
|
||||
brand: editPaint.brand,
|
||||
line: editPaint.line,
|
||||
color: editPaint.color,
|
||||
colorHex: editPaint.colorHex,
|
||||
finish: editPaint.finish,
|
||||
volumeML: editPaint.volumeML,
|
||||
usedML: editPaint.usedML,
|
||||
cost: editPaint.cost,
|
||||
purchaseDate: editPaint.purchaseDate,
|
||||
notes: editPaint.notes,
|
||||
vendorId: editPaint.vendor?.id ?? null,
|
||||
locationId: editPaint.location?.id ?? null,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
vendors={vendors}
|
||||
locations={locations}
|
||||
/>
|
||||
|
||||
<DeleteDialog
|
||||
open={!!deleteId}
|
||||
onOpenChange={(open) => !open && setDeleteId(null)}
|
||||
title="Delete Paint"
|
||||
description="This will permanently delete this paint and all its usage logs."
|
||||
onConfirm={handleDelete}
|
||||
isLoading={isPending}
|
||||
/>
|
||||
|
||||
{usagePaint && (
|
||||
<UsageLogDialog
|
||||
open={!!usagePaint}
|
||||
onOpenChange={(open) => !open && setUsagePaint(null)}
|
||||
itemName={usagePaint.name}
|
||||
unit="ml"
|
||||
onSubmit={async (amount, notes) => {
|
||||
const result = await logPaintUsage(usagePaint.id, { amount, notes });
|
||||
return result;
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
155
src/app/(app)/paints/actions.ts
Normal file
155
src/app/(app)/paints/actions.ts
Normal file
@@ -0,0 +1,155 @@
|
||||
"use server";
|
||||
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { paintSchema } from "@/schemas/paint.schema";
|
||||
import { usageLogSchema } from "@/schemas/usage-log.schema";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import type { ActionResult } from "@/types/api.types";
|
||||
|
||||
export async function createPaint(input: unknown): Promise<ActionResult<{ id: string }>> {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
|
||||
|
||||
const parsed = paintSchema.safeParse(input);
|
||||
if (!parsed.success) return { success: false, error: "Validation failed" };
|
||||
|
||||
try {
|
||||
const paint = await prisma.paint.create({
|
||||
data: {
|
||||
name: parsed.data.name,
|
||||
brand: parsed.data.brand,
|
||||
line: parsed.data.line || null,
|
||||
color: parsed.data.color,
|
||||
colorHex: parsed.data.colorHex,
|
||||
finish: parsed.data.finish,
|
||||
volumeML: parsed.data.volumeML,
|
||||
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("/paints");
|
||||
revalidatePath("/dashboard");
|
||||
return { success: true, data: { id: paint.id } };
|
||||
} catch {
|
||||
return { success: false, error: "Failed to create paint" };
|
||||
}
|
||||
}
|
||||
|
||||
export async function updatePaint(id: string, input: unknown): Promise<ActionResult> {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
|
||||
|
||||
const parsed = paintSchema.safeParse(input);
|
||||
if (!parsed.success) return { success: false, error: "Validation failed" };
|
||||
|
||||
const existing = await prisma.paint.findFirst({ where: { id, userId: session.user.id } });
|
||||
if (!existing) return { success: false, error: "Not found" };
|
||||
|
||||
try {
|
||||
await prisma.paint.update({
|
||||
where: { id },
|
||||
data: {
|
||||
name: parsed.data.name,
|
||||
brand: parsed.data.brand,
|
||||
line: parsed.data.line || null,
|
||||
color: parsed.data.color,
|
||||
colorHex: parsed.data.colorHex,
|
||||
finish: parsed.data.finish,
|
||||
volumeML: parsed.data.volumeML,
|
||||
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("/paints");
|
||||
revalidatePath("/dashboard");
|
||||
return { success: true, data: undefined };
|
||||
} catch {
|
||||
return { success: false, error: "Failed to update paint" };
|
||||
}
|
||||
}
|
||||
|
||||
export async function deletePaint(id: string): Promise<ActionResult> {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
|
||||
|
||||
const existing = await prisma.paint.findFirst({ where: { id, userId: session.user.id } });
|
||||
if (!existing) return { success: false, error: "Not found" };
|
||||
|
||||
try {
|
||||
await prisma.paint.delete({ where: { id } });
|
||||
revalidatePath("/paints");
|
||||
revalidatePath("/dashboard");
|
||||
return { success: true, data: undefined };
|
||||
} catch {
|
||||
return { success: false, error: "Failed to delete paint" };
|
||||
}
|
||||
}
|
||||
|
||||
export async function archivePaint(id: string): Promise<ActionResult> {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
|
||||
|
||||
const existing = await prisma.paint.findFirst({ where: { id, userId: session.user.id } });
|
||||
if (!existing) return { success: false, error: "Not found" };
|
||||
|
||||
try {
|
||||
await prisma.paint.update({
|
||||
where: { id },
|
||||
data: { archived: !existing.archived },
|
||||
});
|
||||
revalidatePath("/paints");
|
||||
revalidatePath("/dashboard");
|
||||
return { success: true, data: undefined };
|
||||
} catch {
|
||||
return { success: false, error: "Failed to archive paint" };
|
||||
}
|
||||
}
|
||||
|
||||
export async function logPaintUsage(paintId: 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.paint.findFirst({ where: { id: paintId, userId: session.user.id } });
|
||||
if (!existing) return { success: false, error: "Not found" };
|
||||
|
||||
try {
|
||||
await prisma.$transaction([
|
||||
prisma.usageLog.create({
|
||||
data: {
|
||||
itemType: "PAINT",
|
||||
itemId: paintId,
|
||||
paintId,
|
||||
amount: parsed.data.amount,
|
||||
unit: "ml",
|
||||
notes: parsed.data.notes || null,
|
||||
userId: session.user.id,
|
||||
},
|
||||
}),
|
||||
prisma.paint.update({
|
||||
where: { id: paintId },
|
||||
data: { usedML: { increment: parsed.data.amount } },
|
||||
}),
|
||||
]);
|
||||
|
||||
revalidatePath("/paints");
|
||||
revalidatePath("/dashboard");
|
||||
return { success: true, data: undefined };
|
||||
} catch {
|
||||
return { success: false, error: "Failed to log usage" };
|
||||
}
|
||||
}
|
||||
34
src/app/(app)/paints/loading.tsx
Normal file
34
src/app/(app)/paints/loading.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
|
||||
export default function PaintsLoading() {
|
||||
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>
|
||||
);
|
||||
}
|
||||
44
src/app/(app)/paints/page.tsx
Normal file
44
src/app/(app)/paints/page.tsx
Normal file
@@ -0,0 +1,44 @@
|
||||
import { auth } from "@/lib/auth";
|
||||
import { redirect } from "next/navigation";
|
||||
import { getPaints } from "@/data/paint.queries";
|
||||
import { getVendorOptions } from "@/data/vendor.queries";
|
||||
import { getLocationOptions } from "@/data/location.queries";
|
||||
import { getUserSettings } from "@/data/settings.queries";
|
||||
import { PaintTable } from "./_components/paint-table";
|
||||
|
||||
interface PaintsPageProps {
|
||||
searchParams: Promise<Record<string, string | string[] | undefined>>;
|
||||
}
|
||||
|
||||
export default async function PaintsPage({ searchParams }: PaintsPageProps) {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) redirect("/login");
|
||||
|
||||
const params = await searchParams;
|
||||
const [paintsResult, vendors, locations, settings] = await Promise.all([
|
||||
getPaints(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,
|
||||
finish: params.finish,
|
||||
vendor: params.vendor,
|
||||
location: params.location,
|
||||
}),
|
||||
getVendorOptions(session.user.id),
|
||||
getLocationOptions(session.user.id),
|
||||
getUserSettings(session.user.id),
|
||||
]);
|
||||
|
||||
return (
|
||||
<PaintTable
|
||||
data={JSON.parse(JSON.stringify(paintsResult.data))}
|
||||
pageCount={paintsResult.pageCount}
|
||||
totalCount={paintsResult.totalCount}
|
||||
vendors={vendors}
|
||||
locations={locations}
|
||||
lowStockThreshold={settings.lowStockThreshold}
|
||||
/>
|
||||
);
|
||||
}
|
||||
184
src/app/(app)/resins/_components/resin-columns.tsx
Normal file
184
src/app/(app)/resins/_components/resin-columns.tsx
Normal 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,
|
||||
},
|
||||
];
|
||||
}
|
||||
363
src/app/(app)/resins/_components/resin-form.tsx
Normal file
363
src/app/(app)/resins/_components/resin-form.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
50
src/app/(app)/resins/_components/resin-modal.tsx
Normal file
50
src/app/(app)/resins/_components/resin-modal.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
213
src/app/(app)/resins/_components/resin-table.tsx
Normal file
213
src/app/(app)/resins/_components/resin-table.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
153
src/app/(app)/resins/actions.ts
Normal file
153
src/app/(app)/resins/actions.ts
Normal 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" };
|
||||
}
|
||||
}
|
||||
34
src/app/(app)/resins/loading.tsx
Normal file
34
src/app/(app)/resins/loading.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
44
src/app/(app)/resins/page.tsx
Normal file
44
src/app/(app)/resins/page.tsx
Normal 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}
|
||||
/>
|
||||
);
|
||||
}
|
||||
205
src/app/(app)/settings/_components/settings-form.tsx
Normal file
205
src/app/(app)/settings/_components/settings-form.tsx
Normal file
@@ -0,0 +1,205 @@
|
||||
"use client";
|
||||
|
||||
import { useTransition } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { toast } from "sonner";
|
||||
import { useTheme } from "next-themes";
|
||||
import { settingsSchema, type SettingsInput } from "@/schemas/settings.schema";
|
||||
import { CURRENCIES, UNITS } from "@/lib/constants";
|
||||
import { updateSettings } from "../actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
|
||||
interface SettingsFormProps {
|
||||
settings: {
|
||||
lowStockThreshold: number;
|
||||
currency: string;
|
||||
theme: string;
|
||||
units: string;
|
||||
};
|
||||
}
|
||||
|
||||
export function SettingsForm({ settings }: SettingsFormProps) {
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const { setTheme } = useTheme();
|
||||
|
||||
const form = useForm<SettingsInput>({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
resolver: zodResolver(settingsSchema) as any,
|
||||
defaultValues: {
|
||||
lowStockThreshold: settings.lowStockThreshold,
|
||||
currency: settings.currency as SettingsInput["currency"],
|
||||
theme: settings.theme as SettingsInput["theme"],
|
||||
units: settings.units as SettingsInput["units"],
|
||||
},
|
||||
});
|
||||
|
||||
function onSubmit(values: SettingsInput) {
|
||||
startTransition(async () => {
|
||||
const result = await updateSettings(values);
|
||||
if (!result.success) {
|
||||
toast.error(result.error);
|
||||
return;
|
||||
}
|
||||
setTheme(values.theme);
|
||||
toast.success("Settings updated");
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Inventory Settings</CardTitle>
|
||||
<CardDescription>
|
||||
Configure stock thresholds and display preferences.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="lowStockThreshold"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Low Stock Threshold (%)</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="number" min="0" max="100" step="1" {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Items with remaining stock below this percentage will be flagged as
|
||||
low stock.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="currency"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Currency</FormLabel>
|
||||
<Select onValueChange={field.onChange} value={field.value}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{CURRENCIES.map((c) => (
|
||||
<SelectItem key={c} value={c}>
|
||||
{c}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormDescription>
|
||||
Display currency for cost values.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="units"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Unit System</FormLabel>
|
||||
<Select onValueChange={field.onChange} value={field.value}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{UNITS.map((u) => (
|
||||
<SelectItem key={u} value={u}>
|
||||
{u.charAt(0).toUpperCase() + u.slice(1)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormDescription>
|
||||
Measurement system for weight and volume.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Separator />
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Appearance</CardTitle>
|
||||
<CardDescription>Customize the look and feel.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="theme"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Theme</FormLabel>
|
||||
<Select onValueChange={field.onChange} value={field.value}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
<SelectItem value="dark">Dark</SelectItem>
|
||||
<SelectItem value="light">Light</SelectItem>
|
||||
<SelectItem value="system">System</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormDescription>
|
||||
Choose your preferred color theme.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button type="submit" disabled={isPending}>
|
||||
{isPending ? "Saving..." : "Save Settings"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
43
src/app/(app)/settings/actions.ts
Normal file
43
src/app/(app)/settings/actions.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
"use server";
|
||||
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { settingsSchema } from "@/schemas/settings.schema";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import type { ActionResult } from "@/types/api.types";
|
||||
|
||||
export async function updateSettings(input: unknown): Promise<ActionResult> {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
|
||||
|
||||
const parsed = settingsSchema.safeParse(input);
|
||||
if (!parsed.success) return { success: false, error: "Validation failed" };
|
||||
|
||||
try {
|
||||
await prisma.userSettings.upsert({
|
||||
where: { userId: session.user.id },
|
||||
update: {
|
||||
lowStockThreshold: parsed.data.lowStockThreshold,
|
||||
currency: parsed.data.currency,
|
||||
theme: parsed.data.theme,
|
||||
units: parsed.data.units,
|
||||
},
|
||||
create: {
|
||||
userId: session.user.id,
|
||||
lowStockThreshold: parsed.data.lowStockThreshold,
|
||||
currency: parsed.data.currency,
|
||||
theme: parsed.data.theme,
|
||||
units: parsed.data.units,
|
||||
},
|
||||
});
|
||||
|
||||
revalidatePath("/settings");
|
||||
revalidatePath("/dashboard");
|
||||
revalidatePath("/filaments");
|
||||
revalidatePath("/resins");
|
||||
revalidatePath("/paints");
|
||||
return { success: true, data: undefined };
|
||||
} catch {
|
||||
return { success: false, error: "Failed to update settings" };
|
||||
}
|
||||
}
|
||||
24
src/app/(app)/settings/loading.tsx
Normal file
24
src/app/(app)/settings/loading.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
|
||||
export default function SettingsLoading() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<Skeleton className="h-8 w-32" />
|
||||
<Skeleton className="mt-1 h-4 w-64" />
|
||||
</div>
|
||||
<div className="max-w-2xl space-y-6">
|
||||
<div className="rounded-lg border p-6 space-y-4">
|
||||
<Skeleton className="h-6 w-40" />
|
||||
<div className="space-y-3">
|
||||
<Skeleton className="h-9 w-full" />
|
||||
<Skeleton className="h-9 w-full" />
|
||||
<Skeleton className="h-9 w-full" />
|
||||
<Skeleton className="h-9 w-full" />
|
||||
</div>
|
||||
<Skeleton className="h-9 w-24" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
26
src/app/(app)/settings/page.tsx
Normal file
26
src/app/(app)/settings/page.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
import { auth } from "@/lib/auth";
|
||||
import { redirect } from "next/navigation";
|
||||
import { getUserSettings } from "@/data/settings.queries";
|
||||
import { PageHeader } from "@/components/shared/page-header";
|
||||
import { SettingsForm } from "./_components/settings-form";
|
||||
|
||||
export default async function SettingsPage() {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) redirect("/login");
|
||||
|
||||
const settings = await getUserSettings(session.user.id);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PageHeader
|
||||
title="Settings"
|
||||
description="Manage your application preferences"
|
||||
/>
|
||||
<div className="max-w-2xl">
|
||||
<SettingsForm
|
||||
settings={JSON.parse(JSON.stringify(settings))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
120
src/app/(app)/vendors/_components/vendor-columns.tsx
vendored
Normal file
120
src/app/(app)/vendors/_components/vendor-columns.tsx
vendored
Normal file
@@ -0,0 +1,120 @@
|
||||
"use client";
|
||||
|
||||
import { type ColumnDef } from "@tanstack/react-table";
|
||||
import { MoreHorizontal, Pencil, Archive, Trash2, ExternalLink } from "lucide-react";
|
||||
import { DataTableColumnHeader } from "@/components/shared/data-table-column-header";
|
||||
import { StatusBadge } from "@/components/shared/status-badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
|
||||
interface VendorRow {
|
||||
id: string;
|
||||
name: string;
|
||||
website: string | null;
|
||||
notes: string | null;
|
||||
archived: boolean;
|
||||
createdAt: Date;
|
||||
_count: { filaments: number; resins: number; paints: number };
|
||||
}
|
||||
|
||||
interface VendorColumnsProps {
|
||||
onEdit: (vendor: VendorRow) => void;
|
||||
onArchive: (id: string) => void;
|
||||
onDelete: (id: string) => void;
|
||||
}
|
||||
|
||||
export function getVendorColumns({
|
||||
onEdit,
|
||||
onArchive,
|
||||
onDelete,
|
||||
}: VendorColumnsProps): ColumnDef<VendorRow, unknown>[] {
|
||||
return [
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: ({ column }) => <DataTableColumnHeader column={column} title="Name" />,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium">{row.original.name}</span>
|
||||
{row.original.archived && <StatusBadge variant="archived" />}
|
||||
</div>
|
||||
),
|
||||
enableHiding: false,
|
||||
},
|
||||
{
|
||||
accessorKey: "website",
|
||||
header: ({ column }) => <DataTableColumnHeader column={column} title="Website" />,
|
||||
cell: ({ row }) =>
|
||||
row.original.website ? (
|
||||
<a
|
||||
href={row.original.website}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-1 text-sm text-primary hover:underline"
|
||||
>
|
||||
{new URL(row.original.website).hostname}
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</a>
|
||||
) : (
|
||||
<span className="text-muted-foreground">—</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "items",
|
||||
header: "Items",
|
||||
cell: ({ row }) => {
|
||||
const c = row.original._count;
|
||||
return (
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{c.filaments + c.resins + c.paints}
|
||||
</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "createdAt",
|
||||
header: ({ column }) => <DataTableColumnHeader column={column} title="Created" />,
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{new Date(row.original.createdAt).toLocaleDateString()}
|
||||
</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={() => 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,
|
||||
},
|
||||
];
|
||||
}
|
||||
109
src/app/(app)/vendors/_components/vendor-form.tsx
vendored
Normal file
109
src/app/(app)/vendors/_components/vendor-form.tsx
vendored
Normal file
@@ -0,0 +1,109 @@
|
||||
"use client";
|
||||
|
||||
import { useTransition } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { toast } from "sonner";
|
||||
import { vendorSchema, type VendorInput } from "@/schemas/vendor.schema";
|
||||
import { createVendor, updateVendor } from "../actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
|
||||
interface VendorFormProps {
|
||||
vendor?: { id: string; name: string; website: string | null; notes: string | null };
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
export function VendorForm({ vendor, onSuccess }: VendorFormProps) {
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const isEditing = !!vendor;
|
||||
|
||||
const form = useForm<VendorInput>({
|
||||
resolver: zodResolver(vendorSchema),
|
||||
defaultValues: {
|
||||
name: vendor?.name ?? "",
|
||||
website: vendor?.website ?? "",
|
||||
notes: vendor?.notes ?? "",
|
||||
},
|
||||
});
|
||||
|
||||
function onSubmit(values: VendorInput) {
|
||||
startTransition(async () => {
|
||||
const result = isEditing
|
||||
? await updateVendor(vendor!.id, values)
|
||||
: await createVendor(values);
|
||||
|
||||
if (!result.success) {
|
||||
toast.error(result.error);
|
||||
return;
|
||||
}
|
||||
|
||||
toast.success(isEditing ? "Vendor updated" : "Vendor created");
|
||||
form.reset();
|
||||
onSuccess();
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Vendor name" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="website"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Website</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="https://example.com" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="notes"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Notes</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea placeholder="Optional notes" rows={3} {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button type="submit" disabled={isPending}>
|
||||
{isPending ? "Saving..." : isEditing ? "Update" : "Create"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
32
src/app/(app)/vendors/_components/vendor-modal.tsx
vendored
Normal file
32
src/app/(app)/vendors/_components/vendor-modal.tsx
vendored
Normal file
@@ -0,0 +1,32 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { VendorForm } from "./vendor-form";
|
||||
|
||||
interface VendorModalProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
vendor?: { id: string; name: string; website: string | null; notes: string | null };
|
||||
}
|
||||
|
||||
export function VendorModal({ open, onOpenChange, vendor }: VendorModalProps) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{vendor ? "Edit Vendor" : "Add Vendor"}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{vendor ? "Update the vendor details below." : "Add a new vendor to your inventory."}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<VendorForm vendor={vendor} onSuccess={() => onOpenChange(false)} />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
139
src/app/(app)/vendors/_components/vendor-table.tsx
vendored
Normal file
139
src/app/(app)/vendors/_components/vendor-table.tsx
vendored
Normal file
@@ -0,0 +1,139 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useTransition } 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 { useDebounce } from "@/hooks/use-debounce";
|
||||
import { getVendorColumns } from "./vendor-columns";
|
||||
import { VendorModal } from "./vendor-modal";
|
||||
import { deleteVendor, archiveVendor } 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 { DeleteDialog } from "@/components/shared/delete-dialog";
|
||||
import { PageHeader } from "@/components/shared/page-header";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
|
||||
interface VendorRow {
|
||||
id: string;
|
||||
name: string;
|
||||
website: string | null;
|
||||
notes: string | null;
|
||||
archived: boolean;
|
||||
createdAt: Date;
|
||||
_count: { filaments: number; resins: number; paints: number };
|
||||
}
|
||||
|
||||
interface VendorTableProps {
|
||||
data: VendorRow[];
|
||||
pageCount: number;
|
||||
totalCount: number;
|
||||
}
|
||||
|
||||
export function VendorTable({ data, pageCount, totalCount }: VendorTableProps) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [editVendor, setEditVendor] = useState<VendorRow | undefined>();
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||
|
||||
const [searchValue, setSearchValue] = useState(searchParams.get("search") ?? "");
|
||||
const debouncedSearch = useDebounce(searchValue, 300);
|
||||
|
||||
// Update URL when search changes
|
||||
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 = getVendorColumns({
|
||||
onEdit: (vendor) => {
|
||||
setEditVendor(vendor);
|
||||
setModalOpen(true);
|
||||
},
|
||||
onArchive: (id) => {
|
||||
startTransition(async () => {
|
||||
const result = await archiveVendor(id);
|
||||
if (result.success) {
|
||||
toast.success("Vendor updated");
|
||||
} else {
|
||||
toast.error(result.error);
|
||||
}
|
||||
});
|
||||
},
|
||||
onDelete: (id) => setDeleteId(id),
|
||||
});
|
||||
|
||||
const { table } = useDataTable({ data, columns, pageCount });
|
||||
|
||||
const handleDelete = () => {
|
||||
if (!deleteId) return;
|
||||
startTransition(async () => {
|
||||
const result = await deleteVendor(deleteId);
|
||||
if (result.success) {
|
||||
toast.success("Vendor deleted");
|
||||
setDeleteId(null);
|
||||
} else {
|
||||
toast.error(result.error);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<PageHeader title="Vendors" description="Manage your inventory vendors">
|
||||
<Button onClick={() => { setEditVendor(undefined); setModalOpen(true); }}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Add Vendor
|
||||
</Button>
|
||||
</PageHeader>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="relative flex-1 max-w-sm">
|
||||
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search vendors..."
|
||||
value={searchValue}
|
||||
onChange={(e) => updateSearch(e.target.value)}
|
||||
className="pl-9 h-9"
|
||||
/>
|
||||
</div>
|
||||
<DataTableViewOptions table={table} />
|
||||
</div>
|
||||
|
||||
<DataTable table={table} emptyMessage="No vendors found. Add your first vendor!" />
|
||||
<DataTablePagination table={table} totalCount={totalCount} />
|
||||
|
||||
<VendorModal
|
||||
open={modalOpen}
|
||||
onOpenChange={(open) => {
|
||||
setModalOpen(open);
|
||||
if (!open) setEditVendor(undefined);
|
||||
}}
|
||||
vendor={editVendor}
|
||||
/>
|
||||
|
||||
<DeleteDialog
|
||||
open={!!deleteId}
|
||||
onOpenChange={(open) => !open && setDeleteId(null)}
|
||||
title="Delete Vendor"
|
||||
description="This will permanently delete this vendor. Items linked to this vendor will be unlinked."
|
||||
onConfirm={handleDelete}
|
||||
isLoading={isPending}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
97
src/app/(app)/vendors/actions.ts
vendored
Normal file
97
src/app/(app)/vendors/actions.ts
vendored
Normal file
@@ -0,0 +1,97 @@
|
||||
"use server";
|
||||
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { vendorSchema } from "@/schemas/vendor.schema";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import type { ActionResult } from "@/types/api.types";
|
||||
|
||||
export async function createVendor(input: unknown): Promise<ActionResult<{ id: string }>> {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
|
||||
|
||||
const parsed = vendorSchema.safeParse(input);
|
||||
if (!parsed.success) {
|
||||
return { success: false, error: "Validation failed" };
|
||||
}
|
||||
|
||||
try {
|
||||
const vendor = await prisma.vendor.create({
|
||||
data: {
|
||||
...parsed.data,
|
||||
website: parsed.data.website || null,
|
||||
notes: parsed.data.notes || null,
|
||||
userId: session.user.id,
|
||||
},
|
||||
});
|
||||
|
||||
revalidatePath("/vendors");
|
||||
return { success: true, data: { id: vendor.id } };
|
||||
} catch {
|
||||
return { success: false, error: "Failed to create vendor" };
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateVendor(id: string, input: unknown): Promise<ActionResult> {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
|
||||
|
||||
const parsed = vendorSchema.safeParse(input);
|
||||
if (!parsed.success) {
|
||||
return { success: false, error: "Validation failed" };
|
||||
}
|
||||
|
||||
const existing = await prisma.vendor.findFirst({ where: { id, userId: session.user.id } });
|
||||
if (!existing) return { success: false, error: "Not found" };
|
||||
|
||||
try {
|
||||
await prisma.vendor.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...parsed.data,
|
||||
website: parsed.data.website || null,
|
||||
notes: parsed.data.notes || null,
|
||||
},
|
||||
});
|
||||
|
||||
revalidatePath("/vendors");
|
||||
return { success: true, data: undefined };
|
||||
} catch {
|
||||
return { success: false, error: "Failed to update vendor" };
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteVendor(id: string): Promise<ActionResult> {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
|
||||
|
||||
const existing = await prisma.vendor.findFirst({ where: { id, userId: session.user.id } });
|
||||
if (!existing) return { success: false, error: "Not found" };
|
||||
|
||||
try {
|
||||
await prisma.vendor.delete({ where: { id } });
|
||||
revalidatePath("/vendors");
|
||||
return { success: true, data: undefined };
|
||||
} catch {
|
||||
return { success: false, error: "Failed to delete vendor" };
|
||||
}
|
||||
}
|
||||
|
||||
export async function archiveVendor(id: string): Promise<ActionResult> {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
|
||||
|
||||
const existing = await prisma.vendor.findFirst({ where: { id, userId: session.user.id } });
|
||||
if (!existing) return { success: false, error: "Not found" };
|
||||
|
||||
try {
|
||||
await prisma.vendor.update({
|
||||
where: { id },
|
||||
data: { archived: !existing.archived },
|
||||
});
|
||||
revalidatePath("/vendors");
|
||||
return { success: true, data: undefined };
|
||||
} catch {
|
||||
return { success: false, error: "Failed to archive vendor" };
|
||||
}
|
||||
}
|
||||
18
src/app/(app)/vendors/loading.tsx
vendored
Normal file
18
src/app/(app)/vendors/loading.tsx
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
|
||||
export default function VendorsLoading() {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<Skeleton className="h-8 w-40" />
|
||||
<Skeleton className="h-9 w-28" />
|
||||
</div>
|
||||
<Skeleton className="h-10 w-full" />
|
||||
<div className="space-y-2">
|
||||
{Array.from({ length: 5 }).map((_, i) => (
|
||||
<Skeleton key={i} className="h-10 w-full" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
19
src/app/(app)/vendors/page.tsx
vendored
Normal file
19
src/app/(app)/vendors/page.tsx
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
import { auth } from "@/lib/auth";
|
||||
import { redirect } from "next/navigation";
|
||||
import { getVendors } from "@/data/vendor.queries";
|
||||
import type { DataTableSearchParams } from "@/types/table.types";
|
||||
import { VendorTable } from "./_components/vendor-table";
|
||||
|
||||
interface Props {
|
||||
searchParams: Promise<DataTableSearchParams>;
|
||||
}
|
||||
|
||||
export default async function VendorsPage({ searchParams }: Props) {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) redirect("/login");
|
||||
|
||||
const params = await searchParams;
|
||||
const { data, pageCount, totalCount } = await getVendors(session.user.id, params);
|
||||
|
||||
return <VendorTable data={data} pageCount={pageCount} totalCount={totalCount} />;
|
||||
}
|
||||
Reference in New Issue
Block a user