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} />;
|
||||
}
|
||||
7
src/app/(auth)/layout.tsx
Normal file
7
src/app/(auth)/layout.tsx
Normal file
@@ -0,0 +1,7 @@
|
||||
export default function AuthLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-background">
|
||||
<div className="w-full max-w-md space-y-6 px-4">{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
32
src/app/(auth)/login/actions.ts
Normal file
32
src/app/(auth)/login/actions.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
"use server";
|
||||
|
||||
import { signIn } from "@/lib/auth";
|
||||
import { loginSchema } from "@/schemas/auth.schema";
|
||||
import { AuthError } from "next-auth";
|
||||
|
||||
export async function loginAction(values: { email: string; password: string }) {
|
||||
const parsed = loginSchema.safeParse(values);
|
||||
if (!parsed.success) {
|
||||
return { error: "Invalid email or password" };
|
||||
}
|
||||
|
||||
try {
|
||||
await signIn("credentials", {
|
||||
email: parsed.data.email,
|
||||
password: parsed.data.password,
|
||||
redirect: false,
|
||||
});
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
if (error instanceof AuthError) {
|
||||
switch (error.type) {
|
||||
case "CredentialsSignin":
|
||||
return { error: "Invalid email or password" };
|
||||
default:
|
||||
return { error: "Something went wrong" };
|
||||
}
|
||||
}
|
||||
// This is a redirect error thrown by next-auth on success - rethrow it
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
133
src/app/(auth)/login/page.tsx
Normal file
133
src/app/(auth)/login/page.tsx
Normal file
@@ -0,0 +1,133 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useTransition } from "react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { Flame } from "lucide-react";
|
||||
import { loginSchema, type LoginInput } from "@/schemas/auth.schema";
|
||||
import { loginAction } from "./actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import { APP_NAME } from "@/lib/constants";
|
||||
|
||||
export default function LoginPage() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const callbackUrl = searchParams.get("callbackUrl") || "/dashboard";
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
const form = useForm<LoginInput>({
|
||||
resolver: zodResolver(loginSchema) as any,
|
||||
defaultValues: { email: "", password: "" },
|
||||
});
|
||||
|
||||
function onSubmit(values: LoginInput) {
|
||||
setError(null);
|
||||
startTransition(async () => {
|
||||
try {
|
||||
const result = await loginAction(values);
|
||||
|
||||
if (result?.error) {
|
||||
setError(result.error);
|
||||
return;
|
||||
}
|
||||
|
||||
router.push(callbackUrl);
|
||||
router.refresh();
|
||||
} catch {
|
||||
// Redirect from server action — Next.js handles this automatically
|
||||
router.push(callbackUrl);
|
||||
router.refresh();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col items-center gap-2 text-center">
|
||||
<Flame className="h-10 w-10 text-primary" />
|
||||
<h1 className="text-2xl font-bold tracking-tight">{APP_NAME}</h1>
|
||||
<p className="text-sm text-muted-foreground">Sign in to manage your inventory</p>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Sign In</CardTitle>
|
||||
<CardDescription>Enter your credentials to continue</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
{error && (
|
||||
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="email"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Email</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="email"
|
||||
placeholder="admin@dragonsstash.local"
|
||||
autoComplete="email"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="password"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Password</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="Enter your password"
|
||||
autoComplete="current-password"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<Button type="submit" className="w-full" disabled={isPending}>
|
||||
{isPending ? "Signing in..." : "Sign In"}
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
|
||||
<p className="mt-4 text-center text-sm text-muted-foreground">
|
||||
Don't have an account?{" "}
|
||||
<Link href="/register" className="text-primary underline-offset-4 hover:underline">
|
||||
Register
|
||||
</Link>
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</>
|
||||
);
|
||||
}
|
||||
42
src/app/(auth)/register/actions.ts
Normal file
42
src/app/(auth)/register/actions.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
"use server";
|
||||
|
||||
import bcrypt from "bcryptjs";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { registerSchema } from "@/schemas/auth.schema";
|
||||
import type { ActionResult } from "@/types/api.types";
|
||||
|
||||
export async function registerUser(input: unknown): Promise<ActionResult<{ id: string }>> {
|
||||
const parsed = registerSchema.safeParse(input);
|
||||
if (!parsed.success) {
|
||||
return { success: false, error: "Validation failed" };
|
||||
}
|
||||
|
||||
const existing = await prisma.user.findUnique({
|
||||
where: { email: parsed.data.email },
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
return { success: false, error: "An account with this email already exists" };
|
||||
}
|
||||
|
||||
const hashedPassword = await bcrypt.hash(parsed.data.password, 10);
|
||||
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
name: parsed.data.name,
|
||||
email: parsed.data.email,
|
||||
hashedPassword,
|
||||
role: "USER",
|
||||
settings: {
|
||||
create: {
|
||||
lowStockThreshold: 10,
|
||||
currency: "USD",
|
||||
theme: "dark",
|
||||
units: "metric",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return { success: true, data: { id: user.id } };
|
||||
}
|
||||
176
src/app/(auth)/register/page.tsx
Normal file
176
src/app/(auth)/register/page.tsx
Normal file
@@ -0,0 +1,176 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useTransition } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { Flame } from "lucide-react";
|
||||
import { registerSchema, type RegisterInput } from "@/schemas/auth.schema";
|
||||
import { registerUser } from "./actions";
|
||||
import { loginAction } from "../login/actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import { APP_NAME } from "@/lib/constants";
|
||||
|
||||
export default function RegisterPage() {
|
||||
const router = useRouter();
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
const form = useForm<RegisterInput>({
|
||||
resolver: zodResolver(registerSchema) as any,
|
||||
defaultValues: { name: "", email: "", password: "", confirmPassword: "" },
|
||||
});
|
||||
|
||||
function onSubmit(values: RegisterInput) {
|
||||
setError(null);
|
||||
startTransition(async () => {
|
||||
const result = await registerUser(values);
|
||||
|
||||
if (!result.success) {
|
||||
setError(result.error);
|
||||
return;
|
||||
}
|
||||
|
||||
// Auto-login after registration using server action
|
||||
try {
|
||||
const loginResult = await loginAction({
|
||||
email: values.email,
|
||||
password: values.password,
|
||||
});
|
||||
|
||||
if (loginResult?.error) {
|
||||
setError("Account created but sign in failed. Please try logging in.");
|
||||
return;
|
||||
}
|
||||
|
||||
router.push("/dashboard");
|
||||
router.refresh();
|
||||
} catch {
|
||||
// Redirect from server action
|
||||
router.push("/dashboard");
|
||||
router.refresh();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col items-center gap-2 text-center">
|
||||
<Flame className="h-10 w-10 text-primary" />
|
||||
<h1 className="text-2xl font-bold tracking-tight">{APP_NAME}</h1>
|
||||
<p className="text-sm text-muted-foreground">Create an account to get started</p>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Create Account</CardTitle>
|
||||
<CardDescription>Fill in your details below</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
{error && (
|
||||
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Your name" autoComplete="name" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="email"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Email</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="email"
|
||||
placeholder="you@example.com"
|
||||
autoComplete="email"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="password"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Password</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="At least 6 characters"
|
||||
autoComplete="new-password"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="confirmPassword"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Confirm Password</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="Repeat your password"
|
||||
autoComplete="new-password"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<Button type="submit" className="w-full" disabled={isPending}>
|
||||
{isPending ? "Creating account..." : "Create Account"}
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
|
||||
<p className="mt-4 text-center text-sm text-muted-foreground">
|
||||
Already have an account?{" "}
|
||||
<Link href="/login" className="text-primary underline-offset-4 hover:underline">
|
||||
Sign in
|
||||
</Link>
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</>
|
||||
);
|
||||
}
|
||||
3
src/app/api/auth/[...nextauth]/route.ts
Normal file
3
src/app/api/auth/[...nextauth]/route.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import { handlers } from "@/lib/auth";
|
||||
|
||||
export const { GET, POST } = handlers;
|
||||
52
src/app/api/catalog/filaments/route.ts
Normal file
52
src/app/api/catalog/filaments/route.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import type { CatalogBrand, CatalogResponse } from "@/types/catalog.types";
|
||||
import { fetchFilaments } from "@/lib/catalog/shopify";
|
||||
import { deduplicateItems } from "@/lib/catalog/cache";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const { searchParams } = req.nextUrl;
|
||||
const brandFilter = searchParams.get("brand")?.toLowerCase();
|
||||
const search = searchParams.get("search")?.toLowerCase();
|
||||
|
||||
try {
|
||||
let items = deduplicateItems(await fetchFilaments());
|
||||
|
||||
// Build brand summary from unfiltered data
|
||||
const brandMap = new Map<string, number>();
|
||||
for (const p of items) {
|
||||
brandMap.set(p.brand, (brandMap.get(p.brand) ?? 0) + 1);
|
||||
}
|
||||
|
||||
if (brandFilter) {
|
||||
items = items.filter((p) => p.brand.toLowerCase() === brandFilter);
|
||||
}
|
||||
|
||||
if (search) {
|
||||
items = items.filter(
|
||||
(p) =>
|
||||
p.name.toLowerCase().includes(search) ||
|
||||
p.brand.toLowerCase().includes(search) ||
|
||||
(p.color && p.color.toLowerCase().includes(search)) ||
|
||||
(p.material && p.material.toLowerCase().includes(search)),
|
||||
);
|
||||
}
|
||||
|
||||
const brands: CatalogBrand[] = Array.from(brandMap.entries())
|
||||
.map(([name, count]) => ({
|
||||
id: name.toLowerCase().replace(/[^a-z0-9]/g, "_"),
|
||||
name,
|
||||
type: "filament" as const,
|
||||
itemCount: count,
|
||||
}))
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
|
||||
const response: CatalogResponse = { items, brands };
|
||||
return NextResponse.json(response);
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch filament catalog:", error);
|
||||
return NextResponse.json(
|
||||
{ items: [], brands: [], error: "Failed to fetch filament data" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
47
src/app/api/catalog/paints/route.ts
Normal file
47
src/app/api/catalog/paints/route.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import type { CatalogBrand, CatalogItem, CatalogResponse } from "@/types/catalog.types";
|
||||
|
||||
// Static import — bundled at build time from the generated JSON
|
||||
import paintsData from "@/data/catalog/paints.json";
|
||||
|
||||
const allPaints = paintsData as CatalogItem[];
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const { searchParams } = req.nextUrl;
|
||||
const brandFilter = searchParams.get("brand")?.toLowerCase();
|
||||
const search = searchParams.get("search")?.toLowerCase();
|
||||
|
||||
let items = allPaints;
|
||||
|
||||
if (brandFilter) {
|
||||
items = items.filter((p) => p.brand.toLowerCase() === brandFilter);
|
||||
}
|
||||
|
||||
if (search) {
|
||||
items = items.filter(
|
||||
(p) =>
|
||||
p.name.toLowerCase().includes(search) ||
|
||||
p.brand.toLowerCase().includes(search) ||
|
||||
(p.line && p.line.toLowerCase().includes(search)) ||
|
||||
(p.productCode && p.productCode.toLowerCase().includes(search)),
|
||||
);
|
||||
}
|
||||
|
||||
// Build brand summary from the FULL dataset (not filtered)
|
||||
const brandMap = new Map<string, number>();
|
||||
for (const p of allPaints) {
|
||||
brandMap.set(p.brand, (brandMap.get(p.brand) ?? 0) + 1);
|
||||
}
|
||||
|
||||
const brands: CatalogBrand[] = Array.from(brandMap.entries())
|
||||
.map(([name, count]) => ({
|
||||
id: name.toLowerCase().replace(/[^a-z0-9]/g, "_"),
|
||||
name,
|
||||
type: "paint" as const,
|
||||
itemCount: count,
|
||||
}))
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
|
||||
const response: CatalogResponse = { items, brands };
|
||||
return NextResponse.json(response);
|
||||
}
|
||||
52
src/app/api/catalog/resins/route.ts
Normal file
52
src/app/api/catalog/resins/route.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import type { CatalogBrand, CatalogResponse } from "@/types/catalog.types";
|
||||
import { fetchResins } from "@/lib/catalog/shopify";
|
||||
import { deduplicateItems } from "@/lib/catalog/cache";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const { searchParams } = req.nextUrl;
|
||||
const brandFilter = searchParams.get("brand")?.toLowerCase();
|
||||
const search = searchParams.get("search")?.toLowerCase();
|
||||
|
||||
try {
|
||||
let items = deduplicateItems(await fetchResins());
|
||||
|
||||
// Build brand summary from unfiltered data
|
||||
const brandMap = new Map<string, number>();
|
||||
for (const p of items) {
|
||||
brandMap.set(p.brand, (brandMap.get(p.brand) ?? 0) + 1);
|
||||
}
|
||||
|
||||
if (brandFilter) {
|
||||
items = items.filter((p) => p.brand.toLowerCase() === brandFilter);
|
||||
}
|
||||
|
||||
if (search) {
|
||||
items = items.filter(
|
||||
(p) =>
|
||||
p.name.toLowerCase().includes(search) ||
|
||||
p.brand.toLowerCase().includes(search) ||
|
||||
(p.color && p.color.toLowerCase().includes(search)) ||
|
||||
(p.resinType && p.resinType.toLowerCase().includes(search)),
|
||||
);
|
||||
}
|
||||
|
||||
const brands: CatalogBrand[] = Array.from(brandMap.entries())
|
||||
.map(([name, count]) => ({
|
||||
id: name.toLowerCase().replace(/[^a-z0-9]/g, "_"),
|
||||
name,
|
||||
type: "resin" as const,
|
||||
itemCount: count,
|
||||
}))
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
|
||||
const response: CatalogResponse = { items, brands };
|
||||
return NextResponse.json(response);
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch resin catalog:", error);
|
||||
return NextResponse.json(
|
||||
{ items: [], brands: [], error: "Failed to fetch resin data" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
27
src/app/api/health/route.ts
Normal file
27
src/app/api/health/route.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
await prisma.$queryRaw`SELECT 1`;
|
||||
return NextResponse.json(
|
||||
{
|
||||
status: "healthy",
|
||||
timestamp: new Date().toISOString(),
|
||||
database: "connected",
|
||||
},
|
||||
{ status: 200 }
|
||||
);
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{
|
||||
status: "unhealthy",
|
||||
timestamp: new Date().toISOString(),
|
||||
database: "disconnected",
|
||||
},
|
||||
{ status: 503 }
|
||||
);
|
||||
}
|
||||
}
|
||||
19
src/app/error.tsx
Normal file
19
src/app/error.tsx
Normal file
@@ -0,0 +1,19 @@
|
||||
"use client";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export default function Error({
|
||||
error,
|
||||
reset,
|
||||
}: {
|
||||
error: Error & { digest?: string };
|
||||
reset: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col items-center justify-center gap-4">
|
||||
<h1 className="text-2xl font-bold">Something went wrong</h1>
|
||||
<p className="text-sm text-muted-foreground">{error.message}</p>
|
||||
<Button onClick={reset}>Try again</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
BIN
src/app/favicon.ico
Normal file
BIN
src/app/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
139
src/app/globals.css
Normal file
139
src/app/globals.css
Normal file
@@ -0,0 +1,139 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
@import "shadcn/tailwind.css";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-geist-sans);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-ring: var(--ring);
|
||||
--color-input: var(--input);
|
||||
--color-border: var(--border);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-card: var(--card);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
--radius-2xl: calc(var(--radius) + 8px);
|
||||
--radius-3xl: calc(var(--radius) + 12px);
|
||||
--radius-4xl: calc(var(--radius) + 16px);
|
||||
}
|
||||
|
||||
/* Dragon's Stash Dark Theme (default) */
|
||||
:root {
|
||||
--radius: 0.5rem;
|
||||
/* Background: #0f0f12 */
|
||||
--background: oklch(0.13 0.005 285);
|
||||
--foreground: oklch(0.93 0 0);
|
||||
/* Card: #17171c */
|
||||
--card: oklch(0.17 0.005 285);
|
||||
--card-foreground: oklch(0.93 0 0);
|
||||
/* Popover matches card */
|
||||
--popover: oklch(0.17 0.005 285);
|
||||
--popover-foreground: oklch(0.93 0 0);
|
||||
/* Primary: #f97316 (orange) */
|
||||
--primary: oklch(0.702 0.183 54.13);
|
||||
--primary-foreground: oklch(1 0 0);
|
||||
/* Secondary */
|
||||
--secondary: oklch(0.2 0.005 285);
|
||||
--secondary-foreground: oklch(0.93 0 0);
|
||||
/* Muted */
|
||||
--muted: oklch(0.2 0.005 285);
|
||||
--muted-foreground: oklch(0.6 0 0);
|
||||
/* Accent: same as primary (orange) */
|
||||
--accent: oklch(0.702 0.183 54.13);
|
||||
--accent-foreground: oklch(1 0 0);
|
||||
/* Destructive */
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
/* Border: #26262c */
|
||||
--border: oklch(0.23 0.005 285);
|
||||
--input: oklch(0.23 0.005 285);
|
||||
--ring: oklch(0.702 0.183 54.13);
|
||||
/* Charts */
|
||||
--chart-1: oklch(0.702 0.183 54.13);
|
||||
--chart-2: oklch(0.6 0.118 184.704);
|
||||
--chart-3: oklch(0.398 0.07 227.392);
|
||||
--chart-4: oklch(0.828 0.189 84.429);
|
||||
--chart-5: oklch(0.769 0.188 70.08);
|
||||
/* Sidebar */
|
||||
--sidebar: oklch(0.13 0.005 285);
|
||||
--sidebar-foreground: oklch(0.93 0 0);
|
||||
--sidebar-primary: oklch(0.702 0.183 54.13);
|
||||
--sidebar-primary-foreground: oklch(1 0 0);
|
||||
--sidebar-accent: oklch(0.2 0.005 285);
|
||||
--sidebar-accent-foreground: oklch(0.93 0 0);
|
||||
--sidebar-border: oklch(0.23 0.005 285);
|
||||
--sidebar-ring: oklch(0.702 0.183 54.13);
|
||||
}
|
||||
|
||||
/* Light theme override */
|
||||
.light {
|
||||
--background: oklch(0.985 0 0);
|
||||
--foreground: oklch(0.145 0 0);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.145 0 0);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.145 0 0);
|
||||
--primary: oklch(0.602 0.183 54.13);
|
||||
--primary-foreground: oklch(1 0 0);
|
||||
--secondary: oklch(0.97 0 0);
|
||||
--secondary-foreground: oklch(0.205 0 0);
|
||||
--muted: oklch(0.97 0 0);
|
||||
--muted-foreground: oklch(0.556 0 0);
|
||||
--accent: oklch(0.602 0.183 54.13);
|
||||
--accent-foreground: oklch(1 0 0);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--border: oklch(0.922 0 0);
|
||||
--input: oklch(0.922 0 0);
|
||||
--ring: oklch(0.602 0.183 54.13);
|
||||
--chart-1: oklch(0.602 0.183 54.13);
|
||||
--chart-2: oklch(0.6 0.118 184.704);
|
||||
--chart-3: oklch(0.398 0.07 227.392);
|
||||
--chart-4: oklch(0.828 0.189 84.429);
|
||||
--chart-5: oklch(0.769 0.188 70.08);
|
||||
--sidebar: oklch(0.985 0 0);
|
||||
--sidebar-foreground: oklch(0.145 0 0);
|
||||
--sidebar-primary: oklch(0.602 0.183 54.13);
|
||||
--sidebar-primary-foreground: oklch(1 0 0);
|
||||
--sidebar-accent: oklch(0.97 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.205 0 0);
|
||||
--sidebar-border: oklch(0.922 0 0);
|
||||
--sidebar-ring: oklch(0.602 0.183 54.13);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
44
src/app/layout.tsx
Normal file
44
src/app/layout.tsx
Normal file
@@ -0,0 +1,44 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Geist, Geist_Mono } from "next/font/google";
|
||||
import { SessionProvider } from "@/components/providers/session-provider";
|
||||
import { ThemeProvider } from "@/components/providers/theme-provider";
|
||||
import { Toaster } from "@/components/ui/sonner";
|
||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
import { APP_NAME } from "@/lib/constants";
|
||||
import "./globals.css";
|
||||
|
||||
const geistSans = Geist({
|
||||
variable: "--font-geist-sans",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
const geistMono = Geist_Mono({
|
||||
variable: "--font-geist-mono",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: {
|
||||
default: APP_NAME,
|
||||
template: `%s | ${APP_NAME}`,
|
||||
},
|
||||
description:
|
||||
"Self-hosted inventory management for 3D printing filament, resin, and miniature paints",
|
||||
};
|
||||
|
||||
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<html lang="en" className="dark" suppressHydrationWarning>
|
||||
<body className={`${geistSans.variable} ${geistMono.variable} font-sans antialiased`}>
|
||||
<SessionProvider>
|
||||
<ThemeProvider>
|
||||
<TooltipProvider delayDuration={0}>
|
||||
{children}
|
||||
<Toaster richColors position="bottom-right" />
|
||||
</TooltipProvider>
|
||||
</ThemeProvider>
|
||||
</SessionProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
9
src/app/loading.tsx
Normal file
9
src/app/loading.tsx
Normal file
@@ -0,0 +1,9 @@
|
||||
import { Flame } from "lucide-react";
|
||||
|
||||
export default function Loading() {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center">
|
||||
<Flame className="h-8 w-8 animate-pulse text-primary" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
14
src/app/not-found.tsx
Normal file
14
src/app/not-found.tsx
Normal file
@@ -0,0 +1,14 @@
|
||||
import Link from "next/link";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export default function NotFound() {
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col items-center justify-center gap-4">
|
||||
<h1 className="text-4xl font-bold">404</h1>
|
||||
<p className="text-muted-foreground">Page not found</p>
|
||||
<Button asChild>
|
||||
<Link href="/dashboard">Back to Dashboard</Link>
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
5
src/app/page.tsx
Normal file
5
src/app/page.tsx
Normal file
@@ -0,0 +1,5 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
export default function Home() {
|
||||
redirect("/dashboard");
|
||||
}
|
||||
46
src/components/layout/header.tsx
Normal file
46
src/components/layout/header.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
"use client";
|
||||
|
||||
import { usePathname } from "next/navigation";
|
||||
import { Menu } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet";
|
||||
import { UserMenu } from "./user-menu";
|
||||
import { MobileSidebar } from "./mobile-sidebar";
|
||||
|
||||
const routeTitles: Record<string, string> = {
|
||||
"/dashboard": "Dashboard",
|
||||
"/filaments": "Filaments",
|
||||
"/resins": "Resins",
|
||||
"/paints": "Paints",
|
||||
"/vendors": "Vendors",
|
||||
"/locations": "Locations",
|
||||
"/settings": "Settings",
|
||||
};
|
||||
|
||||
export function Header() {
|
||||
const pathname = usePathname();
|
||||
const title = routeTitles[pathname] || "Dragon's Stash";
|
||||
|
||||
return (
|
||||
<header className="sticky top-0 z-30 flex h-14 items-center gap-4 border-b border-border bg-background/95 px-4 backdrop-blur supports-[backdrop-filter]:bg-background/60 lg:px-6">
|
||||
{/* Mobile menu */}
|
||||
<Sheet>
|
||||
<SheetTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="lg:hidden">
|
||||
<Menu className="h-5 w-5" />
|
||||
<span className="sr-only">Toggle menu</span>
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
<SheetContent side="left" className="w-60 p-0">
|
||||
<MobileSidebar />
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
|
||||
<h1 className="text-lg font-semibold">{title}</h1>
|
||||
|
||||
<div className="ml-auto">
|
||||
<UserMenu />
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
66
src/components/layout/mobile-sidebar.tsx
Normal file
66
src/components/layout/mobile-sidebar.tsx
Normal file
@@ -0,0 +1,66 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import {
|
||||
LayoutDashboard,
|
||||
Cylinder,
|
||||
Droplets,
|
||||
Paintbrush,
|
||||
Building2,
|
||||
MapPin,
|
||||
Settings,
|
||||
Flame,
|
||||
} from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { APP_NAME } from "@/lib/constants";
|
||||
import { SheetHeader, SheetTitle } from "@/components/ui/sheet";
|
||||
|
||||
const icons = { LayoutDashboard, Cylinder, Droplets, Paintbrush, Building2, MapPin, Settings };
|
||||
|
||||
const navItems = [
|
||||
{ label: "Dashboard", href: "/dashboard", icon: "LayoutDashboard" as const },
|
||||
{ label: "Filaments", href: "/filaments", icon: "Cylinder" as const },
|
||||
{ label: "Resins", href: "/resins", icon: "Droplets" as const },
|
||||
{ label: "Paints", href: "/paints", icon: "Paintbrush" as const },
|
||||
{ label: "Vendors", href: "/vendors", icon: "Building2" as const },
|
||||
{ label: "Locations", href: "/locations", icon: "MapPin" as const },
|
||||
{ label: "Settings", href: "/settings", icon: "Settings" as const },
|
||||
];
|
||||
|
||||
export function MobileSidebar() {
|
||||
const pathname = usePathname();
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col">
|
||||
<SheetHeader className="border-b border-border p-4">
|
||||
<SheetTitle className="flex items-center gap-2">
|
||||
<Flame className="h-5 w-5 text-primary" />
|
||||
{APP_NAME}
|
||||
</SheetTitle>
|
||||
</SheetHeader>
|
||||
<nav className="flex-1 space-y-1 p-2">
|
||||
{navItems.map((item) => {
|
||||
const Icon = icons[item.icon];
|
||||
const isActive = pathname.startsWith(item.href);
|
||||
|
||||
return (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
className={cn(
|
||||
"flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors",
|
||||
isActive
|
||||
? "border-l-2 border-primary bg-primary/10 text-primary"
|
||||
: "text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||
)}
|
||||
>
|
||||
<Icon className="h-4 w-4" />
|
||||
<span>{item.label}</span>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
117
src/components/layout/sidebar.tsx
Normal file
117
src/components/layout/sidebar.tsx
Normal file
@@ -0,0 +1,117 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import {
|
||||
LayoutDashboard,
|
||||
Cylinder,
|
||||
Droplets,
|
||||
Paintbrush,
|
||||
Building2,
|
||||
MapPin,
|
||||
Settings,
|
||||
Flame,
|
||||
PanelLeftClose,
|
||||
PanelLeft,
|
||||
} from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { APP_NAME } from "@/lib/constants";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
|
||||
const icons = {
|
||||
LayoutDashboard,
|
||||
Cylinder,
|
||||
Droplets,
|
||||
Paintbrush,
|
||||
Building2,
|
||||
MapPin,
|
||||
Settings,
|
||||
} as const;
|
||||
|
||||
const navItems = [
|
||||
{ label: "Dashboard", href: "/dashboard", icon: "LayoutDashboard" as const },
|
||||
{ label: "Filaments", href: "/filaments", icon: "Cylinder" as const },
|
||||
{ label: "Resins", href: "/resins", icon: "Droplets" as const },
|
||||
{ label: "Paints", href: "/paints", icon: "Paintbrush" as const },
|
||||
{ label: "Vendors", href: "/vendors", icon: "Building2" as const },
|
||||
{ label: "Locations", href: "/locations", icon: "MapPin" as const },
|
||||
{ label: "Settings", href: "/settings", icon: "Settings" as const },
|
||||
];
|
||||
|
||||
export function Sidebar() {
|
||||
const pathname = usePathname();
|
||||
const [collapsed, setCollapsed] = useState(false);
|
||||
|
||||
return (
|
||||
<aside
|
||||
className={cn(
|
||||
"flex h-screen flex-col border-r border-border bg-card transition-all duration-200",
|
||||
collapsed ? "w-16" : "w-60"
|
||||
)}
|
||||
>
|
||||
{/* Logo */}
|
||||
<div className="flex h-14 items-center gap-2 border-b border-border px-4">
|
||||
<Flame className="h-6 w-6 shrink-0 text-primary" />
|
||||
{!collapsed && (
|
||||
<span className="text-sm font-bold tracking-tight">{APP_NAME}</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Navigation */}
|
||||
<nav className="flex-1 space-y-1 p-2">
|
||||
{navItems.map((item) => {
|
||||
const Icon = icons[item.icon];
|
||||
const isActive = pathname.startsWith(item.href);
|
||||
|
||||
const link = (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
className={cn(
|
||||
"flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors",
|
||||
isActive
|
||||
? "border-l-2 border-primary bg-primary/10 text-primary"
|
||||
: "text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||
)}
|
||||
>
|
||||
<Icon className="h-4 w-4 shrink-0" />
|
||||
{!collapsed && <span>{item.label}</span>}
|
||||
</Link>
|
||||
);
|
||||
|
||||
if (collapsed) {
|
||||
return (
|
||||
<Tooltip key={item.href}>
|
||||
<TooltipTrigger asChild>{link}</TooltipTrigger>
|
||||
<TooltipContent side="right">{item.label}</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
return link;
|
||||
})}
|
||||
</nav>
|
||||
|
||||
{/* Collapse toggle */}
|
||||
<div className="border-t border-border p-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="w-full justify-center"
|
||||
onClick={() => setCollapsed(!collapsed)}
|
||||
>
|
||||
{collapsed ? (
|
||||
<PanelLeft className="h-4 w-4" />
|
||||
) : (
|
||||
<>
|
||||
<PanelLeftClose className="h-4 w-4 mr-2" />
|
||||
<span className="text-xs">Collapse</span>
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
61
src/components/layout/user-menu.tsx
Normal file
61
src/components/layout/user-menu.tsx
Normal file
@@ -0,0 +1,61 @@
|
||||
"use client";
|
||||
|
||||
import { signOut, useSession } from "next-auth/react";
|
||||
import Link from "next/link";
|
||||
import { LogOut, Settings, User } from "lucide-react";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
|
||||
export function UserMenu() {
|
||||
const { data: session } = useSession();
|
||||
|
||||
if (!session?.user) return null;
|
||||
|
||||
const initials = session.user.name
|
||||
? session.user.name
|
||||
.split(" ")
|
||||
.map((n) => n[0])
|
||||
.join("")
|
||||
.toUpperCase()
|
||||
.slice(0, 2)
|
||||
: "U";
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger className="flex items-center gap-2 rounded-md px-2 py-1 hover:bg-muted">
|
||||
<Avatar className="h-7 w-7">
|
||||
<AvatarImage src={session.user.image || undefined} />
|
||||
<AvatarFallback className="bg-primary/20 text-xs text-primary">{initials}</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="hidden text-sm font-medium md:inline-block">{session.user.name}</span>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-56">
|
||||
<DropdownMenuLabel>
|
||||
<div className="flex flex-col">
|
||||
<span className="text-sm">{session.user.name}</span>
|
||||
<span className="text-xs text-muted-foreground">{session.user.email}</span>
|
||||
</div>
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href="/settings">
|
||||
<Settings className="mr-2 h-4 w-4" />
|
||||
Settings
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => signOut({ callbackUrl: "/login" })}>
|
||||
<LogOut className="mr-2 h-4 w-4" />
|
||||
Sign out
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
7
src/components/providers/session-provider.tsx
Normal file
7
src/components/providers/session-provider.tsx
Normal file
@@ -0,0 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { SessionProvider as NextAuthSessionProvider } from "next-auth/react";
|
||||
|
||||
export function SessionProvider({ children }: { children: React.ReactNode }) {
|
||||
return <NextAuthSessionProvider>{children}</NextAuthSessionProvider>;
|
||||
}
|
||||
11
src/components/providers/theme-provider.tsx
Normal file
11
src/components/providers/theme-provider.tsx
Normal file
@@ -0,0 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import { ThemeProvider as NextThemesProvider } from "next-themes";
|
||||
|
||||
export function ThemeProvider({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<NextThemesProvider attribute="class" defaultTheme="dark" enableSystem disableTransitionOnChange>
|
||||
{children}
|
||||
</NextThemesProvider>
|
||||
);
|
||||
}
|
||||
198
src/components/shared/autocomplete-input.tsx
Normal file
198
src/components/shared/autocomplete-input.tsx
Normal file
@@ -0,0 +1,198 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { ColorSwatch } from "@/components/shared/color-swatch";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { CatalogItem, CatalogItemType } from "@/types/catalog.types";
|
||||
|
||||
const API_PATHS: Record<CatalogItemType, string> = {
|
||||
filament: "/api/catalog/filaments",
|
||||
resin: "/api/catalog/resins",
|
||||
paint: "/api/catalog/paints",
|
||||
};
|
||||
|
||||
interface AutocompleteInputProps {
|
||||
/** Which catalog to search */
|
||||
type: CatalogItemType;
|
||||
/** Called when a suggestion is selected — use this to auto-fill the form */
|
||||
onSelectItem: (item: CatalogItem) => void;
|
||||
/** The current text value of the input */
|
||||
value: string;
|
||||
/** Standard onChange for the text input */
|
||||
onChange: (value: string) => void;
|
||||
/** Input placeholder */
|
||||
placeholder?: string;
|
||||
/** Additional className for the input */
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A text input with catalog autocomplete suggestions.
|
||||
* When the user types ≥ 2 chars, it searches the catalog API and shows
|
||||
* a dropdown of matching products. Selecting one calls onSelectItem
|
||||
* to auto-fill the entire form.
|
||||
*/
|
||||
export function AutocompleteInput({
|
||||
type,
|
||||
onSelectItem,
|
||||
value,
|
||||
onChange,
|
||||
placeholder,
|
||||
className,
|
||||
}: AutocompleteInputProps) {
|
||||
const [suggestions, setSuggestions] = useState<CatalogItem[]>([]);
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [activeIndex, setActiveIndex] = useState(-1);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const suppressRef = useRef(false);
|
||||
|
||||
// Fetch suggestions when value changes (debounced)
|
||||
const fetchSuggestions = useCallback(
|
||||
async (query: string) => {
|
||||
if (query.length < 2) {
|
||||
setSuggestions([]);
|
||||
setIsOpen(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams({ search: query });
|
||||
const resp = await fetch(`${API_PATHS[type]}?${params.toString()}`);
|
||||
if (!resp.ok) return;
|
||||
|
||||
const data = await resp.json();
|
||||
const items: CatalogItem[] = (data.items ?? []).slice(0, 8);
|
||||
setSuggestions(items);
|
||||
setIsOpen(items.length > 0);
|
||||
setActiveIndex(-1);
|
||||
} catch {
|
||||
setSuggestions([]);
|
||||
setIsOpen(false);
|
||||
}
|
||||
},
|
||||
[type],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
// Don't fetch right after selecting an item
|
||||
if (suppressRef.current) {
|
||||
suppressRef.current = false;
|
||||
return;
|
||||
}
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
fetchSuggestions(value);
|
||||
}, 300);
|
||||
return () => clearTimeout(timeout);
|
||||
}, [value, fetchSuggestions]);
|
||||
|
||||
// Close on click outside
|
||||
useEffect(() => {
|
||||
function handleClickOutside(e: MouseEvent) {
|
||||
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
|
||||
setIsOpen(false);
|
||||
}
|
||||
}
|
||||
document.addEventListener("mousedown", handleClickOutside);
|
||||
return () => document.removeEventListener("mousedown", handleClickOutside);
|
||||
}, []);
|
||||
|
||||
function handleSelect(item: CatalogItem) {
|
||||
suppressRef.current = true;
|
||||
onSelectItem(item);
|
||||
setIsOpen(false);
|
||||
setSuggestions([]);
|
||||
}
|
||||
|
||||
function handleKeyDown(e: React.KeyboardEvent) {
|
||||
if (!isOpen || suggestions.length === 0) return;
|
||||
|
||||
if (e.key === "ArrowDown") {
|
||||
e.preventDefault();
|
||||
setActiveIndex((prev) => (prev + 1) % suggestions.length);
|
||||
} else if (e.key === "ArrowUp") {
|
||||
e.preventDefault();
|
||||
setActiveIndex((prev) => (prev - 1 + suggestions.length) % suggestions.length);
|
||||
} else if (e.key === "Enter" && activeIndex >= 0) {
|
||||
e.preventDefault();
|
||||
handleSelect(suggestions[activeIndex]);
|
||||
} else if (e.key === "Escape") {
|
||||
setIsOpen(false);
|
||||
}
|
||||
}
|
||||
|
||||
function getSubLabel(item: CatalogItem): string | null {
|
||||
if (item.type === "filament" && item.material) return item.material;
|
||||
if (item.type === "resin" && item.resinType) return item.resinType;
|
||||
if (item.type === "paint" && item.line) return item.line;
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className="relative">
|
||||
<Input
|
||||
ref={inputRef}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
onFocus={() => {
|
||||
if (suggestions.length > 0) setIsOpen(true);
|
||||
}}
|
||||
placeholder={placeholder}
|
||||
className={className}
|
||||
autoComplete="off"
|
||||
/>
|
||||
|
||||
{isOpen && suggestions.length > 0 && (
|
||||
<div className="absolute top-full left-0 z-50 mt-1 w-full rounded-md border bg-popover shadow-md">
|
||||
<div className="max-h-[240px] overflow-y-auto py-1">
|
||||
{suggestions.map((item, idx) => {
|
||||
const sub = getSubLabel(item);
|
||||
return (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
className={cn(
|
||||
"flex w-full items-center gap-2 px-3 py-1.5 text-left text-sm hover:bg-accent",
|
||||
idx === activeIndex && "bg-accent",
|
||||
)}
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault(); // Prevent blur before click
|
||||
handleSelect(item);
|
||||
}}
|
||||
onMouseEnter={() => setActiveIndex(idx)}
|
||||
>
|
||||
{item.colorHex ? (
|
||||
<ColorSwatch hex={item.colorHex} size="sm" className="shrink-0" />
|
||||
) : (
|
||||
<div className="h-4 w-4 shrink-0 rounded-sm border border-dashed border-border" />
|
||||
)}
|
||||
|
||||
<span className="min-w-0 flex-1 truncate">{item.name}</span>
|
||||
|
||||
{sub && (
|
||||
<Badge variant="secondary" className="shrink-0 text-[10px] px-1 py-0">
|
||||
{sub}
|
||||
</Badge>
|
||||
)}
|
||||
|
||||
{item.price != null && (
|
||||
<span className="shrink-0 text-xs text-muted-foreground">
|
||||
${item.price.toFixed(2)}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className="border-t px-3 py-1 text-[10px] text-muted-foreground">
|
||||
Select to auto-fill form
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
37
src/components/shared/catalog-browser-button.tsx
Normal file
37
src/components/shared/catalog-browser-button.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Search } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CatalogBrowser } from "@/components/shared/catalog-browser";
|
||||
import type { CatalogItem, CatalogItemType } from "@/types/catalog.types";
|
||||
|
||||
interface CatalogBrowserButtonProps {
|
||||
type: CatalogItemType;
|
||||
onSelect: (item: CatalogItem) => void;
|
||||
}
|
||||
|
||||
export function CatalogBrowserButton({ type, onSelect }: CatalogBrowserButtonProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setOpen(true)}
|
||||
>
|
||||
<Search className="mr-2 h-4 w-4" />
|
||||
Browse Catalog
|
||||
</Button>
|
||||
|
||||
<CatalogBrowser
|
||||
type={type}
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
onSelect={onSelect}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
226
src/components/shared/catalog-browser.tsx
Normal file
226
src/components/shared/catalog-browser.tsx
Normal file
@@ -0,0 +1,226 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import type { CatalogItem, CatalogItemType, CatalogBrand } from "@/types/catalog.types";
|
||||
import {
|
||||
CommandDialog,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
} from "@/components/ui/command";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { ColorSwatch } from "@/components/shared/color-swatch";
|
||||
import { Loader2 } from "lucide-react";
|
||||
|
||||
interface CatalogBrowserProps {
|
||||
type: CatalogItemType;
|
||||
onSelect: (item: CatalogItem) => void;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
const TYPE_LABELS: Record<CatalogItemType, string> = {
|
||||
filament: "Filaments",
|
||||
resin: "Resins",
|
||||
paint: "Paints",
|
||||
};
|
||||
|
||||
const API_PATHS: Record<CatalogItemType, string> = {
|
||||
filament: "/api/catalog/filaments",
|
||||
resin: "/api/catalog/resins",
|
||||
paint: "/api/catalog/paints",
|
||||
};
|
||||
|
||||
export function CatalogBrowser({
|
||||
type,
|
||||
onSelect,
|
||||
open,
|
||||
onOpenChange,
|
||||
}: CatalogBrowserProps) {
|
||||
const [items, setItems] = useState<CatalogItem[]>([]);
|
||||
const [brands, setBrands] = useState<CatalogBrand[]>([]);
|
||||
const [activeBrand, setActiveBrand] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [search, setSearch] = useState("");
|
||||
const [hasFetched, setHasFetched] = useState(false);
|
||||
|
||||
// Fetch catalog data when dialog opens
|
||||
const fetchData = useCallback(
|
||||
async (brandFilter?: string, searchFilter?: string) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
if (brandFilter) params.set("brand", brandFilter);
|
||||
if (searchFilter && searchFilter.length >= 2) params.set("search", searchFilter);
|
||||
|
||||
const resp = await fetch(`${API_PATHS[type]}?${params.toString()}`);
|
||||
if (!resp.ok) throw new Error("Failed to fetch catalog");
|
||||
|
||||
const data = await resp.json();
|
||||
setItems(data.items ?? []);
|
||||
if (data.brands) setBrands(data.brands);
|
||||
} catch (err) {
|
||||
console.error("Catalog fetch error:", err);
|
||||
setItems([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[type],
|
||||
);
|
||||
|
||||
// Initial fetch when opening
|
||||
useEffect(() => {
|
||||
if (open && !hasFetched) {
|
||||
setHasFetched(true);
|
||||
fetchData();
|
||||
}
|
||||
if (!open) {
|
||||
setHasFetched(false);
|
||||
setActiveBrand(null);
|
||||
setSearch("");
|
||||
}
|
||||
}, [open, hasFetched, fetchData]);
|
||||
|
||||
// Refetch when brand changes
|
||||
useEffect(() => {
|
||||
if (!open || !hasFetched) return;
|
||||
fetchData(activeBrand ?? undefined);
|
||||
}, [activeBrand, open, hasFetched, fetchData]);
|
||||
|
||||
function handleSelect(item: CatalogItem) {
|
||||
onSelect(item);
|
||||
onOpenChange(false);
|
||||
}
|
||||
|
||||
// Debounced search
|
||||
useEffect(() => {
|
||||
if (!open || !hasFetched) return;
|
||||
const timeout = setTimeout(() => {
|
||||
fetchData(activeBrand ?? undefined, search || undefined);
|
||||
}, 300);
|
||||
return () => clearTimeout(timeout);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [search]);
|
||||
|
||||
/** Secondary badge text based on item type */
|
||||
function getSubLabel(item: CatalogItem): string | null {
|
||||
if (item.type === "filament" && item.material) return item.material;
|
||||
if (item.type === "resin" && item.resinType) return item.resinType;
|
||||
if (item.type === "paint" && item.line) return item.line;
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<CommandDialog
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
title={`Browse ${TYPE_LABELS[type]} Catalog`}
|
||||
description={`Search and select a product to auto-fill the form`}
|
||||
>
|
||||
<CommandInput
|
||||
placeholder={`Search ${TYPE_LABELS[type].toLowerCase()}...`}
|
||||
value={search}
|
||||
onValueChange={setSearch}
|
||||
/>
|
||||
|
||||
{/* Brand filter chips */}
|
||||
{brands.length > 1 && (
|
||||
<div className="flex flex-wrap gap-1.5 border-b px-3 py-2">
|
||||
<Badge
|
||||
variant={activeBrand === null ? "default" : "outline"}
|
||||
className="cursor-pointer text-xs"
|
||||
onClick={() => setActiveBrand(null)}
|
||||
>
|
||||
All
|
||||
</Badge>
|
||||
{brands.map((b) => (
|
||||
<Badge
|
||||
key={b.id}
|
||||
variant={activeBrand === b.name ? "default" : "outline"}
|
||||
className="cursor-pointer text-xs"
|
||||
onClick={() =>
|
||||
setActiveBrand(activeBrand === b.name ? null : b.name)
|
||||
}
|
||||
>
|
||||
{b.name}
|
||||
<span className="ml-1 opacity-60">{b.itemCount}</span>
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<CommandList className="max-h-[400px]">
|
||||
{loading && (
|
||||
<div className="flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
Loading catalog...
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && items.length === 0 && (
|
||||
<CommandEmpty>No products found.</CommandEmpty>
|
||||
)}
|
||||
|
||||
{!loading && items.length > 0 && (
|
||||
<CommandGroup heading={`${items.length} product${items.length !== 1 ? "s" : ""}`}>
|
||||
{items.slice(0, 200).map((item) => {
|
||||
const sub = getSubLabel(item);
|
||||
return (
|
||||
<CommandItem
|
||||
key={item.id}
|
||||
value={`${item.name} ${item.brand} ${item.color ?? ""} ${sub ?? ""}`}
|
||||
onSelect={() => handleSelect(item)}
|
||||
className="flex items-center gap-3 py-2"
|
||||
>
|
||||
{/* Colour swatch */}
|
||||
{item.colorHex ? (
|
||||
<ColorSwatch hex={item.colorHex} size="md" className="shrink-0" />
|
||||
) : (
|
||||
<div className="h-6 w-6 shrink-0 rounded-sm border border-dashed border-border" />
|
||||
)}
|
||||
|
||||
{/* Name + brand */}
|
||||
<div className="flex min-w-0 flex-1 flex-col">
|
||||
<span className="truncate font-medium text-sm">
|
||||
{item.name}
|
||||
</span>
|
||||
<span className="truncate text-xs text-muted-foreground">
|
||||
{item.brand}
|
||||
{item.color && item.color !== item.name
|
||||
? ` — ${item.color}`
|
||||
: ""}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Type / material badge */}
|
||||
{sub && (
|
||||
<Badge variant="secondary" className="shrink-0 text-xs">
|
||||
{sub}
|
||||
</Badge>
|
||||
)}
|
||||
|
||||
{/* Finish badge for paints */}
|
||||
{item.finish && item.finish !== "Matte" && (
|
||||
<Badge variant="outline" className="shrink-0 text-xs">
|
||||
{item.finish}
|
||||
</Badge>
|
||||
)}
|
||||
|
||||
{/* Price */}
|
||||
{item.price != null && (
|
||||
<span className="shrink-0 text-xs text-muted-foreground">
|
||||
${item.price.toFixed(2)}
|
||||
</span>
|
||||
)}
|
||||
</CommandItem>
|
||||
);
|
||||
})}
|
||||
</CommandGroup>
|
||||
)}
|
||||
</CommandList>
|
||||
</CommandDialog>
|
||||
);
|
||||
}
|
||||
37
src/components/shared/color-swatch.tsx
Normal file
37
src/components/shared/color-swatch.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface ColorSwatchProps {
|
||||
hex: string;
|
||||
size?: "sm" | "md" | "lg";
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const sizeClasses = {
|
||||
sm: "h-4 w-4",
|
||||
md: "h-6 w-6",
|
||||
lg: "h-8 w-8",
|
||||
};
|
||||
|
||||
export function ColorSwatch({ hex, size = "sm", className }: ColorSwatchProps) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-sm border border-border",
|
||||
sizeClasses[size],
|
||||
className
|
||||
)}
|
||||
style={{ backgroundColor: hex }}
|
||||
title={hex}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ColorPreviewStrip({ hex, className }: { hex: string; className?: string }) {
|
||||
return (
|
||||
<div
|
||||
className={cn("h-full w-1 rounded-full", className)}
|
||||
style={{ backgroundColor: hex }}
|
||||
title={hex}
|
||||
/>
|
||||
);
|
||||
}
|
||||
49
src/components/shared/data-table-column-header.tsx
Normal file
49
src/components/shared/data-table-column-header.tsx
Normal file
@@ -0,0 +1,49 @@
|
||||
"use client";
|
||||
|
||||
import { type Column } from "@tanstack/react-table";
|
||||
import { ArrowDown, ArrowUp, ArrowUpDown } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
interface DataTableColumnHeaderProps<TData, TValue> {
|
||||
column: Column<TData, TValue>;
|
||||
title: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function DataTableColumnHeader<TData, TValue>({
|
||||
column,
|
||||
title,
|
||||
className,
|
||||
}: DataTableColumnHeaderProps<TData, TValue>) {
|
||||
if (!column.getCanSort()) {
|
||||
return <div className={cn(className)}>{title}</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className={cn("-ml-3 h-8 text-xs", className)}
|
||||
onClick={() => {
|
||||
const currentSort = column.getIsSorted();
|
||||
if (currentSort === false) {
|
||||
column.toggleSorting(false);
|
||||
} else if (currentSort === "asc") {
|
||||
column.toggleSorting(true);
|
||||
} else {
|
||||
column.clearSorting();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span>{title}</span>
|
||||
{column.getIsSorted() === "desc" ? (
|
||||
<ArrowDown className="ml-1 h-3 w-3" />
|
||||
) : column.getIsSorted() === "asc" ? (
|
||||
<ArrowUp className="ml-1 h-3 w-3" />
|
||||
) : (
|
||||
<ArrowUpDown className="ml-1 h-3 w-3 opacity-50" />
|
||||
)}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
126
src/components/shared/data-table-faceted-filter.tsx
Normal file
126
src/components/shared/data-table-faceted-filter.tsx
Normal file
@@ -0,0 +1,126 @@
|
||||
"use client";
|
||||
|
||||
import { CheckIcon, PlusCircle } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
CommandSeparator,
|
||||
} from "@/components/ui/command";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
|
||||
interface FacetedFilterOption {
|
||||
label: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
interface DataTableFacetedFilterProps {
|
||||
title: string;
|
||||
options: FacetedFilterOption[];
|
||||
selectedValues: Set<string>;
|
||||
onSelectionChange: (values: Set<string>) => void;
|
||||
}
|
||||
|
||||
export function DataTableFacetedFilter({
|
||||
title,
|
||||
options,
|
||||
selectedValues,
|
||||
onSelectionChange,
|
||||
}: DataTableFacetedFilterProps) {
|
||||
return (
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button variant="outline" size="sm" className="h-8 border-dashed">
|
||||
<PlusCircle className="mr-2 h-3.5 w-3.5" />
|
||||
{title}
|
||||
{selectedValues.size > 0 && (
|
||||
<>
|
||||
<Separator orientation="vertical" className="mx-2 h-4" />
|
||||
<Badge variant="secondary" className="rounded-sm px-1 font-normal lg:hidden">
|
||||
{selectedValues.size}
|
||||
</Badge>
|
||||
<div className="hidden space-x-1 lg:flex">
|
||||
{selectedValues.size > 2 ? (
|
||||
<Badge variant="secondary" className="rounded-sm px-1 font-normal">
|
||||
{selectedValues.size} selected
|
||||
</Badge>
|
||||
) : (
|
||||
options
|
||||
.filter((option) => selectedValues.has(option.value))
|
||||
.map((option) => (
|
||||
<Badge
|
||||
key={option.value}
|
||||
variant="secondary"
|
||||
className="rounded-sm px-1 font-normal"
|
||||
>
|
||||
{option.label}
|
||||
</Badge>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-[200px] p-0" align="start">
|
||||
<Command>
|
||||
<CommandInput placeholder={title} className="h-9" />
|
||||
<CommandList>
|
||||
<CommandEmpty>No results found.</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{options.map((option) => {
|
||||
const isSelected = selectedValues.has(option.value);
|
||||
return (
|
||||
<CommandItem
|
||||
key={option.value}
|
||||
onSelect={() => {
|
||||
const newValues = new Set(selectedValues);
|
||||
if (isSelected) {
|
||||
newValues.delete(option.value);
|
||||
} else {
|
||||
newValues.add(option.value);
|
||||
}
|
||||
onSelectionChange(newValues);
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
|
||||
isSelected
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "opacity-50 [&_svg]:invisible"
|
||||
)}
|
||||
>
|
||||
<CheckIcon className="h-3.5 w-3.5" />
|
||||
</div>
|
||||
<span className="text-sm">{option.label}</span>
|
||||
</CommandItem>
|
||||
);
|
||||
})}
|
||||
</CommandGroup>
|
||||
{selectedValues.size > 0 && (
|
||||
<>
|
||||
<CommandSeparator />
|
||||
<CommandGroup>
|
||||
<CommandItem
|
||||
onSelect={() => onSelectionChange(new Set())}
|
||||
className="justify-center text-center text-xs"
|
||||
>
|
||||
Clear filters
|
||||
</CommandItem>
|
||||
</CommandGroup>
|
||||
</>
|
||||
)}
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
117
src/components/shared/data-table-pagination.tsx
Normal file
117
src/components/shared/data-table-pagination.tsx
Normal file
@@ -0,0 +1,117 @@
|
||||
"use client";
|
||||
|
||||
import { type Table } from "@tanstack/react-table";
|
||||
import {
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
ChevronsLeft,
|
||||
ChevronsRight,
|
||||
} from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { PAGE_SIZE_OPTIONS } from "@/lib/constants";
|
||||
|
||||
interface DataTablePaginationProps<TData> {
|
||||
table: Table<TData>;
|
||||
totalCount?: number;
|
||||
}
|
||||
|
||||
export function DataTablePagination<TData>({
|
||||
table,
|
||||
totalCount,
|
||||
}: DataTablePaginationProps<TData>) {
|
||||
const pageIndex = table.getState().pagination.pageIndex;
|
||||
const pageSize = table.getState().pagination.pageSize;
|
||||
const pageCount = table.getPageCount();
|
||||
|
||||
const from = pageIndex * pageSize + 1;
|
||||
const to = Math.min((pageIndex + 1) * pageSize, totalCount ?? 0);
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-between px-2 py-4">
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{totalCount ? (
|
||||
<>
|
||||
Showing {from}-{to} of {totalCount} results
|
||||
</>
|
||||
) : (
|
||||
"No results"
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground">Rows</span>
|
||||
<Select
|
||||
value={`${pageSize}`}
|
||||
onValueChange={(value) => {
|
||||
table.setPageSize(Number(value));
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="h-8 w-[70px]">
|
||||
<SelectValue placeholder={`${pageSize}`} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{PAGE_SIZE_OPTIONS.map((size) => (
|
||||
<SelectItem key={size} value={`${size}`}>
|
||||
{size}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Page {pageIndex + 1} of {pageCount || 1}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={() => table.setPageIndex(0)}
|
||||
disabled={!table.getCanPreviousPage()}
|
||||
>
|
||||
<ChevronsLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={() => table.previousPage()}
|
||||
disabled={!table.getCanPreviousPage()}
|
||||
>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={() => table.nextPage()}
|
||||
disabled={!table.getCanNextPage()}
|
||||
>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={() => table.setPageIndex(pageCount - 1)}
|
||||
disabled={!table.getCanNextPage()}
|
||||
>
|
||||
<ChevronsRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
47
src/components/shared/data-table-view-options.tsx
Normal file
47
src/components/shared/data-table-view-options.tsx
Normal file
@@ -0,0 +1,47 @@
|
||||
"use client";
|
||||
|
||||
import { type Table } from "@tanstack/react-table";
|
||||
import { SlidersHorizontal } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
|
||||
interface DataTableViewOptionsProps<TData> {
|
||||
table: Table<TData>;
|
||||
}
|
||||
|
||||
export function DataTableViewOptions<TData>({ table }: DataTableViewOptionsProps<TData>) {
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="sm" className="h-8">
|
||||
<SlidersHorizontal className="mr-2 h-3.5 w-3.5" />
|
||||
Columns
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-40">
|
||||
<DropdownMenuLabel className="text-xs">Toggle columns</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
{table
|
||||
.getAllColumns()
|
||||
.filter((column) => typeof column.accessorFn !== "undefined" && column.getCanHide())
|
||||
.map((column) => (
|
||||
<DropdownMenuCheckboxItem
|
||||
key={column.id}
|
||||
className="text-xs capitalize"
|
||||
checked={column.getIsVisible()}
|
||||
onCheckedChange={(value) => column.toggleVisibility(!!value)}
|
||||
>
|
||||
{column.id}
|
||||
</DropdownMenuCheckboxItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
58
src/components/shared/data-table.tsx
Normal file
58
src/components/shared/data-table.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
"use client";
|
||||
|
||||
import { type Table as TanStackTable, flexRender } from "@tanstack/react-table";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { EmptyState } from "./empty-state";
|
||||
|
||||
interface DataTableProps<TData> {
|
||||
table: TanStackTable<TData>;
|
||||
emptyMessage?: string;
|
||||
}
|
||||
|
||||
export function DataTable<TData>({ table, emptyMessage }: DataTableProps<TData>) {
|
||||
return (
|
||||
<div className="rounded-md border border-border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id} className="hover:bg-transparent">
|
||||
{headerGroup.headers.map((header) => (
|
||||
<TableHead key={header.id} className="h-9 text-xs font-medium text-muted-foreground">
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(header.column.columnDef.header, header.getContext())}
|
||||
</TableHead>
|
||||
))}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{table.getRowModel().rows?.length ? (
|
||||
table.getRowModel().rows.map((row) => (
|
||||
<TableRow key={row.id} className="h-10 border-border hover:bg-muted/50">
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id} className="py-1.5 text-sm">
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell colSpan={table.getAllColumns().length} className="h-32 text-center">
|
||||
<EmptyState message={emptyMessage} />
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
51
src/components/shared/delete-dialog.tsx
Normal file
51
src/components/shared/delete-dialog.tsx
Normal file
@@ -0,0 +1,51 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
|
||||
interface DeleteDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
title?: string;
|
||||
description?: string;
|
||||
onConfirm: () => void;
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
export function DeleteDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
title = "Are you sure?",
|
||||
description = "This action cannot be undone.",
|
||||
onConfirm,
|
||||
isLoading,
|
||||
}: DeleteDialogProps) {
|
||||
return (
|
||||
<AlertDialog open={open} onOpenChange={onOpenChange}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{title}</AlertDialogTitle>
|
||||
<AlertDialogDescription>{description}</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isLoading}>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={onConfirm}
|
||||
disabled={isLoading}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{isLoading ? "Deleting..." : "Delete"}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
18
src/components/shared/empty-state.tsx
Normal file
18
src/components/shared/empty-state.tsx
Normal file
@@ -0,0 +1,18 @@
|
||||
import { Package } from "lucide-react";
|
||||
|
||||
interface EmptyStateProps {
|
||||
message?: string;
|
||||
icon?: React.ReactNode;
|
||||
}
|
||||
|
||||
export function EmptyState({
|
||||
message = "No results found",
|
||||
icon,
|
||||
}: EmptyStateProps) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center gap-2 py-8 text-center">
|
||||
{icon || <Package className="h-8 w-8 text-muted-foreground/50" />}
|
||||
<p className="text-sm text-muted-foreground">{message}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
17
src/components/shared/page-header.tsx
Normal file
17
src/components/shared/page-header.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
interface PageHeaderProps {
|
||||
title: string;
|
||||
description?: string;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
export function PageHeader({ title, description, children }: PageHeaderProps) {
|
||||
return (
|
||||
<div className="mb-6 flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold tracking-tight">{title}</h2>
|
||||
{description && <p className="text-sm text-muted-foreground">{description}</p>}
|
||||
</div>
|
||||
{children && <div className="flex items-center gap-2">{children}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
40
src/components/shared/stat-card.tsx
Normal file
40
src/components/shared/stat-card.tsx
Normal file
@@ -0,0 +1,40 @@
|
||||
import { type LucideIcon } from "lucide-react";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface StatCardProps {
|
||||
title: string;
|
||||
value: string | number;
|
||||
icon: LucideIcon;
|
||||
description?: string;
|
||||
className?: string;
|
||||
iconClassName?: string;
|
||||
}
|
||||
|
||||
export function StatCard({
|
||||
title,
|
||||
value,
|
||||
icon: Icon,
|
||||
description,
|
||||
className,
|
||||
iconClassName,
|
||||
}: StatCardProps) {
|
||||
return (
|
||||
<Card className={cn("border-border", className)}>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs font-medium text-muted-foreground">{title}</p>
|
||||
<p className="text-2xl font-bold">{value}</p>
|
||||
{description && (
|
||||
<p className="text-xs text-muted-foreground">{description}</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="rounded-md bg-primary/10 p-2.5">
|
||||
<Icon className={cn("h-5 w-5 text-primary", iconClassName)} />
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
51
src/components/shared/status-badge.tsx
Normal file
51
src/components/shared/status-badge.tsx
Normal file
@@ -0,0 +1,51 @@
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type StatusVariant = "inStock" | "lowStock" | "empty" | "archived";
|
||||
|
||||
interface StatusBadgeProps {
|
||||
variant: StatusVariant;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const variantConfig: Record<StatusVariant, { label: string; className: string }> = {
|
||||
inStock: {
|
||||
label: "In Stock",
|
||||
className: "bg-emerald-500/15 text-emerald-400 border-emerald-500/30",
|
||||
},
|
||||
lowStock: {
|
||||
label: "Low Stock",
|
||||
className: "bg-orange-500/15 text-orange-400 border-orange-500/30",
|
||||
},
|
||||
empty: {
|
||||
label: "Empty",
|
||||
className: "bg-red-500/15 text-red-400 border-red-500/30",
|
||||
},
|
||||
archived: {
|
||||
label: "Archived",
|
||||
className: "bg-zinc-500/15 text-zinc-400 border-zinc-500/30",
|
||||
},
|
||||
};
|
||||
|
||||
export function StatusBadge({ variant, className }: StatusBadgeProps) {
|
||||
const config = variantConfig[variant];
|
||||
|
||||
return (
|
||||
<Badge variant="outline" className={cn("text-[10px] font-medium", config.className, className)}>
|
||||
{config.label}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
|
||||
export function getStockStatus(
|
||||
remaining: number,
|
||||
total: number,
|
||||
threshold: number,
|
||||
archived: boolean
|
||||
): StatusVariant {
|
||||
if (archived) return "archived";
|
||||
const percent = total > 0 ? (remaining / total) * 100 : 0;
|
||||
if (percent <= 0) return "empty";
|
||||
if (percent <= threshold) return "lowStock";
|
||||
return "inStock";
|
||||
}
|
||||
140
src/components/shared/usage-log-dialog.tsx
Normal file
140
src/components/shared/usage-log-dialog.tsx
Normal file
@@ -0,0 +1,140 @@
|
||||
"use client";
|
||||
|
||||
import { useTransition } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { z } from "zod/v4";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
const usageSchema = z.object({
|
||||
amount: z.coerce.number().positive("Amount must be positive"),
|
||||
notes: z.string().max(512).optional(),
|
||||
});
|
||||
|
||||
type UsageInput = z.infer<typeof usageSchema>;
|
||||
|
||||
interface UsageLogDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
itemName: string;
|
||||
unit: "g" | "ml";
|
||||
onSubmit: (amount: number, notes?: string) => Promise<{ success: boolean; error?: string }>;
|
||||
}
|
||||
|
||||
export function UsageLogDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
itemName,
|
||||
unit,
|
||||
onSubmit,
|
||||
}: UsageLogDialogProps) {
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
const form = useForm<UsageInput>({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
resolver: zodResolver(usageSchema) as any,
|
||||
defaultValues: { amount: 0, notes: "" },
|
||||
});
|
||||
|
||||
function handleSubmit(values: UsageInput) {
|
||||
startTransition(async () => {
|
||||
const result = await onSubmit(values.amount, values.notes);
|
||||
|
||||
if (!result.success) {
|
||||
toast.error(result.error || "Failed to log usage");
|
||||
return;
|
||||
}
|
||||
|
||||
toast.success("Usage logged successfully");
|
||||
form.reset();
|
||||
onOpenChange(false);
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Log Usage</DialogTitle>
|
||||
<DialogDescription>
|
||||
Record usage for {itemName}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="amount"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Amount ({unit})</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
step="0.1"
|
||||
min="0"
|
||||
placeholder={`Amount in ${unit}`}
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="notes"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Notes (optional)</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
placeholder="What was this used for?"
|
||||
rows={3}
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
disabled={isPending}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isPending}>
|
||||
{isPending ? "Logging..." : "Log Usage"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
196
src/components/ui/alert-dialog.tsx
Normal file
196
src/components/ui/alert-dialog.tsx
Normal file
@@ -0,0 +1,196 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { AlertDialog as AlertDialogPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
function AlertDialog({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
|
||||
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
|
||||
}
|
||||
|
||||
function AlertDialogTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Overlay
|
||||
data-slot="alert-dialog-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogContent({
|
||||
className,
|
||||
size = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Content> & {
|
||||
size?: "default" | "sm"
|
||||
}) {
|
||||
return (
|
||||
<AlertDialogPortal>
|
||||
<AlertDialogOverlay />
|
||||
<AlertDialogPrimitive.Content
|
||||
data-slot="alert-dialog-content"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 group/alert-dialog-content fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 data-[size=sm]:max-w-xs data-[size=default]:sm:max-w-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</AlertDialogPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogHeader({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-dialog-header"
|
||||
className={cn(
|
||||
"grid grid-rows-[auto_1fr] place-items-center gap-1.5 text-center has-data-[slot=alert-dialog-media]:grid-rows-[auto_auto_1fr] has-data-[slot=alert-dialog-media]:gap-x-6 sm:group-data-[size=default]/alert-dialog-content:place-items-start sm:group-data-[size=default]/alert-dialog-content:text-left sm:group-data-[size=default]/alert-dialog-content:has-data-[slot=alert-dialog-media]:grid-rows-[auto_1fr]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogFooter({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-dialog-footer"
|
||||
className={cn(
|
||||
"flex flex-col-reverse gap-2 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Title
|
||||
data-slot="alert-dialog-title"
|
||||
className={cn(
|
||||
"text-lg font-semibold sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Description
|
||||
data-slot="alert-dialog-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogMedia({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-dialog-media"
|
||||
className={cn(
|
||||
"bg-muted mb-2 inline-flex size-16 items-center justify-center rounded-md sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogAction({
|
||||
className,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Action> &
|
||||
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
|
||||
return (
|
||||
<Button variant={variant} size={size} asChild>
|
||||
<AlertDialogPrimitive.Action
|
||||
data-slot="alert-dialog-action"
|
||||
className={cn(className)}
|
||||
{...props}
|
||||
/>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogCancel({
|
||||
className,
|
||||
variant = "outline",
|
||||
size = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel> &
|
||||
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
|
||||
return (
|
||||
<Button variant={variant} size={size} asChild>
|
||||
<AlertDialogPrimitive.Cancel
|
||||
data-slot="alert-dialog-cancel"
|
||||
className={cn(className)}
|
||||
{...props}
|
||||
/>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogMedia,
|
||||
AlertDialogOverlay,
|
||||
AlertDialogPortal,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
}
|
||||
109
src/components/ui/avatar.tsx
Normal file
109
src/components/ui/avatar.tsx
Normal file
@@ -0,0 +1,109 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Avatar as AvatarPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Avatar({
|
||||
className,
|
||||
size = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof AvatarPrimitive.Root> & {
|
||||
size?: "default" | "sm" | "lg"
|
||||
}) {
|
||||
return (
|
||||
<AvatarPrimitive.Root
|
||||
data-slot="avatar"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"group/avatar relative flex size-8 shrink-0 overflow-hidden rounded-full select-none data-[size=lg]:size-10 data-[size=sm]:size-6",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AvatarImage({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
|
||||
return (
|
||||
<AvatarPrimitive.Image
|
||||
data-slot="avatar-image"
|
||||
className={cn("aspect-square size-full", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AvatarFallback({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
|
||||
return (
|
||||
<AvatarPrimitive.Fallback
|
||||
data-slot="avatar-fallback"
|
||||
className={cn(
|
||||
"bg-muted text-muted-foreground flex size-full items-center justify-center rounded-full text-sm group-data-[size=sm]/avatar:text-xs",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="avatar-badge"
|
||||
className={cn(
|
||||
"bg-primary text-primary-foreground ring-background absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full ring-2 select-none",
|
||||
"group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden",
|
||||
"group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2",
|
||||
"group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AvatarGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="avatar-group"
|
||||
className={cn(
|
||||
"*:data-[slot=avatar]:ring-background group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AvatarGroupCount({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="avatar-group-count"
|
||||
className={cn(
|
||||
"bg-muted text-muted-foreground ring-background relative flex size-8 shrink-0 items-center justify-center rounded-full text-sm ring-2 group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=sm]/avatar-group:size-6 [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Avatar,
|
||||
AvatarImage,
|
||||
AvatarFallback,
|
||||
AvatarBadge,
|
||||
AvatarGroup,
|
||||
AvatarGroupCount,
|
||||
}
|
||||
48
src/components/ui/badge.tsx
Normal file
48
src/components/ui/badge.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { Slot } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center justify-center rounded-full border border-transparent px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
|
||||
destructive:
|
||||
"bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
||||
ghost: "[a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
||||
link: "text-primary underline-offset-4 [a&]:hover:underline",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Badge({
|
||||
className,
|
||||
variant = "default",
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"span"> &
|
||||
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot.Root : "span"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="badge"
|
||||
data-variant={variant}
|
||||
className={cn(badgeVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants }
|
||||
64
src/components/ui/button.tsx
Normal file
64
src/components/ui/button.tsx
Normal file
@@ -0,0 +1,64 @@
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { Slot } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
ghost:
|
||||
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||
xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",
|
||||
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
||||
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||
icon: "size-9",
|
||||
"icon-xs": "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3",
|
||||
"icon-sm": "size-8",
|
||||
"icon-lg": "size-10",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot.Root : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
data-variant={variant}
|
||||
data-size={size}
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
92
src/components/ui/card.tsx
Normal file
92
src/components/ui/card.tsx
Normal file
@@ -0,0 +1,92 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card"
|
||||
className={cn(
|
||||
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-header"
|
||||
className={cn(
|
||||
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-title"
|
||||
className={cn("leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-action"
|
||||
className={cn(
|
||||
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-content"
|
||||
className={cn("px-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-footer"
|
||||
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardFooter,
|
||||
CardTitle,
|
||||
CardAction,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
}
|
||||
32
src/components/ui/checkbox.tsx
Normal file
32
src/components/ui/checkbox.tsx
Normal file
@@ -0,0 +1,32 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { CheckIcon } from "lucide-react"
|
||||
import { Checkbox as CheckboxPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Checkbox({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
|
||||
return (
|
||||
<CheckboxPrimitive.Root
|
||||
data-slot="checkbox"
|
||||
className={cn(
|
||||
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator
|
||||
data-slot="checkbox-indicator"
|
||||
className="grid place-content-center text-current transition-none"
|
||||
>
|
||||
<CheckIcon className="size-3.5" />
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Checkbox }
|
||||
184
src/components/ui/command.tsx
Normal file
184
src/components/ui/command.tsx
Normal file
@@ -0,0 +1,184 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Command as CommandPrimitive } from "cmdk"
|
||||
import { SearchIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
|
||||
function Command({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive>) {
|
||||
return (
|
||||
<CommandPrimitive
|
||||
data-slot="command"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandDialog({
|
||||
title = "Command Palette",
|
||||
description = "Search for a command to run...",
|
||||
children,
|
||||
className,
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Dialog> & {
|
||||
title?: string
|
||||
description?: string
|
||||
className?: string
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<Dialog {...props}>
|
||||
<DialogHeader className="sr-only">
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>{description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogContent
|
||||
className={cn("overflow-hidden p-0", className)}
|
||||
showCloseButton={showCloseButton}
|
||||
>
|
||||
<Command className="[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
|
||||
{children}
|
||||
</Command>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandInput({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Input>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="command-input-wrapper"
|
||||
className="flex h-9 items-center gap-2 border-b px-3"
|
||||
>
|
||||
<SearchIcon className="size-4 shrink-0 opacity-50" />
|
||||
<CommandPrimitive.Input
|
||||
data-slot="command-input"
|
||||
className={cn(
|
||||
"placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandList({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.List>) {
|
||||
return (
|
||||
<CommandPrimitive.List
|
||||
data-slot="command-list"
|
||||
className={cn(
|
||||
"max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandEmpty({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Empty>) {
|
||||
return (
|
||||
<CommandPrimitive.Empty
|
||||
data-slot="command-empty"
|
||||
className="py-6 text-center text-sm"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandGroup({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Group>) {
|
||||
return (
|
||||
<CommandPrimitive.Group
|
||||
data-slot="command-group"
|
||||
className={cn(
|
||||
"text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Separator>) {
|
||||
return (
|
||||
<CommandPrimitive.Separator
|
||||
data-slot="command-separator"
|
||||
className={cn("bg-border -mx-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Item>) {
|
||||
return (
|
||||
<CommandPrimitive.Item
|
||||
data-slot="command-item"
|
||||
className={cn(
|
||||
"data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="command-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Command,
|
||||
CommandDialog,
|
||||
CommandInput,
|
||||
CommandList,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandItem,
|
||||
CommandShortcut,
|
||||
CommandSeparator,
|
||||
}
|
||||
158
src/components/ui/dialog.tsx
Normal file
158
src/components/ui/dialog.tsx
Normal file
@@ -0,0 +1,158 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { XIcon } from "lucide-react"
|
||||
import { Dialog as DialogPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
function Dialog({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
||||
}
|
||||
|
||||
function DialogTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
||||
}
|
||||
|
||||
function DialogPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
||||
}
|
||||
|
||||
function DialogClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
||||
}
|
||||
|
||||
function DialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<DialogPrimitive.Overlay
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogContent({
|
||||
className,
|
||||
children,
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DialogPortal data-slot="dialog-portal">
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
data-slot="dialog-content"
|
||||
className={cn(
|
||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 outline-none sm:max-w-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close
|
||||
data-slot="dialog-close"
|
||||
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
|
||||
>
|
||||
<XIcon />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-header"
|
||||
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogFooter({
|
||||
className,
|
||||
showCloseButton = false,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-footer"
|
||||
className={cn(
|
||||
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close asChild>
|
||||
<Button variant="outline">Close</Button>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||
return (
|
||||
<DialogPrimitive.Title
|
||||
data-slot="dialog-title"
|
||||
className={cn("text-lg leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||
return (
|
||||
<DialogPrimitive.Description
|
||||
data-slot="dialog-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
}
|
||||
257
src/components/ui/dropdown-menu.tsx
Normal file
257
src/components/ui/dropdown-menu.tsx
Normal file
@@ -0,0 +1,257 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||
import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function DropdownMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
||||
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
|
||||
}
|
||||
|
||||
function DropdownMenuPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Trigger
|
||||
data-slot="dropdown-menu-trigger"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuContent({
|
||||
className,
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal>
|
||||
<DropdownMenuPrimitive.Content
|
||||
data-slot="dropdown-menu-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</DropdownMenuPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Item
|
||||
data-slot="dropdown-menu-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.CheckboxItem
|
||||
data-slot="dropdown-menu-checkbox-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.CheckboxItem>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioGroup
|
||||
data-slot="dropdown-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioItem
|
||||
data-slot="dropdown-menu-radio-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CircleIcon className="size-2 fill-current" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.RadioItem>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Label
|
||||
data-slot="dropdown-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Separator
|
||||
data-slot="dropdown-menu-separator"
|
||||
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="dropdown-menu-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
||||
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
|
||||
}
|
||||
|
||||
function DropdownMenuSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubTrigger
|
||||
data-slot="dropdown-menu-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto size-4" />
|
||||
</DropdownMenuPrimitive.SubTrigger>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSubContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubContent
|
||||
data-slot="dropdown-menu-sub-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
DropdownMenu,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuShortcut,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuSubContent,
|
||||
}
|
||||
167
src/components/ui/form.tsx
Normal file
167
src/components/ui/form.tsx
Normal file
@@ -0,0 +1,167 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import type { Label as LabelPrimitive } from "radix-ui"
|
||||
import { Slot } from "radix-ui"
|
||||
import {
|
||||
Controller,
|
||||
FormProvider,
|
||||
useFormContext,
|
||||
useFormState,
|
||||
type ControllerProps,
|
||||
type FieldPath,
|
||||
type FieldValues,
|
||||
} from "react-hook-form"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Label } from "@/components/ui/label"
|
||||
|
||||
const Form = FormProvider
|
||||
|
||||
type FormFieldContextValue<
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||
> = {
|
||||
name: TName
|
||||
}
|
||||
|
||||
const FormFieldContext = React.createContext<FormFieldContextValue>(
|
||||
{} as FormFieldContextValue
|
||||
)
|
||||
|
||||
const FormField = <
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||
>({
|
||||
...props
|
||||
}: ControllerProps<TFieldValues, TName>) => {
|
||||
return (
|
||||
<FormFieldContext.Provider value={{ name: props.name }}>
|
||||
<Controller {...props} />
|
||||
</FormFieldContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
const useFormField = () => {
|
||||
const fieldContext = React.useContext(FormFieldContext)
|
||||
const itemContext = React.useContext(FormItemContext)
|
||||
const { getFieldState } = useFormContext()
|
||||
const formState = useFormState({ name: fieldContext.name })
|
||||
const fieldState = getFieldState(fieldContext.name, formState)
|
||||
|
||||
if (!fieldContext) {
|
||||
throw new Error("useFormField should be used within <FormField>")
|
||||
}
|
||||
|
||||
const { id } = itemContext
|
||||
|
||||
return {
|
||||
id,
|
||||
name: fieldContext.name,
|
||||
formItemId: `${id}-form-item`,
|
||||
formDescriptionId: `${id}-form-item-description`,
|
||||
formMessageId: `${id}-form-item-message`,
|
||||
...fieldState,
|
||||
}
|
||||
}
|
||||
|
||||
type FormItemContextValue = {
|
||||
id: string
|
||||
}
|
||||
|
||||
const FormItemContext = React.createContext<FormItemContextValue>(
|
||||
{} as FormItemContextValue
|
||||
)
|
||||
|
||||
function FormItem({ className, ...props }: React.ComponentProps<"div">) {
|
||||
const id = React.useId()
|
||||
|
||||
return (
|
||||
<FormItemContext.Provider value={{ id }}>
|
||||
<div
|
||||
data-slot="form-item"
|
||||
className={cn("grid gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
</FormItemContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function FormLabel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||
const { error, formItemId } = useFormField()
|
||||
|
||||
return (
|
||||
<Label
|
||||
data-slot="form-label"
|
||||
data-error={!!error}
|
||||
className={cn("data-[error=true]:text-destructive", className)}
|
||||
htmlFor={formItemId}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FormControl({ ...props }: React.ComponentProps<typeof Slot.Root>) {
|
||||
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
|
||||
|
||||
return (
|
||||
<Slot.Root
|
||||
data-slot="form-control"
|
||||
id={formItemId}
|
||||
aria-describedby={
|
||||
!error
|
||||
? `${formDescriptionId}`
|
||||
: `${formDescriptionId} ${formMessageId}`
|
||||
}
|
||||
aria-invalid={!!error}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||
const { formDescriptionId } = useFormField()
|
||||
|
||||
return (
|
||||
<p
|
||||
data-slot="form-description"
|
||||
id={formDescriptionId}
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
|
||||
const { error, formMessageId } = useFormField()
|
||||
const body = error ? String(error?.message ?? "") : props.children
|
||||
|
||||
if (!body) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<p
|
||||
data-slot="form-message"
|
||||
id={formMessageId}
|
||||
className={cn("text-destructive text-sm", className)}
|
||||
{...props}
|
||||
>
|
||||
{body}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
useFormField,
|
||||
Form,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormMessage,
|
||||
FormField,
|
||||
}
|
||||
21
src/components/ui/input.tsx
Normal file
21
src/components/ui/input.tsx
Normal file
@@ -0,0 +1,21 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Input }
|
||||
24
src/components/ui/label.tsx
Normal file
24
src/components/ui/label.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Label as LabelPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Label({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||
return (
|
||||
<LabelPrimitive.Root
|
||||
data-slot="label"
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Label }
|
||||
89
src/components/ui/popover.tsx
Normal file
89
src/components/ui/popover.tsx
Normal file
@@ -0,0 +1,89 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Popover as PopoverPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Popover({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
|
||||
return <PopoverPrimitive.Root data-slot="popover" {...props} />
|
||||
}
|
||||
|
||||
function PopoverTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
|
||||
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
|
||||
}
|
||||
|
||||
function PopoverContent({
|
||||
className,
|
||||
align = "center",
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
|
||||
return (
|
||||
<PopoverPrimitive.Portal>
|
||||
<PopoverPrimitive.Content
|
||||
data-slot="popover-content"
|
||||
align={align}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</PopoverPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function PopoverAnchor({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
|
||||
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
|
||||
}
|
||||
|
||||
function PopoverHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="popover-header"
|
||||
className={cn("flex flex-col gap-1 text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function PopoverTitle({ className, ...props }: React.ComponentProps<"h2">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="popover-title"
|
||||
className={cn("font-medium", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function PopoverDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"p">) {
|
||||
return (
|
||||
<p
|
||||
data-slot="popover-description"
|
||||
className={cn("text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Popover,
|
||||
PopoverTrigger,
|
||||
PopoverContent,
|
||||
PopoverAnchor,
|
||||
PopoverHeader,
|
||||
PopoverTitle,
|
||||
PopoverDescription,
|
||||
}
|
||||
58
src/components/ui/scroll-area.tsx
Normal file
58
src/components/ui/scroll-area.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { ScrollArea as ScrollAreaPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function ScrollArea({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.Root
|
||||
data-slot="scroll-area"
|
||||
className={cn("relative", className)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Viewport
|
||||
data-slot="scroll-area-viewport"
|
||||
className="focus-visible:ring-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:outline-1"
|
||||
>
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
function ScrollBar({
|
||||
className,
|
||||
orientation = "vertical",
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
||||
data-slot="scroll-area-scrollbar"
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"flex touch-none p-px transition-colors select-none",
|
||||
orientation === "vertical" &&
|
||||
"h-full w-2.5 border-l border-l-transparent",
|
||||
orientation === "horizontal" &&
|
||||
"h-2.5 flex-col border-t border-t-transparent",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.ScrollAreaThumb
|
||||
data-slot="scroll-area-thumb"
|
||||
className="bg-border relative flex-1 rounded-full"
|
||||
/>
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
)
|
||||
}
|
||||
|
||||
export { ScrollArea, ScrollBar }
|
||||
190
src/components/ui/select.tsx
Normal file
190
src/components/ui/select.tsx
Normal file
@@ -0,0 +1,190 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
|
||||
import { Select as SelectPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Select({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
||||
return <SelectPrimitive.Root data-slot="select" {...props} />
|
||||
}
|
||||
|
||||
function SelectGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
||||
return <SelectPrimitive.Group data-slot="select-group" {...props} />
|
||||
}
|
||||
|
||||
function SelectValue({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
||||
return <SelectPrimitive.Value data-slot="select-value" {...props} />
|
||||
}
|
||||
|
||||
function SelectTrigger({
|
||||
className,
|
||||
size = "default",
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
|
||||
size?: "sm" | "default"
|
||||
}) {
|
||||
return (
|
||||
<SelectPrimitive.Trigger
|
||||
data-slot="select-trigger"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDownIcon className="size-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectContent({
|
||||
className,
|
||||
children,
|
||||
position = "item-aligned",
|
||||
align = "center",
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
|
||||
return (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
data-slot="select-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
|
||||
position === "popper" &&
|
||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||
className
|
||||
)}
|
||||
position={position}
|
||||
align={align}
|
||||
{...props}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
"p-1",
|
||||
position === "popper" &&
|
||||
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectLabel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
|
||||
return (
|
||||
<SelectPrimitive.Label
|
||||
data-slot="select-label"
|
||||
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
|
||||
return (
|
||||
<SelectPrimitive.Item
|
||||
data-slot="select-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span
|
||||
data-slot="select-item-indicator"
|
||||
className="absolute right-2 flex size-3.5 items-center justify-center"
|
||||
>
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
|
||||
return (
|
||||
<SelectPrimitive.Separator
|
||||
data-slot="select-separator"
|
||||
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectScrollUpButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
data-slot="select-scroll-up-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUpIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectScrollDownButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
data-slot="select-scroll-down-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDownIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectScrollDownButton,
|
||||
SelectScrollUpButton,
|
||||
SelectSeparator,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
}
|
||||
28
src/components/ui/separator.tsx
Normal file
28
src/components/ui/separator.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Separator as SeparatorPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Separator({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
decorative = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
|
||||
return (
|
||||
<SeparatorPrimitive.Root
|
||||
data-slot="separator"
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Separator }
|
||||
143
src/components/ui/sheet.tsx
Normal file
143
src/components/ui/sheet.tsx
Normal file
@@ -0,0 +1,143 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { XIcon } from "lucide-react"
|
||||
import { Dialog as SheetPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
|
||||
return <SheetPrimitive.Root data-slot="sheet" {...props} />
|
||||
}
|
||||
|
||||
function SheetTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
|
||||
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
|
||||
}
|
||||
|
||||
function SheetClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Close>) {
|
||||
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
|
||||
}
|
||||
|
||||
function SheetPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
|
||||
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
|
||||
}
|
||||
|
||||
function SheetOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
|
||||
return (
|
||||
<SheetPrimitive.Overlay
|
||||
data-slot="sheet-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetContent({
|
||||
className,
|
||||
children,
|
||||
side = "right",
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
|
||||
side?: "top" | "right" | "bottom" | "left"
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<SheetPortal>
|
||||
<SheetOverlay />
|
||||
<SheetPrimitive.Content
|
||||
data-slot="sheet-content"
|
||||
className={cn(
|
||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
|
||||
side === "right" &&
|
||||
"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",
|
||||
side === "left" &&
|
||||
"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",
|
||||
side === "top" &&
|
||||
"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",
|
||||
side === "bottom" &&
|
||||
"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
|
||||
<XIcon className="size-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</SheetPrimitive.Close>
|
||||
)}
|
||||
</SheetPrimitive.Content>
|
||||
</SheetPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sheet-header"
|
||||
className={cn("flex flex-col gap-1.5 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sheet-footer"
|
||||
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Title>) {
|
||||
return (
|
||||
<SheetPrimitive.Title
|
||||
data-slot="sheet-title"
|
||||
className={cn("text-foreground font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Description>) {
|
||||
return (
|
||||
<SheetPrimitive.Description
|
||||
data-slot="sheet-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Sheet,
|
||||
SheetTrigger,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetFooter,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
}
|
||||
13
src/components/ui/skeleton.tsx
Normal file
13
src/components/ui/skeleton.tsx
Normal file
@@ -0,0 +1,13 @@
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="skeleton"
|
||||
className={cn("bg-accent animate-pulse rounded-md", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Skeleton }
|
||||
40
src/components/ui/sonner.tsx
Normal file
40
src/components/ui/sonner.tsx
Normal file
@@ -0,0 +1,40 @@
|
||||
"use client"
|
||||
|
||||
import {
|
||||
CircleCheckIcon,
|
||||
InfoIcon,
|
||||
Loader2Icon,
|
||||
OctagonXIcon,
|
||||
TriangleAlertIcon,
|
||||
} from "lucide-react"
|
||||
import { useTheme } from "next-themes"
|
||||
import { Toaster as Sonner, type ToasterProps } from "sonner"
|
||||
|
||||
const Toaster = ({ ...props }: ToasterProps) => {
|
||||
const { theme = "system" } = useTheme()
|
||||
|
||||
return (
|
||||
<Sonner
|
||||
theme={theme as ToasterProps["theme"]}
|
||||
className="toaster group"
|
||||
icons={{
|
||||
success: <CircleCheckIcon className="size-4" />,
|
||||
info: <InfoIcon className="size-4" />,
|
||||
warning: <TriangleAlertIcon className="size-4" />,
|
||||
error: <OctagonXIcon className="size-4" />,
|
||||
loading: <Loader2Icon className="size-4 animate-spin" />,
|
||||
}}
|
||||
style={
|
||||
{
|
||||
"--normal-bg": "var(--popover)",
|
||||
"--normal-text": "var(--popover-foreground)",
|
||||
"--normal-border": "var(--border)",
|
||||
"--border-radius": "var(--radius)",
|
||||
} as React.CSSProperties
|
||||
}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Toaster }
|
||||
35
src/components/ui/switch.tsx
Normal file
35
src/components/ui/switch.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Switch as SwitchPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Switch({
|
||||
className,
|
||||
size = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof SwitchPrimitive.Root> & {
|
||||
size?: "sm" | "default"
|
||||
}) {
|
||||
return (
|
||||
<SwitchPrimitive.Root
|
||||
data-slot="switch"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 group/switch inline-flex shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-[1.15rem] data-[size=default]:w-8 data-[size=sm]:h-3.5 data-[size=sm]:w-6",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<SwitchPrimitive.Thumb
|
||||
data-slot="switch-thumb"
|
||||
className={cn(
|
||||
"bg-background dark:data-[state=unchecked]:bg-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block rounded-full ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0"
|
||||
)}
|
||||
/>
|
||||
</SwitchPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Switch }
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user