summaryrefslogtreecommitdiff
path: root/lib/email-whitelist/table
diff options
context:
space:
mode:
Diffstat (limited to 'lib/email-whitelist/table')
-rw-r--r--lib/email-whitelist/table/create-whitelist-dialog.tsx179
-rw-r--r--lib/email-whitelist/table/delete-whitelist-dialog.tsx137
-rw-r--r--lib/email-whitelist/table/update-whitelist-dialog.tsx193
-rw-r--r--lib/email-whitelist/table/whitelist-table-columns.tsx208
-rw-r--r--lib/email-whitelist/table/whitelist-table.tsx130
5 files changed, 847 insertions, 0 deletions
diff --git a/lib/email-whitelist/table/create-whitelist-dialog.tsx b/lib/email-whitelist/table/create-whitelist-dialog.tsx
new file mode 100644
index 00000000..d82ac168
--- /dev/null
+++ b/lib/email-whitelist/table/create-whitelist-dialog.tsx
@@ -0,0 +1,179 @@
+'use client'
+
+import * as React from "react"
+import { zodResolver } from "@hookform/resolvers/zod"
+import { Loader } from "lucide-react"
+import { useForm } from "react-hook-form"
+import { toast } from "sonner"
+import { z } from "zod"
+import { useSession } from "next-auth/react"
+
+import { Button } from "@/components/ui/button"
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog"
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form"
+import { Input } from "@/components/ui/input"
+import { Textarea } from "@/components/ui/textarea"
+
+import { createEmailWhitelistAction } from "../service"
+
+// Validation Schema
+const createWhitelistSchema = z.object({
+ value: z.string()
+ .min(1, "값은 필수입니다")
+ .max(255, "값은 255자를 초과할 수 없습니다")
+ .refine((value) => {
+ // 이메일 형식 또는 도메인 형식 중 하나여야 함
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+
+ // 도메인 검증: 최소 하나의 .이 있어야 하고, TLD가 있어야 함
+ // 예: company.com, sub.company.com, company.co.kr
+ const domainRegex = /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*\.[a-zA-Z]{2,}$/;
+
+ return emailRegex.test(value) || domainRegex.test(value);
+ }, "올바른 이메일 주소 또는 도메인 형식이 아닙니다 (도메인은 최소 1개의 TLD가 필요합니다)"),
+ description: z.string().max(500, "설명은 500자 이하여야 합니다").optional(),
+})
+
+type CreateWhitelistSchema = z.infer<typeof createWhitelistSchema>
+
+interface CreateWhitelistDialogProps
+ extends Omit<React.ComponentPropsWithRef<typeof Dialog>, 'children'> {
+ open?: boolean
+ onOpenChange?: (open: boolean) => void
+}
+
+export function CreateWhitelistDialog({ ...props }: CreateWhitelistDialogProps) {
+ const [isCreatePending, startCreateTransition] = React.useTransition()
+ const { data: session } = useSession();
+
+ const form = useForm<CreateWhitelistSchema>({
+ resolver: zodResolver(createWhitelistSchema),
+ defaultValues: {
+ value: "",
+ description: "",
+ },
+ })
+
+ // 입력값 소문자 변환
+ React.useEffect(() => {
+ const watchedValue = form.watch("value")
+ if (watchedValue && watchedValue !== watchedValue.toLowerCase()) {
+ form.setValue("value", watchedValue.toLowerCase())
+ }
+ }, [form])
+
+ function onSubmit(input: CreateWhitelistSchema) {
+ startCreateTransition(async () => {
+ if (!session?.user?.id) {
+ toast.error("로그인이 필요합니다")
+ return
+ }
+
+ const { error } = await createEmailWhitelistAction({
+ value: input.value,
+ description: input.description,
+ })
+
+ if (error) {
+ toast.error(error)
+ return
+ }
+
+ form.reset()
+ props.onOpenChange?.(false)
+ toast.success("화이트리스트 도메인이 추가되었습니다")
+ })
+ }
+
+ return (
+ <Dialog {...props}>
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader>
+ <DialogTitle>화이트리스트 추가</DialogTitle>
+ <DialogDescription>
+ SMS 인증을 우회할 이메일 주소 또는 도메인을 추가합니다. 등록된 이메일이나 도메인의 주소로 로그인 시 SMS 인증을 건너뜁니다.
+ </DialogDescription>
+ </DialogHeader>
+ <Form {...form}>
+ <form
+ onSubmit={form.handleSubmit(onSubmit)}
+ className="space-y-4"
+ >
+ <FormField
+ control={form.control}
+ name="value"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>이메일 주소 또는 도메인</FormLabel>
+ <FormControl>
+ <Input
+ placeholder="예: user@company.com 또는 company.com"
+ {...field}
+ />
+ </FormControl>
+ <FormDescription>
+ 이메일 주소나 도메인을 입력하세요. @가 포함되면 개별 이메일로, 그렇지 않으면 도메인 전체로 등록됩니다. 도메인은 최소 1개의 TLD가 필요합니다.
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="description"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>설명 (선택사항)</FormLabel>
+ <FormControl>
+ <Textarea
+ placeholder="도메인에 대한 설명을 입력하세요"
+ className="min-h-[80px]"
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => props.onOpenChange?.(false)}
+ disabled={isCreatePending}
+ >
+ 취소
+ </Button>
+ <Button disabled={isCreatePending}>
+ {isCreatePending && (
+ <Loader
+ className="mr-2 size-4 animate-spin"
+ aria-hidden="true"
+ />
+ )}
+ 추가
+ </Button>
+ </DialogFooter>
+ </form>
+ </Form>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/lib/email-whitelist/table/delete-whitelist-dialog.tsx b/lib/email-whitelist/table/delete-whitelist-dialog.tsx
new file mode 100644
index 00000000..c01e675b
--- /dev/null
+++ b/lib/email-whitelist/table/delete-whitelist-dialog.tsx
@@ -0,0 +1,137 @@
+// delete-whitelist-dialog.tsx
+"use client"
+
+import * as React from "react"
+import { Loader, Trash } from "lucide-react"
+import { toast } from "sonner"
+
+import { Button } from "@/components/ui/button"
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog"
+import { type EmailWhitelist } from "../service"
+
+import { deleteEmailWhitelistAction } from "../service"
+
+interface DeleteWhitelistDialogProps
+ extends React.ComponentPropsWithRef<typeof Dialog> {
+ whitelists: EmailWhitelist[]
+ showTrigger?: boolean
+ onSuccess?: () => void
+}
+
+export function DeleteWhitelistDialog({
+ whitelists,
+ showTrigger = true,
+ onSuccess,
+ ...props
+}: DeleteWhitelistDialogProps) {
+ const [isDeletePending, startDeleteTransition] = React.useTransition()
+
+ const isMultiple = whitelists.length > 1
+ const whitelistInfo = isMultiple ? `${whitelists.length}개 도메인` : whitelists[0]?.domain
+
+ function onDelete() {
+ startDeleteTransition(async () => {
+ const ids = whitelists.map(w => w.id)
+ const { error } = await deleteEmailWhitelistAction(ids)
+
+ if (error) {
+ toast.error(error)
+ return
+ }
+
+ props.onOpenChange?.(false)
+ onSuccess?.()
+ toast.success(
+ isMultiple
+ ? `${whitelists.length}개 도메인이 삭제되었습니다`
+ : "도메인이 삭제되었습니다"
+ )
+ })
+ }
+
+ return (
+ <Dialog {...props}>
+ {showTrigger && (
+ <DialogTrigger asChild>
+ <Button
+ variant="outline"
+ size="sm"
+ className="text-destructive hover:text-destructive"
+ >
+ <Trash className="mr-2 size-4" aria-hidden="true" />
+ 삭제
+ </Button>
+ </DialogTrigger>
+ )}
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>화이트리스트 도메인 삭제 확인</DialogTitle>
+ <DialogDescription>
+ 정말로 <strong>{whitelistInfo}</strong>을(를) 삭제하시겠습니까?
+ {!isMultiple && (
+ <>
+ <br />
+ 이 작업은 되돌릴 수 없습니다.
+ </>
+ )}
+ </DialogDescription>
+ </DialogHeader>
+
+ {/* 삭제될 도메인 목록 표시 */}
+ {whitelists.length > 0 && (
+ <div className="rounded-lg bg-muted p-3 max-h-40 overflow-y-auto">
+ <h4 className="text-sm font-medium mb-2">삭제될 항목</h4>
+ <div className="space-y-1">
+ {whitelists.map((whitelist) => {
+ const displayValue = whitelist.email || whitelist.domain || '';
+ const isEmail = displayValue.includes('@');
+
+ return (
+ <div key={whitelist.id} className="text-xs text-muted-foreground">
+ <div className="font-medium font-mono">
+ {isEmail ? displayValue : `@${displayValue}`}
+ </div>
+ {whitelist.description && (
+ <div className="text-xs">{whitelist.description}</div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ )}
+
+ <DialogFooter>
+ <Button
+ variant="outline"
+ onClick={() => props.onOpenChange?.(false)}
+ disabled={isDeletePending}
+ >
+ 취소
+ </Button>
+ <Button
+ variant="destructive"
+ onClick={onDelete}
+ disabled={isDeletePending}
+ >
+ {isDeletePending && (
+ <Loader
+ className="mr-2 size-4 animate-spin"
+ aria-hidden="true"
+ />
+ )}
+ {isMultiple ? `${whitelists.length}개 삭제` : "삭제"}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/lib/email-whitelist/table/update-whitelist-dialog.tsx b/lib/email-whitelist/table/update-whitelist-dialog.tsx
new file mode 100644
index 00000000..2a798e30
--- /dev/null
+++ b/lib/email-whitelist/table/update-whitelist-dialog.tsx
@@ -0,0 +1,193 @@
+'use client'
+
+import * as React from "react"
+import { zodResolver } from "@hookform/resolvers/zod"
+import { Loader } from "lucide-react"
+import { useForm } from "react-hook-form"
+import { toast } from "sonner"
+import { z } from "zod"
+import { useSession } from "next-auth/react"
+
+import { Button } from "@/components/ui/button"
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog"
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form"
+import { Input } from "@/components/ui/input"
+import { Textarea } from "@/components/ui/textarea"
+
+import { updateEmailWhitelistAction, type EmailWhitelist } from "../service"
+
+// Validation Schema
+const updateWhitelistSchema = z.object({
+ value: z.string()
+ .min(1, "값은 필수입니다")
+ .max(255, "값은 255자를 초과할 수 없습니다")
+ .refine((value) => {
+ // 이메일 형식 또는 도메인 형식 중 하나여야 함
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+
+ // 도메인 검증: 최소 하나의 .이 있어야 하고, TLD가 있어야 함
+ // 예: company.com, sub.company.com, company.co.kr
+ const domainRegex = /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*\.[a-zA-Z]{2,}$/;
+
+ return emailRegex.test(value) || domainRegex.test(value);
+ }, "올바른 이메일 주소 또는 도메인 형식이 아닙니다 (도메인은 최소 1개의 TLD가 필요합니다)"),
+ description: z.string().max(500, "설명은 500자 이하여야 합니다").optional(),
+})
+
+type UpdateWhitelistSchema = z.infer<typeof updateWhitelistSchema>
+
+interface UpdateWhitelistDialogProps
+ extends React.ComponentPropsWithRef<typeof Dialog> {
+ whitelist?: EmailWhitelist | null
+}
+
+export function UpdateWhitelistDialog({ whitelist, ...props }: UpdateWhitelistDialogProps) {
+ const [isUpdatePending, startUpdateTransition] = React.useTransition()
+ const { data: session } = useSession();
+
+ const form = useForm<UpdateWhitelistSchema>({
+ resolver: zodResolver(updateWhitelistSchema),
+ defaultValues: {
+ value: "",
+ description: "",
+ },
+ })
+
+ // 화이트리스트 데이터가 변경되면 폼 초기화
+ React.useEffect(() => {
+ if (whitelist) {
+ form.reset({
+ value: whitelist.displayValue || "",
+ description: whitelist.description || "",
+ })
+ }
+ }, [whitelist, form])
+
+ // 입력값 소문자 변환
+ React.useEffect(() => {
+ const watchedValue = form.watch("value")
+ if (watchedValue && watchedValue !== watchedValue.toLowerCase()) {
+ form.setValue("value", watchedValue.toLowerCase())
+ }
+ }, [form])
+
+ function onSubmit(input: UpdateWhitelistSchema) {
+ startUpdateTransition(async () => {
+ if (!session?.user?.id) {
+ toast.error("로그인이 필요합니다")
+ return
+ }
+
+ if (!whitelist) {
+ toast.error("수정할 데이터를 찾을 수 없습니다")
+ return
+ }
+
+ const { error } = await updateEmailWhitelistAction({
+ id: whitelist.id,
+ value: input.value,
+ description: input.description,
+ })
+
+ if (error) {
+ toast.error(error)
+ return
+ }
+
+ props.onOpenChange?.(false)
+ toast.success("화이트리스트 도메인이 수정되었습니다")
+ })
+ }
+
+ return (
+ <Dialog {...props}>
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader>
+ <DialogTitle>화이트리스트 수정</DialogTitle>
+ <DialogDescription>
+ 화이트리스트 정보를 수정합니다.
+ </DialogDescription>
+ </DialogHeader>
+ <Form {...form}>
+ <form
+ onSubmit={form.handleSubmit(onSubmit)}
+ className="space-y-4"
+ >
+ <FormField
+ control={form.control}
+ name="value"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>이메일 주소 또는 도메인</FormLabel>
+ <FormControl>
+ <Input
+ placeholder="예: user@company.com 또는 company.com"
+ {...field}
+ />
+ </FormControl>
+ <FormDescription>
+ 이메일 주소나 도메인을 입력하세요. @가 포함되면 개별 이메일로, 그렇지 않으면 도메인 전체로 등록됩니다. 도메인은 최소 1개의 TLD가 필요합니다.
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="description"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>설명 (선택사항)</FormLabel>
+ <FormControl>
+ <Textarea
+ placeholder="도메인에 대한 설명을 입력하세요"
+ className="min-h-[80px]"
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => props.onOpenChange?.(false)}
+ disabled={isUpdatePending}
+ >
+ 취소
+ </Button>
+ <Button disabled={isUpdatePending}>
+ {isUpdatePending && (
+ <Loader
+ className="mr-2 size-4 animate-spin"
+ aria-hidden="true"
+ />
+ )}
+ 수정
+ </Button>
+ </DialogFooter>
+ </form>
+ </Form>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/lib/email-whitelist/table/whitelist-table-columns.tsx b/lib/email-whitelist/table/whitelist-table-columns.tsx
new file mode 100644
index 00000000..2533d863
--- /dev/null
+++ b/lib/email-whitelist/table/whitelist-table-columns.tsx
@@ -0,0 +1,208 @@
+'use client';
+
+/* IMPORT */
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Checkbox } from '@/components/ui/checkbox';
+import { MoreHorizontal, Trash, Pencil } from 'lucide-react';
+import { DataTableColumnHeaderSimple } from '@/components/data-table/data-table-column-simple-header';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { formatDate } from '@/lib/utils';
+import { type ColumnDef } from '@tanstack/react-table';
+import { type Dispatch, type SetStateAction } from 'react';
+import { type DataTableRowAction } from '@/types/table';
+import { type EmailWhitelist } from '../service';
+
+// ----------------------------------------------------------------------------------------------------
+
+/* TYPES */
+interface GetColumnsProps {
+ setRowAction: Dispatch<SetStateAction<DataTableRowAction<EmailWhitelist> | null>>;
+}
+
+// ----------------------------------------------------------------------------------------------------
+
+/* FUNCTION FOR GETTING COLUMNS SETTING */
+export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<EmailWhitelist>[] {
+ return [
+ // [1] Checkbox Column
+ {
+ id: 'select',
+ header: ({ table }) => (
+ <Checkbox
+ checked={
+ table.getIsAllPageRowsSelected() ||
+ (table.getIsSomePageRowsSelected() && 'indeterminate')
+ }
+ onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
+ aria-label="Select all"
+ className="translate-y-0.5"
+ />
+ ),
+ cell: ({ row }) => (
+ <Checkbox
+ checked={row.getIsSelected()}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ aria-label="Select row"
+ className="translate-y-0.5"
+ />
+ ),
+ enableSorting: false,
+ enableHiding: false,
+ },
+
+ // [2] ID Column
+ {
+ accessorKey: 'id',
+ header: ({ column }) => (
+ <DataTableColumnHeaderSimple column={column} title="ID" />
+ ),
+ cell: ({ row }) => <div>{row.getValue('id')}</div>,
+ enableSorting: false,
+ enableHiding: false,
+ size: 80,
+ },
+
+ // [3] Email/Domain Column
+ {
+ accessorKey: 'displayValue',
+ header: ({ column }) => (
+ <DataTableColumnHeaderSimple column={column} title="이메일/도메인" />
+ ),
+ cell: ({ row }) => {
+ const displayValue = row.getValue('displayValue') as string;
+ const isEmail = displayValue.includes('@');
+
+ return (
+ <div className="flex space-x-2">
+ <Badge variant={isEmail ? 'default' : 'outline'} className="font-mono">
+ {isEmail ? displayValue : `@${displayValue}`}
+ </Badge>
+ </div>
+ );
+ },
+ enableSorting: false,
+ size: 220,
+ },
+
+ // [4] Description Column
+ {
+ accessorKey: 'description',
+ header: ({ column }) => (
+ <DataTableColumnHeaderSimple column={column} title="설명" />
+ ),
+ cell: ({ row }) => {
+ const description = row.getValue('description') as string;
+ return (
+ <div className="truncate" title={description || ''}>
+ {description || '-'}
+ </div>
+ );
+ },
+ enableSorting: false,
+ size: 200,
+ },
+
+ // [5] Created At Column
+ {
+ accessorKey: 'createdAt',
+ header: ({ column }) => (
+ <DataTableColumnHeaderSimple column={column} title="생성일" />
+ ),
+ cell: ({ row }) => {
+ const date = row.getValue('createdAt') as Date;
+ return <div>{formatDate(date, "KR")}</div>;
+ },
+ enableSorting: false,
+ size: 120,
+ },
+
+ // [6] Created By Column
+ {
+ accessorKey: 'createdByName',
+ header: ({ column }) => (
+ <DataTableColumnHeaderSimple column={column} title="생성자" />
+ ),
+ cell: ({ row }) => {
+ const name = row.getValue('createdByName') as string;
+ return <div>{name || '-'}</div>;
+ },
+ enableSorting: false,
+ size: 100,
+ },
+
+ // [7] Updated At Column
+ {
+ accessorKey: 'updatedAt',
+ header: ({ column }) => (
+ <DataTableColumnHeaderSimple column={column} title="수정일" />
+ ),
+ cell: ({ row }) => {
+ const date = row.getValue('updatedAt') as Date;
+ return <div>{formatDate(date, "KR")}</div>;
+ },
+ enableSorting: false,
+ size: 120,
+ },
+
+ // [8] Updated By Column
+ {
+ accessorKey: 'updatedByName',
+ header: ({ column }) => (
+ <DataTableColumnHeaderSimple column={column} title="수정자" />
+ ),
+ cell: ({ row }) => {
+ const name = row.getValue('updatedByName') as string;
+ return <div>{name || '-'}</div>;
+ },
+ enableSorting: false,
+ size: 100,
+ },
+
+ // [9] Actions Column
+ {
+ id: 'actions',
+ cell: ({ row }) => (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ aria-label="Open menu"
+ variant="ghost"
+ className="flex size-6 p-0 data-[state=open]:bg-muted"
+ >
+ <MoreHorizontal className="size-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-[160px]">
+ <DropdownMenuItem
+ onSelect={() => setRowAction({ row, type: 'update' })}
+ >
+ <Pencil className="mr-2 size-4" />
+ 수정
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onSelect={() => setRowAction({ row, type: 'delete' })}
+ className="text-destructive"
+ >
+ <Trash className="mr-2 size-4" />
+ 삭제
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ),
+ enableSorting: false,
+ enableHiding: false,
+ enableResizing: false,
+ size: 80,
+ minSize: 80,
+ maxSize: 80,
+ },
+ ];
+}
diff --git a/lib/email-whitelist/table/whitelist-table.tsx b/lib/email-whitelist/table/whitelist-table.tsx
new file mode 100644
index 00000000..5d623669
--- /dev/null
+++ b/lib/email-whitelist/table/whitelist-table.tsx
@@ -0,0 +1,130 @@
+"use client"
+
+import * as React from "react"
+import type {
+ DataTableAdvancedFilterField,
+ DataTableFilterField,
+ DataTableRowAction,
+} from "@/types/table"
+
+import { useDataTable } from "@/hooks/use-data-table"
+import { DataTable } from "@/components/data-table/data-table"
+import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar"
+
+import { getColumns } from "./whitelist-table-columns"
+import { type EmailWhitelist } from "../service"
+import { getEmailWhitelistList } from "../service"
+import { UpdateWhitelistDialog } from "./update-whitelist-dialog"
+import { CreateWhitelistDialog } from "./create-whitelist-dialog"
+import { DeleteWhitelistDialog } from "./delete-whitelist-dialog"
+
+interface WhitelistTableProps {
+ promises: Promise<
+ [
+ Awaited<ReturnType<typeof getEmailWhitelistList>>,
+ ]
+ >
+}
+
+export function WhitelistTable({ promises }: WhitelistTableProps) {
+ const [{ data, pageCount }] = React.use(promises)
+
+ const [rowAction, setRowAction] =
+ React.useState<DataTableRowAction<EmailWhitelist> | null>(null)
+
+ const [showCreateDialog, setShowCreateDialog] = React.useState(false)
+
+ const columns = React.useMemo(
+ () => getColumns({ setRowAction }),
+ [setRowAction]
+ )
+
+ /**
+ * 기본 필터 필드 (드롭다운 형태)
+ */
+ const filterFields: DataTableFilterField<EmailWhitelist>[] = []
+
+ /**
+ * 고급 필터 필드 (검색, 날짜 등)
+ */
+ const advancedFilterFields: DataTableAdvancedFilterField<EmailWhitelist>[] = [
+ {
+ id: "displayValue",
+ label: "이메일/도메인",
+ type: "text",
+ },
+ {
+ id: "description",
+ label: "설명",
+ type: "text",
+ },
+ {
+ id: "createdAt",
+ label: "생성일",
+ type: "date",
+ },
+ {
+ id: "updatedAt",
+ label: "수정일",
+ type: "date",
+ },
+ ]
+
+ const { table } = useDataTable({
+ data,
+ columns,
+ pageCount,
+ filterFields,
+ enableAdvancedFilter: true,
+ initialState: {
+ sorting: [{ id: "createdAt", desc: true }],
+ columnPinning: { right: ["actions"] },
+ },
+ getRowId: (originalRow) => String(originalRow.id),
+ shallow: false,
+ clearOnDefault: true,
+ })
+
+ return (
+ <>
+ <DataTable table={table}>
+ <DataTableAdvancedToolbar
+ table={table}
+ filterFields={advancedFilterFields}
+ shallow={false}
+ >
+ <CreateWhitelistDialog
+ open={showCreateDialog}
+ onOpenChange={setShowCreateDialog}
+ />
+ <button
+ type="button"
+ className="inline-flex items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground shadow transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50"
+ onClick={() => setShowCreateDialog(true)}
+ >
+ 이메일/도메인 추가
+ </button>
+ </DataTableAdvancedToolbar>
+ </DataTable>
+
+ {/* 도메인 수정 Dialog */}
+ <UpdateWhitelistDialog
+ open={rowAction?.type === "update"}
+ onOpenChange={() => setRowAction(null)}
+ whitelist={rowAction?.type === "update" ? rowAction.row.original : null}
+ />
+
+ {/* 도메인 삭제 Dialog */}
+ <DeleteWhitelistDialog
+ open={rowAction?.type === "delete"}
+ onOpenChange={() => setRowAction(null)}
+ whitelists={rowAction?.type === "delete" ? [rowAction.row.original] : []}
+ showTrigger={false}
+ onSuccess={() => {
+ setRowAction(null)
+ // 테이블 새로고침은 server action에서 자동으로 처리됨
+ }}
+ />
+ </>
+ )
+}