From a9575387c3a765a1a65ebc179dae16a21af6eb25 Mon Sep 17 00:00:00 2001 From: dujinkim Date: Fri, 12 Sep 2025 08:01:02 +0000 Subject: (임수민) 일반 계약 템플릿 구현 및 basic contract 필터 수정 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../add-general-contract-template-dialog.tsx | 383 +++++++++++ .../template/create-revision-dialog.tsx | 435 +++++++++++++ .../template/general-contract-template-columns.tsx | 698 +++++++++++++++++++++ .../general-contract-template-toolbar-actions.tsx | 131 ++++ .../template/general-contract-template-viewer.tsx | 234 +++++++ .../template/general-contract-template.tsx | 287 +++++++++ .../template/template-editor-wrapper.tsx | 449 +++++++++++++ .../template/update-generalContract-sheet.tsx | 314 +++++++++ 8 files changed, 2931 insertions(+) create mode 100644 lib/general-contract-template/template/add-general-contract-template-dialog.tsx create mode 100644 lib/general-contract-template/template/create-revision-dialog.tsx create mode 100644 lib/general-contract-template/template/general-contract-template-columns.tsx create mode 100644 lib/general-contract-template/template/general-contract-template-toolbar-actions.tsx create mode 100644 lib/general-contract-template/template/general-contract-template-viewer.tsx create mode 100644 lib/general-contract-template/template/general-contract-template.tsx create mode 100644 lib/general-contract-template/template/template-editor-wrapper.tsx create mode 100644 lib/general-contract-template/template/update-generalContract-sheet.tsx (limited to 'lib/general-contract-template/template') diff --git a/lib/general-contract-template/template/add-general-contract-template-dialog.tsx b/lib/general-contract-template/template/add-general-contract-template-dialog.tsx new file mode 100644 index 00000000..8862fb4b --- /dev/null +++ b/lib/general-contract-template/template/add-general-contract-template-dialog.tsx @@ -0,0 +1,383 @@ +"use client"; + +import * as React from "react"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { useForm } from "react-hook-form"; +import * as z from "zod"; +import { toast } from "sonner"; +// uuid는 단순 업로드 방식으로 변경하며 사용하지 않음 +import { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog"; +import { + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, + FormDescription, +} from "@/components/ui/form"; +import { Button } from "@/components/ui/button"; +import { Switch } from "@/components/ui/switch"; +import { Input } from "@/components/ui/input"; +import { + Dropzone, + DropzoneZone, + DropzoneUploadIcon, + DropzoneTitle, + DropzoneDescription, + DropzoneInput +} from "@/components/ui/dropzone"; +import { Progress } from "@/components/ui/progress"; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; +import { useRouter } from "next/navigation"; +import { createTemplateFromUpload } from "../actions"; + +// (불필요한 템플릿/프로젝트 로딩 로직 제거) + +const templateFormSchema = z.object({ + contractTemplateType: z.string().min(2, "계약 종류는 2자리 영문입니다.").max(2, "계약 종류는 2자리 영문입니다.").regex(/^[A-Za-z]{2}$/, "영문 2자리로 입력하세요."), + contractTemplateName: z.string().min(1, "계약 문서명을 입력하세요."), + legalReviewRequired: z.boolean().default(false), + file: z.instanceof(File, { + message: "파일을 업로드해주세요.", + }), +}) +.refine((data) => { + if (data.file && data.file.size > 100 * 1024 * 1024) return false; + return true; +}, { + message: "파일 크기는 100MB 이하여야 합니다.", + path: ["file"], +}) +.refine((data) => { + if (data.file) { + const isValidType = data.file.type === 'application/msword' || + data.file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'; + return isValidType; + } + return true; +}, { + message: "워드 파일(.doc, .docx)만 업로드 가능합니다.", + path: ["file"], +}); + +type TemplateFormValues = z.infer; + +export function AddGeneralContractTemplateDialog() { + const [open, setOpen] = React.useState(false); + const [isLoading, setIsLoading] = React.useState(false); + const [selectedFile, setSelectedFile] = React.useState(null); + const [uploadProgress, setUploadProgress] = React.useState(0); + const [showProgress, setShowProgress] = React.useState(false); + const router = useRouter(); + + // 기본값 + const defaultValues: Partial = { + contractTemplateType: "", + contractTemplateName: "", + legalReviewRequired: false, + }; + + const form = useForm({ + resolver: zodResolver(templateFormSchema), + defaultValues, + mode: "onChange", + }); + + // (불필요한 데이터 로딩 제거) + + const handleFileChange = (files: File[]) => { + if (files.length > 0) { + const file = files[0]; + setSelectedFile(file); + form.setValue("file", file); + } + }; + + // (프로젝트/템플릿 관련 핸들러 제거) + + // 청크 업로드 설정 (basic과 동일 패턴) + const CHUNK_SIZE = 1 * 1024 * 1024; + + const uploadFileInChunks = async (file: File, fileId: string) => { + const totalChunks = Math.ceil(file.size / CHUNK_SIZE); + setShowProgress(true); + setUploadProgress(0); + + for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) { + const start = chunkIndex * CHUNK_SIZE; + const end = Math.min(start + CHUNK_SIZE, file.size); + const chunk = file.slice(start, end); + + const formData = new FormData(); + formData.append('chunk', chunk); + formData.append('filename', file.name); + formData.append('chunkIndex', chunkIndex.toString()); + formData.append('totalChunks', totalChunks.toString()); + formData.append('fileId', fileId); + + const response = await fetch('/api/upload/generalContract/chunk', { + method: 'POST', + body: formData, + }); + + if (!response.ok) { + throw new Error(`청크 업로드 실패: ${response.statusText}`); + } + + const progress = Math.round(((chunkIndex + 1) / totalChunks) * 100); + setUploadProgress(progress); + + const result = await response.json(); + if (chunkIndex === totalChunks - 1) { + return result; + } + } + }; + + async function onSubmit(formData: TemplateFormValues) { + setIsLoading(true); + try { + // 파일 업로드 (청크 업로드 → 마지막 청크에서 filePath 반환) + const { v4: uuidv4 } = await import('uuid'); + const fileId = uuidv4(); + const uploadResult = await uploadFileInChunks(formData.file, fileId); + + if (!uploadResult?.success) { + throw new Error("파일 업로드에 실패했습니다."); + } + + // 업로드 완료 후 DB 저장 API 호출 (basic과 동일 플로우) + const saveResponse = await fetch('/api/upload/generalContract/complete', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + contractTemplateType: formData.contractTemplateType, + contractTemplateName: formData.contractTemplateName, + legalReviewRequired: formData.legalReviewRequired, + revision: 1, + status: 'ACTIVE', + fileName: uploadResult.fileName, + filePath: uploadResult.filePath, + }), + }); + + const saveResult = await saveResponse.json(); + if (!saveResult?.success) { + throw new Error(saveResult?.error || '템플릿 정보 저장에 실패했습니다.'); + } + + toast.success('템플릿이 성공적으로 추가되었습니다.'); + form.reset(); + setSelectedFile(null); + setOpen(false); + setShowProgress(false); + router.refresh(); + } catch (error) { + console.error("Submit error:", error); + toast.error(error instanceof Error ? error.message : "템플릿 추가 중 오류가 발생했습니다."); + } finally { + setIsLoading(false); + } + } + + React.useEffect(() => { + if (!open) { + form.reset(); + setSelectedFile(null); + setShowProgress(false); + setUploadProgress(0); + } + }, [open, form]); + + function handleDialogOpenChange(nextOpen: boolean) { + if (!nextOpen) { + form.reset(); + } + setOpen(nextOpen); + } + + // (이전 필드 watch 제거) + + const isSubmitDisabled = isLoading || + !form.watch("contractTemplateType") || + !form.watch("contractTemplateName") || + !form.watch("file"); + + return ( + + + + + + + 신규등록 - 일반계약 표준양식 + + 계약 종류, 계약 문서명, 법무 검토, 첨부파일을 입력하세요. + * 표시된 항목은 필수 입력사항입니다. + + + +
+
+ + + + 계약 종류 + + + ( + + + 계약 종류 * + + field.onChange(e.target.value.toUpperCase().slice(0, 2))} + maxLength={2} + /> + + + )} + /> + + + + + + 계약 문서명 + + + ( + + + 계약 문서명 * + + + + + )} + /> + + + + + + 법무 검토 + + + ( + +
+ 법무검토 필요 + + 법무팀 검토가 필요한 템플릿인지 설정 + +
+ + + +
+ )} + /> +
+
+ + + + 파일 업로드 + + 템플릿 파일을 업로드하세요 + + + + ( + + + 템플릿 파일 * + + + + + + + {selectedFile ? selectedFile.name : "워드 파일을 여기에 드래그하세요"} + + + {selectedFile + ? `파일 크기: ${(selectedFile.size / (1024 * 1024)).toFixed(2)} MB` + : "또는 클릭하여 워드 파일(.doc, .docx)을 선택하세요 (최대 100MB)"} + + + + + + + + )} + /> + + {showProgress && ( +
+
+ 업로드 진행률 + {uploadProgress}% +
+ +
+ )} +
+
+
+ +
+ + + + + +
+
+ ); +} \ No newline at end of file diff --git a/lib/general-contract-template/template/create-revision-dialog.tsx b/lib/general-contract-template/template/create-revision-dialog.tsx new file mode 100644 index 00000000..86939f7c --- /dev/null +++ b/lib/general-contract-template/template/create-revision-dialog.tsx @@ -0,0 +1,435 @@ +"use client"; + +import * as React from "react"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { useForm } from "react-hook-form"; +import * as z from "zod"; +import { toast } from "sonner"; +import { v4 as uuidv4 } from 'uuid'; +import { FileText, Loader, Copy } from "lucide-react"; +import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog"; +import { + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, + FormDescription, +} from "@/components/ui/form"; +import { Input } from "@/components/ui/input"; +import { Button } from "@/components/ui/button"; +import { Switch } from "@/components/ui/switch"; +import { + Dropzone, + DropzoneZone, + DropzoneUploadIcon, + DropzoneTitle, + DropzoneDescription, + DropzoneInput +} from "@/components/ui/dropzone"; +import { Progress } from "@/components/ui/progress"; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; +import { Badge } from "@/components/ui/badge"; +import { useRouter } from "next/navigation"; +import { GeneralContractTemplate } from "@/db/schema"; +import { createGeneralContractTemplateRevisionAction } from "../actions"; + +// 리비전 생성 스키마 정의 +const createRevisionSchema = z.object({ + contractTemplateName: z.string().min(1, "계약 문서명을 입력해주세요."), + contractTemplateType: z.string().min(1, "계약 종류를 입력해주세요."), + revision: z.number().min(1, "리비전 번호는 1 이상이어야 합니다."), + legalReviewRequired: z.boolean(), + file: z.instanceof(File).optional(), +}); + +type CreateRevisionFormValues = z.infer; + +interface CreateRevisionDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + baseTemplate: GeneralContractTemplate | null; + onSuccess?: () => void; +} + +export function CreateRevisionDialog({ + open, + onOpenChange, + baseTemplate, + onSuccess +}: CreateRevisionDialogProps) { + const router = useRouter(); + const [isLoading, setIsLoading] = React.useState(false); + const [uploadProgress, setUploadProgress] = React.useState(0); + const [suggestedRevision, setSuggestedRevision] = React.useState(1); + + // 기본 템플릿의 다음 리비전 번호 계산 + React.useEffect(() => { + if (baseTemplate) { + setSuggestedRevision(baseTemplate.revision + 1); + } + }, [baseTemplate]); + + // 기본값 설정 (기존 템플릿의 설정을 상속) + const defaultValues: Partial = React.useMemo(() => { + if (!baseTemplate) return {}; + + return { + contractTemplateName: baseTemplate.contractTemplateName, + contractTemplateType: baseTemplate.contractTemplateType, + revision: suggestedRevision, + legalReviewRequired: baseTemplate.legalReviewRequired || false, + }; + }, [baseTemplate, suggestedRevision]); + + // 폼 초기화 + const form = useForm({ + resolver: zodResolver(createRevisionSchema), + defaultValues, + mode: "onChange", + }); + + // baseTemplate이 변경될 때 폼 값 재설정 + React.useEffect(() => { + if (baseTemplate && defaultValues) { + form.reset(defaultValues); + } + }, [baseTemplate, defaultValues, form]); + + // 파일 업로드 핸들러 (basic-contract와 동일한 방식) + const uploadFileInChunks = async (file: File, fileId: string) => { + const chunkSize = 1024 * 1024; // 1MB chunks + const totalChunks = Math.ceil(file.size / chunkSize); + + for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) { + const start = chunkIndex * chunkSize; + const end = Math.min(start + chunkSize, file.size); + const chunk = file.slice(start, end); + + const formData = new FormData(); + formData.append('file', chunk); + formData.append('chunkIndex', chunkIndex.toString()); + formData.append('totalChunks', totalChunks.toString()); + formData.append('fileId', fileId); + formData.append('fileName', file.name); + + try { + const response = await fetch('/api/upload/generalContract/chunk', { + method: 'POST', + body: formData, + }); + + if (!response.ok) { + throw new Error(`청크 업로드 실패: ${response.statusText}`); + } + + // 진행률 업데이트 + const progress = Math.round(((chunkIndex + 1) / totalChunks) * 100); + setUploadProgress(progress); + + const result = await response.json(); + + // 마지막 청크인 경우 파일 경로 반환 + if (chunkIndex === totalChunks - 1) { + return result; + } + } catch (error) { + console.error(`청크 ${chunkIndex} 업로드 오류:`, error); + throw error; + } + } + }; + + async function onSubmit(formData: CreateRevisionFormValues) { + if (!baseTemplate) { + toast.error("기본 템플릿 정보가 없습니다."); + return; + } + + setIsLoading(true); + setUploadProgress(0); + + try { + let fileName = baseTemplate.fileName || ""; + let filePath = baseTemplate.filePath || ""; + + // 새 파일이 업로드된 경우 + if (formData.file) { + const fileId = uuidv4(); + const uploadResult = await uploadFileInChunks(formData.file, fileId); + + if (!uploadResult.success) { + throw new Error("파일 업로드에 실패했습니다."); + } + + fileName = uploadResult.fileName; + filePath = uploadResult.filePath; + } + + // Server Action으로 리비전 생성 + const result = await createGeneralContractTemplateRevisionAction({ + baseTemplateId: baseTemplate.id, + contractTemplateName: formData.contractTemplateName, + contractTemplateType: formData.contractTemplateType, + revision: formData.revision, + legalReviewRequired: formData.legalReviewRequired, + fileName, + filePath, + }); + + toast.success(result.message); + + onSuccess?.(); + onOpenChange(false); + form.reset(); + + // 페이지 새로고침 + window.location.reload(); + + } catch (error) { + console.error("리비전 생성 오류:", error); + toast.error("리비전 생성 중 오류가 발생했습니다."); + } finally { + setIsLoading(false); + setUploadProgress(0); + } + } + + if (!baseTemplate) return null; + + return ( + + + {/* 고정된 헤더 */} + + + + 새 리비전 생성 + + +
+
+ + {baseTemplate.contractTemplateName} + 현재 v{baseTemplate.revision} + + 새 v{suggestedRevision} +
+

+ 기존 템플릿을 기반으로 새로운 리비전을 생성합니다. + * 표시된 항목은 필수 입력사항입니다. +

+
+
+
+ + {/* 스크롤 가능한 컨텐츠 영역 */} +
+
+ + {/* 리비전 정보 */} + + + 리비전 정보 + + 새로 생성할 리비전의 번호를 설정하세요 + + + + ( + + + 리비전 번호 * + + + field.onChange(parseInt(e.target.value) || suggestedRevision)} + /> + + + 권장 리비전: {suggestedRevision} (현재 리비전보다 큰 숫자여야 합니다) + + + + )} + /> + + ( + +
+ 법무검토 필요 + + 법무팀 검토가 필요한 템플릿인지 설정 + +
+ + + +
+ )} + /> +
+
+ + {/* 기본 정보 */} + + + 기본 정보 + + 템플릿의 기본 정보를 입력하세요 + + + + ( + + 계약 문서명 * + + + + + + )} + /> + + ( + + 계약 종류 * + + + + + + )} + /> + + + + {/* 파일 업로드 */} + + + 파일 업로드 + + 새로운 파일을 업로드하거나 기존 파일을 사용할 수 있습니다. + + + + ( + + 새 파일 (선택사항) + + { + if (acceptedFiles.length > 0) { + onChange(acceptedFiles[0]); + } + }} + accept={{ + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': ['.docx'], + 'application/msword': ['.doc'], + }} + maxFiles={1} + > + + + 파일을 드래그하거나 클릭하여 업로드 + + DOCX 또는 DOC 파일만 업로드 가능합니다. + + + + + + {value && ( +
+ + {value.name} +
+ )} + {uploadProgress > 0 && uploadProgress < 100 && ( +
+ +

+ 업로드 중... {Math.round(uploadProgress)}% +

+
+ )} + +
+ )} + /> + + {baseTemplate?.fileName && ( +
+

기존 파일:

+
+ + {baseTemplate.fileName} + 기존 파일 사용 +
+
+ )} +
+
+
+ +
+ + {/* 고정된 푸터 */} + +
+ + +
+
+
+
+ ); +} diff --git a/lib/general-contract-template/template/general-contract-template-columns.tsx b/lib/general-contract-template/template/general-contract-template-columns.tsx new file mode 100644 index 00000000..e4167839 --- /dev/null +++ b/lib/general-contract-template/template/general-contract-template-columns.tsx @@ -0,0 +1,698 @@ +"use client" + +import * as React from "react" +import { type DataTableRowAction } from "@/types/table" +import { type ColumnDef } from "@tanstack/react-table" +import { Download, Ellipsis, Paperclip, CheckCircle, XCircle, Eye, Copy, GitBranch } from "lucide-react" +import { toast } from "sonner" + +import { getErrorMessage } from "@/lib/handle-error" +import { formatDate, formatDateTime } from "@/lib/utils" +import { Badge } from "@/components/ui/badge" +import { Button } from "@/components/ui/button" +import { Checkbox } from "@/components/ui/checkbox" +import { users } from "@/db/schema" +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuRadioGroup, + DropdownMenuRadioItem, + DropdownMenuSeparator, + DropdownMenuShortcut, + DropdownMenuSub, + DropdownMenuSubContent, + DropdownMenuSubTrigger, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu" +import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip" + +import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header" +import { GeneralContractTemplate } from "@/db/schema" +import { quickDownload } from "@/lib/file-download" +import { useRouter } from "next/navigation" + +interface GetColumnsProps { + setRowAction: React.Dispatch | null>> + router: ReturnType +} + +/** + * 파일 다운로드 함수 (공용 유틸리티 사용) + */ +const handleFileDownload = async (filePath: string, fileName: string) => { + try { + await quickDownload(filePath, fileName); + } catch (error) { + console.error("파일 다운로드 오류:", error); + toast.error("파일 다운로드 중 오류가 발생했습니다."); + } +}; + +/** + * tanstack table 컬럼 정의 (중첩 헤더 버전) + */ +export function getColumns({ setRowAction, router }: GetColumnsProps): ColumnDef[] { + // ---------------------------------------------------------------- + // 1) select 컬럼 (체크박스) + // ---------------------------------------------------------------- + const selectColumn: ColumnDef = { + id: "select", + header: ({ table }) => ( + table.toggleAllPageRowsSelected(!!value)} + aria-label="Select all" + className="translate-y-0.5" + /> + ), + cell: ({ row }) => ( + row.toggleSelected(!!value)} + aria-label="Select row" + className="translate-y-0.5" + /> + ), + size: 30, + minSize: 30, + maxSize: 30, + enableSorting: false, + enableHiding: false, + } + + // ---------------------------------------------------------------- + // 2) 파일 다운로드 컬럼 (아이콘) + // ---------------------------------------------------------------- + const downloadColumn: ColumnDef = { + id: "download", + header: "", + cell: ({ row }) => { + const template = row.original; + + return ( + + ); + }, + size: 30, + minSize: 30, + maxSize: 30, + enableSorting: false, + } + + // ---------------------------------------------------------------- + // 3) actions 컬럼 (Dropdown 메뉴) + // ---------------------------------------------------------------- + const actionsColumn: ColumnDef = { + id: "actions", + header: "", + enableHiding: false, + cell: function Cell({ row }) { + const [isUpdatePending, startUpdateTransition] = React.useTransition() + const template = row.original; + + const handleViewDetails = () => { + router.push(`/evcp/general-contract-template/${template.id}`); + }; + + return ( + + + + + + router.push(`/evcp/general-contract-template/${template.id}`)} + > + {/* */} + 상세보기 + + + + + setRowAction({ row, type: "create-revision" })} + > + {/* */} + 리비전 생성하기 + + + + + setRowAction({ row, type: "update" })} + > + 수정하기 + + + {template.status === 'ACTIVE' && ( + setRowAction({ row, type: "dispose" })} + > + 폐기하기 + + )} + + {template.status === 'DISPOSED' && template.disposedAt && ( + setRowAction({ row, type: "restore" })} + > + 복구하기 + + )} + + + setRowAction({ row, type: "delete" })} + > + 삭제하기 + {/* ⌘⌫ */} + + + + ) + }, + size: 30, + minSize: 30, + maxSize: 30, + } + + // ---------------------------------------------------------------- + // 4) 컬럼 정의 + // ---------------------------------------------------------------- + const basicInfoColumns: ColumnDef[] = [ + { + accessorKey: "id", + header: ({ column }) => , + cell: ({ row }) => { + // Sequential number based on table order + return ( +
+ {row.index + 1} +
+ ); + }, + size: 60, + minSize: 50, + maxSize: 80, + enableSorting: false, + }, + { + accessorKey: "status", + header: ({ column }) => , + cell: ({ row }) => { + const status = row.getValue("status") as string; + const getStatusDisplay = (status: string) => { + switch (status) { + case "ACTIVE": + return "A"; + case "DISPOSED": + return "D"; + case "INACTIVE": + return ""; // 빈 문자열로 "Null" 표현 + default: + return ""; + } + }; + return ( +
+ {getStatusDisplay(status)} +
+ ); + }, + size: 80, + minSize: 60, + maxSize: 120, + enableResizing: true, + filterFn: (row, id, value) => { + return value.includes(row.getValue(id)); + }, + }, + { + accessorKey: "contractTemplateType", + header: ({ column }) => , + cell: ({ row }) => { + const contractType = row.getValue("contractTemplateType") as string; + return ( +
+ {contractType} +
+ ); + }, + size: 100, + minSize: 80, + maxSize: 150, + enableResizing: true, + filterFn: (row, id, value) => { + return value.includes(row.getValue(id)); + }, + }, + + { + accessorKey: "contractTemplateName", + header: ({ column }) => , + cell: ({ row }) => { + const template = row.original; + + const handleClick = () => { + router.push(`/evcp/general-contract-template/${template.id}`); + }; + + return ( +
+ +
+ ); + }, + size: 250, + minSize: 200, + maxSize: 400, + enableResizing: true, + }, + { + accessorKey: "revision", + header: ({ column }) => , + cell: ({ row }) => { + const revision = row.getValue("revision") as number; + return ( +
+ {revision} +
+ ); + }, + size: 80, + minSize: 60, + maxSize: 120, + enableResizing: true, + }, + ]; + + // const scopeColumns: ColumnDef[] = [ + // { + // accessorKey: "shipBuildingApplicable", + // header: ({ column }) => , + // cell: ({ row }) => { + // const applicable = row.getValue("shipBuildingApplicable") as boolean; + // return ( + //
+ // {applicable ? ( + // + // ) : ( + // + // )} + //
+ // ); + // }, + // size: 80, + // enableResizing: true, + // }, + // { + // accessorKey: "windApplicable", + // header: ({ column }) => , + // cell: ({ row }) => { + // const applicable = row.getValue("windApplicable") as boolean; + // return ( + //
+ // {applicable ? ( + // + // ) : ( + // + // )} + //
+ // ); + // }, + // size: 60, + // enableResizing: true, + // }, + // { + // accessorKey: "pcApplicable", + // header: ({ column }) => , + // cell: ({ row }) => { + // const applicable = row.getValue("pcApplicable") as boolean; + // return ( + //
+ // {applicable ? ( + // + // ) : ( + // + // )} + //
+ // ); + // }, + // size: 50, + // enableResizing: true, + // }, + // { + // accessorKey: "nbApplicable", + // header: ({ column }) => , + // cell: ({ row }) => { + // const applicable = row.getValue("nbApplicable") as boolean; + // return ( + //
+ // {applicable ? ( + // + // ) : ( + // + // )} + //
+ // ); + // }, + // size: 50, + // enableResizing: true, + // }, + // { + // accessorKey: "rcApplicable", + // header: ({ column }) => , + // cell: ({ row }) => { + // const applicable = row.getValue("rcApplicable") as boolean; + // return ( + //
+ // {applicable ? ( + // + // ) : ( + // + // )} + //
+ // ); + // }, + // size: 50, + // enableResizing: true, + // }, + // { + // accessorKey: "gyApplicable", + // header: ({ column }) => , + // cell: ({ row }) => { + // const applicable = row.getValue("gyApplicable") as boolean; + // return ( + //
+ // {applicable ? ( + // + // ) : ( + // + // )} + //
+ // ); + // }, + // size: 50, + // enableResizing: true, + // }, + // { + // accessorKey: "sysApplicable", + // header: ({ column }) => , + // cell: ({ row }) => { + // const applicable = row.getValue("sysApplicable") as boolean; + // return ( + //
+ // {applicable ? ( + // + // ) : ( + // + // )} + //
+ // ); + // }, + // size: 60, + // enableResizing: true, + // }, + // { + // accessorKey: "infraApplicable", + // header: ({ column }) => , + // cell: ({ row }) => { + // const applicable = row.getValue("infraApplicable") as boolean; + // return ( + //
+ // {applicable ? ( + // + // ) : ( + // + // )} + //
+ // ); + // }, + // size: 60, + // enableResizing: true, + // }, + // ]; + + const fileInfoColumns: ColumnDef[] = [ + { + accessorKey: "fileName", + header: ({ column }) => , + cell: ({ row }) => { + const fileName = row.getValue("fileName") as string; + return ( +
+ + {fileName} + +
+ ); + }, + size: 200, + minSize: 150, + maxSize: 300, + enableResizing: true, + }, + ]; + + const auditColumns: ColumnDef[] = [ + { + accessorKey: "createdAt", + header: ({ column }) => , + cell: ({ row }) => { + const date = row.getValue("createdAt") as Date; + return date ? formatDateTime(date, "ko-KR") : "-"; + }, + size: 120, + minSize: 100, + maxSize: 180, + enableResizing: true, + }, + { + accessorKey: "updatedAt", + header: ({ column }) => , + cell: ({ row }) => { + const date = row.getValue("updatedAt") as Date; + return date ? formatDateTime(date, "ko-KR") : "-"; + }, + size: 120, + minSize: 100, + maxSize: 180, + enableResizing: true, + }, + { + accessorKey: "disposedAt", + header: ({ column }) => , + cell: ({ row }) => { + const date = row.getValue("disposedAt") as Date; + return date ? formatDateTime(date, "ko-KR") : "-"; + }, + size: 120, + minSize: 100, + maxSize: 180, + enableResizing: true, + }, + { + accessorKey: "restoredAt", + header: ({ column }) => , + cell: ({ row }) => { + const date = row.getValue("restoredAt") as Date; + return date ? formatDateTime(date, "ko-KR") : "-"; + }, + size: 120, + minSize: 100, + maxSize: 180, + enableResizing: true, + }, + ]; + + // ---------------------------------------------------------------- + // 5) 최종 컬럼 배열: 사용자 요구사항 순서에 맞게 재배치 + // ---------------------------------------------------------------- + return [ + selectColumn, // ㅁ* (체크박스) + { // No. + accessorKey: "id", + header: ({ column }) => , + cell: ({ row }) => { + return ( +
+ {row.index + 1} +
+ ); + }, + size: 40, + minSize: 40, + maxSize: 70, + enableSorting: false, + }, + { // 상태 + accessorKey: "status", + header: ({ column }) => , + cell: ({ row }) => { + const status = row.getValue("status") as string; + let displayStatus = ""; + if (status === "ACTIVE") displayStatus = "A"; + else if (status === "DISPOSED") displayStatus = "D"; + // INACTIVE는 빈 문자열로 "Null" 표현 + + return ( +
+ {displayStatus} +
+ ); + }, + size: 50, + minSize: 40, + maxSize: 70, + enableResizing: true, + }, + { // 계약종류 + accessorKey: "contractTemplateType", + header: ({ column }) => , + cell: ({ row }) => { + const contractType = row.getValue("contractTemplateType") as string; + return ( +
+ {contractType} +
+ ); + }, + size: 80, + minSize: 60, + maxSize: 120, + enableResizing: true, + }, + { // 계약문서명 + accessorKey: "contractTemplateName", + header: ({ column }) => , + cell: ({ row }) => { + const contractName = row.getValue("contractTemplateName") as string; + return ( +
+ {contractName} +
+ ); + }, + size: 200, + minSize: 150, + maxSize: 1000, + enableResizing: true, + }, + { // Rev. + accessorKey: "revision", + header: ({ column }) => , + cell: ({ row }) => { + const revision = row.getValue("revision") as number; + return ( +
+ {revision} +
+ ); + }, + size: 60, + minSize: 50, + maxSize: 80, + enableResizing: true, + }, + { // 법무검토 + accessorKey: "legalReviewRequired", + header: ({ column }) => , + cell: ({ row }) => { + const required = row.getValue("legalReviewRequired") as boolean; + return ( + + {required ? "필요" : "불필요"} + + ); + }, + size: 100, + minSize: 80, + maxSize: 150, + enableResizing: true, + }, + { // 최종 Update일 + accessorKey: "updatedAt", + header: ({ column }) => , + cell: ({ row }) => { + const date = row.getValue("updatedAt") as Date; + return date ? formatDate(date) : ""; + }, + size: 120, + minSize: 100, + maxSize: 180, + enableResizing: true, + }, + { // 최종 Update자 + accessorKey: "updatedByName", + header: ({ column }) => , + cell: ({ row }) => { + const updatedByName = row.getValue("updatedByName") as string | null; + return updatedByName || ""; + }, + size: 120, + minSize: 100, + maxSize: 180, + enableResizing: true, + }, + { // 폐기일자 + accessorKey: "disposedAt", + header: ({ column }) => , + cell: ({ row }) => { + const date = row.getValue("disposedAt") as Date | null; + return date ? formatDate(date) : ""; + }, + size: 120, + minSize: 100, + maxSize: 180, + enableResizing: true, + }, + { // 첨부 + accessorKey: "fileName", + header: ({ column }) => , + cell: ({ row }) => { + const template = row.original; + + return ( + + ); + }, + maxSize: 50, + enableSorting: false, + }, + actionsColumn, // 빈 컬럼 (···) + ] +} \ No newline at end of file diff --git a/lib/general-contract-template/template/general-contract-template-toolbar-actions.tsx b/lib/general-contract-template/template/general-contract-template-toolbar-actions.tsx new file mode 100644 index 00000000..03818109 --- /dev/null +++ b/lib/general-contract-template/template/general-contract-template-toolbar-actions.tsx @@ -0,0 +1,131 @@ +"use client" + +import * as React from "react" +import { useRouter } from "next/navigation" +import { Trash2, FileText } from "lucide-react" +import { toast } from "sonner" + +import { Button } from "@/components/ui/button" +import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog" +import { disposeTemplates } from "../actions" +import { AddGeneralContractTemplateDialog } from "./add-general-contract-template-dialog" + +interface GeneralContractTemplateToolbarActionsProps { + selectedRows?: any[] + onSelectionChange?: (selectedRows: any[]) => void +} + +export function GeneralContractTemplateToolbarActions({ + selectedRows = [], + onSelectionChange +}: GeneralContractTemplateToolbarActionsProps) { + const router = useRouter() + const [isModifyOpen, setIsModifyOpen] = React.useState(false) + const [isDisposeOpen, setIsDisposeOpen] = React.useState(false) + const [isContractStatusOpen, setIsContractStatusOpen] = React.useState(false) + + // 폐기 버튼 클릭 + const handleDispose = () => { + if (selectedRows.length === 0) { + toast.error("폐기할 문서를 선택해주세요.") + return + } + + setIsDisposeOpen(true) + } + + // 계약현황 버튼 클릭 + const handleContractStatus = () => { + if (selectedRows.length === 0) { + toast.error("확인할 문서를 선택해주세요.") + return + } + + if (selectedRows.length > 1) { + toast.error("한 번에 하나의 문서만 확인할 수 있습니다.") + return + } + + // 일반계약관리 페이지로 이동 + router.push(`/evcp/general-contracts`) + } + + // 실제 폐기 처리 + const handleConfirmDispose = async () => { + try { + // 폐기할 템플릿 ID들 추출 + const templateIds = selectedRows.map(row => row.id) + + // Server Action 호출 + const result = await disposeTemplates(templateIds) + + toast.success(result.message) + setIsDisposeOpen(false) + + // 페이지 새로고침 또는 테이블 업데이트 + window.location.reload() + } catch (error) { + console.error('폐기 처리 오류:', error) + toast.error(error instanceof Error ? error.message : "폐기 처리 중 오류가 발생했습니다.") + } + } + + return ( + <> +
+ {/* 신규등록: 다이얼로그 사용 */} + + + {/* 계약현황 버튼 */} + + + {/* 폐기 버튼 */} + +
+ + {/* 폐기 확인 다이얼로그 */} + + + + 문서 폐기 확인 + + 선택된 {selectedRows.length}개의 문서를 폐기하시겠습니까? +
+ 폐기된 문서는 복구할 수 없습니다. +
+
+
+ + +
+
+
+ + ) +} diff --git a/lib/general-contract-template/template/general-contract-template-viewer.tsx b/lib/general-contract-template/template/general-contract-template-viewer.tsx new file mode 100644 index 00000000..25562256 --- /dev/null +++ b/lib/general-contract-template/template/general-contract-template-viewer.tsx @@ -0,0 +1,234 @@ +"use client"; + +import React, { + useState, + useEffect, + useRef, + SetStateAction, + Dispatch, +} from "react"; +import { WebViewerInstance } from "@pdftron/webviewer"; +import { Loader2 } from "lucide-react"; +import { toast } from "sonner"; + +interface GeneralContractTemplateViewerProps { + templateId?: number; + filePath?: string; + instance: WebViewerInstance | null; + setInstance: Dispatch>; +} + +export function GeneralContractTemplateViewer({ + templateId, + filePath, + instance, + setInstance, +}: GeneralContractTemplateViewerProps) { + const [fileLoading, setFileLoading] = useState(true); + const viewer = useRef(null); + const initialized = useRef(false); + const isCancelled = useRef(false); + + // WebViewer 초기화 (기존 SignViewer와 완전히 동일) + useEffect(() => { + if (!initialized.current && viewer.current) { + initialized.current = true; + isCancelled.current = false; + + requestAnimationFrame(() => { + if (viewer.current) { + import("@pdftron/webviewer").then(({ default: WebViewer }) => { + if (isCancelled.current) { + console.log("📛 WebViewer 초기화 취소됨"); + return; + } + + // viewerElement이 확실히 존재함을 확인 + const viewerElement = viewer.current; + if (!viewerElement) return; + + WebViewer( + { + path: "/pdftronWeb", + licenseKey: process.env.NEXT_PUBLIC_PDFTRON_WEBVIEW_KEY, + fullAPI: true, + // 한글 입력 지원을 위한 설정 + enableOfficeEditing: true, // Office 편집 모드에서 IME 지원 필요 + l: "ko", // 한국어 로케일 설정 + }, + viewerElement + ).then((instance: WebViewerInstance) => { + setInstance(instance); + setFileLoading(false); + + try { + const { disableElements, enableElements, setToolbarGroup } = instance.UI; + + // 편집에 필요한 요소들 활성화 + enableElements([ + "toolbarGroup-Edit", + "toolbarGroup-Insert", + "textSelectButton", + "panToolButton" + ]); + + // 불필요한 요소들만 비활성화 + disableElements([ + "toolbarGroup-Annotate", // 주석 도구 + "toolbarGroup-Shapes", // 도형 도구 + "toolbarGroup-Forms", // 폼 도구 + "signatureToolButton", // 서명 도구 + "stampToolButton", // 스탬프 도구 + "rubberStampToolButton", // 러버스탬프 도구 + "freeHandToolButton", // 자유 그리기 + "stickyToolButton", // 스티키 노트 + "calloutToolButton", // 콜아웃 + ]); + + // 편집 툴바 설정 + setToolbarGroup("toolbarGroup-Edit"); + + // 한글 입력 지원을 위한 추가 설정 + const iframeWindow = instance.UI.iframeWindow; + if (iframeWindow && iframeWindow.document) { + // IME 지원 활성화 + const documentBody = iframeWindow.document.body; + if (documentBody) { + documentBody.style.imeMode = 'active'; + documentBody.setAttribute('lang', 'ko-KR'); + } + + // 키보드 이벤트 리스너 추가 (한글 입력 감지) + iframeWindow.document.addEventListener('compositionstart', (e) => { + console.log('🇰🇷 한글 입력 시작'); + }); + + iframeWindow.document.addEventListener('compositionend', (e) => { + console.log('🇰🇷 한글 입력 완료:', e.data); + }); + } + + console.log("📝 WebViewer 한글 지원 초기화 완료"); + } catch (uiError) { + console.warn("⚠️ UI 설정 중 오류 (무시됨):", uiError); + } + }).catch((error) => { + console.error("❌ WebViewer 초기화 실패:", error); + setFileLoading(false); + toast.error("뷰어 초기화에 실패했습니다."); + }); + }); + } + }); + } + + return () => { + if (instance) { + instance.UI.dispose(); + } + isCancelled.current = true; + setTimeout(() => cleanupHtmlStyle(), 500); + }; + }, []); + + // 문서 로드 (기존 SignViewer와 동일) + useEffect(() => { + if (!instance || !filePath) return; + + loadDocument(instance, filePath); + }, [instance, filePath]); + + // 한글 지원 Office 문서 로드 + const loadDocument = async (instance: WebViewerInstance, documentPath: string) => { + setFileLoading(true); + try { + // 절대 URL로 변환 + const fullPath = documentPath.startsWith('http') + ? documentPath + : `${window.location.origin}${documentPath}`; + + // 파일명 추출 + const fileName = documentPath.split('/').pop() || 'document.docx'; + + console.log("📄 한글 지원 Office 문서 로드 시작:", fullPath); + console.log("📎 파일명:", fileName); + + // PDFTron 공식 방법: instance.UI.loadDocument() + 한글 지원 옵션 + await instance.UI.loadDocument(fullPath, { + filename: fileName, + enableOfficeEditing: true, + // 한글 입력 지원을 위한 추가 옵션 + officeOptions: { + locale: 'ko-KR', + enableIME: true, + } + }); + + // 문서 로드 후 한글 입력 환경 설정 + setTimeout(() => { + try { + const iframeWindow = instance.UI.iframeWindow; + if (iframeWindow && iframeWindow.document) { + // Office 편집기 컨테이너 찾기 + const officeContainer = iframeWindow.document.querySelector('[data-office-editor]') || + iframeWindow.document.querySelector('.office-editor') || + iframeWindow.document.body; + + if (officeContainer) { + // 한글 입력 최적화 설정 + officeContainer.style.imeMode = 'active'; + officeContainer.setAttribute('lang', 'ko-KR'); + officeContainer.setAttribute('inputmode', 'text'); + + console.log("🇰🇷 한글 입력 환경 설정 완료"); + } + } + } catch (setupError) { + console.warn("⚠️ 한글 입력 환경 설정 실패:", setupError); + } + }, 1000); + + console.log("✅ 한글 지원 Office 편집 모드로 문서 로드 완료"); + toast.success("Office 편집 모드가 활성화되었습니다.", { + description: "한글 입력이 안 될 경우 외부에서 작성 후 복사-붙여넣기를 사용하세요." + }); + + } catch (err) { + console.error("❌ Office 문서 로딩 중 오류:", err); + toast.error(`Office 문서 로드 실패: ${err instanceof Error ? err.message : '알 수 없는 오류'}`); + } finally { + setFileLoading(false); + } + }; + + // 기존 SignViewer와 동일한 렌더링 (확대 문제 해결) + return ( +
+
+ {fileLoading && ( +
+ +

문서 로딩 중...

+
+ )} +
+
+ ); +} + +// WebViewer 정리 함수 (기존과 동일) +const cleanupHtmlStyle = () => { + // iframe 스타일 정리 (WebViewer가 추가한 스타일) + const elements = document.querySelectorAll('.Document_container'); + elements.forEach((elem) => { + elem.remove(); + }); +}; \ No newline at end of file diff --git a/lib/general-contract-template/template/general-contract-template.tsx b/lib/general-contract-template/template/general-contract-template.tsx new file mode 100644 index 00000000..f66e8cf9 --- /dev/null +++ b/lib/general-contract-template/template/general-contract-template.tsx @@ -0,0 +1,287 @@ +"use client"; + +import * as React from "react"; +import { useRouter } from "next/navigation"; +import { DataTable } from "@/components/data-table/data-table"; +import { useDataTable } from "@/hooks/use-data-table"; +import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar"; +import type { + DataTableAdvancedFilterField, + DataTableRowAction, +} from "@/types/table" +import { getContractTemplates} from "../service"; +import { getColumns } from "./general-contract-template-columns"; +import { GeneralContractTemplateToolbarActions } from "./general-contract-template-toolbar-actions"; +import { UpdateTemplateSheet } from "./update-generalContract-sheet"; +import { CreateRevisionDialog } from "./create-revision-dialog"; +import { removeTemplates } from "../service"; +import { disposeTemplates, restoreTemplates } from "../actions"; +import { toast } from "sonner"; +import { Button } from "@/components/ui/button"; +import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"; + +import { GeneralContractTemplate } from "@/db/schema"; + +interface ContractTemplateTableProps { + promises: Promise< + [ + Awaited>, + ] + > +} + +export function ContractTemplateTable({ promises }: ContractTemplateTableProps) { + const router = useRouter(); + const [rowAction, setRowAction] = + React.useState | null>(null) + const [selectedRows, setSelectedRows] = React.useState([]) + const [isDeleteDialogOpen, setIsDeleteDialogOpen] = React.useState(false) + const [isDisposeDialogOpen, setIsDisposeDialogOpen] = React.useState(false) + const [isRestoreDialogOpen, setIsRestoreDialogOpen] = React.useState(false) + const [isCreateRevisionDialogOpen, setIsCreateRevisionDialogOpen] = React.useState(false) + const [{ data, pageCount }] = + React.use(promises) + + // 컬럼 설정 - router와 setRowAction을 전달 + const columns = React.useMemo( + () => getColumns({ setRowAction, router }), + [setRowAction, router] + ) + + // config 기반으로 필터 필드 설정 + const advancedFilterFields: DataTableAdvancedFilterField[] = [ + { id: "contractTemplateName", label: "계약문서명", type: "text" }, + { + id: "status", label: "상태", type: "select", options: [ + { label: "전체", value: "ALL" }, + { label: "활성화(A)", value: "ACTIVE" }, + { label: "비활성화(Null)", value: "INACTIVE" }, + { label: "폐기(D)", value: "DISPOSED" }, + ] + }, + { id: "contractTemplateType", label: "계약종류", type: "text" }, + { id: "fileName", label: "파일명", type: "text" }, + { id: "createdAt", label: "생성일", type: "date" }, + { id: "updatedAt", label: "수정일", type: "date" }, + ]; + + const { table } = useDataTable({ + data, + columns, + pageCount, + enablePinning: true, + enableAdvancedFilter: true, + initialState: { + sorting: [{ id: "createdAt", desc: true }], + columnPinning: { right: ["actions"] }, + }, + getRowId: (originalRow) => String(originalRow.id), + shallow: false, + clearOnDefault: true, + }) + + // 선택된 행들 추적 + React.useEffect(() => { + const selectedRowModels = table.getFilteredSelectedRowModel().rows + const selectedData = selectedRowModels.map(row => row.original) + setSelectedRows(selectedData) + }, [table.getState().rowSelection]) + + // rowAction 처리 + React.useEffect(() => { + if (rowAction?.type === "delete") { + setIsDeleteDialogOpen(true) + } else if (rowAction?.type === "dispose") { + setIsDisposeDialogOpen(true) + } else if (rowAction?.type === "restore") { + setIsRestoreDialogOpen(true) + } else if (rowAction?.type === "create-revision") { + setIsCreateRevisionDialogOpen(true) + } + }, [rowAction]) + + // 삭제 확인 처리 + const handleConfirmDelete = async () => { + if (!rowAction?.row) return + + try { + const result = await removeTemplates({ ids: [rowAction.row.original.id] }) + + if (result.error) { + toast.error(result.error) + return + } + + toast.success("템플릿이 삭제되었습니다.") + setIsDeleteDialogOpen(false) + setRowAction(null) + + // 페이지 새로고침 + window.location.reload() + } catch (error) { + console.error('삭제 처리 오류:', error) + toast.error("삭제 처리 중 오류가 발생했습니다.") + } + } + + // 폐기 확인 처리 + const handleConfirmDispose = async () => { + if (!rowAction?.row) return + + try { + const result = await disposeTemplates([rowAction.row.original.id]) + + toast.success(result.message) + setIsDisposeDialogOpen(false) + setRowAction(null) + + // 페이지 새로고침 + window.location.reload() + } catch (error) { + console.error('폐기 처리 오류:', error) + toast.error("폐기 처리 중 오류가 발생했습니다.") + } + } + + // 복구 확인 처리 + const handleConfirmRestore = async () => { + if (!rowAction?.row) return + + try { + const result = await restoreTemplates([rowAction.row.original.id]) + + toast.success(result.message) + setIsRestoreDialogOpen(false) + setRowAction(null) + + // 페이지 새로고침 + window.location.reload() + } catch (error) { + console.error('복구 처리 오류:', error) + toast.error("복구 처리 중 오류가 발생했습니다.") + } + } + + return ( + <> + + + + + + + setRowAction(null)} + template={rowAction?.row.original ?? null} + /> + + {/* 삭제 확인 다이얼로그 */} + + + + 템플릿 삭제 확인 + + "{rowAction?.row?.original?.contractTemplateName}" 템플릿을 삭제하시겠습니까? +
+ 삭제된 템플릿은 복구할 수 없습니다. +
+
+
+ + +
+
+
+ + {/* 폐기 확인 다이얼로그 */} + + + + 템플릿 폐기 확인 + + "{rowAction?.row?.original?.contractTemplateName}" 템플릿을 폐기하시겠습니까? +
+ 폐기된 템플릿은 복구할 수 있습니다. +
+
+
+ + +
+
+
+ + {/* 복구 확인 다이얼로그 */} + + + + 템플릿 복구 확인 + + "{rowAction?.row?.original?.contractTemplateName}" 템플릿을 복구하시겠습니까? +
+ 복구된 템플릿은 다시 사용할 수 있습니다. +
+
+
+ + +
+
+
+ + {/* 리비전 생성 다이얼로그 */} + { + setRowAction(null) + }} + /> + + ); +} \ No newline at end of file diff --git a/lib/general-contract-template/template/template-editor-wrapper.tsx b/lib/general-contract-template/template/template-editor-wrapper.tsx new file mode 100644 index 00000000..992ed4e0 --- /dev/null +++ b/lib/general-contract-template/template/template-editor-wrapper.tsx @@ -0,0 +1,449 @@ +"use client"; + +import * as React from "react"; +import { Button } from "@/components/ui/button"; +import { toast } from "sonner"; +import { Save, RefreshCw, Type, FileText, AlertCircle } from "lucide-react"; +import type { WebViewerInstance } from "@pdftron/webviewer"; +import { Badge } from "@/components/ui/badge"; +import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"; +import { GeneralContractTemplateViewer } from "@/lib/general-contract-template/template/general-contract-template-viewer"; +import { getExistingTemplateNamesById, saveTemplateFile } from "@/lib/general-contract-template/service"; + +// 변수 패턴 감지를 위한 정규식 +const VARIABLE_PATTERN = /\{\{([^}]+)\}\}/g; + +const getVariablesForTemplate = (templateName: string): string[] => { + // 정확한 매치 먼저 확인 + if (TEMPLATE_VARIABLES_MAP[templateName as keyof typeof TEMPLATE_VARIABLES_MAP]) { + return [...TEMPLATE_VARIABLES_MAP[templateName as keyof typeof TEMPLATE_VARIABLES_MAP]]; + } + + // GTC가 포함된 경우 확인 + if (templateName.includes("GTC")) { + return [...TEMPLATE_VARIABLES_MAP["GTC"]]; + } + + // 다른 키워드들도 포함 관계로 확인 + for (const [key, variables] of Object.entries(TEMPLATE_VARIABLES_MAP)) { + if (templateName.includes(key)) { + return [...variables]; + } + } + + // 기본값 반환 (basic-contract와 동일) + return ["company_name", "company_address", "representative_name", "signature_date"]; +}; + +// 템플릿 이름별 변수 매핑 (basic-contract와 동일) +const TEMPLATE_VARIABLES_MAP = { + "준법서약 (한글)": ["company_name", "company_address", "representative_name", "signature_date"], + "준법서약 (영문)": ["company_name", "company_address", "representative_name", "signature_date"], + "기술자료 요구서": ["company_name", "company_address", "representative_name", "signature_date", 'tax_id', 'phone_number'], + "비밀유지 계약서": ["company_name", "company_address", "representative_name", "signature_date"], + "표준하도급기본 계약서": ["company_name", "company_address", "representative_name", "signature_date"], + "GTC": ["company_name", "company_address", "representative_name", "signature_date"], + "안전보건관리 약정서": ["company_name", "company_address", "representative_name", "signature_date"], + "동반성장": ["company_name", "company_address", "representative_name", "signature_date"], + "윤리규범 준수 서약서": ["company_name", "company_address", "representative_name", "signature_date"], + "기술자료 동의서": ["company_name", "company_address", "representative_name", "signature_date", 'tax_id', 'phone_number'], + "내국신용장 미개설 합의서": ["company_name", "company_address", "representative_name", "signature_date"], + "직납자재 하도급대급등 연동제 의향서": ["company_name", "company_address", "representative_name", "signature_date"] +} as const; + +// 변수별 한글 설명 매핑 (basic-contract와 동일) +const VARIABLE_DESCRIPTION_MAP = { + "company_name": "협력회사명", + "vendor_name": "협력회사명", + "company_address": "회사주소", + "address": "회사주소", + "representative_name": "대표자명", + "signature_date": "서명날짜", + "today_date": "오늘날짜", + "tax_id": "사업자등록번호", + "phone_number": "전화번호", + "phone": "전화번호", + "email": "이메일" +} as const; + +interface TemplateEditorWrapperProps { + templateId: string | number; + filePath: string | null; + fileName: string | null; + refreshAction?: () => Promise | void; +} + +export function TemplateEditorWrapper({ + templateId, + filePath, + fileName, + refreshAction +}: TemplateEditorWrapperProps) { + const [instance, setInstance] = React.useState(null); + const [isSaving, setIsSaving] = React.useState(false); + const [documentVariables, setDocumentVariables] = React.useState([]); + const [templateName, setTemplateName] = React.useState(""); + const [predefinedVariables, setPredefinedVariables] = React.useState([]); + + // 템플릿 이름 로드 및 변수 설정 + React.useEffect(() => { + const loadTemplateInfo = async () => { + try { + const name = await getExistingTemplateNamesById(Number(templateId)); + setTemplateName(name); + + // 템플릿 이름에 따른 변수 설정 + const variables = getVariablesForTemplate(name); + setPredefinedVariables([...variables]); + + console.log("🏷️ 템플릿 이름:", name); + console.log("📝 할당된 변수들:", variables); + } catch (error) { + console.error("템플릿 정보 로드 오류:", error); + // 기본 변수 설정 + setPredefinedVariables(["company_name", "company_address", "representative_name", "signature_date"]); + } + }; + + if (templateId) { + loadTemplateInfo(); + } + }, [templateId]); + + // 문서에서 변수 추출 + const extractVariablesFromDocument = async () => { + if (!instance) return; + + try { + const { documentViewer } = instance.Core; + const doc = documentViewer.getDocument(); + + if (!doc) return; + + // 문서 텍스트 추출 + const textContent = await doc.getDocumentCompletePromise().then(async () => { + const pageCount = doc.getPageCount(); + let fullText = ""; + + for (let i = 1; i <= pageCount; i++) { + try { + const pageText = await doc.loadPageText(i); + fullText += pageText + " "; + } catch (error) { + console.warn(`페이지 ${i} 텍스트 추출 실패:`, error); + } + } + + return fullText; + }); + + // 변수 패턴 매칭 + const matches = textContent.match(VARIABLE_PATTERN); + const variables = matches + ? [...new Set(matches.map(match => match.replace(/[{}]/g, '')))] + : []; + + setDocumentVariables(variables); + + if (variables.length > 0) { + console.log("🔍 발견된 변수들:", variables); + } + + } catch (error) { + console.error("변수 추출 중 오류:", error); + } + }; + + // 인스턴스가 변경될 때마다 변수 추출 + React.useEffect(() => { + if (instance) { + // 문서 로드 완료 이벤트 리스너 추가 + const { documentViewer } = instance.Core; + + const onDocumentLoaded = () => { + setTimeout(() => extractVariablesFromDocument(), 1000); + }; + + documentViewer.addEventListener("documentLoaded", onDocumentLoaded); + + return () => { + documentViewer.removeEventListener("documentLoaded", onDocumentLoaded); + }; + } + }, [instance]); + + const handleSave = async () => { + if (!instance) { + toast.error("뷰어가 준비되지 않았습니다."); + return; + } + + try { + setIsSaving(true); + const { documentViewer } = instance.Core; + const doc = documentViewer.getDocument(); + if (!doc) throw new Error("문서를 찾을 수 없습니다."); + + const data = await doc.getFileData({ + downloadType: "office", + includeAnnotations: true, + }); + + const formData = new FormData(); + formData.append( + "file", + new Blob([data], { + type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + }), + fileName ?? "document.docx" + ); + + const result = await saveTemplateFile(Number(templateId), formData); + if ((result as any)?.error) throw new Error((result as any).error); + toast.success("템플릿이 성공적으로 저장되었습니다."); + + // 변수 재추출 + await extractVariablesFromDocument(); + + if (refreshAction) await refreshAction(); + } catch (err) { + console.error(err); + toast.error(err instanceof Error ? err.message : "저장 중 오류가 발생했습니다."); + } finally { + setIsSaving(false); + } + }; + + // 변수 삽입 함수 (한글 입력 제한 고려) + const insertVariable = async (variableName: string) => { + if (!instance) { + toast.error("뷰어가 준비되지 않았습니다."); + return; + } + + try { + const textToInsert = `{{${variableName}}}`; + + // 1단계: 클립보드 API 시도 + if (navigator.clipboard && navigator.clipboard.writeText) { + try { + await navigator.clipboard.writeText(textToInsert); + toast.success(`변수 "${textToInsert}"가 클립보드에 복사되었습니다.`, { + description: "문서에서 원하는 위치에 Ctrl+V로 붙여넣기 하세요." + }); + return; + } catch (clipboardError) { + console.warn("클립보드 API 사용 실패:", clipboardError); + } + } + + // 2단계: Office 편집기에 직접 삽입 시도 (실험적) + try { + const { documentViewer } = instance.Core; + const doc = documentViewer.getDocument(); + + if (doc && typeof doc.getOfficeEditor === 'function') { + const officeEditor = doc.getOfficeEditor(); + if (officeEditor && typeof (officeEditor as any).insertText === 'function') { + await (officeEditor as any).insertText(textToInsert); + toast.success(`변수 "${textToInsert}"가 문서에 삽입되었습니다.`); + return; + } + } + } catch (insertError) { + console.warn("직접 삽입 실패:", insertError); + } + + // 3단계: 임시 텍스트 영역을 통한 복사 (대안) + try { + const textArea = document.createElement('textarea'); + textArea.value = textToInsert; + textArea.style.position = 'fixed'; + textArea.style.left = '-9999px'; + textArea.style.top = '-9999px'; + document.body.appendChild(textArea); + textArea.focus(); + textArea.select(); + + const successful = document.execCommand('copy'); + document.body.removeChild(textArea); + + if (successful) { + toast.success(`변수 "${textToInsert}"가 클립보드에 복사되었습니다.`, { + description: "문서에서 원하는 위치에 Ctrl+V로 붙여넣기 하세요." + }); + } else { + throw new Error("복사 명령 실행 실패"); + } + } catch (fallbackError) { + console.error("모든 복사 방법 실패:", fallbackError); + toast.error("변수 복사에 실패했습니다. 수동으로 입력해주세요."); + } + } catch (error) { + console.error("변수 삽입 실패:", error); + toast.error("변수 삽입에 실패했습니다."); + } + }; + + if (!filePath || !fileName) { + return ( +
+ 첨부파일이 없습니다. +
+ ); + } + + // 문서 새로고침 + const handleRefresh = () => { + window.location.reload(); + }; + + return ( +
+ {/* 상단 도구 모음 */} +
+
+
+ + + +
+ +
+ + + {fileName} + + {templateName && ( + + + {templateName} + + )} + {documentVariables.length > 0 && ( + + + 변수 {documentVariables.length}개 + + )} +
+
+ + {/* 변수 도구 */} + {(documentVariables.length > 0 || predefinedVariables.length > 0) && ( +
+
+

+ + 변수 관리 + {templateName && ( + + ({templateName}) + + )} +

+
+ +
+ {/* 발견된 변수들 */} + {documentVariables.length > 0 && ( +
+

문서에서 발견된 변수:

+
+ {documentVariables.map((variable, index) => ( + + {`{{${variable}}}`} + + ))} +
+
+ )} + + {/* 템플릿별 미리 정의된 변수들 */} + {predefinedVariables.length > 0 && ( +
+

+ {templateName ? `${templateName}에 권장되는 변수` : "자주 사용하는 변수"} (클릭하여 복사): +

+ +
+ {predefinedVariables.map((variable, index) => ( + + + + + +

{VARIABLE_DESCRIPTION_MAP[variable as keyof typeof VARIABLE_DESCRIPTION_MAP] || variable}

+
+
+ ))} +
+
+
+ )} +
+
+ )} +
+ + {/* 뷰어 영역 (확대 문제 해결을 위한 컨테이너 격리) */} +
+
+ +
+
+ + {/* 하단 안내 (한글 입력 팁 포함) */} +
+
+
+ + {'{{변수명}}'} 형식으로 변수를 삽입하면 계약서 생성 시 실제 값으로 치환됩니다. +
+
+ + 한글 입력 제한시 외부 에디터에서 작성 후 복사-붙여넣기를 사용하세요. +
+
+
+
+ ); +} + + diff --git a/lib/general-contract-template/template/update-generalContract-sheet.tsx b/lib/general-contract-template/template/update-generalContract-sheet.tsx new file mode 100644 index 00000000..9949d127 --- /dev/null +++ b/lib/general-contract-template/template/update-generalContract-sheet.tsx @@ -0,0 +1,314 @@ +"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 * as z from "zod" + +import { Button } from "@/components/ui/button" +import { Switch } from "@/components/ui/switch" +import { + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, + FormDescription, +} from "@/components/ui/form" +import { + Sheet, + SheetClose, + SheetContent, + SheetDescription, + SheetFooter, + SheetHeader, + SheetTitle, +} from "@/components/ui/sheet" +import { + Dropzone, + DropzoneZone, + DropzoneUploadIcon, + DropzoneTitle, + DropzoneDescription, + DropzoneInput +} from "@/components/ui/dropzone" +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" +import { Input } from "@/components/ui/input" +import { updateTemplate } from "../service" +import { GeneralContractTemplate } from "@/db/schema" + +// 업데이트 스키마: 계약종류, 계약문서명, 법무검토, 파일(선택) +export const updateTemplateSchema = z.object({ + contractTemplateType: z + .string() + .min(2, "계약 종류는 2자리 영문입니다.") + .max(2, "계약 종류는 2자리 영문입니다.") + .regex(/^[A-Za-z]{2}$/, "영문 2자리로 입력하세요."), + contractTemplateName: z.string().min(1, "계약 문서명을 입력하세요."), + legalReviewRequired: z.boolean(), + file: z + .instanceof(File, { message: "파일을 업로드해주세요." }) + .refine((file) => file.size <= 100 * 1024 * 1024, { + message: "파일 크기는 100MB 이하여야 합니다.", + }) + .refine( + (file) => + file.type === 'application/msword' || + file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + { message: "워드 파일(.doc, .docx)만 업로드 가능합니다." } + ) + .optional(), +}); + +export type UpdateTemplateSchema = z.infer + +interface UpdateTemplateSheetProps + extends React.ComponentPropsWithRef { + template: GeneralContractTemplate | null + onSuccess?: () => void +} + +export function UpdateTemplateSheet({ template, onSuccess, ...props }: UpdateTemplateSheetProps) { + const [isUpdatePending, startUpdateTransition] = React.useTransition() + const [selectedFile, setSelectedFile] = React.useState(null) + + const form = useForm({ + resolver: zodResolver(updateTemplateSchema), + defaultValues: { + contractTemplateType: template?.contractTemplateType ?? "", + contractTemplateName: template?.contractTemplateName ?? "", + legalReviewRequired: template?.legalReviewRequired ?? false, + }, + mode: "onChange" + }) + + // 파일 선택 핸들러 + const handleFileChange = (files: File[]) => { + if (files.length > 0) { + const file = files[0]; + setSelectedFile(file); + form.setValue("file", file); + } + }; + + // 템플릿 변경 시 폼 값 업데이트 + React.useEffect(() => { + if (template) { + form.reset({ + contractTemplateType: template.contractTemplateType ?? "", + contractTemplateName: template.contractTemplateName ?? "", + legalReviewRequired: template.legalReviewRequired ?? false, + }); + } + }, [template, form]); + + function onSubmit(input: UpdateTemplateSchema) { + startUpdateTransition(async () => { + if (!template) return + + // FormData 객체 생성하여 파일과 데이터를 함께 전송 + const formData = new FormData(); + formData.append("contractTemplateType", input.contractTemplateType); + formData.append("contractTemplateName", input.contractTemplateName); + formData.append("legalReviewRequired", input.legalReviewRequired.toString()); + // basic-contract와 동일하게 리비전은 서버에서 증가 처리 + + if (input.file) { + formData.append("file", input.file); + } + + try { + // 서비스 함수 호출 + const { error } = await updateTemplate({ + id: template.id, + formData, + }); + + if (error) { + toast.error(error); + return; + } + + form.reset(); + setSelectedFile(null); + props.onOpenChange?.(false); + toast.success("일반계약 템플릿이 성공적으로 업데이트되었습니다."); + onSuccess?.(); + } catch (error) { + console.error("Update error:", error); + toast.error("일반계약 템플릿 업데이트 중 오류가 발생했습니다."); + } + }); + } + + if (!template) return null; + + return ( + + + {/* 고정된 헤더 */} + + 일반계약 템플릿 수정 + 계약 기본정보를 수정하고 파일을 교체할 수 있습니다 + + + {/* 스크롤 가능한 컨텐츠 영역 */} +
+
+ + {/* 1. 계약 종류 */} + + + 계약 종류 + + + ( + + 계약 종류 + field.onChange(e.target.value.toUpperCase().slice(0, 2))} + maxLength={2} + /> + + + )} + /> + + + + {/* 2. 계약 문서명 */} + + + 계약 문서명 + + + ( + + 계약 문서명 + + + + )} + /> + + + + {/* 3. 법무 검토 */} + + + 법무 검토 + + + ( + +
+ 법무검토 필요 + 법무팀 검토가 필요한 템플릿인지 설정 +
+ + + +
+ )} + /> +
+
+ + {/* 4. 파일 업데이트 */} + + + 파일 업데이트 + + 새로운 템플릿 파일을 업로드하세요 + + + + ( + + 새 템플릿 파일 (선택사항) + + + + + + {selectedFile + ? selectedFile.name + : "새 워드 파일을 드래그하세요"} + + + {selectedFile + ? `파일 크기: ${(selectedFile.size / (1024 * 1024)).toFixed(2)} MB` + : "또는 클릭하여 워드 파일(.doc, .docx)을 선택하세요 (최대 100MB)"} + + + + + + + 파일을 업로드하지 않으면 기존 파일이 유지됩니다 + + + + )} + /> + + +
+ +
+ + {/* 고정된 푸터 */} + + + + + + +
+
+ ) +} \ No newline at end of file -- cgit v1.2.3