mirror of
https://github.com/xCyanGrizzly/DragonsStash.git
synced 2026-05-11 06:11:15 +00:00
added other materials tab
This commit is contained in:
@@ -31,6 +31,7 @@ model User {
|
|||||||
filaments Filament[]
|
filaments Filament[]
|
||||||
resins Resin[]
|
resins Resin[]
|
||||||
paints Paint[]
|
paints Paint[]
|
||||||
|
supplies Supply[]
|
||||||
vendors Vendor[]
|
vendors Vendor[]
|
||||||
locations Location[]
|
locations Location[]
|
||||||
usageLogs UsageLog[]
|
usageLogs UsageLog[]
|
||||||
@@ -92,6 +93,7 @@ model Vendor {
|
|||||||
filaments Filament[]
|
filaments Filament[]
|
||||||
resins Resin[]
|
resins Resin[]
|
||||||
paints Paint[]
|
paints Paint[]
|
||||||
|
supplies Supply[]
|
||||||
|
|
||||||
@@index([userId])
|
@@index([userId])
|
||||||
@@index([archived])
|
@@index([archived])
|
||||||
@@ -110,6 +112,7 @@ model Location {
|
|||||||
filaments Filament[]
|
filaments Filament[]
|
||||||
resins Resin[]
|
resins Resin[]
|
||||||
paints Paint[]
|
paints Paint[]
|
||||||
|
supplies Supply[]
|
||||||
|
|
||||||
@@index([userId])
|
@@index([userId])
|
||||||
@@index([archived])
|
@@index([archived])
|
||||||
@@ -230,6 +233,7 @@ model Tag {
|
|||||||
filaments TagOnFilament[]
|
filaments TagOnFilament[]
|
||||||
resins TagOnResin[]
|
resins TagOnResin[]
|
||||||
paints TagOnPaint[]
|
paints TagOnPaint[]
|
||||||
|
supplies TagOnSupply[]
|
||||||
|
|
||||||
@@unique([name, userId])
|
@@unique([name, userId])
|
||||||
@@index([userId])
|
@@index([userId])
|
||||||
@@ -265,12 +269,57 @@ model TagOnPaint {
|
|||||||
@@id([paintId, tagId])
|
@@id([paintId, tagId])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
model Supply {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
name String @db.VarChar(128)
|
||||||
|
brand String @db.VarChar(64)
|
||||||
|
category String @db.VarChar(32)
|
||||||
|
color String? @db.VarChar(64)
|
||||||
|
colorHex String? @db.VarChar(7)
|
||||||
|
totalAmount Float
|
||||||
|
usedAmount Float @default(0)
|
||||||
|
unit String @db.VarChar(16)
|
||||||
|
purchaseDate DateTime?
|
||||||
|
cost Float?
|
||||||
|
notes String? @db.Text
|
||||||
|
archived Boolean @default(false)
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
userId String
|
||||||
|
vendorId String?
|
||||||
|
locationId String?
|
||||||
|
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
vendor Vendor? @relation(fields: [vendorId], references: [id], onDelete: SetNull)
|
||||||
|
location Location? @relation(fields: [locationId], references: [id], onDelete: SetNull)
|
||||||
|
tags TagOnSupply[]
|
||||||
|
usageLogs UsageLog[]
|
||||||
|
|
||||||
|
@@index([userId])
|
||||||
|
@@index([vendorId])
|
||||||
|
@@index([locationId])
|
||||||
|
@@index([category])
|
||||||
|
@@index([archived])
|
||||||
|
@@index([brand])
|
||||||
|
}
|
||||||
|
|
||||||
|
model TagOnSupply {
|
||||||
|
supplyId String
|
||||||
|
tagId String
|
||||||
|
|
||||||
|
supply Supply @relation(fields: [supplyId], references: [id], onDelete: Cascade)
|
||||||
|
tag Tag @relation(fields: [tagId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@id([supplyId, tagId])
|
||||||
|
}
|
||||||
|
|
||||||
model UsageLog {
|
model UsageLog {
|
||||||
id String @id @default(cuid())
|
id String @id @default(cuid())
|
||||||
itemType String @db.VarChar(16)
|
itemType String @db.VarChar(16)
|
||||||
itemId String
|
itemId String
|
||||||
amount Float
|
amount Float
|
||||||
unit String @db.VarChar(4)
|
unit String @db.VarChar(16)
|
||||||
notes String? @db.Text
|
notes String? @db.Text
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
userId String
|
userId String
|
||||||
@@ -282,6 +331,8 @@ model UsageLog {
|
|||||||
resinId String?
|
resinId String?
|
||||||
paint Paint? @relation(fields: [paintId], references: [id], onDelete: Cascade)
|
paint Paint? @relation(fields: [paintId], references: [id], onDelete: Cascade)
|
||||||
paintId String?
|
paintId String?
|
||||||
|
supply Supply? @relation(fields: [supplyId], references: [id], onDelete: Cascade)
|
||||||
|
supplyId String?
|
||||||
|
|
||||||
@@index([userId])
|
@@index([userId])
|
||||||
@@index([itemType, itemId])
|
@@index([itemType, itemId])
|
||||||
|
|||||||
188
src/app/(app)/supplies/_components/supply-columns.tsx
Normal file
188
src/app/(app)/supplies/_components/supply-columns.tsx
Normal file
@@ -0,0 +1,188 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { type ColumnDef } from "@tanstack/react-table";
|
||||||
|
import { MoreHorizontal, Pencil, Archive, Trash2, Package } 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 SupplyRow {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
brand: string;
|
||||||
|
category: string;
|
||||||
|
color: string | null;
|
||||||
|
colorHex: string | null;
|
||||||
|
totalAmount: number;
|
||||||
|
usedAmount: number;
|
||||||
|
unit: string;
|
||||||
|
cost: number | null;
|
||||||
|
purchaseDate: Date | null;
|
||||||
|
notes: string | null;
|
||||||
|
archived: boolean;
|
||||||
|
vendor: { id: string; name: string } | null;
|
||||||
|
location: { id: string; name: string } | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SupplyColumnsProps {
|
||||||
|
onEdit: (supply: SupplyRow) => void;
|
||||||
|
onArchive: (id: string) => void;
|
||||||
|
onDelete: (id: string) => void;
|
||||||
|
onLogUsage: (supply: SupplyRow) => void;
|
||||||
|
lowStockThreshold: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getSupplyColumns({
|
||||||
|
onEdit,
|
||||||
|
onArchive,
|
||||||
|
onDelete,
|
||||||
|
onLogUsage,
|
||||||
|
lowStockThreshold,
|
||||||
|
}: SupplyColumnsProps): ColumnDef<SupplyRow, unknown>[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
id: "color",
|
||||||
|
header: "",
|
||||||
|
cell: ({ row }) =>
|
||||||
|
row.original.colorHex ? (
|
||||||
|
<ColorSwatch hex={row.original.colorHex} size="sm" />
|
||||||
|
) : null,
|
||||||
|
enableHiding: false,
|
||||||
|
size: 40,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "name",
|
||||||
|
header: ({ column }) => <DataTableColumnHeader column={column} title="Name" />,
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const remaining = row.original.totalAmount - row.original.usedAmount;
|
||||||
|
const status = getStockStatus(
|
||||||
|
remaining,
|
||||||
|
row.original.totalAmount,
|
||||||
|
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">{row.original.brand}</span>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "category",
|
||||||
|
header: ({ column }) => <DataTableColumnHeader column={column} title="Category" />,
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<Badge variant="secondary" className="text-xs">
|
||||||
|
{row.original.category}
|
||||||
|
</Badge>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "remaining",
|
||||||
|
header: ({ column }) => <DataTableColumnHeader column={column} title="Remaining" />,
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const remaining = row.original.totalAmount - row.original.usedAmount;
|
||||||
|
const percent =
|
||||||
|
row.original.totalAmount > 0
|
||||||
|
? (remaining / row.original.totalAmount) * 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)} {row.original.unit}
|
||||||
|
</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)}>
|
||||||
|
<Package 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,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
370
src/app/(app)/supplies/_components/supply-form.tsx
Normal file
370
src/app/(app)/supplies/_components/supply-form.tsx
Normal file
@@ -0,0 +1,370 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useTransition } from "react";
|
||||||
|
import { useForm } from "react-hook-form";
|
||||||
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { supplySchema, type SupplyInput } from "@/schemas/supply.schema";
|
||||||
|
import { SUPPLY_CATEGORIES, SUPPLY_UNITS, SUPPLY_CATEGORY_DEFAULTS } from "@/lib/constants";
|
||||||
|
import { createSupply, updateSupply } 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";
|
||||||
|
|
||||||
|
interface SupplyFormProps {
|
||||||
|
supply?: {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
brand: string;
|
||||||
|
category: string;
|
||||||
|
color: string | null;
|
||||||
|
colorHex: string | null;
|
||||||
|
totalAmount: number;
|
||||||
|
usedAmount: number;
|
||||||
|
unit: string;
|
||||||
|
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 SupplyForm({ supply, vendors, locations, onSuccess }: SupplyFormProps) {
|
||||||
|
const [isPending, startTransition] = useTransition();
|
||||||
|
const isEditing = !!supply;
|
||||||
|
|
||||||
|
const form = useForm<SupplyInput>({
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
resolver: zodResolver(supplySchema) as any,
|
||||||
|
defaultValues: {
|
||||||
|
name: supply?.name ?? "",
|
||||||
|
brand: supply?.brand ?? "",
|
||||||
|
category: (supply?.category as SupplyInput["category"]) ?? "Glitter",
|
||||||
|
color: supply?.color ?? "",
|
||||||
|
colorHex: supply?.colorHex ?? "",
|
||||||
|
totalAmount: supply?.totalAmount ?? SUPPLY_CATEGORY_DEFAULTS["Glitter"].totalAmount,
|
||||||
|
usedAmount: supply?.usedAmount ?? 0,
|
||||||
|
unit: supply?.unit ?? SUPPLY_CATEGORY_DEFAULTS["Glitter"].unit,
|
||||||
|
cost: supply?.cost ?? undefined,
|
||||||
|
purchaseDate: supply?.purchaseDate
|
||||||
|
? new Date(supply.purchaseDate).toISOString().split("T")[0]
|
||||||
|
: "",
|
||||||
|
notes: supply?.notes ?? "",
|
||||||
|
vendorId: supply?.vendorId ?? "",
|
||||||
|
locationId: supply?.locationId ?? "",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// eslint-disable-next-line react-hooks/incompatible-library -- RHF watch is safe here
|
||||||
|
const watchColorHex = form.watch("colorHex");
|
||||||
|
// eslint-disable-next-line react-hooks/incompatible-library
|
||||||
|
const watchUnit = form.watch("unit");
|
||||||
|
|
||||||
|
function onSubmit(values: SupplyInput) {
|
||||||
|
startTransition(async () => {
|
||||||
|
const result = isEditing
|
||||||
|
? await updateSupply(supply!.id, values)
|
||||||
|
: await createSupply(values);
|
||||||
|
|
||||||
|
if (!result.success) {
|
||||||
|
toast.error(result.error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
toast.success(isEditing ? "Supply updated" : "Supply created");
|
||||||
|
form.reset();
|
||||||
|
onSuccess();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Form {...form}>
|
||||||
|
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||||
|
<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>
|
||||||
|
<Input placeholder="Supply 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="category"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Category</FormLabel>
|
||||||
|
<Select
|
||||||
|
onValueChange={(val) => {
|
||||||
|
field.onChange(val);
|
||||||
|
if (!isEditing) {
|
||||||
|
const defaults = SUPPLY_CATEGORY_DEFAULTS[val];
|
||||||
|
if (defaults) {
|
||||||
|
form.setValue("unit", defaults.unit);
|
||||||
|
form.setValue("totalAmount", defaults.totalAmount);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
value={field.value}
|
||||||
|
>
|
||||||
|
<FormControl>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue placeholder="Select category" />
|
||||||
|
</SelectTrigger>
|
||||||
|
</FormControl>
|
||||||
|
<SelectContent>
|
||||||
|
{SUPPLY_CATEGORIES.map((c) => (
|
||||||
|
<SelectItem key={c} value={c}>
|
||||||
|
{c}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="color"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Color (optional)</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input placeholder="e.g. Rose Gold" {...field} />
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="colorHex"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Color Hex (optional)</FormLabel>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<FormControl>
|
||||||
|
<Input placeholder="#000000" {...field} className="flex-1" />
|
||||||
|
</FormControl>
|
||||||
|
<input
|
||||||
|
type="color"
|
||||||
|
value={field.value || "#000000"}
|
||||||
|
onChange={(e) => field.onChange(e.target.value)}
|
||||||
|
className="h-9 w-9 cursor-pointer rounded border border-border bg-transparent p-0.5"
|
||||||
|
/>
|
||||||
|
{watchColorHex && (
|
||||||
|
<ColorSwatch hex={watchColorHex} size="md" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="totalAmount"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Total Amount ({watchUnit || "units"})</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input type="number" step="0.1" min="0" {...field} />
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="usedAmount"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Used ({watchUnit || "units"})</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input type="number" step="0.1" min="0" {...field} />
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="unit"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Unit</FormLabel>
|
||||||
|
<Select onValueChange={field.onChange} value={field.value}>
|
||||||
|
<FormControl>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue placeholder="Select unit" />
|
||||||
|
</SelectTrigger>
|
||||||
|
</FormControl>
|
||||||
|
<SelectContent>
|
||||||
|
{SUPPLY_UNITS.map((u) => (
|
||||||
|
<SelectItem key={u} value={u}>
|
||||||
|
{u}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<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)/supplies/_components/supply-modal.tsx
Normal file
50
src/app/(app)/supplies/_components/supply-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 { SupplyForm } from "./supply-form";
|
||||||
|
|
||||||
|
interface SupplyModalProps {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
supply?: Parameters<typeof SupplyForm>[0]["supply"];
|
||||||
|
vendors: { id: string; name: string }[];
|
||||||
|
locations: { id: string; name: string }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SupplyModal({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
supply,
|
||||||
|
vendors,
|
||||||
|
locations,
|
||||||
|
}: SupplyModalProps) {
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent className="sm:max-w-2xl max-h-[90vh]">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{supply ? "Edit Supply" : "Add Supply"}</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
{supply
|
||||||
|
? "Update the supply details below."
|
||||||
|
: "Add a new supply to your inventory."}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<ScrollArea className="max-h-[70vh] pr-4">
|
||||||
|
<SupplyForm
|
||||||
|
supply={supply}
|
||||||
|
vendors={vendors}
|
||||||
|
locations={locations}
|
||||||
|
onSuccess={() => onOpenChange(false)}
|
||||||
|
/>
|
||||||
|
</ScrollArea>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
214
src/app/(app)/supplies/_components/supply-table.tsx
Normal file
214
src/app/(app)/supplies/_components/supply-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 { SUPPLY_CATEGORIES } from "@/lib/constants";
|
||||||
|
import { getSupplyColumns, type SupplyRow } from "./supply-columns";
|
||||||
|
import { SupplyModal } from "./supply-modal";
|
||||||
|
import { deleteSupply, archiveSupply, logSupplyUsage } 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 SupplyTableProps {
|
||||||
|
data: SupplyRow[];
|
||||||
|
pageCount: number;
|
||||||
|
totalCount: number;
|
||||||
|
vendors: { id: string; name: string }[];
|
||||||
|
locations: { id: string; name: string }[];
|
||||||
|
lowStockThreshold: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SupplyTable({
|
||||||
|
data,
|
||||||
|
pageCount,
|
||||||
|
totalCount,
|
||||||
|
vendors,
|
||||||
|
locations,
|
||||||
|
lowStockThreshold,
|
||||||
|
}: SupplyTableProps) {
|
||||||
|
const router = useRouter();
|
||||||
|
const pathname = usePathname();
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
const [isPending, startTransition] = useTransition();
|
||||||
|
|
||||||
|
const [modalOpen, setModalOpen] = useState(false);
|
||||||
|
const [editSupply, setEditSupply] = useState<SupplyRow | undefined>();
|
||||||
|
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||||
|
const [usageSupply, setUsageSupply] = useState<SupplyRow | null>(null);
|
||||||
|
const [searchValue, setSearchValue] = useState(searchParams.get("search") ?? "");
|
||||||
|
|
||||||
|
const categoryFilter = new Set(searchParams.getAll("category"));
|
||||||
|
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 = getSupplyColumns({
|
||||||
|
onEdit: (supply) => {
|
||||||
|
setEditSupply(supply);
|
||||||
|
setModalOpen(true);
|
||||||
|
},
|
||||||
|
onArchive: (id) => {
|
||||||
|
startTransition(async () => {
|
||||||
|
const result = await archiveSupply(id);
|
||||||
|
if (result.success) toast.success("Supply updated");
|
||||||
|
else toast.error(result.error);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onDelete: (id) => setDeleteId(id),
|
||||||
|
onLogUsage: (supply) => setUsageSupply(supply),
|
||||||
|
lowStockThreshold,
|
||||||
|
});
|
||||||
|
|
||||||
|
const { table } = useDataTable({ data, columns, pageCount });
|
||||||
|
|
||||||
|
const handleDelete = () => {
|
||||||
|
if (!deleteId) return;
|
||||||
|
startTransition(async () => {
|
||||||
|
const result = await deleteSupply(deleteId);
|
||||||
|
if (result.success) {
|
||||||
|
toast.success("Supply deleted");
|
||||||
|
setDeleteId(null);
|
||||||
|
} else {
|
||||||
|
toast.error(result.error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const categoryOptions = SUPPLY_CATEGORIES.map((c) => ({ label: c, value: c }));
|
||||||
|
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="Supplies" description="Manage your dice-making and crafting supplies">
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
setEditSupply(undefined);
|
||||||
|
setModalOpen(true);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Plus className="mr-2 h-4 w-4" />
|
||||||
|
Add Supply
|
||||||
|
</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 supplies..."
|
||||||
|
value={searchValue}
|
||||||
|
onChange={(e) => updateSearch(e.target.value)}
|
||||||
|
className="pl-9 h-9"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<DataTableFacetedFilter
|
||||||
|
title="Category"
|
||||||
|
options={categoryOptions}
|
||||||
|
selectedValues={categoryFilter}
|
||||||
|
onSelectionChange={(values) => updateFilters("category", 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 supplies found. Add your first supply!" />
|
||||||
|
<DataTablePagination table={table} totalCount={totalCount} />
|
||||||
|
|
||||||
|
<SupplyModal
|
||||||
|
open={modalOpen}
|
||||||
|
onOpenChange={(open) => {
|
||||||
|
setModalOpen(open);
|
||||||
|
if (!open) setEditSupply(undefined);
|
||||||
|
}}
|
||||||
|
supply={
|
||||||
|
editSupply
|
||||||
|
? {
|
||||||
|
id: editSupply.id,
|
||||||
|
name: editSupply.name,
|
||||||
|
brand: editSupply.brand,
|
||||||
|
category: editSupply.category,
|
||||||
|
color: editSupply.color,
|
||||||
|
colorHex: editSupply.colorHex,
|
||||||
|
totalAmount: editSupply.totalAmount,
|
||||||
|
usedAmount: editSupply.usedAmount,
|
||||||
|
unit: editSupply.unit,
|
||||||
|
cost: editSupply.cost,
|
||||||
|
purchaseDate: editSupply.purchaseDate,
|
||||||
|
notes: editSupply.notes,
|
||||||
|
vendorId: editSupply.vendor?.id ?? null,
|
||||||
|
locationId: editSupply.location?.id ?? null,
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
vendors={vendors}
|
||||||
|
locations={locations}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<DeleteDialog
|
||||||
|
open={!!deleteId}
|
||||||
|
onOpenChange={(open) => !open && setDeleteId(null)}
|
||||||
|
title="Delete Supply"
|
||||||
|
description="This will permanently delete this supply and all its usage logs."
|
||||||
|
onConfirm={handleDelete}
|
||||||
|
isLoading={isPending}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{usageSupply && (
|
||||||
|
<UsageLogDialog
|
||||||
|
open={!!usageSupply}
|
||||||
|
onOpenChange={(open) => !open && setUsageSupply(null)}
|
||||||
|
itemName={usageSupply.name}
|
||||||
|
unit={usageSupply.unit}
|
||||||
|
onSubmit={async (amount, notes) => {
|
||||||
|
const result = await logSupplyUsage(usageSupply.id, { amount, notes });
|
||||||
|
return result;
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
155
src/app/(app)/supplies/actions.ts
Normal file
155
src/app/(app)/supplies/actions.ts
Normal file
@@ -0,0 +1,155 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
import { supplySchema } from "@/schemas/supply.schema";
|
||||||
|
import { usageLogSchema } from "@/schemas/usage-log.schema";
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import type { ActionResult } from "@/types/api.types";
|
||||||
|
|
||||||
|
export async function createSupply(input: unknown): Promise<ActionResult<{ id: string }>> {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
|
||||||
|
|
||||||
|
const parsed = supplySchema.safeParse(input);
|
||||||
|
if (!parsed.success) return { success: false, error: "Validation failed" };
|
||||||
|
|
||||||
|
try {
|
||||||
|
const supply = await prisma.supply.create({
|
||||||
|
data: {
|
||||||
|
name: parsed.data.name,
|
||||||
|
brand: parsed.data.brand,
|
||||||
|
category: parsed.data.category,
|
||||||
|
color: parsed.data.color || null,
|
||||||
|
colorHex: parsed.data.colorHex || null,
|
||||||
|
totalAmount: parsed.data.totalAmount,
|
||||||
|
usedAmount: parsed.data.usedAmount,
|
||||||
|
unit: parsed.data.unit,
|
||||||
|
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("/supplies");
|
||||||
|
revalidatePath("/dashboard");
|
||||||
|
return { success: true, data: { id: supply.id } };
|
||||||
|
} catch {
|
||||||
|
return { success: false, error: "Failed to create supply" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateSupply(id: string, input: unknown): Promise<ActionResult> {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
|
||||||
|
|
||||||
|
const parsed = supplySchema.safeParse(input);
|
||||||
|
if (!parsed.success) return { success: false, error: "Validation failed" };
|
||||||
|
|
||||||
|
const existing = await prisma.supply.findFirst({ where: { id, userId: session.user.id } });
|
||||||
|
if (!existing) return { success: false, error: "Not found" };
|
||||||
|
|
||||||
|
try {
|
||||||
|
await prisma.supply.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
name: parsed.data.name,
|
||||||
|
brand: parsed.data.brand,
|
||||||
|
category: parsed.data.category,
|
||||||
|
color: parsed.data.color || null,
|
||||||
|
colorHex: parsed.data.colorHex || null,
|
||||||
|
totalAmount: parsed.data.totalAmount,
|
||||||
|
usedAmount: parsed.data.usedAmount,
|
||||||
|
unit: parsed.data.unit,
|
||||||
|
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("/supplies");
|
||||||
|
revalidatePath("/dashboard");
|
||||||
|
return { success: true, data: undefined };
|
||||||
|
} catch {
|
||||||
|
return { success: false, error: "Failed to update supply" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteSupply(id: string): Promise<ActionResult> {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
|
||||||
|
|
||||||
|
const existing = await prisma.supply.findFirst({ where: { id, userId: session.user.id } });
|
||||||
|
if (!existing) return { success: false, error: "Not found" };
|
||||||
|
|
||||||
|
try {
|
||||||
|
await prisma.supply.delete({ where: { id } });
|
||||||
|
revalidatePath("/supplies");
|
||||||
|
revalidatePath("/dashboard");
|
||||||
|
return { success: true, data: undefined };
|
||||||
|
} catch {
|
||||||
|
return { success: false, error: "Failed to delete supply" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function archiveSupply(id: string): Promise<ActionResult> {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
|
||||||
|
|
||||||
|
const existing = await prisma.supply.findFirst({ where: { id, userId: session.user.id } });
|
||||||
|
if (!existing) return { success: false, error: "Not found" };
|
||||||
|
|
||||||
|
try {
|
||||||
|
await prisma.supply.update({
|
||||||
|
where: { id },
|
||||||
|
data: { archived: !existing.archived },
|
||||||
|
});
|
||||||
|
revalidatePath("/supplies");
|
||||||
|
revalidatePath("/dashboard");
|
||||||
|
return { success: true, data: undefined };
|
||||||
|
} catch {
|
||||||
|
return { success: false, error: "Failed to archive supply" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function logSupplyUsage(supplyId: 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.supply.findFirst({ where: { id: supplyId, userId: session.user.id } });
|
||||||
|
if (!existing) return { success: false, error: "Not found" };
|
||||||
|
|
||||||
|
try {
|
||||||
|
await prisma.$transaction([
|
||||||
|
prisma.usageLog.create({
|
||||||
|
data: {
|
||||||
|
itemType: "SUPPLY",
|
||||||
|
itemId: supplyId,
|
||||||
|
supplyId,
|
||||||
|
amount: parsed.data.amount,
|
||||||
|
unit: existing.unit,
|
||||||
|
notes: parsed.data.notes || null,
|
||||||
|
userId: session.user.id,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
prisma.supply.update({
|
||||||
|
where: { id: supplyId },
|
||||||
|
data: { usedAmount: { increment: parsed.data.amount } },
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
revalidatePath("/supplies");
|
||||||
|
revalidatePath("/dashboard");
|
||||||
|
return { success: true, data: undefined };
|
||||||
|
} catch {
|
||||||
|
return { success: false, error: "Failed to log usage" };
|
||||||
|
}
|
||||||
|
}
|
||||||
34
src/app/(app)/supplies/loading.tsx
Normal file
34
src/app/(app)/supplies/loading.tsx
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
|
|
||||||
|
export default function SuppliesLoading() {
|
||||||
|
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)/supplies/page.tsx
Normal file
44
src/app/(app)/supplies/page.tsx
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { getSupplies } from "@/data/supply.queries";
|
||||||
|
import { getVendorOptions } from "@/data/vendor.queries";
|
||||||
|
import { getLocationOptions } from "@/data/location.queries";
|
||||||
|
import { getUserSettings } from "@/data/settings.queries";
|
||||||
|
import { SupplyTable } from "./_components/supply-table";
|
||||||
|
|
||||||
|
interface SuppliesPageProps {
|
||||||
|
searchParams: Promise<Record<string, string | string[] | undefined>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function SuppliesPage({ searchParams }: SuppliesPageProps) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user?.id) redirect("/login");
|
||||||
|
|
||||||
|
const params = await searchParams;
|
||||||
|
const [suppliesResult, vendors, locations, settings] = await Promise.all([
|
||||||
|
getSupplies(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,
|
||||||
|
category: params.category,
|
||||||
|
vendor: params.vendor,
|
||||||
|
location: params.location,
|
||||||
|
}),
|
||||||
|
getVendorOptions(session.user.id),
|
||||||
|
getLocationOptions(session.user.id),
|
||||||
|
getUserSettings(session.user.id),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<SupplyTable
|
||||||
|
data={JSON.parse(JSON.stringify(suppliesResult.data))}
|
||||||
|
pageCount={suppliesResult.pageCount}
|
||||||
|
totalCount={suppliesResult.totalCount}
|
||||||
|
vendors={vendors}
|
||||||
|
locations={locations}
|
||||||
|
lowStockThreshold={settings.lowStockThreshold}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
Cylinder,
|
Cylinder,
|
||||||
Droplets,
|
Droplets,
|
||||||
Paintbrush,
|
Paintbrush,
|
||||||
|
Gem,
|
||||||
Building2,
|
Building2,
|
||||||
MapPin,
|
MapPin,
|
||||||
Settings,
|
Settings,
|
||||||
@@ -25,6 +26,7 @@ const icons = {
|
|||||||
Cylinder,
|
Cylinder,
|
||||||
Droplets,
|
Droplets,
|
||||||
Paintbrush,
|
Paintbrush,
|
||||||
|
Gem,
|
||||||
Building2,
|
Building2,
|
||||||
MapPin,
|
MapPin,
|
||||||
Settings,
|
Settings,
|
||||||
@@ -35,6 +37,7 @@ const navItems = [
|
|||||||
{ label: "Filaments", href: "/filaments", icon: "Cylinder" as const },
|
{ label: "Filaments", href: "/filaments", icon: "Cylinder" as const },
|
||||||
{ label: "Resins", href: "/resins", icon: "Droplets" as const },
|
{ label: "Resins", href: "/resins", icon: "Droplets" as const },
|
||||||
{ label: "Paints", href: "/paints", icon: "Paintbrush" as const },
|
{ label: "Paints", href: "/paints", icon: "Paintbrush" as const },
|
||||||
|
{ label: "Supplies", href: "/supplies", icon: "Gem" as const },
|
||||||
{ label: "Vendors", href: "/vendors", icon: "Building2" as const },
|
{ label: "Vendors", href: "/vendors", icon: "Building2" as const },
|
||||||
{ label: "Locations", href: "/locations", icon: "MapPin" as const },
|
{ label: "Locations", href: "/locations", icon: "MapPin" as const },
|
||||||
{ label: "Settings", href: "/settings", icon: "Settings" as const },
|
{ label: "Settings", href: "/settings", icon: "Settings" as const },
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ interface UsageLogDialogProps {
|
|||||||
open: boolean;
|
open: boolean;
|
||||||
onOpenChange: (open: boolean) => void;
|
onOpenChange: (open: boolean) => void;
|
||||||
itemName: string;
|
itemName: string;
|
||||||
unit: "g" | "ml";
|
unit: string;
|
||||||
onSubmit: (amount: number, notes?: string) => Promise<{ success: boolean; error?: string }>;
|
onSubmit: (amount: number, notes?: string) => Promise<{ success: boolean; error?: string }>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { prisma } from "@/lib/prisma";
|
|||||||
interface LowStockItem {
|
interface LowStockItem {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
type: "filament" | "resin" | "paint";
|
type: "filament" | "resin" | "paint" | "supply";
|
||||||
colorHex: string;
|
colorHex: string;
|
||||||
remaining: number;
|
remaining: number;
|
||||||
total: number;
|
total: number;
|
||||||
@@ -33,7 +33,7 @@ export async function getDashboardStats(
|
|||||||
userId: string,
|
userId: string,
|
||||||
lowStockThreshold: number
|
lowStockThreshold: number
|
||||||
): Promise<DashboardStats> {
|
): Promise<DashboardStats> {
|
||||||
const [filaments, resins, paints, usageLogs24h, recentLogs] = await Promise.all([
|
const [filaments, resins, paints, supplies, usageLogs24h, recentLogs] = await Promise.all([
|
||||||
prisma.filament.findMany({
|
prisma.filament.findMany({
|
||||||
where: { userId, archived: false },
|
where: { userId, archived: false },
|
||||||
select: {
|
select: {
|
||||||
@@ -67,6 +67,17 @@ export async function getDashboardStats(
|
|||||||
cost: true,
|
cost: true,
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
|
prisma.supply.findMany({
|
||||||
|
where: { userId, archived: false },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
colorHex: true,
|
||||||
|
totalAmount: true,
|
||||||
|
usedAmount: true,
|
||||||
|
cost: true,
|
||||||
|
},
|
||||||
|
}),
|
||||||
prisma.usageLog.count({
|
prisma.usageLog.count({
|
||||||
where: {
|
where: {
|
||||||
userId,
|
userId,
|
||||||
@@ -81,16 +92,18 @@ export async function getDashboardStats(
|
|||||||
filament: { select: { name: true } },
|
filament: { select: { name: true } },
|
||||||
resin: { select: { name: true } },
|
resin: { select: { name: true } },
|
||||||
paint: { select: { name: true } },
|
paint: { select: { name: true } },
|
||||||
|
supply: { select: { name: true } },
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const totalItems = filaments.length + resins.length + paints.length;
|
const totalItems = filaments.length + resins.length + paints.length + supplies.length;
|
||||||
|
|
||||||
const inventoryValue =
|
const inventoryValue =
|
||||||
filaments.reduce((sum: number, f: { cost: number | null }) => sum + (f.cost ?? 0), 0) +
|
filaments.reduce((sum: number, f: { cost: number | null }) => sum + (f.cost ?? 0), 0) +
|
||||||
resins.reduce((sum: number, r: { cost: number | null }) => sum + (r.cost ?? 0), 0) +
|
resins.reduce((sum: number, r: { cost: number | null }) => sum + (r.cost ?? 0), 0) +
|
||||||
paints.reduce((sum: number, p: { cost: number | null }) => sum + (p.cost ?? 0), 0);
|
paints.reduce((sum: number, p: { cost: number | null }) => sum + (p.cost ?? 0), 0) +
|
||||||
|
supplies.reduce((sum: number, s: { cost: number | null }) => sum + (s.cost ?? 0), 0);
|
||||||
|
|
||||||
const lowStockItems: LowStockItem[] = [];
|
const lowStockItems: LowStockItem[] = [];
|
||||||
|
|
||||||
@@ -142,6 +155,22 @@ export async function getDashboardStats(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for (const s of supplies) {
|
||||||
|
const remaining = s.totalAmount - s.usedAmount;
|
||||||
|
const percent = s.totalAmount > 0 ? (remaining / s.totalAmount) * 100 : 0;
|
||||||
|
if (percent <= lowStockThreshold && percent > 0) {
|
||||||
|
lowStockItems.push({
|
||||||
|
id: s.id,
|
||||||
|
name: s.name,
|
||||||
|
type: "supply",
|
||||||
|
colorHex: s.colorHex ?? "#6b7280",
|
||||||
|
remaining,
|
||||||
|
total: s.totalAmount,
|
||||||
|
percent,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
lowStockItems.sort((a, b) => a.percent - b.percent);
|
lowStockItems.sort((a, b) => a.percent - b.percent);
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
@@ -153,7 +182,7 @@ export async function getDashboardStats(
|
|||||||
notes: log.notes,
|
notes: log.notes,
|
||||||
createdAt: log.createdAt,
|
createdAt: log.createdAt,
|
||||||
itemName:
|
itemName:
|
||||||
log.filament?.name ?? log.resin?.name ?? log.paint?.name ?? "Unknown",
|
log.filament?.name ?? log.resin?.name ?? log.paint?.name ?? log.supply?.name ?? "Unknown",
|
||||||
}));
|
}));
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
80
src/data/supply.queries.ts
Normal file
80
src/data/supply.queries.ts
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
import { Prisma } from "@prisma/client";
|
||||||
|
import type { DataTableSearchParams } from "@/types/table.types";
|
||||||
|
|
||||||
|
interface SupplySearchParams extends DataTableSearchParams {
|
||||||
|
category?: string | string[];
|
||||||
|
vendor?: string | string[];
|
||||||
|
location?: string | string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getSupplies(userId: string, params: SupplySearchParams) {
|
||||||
|
const page = Number(params.page) || 1;
|
||||||
|
const perPage = Number(params.perPage) || 20;
|
||||||
|
const skip = (page - 1) * perPage;
|
||||||
|
|
||||||
|
const categories = Array.isArray(params.category)
|
||||||
|
? params.category
|
||||||
|
: params.category
|
||||||
|
? [params.category]
|
||||||
|
: [];
|
||||||
|
const vendorIds = Array.isArray(params.vendor)
|
||||||
|
? params.vendor
|
||||||
|
: params.vendor
|
||||||
|
? [params.vendor]
|
||||||
|
: [];
|
||||||
|
const locationIds = Array.isArray(params.location)
|
||||||
|
? params.location
|
||||||
|
: params.location
|
||||||
|
? [params.location]
|
||||||
|
: [];
|
||||||
|
|
||||||
|
const where: Prisma.SupplyWhereInput = {
|
||||||
|
userId,
|
||||||
|
archived: params.archived === "true" ? undefined : false,
|
||||||
|
...(params.search && {
|
||||||
|
OR: [
|
||||||
|
{ name: { contains: params.search, mode: "insensitive" as Prisma.QueryMode } },
|
||||||
|
{ brand: { contains: params.search, mode: "insensitive" as Prisma.QueryMode } },
|
||||||
|
{ color: { contains: params.search, mode: "insensitive" as Prisma.QueryMode } },
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
...(categories.length > 0 && { category: { in: categories } }),
|
||||||
|
...(vendorIds.length > 0 && { vendorId: { in: vendorIds } }),
|
||||||
|
...(locationIds.length > 0 && { locationId: { in: locationIds } }),
|
||||||
|
};
|
||||||
|
|
||||||
|
const sortField = params.sort || "createdAt";
|
||||||
|
const sortOrder = params.order || "desc";
|
||||||
|
|
||||||
|
const [data, totalCount] = await Promise.all([
|
||||||
|
prisma.supply.findMany({
|
||||||
|
where,
|
||||||
|
orderBy: { [sortField]: sortOrder },
|
||||||
|
skip,
|
||||||
|
take: perPage,
|
||||||
|
include: {
|
||||||
|
vendor: { select: { id: true, name: true } },
|
||||||
|
location: { select: { id: true, name: true } },
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
prisma.supply.count({ where }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
data,
|
||||||
|
pageCount: Math.ceil(totalCount / perPage),
|
||||||
|
totalCount,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getSupplyById(id: string, userId: string) {
|
||||||
|
return prisma.supply.findFirst({
|
||||||
|
where: { id, userId },
|
||||||
|
include: {
|
||||||
|
vendor: { select: { id: true, name: true } },
|
||||||
|
location: { select: { id: true, name: true } },
|
||||||
|
tags: { include: { tag: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ export const NAV_ITEMS = [
|
|||||||
{ label: "Filaments", href: "/filaments", icon: "Cylinder" },
|
{ label: "Filaments", href: "/filaments", icon: "Cylinder" },
|
||||||
{ label: "Resins", href: "/resins", icon: "Droplets" },
|
{ label: "Resins", href: "/resins", icon: "Droplets" },
|
||||||
{ label: "Paints", href: "/paints", icon: "Paintbrush" },
|
{ label: "Paints", href: "/paints", icon: "Paintbrush" },
|
||||||
|
{ label: "Supplies", href: "/supplies", icon: "Gem" },
|
||||||
{ label: "Vendors", href: "/vendors", icon: "Building2" },
|
{ label: "Vendors", href: "/vendors", icon: "Building2" },
|
||||||
{ label: "Locations", href: "/locations", icon: "MapPin" },
|
{ label: "Locations", href: "/locations", icon: "MapPin" },
|
||||||
{ label: "Settings", href: "/settings", icon: "Settings" },
|
{ label: "Settings", href: "/settings", icon: "Settings" },
|
||||||
@@ -47,6 +48,32 @@ export const PAINT_FINISHES = [
|
|||||||
"Other",
|
"Other",
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
|
export const SUPPLY_CATEGORIES = [
|
||||||
|
"Glitter",
|
||||||
|
"Alcohol Ink",
|
||||||
|
"Mica Powder",
|
||||||
|
"Pigment",
|
||||||
|
"Silicone",
|
||||||
|
"Resin Additive",
|
||||||
|
"Sanding/Polishing",
|
||||||
|
"Mold",
|
||||||
|
"Other",
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export const SUPPLY_UNITS = ["g", "ml", "sheets", "pieces", "oz"] as const;
|
||||||
|
|
||||||
|
export const SUPPLY_CATEGORY_DEFAULTS: Record<string, { unit: string; totalAmount: number }> = {
|
||||||
|
"Glitter": { unit: "g", totalAmount: 50 },
|
||||||
|
"Alcohol Ink": { unit: "ml", totalAmount: 15 },
|
||||||
|
"Mica Powder": { unit: "g", totalAmount: 25 },
|
||||||
|
"Pigment": { unit: "g", totalAmount: 25 },
|
||||||
|
"Silicone": { unit: "ml", totalAmount: 500 },
|
||||||
|
"Resin Additive": { unit: "ml", totalAmount: 100 },
|
||||||
|
"Sanding/Polishing": { unit: "sheets", totalAmount: 10 },
|
||||||
|
"Mold": { unit: "pieces", totalAmount: 1 },
|
||||||
|
"Other": { unit: "g", totalAmount: 100 },
|
||||||
|
};
|
||||||
|
|
||||||
export const CURRENCIES = ["USD", "EUR", "GBP", "CAD", "AUD", "JPY"] as const;
|
export const CURRENCIES = ["USD", "EUR", "GBP", "CAD", "AUD", "JPY"] as const;
|
||||||
|
|
||||||
export const UNITS = ["metric", "imperial"] as const;
|
export const UNITS = ["metric", "imperial"] as const;
|
||||||
|
|||||||
20
src/schemas/supply.schema.ts
Normal file
20
src/schemas/supply.schema.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import { z } from "zod/v4";
|
||||||
|
import { SUPPLY_CATEGORIES } from "@/lib/constants";
|
||||||
|
|
||||||
|
export const supplySchema = z.object({
|
||||||
|
name: z.string().min(1, "Name is required").max(128),
|
||||||
|
brand: z.string().min(1, "Brand is required").max(64),
|
||||||
|
category: z.enum(SUPPLY_CATEGORIES),
|
||||||
|
color: z.string().max(64).optional().or(z.literal("")),
|
||||||
|
colorHex: z.string().regex(/^#[0-9A-Fa-f]{6}$/, "Invalid hex color").optional().or(z.literal("")),
|
||||||
|
totalAmount: z.coerce.number().positive("Total amount must be positive"),
|
||||||
|
usedAmount: z.coerce.number().min(0).default(0),
|
||||||
|
unit: z.string().min(1, "Unit is required").max(16),
|
||||||
|
vendorId: z.string().optional().or(z.literal("")),
|
||||||
|
locationId: z.string().optional().or(z.literal("")),
|
||||||
|
purchaseDate: z.string().optional().or(z.literal("")),
|
||||||
|
cost: z.coerce.number().min(0).optional(),
|
||||||
|
notes: z.string().max(1024).optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type SupplyInput = z.output<typeof supplySchema>;
|
||||||
Reference in New Issue
Block a user