feat: implement complete invoicing application with CSV import and PDF export

- Add comprehensive CSV import system with drag-and-drop upload and validation
- Create UniversalTable component with advanced filtering, searching, and batch actions
- Implement invoice management (view, edit, delete) with professional PDF export
- Add client management with full CRUD operations
- Set up authentication with NextAuth.js and email/password login
- Configure database schema with users, clients, invoices, and invoice_items tables
- Build responsive UI with shadcn/ui components and emerald branding
- Add type-safe API layer with tRPC and Zod validation
- Include proper error handling and user feedback with toast notifications
- Set up development environment with Bun, TypeScript, and Tailwind CSS
This commit is contained in:
2025-07-10 04:07:19 -04:00
commit 2d217fab47
85 changed files with 17074 additions and 0 deletions

View File

@@ -0,0 +1,46 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "~/lib/utils"
const badgeVariants = cva(
"inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
secondary:
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
destructive:
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Badge({
className,
variant,
asChild = false,
...props
}: React.ComponentProps<"span"> &
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "span"
return (
<Comp
data-slot="badge"
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
)
}
export { Badge, badgeVariants }

View File

@@ -0,0 +1,109 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { ChevronRight, MoreHorizontal } from "lucide-react"
import { cn } from "~/lib/utils"
function Breadcrumb({ ...props }: React.ComponentProps<"nav">) {
return <nav aria-label="breadcrumb" data-slot="breadcrumb" {...props} />
}
function BreadcrumbList({ className, ...props }: React.ComponentProps<"ol">) {
return (
<ol
data-slot="breadcrumb-list"
className={cn(
"text-muted-foreground flex flex-wrap items-center gap-1.5 text-sm break-words sm:gap-2.5",
className
)}
{...props}
/>
)
}
function BreadcrumbItem({ className, ...props }: React.ComponentProps<"li">) {
return (
<li
data-slot="breadcrumb-item"
className={cn("inline-flex items-center gap-1.5", className)}
{...props}
/>
)
}
function BreadcrumbLink({
asChild,
className,
...props
}: React.ComponentProps<"a"> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot : "a"
return (
<Comp
data-slot="breadcrumb-link"
className={cn("hover:text-foreground transition-colors", className)}
{...props}
/>
)
}
function BreadcrumbPage({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
data-slot="breadcrumb-page"
role="link"
aria-disabled="true"
aria-current="page"
className={cn("text-foreground font-normal", className)}
{...props}
/>
)
}
function BreadcrumbSeparator({
children,
className,
...props
}: React.ComponentProps<"li">) {
return (
<li
data-slot="breadcrumb-separator"
role="presentation"
aria-hidden="true"
className={cn("[&>svg]:size-3.5", className)}
{...props}
>
{children ?? <ChevronRight />}
</li>
)
}
function BreadcrumbEllipsis({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="breadcrumb-ellipsis"
role="presentation"
aria-hidden="true"
className={cn("flex size-9 items-center justify-center", className)}
{...props}
>
<MoreHorizontal className="size-4" />
<span className="sr-only">More</span>
</span>
)
}
export {
Breadcrumb,
BreadcrumbList,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbPage,
BreadcrumbSeparator,
BreadcrumbEllipsis,
}

View File

@@ -0,0 +1,59 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "~/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
{
variants: {
variant: {
default:
"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
destructive:
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Button({
className,
variant,
size,
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Button, buttonVariants }

View File

@@ -0,0 +1,213 @@
"use client"
import * as React from "react"
import {
ChevronDownIcon,
ChevronLeftIcon,
ChevronRightIcon,
} from "lucide-react"
import { DayButton, DayPicker, getDefaultClassNames } from "react-day-picker"
import { cn } from "~/lib/utils"
import { Button, buttonVariants } from "~/components/ui/button"
function Calendar({
className,
classNames,
showOutsideDays = true,
captionLayout = "label",
buttonVariant = "ghost",
formatters,
components,
...props
}: React.ComponentProps<typeof DayPicker> & {
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
}) {
const defaultClassNames = getDefaultClassNames()
return (
<DayPicker
showOutsideDays={showOutsideDays}
className={cn(
"bg-background group/calendar p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
className
)}
captionLayout={captionLayout}
formatters={{
formatMonthDropdown: (date) =>
date.toLocaleString("default", { month: "short" }),
...formatters,
}}
classNames={{
root: cn("w-fit", defaultClassNames.root),
months: cn(
"flex gap-4 flex-col md:flex-row relative",
defaultClassNames.months
),
month: cn("flex flex-col w-full gap-4", defaultClassNames.month),
nav: cn(
"flex items-center gap-1 w-full absolute top-0 inset-x-0 justify-between",
defaultClassNames.nav
),
button_previous: cn(
buttonVariants({ variant: buttonVariant }),
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
defaultClassNames.button_previous
),
button_next: cn(
buttonVariants({ variant: buttonVariant }),
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
defaultClassNames.button_next
),
month_caption: cn(
"flex items-center justify-center h-(--cell-size) w-full px-(--cell-size)",
defaultClassNames.month_caption
),
dropdowns: cn(
"w-full flex items-center text-sm font-medium justify-center h-(--cell-size) gap-1.5",
defaultClassNames.dropdowns
),
dropdown_root: cn(
"relative has-focus:border-ring border border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] rounded-md",
defaultClassNames.dropdown_root
),
dropdown: cn(
"absolute bg-popover inset-0 opacity-0",
defaultClassNames.dropdown
),
caption_label: cn(
"select-none font-medium",
captionLayout === "label"
? "text-sm"
: "rounded-md pl-2 pr-1 flex items-center gap-1 text-sm h-8 [&>svg]:text-muted-foreground [&>svg]:size-3.5",
defaultClassNames.caption_label
),
table: "w-full border-collapse",
weekdays: cn("flex", defaultClassNames.weekdays),
weekday: cn(
"text-muted-foreground rounded-md flex-1 font-normal text-[0.8rem] select-none",
defaultClassNames.weekday
),
week: cn("flex w-full mt-2", defaultClassNames.week),
week_number_header: cn(
"select-none w-(--cell-size)",
defaultClassNames.week_number_header
),
week_number: cn(
"text-[0.8rem] select-none text-muted-foreground",
defaultClassNames.week_number
),
day: cn(
"relative w-full h-full p-0 text-center [&:first-child[data-selected=true]_button]:rounded-l-md [&:last-child[data-selected=true]_button]:rounded-r-md group/day aspect-square select-none",
defaultClassNames.day
),
range_start: cn(
"rounded-l-md bg-accent",
defaultClassNames.range_start
),
range_middle: cn("rounded-none", defaultClassNames.range_middle),
range_end: cn("rounded-r-md bg-accent", defaultClassNames.range_end),
today: cn(
"bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",
defaultClassNames.today
),
outside: cn(
"text-muted-foreground aria-selected:text-muted-foreground",
defaultClassNames.outside
),
disabled: cn(
"text-muted-foreground opacity-50",
defaultClassNames.disabled
),
hidden: cn("invisible", defaultClassNames.hidden),
...classNames,
}}
components={{
Root: ({ className, rootRef, ...props }) => {
return (
<div
data-slot="calendar"
ref={rootRef}
className={cn(className)}
{...props}
/>
)
},
Chevron: ({ className, orientation, ...props }) => {
if (orientation === "left") {
return (
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
)
}
if (orientation === "right") {
return (
<ChevronRightIcon
className={cn("size-4", className)}
{...props}
/>
)
}
return (
<ChevronDownIcon className={cn("size-4", className)} {...props} />
)
},
DayButton: CalendarDayButton,
WeekNumber: ({ children, ...props }) => {
return (
<td {...props}>
<div className="flex size-(--cell-size) items-center justify-center text-center">
{children}
</div>
</td>
)
},
...components,
}}
{...props}
/>
)
}
function CalendarDayButton({
className,
day,
modifiers,
...props
}: React.ComponentProps<typeof DayButton>) {
const defaultClassNames = getDefaultClassNames()
const ref = React.useRef<HTMLButtonElement>(null)
React.useEffect(() => {
if (modifiers.focused) ref.current?.focus()
}, [modifiers.focused])
return (
<Button
ref={ref}
variant="ghost"
size="icon"
data-day={day.date.toLocaleDateString()}
data-selected-single={
modifiers.selected &&
!modifiers.range_start &&
!modifiers.range_end &&
!modifiers.range_middle
}
data-range-start={modifiers.range_start}
data-range-end={modifiers.range_end}
data-range-middle={modifiers.range_middle}
className={cn(
"data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 dark:hover:text-accent-foreground flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md [&>span]:text-xs [&>span]:opacity-70",
defaultClassNames.day,
className
)}
{...props}
/>
)
}
export { Calendar, CalendarDayButton }

View File

@@ -0,0 +1,92 @@
import * as React from "react"
import { cn } from "~/lib/utils"
function Card({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card"
className={cn(
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
className
)}
{...props}
/>
)
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
className
)}
{...props}
/>
)
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn("leading-none font-semibold", className)}
{...props}
/>
)
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
{...props}
/>
)
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-6", className)}
{...props}
/>
)
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
{...props}
/>
)
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
}

View File

@@ -0,0 +1,32 @@
"use client"
import * as React from "react"
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
import { CheckIcon } from "lucide-react"
import { cn } from "~/lib/utils"
function Checkbox({
className,
...props
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
return (
<CheckboxPrimitive.Root
data-slot="checkbox"
className={cn(
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
>
<CheckboxPrimitive.Indicator
data-slot="checkbox-indicator"
className="flex items-center justify-center text-current transition-none"
>
<CheckIcon className="size-3.5" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
)
}
export { Checkbox }

View File

@@ -0,0 +1,77 @@
"use client"
import { format } from "date-fns"
import { Calendar as CalendarIcon } from "lucide-react"
import * as React from "react"
import { Button } from "~/components/ui/button"
import { Calendar } from "~/components/ui/calendar"
import { Label } from "~/components/ui/label"
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "~/components/ui/popover"
import { cn } from "~/lib/utils"
interface DatePickerProps {
date?: Date
onDateChange: (date: Date | undefined) => void
label?: string
placeholder?: string
className?: string
disabled?: boolean
required?: boolean
id?: string
}
export function DatePicker({
date,
onDateChange,
label,
placeholder = "Select date",
className,
disabled = false,
required = false,
id
}: DatePickerProps) {
const [open, setOpen] = React.useState(false)
return (
<div className={cn("flex flex-col gap-2", className)}>
{label && (
<Label htmlFor={id} className="text-sm font-medium text-gray-700">
{label}
{required && <span className="text-red-500 ml-1">*</span>}
</Label>
)}
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
id={id}
disabled={disabled}
className={cn(
"w-full justify-between font-normal h-9 border-gray-200 focus:border-emerald-500 focus:ring-emerald-500 text-sm",
!date && "text-gray-500"
)}
>
{date ? format(date, "PPP") : placeholder}
<CalendarIcon className="h-4 w-4 text-gray-400" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto overflow-hidden p-0" align="start">
<Calendar
mode="single"
selected={date}
captionLayout="dropdown"
onSelect={(selectedDate: Date | undefined) => {
onDateChange(selectedDate)
setOpen(false)
}}
/>
</PopoverContent>
</Popover>
</div>
)
}

View File

@@ -0,0 +1,143 @@
"use client"
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { XIcon } from "lucide-react"
import { cn } from "~/lib/utils"
function Dialog({
...props
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger({
...props
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogPortal({
...props
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
function DialogClose({
...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
)
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean
}) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
>
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
}
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
{...props}
/>
)
}
function DialogTitle({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)}
{...props}
/>
)
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}

View File

@@ -0,0 +1,257 @@
"use client"
import * as React from "react"
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
import { cn } from "~/lib/utils"
function DropdownMenu({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
}
function DropdownMenuPortal({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
return (
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
)
}
function DropdownMenuTrigger({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
return (
<DropdownMenuPrimitive.Trigger
data-slot="dropdown-menu-trigger"
{...props}
/>
)
}
function DropdownMenuContent({
className,
sideOffset = 4,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
return (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
)
}
function DropdownMenuGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
return (
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
)
}
function DropdownMenuItem({
className,
inset,
variant = "default",
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
variant?: "default" | "destructive"
}) {
return (
<DropdownMenuPrimitive.Item
data-slot="dropdown-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function DropdownMenuCheckboxItem({
className,
children,
checked,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
return (
<DropdownMenuPrimitive.CheckboxItem
data-slot="dropdown-menu-checkbox-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
checked={checked}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
)
}
function DropdownMenuRadioGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
return (
<DropdownMenuPrimitive.RadioGroup
data-slot="dropdown-menu-radio-group"
{...props}
/>
)
}
function DropdownMenuRadioItem({
className,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
return (
<DropdownMenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
)
}
function DropdownMenuLabel({
className,
inset,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.Label
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn(
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
className
)}
{...props}
/>
)
}
function DropdownMenuSeparator({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
return (
<DropdownMenuPrimitive.Separator
data-slot="dropdown-menu-separator"
className={cn("bg-border -mx-1 my-1 h-px", className)}
{...props}
/>
)
}
function DropdownMenuShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className
)}
{...props}
/>
)
}
function DropdownMenuSub({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
}
function DropdownMenuSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.SubTrigger
data-slot="dropdown-menu-sub-trigger"
data-inset={inset}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8",
className
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto size-4" />
</DropdownMenuPrimitive.SubTrigger>
)
}
function DropdownMenuSubContent({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
return (
<DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
className
)}
{...props}
/>
)
}
export {
DropdownMenu,
DropdownMenuPortal,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
}

View File

@@ -0,0 +1,223 @@
"use client";
import * as React from "react";
import { useCallback } from "react";
import { useDropzone } from "react-dropzone";
import { cn } from "~/lib/utils";
import { Upload, FileText, X, CheckCircle, AlertCircle } from "lucide-react";
import { Button } from "./button";
interface FileUploadProps {
onFilesSelected: (files: File[]) => void;
accept?: Record<string, string[]>;
maxFiles?: number;
maxSize?: number;
className?: string;
disabled?: boolean;
placeholder?: string;
description?: string;
}
interface FilePreviewProps {
file: File;
onRemove: () => void;
status?: "success" | "error" | "pending";
error?: string;
}
function FilePreview({ file, onRemove, status = "pending", error }: FilePreviewProps) {
const getStatusIcon = () => {
switch (status) {
case "success":
return <CheckCircle className="h-4 w-4 text-green-600" />;
case "error":
return <AlertCircle className="h-4 w-4 text-red-600" />;
default:
return <FileText className="h-4 w-4 text-gray-400" />;
}
};
const getStatusColor = () => {
switch (status) {
case "success":
return "border-green-200 bg-green-50";
case "error":
return "border-red-200 bg-red-50";
default:
return "border-gray-200 bg-gray-50";
}
};
return (
<div className={cn(
"flex items-center justify-between p-3 rounded-lg border",
getStatusColor()
)}>
<div className="flex items-center gap-3">
{getStatusIcon()}
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-gray-900 truncate">{file.name}</p>
<p className="text-xs text-gray-500">
{(file.size / 1024 / 1024).toFixed(2)} MB
</p>
{error && (
<p className="text-xs text-red-600 mt-1">{error}</p>
)}
</div>
</div>
<Button
variant="ghost"
size="sm"
onClick={onRemove}
className="h-6 w-6 p-0 text-gray-400 hover:text-gray-600"
>
<X className="h-3 w-3" />
</Button>
</div>
);
}
export function FileUpload({
onFilesSelected,
accept,
maxFiles = 10,
maxSize = 10 * 1024 * 1024, // 10MB default
className,
disabled = false,
placeholder = "Drag & drop files here, or click to select",
description
}: FileUploadProps) {
const [files, setFiles] = React.useState<File[]>([]);
const [errors, setErrors] = React.useState<Record<string, string>>({});
const onDrop = useCallback((acceptedFiles: File[], rejectedFiles: any[]) => {
// Handle accepted files
const newFiles = [...files, ...acceptedFiles];
setFiles(newFiles);
onFilesSelected(newFiles);
// Handle rejected files
const newErrors: Record<string, string> = { ...errors };
rejectedFiles.forEach(({ file, errors }) => {
const errorMessage = errors.map((e: any) => {
if (e.code === 'file-too-large') {
return `File is too large. Max size is ${(maxSize / 1024 / 1024).toFixed(1)}MB`;
}
if (e.code === 'file-invalid-type') {
return 'File type not supported';
}
if (e.code === 'too-many-files') {
return `Too many files. Max is ${maxFiles}`;
}
return e.message;
}).join(', ');
newErrors[file.name] = errorMessage;
});
setErrors(newErrors);
}, [files, onFilesSelected, errors, maxFiles, maxSize]);
const removeFile = (fileToRemove: File) => {
const newFiles = files.filter(file => file !== fileToRemove);
setFiles(newFiles);
onFilesSelected(newFiles);
const newErrors = { ...errors };
delete newErrors[fileToRemove.name];
setErrors(newErrors);
};
const { getRootProps, getInputProps, isDragActive, isDragReject } = useDropzone({
onDrop,
accept,
maxFiles,
maxSize,
disabled
});
return (
<div className={cn("space-y-4", className)}>
<div
{...getRootProps()}
className={cn(
"border-2 border-dashed rounded-lg p-8 text-center transition-colors cursor-pointer",
"hover:border-emerald-400 hover:bg-emerald-50/50",
isDragActive && "border-emerald-400 bg-emerald-50/50",
isDragReject && "border-red-400 bg-red-50/50",
disabled && "opacity-50 cursor-not-allowed",
"bg-white/80 backdrop-blur-sm"
)}
>
<input {...getInputProps()} />
<div className="flex flex-col items-center gap-4">
<div className={cn(
"p-3 rounded-full transition-colors",
isDragActive ? "bg-emerald-100" : "bg-gray-100",
isDragReject && "bg-red-100"
)}>
<Upload className={cn(
"h-6 w-6 transition-colors",
isDragActive ? "text-emerald-600" : "text-gray-400",
isDragReject && "text-red-600"
)} />
</div>
<div className="space-y-2">
<p className={cn(
"text-lg font-medium transition-colors",
isDragActive ? "text-emerald-600" : "text-gray-900",
isDragReject && "text-red-600"
)}>
{isDragActive
? isDragReject
? "File type not supported"
: "Drop files here"
: placeholder
}
</p>
{description && (
<p className="text-sm text-gray-500">{description}</p>
)}
<p className="text-xs text-gray-400">
Max {maxFiles} file{maxFiles !== 1 ? 's' : ''} {(maxSize / 1024 / 1024).toFixed(1)}MB each
</p>
</div>
</div>
</div>
{/* File List */}
{files.length > 0 && (
<div className="space-y-2">
<h4 className="text-sm font-medium text-gray-700">Selected Files</h4>
<div className="space-y-2 max-h-60 overflow-y-auto">
{files.map((file, index) => (
<FilePreview
key={`${file.name}-${index}`}
file={file}
onRemove={() => removeFile(file)}
status={errors[file.name] ? "error" : "success"}
error={errors[file.name]}
/>
))}
</div>
</div>
)}
{/* Error Summary */}
{Object.keys(errors).length > 0 && (
<div className="p-3 bg-red-50 border border-red-200 rounded-lg">
<div className="flex items-center gap-2 mb-2">
<AlertCircle className="h-4 w-4 text-red-600" />
<span className="text-sm font-medium text-red-800">Upload Errors</span>
</div>
<ul className="text-sm text-red-700 space-y-1">
{Object.entries(errors).map(([fileName, error]) => (
<li key={fileName} className="flex items-start gap-2">
<span className="text-red-600"></span>
<span><strong>{fileName}:</strong> {error}</span>
</li>
))}
</ul>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,21 @@
import * as React from "react"
import { cn } from "~/lib/utils"
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
data-slot="input"
className={cn(
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
className
)}
{...props}
/>
)
}
export { Input }

View File

@@ -0,0 +1,24 @@
"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cn } from "~/lib/utils"
function Label({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
)}
{...props}
/>
)
}
export { Label }

View File

@@ -0,0 +1,168 @@
import * as React from "react"
import * as NavigationMenuPrimitive from "@radix-ui/react-navigation-menu"
import { cva } from "class-variance-authority"
import { ChevronDownIcon } from "lucide-react"
import { cn } from "~/lib/utils"
function NavigationMenu({
className,
children,
viewport = true,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Root> & {
viewport?: boolean
}) {
return (
<NavigationMenuPrimitive.Root
data-slot="navigation-menu"
data-viewport={viewport}
className={cn(
"group/navigation-menu relative flex max-w-max flex-1 items-center justify-center",
className
)}
{...props}
>
{children}
{viewport && <NavigationMenuViewport />}
</NavigationMenuPrimitive.Root>
)
}
function NavigationMenuList({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.List>) {
return (
<NavigationMenuPrimitive.List
data-slot="navigation-menu-list"
className={cn(
"group flex flex-1 list-none items-center justify-center gap-1",
className
)}
{...props}
/>
)
}
function NavigationMenuItem({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Item>) {
return (
<NavigationMenuPrimitive.Item
data-slot="navigation-menu-item"
className={cn("relative", className)}
{...props}
/>
)
}
const navigationMenuTriggerStyle = cva(
"group inline-flex h-9 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=open]:hover:bg-accent data-[state=open]:text-accent-foreground data-[state=open]:focus:bg-accent data-[state=open]:bg-accent/50 focus-visible:ring-ring/50 outline-none transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1"
)
function NavigationMenuTrigger({
className,
children,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Trigger>) {
return (
<NavigationMenuPrimitive.Trigger
data-slot="navigation-menu-trigger"
className={cn(navigationMenuTriggerStyle(), "group", className)}
{...props}
>
{children}{" "}
<ChevronDownIcon
className="relative top-[1px] ml-1 size-3 transition duration-300 group-data-[state=open]:rotate-180"
aria-hidden="true"
/>
</NavigationMenuPrimitive.Trigger>
)
}
function NavigationMenuContent({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Content>) {
return (
<NavigationMenuPrimitive.Content
data-slot="navigation-menu-content"
className={cn(
"data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 top-0 left-0 w-full p-2 pr-2.5 md:absolute md:w-auto",
"group-data-[viewport=false]/navigation-menu:bg-popover group-data-[viewport=false]/navigation-menu:text-popover-foreground group-data-[viewport=false]/navigation-menu:data-[state=open]:animate-in group-data-[viewport=false]/navigation-menu:data-[state=closed]:animate-out group-data-[viewport=false]/navigation-menu:data-[state=closed]:zoom-out-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:zoom-in-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:fade-in-0 group-data-[viewport=false]/navigation-menu:data-[state=closed]:fade-out-0 group-data-[viewport=false]/navigation-menu:top-full group-data-[viewport=false]/navigation-menu:mt-1.5 group-data-[viewport=false]/navigation-menu:overflow-hidden group-data-[viewport=false]/navigation-menu:rounded-md group-data-[viewport=false]/navigation-menu:border group-data-[viewport=false]/navigation-menu:shadow group-data-[viewport=false]/navigation-menu:duration-200 **:data-[slot=navigation-menu-link]:focus:ring-0 **:data-[slot=navigation-menu-link]:focus:outline-none",
className
)}
{...props}
/>
)
}
function NavigationMenuViewport({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Viewport>) {
return (
<div
className={cn(
"absolute top-full left-0 isolate z-50 flex justify-center"
)}
>
<NavigationMenuPrimitive.Viewport
data-slot="navigation-menu-viewport"
className={cn(
"origin-top-center bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border shadow md:w-[var(--radix-navigation-menu-viewport-width)]",
className
)}
{...props}
/>
</div>
)
}
function NavigationMenuLink({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Link>) {
return (
<NavigationMenuPrimitive.Link
data-slot="navigation-menu-link"
className={cn(
"data-[active=true]:focus:bg-accent data-[active=true]:hover:bg-accent data-[active=true]:bg-accent/50 data-[active=true]:text-accent-foreground hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus-visible:ring-ring/50 [&_svg:not([class*='text-'])]:text-muted-foreground flex flex-col gap-1 rounded-sm p-2 text-sm transition-all outline-none focus-visible:ring-[3px] focus-visible:outline-1 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function NavigationMenuIndicator({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Indicator>) {
return (
<NavigationMenuPrimitive.Indicator
data-slot="navigation-menu-indicator"
className={cn(
"data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden",
className
)}
{...props}
>
<div className="bg-border relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm shadow-md" />
</NavigationMenuPrimitive.Indicator>
)
}
export {
NavigationMenu,
NavigationMenuList,
NavigationMenuItem,
NavigationMenuContent,
NavigationMenuTrigger,
NavigationMenuLink,
NavigationMenuIndicator,
NavigationMenuViewport,
navigationMenuTriggerStyle,
}

View File

@@ -0,0 +1,48 @@
"use client"
import * as React from "react"
import * as PopoverPrimitive from "@radix-ui/react-popover"
import { cn } from "~/lib/utils"
function Popover({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />
}
function PopoverTrigger({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
}
function PopoverContent({
className,
align = "center",
sideOffset = 4,
...props
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
data-slot="popover-content"
align={align}
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
)
}
function PopoverAnchor({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
}
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }

View File

@@ -0,0 +1,31 @@
"use client"
import * as React from "react"
import * as ProgressPrimitive from "@radix-ui/react-progress"
import { cn } from "~/lib/utils"
function Progress({
className,
value,
...props
}: React.ComponentProps<typeof ProgressPrimitive.Root>) {
return (
<ProgressPrimitive.Root
data-slot="progress"
className={cn(
"bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",
className
)}
{...props}
>
<ProgressPrimitive.Indicator
data-slot="progress-indicator"
className="bg-primary h-full w-full flex-1 transition-all"
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
/>
</ProgressPrimitive.Root>
)
}
export { Progress }

139
src/components/ui/sheet.tsx Normal file
View File

@@ -0,0 +1,139 @@
"use client"
import * as React from "react"
import * as SheetPrimitive from "@radix-ui/react-dialog"
import { XIcon } from "lucide-react"
import { cn } from "~/lib/utils"
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
return <SheetPrimitive.Root data-slot="sheet" {...props} />
}
function SheetTrigger({
...props
}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
}
function SheetClose({
...props
}: React.ComponentProps<typeof SheetPrimitive.Close>) {
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
}
function SheetPortal({
...props
}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
}
function SheetOverlay({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
return (
<SheetPrimitive.Overlay
data-slot="sheet-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
)
}
function SheetContent({
className,
children,
side = "right",
...props
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
side?: "top" | "right" | "bottom" | "left"
}) {
return (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content
data-slot="sheet-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
side === "right" &&
"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",
side === "left" &&
"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",
side === "top" &&
"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",
side === "bottom" &&
"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",
className
)}
{...props}
>
{children}
<SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
<XIcon className="size-4" />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
</SheetPrimitive.Content>
</SheetPortal>
)
}
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-header"
className={cn("flex flex-col gap-1.5 p-4", className)}
{...props}
/>
)
}
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-footer"
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
{...props}
/>
)
}
function SheetTitle({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Title>) {
return (
<SheetPrimitive.Title
data-slot="sheet-title"
className={cn("text-foreground font-semibold", className)}
{...props}
/>
)
}
function SheetDescription({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Description>) {
return (
<SheetPrimitive.Description
data-slot="sheet-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
export {
Sheet,
SheetTrigger,
SheetClose,
SheetContent,
SheetHeader,
SheetFooter,
SheetTitle,
SheetDescription,
}

View File

@@ -0,0 +1,13 @@
import { cn } from "~/lib/utils"
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="skeleton"
className={cn("bg-accent animate-pulse rounded-md", className)}
{...props}
/>
)
}
export { Skeleton }

116
src/components/ui/table.tsx Normal file
View File

@@ -0,0 +1,116 @@
"use client"
import * as React from "react"
import { cn } from "~/lib/utils"
function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
<div
data-slot="table-container"
className="relative w-full overflow-x-auto"
>
<table
data-slot="table"
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
)
}
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return (
<thead
data-slot="table-header"
className={cn("[&_tr]:border-b", className)}
{...props}
/>
)
}
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
return (
<tbody
data-slot="table-body"
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
)
}
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
return (
<tfoot
data-slot="table-footer"
className={cn(
"bg-muted/50 border-t font-medium [&>tr]:last:border-b-0",
className
)}
{...props}
/>
)
}
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
return (
<tr
data-slot="table-row"
className={cn(
"hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
className
)}
{...props}
/>
)
}
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
return (
<th
data-slot="table-head"
className={cn(
"text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
)
}
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
return (
<td
data-slot="table-cell"
className={cn(
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
)
}
function TableCaption({
className,
...props
}: React.ComponentProps<"caption">) {
return (
<caption
data-slot="table-caption"
className={cn("text-muted-foreground mt-4 text-sm", className)}
{...props}
/>
)
}
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}

View File

@@ -0,0 +1,66 @@
"use client"
import * as React from "react"
import * as TabsPrimitive from "@radix-ui/react-tabs"
import { cn } from "~/lib/utils"
function Tabs({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
return (
<TabsPrimitive.Root
data-slot="tabs"
className={cn("flex flex-col gap-2", className)}
{...props}
/>
)
}
function TabsList({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.List>) {
return (
<TabsPrimitive.List
data-slot="tabs-list"
className={cn(
"bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",
className
)}
{...props}
/>
)
}
function TabsTrigger({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
return (
<TabsPrimitive.Trigger
data-slot="tabs-trigger"
className={cn(
"data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function TabsContent({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Content>) {
return (
<TabsPrimitive.Content
data-slot="tabs-content"
className={cn("flex-1 outline-none", className)}
{...props}
/>
)
}
export { Tabs, TabsList, TabsTrigger, TabsContent }

View File

@@ -0,0 +1,18 @@
import * as React from "react"
import { cn } from "~/lib/utils"
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
return (
<textarea
data-slot="textarea"
className={cn(
"border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className
)}
{...props}
/>
)
}
export { Textarea }

View File

@@ -0,0 +1,8 @@
// Copied from shadcn/ui documentation
import * as React from "react"
import { Toaster as Sonner } from "sonner"
export function Toaster() {
return <Sonner richColors position="top-center" />
}

View File

@@ -0,0 +1,839 @@
"use client";
import { ChevronDown, Download, FileText, Filter, LayoutGrid, List, Plus, Search, Trash2, UserPlus, Pencil } from "lucide-react";
import Link from "next/link";
import * as React from "react";
import { toast } from "sonner";
import { Button } from "~/components/ui/button";
import { Checkbox } from "~/components/ui/checkbox";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "~/components/ui/dialog";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "~/components/ui/dropdown-menu";
import { Input } from "~/components/ui/input";
import { Skeleton } from "~/components/ui/skeleton";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "~/components/ui/table";
import { generateInvoicePDF } from "~/lib/pdf-export";
import { api } from "~/trpc/react";
interface UniversalTableProps {
resource: "clients" | "invoices";
}
interface Client {
id: string;
name: string;
email: string | null;
phone: string | null;
addressLine1: string | null;
addressLine2: string | null;
city: string | null;
state: string | null;
postalCode: string | null;
country: string | null;
createdById: string;
createdAt: Date;
updatedAt: Date | null;
}
interface Invoice {
id: string;
invoiceNumber: string;
clientId: string;
client?: Client;
issueDate: Date;
dueDate: Date;
status: "draft" | "sent" | "paid" | "overdue";
totalAmount: number;
notes: string | null;
createdById: string;
createdAt: Date;
updatedAt: Date | null;
}
const statusColors = {
draft: "bg-gray-100 text-gray-800",
sent: "bg-blue-100 text-blue-800",
paid: "bg-green-100 text-green-800",
overdue: "bg-red-100 text-red-800",
} as const;
const statusLabels = {
draft: "Draft",
sent: "Sent",
paid: "Paid",
overdue: "Overdue",
} as const;
export function UniversalTable({ resource }: UniversalTableProps) {
const [view, setView] = React.useState<"table" | "grid">("table");
const [search, setSearch] = React.useState("");
const [selected, setSelected] = React.useState<string[]>([]);
const [deleteDialogOpen, setDeleteDialogOpen] = React.useState(false);
const [itemToDelete, setItemToDelete] = React.useState<string | null>(null);
const [sortField, setSortField] = React.useState<string>("");
const [sortDirection, setSortDirection] = React.useState<"asc" | "desc">("desc");
const [currentPage, setCurrentPage] = React.useState(1);
const [itemsPerPage, setItemsPerPage] = React.useState(10);
const [statusFilter, setStatusFilter] = React.useState<string>("all");
const [batchStatusDialogOpen, setBatchStatusDialogOpen] = React.useState(false);
const [exportingPDF, setExportingPDF] = React.useState<string | null>(null);
// Fetch real data for clients or invoices
const { data, isLoading, refetch } = resource === "clients"
? api.clients.getAll.useQuery()
: api.invoices.getAll.useQuery();
const deleteClient = api.clients.delete.useMutation({
onSuccess: () => {
toast.success("Client deleted successfully");
setDeleteDialogOpen(false);
setItemToDelete(null);
setSelected([]);
void refetch();
},
onError: (error) => {
toast.error(error.message ?? "Failed to delete client");
},
});
const deleteInvoice = api.invoices.delete.useMutation({
onSuccess: () => {
toast.success("Invoice deleted successfully");
setDeleteDialogOpen(false);
setItemToDelete(null);
setSelected([]);
void refetch();
},
onError: (error) => {
toast.error(error.message ?? "Failed to delete invoice");
},
});
const updateInvoiceStatus = api.invoices.updateStatus.useMutation({
onSuccess: () => {
toast.success("Status updated successfully");
setBatchStatusDialogOpen(false);
setSelected([]);
void refetch();
},
onError: (error) => {
toast.error(error.message ?? "Failed to update status");
},
});
const handleDelete = (id: string) => {
setItemToDelete(id);
setDeleteDialogOpen(true);
};
const confirmDelete = () => {
if (itemToDelete && itemToDelete !== "batch") {
if (resource === "clients") {
deleteClient.mutate({ id: itemToDelete });
} else if (resource === "invoices") {
deleteInvoice.mutate({ id: itemToDelete });
}
}
};
const handleBatchDelete = () => {
if (selected.length > 0) {
setItemToDelete("batch");
setDeleteDialogOpen(true);
}
};
const handleBatchStatusUpdate = (newStatus: "draft" | "sent" | "paid" | "overdue") => {
if (selected.length > 0 && resource === "invoices") {
Promise.all(selected.map(id => updateInvoiceStatus.mutateAsync({ id, status: newStatus })))
.then(() => {
toast.success(`Updated ${selected.length} invoice${selected.length > 1 ? 's' : ''} to ${newStatus}`);
setBatchStatusDialogOpen(false);
setSelected([]);
void refetch();
})
.catch((error) => {
toast.error("Failed to update some invoices");
});
}
};
const handlePDFExport = async (invoice: Invoice) => {
setExportingPDF(invoice.id);
try {
await generateInvoicePDF(invoice);
toast.success("PDF exported successfully");
} catch (error) {
console.error("PDF export error:", error);
toast.error("Failed to export PDF. Please try again.");
} finally {
setExportingPDF(null);
}
};
const confirmBatchDelete = async () => {
if (selected.length > 0) {
try {
if (resource === "clients") {
await Promise.all(selected.map(id => deleteClient.mutateAsync({ id })));
toast.success("Selected clients deleted successfully");
} else if (resource === "invoices") {
await Promise.all(selected.map(id => deleteInvoice.mutateAsync({ id })));
toast.success("Selected invoices deleted successfully");
}
setDeleteDialogOpen(false);
setItemToDelete(null);
setSelected([]);
void refetch();
} catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : `Failed to delete selected ${resource}`;
toast.error(errorMessage);
}
}
};
// Filter and sort data
const filteredAndSortedData = React.useMemo(() => {
if (!data) return [];
let filtered: (Client | Invoice)[] = data as (Client | Invoice)[];
// Filter by search across all columns
if (search) {
const searchLower = search.toLowerCase();
if (resource === "clients") {
filtered = (data as Client[]).filter((row) =>
(row.name?.toLowerCase().includes(searchLower) ?? false) ||
(row.email?.toLowerCase().includes(searchLower) ?? false) ||
(row.phone?.toLowerCase().includes(searchLower) ?? false) ||
(row.addressLine1?.toLowerCase().includes(searchLower) ?? false) ||
(row.city?.toLowerCase().includes(searchLower) ?? false) ||
(row.state?.toLowerCase().includes(searchLower) ?? false)
);
} else if (resource === "invoices") {
filtered = (data as Invoice[]).filter((row) =>
(row.invoiceNumber?.toLowerCase().includes(searchLower) ?? false) ||
(row.client?.name?.toLowerCase().includes(searchLower) ?? false) ||
(row.client?.email?.toLowerCase().includes(searchLower) ?? false) ||
(row.status?.toLowerCase().includes(searchLower) ?? false) ||
(row.totalAmount?.toString().includes(searchLower) ?? false) ||
(row.notes?.toLowerCase().includes(searchLower) ?? false)
);
}
}
// Filter by status
if (statusFilter !== "all" && resource === "invoices") {
filtered = filtered.filter((row) => (row as Invoice).status === statusFilter);
}
// Sort data
if (sortField) {
filtered = [...filtered].sort((a, b) => {
let aValue: unknown = (a as unknown as Record<string, unknown>)[sortField];
let bValue: unknown = (b as unknown as Record<string, unknown>)[sortField];
// Handle nested properties (e.g., client.name)
if (sortField === "client.name") {
aValue = (a as Invoice).client?.name;
bValue = (b as Invoice).client?.name;
}
// Handle date fields
if (sortField === "issueDate" || sortField === "dueDate" || sortField === "createdAt") {
aValue = new Date(aValue as string | number | Date).getTime();
bValue = new Date(bValue as string | number | Date).getTime();
}
// Handle numeric fields
if (sortField === "totalAmount") {
aValue = parseFloat(String(aValue)) || 0;
bValue = parseFloat(String(bValue)) || 0;
}
// Type-safe comparison
const aNum = typeof aValue === 'number' ? aValue : 0;
const bNum = typeof bValue === 'number' ? bValue : 0;
if (aNum < bNum) return sortDirection === "asc" ? -1 : 1;
if (aNum > bNum) return sortDirection === "asc" ? 1 : -1;
return 0;
});
} else {
// Default sort by date (newest first for invoices, name for clients)
if (resource === "invoices") {
filtered = [...filtered].sort((a, b) => {
const aDate = new Date((a as Invoice).issueDate ?? (a as Invoice).createdAt).getTime();
const bDate = new Date((b as Invoice).issueDate ?? (b as Invoice).createdAt).getTime();
return bDate - aDate; // Newest first
});
} else if (resource === "clients") {
filtered = [...filtered].sort((a, b) => {
return ((a as Client).name ?? "").localeCompare((b as Client).name ?? "");
});
}
}
return filtered;
}, [data, search, resource, sortField, sortDirection, statusFilter]);
// Pagination logic
const totalPages = Math.ceil(filteredAndSortedData.length / itemsPerPage);
const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = startIndex + itemsPerPage;
const paginatedData = filteredAndSortedData.slice(startIndex, endIndex);
// Reset to first page when search or filters change
React.useEffect(() => {
setCurrentPage(1);
}, [search, sortField, sortDirection, statusFilter]);
const allSelected = selected.length === (paginatedData?.length ?? 0) && (paginatedData?.length ?? 0) > 0;
const toggleAll = () => setSelected(allSelected ? [] : (paginatedData ?? []).map((d) => d.id));
const toggleOne = (id: string) => setSelected((sel) => sel.includes(id) ? sel.filter((x) => x !== id) : [...sel, id]);
const handleSort = (field: string) => {
if (sortField === field) {
setSortDirection(sortDirection === "asc" ? "desc" : "asc");
} else {
setSortField(field);
setSortDirection("asc");
}
};
const formatCurrency = (amount: number) => {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
}).format(amount);
};
const formatDate = (date: Date) => {
return new Date(date).toLocaleDateString();
};
const renderTableHeaders = () => {
if (resource === "clients") {
return (
<>
<TableHead className="w-12 py-4 px-4">
<Checkbox
checked={allSelected}
onCheckedChange={toggleAll}
aria-label="Select all"
className="data-[state=checked]:bg-emerald-600 data-[state=checked]:border-emerald-600"
/>
</TableHead>
<TableHead
className="py-4 px-4 font-semibold text-gray-700 text-base cursor-pointer hover:bg-gray-50"
onClick={() => handleSort("name")}
>
<div className="flex items-center gap-1">
Name
{sortField === "name" && (
<ChevronDown className={`h-3 w-3 transition-transform ${sortDirection === "asc" ? "rotate-180" : ""}`} />
)}
</div>
</TableHead>
<TableHead className="py-4 px-4 font-semibold text-gray-700 text-base">Email</TableHead>
<TableHead className="py-4 px-4 font-semibold text-gray-700 text-base">Phone</TableHead>
<TableHead className="w-8 py-4 px-4"></TableHead>
</>
);
} else if (resource === "invoices") {
return (
<>
<TableHead className="w-12 py-4 px-4">
<Checkbox
checked={allSelected}
onCheckedChange={toggleAll}
aria-label="Select all"
className="data-[state=checked]:bg-emerald-600 data-[state=checked]:border-emerald-600"
/>
</TableHead>
<TableHead
className="py-4 px-4 font-semibold text-gray-700 text-base cursor-pointer hover:bg-gray-50"
onClick={() => handleSort("invoiceNumber")}
>
<div className="flex items-center gap-1">
Invoice #
{sortField === "invoiceNumber" && (
<ChevronDown className={`h-3 w-3 transition-transform ${sortDirection === "asc" ? "rotate-180" : ""}`} />
)}
</div>
</TableHead>
<TableHead
className="py-4 px-4 font-semibold text-gray-700 text-base cursor-pointer hover:bg-gray-50"
onClick={() => handleSort("client.name")}
>
<div className="flex items-center gap-1">
Client
{sortField === "client.name" && (
<ChevronDown className={`h-3 w-3 transition-transform ${sortDirection === "asc" ? "rotate-180" : ""}`} />
)}
</div>
</TableHead>
<TableHead
className="py-4 px-4 font-semibold text-gray-700 text-base cursor-pointer hover:bg-gray-50"
onClick={() => handleSort("status")}
>
<div className="flex items-center gap-1">
Status
{sortField === "status" && (
<ChevronDown className={`h-3 w-3 transition-transform ${sortDirection === "asc" ? "rotate-180" : ""}`} />
)}
</div>
</TableHead>
<TableHead
className="py-4 px-4 font-semibold text-gray-700 text-base cursor-pointer hover:bg-gray-50"
onClick={() => handleSort("totalAmount")}
>
<div className="flex items-center gap-1">
Total
{sortField === "totalAmount" && (
<ChevronDown className={`h-3 w-3 transition-transform ${sortDirection === "asc" ? "rotate-180" : ""}`} />
)}
</div>
</TableHead>
<TableHead
className="py-4 px-4 font-semibold text-gray-700 text-base cursor-pointer hover:bg-gray-50"
onClick={() => handleSort("dueDate")}
>
<div className="flex items-center gap-1">
Due Date
{sortField === "dueDate" && (
<ChevronDown className={`h-3 w-3 transition-transform ${sortDirection === "asc" ? "rotate-180" : ""}`} />
)}
</div>
</TableHead>
<TableHead className="w-8 py-4 px-4"></TableHead>
</>
);
}
return null;
};
const renderTableRows = () => {
if (isLoading) {
const skeletonCount = resource === "invoices" ? 6 : 5;
return Array.from({ length: skeletonCount }).map((_, index) => (
<TableRow key={`skeleton-${index}`}>
<TableCell className="py-4 px-4"><Skeleton className="h-4 w-4" /></TableCell>
<TableCell className="py-4 px-4"><Skeleton className="h-4 w-32" /></TableCell>
<TableCell className="py-4 px-4"><Skeleton className="h-4 w-40" /></TableCell>
<TableCell className="py-4 px-4"><Skeleton className="h-4 w-28" /></TableCell>
{resource === "invoices" && (
<>
<TableCell className="py-4 px-4"><Skeleton className="h-4 w-20" /></TableCell>
<TableCell className="py-4 px-4"><Skeleton className="h-4 w-24" /></TableCell>
</>
)}
<TableCell className="py-4 px-4"><Skeleton className="h-8 w-8 rounded" /></TableCell>
</TableRow>
));
}
if (paginatedData.length === 0) {
const colSpan = resource === "invoices" ? 7 : 5;
return (
<TableRow>
<TableCell colSpan={colSpan} className="py-12 text-center text-gray-500">
<div className="flex flex-col items-center gap-2">
{resource === "clients" ? (
<UserPlus className="h-8 w-8 text-emerald-400 mb-2" />
) : (
<FileText className="h-8 w-8 text-emerald-400 mb-2" />
)}
<div className="text-lg font-semibold">No {resource} found</div>
<div className="text-gray-500 mb-2">Get started by adding your first {resource.slice(0, -1)}.</div>
<Button asChild className="bg-gradient-to-r from-emerald-600 to-teal-600 text-white font-medium">
<Link href={`/dashboard/${resource}/new`}>
<Plus className="mr-2 h-4 w-4" /> Add {resource.slice(0, -1).charAt(0).toUpperCase() + resource.slice(0, -1).slice(1)}
</Link>
</Button>
</div>
</TableCell>
</TableRow>
);
}
return paginatedData.map((row) => {
if (resource === "clients") {
const client = row as Client;
return (
<TableRow
key={client.id}
data-selected={selected.includes(client.id)}
className="transition-colors hover:bg-emerald-50/60 group cursor-pointer"
onClick={e => {
if ((e.target as HTMLElement).closest('button, input, [role="menuitem"]')) return;
window.location.href = `/dashboard/clients/${client.id}/edit`;
}}
>
<TableCell className="py-4 px-4" onClick={e => e.stopPropagation()}>
<Checkbox
checked={selected.includes(client.id)}
onCheckedChange={() => toggleOne(client.id)}
aria-label="Select row"
className="data-[state=checked]:bg-emerald-600 data-[state=checked]:border-emerald-600"
/>
</TableCell>
<TableCell className="py-4 px-4 text-gray-900 text-base font-medium group-hover:text-emerald-700">
<Link href={`/dashboard/clients/${client.id}/edit`} className="hover:underline">
{client.name}
</Link>
</TableCell>
<TableCell className="py-4 px-4 text-gray-700">{client.email}</TableCell>
<TableCell className="py-4 px-4 text-gray-700">{client.phone}</TableCell>
<TableCell className="py-4 px-4" onClick={e => e.stopPropagation()}>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" aria-label="Actions">
...
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem asChild>
<Link href={`/dashboard/clients/${client.id}/edit`}>Edit</Link>
</DropdownMenuItem>
<DropdownMenuItem variant="destructive" onClick={() => handleDelete(client.id)}>Delete</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
</TableRow>
);
} else if (resource === "invoices") {
const invoice = row as Invoice;
return (
<TableRow
key={invoice.id}
data-selected={selected.includes(invoice.id)}
className="transition-colors hover:bg-emerald-50/60 group cursor-pointer"
onClick={e => {
if ((e.target as HTMLElement).closest('button, input, [role="menuitem"]')) return;
window.location.href = `/dashboard/invoices/${invoice.id}`;
}}
>
<TableCell className="py-4 px-4" onClick={e => e.stopPropagation()}>
<Checkbox
checked={selected.includes(invoice.id)}
onCheckedChange={() => toggleOne(invoice.id)}
aria-label="Select row"
className="data-[state=checked]:bg-emerald-600 data-[state=checked]:border-emerald-600"
/>
</TableCell>
<TableCell className="py-4 px-4 text-gray-900 text-base font-medium group-hover:text-emerald-700">
<Link href={`/dashboard/invoices/${invoice.id}`} className="hover:underline">
{invoice.invoiceNumber}
</Link>
</TableCell>
<TableCell className="py-4 px-4 text-gray-700">{invoice.client?.name}</TableCell>
<TableCell className="py-4 px-4">
<span className={`px-2 py-1 rounded-full text-xs font-medium ${statusColors[invoice.status]}`}>
{statusLabels[invoice.status]}
</span>
</TableCell>
<TableCell className="py-4 px-4 text-gray-700 font-medium">{formatCurrency(invoice.totalAmount)}</TableCell>
<TableCell className="py-4 px-4 text-gray-700">{formatDate(invoice.dueDate)}</TableCell>
<TableCell className="py-4 px-4" onClick={e => e.stopPropagation()}>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" aria-label="Actions">
...
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem asChild>
<Link href={`/dashboard/invoices/${invoice.id}/edit`}>
<Pencil className="h-4 w-4 mr-2" />
Edit
</Link>
</DropdownMenuItem>
<DropdownMenuItem variant="destructive" onClick={() => handleDelete(invoice.id)}><Trash2 className="h-4 w-4 mr-2" />Delete</DropdownMenuItem>
<DropdownMenuItem onClick={() => handlePDFExport(invoice)} disabled={exportingPDF === invoice.id}>
<Download className="h-4 w-4 mr-2" />
{exportingPDF === invoice.id ? "Generating..." : "Export"}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
</TableRow>
);
}
return null;
});
};
return (
<div className="w-full">
{/* Controls */}
<div className="flex flex-col sm:flex-row sm:items-center gap-4 mb-4 p-4 bg-white/90 rounded-lg border border-gray-200 shadow-sm">
<div className="flex gap-2 items-center">
<Button variant={view === "table" ? "default" : "ghost"} size="icon" onClick={() => setView("table")}> <List className="h-4 w-4" /> </Button>
<Button variant={view === "grid" ? "default" : "ghost"} size="icon" onClick={() => setView("grid")}> <LayoutGrid className="h-4 w-4" /> </Button>
{/* Filter Dropdown */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon">
<Filter className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-48">
<DropdownMenuItem className="font-medium text-gray-700">Filters</DropdownMenuItem>
{resource === "invoices" && (
<>
<DropdownMenuItem
onClick={() => setStatusFilter("all")}
className={statusFilter === "all" ? "bg-emerald-50 text-emerald-700" : ""}
>
All Statuses
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setStatusFilter("draft")}
className={statusFilter === "draft" ? "bg-emerald-50 text-emerald-700" : ""}
>
Draft
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setStatusFilter("sent")}
className={statusFilter === "sent" ? "bg-emerald-50 text-emerald-700" : ""}
>
Sent
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setStatusFilter("paid")}
className={statusFilter === "paid" ? "bg-emerald-50 text-emerald-700" : ""}
>
Paid
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setStatusFilter("overdue")}
className={statusFilter === "overdue" ? "bg-emerald-50 text-emerald-700" : ""}
>
Overdue
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
</div>
<div className="flex gap-2 items-center min-w-0 flex-1">
<Input
placeholder={`Search ${resource}...`}
value={search}
onChange={(e) => setSearch(e.target.value)}
className="max-w-xs"
/>
<Button variant="outline" size="icon"><Search className="h-4 w-4" /></Button>
</div>
<div className="flex gap-2 items-center flex-shrink-0">
{selected.length > 0 && (
<>
<span className="text-sm text-gray-500">{selected.length} selected</span>
{resource === "invoices" && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm">
Update Status <ChevronDown className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => handleBatchStatusUpdate("draft")}>
Mark as Draft
</DropdownMenuItem>
<DropdownMenuItem onClick={() => handleBatchStatusUpdate("sent")}>
Mark as Sent
</DropdownMenuItem>
<DropdownMenuItem onClick={() => handleBatchStatusUpdate("paid")}>
Mark as Paid
</DropdownMenuItem>
<DropdownMenuItem onClick={() => handleBatchStatusUpdate("overdue")}>
Mark as Overdue
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
<Button variant="destructive" size="sm" onClick={handleBatchDelete}><Trash2 className="h-4 w-4 mr-1" />Delete</Button>
</>
)}
</div>
</div>
{/* Table View */}
{view === "table" && (
<div className="rounded-2xl shadow-xl border border-gray-200 bg-white/90 overflow-hidden">
<Table className="w-full">
<TableHeader>
<TableRow>
{renderTableHeaders()}
</TableRow>
</TableHeader>
<TableBody>
{renderTableRows()}
</TableBody>
</Table>
</div>
)}
{/* Pagination Controls */}
{view === "table" && totalPages > 1 && (
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4 px-4 py-3 bg-white/95 border-t border-gray-200 rounded-xl shadow-sm mt-4">
<div className="flex items-center gap-2 text-sm text-gray-600">
<span>
Showing {startIndex + 1} to {Math.min(endIndex, filteredAndSortedData.length)} of {filteredAndSortedData.length} {resource}
</span>
<select
value={itemsPerPage}
onChange={(e) => {
setItemsPerPage(Number(e.target.value));
setCurrentPage(1);
}}
className="w-28 h-8 px-2 py-1 text-sm border border-gray-300 rounded-md bg-white focus:border-emerald-500 focus:ring-emerald-500"
>
<option value={5}>5 per page</option>
<option value={10}>10 per page</option>
<option value={25}>25 per page</option>
<option value={50}>50 per page</option>
</select>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
disabled={currentPage === 1}
aria-label="Previous page"
>
Previous
</Button>
<div className="flex items-center gap-1">
{Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
const pageNum = i + 1;
if (totalPages <= 5) {
return (
<Button
key={pageNum}
variant={currentPage === pageNum ? "default" : "outline"}
size="sm"
onClick={() => setCurrentPage(pageNum)}
className="w-8 h-8 p-0"
aria-current={currentPage === pageNum ? "page" : undefined}
>
{pageNum}
</Button>
);
}
if (pageNum === 1 || pageNum === totalPages || (pageNum >= currentPage - 1 && pageNum <= currentPage + 1)) {
return (
<Button
key={pageNum}
variant={currentPage === pageNum ? "default" : "outline"}
size="sm"
onClick={() => setCurrentPage(pageNum)}
className="w-8 h-8 p-0"
aria-current={currentPage === pageNum ? "page" : undefined}
>
{pageNum}
</Button>
);
}
if (pageNum === currentPage - 2 || pageNum === currentPage + 2) {
return <span key={pageNum} className="px-2 text-gray-400">...</span>;
}
return null;
})}
</div>
<Button
variant="outline"
size="sm"
onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
disabled={currentPage === totalPages}
aria-label="Next page"
>
Next
</Button>
</div>
</div>
)}
{/* Grid View (placeholder) */}
{view === "grid" && (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{isLoading ? (
Array.from({ length: 6 }).map((_, index) => (
<div key={`skeleton-card-${index}`} className="bg-white/90 rounded-2xl shadow-xl border border-gray-200 p-4 flex flex-col gap-2">
<Skeleton className="h-6 w-32" />
<Skeleton className="h-4 w-40" />
<Skeleton className="h-4 w-28" />
</div>
))
) : filteredAndSortedData.length === 0 ? (
<div className="col-span-full flex flex-col items-center py-16 text-gray-500">
{resource === "clients" ? (
<UserPlus className="h-8 w-8 text-emerald-400 mb-2" />
) : (
<FileText className="h-8 w-8 text-emerald-400 mb-2" />
)}
<div className="text-lg font-semibold">No {resource} found</div>
<div className="text-gray-500 mb-2">Get started by adding your first {resource.slice(0, -1)}.</div>
<Button asChild className="bg-gradient-to-r from-emerald-600 to-teal-600 text-white font-medium">
<Link href={`/dashboard/${resource}/new`}>
<Plus className="mr-2 h-4 w-4" /> Add {resource.slice(0, -1).charAt(0).toUpperCase() + resource.slice(0, -1).slice(1)}
</Link>
</Button>
</div>
) : (
filteredAndSortedData.map((row) => {
if (resource === "clients") {
const client = row as Client;
return (
<div key={client.id} className="bg-white/90 rounded-2xl shadow-xl border border-gray-200 p-4 flex flex-col gap-2 transition-colors hover:bg-emerald-50/60 cursor-pointer">
<div className="font-semibold text-lg text-gray-900 group-hover:text-emerald-700">{client.name}</div>
<div className="text-sm text-gray-700">{client.email}</div>
<div className="text-sm text-gray-700">{client.phone}</div>
</div>
);
} else {
const invoice = row as Invoice;
return (
<div key={invoice.id} className="bg-white/90 rounded-2xl shadow-xl border border-gray-200 p-4 flex flex-col gap-2 transition-colors hover:bg-emerald-50/60 cursor-pointer">
<div className="font-semibold text-lg text-gray-900 group-hover:text-emerald-700">{invoice.invoiceNumber}</div>
<div className="text-sm text-gray-700">{invoice.client?.name}</div>
<div className="text-sm text-gray-700">{formatCurrency(invoice.totalAmount)}</div>
</div>
);
}
})
)}
</div>
)}
{/* Confirmation Dialog */}
<Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<DialogContent className="bg-white/95 backdrop-blur-sm border-0 shadow-2xl">
<DialogHeader>
<DialogTitle className="text-xl font-bold text-gray-800">Delete {resource.slice(0, -1).charAt(0).toUpperCase() + resource.slice(0, -1).slice(1)}{itemToDelete === "batch" ? "s" : ""}</DialogTitle>
<DialogDescription className="text-gray-600">
{itemToDelete === "batch"
? `Are you sure you want to delete the selected ${resource}? This action cannot be undone.`
: `Are you sure you want to delete this ${resource.slice(0, -1)}? This action cannot be undone.`}
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button
variant="outline"
onClick={() => setDeleteDialogOpen(false)}
className="border-gray-300 text-gray-700 hover:bg-gray-50"
>
Cancel
</Button>
<Button
variant="destructive"
onClick={itemToDelete === "batch" ? confirmBatchDelete : confirmDelete}
className="bg-red-600 hover:bg-red-700"
>
Delete
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}