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:
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}
|
||||
/>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user