diff options
Diffstat (limited to 'lib/general-contract-template/template')
8 files changed, 2931 insertions, 0 deletions
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<typeof templateFormSchema>; + +export function AddGeneralContractTemplateDialog() { + const [open, setOpen] = React.useState(false); + const [isLoading, setIsLoading] = React.useState(false); + const [selectedFile, setSelectedFile] = React.useState<File | null>(null); + const [uploadProgress, setUploadProgress] = React.useState(0); + const [showProgress, setShowProgress] = React.useState(false); + const router = useRouter(); + + // 기본값 + const defaultValues: Partial<TemplateFormValues> = { + contractTemplateType: "", + contractTemplateName: "", + legalReviewRequired: false, + }; + + const form = useForm<TemplateFormValues>({ + 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 ( + <Dialog open={open} onOpenChange={handleDialogOpenChange}> + <DialogTrigger asChild> + <Button variant="default" size="sm"> + 신규등록 + </Button> + </DialogTrigger> + <DialogContent className="sm:max-w-[600px] h-[90vh] flex flex-col p-0"> + <DialogHeader className="p-6 pb-4 border-b"> + <DialogTitle>신규등록 - 일반계약 표준양식</DialogTitle> + <DialogDescription> + 계약 종류, 계약 문서명, 법무 검토, 첨부파일을 입력하세요. + <span className="text-red-500 mt-1 block text-sm">* 표시된 항목은 필수 입력사항입니다.</span> + </DialogDescription> + </DialogHeader> + + <div className="flex-1 overflow-y-auto px-6"> + <Form {...form}> + <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6 py-4"> + <Card> + <CardHeader> + <CardTitle className="text-lg">계약 종류</CardTitle> + </CardHeader> + <CardContent> + <FormField + control={form.control} + name="contractTemplateType" + render={({ field }) => ( + <FormItem> + <FormLabel> + 계약 종류 <span className="text-red-500">*</span> + </FormLabel> + <Input + placeholder="2자리 영문 (예: LO)" + value={field.value} + onChange={(e) => field.onChange(e.target.value.toUpperCase().slice(0, 2))} + maxLength={2} + /> + <FormMessage /> + </FormItem> + )} + /> + </CardContent> + </Card> + + <Card> + <CardHeader> + <CardTitle className="text-lg">계약 문서명</CardTitle> + </CardHeader> + <CardContent> + <FormField + control={form.control} + name="contractTemplateName" + render={({ field }) => ( + <FormItem> + <FormLabel> + 계약 문서명 <span className="text-red-500">*</span> + </FormLabel> + <Input + placeholder="계약문서명을 입력하세요" + value={field.value} + onChange={field.onChange} + /> + <FormMessage /> + </FormItem> + )} + /> + </CardContent> + </Card> + + <Card> + <CardHeader> + <CardTitle className="text-lg">법무 검토</CardTitle> + </CardHeader> + <CardContent> + <FormField + control={form.control} + name="legalReviewRequired" + render={({ field }) => ( + <FormItem className="flex flex-row items-center justify-between rounded-lg border p-3 shadow-sm"> + <div className="space-y-0.5"> + <FormLabel>법무검토 필요</FormLabel> + <FormDescription> + 법무팀 검토가 필요한 템플릿인지 설정 + </FormDescription> + </div> + <FormControl> + <Switch + checked={field.value} + onCheckedChange={field.onChange} + /> + </FormControl> + </FormItem> + )} + /> + </CardContent> + </Card> + + <Card> + <CardHeader> + <CardTitle className="text-lg">파일 업로드</CardTitle> + <CardDescription> + 템플릿 파일을 업로드하세요 + </CardDescription> + </CardHeader> + <CardContent> + <FormField + control={form.control} + name="file" + render={() => ( + <FormItem> + <FormLabel> + 템플릿 파일 <span className="text-red-500">*</span> + </FormLabel> + <FormControl> + <Dropzone + onDrop={handleFileChange} + accept={{ + 'application/msword': ['.doc'], + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': ['.docx'] + }} + > + <DropzoneZone> + <DropzoneUploadIcon className="h-10 w-10 text-muted-foreground" /> + <DropzoneTitle> + {selectedFile ? selectedFile.name : "워드 파일을 여기에 드래그하세요"} + </DropzoneTitle> + <DropzoneDescription> + {selectedFile + ? `파일 크기: ${(selectedFile.size / (1024 * 1024)).toFixed(2)} MB` + : "또는 클릭하여 워드 파일(.doc, .docx)을 선택하세요 (최대 100MB)"} + </DropzoneDescription> + <DropzoneInput /> + </DropzoneZone> + </Dropzone> + </FormControl> + <FormMessage /> + </FormItem> + )} + /> + + {showProgress && ( + <div className="space-y-2 mt-4"> + <div className="flex justify-between text-sm"> + <span>업로드 진행률</span> + <span>{uploadProgress}%</span> + </div> + <Progress value={uploadProgress} /> + </div> + )} + </CardContent> + </Card> + </form> + </Form> + </div> + + <DialogFooter className="p-6 pt-4 border-t"> + <Button + type="button" + variant="outline" + onClick={() => setOpen(false)} + disabled={isLoading} + > + 취소 + </Button> + <Button + type="button" + onClick={form.handleSubmit(onSubmit)} + disabled={isSubmitDisabled} + > + {isLoading ? "처리 중..." : "추가"} + </Button> + </DialogFooter> + </DialogContent> + </Dialog> + ); +}
\ 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<typeof createRevisionSchema>; + +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<number>(1); + + // 기본 템플릿의 다음 리비전 번호 계산 + React.useEffect(() => { + if (baseTemplate) { + setSuggestedRevision(baseTemplate.revision + 1); + } + }, [baseTemplate]); + + // 기본값 설정 (기존 템플릿의 설정을 상속) + const defaultValues: Partial<CreateRevisionFormValues> = React.useMemo(() => { + if (!baseTemplate) return {}; + + return { + contractTemplateName: baseTemplate.contractTemplateName, + contractTemplateType: baseTemplate.contractTemplateType, + revision: suggestedRevision, + legalReviewRequired: baseTemplate.legalReviewRequired || false, + }; + }, [baseTemplate, suggestedRevision]); + + // 폼 초기화 + const form = useForm<CreateRevisionFormValues>({ + 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 ( + <Dialog open={open} onOpenChange={onOpenChange}> + <DialogContent className="sm:max-w-[600px] h-[90vh] flex flex-col p-0"> + {/* 고정된 헤더 */} + <DialogHeader className="p-6 pb-4 border-b"> + <DialogTitle className="flex items-center gap-2"> + <Copy className="h-5 w-5" /> + 새 리비전 생성 + </DialogTitle> + <DialogDescription> + <div className="space-y-2"> + <div className="flex items-center gap-2"> + <FileText className="h-4 w-4" /> + <span className="font-medium">{baseTemplate.contractTemplateName}</span> + <Badge variant="outline">현재 v{baseTemplate.revision}</Badge> + <span>→</span> + <Badge variant="default">새 v{suggestedRevision}</Badge> + </div> + <p className="text-sm"> + 기존 템플릿을 기반으로 새로운 리비전을 생성합니다. + <span className="text-red-500 mt-1 block">* 표시된 항목은 필수 입력사항입니다.</span> + </p> + </div> + </DialogDescription> + </DialogHeader> + + {/* 스크롤 가능한 컨텐츠 영역 */} + <div className="flex-1 overflow-y-auto px-6"> + <Form {...form}> + <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6 py-4"> + {/* 리비전 정보 */} + <Card> + <CardHeader> + <CardTitle className="text-lg">리비전 정보</CardTitle> + <CardDescription> + 새로 생성할 리비전의 번호를 설정하세요 + </CardDescription> + </CardHeader> + <CardContent className="space-y-4"> + <FormField + control={form.control} + name="revision" + render={({ field }) => ( + <FormItem> + <FormLabel> + 리비전 번호 <span className="text-red-500">*</span> + </FormLabel> + <FormControl> + <Input + type="number" + min={suggestedRevision} + {...field} + onChange={(e) => field.onChange(parseInt(e.target.value) || suggestedRevision)} + /> + </FormControl> + <FormDescription> + 권장 리비전: {suggestedRevision} (현재 리비전보다 큰 숫자여야 합니다) + </FormDescription> + <FormMessage /> + </FormItem> + )} + /> + + <FormField + control={form.control} + name="legalReviewRequired" + render={({ field }) => ( + <FormItem className="flex flex-row items-center justify-between rounded-lg border p-3 shadow-sm"> + <div className="space-y-0.5"> + <FormLabel>법무검토 필요</FormLabel> + <FormDescription> + 법무팀 검토가 필요한 템플릿인지 설정 + </FormDescription> + </div> + <FormControl> + <Switch + checked={field.value} + onCheckedChange={field.onChange} + /> + </FormControl> + </FormItem> + )} + /> + </CardContent> + </Card> + + {/* 기본 정보 */} + <Card> + <CardHeader> + <CardTitle className="text-lg">기본 정보</CardTitle> + <CardDescription> + 템플릿의 기본 정보를 입력하세요 + </CardDescription> + </CardHeader> + <CardContent className="space-y-4"> + <FormField + control={form.control} + name="contractTemplateName" + render={({ field }) => ( + <FormItem> + <FormLabel>계약 문서명 <span className="text-red-500">*</span></FormLabel> + <FormControl> + <Input + placeholder="계약 문서명을 입력하세요" + {...field} + /> + </FormControl> + <FormMessage /> + </FormItem> + )} + /> + + <FormField + control={form.control} + name="contractTemplateType" + render={({ field }) => ( + <FormItem> + <FormLabel>계약 종류 <span className="text-red-500">*</span></FormLabel> + <FormControl> + <Input + placeholder="계약 종류를 입력하세요 (예: LO, FA, PO, CS, EU)" + {...field} + /> + </FormControl> + <FormMessage /> + </FormItem> + )} + /> + </CardContent> + </Card> + + {/* 파일 업로드 */} + <Card> + <CardHeader> + <CardTitle className="text-lg">파일 업로드</CardTitle> + <CardDescription> + 새로운 파일을 업로드하거나 기존 파일을 사용할 수 있습니다. + </CardDescription> + </CardHeader> + <CardContent> + <FormField + control={form.control} + name="file" + render={({ field: { onChange, value, ...field } }) => ( + <FormItem> + <FormLabel>새 파일 (선택사항)</FormLabel> + <FormControl> + <Dropzone + onDrop={(acceptedFiles) => { + if (acceptedFiles.length > 0) { + onChange(acceptedFiles[0]); + } + }} + accept={{ + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': ['.docx'], + 'application/msword': ['.doc'], + }} + maxFiles={1} + > + <DropzoneZone> + <DropzoneUploadIcon className="mx-auto h-10 w-10 text-muted-foreground" /> + <DropzoneTitle>파일을 드래그하거나 클릭하여 업로드</DropzoneTitle> + <DropzoneDescription> + DOCX 또는 DOC 파일만 업로드 가능합니다. + </DropzoneDescription> + <DropzoneInput /> + </DropzoneZone> + </Dropzone> + </FormControl> + {value && ( + <div className="mt-2 flex items-center gap-2"> + <FileText className="h-4 w-4" /> + <span className="text-sm">{value.name}</span> + </div> + )} + {uploadProgress > 0 && uploadProgress < 100 && ( + <div className="mt-2"> + <Progress value={uploadProgress} className="w-full" /> + <p className="text-xs text-muted-foreground mt-1"> + 업로드 중... {Math.round(uploadProgress)}% + </p> + </div> + )} + <FormMessage /> + </FormItem> + )} + /> + + {baseTemplate?.fileName && ( + <div className="mt-4 p-3 bg-muted rounded-lg"> + <p className="text-sm text-muted-foreground mb-2">기존 파일:</p> + <div className="flex items-center gap-2"> + <FileText className="h-4 w-4" /> + <span className="text-sm">{baseTemplate.fileName}</span> + <Badge variant="secondary">기존 파일 사용</Badge> + </div> + </div> + )} + </CardContent> + </Card> + </form> + </Form> + </div> + + {/* 고정된 푸터 */} + <DialogFooter className="p-6 pt-4 border-t bg-muted/50"> + <div className="flex justify-end gap-3 w-full"> + <Button + type="button" + variant="outline" + onClick={() => onOpenChange(false)} + disabled={isLoading} + > + 취소 + </Button> + <Button + type="submit" + onClick={form.handleSubmit(onSubmit)} + disabled={isLoading} + > + {isLoading ? ( + <> + <Loader className="mr-2 h-4 w-4 animate-spin" /> + 리비전 생성 중... + </> + ) : ( + "리비전 생성" + )} + </Button> + </div> + </DialogFooter> + </DialogContent> + </Dialog> + ); +} 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<React.SetStateAction<DataTableRowAction<GeneralContractTemplate> | null>> + router: ReturnType<typeof useRouter> +} + +/** + * 파일 다운로드 함수 (공용 유틸리티 사용) + */ +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<GeneralContractTemplate>[] { + // ---------------------------------------------------------------- + // 1) select 컬럼 (체크박스) + // ---------------------------------------------------------------- + const selectColumn: ColumnDef<GeneralContractTemplate> = { + 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" + /> + ), + size: 30, + minSize: 30, + maxSize: 30, + enableSorting: false, + enableHiding: false, + } + + // ---------------------------------------------------------------- + // 2) 파일 다운로드 컬럼 (아이콘) + // ---------------------------------------------------------------- + const downloadColumn: ColumnDef<GeneralContractTemplate> = { + id: "download", + header: "", + cell: ({ row }) => { + const template = row.original; + + return ( + <Button + variant="ghost" + size="icon" + onClick={() => handleFileDownload(template.filePath || "", template.fileName || "")} + title={`${template.fileName} 다운로드`} + className="hover:bg-muted" + > + <Paperclip className="h-4 w-4" /> + <span className="sr-only">다운로드</span> + </Button> + ); + }, + size: 30, + minSize: 30, + maxSize: 30, + enableSorting: false, + } + + // ---------------------------------------------------------------- + // 3) actions 컬럼 (Dropdown 메뉴) + // ---------------------------------------------------------------- + const actionsColumn: ColumnDef<GeneralContractTemplate> = { + 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 ( + <DropdownMenu> + <DropdownMenuTrigger asChild> + <Button + aria-label="Open menu" + variant="ghost" + className="flex size-8 p-0 data-[state=open]:bg-muted" + > + <Ellipsis className="size-4" aria-hidden="true" /> + </Button> + </DropdownMenuTrigger> + <DropdownMenuContent align="end" className="w-44"> + <DropdownMenuItem + onSelect={() => router.push(`/evcp/general-contract-template/${template.id}`)} + > + {/* <Eye className="mr-2 h-4 w-4" /> */} + 상세보기 + </DropdownMenuItem> + + <DropdownMenuSeparator /> + + <DropdownMenuItem + onSelect={() => setRowAction({ row, type: "create-revision" })} + > + {/* <GitBranch className="mr-2 h-4 w-4" /> */} + 리비전 생성하기 + </DropdownMenuItem> + + <DropdownMenuSeparator /> + + <DropdownMenuItem + onSelect={() => setRowAction({ row, type: "update" })} + > + 수정하기 + </DropdownMenuItem> + + {template.status === 'ACTIVE' && ( + <DropdownMenuItem + onSelect={() => setRowAction({ row, type: "dispose" })} + > + 폐기하기 + </DropdownMenuItem> + )} + + {template.status === 'DISPOSED' && template.disposedAt && ( + <DropdownMenuItem + onSelect={() => setRowAction({ row, type: "restore" })} + > + 복구하기 + </DropdownMenuItem> + )} + + <DropdownMenuSeparator /> + <DropdownMenuItem + onSelect={() => setRowAction({ row, type: "delete" })} + > + 삭제하기 + {/* <DropdownMenuShortcut>⌘⌫</DropdownMenuShortcut> */} + </DropdownMenuItem> + </DropdownMenuContent> + </DropdownMenu> + ) + }, + size: 30, + minSize: 30, + maxSize: 30, + } + + // ---------------------------------------------------------------- + // 4) 컬럼 정의 + // ---------------------------------------------------------------- + const basicInfoColumns: ColumnDef<GeneralContractTemplate>[] = [ + { + accessorKey: "id", + header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="No." />, + cell: ({ row }) => { + // Sequential number based on table order + return ( + <div className="w-[60px] text-center"> + {row.index + 1} + </div> + ); + }, + size: 60, + minSize: 50, + maxSize: 80, + enableSorting: false, + }, + { + accessorKey: "status", + header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="상태" />, + 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 ( + <div className="w-[40px] text-center"> + <span>{getStatusDisplay(status)}</span> + </div> + ); + }, + size: 80, + minSize: 60, + maxSize: 120, + enableResizing: true, + filterFn: (row, id, value) => { + return value.includes(row.getValue(id)); + }, + }, + { + accessorKey: "contractTemplateType", + header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="계약종류" />, + cell: ({ row }) => { + const contractType = row.getValue("contractTemplateType") as string; + return ( + <div className="w-[80px] text-center font-mono text-sm"> + {contractType} + </div> + ); + }, + size: 100, + minSize: 80, + maxSize: 150, + enableResizing: true, + filterFn: (row, id, value) => { + return value.includes(row.getValue(id)); + }, + }, + + { + accessorKey: "contractTemplateName", + header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="계약문서명" />, + cell: ({ row }) => { + const template = row.original; + + const handleClick = () => { + router.push(`/evcp/general-contract-template/${template.id}`); + }; + + return ( + <div className="flex flex-col min-w-0"> + <button + onClick={handleClick} + className="truncate text-left hover:text-blue-600 hover:underline cursor-pointer transition-colors" + title="클릭하여 상세보기" + > + {template.contractTemplateName} + </button> + </div> + ); + }, + size: 250, + minSize: 200, + maxSize: 400, + enableResizing: true, + }, + { + accessorKey: "revision", + header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="Rev." />, + cell: ({ row }) => { + const revision = row.getValue("revision") as number; + return ( + <div className="w-[60px] text-center"> + {revision} + </div> + ); + }, + size: 80, + minSize: 60, + maxSize: 120, + enableResizing: true, + }, + ]; + + // const scopeColumns: ColumnDef<BasicContractTemplate>[] = [ + // { + // accessorKey: "shipBuildingApplicable", + // header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="조선해양" />, + // cell: ({ row }) => { + // const applicable = row.getValue("shipBuildingApplicable") as boolean; + // return ( + // <div className="flex justify-center"> + // {applicable ? ( + // <CheckCircle className="h-4 w-4 text-green-500" /> + // ) : ( + // <XCircle className="h-4 w-4 text-gray-300" /> + // )} + // </div> + // ); + // }, + // size: 80, + // enableResizing: true, + // }, + // { + // accessorKey: "windApplicable", + // header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="풍력" />, + // cell: ({ row }) => { + // const applicable = row.getValue("windApplicable") as boolean; + // return ( + // <div className="flex justify-center"> + // {applicable ? ( + // <CheckCircle className="h-4 w-4 text-green-500" /> + // ) : ( + // <XCircle className="h-4 w-4 text-gray-300" /> + // )} + // </div> + // ); + // }, + // size: 60, + // enableResizing: true, + // }, + // { + // accessorKey: "pcApplicable", + // header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="PC" />, + // cell: ({ row }) => { + // const applicable = row.getValue("pcApplicable") as boolean; + // return ( + // <div className="flex justify-center"> + // {applicable ? ( + // <CheckCircle className="h-4 w-4 text-green-500" /> + // ) : ( + // <XCircle className="h-4 w-4 text-gray-300" /> + // )} + // </div> + // ); + // }, + // size: 50, + // enableResizing: true, + // }, + // { + // accessorKey: "nbApplicable", + // header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="NB" />, + // cell: ({ row }) => { + // const applicable = row.getValue("nbApplicable") as boolean; + // return ( + // <div className="flex justify-center"> + // {applicable ? ( + // <CheckCircle className="h-4 w-4 text-green-500" /> + // ) : ( + // <XCircle className="h-4 w-4 text-gray-300" /> + // )} + // </div> + // ); + // }, + // size: 50, + // enableResizing: true, + // }, + // { + // accessorKey: "rcApplicable", + // header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="RC" />, + // cell: ({ row }) => { + // const applicable = row.getValue("rcApplicable") as boolean; + // return ( + // <div className="flex justify-center"> + // {applicable ? ( + // <CheckCircle className="h-4 w-4 text-green-500" /> + // ) : ( + // <XCircle className="h-4 w-4 text-gray-300" /> + // )} + // </div> + // ); + // }, + // size: 50, + // enableResizing: true, + // }, + // { + // accessorKey: "gyApplicable", + // header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="GY" />, + // cell: ({ row }) => { + // const applicable = row.getValue("gyApplicable") as boolean; + // return ( + // <div className="flex justify-center"> + // {applicable ? ( + // <CheckCircle className="h-4 w-4 text-green-500" /> + // ) : ( + // <XCircle className="h-4 w-4 text-gray-300" /> + // )} + // </div> + // ); + // }, + // size: 50, + // enableResizing: true, + // }, + // { + // accessorKey: "sysApplicable", + // header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="S&Sys" />, + // cell: ({ row }) => { + // const applicable = row.getValue("sysApplicable") as boolean; + // return ( + // <div className="flex justify-center"> + // {applicable ? ( + // <CheckCircle className="h-4 w-4 text-green-500" /> + // ) : ( + // <XCircle className="h-4 w-4 text-gray-300" /> + // )} + // </div> + // ); + // }, + // size: 60, + // enableResizing: true, + // }, + // { + // accessorKey: "infraApplicable", + // header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="Infra" />, + // cell: ({ row }) => { + // const applicable = row.getValue("infraApplicable") as boolean; + // return ( + // <div className="flex justify-center"> + // {applicable ? ( + // <CheckCircle className="h-4 w-4 text-green-500" /> + // ) : ( + // <XCircle className="h-4 w-4 text-gray-300" /> + // )} + // </div> + // ); + // }, + // size: 60, + // enableResizing: true, + // }, + // ]; + + const fileInfoColumns: ColumnDef<GeneralContractTemplate>[] = [ + { + accessorKey: "fileName", + header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="파일명" />, + cell: ({ row }) => { + const fileName = row.getValue("fileName") as string; + return ( + <div className="min-w-0 max-w-full"> + <span className="block truncate" title={fileName}> + {fileName} + </span> + </div> + ); + }, + size: 200, + minSize: 150, + maxSize: 300, + enableResizing: true, + }, + ]; + + const auditColumns: ColumnDef<GeneralContractTemplate>[] = [ + { + accessorKey: "createdAt", + header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="생성일" />, + 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 }) => <DataTableColumnHeaderSimple column={column} title="수정일" />, + 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 }) => <DataTableColumnHeaderSimple column={column} title="폐기일" />, + 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 }) => <DataTableColumnHeaderSimple column={column} title="복구일" />, + 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 }) => <DataTableColumnHeaderSimple column={column} title="No." />, + cell: ({ row }) => { + return ( + <div className="w-[60px] text-center"> + {row.index + 1} + </div> + ); + }, + size: 40, + minSize: 40, + maxSize: 70, + enableSorting: false, + }, + { // 상태 + accessorKey: "status", + header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="상태" />, + 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 ( + <div className="w-[50px] text-center font-medium"> + {displayStatus} + </div> + ); + }, + size: 50, + minSize: 40, + maxSize: 70, + enableResizing: true, + }, + { // 계약종류 + accessorKey: "contractTemplateType", + header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="계약종류" />, + cell: ({ row }) => { + const contractType = row.getValue("contractTemplateType") as string; + return ( + <div className="w-[80px] text-center font-medium"> + {contractType} + </div> + ); + }, + size: 80, + minSize: 60, + maxSize: 120, + enableResizing: true, + }, + { // 계약문서명 + accessorKey: "contractTemplateName", + header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="계약문서명" />, + cell: ({ row }) => { + const contractName = row.getValue("contractTemplateName") as string; + return ( + <div className="max-w-[400px] truncate" title={contractName}> + {contractName} + </div> + ); + }, + size: 200, + minSize: 150, + maxSize: 1000, + enableResizing: true, + }, + { // Rev. + accessorKey: "revision", + header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="Rev." />, + cell: ({ row }) => { + const revision = row.getValue("revision") as number; + return ( + <div className="w-[60px] text-center"> + {revision} + </div> + ); + }, + size: 60, + minSize: 50, + maxSize: 80, + enableResizing: true, + }, + { // 법무검토 + accessorKey: "legalReviewRequired", + header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="법무검토" />, + cell: ({ row }) => { + const required = row.getValue("legalReviewRequired") as boolean; + return ( + <Badge variant={required ? "destructive" : "secondary"}> + {required ? "필요" : "불필요"} + </Badge> + ); + }, + size: 100, + minSize: 80, + maxSize: 150, + enableResizing: true, + }, + { // 최종 Update일 + accessorKey: "updatedAt", + header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="최종 Update일" />, + 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 }) => <DataTableColumnHeaderSimple column={column} title="최종 Update자" />, + cell: ({ row }) => { + const updatedByName = row.getValue("updatedByName") as string | null; + return updatedByName || ""; + }, + size: 120, + minSize: 100, + maxSize: 180, + enableResizing: true, + }, + { // 폐기일자 + accessorKey: "disposedAt", + header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="폐기일자" />, + 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 }) => <DataTableColumnHeaderSimple column={column} title="첨부" />, + cell: ({ row }) => { + const template = row.original; + + return ( + <Button + variant="ghost" + size="icon" + onClick={() => handleFileDownload(template.filePath || "", template.fileName || "")} + title={`${template.fileName} 다운로드`} + className="hover:bg-muted" + > + <Paperclip className="h-4 w-4" /> + <span className="sr-only">다운로드</span> + </Button> + ); + }, + 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 ( + <> + <div className="flex items-center gap-2"> + {/* 신규등록: 다이얼로그 사용 */} + <AddGeneralContractTemplateDialog /> + + {/* 계약현황 버튼 */} + <Button + onClick={handleContractStatus} + variant="outline" + size="sm" + className="border-blue-600 text-blue-600 hover:bg-blue-50" + > + <FileText className="mr-2 h-4 w-4" /> + 계약현황 + </Button> + + {/* 폐기 버튼 */} + <Button + onClick={handleDispose} + variant="outline" + size="sm" + className="border-red-600 text-red-600 hover:bg-red-50" + > + <Trash2 className="mr-2 h-4 w-4" /> + 폐기 + </Button> + </div> + + {/* 폐기 확인 다이얼로그 */} + <Dialog open={isDisposeOpen} onOpenChange={setIsDisposeOpen}> + <DialogContent> + <DialogHeader> + <DialogTitle>문서 폐기 확인</DialogTitle> + <DialogDescription> + 선택된 {selectedRows.length}개의 문서를 폐기하시겠습니까? + <br /> + 폐기된 문서는 복구할 수 없습니다. + </DialogDescription> + </DialogHeader> + <div className="flex justify-end gap-2"> + <Button + variant="outline" + onClick={() => setIsDisposeOpen(false)} + > + 취소 + </Button> + <Button + variant="destructive" + onClick={handleConfirmDispose} + > + 폐기 + </Button> + </div> + </DialogContent> + </Dialog> + </> + ) +} 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<SetStateAction<WebViewerInstance | null>>; +} + +export function GeneralContractTemplateViewer({ + templateId, + filePath, + instance, + setInstance, +}: GeneralContractTemplateViewerProps) { + const [fileLoading, setFileLoading] = useState<boolean>(true); + const viewer = useRef<HTMLDivElement>(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 ( + <div className="relative w-full h-full overflow-hidden"> + <div + ref={viewer} + className="w-full h-full" + style={{ + position: 'relative', + overflow: 'hidden', + contain: 'layout style paint', // CSS containment로 격리 + }} + > + {fileLoading && ( + <div className="absolute inset-0 flex flex-col items-center justify-center bg-white bg-opacity-90 z-10"> + <Loader2 className="h-8 w-8 text-blue-500 animate-spin mb-4" /> + <p className="text-sm text-muted-foreground">문서 로딩 중...</p> + </div> + )} + </div> + </div> + ); +} + +// 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<ReturnType<typeof getContractTemplates>>, + ] + > +} + +export function ContractTemplateTable({ promises }: ContractTemplateTableProps) { + const router = useRouter(); + const [rowAction, setRowAction] = + React.useState<DataTableRowAction<GeneralContractTemplate> | null>(null) + const [selectedRows, setSelectedRows] = React.useState<GeneralContractTemplate[]>([]) + 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<GeneralContractTemplate>[] = [ + { 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 ( + <> + <DataTable table={table}> + <DataTableAdvancedToolbar + table={table} + filterFields={advancedFilterFields} + shallow={false} + > + <GeneralContractTemplateToolbarActions selectedRows={selectedRows} /> + </DataTableAdvancedToolbar> + </DataTable> + + <UpdateTemplateSheet + open={rowAction?.type === "update"} + onOpenChange={() => setRowAction(null)} + template={rowAction?.row.original ?? null} + /> + + {/* 삭제 확인 다이얼로그 */} + <Dialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}> + <DialogContent> + <DialogHeader> + <DialogTitle>템플릿 삭제 확인</DialogTitle> + <DialogDescription> + "{rowAction?.row?.original?.contractTemplateName}" 템플릿을 삭제하시겠습니까? + <br /> + 삭제된 템플릿은 복구할 수 없습니다. + </DialogDescription> + </DialogHeader> + <div className="flex justify-end gap-2"> + <Button + variant="outline" + onClick={() => { + setIsDeleteDialogOpen(false) + setRowAction(null) + }} + > + 취소 + </Button> + <Button + variant="destructive" + onClick={handleConfirmDelete} + > + 삭제 + </Button> + </div> + </DialogContent> + </Dialog> + + {/* 폐기 확인 다이얼로그 */} + <Dialog open={isDisposeDialogOpen} onOpenChange={setIsDisposeDialogOpen}> + <DialogContent> + <DialogHeader> + <DialogTitle>템플릿 폐기 확인</DialogTitle> + <DialogDescription> + "{rowAction?.row?.original?.contractTemplateName}" 템플릿을 폐기하시겠습니까? + <br /> + 폐기된 템플릿은 복구할 수 있습니다. + </DialogDescription> + </DialogHeader> + <div className="flex justify-end gap-2"> + <Button + variant="outline" + onClick={() => { + setIsDisposeDialogOpen(false) + setRowAction(null) + }} + > + 취소 + </Button> + <Button + variant="destructive" + onClick={handleConfirmDispose} + > + 폐기 + </Button> + </div> + </DialogContent> + </Dialog> + + {/* 복구 확인 다이얼로그 */} + <Dialog open={isRestoreDialogOpen} onOpenChange={setIsRestoreDialogOpen}> + <DialogContent> + <DialogHeader> + <DialogTitle>템플릿 복구 확인</DialogTitle> + <DialogDescription> + "{rowAction?.row?.original?.contractTemplateName}" 템플릿을 복구하시겠습니까? + <br /> + 복구된 템플릿은 다시 사용할 수 있습니다. + </DialogDescription> + </DialogHeader> + <div className="flex justify-end gap-2"> + <Button + variant="outline" + onClick={() => { + setIsRestoreDialogOpen(false) + setRowAction(null) + }} + > + 취소 + </Button> + <Button + variant="default" + onClick={handleConfirmRestore} + > + 복구 + </Button> + </div> + </DialogContent> + </Dialog> + + {/* 리비전 생성 다이얼로그 */} + <CreateRevisionDialog + open={isCreateRevisionDialogOpen} + onOpenChange={setIsCreateRevisionDialogOpen} + baseTemplate={rowAction?.row?.original || null} + onSuccess={() => { + 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> | void; +} + +export function TemplateEditorWrapper({ + templateId, + filePath, + fileName, + refreshAction +}: TemplateEditorWrapperProps) { + const [instance, setInstance] = React.useState<WebViewerInstance | null>(null); + const [isSaving, setIsSaving] = React.useState(false); + const [documentVariables, setDocumentVariables] = React.useState<string[]>([]); + const [templateName, setTemplateName] = React.useState<string>(""); + const [predefinedVariables, setPredefinedVariables] = React.useState<string[]>([]); + + // 템플릿 이름 로드 및 변수 설정 + 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 ( + <div className="h-full w-full flex items-center justify-center text-muted-foreground"> + 첨부파일이 없습니다. + </div> + ); + } + + // 문서 새로고침 + const handleRefresh = () => { + window.location.reload(); + }; + + return ( + <div className="h-full flex flex-col"> + {/* 상단 도구 모음 */} + <div className="border-b bg-gray-50 p-3"> + <div className="flex items-center justify-between"> + <div className="flex items-center space-x-2"> + <Button + variant="outline" + size="sm" + onClick={handleSave} + disabled={isSaving || !instance} + > + {isSaving ? ( + <> + <RefreshCw className="mr-2 h-4 w-4 animate-spin" /> + 저장 중... + </> + ) : ( + <> + <Save className="mr-2 h-4 w-4" /> + 저장 + </> + )} + </Button> + + <Button + variant="outline" + size="sm" + onClick={handleRefresh} + > + <RefreshCw className="mr-2 h-4 w-4" /> + 새로고침 + </Button> + </div> + + <div className="flex items-center space-x-2"> + <Badge variant="outline"> + <FileText className="mr-1 h-3 w-3" /> + {fileName} + </Badge> + {templateName && ( + <Badge variant="secondary"> + <Type className="mr-1 h-3 w-3" /> + {templateName} + </Badge> + )} + {documentVariables.length > 0 && ( + <Badge variant="secondary"> + <Type className="mr-1 h-3 w-3" /> + 변수 {documentVariables.length}개 + </Badge> + )} + </div> + </div> + + {/* 변수 도구 */} + {(documentVariables.length > 0 || predefinedVariables.length > 0) && ( + <div className="mt-3 p-3 bg-white rounded border"> + <div className="mb-2"> + <h4 className="text-sm font-medium flex items-center"> + <Type className="mr-2 h-4 w-4 text-blue-500" /> + 변수 관리 + {templateName && ( + <span className="ml-2 text-xs text-muted-foreground"> + ({templateName}) + </span> + )} + </h4> + </div> + + <div className="space-y-3"> + {/* 발견된 변수들 */} + {documentVariables.length > 0 && ( + <div> + <p className="text-xs text-muted-foreground mb-2">문서에서 발견된 변수:</p> + <div className="flex flex-wrap gap-1"> + {documentVariables.map((variable, index) => ( + <Badge key={index} variant="outline" className="text-xs"> + {`{{${variable}}}`} + </Badge> + ))} + </div> + </div> + )} + + {/* 템플릿별 미리 정의된 변수들 */} + {predefinedVariables.length > 0 && ( + <div> + <p className="text-xs text-muted-foreground mb-2"> + {templateName ? `${templateName}에 권장되는 변수` : "자주 사용하는 변수"} (클릭하여 복사): + </p> + <TooltipProvider> + <div className="flex flex-wrap gap-1"> + {predefinedVariables.map((variable, index) => ( + <Tooltip key={index}> + <TooltipTrigger asChild> + <Button + variant="ghost" + size="sm" + className="h-6 px-2 text-xs hover:bg-blue-50" + onClick={() => insertVariable(variable)} + > + {`{{${variable}}}`} + </Button> + </TooltipTrigger> + <TooltipContent> + <p>{VARIABLE_DESCRIPTION_MAP[variable as keyof typeof VARIABLE_DESCRIPTION_MAP] || variable}</p> + </TooltipContent> + </Tooltip> + ))} + </div> + </TooltipProvider> + </div> + )} + </div> + </div> + )} + </div> + + {/* 뷰어 영역 (확대 문제 해결을 위한 컨테이너 격리) */} + <div className="flex-1 relative overflow-hidden"> + <div className="absolute inset-0"> + <GeneralContractTemplateViewer + templateId={typeof templateId === 'string' ? parseInt(templateId) : templateId} + filePath={filePath} + instance={instance} + setInstance={setInstance} + /> + </div> + </div> + + {/* 하단 안내 (한글 입력 팁 포함) */} + <div className="border-t bg-gray-50 p-2"> + <div className="flex items-center justify-between text-xs text-muted-foreground"> + <div className="flex items-center"> + <AlertCircle className="inline h-3 w-3 mr-1" /> + {'{{변수명}}'} 형식으로 변수를 삽입하면 계약서 생성 시 실제 값으로 치환됩니다. + </div> + <div className="flex items-center text-orange-600"> + <AlertCircle className="inline h-3 w-3 mr-1" /> + 한글 입력 제한시 외부 에디터에서 작성 후 복사-붙여넣기를 사용하세요. + </div> + </div> + </div> + </div> + ); +} + + 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<typeof updateTemplateSchema> + +interface UpdateTemplateSheetProps + extends React.ComponentPropsWithRef<typeof Sheet> { + template: GeneralContractTemplate | null + onSuccess?: () => void +} + +export function UpdateTemplateSheet({ template, onSuccess, ...props }: UpdateTemplateSheetProps) { + const [isUpdatePending, startUpdateTransition] = React.useTransition() + const [selectedFile, setSelectedFile] = React.useState<File | null>(null) + + const form = useForm<UpdateTemplateSchema>({ + 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 ( + <Sheet {...props}> + <SheetContent className="sm:max-w-[500px] h-[100vh] flex flex-col p-0"> + {/* 고정된 헤더 */} + <SheetHeader className="p-6 pb-4 border-b"> + <SheetTitle>일반계약 템플릿 수정</SheetTitle> + <SheetDescription>계약 기본정보를 수정하고 파일을 교체할 수 있습니다</SheetDescription> + </SheetHeader> + + {/* 스크롤 가능한 컨텐츠 영역 */} + <div className="flex-1 overflow-y-auto px-6"> + <Form {...form}> + <form + onSubmit={form.handleSubmit(onSubmit)} + className="space-y-6 py-4" + > + {/* 1. 계약 종류 */} + <Card> + <CardHeader> + <CardTitle className="text-lg">계약 종류</CardTitle> + </CardHeader> + <CardContent> + <FormField + control={form.control} + name="contractTemplateType" + render={({ field }) => ( + <FormItem> + <FormLabel>계약 종류</FormLabel> + <Input + placeholder="2자리 영문 (예: LO)" + value={field.value} + onChange={(e) => field.onChange(e.target.value.toUpperCase().slice(0, 2))} + maxLength={2} + /> + <FormMessage /> + </FormItem> + )} + /> + </CardContent> + </Card> + + {/* 2. 계약 문서명 */} + <Card> + <CardHeader> + <CardTitle className="text-lg">계약 문서명</CardTitle> + </CardHeader> + <CardContent> + <FormField + control={form.control} + name="contractTemplateName" + render={({ field }) => ( + <FormItem> + <FormLabel>계약 문서명</FormLabel> + <Input + placeholder="계약문서명을 입력하세요" + value={field.value} + onChange={field.onChange} + /> + <FormMessage /> + </FormItem> + )} + /> + </CardContent> + </Card> + + {/* 3. 법무 검토 */} + <Card> + <CardHeader> + <CardTitle className="text-lg">법무 검토</CardTitle> + </CardHeader> + <CardContent> + <FormField + control={form.control} + name="legalReviewRequired" + render={({ field }) => ( + <FormItem className="flex flex-row items-center justify-between rounded-lg border p-3 shadow-sm"> + <div className="space-y-0.5"> + <FormLabel>법무검토 필요</FormLabel> + <FormDescription>법무팀 검토가 필요한 템플릿인지 설정</FormDescription> + </div> + <FormControl> + <Switch + checked={field.value} + onCheckedChange={field.onChange} + /> + </FormControl> + </FormItem> + )} + /> + </CardContent> + </Card> + + {/* 4. 파일 업데이트 */} + <Card> + <CardHeader> + <CardTitle className="text-lg">파일 업데이트</CardTitle> + <CardDescription> + 새로운 템플릿 파일을 업로드하세요 + </CardDescription> + </CardHeader> + <CardContent> + <FormField + control={form.control} + name="file" + render={() => ( + <FormItem> + <FormLabel>새 템플릿 파일 (선택사항)</FormLabel> + <FormControl> + <Dropzone + onDrop={handleFileChange} + accept={{ + 'application/msword': ['.doc'], + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': ['.docx'] + }} + > + <DropzoneZone> + <DropzoneUploadIcon className="h-10 w-10 text-muted-foreground" /> + <DropzoneTitle> + {selectedFile + ? selectedFile.name + : "새 워드 파일을 드래그하세요"} + </DropzoneTitle> + <DropzoneDescription> + {selectedFile + ? `파일 크기: ${(selectedFile.size / (1024 * 1024)).toFixed(2)} MB` + : "또는 클릭하여 워드 파일(.doc, .docx)을 선택하세요 (최대 100MB)"} + </DropzoneDescription> + <DropzoneInput /> + </DropzoneZone> + </Dropzone> + </FormControl> + <FormDescription> + 파일을 업로드하지 않으면 기존 파일이 유지됩니다 + </FormDescription> + <FormMessage /> + </FormItem> + )} + /> + </CardContent> + </Card> + </form> + </Form> + </div> + + {/* 고정된 푸터 */} + <SheetFooter className="p-6 pt-4 border-t"> + <SheetClose asChild> + <Button type="button" variant="outline"> + 취소 + </Button> + </SheetClose> + <Button + type="button" + onClick={form.handleSubmit(onSubmit)} + disabled={isUpdatePending} + > + {isUpdatePending && ( + <Loader className="mr-2 size-4 animate-spin" aria-hidden="true" /> + )} + 업데이트 + </Button> + </SheetFooter> + </SheetContent> + </Sheet> + ) +}
\ No newline at end of file |
