summaryrefslogtreecommitdiff
path: root/lib/project-doc-templates/table
diff options
context:
space:
mode:
Diffstat (limited to 'lib/project-doc-templates/table')
-rw-r--r--lib/project-doc-templates/table/add-project-doc-template-dialog.tsx642
-rw-r--r--lib/project-doc-templates/table/doc-template-table.tsx716
-rw-r--r--lib/project-doc-templates/table/project-doc-template-editor.tsx645
-rw-r--r--lib/project-doc-templates/table/template-detail-dialog.tsx121
-rw-r--r--lib/project-doc-templates/table/template-edit-sheet.tsx305
5 files changed, 2429 insertions, 0 deletions
diff --git a/lib/project-doc-templates/table/add-project-doc-template-dialog.tsx b/lib/project-doc-templates/table/add-project-doc-template-dialog.tsx
new file mode 100644
index 00000000..fb36aebd
--- /dev/null
+++ b/lib/project-doc-templates/table/add-project-doc-template-dialog.tsx
@@ -0,0 +1,642 @@
+"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 { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Textarea } from "@/components/ui/textarea";
+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 { Plus, X, FileText, AlertCircle } from "lucide-react";
+import { useRouter } from "next/navigation";
+import { createProjectDocTemplate } from "@/lib/project-doc-templates/service";
+import { ProjectSelector } from "@/components/ProjectSelector";
+import type { TemplateVariable } from "@/db/schema/project-doc-templates";
+import type { Project } from "@/lib/rfqs/service";
+
+// 기본 변수들 (읽기 전용)
+const DEFAULT_VARIABLES_DISPLAY: TemplateVariable[] = [
+ { name: "document_number", displayName: "문서번호", type: "text", required: true, description: "문서 고유 번호" },
+ { name: "project_code", displayName: "프로젝트 코드", type: "text", required: true, description: "프로젝트 식별 코드" },
+ { name: "project_name", displayName: "프로젝트명", type: "text", required: true, description: "프로젝트 이름" },
+];
+
+const templateFormSchema = z.object({
+ templateName: z.string().min(1, "템플릿 이름을 입력해주세요."),
+ templateCode: z.string().optional(),
+ description: z.string().optional(),
+ projectId: z.number({
+ required_error: "프로젝트를 선택해주세요.",
+ }),
+ customVariables: z.array(z.object({
+ name: z.string().min(1, "변수명을 입력해주세요."),
+ displayName: z.string().min(1, "표시명을 입력해주세요."),
+ type: z.enum(["text", "number", "date", "select"]),
+ required: z.boolean(),
+ defaultValue: z.string().optional(),
+ description: z.string().optional(),
+ })).default([]),
+ 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 validTypes = [
+ 'application/msword',
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
+ ];
+ return validTypes.includes(data.file.type);
+ }
+ return true;
+}, {
+ message: "워드 파일(.doc, .docx)만 업로드 가능합니다.",
+ path: ["file"],
+});
+
+type TemplateFormValues = z.infer<typeof templateFormSchema>;
+
+export function AddProjectDocTemplateDialog() {
+ 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 [selectedProject, setSelectedProject] = React.useState<Project | null>(null);
+ const router = useRouter();
+
+ const form = useForm<TemplateFormValues>({
+ resolver: zodResolver(templateFormSchema),
+ defaultValues: {
+ templateName: "",
+ templateCode: "",
+ description: "",
+ customVariables: [],
+ },
+ mode: "onChange",
+ });
+
+ // 프로젝트 선택 시 처리
+ const handleProjectSelect = (project: Project) => {
+ setSelectedProject(project);
+ form.setValue("projectId", project.id);
+ // 템플릿 이름 자동 설정 (원하면)
+ if (!form.getValues("templateName")) {
+ form.setValue("templateName", `${project.projectCode} 벤더문서 커버 템플릿`);
+ }
+ };
+
+ const handleFileChange = (files: File[]) => {
+ if (files.length > 0) {
+ const file = files[0];
+ setSelectedFile(file);
+ form.setValue("file", file);
+ }
+ };
+
+ // 사용자 정의 변수 추가
+ const addCustomVariable = () => {
+ const currentVars = form.getValues("customVariables");
+ form.setValue("customVariables", [
+ ...currentVars,
+ {
+ name: "",
+ displayName: "",
+ type: "text",
+ required: false,
+ defaultValue: "",
+ description: "",
+ },
+ ]);
+ };
+
+ // 사용자 정의 변수 제거
+ const removeCustomVariable = (index: number) => {
+ const currentVars = form.getValues("customVariables");
+ form.setValue("customVariables", currentVars.filter((_, i) => i !== index));
+ };
+
+ // 청크 업로드
+ 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/project-doc-template/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 {
+ // 파일 업로드
+ const fileId = uuidv4();
+ const uploadResult = await uploadFileInChunks(formData.file, fileId);
+
+ if (!uploadResult?.success) {
+ throw new Error("파일 업로드에 실패했습니다.");
+ }
+
+ // 템플릿 생성 (고정값들 적용)
+ const result = await createProjectDocTemplate({
+ templateName: formData.templateName,
+ templateCode: formData.templateCode,
+ description: formData.description,
+ projectId: formData.projectId,
+ templateType: "PROJECT", // 고정
+ documentType: "VENDOR_DOC_COVER", // 벤더문서 커버로 고정
+ filePath: uploadResult.filePath,
+ fileName: uploadResult.fileName,
+ fileSize: formData.file.size,
+ mimeType: formData.file.type,
+ variables: formData.customVariables,
+ isPublic: false, // 고정
+ requiresApproval: false, // 고정
+ });
+
+ if (!result.success) {
+ throw new Error(result.error || "템플릿 생성에 실패했습니다.");
+ }
+
+ toast.success("템플릿이 성공적으로 추가되었습니다.");
+ form.reset();
+ setSelectedFile(null);
+ setSelectedProject(null);
+ setOpen(false);
+ setShowProgress(false);
+ router.refresh();
+ } catch (error) {
+ console.error("Submit error:", error);
+ toast.error(error instanceof Error ? error.message : "템플릿 추가 중 오류가 발생했습니다.");
+ } finally {
+ setIsLoading(false);
+ }
+ }
+
+ const customVariables = form.watch("customVariables");
+
+ // 다이얼로그 닫을 때 폼 초기화
+ React.useEffect(() => {
+ if (!open) {
+ form.reset();
+ setSelectedFile(null);
+ setSelectedProject(null);
+ setShowProgress(false);
+ setUploadProgress(0);
+ }
+ }, [open, form]);
+
+ return (
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogTrigger asChild>
+ <Button variant="default" size="sm">
+ <Plus className="mr-2 h-4 w-4" />
+ 템플릿 추가
+ </Button>
+ </DialogTrigger>
+ <DialogContent className="max-w-4xl h-[90vh] flex flex-col p-0">
+ {/* 헤더 - 고정 */}
+ <DialogHeader className="px-6 py-4 border-b">
+ <DialogTitle>프로젝트 벤더문서 커버 템플릿 추가</DialogTitle>
+ <DialogDescription>
+ 프로젝트별 벤더문서 커버 템플릿을 등록합니다. 기본 변수(document_number, project_code, project_name)는 자동으로 포함됩니다.
+ </DialogDescription>
+ </DialogHeader>
+
+ {/* 본문 - 스크롤 영역 */}
+ <div className="flex-1 overflow-y-auto px-6 py-4">
+ <Form {...form}>
+ <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
+ {/* 프로젝트 선택 및 기본 정보 */}
+ <Card>
+ <CardHeader>
+ <CardTitle className="text-lg">기본 정보</CardTitle>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ {/* 프로젝트 선택 - 필수 */}
+ <FormField
+ control={form.control}
+ name="projectId"
+ render={() => (
+ <FormItem>
+ <FormLabel>
+ 프로젝트 <span className="text-red-500">*</span>
+ </FormLabel>
+ <FormControl>
+ <ProjectSelector
+ selectedProjectId={selectedProject?.id}
+ onProjectSelect={handleProjectSelect}
+ placeholder="프로젝트를 선택하세요..."
+ filterType="plant" // 또는 필요한 타입
+ />
+ </FormControl>
+ <FormDescription>
+ 템플릿을 적용할 프로젝트를 선택하세요.
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ {selectedProject && (
+ <div className="p-3 bg-muted rounded-lg">
+ <p className="text-sm">
+ <span className="font-medium">선택된 프로젝트:</span> {selectedProject.projectCode} - {selectedProject.projectName}
+ </p>
+ </div>
+ )}
+
+ <div className="grid grid-cols-2 gap-4">
+ <FormField
+ control={form.control}
+ name="templateName"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>
+ 템플릿 이름 <span className="text-red-500">*</span>
+ </FormLabel>
+ <FormControl>
+ <Input placeholder="예: S123 벤더문서 커버 템플릿" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="templateCode"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>템플릿 코드</FormLabel>
+ <FormControl>
+ <Input placeholder="자동 생성됨 (선택사항)" {...field} />
+ </FormControl>
+ <FormDescription>비워두면 자동으로 생성됩니다.</FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+
+ <FormField
+ control={form.control}
+ name="description"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>설명</FormLabel>
+ <FormControl>
+ <Textarea
+ placeholder="템플릿에 대한 설명을 입력하세요."
+ className="min-h-[80px]"
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ {/* 고정 정보 표시 */}
+ <div className="flex gap-2">
+ <Badge variant="outline">템플릿 타입: 프로젝트</Badge>
+ <Badge variant="outline">문서 타입: 벤더문서 커버</Badge>
+ </div>
+ </CardContent>
+ </Card>
+
+ {/* 변수 설정 */}
+ <Card>
+ <CardHeader>
+ <CardTitle className="text-lg">템플릿 변수</CardTitle>
+ <CardDescription>
+ 문서에서 사용할 변수를 정의합니다. 템플릿에서 {'{{변수명}}'} 형식으로 사용됩니다.
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ {/* 기본 변수 표시 */}
+ <div>
+ <div className="flex items-center mb-2">
+ <Badge variant="outline" className="text-xs">
+ 기본 변수 (자동 포함)
+ </Badge>
+ </div>
+ <div className="space-y-2">
+ {DEFAULT_VARIABLES_DISPLAY.map((variable) => (
+ <div key={variable.name} className="flex items-center gap-2 p-2 bg-muted/50 rounded">
+ <Badge variant="secondary">
+ {`{{${variable.name}}}`}
+ </Badge>
+ <span className="text-sm">{variable.displayName}</span>
+ <span className="text-xs text-muted-foreground">({variable.description})</span>
+ {variable.required && (
+ <Badge variant="destructive" className="text-xs">필수</Badge>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {/* 사용자 정의 변수 */}
+ <div>
+ <div className="flex items-center justify-between mb-2">
+ <Badge variant="outline" className="text-xs">
+ 사용자 정의 변수
+ </Badge>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={addCustomVariable}
+ >
+ <Plus className="mr-2 h-4 w-4" />
+ 변수 추가
+ </Button>
+ </div>
+
+ {customVariables.length > 0 ? (
+ <div className="space-y-3">
+ {customVariables.map((_, index) => (
+ <div key={index} className="p-3 border rounded-lg space-y-3">
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium">변수 #{index + 1}</span>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => removeCustomVariable(index)}
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ </div>
+
+ <div className="grid grid-cols-3 gap-3">
+ <FormField
+ control={form.control}
+ name={`customVariables.${index}.name`}
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>변수명</FormLabel>
+ <FormControl>
+ <Input placeholder="예: vendor_name" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name={`customVariables.${index}.displayName`}
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>표시명</FormLabel>
+ <FormControl>
+ <Input placeholder="예: 벤더명" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name={`customVariables.${index}.type`}
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>타입</FormLabel>
+ <FormControl>
+ <select
+ className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background"
+ {...field}
+ >
+ <option value="text">텍스트</option>
+ <option value="number">숫자</option>
+ <option value="date">날짜</option>
+ <option value="select">선택</option>
+ </select>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+
+ <div className="grid grid-cols-2 gap-3">
+ <FormField
+ control={form.control}
+ name={`customVariables.${index}.defaultValue`}
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>기본값</FormLabel>
+ <FormControl>
+ <Input placeholder="선택사항" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name={`customVariables.${index}.required`}
+ render={({ field }) => (
+ <FormItem className="flex flex-row items-center justify-between rounded-lg border p-2">
+ <FormLabel className="text-sm">필수</FormLabel>
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ </div>
+
+ <FormField
+ control={form.control}
+ name={`customVariables.${index}.description`}
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>설명</FormLabel>
+ <FormControl>
+ <Input placeholder="변수 설명 (선택사항)" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+ ))}
+ </div>
+ ) : (
+ <div className="text-center py-4 text-sm text-muted-foreground">
+ 추가된 사용자 정의 변수가 없습니다.
+ </div>
+ )}
+ </div>
+ </CardContent>
+ </Card>
+
+ {/* 파일 업로드 */}
+ <Card>
+ <CardHeader>
+ <CardTitle className="text-lg">템플릿 파일</CardTitle>
+ <CardDescription>
+ 워드 파일(.doc, .docx)을 업로드하세요. 파일 내 {'{{변수명}}'} 형식으로 변수를 사용할 수 있습니다.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <FormField
+ control={form.control}
+ name="file"
+ render={() => (
+ <FormItem>
+ <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`
+ : "또는 클릭하여 파일을 선택하세요 (최대 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>
+ )}
+
+ {/* 변수 사용 안내 */}
+ <div className="mt-4 p-3 bg-blue-50 rounded-lg">
+ <div className="flex items-start">
+ <AlertCircle className="h-4 w-4 text-blue-600 mt-0.5 mr-2 flex-shrink-0" />
+ <div className="text-sm text-blue-900">
+ <p className="font-medium mb-1">변수 사용 방법</p>
+ <ul className="list-disc list-inside space-y-1 text-xs">
+ <li>워드 문서에서 {'{{변수명}}'} 형식으로 변수를 삽입하세요.</li>
+ <li>예시: {'{{document_number}}'}, {'{{project_code}}'}, {'{{project_name}}'}</li>
+ <li>문서 생성 시 변수가 실제 값으로 치환됩니다.</li>
+ </ul>
+ </div>
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+ </form>
+ </Form>
+ </div>
+
+ {/* 푸터 - 고정 */}
+ <DialogFooter className="px-6 py-4 border-t">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => setOpen(false)}
+ disabled={isLoading}
+ >
+ 취소
+ </Button>
+ <Button
+ type="button"
+ onClick={form.handleSubmit(onSubmit)}
+ disabled={isLoading || !form.watch("file") || !form.watch("projectId")}
+ >
+ {isLoading ? "처리 중..." : "템플릿 추가"}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+} \ No newline at end of file
diff --git a/lib/project-doc-templates/table/doc-template-table.tsx b/lib/project-doc-templates/table/doc-template-table.tsx
new file mode 100644
index 00000000..7d8210d8
--- /dev/null
+++ b/lib/project-doc-templates/table/doc-template-table.tsx
@@ -0,0 +1,716 @@
+"use client";
+
+import * as React from "react";
+import { useRouter } from "next/navigation";
+import { type ColumnDef } from "@tanstack/react-table";
+import {
+ Download,
+ Ellipsis,
+ Paperclip,
+ Eye,
+ Copy,
+ GitBranch,
+ Globe,
+ Lock,
+ FolderOpen,
+ FileText
+} from "lucide-react";
+import { toast } from "sonner";
+import { formatDateTime } from "@/lib/utils";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Checkbox } from "@/components/ui/checkbox";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { 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 { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header";
+import type {
+ DataTableAdvancedFilterField,
+ DataTableRowAction,
+} from "@/types/table";
+import {
+ getProjectDocTemplates,
+ deleteProjectDocTemplate,
+ createTemplateVersion
+} from "@/lib/project-doc-templates/service";
+import type { ProjectDocTemplate } from "@/db/schema/project-doc-templates";
+import { quickDownload } from "@/lib/file-download";
+import { AddProjectDocTemplateDialog } from "./add-project-doc-template-dialog";
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Label } from "@/components/ui/label";
+import { Input } from "@/components/ui/input";
+import { Progress } from "@/components/ui/progress";
+import { AlertCircle, RefreshCw } from "lucide-react";
+import { TemplateDetailDialog } from "./template-detail-dialog";
+import { TemplateEditSheet } from "./template-edit-sheet";
+
+// 문서 타입 라벨 매핑
+const DOCUMENT_TYPE_LABELS: Record<string, string> = {
+ CONTRACT: "계약서",
+ SPECIFICATION: "사양서",
+ REPORT: "보고서",
+ DRAWING: "도면",
+ MANUAL: "매뉴얼",
+ PROCEDURE: "절차서",
+ STANDARD: "표준문서",
+ OTHER: "기타",
+};
+
+// 파일 다운로드 함수
+const handleFileDownload = async (filePath: string, fileName: string) => {
+ try {
+ await quickDownload(filePath, fileName);
+ } catch (error) {
+ console.error("파일 다운로드 오류:", error);
+ toast.error("파일 다운로드 중 오류가 발생했습니다.");
+ }
+};
+
+// 컬럼 정의 함수 - 핸들러들을 props로 받음
+export function getColumns({
+ onViewDetail,
+ onEdit,
+ onDelete,
+ onCreateVersion,
+}: {
+ onViewDetail: (template: ProjectDocTemplate) => void;
+ onEdit: (template: ProjectDocTemplate) => void;
+ onDelete: (template: ProjectDocTemplate) => void;
+ onCreateVersion: (template: ProjectDocTemplate) => void;
+}): ColumnDef<ProjectDocTemplate>[] {
+
+ // 체크박스 컬럼
+ const selectColumn: ColumnDef<ProjectDocTemplate> = {
+ 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"
+ />
+ ),
+ maxSize: 30,
+ enableSorting: false,
+ enableHiding: false,
+ };
+
+ // 다운로드 컬럼
+ const downloadColumn: ColumnDef<ProjectDocTemplate> = {
+ 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>
+ );
+ },
+ maxSize: 30,
+ enableSorting: false,
+ };
+
+ // 액션 컬럼
+ const actionsColumn: ColumnDef<ProjectDocTemplate> = {
+ id: "actions",
+ enableHiding: false,
+ cell: ({ row }) => {
+ const template = row.original;
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ aria-label="Open menu"
+ variant="ghost"
+ className="flex size-8 p-0 data-[state=open]:bg-muted"
+ >
+ <Ellipsis className="size-4" aria-hidden="true" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-44">
+ <DropdownMenuItem onSelect={() => onViewDetail(template)}>
+ <Eye className="mr-2 h-4 w-4" />
+ 상세보기
+ </DropdownMenuItem>
+
+ <DropdownMenuItem onSelect={() => onEdit(template)}>
+ 수정하기
+ </DropdownMenuItem>
+
+ <DropdownMenuSeparator />
+
+ <DropdownMenuItem onSelect={() => onCreateVersion(template)}>
+ <GitBranch className="mr-2 h-4 w-4" />
+ 새 버전 생성
+ </DropdownMenuItem>
+
+ <DropdownMenuSeparator />
+
+ <DropdownMenuItem
+ onSelect={() => onDelete(template)}
+ className="text-destructive"
+ >
+ 삭제하기
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+ },
+ maxSize: 30,
+ };
+
+ // 데이터 컬럼들
+ const dataColumns: ColumnDef<ProjectDocTemplate>[] = [
+ {
+ accessorKey: "status",
+ header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="상태" />,
+ cell: ({ row }) => {
+ const status = row.getValue("status") as string;
+ const statusMap: Record<string, { label: string; variant: "default" | "secondary" | "destructive" | "outline" }> = {
+ ACTIVE: { label: "활성", variant: "default" },
+ INACTIVE: { label: "비활성", variant: "secondary" },
+ DRAFT: { label: "초안", variant: "outline" },
+ ARCHIVED: { label: "보관", variant: "secondary" },
+ };
+ const statusInfo = statusMap[status] || { label: status, variant: "outline" };
+ return (
+ <Badge variant={statusInfo.variant}>
+ {statusInfo.label}
+ </Badge>
+ );
+ },
+ size: 80,
+ enableResizing: true,
+ },
+ {
+ accessorKey: "templateName",
+ header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="템플릿명" />,
+ cell: ({ row }) => {
+ const template = row.original;
+
+ return (
+ <div className="flex flex-col min-w-0">
+ <button
+ onClick={() => onViewDetail(template)}
+ className="truncate text-left hover:text-blue-600 hover:underline cursor-pointer transition-colors"
+ title="클릭하여 상세보기"
+ >
+ {template.templateName}
+ </button>
+ {template.templateCode && (
+ <span className="text-xs text-muted-foreground">{template.templateCode}</span>
+ )}
+ </div>
+ );
+ },
+ size: 250,
+ enableResizing: true,
+ },
+ {
+ accessorKey: "projectCode",
+ header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="프로젝트" />,
+ cell: ({ row }) => {
+ const template = row.original;
+ if (!template.projectCode) return <span className="text-muted-foreground">-</span>;
+
+ return (
+ <div className="flex flex-col min-w-0">
+ <span className="font-medium truncate">{template.projectCode}</span>
+ {template.projectName && (
+ <span className="text-xs text-muted-foreground truncate">{template.projectName}</span>
+ )}
+ </div>
+ );
+ },
+ size: 150,
+ enableResizing: true,
+ },
+ {
+ accessorKey: "version",
+ header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="버전" />,
+ cell: ({ row }) => {
+ const template = row.original;
+ return (
+ <div className="flex items-center gap-2">
+ <Badge variant="outline" className="text-xs">
+ v{template.version}
+ </Badge>
+ {template.isLatest && (
+ <Badge variant="secondary" className="text-xs">
+ 최신
+ </Badge>
+ )}
+ </div>
+ );
+ },
+ size: 100,
+ enableResizing: true,
+ },
+ {
+ id: "variables",
+ header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="변수" />,
+ cell: ({ row }) => {
+ const template = row.original;
+ const variableCount = template.variables?.length || 0;
+ const requiredCount = template.requiredVariables?.length || 0;
+
+ return (
+ <div className="text-xs">
+ <span>{variableCount}개</span>
+ {requiredCount > 0 && (
+ <span className="text-muted-foreground ml-1">
+ (필수: {requiredCount})
+ </span>
+ )}
+ </div>
+ );
+ },
+ size: 100,
+ enableResizing: true,
+ },
+ {
+ accessorKey: "fileName",
+ header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="파일명" />,
+ cell: ({ row }) => {
+ const fileName = row.getValue("fileName") as string;
+ const template = row.original;
+ const fileSizeMB = template.fileSize ? (template.fileSize / (1024 * 1024)).toFixed(2) : null;
+
+ return (
+ <div className="min-w-0 max-w-full">
+ <span className="block truncate text-sm" title={fileName}>
+ {fileName}
+ </span>
+ {fileSizeMB && (
+ <span className="text-xs text-muted-foreground">{fileSizeMB} MB</span>
+ )}
+ </div>
+ );
+ },
+ size: 200,
+ enableResizing: true,
+ },
+ {
+ accessorKey: "createdAt",
+ header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="생성일" />,
+ cell: ({ row }) => {
+ const date = row.getValue("createdAt") as Date;
+ const template = row.original;
+ return (
+ <div className="text-xs">
+ <div>{date ? formatDateTime(date, "KR") : "-"}</div>
+ {template.createdByName && (
+ <span className="text-muted-foreground">{template.createdByName}</span>
+ )}
+ </div>
+ );
+ },
+ size: 140,
+ enableResizing: true,
+ },
+ {
+ accessorKey: "updatedAt",
+ header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="수정일" />,
+ cell: ({ row }) => {
+ const date = row.getValue("updatedAt") as Date;
+ const template = row.original;
+ return (
+ <div className="text-xs">
+ <div>{date ? formatDateTime(date, "KR") : "-"}</div>
+ {template.updatedByName && (
+ <span className="text-muted-foreground">{template.updatedByName}</span>
+ )}
+ </div>
+ );
+ },
+ size: 140,
+ enableResizing: true,
+ },
+ ];
+
+ return [selectColumn, downloadColumn, ...dataColumns, actionsColumn];
+}
+
+// 메인 테이블 컴포넌트
+interface ProjectDocTemplateTableProps {
+ promises: Promise<
+ [
+ Awaited<ReturnType<typeof getProjectDocTemplates>>,
+ ]
+>
+}
+
+export function ProjectDocTemplateTable({
+ promises
+}: ProjectDocTemplateTableProps) {
+ const router = useRouter();
+ const [selectedTemplate, setSelectedTemplate] = React.useState<ProjectDocTemplate | null>(null);
+ const [detailOpen, setDetailOpen] = React.useState(false);
+ const [editOpen, setEditOpen] = React.useState(false);
+ const [versionTemplate, setVersionTemplate] = React.useState<ProjectDocTemplate | null>(null);
+ const [versionOpen, setVersionOpen] = React.useState(false);
+
+ const [{ data, pageCount }] = React.use(promises);
+
+ // 액션 핸들러들
+ const handleViewDetail = (template: ProjectDocTemplate) => {
+ setSelectedTemplate(template);
+ setDetailOpen(true);
+ };
+
+ const handleEdit = (template: ProjectDocTemplate) => {
+ setSelectedTemplate(template);
+ setEditOpen(true);
+ };
+
+ const handleDelete = async (template: ProjectDocTemplate) => {
+ if (confirm("정말로 이 템플릿을 삭제하시겠습니까?")) {
+ const result = await deleteProjectDocTemplate(template.id);
+ if (result.success) {
+ toast.success("템플릿이 삭제되었습니다.");
+ router.refresh();
+ } else {
+ toast.error(result.error || "삭제에 실패했습니다.");
+ }
+ }
+ };
+
+ const handleCreateVersion = (template: ProjectDocTemplate) => {
+ setVersionTemplate(template);
+ setVersionOpen(true);
+ };
+
+ // 컬럼 설정 - 핸들러들을 전달
+ const columns = React.useMemo(
+ () => getColumns({
+ onViewDetail: handleViewDetail,
+ onEdit: handleEdit,
+ onDelete: handleDelete,
+ onCreateVersion: handleCreateVersion,
+ }),
+ []
+ );
+
+ // 필터 필드 설정
+ const advancedFilterFields: DataTableAdvancedFilterField<ProjectDocTemplate>[] = [
+ { id: "templateName", label: "템플릿명", type: "text" },
+ {
+ id: "status",
+ label: "상태",
+ type: "select",
+ options: [
+ { label: "활성", value: "ACTIVE" },
+ { label: "비활성", value: "INACTIVE" },
+ { label: "초안", value: "DRAFT" },
+ { label: "보관", value: "ARCHIVED" },
+ ],
+ },
+ { id: "projectCode", label: "프로젝트 코드", type: "text" },
+ { id: "createdAt", label: "생성일", type: "date" },
+ { id: "updatedAt", label: "수정일", type: "date" },
+ ];
+
+ const { table } = useDataTable({
+ data,
+ columns,
+ pageCount,
+ filterFields: advancedFilterFields,
+ enablePinning: true,
+ enableAdvancedFilter: true,
+ initialState: {
+ sorting: [{ id: "createdAt", desc: true }],
+ columnPinning: { right: ["actions"] },
+ },
+ getRowId: (originalRow) => String(originalRow.id),
+ shallow: false,
+ clearOnDefault: true,
+ });
+
+ return (
+ <>
+ <DataTable table={table}>
+ <DataTableAdvancedToolbar
+ table={table}
+ filterFields={advancedFilterFields}
+ shallow={false}
+ >
+ <div className="flex items-center gap-2">
+ <AddProjectDocTemplateDialog />
+ {table.getFilteredSelectedRowModel().rows.length > 0 && (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ const selectedRows = table.getFilteredSelectedRowModel().rows;
+ console.log("Selected templates:", selectedRows.map(r => r.original));
+ toast.info(`${selectedRows.length}개 템플릿 선택됨`);
+ }}
+ >
+ 선택 항목 처리 ({table.getFilteredSelectedRowModel().rows.length})
+ </Button>
+ )}
+ </div>
+ </DataTableAdvancedToolbar>
+ </DataTable>
+
+ {/* 상세보기 다이얼로그 */}
+ {selectedTemplate && (
+ <TemplateDetailDialog
+ template={selectedTemplate}
+ open={detailOpen}
+ onOpenChange={setDetailOpen}
+ />
+ )}
+
+ {/* 수정 Sheet */}
+ {selectedTemplate && (
+ <TemplateEditSheet
+ template={selectedTemplate}
+ open={editOpen}
+ onOpenChange={setEditOpen}
+ onSuccess={() => {
+ router.refresh();
+ }}
+ />
+ )}
+
+ {/* 새 버전 생성 다이얼로그 */}
+ {versionTemplate && (
+ <CreateVersionDialog
+ template={versionTemplate}
+ open={versionOpen}
+ onOpenChange={(open) => {
+ setVersionOpen(open);
+ if (!open) setVersionTemplate(null);
+ }}
+ onSuccess={() => {
+ setVersionOpen(false);
+ setVersionTemplate(null);
+ router.refresh();
+ toast.success("새 버전이 생성되었습니다.");
+ }}
+ />
+ )}
+ </>
+ );
+}
+
+// 새 버전 생성 다이얼로그 컴포넌트
+interface CreateVersionDialogProps {
+ template: ProjectDocTemplate;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onSuccess: () => void;
+}
+
+
+function CreateVersionDialog({ template, onClose, onSuccess }: CreateVersionDialogProps) {
+ const [isLoading, setIsLoading] = React.usseState(false);
+ const [selectedFile, setSelectedFile] = React.useState<File | null>(null);
+ const [uploadProgress, setUploadProgress] = React.useState(0);
+ const [showProgress, setShowProgress] = React.useState(false);
+
+ // 청크 업로드 함수
+ const CHUNK_SIZE = 1 * 1024 * 1024; // 1MB
+
+ 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/project-doc-template/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;
+ }
+ }
+ };
+
+ const handleSubmit = async () => {
+ if (!selectedFile) {
+ toast.error("파일을 선택해주세요.");
+ return;
+ }
+
+ setIsLoading(true);
+ try {
+ // 1. 파일 업로드 (청크 방식)
+ const fileId = `version_${template.id}_${Date.now()}`;
+ const uploadResult = await uploadFileInChunks(selectedFile, fileId);
+
+ if (!uploadResult?.success) {
+ throw new Error("파일 업로드에 실패했습니다.");
+ }
+
+ // 2. 업로드된 파일 정보로 새 버전 생성
+ const result = await createTemplateVersion(template.id, {
+ filePath: uploadResult.filePath,
+ fileName: uploadResult.fileName,
+ fileSize: uploadResult.fileSize || selectedFile.size,
+ mimeType: uploadResult.mimeType || selectedFile.type,
+ variables: template.variables, // 기존 변수 유지
+ });
+
+ if (result.success) {
+ toast.success(`버전 ${template.version + 1}이 생성되었습니다.`);
+ onSuccess();
+ } else {
+ throw new Error(result.error);
+ }
+ } catch (error) {
+ console.error("Failed to create version:", error);
+ toast.error(error instanceof Error ? error.message : "새 버전 생성에 실패했습니다.");
+ } finally {
+ setIsLoading(false);
+ setShowProgress(false);
+ setUploadProgress(0);
+ }
+ };
+
+ return (
+ <Dialog open={true} onOpenChange={onClose}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>새 버전 생성</DialogTitle>
+ <DialogDescription>
+ {template.templateName}의 새 버전을 생성합니다.
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-4">
+ {/* 버전 정보 표시 */}
+ <div className="rounded-lg border p-3 bg-muted/50">
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium">현재 버전</span>
+ <Badge variant="outline">v{template.version}</Badge>
+ </div>
+ <div className="flex items-center justify-between mt-2">
+ <span className="text-sm font-medium">새 버전</span>
+ <Badge variant="default">v{template.version + 1}</Badge>
+ </div>
+ </div>
+
+ {/* 파일 선택 */}
+ <div>
+ <Label htmlFor="file">
+ 새 템플릿 파일 <span className="text-red-500">*</span>
+ </Label>
+ <div className="mt-2">
+ <Input
+ id="file"
+ type="file"
+ accept=".doc,.docx"
+ onChange={(e) => setSelectedFile(e.target.files?.[0] || null)}
+ disabled={isLoading}
+ />
+ </div>
+ {selectedFile && (
+ <p className="mt-2 text-sm text-muted-foreground">
+ 선택된 파일: {selectedFile.name} ({(selectedFile.size / 1024 / 1024).toFixed(2)} MB)
+ </p>
+ )}
+ </div>
+
+ {/* 업로드 진행률 */}
+ {showProgress && (
+ <div className="space-y-2">
+ <div className="flex justify-between text-sm">
+ <span>업로드 진행률</span>
+ <span>{uploadProgress}%</span>
+ </div>
+ <Progress value={uploadProgress} />
+ </div>
+ )}
+
+ {/* 안내 메시지 */}
+ <div className="rounded-lg border border-yellow-200 bg-yellow-50 p-3">
+ <div className="flex">
+ <AlertCircle className="h-4 w-4 text-yellow-600 mr-2 flex-shrink-0 mt-0.5" />
+ <div className="text-sm text-yellow-800">
+ <p className="font-medium">주의사항</p>
+ <ul className="mt-1 list-disc list-inside text-xs space-y-1">
+ <li>새 버전 생성 후에는 이전 버전으로 되돌릴 수 없습니다.</li>
+ <li>기존 변수 설정은 그대로 유지됩니다.</li>
+ <li>파일 형식은 기존과 동일해야 합니다 (.doc/.docx).</li>
+ </ul>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <DialogFooter>
+ <Button
+ variant="outline"
+ onClick={onClose}
+ disabled={isLoading}
+ >
+ 취소
+ </Button>
+ <Button
+ onClick={handleSubmit}
+ disabled={isLoading || !selectedFile}
+ >
+ {isLoading ? (
+ <>
+ <RefreshCw className="mr-2 h-4 w-4 animate-spin" />
+ 생성 중...
+ </>
+ ) : (
+ '버전 생성'
+ )}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+} \ No newline at end of file
diff --git a/lib/project-doc-templates/table/project-doc-template-editor.tsx b/lib/project-doc-templates/table/project-doc-template-editor.tsx
new file mode 100644
index 00000000..e4f798a9
--- /dev/null
+++ b/lib/project-doc-templates/table/project-doc-template-editor.tsx
@@ -0,0 +1,645 @@
+"use client";
+
+import * as React from "react";
+import { Button } from "@/components/ui/button";
+import { toast } from "sonner";
+import {
+ Save,
+ RefreshCw,
+ Type,
+ FileText,
+ AlertCircle,
+ Copy,
+ Download,
+ Settings,
+ ChevronDown,
+ ChevronUp
+} 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 {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ Collapsible,
+ CollapsibleContent,
+ CollapsibleTrigger,
+} from "@/components/ui/collapsible";
+import {
+ getProjectDocTemplateById,
+ updateProjectDocTemplate,
+ type DocTemplateVariable
+} from "@/lib/project-doc-templates/service";
+import type { ProjectDocTemplate } from "@/db/schema/project-doc-templates";
+import { BasicContractTemplateViewer } from "@/lib/basic-contract/template/basic-contract-template-viewer";
+import { v4 as uuidv4 } from 'uuid';
+import { Progress } from "@/components/ui/progress";
+
+interface ProjectDocTemplateEditorProps {
+ templateId: string | number;
+ filePath: string;
+ fileName: string;
+ refreshAction?: () => Promise<void>;
+ mode?: "view" | "edit";
+}
+
+// 변수별 한글 설명 매핑은 기존과 동일
+const VARIABLE_DESCRIPTION_MAP: Record<string, string> = {
+ "document_number": "문서번호",
+ "project_code": "프로젝트 코드",
+ "project_name": "프로젝트명",
+ "created_date": "작성일",
+ "author_name": "작성자",
+ "department": "부서명",
+ "company_name": "회사명",
+ "company_address": "회사주소",
+ "representative_name": "대표자명",
+ "signature_date": "서명날짜",
+ "today_date": "오늘날짜",
+ "tax_id": "사업자등록번호",
+ "phone_number": "전화번호",
+ "email": "이메일",
+};
+
+const VARIABLE_PATTERN = /\{\{([^}]+)\}\}/g;
+
+export function ProjectDocTemplateEditor({
+ templateId,
+ filePath,
+ fileName,
+ refreshAction,
+ mode = "edit",
+}: ProjectDocTemplateEditorProps) {
+ const [instance, setInstance] = React.useState<WebViewerInstance | null>(null);
+ const [isSaving, setIsSaving] = React.useState(false);
+ const [documentVariables, setDocumentVariables] = React.useState<string[]>([]);
+ const [templateInfo, setTemplateInfo] = React.useState<ProjectDocTemplate | null>(null);
+ const [predefinedVariables, setPredefinedVariables] = React.useState<DocTemplateVariable[]>([]);
+ const [isVariablePanelOpen, setIsVariablePanelOpen] = React.useState(false); // 변수 패널 접기/펴기 상태
+ const [uploadProgress, setUploadProgress] = React.useState(0);
+ const [showProgress, setShowProgress] = React.useState(false);
+
+ // 템플릿 정보 로드
+ React.useEffect(() => {
+ const loadTemplateInfo = async () => {
+ try {
+ const data = await getProjectDocTemplateById(Number(templateId));
+ setTemplateInfo(data as ProjectDocTemplate);
+ setPredefinedVariables(data.variables || []);
+
+ console.log("📋 템플릿 정보:", data);
+ console.log("📝 정의된 변수들:", data.variables);
+ } catch (error) {
+ console.error("템플릿 정보 로드 오류:", error);
+ toast.error("템플릿 정보를 불러오는데 실패했습니다.");
+ }
+ };
+
+ 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);
+
+ const undefinedVars = variables.filter(
+ v => !predefinedVariables.find(pv => pv.name === v)
+ );
+
+ if (undefinedVars.length > 0) {
+ toast.warning(
+ `정의되지 않은 변수가 발견되었습니다: ${undefinedVars.join(", ")}`,
+ { duration: 5000 }
+ );
+ }
+ }
+
+ } catch (error) {
+ console.error("변수 추출 중 오류:", error);
+ }
+ };
+
+ // 청크 업로드 함수
+ const CHUNK_SIZE = 1 * 1024 * 1024; // 1MB
+
+ const uploadFileInChunks = async (file: Blob, fileName: string, 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', fileName);
+ formData.append('chunkIndex', chunkIndex.toString());
+ formData.append('totalChunks', totalChunks.toString());
+ formData.append('fileId', fileId);
+
+ const response = await fetch('/api/upload/project-doc-template/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;
+ }
+ }
+ };
+
+ // 문서 저장 - 개선된 버전
+ const handleSave = async () => {
+ if (!instance || mode === "view") {
+ toast.error(mode === "view" ? "읽기 전용 모드입니다." : "뷰어가 준비되지 않았습니다.");
+ return;
+ }
+
+ setIsSaving(true);
+ try {
+ const { documentViewer } = instance.Core;
+ const doc = documentViewer.getDocument();
+
+ if (!doc) {
+ throw new Error("문서를 찾을 수 없습니다.");
+ }
+
+ // Word 문서 데이터 추출
+ const data = await doc.getFileData({
+ downloadType: "office",
+ includeAnnotations: true
+ });
+
+ // Blob 생성
+ const fileBlob = new Blob([data], {
+ type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
+ });
+
+ // 파일 업로드 (청크 방식)
+ const fileId = `template_${templateId}_${Date.now()}`;
+ const uploadResult = await uploadFileInChunks(fileBlob, fileName, fileId);
+
+ if (!uploadResult?.success) {
+ throw new Error("파일 업로드에 실패했습니다.");
+ }
+
+ // 서버에 파일 경로 업데이트
+ const updateResult = await updateProjectDocTemplate(Number(templateId), {
+ filePath: uploadResult.filePath,
+ fileName: uploadResult.fileName,
+ fileSize: uploadResult.fileSize,
+ variables: documentVariables.length > 0 ?
+ documentVariables.map(varName => {
+ const existing = predefinedVariables.find(v => v.name === varName);
+ return existing || {
+ name: varName,
+ displayName: VARIABLE_DESCRIPTION_MAP[varName] || varName,
+ type: "text" as const,
+ required: false,
+ description: ""
+ };
+ }) : predefinedVariables
+ });
+
+ if (!updateResult.success) {
+ throw new Error(updateResult.error || "템플릿 업데이트에 실패했습니다.");
+ }
+
+ toast.success("템플릿이 성공적으로 저장되었습니다.");
+
+ // 변수 재추출
+ await extractVariablesFromDocument();
+
+ // 페이지 새로고침
+ if (refreshAction) {
+ await refreshAction();
+ }
+
+ } catch (error) {
+ console.error("저장 오류:", error);
+ toast.error(error instanceof Error ? error.message : "저장 중 오류가 발생했습니다.");
+ } finally {
+ setIsSaving(false);
+ setShowProgress(false);
+ setUploadProgress(0);
+ }
+ };
+
+ // 나머지 함수들은 기존과 동일
+ React.useEffect(() => {
+ if (instance) {
+ const { documentViewer } = instance.Core;
+
+ const onDocumentLoaded = () => {
+ setTimeout(() => extractVariablesFromDocument(), 1000);
+ };
+
+ documentViewer.addEventListener("documentLoaded", onDocumentLoaded);
+
+ return () => {
+ documentViewer.removeEventListener("documentLoaded", onDocumentLoaded);
+ };
+ }
+ }, [instance, predefinedVariables]);
+
+ const insertVariable = async (variable: DocTemplateVariable) => {
+ if (!instance) {
+ toast.error("뷰어가 준비되지 않았습니다.");
+ return;
+ }
+
+ const textToInsert = `{{${variable.name}}}`; // variable.name으로 수정
+
+ try {
+ // textarea를 보이는 위치에 잠시 생성
+ const tempTextArea = document.createElement('textarea');
+ tempTextArea.value = textToInsert;
+ tempTextArea.style.position = 'fixed';
+ tempTextArea.style.top = '20px';
+ tempTextArea.style.left = '20px';
+ tempTextArea.style.width = '200px';
+ tempTextArea.style.height = '30px';
+ tempTextArea.style.fontSize = '12px';
+ tempTextArea.style.zIndex = '10000';
+ tempTextArea.style.opacity = '0.01'; // 거의 투명하게
+
+ document.body.appendChild(tempTextArea);
+
+ // 포커스와 선택을 확실하게
+ tempTextArea.focus();
+ tempTextArea.select();
+ tempTextArea.setSelectionRange(0, tempTextArea.value.length); // 전체 선택 보장
+
+ let successful = false;
+ try {
+ successful = document.execCommand('copy');
+ console.log('복사 시도 결과:', successful, '복사된 텍스트:', textToInsert);
+ } catch (err) {
+ console.error('execCommand 실패:', err);
+ }
+
+ // 잠시 후 제거 (즉시 제거하면 복사가 안될 수 있음)
+ setTimeout(() => {
+ document.body.removeChild(tempTextArea);
+ }, 100);
+
+ if (successful) {
+ toast.success(
+ <div>
+ <p className="font-medium">{variable.displayName} 변수가 복사되었습니다.</p>
+ <code className="bg-gray-100 px-1 rounded text-xs">{textToInsert}</code>
+ <p className="text-sm text-muted-foreground mt-1">
+ 문서에서 원하는 위치에 Ctrl+V로 붙여넣기 하세요.
+ </p>
+ </div>,
+ { duration: 3000 }
+ );
+
+ // 복사 확인용 - 개발 중에만 사용
+ if (process.env.NODE_ENV === 'development') {
+ navigator.clipboard.readText().then(text => {
+ console.log('클립보드 내용:', text);
+ }).catch(err => {
+ console.log('클립보드 읽기 실패:', err);
+ });
+ }
+ } else {
+ // 복사 실패 시 대안 제공
+ const fallbackInput = document.createElement('input');
+ fallbackInput.value = textToInsert;
+ fallbackInput.style.position = 'fixed';
+ fallbackInput.style.top = '50%';
+ fallbackInput.style.left = '50%';
+ fallbackInput.style.transform = 'translate(-50%, -50%)';
+ fallbackInput.style.zIndex = '10001';
+ fallbackInput.style.padding = '8px';
+ fallbackInput.style.border = '2px solid #3b82f6';
+ fallbackInput.style.borderRadius = '4px';
+ fallbackInput.style.backgroundColor = 'white';
+
+ document.body.appendChild(fallbackInput);
+ fallbackInput.select();
+
+ toast.error(
+ <div>
+ <p className="font-medium">자동 복사 실패</p>
+ <p className="text-sm">표시된 텍스트를 Ctrl+C로 복사하세요.</p>
+ </div>,
+ {
+ duration: 5000,
+ onDismiss: () => {
+ if (document.body.contains(fallbackInput)) {
+ document.body.removeChild(fallbackInput);
+ }
+ }
+ }
+ );
+ }
+
+ } catch (error) {
+ console.error("변수 삽입 오류:", error);
+ toast.error("변수 삽입 중 오류가 발생했습니다.");
+ }
+ };
+
+ const handleDownload = async () => {
+ try {
+ const response = await fetch(filePath);
+ const blob = await response.blob();
+ const url = window.URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.style.display = 'none';
+ a.href = url;
+ a.download = fileName;
+ document.body.appendChild(a);
+ a.click();
+ window.URL.revokeObjectURL(url);
+ toast.success("파일이 다운로드되었습니다.");
+ } catch (error) {
+ console.error("다운로드 오류:", error);
+ toast.error("파일 다운로드 중 오류가 발생했습니다.");
+ }
+ };
+
+ const handleRefresh = () => {
+ window.location.reload();
+ };
+
+ const isReadOnly = mode === "view";
+
+ 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">
+ {!isReadOnly && (
+ <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={handleDownload}
+ >
+ <Download 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">
+ {templateInfo?.projectCode && (
+ <Badge variant="outline">
+ <FileText className="mr-1 h-3 w-3" />
+ {templateInfo.projectCode}
+ </Badge>
+ )}
+ <Badge variant="secondary">
+ {fileName}
+ </Badge>
+ {documentVariables.length > 0 && (
+ <Badge variant="secondary">
+ <Type className="mr-1 h-3 w-3" />
+ 변수 {documentVariables.length}개
+ </Badge>
+ )}
+ </div>
+ </div>
+
+
+ {/* 변수 도구 - Collapsible로 변경 */}
+ {(predefinedVariables.length > 0 || documentVariables.length > 0) && (
+ <Collapsible
+ open={isVariablePanelOpen}
+ onOpenChange={setIsVariablePanelOpen}
+ className="mt-3"
+ >
+ <Card>
+ <CardHeader className="pb-3">
+ <div className="flex items-center justify-between">
+ <CardTitle className="text-sm flex items-center">
+ <Type className="mr-2 h-4 w-4 text-blue-500" />
+ 템플릿 변수 관리
+ {documentVariables.length > 0 && (
+ <Badge variant="secondary" className="ml-2">
+ {documentVariables.length}개
+ </Badge>
+ )}
+ </CardTitle>
+ <CollapsibleTrigger asChild>
+ <Button variant="ghost" size="sm">
+ {isVariablePanelOpen ? (
+ <>
+ <ChevronUp className="h-4 w-4 mr-1" />
+ 접기
+ </>
+ ) : (
+ <>
+ <ChevronDown className="h-4 w-4 mr-1" />
+ 펼치기
+ </>
+ )}
+ </Button>
+ </CollapsibleTrigger>
+ </div>
+ </CardHeader>
+
+ <CollapsibleContent>
+ <CardContent className="space-y-3">
+ {/* 정의된 변수들 */}
+ {predefinedVariables.length > 0 && (
+ <div>
+ <p className="text-xs text-muted-foreground mb-2">정의된 템플릿 변수 (클릭하여 복사):</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-7 px-2 text-xs hover:bg-blue-50"
+ onClick={() => !isReadOnly && insertVariable(variable)}
+ disabled={isReadOnly}
+ >
+ <span className="font-mono">
+ {`{{${variable.name}}}`}
+ </span>
+ {variable.required && (
+ <span className="ml-1 text-red-500">*</span>
+ )}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <div className="space-y-1">
+ <p className="font-medium">{variable.displayName}</p>
+ {variable.description && (
+ <p className="text-xs">{variable.description}</p>
+ )}
+ {variable.defaultValue && (
+ <p className="text-xs">기본값: {variable.defaultValue}</p>
+ )}
+ <p className="text-xs text-muted-foreground">
+ 타입: {variable.type} {variable.required && "(필수)"}
+ </p>
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ ))}
+ </div>
+ </TooltipProvider>
+ </div>
+ )}
+
+ {/* 문서에서 발견된 변수들 */}
+ {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) => {
+ const isDefined = predefinedVariables.find(v => v.name === variable);
+ return (
+ <Badge
+ key={index}
+ variant={isDefined ? "secondary" : "destructive"}
+ className="text-xs"
+ >
+ {`{{${variable}}}`}
+ {!isDefined && (
+ <AlertCircle className="ml-1 h-3 w-3" />
+ )}
+ </Badge>
+ );
+ })}
+ </div>
+ </div>
+ )}
+
+ {/* 변수 사용 안내 */}
+ <div className="mt-3 p-2 bg-blue-50 rounded-lg">
+ <div className="flex items-start">
+ <AlertCircle className="h-4 w-4 text-blue-600 mt-0.5 mr-2 flex-shrink-0" />
+ <div className="text-xs text-blue-900 space-y-1">
+ <p className="font-medium">변수 사용 안내</p>
+ <ul className="list-disc list-inside space-y-0.5">
+ <li>{'{{변수명}}'} 형식으로 문서에 변수를 삽입하세요.</li>
+ <li>필수 변수(*)는 반드시 값이 입력되어야 합니다.</li>
+ <li>한글 입력 제한 시 외부 에디터에서 작성 후 붙여넣기 하세요.</li>
+ </ul>
+ </div>
+ </div>
+ </div>
+ </CardContent>
+ </CollapsibleContent>
+ </Card>
+ </Collapsible>
+ )}
+
+ {/* 업로드 진행률 */}
+ {showProgress && (
+ <div className="mt-3 p-3 bg-white rounded border">
+ <div className="space-y-2">
+ <div className="flex justify-between text-sm">
+ <span>저장 진행률</span>
+ <span>{uploadProgress}%</span>
+ </div>
+ <Progress value={uploadProgress} />
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* 뷰어 영역 */}
+ <div className="flex-1 relative overflow-hidden">
+ <div className="absolute inset-0">
+ <BasicContractTemplateViewer
+ templateId={templateId}
+ filePath={filePath}
+ instance={instance}
+ setInstance={setInstance}
+ />
+ </div>
+ </div>
+ </div>
+ );
+} \ No newline at end of file
diff --git a/lib/project-doc-templates/table/template-detail-dialog.tsx b/lib/project-doc-templates/table/template-detail-dialog.tsx
new file mode 100644
index 00000000..0810a58a
--- /dev/null
+++ b/lib/project-doc-templates/table/template-detail-dialog.tsx
@@ -0,0 +1,121 @@
+// lib/project-doc-template/template-detail-dialog.tsx
+"use client";
+
+import * as React from "react";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Badge } from "@/components/ui/badge";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
+import { ProjectDocTemplateEditor } from "./project-doc-template-editor";
+import { getProjectDocTemplateById } from "@/lib/project-doc-templates/service";
+import type { ProjectDocTemplate } from "@/db/schema/project-doc-templates";
+import { formatDateTime } from "@/lib/utils";
+import { FileText, Clock, User, GitBranch, Variable } from "lucide-react";
+
+interface TemplateDetailDialogProps {
+ template: ProjectDocTemplate;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}
+
+export function TemplateDetailDialog({
+ template,
+ open,
+ onOpenChange,
+}: TemplateDetailDialogProps) {
+ const [templateDetail, setTemplateDetail] = React.useState<any>(null);
+ const [isLoading, setIsLoading] = React.useState(true);
+
+ // 템플릿 상세 정보 로드
+ React.useEffect(() => {
+ if (open && template.id) {
+ setIsLoading(true);
+ getProjectDocTemplateById(template.id)
+ .then(setTemplateDetail)
+ .catch(console.error)
+ .finally(() => setIsLoading(false));
+ }
+ }, [open, template.id]);
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-7xl h-[90vh] p-0 flex flex-col">
+ <DialogHeader className="px-6 py-4 border-b">
+ <DialogTitle className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <FileText className="h-5 w-5" />
+ {template.templateName}
+ </div>
+ <div className="flex gap-2">
+ <Badge variant="outline">v{template.version}</Badge>
+ {template.isLatest && <Badge variant="default">최신</Badge>}
+ <Badge variant="secondary">{template.status}</Badge>
+ </div>
+ </DialogTitle>
+ </DialogHeader>
+
+ <Tabs defaultValue="viewer" className="flex-1 flex flex-col">
+ <TabsList className="mx-6 mt-2">
+ <TabsTrigger value="viewer">문서 보기</TabsTrigger>
+ <TabsTrigger value="history">버전 히스토리</TabsTrigger>
+ </TabsList>
+
+ <TabsContent value="viewer" className="flex-1 mt-0">
+ <div className="h-full">
+ <ProjectDocTemplateEditor
+ templateId={template.id}
+ filePath={template.filePath}
+ fileName={template.fileName}
+ // mode="view" // 읽기 전용 모드
+ />
+ </div>
+ </TabsContent>
+
+
+ <TabsContent value="history" className="flex-1 overflow-y-auto px-6">
+ <div className="space-y-4 py-4">
+ {templateDetail?.versionHistory && templateDetail.versionHistory.length > 0 ? (
+ templateDetail.versionHistory.map((version: any) => (
+ <Card key={version.id} className={version.id === template.id ? "border-primary" : ""}>
+ <CardHeader>
+ <CardTitle className="text-base flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <GitBranch className="h-4 w-4" />
+ 버전 {version.version}
+ </div>
+ <div className="flex gap-2">
+ {version.isLatest && <Badge variant="default">최신</Badge>}
+ {version.id === template.id && <Badge variant="secondary">현재</Badge>}
+ </div>
+ </CardTitle>
+ </CardHeader>
+ <CardContent>
+ <div className="text-sm space-y-1">
+ <p>
+ <span className="text-muted-foreground">생성일:</span> {formatDateTime(version.createdAt, "KR")}
+ </p>
+ <p>
+ <span className="text-muted-foreground">생성자:</span> {version.createdByName || '-'}
+ </p>
+ <p>
+ <span className="text-muted-foreground">파일:</span> {version.fileName}
+ </p>
+ </div>
+ </CardContent>
+ </Card>
+ ))
+ ) : (
+ <p className="text-sm text-muted-foreground">버전 히스토리가 없습니다.</p>
+ )}
+ </div>
+ </TabsContent>
+ </Tabs>
+ </DialogContent>
+ </Dialog>
+ );
+} \ No newline at end of file
diff --git a/lib/project-doc-templates/table/template-edit-sheet.tsx b/lib/project-doc-templates/table/template-edit-sheet.tsx
new file mode 100644
index 00000000..a745045c
--- /dev/null
+++ b/lib/project-doc-templates/table/template-edit-sheet.tsx
@@ -0,0 +1,305 @@
+// lib/project-doc-template/template-edit-sheet.tsx
+"use client";
+
+import * as React from "react";
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
+ SheetFooter,
+} from "@/components/ui/sheet";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Textarea } from "@/components/ui/textarea";
+import { Badge } from "@/components/ui/badge";
+import { Switch } from "@/components/ui/switch";
+import { toast } from "sonner";
+import { updateProjectDocTemplate } from "@/lib/project-doc-templates/service";
+import type { ProjectDocTemplate, DocTemplateVariable } from "@/db/schema/project-doc-templates";
+import { Plus, X, Save, Loader2 } from "lucide-react";
+
+interface TemplateEditSheetProps {
+ template: ProjectDocTemplate | null;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onSuccess?: () => void;
+}
+
+export function TemplateEditSheet({
+ template,
+ open,
+ onOpenChange,
+ onSuccess,
+}: TemplateEditSheetProps) {
+ const [isLoading, setIsLoading] = React.useState(false);
+ const [formData, setFormData] = React.useState({
+ templateName: "",
+ description: "",
+ variables: [] as DocTemplateVariable[],
+ status: "ACTIVE",
+ });
+
+ // 템플릿 데이터 로드
+ React.useEffect(() => {
+ if (template && open) {
+ setFormData({
+ templateName: template.templateName || "",
+ description: template.description || "",
+ variables: template.variables || [],
+ status: template.status || "ACTIVE",
+ });
+ }
+ }, [template, open]);
+
+ // 변수 추가
+ const addVariable = () => {
+ setFormData({
+ ...formData,
+ variables: [
+ ...formData.variables,
+ {
+ name: "",
+ displayName: "",
+ type: "text",
+ required: false,
+ defaultValue: "",
+ description: "",
+ },
+ ],
+ });
+ };
+
+ // 변수 제거
+ const removeVariable = (index: number) => {
+ setFormData({
+ ...formData,
+ variables: formData.variables.filter((_, i) => i !== index),
+ });
+ };
+
+ // 변수 업데이트
+ const updateVariable = (index: number, field: string, value: any) => {
+ const updatedVariables = [...formData.variables];
+ updatedVariables[index] = {
+ ...updatedVariables[index],
+ [field]: value,
+ };
+ setFormData({
+ ...formData,
+ variables: updatedVariables,
+ });
+ };
+
+ // 저장 처리
+ const handleSave = async () => {
+ if (!template) return;
+
+ setIsLoading(true);
+ try {
+ const result = await updateProjectDocTemplate(template.id, {
+ templateName: formData.templateName,
+ description: formData.description,
+ variables: formData.variables,
+ status: formData.status,
+ });
+
+ if (result.success) {
+ toast.success("템플릿이 수정되었습니다.");
+ onOpenChange(false);
+ onSuccess?.();
+ } else {
+ throw new Error(result.error);
+ }
+ } catch (error) {
+ console.error("Failed to update template:", error);
+ toast.error(error instanceof Error ? error.message : "템플릿 수정에 실패했습니다.");
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent className="w-[600px] sm:max-w-[600px] overflow-y-auto">
+ <SheetHeader>
+ <SheetTitle>템플릿 수정</SheetTitle>
+ <SheetDescription>
+ 템플릿 정보와 변수를 수정할 수 있습니다. 파일을 변경하려면 새 버전을 생성하세요.
+ </SheetDescription>
+ </SheetHeader>
+
+ <div className="space-y-6 py-6">
+ {/* 기본 정보 */}
+ <div className="space-y-4">
+ <div>
+ <Label htmlFor="templateName">템플릿 이름</Label>
+ <Input
+ id="templateName"
+ value={formData.templateName}
+ onChange={(e) => setFormData({ ...formData, templateName: e.target.value })}
+ placeholder="템플릿 이름을 입력하세요"
+ />
+ </div>
+
+ <div>
+ <Label htmlFor="description">설명</Label>
+ <Textarea
+ id="description"
+ value={formData.description}
+ onChange={(e) => setFormData({ ...formData, description: e.target.value })}
+ placeholder="템플릿 설명을 입력하세요"
+ className="min-h-[80px]"
+ />
+ </div>
+
+ <div>
+ <Label htmlFor="status">상태</Label>
+ <select
+ id="status"
+ className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
+ value={formData.status}
+ onChange={(e) => setFormData({ ...formData, status: e.target.value })}
+ >
+ <option value="ACTIVE">활성</option>
+ <option value="INACTIVE">비활성</option>
+ <option value="DRAFT">초안</option>
+ <option value="ARCHIVED">보관</option>
+ </select>
+ </div>
+ </div>
+
+ {/* 변수 관리 */}
+ <div>
+ <div className="flex items-center justify-between mb-4">
+ <Label>템플릿 변수</Label>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={addVariable}
+ >
+ <Plus className="mr-2 h-4 w-4" />
+ 변수 추가
+ </Button>
+ </div>
+
+ {/* 기본 변수 표시 */}
+ <div className="mb-4 p-3 bg-muted/50 rounded-lg">
+ <p className="text-xs font-medium mb-2">기본 변수 (수정 불가)</p>
+ <div className="space-y-1">
+ <Badge variant="secondary">document_number</Badge>
+ <Badge variant="secondary" className="ml-2">project_code</Badge>
+ <Badge variant="secondary" className="ml-2">project_name</Badge>
+ </div>
+ </div>
+
+ {/* 사용자 정의 변수 */}
+ {formData.variables.length > 0 ? (
+ <div className="space-y-3">
+ {formData.variables.map((variable, index) => (
+ <div key={index} className="p-3 border rounded-lg space-y-3">
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium">변수 #{index + 1}</span>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => removeVariable(index)}
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ </div>
+
+ <div className="grid grid-cols-2 gap-3">
+ <div>
+ <Label>변수명</Label>
+ <Input
+ value={variable.name}
+ onChange={(e) => updateVariable(index, "name", e.target.value)}
+ placeholder="예: vendor_name"
+ />
+ </div>
+ <div>
+ <Label>표시명</Label>
+ <Input
+ value={variable.displayName}
+ onChange={(e) => updateVariable(index, "displayName", e.target.value)}
+ placeholder="예: 벤더명"
+ />
+ </div>
+ </div>
+
+ <div className="grid grid-cols-2 gap-3">
+ <div>
+ <Label>타입</Label>
+ <select
+ className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
+ value={variable.type}
+ onChange={(e) => updateVariable(index, "type", e.target.value)}
+ >
+ <option value="text">텍스트</option>
+ <option value="number">숫자</option>
+ <option value="date">날짜</option>
+ <option value="select">선택</option>
+ </select>
+ </div>
+ <div className="flex items-center justify-between rounded-lg border p-2">
+ <Label className="text-sm">필수</Label>
+ <Switch
+ checked={variable.required}
+ onCheckedChange={(checked) => updateVariable(index, "required", checked)}
+ />
+ </div>
+ </div>
+
+ <div>
+ <Label>설명</Label>
+ <Input
+ value={variable.description || ""}
+ onChange={(e) => updateVariable(index, "description", e.target.value)}
+ placeholder="변수 설명 (선택사항)"
+ />
+ </div>
+ </div>
+ ))}
+ </div>
+ ) : (
+ <div className="text-center py-4 text-sm text-muted-foreground">
+ 사용자 정의 변수가 없습니다.
+ </div>
+ )}
+ </div>
+ </div>
+
+ <SheetFooter>
+ <Button
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ disabled={isLoading}
+ >
+ 취소
+ </Button>
+ <Button
+ onClick={handleSave}
+ disabled={isLoading}
+ >
+ {isLoading ? (
+ <>
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ 저장 중...
+ </>
+ ) : (
+ <>
+ <Save className="mr-2 h-4 w-4" />
+ 저장
+ </>
+ )}
+ </Button>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ );
+} \ No newline at end of file