summaryrefslogtreecommitdiff
path: root/lib/email-template/table
diff options
context:
space:
mode:
Diffstat (limited to 'lib/email-template/table')
-rw-r--r--lib/email-template/table/create-template-sheet.tsx381
-rw-r--r--lib/email-template/table/delete-template-dialog.tsx137
-rw-r--r--lib/email-template/table/duplicate-template-sheet.tsx208
-rw-r--r--lib/email-template/table/email-template-table.tsx155
-rw-r--r--lib/email-template/table/template-table-columns.tsx296
-rw-r--r--lib/email-template/table/template-table-toolbar-actions.tsx115
-rw-r--r--lib/email-template/table/update-template-sheet.tsx215
7 files changed, 1507 insertions, 0 deletions
diff --git a/lib/email-template/table/create-template-sheet.tsx b/lib/email-template/table/create-template-sheet.tsx
new file mode 100644
index 00000000..199e20ab
--- /dev/null
+++ b/lib/email-template/table/create-template-sheet.tsx
@@ -0,0 +1,381 @@
+"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 { useRouter } from "next/navigation"
+import { useSession } from "next-auth/react"
+
+import { Button } from "@/components/ui/button"
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+ FormDescription,
+} from "@/components/ui/form"
+import { Input } from "@/components/ui/input"
+import { Textarea } from "@/components/ui/textarea"
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select"
+import {
+ Sheet,
+ SheetClose,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+} from "@/components/ui/sheet"
+
+import { createTemplateAction } from "../service"
+import { TEMPLATE_CATEGORY_OPTIONS } from "../validations"
+
+// Validation Schema (수정됨)
+const createTemplateSchema = z.object({
+ name: z.string().min(1, "템플릿 이름은 필수입니다").max(100, "템플릿 이름은 100자 이하여야 합니다"),
+ slug: z.string()
+ .min(1, "Slug는 필수입니다")
+ .max(50, "Slug는 50자 이하여야 합니다")
+ .regex(/^[a-z0-9-]+$/, "Slug는 소문자, 숫자, 하이픈만 사용 가능합니다"),
+ description: z.string().max(500, "설명은 500자 이하여야 합니다").optional(),
+ category: z.string().optional(), // 빈 문자열이나 undefined 모두 허용
+})
+
+
+
+type CreateTemplateSchema = z.infer<typeof createTemplateSchema>
+
+interface CreateTemplateSheetProps
+ extends React.ComponentPropsWithRef<typeof Sheet> {
+}
+
+export function CreateTemplateSheet({ ...props }: CreateTemplateSheetProps) {
+ const [isCreatePending, startCreateTransition] = React.useTransition()
+ const router = useRouter()
+ const { data: session } = useSession();
+
+ // 또는 더 안전하게
+ if (!session?.user?.id) {
+ toast.error("로그인이 필요합니다")
+ return
+ }
+
+ const form = useForm<CreateTemplateSchema>({
+ resolver: zodResolver(createTemplateSchema),
+ defaultValues: {
+ name: "",
+ slug: "",
+ description: "",
+ category: undefined, // 기본값을 undefined로 설정
+ },
+ })
+
+ // 이름 입력 시 자동으로 slug 생성
+ const watchedName = form.watch("name")
+ React.useEffect(() => {
+ if (watchedName && !form.formState.dirtyFields.slug) {
+ const autoSlug = watchedName
+ .toLowerCase()
+ .replace(/[^a-z0-9\s-]/g, '') // 특수문자 제거
+ .replace(/\s+/g, '-') // 공백을 하이픈으로
+ .replace(/-+/g, '-') // 연속 하이픈 제거
+ .trim()
+ .slice(0, 50) // 최대 50자
+
+ form.setValue("slug", autoSlug, { shouldValidate: false })
+ }
+ }, [watchedName, form])
+
+ // 기본 템플릿 내용 생성
+ const getDefaultContent = (category: string, name: string) => {
+ const templates = {
+ 'welcome-email': `
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="UTF-8">
+ <title>환영합니다!</title>
+</head>
+<body>
+ <div style="max-width: 600px; margin: 0 auto; font-family: Arial, sans-serif;">
+ <h1>안녕하세요, {{userName}}님!</h1>
+ <p>${name}에 오신 것을 환영합니다.</p>
+ <p>{{message}}</p>
+ </div>
+</body>
+</html>`,
+ 'password-reset': `
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="UTF-8">
+ <title>비밀번호 재설정</title>
+</head>
+<body>
+ <div style="max-width: 600px; margin: 0 auto; font-family: Arial, sans-serif;">
+ <h1>비밀번호 재설정</h1>
+ <p>안녕하세요, {{userName}}님.</p>
+ <p>비밀번호 재설정을 위해 아래 링크를 클릭해주세요.</p>
+ <a href="{{resetLink}}">비밀번호 재설정</a>
+ </div>
+</body>
+</html>`,
+ 'notification': `
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="UTF-8">
+ <title>알림</title>
+</head>
+<body>
+ <div style="max-width: 600px; margin: 0 auto; font-family: Arial, sans-serif;">
+ <h1>알림</h1>
+ <p>안녕하세요, {{userName}}님.</p>
+ <p>{{message}}</p>
+ </div>
+</body>
+</html>`,
+ }
+
+ return templates[category as keyof typeof templates] || `
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="UTF-8">
+ <title>${name}</title>
+</head>
+<body>
+ <div style="max-width: 600px; margin: 0 auto; font-family: Arial, sans-serif;">
+ <h1>${name}</h1>
+ <p>안녕하세요, {{userName}}님.</p>
+ <p>{{message}}</p>
+ </div>
+</body>
+</html>`
+ }
+
+ // 기본 변수 생성
+ const getDefaultVariables = (category: string) => {
+ const variableTemplates = {
+ 'welcome-email': [
+ { variableName: 'userName', variableType: 'string', isRequired: true, description: '사용자 이름' },
+ { variableName: 'email', variableType: 'string', isRequired: true, description: '사용자 이메일' },
+ { variableName: 'message', variableType: 'string', isRequired: false, description: '환영 메시지' },
+ ],
+ 'password-reset': [
+ { variableName: 'userName', variableType: 'string', isRequired: true, description: '사용자 이름' },
+ { variableName: 'expiryTime', variableType: 'string', isRequired: true, description: '링크 유효 시간' },
+ { variableName: 'resetLink', variableType: 'string', isRequired: true, description: '재설정 URL' },
+ { variableName: 'supportEmail', variableType: 'string', isRequired: true, description: 'eVCP 서포터 이메일' },
+ ],
+ 'notification': [
+ { variableName: 'userName', variableType: 'string', isRequired: true, description: '사용자 이름' },
+ { variableName: 'email', variableType: 'string', isRequired: true, description: '사용자 이메일' },
+ { variableName: 'message', variableType: 'string', isRequired: true, description: '알림 메시지' },
+ ],
+ }
+
+ return variableTemplates[category as keyof typeof variableTemplates] || [
+ { variableName: 'userName', variableType: 'string', isRequired: true, description: '사용자 이름' },
+ { variableName: 'message', variableType: 'string', isRequired: false, description: '메시지 내용' },
+ ]
+ }
+
+ const getDefaultSubject = (category: string, name: string) => {
+ const subjectTemplates = {
+ 'welcome-email': '{{siteName}}에 오신 것을 환영합니다, {{userName}}님!',
+ 'password-reset': '{{userName}}님의 비밀번호 재설정 요청',
+ 'notification': '[{{notificationType}}] {{title}}',
+ 'invoice': '{{companyName}} 인보이스 #{{invoiceNumber}}',
+ 'marketing': '{{title}} - {{siteName}}',
+ 'system': '[시스템] {{title}}'
+ }
+
+ return subjectTemplates[category as keyof typeof subjectTemplates] ||
+ `${name} - {{siteName}}`
+ }
+
+
+ function onSubmit(input: CreateTemplateSchema) {
+ startCreateTransition(async () => {
+ if (!session?.user?.id) {
+ toast.error("로그인이 필요합니다")
+ return
+ }
+
+
+ const defaultContent = getDefaultContent(input.category || '', input.name)
+ const defaultVariables = getDefaultVariables(input.category || '')
+ const defaultSubject = getDefaultSubject(input.category || '', input.name)
+
+ const { error, data } = await createTemplateAction({
+ name: input.name,
+ slug: input.slug,
+ subject: defaultSubject,
+ content: defaultContent,
+ description: input.description,
+ category: input.category || undefined, // 빈 문자열 대신 undefined 전달
+ sampleData: {
+ userName: '홍길동',
+ email: 'user@example.com',
+ message: '샘플 메시지입니다.',
+ },
+ createdBy: Number(session.user.id),
+ variables: defaultVariables,
+ })
+
+ if (error) {
+ toast.error(error)
+ return
+ }
+
+ form.reset()
+ props.onOpenChange?.(false)
+ toast.success("템플릿이 생성되었습니다")
+
+ // 생성된 템플릿의 세부 페이지로 이동
+ if (data?.slug) {
+ router.push(`/evcp/email-template/${data.slug}`)
+ } else {
+ window.location.reload()
+ }
+ })
+ }
+
+ return (
+ <Sheet {...props}>
+ <SheetContent className="flex flex-col gap-6 sm:max-w-md">
+ <SheetHeader className="text-left">
+ <SheetTitle>새 템플릿 생성</SheetTitle>
+ <SheetDescription>
+ 새로운 이메일 템플릿을 생성합니다. 기본 구조가 자동으로 생성되며, 생성 후 세부 내용을 편집할 수 있습니다.
+ </SheetDescription>
+ </SheetHeader>
+ <Form {...form}>
+ <form
+ onSubmit={form.handleSubmit(onSubmit)}
+ className="flex flex-col gap-4"
+ >
+ <FormField
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>템플릿 이름</FormLabel>
+ <FormControl>
+ <Input
+ placeholder="예: 신규 회원 환영 메일"
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="slug"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Slug</FormLabel>
+ <FormControl>
+ <Input
+ placeholder="예: welcome-new-member"
+ {...field}
+ />
+ </FormControl>
+ <FormDescription>
+ URL에 사용될 고유 식별자입니다. 소문자, 숫자, 하이픈만 사용 가능합니다.
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="category"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>카테고리</FormLabel>
+ <Select
+ onValueChange={(value) => {
+ // "none" 값이 선택되면 undefined로 설정
+ field.onChange(value === "none" ? undefined : value)
+ }}
+ value={field.value || "none"} // undefined인 경우 "none"으로 표시
+ >
+ <FormControl>
+ <SelectTrigger>
+ <SelectValue placeholder="카테고리를 선택하세요" />
+ </SelectTrigger>
+ </FormControl>
+ <SelectContent>
+ <SelectItem value="none">카테고리 없음</SelectItem>
+ {TEMPLATE_CATEGORY_OPTIONS.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FormDescription>
+ 카테고리에 따라 기본 템플릿과 변수가 자동으로 생성됩니다.
+ </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>
+ )}
+ />
+
+ <SheetFooter className="gap-2 pt-2 sm:space-x-0">
+ <SheetClose asChild>
+ <Button type="button" variant="outline">
+ 취소
+ </Button>
+ </SheetClose>
+ <Button disabled={isCreatePending}>
+ {isCreatePending && (
+ <Loader
+ className="mr-2 size-4 animate-spin"
+ aria-hidden="true"
+ />
+ )}
+ 생성 후 편집하기
+ </Button>
+ </SheetFooter>
+ </form>
+ </Form>
+ </SheetContent>
+ </Sheet>
+ )
+} \ No newline at end of file
diff --git a/lib/email-template/table/delete-template-dialog.tsx b/lib/email-template/table/delete-template-dialog.tsx
new file mode 100644
index 00000000..5bc7dc53
--- /dev/null
+++ b/lib/email-template/table/delete-template-dialog.tsx
@@ -0,0 +1,137 @@
+// delete-template-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 TemplateListView } from "@/db/schema"
+
+import { deleteTemplate, bulkDeleteTemplates } from "../service"
+
+interface DeleteTemplateDialogProps
+ extends React.ComponentPropsWithRef<typeof Dialog> {
+ templates: TemplateListView[]
+ showTrigger?: boolean
+ onSuccess?: () => void
+}
+
+export function DeleteTemplateDialog({
+ templates,
+ showTrigger = true,
+ onSuccess,
+ ...props
+}: DeleteTemplateDialogProps) {
+ const [isDeletePending, startDeleteTransition] = React.useTransition()
+
+ const isMultiple = templates.length > 1
+ const templateName = isMultiple ? `${templates.length}개 템플릿` : templates[0]?.name
+
+ function onDelete() {
+ startDeleteTransition(async () => {
+ let result
+
+ if (isMultiple) {
+ const ids = templates.map(t => t.id)
+ result = await bulkDeleteTemplates(ids)
+ } else {
+ result = await deleteTemplate(templates[0].id)
+ }
+
+ if (result.error) {
+ toast.error(result.error)
+ return
+ }
+
+ props.onOpenChange?.(false)
+ onSuccess?.()
+ toast.success(
+ isMultiple
+ ? `${templates.length}개 템플릿이 삭제되었습니다`
+ : "템플릿이 삭제되었습니다"
+ )
+
+ // 페이지 새로고침으로 데이터 갱신
+ window.location.reload()
+ })
+ }
+
+ 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>{templateName}</strong>을(를) 삭제하시겠습니까?
+ {!isMultiple && (
+ <>
+ <br />
+ 이 작업은 되돌릴 수 없습니다.
+ </>
+ )}
+ </DialogDescription>
+ </DialogHeader>
+
+ {/* 삭제될 템플릿 목록 표시 */}
+ {templates.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">
+ {templates.map((template) => (
+ <div key={template.id} className="text-xs text-muted-foreground">
+ <div className="font-medium">{template.name}</div>
+ <div>Slug: <code className="bg-background px-1 rounded">{template.slug}</code></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 ? `${templates.length}개 삭제` : "삭제"}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+} \ No newline at end of file
diff --git a/lib/email-template/table/duplicate-template-sheet.tsx b/lib/email-template/table/duplicate-template-sheet.tsx
new file mode 100644
index 00000000..767a8bb6
--- /dev/null
+++ b/lib/email-template/table/duplicate-template-sheet.tsx
@@ -0,0 +1,208 @@
+"use client"
+
+import * as React from "react"
+import { type TemplateListView } from "@/db/schema/template-views"
+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 { useRouter } from "next/navigation"
+
+import { Button } from "@/components/ui/button"
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+ FormDescription,
+} from "@/components/ui/form"
+import { Input } from "@/components/ui/input"
+import {
+ Sheet,
+ SheetClose,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+} from "@/components/ui/sheet"
+
+import { duplicateTemplate } from "../service"
+
+// Validation Schema
+const duplicateTemplateSchema = z.object({
+ name: z.string().min(1, "템플릿 이름은 필수입니다").max(100, "템플릿 이름은 100자 이하여야 합니다"),
+ slug: z.string()
+ .min(1, "Slug는 필수입니다")
+ .max(50, "Slug는 50자 이하여야 합니다")
+ .regex(/^[a-z0-9-]+$/, "Slug는 소문자, 숫자, 하이픈만 사용 가능합니다"),
+})
+
+type DuplicateTemplateSchema = z.infer<typeof duplicateTemplateSchema>
+
+interface DuplicateTemplateSheetProps
+ extends React.ComponentPropsWithRef<typeof Sheet> {
+ template: TemplateListView | null
+}
+
+export function DuplicateTemplateSheet({ template, ...props }: DuplicateTemplateSheetProps) {
+ const [isDuplicatePending, startDuplicateTransition] = React.useTransition()
+ const router = useRouter()
+
+ const form = useForm<DuplicateTemplateSchema>({
+ resolver: zodResolver(duplicateTemplateSchema),
+ defaultValues: {
+ name: "",
+ slug: "",
+ },
+ })
+
+ React.useEffect(() => {
+ if (template) {
+ const copyName = `${template.name} (복사본)`
+ const copySlug = `${template.slug}-copy-${Date.now()}`
+
+ form.reset({
+ name: copyName,
+ slug: copySlug,
+ })
+ }
+ }, [template, form])
+
+ // 이름 입력 시 자동으로 slug 생성
+ const watchedName = form.watch("name")
+ React.useEffect(() => {
+ if (watchedName && !form.formState.dirtyFields.slug) {
+ const autoSlug = watchedName
+ .toLowerCase()
+ .replace(/[^a-z0-9\s-]/g, '')
+ .replace(/\s+/g, '-')
+ .replace(/-+/g, '-')
+ .trim()
+ .slice(0, 50)
+
+ form.setValue("slug", autoSlug, { shouldValidate: false })
+ }
+ }, [watchedName, form])
+
+ function onSubmit(input: DuplicateTemplateSchema) {
+ startDuplicateTransition(async () => {
+ if (!template) return
+
+ // 현재 사용자 ID (실제로는 인증에서 가져와야 함)
+ const currentUserId = "current-user-id" // TODO: 실제 사용자 ID로 교체
+
+ const { error, data } = await duplicateTemplate(
+ template.id,
+ input.name,
+ input.slug,
+ currentUserId
+ )
+
+ if (error) {
+ toast.error(error)
+ return
+ }
+
+ form.reset()
+ props.onOpenChange?.(false)
+ toast.success("템플릿이 복제되었습니다")
+
+ // 복제된 템플릿의 세부 페이지로 이동
+ if (data?.slug) {
+ router.push(`/evcp/templates/${data.slug}`)
+ } else {
+ window.location.reload()
+ }
+ })
+ }
+
+ return (
+ <Sheet {...props}>
+ <SheetContent className="flex flex-col gap-6 sm:max-w-md">
+ <SheetHeader className="text-left">
+ <SheetTitle>템플릿 복제</SheetTitle>
+ <SheetDescription>
+ 기존 템플릿을 복사하여 새로운 템플릿을 생성합니다. 모든 내용과 변수가 복제됩니다.
+ </SheetDescription>
+ </SheetHeader>
+
+ {template && (
+ <div className="rounded-lg bg-muted p-3">
+ <h4 className="text-sm font-medium mb-2">원본 템플릿</h4>
+ <div className="space-y-1 text-xs text-muted-foreground">
+ <div>이름: {template.name}</div>
+ <div>Slug: <code className="bg-background px-1 rounded">{template.slug}</code></div>
+ <div>카테고리: {template.categoryDisplayName}</div>
+ <div>변수: {template.variableCount}개</div>
+ </div>
+ </div>
+ )}
+
+ <Form {...form}>
+ <form
+ onSubmit={form.handleSubmit(onSubmit)}
+ className="flex flex-col gap-4"
+ >
+ <FormField
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>새 템플릿 이름</FormLabel>
+ <FormControl>
+ <Input
+ placeholder="복제된 템플릿의 이름을 입력하세요"
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="slug"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>새 Slug</FormLabel>
+ <FormControl>
+ <Input
+ placeholder="복제된 템플릿의 slug를 입력하세요"
+ {...field}
+ />
+ </FormControl>
+ <FormDescription>
+ 고유한 식별자여야 합니다. 소문자, 숫자, 하이픈만 사용 가능합니다.
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <SheetFooter className="gap-2 pt-2 sm:space-x-0">
+ <SheetClose asChild>
+ <Button type="button" variant="outline">
+ 취소
+ </Button>
+ </SheetClose>
+ <Button disabled={isDuplicatePending}>
+ {isDuplicatePending && (
+ <Loader
+ className="mr-2 size-4 animate-spin"
+ aria-hidden="true"
+ />
+ )}
+ 복제하기
+ </Button>
+ </SheetFooter>
+ </form>
+ </Form>
+ </SheetContent>
+ </Sheet>
+ )
+} \ No newline at end of file
diff --git a/lib/email-template/table/email-template-table.tsx b/lib/email-template/table/email-template-table.tsx
new file mode 100644
index 00000000..65e93a10
--- /dev/null
+++ b/lib/email-template/table/email-template-table.tsx
@@ -0,0 +1,155 @@
+"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 { TemplateTableToolbarActions } from "./template-table-toolbar-actions"
+import { getColumns } from "./template-table-columns"
+import { type TemplateListView } from "@/db/schema"
+import { getTemplateList } from "../service"
+import { UpdateTemplateSheet } from "./update-template-sheet"
+import { CreateTemplateSheet } from "./create-template-sheet"
+import { DuplicateTemplateSheet } from "./duplicate-template-sheet"
+import { DeleteTemplateDialog } from "./delete-template-dialog"
+
+interface TemplateTableProps {
+ promises: Promise<
+ [
+ Awaited<ReturnType<typeof getTemplateList>>,
+ ]
+ >
+}
+
+export function TemplateTable({ promises }: TemplateTableProps) {
+ const [{ data, pageCount }] = React.use(promises)
+
+ const [rowAction, setRowAction] =
+ React.useState<DataTableRowAction<TemplateListView> | null>(null)
+
+ const [showCreateSheet, setShowCreateSheet] = React.useState(false)
+
+ const columns = React.useMemo(
+ () => getColumns({ setRowAction }),
+ [setRowAction]
+ )
+
+ /**
+ * 기본 필터 필드 (드롭다운 형태)
+ */
+ const filterFields: DataTableFilterField<TemplateListView>[] = [
+
+ ]
+
+ /**
+ * 고급 필터 필드 (검색, 날짜 등)
+ */
+ const advancedFilterFields: DataTableAdvancedFilterField<TemplateListView>[] = [
+ {
+ id: "name",
+ label: "템플릿 이름",
+ type: "text",
+ },
+ {
+ id: "slug",
+ label: "Slug",
+ type: "text",
+ },
+
+ {
+ id: "variableCount",
+ label: "변수 개수",
+ type: "text",
+ },
+ {
+ id: "version",
+ label: "버전",
+ type: "text",
+ },
+ {
+ id: "createdAt",
+ label: "생성일",
+ type: "date",
+ },
+ {
+ id: "updatedAt",
+ label: "수정일",
+ type: "date",
+ },
+ ]
+
+ const { table } = useDataTable({
+ data,
+ columns,
+ pageCount,
+ filterFields,
+ enablePinning: true,
+ enableAdvancedFilter: true,
+ initialState: {
+ sorting: [{ id: "updatedAt", desc: true }],
+ columnPinning: { right: ["actions"] },
+ columnVisibility: {
+ slug: false, // 기본적으로 slug 컬럼은 숨김
+ },
+ },
+ getRowId: (originalRow) => String(originalRow.id),
+ shallow: false,
+ clearOnDefault: true,
+ })
+
+ return (
+ <>
+ <DataTable table={table}>
+ <DataTableAdvancedToolbar
+ table={table}
+ filterFields={advancedFilterFields}
+ shallow={false}
+ >
+ <TemplateTableToolbarActions
+ table={table}
+ onCreateTemplate={() => setShowCreateSheet(true)}
+ />
+ </DataTableAdvancedToolbar>
+ </DataTable>
+
+ {/* 새 템플릿 생성 Sheet */}
+ <CreateTemplateSheet
+ open={showCreateSheet}
+ onOpenChange={setShowCreateSheet}
+ />
+
+ {/* 템플릿 수정 Sheet */}
+ <UpdateTemplateSheet
+ open={rowAction?.type === "update"}
+ onOpenChange={() => setRowAction(null)}
+ template={rowAction?.type === "update" ? rowAction.row.original : null}
+ />
+
+ {/* 템플릿 복제 Sheet */}
+ <DuplicateTemplateSheet
+ open={rowAction?.type === "duplicate"}
+ onOpenChange={() => setRowAction(null)}
+ template={rowAction?.type === "duplicate" ? rowAction.row.original : null}
+ />
+
+ {/* 템플릿 삭제 Dialog */}
+ <DeleteTemplateDialog
+ open={rowAction?.type === "delete"}
+ onOpenChange={() => setRowAction(null)}
+ templates={rowAction?.type === "delete" ? [rowAction.row.original] : []}
+ showTrigger={false}
+ onSuccess={() => {
+ setRowAction(null)
+ // 테이블 새로고침은 server action에서 자동으로 처리됨
+ }}
+ />
+ </>
+ )
+} \ No newline at end of file
diff --git a/lib/email-template/table/template-table-columns.tsx b/lib/email-template/table/template-table-columns.tsx
new file mode 100644
index 00000000..d20739cc
--- /dev/null
+++ b/lib/email-template/table/template-table-columns.tsx
@@ -0,0 +1,296 @@
+"use client"
+
+import * as React from "react"
+import { type ColumnDef } from "@tanstack/react-table"
+import { ArrowUpDown, Copy, MoreHorizontal, Edit, Trash, Eye } from "lucide-react"
+import Link from "next/link"
+
+import { Badge } from "@/components/ui/badge"
+import { Button } from "@/components/ui/button"
+import { Checkbox } from "@/components/ui/checkbox"
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu"
+import { toast } from "sonner"
+import { formatDate } from "@/lib/utils"
+import { type TemplateListView } from "@/db/schema"
+import { type DataTableRowAction } from "@/types/table"
+import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
+import { getCategoryDisplayName, getCategoryVariant } from "../validations"
+
+interface GetColumnsProps {
+ setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<TemplateListView> | null>>
+}
+
+export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<TemplateListView>[] {
+ return [
+ // 체크박스 컬럼
+ {
+ 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,
+ },
+
+ // 템플릿 이름 컬럼 (클릭 시 세부 페이지로)
+ {
+ accessorKey: "name",
+ header: ({ column }) => (
+ <DataTableColumnHeaderSimple column={column} title="템플릿 이름" />
+ ),
+ cell: ({ row }) => {
+ const template = row.original
+ return (
+ <div className="flex flex-col gap-1">
+ <Link
+ href={`/evcp/email-template/${template.slug}`}
+ className="font-medium text-blue-600 hover:text-blue-800 hover:underline"
+ >
+ {template.name}
+ </Link>
+ {template.description && (
+ <div className="text-xs text-muted-foreground line-clamp-2">
+ {template.description}
+ </div>
+ )}
+ </div>
+ )
+ },
+ enableSorting: true,
+ enableHiding: false,
+ size:200
+ },
+
+ {
+ accessorKey: "subject",
+ header: ({ column }) => (
+ <DataTableColumnHeaderSimple column={column} title="이메일 제목" />
+ ),
+ cell: ({ getValue }) => {
+ const subject = getValue() as string
+ return (
+ <div className="text-sm text-muted-foreground">
+ {subject}
+ </div>
+ )
+ },
+ enableSorting: true,
+ size:250
+ },
+
+ // Slug 컬럼
+ {
+ accessorKey: "slug",
+ header: ({ column }) => (
+ <DataTableColumnHeaderSimple column={column} title="Slug" />
+ ),
+ cell: ({ getValue }) => {
+ const slug = getValue() as string
+ return (
+ <div className="font-mono text-sm text-muted-foreground">
+ {slug}
+ </div>
+ )
+ },
+ enableSorting: true,
+ size:120
+
+ },
+
+ // 카테고리 컬럼
+ {
+ accessorKey: "category",
+ header: ({ column }) => (
+ <DataTableColumnHeaderSimple column={column} title="카테고리" />
+ ),
+ cell: ({ row }) => {
+ const category = row.original.category
+ const displayName = getCategoryDisplayName(category)
+ const variant = getCategoryVariant(category)
+
+ return (
+ <Badge variant={variant}>
+ {displayName}
+ </Badge>
+ )
+ },
+ enableSorting: true,
+ filterFn: (row, id, value) => {
+ return value.includes(row.getValue(id))
+ },
+ size:120
+
+ },
+
+ // 변수 개수 컬럼
+ {
+ accessorKey: "variableCount",
+ header: ({ column }) => (
+ <DataTableColumnHeaderSimple column={column} title="변수" />
+ ),
+ cell: ({ row }) => {
+ const variableCount = row.original.variableCount
+ const requiredCount = row.original.requiredVariableCount
+
+ return (
+ <div className="text-center">
+ <div className="text-sm font-medium">{variableCount}</div>
+ {requiredCount > 0 && (
+ <div className="text-xs text-muted-foreground">
+ 필수: {requiredCount}
+ </div>
+ )}
+ </div>
+ )
+ },
+ enableSorting: true,
+ size:80
+
+ },
+
+ // 버전 컬럼
+ {
+ accessorKey: "version",
+ header: ({ column }) => (
+ <DataTableColumnHeaderSimple column={column} title="버전" />
+ ),
+ cell: ({ getValue }) => {
+ const version = getValue() as number
+ return (
+ <div className="text-center">
+ <Badge variant="outline" className="font-mono text-xs">
+ v{version}
+ </Badge>
+ </div>
+ )
+ },
+ enableSorting: true,
+ size:80
+
+ },
+
+ // 생성일 컬럼
+ {
+ accessorKey: "createdAt",
+ header: ({ column }) => (
+ <DataTableColumnHeaderSimple column={column} title="생성일" />
+ ),
+ cell: ({ cell }) => {
+ const date = cell.getValue() as Date
+ return (
+ <div className="text-sm text-muted-foreground">
+ {formatDate(date)}
+ </div>
+ )
+ },
+ enableSorting: true,
+ size:200
+
+ },
+
+ // 수정일 컬럼
+ {
+ accessorKey: "updatedAt",
+ header: ({ column }) => (
+ <DataTableColumnHeaderSimple column={column} title="수정일" />
+ ),
+ cell: ({ cell }) => {
+ const date = cell.getValue() as Date
+ return (
+ <div className="text-sm text-muted-foreground">
+ {formatDate(date)}
+ </div>
+ )
+ },
+ enableSorting: true,
+ size:200
+
+ },
+
+ // Actions 컬럼
+ {
+ id: "actions",
+ cell: ({ row }) => {
+ const template = row.original
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ aria-label="Open menu"
+ variant="ghost"
+ className="flex size-8 p-0 data-[state=open]:bg-muted"
+ >
+ <MoreHorizontal className="size-4" aria-hidden="true" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-40">
+ <DropdownMenuItem asChild>
+ <Link href={`/evcp/templates/${template.slug}`}>
+ <Eye className="mr-2 size-4" aria-hidden="true" />
+ 보기
+ </Link>
+ </DropdownMenuItem>
+
+ <DropdownMenuItem
+ onClick={() => {
+ setRowAction({ type: "update", row })
+ }}
+ >
+ <Edit className="mr-2 size-4" aria-hidden="true" />
+ 수정
+ </DropdownMenuItem>
+
+ <DropdownMenuItem
+ onClick={() => {
+ setRowAction({ type: "duplicate", row })
+ }}
+ >
+ <Copy className="mr-2 size-4" aria-hidden="true" />
+ 복제
+ </DropdownMenuItem>
+
+ <DropdownMenuSeparator />
+
+ <DropdownMenuItem
+ onClick={() => {
+ setRowAction({ type: "delete", row })
+ }}
+ className="text-destructive focus:text-destructive"
+ >
+ <Trash className="mr-2 size-4" aria-hidden="true" />
+ 삭제
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+ },
+ enableSorting: false,
+ enableHiding: false,
+ size:80
+
+ },
+ ]
+} \ No newline at end of file
diff --git a/lib/email-template/table/template-table-toolbar-actions.tsx b/lib/email-template/table/template-table-toolbar-actions.tsx
new file mode 100644
index 00000000..a7e107c6
--- /dev/null
+++ b/lib/email-template/table/template-table-toolbar-actions.tsx
@@ -0,0 +1,115 @@
+"use client"
+
+import * as React from "react"
+import { type Table } from "@tanstack/react-table"
+import { Download, Plus, Trash } from "lucide-react"
+
+import { Button } from "@/components/ui/button"
+import { type TemplateListView } from "@/db/schema/template-views"
+import { DeleteTemplateDialog } from "./delete-template-dialog"
+import { toast } from "sonner"
+
+interface TemplateTableToolbarActionsProps {
+ table: Table<TemplateListView>
+ onCreateTemplate: () => void
+}
+
+export function TemplateTableToolbarActions({
+ table,
+ onCreateTemplate,
+}: TemplateTableToolbarActionsProps) {
+ const [showDeleteDialog, setShowDeleteDialog] = React.useState(false)
+
+ const selectedRows = table.getFilteredSelectedRowModel().rows
+ const selectedTemplates = selectedRows.map(row => row.original)
+
+ // CSV 내보내기 함수
+ const exportToCsv = React.useCallback(() => {
+ const headers = ['이름', 'Slug', '카테고리', '변수 개수', '버전', '생성일', '수정일']
+ const csvData = [
+ headers,
+ ...table.getFilteredRowModel().rows.map(row => {
+ const template = row.original
+ return [
+ template.name,
+ template.slug,
+ template.categoryDisplayName || '미분류',
+ template.variableCount.toString(),
+ template.version.toString(),
+ new Date(template.createdAt).toLocaleDateString('ko-KR'),
+ new Date(template.updatedAt).toLocaleDateString('ko-KR'),
+ ]
+ })
+ ]
+
+ const csvContent = csvData.map(row =>
+ row.map(field => `"${field}"`).join(',')
+ ).join('\n')
+
+ const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
+ const link = document.createElement('a')
+
+ if (link.download !== undefined) {
+ const url = URL.createObjectURL(blob)
+ link.setAttribute('href', url)
+ link.setAttribute('download', `templates_${new Date().toISOString().split('T')[0]}.csv`)
+ link.style.visibility = 'hidden'
+ document.body.appendChild(link)
+ link.click()
+ document.body.removeChild(link)
+ }
+
+ toast.success('템플릿 목록이 CSV로 내보내졌습니다.')
+ }, [table])
+
+ return (
+ <div className="flex items-center gap-2">
+ {/* 새 템플릿 생성 버튼 */}
+ <Button
+ variant="default"
+ size="sm"
+ onClick={onCreateTemplate}
+ >
+ <Plus className="mr-2 size-4" aria-hidden="true" />
+ 새 템플릿
+ </Button>
+
+ {/* CSV 내보내기 버튼 */}
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={exportToCsv}
+ >
+ <Download className="mr-2 size-4" aria-hidden="true" />
+ 내보내기
+ </Button>
+
+ {/* 선택된 항목 일괄 삭제 버튼 */}
+ {selectedTemplates.length > 0 && (
+ <>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setShowDeleteDialog(true)}
+ className="text-destructive hover:text-destructive"
+ >
+ <Trash className="mr-2 size-4" aria-hidden="true" />
+ 삭제 ({selectedTemplates.length})
+ </Button>
+
+ {/* 일괄 삭제 Dialog */}
+ <DeleteTemplateDialog
+ open={showDeleteDialog}
+ onOpenChange={setShowDeleteDialog}
+ templates={selectedTemplates}
+ showTrigger={false}
+ onSuccess={() => {
+ table.toggleAllRowsSelected(false)
+ setShowDeleteDialog(false)
+ }}
+ />
+ </>
+ )}
+ </div>
+ )
+} \ No newline at end of file
diff --git a/lib/email-template/table/update-template-sheet.tsx b/lib/email-template/table/update-template-sheet.tsx
new file mode 100644
index 00000000..58da0626
--- /dev/null
+++ b/lib/email-template/table/update-template-sheet.tsx
@@ -0,0 +1,215 @@
+"use client"
+
+import * as React from "react"
+import { type TemplateListView} from "@/db/schema"
+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 { Button } from "@/components/ui/button"
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form"
+import { Input } from "@/components/ui/input"
+import { Textarea } from "@/components/ui/textarea"
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select"
+import {
+ Sheet,
+ SheetClose,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+} from "@/components/ui/sheet"
+
+import { updateTemplateAction } from "../service"
+import { TEMPLATE_CATEGORY_OPTIONS } from "../validations"
+
+// Validation Schema
+const updateTemplateSchema = z.object({
+ name: z.string().min(1, "템플릿 이름은 필수입니다").max(100, "템플릿 이름은 100자 이하여야 합니다"),
+ description: z.string().max(500, "설명은 500자 이하여야 합니다").optional(),
+ category: z.string().optional(),
+})
+
+type UpdateTemplateSchema = z.infer<typeof updateTemplateSchema>
+
+interface UpdateTemplateSheetProps
+ extends React.ComponentPropsWithRef<typeof Sheet> {
+ template: TemplateListView | null
+}
+
+export function UpdateTemplateSheet({ template, ...props }: UpdateTemplateSheetProps) {
+ const [isUpdatePending, startUpdateTransition] = React.useTransition()
+
+ const form = useForm<UpdateTemplateSchema>({
+ resolver: zodResolver(updateTemplateSchema),
+ defaultValues: {
+ name: template?.name ?? "",
+ description: template?.description ?? "",
+ category: template?.category ?? "",
+ },
+ })
+
+ React.useEffect(() => {
+ if (template) {
+ form.reset({
+ name: template.name ?? "",
+ description: template.description ?? "",
+ category: template.category ?? "",
+ })
+ }
+ }, [template, form])
+
+ function onSubmit(input: UpdateTemplateSchema) {
+ startUpdateTransition(async () => {
+ if (!template) return
+
+ // 현재 사용자 ID (실제로는 인증에서 가져와야 함)
+ const currentUserId = "current-user-id" // TODO: 실제 사용자 ID로 교체
+
+ const { error } = await updateTemplateAction(template.slug, {
+ name: input.name,
+ description: input.description || undefined,
+ // category는 일반적으로 수정하지 않는 것이 좋지만, 필요시 포함
+ updatedBy: currentUserId,
+ })
+
+ if (error) {
+ toast.error(error)
+ return
+ }
+
+ form.reset()
+ props.onOpenChange?.(false)
+ toast.success("템플릿이 업데이트되었습니다")
+
+ // 페이지 새로고침으로 데이터 갱신
+ window.location.reload()
+ })
+ }
+
+ return (
+ <Sheet {...props}>
+ <SheetContent className="flex flex-col gap-6 sm:max-w-md">
+ <SheetHeader className="text-left">
+ <SheetTitle>템플릿 수정</SheetTitle>
+ <SheetDescription>
+ 템플릿의 기본 정보를 수정할 수 있습니다. 템플릿 내용을 수정하려면 세부 페이지에서 편집하세요.
+ </SheetDescription>
+ </SheetHeader>
+ <Form {...form}>
+ <form
+ onSubmit={form.handleSubmit(onSubmit)}
+ className="flex flex-col gap-4"
+ >
+ <FormField
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>템플릿 이름</FormLabel>
+ <FormControl>
+ <Input
+ placeholder="템플릿 이름을 입력하세요"
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="description"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>설명</FormLabel>
+ <FormControl>
+ <Textarea
+ placeholder="템플릿에 대한 설명을 입력하세요"
+ className="min-h-[80px]"
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="category"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>카테고리</FormLabel>
+ <Select onValueChange={field.onChange} value={field.value}>
+ <FormControl>
+ <SelectTrigger>
+ <SelectValue placeholder="카테고리를 선택하세요" />
+ </SelectTrigger>
+ </FormControl>
+ <SelectContent>
+ <SelectItem value="">카테고리 없음</SelectItem>
+ {TEMPLATE_CATEGORY_OPTIONS.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ {/* 현재 정보 표시 */}
+ {template && (
+ <div className="rounded-lg bg-muted p-3">
+ <h4 className="text-sm font-medium mb-2">현재 정보</h4>
+ <div className="space-y-1 text-xs text-muted-foreground">
+ <div>Slug: <code className="bg-background px-1 rounded">{template.slug}</code></div>
+ <div>버전: v{template.version}</div>
+ <div>변수: {template.variableCount}개 (필수: {template.requiredVariableCount}개)</div>
+ <div>수정일: {new Date(template.updatedAt).toLocaleString('ko-KR')}</div>
+ </div>
+ </div>
+ )}
+
+ <SheetFooter className="gap-2 pt-2 sm:space-x-0">
+ <SheetClose asChild>
+ <Button type="button" variant="outline">
+ 취소
+ </Button>
+ </SheetClose>
+ <Button disabled={isUpdatePending}>
+ {isUpdatePending && (
+ <Loader
+ className="mr-2 size-4 animate-spin"
+ aria-hidden="true"
+ />
+ )}
+ 저장
+ </Button>
+ </SheetFooter>
+ </form>
+ </Form>
+ </SheetContent>
+ </Sheet>
+ )
+} \ No newline at end of file