mirror of
https://github.com/xCyanGrizzly/DragonsStash.git
synced 2026-05-11 06:11:15 +00:00
Init
This commit is contained in:
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}
|
||||
/>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user