diff options
| author | joonhoekim <26rote@gmail.com> | 2025-08-11 09:34:40 +0000 |
|---|---|---|
| committer | joonhoekim <26rote@gmail.com> | 2025-08-11 09:34:40 +0000 |
| commit | bcd462d6e60871b86008e072f4b914138fc5c328 (patch) | |
| tree | c22876fd6c6e7e48254587848b9dff50cdb8b032 /lib/approval-template | |
| parent | cbb4c7fe0b94459162ad5e998bc05cd293e0ff96 (diff) | |
(김준회) 리치텍스트에디터 (결재템플릿을 위한 공통컴포넌트), command-menu 에러 수정, 결재 템플릿 관리, 결재선 관리, ECC RFQ+PR Item 수신시 비즈니스테이블(ProcurementRFQ) 데이터 적재, WSDL 오류 수정
Diffstat (limited to 'lib/approval-template')
10 files changed, 1491 insertions, 0 deletions
diff --git a/lib/approval-template/editor/approval-template-editor.tsx b/lib/approval-template/editor/approval-template-editor.tsx new file mode 100644 index 00000000..f23ac4bd --- /dev/null +++ b/lib/approval-template/editor/approval-template-editor.tsx @@ -0,0 +1,257 @@ +"use client" + +import * as React from "react" +import { toast } from "sonner" +import { Loader, Save, ArrowLeft } from "lucide-react" +import Link from "next/link" + +import { Button } from "@/components/ui/button" +import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card" +import { Input } from "@/components/ui/input" +import RichTextEditor from "@/components/rich-text-editor/RichTextEditor" +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" +import { Separator } from "@/components/ui/separator" +import { Badge } from "@/components/ui/badge" +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" +import { formatApprovalLine } from "@/lib/approval-line/utils/format" +import { getApprovalLineOptionsAction } from "@/lib/approval-line/service" + +import { type ApprovalTemplate } from "@/lib/approval-template/service" +import { type Editor } from "@tiptap/react" +import { updateApprovalTemplateAction } from "@/lib/approval-template/service" +import { useSession } from "next-auth/react" + +interface ApprovalTemplateEditorProps { + templateId: string + initialTemplate: ApprovalTemplate + staticVariables?: Array<{ variableName: string }> + approvalLineOptions: Array<{ id: string; name: string }> + approvalLineCategories: string[] +} + +export function ApprovalTemplateEditor({ templateId, initialTemplate, staticVariables = [], approvalLineOptions, approvalLineCategories }: ApprovalTemplateEditorProps) { + const { data: session } = useSession() + const [rte, setRte] = React.useState<Editor | null>(null) + const [template, setTemplate] = React.useState(initialTemplate) + const [isSaving, startSaving] = React.useTransition() + + // 편집기에 전달할 변수 목록 + // 템플릿(DB) 변수 + 정적(config) 변수 병합 + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const dbVariables: string[] = Array.isArray((template as any).variables) + ? // eslint-disable-next-line @typescript-eslint/no-explicit-any + (template as any).variables.map((v: any) => v.variableName) + : [] + + const mergedVariables = Array.from(new Set([...dbVariables, ...staticVariables.map((v) => v.variableName)])) + + const variableOptions = mergedVariables.map((name) => ({ label: name, html: `{{${name}}}` })) + + const [form, setForm] = React.useState({ + name: template.name, + subject: template.subject, + content: template.content, + description: template.description ?? "", + category: template.category ?? "", + approvalLineId: (template as { approvalLineId?: string | null }).approvalLineId ?? "", + }) + + const [category, setCategory] = React.useState(form.category ?? (approvalLineCategories[0] ?? "")) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const [lineOptions, setLineOptions] = React.useState(approvalLineOptions as Array<{ id: string; name: string; aplns?: any[]; category?: string | null }>) + const [isLoadingLines, setIsLoadingLines] = React.useState(false) + + React.useEffect(() => { + let active = true + const run = async () => { + setIsLoadingLines(true) + const { success, data } = await getApprovalLineOptionsAction(category || undefined) + if (active) { + setIsLoadingLines(false) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (success && data) setLineOptions(data as any) + // 카테고리 바뀌면 결재선 선택 초기화 + setForm((prev) => ({ ...prev, category, approvalLineId: "" })) + } + } + run() + return () => { + active = false + } + }, [category]) + + function handleChange(e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) { + const { name, value } = e.target + setForm((prev) => ({ ...prev, [name]: value })) + } + + function handleSave() { + startSaving(async () => { + if (!session?.user?.id) { + toast.error("로그인이 필요합니다") + return + } + + const { success, error, data } = await updateApprovalTemplateAction(templateId, { + name: form.name, + subject: form.subject, + content: form.content, + description: form.description, + category: form.category || undefined, + approvalLineId: form.approvalLineId ? form.approvalLineId : null, + updatedBy: Number(session.user.id), + }) + + if (!success || error || !data) { + toast.error(error ?? "저장에 실패했습니다") + return + } + + setTemplate(data) + toast.success("저장되었습니다") + }) + } + + return ( + <div className="flex flex-1 flex-col gap-4 p-4 md:gap-8 md:p-8"> + {/* Header */} + <div className="flex items-center gap-4"> + <Button variant="ghost" size="icon" asChild> + <Link href="/evcp/approval/template"> + <ArrowLeft className="h-4 w-4" /> + </Link> + </Button> + <div className="flex-1"> + <div className="flex items-center gap-3"> + <h1 className="text-2xl font-semibold">{template.name}</h1> + <Badge variant="outline" className="text-xs"> + 최근 수정: {new Date(template.updatedAt).toLocaleDateString("ko-KR")} + </Badge> + {template.category && ( + <Badge variant="secondary" className="text-xs">{template.category}</Badge> + )} + </div> + <p className="text-sm text-muted-foreground">{template.description || "결재 템플릿 편집"}</p> + </div> + <Button onClick={handleSave} disabled={isSaving}> + {isSaving && <Loader className="mr-2 h-4 w-4 animate-spin" />} + <Save className="mr-2 h-4 w-4" /> 저장 + </Button> + </div> + + <Separator /> + + <Tabs defaultValue="editor" className="flex-1"> + <TabsList className="grid w-full grid-cols-2"> + <TabsTrigger value="editor">편집</TabsTrigger> + <TabsTrigger value="preview">미리보기</TabsTrigger> + </TabsList> + + <TabsContent value="editor" className="mt-4 flex flex-col gap-4"> + <Card> + <CardHeader> + <CardTitle>기본 정보</CardTitle> + </CardHeader> + <CardContent className="space-y-4"> + <div className="grid grid-cols-1 md:grid-cols-2 gap-4"> + <div className="space-y-2"> + <label className="text-sm font-medium">이름</label> + <Input name="name" value={form.name} onChange={handleChange} /> + </div> + <div className="space-y-2"> + <label className="text-sm font-medium">카테고리</label> + <Select + value={category} + onValueChange={(value) => setCategory(value)} + > + <SelectTrigger> + <SelectValue placeholder="카테고리를 선택하세요" /> + </SelectTrigger> + <SelectContent> + {approvalLineCategories.map((cat) => ( + <SelectItem key={cat} value={cat}> + {cat} + </SelectItem> + ))} + </SelectContent> + </Select> + </div> + </div> + <div className="space-y-2"> + <label className="text-sm font-medium">설명 (선택)</label> + <Input name="description" value={form.description} onChange={handleChange} /> + </div> + <div className="space-y-2"> + <label className="text-sm font-medium">제목</label> + <Input name="subject" value={form.subject} onChange={handleChange} /> + </div> + <div className="space-y-2"> + <label className="text-sm font-medium">결재선</label> + <Select + value={form.approvalLineId} + onValueChange={(value) => setForm((prev) => ({ ...prev, approvalLineId: value }))} + disabled={!category || isLoadingLines} + > + <SelectTrigger> + <SelectValue placeholder={category ? (isLoadingLines ? "불러오는 중..." : "결재선을 선택하세요") : "카테고리를 먼저 선택하세요"} /> + </SelectTrigger> + <SelectContent> + {lineOptions.map((opt) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const label = opt.aplns ? `${opt.name} — ${formatApprovalLine(opt.aplns as any)}` : opt.name + return ( + <SelectItem key={opt.id} value={opt.id}> + {label} + </SelectItem> + ) + })} + </SelectContent> + </Select> + </div> + </CardContent> + </Card> + + <Card> + <CardHeader> + <CardTitle>HTML 내용</CardTitle> + <CardDescription>표, 이미지, 변수 등을 자유롭게 편집하세요.</CardDescription> + </CardHeader> + <CardContent> + {variableOptions.length > 0 && ( + <div className="mb-4 flex flex-wrap gap-2"> + {variableOptions.map((v: { label: string; html: string }) => ( + <Button + key={v.label} + variant="outline" + size="sm" + onClick={() => rte?.chain().focus().insertContent(v.html).run()} + > + {`{{${v.label}}}`} + </Button> + ))} + </div> + )} + <RichTextEditor + value={form.content} + onChange={(val) => setForm((prev) => ({ ...prev, content: val }))} + onReady={(editor) => setRte(editor)} + height="400px" + /> + </CardContent> + </Card> + </TabsContent> + + <TabsContent value="preview" className="mt-4"> + <Card> + <CardHeader> + <CardTitle>미리보기</CardTitle> + </CardHeader> + <CardContent className="border rounded-md p-4 overflow-auto bg-background"> + <div dangerouslySetInnerHTML={{ __html: form.content }} /> + </CardContent> + </Card> + </TabsContent> + </Tabs> + </div> + ) +} diff --git a/lib/approval-template/service.ts b/lib/approval-template/service.ts new file mode 100644 index 00000000..5dc989d9 --- /dev/null +++ b/lib/approval-template/service.ts @@ -0,0 +1,330 @@ +'use server'; + +import db from '@/db/db'; +import { + and, + asc, + count, + desc, + eq, + ilike, + or, +} from 'drizzle-orm'; + +import { + approvalTemplates, + approvalTemplateVariables, + approvalTemplateHistory, +} from '@/db/schema/knox/approvals'; + +import { filterColumns } from '@/lib/filter-columns'; + +// --------------------------------------------- +// Types +// --------------------------------------------- + +export type ApprovalTemplate = typeof approvalTemplates.$inferSelect; +export type ApprovalTemplateVariable = + typeof approvalTemplateVariables.$inferSelect; +export type ApprovalTemplateHistory = + typeof approvalTemplateHistory.$inferSelect; + +export interface ApprovalTemplateWithVariables extends ApprovalTemplate { + variables: ApprovalTemplateVariable[]; +} + +// --------------------------------------------- +// List & read helpers +// --------------------------------------------- + +interface ListInput { + page: number; + perPage: number; + search?: string; + filters?: Record<string, unknown>[]; + joinOperator?: 'and' | 'or'; + sort?: Array<{ id: string; desc: boolean }>; +} + +export async function getApprovalTemplateList(input: ListInput) { + const offset = (input.page - 1) * input.perPage; + + /* ------------------------------------------------------------------ + * WHERE 절 구성 + * ----------------------------------------------------------------*/ + const advancedWhere = filterColumns({ + table: approvalTemplates, + filters: input.filters, + joinOperator: input.joinOperator, + }); + + // 전역 검색 (name, subject, description, category) + let globalWhere; + if (input.search) { + const s = `%${input.search}%`; + globalWhere = or( + ilike(approvalTemplates.name, s), + ilike(approvalTemplates.subject, s), + ilike(approvalTemplates.description, s), + ilike(approvalTemplates.category, s), + ); + } + + const conditions = []; + if (advancedWhere) conditions.push(advancedWhere); + if (globalWhere) conditions.push(globalWhere); + + const where = + conditions.length === 0 + ? undefined + : conditions.length === 1 + ? conditions[0] + : and(...conditions); + + /* ------------------------------------------------------------------ + * ORDER BY 절 구성 + * ----------------------------------------------------------------*/ + let orderBy; + try { + orderBy = input.sort && input.sort.length > 0 + ? input.sort + .map((item) => { + if (!item || !item.id || typeof item.id !== 'string') return null; + if (!(item.id in approvalTemplates)) return null; + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + const col = approvalTemplates[item.id]; + return item.desc ? desc(col) : asc(col); + }) + .filter((v): v is Exclude<typeof v, null> => v !== null) + : [desc(approvalTemplates.updatedAt)]; + } catch { + orderBy = [desc(approvalTemplates.updatedAt)]; + } + + /* ------------------------------------------------------------------ + * 데이터 조회 + * ----------------------------------------------------------------*/ + const data = await db + .select() + .from(approvalTemplates) + .where(where) + .orderBy(...orderBy) + .limit(input.perPage) + .offset(offset); + + const totalResult = await db + .select({ count: count() }) + .from(approvalTemplates) + .where(where); + + const total = totalResult[0]?.count ?? 0; + const pageCount = Math.ceil(total / input.perPage); + + return { + data, + pageCount, + }; +} + +// ---------------------------------------------------- +// Get single template + variables +// ---------------------------------------------------- +export async function getApprovalTemplate(id: string): Promise<ApprovalTemplateWithVariables | null> { + const [template] = await db + .select() + .from(approvalTemplates) + .where(eq(approvalTemplates.id, id)) + .limit(1); + + if (!template) return null; + + const variables = await db + .select() + .from(approvalTemplateVariables) + .where(eq(approvalTemplateVariables.approvalTemplateId, id)) + .orderBy(approvalTemplateVariables.variableName); + + return { + ...template, + variables, + }; +} + +// ---------------------------------------------------- +// Create template +// ---------------------------------------------------- +interface CreateInput { + name: string; + subject: string; + content: string; + category?: string; + description?: string; + createdBy: number; + approvalLineId?: string | null; + variables?: Array<{ + variableName: string; + variableType: string; + defaultValue?: string; + description?: string; + }>; +} + +export async function createApprovalTemplate(data: CreateInput): Promise<ApprovalTemplateWithVariables> { + // 중복 이름 체크 (옵션) + const existing = await db + .select({ id: approvalTemplates.id }) + .from(approvalTemplates) + .where(eq(approvalTemplates.name, data.name)) + .limit(1); + + if (existing.length > 0) { + throw new Error('이미 존재하는 템플릿 이름입니다.'); + } + + const [newTemplate] = await db + .insert(approvalTemplates) + .values({ + name: data.name, + subject: data.subject, + content: data.content, + category: data.category, + description: data.description, + approvalLineId: data.approvalLineId ?? null, + createdBy: data.createdBy, + }) + .returning(); + + if (data.variables?.length) { + const variableRows = data.variables.map((v) => ({ + approvalTemplateId: newTemplate.id, + variableName: v.variableName, + variableType: v.variableType, + defaultValue: v.defaultValue, + description: v.description, + createdBy: data.createdBy, + })); + await db.insert(approvalTemplateVariables).values(variableRows); + } + + const result = await getApprovalTemplate(newTemplate.id); + if (!result) throw new Error('생성된 템플릿을 조회할 수 없습니다.'); + return result; +} + +// ---------------------------------------------------- +// Update template +// ---------------------------------------------------- +interface UpdateInput { + name?: string; + subject?: string; + content?: string; + description?: string; + category?: string; + approvalLineId?: string | null; + updatedBy: number; +} + +export async function updateApprovalTemplate(id: string, data: UpdateInput): Promise<ApprovalTemplateWithVariables> { + const existing = await getApprovalTemplate(id); + if (!existing) throw new Error('템플릿을 찾을 수 없습니다.'); + + // 버전 계산 - 현재 히스토리 카운트 + 1 + const versionResult = await db + .select({ count: count() }) + .from(approvalTemplateHistory) + .where(eq(approvalTemplateHistory.templateId, id)); + const nextVersion = Number(versionResult[0]?.count ?? 0) + 1; + + // 히스토리 저장 + await db.insert(approvalTemplateHistory).values({ + templateId: id, + version: nextVersion, + subject: existing.subject, + content: existing.content, + changeDescription: '템플릿 업데이트', + changedBy: data.updatedBy, + }); + + // 템플릿 업데이트 + await db + .update(approvalTemplates) + .set({ + name: data.name ?? existing.name, + subject: data.subject ?? existing.subject, + content: data.content ?? existing.content, + description: data.description ?? existing.description, + category: data.category ?? existing.category, + approvalLineId: data.approvalLineId === undefined ? existing.approvalLineId : data.approvalLineId, + updatedAt: new Date(), + }) + .where(eq(approvalTemplates.id, id)); + + const result = await getApprovalTemplate(id); + if (!result) throw new Error('업데이트된 템플릿을 조회할 수 없습니다.'); + return result; +} + +// ---------------------------------------------------- +// Server Actions +// ---------------------------------------------------- +export async function updateApprovalTemplateAction(id: string, data: UpdateInput) { + try { + const updated = await updateApprovalTemplate(id, data) + return { success: true, data: updated } + } catch (error) { + return { + success: false, + error: error instanceof Error ? error.message : '업데이트에 실패했습니다.' + } + } +} + +// ---------------------------------------------------- +// Duplicate template +// ---------------------------------------------------- +export async function duplicateApprovalTemplate( + id: string, + newName: string, + createdBy: number, +): Promise<{ success: boolean; error?: string; data?: ApprovalTemplate }> { + try { + const existing = await getApprovalTemplate(id) + if (!existing) return { success: false, error: '템플릿을 찾을 수 없습니다.' } + + // 새 템플릿 생성 + const duplicated = await createApprovalTemplate({ + name: newName, + subject: existing.subject, + content: existing.content, + category: existing.category ?? undefined, + description: existing.description ? `${existing.description} (복사본)` : undefined, + createdBy, + variables: existing.variables?.map((v) => ({ + variableName: v.variableName, + variableType: v.variableType, + defaultValue: v.defaultValue, + description: v.description, + })), + }) + + return { success: true, data: duplicated } + } catch (error) { + return { success: false, error: error instanceof Error ? error.message : '복제에 실패했습니다.' } + } +} + +// ---------------------------------------------------- +// Delete (soft delete X -> 실제 삭제) +// ---------------------------------------------------- +export async function deleteApprovalTemplate(id: string): Promise<{ success: boolean; error?: string }> { + try { + await db.delete(approvalTemplates).where(eq(approvalTemplates.id, id)); + return { success: true }; + } catch (error) { + return { + success: false, + error: error instanceof Error ? error.message : '삭제에 실패했습니다.', + }; + } +}
\ No newline at end of file diff --git a/lib/approval-template/table/approval-template-table-columns.tsx b/lib/approval-template/table/approval-template-table-columns.tsx new file mode 100644 index 00000000..8447c7d2 --- /dev/null +++ b/lib/approval-template/table/approval-template-table-columns.tsx @@ -0,0 +1,165 @@ +"use client" + +import * as React from 'react'; +import { type ColumnDef } from '@tanstack/react-table'; +import { MoreHorizontal, Copy, Trash, Eye } from 'lucide-react'; +import Link from 'next/link'; + +import { Checkbox } from '@/components/ui/checkbox'; +import { Button } from '@/components/ui/button'; +import { Badge } from '@/components/ui/badge'; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from '@/components/ui/dropdown-menu'; +import { formatDate } from '@/lib/utils'; +import { DataTableColumnHeaderSimple } from '@/components/data-table/data-table-column-simple-header'; +import { type ApprovalTemplate } from '@/lib/approval-template/service'; +import { type DataTableRowAction } from '@/types/table'; + +interface GetColumnsProps { + setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<ApprovalTemplate> | null>> +} + +export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<ApprovalTemplate>[] { + 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: _row }) => { + const t = _row.original; + return ( + <div className="flex flex-col gap-1"> + <span className="font-medium">{t.name}</span> + {t.description && ( + <div className="text-xs text-muted-foreground line-clamp-2">{t.description}</div> + )} + </div> + ); + }, + enableSorting: true, + enableHiding: false, + size: 220, + }, + { + 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, + }, + { + accessorKey: 'category', + header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="카테고리" />, + cell: ({ getValue }) => { + const category = getValue() as string | null; + if (!category) return <div>-</div>; + return <Badge variant="outline">{category}</Badge>; + }, + enableSorting: true, + size: 120, + }, + { + 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, + }, + { + 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/approval/template/${template.id}`}> + <Eye className="mr-2 size-4" aria-hidden="true" /> + 상세 보기 + </Link> + </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/approval-template/table/approval-template-table-toolbar-actions.tsx b/lib/approval-template/table/approval-template-table-toolbar-actions.tsx new file mode 100644 index 00000000..08aba97a --- /dev/null +++ b/lib/approval-template/table/approval-template-table-toolbar-actions.tsx @@ -0,0 +1,114 @@ +"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 ApprovalTemplate } from "@/lib/approval-template/service" +import { toast } from "sonner" +import { DeleteApprovalTemplateDialog } from "./delete-approval-template-dialog" + +interface ApprovalTemplateTableToolbarActionsProps { + table: Table<ApprovalTemplate> + onCreateTemplate: () => void +} + +export function ApprovalTemplateTableToolbarActions({ + table, + onCreateTemplate, +}: ApprovalTemplateTableToolbarActionsProps) { + 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 = [ + "이름", + "제목", + "카테고리", + "생성일", + "수정일", + ] + + const csvData = [ + headers, + ...table.getFilteredRowModel().rows.map((row) => { + const t = row.original + return [ + t.name, + t.subject, + t.category ?? "-", + new Date(t.createdAt).toLocaleDateString("ko-KR"), + new Date(t.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", + `approval_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> + + <DeleteApprovalTemplateDialog + open={showDeleteDialog} + onOpenChange={setShowDeleteDialog} + templates={selectedTemplates} + showTrigger={false} + onSuccess={() => { + table.toggleAllRowsSelected(false) + setShowDeleteDialog(false) + }} + /> + </> + )} + </div> + ) +} diff --git a/lib/approval-template/table/approval-template-table.tsx b/lib/approval-template/table/approval-template-table.tsx new file mode 100644 index 00000000..d7f0e478 --- /dev/null +++ b/lib/approval-template/table/approval-template-table.tsx @@ -0,0 +1,135 @@ +"use client"; + +import * as React from 'react'; +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 type { + DataTableAdvancedFilterField, + DataTableFilterField, + DataTableRowAction, +} from '@/types/table'; + +import { getColumns } from './approval-template-table-columns'; +import { getApprovalTemplateList } from '../service'; +import { type ApprovalTemplate } from '../service'; +import { ApprovalTemplateTableToolbarActions } from './approval-template-table-toolbar-actions'; +import { CreateApprovalTemplateSheet } from './create-approval-template-sheet'; +import { UpdateApprovalTemplateSheet } from './update-approval-template-sheet'; +import { DuplicateApprovalTemplateSheet } from './duplicate-approval-template-sheet'; +import { DeleteApprovalTemplateDialog } from './delete-approval-template-dialog'; + +interface ApprovalTemplateTableProps { + promises: Promise<[ + Awaited<ReturnType<typeof getApprovalTemplateList>>, + ]>; +} + +export function ApprovalTemplateTable({ promises }: ApprovalTemplateTableProps) { + const [{ data, pageCount }] = React.use(promises); + + const [rowAction, setRowAction] = + React.useState<DataTableRowAction<ApprovalTemplate> | null>(null); + + const [showCreateSheet, setShowCreateSheet] = React.useState(false); + + const columns = React.useMemo( + () => getColumns({ setRowAction }), + [setRowAction] + ); + + // 기본 & 고급 필터 필드 (추후 확장 가능) + const filterFields: DataTableFilterField<ApprovalTemplate>[] = []; + const advancedFilterFields: DataTableAdvancedFilterField<ApprovalTemplate>[] = [ + { + id: 'name', + label: '템플릿 이름', + type: 'text', + }, + { + id: 'subject', + label: '제목', + type: 'text', + }, + { + id: 'category', + 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'] }, + }, + getRowId: (row) => String(row.id), + shallow: false, + clearOnDefault: true, + }); + + return ( + <> + <DataTable table={table}> + <DataTableAdvancedToolbar + table={table} + filterFields={advancedFilterFields} + shallow={false} + > + <ApprovalTemplateTableToolbarActions + table={table} + onCreateTemplate={() => setShowCreateSheet(true)} + /> + </DataTableAdvancedToolbar> + </DataTable> + + {/* 새 템플릿 생성 Sheet */} + <CreateApprovalTemplateSheet + open={showCreateSheet} + onOpenChange={setShowCreateSheet} + /> + + {/* 템플릿 수정 Sheet */} + <UpdateApprovalTemplateSheet + open={rowAction?.type === "update"} + onOpenChange={() => setRowAction(null)} + template={rowAction?.type === "update" ? rowAction.row.original : null} + /> + + {/* 템플릿 복제 Sheet */} + <DuplicateApprovalTemplateSheet + open={rowAction?.type === "duplicate"} + onOpenChange={() => setRowAction(null)} + template={rowAction?.type === "duplicate" ? rowAction.row.original : null} + /> + + {/* 템플릿 삭제 Dialog */} + <DeleteApprovalTemplateDialog + 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/approval-template/table/create-approval-template-sheet.tsx b/lib/approval-template/table/create-approval-template-sheet.tsx new file mode 100644 index 00000000..7e899175 --- /dev/null +++ b/lib/approval-template/table/create-approval-template-sheet.tsx @@ -0,0 +1,174 @@ +"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 { + Sheet, + SheetClose, + SheetContent, + SheetDescription, + SheetFooter, + SheetHeader, + SheetTitle, +} from "@/components/ui/sheet" + +import { createApprovalTemplate } from "../service" + +const createSchema = z.object({ + name: z.string().min(1, "이름은 필수입니다").max(100, "100자 이하"), + subject: z.string().min(1, "제목은 필수입니다").max(200, "200자 이하"), + category: z.string().optional(), + description: z.string().optional(), +}) + +type CreateSchema = z.infer<typeof createSchema> + +interface CreateApprovalTemplateSheetProps extends React.ComponentPropsWithRef<typeof Sheet> {} + +export function CreateApprovalTemplateSheet({ ...props }: CreateApprovalTemplateSheetProps) { + const [isPending, startTransition] = React.useTransition() + const router = useRouter() + const { data: session } = useSession() + + const form = useForm<CreateSchema>({ + resolver: zodResolver(createSchema), + defaultValues: { + name: "", + subject: "", + category: undefined, + description: "", + }, + }) + + function onSubmit(values: CreateSchema) { + startTransition(async () => { + if (!session?.user?.id) { + toast.error("로그인이 필요합니다") + return + } + + const defaultContent = `<p>{{content}}</p>` + + try { + const template = await createApprovalTemplate({ + name: values.name, + subject: values.subject, + content: defaultContent, + category: values.category || undefined, + description: values.description || undefined, + createdBy: Number(session.user.id), + variables: [], + }) + + toast.success("템플릿이 생성되었습니다") + props.onOpenChange?.(false) + + router.push(`/evcp/approval/template/${template.id}`) + } catch (error) { + toast.error(error instanceof Error ? error.message : "생성에 실패했습니다") + } + }) + } + + 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="subject" + render={({ field }) => ( + <FormItem> + <FormLabel>제목</FormLabel> + <FormControl> + <Input placeholder="예: 견적 승인 요청" {...field} /> + </FormControl> + <FormMessage /> + </FormItem> + )} + /> + + <FormField + control={form.control} + name="category" + render={({ field }) => ( + <FormItem> + <FormLabel>카테고리 (선택)</FormLabel> + <FormControl> + <Input placeholder="카테고리" {...field} /> + </FormControl> + <FormDescription>카테고리를 입력하지 않으면 미분류로 저장됩니다.</FormDescription> + <FormMessage /> + </FormItem> + )} + /> + + <FormField + control={form.control} + name="description" + render={({ field }) => ( + <FormItem> + <FormLabel>설명 (선택)</FormLabel> + <FormControl> + <Input placeholder="설명" {...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={isPending}> + {isPending && <Loader className="mr-2 size-4 animate-spin" aria-hidden="true" />} + 생성 후 편집하기 + </Button> + </SheetFooter> + </form> + </Form> + </SheetContent> + </Sheet> + ) +} diff --git a/lib/approval-template/table/delete-approval-template-dialog.tsx b/lib/approval-template/table/delete-approval-template-dialog.tsx new file mode 100644 index 00000000..9fa0a078 --- /dev/null +++ b/lib/approval-template/table/delete-approval-template-dialog.tsx @@ -0,0 +1,123 @@ +"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 ApprovalTemplate } from "@/lib/approval-template/service" + +import { deleteApprovalTemplate } from "../service" + +interface DeleteApprovalTemplateDialogProps extends React.ComponentPropsWithRef<typeof Dialog> { + templates: ApprovalTemplate[] + showTrigger?: boolean + onSuccess?: () => void +} + +export function DeleteApprovalTemplateDialog({ + templates, + showTrigger = true, + onSuccess, + ...props +}: DeleteApprovalTemplateDialogProps) { + const [isDeletePending, startDeleteTransition] = React.useTransition() + + const isMultiple = templates.length > 1 + const templateName = isMultiple ? `${templates.length}개 템플릿` : templates[0]?.name + + function onDelete() { + startDeleteTransition(async () => { + if (templates.length === 0) return + + // 여러 개면 순차 삭제 (간단히 처리) + for (const t of templates) { + const result = await deleteApprovalTemplate(t.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((t) => ( + <div key={t.id} className="text-xs text-muted-foreground"> + <div className="font-medium">{t.name}</div> + <div>ID: <code className="bg-background px-1 rounded">{t.id}</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> + ) +} diff --git a/lib/approval-template/table/duplicate-approval-template-sheet.tsx b/lib/approval-template/table/duplicate-approval-template-sheet.tsx new file mode 100644 index 00000000..e49000ff --- /dev/null +++ b/lib/approval-template/table/duplicate-approval-template-sheet.tsx @@ -0,0 +1,143 @@ +"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 { Button } from "@/components/ui/button" +import { + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "@/components/ui/form" +import { Input } from "@/components/ui/input" +import { + Sheet, + SheetClose, + SheetContent, + SheetDescription, + SheetFooter, + SheetHeader, + SheetTitle, +} from "@/components/ui/sheet" + +import { type ApprovalTemplate } from "@/lib/approval-template/service" +import { duplicateApprovalTemplate } from "../service" +import { useSession } from "next-auth/react" + +const duplicateSchema = z.object({ + name: z.string().min(1, "템플릿 이름은 필수입니다").max(100, "100자 이내여야 합니다"), +}) + +type DuplicateSchema = z.infer<typeof duplicateSchema> + +interface DuplicateApprovalTemplateSheetProps extends React.ComponentPropsWithRef<typeof Sheet> { + template: ApprovalTemplate | null +} + +export function DuplicateApprovalTemplateSheet({ template, ...props }: DuplicateApprovalTemplateSheetProps) { + const [isPending, startTransition] = React.useTransition() + const router = useRouter() + const { data: session } = useSession() + + const form = useForm<DuplicateSchema>({ + resolver: zodResolver(duplicateSchema), + defaultValues: { name: "" }, + }) + + React.useEffect(() => { + if (template) { + form.reset({ name: `${template.name} (복사본)` }) + } + }, [template, form]) + + function onSubmit(values: DuplicateSchema) { + startTransition(async () => { + if (!template) return + if (!session?.user?.id) { + toast.error("로그인이 필요합니다") + return + } + + const { success, error, data } = await duplicateApprovalTemplate( + template.id, + values.name, + Number(session.user.id), + ) + + if (!success || error) { + toast.error(error ?? "복제에 실패했습니다") + return + } + + toast.success("템플릿이 복제되었습니다") + props.onOpenChange?.(false) + + // 상세 페이지로 이동 (id 기반) + if (data?.id) { + router.push(`/evcp/approval/template/${data.id}`) + } 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>ID: <code className="bg-background px-1 rounded">{template.id}</code></div> + <div>카테고리: {template.category ?? "-"}</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> + )} + /> + + <SheetFooter className="gap-2 pt-2 sm:space-x-0"> + <SheetClose asChild> + <Button type="button" variant="outline"> + 취소 + </Button> + </SheetClose> + <Button disabled={isPending}> + {isPending && <Loader className="mr-2 size-4 animate-spin" aria-hidden="true" />} + 복제하기 + </Button> + </SheetFooter> + </form> + </Form> + </SheetContent> + </Sheet> + ) +} diff --git a/lib/approval-template/table/update-approval-template-sheet.tsx b/lib/approval-template/table/update-approval-template-sheet.tsx new file mode 100644 index 00000000..05f4069c --- /dev/null +++ b/lib/approval-template/table/update-approval-template-sheet.tsx @@ -0,0 +1,23 @@ +"use client" + +import * as React from "react" +import { Sheet } from "@/components/ui/sheet" +import { type ApprovalTemplate } from "@/lib/approval-template/service" + +interface UpdateApprovalTemplateSheetProps extends React.ComponentPropsWithRef<typeof Sheet> { + template: ApprovalTemplate | null +} + +export function UpdateApprovalTemplateSheet({ template, ...props }: UpdateApprovalTemplateSheetProps) { + // 현재 프로젝트 요구사항 범위 내에서는 상세 편집 페이지 또는 별도 에디터가 준비되지 않았으므로 + // 업데이트 시트는 추후 구현합니다. (이메일 템플릿에서는 사용되지 않아 주석 처리되어 있었음) + // 이를 사용하려 할 경우 안내 문구만 표시합니다. + + return ( + <Sheet {...props}> + <div className="p-6 text-sm text-muted-foreground"> + 템플릿 편집 기능은 아직 구현되지 않았습니다. + </div> + </Sheet> + ) +} diff --git a/lib/approval-template/validations.ts b/lib/approval-template/validations.ts new file mode 100644 index 00000000..3b60e478 --- /dev/null +++ b/lib/approval-template/validations.ts @@ -0,0 +1,27 @@ +import { + createSearchParamsCache, + parseAsArrayOf, + parseAsInteger, + parseAsString, + parseAsStringEnum, +} from 'nuqs/server'; +import { z } from 'zod'; + +import { getFiltersStateParser, getSortingStateParser } from '@/lib/parsers'; +import { approvalTemplates } from '@/db/schema/knox/approvals'; + +export const SearchParamsApprovalTemplateCache = createSearchParamsCache({ + flags: parseAsArrayOf(z.enum(['advancedTable', 'floatingBar'])).withDefault([]), + page: parseAsInteger.withDefault(1), + perPage: parseAsInteger.withDefault(10), + sort: getSortingStateParser<typeof approvalTemplates>().withDefault([ + { id: 'updatedAt', desc: true }, + ]), + filters: getFiltersStateParser().withDefault([]), + joinOperator: parseAsStringEnum(['and', 'or']).withDefault('and'), + search: parseAsString.withDefault(''), +}); + +export type GetApprovalTemplateSchema = Awaited< + ReturnType<typeof SearchParamsApprovalTemplateCache.parse> +>;
\ No newline at end of file |
