From 4bad21ef79fdda5f016e2012ba673d6ee6abb5fc Mon Sep 17 00:00:00 2001
From: dujinkim <dujin.kim@dtsolution.co.kr>
Date: Wed, 28 May 2025 17:23:13 +0000
Subject: (대표님) lib 파트 개발 0528
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 .../table/revision-upload-dialog.tsx               | 75 +++++++++++++++++-----
 1 file changed, 59 insertions(+), 16 deletions(-)

(limited to 'lib/vendor-document-list/table/revision-upload-dialog.tsx')

diff --git a/lib/vendor-document-list/table/revision-upload-dialog.tsx b/lib/vendor-document-list/table/revision-upload-dialog.tsx
index ac58b974..546fa7a3 100644
--- a/lib/vendor-document-list/table/revision-upload-dialog.tsx
+++ b/lib/vendor-document-list/table/revision-upload-dialog.tsx
@@ -7,6 +7,7 @@ import { z } from "zod"
 import { toast } from "sonner"
 import { useRouter } from "next/navigation"
 import { useSession } from "next-auth/react"
+import { mutate } from "swr" // ✅ SWR mutate import 추가
 
 import {
   Dialog,
@@ -77,6 +78,11 @@ interface RevisionUploadDialogProps {
   presetStage?: string
   presetRevision?: string
   mode?: 'new' | 'append'
+  onUploadComplete?: () => void // ✅ 업로드 완료 콜백 추가
+}
+
+function getTargetSystem(projectType: "ship" | "plant") {
+  return projectType === "ship" ? "DOLCE" : "SWP"
 }
 
 export function RevisionUploadDialog({
@@ -87,12 +93,19 @@ export function RevisionUploadDialog({
   presetStage,
   presetRevision,
   mode = 'new',
+  onUploadComplete, // ✅ 추가된 prop
 }: RevisionUploadDialogProps) {
+
+  const targetSystem = React.useMemo(
+    () => getTargetSystem(projectType),
+    [projectType]
+  )
+
   const [selectedFiles, setSelectedFiles] = React.useState<File[]>([])
   const [isUploading, setIsUploading] = React.useState(false)
   const [uploadProgress, setUploadProgress] = React.useState(0)
   const router = useRouter()
-  
+
   // ✅ next-auth session 가져오기
   const { data: session } = useSession()
 
@@ -109,7 +122,7 @@ export function RevisionUploadDialog({
     defaultValues: {
       stage: presetStage || document?.currentStageName || "",
       revision: presetRevision || "",
-      uploaderName: session?.user?.name || "", // ✅ session.user.name 사용
+      uploaderName: session?.user?.name || "",
       comment: "",
       attachments: [],
     },
@@ -146,6 +159,34 @@ export function RevisionUploadDialog({
     form.setValue('attachments', updatedFiles, { shouldValidate: true })
   }
 
+  // ✅ 캐시 갱신 함수
+  const refreshCaches = async () => {
+    try {
+      // 1. 서버 컴포넌트 캐시 갱신 (Enhanced Documents 등)
+      router.refresh()
+      
+      // 2. SWR 캐시 갱신 (Sync Status)
+      if (document?.contractId) {
+        await mutate(`/api/sync/status/${document.contractId}/${targetSystem}`)
+        console.log('✅ Sync status cache refreshed')
+      }
+      
+      // 3. 다른 관련 SWR 캐시들도 갱신 (필요시)
+      await mutate(key => 
+        typeof key === 'string' && 
+        key.includes('sync') && 
+        key.includes(String(document?.contractId))
+      )
+      
+      // 4. 상위 컴포넌트 콜백 호출
+      onUploadComplete?.()
+      
+      console.log('✅ All caches refreshed after upload')
+    } catch (error) {
+      console.error('❌ Cache refresh failed:', error)
+    }
+  }
+
   // 업로드 처리
   async function onSubmit(data: RevisionUploadSchema) {
     if (!document) return
@@ -158,8 +199,9 @@ export function RevisionUploadDialog({
       formData.append("documentId", String(document.documentId))
       formData.append("stage", data.stage)
       formData.append("revision", data.revision)
-      formData.append("mode", mode) // 'new' 또는 'append'
-      
+      formData.append("mode", mode)
+      formData.append("targetSystem", targetSystem)
+
       if (data.uploaderName) {
         formData.append("uploaderName", data.uploaderName)
       }
@@ -175,7 +217,7 @@ export function RevisionUploadDialog({
 
       // 진행률 업데이트 시뮬레이션
       const updateProgress = (progress: number) => {
-        setUploadProgress(Math.min(progress, 95)) // 95%까지만 진행률 표시
+        setUploadProgress(Math.min(progress, 95))
       }
 
       // 파일 크기에 따른 진행률 시뮬레이션
@@ -183,7 +225,7 @@ export function RevisionUploadDialog({
       let uploadedSize = 0
       
       const progressInterval = setInterval(() => {
-        uploadedSize += totalSize * 0.1 // 10%씩 증가 시뮬레이션
+        uploadedSize += totalSize * 0.1
         const progress = Math.min((uploadedSize / totalSize) * 100, 90)
         updateProgress(progress)
       }, 300)
@@ -211,10 +253,10 @@ export function RevisionUploadDialog({
       
       console.log('✅ 업로드 성공:', result)
       
-      // 잠시 대기 후 다이얼로그 닫기
-      setTimeout(() => {
+      // ✅ 캐시 갱신 및 다이얼로그 닫기
+      setTimeout(async () => {
+        await refreshCaches()
         handleDialogClose()
-        router.refresh()
       }, 1000)
 
     } catch (error) {
@@ -222,7 +264,7 @@ export function RevisionUploadDialog({
       toast.error(error instanceof Error ? error.message : "업로드 중 오류가 발생했습니다")
     } finally {
       setIsUploading(false)
-      setTimeout(() => setUploadProgress(0), 2000) // 2초 후 진행률 리셋
+      setTimeout(() => setUploadProgress(0), 2000)
     }
   }
 
@@ -230,7 +272,7 @@ export function RevisionUploadDialog({
     form.reset({
       stage: presetStage || document?.currentStageName || "",
       revision: presetRevision || "",
-      uploaderName: session?.user?.name || "", // ✅ 다이얼로그 닫을 때도 session 값으로 리셋
+      uploaderName: session?.user?.name || "",
       comment: "",
       attachments: [],
     })
@@ -257,13 +299,15 @@ export function RevisionUploadDialog({
             <Badge variant={projectType === "ship" ? "default" : "secondary"}>
               {projectType === "ship" ? "조선 프로젝트" : "플랜트 프로젝트"}
             </Badge>
-            {/* ✅ 현재 사용자 정보 표시 */}
+            {/* ✅ 타겟 시스템 표시 추가 */}
+            <Badge variant="outline" className="text-xs">
+              → {targetSystem}
+            </Badge>
             {session?.user?.name && (
               <Badge variant="outline" className="text-xs">
                 업로더: {session.user.name}
               </Badge>
             )}
-            {/* ✅ 모드에 따른 정보 표시 */}
             {mode === 'append' && presetRevision && (
               <Badge variant="outline" className="text-xs">
                 리비전 {presetRevision}에 파일 추가
@@ -320,7 +364,6 @@ export function RevisionUploadDialog({
                       />
                     </FormControl>
                     <FormMessage />
-                    {/* ✅ 모드에 따른 도움말 표시 */}
                     {mode === 'new' && presetRevision && (
                       <p className="text-xs text-gray-500">
                         자동으로 계산된 다음 리비전입니다.
@@ -346,7 +389,7 @@ export function RevisionUploadDialog({
                     <Input 
                       {...field} 
                       placeholder="업로더 이름을 입력하세요"
-                      className="bg-gray-50" // ✅ session 값이므로 읽기 전용 느낌으로 스타일링
+                      className="bg-gray-50"
                     />
                   </FormControl>
                   <FormMessage />
@@ -420,7 +463,7 @@ export function RevisionUploadDialog({
                           <FileListIcon />
                           <FileListInfo>
                             <FileListName>{file.name}</FileListName>
-                            <FileListSize>{prettyBytes(file.size)}</FileListSize>
+                            <FileListSize>{file.size}</FileListSize>
                           </FileListInfo>
                           <FileListAction 
                             onClick={() => removeFile(index)} 
-- 
cgit v1.2.3

