"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 { Dialog, DialogTrigger, 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 { Checkbox } from "@/components/ui/checkbox"; import { Switch } from "@/components/ui/switch"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; 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 { Separator } from "@/components/ui/separator"; import { useRouter } from "next/navigation"; import { BUSINESS_UNITS } from "@/config/basicContractColumnsConfig"; import { getExistingTemplateNames } from "../service"; // ✅ 서버 액션 import // 전체 템플릿 후보 const TEMPLATE_NAME_OPTIONS = [ "준법서약 (한글)", "준법서약 (영문)", "기술자료 요구서", "비밀유지 계약서", "표준하도급기본 계약서", "GTC", "안전보건관리 약정서", "동반성장", "윤리규범 준수 서약서", "기술자료 동의서", "내국신용장 미개설 합의서", "직납자재 하도급대급등 연동제 의향서" ] as const; const templateFormSchema = z.object({ templateName: z.enum(TEMPLATE_NAME_OPTIONS, { required_error: "템플릿 이름을 선택해주세요.", }), legalReviewRequired: z.boolean().default(false), // 적용 범위 shipBuildingApplicable: z.boolean().default(false), windApplicable: z.boolean().default(false), pcApplicable: z.boolean().default(false), nbApplicable: z.boolean().default(false), rcApplicable: z.boolean().default(false), gyApplicable: z.boolean().default(false), sysApplicable: z.boolean().default(false), infraApplicable: z.boolean().default(false), file: z.instanceof(File).optional(), }) .refine((data) => { if (data.templateName !== "General GTC" && !data.file) return false; return true; }, { message: "파일을 업로드해주세요.", path: ["file"], }) .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"], }) .refine((data) => { const scopeFields = [ 'shipBuildingApplicable', 'windApplicable', 'pcApplicable', 'nbApplicable', 'rcApplicable', 'gyApplicable', 'sysApplicable', 'infraApplicable' ]; return scopeFields.some(field => data[field as keyof typeof data] === true); }, { message: "적어도 하나의 적용 범위를 선택해야 합니다.", path: ["shipBuildingApplicable"], }); type TemplateFormValues = z.infer; export function AddTemplateDialog() { 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 [availableTemplateNames, setAvailableTemplateNames] = React.useState(TEMPLATE_NAME_OPTIONS); const router = useRouter(); // 기본값 const defaultValues: Partial = { templateName: undefined, legalReviewRequired: false, shipBuildingApplicable: false, windApplicable: false, pcApplicable: false, nbApplicable: false, rcApplicable: false, gyApplicable: false, sysApplicable: false, infraApplicable: false, }; const form = useForm({ resolver: zodResolver(templateFormSchema), defaultValues, mode: "onChange", }); // 🔸 마운트 시 이미 등록된 templateName 목록 가져와서 필터링 React.useEffect(() => { let cancelled = false; (async () => { try { const usedNames = await getExistingTemplateNames(); if (cancelled) return; // 이미 있는 이름 제외 const filtered = TEMPLATE_NAME_OPTIONS.filter(name => !usedNames.includes(name)); setAvailableTemplateNames(filtered); } catch (err) { console.error("Failed to fetch existing template names", err); // 실패 시 전체 옵션 보여주거나, 오류 알려주기 } })(); return () => { cancelled = true; }; }, []); const handleFileChange = (files: File[]) => { if (files.length > 0) { const file = files[0]; setSelectedFile(file); form.setValue("file", file); } }; const handleSelectAllScopes = (checked: boolean) => { BUSINESS_UNITS.forEach(unit => { form.setValue(unit.key as keyof TemplateFormValues, checked); }); }; // 청크 업로드 설정 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/basicContract/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 { let uploadResult = null; // 📝 파일 업로드가 필요한 경우에만 업로드 진행 if (formData.file) { const fileId = uuidv4(); uploadResult = await uploadFileInChunks(formData.file, fileId); if (!uploadResult?.success) { throw new Error("파일 업로드에 실패했습니다."); } } // 📝 General GTC이고 파일이 없는 경우와 다른 경우 구분 처리 const isGeneralGTC = formData.templateName === "General GTC"; const hasFile = uploadResult && uploadResult.success; const saveResponse = await fetch('/api/upload/basicContract/complete', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ templateName: formData.templateName, revision: 1, legalReviewRequired: formData.legalReviewRequired, shipBuildingApplicable: formData.shipBuildingApplicable, windApplicable: formData.windApplicable, pcApplicable: formData.pcApplicable, nbApplicable: formData.nbApplicable, rcApplicable: formData.rcApplicable, gyApplicable: formData.gyApplicable, sysApplicable: formData.sysApplicable, infraApplicable: formData.infraApplicable, status: "ACTIVE", // 📝 파일이 있는 경우에만 fileName과 filePath 전송 ...(hasFile && { fileName: uploadResult.fileName, filePath: uploadResult.filePath, }), // 📝 파일이 없는 경우 null 전송 (스키마가 nullable이어야 함) ...(!hasFile && { fileName: null, filePath: null, }) }), next: { tags: ["basic-contract-templates"] }, }); const saveResult = await saveResponse.json(); if (!saveResult.success) { console.log(saveResult.error); 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); } const selectedScopesCount = BUSINESS_UNITS.filter(unit => form.watch(unit.key as keyof TemplateFormValues) ).length; const templateNameIsRequired = form.watch("templateName") !== "General GTC"; const isSubmitDisabled = isLoading || !form.watch("templateName") || (templateNameIsRequired && !form.watch("file")) || !BUSINESS_UNITS.some(unit => form.watch(unit.key as keyof TemplateFormValues)); return ( 새 기본계약서 템플릿 추가 템플릿 정보를 입력하고 계약서 파일을 업로드하세요. (리비전은 자동으로 1로 설정됩니다) * 표시된 항목은 필수 입력사항입니다.
{/* 기본 정보 */} 기본 정보
( 템플릿 이름 * 이미 등록되지 않은 템플릿만 표시됩니다. (리비전 1로 생성) )} />
(
법무검토 필요 법무팀 검토가 필요한 템플릿인지 설정
)} />
{/* 적용 범위 */} 적용 범위 * 이 템플릿이 적용될 사업부를 선택하세요. ({selectedScopesCount}개 선택됨)
{BUSINESS_UNITS.map((unit) => ( (
{unit.label}
)} /> ))}
{form.formState.errors.shipBuildingApplicable && (

{form.formState.errors.shipBuildingApplicable.message}

)}
{/* 파일 업로드 */} 파일 업로드 {form.watch("templateName") === "General GTC" ? "General GTC는 파일 업로드가 선택사항입니다" : "템플릿 파일을 업로드하세요"} ( 템플릿 파일 {form.watch("templateName") !== "General GTC" && ( * )} {form.watch("templateName") === "General GTC" && ( (선택사항) )} {selectedFile ? selectedFile.name : "워드 파일을 여기에 드래그하세요"} {selectedFile ? `파일 크기: ${(selectedFile.size / (1024 * 1024)).toFixed(2)} MB` : form.watch("templateName") === "General GTC" ? "또는 클릭하여 워드 파일(.doc, .docx)을 선택하세요 (선택사항, 최대 100MB)" : "또는 클릭하여 워드 파일(.doc, .docx)을 선택하세요 (최대 100MB)"} )} /> {showProgress && (
업로드 진행률 {uploadProgress}%
)}
); }