From af813883db9bae24755e05205647954fd0ab1270 Mon Sep 17 00:00:00 2001
From: joonhoekim <26rote@gmail.com>
Date: Mon, 24 Nov 2025 15:38:35 +0900
Subject: (김준회) dolce 파일업로드 개선 및 nginx conf 수정(커밋관리X)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 lib/dolce/dialogs/b4-bulk-upload-dialog.tsx | 172 ++++++++++++++++++++--------
 1 file changed, 125 insertions(+), 47 deletions(-)

(limited to 'lib/dolce/dialogs/b4-bulk-upload-dialog.tsx')

diff --git a/lib/dolce/dialogs/b4-bulk-upload-dialog.tsx b/lib/dolce/dialogs/b4-bulk-upload-dialog.tsx
index f4816328..cd336e92 100644
--- a/lib/dolce/dialogs/b4-bulk-upload-dialog.tsx
+++ b/lib/dolce/dialogs/b4-bulk-upload-dialog.tsx
@@ -29,10 +29,11 @@ import {
 } from "./b4-upload-validation-dialog";
 import {
   checkB4MappingStatus,
-  bulkUploadB4Files,
+  editDetailDwgReceipt,
   type MappingCheckItem,
   type B4BulkUploadResult,
 } from "../actions";
+import { v4 as uuidv4 } from "uuid";
 
 interface B4BulkUploadDialogProps {
   open: boolean;
@@ -266,62 +267,139 @@ export function B4BulkUploadDialog({
     setCurrentStep("uploading");
     setShowValidationDialog(false);
 
-    // 진행률 시뮬레이션
-    const progressInterval = setInterval(() => {
-      setUploadProgress((prev) => {
-        if (prev >= 90) {
-          clearInterval(progressInterval);
-          return prev;
+    try {
+      console.log(`[B4 일괄 업로드] 시작: ${validFiles.length}개 파일`);
+
+      // 파일을 DrawingNo + RevNo로 그룹화
+      const uploadGroups = new Map<
+        string,
+        Array<{
+          file: File;
+          drawingNo: string;
+          revNo: string;
+          fileName: string;
+          registerGroupId: number;
+        }>
+      >();
+
+      validFiles.forEach((fileResult) => {
+        const groupKey = `${fileResult.parsed!.drawingNo}_${fileResult.parsed!.revNo}`;
+        if (!uploadGroups.has(groupKey)) {
+          uploadGroups.set(groupKey, []);
         }
-        return prev + 10;
+        uploadGroups.get(groupKey)!.push({
+          file: fileResult.file,
+          drawingNo: fileResult.parsed!.drawingNo,
+          revNo: fileResult.parsed!.revNo,
+          fileName: fileResult.file.name,
+          registerGroupId: fileResult.registerGroupId || 0,
+        });
       });
-    }, 500);
 
-    try {
-      // FormData 생성
-      const formData = new FormData();
-      formData.append("projectNo", projectNo);
-      formData.append("userId", userId);
-      formData.append("userName", userName);
-      formData.append("userEmail", userEmail);
-      formData.append("vendorCode", vendorCode);
-      formData.append("registerKind", registerKind); // RegisterKind 추가
-
-      // 파일 및 메타데이터 추가
-      validFiles.forEach((fileResult, index) => {
-        formData.append(`file_${index}`, fileResult.file);
-        formData.append(`drawingNo_${index}`, fileResult.parsed!.drawingNo);
-        formData.append(`revNo_${index}`, fileResult.parsed!.revNo);
-        formData.append(`fileName_${index}`, fileResult.file.name);
-        formData.append(
-          `registerGroupId_${index}`,
-          String(fileResult.registerGroupId || 0)
-        );
-      });
+      console.log(`[B4 일괄 업로드] ${uploadGroups.size}개 그룹으로 묶임`);
+
+      let successCount = 0;
+      let failCount = 0;
+      let completedGroups = 0;
+
+      // 각 그룹별로 순차 처리
+      for (const [groupKey, files] of uploadGroups.entries()) {
+        const { drawingNo, revNo, registerGroupId } = files[0];
+
+        try {
+          console.log(`[B4 업로드] 그룹 ${groupKey}: ${files.length}개 파일`);
+
+          // 1. UploadId 생성
+          const uploadId = uuidv4();
+
+          // 2. 파일 업로드 (공통 API 사용)
+          const formData = new FormData();
+          formData.append("uploadId", uploadId);
+          formData.append("userId", userId);
+          formData.append("fileCount", String(files.length));
+
+          files.forEach((fileInfo, index) => {
+            formData.append(`file_${index}`, fileInfo.file);
+          });
+
+          const uploadResponse = await fetch("/api/dolce/upload-files", {
+            method: "POST",
+            body: formData,
+          });
+
+          if (!uploadResponse.ok) {
+            throw new Error(`파일 업로드 실패: ${uploadResponse.status}`);
+          }
+
+          const uploadResult = await uploadResponse.json();
+
+          if (!uploadResult.success) {
+            throw new Error(uploadResult.error || "파일 업로드 실패");
+          }
+
+          console.log(`[B4 업로드] 그룹 ${groupKey} 파일 업로드 완료`);
+
+          // 3. 상세도면 등록
+          await editDetailDwgReceipt({
+            dwgList: [
+              {
+                Mode: "ADD",
+                Status: "Draft",
+                RegisterId: 0,
+                ProjectNo: projectNo,
+                Discipline: "",
+                DrawingKind: "B4",
+                DrawingNo: drawingNo,
+                DrawingName: "",
+                RegisterGroupId: registerGroupId,
+                RegisterSerialNo: 0,
+                RegisterKind: registerKind,
+                DrawingRevNo: revNo,
+                Category: "TS",
+                Receiver: null,
+                Manager: "",
+                RegisterDesc: "",
+                UploadId: uploadId,
+                RegCompanyCode: vendorCode,
+              },
+            ],
+            userId,
+            userNm: userName,
+            vendorCode,
+            email: userEmail,
+          });
+
+          console.log(`[B4 업로드] 그룹 ${groupKey} 상세도면 등록 완료`);
+
+          successCount += files.length;
+        } catch (error) {
+          console.error(`[B4 업로드] 그룹 ${groupKey} 실패:`, error);
+          failCount += files.length;
+        }
 
-      formData.append("fileCount", String(validFiles.length));
+        // 진행도 업데이트
+        completedGroups++;
+        const progress = Math.round((completedGroups / uploadGroups.size) * 100);
+        setUploadProgress(progress);
+      }
 
-      // 서버 액션 호출
-      const result: B4BulkUploadResult = await bulkUploadB4Files(formData);
+      console.log(`[B4 일괄 업로드] ✅ 완료: 성공 ${successCount}, 실패 ${failCount}`);
 
-      clearInterval(progressInterval);
-      setUploadProgress(100);
-      setUploadResult(result);
+      const result: B4BulkUploadResult = {
+        success: true,
+        successCount,
+        failCount,
+      };
 
-      if (result.success) {
-        setCurrentStep("complete");
-        toast.success(
-          `${result.successCount}/${validFiles.length}개 파일 업로드 완료`
-        );
-      } else {
-        setCurrentStep("files");
-        toast.error(result.error || "업로드 실패");
-      }
+      setUploadResult(result);
+      setCurrentStep("complete");
+      toast.success(`${successCount}/${validFiles.length}개 파일 업로드 완료`);
     } catch (error) {
-      console.error("업로드 실패:", error);
+      console.error("[B4 일괄 업로드] 실패:", error);
       toast.error(
         error instanceof Error ? error.message : "업로드 중 오류가 발생했습니다"
       );
+      setCurrentStep("files");
     } finally {
       setIsUploading(false);
     }
@@ -460,7 +538,7 @@ export function B4BulkUploadDialog({
                         전체 제거
                       </Button>
                     </div>
-                    <div className="max-h-48 overflow-auto space-y-2">
+                    <div className="max-h-60 overflow-y-auto space-y-2">
                       {selectedFiles.map((file, index) => (
                         <div
                           key={index}
-- 
cgit v1.2.3

