From 9e956999c56860d40da08bcefc7109d07afc7e9c Mon Sep 17 00:00:00 2001 From: kjs Date: Fri, 5 Dec 2025 10:46:10 +0900 Subject: [PATCH 01/18] =?UTF-8?q?=EB=AA=A8=EB=8B=AC=20=ED=81=AC=EA=B8=B0?= =?UTF-8?q?=20=EA=B3=A0=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/components/admin/AddColumnModal.tsx | 34 +- .../components/admin/AdvancedBatchModal.tsx | 2 +- frontend/components/admin/BatchJobModal.tsx | 22 +- .../admin/CodeCategoryFormModal.tsx | 16 +- frontend/components/admin/CodeFormModal.tsx | 16 +- .../admin/CollectionConfigModal.tsx | 22 +- .../components/admin/CompanyFormModal.tsx | 32 +- .../components/admin/CreateTableModal.tsx | 38 +- frontend/components/admin/DDLLogViewer.tsx | 28 +- .../admin/ExternalCallConfigModal.tsx | 34 +- .../admin/ExternalDbConnectionModal.tsx | 34 +- frontend/components/admin/LangKeyModal.tsx | 26 +- frontend/components/admin/LanguageModal.tsx | 26 +- frontend/components/admin/LayoutFormModal.tsx | 24 +- frontend/components/admin/MenuFormModal.tsx | 26 +- .../admin/RestApiConnectionModal.tsx | 32 +- frontend/components/admin/RoleDeleteModal.tsx | 32 +- frontend/components/admin/RoleFormModal.tsx | 32 +- frontend/components/admin/SqlQueryModal.tsx | 36 +- frontend/components/admin/TableLogViewer.tsx | 28 +- .../components/admin/TemplateImportExport.tsx | 2 +- frontend/components/admin/UserFormModal.tsx | 30 +- .../components/admin/UserHistoryModal.tsx | 26 +- .../admin/UserPasswordResetModal.tsx | 16 +- .../admin/dashboard/DashboardDesigner.tsx | 30 +- .../admin/dashboard/DashboardSaveModal.tsx | 32 +- .../admin/dashboard/MenuAssignmentModal.tsx | 34 +- .../widgets/yard-3d/MaterialAddModal.tsx | 30 +- .../widgets/yard-3d/MaterialLibrary.tsx | 2 +- .../widgets/yard-3d/YardLayoutCreateModal.tsx | 34 +- .../components/common/BarcodeScanModal.tsx | 47 +- .../components/common/ExcelUploadModal.tsx | 54 +- frontend/components/common/ScreenModal.tsx | 58 +- .../components/common/TableHistoryModal.tsx | 20 +- .../components/common/TableOptionsModal.tsx | 47 +- .../dataflow/ConnectionSetupModal.tsx | 34 +- .../components/dataflow/SaveDiagramModal.tsx | 34 +- .../node-editor/dialogs/LoadFlowDialog.tsx | 2 +- .../components/flow/FlowDataListModal.tsx | 8 +- frontend/components/layout/ProfileModal.tsx | 68 +- frontend/components/mail/MailDetailModal.tsx | 18 +- .../components/multilang/LangKeyModal.tsx | 6 +- .../order/OrderRegistrationModal.tsx | 2 +- .../components/report/ReportCreateModal.tsx | 15 +- .../components/screen/CopyScreenModal.tsx | 2 +- .../components/screen/CreateScreenModal.tsx | 40 +- frontend/components/screen/EditModal.tsx | 55 +- .../screen/FileAttachmentDetailModal.tsx | 6 +- .../screen/InteractiveDataTable.tsx | 6 +- .../screen/InteractiveScreenViewer.tsx | 2 +- .../screen/InteractiveScreenViewerDynamic.tsx | 27 +- .../components/screen/MenuAssignmentModal.tsx | 76 +-- .../screen/ResponsivePreviewModal.tsx | 4 +- frontend/components/screen/SaveModal.tsx | 25 +- .../screen/templates/DataTableTemplate.tsx | 2 +- frontend/components/ui/dialog.tsx | 6 +- frontend/components/ui/resizable-dialog.tsx | 601 ------------------ .../components/webtypes/RepeaterInput.tsx | 91 ++- .../card-display/CardDisplayComponent.tsx | 4 +- .../entity-search-input/EntitySearchModal.tsx | 2 +- .../file-upload/FileViewerModal.tsx | 4 +- .../ItemSelectionModal.tsx | 6 +- .../table-list/TableListComponent.tsx | 90 ++- .../table-list/TableListConfigPanel.tsx | 193 +++--- ..._임베딩_및_데이터_전달_시스템_구현_계획서.md | 1 + 화면_임베딩_시스템_Phase1-4_구현_완료.md | 1 + 화면_임베딩_시스템_충돌_분석_보고서.md | 1 + 67 files changed, 969 insertions(+), 1465 deletions(-) delete mode 100644 frontend/components/ui/resizable-dialog.tsx diff --git a/frontend/components/admin/AddColumnModal.tsx b/frontend/components/admin/AddColumnModal.tsx index 6b9467d9..550c46fc 100644 --- a/frontend/components/admin/AddColumnModal.tsx +++ b/frontend/components/admin/AddColumnModal.tsx @@ -7,13 +7,13 @@ import { useState, useEffect } from "react"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogDescription, - ResizableDialogFooter, -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, +} from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; @@ -197,14 +197,14 @@ export function AddColumnModal({ isOpen, onClose, tableName, onSuccess }: AddCol const inputTypeOption = INPUT_TYPE_OPTIONS.find((opt) => opt.value === column.inputType); return ( - - - - + + + + 컬럼 추가 - {tableName} - - + +
{/* 검증 오류 표시 */} @@ -346,7 +346,7 @@ export function AddColumnModal({ isOpen, onClose, tableName, onSuccess }: AddCol
- + @@ -365,8 +365,8 @@ export function AddColumnModal({ isOpen, onClose, tableName, onSuccess }: AddCol "컬럼 추가" )} - -
-
+ + + ); } diff --git a/frontend/components/admin/AdvancedBatchModal.tsx b/frontend/components/admin/AdvancedBatchModal.tsx index b1667c36..1276bcad 100644 --- a/frontend/components/admin/AdvancedBatchModal.tsx +++ b/frontend/components/admin/AdvancedBatchModal.tsx @@ -198,7 +198,7 @@ export default function AdvancedBatchModal({ return ( - + 고급 배치 생성 diff --git a/frontend/components/admin/BatchJobModal.tsx b/frontend/components/admin/BatchJobModal.tsx index cc9ca22f..b3fbb0e9 100644 --- a/frontend/components/admin/BatchJobModal.tsx +++ b/frontend/components/admin/BatchJobModal.tsx @@ -7,7 +7,7 @@ import { DialogHeader, -} from "@/components/ui/resizable-dialog"; +} from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; @@ -169,13 +169,13 @@ export default function BatchJobModal({ // 상태 제거 - 필요없음 return ( - - - - + + + + {job ? "배치 작업 수정" : "새 배치 작업"} - - + +
{/* 기본 정보 */} @@ -344,7 +344,7 @@ export default function BatchJobModal({ - + - +
-
-
+
+
); } diff --git a/frontend/components/admin/CodeCategoryFormModal.tsx b/frontend/components/admin/CodeCategoryFormModal.tsx index c7c62818..0ba970e0 100644 --- a/frontend/components/admin/CodeCategoryFormModal.tsx +++ b/frontend/components/admin/CodeCategoryFormModal.tsx @@ -3,7 +3,7 @@ import { useEffect } from "react"; import { useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; -import { ResizableDialog, ResizableDialogContent, ResizableDialogHeader, DialogTitle } from "@/components/ui/resizable-dialog"; +import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Textarea } from "@/components/ui/textarea"; @@ -164,11 +164,11 @@ export function CodeCategoryFormModal({ const isLoading = createCategoryMutation.isPending || updateCategoryMutation.isPending; return ( - - - - {isEditing ? "카테고리 수정" : "새 카테고리"} - + + + + {isEditing ? "카테고리 수정" : "새 카테고리"} +
{/* 카테고리 코드 */} @@ -383,7 +383,7 @@ export function CodeCategoryFormModal({
-
-
+ + ); } diff --git a/frontend/components/admin/CodeFormModal.tsx b/frontend/components/admin/CodeFormModal.tsx index 2d6c7d39..977e9e84 100644 --- a/frontend/components/admin/CodeFormModal.tsx +++ b/frontend/components/admin/CodeFormModal.tsx @@ -3,7 +3,7 @@ import { useEffect, useState } from "react"; import { useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; -import { ResizableDialog, ResizableDialogContent, ResizableDialogHeader, DialogTitle } from "@/components/ui/resizable-dialog"; +import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Textarea } from "@/components/ui/textarea"; @@ -153,11 +153,11 @@ export function CodeFormModal({ isOpen, onClose, categoryCode, editingCode, code const isLoading = createCodeMutation.isPending || updateCodeMutation.isPending; return ( - - - - {isEditing ? "코드 수정" : "새 코드"} - + + + + {isEditing ? "코드 수정" : "새 코드"} +
{/* 코드값 */} @@ -328,7 +328,7 @@ export function CodeFormModal({ isOpen, onClose, categoryCode, editingCode, code
-
-
+ + ); } diff --git a/frontend/components/admin/CollectionConfigModal.tsx b/frontend/components/admin/CollectionConfigModal.tsx index ef5e4998..ea099bfa 100644 --- a/frontend/components/admin/CollectionConfigModal.tsx +++ b/frontend/components/admin/CollectionConfigModal.tsx @@ -7,7 +7,7 @@ import { DialogHeader, -} from "@/components/ui/resizable-dialog"; +} from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; @@ -164,13 +164,13 @@ export default function CollectionConfigModal({ ]; return ( - - - - + + + + {config ? "수집 설정 수정" : "새 수집 설정"} - - + +
{/* 기본 정보 */} @@ -331,16 +331,16 @@ export default function CollectionConfigModal({ - + - +
-
-
+ + ); } diff --git a/frontend/components/admin/CompanyFormModal.tsx b/frontend/components/admin/CompanyFormModal.tsx index 56b79294..91cff911 100644 --- a/frontend/components/admin/CompanyFormModal.tsx +++ b/frontend/components/admin/CompanyFormModal.tsx @@ -4,13 +4,13 @@ import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogDescription, - ResizableDialogFooter, -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, +} from "@/components/ui/dialog"; import { LoadingSpinner } from "@/components/common/LoadingSpinner"; import { validateBusinessNumber, formatBusinessNumber } from "@/lib/validation/businessNumber"; @@ -111,8 +111,8 @@ export function CompanyFormModal({ }; return ( - - + - - {isEditMode ? "회사 정보 수정" : "새 회사 등록"} - + + {isEditMode ? "회사 정보 수정" : "새 회사 등록"} +
{/* 회사명 입력 (필수) */} @@ -255,7 +255,7 @@ export function CompanyFormModal({ )}
- + @@ -273,8 +273,8 @@ export function CompanyFormModal({ {(isLoading || isSaving) && } {isEditMode ? "수정" : "등록"} - -
-
+ + + ); } diff --git a/frontend/components/admin/CreateTableModal.tsx b/frontend/components/admin/CreateTableModal.tsx index 8de74c32..ecb6b03f 100644 --- a/frontend/components/admin/CreateTableModal.tsx +++ b/frontend/components/admin/CreateTableModal.tsx @@ -7,13 +7,13 @@ import { useState, useEffect } from "react"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogDescription, - ResizableDialogFooter, -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, +} from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; @@ -321,20 +321,20 @@ export function CreateTableModal({ const isFormValid = !tableNameError && tableName && columns.some((col) => col.name && col.inputType); return ( - - - - + + + + {isDuplicateMode ? "테이블 복제" : "새 테이블 생성"} - - + + {isDuplicateMode ? `${sourceTableName} 테이블을 복제하여 새 테이블을 생성합니다. 테이블명을 입력하고 필요시 컬럼을 수정하세요.` : "최고 관리자만 새로운 테이블을 생성할 수 있습니다. 테이블명과 컬럼 정의를 입력하고 검증 후 생성하세요." } - - + +
{/* 테이블 기본 정보 */} @@ -452,7 +452,7 @@ export function CreateTableModal({ )}
- + @@ -482,8 +482,8 @@ export function CreateTableModal({ isDuplicateMode ? "복제 생성" : "테이블 생성" )} - -
-
+ + + ); } diff --git a/frontend/components/admin/DDLLogViewer.tsx b/frontend/components/admin/DDLLogViewer.tsx index d4441056..f707511b 100644 --- a/frontend/components/admin/DDLLogViewer.tsx +++ b/frontend/components/admin/DDLLogViewer.tsx @@ -7,12 +7,12 @@ import { useState, useEffect } from "react"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogFooter -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogFooter +} from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Badge } from "@/components/ui/badge"; @@ -148,14 +148,14 @@ export function DDLLogViewer({ isOpen, onClose }: DDLLogViewerProps) { }; return ( - - - - + + + + DDL 실행 로그 및 통계 - - + + @@ -407,7 +407,7 @@ export function DDLLogViewer({ isOpen, onClose }: DDLLogViewerProps) { )} - - + + ); } diff --git a/frontend/components/admin/ExternalCallConfigModal.tsx b/frontend/components/admin/ExternalCallConfigModal.tsx index 0217977a..30694034 100644 --- a/frontend/components/admin/ExternalCallConfigModal.tsx +++ b/frontend/components/admin/ExternalCallConfigModal.tsx @@ -6,13 +6,13 @@ import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Textarea } from "@/components/ui/textarea"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogDescription, - ResizableDialogFooter, -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, +} from "@/components/ui/dialog"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { toast } from "sonner"; import { @@ -266,13 +266,13 @@ export function ExternalCallConfigModal({ isOpen, onClose, onSave, editingConfig }; return ( - - - - + + + + {editingConfig ? "외부 호출 설정 편집" : "새 외부 호출 설정"} - - + +
{/* 기본 정보 */} @@ -564,7 +564,7 @@ export function ExternalCallConfigModal({ isOpen, onClose, onSave, editingConfig )}
- + - -
-
+ + + ); } diff --git a/frontend/components/admin/ExternalDbConnectionModal.tsx b/frontend/components/admin/ExternalDbConnectionModal.tsx index 1d0c046f..f5631297 100644 --- a/frontend/components/admin/ExternalDbConnectionModal.tsx +++ b/frontend/components/admin/ExternalDbConnectionModal.tsx @@ -8,13 +8,13 @@ import { Label } from "@/components/ui/label"; import { Textarea } from "@/components/ui/textarea"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogDescription, - ResizableDialogFooter, -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, +} from "@/components/ui/dialog"; import { useToast } from "@/hooks/use-toast"; import { ExternalDbConnectionAPI, @@ -311,13 +311,13 @@ export const ExternalDbConnectionModal: React.FC }; return ( - - - - + + + + {isEditMode ? "연결 정보 수정" : "새 외부 DB 연결 추가"} - - + +
{/* 기본 정보 */} @@ -607,7 +607,7 @@ export const ExternalDbConnectionModal: React.FC
- + - -
-
+ + + ); }; diff --git a/frontend/components/admin/LangKeyModal.tsx b/frontend/components/admin/LangKeyModal.tsx index 034ca213..6801e873 100644 --- a/frontend/components/admin/LangKeyModal.tsx +++ b/frontend/components/admin/LangKeyModal.tsx @@ -2,12 +2,12 @@ import { useState, useEffect } from "react"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogFooter, -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogFooter, +} from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; @@ -66,11 +66,11 @@ export default function LangKeyModal({ isOpen, onClose, onSave, keyData, compani }; return ( - - - - {keyData ? "언어 키 수정" : "새 언어 키 추가"} - + + + + {keyData ? "언어 키 수정" : "새 언어 키 추가"} +
@@ -131,7 +131,7 @@ export default function LangKeyModal({ isOpen, onClose, onSave, keyData, compani
-
-
+ + ); } diff --git a/frontend/components/admin/LanguageModal.tsx b/frontend/components/admin/LanguageModal.tsx index a50f12ef..908ebf0a 100644 --- a/frontend/components/admin/LanguageModal.tsx +++ b/frontend/components/admin/LanguageModal.tsx @@ -2,12 +2,12 @@ import { useState, useEffect } from "react"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogFooter, -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogFooter, +} from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; @@ -68,11 +68,11 @@ export default function LanguageModal({ isOpen, onClose, onSave, languageData }: }; return ( - - - - {languageData ? "언어 수정" : "새 언어 추가"} - + + + + {languageData ? "언어 수정" : "새 언어 추가"} +
@@ -141,8 +141,8 @@ export default function LanguageModal({ isOpen, onClose, onSave, languageData }:
- - + +
); } diff --git a/frontend/components/admin/LayoutFormModal.tsx b/frontend/components/admin/LayoutFormModal.tsx index da6b0f3a..a4bcdf4f 100644 --- a/frontend/components/admin/LayoutFormModal.tsx +++ b/frontend/components/admin/LayoutFormModal.tsx @@ -13,7 +13,7 @@ import { DialogHeader, -} from "@/components/ui/resizable-dialog"; +} from "@/components/ui/dialog"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { Badge } from "@/components/ui/badge"; import { Alert, AlertDescription } from "@/components/ui/alert"; @@ -225,14 +225,14 @@ export const LayoutFormModal: React.FC = ({ open, onOpenCh }; return ( - - - - + + + + 새 레이아웃 생성 - - GUI를 통해 새로운 레이아웃을 쉽게 생성할 수 있습니다. - + + GUI를 통해 새로운 레이아웃을 쉽게 생성할 수 있습니다. + {/* 단계 표시기 */}
@@ -499,7 +499,7 @@ export const LayoutFormModal: React.FC = ({ open, onOpenCh )}
- + {step !== "basic" && !generationResult && ( - -
-
+ + + ); }; diff --git a/frontend/components/admin/MenuFormModal.tsx b/frontend/components/admin/MenuFormModal.tsx index 33d2447e..43f17b52 100644 --- a/frontend/components/admin/MenuFormModal.tsx +++ b/frontend/components/admin/MenuFormModal.tsx @@ -9,11 +9,11 @@ import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Textarea } from "@/components/ui/textarea"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle +} from "@/components/ui/dialog"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"; import { toast } from "sonner"; @@ -684,15 +684,15 @@ export const MenuFormModal: React.FC = ({ }; return ( - - - - + + + + {isEdit ? getText(MENU_MANAGEMENT_KEYS.MODAL_MENU_MODIFY_TITLE) : getText(MENU_MANAGEMENT_KEYS.MODAL_MENU_REGISTER_TITLE)} - - + +
@@ -1067,7 +1067,7 @@ export const MenuFormModal: React.FC = ({
-
-
+ + ); }; diff --git a/frontend/components/admin/RestApiConnectionModal.tsx b/frontend/components/admin/RestApiConnectionModal.tsx index 3de34800..95ac6e76 100644 --- a/frontend/components/admin/RestApiConnectionModal.tsx +++ b/frontend/components/admin/RestApiConnectionModal.tsx @@ -8,13 +8,13 @@ import { Label } from "@/components/ui/label"; import { Textarea } from "@/components/ui/textarea"; import { Switch } from "@/components/ui/switch"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogDescription, - ResizableDialogFooter, -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, +} from "@/components/ui/dialog"; import { useToast } from "@/hooks/use-toast"; import { ExternalRestApiConnectionAPI, @@ -271,11 +271,11 @@ export function RestApiConnectionModal({ isOpen, onClose, onSave, connection }: }; return ( - - - - {connection ? "REST API 연결 수정" : "새 REST API 연결 추가"} - + + + + {connection ? "REST API 연결 수정" : "새 REST API 연결 추가"} +
{/* 기본 정보 */} @@ -574,7 +574,7 @@ export function RestApiConnectionModal({ isOpen, onClose, onSave, connection }:
- + - -
-
+ + + ); } diff --git a/frontend/components/admin/RoleDeleteModal.tsx b/frontend/components/admin/RoleDeleteModal.tsx index 9d178351..9f3cf75a 100644 --- a/frontend/components/admin/RoleDeleteModal.tsx +++ b/frontend/components/admin/RoleDeleteModal.tsx @@ -2,13 +2,13 @@ import React, { useState, useCallback } from "react"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogDescription, - ResizableDialogFooter, -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, +} from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { roleAPI, RoleGroup } from "@/lib/api/role"; import { AlertTriangle } from "lucide-react"; @@ -71,11 +71,11 @@ export function RoleDeleteModal({ isOpen, onClose, onSuccess, role }: RoleDelete if (!role) return null; return ( - - - - 권한 그룹 삭제 - + + + + 권한 그룹 삭제 +
{/* 경고 메시지 */} @@ -133,7 +133,7 @@ export function RoleDeleteModal({ isOpen, onClose, onSuccess, role }: RoleDelete )}
- + - -
-
+ + + ); } diff --git a/frontend/components/admin/RoleFormModal.tsx b/frontend/components/admin/RoleFormModal.tsx index 492a463c..cdeeccc5 100644 --- a/frontend/components/admin/RoleFormModal.tsx +++ b/frontend/components/admin/RoleFormModal.tsx @@ -2,13 +2,13 @@ import React, { useState, useCallback, useEffect, useMemo } from "react"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogDescription, - ResizableDialogFooter, -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, +} from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; @@ -184,11 +184,11 @@ export function RoleFormModal({ isOpen, onClose, onSuccess, editingRole }: RoleF ); return ( - - - - {isEditMode ? "권한 그룹 수정" : "권한 그룹 생성"} - + + + + {isEditMode ? "권한 그룹 수정" : "권한 그룹 생성"} +
{/* 권한 그룹명 */} @@ -359,7 +359,7 @@ export function RoleFormModal({ isOpen, onClose, onSuccess, editingRole }: RoleF )}
- + - -
-
+ + + ); } diff --git a/frontend/components/admin/SqlQueryModal.tsx b/frontend/components/admin/SqlQueryModal.tsx index 4c01f472..6f83d78f 100644 --- a/frontend/components/admin/SqlQueryModal.tsx +++ b/frontend/components/admin/SqlQueryModal.tsx @@ -3,12 +3,12 @@ import { useState, useEffect, ChangeEvent } from "react"; import { Button } from "@/components/ui/button"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogDescription, -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, +} from "@/components/ui/dialog"; import { Textarea } from "@/components/ui/textarea"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; @@ -179,14 +179,14 @@ export const SqlQueryModal: React.FC = ({ isOpen, onClose, c }; return ( - - - - {connectionName} - SQL 쿼리 실행 - + + + + {connectionName} - SQL 쿼리 실행 + 데이터베이스에 대해 SQL SELECT 쿼리를 실행하고 결과를 확인할 수 있습니다. - - + + {/* 쿼리 입력 영역 */}
@@ -228,7 +228,7 @@ export const SqlQueryModal: React.FC = ({ isOpen, onClose, c

사용 가능한 테이블

-
+
{tables.map((table) => (
@@ -263,7 +263,7 @@ export const SqlQueryModal: React.FC = ({ isOpen, onClose, c {loadingColumns ? (
컬럼 정보 로딩 중...
) : selectedTableColumns.length > 0 ? ( -
+
@@ -332,7 +332,7 @@ export const SqlQueryModal: React.FC = ({ isOpen, onClose, c {/* 결과 그리드 */}
-
+
@@ -378,7 +378,7 @@ export const SqlQueryModal: React.FC = ({ isOpen, onClose, c - - + + ); }; diff --git a/frontend/components/admin/TableLogViewer.tsx b/frontend/components/admin/TableLogViewer.tsx index 181c6e4b..147229df 100644 --- a/frontend/components/admin/TableLogViewer.tsx +++ b/frontend/components/admin/TableLogViewer.tsx @@ -2,12 +2,12 @@ import { useState, useEffect } from "react"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogFooter -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogFooter +} from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; @@ -126,14 +126,14 @@ export function TableLogViewer({ tableName, open, onOpenChange }: TableLogViewer }; return ( - - - - + + + + {tableName} - 변경 이력 - - + + {/* 필터 영역 */}
@@ -261,7 +261,7 @@ export function TableLogViewer({ tableName, open, onOpenChange }: TableLogViewer
-
-
+ + ); } diff --git a/frontend/components/admin/TemplateImportExport.tsx b/frontend/components/admin/TemplateImportExport.tsx index a72bb468..e11dada6 100644 --- a/frontend/components/admin/TemplateImportExport.tsx +++ b/frontend/components/admin/TemplateImportExport.tsx @@ -7,7 +7,7 @@ import { Label } from "@/components/ui/label"; import { Textarea } from "@/components/ui/textarea"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Alert, AlertDescription } from "@/components/ui/alert"; -import { ResizableDialog, ResizableDialogContent, ResizableDialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"; +import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"; import { Upload, Download, FileText, AlertCircle, CheckCircle } from "lucide-react"; import { toast } from "sonner"; import { useTemplates } from "@/hooks/admin/useTemplates"; diff --git a/frontend/components/admin/UserFormModal.tsx b/frontend/components/admin/UserFormModal.tsx index b3095e67..a70e82b9 100644 --- a/frontend/components/admin/UserFormModal.tsx +++ b/frontend/components/admin/UserFormModal.tsx @@ -1,7 +1,7 @@ "use client"; import React, { useState, useCallback, useEffect, useMemo } from "react"; -import { ResizableDialog, ResizableDialogContent, ResizableDialogHeader, ResizableDialogTitle } from "@/components/ui/resizable-dialog"; +import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; @@ -32,11 +32,11 @@ function AlertModal({ isOpen, onClose, title, message, type = "info" }: AlertMod }; return ( - - - - {title} - + + + + {title} +

{message}

@@ -45,8 +45,8 @@ function AlertModal({ isOpen, onClose, title, message, type = "info" }: AlertMod 확인 -
-
+ + ); } @@ -441,11 +441,11 @@ export function UserFormModal({ isOpen, onClose, onSuccess, editingUser }: UserF return ( <> - - - - {isEditMode ? "사용자 정보 수정" : "사용자 등록"} - + + + + {isEditMode ? "사용자 정보 수정" : "사용자 등록"} +
{/* 기본 정보 */} @@ -684,8 +684,8 @@ export function UserFormModal({ isOpen, onClose, onSuccess, editingUser }: UserF {isLoading ? "처리중..." : isEditMode ? "수정" : "등록"}
-
-
+ + {/* 알림 모달 */} - - - + + + + 사용자 관리 이력 - +
{userName} ({userId})의 변경이력을 조회합니다.
-
+
{/* 로딩 상태 */} @@ -254,7 +254,7 @@ export function UserHistoryModal({ isOpen, onClose, userId, userName }: UserHist 닫기
-
- + + ); } diff --git a/frontend/components/admin/UserPasswordResetModal.tsx b/frontend/components/admin/UserPasswordResetModal.tsx index dc9fd206..086b1556 100644 --- a/frontend/components/admin/UserPasswordResetModal.tsx +++ b/frontend/components/admin/UserPasswordResetModal.tsx @@ -1,7 +1,7 @@ "use client"; import React, { useState, useCallback } from "react"; -import { ResizableDialog, ResizableDialogContent, ResizableDialogHeader, DialogTitle } from "@/components/ui/resizable-dialog"; +import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; @@ -127,11 +127,11 @@ export function UserPasswordResetModal({ isOpen, onClose, userId, userName, onSu if (!userId) return null; return ( - - - - 비밀번호 초기화 - + + + + 비밀번호 초기화 +
{/* 대상 사용자 정보 */} @@ -215,7 +215,7 @@ export function UserPasswordResetModal({ isOpen, onClose, userId, userName, onSu {isLoading ? "처리중..." : "초기화"}
-
+ {/* 알림 모달 */} -
+ ); } diff --git a/frontend/components/admin/dashboard/DashboardDesigner.tsx b/frontend/components/admin/dashboard/DashboardDesigner.tsx index 4c70419e..08296fd1 100644 --- a/frontend/components/admin/dashboard/DashboardDesigner.tsx +++ b/frontend/components/admin/dashboard/DashboardDesigner.tsx @@ -13,12 +13,12 @@ import { DashboardProvider } from "@/contexts/DashboardContext"; import { useMenu } from "@/contexts/MenuContext"; import { useKeyboardShortcuts } from "./hooks/useKeyboardShortcuts"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogDescription, - ResizableDialogHeader, - ResizableDialogTitle, -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; import { AlertDialog, AlertDialogAction, @@ -639,23 +639,23 @@ export default function DashboardDesigner({ dashboardId: initialDashboardId }: D /> {/* 저장 성공 모달 */} - { setSuccessModalOpen(false); router.push("/admin/dashboard"); }} > - - + +
- 저장 완료 - + 저장 완료 + 대시보드가 성공적으로 저장되었습니다. - -
+ +
-
-
+ + {/* 초기화 확인 모달 */} diff --git a/frontend/components/admin/dashboard/DashboardSaveModal.tsx b/frontend/components/admin/dashboard/DashboardSaveModal.tsx index 2c9ff4d6..f99984e8 100644 --- a/frontend/components/admin/dashboard/DashboardSaveModal.tsx +++ b/frontend/components/admin/dashboard/DashboardSaveModal.tsx @@ -2,13 +2,13 @@ import { useState, useEffect } from "react"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogDescription, - ResizableDialogFooter, -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, +} from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; @@ -174,11 +174,11 @@ export function DashboardSaveModal({ const flatMenus = flattenMenus(currentMenus); return ( - - - - {isEditing ? "대시보드 수정" : "대시보드 저장"} - + + + + {isEditing ? "대시보드 수정" : "대시보드 저장"} +
{/* 대시보드 이름 */} @@ -312,7 +312,7 @@ export function DashboardSaveModal({
- + @@ -329,8 +329,8 @@ export function DashboardSaveModal({ )} - -
-
+ + + ); } diff --git a/frontend/components/admin/dashboard/MenuAssignmentModal.tsx b/frontend/components/admin/dashboard/MenuAssignmentModal.tsx index 5e8869a9..a6f01c8b 100644 --- a/frontend/components/admin/dashboard/MenuAssignmentModal.tsx +++ b/frontend/components/admin/dashboard/MenuAssignmentModal.tsx @@ -2,13 +2,13 @@ import React, { useState, useEffect } from "react"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogDescription, - ResizableDialogFooter, -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, +} from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Label } from "@/components/ui/label"; import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"; @@ -116,14 +116,14 @@ export const MenuAssignmentModal: React.FC = ({ }; return ( - - - + + +
- 대시보드 저장 완료 - '{dashboardTitle}' 대시보드가 저장되었습니다. + 대시보드 저장 완료 + '{dashboardTitle}' 대시보드가 저장되었습니다.
-
+
@@ -200,13 +200,13 @@ export const MenuAssignmentModal: React.FC = ({ )}
- + - - - + + + ); }; diff --git a/frontend/components/admin/dashboard/widgets/yard-3d/MaterialAddModal.tsx b/frontend/components/admin/dashboard/widgets/yard-3d/MaterialAddModal.tsx index b5831d27..3f64c2b2 100644 --- a/frontend/components/admin/dashboard/widgets/yard-3d/MaterialAddModal.tsx +++ b/frontend/components/admin/dashboard/widgets/yard-3d/MaterialAddModal.tsx @@ -3,13 +3,13 @@ import { useState } from "react"; import { Button } from "@/components/ui/button"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogDescription, - ResizableDialogFooter, -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, +} from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Loader2 } from "lucide-react"; @@ -94,10 +94,10 @@ export default function MaterialAddModal({ isOpen, material, onClose, onAdd }: M if (!open) onClose(); }} > - - - 자재 배치 설정 - + + + 자재 배치 설정 +
{/* 자재 정보 */} @@ -233,7 +233,7 @@ export default function MaterialAddModal({ isOpen, material, onClose, onAdd }: M
- + @@ -247,8 +247,8 @@ export default function MaterialAddModal({ isOpen, material, onClose, onAdd }: M "배치" )} - -
-
+ + + ); } diff --git a/frontend/components/admin/dashboard/widgets/yard-3d/MaterialLibrary.tsx b/frontend/components/admin/dashboard/widgets/yard-3d/MaterialLibrary.tsx index 15b6db93..79909658 100644 --- a/frontend/components/admin/dashboard/widgets/yard-3d/MaterialLibrary.tsx +++ b/frontend/components/admin/dashboard/widgets/yard-3d/MaterialLibrary.tsx @@ -3,7 +3,7 @@ import { useState, useEffect } from "react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; -import { ResizableDialog, ResizableDialogContent, ResizableDialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"; +import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { Search, Loader2 } from "lucide-react"; import { materialApi } from "@/lib/api/yardLayoutApi"; diff --git a/frontend/components/admin/dashboard/widgets/yard-3d/YardLayoutCreateModal.tsx b/frontend/components/admin/dashboard/widgets/yard-3d/YardLayoutCreateModal.tsx index e6c8a3b8..feac0f22 100644 --- a/frontend/components/admin/dashboard/widgets/yard-3d/YardLayoutCreateModal.tsx +++ b/frontend/components/admin/dashboard/widgets/yard-3d/YardLayoutCreateModal.tsx @@ -3,13 +3,13 @@ import { useState } from "react"; import { Button } from "@/components/ui/button"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogDescription, - ResizableDialogFooter, -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, +} from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Alert, AlertDescription } from "@/components/ui/alert"; @@ -64,14 +64,14 @@ export default function YardLayoutCreateModal({ isOpen, onClose, onCreate }: Yar }; return ( - - e.stopPropagation()}> - + + e.stopPropagation()}> +
- 새로운 3D필드 생성 - 필드 이름을 입력하세요 + 새로운 3D필드 생성 + 필드 이름을 입력하세요
-
+
@@ -100,7 +100,7 @@ export default function YardLayoutCreateModal({ isOpen, onClose, onCreate }: Yar )}
- + @@ -114,8 +114,8 @@ export default function YardLayoutCreateModal({ isOpen, onClose, onCreate }: Yar "생성" )} - - - + + + ); } diff --git a/frontend/components/common/BarcodeScanModal.tsx b/frontend/components/common/BarcodeScanModal.tsx index 7c615941..34706b8c 100644 --- a/frontend/components/common/BarcodeScanModal.tsx +++ b/frontend/components/common/BarcodeScanModal.tsx @@ -2,13 +2,13 @@ import React, { useState, useRef, useEffect } from "react"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogDescription, - ResizableDialogFooter, -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, +} from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { toast } from "sonner"; import { Camera, CameraOff, CheckCircle2, AlertCircle, Scan } from "lucide-react"; @@ -179,26 +179,15 @@ export const BarcodeScanModal: React.FC = ({ }; return ( - - - - 바코드 스캔 - + + + + 바코드 스캔 + 카메라로 바코드를 스캔하세요. {targetField && ` (대상 필드: ${targetField})`} - 모달 테두리를 드래그하여 크기를 조절할 수 있습니다. - - + +
{/* 카메라 권한 요청 대기 중 */} @@ -337,7 +326,7 @@ export const BarcodeScanModal: React.FC = ({ )}
- + )} - -
-
+ + + ); }; diff --git a/frontend/components/common/ExcelUploadModal.tsx b/frontend/components/common/ExcelUploadModal.tsx index c5a25a65..0f080bcc 100644 --- a/frontend/components/common/ExcelUploadModal.tsx +++ b/frontend/components/common/ExcelUploadModal.tsx @@ -2,13 +2,13 @@ import React, { useState, useRef, useEffect } from "react"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogDescription, - ResizableDialogFooter, -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, +} from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Label } from "@/components/ui/label"; import { @@ -385,27 +385,27 @@ export const ExcelUploadModal: React.FC = ({ }, [open]); return ( - - + - - + + 엑셀 데이터 업로드 - - + + 엑셀 파일을 선택하고 컬럼을 매핑하여 데이터를 업로드하세요. 모달 테두리를 드래그하여 크기를 조절할 수 있습니다. - - + + {/* 스텝 인디케이터 */}
@@ -863,7 +863,7 @@ export const ExcelUploadModal: React.FC = ({ )}
- + )} - -
-
+ + + ); }; diff --git a/frontend/components/common/ScreenModal.tsx b/frontend/components/common/ScreenModal.tsx index a048bbe4..4da781e6 100644 --- a/frontend/components/common/ScreenModal.tsx +++ b/frontend/components/common/ScreenModal.tsx @@ -2,12 +2,12 @@ import React, { useState, useEffect, useRef } from "react"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogDescription, -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, +} from "@/components/ui/dialog"; import { Checkbox } from "@/components/ui/checkbox"; import { Label } from "@/components/ui/label"; import { InteractiveScreenViewerDynamic } from "@/components/screen/InteractiveScreenViewerDynamic"; @@ -514,16 +514,18 @@ export const ScreenModal: React.FC = ({ className }) => { } // 화면관리에서 설정한 크기 = 컨텐츠 영역 크기 - // 실제 모달 크기 = 컨텐츠 + 헤더 + 연속등록 체크박스 - const headerHeight = 60; // DialogHeader (타이틀 + 패딩) + // 실제 모달 크기 = 컨텐츠 + 헤더 + 연속등록 체크박스 + gap + padding + const headerHeight = 52; // DialogHeader (타이틀 + border-b + py-3) const footerHeight = 52; // 연속 등록 모드 체크박스 영역 + const dialogGap = 16; // DialogContent gap-4 + const extraPadding = 24; // 추가 여백 (안전 마진) - const totalHeight = screenDimensions.height + headerHeight + footerHeight; + const totalHeight = screenDimensions.height + headerHeight + footerHeight + dialogGap + extraPadding; return { className: "overflow-hidden p-0", style: { - width: `${Math.min(screenDimensions.width, window.innerWidth * 0.98)}px`, + width: `${Math.min(screenDimensions.width + 48, window.innerWidth * 0.98)}px`, // 좌우 패딩 추가 height: `${Math.min(totalHeight, window.innerHeight * 0.95)}px`, maxWidth: "98vw", maxHeight: "95vh", @@ -593,36 +595,28 @@ export const ScreenModal: React.FC = ({ className }) => { ]); return ( - - + - +
- {modalState.title} + {modalState.title} {modalState.description && !loading && ( - + {modalState.description} - + )} {loading && ( - + {loading ? "화면을 불러오는 중입니다..." : ""} - + )}
-
+ -
+
{loading ? (
@@ -728,8 +722,8 @@ export const ScreenModal: React.FC = ({ className }) => {
- - + + ); }; diff --git a/frontend/components/common/TableHistoryModal.tsx b/frontend/components/common/TableHistoryModal.tsx index 033c18ac..f2970b4f 100644 --- a/frontend/components/common/TableHistoryModal.tsx +++ b/frontend/components/common/TableHistoryModal.tsx @@ -7,12 +7,12 @@ import React, { useEffect, useState } from "react"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogDescription, -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, +} from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; @@ -209,7 +209,7 @@ export function TableHistoryModal({ - + 변경 이력{" "} {!recordId && ( @@ -217,12 +217,12 @@ export function TableHistoryModal({ 전체 )} - - + + {recordId ? `${recordDisplayValue || recordLabel || "-"} - ${tableName} 테이블` : `${tableName} 테이블 전체 이력`} - + {loading ? ( diff --git a/frontend/components/common/TableOptionsModal.tsx b/frontend/components/common/TableOptionsModal.tsx index f19a1a07..64b2b02d 100644 --- a/frontend/components/common/TableOptionsModal.tsx +++ b/frontend/components/common/TableOptionsModal.tsx @@ -2,13 +2,13 @@ import React, { useState, useEffect } from "react"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogDescription, - ResizableDialogFooter, -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, +} from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Label } from "@/components/ui/label"; import { Switch } from "@/components/ui/switch"; @@ -150,23 +150,14 @@ export function TableOptionsModal({ }; return ( - - - - 테이블 옵션 - - 컬럼 표시/숨기기, 순서 변경, 틀고정 등을 설정할 수 있습니다. 모달 테두리를 드래그하여 크기를 조절할 수 있습니다. - - + + + + 테이블 옵션 + + 컬럼 표시/숨기기, 순서 변경, 틀고정 등을 설정할 수 있습니다. + + @@ -303,7 +294,7 @@ export function TableOptionsModal({ - + - - - + + + ); } diff --git a/frontend/components/dataflow/ConnectionSetupModal.tsx b/frontend/components/dataflow/ConnectionSetupModal.tsx index 450509ee..9b6482a4 100644 --- a/frontend/components/dataflow/ConnectionSetupModal.tsx +++ b/frontend/components/dataflow/ConnectionSetupModal.tsx @@ -2,13 +2,13 @@ import React, { useState, useEffect, useCallback } from "react"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogDescription, - ResizableDialogFooter, -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, +} from "@/components/ui/dialog"; import { AlertDialog, AlertDialogAction, @@ -673,14 +673,14 @@ export const ConnectionSetupModal: React.FC = ({ return ( <> - - - - + + + + 필드 연결 설정 - - + +
{/* 기본 연결 설정 */} @@ -719,16 +719,16 @@ export const ConnectionSetupModal: React.FC = ({ {renderConnectionTypeSettings()}
- + - -
-
+ + + diff --git a/frontend/components/dataflow/SaveDiagramModal.tsx b/frontend/components/dataflow/SaveDiagramModal.tsx index 70a12e39..af7f004f 100644 --- a/frontend/components/dataflow/SaveDiagramModal.tsx +++ b/frontend/components/dataflow/SaveDiagramModal.tsx @@ -2,13 +2,13 @@ import React, { useState, useEffect } from "react"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogDescription, - ResizableDialogFooter, -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, +} from "@/components/ui/dialog"; import { AlertDialog, AlertDialogAction, @@ -133,11 +133,11 @@ const SaveDiagramModal: React.FC = ({ return ( <> - - - - 📊 관계도 저장 - + + + + 📊 관계도 저장 +
{/* 관계도 이름 입력 */} @@ -203,7 +203,7 @@ const SaveDiagramModal: React.FC = ({ 관계 목록 -
+
{relationships.map((relationship, index) => (
= ({ )}
- + @@ -260,9 +260,9 @@ const SaveDiagramModal: React.FC = ({ "저장하기" )} - - - + + +
{/* 저장 성공 알림 모달 */} diff --git a/frontend/components/dataflow/node-editor/dialogs/LoadFlowDialog.tsx b/frontend/components/dataflow/node-editor/dialogs/LoadFlowDialog.tsx index 7cdd28fd..d5cc9b18 100644 --- a/frontend/components/dataflow/node-editor/dialogs/LoadFlowDialog.tsx +++ b/frontend/components/dataflow/node-editor/dialogs/LoadFlowDialog.tsx @@ -6,7 +6,7 @@ import { useEffect, useState } from "react"; import { Loader2, FileJson, Calendar, Trash2 } from "lucide-react"; -import { ResizableDialog, ResizableDialogContent, ResizableDialogDescription, ResizableDialogHeader, DialogTitle } from "@/components/ui/dialog"; +import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { ScrollArea } from "@/components/ui/scroll-area"; import { getNodeFlows, deleteNodeFlow } from "@/lib/api/nodeFlows"; diff --git a/frontend/components/flow/FlowDataListModal.tsx b/frontend/components/flow/FlowDataListModal.tsx index 61264ffb..352860e5 100644 --- a/frontend/components/flow/FlowDataListModal.tsx +++ b/frontend/components/flow/FlowDataListModal.tsx @@ -1,7 +1,7 @@ "use client"; import React, { useEffect, useState } from "react"; -import { ResizableDialog, ResizableDialogContent, ResizableDialogHeader, DialogDescription } from "@/components/ui/resizable-dialog"; +import { Dialog, DialogContent, DialogHeader, DialogDescription } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; import { Table, TableHeader, TableRow, TableHead, TableBody, TableCell } from "@/components/ui/table"; @@ -130,11 +130,11 @@ export function FlowDataListModal({ - + {stepName} {data.length}건 - - 이 단계에 해당하는 데이터 목록입니다 + + 이 단계에 해당하는 데이터 목록입니다
diff --git a/frontend/components/layout/ProfileModal.tsx b/frontend/components/layout/ProfileModal.tsx index e79d3357..ad23acb4 100644 --- a/frontend/components/layout/ProfileModal.tsx +++ b/frontend/components/layout/ProfileModal.tsx @@ -1,11 +1,11 @@ import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogDescription, - ResizableDialogFooter, -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, +} from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; @@ -48,11 +48,11 @@ function AlertModal({ isOpen, onClose, title, message, type = "info" }: AlertMod }; return ( - - - - {title} - + + + + {title} +

{message}

@@ -61,8 +61,8 @@ function AlertModal({ isOpen, onClose, title, message, type = "info" }: AlertMod 확인
-
-
+ + ); } @@ -165,11 +165,11 @@ export function ProfileModal({ }; return ( <> - - - - 프로필 수정 - + + + + 프로필 수정 +
{/* 프로필 사진 섹션 */} @@ -449,16 +449,16 @@ export function ProfileModal({ )}
- + - -
-
+ + + {/* 알림 모달 */} - - - 새 차량 등록 - + + + + 새 차량 등록 + 새로운 차량 정보를 입력해주세요. - - + +
@@ -501,16 +501,16 @@ export function ProfileModal({
- + - -
- + + + )} ); diff --git a/frontend/components/mail/MailDetailModal.tsx b/frontend/components/mail/MailDetailModal.tsx index e945bbd9..0a25c2a3 100644 --- a/frontend/components/mail/MailDetailModal.tsx +++ b/frontend/components/mail/MailDetailModal.tsx @@ -6,7 +6,7 @@ import { DialogContent, DialogHeader, -} from "@/components/ui/resizable-dialog"; +} from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; import { @@ -186,13 +186,13 @@ export default function MailDetailModal({ }; return ( - - - - + + + + 메일 상세 - - + + {loading ? (
@@ -375,8 +375,8 @@ export default function MailDetailModal({
) : null} - - + + ); } diff --git a/frontend/components/multilang/LangKeyModal.tsx b/frontend/components/multilang/LangKeyModal.tsx index c25164f5..06189c58 100644 --- a/frontend/components/multilang/LangKeyModal.tsx +++ b/frontend/components/multilang/LangKeyModal.tsx @@ -1,7 +1,7 @@ "use client"; import { useState, useEffect } from "react"; -import { ResizableDialog, ResizableDialogContent, ResizableDialogHeader, DialogTitle } from "@/components/ui/resizable-dialog"; +import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; @@ -141,9 +141,9 @@ export function LangKeyModal({ return ( - + - {langKey ? "다국어 키 수정" : "새 다국어 키 추가"} + {langKey ? "다국어 키 수정" : "새 다국어 키 추가"}
diff --git a/frontend/components/order/OrderRegistrationModal.tsx b/frontend/components/order/OrderRegistrationModal.tsx index 615f0426..e47e124f 100644 --- a/frontend/components/order/OrderRegistrationModal.tsx +++ b/frontend/components/order/OrderRegistrationModal.tsx @@ -210,7 +210,7 @@ export function OrderRegistrationModal({ return ( - + 수주 등록 diff --git a/frontend/components/report/ReportCreateModal.tsx b/frontend/components/report/ReportCreateModal.tsx index ef2a325d..c51dd982 100644 --- a/frontend/components/report/ReportCreateModal.tsx +++ b/frontend/components/report/ReportCreateModal.tsx @@ -4,11 +4,10 @@ import { useState, useEffect } from "react"; import { Dialog, DialogContent, - - DialogHeader, - -} from "@/components/ui/resizable-dialog"; + DialogTitle, + DialogFooter, +} from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; @@ -120,8 +119,8 @@ export function ReportCreateModal({ isOpen, onClose, onSuccess }: ReportCreateMo - 새 리포트 생성 - 새로운 리포트를 생성합니다. 필수 항목을 입력해주세요. + 새 리포트 생성 + 새로운 리포트를 생성합니다. 필수 항목을 입력해주세요.
@@ -207,7 +206,7 @@ export function ReportCreateModal({ isOpen, onClose, onSuccess }: ReportCreateMo
- + @@ -221,7 +220,7 @@ export function ReportCreateModal({ isOpen, onClose, onSuccess }: ReportCreateMo "생성" )} - +
); diff --git a/frontend/components/screen/CopyScreenModal.tsx b/frontend/components/screen/CopyScreenModal.tsx index 75493e4f..c37603c5 100644 --- a/frontend/components/screen/CopyScreenModal.tsx +++ b/frontend/components/screen/CopyScreenModal.tsx @@ -424,7 +424,7 @@ export default function CopyScreenModal({ return ( - + diff --git a/frontend/components/screen/CreateScreenModal.tsx b/frontend/components/screen/CreateScreenModal.tsx index 4f0e5eb9..fc39140d 100644 --- a/frontend/components/screen/CreateScreenModal.tsx +++ b/frontend/components/screen/CreateScreenModal.tsx @@ -2,12 +2,12 @@ import { useEffect, useMemo, useState, useRef } from "react"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogFooter, -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogFooter, +} from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; @@ -271,21 +271,11 @@ export default function CreateScreenModal({ open, onOpenChange, onCreated }: Cre }; return ( - - - - 새 화면 생성 - + + + + 새 화면 생성 +
@@ -603,15 +593,15 @@ export default function CreateScreenModal({ open, onOpenChange, onCreated }: Cre )}
- + - - - + + +
); } diff --git a/frontend/components/screen/EditModal.tsx b/frontend/components/screen/EditModal.tsx index cde9086c..dafe07a5 100644 --- a/frontend/components/screen/EditModal.tsx +++ b/frontend/components/screen/EditModal.tsx @@ -2,13 +2,13 @@ import React, { useState, useEffect } from "react"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogDescription, - ResizableDialogFooter, -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, +} from "@/components/ui/dialog"; import { InteractiveScreenViewerDynamic } from "@/components/screen/InteractiveScreenViewerDynamic"; import { screenApi } from "@/lib/api/screen"; import { ComponentData } from "@/types/screen"; @@ -661,14 +661,17 @@ export const EditModal: React.FC = ({ className }) => { } // 화면관리에서 설정한 크기 = 컨텐츠 영역 크기 - // 실제 모달 크기 = 컨텐츠 + 헤더 - const headerHeight = 60; // DialogHeader - const totalHeight = screenDimensions.height + headerHeight; + // 실제 모달 크기 = 컨텐츠 + 헤더 + gap + padding + const headerHeight = 52; // DialogHeader (타이틀 + border-b + py-3) + const dialogGap = 16; // DialogContent gap-4 + const extraPadding = 24; // 추가 여백 (안전 마진) + + const totalHeight = screenDimensions.height + headerHeight + dialogGap + extraPadding; return { className: "overflow-hidden p-0", style: { - width: `${Math.min(screenDimensions.width, window.innerWidth * 0.98)}px`, + width: `${Math.min(screenDimensions.width + 48, window.innerWidth * 0.98)}px`, // 좌우 패딩 추가 height: `${Math.min(totalHeight, window.innerHeight * 0.95)}px`, maxWidth: "98vw", maxHeight: "95vh", @@ -679,32 +682,24 @@ export const EditModal: React.FC = ({ className }) => { const modalStyle = getModalStyle(); return ( - - + - +
- {modalState.title || "데이터 수정"} + {modalState.title || "데이터 수정"} {modalState.description && !loading && ( - {modalState.description} + {modalState.description} )} {loading && ( - {loading ? "화면을 불러오는 중입니다..." : ""} + {loading ? "화면을 불러오는 중입니다..." : ""} )}
-
+
-
+
{loading ? (
@@ -795,8 +790,8 @@ export const EditModal: React.FC = ({ className }) => {
)}
- - + +
); }; diff --git a/frontend/components/screen/FileAttachmentDetailModal.tsx b/frontend/components/screen/FileAttachmentDetailModal.tsx index 77015589..835f8940 100644 --- a/frontend/components/screen/FileAttachmentDetailModal.tsx +++ b/frontend/components/screen/FileAttachmentDetailModal.tsx @@ -1,7 +1,7 @@ "use client"; import React, { useState, useCallback, useEffect } from "react"; -import { ResizableDialog, ResizableDialogContent, ResizableDialogHeader, DialogTitle } from "@/components/ui/resizable-dialog"; +import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Badge } from "@/components/ui/badge"; @@ -352,9 +352,9 @@ export const FileAttachmentDetailModal: React.FC
- + 파일 첨부 관리 - {component.label || component.id} - + diff --git a/frontend/components/screen/InteractiveDataTable.tsx b/frontend/components/screen/InteractiveDataTable.tsx index 88d11447..b681aa35 100644 --- a/frontend/components/screen/InteractiveDataTable.tsx +++ b/frontend/components/screen/InteractiveDataTable.tsx @@ -2471,7 +2471,7 @@ export const InteractiveDataTable: React.FC = ({ {/* 기존 데이터 추가 모달 (제거 예정 - SaveModal로 대체됨) */} {}}> - + {component.addModalConfig?.title || "새 데이터 추가"} @@ -2517,7 +2517,7 @@ export const InteractiveDataTable: React.FC = ({ {/* 기존 데이터 수정 모달 (제거 예정 - SaveModal로 대체됨) */} {}}> - + 데이터 수정 선택된 데이터를 수정합니다. @@ -2773,7 +2773,7 @@ export const InteractiveDataTable: React.FC = ({ {/* 파일 관리 모달 */} - + diff --git a/frontend/components/screen/InteractiveScreenViewer.tsx b/frontend/components/screen/InteractiveScreenViewer.tsx index 8e1f1ce3..d9186999 100644 --- a/frontend/components/screen/InteractiveScreenViewer.tsx +++ b/frontend/components/screen/InteractiveScreenViewer.tsx @@ -8,7 +8,7 @@ import { Checkbox } from "@/components/ui/checkbox"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Calendar } from "@/components/ui/calendar"; import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; -import { Dialog, DialogContent, DialogHeader, DialogTitle, ResizableDialog, ResizableDialogContent, ResizableDialogHeader } from "@/components/ui/dialog"; +import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { CalendarIcon, File, Upload, X } from "lucide-react"; import { format } from "date-fns"; import { ko } from "date-fns/locale"; diff --git a/frontend/components/screen/InteractiveScreenViewerDynamic.tsx b/frontend/components/screen/InteractiveScreenViewerDynamic.tsx index 3c9d16f5..41983df3 100644 --- a/frontend/components/screen/InteractiveScreenViewerDynamic.tsx +++ b/frontend/components/screen/InteractiveScreenViewerDynamic.tsx @@ -3,8 +3,7 @@ import React, { useState, useCallback, useEffect } from "react"; import { Input } from "@/components/ui/input"; import { Button } from "@/components/ui/button"; -import { ResizableDialog, ResizableDialogContent, ResizableDialogHeader } from "@/components/ui/resizable-dialog"; -import { DialogTitle, DialogHeader } from "@/components/ui/dialog"; +import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { useAuth } from "@/hooks/useAuth"; import { uploadFilesAndCreateData } from "@/lib/api/file"; import { toast } from "sonner"; @@ -776,17 +775,15 @@ export const InteractiveScreenViewerDynamic: React.FC setPopupScreen(null)}> - setPopupScreen(null)}> + {popupScreen.title} @@ -820,8 +817,8 @@ export const InteractiveScreenViewerDynamic: React.FC )} - - + + )} ); diff --git a/frontend/components/screen/MenuAssignmentModal.tsx b/frontend/components/screen/MenuAssignmentModal.tsx index 6fd586a8..fddf0bcc 100644 --- a/frontend/components/screen/MenuAssignmentModal.tsx +++ b/frontend/components/screen/MenuAssignmentModal.tsx @@ -2,13 +2,13 @@ import React, { useState, useEffect, useRef } from "react"; import { - ResizableDialog, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogTitle, - ResizableDialogDescription, - ResizableDialogFooter, -} from "@/components/ui/resizable-dialog"; + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, +} from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; @@ -345,26 +345,26 @@ export const MenuAssignmentModal: React.FC = ({ return ( <> - - + + {assignmentSuccess ? ( // 성공 화면 <> - - + +
{assignmentMessage.includes("나중에") ? "화면 저장 완료" : "화면 할당 완료"} -
- + + {assignmentMessage.includes("나중에") ? "화면이 성공적으로 저장되었습니다. 나중에 메뉴에 할당할 수 있습니다." : "화면이 성공적으로 메뉴에 할당되었습니다."} - -
+
+
@@ -386,7 +386,7 @@ export const MenuAssignmentModal: React.FC = ({
- + - + ) : ( // 기본 할당 화면 <> - - + + 메뉴에 화면 할당 - - + + 저장된 화면을 메뉴에 할당하여 사용자가 접근할 수 있도록 설정합니다. - + {screenInfo && (
@@ -432,7 +432,7 @@ export const MenuAssignmentModal: React.FC = ({ {screenInfo.description &&

{screenInfo.description}

}
)} - +
{/* 메뉴 선택 (검색 기능 포함) */} @@ -550,7 +550,7 @@ export const MenuAssignmentModal: React.FC = ({ )}
- + - + )} - - + +
{/* 화면 교체 확인 대화상자 */} - - - - + + + + 화면 교체 확인 - - 선택한 메뉴에 이미 할당된 화면이 있습니다. - + + 선택한 메뉴에 이미 할당된 화면이 있습니다. +
{/* 기존 화면 목록 */} @@ -628,7 +628,7 @@ export const MenuAssignmentModal: React.FC = ({
- + @@ -652,9 +652,9 @@ export const MenuAssignmentModal: React.FC = ({ )} - - - + +
+ ); }; diff --git a/frontend/components/screen/ResponsivePreviewModal.tsx b/frontend/components/screen/ResponsivePreviewModal.tsx index 3b121e58..1e05a86b 100644 --- a/frontend/components/screen/ResponsivePreviewModal.tsx +++ b/frontend/components/screen/ResponsivePreviewModal.tsx @@ -1,7 +1,7 @@ "use client"; import React, { useState, createContext, useContext } from "react"; -import { ResizableDialog, ResizableDialogContent, ResizableDialogHeader, DialogTitle } from "@/components/ui/resizable-dialog"; +import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Monitor, Tablet, Smartphone } from "lucide-react"; import { ComponentData } from "@/types/screen"; @@ -76,7 +76,7 @@ export const ResponsivePreviewModal: React.FC = ({ - 반응형 미리보기 + 반응형 미리보기 {/* 디바이스 선택 버튼들 */}
diff --git a/frontend/components/screen/SaveModal.tsx b/frontend/components/screen/SaveModal.tsx index bf8ee9ce..4e158719 100644 --- a/frontend/components/screen/SaveModal.tsx +++ b/frontend/components/screen/SaveModal.tsx @@ -1,7 +1,7 @@ "use client"; import React, { useState, useEffect } from "react"; -import { ResizableDialog, ResizableDialogContent, ResizableDialogHeader, ResizableDialogTitle } from "@/components/ui/resizable-dialog"; +import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { X, Save, Loader2 } from "lucide-react"; import { toast } from "sonner"; @@ -232,22 +232,19 @@ export const SaveModal: React.FC = ({ const dynamicSize = calculateDynamicSize(); return ( - !isSaving && !open && onClose()}> - !isSaving && !open && onClose()}> + - +
- {initialData ? "데이터 수정" : "데이터 등록"} + {initialData ? "데이터 수정" : "데이터 등록"}
-
+
{loading ? ( @@ -376,7 +373,7 @@ export const SaveModal: React.FC = ({
화면에 컴포넌트가 없습니다.
)}
-
-
+ +
); }; diff --git a/frontend/components/screen/templates/DataTableTemplate.tsx b/frontend/components/screen/templates/DataTableTemplate.tsx index d83d2fc1..b24f27c3 100644 --- a/frontend/components/screen/templates/DataTableTemplate.tsx +++ b/frontend/components/screen/templates/DataTableTemplate.tsx @@ -8,7 +8,7 @@ import { Input } from "@/components/ui/input"; import { Badge } from "@/components/ui/badge"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Checkbox } from "@/components/ui/checkbox"; -import { ResizableDialog, ResizableDialogContent, ResizableDialogDescription, DialogFooter, ResizableDialogHeader, DialogTitle } from "@/components/ui/dialog"; +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { toast } from "sonner"; import { useAuth } from "@/hooks/useAuth"; diff --git a/frontend/components/ui/dialog.tsx b/frontend/components/ui/dialog.tsx index 4256e329..5552ade5 100644 --- a/frontend/components/ui/dialog.tsx +++ b/frontend/components/ui/dialog.tsx @@ -38,7 +38,7 @@ const DialogContent = React.forwardRef< ) => ( -
+
); DialogHeader.displayName = "DialogHeader"; const DialogFooter = ({ className, ...props }: React.HTMLAttributes) => ( -
+
); DialogFooter.displayName = "DialogFooter"; diff --git a/frontend/components/ui/resizable-dialog.tsx b/frontend/components/ui/resizable-dialog.tsx deleted file mode 100644 index 54d18ed7..00000000 --- a/frontend/components/ui/resizable-dialog.tsx +++ /dev/null @@ -1,601 +0,0 @@ -"use client"; - -import * as React from "react"; -import * as DialogPrimitive from "@radix-ui/react-dialog"; -import { X } from "lucide-react"; -import { cn } from "@/lib/utils"; - -// 🆕 Context를 사용하여 open 상태 공유 -const ResizableDialogContext = React.createContext<{ open: boolean }>({ open: false }); - -// 🆕 ResizableDialog를 래핑하여 Context 제공 -const ResizableDialog: React.FC> = ({ - children, - open = false, - ...props -}) => { - return ( - - - {children} - - - ); -}; - -const ResizableDialogTrigger = DialogPrimitive.Trigger; - -const ResizableDialogPortal = DialogPrimitive.Portal; - -const ResizableDialogClose = DialogPrimitive.Close; - -const ResizableDialogOverlay = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)); -ResizableDialogOverlay.displayName = DialogPrimitive.Overlay.displayName; - -interface ResizableDialogContentProps - extends React.ComponentPropsWithoutRef { - minWidth?: number; - minHeight?: number; - maxWidth?: number; - maxHeight?: number; - defaultWidth?: number; - defaultHeight?: number; - modalId?: string; // localStorage 저장용 고유 ID - userId?: string; // 사용자별 저장용 - open?: boolean; // 🆕 모달 열림/닫힘 상태 (외부에서 전달) - disableFlexLayout?: boolean; // 🆕 flex 레이아웃 비활성화 (absolute 레이아웃용) -} - -const ResizableDialogContent = React.forwardRef< - React.ElementRef, - ResizableDialogContentProps ->( - ( - { - className, - children, - minWidth = 400, - minHeight = 300, - maxWidth = 1600, - maxHeight = 1200, - defaultWidth = 600, - defaultHeight = 500, - modalId, - userId = "guest", - open: externalOpen, // 🆕 외부에서 전달받은 open 상태 - disableFlexLayout = false, // 🆕 flex 레이아웃 비활성화 - style: userStyle, - ...props - }, - ref - ) => { - const contentRef = React.useRef(null); - - // 고정된 ID 생성 (한번 생성되면 컴포넌트 생명주기 동안 유지) - const stableIdRef = React.useRef(null); - - if (!stableIdRef.current) { - if (modalId) { - stableIdRef.current = modalId; - // // console.log("✅ ResizableDialog - 명시적 modalId 사용:", modalId); - } else { - // className 기반 ID 생성 - if (className) { - const hash = className.split('').reduce((acc, char) => { - return ((acc << 5) - acc) + char.charCodeAt(0); - }, 0); - stableIdRef.current = `modal-${Math.abs(hash).toString(36)}`; - // console.log("🔄 ResizableDialog - className 기반 ID 생성:", { className, generatedId: stableIdRef.current }); - } else if (userStyle) { - // userStyle 기반 ID 생성 - const styleStr = JSON.stringify(userStyle); - const hash = styleStr.split('').reduce((acc, char) => { - return ((acc << 5) - acc) + char.charCodeAt(0); - }, 0); - stableIdRef.current = `modal-${Math.abs(hash).toString(36)}`; - // console.log("🔄 ResizableDialog - userStyle 기반 ID 생성:", { userStyle, generatedId: stableIdRef.current }); - } else { - // 기본 ID - stableIdRef.current = 'modal-default'; - // console.log("⚠️ ResizableDialog - 기본 ID 사용 (모든 모달이 같은 크기 공유)"); - } - } - } - - const effectiveModalId = stableIdRef.current; - - // 실제 렌더링된 크기를 감지하여 초기 크기로 사용 - const getInitialSize = React.useCallback(() => { - if (typeof window === 'undefined') return { width: defaultWidth, height: defaultHeight }; - - // 1순위: userStyle에서 크기 추출 (화면관리에서 지정한 크기 - 항상 초기값으로 사용) - if (userStyle) { - const styleWidth = typeof userStyle.width === 'string' - ? parseInt(userStyle.width) - : userStyle.width; - const styleHeight = typeof userStyle.height === 'string' - ? parseInt(userStyle.height) - : userStyle.height; - - if (styleWidth && styleHeight) { - const finalSize = { - width: Math.max(minWidth, Math.min(maxWidth, styleWidth)), - height: Math.max(minHeight, Math.min(maxHeight, styleHeight)), - }; - return finalSize; - } - } - - // 2순위: 현재 렌더링된 크기 사용 (주석처리 - 모달이 열린 후 늘어나는 현상 방지) - // if (contentRef.current) { - // const rect = contentRef.current.getBoundingClientRect(); - // if (rect.width > 0 && rect.height > 0) { - // return { - // width: Math.max(minWidth, Math.min(maxWidth, rect.width)), - // height: Math.max(minHeight, Math.min(maxHeight, rect.height)), - // }; - // } - // } - - // 3순위: defaultWidth/defaultHeight 사용 - return { width: defaultWidth, height: defaultHeight }; - }, [defaultWidth, defaultHeight, minWidth, minHeight, maxWidth, maxHeight, userStyle]); - - const [size, setSize] = React.useState(getInitialSize); - const [isResizing, setIsResizing] = React.useState(false); - const [resizeDirection, setResizeDirection] = React.useState(""); - const [isInitialized, setIsInitialized] = React.useState(false); - - // userStyle이 변경되면 크기 업데이트 (화면 데이터 로딩 완료 시) - React.useEffect(() => { - // 1. localStorage에서 사용자가 리사이징한 크기 확인 - let savedSize: { width: number; height: number; userResized: boolean } | null = null; - - if (effectiveModalId && typeof window !== 'undefined') { - try { - const storageKey = `modal_size_${effectiveModalId}_${userId}`; - const saved = localStorage.getItem(storageKey); - - if (saved) { - const parsed = JSON.parse(saved); - if (parsed.userResized) { - savedSize = { - width: Math.max(minWidth, Math.min(maxWidth, parsed.width)), - height: Math.max(minHeight, Math.min(maxHeight, parsed.height)), - userResized: true, - }; - // console.log("💾 사용자가 리사이징한 크기 복원:", savedSize); - } - } - } catch (error) { - console.error("❌ 모달 크기 복원 실패:", error); - } - } - - // 2. 우선순위: 사용자 리사이징 > userStyle > 기본값 - if (savedSize && savedSize.userResized) { - // 사용자가 리사이징한 크기 우선 - setSize({ width: savedSize.width, height: savedSize.height }); - setUserResized(true); - } else if (userStyle && userStyle.width && userStyle.height) { - // 화면관리에서 설정한 크기 - const styleWidth = typeof userStyle.width === 'string' - ? parseInt(userStyle.width) - : userStyle.width; - const styleHeight = typeof userStyle.height === 'string' - ? parseInt(userStyle.height) - : userStyle.height; - - if (styleWidth && styleHeight) { - const newSize = { - width: Math.max(minWidth, Math.min(maxWidth, styleWidth)), - height: Math.max(minHeight, Math.min(maxHeight, styleHeight)), - }; - setSize(newSize); - } - } - }, [userStyle, minWidth, maxWidth, minHeight, maxHeight, effectiveModalId, userId]); - const [lastModalId, setLastModalId] = React.useState(null); - const [userResized, setUserResized] = React.useState(false); // 사용자가 실제로 리사이징했는지 추적 - - // 🆕 Context에서 open 상태 가져오기 (우선순위: externalOpen > context.open) - const context = React.useContext(ResizableDialogContext); - const actualOpen = externalOpen !== undefined ? externalOpen : context.open; - - // 🆕 모달이 닫혔다가 다시 열릴 때 초기화 리셋 - const [wasOpen, setWasOpen] = React.useState(false); - - React.useEffect(() => { - // console.log("🔍 모달 상태 변화 감지:", { actualOpen, wasOpen, externalOpen, contextOpen: context.open, effectiveModalId }); - - if (actualOpen && !wasOpen) { - // 모달이 방금 열림 - // console.log("🔓 모달 열림 감지, 초기화 리셋:", { effectiveModalId }); - setIsInitialized(false); - setWasOpen(true); - } else if (!actualOpen && wasOpen) { - // 모달이 방금 닫힘 - // console.log("🔒 모달 닫힘 감지:", { effectiveModalId }); - setWasOpen(false); - } - }, [actualOpen, wasOpen, effectiveModalId, externalOpen, context.open]); - - // modalId가 변경되면 초기화 리셋 (다른 모달이 열린 경우) - React.useEffect(() => { - if (effectiveModalId !== lastModalId) { - // console.log("🔄 모달 ID 변경 감지, 초기화 리셋:", { 이전: lastModalId, 현재: effectiveModalId, isInitialized }); - setIsInitialized(false); - setUserResized(false); // 사용자 리사이징 플래그도 리셋 - setLastModalId(effectiveModalId); - } - }, [effectiveModalId, lastModalId, isInitialized]); - - // 모달이 열릴 때 초기 크기 설정 (localStorage와 내용 크기 중 큰 값 사용) - // 주석처리 - 사용자가 설정한 크기(userStyle)만 사용하도록 변경 - // React.useEffect(() => { - // // console.log("🔍 초기 크기 설정 useEffect 실행:", { isInitialized, hasContentRef: !!contentRef.current, effectiveModalId }); - // - // if (!isInitialized) { - // // 내용의 실제 크기 측정 (약간의 지연 후, contentRef가 준비될 때까지 대기) - // // 여러 번 시도하여 contentRef가 준비될 때까지 대기 - // let attempts = 0; - // const maxAttempts = 10; - // - // const measureContent = () => { - // attempts++; - // - // // scrollHeight/scrollWidth를 사용하여 실제 내용 크기 측정 (스크롤 포함) - // let contentWidth = defaultWidth; - // let contentHeight = defaultHeight; - // - // // if (contentRef.current) { - // // // scrollHeight/scrollWidth 그대로 사용 (여유 공간 제거) - // // contentWidth = contentRef.current.scrollWidth || defaultWidth; - // // contentHeight = contentRef.current.scrollHeight || defaultHeight; - // // - // // // console.log("📏 모달 내용 크기 측정:", { attempt: attempts, scrollWidth: contentRef.current.scrollWidth, scrollHeight: contentRef.current.scrollHeight, clientWidth: contentRef.current.clientWidth, clientHeight: contentRef.current.clientHeight, contentWidth, contentHeight }); - // // } else { - // // // console.log("⚠️ contentRef 없음, 재시도:", { attempt: attempts, maxAttempts, defaultWidth, defaultHeight }); - // // - // // // contentRef가 아직 없으면 재시도 - // // if (attempts < maxAttempts) { - // // setTimeout(measureContent, 100); - // // return; - // // } - // // } - // - // // 패딩 추가 (p-6 * 2 = 48px) - // const paddingAndMargin = 48; - // const initialSize = getInitialSize(); - // - // // 내용 크기 기반 최소 크기 계산 - // const contentBasedSize = { - // width: Math.max(minWidth, Math.min(maxWidth, Math.max(contentWidth + paddingAndMargin, initialSize.width))), - // height: Math.max(minHeight, Math.min(maxHeight, Math.max(contentHeight + paddingAndMargin, initialSize.height))), - // }; - // - // // console.log("📐 내용 기반 크기:", contentBasedSize); - // - // // localStorage에서 저장된 크기 확인 - // let finalSize = contentBasedSize; - // - // if (effectiveModalId && typeof window !== 'undefined') { - // try { - // const storageKey = `modal_size_${effectiveModalId}_${userId}`; - // const saved = localStorage.getItem(storageKey); - // - // // console.log("📦 localStorage 확인:", { effectiveModalId, userId, storageKey, saved: saved ? "있음" : "없음" }); - // - // if (saved) { - // const parsed = JSON.parse(saved); - // - // // userResized 플래그 확인 - // if (parsed.userResized) { - // const savedSize = { - // width: Math.max(minWidth, Math.min(maxWidth, parsed.width)), - // height: Math.max(minHeight, Math.min(maxHeight, parsed.height)), - // }; - // - // // console.log("💾 사용자가 리사이징한 크기 복원:", savedSize); - // - // // ✅ 중요: 사용자가 명시적으로 리사이징한 경우, 사용자 크기를 우선 사용 - // // (사용자가 의도적으로 작게 만든 것을 존중) - // finalSize = savedSize; - // setUserResized(true); - // - // // console.log("✅ 최종 크기 (사용자가 설정한 크기 우선 적용):", { savedSize, contentBasedSize, finalSize, note: "사용자가 리사이징한 크기를 그대로 사용합니다" }); - // } else { - // // console.log("ℹ️ 자동 계산된 크기는 무시, 내용 크기 사용"); - // } - // } else { - // // console.log("ℹ️ localStorage에 저장된 크기 없음, 내용 크기 사용"); - // } - // } catch (error) { - // // console.error("❌ 모달 크기 복원 실패:", error); - // } - // } - // - // setSize(finalSize); - // setIsInitialized(true); - // }; - // - // // 첫 시도는 300ms 후에 시작 - // setTimeout(measureContent, 300); - // } - // }, [isInitialized, getInitialSize, effectiveModalId, userId, minWidth, maxWidth, minHeight, maxHeight, defaultWidth, defaultHeight]); - - const startResize = (direction: string) => (e: React.MouseEvent) => { - e.preventDefault(); - e.stopPropagation(); - setIsResizing(true); - setResizeDirection(direction); - - const startX = e.clientX; - const startY = e.clientY; - const startWidth = size.width; - const startHeight = size.height; - - const handleMouseMove = (moveEvent: MouseEvent) => { - const deltaX = moveEvent.clientX - startX; - const deltaY = moveEvent.clientY - startY; - - let newWidth = startWidth; - let newHeight = startHeight; - - if (direction.includes("e")) { - newWidth = Math.max(minWidth, Math.min(maxWidth, startWidth + deltaX)); - } - if (direction.includes("w")) { - newWidth = Math.max(minWidth, Math.min(maxWidth, startWidth - deltaX)); - } - if (direction.includes("s")) { - newHeight = Math.max(minHeight, Math.min(maxHeight, startHeight + deltaY)); - } - if (direction.includes("n")) { - newHeight = Math.max(minHeight, Math.min(maxHeight, startHeight - deltaY)); - } - - setSize({ width: newWidth, height: newHeight }); - }; - - const handleMouseUp = () => { - setIsResizing(false); - setResizeDirection(""); - document.removeEventListener("mousemove", handleMouseMove); - document.removeEventListener("mouseup", handleMouseUp); - - // 사용자가 리사이징했음을 표시 - setUserResized(true); - - // ✅ 중요: 현재 실제 DOM 크기를 저장 (state가 아닌 실제 크기) - if (effectiveModalId && typeof window !== 'undefined' && contentRef.current) { - try { - const storageKey = `modal_size_${effectiveModalId}_${userId}`; - - // contentRef의 부모 요소(모달 컨테이너)의 실제 크기 사용 - const modalElement = contentRef.current.parentElement; - const actualWidth = modalElement?.offsetWidth || size.width; - const actualHeight = modalElement?.offsetHeight || size.height; - - const currentSize = { - width: actualWidth, - height: actualHeight, - userResized: true, // 사용자가 직접 리사이징했음을 표시 - }; - localStorage.setItem(storageKey, JSON.stringify(currentSize)); - // console.log("💾 localStorage에 크기 저장 (사용자 리사이징):", { effectiveModalId, userId, storageKey, size: currentSize, stateSize: { width: size.width, height: size.height } }); - } catch (error) { - // console.error("❌ 모달 크기 저장 실패:", error); - } - } - }; - - document.addEventListener("mousemove", handleMouseMove); - document.addEventListener("mouseup", handleMouseUp); - }; - - return ( - - - -
- {children} -
- - {/* 리사이즈 핸들 */} - {/* 오른쪽 */} -
- {/* 아래 */} -
- {/* 오른쪽 아래 */} -
- {/* 왼쪽 */} -
- {/* 위 */} -
- {/* 왼쪽 아래 */} -
- {/* 오른쪽 위 */} -
- {/* 왼쪽 위 */} -
- - {/* 리셋 버튼 (사용자가 리사이징한 경우만 표시) */} - {userResized && ( - - )} - - - - Close - - - - ); - } -); -ResizableDialogContent.displayName = DialogPrimitive.Content.displayName; - -const ResizableDialogHeader = ({ - className, - ...props -}: React.HTMLAttributes) => ( -
-); -ResizableDialogHeader.displayName = "ResizableDialogHeader"; - -const ResizableDialogFooter = ({ - className, - ...props -}: React.HTMLAttributes) => ( -
-); -ResizableDialogFooter.displayName = "ResizableDialogFooter"; - -const ResizableDialogTitle = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)); -ResizableDialogTitle.displayName = DialogPrimitive.Title.displayName; - -const ResizableDialogDescription = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)); -ResizableDialogDescription.displayName = - DialogPrimitive.Description.displayName; - -export { - ResizableDialog, - ResizableDialogPortal, - ResizableDialogOverlay, - ResizableDialogClose, - ResizableDialogTrigger, - ResizableDialogContent, - ResizableDialogHeader, - ResizableDialogFooter, - ResizableDialogTitle, - ResizableDialogDescription, -}; - diff --git a/frontend/components/webtypes/RepeaterInput.tsx b/frontend/components/webtypes/RepeaterInput.tsx index ade700e1..ce9d4cf6 100644 --- a/frontend/components/webtypes/RepeaterInput.tsx +++ b/frontend/components/webtypes/RepeaterInput.tsx @@ -428,6 +428,31 @@ export const RepeaterInput: React.FC = ({ return {option?.label || value}; } + // 🆕 카테고리 매핑이 있는 경우 라벨로 변환 (조인된 테이블의 카테고리 필드) + const mapping = categoryMappings[field.name]; + if (mapping && value) { + const valueStr = String(value); + const categoryData = mapping[valueStr]; + if (categoryData) { + // 색상이 있으면 배지로 표시 + if (categoryData.color && categoryData.color !== "none" && categoryData.color !== "#64748b") { + return ( + + {categoryData.label} + + ); + } + // 색상이 없으면 텍스트로 표시 + return {categoryData.label}; + } + } + // 일반 텍스트 return ( @@ -556,44 +581,40 @@ export const RepeaterInput: React.FC = ({ } }; - // 카테고리 매핑 로드 (카테고리 필드가 있을 때 자동 로드) + // 카테고리 매핑 로드 (카테고리 필드 + readonly 필드에 대해 자동 로드) // 테이블 리스트와 동일한 API 사용: /table-categories/{tableName}/{columnName}/values useEffect(() => { + // 카테고리 타입 필드 + readonly 필드 (조인된 테이블에서 온 데이터일 가능성) const categoryFields = fields.filter(f => f.type === "category"); - if (categoryFields.length === 0) return; + const readonlyFields = fields.filter(f => f.displayMode === "readonly" && f.type === "text"); + + if (categoryFields.length === 0 && readonlyFields.length === 0) return; const loadCategoryMappings = async () => { const apiClient = (await import("@/lib/api/client")).apiClient; + // 1. 카테고리 타입 필드 매핑 로드 for (const field of categoryFields) { - const columnName = field.name; // 실제 컬럼명 - const categoryCode = field.categoryCode || columnName; + const columnName = field.name; - // 이미 로드된 경우 스킵 if (categoryMappings[columnName]) continue; try { - // config에서 targetTable 가져오기, 없으면 스킵 const tableName = config.targetTable; - if (!tableName) { - console.warn(`[RepeaterInput] targetTable이 설정되지 않아 카테고리 매핑을 로드할 수 없습니다.`); - continue; - } + if (!tableName) continue; console.log(`📡 [RepeaterInput] 카테고리 매핑 로드: ${tableName}/${columnName}`); - // 테이블 리스트와 동일한 API 사용 const response = await apiClient.get(`/table-categories/${tableName}/${columnName}/values`); if (response.data.success && response.data.data && Array.isArray(response.data.data)) { const mapping: Record = {}; response.data.data.forEach((item: any) => { - // valueCode를 문자열로 변환하여 키로 사용 (테이블 리스트와 동일) const key = String(item.valueCode); mapping[key] = { label: item.valueLabel || key, - color: item.color || "#64748b", // color 필드 사용 (DB 컬럼명과 동일) + color: item.color || "#64748b", }; }); @@ -608,6 +629,50 @@ export const RepeaterInput: React.FC = ({ console.error(`❌ [RepeaterInput] 카테고리 매핑 로드 실패 (${columnName}):`, error); } } + + // 2. 🆕 readonly 필드에 대해 조인된 테이블 (item_info)에서 카테고리 매핑 로드 + // material, division 등 조인된 테이블의 카테고리 필드 + const joinedTableFields = ['material', 'division', 'status', 'currency_code']; + const fieldsToLoadFromJoinedTable = readonlyFields.filter(f => joinedTableFields.includes(f.name)); + + if (fieldsToLoadFromJoinedTable.length > 0) { + // item_info 테이블에서 카테고리 매핑 로드 + const joinedTableName = 'item_info'; + + for (const field of fieldsToLoadFromJoinedTable) { + const columnName = field.name; + + if (categoryMappings[columnName]) continue; + + try { + console.log(`📡 [RepeaterInput] 조인 테이블 카테고리 매핑 로드: ${joinedTableName}/${columnName}`); + + const response = await apiClient.get(`/table-categories/${joinedTableName}/${columnName}/values`); + + if (response.data.success && response.data.data && Array.isArray(response.data.data)) { + const mapping: Record = {}; + + response.data.data.forEach((item: any) => { + const key = String(item.valueCode); + mapping[key] = { + label: item.valueLabel || key, + color: item.color || "#64748b", + }; + }); + + console.log(`✅ [RepeaterInput] 조인 테이블 카테고리 매핑 로드 완료 [${columnName}]:`, mapping); + + setCategoryMappings(prev => ({ + ...prev, + [columnName]: mapping, + })); + } + } catch (error) { + // 카테고리가 없는 필드는 무시 + console.log(`ℹ️ [RepeaterInput] 조인 테이블 카테고리 없음 (${columnName})`); + } + } + } }; loadCategoryMappings(); diff --git a/frontend/lib/registry/components/card-display/CardDisplayComponent.tsx b/frontend/lib/registry/components/card-display/CardDisplayComponent.tsx index f8bf39c7..55f6ea25 100644 --- a/frontend/lib/registry/components/card-display/CardDisplayComponent.tsx +++ b/frontend/lib/registry/components/card-display/CardDisplayComponent.tsx @@ -968,7 +968,7 @@ export const CardDisplayComponent: React.FC = ({ {/* 상세보기 모달 */} - + 📋 @@ -1041,7 +1041,7 @@ export const CardDisplayComponent: React.FC = ({ {/* 편집 모달 */} - + ✏️ diff --git a/frontend/lib/registry/components/entity-search-input/EntitySearchModal.tsx b/frontend/lib/registry/components/entity-search-input/EntitySearchModal.tsx index 00daed0a..7f841ec3 100644 --- a/frontend/lib/registry/components/entity-search-input/EntitySearchModal.tsx +++ b/frontend/lib/registry/components/entity-search-input/EntitySearchModal.tsx @@ -79,7 +79,7 @@ export function EntitySearchModal({ return ( - + {modalTitle} diff --git a/frontend/lib/registry/components/file-upload/FileViewerModal.tsx b/frontend/lib/registry/components/file-upload/FileViewerModal.tsx index 8ccb93ff..9eb0edeb 100644 --- a/frontend/lib/registry/components/file-upload/FileViewerModal.tsx +++ b/frontend/lib/registry/components/file-upload/FileViewerModal.tsx @@ -491,7 +491,7 @@ export const FileViewerModal: React.FC = ({ file, isOpen, return ( {}}> - +
@@ -506,7 +506,7 @@ export const FileViewerModal: React.FC = ({ file, isOpen, -
{renderPreview()}
+
{renderPreview()}
{/* 파일 정보 및 액션 버튼 */}
diff --git a/frontend/lib/registry/components/modal-repeater-table/ItemSelectionModal.tsx b/frontend/lib/registry/components/modal-repeater-table/ItemSelectionModal.tsx index 60da98f8..456594c2 100644 --- a/frontend/lib/registry/components/modal-repeater-table/ItemSelectionModal.tsx +++ b/frontend/lib/registry/components/modal-repeater-table/ItemSelectionModal.tsx @@ -166,7 +166,7 @@ export function ItemSelectionModal({ return ( - + {modalTitle} @@ -222,8 +222,8 @@ export function ItemSelectionModal({ )} {/* 검색 결과 테이블 */} -
-
+
+
diff --git a/frontend/lib/registry/components/table-list/TableListComponent.tsx b/frontend/lib/registry/components/table-list/TableListComponent.tsx index 4f78ed23..22c26e45 100644 --- a/frontend/lib/registry/components/table-list/TableListComponent.tsx +++ b/frontend/lib/registry/components/table-list/TableListComponent.tsx @@ -969,15 +969,30 @@ export const TableListComponent: React.FC = ({ try { const mappings: Record> = {}; + const apiClient = (await import("@/lib/api/client")).apiClient; for (const columnName of categoryColumns) { try { + // 🆕 엔티티 조인 컬럼 처리: "테이블명.컬럼명" 형태인지 확인 + let targetTable = tableConfig.selectedTable; + let targetColumn = columnName; + + if (columnName.includes(".")) { + const parts = columnName.split("."); + targetTable = parts[0]; // 조인된 테이블명 (예: item_info) + targetColumn = parts[1]; // 실제 컬럼명 (예: material) + console.log(`🔗 [TableList] 엔티티 조인 컬럼 감지:`, { + originalColumn: columnName, + targetTable, + targetColumn, + }); + } + console.log(`📡 [TableList] API 호출 시작 [${columnName}]:`, { - url: `/table-categories/${tableConfig.selectedTable}/${columnName}/values`, + url: `/table-categories/${targetTable}/${targetColumn}/values`, }); - const apiClient = (await import("@/lib/api/client")).apiClient; - const response = await apiClient.get(`/table-categories/${tableConfig.selectedTable}/${columnName}/values`); + const response = await apiClient.get(`/table-categories/${targetTable}/${targetColumn}/values`); console.log(`📡 [TableList] API 응답 [${columnName}]:`, { success: response.data.success, @@ -1000,6 +1015,7 @@ export const TableListComponent: React.FC = ({ }); if (Object.keys(mapping).length > 0) { + // 🆕 원래 컬럼명(item_info.material)으로 매핑 저장 mappings[columnName] = mapping; console.log(`✅ [TableList] 카테고리 매핑 로드 완료 [${columnName}]:`, { columnName, @@ -1028,6 +1044,59 @@ export const TableListComponent: React.FC = ({ } } + // 🆕 엔티티 조인 컬럼 중 카테고리 타입이 아니지만 조인된 테이블의 카테고리 필드인 경우도 로드 + // 화면 설정의 columns에서 "테이블명.컬럼명" 형태의 조인 컬럼 추출 + const joinedColumns = tableConfig.columns + ?.filter((col) => col.columnName?.includes(".")) + .map((col) => col.columnName) || []; + + // 알려진 카테고리 필드 목록 (조인된 테이블에서 자주 사용되는 카테고리 컬럼) + const knownCategoryFields = ["material", "division", "status", "currency_code", "inbound_type", "outbound_type"]; + + for (const joinedColumn of joinedColumns) { + // 이미 로드된 컬럼은 스킵 + if (mappings[joinedColumn]) continue; + + const parts = joinedColumn.split("."); + if (parts.length !== 2) continue; + + const joinedTable = parts[0]; + const joinedColumnName = parts[1]; + + // 알려진 카테고리 필드인 경우만 로드 시도 + if (!knownCategoryFields.includes(joinedColumnName)) continue; + + try { + console.log(`📡 [TableList] 조인 테이블 카테고리 로드 시도 [${joinedColumn}]:`, { + url: `/table-categories/${joinedTable}/${joinedColumnName}/values`, + }); + + const response = await apiClient.get(`/table-categories/${joinedTable}/${joinedColumnName}/values`); + + if (response.data.success && response.data.data && Array.isArray(response.data.data)) { + const mapping: Record = {}; + + response.data.data.forEach((item: any) => { + const key = String(item.valueCode); + mapping[key] = { + label: item.valueLabel, + color: item.color, + }; + }); + + if (Object.keys(mapping).length > 0) { + mappings[joinedColumn] = mapping; + console.log(`✅ [TableList] 조인 테이블 카테고리 매핑 로드 완료 [${joinedColumn}]:`, { + mappingCount: Object.keys(mapping).length, + }); + } + } + } catch (error) { + // 조인 테이블 카테고리 로드 실패는 무시 (카테고리가 아닌 필드일 수 있음) + console.log(`ℹ️ [TableList] 조인 테이블 카테고리 없음 (${joinedColumn})`); + } + } + console.log("📊 [TableList] 전체 카테고리 매핑 설정:", { mappingsCount: Object.keys(mappings).length, mappingsKeys: Object.keys(mappings), @@ -1047,7 +1116,7 @@ export const TableListComponent: React.FC = ({ }; loadCategoryMappings(); - }, [tableConfig.selectedTable, categoryColumns.length, JSON.stringify(categoryColumns)]); // 더 명확한 의존성 + }, [tableConfig.selectedTable, categoryColumns.length, JSON.stringify(categoryColumns), JSON.stringify(tableConfig.columns)]); // 더 명확한 의존성 // ======================================== // 데이터 가져오기 @@ -1885,7 +1954,18 @@ export const TableListComponent: React.FC = ({ if (inputType === "category") { if (!value) return ""; - const mapping = categoryMappings[column.columnName]; + // 🆕 엔티티 조인 컬럼의 경우 여러 형태로 매핑 찾기 + // 1. 원래 컬럼명 (item_info.material) + // 2. 점(.) 뒤의 컬럼명만 (material) + let mapping = categoryMappings[column.columnName]; + + if (!mapping && column.columnName.includes(".")) { + const simpleColumnName = column.columnName.split(".").pop(); + if (simpleColumnName) { + mapping = categoryMappings[simpleColumnName]; + } + } + const { Badge } = require("@/components/ui/badge"); // 다중 값 처리: 콤마로 구분된 값들을 분리 diff --git a/frontend/lib/registry/components/table-list/TableListConfigPanel.tsx b/frontend/lib/registry/components/table-list/TableListConfigPanel.tsx index 209b3d2d..17ab3417 100644 --- a/frontend/lib/registry/components/table-list/TableListConfigPanel.tsx +++ b/frontend/lib/registry/components/table-list/TableListConfigPanel.tsx @@ -265,7 +265,7 @@ export const TableListConfigPanel: React.FC = ({ columnName: col.columnName || col.column_name, dataType: col.dataType || col.data_type || "text", label: col.displayName || col.columnLabel || col.column_label || col.columnName || col.column_name, - })) + })), ); console.log("✅ 참조 테이블 컬럼 로드 완료:", columns.length, "개"); } @@ -511,7 +511,7 @@ export const TableListConfigPanel: React.FC = ({ // 🎯 엔티티 컬럼의 표시 컬럼 정보 로드 const loadEntityDisplayConfig = async (column: ColumnConfig) => { const configKey = `${column.columnName}`; - + // 이미 로드된 경우 스킵 if (entityDisplayConfigs[configKey]) return; @@ -609,7 +609,7 @@ export const TableListConfigPanel: React.FC = ({ // 기본 테이블 컬럼 정보는 항상 로드 const sourceResult = await entityJoinApi.getReferenceTableColumns(sourceTable); const sourceColumns = sourceResult.columns || []; - + // joinTable이 있으면 조인 테이블 컬럼도 로드 let joinColumns: Array<{ columnName: string; displayName: string; dataType: string }> = []; if (joinTable) { @@ -761,9 +761,7 @@ export const TableListConfigPanel: React.FC = ({ placeholder="테이블 제목 입력..." className="h-8 text-xs" /> -

- 우선순위: 사용자 입력 제목 → 테이블 라벨명 → 테이블명 -

+

우선순위: 사용자 입력 제목 → 테이블 라벨명 → 테이블명

@@ -782,7 +780,7 @@ export const TableListConfigPanel: React.FC = ({ /> - + {config.checkbox?.enabled && ( <>
@@ -793,7 +791,7 @@ export const TableListConfigPanel: React.FC = ({ />
- +
{/* 참조 테이블 미설정 안내 */} - {!column.entityDisplayConfig?.joinTable && entityDisplayConfigs[column.columnName].sourceColumns.length > 0 && ( -
- 현재 기본 테이블 컬럼만 표시됩니다. 테이블 타입 관리에서 참조 테이블을 설정하면 조인된 테이블의 컬럼도 선택할 수 있습니다. -
- )} + {!column.entityDisplayConfig?.joinTable && + entityDisplayConfigs[column.columnName].sourceColumns.length > 0 && ( +
+ 현재 기본 테이블 컬럼만 표시됩니다. 테이블 타입 관리에서 참조 테이블을 설정하면 조인된 + 테이블의 컬럼도 선택할 수 있습니다. +
+ )} {/* 선택된 컬럼 미리보기 */} {entityDisplayConfigs[column.columnName].selectedColumns.length > 0 && ( @@ -1107,7 +1109,7 @@ export const TableListConfigPanel: React.FC = ({ // 해당 컬럼의 input_type 확인 const columnInfo = availableColumns.find((col) => col.columnName === column.columnName); const isNumberType = columnInfo?.input_type === "number" || columnInfo?.input_type === "decimal"; - + return (
= ({ {columnInfo?.label || column.displayName || column.columnName} - + {/* 숫자 타입인 경우 천단위 구분자 설정 */} {isNumberType && (
@@ -1131,9 +1133,9 @@ export const TableListConfigPanel: React.FC = ({ }} className="h-3 w-3" /> - @@ -1147,8 +1149,7 @@ export const TableListConfigPanel: React.FC = ({ checked={config.filter?.filters?.some((f) => f.columnName === column.columnName) || false} onCheckedChange={(checked) => { const currentFilters = config.filter?.filters || []; - const columnLabel = - columnInfo?.label || column.displayName || column.columnName; + const columnLabel = columnInfo?.label || column.displayName || column.columnName; if (checked) { // 필터 추가 @@ -1240,9 +1241,7 @@ export const TableListConfigPanel: React.FC = ({ placeholder="40" className="h-8 text-xs" /> -

- 기본값: 40px (0-200px 범위, 10px 단위 권장) -

+

기본값: 40px (0-200px 범위, 10px 단위 권장)

)} @@ -1251,19 +1250,20 @@ export const TableListConfigPanel: React.FC = ({

데이터 필터링

-

- 특정 컬럼 값으로 데이터를 필터링합니다 -

+

특정 컬럼 값으로 데이터를 필터링합니다


({ - columnName: col.columnName, - columnLabel: col.label || col.columnName, - dataType: col.dataType, - input_type: col.input_type, // 🆕 실제 input_type 전달 - } as any))} + columns={availableColumns.map( + (col) => + ({ + columnName: col.columnName, + columnLabel: col.label || col.columnName, + dataType: col.dataType, + input_type: col.input_type, // 🆕 실제 input_type 전달 + }) as any, + )} config={config.dataFilter} onConfigChange={(dataFilter) => handleChange("dataFilter", dataFilter)} /> @@ -1273,12 +1273,12 @@ export const TableListConfigPanel: React.FC = ({

연결된 필터

-

+

셀렉트박스 등 다른 컴포넌트의 값으로 테이블 데이터를 실시간 필터링합니다


- + {/* 연결된 필터 목록 */}
{(config.linkedFilters || []).map((filter, index) => ( @@ -1293,16 +1293,12 @@ export const TableListConfigPanel: React.FC = ({ newFilters[index] = { ...filter, sourceComponentId: e.target.value }; handleChange("linkedFilters", newFilters); }} - className="h-7 text-xs flex-1" + className="h-7 flex-1 text-xs" /> - + - @@ -1311,7 +1307,7 @@ export const TableListConfigPanel: React.FC = ({ - 컬럼을 찾을 수 없습니다 + 컬럼을 찾을 수 없습니다 {availableColumns.map((col) => ( = ({ {col.label || col.columnName} @@ -1353,7 +1349,7 @@ export const TableListConfigPanel: React.FC = ({
))} - + {/* 연결된 필터 추가 버튼 */} - -

+ +

예: 셀렉트박스(ID: select-basic-123)의 값으로 테이블의 inbound_type 컬럼을 필터링

@@ -1381,12 +1377,12 @@ export const TableListConfigPanel: React.FC = ({

제외 필터

-

+

다른 테이블에 이미 존재하는 데이터를 목록에서 제외합니다


- + {/* 제외 필터 활성화 */}
= ({ 제외 필터 활성화
- + {config.excludeFilter?.enabled && (
{/* 참조 테이블 선택 */} @@ -1411,11 +1407,7 @@ export const TableListConfigPanel: React.FC = ({ - @@ -1424,7 +1416,7 @@ export const TableListConfigPanel: React.FC = ({ - 테이블을 찾을 수 없습니다 + 테이블을 찾을 수 없습니다 {availableTables.map((table) => ( = ({ {table.displayName || table.tableName} @@ -1457,7 +1451,7 @@ export const TableListConfigPanel: React.FC = ({
- + {config.excludeFilter?.referenceTable && ( <> {/* 비교 컬럼 설정 - 한 줄에 두 개 */} @@ -1473,9 +1467,7 @@ export const TableListConfigPanel: React.FC = ({ disabled={loadingReferenceColumns} className="h-8 w-full justify-between text-xs" > - {loadingReferenceColumns - ? "..." - : config.excludeFilter?.referenceColumn || "선택"} + {loadingReferenceColumns ? "..." : config.excludeFilter?.referenceColumn || "선택"} @@ -1483,7 +1475,7 @@ export const TableListConfigPanel: React.FC = ({ - 없음 + 없음 {referenceTableColumns.map((col) => ( = ({ {col.label || col.columnName} @@ -1512,17 +1506,13 @@ export const TableListConfigPanel: React.FC = ({
- + {/* 소스 컬럼 (현재 테이블) */}
- @@ -1531,7 +1521,7 @@ export const TableListConfigPanel: React.FC = ({ - 없음 + 없음 {availableColumns.map((col) => ( = ({ {col.label || col.columnName} @@ -1561,11 +1553,11 @@ export const TableListConfigPanel: React.FC = ({
- + {/* 조건 필터 - 특정 조건의 데이터만 제외 */}
-

+

특정 조건의 데이터만 제외하려면 설정하세요 (예: 특정 거래처의 품목만)

@@ -1578,9 +1570,9 @@ export const TableListConfigPanel: React.FC = ({ disabled={loadingReferenceColumns} className="h-8 w-full justify-between text-xs" > - {loadingReferenceColumns - ? "..." - : config.excludeFilter?.filterColumn + {loadingReferenceColumns + ? "..." + : config.excludeFilter?.filterColumn ? `매핑: ${config.excludeFilter.filterColumn}` : "매핑 테이블 컬럼"} @@ -1590,7 +1582,7 @@ export const TableListConfigPanel: React.FC = ({ - 없음 + 없음 = ({ filterValueField: undefined, }); }} - className="text-xs text-muted-foreground" + className="text-muted-foreground text-xs" > - + 사용 안함 {referenceTableColumns.map((col) => ( @@ -1624,7 +1621,9 @@ export const TableListConfigPanel: React.FC = ({ {col.label || col.columnName} @@ -1635,7 +1634,7 @@ export const TableListConfigPanel: React.FC = ({ - + {/* 필터 값 필드명 (부모 화면에서 전달받는 필드) */} = ({
)} - + {/* 설정 요약 */} - {config.excludeFilter?.referenceTable && config.excludeFilter?.referenceColumn && config.excludeFilter?.sourceColumn && ( -
- 설정 요약: {config.selectedTable || screenTableName}.{config.excludeFilter.sourceColumn} 가 - {" "}{config.excludeFilter.referenceTable}.{config.excludeFilter.referenceColumn} 에 - {config.excludeFilter.filterColumn && config.excludeFilter.filterValueField && ( - <> ({config.excludeFilter.filterColumn}=URL의 {config.excludeFilter.filterValueField}일 때) - )} - {" "}이미 있으면 제외 -
- )} + {config.excludeFilter?.referenceTable && + config.excludeFilter?.referenceColumn && + config.excludeFilter?.sourceColumn && ( +
+ 설정 요약: {config.selectedTable || screenTableName}. + {config.excludeFilter.sourceColumn} 가 {config.excludeFilter.referenceTable}. + {config.excludeFilter.referenceColumn} 에 + {config.excludeFilter.filterColumn && config.excludeFilter.filterValueField && ( + <> + {" "} + ({config.excludeFilter.filterColumn}=URL의 {config.excludeFilter.filterValueField}일 때) + + )}{" "} + 이미 있으면 제외 +
+ )}
)} diff --git a/화면_임베딩_및_데이터_전달_시스템_구현_계획서.md b/화면_임베딩_및_데이터_전달_시스템_구현_계획서.md index 74d9d0ed..687896c1 100644 --- a/화면_임베딩_및_데이터_전달_시스템_구현_계획서.md +++ b/화면_임베딩_및_데이터_전달_시스템_구현_계획서.md @@ -1680,3 +1680,4 @@ const 출고등록_설정: ScreenSplitPanel = { 화면 임베딩 및 데이터 전달 시스템은 복잡한 업무 워크플로우를 효율적으로 처리할 수 있는 강력한 기능입니다. 단계별로 체계적으로 구현하면 약 3.5개월 내에 완성할 수 있으며, 이를 통해 사용자 경험을 크게 향상시킬 수 있습니다. + diff --git a/화면_임베딩_시스템_Phase1-4_구현_완료.md b/화면_임베딩_시스템_Phase1-4_구현_완료.md index 47526bb1..bc025b41 100644 --- a/화면_임베딩_시스템_Phase1-4_구현_완료.md +++ b/화면_임베딩_시스템_Phase1-4_구현_완료.md @@ -527,3 +527,4 @@ const { data: config } = await getScreenSplitPanel(screenId); 이제 입고 등록과 같은 복잡한 워크플로우를 구현할 수 있습니다. 다음 단계는 각 컴포넌트 타입별 DataReceivable 인터페이스 구현과 설정 UI 개발입니다. + diff --git a/화면_임베딩_시스템_충돌_분석_보고서.md b/화면_임베딩_시스템_충돌_분석_보고서.md index 135d36d8..cdd94d36 100644 --- a/화면_임베딩_시스템_충돌_분석_보고서.md +++ b/화면_임베딩_시스템_충돌_분석_보고서.md @@ -514,3 +514,4 @@ function ScreenViewPage() { 새로운 시스템은 기존 시스템과 **독립적으로 동작**하며, 최소한의 수정만으로 통합 가능합니다. 화면 페이지에 조건 분기만 추가하면 바로 사용할 수 있습니다. + From 662956edd44e566cee7355ea6324cb60b203b69c Mon Sep 17 00:00:00 2001 From: kjs Date: Fri, 5 Dec 2025 11:04:42 +0900 Subject: [PATCH 02/18] =?UTF-8?q?=EC=97=94=ED=8B=B0=ED=8B=B0=20=EC=B9=B4?= =?UTF-8?q?=ED=85=8C=EA=B3=A0=EB=A6=AC=20=ED=83=80=EC=9E=85=20=EC=BB=AC?= =?UTF-8?q?=EB=9F=BC=20=EB=B0=B0=EC=A7=80=20=ED=91=9C=EC=8B=9C=EA=B8=B0?= =?UTF-8?q?=EB=8A=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../table-list/TableListComponent.tsx | 130 +++++++++++++----- ..._임베딩_및_데이터_전달_시스템_구현_계획서.md | 1 + 화면_임베딩_시스템_Phase1-4_구현_완료.md | 1 + 화면_임베딩_시스템_충돌_분석_보고서.md | 1 + 4 files changed, 101 insertions(+), 32 deletions(-) diff --git a/frontend/lib/registry/components/table-list/TableListComponent.tsx b/frontend/lib/registry/components/table-list/TableListComponent.tsx index 22c26e45..5b397d57 100644 --- a/frontend/lib/registry/components/table-list/TableListComponent.tsx +++ b/frontend/lib/registry/components/table-list/TableListComponent.tsx @@ -365,6 +365,10 @@ export const TableListComponent: React.FC = ({ const [columnMeta, setColumnMeta] = useState< Record >({}); + // 🆕 엔티티 조인 테이블의 컬럼 메타데이터 (테이블명.컬럼명 → inputType) + const [joinedColumnMeta, setJoinedColumnMeta] = useState< + Record + >({}); const [categoryMappings, setCategoryMappings] = useState< Record> >({}); @@ -1044,58 +1048,119 @@ export const TableListComponent: React.FC = ({ } } - // 🆕 엔티티 조인 컬럼 중 카테고리 타입이 아니지만 조인된 테이블의 카테고리 필드인 경우도 로드 - // 화면 설정의 columns에서 "테이블명.컬럼명" 형태의 조인 컬럼 추출 + // 🆕 엔티티 조인 컬럼의 inputType 정보 가져오기 및 카테고리 매핑 로드 + // 1. "테이블명.컬럼명" 형태의 조인 컬럼 추출 const joinedColumns = tableConfig.columns ?.filter((col) => col.columnName?.includes(".")) .map((col) => col.columnName) || []; - // 알려진 카테고리 필드 목록 (조인된 테이블에서 자주 사용되는 카테고리 컬럼) - const knownCategoryFields = ["material", "division", "status", "currency_code", "inbound_type", "outbound_type"]; + // 2. additionalJoinInfo가 있는 컬럼도 추출 (예: item_code_material → item_info.material) + const additionalJoinColumns = tableConfig.columns + ?.filter((col: any) => col.additionalJoinInfo?.referenceTable) + .map((col: any) => ({ + columnName: col.columnName, // 예: item_code_material + referenceTable: col.additionalJoinInfo.referenceTable, // 예: item_info + // joinAlias에서 실제 컬럼명 추출 (item_code_material → material) + actualColumn: col.additionalJoinInfo.joinAlias?.replace(`${col.additionalJoinInfo.sourceColumn}_`, '') || col.columnName, + })) || []; + console.log("🔍 [TableList] additionalJoinInfo 컬럼:", additionalJoinColumns); + + // 조인 테이블별로 그룹화 + const joinedTableColumns: Record = {}; + + // "테이블명.컬럼명" 형태 처리 for (const joinedColumn of joinedColumns) { - // 이미 로드된 컬럼은 스킵 - if (mappings[joinedColumn]) continue; - const parts = joinedColumn.split("."); if (parts.length !== 2) continue; const joinedTable = parts[0]; const joinedColumnName = parts[1]; - // 알려진 카테고리 필드인 경우만 로드 시도 - if (!knownCategoryFields.includes(joinedColumnName)) continue; - + if (!joinedTableColumns[joinedTable]) { + joinedTableColumns[joinedTable] = []; + } + joinedTableColumns[joinedTable].push({ + columnName: joinedColumn, + actualColumn: joinedColumnName, + }); + } + + // additionalJoinInfo 형태 처리 + for (const col of additionalJoinColumns) { + if (!joinedTableColumns[col.referenceTable]) { + joinedTableColumns[col.referenceTable] = []; + } + joinedTableColumns[col.referenceTable].push({ + columnName: col.columnName, // 예: item_code_material + actualColumn: col.actualColumn, // 예: material + }); + } + + console.log("🔍 [TableList] 조인 테이블별 컬럼:", joinedTableColumns); + + // 조인된 테이블별로 inputType 정보 가져오기 + const newJoinedColumnMeta: Record = {}; + + for (const [joinedTable, columns] of Object.entries(joinedTableColumns)) { try { - console.log(`📡 [TableList] 조인 테이블 카테고리 로드 시도 [${joinedColumn}]:`, { - url: `/table-categories/${joinedTable}/${joinedColumnName}/values`, - }); + // 조인 테이블의 컬럼 inputType 정보 가져오기 (이미 import된 tableTypeApi 사용) + const inputTypes = await tableTypeApi.getColumnInputTypes(joinedTable); - const response = await apiClient.get(`/table-categories/${joinedTable}/${joinedColumnName}/values`); + console.log(`📡 [TableList] 조인 테이블 inputType 로드 [${joinedTable}]:`, inputTypes); - if (response.data.success && response.data.data && Array.isArray(response.data.data)) { - const mapping: Record = {}; + for (const col of columns) { + const inputTypeInfo = inputTypes.find((it: any) => it.columnName === col.actualColumn); - response.data.data.forEach((item: any) => { - const key = String(item.valueCode); - mapping[key] = { - label: item.valueLabel, - color: item.color, - }; - }); + // 컬럼명 그대로 저장 (item_code_material 또는 item_info.material) + newJoinedColumnMeta[col.columnName] = { + inputType: inputTypeInfo?.inputType, + }; - if (Object.keys(mapping).length > 0) { - mappings[joinedColumn] = mapping; - console.log(`✅ [TableList] 조인 테이블 카테고리 매핑 로드 완료 [${joinedColumn}]:`, { - mappingCount: Object.keys(mapping).length, - }); + console.log(` 🔗 [${col.columnName}] (실제: ${col.actualColumn}) inputType: ${inputTypeInfo?.inputType || "unknown"}`); + + // inputType이 category인 경우 카테고리 매핑 로드 + if (inputTypeInfo?.inputType === "category" && !mappings[col.columnName]) { + try { + console.log(`📡 [TableList] 조인 테이블 카테고리 로드 시도 [${col.columnName}]:`, { + url: `/table-categories/${joinedTable}/${col.actualColumn}/values`, + }); + + const response = await apiClient.get(`/table-categories/${joinedTable}/${col.actualColumn}/values`); + + if (response.data.success && response.data.data && Array.isArray(response.data.data)) { + const mapping: Record = {}; + + response.data.data.forEach((item: any) => { + const key = String(item.valueCode); + mapping[key] = { + label: item.valueLabel, + color: item.color, + }; + }); + + if (Object.keys(mapping).length > 0) { + mappings[col.columnName] = mapping; + console.log(`✅ [TableList] 조인 테이블 카테고리 매핑 로드 완료 [${col.columnName}]:`, { + mappingCount: Object.keys(mapping).length, + }); + } + } + } catch (error) { + console.log(`ℹ️ [TableList] 조인 테이블 카테고리 없음 (${col.columnName})`); + } } } } catch (error) { - // 조인 테이블 카테고리 로드 실패는 무시 (카테고리가 아닌 필드일 수 있음) - console.log(`ℹ️ [TableList] 조인 테이블 카테고리 없음 (${joinedColumn})`); + console.error(`❌ [TableList] 조인 테이블 inputType 로드 실패 [${joinedTable}]:`, error); } } + + // 조인 컬럼 메타데이터 상태 업데이트 + if (Object.keys(newJoinedColumnMeta).length > 0) { + setJoinedColumnMeta(newJoinedColumnMeta); + console.log("✅ [TableList] 조인 컬럼 메타데이터 설정:", newJoinedColumnMeta); + } console.log("📊 [TableList] 전체 카테고리 매핑 설정:", { mappingsCount: Object.keys(mappings).length, @@ -1929,7 +1994,8 @@ export const TableListComponent: React.FC = ({ return rowData.writer_name; } - const meta = columnMeta[column.columnName]; + // 🆕 메인 테이블 메타 또는 조인 테이블 메타에서 정보 가져오기 + const meta = columnMeta[column.columnName] || joinedColumnMeta[column.columnName]; // inputType 기반 포맷팅 (columnMeta에서 가져온 inputType 우선) const inputType = meta?.inputType || column.inputType; @@ -2119,7 +2185,7 @@ export const TableListComponent: React.FC = ({ return String(value); } }, - [columnMeta, optimizedConvertCode, categoryMappings], + [columnMeta, joinedColumnMeta, optimizedConvertCode, categoryMappings], ); // ======================================== diff --git a/화면_임베딩_및_데이터_전달_시스템_구현_계획서.md b/화면_임베딩_및_데이터_전달_시스템_구현_계획서.md index 687896c1..313a7567 100644 --- a/화면_임베딩_및_데이터_전달_시스템_구현_계획서.md +++ b/화면_임베딩_및_데이터_전달_시스템_구현_계획서.md @@ -1681,3 +1681,4 @@ const 출고등록_설정: ScreenSplitPanel = { + diff --git a/화면_임베딩_시스템_Phase1-4_구현_완료.md b/화면_임베딩_시스템_Phase1-4_구현_완료.md index bc025b41..373b6ec7 100644 --- a/화면_임베딩_시스템_Phase1-4_구현_완료.md +++ b/화면_임베딩_시스템_Phase1-4_구현_완료.md @@ -528,3 +528,4 @@ const { data: config } = await getScreenSplitPanel(screenId); + diff --git a/화면_임베딩_시스템_충돌_분석_보고서.md b/화면_임베딩_시스템_충돌_분석_보고서.md index cdd94d36..5d315706 100644 --- a/화면_임베딩_시스템_충돌_분석_보고서.md +++ b/화면_임베딩_시스템_충돌_분석_보고서.md @@ -515,3 +515,4 @@ function ScreenViewPage() { + From 1c329b5e0c23c9c18288672e9d32ba504abf540b Mon Sep 17 00:00:00 2001 From: kjs Date: Fri, 5 Dec 2025 14:08:07 +0900 Subject: [PATCH 03/18] =?UTF-8?q?=ED=99=94=EB=A9=B4=20=EB=B6=84=ED=95=A0?= =?UTF-8?q?=20=ED=8C=A8=EB=84=90=20=EC=9E=90=EB=8F=99=EC=9C=BC=EB=A1=9C=20?= =?UTF-8?q?=EB=8D=B0=EC=9D=B4=ED=84=B0=20=EB=84=98=EA=B8=B0=EB=8A=94=20?= =?UTF-8?q?=EA=B8=B0=EB=8A=A5=20=EC=84=A4=EC=A0=95=20=EA=B0=80=EB=8A=A5?= =?UTF-8?q?=ED=95=98=EA=B2=8C=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../screen-embedding/EmbeddedScreen.tsx | 7 ++++++ .../screen-embedding/ScreenSplitPanel.tsx | 1 + .../screen/InteractiveScreenViewerDynamic.tsx | 6 +++-- frontend/contexts/SplitPanelContext.tsx | 8 +++++++ .../card-display/CardDisplayComponent.tsx | 3 ++- .../ScreenSplitPanelConfigPanel.tsx | 22 +++++++++++++++++++ .../table-list/TableListComponent.tsx | 3 ++- 7 files changed, 46 insertions(+), 4 deletions(-) diff --git a/frontend/components/screen-embedding/EmbeddedScreen.tsx b/frontend/components/screen-embedding/EmbeddedScreen.tsx index 3880fc54..d8e62c00 100644 --- a/frontend/components/screen-embedding/EmbeddedScreen.tsx +++ b/frontend/components/screen-embedding/EmbeddedScreen.tsx @@ -92,10 +92,17 @@ export const EmbeddedScreen = forwardRef { // 우측 화면인 경우에만 적용 if (position !== "right" || !splitPanelContext) return; + // 자동 데이터 전달이 비활성화된 경우 스킵 + if (splitPanelContext.disableAutoDataTransfer) { + console.log("🔗 [EmbeddedScreen] 자동 데이터 전달 비활성화됨 - 버튼 클릭으로만 전달"); + return; + } + const mappedData = splitPanelContext.getMappedParentData(); if (Object.keys(mappedData).length > 0) { console.log("🔗 [EmbeddedScreen] 분할 패널 부모 데이터 자동 반영:", mappedData); diff --git a/frontend/components/screen-embedding/ScreenSplitPanel.tsx b/frontend/components/screen-embedding/ScreenSplitPanel.tsx index 60b6bf24..1b0eeb65 100644 --- a/frontend/components/screen-embedding/ScreenSplitPanel.tsx +++ b/frontend/components/screen-embedding/ScreenSplitPanel.tsx @@ -128,6 +128,7 @@ export function ScreenSplitPanel({ screenId, config, initialFormData }: ScreenSp rightScreenId={config?.rightScreenId || null} parentDataMapping={config?.parentDataMapping || []} linkedFilters={config?.linkedFilters || []} + disableAutoDataTransfer={config?.disableAutoDataTransfer ?? false} >
{/* 좌측 패널 */} diff --git a/frontend/components/screen/InteractiveScreenViewerDynamic.tsx b/frontend/components/screen/InteractiveScreenViewerDynamic.tsx index 41983df3..97dc0734 100644 --- a/frontend/components/screen/InteractiveScreenViewerDynamic.tsx +++ b/frontend/components/screen/InteractiveScreenViewerDynamic.tsx @@ -118,17 +118,19 @@ export const InteractiveScreenViewerDynamic: React.FC>({}); // 🆕 분할 패널에서 매핑된 부모 데이터 가져오기 + // disableAutoDataTransfer가 true이면 자동 전달 비활성화 (버튼 클릭으로만 전달) const splitPanelMappedData = React.useMemo(() => { - if (splitPanelContext) { + if (splitPanelContext && !splitPanelContext.disableAutoDataTransfer) { return splitPanelContext.getMappedParentData(); } return {}; - }, [splitPanelContext, splitPanelContext?.selectedLeftData]); + }, [splitPanelContext, splitPanelContext?.selectedLeftData, splitPanelContext?.disableAutoDataTransfer]); // formData 결정 (외부에서 전달받은 것이 있으면 우선 사용, 분할 패널 데이터도 병합) const formData = React.useMemo(() => { const baseData = externalFormData || localFormData; // 분할 패널 매핑 데이터가 있으면 병합 (기존 값이 없는 경우에만) + // disableAutoDataTransfer가 true이면 자동 병합 안함 if (Object.keys(splitPanelMappedData).length > 0) { const merged = { ...baseData }; for (const [key, value] of Object.entries(splitPanelMappedData)) { diff --git a/frontend/contexts/SplitPanelContext.tsx b/frontend/contexts/SplitPanelContext.tsx index 99cccdd8..20a0be00 100644 --- a/frontend/contexts/SplitPanelContext.tsx +++ b/frontend/contexts/SplitPanelContext.tsx @@ -88,6 +88,9 @@ interface SplitPanelContextValue { // 🆕 연결 필터 값 가져오기 (우측 테이블 조회 시 사용) getLinkedFilterValues: () => Record; + + // 🆕 자동 데이터 전달 비활성화 여부 (버튼 클릭 시에만 데이터 전달) + disableAutoDataTransfer: boolean; } const SplitPanelContext = createContext(null); @@ -98,6 +101,7 @@ interface SplitPanelProviderProps { rightScreenId: number | null; parentDataMapping?: ParentDataMapping[]; // 🆕 부모 데이터 매핑 설정 linkedFilters?: LinkedFilter[]; // 🆕 연결 필터 설정 + disableAutoDataTransfer?: boolean; // 🆕 자동 데이터 전달 비활성화 (버튼 클릭 시에만 전달) children: React.ReactNode; } @@ -110,6 +114,7 @@ export function SplitPanelProvider({ rightScreenId, parentDataMapping = [], linkedFilters = [], + disableAutoDataTransfer = false, children, }: SplitPanelProviderProps) { // 좌측/우측 화면의 데이터 수신자 맵 @@ -372,6 +377,8 @@ export function SplitPanelProvider({ // 🆕 연결 필터 관련 linkedFilters, getLinkedFilterValues, + // 🆕 자동 데이터 전달 비활성화 여부 + disableAutoDataTransfer, }), [ splitPanelId, leftScreenId, @@ -391,6 +398,7 @@ export function SplitPanelProvider({ getMappedParentData, linkedFilters, getLinkedFilterValues, + disableAutoDataTransfer, ]); return ( diff --git a/frontend/lib/registry/components/card-display/CardDisplayComponent.tsx b/frontend/lib/registry/components/card-display/CardDisplayComponent.tsx index 55f6ea25..a3876188 100644 --- a/frontend/lib/registry/components/card-display/CardDisplayComponent.tsx +++ b/frontend/lib/registry/components/card-display/CardDisplayComponent.tsx @@ -345,7 +345,8 @@ export const CardDisplayComponent: React.FC = ({ } // 분할 패널 컨텍스트에 선택된 데이터 저장 (좌측 화면인 경우) - if (splitPanelContext && splitPanelPosition === "left") { + // disableAutoDataTransfer가 true이면 자동 전달 비활성화 (버튼 클릭으로만 전달) + if (splitPanelContext && splitPanelPosition === "left" && !splitPanelContext.disableAutoDataTransfer) { if (checked) { splitPanelContext.setSelectedLeftData(data); console.log("[CardDisplay] 분할 패널 좌측 데이터 저장:", { diff --git a/frontend/lib/registry/components/screen-split-panel/ScreenSplitPanelConfigPanel.tsx b/frontend/lib/registry/components/screen-split-panel/ScreenSplitPanelConfigPanel.tsx index b8a1d3dc..0c167ab5 100644 --- a/frontend/lib/registry/components/screen-split-panel/ScreenSplitPanelConfigPanel.tsx +++ b/frontend/lib/registry/components/screen-split-panel/ScreenSplitPanelConfigPanel.tsx @@ -53,6 +53,7 @@ export function ScreenSplitPanelConfigPanel({ config = {}, onChange }: ScreenSpl buttonPosition: config.buttonPosition || "center", parentDataMapping: config.parentDataMapping || [] as ParentDataMapping[], linkedFilters: config.linkedFilters || [] as LinkedFilter[], + disableAutoDataTransfer: config.disableAutoDataTransfer ?? false, // 자동 데이터 전달 비활성화 ...config, }); @@ -69,6 +70,7 @@ export function ScreenSplitPanelConfigPanel({ config = {}, onChange }: ScreenSpl buttonPosition: config.buttonPosition || "center", parentDataMapping: config.parentDataMapping || [], linkedFilters: config.linkedFilters || [], + disableAutoDataTransfer: config.disableAutoDataTransfer ?? false, ...config, }); }, [config]); @@ -386,6 +388,26 @@ export function ScreenSplitPanelConfigPanel({ config = {}, onChange }: ScreenSpl onCheckedChange={(checked) => updateConfig("resizable", checked)} />
+ + + +
+
+ +

+ 좌측 행 선택 시 우측으로 데이터가 자동 전달되지 않습니다. +
+ 버튼 클릭으로만 데이터를 전달하려면 활성화하세요. +

+
+ updateConfig("disableAutoDataTransfer", checked)} + /> +
diff --git a/frontend/lib/registry/components/table-list/TableListComponent.tsx b/frontend/lib/registry/components/table-list/TableListComponent.tsx index 5b397d57..64e6e540 100644 --- a/frontend/lib/registry/components/table-list/TableListComponent.tsx +++ b/frontend/lib/registry/components/table-list/TableListComponent.tsx @@ -1764,7 +1764,8 @@ export const TableListComponent: React.FC = ({ handleRowSelection(rowKey, !isCurrentlySelected); // 🆕 분할 패널 컨텍스트에 선택된 데이터 저장 (좌측 화면인 경우) - if (splitPanelContext && splitPanelPosition === "left") { + // disableAutoDataTransfer가 true이면 자동 전달 비활성화 (버튼 클릭으로만 전달) + if (splitPanelContext && splitPanelPosition === "left" && !splitPanelContext.disableAutoDataTransfer) { if (!isCurrentlySelected) { // 선택된 경우: 데이터 저장 splitPanelContext.setSelectedLeftData(row); From 96321f502fddcf0ea4257b0311b464898ef6e132 Mon Sep 17 00:00:00 2001 From: kjs Date: Fri, 5 Dec 2025 15:18:55 +0900 Subject: [PATCH 04/18] =?UTF-8?q?=EC=A0=9C=EC=96=B4=20=EC=A7=91=EA=B3=84?= =?UTF-8?q?=ED=95=A8=EC=88=98=20=EB=85=B8=EB=93=9C=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/services/nodeFlowExecutionService.ts | 160 ++++++ .../dataflow/node-editor/FlowEditor.tsx | 2 + .../node-editor/nodes/AggregateNode.tsx | 107 ++++ .../node-editor/panels/PropertiesPanel.tsx | 6 + .../panels/properties/AggregateProperties.tsx | 526 ++++++++++++++++++ .../properties/InsertActionProperties.tsx | 45 +- .../properties/UpdateActionProperties.tsx | 42 +- .../properties/UpsertActionProperties.tsx | 40 +- .../node-editor/sidebar/nodePaletteConfig.ts | 8 + frontend/types/node-editor.ts | 30 + 10 files changed, 959 insertions(+), 7 deletions(-) create mode 100644 frontend/components/dataflow/node-editor/nodes/AggregateNode.tsx create mode 100644 frontend/components/dataflow/node-editor/panels/properties/AggregateProperties.tsx diff --git a/backend-node/src/services/nodeFlowExecutionService.ts b/backend-node/src/services/nodeFlowExecutionService.ts index 9cdd85f3..e70a1dae 100644 --- a/backend-node/src/services/nodeFlowExecutionService.ts +++ b/backend-node/src/services/nodeFlowExecutionService.ts @@ -528,6 +528,9 @@ export class NodeFlowExecutionService { case "dataTransform": return this.executeDataTransform(node, inputData, context); + case "aggregate": + return this.executeAggregate(node, inputData, context); + case "insertAction": return this.executeInsertAction(node, inputData, context, client); @@ -3197,4 +3200,161 @@ export class NodeFlowExecutionService { "upsertAction", ].includes(nodeType); } + + /** + * 집계 노드 실행 (SUM, COUNT, AVG, MIN, MAX 등) + */ + private static async executeAggregate( + node: FlowNode, + inputData: any, + context: ExecutionContext + ): Promise { + const { groupByFields = [], aggregations = [], havingConditions = [] } = node.data; + + logger.info(`📊 집계 노드 실행: ${node.data.displayName || node.id}`); + + // 입력 데이터가 없으면 빈 배열 반환 + if (!inputData || !Array.isArray(inputData) || inputData.length === 0) { + logger.warn("⚠️ 집계할 입력 데이터가 없습니다."); + return []; + } + + logger.info(`📥 입력 데이터: ${inputData.length}건`); + logger.info(`📊 그룹 기준: ${groupByFields.length > 0 ? groupByFields.map((f: any) => f.field).join(", ") : "전체"}`); + logger.info(`📊 집계 연산: ${aggregations.length}개`); + + // 그룹화 수행 + const groups = new Map(); + + for (const row of inputData) { + // 그룹 키 생성 + const groupKey = groupByFields.length > 0 + ? groupByFields.map((f: any) => String(row[f.field] ?? "")).join("|||") + : "__ALL__"; + + if (!groups.has(groupKey)) { + groups.set(groupKey, []); + } + groups.get(groupKey)!.push(row); + } + + logger.info(`📊 그룹 수: ${groups.size}개`); + + // 각 그룹에 대해 집계 수행 + const results: any[] = []; + + for (const [groupKey, groupRows] of groups) { + const resultRow: any = {}; + + // 그룹 기준 필드값 추가 + if (groupByFields.length > 0) { + const keyValues = groupKey.split("|||"); + groupByFields.forEach((field: any, idx: number) => { + resultRow[field.field] = keyValues[idx]; + }); + } + + // 각 집계 연산 수행 + for (const agg of aggregations) { + const { sourceField, function: aggFunc, outputField } = agg; + + if (!outputField) continue; + + let aggregatedValue: any; + + switch (aggFunc) { + case "SUM": + aggregatedValue = groupRows.reduce((sum: number, row: any) => { + const val = parseFloat(row[sourceField]); + return sum + (isNaN(val) ? 0 : val); + }, 0); + break; + + case "COUNT": + aggregatedValue = groupRows.length; + break; + + case "AVG": + const sum = groupRows.reduce((acc: number, row: any) => { + const val = parseFloat(row[sourceField]); + return acc + (isNaN(val) ? 0 : val); + }, 0); + aggregatedValue = groupRows.length > 0 ? sum / groupRows.length : 0; + break; + + case "MIN": + aggregatedValue = groupRows.reduce((min: number | null, row: any) => { + const val = parseFloat(row[sourceField]); + if (isNaN(val)) return min; + return min === null ? val : Math.min(min, val); + }, null); + break; + + case "MAX": + aggregatedValue = groupRows.reduce((max: number | null, row: any) => { + const val = parseFloat(row[sourceField]); + if (isNaN(val)) return max; + return max === null ? val : Math.max(max, val); + }, null); + break; + + case "FIRST": + aggregatedValue = groupRows.length > 0 ? groupRows[0][sourceField] : null; + break; + + case "LAST": + aggregatedValue = groupRows.length > 0 ? groupRows[groupRows.length - 1][sourceField] : null; + break; + + default: + logger.warn(`⚠️ 지원하지 않는 집계 함수: ${aggFunc}`); + aggregatedValue = null; + } + + resultRow[outputField] = aggregatedValue; + logger.info(` ${aggFunc}(${sourceField}) → ${outputField}: ${aggregatedValue}`); + } + + results.push(resultRow); + } + + // HAVING 조건 적용 (집계 후 필터링) + let filteredResults = results; + if (havingConditions && havingConditions.length > 0) { + filteredResults = results.filter((row) => { + return havingConditions.every((condition: any) => { + const fieldValue = row[condition.field]; + const compareValue = parseFloat(condition.value); + + switch (condition.operator) { + case "=": + return fieldValue === compareValue; + case "!=": + return fieldValue !== compareValue; + case ">": + return fieldValue > compareValue; + case ">=": + return fieldValue >= compareValue; + case "<": + return fieldValue < compareValue; + case "<=": + return fieldValue <= compareValue; + default: + return true; + } + }); + }); + + logger.info(`📊 HAVING 필터링: ${results.length}건 → ${filteredResults.length}건`); + } + + logger.info(`✅ 집계 완료: ${filteredResults.length}건 결과`); + + // 결과 샘플 출력 + if (filteredResults.length > 0) { + logger.info(`📄 결과 샘플:`, JSON.stringify(filteredResults[0], null, 2)); + } + + return filteredResults; + } } diff --git a/frontend/components/dataflow/node-editor/FlowEditor.tsx b/frontend/components/dataflow/node-editor/FlowEditor.tsx index c87c80aa..f74d35aa 100644 --- a/frontend/components/dataflow/node-editor/FlowEditor.tsx +++ b/frontend/components/dataflow/node-editor/FlowEditor.tsx @@ -25,6 +25,7 @@ import { UpdateActionNode } from "./nodes/UpdateActionNode"; import { DeleteActionNode } from "./nodes/DeleteActionNode"; import { UpsertActionNode } from "./nodes/UpsertActionNode"; import { DataTransformNode } from "./nodes/DataTransformNode"; +import { AggregateNode } from "./nodes/AggregateNode"; import { RestAPISourceNode } from "./nodes/RestAPISourceNode"; import { CommentNode } from "./nodes/CommentNode"; import { LogNode } from "./nodes/LogNode"; @@ -41,6 +42,7 @@ const nodeTypes = { // 변환/조건 condition: ConditionNode, dataTransform: DataTransformNode, + aggregate: AggregateNode, // 액션 insertAction: InsertActionNode, updateAction: UpdateActionNode, diff --git a/frontend/components/dataflow/node-editor/nodes/AggregateNode.tsx b/frontend/components/dataflow/node-editor/nodes/AggregateNode.tsx new file mode 100644 index 00000000..51ed5371 --- /dev/null +++ b/frontend/components/dataflow/node-editor/nodes/AggregateNode.tsx @@ -0,0 +1,107 @@ +"use client"; + +/** + * 집계 노드 (Aggregate Node) + * SUM, COUNT, AVG, MIN, MAX 등 집계 연산을 수행 + */ + +import { memo } from "react"; +import { Handle, Position, NodeProps } from "reactflow"; +import { Calculator, Layers } from "lucide-react"; +import type { AggregateNodeData, AggregateFunction } from "@/types/node-editor"; + +// 집계 함수별 아이콘/라벨 +const AGGREGATE_FUNCTION_LABELS: Record = { + SUM: "합계", + COUNT: "개수", + AVG: "평균", + MIN: "최소", + MAX: "최대", + FIRST: "첫번째", + LAST: "마지막", +}; + +export const AggregateNode = memo(({ data, selected }: NodeProps) => { + const groupByCount = data.groupByFields?.length || 0; + const aggregationCount = data.aggregations?.length || 0; + + return ( +
+ {/* 헤더 */} +
+ +
+
{data.displayName || "집계"}
+
+ {groupByCount > 0 ? `${groupByCount}개 그룹` : "전체"} / {aggregationCount}개 집계 +
+
+
+ + {/* 본문 */} +
+ {/* 그룹 기준 */} + {groupByCount > 0 && ( +
+
+ + 그룹 기준 +
+
+ {data.groupByFields.slice(0, 3).map((field, idx) => ( + + {field.fieldLabel || field.field} + + ))} + {data.groupByFields.length > 3 && ( + +{data.groupByFields.length - 3} + )} +
+
+ )} + + {/* 집계 연산 */} + {aggregationCount > 0 ? ( +
+ {data.aggregations.slice(0, 4).map((agg, idx) => ( +
+
+ + {AGGREGATE_FUNCTION_LABELS[agg.function] || agg.function} + + + {agg.outputFieldLabel || agg.outputField} + +
+
+ {agg.sourceFieldLabel || agg.sourceField} +
+
+ ))} + {data.aggregations.length > 4 && ( +
+ ... 외 {data.aggregations.length - 4}개 +
+ )} +
+ ) : ( +
집계 연산 없음
+ )} +
+ + {/* 핸들 */} + + +
+ ); +}); + +AggregateNode.displayName = "AggregateNode"; + diff --git a/frontend/components/dataflow/node-editor/panels/PropertiesPanel.tsx b/frontend/components/dataflow/node-editor/panels/PropertiesPanel.tsx index ada62e8d..cf7c7e6e 100644 --- a/frontend/components/dataflow/node-editor/panels/PropertiesPanel.tsx +++ b/frontend/components/dataflow/node-editor/panels/PropertiesPanel.tsx @@ -16,6 +16,7 @@ import { DeleteActionProperties } from "./properties/DeleteActionProperties"; import { ExternalDBSourceProperties } from "./properties/ExternalDBSourceProperties"; import { UpsertActionProperties } from "./properties/UpsertActionProperties"; import { DataTransformProperties } from "./properties/DataTransformProperties"; +import { AggregateProperties } from "./properties/AggregateProperties"; import { RestAPISourceProperties } from "./properties/RestAPISourceProperties"; import { CommentProperties } from "./properties/CommentProperties"; import { LogProperties } from "./properties/LogProperties"; @@ -122,6 +123,9 @@ function NodePropertiesRenderer({ node }: { node: any }) { case "dataTransform": return ; + case "aggregate": + return ; + case "restAPISource": return ; @@ -157,9 +161,11 @@ function getNodeTypeLabel(type: NodeType): string { tableSource: "테이블 소스", externalDBSource: "외부 DB 소스", restAPISource: "REST API 소스", + referenceLookup: "참조 조회", condition: "조건 분기", fieldMapping: "필드 매핑", dataTransform: "데이터 변환", + aggregate: "집계", insertAction: "INSERT 액션", updateAction: "UPDATE 액션", deleteAction: "DELETE 액션", diff --git a/frontend/components/dataflow/node-editor/panels/properties/AggregateProperties.tsx b/frontend/components/dataflow/node-editor/panels/properties/AggregateProperties.tsx new file mode 100644 index 00000000..6d3d7311 --- /dev/null +++ b/frontend/components/dataflow/node-editor/panels/properties/AggregateProperties.tsx @@ -0,0 +1,526 @@ +"use client"; + +/** + * 집계 노드 속성 편집 패널 + * SUM, COUNT, AVG, MIN, MAX 등 집계 연산 설정 + */ + +import { useEffect, useState, useCallback } from "react"; +import { Plus, Trash2, Calculator, Layers, Filter } from "lucide-react"; +import { Label } from "@/components/ui/label"; +import { Input } from "@/components/ui/input"; +import { Button } from "@/components/ui/button"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; +import { Checkbox } from "@/components/ui/checkbox"; +import { useFlowEditorStore } from "@/lib/stores/flowEditorStore"; +import type { AggregateNodeData, AggregateFunction } from "@/types/node-editor"; + +interface AggregatePropertiesProps { + nodeId: string; + data: AggregateNodeData; +} + +// 집계 함수 옵션 +const AGGREGATE_FUNCTIONS: Array<{ value: AggregateFunction; label: string; description: string }> = [ + { value: "SUM", label: "합계 (SUM)", description: "숫자 필드의 합계를 계산합니다" }, + { value: "COUNT", label: "개수 (COUNT)", description: "레코드 개수를 계산합니다" }, + { value: "AVG", label: "평균 (AVG)", description: "숫자 필드의 평균을 계산합니다" }, + { value: "MIN", label: "최소 (MIN)", description: "최소값을 찾습니다" }, + { value: "MAX", label: "최대 (MAX)", description: "최대값을 찾습니다" }, + { value: "FIRST", label: "첫번째 (FIRST)", description: "그룹의 첫 번째 값을 가져옵니다" }, + { value: "LAST", label: "마지막 (LAST)", description: "그룹의 마지막 값을 가져옵니다" }, +]; + +// 비교 연산자 옵션 +const OPERATORS = [ + { value: "=", label: "같음 (=)" }, + { value: "!=", label: "다름 (!=)" }, + { value: ">", label: "보다 큼 (>)" }, + { value: ">=", label: "크거나 같음 (>=)" }, + { value: "<", label: "보다 작음 (<)" }, + { value: "<=", label: "작거나 같음 (<=)" }, +]; + +export function AggregateProperties({ nodeId, data }: AggregatePropertiesProps) { + const { updateNode, nodes, edges } = useFlowEditorStore(); + + // 로컬 상태 + const [displayName, setDisplayName] = useState(data.displayName || "집계"); + const [groupByFields, setGroupByFields] = useState(data.groupByFields || []); + const [aggregations, setAggregations] = useState(data.aggregations || []); + const [havingConditions, setHavingConditions] = useState(data.havingConditions || []); + + // 소스 필드 목록 (연결된 입력 노드에서 가져오기) + const [sourceFields, setSourceFields] = useState>([]); + + // 데이터 변경 시 로컬 상태 업데이트 + useEffect(() => { + setDisplayName(data.displayName || "집계"); + setGroupByFields(data.groupByFields || []); + setAggregations(data.aggregations || []); + setHavingConditions(data.havingConditions || []); + }, [data]); + + // 연결된 소스 노드에서 필드 가져오기 + useEffect(() => { + const inputEdges = edges.filter((edge) => edge.target === nodeId); + const sourceNodeIds = inputEdges.map((edge) => edge.source); + const sourceNodes = nodes.filter((node) => sourceNodeIds.includes(node.id)); + + const fields: Array<{ name: string; label?: string; type?: string }> = []; + sourceNodes.forEach((node) => { + if (node.data.fields) { + node.data.fields.forEach((field: any) => { + fields.push({ + name: field.name, + label: field.label || field.displayName, + type: field.type, + }); + }); + } + }); + + setSourceFields(fields); + }, [nodeId, nodes, edges]); + + // 저장 함수 + const saveToNode = useCallback( + (updates: Partial) => { + updateNode(nodeId, { + displayName, + groupByFields, + aggregations, + havingConditions, + ...updates, + }); + }, + [nodeId, updateNode, displayName, groupByFields, aggregations, havingConditions] + ); + + // 그룹 기준 필드 토글 + const handleGroupByToggle = (fieldName: string, checked: boolean) => { + let newGroupByFields; + if (checked) { + const field = sourceFields.find((f) => f.name === fieldName); + newGroupByFields = [...groupByFields, { field: fieldName, fieldLabel: field?.label }]; + } else { + newGroupByFields = groupByFields.filter((f) => f.field !== fieldName); + } + setGroupByFields(newGroupByFields); + saveToNode({ groupByFields: newGroupByFields }); + }; + + // 집계 연산 추가 + const handleAddAggregation = () => { + const newAggregation = { + id: `agg_${Date.now()}`, + sourceField: "", + sourceFieldLabel: "", + function: "SUM" as AggregateFunction, + outputField: "", + outputFieldLabel: "", + }; + const newAggregations = [...aggregations, newAggregation]; + setAggregations(newAggregations); + saveToNode({ aggregations: newAggregations }); + }; + + // 집계 연산 삭제 + const handleRemoveAggregation = (index: number) => { + const newAggregations = aggregations.filter((_, i) => i !== index); + setAggregations(newAggregations); + saveToNode({ aggregations: newAggregations }); + }; + + // 집계 연산 변경 + const handleAggregationChange = (index: number, field: string, value: any) => { + const newAggregations = [...aggregations]; + + if (field === "sourceField") { + const sourceField = sourceFields.find((f) => f.name === value); + newAggregations[index] = { + ...newAggregations[index], + sourceField: value, + sourceFieldLabel: sourceField?.label, + // 출력 필드명 자동 생성 (예: sum_amount) + outputField: + newAggregations[index].outputField || + `${newAggregations[index].function.toLowerCase()}_${value}`, + }; + } else if (field === "function") { + newAggregations[index] = { + ...newAggregations[index], + function: value, + // 출력 필드명 업데이트 + outputField: newAggregations[index].sourceField + ? `${value.toLowerCase()}_${newAggregations[index].sourceField}` + : newAggregations[index].outputField, + }; + } else { + newAggregations[index] = { ...newAggregations[index], [field]: value }; + } + + setAggregations(newAggregations); + saveToNode({ aggregations: newAggregations }); + }; + + // HAVING 조건 추가 + const handleAddHavingCondition = () => { + const newCondition = { + field: "", + operator: "=", + value: "", + }; + const newConditions = [...havingConditions, newCondition]; + setHavingConditions(newConditions); + saveToNode({ havingConditions: newConditions }); + }; + + // HAVING 조건 삭제 + const handleRemoveHavingCondition = (index: number) => { + const newConditions = havingConditions.filter((_, i) => i !== index); + setHavingConditions(newConditions); + saveToNode({ havingConditions: newConditions }); + }; + + // HAVING 조건 변경 + const handleHavingConditionChange = (index: number, field: string, value: any) => { + const newConditions = [...havingConditions]; + newConditions[index] = { ...newConditions[index], [field]: value }; + setHavingConditions(newConditions); + saveToNode({ havingConditions: newConditions }); + }; + + // 집계 결과 필드 목록 (HAVING 조건에서 선택용) + const aggregatedFields = aggregations + .filter((agg) => agg.outputField) + .map((agg) => ({ + name: agg.outputField, + label: agg.outputFieldLabel || agg.outputField, + })); + + return ( +
+
+ {/* 헤더 */} +
+ + 집계 노드 +
+ + {/* 기본 정보 */} +
+

기본 정보

+
+ + { + setDisplayName(e.target.value); + saveToNode({ displayName: e.target.value }); + }} + className="mt-1" + placeholder="노드 표시 이름" + /> +
+
+ + {/* 그룹 기준 필드 */} +
+
+ +

그룹 기준 필드

+
+

+ 선택한 필드를 기준으로 데이터를 그룹화합니다. 선택하지 않으면 전체 데이터를 하나의 그룹으로 처리합니다. +

+ + {sourceFields.length === 0 ? ( +
+ 연결된 소스 노드가 없습니다 +
+ ) : ( +
+
+ {sourceFields.map((field) => { + const isChecked = groupByFields.some((f) => f.field === field.name); + return ( +
+ handleGroupByToggle(field.name, checked as boolean)} + /> + +
+ ); + })} +
+
+ )} + + {groupByFields.length > 0 && ( +
+ {groupByFields.map((field) => ( + + {field.fieldLabel || field.field} + + ))} +
+ )} +
+ + {/* 집계 연산 */} +
+
+
+ +

집계 연산

+
+ +
+

SUM, COUNT, AVG 등 집계 연산을 설정합니다.

+ + {aggregations.length === 0 ? ( +
+ 집계 연산을 추가하세요 +
+ ) : ( +
+ {aggregations.map((agg, index) => ( +
+
+ 집계 #{index + 1} + +
+ +
+ {/* 집계 함수 선택 */} +
+ + +
+ + {/* 소스 필드 선택 */} +
+ + +
+ + {/* 출력 필드명 */} +
+ + handleAggregationChange(index, "outputField", e.target.value)} + placeholder="예: total_amount" + className="mt-1 h-8 text-xs" + /> +

+ 집계 결과가 저장될 필드명입니다 +

+
+ + {/* 출력 필드 라벨 */} +
+ + handleAggregationChange(index, "outputFieldLabel", e.target.value)} + placeholder="예: 총 금액" + className="mt-1 h-8 text-xs" + /> +
+
+
+ ))} +
+ )} +
+ + {/* HAVING 조건 (선택) */} +
+
+
+ +

집계 후 필터 (HAVING)

+
+ +
+

집계 결과에 대한 필터링 조건을 설정합니다 (선택 사항).

+ + {havingConditions.length === 0 ? ( +
+ 집계 후 필터링이 필요하면 조건을 추가하세요 +
+ ) : ( +
+ {havingConditions.map((condition, index) => ( +
+ {/* 집계 결과 필드 선택 */} + + + {/* 연산자 선택 */} + + + {/* 비교값 */} + handleHavingConditionChange(index, "value", e.target.value)} + placeholder="값" + className="h-8 flex-1 text-xs" + /> + + {/* 삭제 버튼 */} + +
+ ))} +
+ )} +
+ + {/* 미리보기 */} + {(groupByFields.length > 0 || aggregations.length > 0) && ( +
+

집계 결과 미리보기

+
+
+ 그룹 기준:{" "} + {groupByFields.length > 0 + ? groupByFields.map((f) => f.fieldLabel || f.field).join(", ") + : "전체 (그룹 없음)"} +
+
+ 집계 컬럼:{" "} + {aggregations.length > 0 + ? aggregations + .filter((a) => a.outputField) + .map((a) => `${a.function}(${a.sourceFieldLabel || a.sourceField}) → ${a.outputFieldLabel || a.outputField}`) + .join(", ") + : "없음"} +
+
+
+ )} +
+
+ ); +} + diff --git a/frontend/components/dataflow/node-editor/panels/properties/InsertActionProperties.tsx b/frontend/components/dataflow/node-editor/panels/properties/InsertActionProperties.tsx index 5f3b3220..465a88fd 100644 --- a/frontend/components/dataflow/node-editor/panels/properties/InsertActionProperties.tsx +++ b/frontend/components/dataflow/node-editor/panels/properties/InsertActionProperties.tsx @@ -236,7 +236,48 @@ export function InsertActionProperties({ nodeId, data }: InsertActionPropertiesP console.log("⚠️ REST API 노드에 responseFields 없음"); } } - // 3️⃣ 테이블/외부DB 소스 노드 + // 3️⃣ 집계(Aggregate) 노드: 그룹 필드 + 집계 결과 필드 + else if (node.type === "aggregate") { + console.log("✅ 집계 노드 발견"); + const nodeData = node.data as any; + + // 그룹 기준 필드 추가 (field 또는 fieldName 둘 다 지원) + if (nodeData.groupByFields && Array.isArray(nodeData.groupByFields)) { + console.log(` 📊 ${nodeData.groupByFields.length}개 그룹 필드 발견`); + nodeData.groupByFields.forEach((groupField: any) => { + const fieldName = groupField.field || groupField.fieldName; + if (fieldName) { + fields.push({ + name: fieldName, + label: groupField.fieldLabel || fieldName, + sourcePath: currentPath, + }); + } + }); + } + + // 집계 결과 필드 추가 (aggregations 또는 aggregateFunctions 둘 다 지원) + const aggregations = nodeData.aggregations || nodeData.aggregateFunctions || []; + if (Array.isArray(aggregations)) { + console.log(` 📊 ${aggregations.length}개 집계 함수 발견`); + aggregations.forEach((aggFunc: any) => { + // outputField 또는 targetField 둘 다 지원 + const outputFieldName = aggFunc.outputField || aggFunc.targetField; + // function 또는 aggregateType 둘 다 지원 + const funcType = aggFunc.function || aggFunc.aggregateType; + if (outputFieldName) { + fields.push({ + name: outputFieldName, + label: aggFunc.outputFieldLabel || aggFunc.targetFieldLabel || `${funcType}(${aggFunc.sourceFieldLabel || aggFunc.sourceField})`, + sourcePath: currentPath, + }); + } + }); + } + + // 집계 노드는 상위 노드의 필드를 그대로 통과시키지 않음 (집계된 결과만 전달) + } + // 4️⃣ 테이블/외부DB 소스 노드 else if (node.type === "tableSource" || node.type === "externalDBSource") { const nodeFields = (node.data as any).fields || (node.data as any).outputFields; const displayName = (node.data as any).displayName || (node.data as any).tableName || node.id; @@ -266,7 +307,7 @@ export function InsertActionProperties({ nodeId, data }: InsertActionPropertiesP foundRestAPI = foundRestAPI || upperResult.hasRestAPI; } } - // 4️⃣ 통과 노드 (조건, 기타 모든 노드): 상위 노드로 계속 탐색 + // 5️⃣ 통과 노드 (조건, 기타 모든 노드): 상위 노드로 계속 탐색 else { console.log(`✅ 통과 노드 (${node.type}) → 상위 노드로 계속 탐색`); const upperResult = getAllSourceFields(node.id, visitedNodes, currentPath); diff --git a/frontend/components/dataflow/node-editor/panels/properties/UpdateActionProperties.tsx b/frontend/components/dataflow/node-editor/panels/properties/UpdateActionProperties.tsx index 7d6d2e5a..6d109d5b 100644 --- a/frontend/components/dataflow/node-editor/panels/properties/UpdateActionProperties.tsx +++ b/frontend/components/dataflow/node-editor/panels/properties/UpdateActionProperties.tsx @@ -212,7 +212,43 @@ export function UpdateActionProperties({ nodeId, data }: UpdateActionPropertiesP fields.push(...upperFields); } } - // 2️⃣ REST API 소스 노드 + // 2️⃣ 집계(Aggregate) 노드: 그룹 필드 + 집계 결과 필드 + else if (node.type === "aggregate") { + const nodeData = node.data as any; + + // 그룹 기준 필드 추가 (field 또는 fieldName 둘 다 지원) + if (nodeData.groupByFields && Array.isArray(nodeData.groupByFields)) { + nodeData.groupByFields.forEach((groupField: any) => { + const fieldName = groupField.field || groupField.fieldName; + if (fieldName) { + fields.push({ + name: fieldName, + label: groupField.fieldLabel || fieldName, + }); + } + }); + } + + // 집계 결과 필드 추가 (aggregations 또는 aggregateFunctions 둘 다 지원) + const aggregations = nodeData.aggregations || nodeData.aggregateFunctions || []; + if (Array.isArray(aggregations)) { + aggregations.forEach((aggFunc: any) => { + // outputField 또는 targetField 둘 다 지원 + const outputFieldName = aggFunc.outputField || aggFunc.targetField; + // function 또는 aggregateType 둘 다 지원 + const funcType = aggFunc.function || aggFunc.aggregateType; + if (outputFieldName) { + fields.push({ + name: outputFieldName, + label: aggFunc.outputFieldLabel || aggFunc.targetFieldLabel || `${funcType}(${aggFunc.sourceFieldLabel || aggFunc.sourceField})`, + }); + } + }); + } + + // 집계 노드는 상위 노드의 필드를 그대로 통과시키지 않음 (집계된 결과만 전달) + } + // 3️⃣ REST API 소스 노드 else if (node.type === "restAPISource") { foundRestAPI = true; const responseFields = (node.data as any).responseFields; @@ -229,7 +265,7 @@ export function UpdateActionProperties({ nodeId, data }: UpdateActionPropertiesP }); } } - // 3️⃣ 테이블/외부DB 소스 노드 + // 4️⃣ 테이블/외부DB 소스 노드 else if (node.type === "tableSource" || node.type === "externalDBSource") { const nodeFields = (node.data as any).fields || (node.data as any).outputFields; @@ -251,7 +287,7 @@ export function UpdateActionProperties({ nodeId, data }: UpdateActionPropertiesP foundRestAPI = foundRestAPI || upperResult.hasRestAPI; } } - // 4️⃣ 통과 노드 (조건, 기타 모든 노드): 상위 노드로 계속 탐색 + // 5️⃣ 통과 노드 (조건, 기타 모든 노드): 상위 노드로 계속 탐색 else { const upperResult = getAllSourceFields(node.id, visitedNodes); fields.push(...upperResult.fields); diff --git a/frontend/components/dataflow/node-editor/panels/properties/UpsertActionProperties.tsx b/frontend/components/dataflow/node-editor/panels/properties/UpsertActionProperties.tsx index 50a53603..57d5d4f2 100644 --- a/frontend/components/dataflow/node-editor/panels/properties/UpsertActionProperties.tsx +++ b/frontend/components/dataflow/node-editor/panels/properties/UpsertActionProperties.tsx @@ -212,7 +212,43 @@ export function UpsertActionProperties({ nodeId, data }: UpsertActionPropertiesP }); } } - // 3️⃣ 테이블/외부DB 소스 노드 + // 3️⃣ 집계(Aggregate) 노드: 그룹 필드 + 집계 결과 필드 + else if (node.type === "aggregate") { + const nodeData = node.data as any; + + // 그룹 기준 필드 추가 (field 또는 fieldName 둘 다 지원) + if (nodeData.groupByFields && Array.isArray(nodeData.groupByFields)) { + nodeData.groupByFields.forEach((groupField: any) => { + const fieldName = groupField.field || groupField.fieldName; + if (fieldName) { + fields.push({ + name: fieldName, + label: groupField.fieldLabel || fieldName, + }); + } + }); + } + + // 집계 결과 필드 추가 (aggregations 또는 aggregateFunctions 둘 다 지원) + const aggregations = nodeData.aggregations || nodeData.aggregateFunctions || []; + if (Array.isArray(aggregations)) { + aggregations.forEach((aggFunc: any) => { + // outputField 또는 targetField 둘 다 지원 + const outputFieldName = aggFunc.outputField || aggFunc.targetField; + // function 또는 aggregateType 둘 다 지원 + const funcType = aggFunc.function || aggFunc.aggregateType; + if (outputFieldName) { + fields.push({ + name: outputFieldName, + label: aggFunc.outputFieldLabel || aggFunc.targetFieldLabel || `${funcType}(${aggFunc.sourceFieldLabel || aggFunc.sourceField})`, + }); + } + }); + } + + // 집계 노드는 상위 노드의 필드를 그대로 통과시키지 않음 (집계된 결과만 전달) + } + // 4️⃣ 테이블/외부DB 소스 노드 else if (node.type === "tableSource" || node.type === "externalDBSource") { const nodeFields = (node.data as any).fields || (node.data as any).outputFields; @@ -234,7 +270,7 @@ export function UpsertActionProperties({ nodeId, data }: UpsertActionPropertiesP foundRestAPI = foundRestAPI || upperResult.hasRestAPI; } } - // 4️⃣ 통과 노드 (조건, 기타 모든 노드): 상위 노드로 계속 탐색 + // 5️⃣ 통과 노드 (조건, 기타 모든 노드): 상위 노드로 계속 탐색 else { const upperResult = getAllSourceFields(node.id, visitedNodes); fields.push(...upperResult.fields); diff --git a/frontend/components/dataflow/node-editor/sidebar/nodePaletteConfig.ts b/frontend/components/dataflow/node-editor/sidebar/nodePaletteConfig.ts index 97a5b19e..2ff31689 100644 --- a/frontend/components/dataflow/node-editor/sidebar/nodePaletteConfig.ts +++ b/frontend/components/dataflow/node-editor/sidebar/nodePaletteConfig.ts @@ -60,6 +60,14 @@ export const NODE_PALETTE: NodePaletteItem[] = [ category: "transform", color: "#06B6D4", // 청록색 }, + { + type: "aggregate", + label: "집계", + icon: "", + description: "SUM, COUNT, AVG 등 집계 연산을 수행합니다", + category: "transform", + color: "#A855F7", // 보라색 + }, // ======================================================================== // 액션 diff --git a/frontend/types/node-editor.ts b/frontend/types/node-editor.ts index 8959a691..fc5adb89 100644 --- a/frontend/types/node-editor.ts +++ b/frontend/types/node-editor.ts @@ -15,6 +15,7 @@ export type NodeType = | "referenceLookup" // 참조 테이블 조회 (내부 DB 전용) | "condition" // 조건 분기 | "dataTransform" // 데이터 변환 + | "aggregate" // 집계 노드 (SUM, COUNT, AVG 등) | "insertAction" // INSERT 액션 | "updateAction" // UPDATE 액션 | "deleteAction" // DELETE 액션 @@ -194,6 +195,34 @@ export interface DataTransformNodeData { displayName?: string; } +// 집계 함수 타입 +export type AggregateFunction = "SUM" | "COUNT" | "AVG" | "MIN" | "MAX" | "FIRST" | "LAST"; + +// 집계 노드 데이터 +export interface AggregateNodeData { + displayName?: string; + // 그룹 기준 컬럼들 + groupByFields: Array<{ + field: string; // 컬럼명 + fieldLabel?: string; // 라벨 + }>; + // 집계 연산들 + aggregations: Array<{ + id: string; // 고유 ID + sourceField: string; // 집계할 소스 필드 + sourceFieldLabel?: string; // 소스 필드 라벨 + function: AggregateFunction; // 집계 함수 + outputField: string; // 출력 필드명 + outputFieldLabel?: string; // 출력 필드 라벨 + }>; + // 집계 후 필터링 (HAVING 절) + havingConditions?: Array<{ + field: string; // 집계 결과 필드 + operator: string; // 비교 연산자 + value: any; // 비교값 + }>; +} + // INSERT 액션 노드 export interface InsertActionNodeData { displayName?: string; @@ -406,6 +435,7 @@ export type NodeData = | ConditionNodeData | FieldMappingNodeData | DataTransformNodeData + | AggregateNodeData | InsertActionNodeData | UpdateActionNodeData | DeleteActionNodeData From 47552bc35c61323fa1a87e761b3aaedf43685b3a Mon Sep 17 00:00:00 2001 From: kjs Date: Fri, 5 Dec 2025 17:28:44 +0900 Subject: [PATCH 05/18] =?UTF-8?q?=EC=A7=91=EA=B3=84=ED=95=A8=EC=88=98=20?= =?UTF-8?q?=EC=A0=9C=EC=96=B4=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/services/dynamicFormService.ts | 18 ++++ .../src/services/nodeFlowExecutionService.ts | 101 +++++++++++------- .../components/webtypes/RepeaterInput.tsx | 14 ++- .../RepeaterFieldGroupRenderer.tsx | 28 +++-- 4 files changed, 110 insertions(+), 51 deletions(-) diff --git a/backend-node/src/services/dynamicFormService.ts b/backend-node/src/services/dynamicFormService.ts index 04586d65..d52c184f 100644 --- a/backend-node/src/services/dynamicFormService.ts +++ b/backend-node/src/services/dynamicFormService.ts @@ -506,6 +506,24 @@ export class DynamicFormService { // 헤더 + 품목을 병합 const rawMergedData = { ...dataToInsert, ...item }; + // 🆕 새 레코드 저장 시 id 제거하여 새 UUID 생성되도록 함 + // _existingRecord가 명시적으로 true인 경우에만 기존 레코드로 처리 (UPDATE) + // 그 외의 경우는 모두 새 레코드로 처리 (INSERT) + const isExistingRecord = rawMergedData._existingRecord === true; + + if (!isExistingRecord) { + // 새 레코드: id 제거하여 새 UUID 자동 생성 + const oldId = rawMergedData.id; + delete rawMergedData.id; + console.log(`🆕 새 레코드로 처리 (id 제거됨: ${oldId})`); + } else { + console.log(`📝 기존 레코드 수정 (id 유지: ${rawMergedData.id})`); + } + + // 메타 플래그 제거 + delete rawMergedData._isNewItem; + delete rawMergedData._existingRecord; + // 🆕 실제 테이블 컬럼만 필터링 (조인/계산 컬럼 제외) const validColumnNames = columnInfo.map((col) => col.column_name); const mergedData: Record = {}; diff --git a/backend-node/src/services/nodeFlowExecutionService.ts b/backend-node/src/services/nodeFlowExecutionService.ts index e70a1dae..7b5f6918 100644 --- a/backend-node/src/services/nodeFlowExecutionService.ts +++ b/backend-node/src/services/nodeFlowExecutionService.ts @@ -833,11 +833,18 @@ export class NodeFlowExecutionService { const sql = `SELECT * FROM ${schemaPrefix}${tableName} ${whereResult.clause}`; + logger.info(`📊 테이블 전체 데이터 조회 SQL: ${sql}`); + const result = await query(sql, whereResult.values); logger.info( `📊 테이블 전체 데이터 조회: ${tableName}, ${result.length}건` ); + + // 디버깅: 조회된 데이터 샘플 출력 + if (result.length > 0) { + logger.info(`📊 조회된 데이터 샘플: ${JSON.stringify(result[0])?.substring(0, 300)}`); + } return result; } @@ -1358,57 +1365,64 @@ export class NodeFlowExecutionService { let updatedCount = 0; const updatedDataArray: any[] = []; - // 🆕 table-all 모드: 단일 SQL로 일괄 업데이트 + // 🆕 table-all 모드: 각 그룹별로 UPDATE 실행 (집계 결과 반영) if (context.currentNodeDataSourceType === "table-all") { - console.log("🚀 table-all 모드: 단일 SQL로 일괄 업데이트 시작"); + console.log("🚀 table-all 모드: 그룹별 업데이트 시작 (총 " + dataArray.length + "개 그룹)"); - // 첫 번째 데이터를 참조하여 SET 절 생성 - const firstData = dataArray[0]; - const setClauses: string[] = []; - const values: any[] = []; - let paramIndex = 1; + // 🔥 각 그룹(데이터)별로 UPDATE 실행 + for (let i = 0; i < dataArray.length; i++) { + const data = dataArray[i]; + const setClauses: string[] = []; + const values: any[] = []; + let paramIndex = 1; - console.log("🗺️ 필드 매핑 처리 중..."); - fieldMappings.forEach((mapping: any) => { - const value = - mapping.staticValue !== undefined - ? mapping.staticValue - : firstData[mapping.sourceField]; + console.log(`\n📦 그룹 ${i + 1}/${dataArray.length} 처리 중...`); + console.log("🗺️ 필드 매핑 처리 중..."); + + fieldMappings.forEach((mapping: any) => { + const value = + mapping.staticValue !== undefined + ? mapping.staticValue + : data[mapping.sourceField]; - console.log( - ` ${mapping.sourceField} → ${mapping.targetField}: ${value === undefined ? "❌ undefined" : "✅ " + value}` + console.log( + ` ${mapping.sourceField} → ${mapping.targetField}: ${value === undefined ? "❌ undefined" : "✅ " + value}` + ); + + if (mapping.targetField) { + setClauses.push(`${mapping.targetField} = $${paramIndex}`); + values.push(value); + paramIndex++; + } + }); + + // WHERE 조건 (사용자 정의 조건만 사용, PK 자동 추가 안 함) + const whereResult = this.buildWhereClause( + whereConditions, + data, + paramIndex ); - if (mapping.targetField) { - setClauses.push(`${mapping.targetField} = $${paramIndex}`); - values.push(value); - paramIndex++; - } - }); + values.push(...whereResult.values); - // WHERE 조건 (사용자 정의 조건만 사용, PK 자동 추가 안 함) - const whereResult = this.buildWhereClause( - whereConditions, - firstData, - paramIndex - ); + const sql = ` + UPDATE ${targetTable} + SET ${setClauses.join(", ")} + ${whereResult.clause} + `; - values.push(...whereResult.values); + console.log("📝 실행할 SQL:", sql); + console.log("📊 바인딩 값:", values); - const sql = ` - UPDATE ${targetTable} - SET ${setClauses.join(", ")} - ${whereResult.clause} - `; - - console.log("📝 실행할 SQL (일괄 처리):", sql); - console.log("📊 바인딩 값:", values); - - const result = await txClient.query(sql, values); - updatedCount = result.rowCount || 0; + const result = await txClient.query(sql, values); + const rowCount = result.rowCount || 0; + updatedCount += rowCount; + + console.log(`✅ 그룹 ${i + 1} UPDATE 완료: ${rowCount}건`); + } logger.info( - `✅ UPDATE 완료 (내부 DB, 일괄 처리): ${targetTable}, ${updatedCount}건` + `✅ UPDATE 완료 (내부 DB, 그룹별 처리): ${targetTable}, 총 ${updatedCount}건` ); // 업데이트된 데이터는 원본 배열 반환 (실제 DB에서 다시 조회하지 않음) @@ -3216,10 +3230,12 @@ export class NodeFlowExecutionService { // 입력 데이터가 없으면 빈 배열 반환 if (!inputData || !Array.isArray(inputData) || inputData.length === 0) { logger.warn("⚠️ 집계할 입력 데이터가 없습니다."); + logger.warn(`⚠️ inputData 타입: ${typeof inputData}, 값: ${JSON.stringify(inputData)?.substring(0, 200)}`); return []; } logger.info(`📥 입력 데이터: ${inputData.length}건`); + logger.info(`📥 입력 데이터 샘플: ${JSON.stringify(inputData[0])?.substring(0, 300)}`); logger.info(`📊 그룹 기준: ${groupByFields.length > 0 ? groupByFields.map((f: any) => f.field).join(", ") : "전체"}`); logger.info(`📊 집계 연산: ${aggregations.length}개`); @@ -3239,6 +3255,11 @@ export class NodeFlowExecutionService { } logger.info(`📊 그룹 수: ${groups.size}개`); + + // 디버깅: 각 그룹의 데이터 출력 + for (const [groupKey, groupRows] of groups) { + logger.info(`📊 그룹 [${groupKey}]: ${groupRows.length}건, inbound_qty 합계: ${groupRows.reduce((sum, row) => sum + parseFloat(row.inbound_qty || 0), 0)}`); + } // 각 그룹에 대해 집계 수행 const results: any[] = []; diff --git a/frontend/components/webtypes/RepeaterInput.tsx b/frontend/components/webtypes/RepeaterInput.tsx index ce9d4cf6..3116b2c6 100644 --- a/frontend/components/webtypes/RepeaterInput.tsx +++ b/frontend/components/webtypes/RepeaterInput.tsx @@ -91,6 +91,8 @@ export const RepeaterInput: React.FC = ({ fields.forEach((field) => { item[field.name] = ""; }); + // 🆕 새 항목임을 표시하는 플래그 추가 (백엔드에서 새 레코드로 처리) + item._isNewItem = true; return item; } @@ -113,6 +115,11 @@ export const RepeaterInput: React.FC = ({ } }); + // 🆕 기존 레코드임을 표시 (id가 있는 경우) + if (updatedItem.id) { + updatedItem._existingRecord = true; + } + return hasChange ? updatedItem : item; }); @@ -125,7 +132,12 @@ export const RepeaterInput: React.FC = ({ : updatedValue; onChange?.(dataWithMeta); } else { - setItems(value); + // 🆕 기존 레코드 플래그 추가 + const valueWithFlag = value.map(item => ({ + ...item, + _existingRecord: !!item.id, + })); + setItems(valueWithFlag); } } }, [value]); diff --git a/frontend/lib/registry/components/repeater-field-group/RepeaterFieldGroupRenderer.tsx b/frontend/lib/registry/components/repeater-field-group/RepeaterFieldGroupRenderer.tsx index c47ff3c9..12219280 100644 --- a/frontend/lib/registry/components/repeater-field-group/RepeaterFieldGroupRenderer.tsx +++ b/frontend/lib/registry/components/repeater-field-group/RepeaterFieldGroupRenderer.tsx @@ -135,6 +135,7 @@ const RepeaterFieldGroupComponent: React.FC = (props) => ...item, _targetTable: targetTable, _originalItemIds: itemIds, // 🆕 원본 ID 목록도 함께 전달 + _existingRecord: !!item.id, // 🆕 기존 레코드 플래그 (id가 있으면 기존 레코드) })); onChange(dataWithMeta); } @@ -228,17 +229,23 @@ const RepeaterFieldGroupComponent: React.FC = (props) => // 반복 필드 그룹에 정의된 필드 + 시스템 필드만 유지 const definedFields = configRef.current.fields || []; const definedFieldNames = new Set(definedFields.map((f: any) => f.name)); - // 시스템 필드 및 필수 필드 추가 - const systemFields = new Set(['id', '_targetTable', 'created_date', 'updated_date', 'writer', 'company_code']); + // 시스템 필드 및 필수 필드 추가 (id는 제외 - 새 레코드로 처리하기 위해) + const systemFields = new Set(['_targetTable', '_isNewItem', 'created_date', 'updated_date', 'writer', 'company_code']); const filteredData = normalizedData.map((item: any) => { const filteredItem: Record = {}; Object.keys(item).forEach(key => { + // 🆕 id 필드는 제외 (새 레코드로 저장되도록) + if (key === 'id') { + return; // id 필드 제외 + } // 정의된 필드이거나 시스템 필드인 경우만 포함 if (definedFieldNames.has(key) || systemFields.has(key)) { filteredItem[key] = item[key]; } }); + // 🆕 새 항목임을 표시하는 플래그 추가 + filteredItem._isNewItem = true; return filteredItem; }); @@ -259,16 +266,16 @@ const RepeaterFieldGroupComponent: React.FC = (props) => newItems = filteredData; addedCount = filteredData.length; } else { - // 🆕 중복 체크: id 또는 고유 식별자를 기준으로 이미 존재하는 항목 제외 - const existingIds = new Set( + // 🆕 중복 체크: item_code를 기준으로 이미 존재하는 항목 제외 (id는 사용하지 않음) + const existingItemCodes = new Set( currentValue - .map((item: any) => item.id || item.po_item_id || item.item_id) + .map((item: any) => item.item_code) .filter(Boolean) ); const uniqueNewItems = filteredData.filter((item: any) => { - const itemId = item.id || item.po_item_id || item.item_id; - if (itemId && existingIds.has(itemId)) { + const itemCode = item.item_code; + if (itemCode && existingItemCodes.has(itemCode)) { duplicateCount++; return false; // 중복 항목 제외 } @@ -291,11 +298,12 @@ const RepeaterFieldGroupComponent: React.FC = (props) => setGroupedData(newItems); // 🆕 SplitPanelContext에 추가된 항목 ID 등록 (좌측 테이블 필터링용) + // item_code를 기준으로 등록 (id는 새 레코드라 없을 수 있음) if (splitPanelContext?.addItemIds && addedCount > 0) { - const newItemIds = newItems - .map((item: any) => String(item.id || item.po_item_id || item.item_id)) + const newItemCodes = newItems + .map((item: any) => String(item.item_code)) .filter(Boolean); - splitPanelContext.addItemIds(newItemIds); + splitPanelContext.addItemIds(newItemCodes); } // JSON 문자열로 변환하여 저장 From cbe5cb4607f4863bb71f6cce7ae92a7c6180233e Mon Sep 17 00:00:00 2001 From: kjs Date: Fri, 5 Dec 2025 17:46:22 +0900 Subject: [PATCH 06/18] =?UTF-8?q?=ED=86=A0=ED=81=B0=20=EC=9E=90=EB=8F=99?= =?UTF-8?q?=20=EA=B0=B1=EC=8B=A0=20=EA=B8=B0=EB=8A=A5=20=EC=B6=94=EA=B0=80?= =?UTF-8?q?=20=EB=B0=8F=20=EC=97=90=EB=9F=AC=20=EC=B2=98=EB=A6=AC=20?= =?UTF-8?q?=EA=B0=9C=EC=84=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend-node/src/app.ts | 5 + backend-node/src/middleware/authMiddleware.ts | 13 +- frontend/lib/api/client.ts | 201 ++++++++++++++++-- 3 files changed, 199 insertions(+), 20 deletions(-) diff --git a/backend-node/src/app.ts b/backend-node/src/app.ts index d214c19a..d36ad8c3 100644 --- a/backend-node/src/app.ts +++ b/backend-node/src/app.ts @@ -8,6 +8,7 @@ import path from "path"; import config from "./config/environment"; import { logger } from "./utils/logger"; import { errorHandler } from "./middleware/errorHandler"; +import { refreshTokenIfNeeded } from "./middleware/authMiddleware"; // 라우터 임포트 import authRoutes from "./routes/authRoutes"; @@ -168,6 +169,10 @@ const limiter = rateLimit({ }); app.use("/api/", limiter); +// 토큰 자동 갱신 미들웨어 (모든 API 요청에 적용) +// 토큰이 1시간 이내에 만료되는 경우 자동으로 갱신하여 응답 헤더에 포함 +app.use("/api/", refreshTokenIfNeeded); + // 헬스 체크 엔드포인트 app.get("/health", (req, res) => { res.status(200).json({ diff --git a/backend-node/src/middleware/authMiddleware.ts b/backend-node/src/middleware/authMiddleware.ts index a54c64c6..6d8c7bda 100644 --- a/backend-node/src/middleware/authMiddleware.ts +++ b/backend-node/src/middleware/authMiddleware.ts @@ -54,16 +54,17 @@ export const authenticateToken = ( next(); } catch (error) { - logger.error( - `인증 실패: ${error instanceof Error ? error.message : "Unknown error"} (${req.ip})` - ); + const errorMessage = error instanceof Error ? error.message : "Unknown error"; + logger.error(`인증 실패: ${errorMessage} (${req.ip})`); + // 토큰 만료 에러인지 확인 + const isTokenExpired = errorMessage.includes("만료"); + res.status(401).json({ success: false, error: { - code: "INVALID_TOKEN", - details: - error instanceof Error ? error.message : "토큰 검증에 실패했습니다.", + code: isTokenExpired ? "TOKEN_EXPIRED" : "INVALID_TOKEN", + details: errorMessage || "토큰 검증에 실패했습니다.", }, }); } diff --git a/frontend/lib/api/client.ts b/frontend/lib/api/client.ts index 7dc811c9..f4a3ccf7 100644 --- a/frontend/lib/api/client.ts +++ b/frontend/lib/api/client.ts @@ -58,6 +58,18 @@ const TokenManager = { return null; }, + setToken: (token: string): void => { + if (typeof window !== "undefined") { + localStorage.setItem("authToken", token); + } + }, + + removeToken: (): void => { + if (typeof window !== "undefined") { + localStorage.removeItem("authToken"); + } + }, + isTokenExpired: (token: string): boolean => { try { const payload = JSON.parse(atob(token.split(".")[1])); @@ -66,8 +78,147 @@ const TokenManager = { return true; } }, + + // 토큰이 곧 만료되는지 확인 (30분 이내) + isTokenExpiringSoon: (token: string): boolean => { + try { + const payload = JSON.parse(atob(token.split(".")[1])); + const expiryTime = payload.exp * 1000; + const currentTime = Date.now(); + const thirtyMinutes = 30 * 60 * 1000; // 30분 + return expiryTime - currentTime < thirtyMinutes && expiryTime > currentTime; + } catch { + return false; + } + }, + + // 토큰 만료까지 남은 시간 (밀리초) + getTimeUntilExpiry: (token: string): number => { + try { + const payload = JSON.parse(atob(token.split(".")[1])); + return payload.exp * 1000 - Date.now(); + } catch { + return 0; + } + }, }; +// 토큰 갱신 중복 방지 플래그 +let isRefreshing = false; +let refreshPromise: Promise | null = null; + +// 토큰 갱신 함수 +const refreshToken = async (): Promise => { + // 이미 갱신 중이면 기존 Promise 반환 + if (isRefreshing && refreshPromise) { + return refreshPromise; + } + + isRefreshing = true; + refreshPromise = (async () => { + try { + const currentToken = TokenManager.getToken(); + if (!currentToken) { + return null; + } + + const response = await axios.post( + `${API_BASE_URL}/auth/refresh`, + {}, + { + headers: { + Authorization: `Bearer ${currentToken}`, + }, + } + ); + + if (response.data?.success && response.data?.data?.token) { + const newToken = response.data.data.token; + TokenManager.setToken(newToken); + console.log("[TokenManager] 토큰 갱신 성공"); + return newToken; + } + return null; + } catch (error) { + console.error("[TokenManager] 토큰 갱신 실패:", error); + return null; + } finally { + isRefreshing = false; + refreshPromise = null; + } + })(); + + return refreshPromise; +}; + +// 자동 토큰 갱신 타이머 +let tokenRefreshTimer: NodeJS.Timeout | null = null; + +// 자동 토큰 갱신 시작 +const startAutoRefresh = (): void => { + if (typeof window === "undefined") return; + + // 기존 타이머 정리 + if (tokenRefreshTimer) { + clearInterval(tokenRefreshTimer); + } + + // 10분마다 토큰 상태 확인 + tokenRefreshTimer = setInterval(async () => { + const token = TokenManager.getToken(); + if (token && TokenManager.isTokenExpiringSoon(token)) { + console.log("[TokenManager] 토큰 만료 임박, 자동 갱신 시작..."); + await refreshToken(); + } + }, 10 * 60 * 1000); // 10분 + + // 페이지 로드 시 즉시 확인 + const token = TokenManager.getToken(); + if (token && TokenManager.isTokenExpiringSoon(token)) { + refreshToken(); + } +}; + +// 사용자 활동 감지 및 토큰 갱신 +const setupActivityBasedRefresh = (): void => { + if (typeof window === "undefined") return; + + let lastActivity = Date.now(); + const activityThreshold = 5 * 60 * 1000; // 5분 + + const handleActivity = (): void => { + const now = Date.now(); + // 마지막 활동으로부터 5분 이상 지났으면 토큰 상태 확인 + if (now - lastActivity > activityThreshold) { + const token = TokenManager.getToken(); + if (token && TokenManager.isTokenExpiringSoon(token)) { + refreshToken(); + } + } + lastActivity = now; + }; + + // 사용자 활동 이벤트 감지 + ["click", "keydown", "scroll", "mousemove"].forEach((event) => { + // 너무 잦은 호출 방지를 위해 throttle 적용 + let throttleTimer: NodeJS.Timeout | null = null; + window.addEventListener(event, () => { + if (!throttleTimer) { + throttleTimer = setTimeout(() => { + handleActivity(); + throttleTimer = null; + }, 1000); // 1초 throttle + } + }, { passive: true }); + }); +}; + +// 클라이언트 사이드에서 자동 갱신 시작 +if (typeof window !== "undefined") { + startAutoRefresh(); + setupActivityBasedRefresh(); +} + // Axios 인스턴스 생성 export const apiClient = axios.create({ baseURL: API_BASE_URL, @@ -138,9 +289,15 @@ apiClient.interceptors.request.use( // 응답 인터셉터 apiClient.interceptors.response.use( (response: AxiosResponse) => { + // 백엔드에서 보내주는 새로운 토큰 처리 + const newToken = response.headers["x-new-token"]; + if (newToken) { + TokenManager.setToken(newToken); + console.log("[TokenManager] 서버에서 새 토큰 수신, 저장 완료"); + } return response; }, - (error: AxiosError) => { + async (error: AxiosError) => { const status = error.response?.status; const url = error.config?.url; @@ -153,7 +310,7 @@ apiClient.interceptors.response.use( } // 일반 409 에러는 간단한 로그만 출력 - console.warn("⚠️ 데이터 중복:", { + console.warn("데이터 중복:", { url: url, message: (error.response?.data as { message?: string })?.message || "중복된 데이터입니다.", }); @@ -161,7 +318,7 @@ apiClient.interceptors.response.use( } // 다른 에러들은 기존처럼 상세 로그 출력 - console.error("❌ API 응답 오류:", { + console.error("API 응답 오류:", { status: status, statusText: error.response?.statusText, url: url, @@ -170,24 +327,40 @@ apiClient.interceptors.response.use( headers: error.config?.headers, }); - // 401 에러 시 상세 정보 출력 - if (status === 401) { - console.error("🚨 401 Unauthorized 오류 상세 정보:", { + // 401 에러 처리 + if (status === 401 && typeof window !== "undefined") { + const errorData = error.response?.data as { error?: { code?: string } }; + const errorCode = errorData?.error?.code; + + console.warn("[Auth] 401 오류 발생:", { url: url, - method: error.config?.method, - headers: error.config?.headers, - requestData: error.config?.data, - responseData: error.response?.data, + errorCode: errorCode, token: TokenManager.getToken() ? "존재" : "없음", }); - } - // 401 에러 시 토큰 제거 및 로그인 페이지로 리다이렉트 - if (status === 401 && typeof window !== "undefined") { - localStorage.removeItem("authToken"); + // 토큰 만료 에러인 경우 갱신 시도 + const originalRequest = error.config as typeof error.config & { _retry?: boolean }; + if (errorCode === "TOKEN_EXPIRED" && originalRequest && !originalRequest._retry) { + console.log("[Auth] 토큰 만료, 갱신 시도..."); + originalRequest._retry = true; + + try { + const newToken = await refreshToken(); + if (newToken && originalRequest) { + originalRequest.headers.Authorization = `Bearer ${newToken}`; + return apiClient.request(originalRequest); + } + } catch (refreshError) { + console.error("[Auth] 토큰 갱신 실패:", refreshError); + } + } + + // 토큰 갱신 실패 또는 다른 401 에러인 경우 로그아웃 + TokenManager.removeToken(); // 로그인 페이지가 아닌 경우에만 리다이렉트 if (window.location.pathname !== "/login") { + console.log("[Auth] 로그인 페이지로 리다이렉트"); window.location.href = "/login"; } } From 09d2d7573d58816a34ac7c147ecedc54eadea67b Mon Sep 17 00:00:00 2001 From: kjs Date: Mon, 8 Dec 2025 11:44:07 +0900 Subject: [PATCH 07/18] =?UTF-8?q?=ED=99=94=EB=A9=B4=20=EA=B0=99=EC=9D=B4?= =?UTF-8?q?=20=EC=A4=84=EC=96=B4=EB=93=A4=EA=B2=8C=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/노드플로우_개선사항.md | 582 ++++++++++++++++++ .../app/(main)/screens/[screenId]/page.tsx | 12 +- 2 files changed, 588 insertions(+), 6 deletions(-) create mode 100644 docs/노드플로우_개선사항.md diff --git a/docs/노드플로우_개선사항.md b/docs/노드플로우_개선사항.md new file mode 100644 index 00000000..3fe6cde2 --- /dev/null +++ b/docs/노드플로우_개선사항.md @@ -0,0 +1,582 @@ +# 노드 플로우 기능 개선 사항 + +> 작성일: 2024-12-08 +> 상태: 분석 완료, 개선 대기 + +## 현재 구현 상태 + +### 잘 구현된 기능 + +| 기능 | 상태 | 설명 | +|------|------|------| +| 위상 정렬 실행 | 완료 | DAG 기반 레벨별 실행 | +| 트랜잭션 관리 | 완료 | 전체 플로우 단일 트랜잭션, 실패 시 자동 롤백 | +| 병렬 실행 | 완료 | 같은 레벨 노드 `Promise.allSettled`로 병렬 처리 | +| CRUD 액션 | 완료 | INSERT, UPDATE, DELETE, UPSERT 지원 | +| 외부 DB 연동 | 완료 | PostgreSQL, MySQL, MSSQL, Oracle 지원 | +| REST API 연동 | 완료 | GET, POST, PUT, DELETE 지원 | +| 조건 분기 | 완료 | 다양한 연산자 지원 | +| 데이터 변환 | 부분 완료 | UPPERCASE, TRIM, EXPLODE 등 기본 변환 | +| 집계 함수 | 완료 | SUM, COUNT, AVG, MIN, MAX, FIRST, LAST | + +### 관련 파일 + +- **백엔드 실행 엔진**: `backend-node/src/services/nodeFlowExecutionService.ts` +- **백엔드 라우트**: `backend-node/src/routes/dataflow/node-flows.ts` +- **프론트엔드 API**: `frontend/lib/api/nodeFlows.ts` +- **프론트엔드 에디터**: `frontend/components/dataflow/node-editor/FlowEditor.tsx` +- **타입 정의**: `backend-node/src/types/flow.ts` + +--- + +## 개선 필요 사항 + +### 1. [우선순위 높음] 실행 이력 로깅 + +**현재 상태**: 플로우 실행 이력이 저장되지 않음 + +**문제점**: +- 언제, 누가, 어떤 플로우를 실행했는지 추적 불가 +- 실패 원인 분석 어려움 +- 감사(Audit) 요구사항 충족 불가 + +**개선 방안**: + +```sql +-- db/migrations/XXX_add_node_flow_execution_log.sql +CREATE TABLE node_flow_execution_log ( + id SERIAL PRIMARY KEY, + flow_id INTEGER NOT NULL REFERENCES node_flows(flow_id) ON DELETE CASCADE, + execution_status VARCHAR(20) NOT NULL, -- 'success', 'failed', 'partial' + execution_time_ms INTEGER, + total_nodes INTEGER, + success_nodes INTEGER, + failed_nodes INTEGER, + skipped_nodes INTEGER, + executed_by VARCHAR(50), + company_code VARCHAR(20), + context_data JSONB, + result_summary JSONB, + error_message TEXT, + created_at TIMESTAMP DEFAULT NOW() +); + +CREATE INDEX idx_flow_execution_log_flow_id ON node_flow_execution_log(flow_id); +CREATE INDEX idx_flow_execution_log_created_at ON node_flow_execution_log(created_at DESC); +CREATE INDEX idx_flow_execution_log_company_code ON node_flow_execution_log(company_code); +``` + +**필요 작업**: +- [ ] 마이그레이션 파일 생성 +- [ ] `nodeFlowExecutionService.ts`에 로그 저장 로직 추가 +- [ ] 실행 이력 조회 API 추가 (`GET /api/dataflow/node-flows/:flowId/executions`) +- [ ] 프론트엔드 실행 이력 UI 추가 + +--- + +### 2. [우선순위 높음] 드라이런(Dry Run) 모드 + +**현재 상태**: 실제 데이터를 변경하지 않고 테스트할 방법 없음 + +**문제점**: +- 프로덕션 데이터에 직접 영향 +- 플로우 디버깅 어려움 +- 신규 플로우 검증 불가 + +**개선 방안**: + +```typescript +// nodeFlowExecutionService.ts +static async executeFlow( + flowId: number, + contextData: Record, + options: { dryRun?: boolean } = {} +): Promise { + if (options.dryRun) { + // 트랜잭션 시작 후 항상 롤백 + return transaction(async (client) => { + const result = await this.executeFlowInternal(flowId, contextData, client); + // 롤백을 위해 의도적으로 에러 발생 + throw new DryRunComplete(result); + }).catch((e) => { + if (e instanceof DryRunComplete) { + return { ...e.result, dryRun: true }; + } + throw e; + }); + } + // 기존 로직... +} +``` + +```typescript +// node-flows.ts 라우트 수정 +router.post("/:flowId/execute", async (req, res) => { + const dryRun = req.query.dryRun === 'true'; + const result = await NodeFlowExecutionService.executeFlow( + parseInt(flowId, 10), + enrichedContextData, + { dryRun } + ); + // ... +}); +``` + +**필요 작업**: +- [ ] `DryRunComplete` 예외 클래스 생성 +- [ ] `executeFlow` 메서드에 `dryRun` 옵션 추가 +- [ ] 라우트에 쿼리 파라미터 처리 추가 +- [ ] 프론트엔드 "테스트 실행" 버튼 추가 + +--- + +### 3. [우선순위 높음] 재시도 메커니즘 + +**현재 상태**: 외부 API/DB 호출 실패 시 재시도 없음 + +**문제점**: +- 일시적 네트워크 오류로 전체 플로우 실패 +- 외부 서비스 불안정 시 신뢰성 저하 + +**개선 방안**: + +```typescript +// utils/retry.ts +export async function withRetry( + fn: () => Promise, + options: { + maxRetries?: number; + delay?: number; + backoffMultiplier?: number; + retryOn?: (error: any) => boolean; + } = {} +): Promise { + const { + maxRetries = 3, + delay = 1000, + backoffMultiplier = 2, + retryOn = () => true + } = options; + + for (let attempt = 0; attempt < maxRetries; attempt++) { + try { + return await fn(); + } catch (error) { + if (attempt === maxRetries - 1 || !retryOn(error)) { + throw error; + } + const waitTime = delay * Math.pow(backoffMultiplier, attempt); + logger.warn(`재시도 ${attempt + 1}/${maxRetries}, ${waitTime}ms 후...`); + await new Promise(r => setTimeout(r, waitTime)); + } + } + throw new Error('재시도 횟수 초과'); +} +``` + +```typescript +// nodeFlowExecutionService.ts에서 사용 +const response = await withRetry( + () => axios({ method, url, headers, data, timeout }), + { + maxRetries: 3, + delay: 1000, + retryOn: (err) => err.code === 'ECONNRESET' || err.response?.status >= 500 + } +); +``` + +**필요 작업**: +- [ ] `withRetry` 유틸리티 함수 생성 +- [ ] REST API 호출 부분에 재시도 로직 적용 +- [ ] 외부 DB 연결 부분에 재시도 로직 적용 +- [ ] 노드별 재시도 설정 UI 추가 (선택사항) + +--- + +### 4. [우선순위 높음] 미완성 데이터 변환 함수 + +**현재 상태**: FORMAT, CALCULATE, JSON_EXTRACT, CUSTOM 변환이 미구현 + +**문제점**: +- 날짜/숫자 포맷팅 불가 +- 계산식 처리 불가 +- JSON 데이터 파싱 불가 + +**개선 방안**: + +```typescript +// nodeFlowExecutionService.ts - applyTransformation 메서드 수정 + +case "FORMAT": + return rows.map((row) => { + const value = row[sourceField]; + let formatted = value; + + if (transform.formatType === 'date') { + // dayjs 사용 + formatted = dayjs(value).format(transform.formatPattern || 'YYYY-MM-DD'); + } else if (transform.formatType === 'number') { + // 숫자 포맷팅 + const num = parseFloat(value); + if (transform.formatPattern === 'currency') { + formatted = num.toLocaleString('ko-KR', { style: 'currency', currency: 'KRW' }); + } else if (transform.formatPattern === 'percent') { + formatted = (num * 100).toFixed(transform.decimals || 0) + '%'; + } else { + formatted = num.toLocaleString('ko-KR', { maximumFractionDigits: transform.decimals || 2 }); + } + } + + return { ...row, [actualTargetField]: formatted }; + }); + +case "CALCULATE": + return rows.map((row) => { + // 간단한 수식 평가 (보안 주의!) + const expression = transform.expression; // 예: "price * quantity" + const result = evaluateExpression(expression, row); + return { ...row, [actualTargetField]: result }; + }); + +case "JSON_EXTRACT": + return rows.map((row) => { + const jsonValue = typeof row[sourceField] === 'string' + ? JSON.parse(row[sourceField]) + : row[sourceField]; + const extracted = jsonPath.query(jsonValue, transform.jsonPath); // JSONPath 라이브러리 사용 + return { ...row, [actualTargetField]: extracted[0] || null }; + }); +``` + +**필요 작업**: +- [ ] `dayjs` 라이브러리 추가 (날짜 포맷팅) +- [ ] `jsonpath` 라이브러리 추가 (JSON 추출) +- [ ] 안전한 수식 평가 함수 구현 (eval 대신) +- [ ] 각 변환 타입별 UI 설정 패널 추가 + +--- + +### 5. [우선순위 중간] 플로우 버전 관리 + +**현재 상태**: 플로우 수정 시 이전 버전 덮어씀 + +**문제점**: +- 실수로 수정한 플로우 복구 불가 +- 변경 이력 추적 불가 + +**개선 방안**: + +```sql +-- db/migrations/XXX_add_node_flow_versions.sql +CREATE TABLE node_flow_versions ( + id SERIAL PRIMARY KEY, + flow_id INTEGER NOT NULL REFERENCES node_flows(flow_id) ON DELETE CASCADE, + version INTEGER NOT NULL, + flow_data JSONB NOT NULL, + change_description TEXT, + created_by VARCHAR(50), + created_at TIMESTAMP DEFAULT NOW(), + UNIQUE(flow_id, version) +); + +CREATE INDEX idx_flow_versions_flow_id ON node_flow_versions(flow_id); +``` + +```typescript +// 플로우 수정 시 버전 저장 +async function updateNodeFlow(flowId, flowData, changeDescription, userId) { + // 현재 버전 조회 + const currentVersion = await queryOne( + 'SELECT COALESCE(MAX(version), 0) as max_version FROM node_flow_versions WHERE flow_id = $1', + [flowId] + ); + + // 새 버전 저장 + await query( + 'INSERT INTO node_flow_versions (flow_id, version, flow_data, change_description, created_by) VALUES ($1, $2, $3, $4, $5)', + [flowId, currentVersion.max_version + 1, flowData, changeDescription, userId] + ); + + // 기존 업데이트 로직... +} +``` + +**필요 작업**: +- [ ] 버전 테이블 마이그레이션 생성 +- [ ] 플로우 수정 시 버전 자동 저장 +- [ ] 버전 목록 조회 API (`GET /api/dataflow/node-flows/:flowId/versions`) +- [ ] 특정 버전으로 롤백 API (`POST /api/dataflow/node-flows/:flowId/rollback/:version`) +- [ ] 프론트엔드 버전 히스토리 UI + +--- + +### 6. [우선순위 중간] 복합 조건 지원 + +**현재 상태**: 조건 노드에서 단일 조건만 지원 + +**문제점**: +- 복잡한 비즈니스 로직 표현 불가 +- 여러 조건을 AND/OR로 조합 불가 + +**개선 방안**: + +```typescript +// 복합 조건 타입 정의 +interface ConditionGroup { + type: 'AND' | 'OR'; + conditions: (Condition | ConditionGroup)[]; +} + +interface Condition { + field: string; + operator: string; + value: any; +} + +// 조건 평가 함수 수정 +function evaluateConditionGroup(group: ConditionGroup, data: any): boolean { + const results = group.conditions.map(condition => { + if ('type' in condition) { + // 중첩된 그룹 + return evaluateConditionGroup(condition, data); + } else { + // 단일 조건 + return evaluateCondition(data[condition.field], condition.operator, condition.value); + } + }); + + return group.type === 'AND' + ? results.every(r => r) + : results.some(r => r); +} +``` + +**필요 작업**: +- [ ] 복합 조건 타입 정의 +- [ ] `evaluateConditionGroup` 함수 구현 +- [ ] 조건 노드 속성 패널 UI 수정 (AND/OR 그룹 빌더) + +--- + +### 7. [우선순위 중간] 비동기 실행 + +**현재 상태**: 동기 실행만 가능 (HTTP 요청 타임아웃 제한) + +**문제점**: +- 대용량 데이터 처리 시 타임아웃 +- 장시간 실행 플로우 처리 불가 + +**개선 방안**: + +```sql +-- 실행 큐 테이블 +CREATE TABLE node_flow_execution_queue ( + id SERIAL PRIMARY KEY, + flow_id INTEGER NOT NULL REFERENCES node_flows(flow_id), + execution_id UUID NOT NULL UNIQUE DEFAULT gen_random_uuid(), + status VARCHAR(20) NOT NULL DEFAULT 'queued', -- queued, running, completed, failed + context_data JSONB, + callback_url TEXT, + result JSONB, + error_message TEXT, + queued_by VARCHAR(50), + company_code VARCHAR(20), + queued_at TIMESTAMP DEFAULT NOW(), + started_at TIMESTAMP, + completed_at TIMESTAMP +); +``` + +```typescript +// 비동기 실행 API +router.post("/:flowId/execute-async", async (req, res) => { + const { callbackUrl, contextData } = req.body; + + // 큐에 추가 + const execution = await queryOne( + `INSERT INTO node_flow_execution_queue (flow_id, context_data, callback_url, queued_by, company_code) + VALUES ($1, $2, $3, $4, $5) RETURNING execution_id`, + [flowId, contextData, callbackUrl, req.user?.userId, req.user?.companyCode] + ); + + // 백그라운드 워커가 처리 + return res.json({ + success: true, + executionId: execution.execution_id, + status: 'queued' + }); +}); + +// 상태 조회 API +router.get("/executions/:executionId", async (req, res) => { + const execution = await queryOne( + 'SELECT * FROM node_flow_execution_queue WHERE execution_id = $1', + [req.params.executionId] + ); + return res.json({ success: true, data: execution }); +}); +``` + +**필요 작업**: +- [ ] 실행 큐 테이블 마이그레이션 +- [ ] 비동기 실행 API 추가 +- [ ] 백그라운드 워커 프로세스 구현 (별도 프로세스 또는 Bull 큐) +- [ ] 웹훅 콜백 기능 구현 +- [ ] 프론트엔드 비동기 실행 상태 폴링 UI + +--- + +### 8. [우선순위 낮음] 플로우 스케줄링 + +**현재 상태**: 수동 실행만 가능 + +**문제점**: +- 정기적인 배치 작업 자동화 불가 +- 특정 시간 예약 실행 불가 + +**개선 방안**: + +```sql +-- 스케줄 테이블 +CREATE TABLE node_flow_schedules ( + id SERIAL PRIMARY KEY, + flow_id INTEGER NOT NULL REFERENCES node_flows(flow_id) ON DELETE CASCADE, + schedule_name VARCHAR(100), + cron_expression VARCHAR(50) NOT NULL, -- '0 9 * * 1-5' (평일 9시) + context_data JSONB, + is_active BOOLEAN DEFAULT true, + last_run_at TIMESTAMP, + next_run_at TIMESTAMP, + created_by VARCHAR(50), + company_code VARCHAR(20), + created_at TIMESTAMP DEFAULT NOW(), + updated_at TIMESTAMP DEFAULT NOW() +); +``` + +**필요 작업**: +- [ ] 스케줄 테이블 마이그레이션 +- [ ] 스케줄 CRUD API +- [ ] node-cron 또는 Bull 스케줄러 통합 +- [ ] 스케줄 관리 UI + +--- + +### 9. [우선순위 낮음] 플러그인 아키텍처 + +**현재 상태**: 새 노드 타입 추가 시 `nodeFlowExecutionService.ts` 직접 수정 필요 + +**문제점**: +- 코드 복잡도 증가 +- 확장성 제한 + +**개선 방안**: + +```typescript +// interfaces/NodeHandler.ts +export interface NodeHandler { + type: string; + execute(node: FlowNode, inputData: any, context: ExecutionContext, client?: any): Promise; + validate?(node: FlowNode): { valid: boolean; errors: string[] }; +} + +// handlers/InsertActionHandler.ts +export class InsertActionHandler implements NodeHandler { + type = 'insertAction'; + + async execute(node, inputData, context, client) { + // 기존 executeInsertAction 로직 + } +} + +// NodeHandlerRegistry.ts +class NodeHandlerRegistry { + private handlers = new Map(); + + register(handler: NodeHandler) { + this.handlers.set(handler.type, handler); + } + + get(type: string): NodeHandler | undefined { + return this.handlers.get(type); + } +} + +// 사용 +const registry = new NodeHandlerRegistry(); +registry.register(new InsertActionHandler()); +registry.register(new UpdateActionHandler()); +// ... + +// executeNodeByType에서 +const handler = registry.get(node.type); +if (handler) { + return handler.execute(node, inputData, context, client); +} +``` + +**필요 작업**: +- [ ] `NodeHandler` 인터페이스 정의 +- [ ] 기존 노드 타입별 핸들러 클래스 분리 +- [ ] `NodeHandlerRegistry` 구현 +- [ ] 커스텀 노드 핸들러 등록 메커니즘 + +--- + +### 10. [우선순위 낮음] 프론트엔드 연동 강화 + +**현재 상태**: 기본 에디터 구현됨 + +**개선 필요 항목**: +- [ ] 실행 결과 시각화 (노드별 성공/실패 표시) +- [ ] 실시간 실행 진행률 표시 +- [ ] 드라이런 모드 UI +- [ ] 실행 이력 조회 UI +- [ ] 버전 히스토리 UI +- [ ] 노드 검증 결과 표시 + +--- + +## 프론트엔드 컴포넌트 CRUD 로직 이전 계획 + +현재 프론트엔드 컴포넌트에서 직접 CRUD를 수행하는 코드들을 노드 플로우로 이전해야 합니다. + +### 이전 대상 컴포넌트 + +| 컴포넌트 | 파일 위치 | 현재 로직 | 이전 우선순위 | +|----------|----------|----------|--------------| +| SplitPanelLayoutComponent | `frontend/lib/registry/components/split-panel-layout/` | createRecord, updateRecord, deleteRecord | 높음 | +| RepeatScreenModalComponent | `frontend/lib/registry/components/repeat-screen-modal/` | 다중 테이블 INSERT/UPDATE/DELETE | 높음 | +| UniversalFormModalComponent | `frontend/lib/registry/components/universal-form-modal/` | 다중 행 저장 | 높음 | +| SelectedItemsDetailInputComponent | `frontend/lib/registry/components/selected-items-detail-input/` | upsertGroupedRecords | 높음 | +| ButtonPrimaryComponent | `frontend/lib/registry/components/button-primary/` | 상태 변경 POST | 중간 | +| SimpleRepeaterTableComponent | `frontend/lib/registry/components/simple-repeater-table/` | 데이터 저장 POST | 중간 | + +### 이전 방식 + +1. **플로우 생성**: 각 컴포넌트의 저장 로직을 노드 플로우로 구현 +2. **프론트엔드 수정**: 직접 API 호출 대신 `executeNodeFlow(flowId, contextData)` 호출 +3. **화면 설정에 플로우 연결**: 버튼 액션에 실행할 플로우 ID 설정 + +```typescript +// 현재 (프론트엔드에서 직접 호출) +const result = await dataApi.createRecord(tableName, data); + +// 개선 후 (플로우 실행) +const result = await executeNodeFlow(flowId, { + formData: data, + tableName: tableName, + action: 'create' +}); +``` + +--- + +## 참고 자료 + +- 노드 플로우 실행 엔진: `backend-node/src/services/nodeFlowExecutionService.ts` +- 플로우 타입 정의: `backend-node/src/types/flow.ts` +- 프론트엔드 플로우 에디터: `frontend/components/dataflow/node-editor/FlowEditor.tsx` +- 프론트엔드 플로우 API: `frontend/lib/api/nodeFlows.ts` + diff --git a/frontend/app/(main)/screens/[screenId]/page.tsx b/frontend/app/(main)/screens/[screenId]/page.tsx index 86362ec8..f556dae2 100644 --- a/frontend/app/(main)/screens/[screenId]/page.tsx +++ b/frontend/app/(main)/screens/[screenId]/page.tsx @@ -216,7 +216,8 @@ function ScreenViewPage() { initAutoFill(); }, [layout, user]); - // 캔버스 비율 조정 (사용자 화면에 맞게 자동 스케일) - 모바일에서는 비활성화 + // 캔버스 비율 조정 (사용자 화면에 맞게 자동 스케일) - 초기 로딩 시에만 계산 + // 브라우저 배율 조정 시 메뉴와 화면이 함께 축소/확대되도록 resize 이벤트는 감지하지 않음 useEffect(() => { // 모바일 환경에서는 스케일 조정 비활성화 (반응형만 작동) if (isMobile) { @@ -262,13 +263,12 @@ function ScreenViewPage() { } }; - // 초기 측정 + // 초기 측정 (한 번만 실행) const timer = setTimeout(updateScale, 100); - window.addEventListener("resize", updateScale); + // resize 이벤트는 감지하지 않음 - 브라우저 배율 조정 시 메뉴와 화면이 함께 변경되도록 return () => { clearTimeout(timer); - window.removeEventListener("resize", updateScale); }; }, [layout, isMobile]); @@ -309,7 +309,7 @@ function ScreenViewPage() {
{/* 레이아웃 준비 중 로딩 표시 */} {!layoutReady && ( @@ -334,7 +334,7 @@ function ScreenViewPage() { maxHeight: `${screenHeight}px`, flexShrink: 0, transform: `scale(${scale})`, - transformOrigin: "center center", + transformOrigin: "top left", overflow: "visible", }} > From e05af3c6f9022314bb942de2ccbef5450f3dfbbe Mon Sep 17 00:00:00 2001 From: kjs Date: Mon, 8 Dec 2025 15:15:44 +0900 Subject: [PATCH 08/18] =?UTF-8?q?=EB=A0=89=20=EA=B5=AC=EC=A1=B0=EB=93=B1?= =?UTF-8?q?=EB=A1=9D=20=EC=BB=B4=ED=8F=AC=EB=84=8C=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/노드플로우_개선사항.md | 1 + frontend/lib/registry/components/index.ts | 3 + .../components/rack-structure/README.md | 148 ++++ .../rack-structure/RackStructureComponent.tsx | 724 ++++++++++++++++++ .../RackStructureConfigPanel.tsx | 287 +++++++ .../rack-structure/RackStructureRenderer.tsx | 44 ++ .../components/rack-structure/config.ts | 27 + .../components/rack-structure/index.ts | 74 ++ .../components/rack-structure/types.ts | 91 +++ ..._임베딩_및_데이터_전달_시스템_구현_계획서.md | 1 + 화면_임베딩_시스템_Phase1-4_구현_완료.md | 1 + 화면_임베딩_시스템_충돌_분석_보고서.md | 1 + 12 files changed, 1402 insertions(+) create mode 100644 frontend/lib/registry/components/rack-structure/README.md create mode 100644 frontend/lib/registry/components/rack-structure/RackStructureComponent.tsx create mode 100644 frontend/lib/registry/components/rack-structure/RackStructureConfigPanel.tsx create mode 100644 frontend/lib/registry/components/rack-structure/RackStructureRenderer.tsx create mode 100644 frontend/lib/registry/components/rack-structure/config.ts create mode 100644 frontend/lib/registry/components/rack-structure/index.ts create mode 100644 frontend/lib/registry/components/rack-structure/types.ts diff --git a/docs/노드플로우_개선사항.md b/docs/노드플로우_개선사항.md index 3fe6cde2..85ae186b 100644 --- a/docs/노드플로우_개선사항.md +++ b/docs/노드플로우_개선사항.md @@ -580,3 +580,4 @@ const result = await executeNodeFlow(flowId, { - 프론트엔드 플로우 에디터: `frontend/components/dataflow/node-editor/FlowEditor.tsx` - 프론트엔드 플로우 API: `frontend/lib/api/nodeFlows.ts` + diff --git a/frontend/lib/registry/components/index.ts b/frontend/lib/registry/components/index.ts index 2a5d45e4..ff9d9240 100644 --- a/frontend/lib/registry/components/index.ts +++ b/frontend/lib/registry/components/index.ts @@ -77,6 +77,9 @@ import "./screen-split-panel/ScreenSplitPanelRenderer"; // 화면 분할 패널 // 🆕 범용 폼 모달 컴포넌트 import "./universal-form-modal/UniversalFormModalRenderer"; // 섹션 기반 폼, 채번규칙, 다중 행 저장 지원 +// 🆕 렉 구조 설정 컴포넌트 +import "./rack-structure/RackStructureRenderer"; // 창고 렉 위치 일괄 생성 + /** * 컴포넌트 초기화 함수 */ diff --git a/frontend/lib/registry/components/rack-structure/README.md b/frontend/lib/registry/components/rack-structure/README.md new file mode 100644 index 00000000..bf03d8dc --- /dev/null +++ b/frontend/lib/registry/components/rack-structure/README.md @@ -0,0 +1,148 @@ +# 렉 구조 설정 컴포넌트 (Rack Structure Config) + +창고 렉 위치를 열 범위와 단 수로 일괄 생성하는 컴포넌트입니다. + +## 핵심 개념 + +이 컴포넌트는 **상위 폼의 필드 값을 읽어서** 위치 코드를 생성합니다. + +### 작동 방식 + +1. 사용자가 화면관리에서 테이블 컬럼(창고코드, 층, 구역 등)을 드래그하여 폼에 배치 +2. 렉 구조 컴포넌트 설정에서 **필드 매핑** 설정 (어떤 폼 필드가 창고/층/구역인지) +3. 런타임에 사용자가 폼 필드에 값을 입력하면, 렉 구조 컴포넌트가 해당 값을 읽어서 사용 + +## 기능 + +### 1. 렉 라인 구조 설정 + +- 조건 추가/삭제 +- 각 조건: 열 범위(시작~종료) + 단 수 +- 자동 위치 수 계산 (예: 1열~3열 x 3단 = 9개) +- 템플릿 저장/불러오기 + +### 2. 등록 미리보기 + +- 통계 카드 (총 위치, 열 수, 최대 단) +- 미리보기 생성 버튼 +- 생성될 위치 목록 테이블 + +## 설정 방법 + +### 1. 화면관리에서 배치 + +1. 상위에 테이블 컬럼들을 배치 (창고코드, 층, 구역, 위치유형, 사용여부) +2. 컴포넌트 팔레트에서 "렉 구조 설정" 선택 +3. 캔버스에 드래그하여 배치 + +### 2. 필드 매핑 설정 + +설정 패널에서 상위 폼의 어떤 필드를 사용할지 매핑합니다: + +| 매핑 항목 | 설명 | +| -------------- | ------------------------------------- | +| 창고 코드 필드 | 위치 코드 생성에 사용할 창고 코드 | +| 층 필드 | 위치 코드 생성에 사용할 층 | +| 구역 필드 | 위치 코드 생성에 사용할 구역 | +| 위치 유형 필드 | 미리보기 테이블에 표시할 위치 유형 | +| 사용 여부 필드 | 미리보기 테이블에 표시할 사용 여부 | + +### 예시 + +상위 폼에 다음 필드가 배치되어 있다면: +- `창고코드(조인)` → 필드명: `warehouse_code` +- `층` → 필드명: `floor` +- `구역` → 필드명: `zone` + +설정 패널에서: +- 창고 코드 필드: `warehouse_code` 선택 +- 층 필드: `floor` 선택 +- 구역 필드: `zone` 선택 + +## 위치 코드 생성 규칙 + +기본 패턴: `{창고코드}-{층}{구역}-{열:2자리}-{단}` + +예시 (창고: WH001, 층: 1, 구역: A): + +- WH001-1A-01-1 (01열, 1단) +- WH001-1A-01-2 (01열, 2단) +- WH001-1A-02-1 (02열, 1단) + +## 설정 옵션 + +| 옵션 | 타입 | 기본값 | 설명 | +| -------------- | ------- | ------ | ---------------- | +| maxConditions | number | 10 | 최대 조건 수 | +| maxRows | number | 99 | 최대 열 수 | +| maxLevels | number | 20 | 최대 단 수 | +| showTemplates | boolean | true | 템플릿 기능 표시 | +| showPreview | boolean | true | 미리보기 표시 | +| showStatistics | boolean | true | 통계 카드 표시 | +| readonly | boolean | false | 읽기 전용 | + +## 출력 데이터 + +`onChange` 콜백으로 생성된 위치 데이터 배열을 반환합니다: + +```typescript +interface GeneratedLocation { + rowNum: number; // 열 번호 + levelNum: number; // 단 번호 + locationCode: string; // 위치 코드 + locationName: string; // 위치명 + locationType?: string; // 위치 유형 + status?: string; // 사용 여부 + warehouseCode?: string; // 창고 코드 (매핑된 값) + floor?: string; // 층 (매핑된 값) + zone?: string; // 구역 (매핑된 값) +} +``` + +## 연동 테이블 + +`warehouse_location` 테이블과 연동됩니다: + +| 컬럼 | 설명 | +| ------------- | --------- | +| warehouse_id | 창고 ID | +| floor | 층 | +| zone | 구역 | +| row_num | 열 번호 | +| level_num | 단 번호 | +| location_code | 위치 코드 | +| location_name | 위치명 | +| location_type | 위치 유형 | +| status | 사용 여부 | + +## 예시 시나리오 + +### 시나리오: A구역에 1~3열은 3단, 4~6열은 5단 렉 생성 + +1. **상위 폼에서 기본 정보 입력** + - 창고: 제1창고 (WH001) - 드래그해서 배치한 필드 + - 층: 1 - 드래그해서 배치한 필드 + - 구역: A - 드래그해서 배치한 필드 + - 위치 유형: 선반 - 드래그해서 배치한 필드 + - 사용 여부: 사용 - 드래그해서 배치한 필드 + +2. **렉 구조 컴포넌트에서 조건 추가** + - 조건 1: 1~3열, 3단 → 9개 + - 조건 2: 4~6열, 5단 → 15개 + +3. **미리보기 생성** + - 총 위치: 24개 + - 열 수: 6개 + - 최대 단: 5단 + +4. **저장** + - 24개의 위치 데이터가 warehouse_location 테이블에 저장됨 + +## 필수 필드 검증 + +미리보기 생성 시 다음 필드가 입력되어 있어야 합니다: +- 창고 코드 +- 층 +- 구역 + +필드가 비어있으면 경고 메시지가 표시됩니다. diff --git a/frontend/lib/registry/components/rack-structure/RackStructureComponent.tsx b/frontend/lib/registry/components/rack-structure/RackStructureComponent.tsx new file mode 100644 index 00000000..f49e4462 --- /dev/null +++ b/frontend/lib/registry/components/rack-structure/RackStructureComponent.tsx @@ -0,0 +1,724 @@ +"use client"; + +import React, { useState, useCallback, useMemo, useEffect } from "react"; +import { Plus, X, Save, FolderOpen, RefreshCw, Eye, AlertCircle } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogFooter, +} from "@/components/ui/dialog"; +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from "@/components/ui/table"; +import { ScrollArea } from "@/components/ui/scroll-area"; +import { Alert, AlertDescription } from "@/components/ui/alert"; +import { cn } from "@/lib/utils"; +import { + RackStructureComponentProps, + RackLineCondition, + RackStructureTemplate, + GeneratedLocation, + RackStructureContext, +} from "./types"; + +// 고유 ID 생성 +const generateId = () => `cond_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; + +// 조건 카드 컴포넌트 +interface ConditionCardProps { + condition: RackLineCondition; + index: number; + onUpdate: (id: string, updates: Partial) => void; + onRemove: (id: string) => void; + maxRows: number; + maxLevels: number; + readonly?: boolean; +} + +const ConditionCard: React.FC = ({ + condition, + index, + onUpdate, + onRemove, + maxRows, + maxLevels, + readonly, +}) => { + // 로컬 상태로 입력값 관리 + const [localValues, setLocalValues] = useState({ + startRow: condition.startRow.toString(), + endRow: condition.endRow.toString(), + levels: condition.levels.toString(), + }); + + // condition이 변경되면 로컬 상태 동기화 + useEffect(() => { + setLocalValues({ + startRow: condition.startRow.toString(), + endRow: condition.endRow.toString(), + levels: condition.levels.toString(), + }); + }, [condition.startRow, condition.endRow, condition.levels]); + + // 계산된 위치 수 + const locationCount = useMemo(() => { + const start = parseInt(localValues.startRow) || 0; + const end = parseInt(localValues.endRow) || 0; + const levels = parseInt(localValues.levels) || 0; + if (start > 0 && end >= start && levels > 0) { + return (end - start + 1) * levels; + } + return 0; + }, [localValues]); + + // 입력값 변경 핸들러 + const handleChange = (field: keyof typeof localValues, value: string) => { + setLocalValues((prev) => ({ ...prev, [field]: value })); + }; + + // blur 시 실제 업데이트 + const handleBlur = (field: keyof typeof localValues) => { + const numValue = parseInt(localValues[field]) || 0; + const clampedValue = Math.max(0, Math.min(numValue, field === "levels" ? maxLevels : maxRows)); + + setLocalValues((prev) => ({ ...prev, [field]: clampedValue.toString() })); + + const updateField = field === "startRow" ? "startRow" : field === "endRow" ? "endRow" : "levels"; + onUpdate(condition.id, { [updateField]: clampedValue }); + }; + + return ( +
+ {/* 헤더 */} +
+ 조건 {index + 1} + {!readonly && ( + + )} +
+ + {/* 내용 */} +
+ {/* 열 범위 */} +
+
+ +
+ handleChange("startRow", e.target.value)} + onBlur={() => handleBlur("startRow")} + disabled={readonly} + className="h-9 text-center" + /> + ~ + handleChange("endRow", e.target.value)} + onBlur={() => handleBlur("endRow")} + disabled={readonly} + className="h-9 text-center" + /> +
+
+
+ + handleChange("levels", e.target.value)} + onBlur={() => handleBlur("levels")} + disabled={readonly} + className="h-9 text-center" + /> +
+
+ + {/* 계산 결과 */} +
+ {locationCount > 0 ? ( + <> + {localValues.startRow}열 ~ {localValues.endRow}열 x {localValues.levels}단 ={" "} + {locationCount}개 + + ) : ( + 값을 입력하세요 + )} +
+
+
+ ); +}; + +// 메인 컴포넌트 +export const RackStructureComponent: React.FC = ({ + config, + context: propContext, + formData, + onChange, + onConditionsChange, + isPreview = false, +}) => { + // 조건 목록 + const [conditions, setConditions] = useState( + config.initialConditions || [] + ); + + // 템플릿 관련 상태 + const [templates, setTemplates] = useState([]); + const [isTemplateDialogOpen, setIsTemplateDialogOpen] = useState(false); + const [templateName, setTemplateName] = useState(""); + const [isSaveMode, setIsSaveMode] = useState(false); + + // 미리보기 데이터 + const [previewData, setPreviewData] = useState([]); + const [isPreviewGenerated, setIsPreviewGenerated] = useState(false); + + // 설정값 + const maxConditions = config.maxConditions || 10; + const maxRows = config.maxRows || 99; + const maxLevels = config.maxLevels || 20; + const readonly = config.readonly || isPreview; + const fieldMapping = config.fieldMapping || {}; + + // 필드 매핑을 통해 formData에서 컨텍스트 추출 + const context: RackStructureContext = useMemo(() => { + // propContext가 있으면 우선 사용 + if (propContext) return propContext; + + // formData와 fieldMapping을 사용하여 컨텍스트 생성 + if (!formData) return {}; + + return { + warehouseCode: fieldMapping.warehouseCodeField + ? formData[fieldMapping.warehouseCodeField] + : undefined, + warehouseName: fieldMapping.warehouseNameField + ? formData[fieldMapping.warehouseNameField] + : undefined, + floor: fieldMapping.floorField + ? formData[fieldMapping.floorField]?.toString() + : undefined, + zone: fieldMapping.zoneField + ? formData[fieldMapping.zoneField] + : undefined, + locationType: fieldMapping.locationTypeField + ? formData[fieldMapping.locationTypeField] + : undefined, + status: fieldMapping.statusField + ? formData[fieldMapping.statusField] + : undefined, + }; + }, [propContext, formData, fieldMapping]); + + // 필수 필드 검증 + const missingFields = useMemo(() => { + const missing: string[] = []; + if (!context.warehouseCode) missing.push("창고 코드"); + if (!context.floor) missing.push("층"); + if (!context.zone) missing.push("구역"); + return missing; + }, [context]); + + // 조건 변경 시 콜백 호출 + useEffect(() => { + onConditionsChange?.(conditions); + setIsPreviewGenerated(false); // 조건 변경 시 미리보기 초기화 + }, [conditions, onConditionsChange]); + + // 조건 추가 + const addCondition = useCallback(() => { + if (conditions.length >= maxConditions) return; + + // 마지막 조건의 다음 열부터 시작 + const lastCondition = conditions[conditions.length - 1]; + const startRow = lastCondition ? lastCondition.endRow + 1 : 1; + + const newCondition: RackLineCondition = { + id: generateId(), + startRow, + endRow: startRow + 2, + levels: 3, + }; + + setConditions((prev) => [...prev, newCondition]); + }, [conditions, maxConditions]); + + // 조건 업데이트 + const updateCondition = useCallback((id: string, updates: Partial) => { + setConditions((prev) => + prev.map((cond) => (cond.id === id ? { ...cond, ...updates } : cond)) + ); + }, []); + + // 조건 삭제 + const removeCondition = useCallback((id: string) => { + setConditions((prev) => prev.filter((cond) => cond.id !== id)); + }, []); + + // 통계 계산 + const statistics = useMemo(() => { + let totalLocations = 0; + let totalRows = 0; + let maxLevel = 0; + const rowSet = new Set(); + + conditions.forEach((cond) => { + if (cond.startRow > 0 && cond.endRow >= cond.startRow && cond.levels > 0) { + const rowCount = cond.endRow - cond.startRow + 1; + totalLocations += rowCount * cond.levels; + for (let r = cond.startRow; r <= cond.endRow; r++) { + rowSet.add(r); + } + maxLevel = Math.max(maxLevel, cond.levels); + } + }); + + totalRows = rowSet.size; + return { totalLocations, totalRows, maxLevel }; + }, [conditions]); + + // 위치 코드 생성 + const generateLocationCode = useCallback( + (row: number, level: number): { code: string; name: string } => { + const warehouseCode = context?.warehouseCode || "WH001"; + const floor = context?.floor || "1"; + const zone = context?.zone || "A"; + + // 코드 생성 (예: WH001-1A-01-1) + const code = `${warehouseCode}-${floor}${zone}-${row.toString().padStart(2, "0")}-${level}`; + + // 이름 생성 (예: A구역-01열-1단) + const name = `${zone}구역-${row.toString().padStart(2, "0")}열-${level}단`; + + return { code, name }; + }, + [context] + ); + + // 미리보기 생성 + const generatePreview = useCallback(() => { + // 필수 필드 검증 + if (missingFields.length > 0) { + alert(`다음 필드를 먼저 입력해주세요: ${missingFields.join(", ")}`); + return; + } + + const locations: GeneratedLocation[] = []; + + conditions.forEach((cond) => { + if (cond.startRow > 0 && cond.endRow >= cond.startRow && cond.levels > 0) { + for (let row = cond.startRow; row <= cond.endRow; row++) { + for (let level = 1; level <= cond.levels; level++) { + const { code, name } = generateLocationCode(row, level); + locations.push({ + rowNum: row, + levelNum: level, + locationCode: code, + locationName: name, + locationType: context?.locationType || "선반", + status: context?.status || "사용", + // 추가 필드 + warehouseCode: context?.warehouseCode, + floor: context?.floor, + zone: context?.zone, + }); + } + } + } + }); + + // 정렬: 열 -> 단 순서 + locations.sort((a, b) => { + if (a.rowNum !== b.rowNum) return a.rowNum - b.rowNum; + return a.levelNum - b.levelNum; + }); + + setPreviewData(locations); + setIsPreviewGenerated(true); + onChange?.(locations); + }, [conditions, context, generateLocationCode, onChange, missingFields]); + + // 템플릿 저장 + const saveTemplate = useCallback(() => { + if (!templateName.trim()) return; + + const newTemplate: RackStructureTemplate = { + id: generateId(), + name: templateName.trim(), + conditions: [...conditions], + createdAt: new Date().toISOString(), + }; + + setTemplates((prev) => [...prev, newTemplate]); + setTemplateName(""); + setIsTemplateDialogOpen(false); + }, [templateName, conditions]); + + // 템플릿 불러오기 + const loadTemplate = useCallback((template: RackStructureTemplate) => { + setConditions(template.conditions.map((c) => ({ ...c, id: generateId() }))); + setIsTemplateDialogOpen(false); + }, []); + + // 템플릿 삭제 + const deleteTemplate = useCallback((templateId: string) => { + setTemplates((prev) => prev.filter((t) => t.id !== templateId)); + }, []); + + return ( +
+ {/* 렉 라인 구조 설정 섹션 */} + + + +
+ 렉 라인 구조 설정 + + {!readonly && ( +
+ {config.showTemplates && ( + <> + + + )} + +
+ )} + + + {/* 필수 필드 경고 */} + {missingFields.length > 0 && ( + + + + 다음 필드를 먼저 입력해주세요: {missingFields.join(", ")} +
+ + (설정 패널에서 필드 매핑을 확인하세요) + +
+
+ )} + + {/* 현재 매핑된 값 표시 */} + {(context.warehouseCode || context.warehouseName || context.floor || context.zone) && ( +
+ {(context.warehouseCode || context.warehouseName) && ( + + 창고: {context.warehouseName || context.warehouseCode} + {context.warehouseName && context.warehouseCode && ` (${context.warehouseCode})`} + + )} + {context.floor && ( + + 층: {context.floor} + + )} + {context.zone && ( + + 구역: {context.zone} + + )} + {context.locationType && ( + + 유형: {context.locationType} + + )} + {context.status && ( + + 상태: {context.status} + + )} +
+ )} + + {/* 안내 메시지 */} +
+
    +
  1. + + 1 + + 조건 추가 버튼을 클릭하여 렉 라인 조건을 생성하세요 +
  2. +
  3. + + 2 + + 각 조건마다 열 범위와 단 수를 입력하세요 +
  4. +
  5. + + 3 + + 예시: 조건1(1~3열, 3단), 조건2(4~6열, 5단) +
  6. +
+
+ + {/* 조건 목록 또는 빈 상태 */} + {conditions.length === 0 ? ( +
+
📦
+

조건을 추가하여 렉 구조를 설정하세요

+ {!readonly && ( + + )} +
+ ) : ( +
+ {conditions.map((condition, index) => ( +
+ +
+ ))} +
+ )} +
+ + + {/* 등록 미리보기 섹션 */} + {config.showPreview && conditions.length > 0 && ( + + + + + 등록 미리보기 + + + + + {/* 통계 카드 */} + {config.showStatistics && ( +
+
+
총 위치
+
{statistics.totalLocations}개
+
+
+
열 수
+
{statistics.totalRows}개
+
+
+
최대 단
+
{statistics.maxLevel}단
+
+
+ )} + + {/* 미리보기 테이블 */} + {isPreviewGenerated && previewData.length > 0 ? ( +
+ +
+ + + No + 위치코드 + 위치명 + + 구역 + + + 유형 + 비고 + + + + {previewData.map((loc, idx) => ( + + {idx + 1} + {loc.locationCode} + {loc.locationName} + {context?.floor || "1"} + {context?.zone || "A"} + + {loc.rowNum.toString().padStart(2, "0")} + + {loc.levelNum} + {loc.locationType} + - + + ))} + +
+ +
+ ) : ( +
+ +

미리보기 생성 버튼을 클릭하여 결과를 확인하세요

+
+ )} + + + )} + + {/* 템플릿 다이얼로그 */} + + + + + {isSaveMode ? "템플릿 저장" : "템플릿 관리"} + + + + {isSaveMode ? ( +
+
+ + setTemplateName(e.target.value)} + placeholder="템플릿 이름을 입력하세요" + /> +
+ + + + +
+ ) : ( +
+ {/* 저장 버튼 */} + {conditions.length > 0 && ( + + )} + + {/* 템플릿 목록 */} + {templates.length > 0 ? ( +
+
저장된 템플릿
+ + {templates.map((template) => ( +
+
+
{template.name}
+
+ {template.conditions.length}개 조건 +
+
+
+ + +
+
+ ))} +
+
+ ) : ( +
+ 저장된 템플릿이 없습니다 +
+ )} +
+ )} +
+
+
+ ); +}; + +// Wrapper 컴포넌트 (레지스트리용) +export const RackStructureWrapper: React.FC = (props) => { + return ( +
+ +
+ ); +}; + + diff --git a/frontend/lib/registry/components/rack-structure/RackStructureConfigPanel.tsx b/frontend/lib/registry/components/rack-structure/RackStructureConfigPanel.tsx new file mode 100644 index 00000000..8f0c8177 --- /dev/null +++ b/frontend/lib/registry/components/rack-structure/RackStructureConfigPanel.tsx @@ -0,0 +1,287 @@ +"use client"; + +import React, { useState, useEffect } from "react"; +import { Label } from "@/components/ui/label"; +import { Input } from "@/components/ui/input"; +import { Switch } from "@/components/ui/switch"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { RackStructureComponentConfig, FieldMapping } from "./types"; + +interface RackStructureConfigPanelProps { + config: RackStructureComponentConfig; + onChange: (config: RackStructureComponentConfig) => void; + // 화면관리에서 전달하는 테이블 컬럼 정보 + tables?: Array<{ + tableName: string; + tableLabel?: string; + columns: Array<{ + columnName: string; + columnLabel?: string; + dataType?: string; + }>; + }>; +} + +export const RackStructureConfigPanel: React.FC = ({ + config, + onChange, + tables = [], +}) => { + // 사용 가능한 컬럼 목록 추출 + const [availableColumns, setAvailableColumns] = useState< + Array<{ value: string; label: string }> + >([]); + + useEffect(() => { + // 모든 테이블의 컬럼을 플랫하게 추출 + const columns: Array<{ value: string; label: string }> = []; + tables.forEach((table) => { + table.columns.forEach((col) => { + columns.push({ + value: col.columnName, + label: col.columnLabel || col.columnName, + }); + }); + }); + setAvailableColumns(columns); + }, [tables]); + + const handleChange = (key: keyof RackStructureComponentConfig, value: any) => { + onChange({ ...config, [key]: value }); + }; + + const handleFieldMappingChange = (field: keyof FieldMapping, value: string) => { + const currentMapping = config.fieldMapping || {}; + onChange({ + ...config, + fieldMapping: { + ...currentMapping, + [field]: value === "__none__" ? undefined : value, + }, + }); + }; + + const fieldMapping = config.fieldMapping || {}; + + return ( +
+ {/* 필드 매핑 섹션 */} +
+
필드 매핑
+

+ 상위 폼에 배치된 필드 중 어떤 필드를 사용할지 선택하세요 +

+ + {/* 창고 코드 필드 */} +
+ + +
+ + {/* 창고명 필드 */} +
+ + +
+ + {/* 층 필드 */} +
+ + +
+ + {/* 구역 필드 */} +
+ + +
+ + {/* 위치 유형 필드 */} +
+ + +
+ + {/* 사용 여부 필드 */} +
+ + +
+
+ + {/* 제한 설정 */} +
+
제한 설정
+ +
+ + handleChange("maxConditions", parseInt(e.target.value) || 10)} + className="h-8" + /> +
+ +
+ + handleChange("maxRows", parseInt(e.target.value) || 99)} + className="h-8" + /> +
+ +
+ + handleChange("maxLevels", parseInt(e.target.value) || 20)} + className="h-8" + /> +
+
+ + {/* UI 설정 */} +
+
UI 설정
+ +
+ + handleChange("showTemplates", checked)} + /> +
+ +
+ + handleChange("showPreview", checked)} + /> +
+ +
+ + handleChange("showStatistics", checked)} + /> +
+ +
+ + handleChange("readonly", checked)} + /> +
+
+
+ ); +}; diff --git a/frontend/lib/registry/components/rack-structure/RackStructureRenderer.tsx b/frontend/lib/registry/components/rack-structure/RackStructureRenderer.tsx new file mode 100644 index 00000000..ab832f51 --- /dev/null +++ b/frontend/lib/registry/components/rack-structure/RackStructureRenderer.tsx @@ -0,0 +1,44 @@ +"use client"; + +import React from "react"; +import { AutoRegisteringComponentRenderer } from "../../AutoRegisteringComponentRenderer"; +import { RackStructureDefinition } from "./index"; +import { RackStructureComponent } from "./RackStructureComponent"; +import { GeneratedLocation } from "./types"; + +/** + * 렉 구조 설정 렌더러 + * 자동 등록 시스템을 사용하여 컴포넌트를 레지스트리에 등록 + */ +export class RackStructureRenderer extends AutoRegisteringComponentRenderer { + static componentDefinition = RackStructureDefinition; + + render(): React.ReactElement { + const { formData, isPreview, config } = this.props as any; + + return ( + + ); + } + + /** + * 생성된 위치 데이터 변경 핸들러 + */ + protected handleLocationsChange = (locations: GeneratedLocation[]) => { + // 생성된 위치 데이터를 formData에 저장 + this.updateComponent({ generatedLocations: locations }); + }; +} + +// 자동 등록 실행 +RackStructureRenderer.registerSelf(); + +// Hot Reload 지원 (개발 모드) +if (process.env.NODE_ENV === "development") { + RackStructureRenderer.enableHotReload(); +} diff --git a/frontend/lib/registry/components/rack-structure/config.ts b/frontend/lib/registry/components/rack-structure/config.ts new file mode 100644 index 00000000..09d9d04b --- /dev/null +++ b/frontend/lib/registry/components/rack-structure/config.ts @@ -0,0 +1,27 @@ +/** + * 렉 구조 컴포넌트 기본 설정 + */ + +import { RackStructureComponentConfig } from "./types"; + +export const defaultConfig: RackStructureComponentConfig = { + // 기본 제한 + maxConditions: 10, + maxRows: 99, + maxLevels: 20, + + // 기본 코드 패턴 + codePattern: "{warehouseCode}-{floor}{zone}-{row:02d}-{level}", + namePattern: "{zone}구역-{row:02d}열-{level}단", + + // UI 설정 + showTemplates: true, + showPreview: true, + showStatistics: true, + readonly: false, + + // 초기 조건 없음 + initialConditions: [], +}; + + diff --git a/frontend/lib/registry/components/rack-structure/index.ts b/frontend/lib/registry/components/rack-structure/index.ts new file mode 100644 index 00000000..a84cc4c6 --- /dev/null +++ b/frontend/lib/registry/components/rack-structure/index.ts @@ -0,0 +1,74 @@ +"use client"; + +import React from "react"; +import { createComponentDefinition } from "../../utils/createComponentDefinition"; +import { ComponentCategory } from "@/types/component"; +import { RackStructureWrapper } from "./RackStructureComponent"; +import { RackStructureConfigPanel } from "./RackStructureConfigPanel"; +import { defaultConfig } from "./config"; + +/** + * 렉 구조 컴포넌트 정의 + * 창고 렉 위치를 일괄 생성하기 위한 구조 설정 컴포넌트 + */ +export const RackStructureDefinition = createComponentDefinition({ + id: "rack-structure", + name: "렉 구조 설정", + nameEng: "Rack Structure Config", + description: "창고 렉 위치를 열 범위와 단 수로 일괄 생성하는 컴포넌트", + category: ComponentCategory.INPUT, + webType: "component", + component: RackStructureWrapper, + defaultConfig: defaultConfig, + defaultSize: { + width: 1200, + height: 800, + gridColumnSpan: "12", + }, + configPanel: RackStructureConfigPanel, + icon: "LayoutGrid", + tags: ["창고", "렉", "위치", "구조", "일괄생성", "WMS"], + version: "1.0.0", + author: "개발팀", + documentation: ` +창고 렉 위치를 일괄 생성하기 위한 구조 설정 컴포넌트입니다. + +## 주요 기능 +- 조건별 열 범위 및 단 수 설정 +- 자동 위치 코드/이름 생성 +- 미리보기 및 통계 표시 +- 템플릿 저장/불러오기 + +## 사용 방법 +1. 상위 폼에서 창고, 층, 구역 정보 선택 +2. 조건 추가 버튼으로 렉 라인 조건 생성 +3. 각 조건의 열 범위와 단 수 입력 +4. 미리보기 생성으로 결과 확인 +5. 저장 시 생성된 위치 데이터가 함께 저장됨 + +## 컨텍스트 데이터 +formData에서 다음 필드를 자동으로 읽어옵니다: +- warehouse_id / warehouseId: 창고 ID +- warehouse_code / warehouseCode: 창고 코드 +- floor: 층 +- zone: 구역 +- location_type / locationType: 위치 유형 +- status: 사용 여부 + `, +}); + +// 타입 내보내기 +export type { + RackStructureComponentConfig, + RackStructureContext, + RackLineCondition, + RackStructureTemplate, + GeneratedLocation, +} from "./types"; + +// 컴포넌트 내보내기 +export { RackStructureComponent, RackStructureWrapper } from "./RackStructureComponent"; +export { RackStructureRenderer } from "./RackStructureRenderer"; +export { RackStructureConfigPanel } from "./RackStructureConfigPanel"; + + diff --git a/frontend/lib/registry/components/rack-structure/types.ts b/frontend/lib/registry/components/rack-structure/types.ts new file mode 100644 index 00000000..485a2208 --- /dev/null +++ b/frontend/lib/registry/components/rack-structure/types.ts @@ -0,0 +1,91 @@ +/** + * 렉 구조 컴포넌트 타입 정의 + */ + +// 렉 라인 조건 (열 범위 + 단 수) +export interface RackLineCondition { + id: string; + startRow: number; // 시작 열 + endRow: number; // 종료 열 + levels: number; // 단 수 +} + +// 렉 구조 템플릿 +export interface RackStructureTemplate { + id: string; + name: string; + conditions: RackLineCondition[]; + createdAt?: string; +} + +// 생성될 위치 데이터 +export interface GeneratedLocation { + rowNum: number; // 열 번호 + levelNum: number; // 단 번호 + locationCode: string; // 위치 코드 (예: WH001-1A-01-1) + locationName: string; // 위치명 (예: A구역-01열-1단) + locationType?: string; // 위치 유형 + status?: string; // 사용 여부 + // 추가 필드 (상위 폼에서 매핑된 값) + warehouseCode?: string; + floor?: string; + zone?: string; +} + +// 필드 매핑 설정 (상위 폼의 어떤 필드를 사용할지) +export interface FieldMapping { + warehouseCodeField?: string; // 창고 코드로 사용할 폼 필드명 + warehouseNameField?: string; // 창고명으로 사용할 폼 필드명 + floorField?: string; // 층으로 사용할 폼 필드명 + zoneField?: string; // 구역으로 사용할 폼 필드명 + locationTypeField?: string; // 위치 유형으로 사용할 폼 필드명 + statusField?: string; // 사용 여부로 사용할 폼 필드명 +} + +// 컴포넌트 설정 +export interface RackStructureComponentConfig { + // 기본 설정 + maxConditions?: number; // 최대 조건 수 (기본: 10) + maxRows?: number; // 최대 열 수 (기본: 99) + maxLevels?: number; // 최대 단 수 (기본: 20) + + // 필드 매핑 (상위 폼의 필드와 연결) + fieldMapping?: FieldMapping; + + // 위치 코드 생성 규칙 + codePattern?: string; // 코드 패턴 (예: "{warehouse}-{floor}{zone}-{row:02d}-{level}") + namePattern?: string; // 이름 패턴 (예: "{zone}구역-{row:02d}열-{level}단") + + // UI 설정 + showTemplates?: boolean; // 템플릿 기능 표시 + showPreview?: boolean; // 미리보기 표시 + showStatistics?: boolean; // 통계 카드 표시 + readonly?: boolean; // 읽기 전용 + + // 초기값 + initialConditions?: RackLineCondition[]; +} + +// 상위 폼에서 전달받는 컨텍스트 데이터 +export interface RackStructureContext { + warehouseId?: string; // 창고 ID + warehouseCode?: string; // 창고 코드 (예: WH001) + warehouseName?: string; // 창고명 (예: 제1창고) + floor?: string; // 층 (예: 1) + zone?: string; // 구역 (예: A) + locationType?: string; // 위치 유형 (예: 선반) + status?: string; // 사용 여부 (예: 사용) +} + +// 컴포넌트 Props +export interface RackStructureComponentProps { + config: RackStructureComponentConfig; + context?: RackStructureContext; + formData?: Record; // 상위 폼 데이터 (필드 매핑에 사용) + onChange?: (locations: GeneratedLocation[]) => void; + onConditionsChange?: (conditions: RackLineCondition[]) => void; + isPreview?: boolean; + tableName?: string; +} + + diff --git a/화면_임베딩_및_데이터_전달_시스템_구현_계획서.md b/화면_임베딩_및_데이터_전달_시스템_구현_계획서.md index 313a7567..29da36f1 100644 --- a/화면_임베딩_및_데이터_전달_시스템_구현_계획서.md +++ b/화면_임베딩_및_데이터_전달_시스템_구현_계획서.md @@ -1682,3 +1682,4 @@ const 출고등록_설정: ScreenSplitPanel = { + diff --git a/화면_임베딩_시스템_Phase1-4_구현_완료.md b/화면_임베딩_시스템_Phase1-4_구현_완료.md index 373b6ec7..2f382cb3 100644 --- a/화면_임베딩_시스템_Phase1-4_구현_완료.md +++ b/화면_임베딩_시스템_Phase1-4_구현_완료.md @@ -529,3 +529,4 @@ const { data: config } = await getScreenSplitPanel(screenId); + diff --git a/화면_임베딩_시스템_충돌_분석_보고서.md b/화면_임베딩_시스템_충돌_분석_보고서.md index 5d315706..8e4cdbd2 100644 --- a/화면_임베딩_시스템_충돌_분석_보고서.md +++ b/화면_임베딩_시스템_충돌_분석_보고서.md @@ -516,3 +516,4 @@ function ScreenViewPage() { + From ec65ad6b9e5fc7e8b5f37ac08a8a60bc2fdfd581 Mon Sep 17 00:00:00 2001 From: kjs Date: Mon, 8 Dec 2025 15:50:58 +0900 Subject: [PATCH 09/18] =?UTF-8?q?=EB=8D=B0=EC=9D=B4=ED=84=B0=EC=A0=84?= =?UTF-8?q?=EB=8B=AC=20=EB=AA=A8=EB=8B=AC=EC=97=B4=EA=B8=B0=20=EC=95=A1?= =?UTF-8?q?=EC=85=98=EC=97=90=20=EC=BB=AC=EB=9F=BC=20=EB=A7=A4=ED=95=91?= =?UTF-8?q?=EA=B8=B0=EB=8A=A5=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/components/screen/ScreenDesigner.tsx | 17 ++ .../config-panels/ButtonConfigPanel.tsx | 278 ++++++++++++++++++ .../screen/panels/PropertiesPanel.tsx | 15 +- frontend/lib/utils/buttonActions.ts | 22 +- 4 files changed, 324 insertions(+), 8 deletions(-) diff --git a/frontend/components/screen/ScreenDesigner.tsx b/frontend/components/screen/ScreenDesigner.tsx index 2118bca3..3a440f07 100644 --- a/frontend/components/screen/ScreenDesigner.tsx +++ b/frontend/components/screen/ScreenDesigner.tsx @@ -2239,10 +2239,27 @@ export default function ScreenDesigner({ selectedScreen, onBackToList }: ScreenD calculatedWidth: `${Math.round(widthPercent * 100) / 100}%`, }); + // 🆕 라벨을 기반으로 기본 columnName 생성 (한글 → 스네이크 케이스) + // 예: "창고코드" → "warehouse_code" 또는 그대로 유지 + const generateDefaultColumnName = (label: string): string => { + // 한글 라벨의 경우 그대로 사용 (나중에 사용자가 수정 가능) + // 영문의 경우 스네이크 케이스로 변환 + if (/[가-힣]/.test(label)) { + // 한글이 포함된 경우: 공백을 언더스코어로, 소문자로 변환 + return label.replace(/\s+/g, "_").toLowerCase(); + } + // 영문의 경우: 카멜케이스/파스칼케이스를 스네이크 케이스로 변환 + return label + .replace(/([a-z])([A-Z])/g, "$1_$2") + .replace(/\s+/g, "_") + .toLowerCase(); + }; + const newComponent: ComponentData = { id: generateComponentId(), type: "component", // ✅ 새 컴포넌트 시스템 사용 label: component.name, + columnName: generateDefaultColumnName(component.name), // 🆕 기본 columnName 자동 생성 widgetType: component.webType, componentType: component.id, // 새 컴포넌트 시스템의 ID (DynamicComponentRenderer용) position: snappedPosition, diff --git a/frontend/components/screen/config-panels/ButtonConfigPanel.tsx b/frontend/components/screen/config-panels/ButtonConfigPanel.tsx index 36f420fd..39f32a73 100644 --- a/frontend/components/screen/config-panels/ButtonConfigPanel.tsx +++ b/frontend/components/screen/config-panels/ButtonConfigPanel.tsx @@ -91,6 +91,14 @@ export const ButtonConfigPanel: React.FC = ({ const [mappingSourceSearch, setMappingSourceSearch] = useState>({}); const [mappingTargetSearch, setMappingTargetSearch] = useState>({}); + // 🆕 openModalWithData 전용 필드 매핑 상태 + const [modalSourceColumns, setModalSourceColumns] = useState>([]); + const [modalTargetColumns, setModalTargetColumns] = useState>([]); + const [modalSourcePopoverOpen, setModalSourcePopoverOpen] = useState>({}); + const [modalTargetPopoverOpen, setModalTargetPopoverOpen] = useState>({}); + const [modalSourceSearch, setModalSourceSearch] = useState>({}); + const [modalTargetSearch, setModalTargetSearch] = useState>({}); + // 🎯 플로우 위젯이 화면에 있는지 확인 const hasFlowWidget = useMemo(() => { const found = allComponents.some((comp: any) => { @@ -318,6 +326,88 @@ export const ButtonConfigPanel: React.FC = ({ loadColumns(); }, [config.action?.dataTransfer?.sourceTable, config.action?.dataTransfer?.targetTable]); + // 🆕 openModalWithData 소스/타겟 테이블 컬럼 로드 + useEffect(() => { + const actionType = config.action?.type; + if (actionType !== "openModalWithData") return; + + const loadModalMappingColumns = async () => { + // 소스 테이블: 현재 화면의 분할 패널 또는 테이블에서 감지 + // allComponents에서 split-panel-layout 또는 table-list 찾기 + let sourceTableName: string | null = null; + + for (const comp of allComponents) { + const compType = comp.componentType || (comp as any).componentConfig?.type; + if (compType === "split-panel-layout" || compType === "screen-split-panel") { + // 분할 패널의 좌측 테이블명 + sourceTableName = (comp as any).componentConfig?.leftPanel?.tableName || + (comp as any).componentConfig?.leftTableName; + break; + } + if (compType === "table-list") { + sourceTableName = (comp as any).componentConfig?.tableName; + break; + } + } + + // 소스 테이블 컬럼 로드 + if (sourceTableName) { + try { + const response = await apiClient.get(`/table-management/tables/${sourceTableName}/columns`); + if (response.data.success) { + let columnData = response.data.data; + if (!Array.isArray(columnData) && columnData?.columns) columnData = columnData.columns; + if (!Array.isArray(columnData) && columnData?.data) columnData = columnData.data; + + if (Array.isArray(columnData)) { + const columns = columnData.map((col: any) => ({ + name: col.name || col.columnName, + label: col.displayName || col.label || col.columnLabel || col.name || col.columnName, + })); + setModalSourceColumns(columns); + console.log(`✅ [openModalWithData] 소스 테이블(${sourceTableName}) 컬럼 로드:`, columns.length); + } + } + } catch (error) { + console.error("소스 테이블 컬럼 로드 실패:", error); + } + } + + // 타겟 화면의 테이블 컬럼 로드 + const targetScreenId = config.action?.targetScreenId; + if (targetScreenId) { + try { + // 타겟 화면 정보 가져오기 + const screenResponse = await apiClient.get(`/screen-management/screens/${targetScreenId}`); + if (screenResponse.data.success && screenResponse.data.data) { + const targetTableName = screenResponse.data.data.tableName; + if (targetTableName) { + const columnResponse = await apiClient.get(`/table-management/tables/${targetTableName}/columns`); + if (columnResponse.data.success) { + let columnData = columnResponse.data.data; + if (!Array.isArray(columnData) && columnData?.columns) columnData = columnData.columns; + if (!Array.isArray(columnData) && columnData?.data) columnData = columnData.data; + + if (Array.isArray(columnData)) { + const columns = columnData.map((col: any) => ({ + name: col.name || col.columnName, + label: col.displayName || col.label || col.columnLabel || col.name || col.columnName, + })); + setModalTargetColumns(columns); + console.log(`✅ [openModalWithData] 타겟 테이블(${targetTableName}) 컬럼 로드:`, columns.length); + } + } + } + } + } catch (error) { + console.error("타겟 화면 테이블 컬럼 로드 실패:", error); + } + } + }; + + loadModalMappingColumns(); + }, [config.action?.type, config.action?.targetScreenId, allComponents]); + // 화면 목록 가져오기 (현재 편집 중인 화면의 회사 코드 기준) useEffect(() => { const fetchScreens = async () => { @@ -1024,6 +1114,194 @@ export const ButtonConfigPanel: React.FC = ({ SelectedItemsDetailInput 컴포넌트가 있는 화면을 선택하세요

+ + {/* 🆕 필드 매핑 설정 (소스 컬럼 → 타겟 컬럼) */} +
+
+ + +
+

+ 소스 테이블의 컬럼명이 타겟 화면의 입력 필드 컬럼명과 다를 때 매핑을 설정하세요. +
+ 예: warehouse_code → warehouse_id (분할 패널의 창고코드를 모달의 창고ID에 매핑) +

+ + {/* 컬럼 로드 상태 표시 */} + {modalSourceColumns.length > 0 || modalTargetColumns.length > 0 ? ( +
+ 소스 컬럼: {modalSourceColumns.length}개 / 타겟 컬럼: {modalTargetColumns.length}개 +
+ ) : ( +
+ 분할 패널 또는 테이블 컴포넌트와 대상 화면을 설정하면 컬럼 목록이 로드됩니다. +
+ )} + + {(config.action?.fieldMappings || []).length === 0 ? ( +
+

+ 매핑이 없으면 같은 이름의 컬럼끼리 자동으로 매핑됩니다. +

+
+ ) : ( +
+ {(config.action?.fieldMappings || []).map((mapping: any, index: number) => ( +
+ {/* 소스 필드 선택 (Combobox) */} +
+ setModalSourcePopoverOpen((prev) => ({ ...prev, [index]: open }))} + > + + + + + + setModalSourceSearch((prev) => ({ ...prev, [index]: value }))} + /> + + 컬럼을 찾을 수 없습니다 + + {modalSourceColumns.map((col) => ( + { + const mappings = [...(config.action?.fieldMappings || [])]; + mappings[index] = { ...mappings[index], sourceField: col.name }; + onUpdateProperty("componentConfig.action.fieldMappings", mappings); + setModalSourcePopoverOpen((prev) => ({ ...prev, [index]: false })); + }} + className="text-xs" + > + + {col.label} + {col.label !== col.name && ( + ({col.name}) + )} + + ))} + + + + + +
+ + + + {/* 타겟 필드 선택 (Combobox) */} +
+ setModalTargetPopoverOpen((prev) => ({ ...prev, [index]: open }))} + > + + + + + + setModalTargetSearch((prev) => ({ ...prev, [index]: value }))} + /> + + 컬럼을 찾을 수 없습니다 + + {modalTargetColumns.map((col) => ( + { + const mappings = [...(config.action?.fieldMappings || [])]; + mappings[index] = { ...mappings[index], targetField: col.name }; + onUpdateProperty("componentConfig.action.fieldMappings", mappings); + setModalTargetPopoverOpen((prev) => ({ ...prev, [index]: false })); + }} + className="text-xs" + > + + {col.label} + {col.label !== col.name && ( + ({col.name}) + )} + + ))} + + + + + +
+ + {/* 삭제 버튼 */} + +
+ ))} +
+ )} +
)} diff --git a/frontend/components/screen/panels/PropertiesPanel.tsx b/frontend/components/screen/panels/PropertiesPanel.tsx index ff21ac3e..bb663c74 100644 --- a/frontend/components/screen/panels/PropertiesPanel.tsx +++ b/frontend/components/screen/panels/PropertiesPanel.tsx @@ -584,20 +584,23 @@ const PropertiesPanelComponent: React.FC = ({
- {selectedComponent.type === "widget" && ( + {(selectedComponent.type === "widget" || selectedComponent.type === "component") && ( <>
onUpdateProperty("columnName", e.target.value)} + placeholder="formData에서 사용할 필드명" + className="h-8" + title="분할 패널에서 데이터를 전달받을 때 사용되는 필드명입니다" /> +

+ 분할 패널에서 데이터를 전달받을 때 매핑되는 필드명 +

diff --git a/frontend/lib/utils/buttonActions.ts b/frontend/lib/utils/buttonActions.ts index 7c1545d8..275efbb5 100644 --- a/frontend/lib/utils/buttonActions.ts +++ b/frontend/lib/utils/buttonActions.ts @@ -59,6 +59,7 @@ export interface ButtonActionConfig { popupWidth?: number; popupHeight?: number; dataSourceId?: string; // 🆕 modalDataStore에서 데이터를 가져올 ID (openModalWithData용) + fieldMappings?: Array<{ sourceField: string; targetField: string }>; // 🆕 필드 매핑 (openModalWithData용) // 확인 메시지 confirmMessage?: string; @@ -1548,10 +1549,27 @@ export class ButtonActionExecutor { } // 🆕 부모 화면의 선택된 데이터 가져오기 (excludeFilter에서 사용) - const parentData = dataRegistry[dataSourceId]?.[0]?.originalData || dataRegistry[dataSourceId]?.[0] || {}; + const rawParentData = dataRegistry[dataSourceId]?.[0]?.originalData || dataRegistry[dataSourceId]?.[0] || {}; + + // 🆕 필드 매핑 적용 (소스 컬럼 → 타겟 컬럼) + let parentData = { ...rawParentData }; + if (config.fieldMappings && Array.isArray(config.fieldMappings) && config.fieldMappings.length > 0) { + console.log("🔄 [openModalWithData] 필드 매핑 적용:", config.fieldMappings); + + config.fieldMappings.forEach((mapping: { sourceField: string; targetField: string }) => { + if (mapping.sourceField && mapping.targetField && rawParentData[mapping.sourceField] !== undefined) { + // 타겟 필드에 소스 필드 값 복사 + parentData[mapping.targetField] = rawParentData[mapping.sourceField]; + console.log(` ✅ ${mapping.sourceField} → ${mapping.targetField}: ${rawParentData[mapping.sourceField]}`); + } + }); + } + console.log("📦 [openModalWithData] 부모 데이터 전달:", { dataSourceId, - parentData, + rawParentData, + mappedParentData: parentData, + fieldMappings: config.fieldMappings, }); // 🆕 전역 모달 상태 업데이트를 위한 이벤트 발생 (URL 파라미터 포함) From 5609e6353f6c260d5fc492b998d6577a660d3053 Mon Sep 17 00:00:00 2001 From: kjs Date: Mon, 8 Dec 2025 17:13:14 +0900 Subject: [PATCH 10/18] =?UTF-8?q?=EC=B0=BD=EA=B3=A0=20=EB=A0=89=20?= =?UTF-8?q?=EA=B5=AC=EC=A1=B0=20=EB=93=B1=EB=A1=9D=20=EC=BB=B4=ED=8F=AC?= =?UTF-8?q?=EB=84=8C=ED=8A=B8=20=EC=A4=91=EB=B3=B5=20=EB=B0=A9=EC=A7=80?= =?UTF-8?q?=EA=B8=B0=EB=8A=A5=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tableCategoryValueController.ts | 47 ++ .../src/routes/tableCategoryValueRoutes.ts | 4 + backend-node/src/services/dataService.ts | 44 +- .../src/services/tableCategoryValueService.ts | 64 ++ .../screen/InteractiveScreenViewer.tsx | 33 + frontend/lib/api/tableCategoryValue.ts | 23 + .../rack-structure/RackStructureComponent.tsx | 384 ++++++++++-- .../rack-structure/RackStructureRenderer.tsx | 30 +- .../components/rack-structure/types.ts | 21 +- frontend/lib/utils/buttonActions.ts | 570 +++++++++++++----- 10 files changed, 1027 insertions(+), 193 deletions(-) diff --git a/backend-node/src/controllers/tableCategoryValueController.ts b/backend-node/src/controllers/tableCategoryValueController.ts index 248bb867..75e225e6 100644 --- a/backend-node/src/controllers/tableCategoryValueController.ts +++ b/backend-node/src/controllers/tableCategoryValueController.ts @@ -527,6 +527,53 @@ export const deleteColumnMappingsByColumn = async (req: AuthenticatedRequest, re } }; +/** + * 카테고리 코드로 라벨 조회 + * + * POST /api/table-categories/labels-by-codes + * + * Body: + * - valueCodes: 카테고리 코드 배열 (예: ["CATEGORY_767659DCUF", "CATEGORY_8292565608"]) + * + * Response: + * - { [code]: label } 형태의 매핑 객체 + */ +export const getCategoryLabelsByCodes = async (req: AuthenticatedRequest, res: Response) => { + try { + const companyCode = req.user!.companyCode; + const { valueCodes } = req.body; + + if (!valueCodes || !Array.isArray(valueCodes) || valueCodes.length === 0) { + return res.json({ + success: true, + data: {}, + }); + } + + logger.info("카테고리 코드로 라벨 조회", { + valueCodes, + companyCode, + }); + + const labels = await tableCategoryValueService.getCategoryLabelsByCodes( + valueCodes, + companyCode + ); + + return res.json({ + success: true, + data: labels, + }); + } catch (error: any) { + logger.error(`카테고리 라벨 조회 실패: ${error.message}`); + return res.status(500).json({ + success: false, + message: "카테고리 라벨 조회 중 오류가 발생했습니다", + error: error.message, + }); + } +}; + /** * 2레벨 메뉴 목록 조회 * diff --git a/backend-node/src/routes/tableCategoryValueRoutes.ts b/backend-node/src/routes/tableCategoryValueRoutes.ts index b79aab75..e59d9b9d 100644 --- a/backend-node/src/routes/tableCategoryValueRoutes.ts +++ b/backend-node/src/routes/tableCategoryValueRoutes.ts @@ -13,6 +13,7 @@ import { deleteColumnMapping, deleteColumnMappingsByColumn, getSecondLevelMenus, + getCategoryLabelsByCodes, } from "../controllers/tableCategoryValueController"; import { authenticateToken } from "../middleware/authMiddleware"; @@ -42,6 +43,9 @@ router.post("/values/bulk-delete", bulkDeleteCategoryValues); // 카테고리 값 순서 변경 router.post("/values/reorder", reorderCategoryValues); +// 카테고리 코드로 라벨 조회 +router.post("/labels-by-codes", getCategoryLabelsByCodes); + // ================================================ // 컬럼 매핑 관련 라우트 (논리명 ↔ 물리명) // ================================================ diff --git a/backend-node/src/services/dataService.ts b/backend-node/src/services/dataService.ts index fd85248d..a278eb97 100644 --- a/backend-node/src/services/dataService.ts +++ b/backend-node/src/services/dataService.ts @@ -907,8 +907,27 @@ class DataService { return validation.error!; } - const columns = Object.keys(data); - const values = Object.values(data); + // 🆕 테이블에 존재하는 컬럼만 필터링 (존재하지 않는 컬럼 제외) + const tableColumns = await this.getTableColumnsSimple(tableName); + const validColumnNames = new Set(tableColumns.map((col: any) => col.column_name)); + + const invalidColumns: string[] = []; + const filteredData = Object.fromEntries( + Object.entries(data).filter(([key]) => { + if (validColumnNames.has(key)) { + return true; + } + invalidColumns.push(key); + return false; + }) + ); + + if (invalidColumns.length > 0) { + console.log(`⚠️ [createRecord] 테이블에 없는 컬럼 제외: ${invalidColumns.join(", ")}`); + } + + const columns = Object.keys(filteredData); + const values = Object.values(filteredData); const placeholders = values.map((_, index) => `$${index + 1}`).join(", "); const columnNames = columns.map((col) => `"${col}"`).join(", "); @@ -951,9 +970,28 @@ class DataService { // _relationInfo 추출 (조인 관계 업데이트용) const relationInfo = data._relationInfo; - const cleanData = { ...data }; + let cleanData = { ...data }; delete cleanData._relationInfo; + // 🆕 테이블에 존재하는 컬럼만 필터링 (존재하지 않는 컬럼 제외) + const tableColumns = await this.getTableColumnsSimple(tableName); + const validColumnNames = new Set(tableColumns.map((col: any) => col.column_name)); + + const invalidColumns: string[] = []; + cleanData = Object.fromEntries( + Object.entries(cleanData).filter(([key]) => { + if (validColumnNames.has(key)) { + return true; + } + invalidColumns.push(key); + return false; + }) + ); + + if (invalidColumns.length > 0) { + console.log(`⚠️ [updateRecord] 테이블에 없는 컬럼 제외: ${invalidColumns.join(", ")}`); + } + // Primary Key 컬럼 찾기 const pkResult = await query<{ attname: string }>( `SELECT a.attname diff --git a/backend-node/src/services/tableCategoryValueService.ts b/backend-node/src/services/tableCategoryValueService.ts index b68d5f05..cdf1b838 100644 --- a/backend-node/src/services/tableCategoryValueService.ts +++ b/backend-node/src/services/tableCategoryValueService.ts @@ -1258,6 +1258,70 @@ class TableCategoryValueService { throw error; } } + + /** + * 카테고리 코드로 라벨 조회 + * + * @param valueCodes - 카테고리 코드 배열 + * @param companyCode - 회사 코드 + * @returns { [code]: label } 형태의 매핑 객체 + */ + async getCategoryLabelsByCodes( + valueCodes: string[], + companyCode: string + ): Promise> { + try { + if (!valueCodes || valueCodes.length === 0) { + return {}; + } + + logger.info("카테고리 코드로 라벨 조회", { valueCodes, companyCode }); + + const pool = getPool(); + + // 동적으로 파라미터 플레이스홀더 생성 + const placeholders = valueCodes.map((_, i) => `$${i + 1}`).join(", "); + + let query: string; + let params: any[]; + + if (companyCode === "*") { + // 최고 관리자: 모든 카테고리 값 조회 + query = ` + SELECT value_code, value_label + FROM table_column_category_values + WHERE value_code IN (${placeholders}) + AND is_active = true + `; + params = valueCodes; + } else { + // 일반 회사: 자신의 카테고리 값 + 공통 카테고리 값 조회 + query = ` + SELECT value_code, value_label + FROM table_column_category_values + WHERE value_code IN (${placeholders}) + AND is_active = true + AND (company_code = $${valueCodes.length + 1} OR company_code = '*') + `; + params = [...valueCodes, companyCode]; + } + + const result = await pool.query(query, params); + + // { [code]: label } 형태로 변환 + const labels: Record = {}; + for (const row of result.rows) { + labels[row.value_code] = row.value_label; + } + + logger.info(`카테고리 라벨 ${Object.keys(labels).length}개 조회 완료`, { companyCode }); + + return labels; + } catch (error: any) { + logger.error(`카테고리 코드로 라벨 조회 실패: ${error.message}`, { error }); + throw error; + } + } } export default new TableCategoryValueService(); diff --git a/frontend/components/screen/InteractiveScreenViewer.tsx b/frontend/components/screen/InteractiveScreenViewer.tsx index d9186999..223490e6 100644 --- a/frontend/components/screen/InteractiveScreenViewer.tsx +++ b/frontend/components/screen/InteractiveScreenViewer.tsx @@ -441,6 +441,39 @@ export const InteractiveScreenViewer: React.FC = ( ); } + // 🆕 렉 구조 컴포넌트 처리 + if (comp.type === "component" && componentType === "rack-structure") { + const { RackStructureComponent } = require("@/lib/registry/components/rack-structure/RackStructureComponent"); + const componentConfig = (comp as any).componentConfig || {}; + // config가 중첩되어 있을 수 있음: componentConfig.config 또는 componentConfig 직접 + const rackConfig = componentConfig.config || componentConfig; + + console.log("🏗️ 렉 구조 컴포넌트 렌더링:", { + componentType, + componentConfig, + rackConfig, + fieldMapping: rackConfig.fieldMapping, + formData, + }); + + return ( +
+ { + console.log("📦 렉 구조 위치 데이터 변경:", locations.length, "개"); + // 컴포넌트의 columnName을 키로 사용 + const fieldKey = (comp as any).columnName || "_rackStructureLocations"; + updateFormData(fieldKey, locations); + }} + isPreview={false} + /> +
+ ); + } + const { widgetType, label, placeholder, required, readonly, columnName } = comp; const fieldName = columnName || comp.id; const currentValue = formData[fieldName] || ""; diff --git a/frontend/lib/api/tableCategoryValue.ts b/frontend/lib/api/tableCategoryValue.ts index 3c5380d1..253e66d0 100644 --- a/frontend/lib/api/tableCategoryValue.ts +++ b/frontend/lib/api/tableCategoryValue.ts @@ -167,6 +167,29 @@ export async function reorderCategoryValues(orderedValueIds: number[]) { } } +/** + * 카테고리 코드로 라벨 조회 + * + * @param valueCodes - 카테고리 코드 배열 (예: ["CATEGORY_767659DCUF", "CATEGORY_8292565608"]) + * @returns { [code]: label } 형태의 매핑 객체 + */ +export async function getCategoryLabelsByCodes(valueCodes: string[]) { + try { + if (!valueCodes || valueCodes.length === 0) { + return { success: true, data: {} }; + } + + const response = await apiClient.post<{ + success: boolean; + data: Record; + }>("/table-categories/labels-by-codes", { valueCodes }); + return response.data; + } catch (error: any) { + console.error("카테고리 라벨 조회 실패:", error); + return { success: false, error: error.message, data: {} }; + } +} + // ================================================ // 컬럼 매핑 관련 API (논리명 ↔ 물리명) // ================================================ diff --git a/frontend/lib/registry/components/rack-structure/RackStructureComponent.tsx b/frontend/lib/registry/components/rack-structure/RackStructureComponent.tsx index f49e4462..7ddd6326 100644 --- a/frontend/lib/registry/components/rack-structure/RackStructureComponent.tsx +++ b/frontend/lib/registry/components/rack-structure/RackStructureComponent.tsx @@ -23,6 +23,8 @@ import { import { ScrollArea } from "@/components/ui/scroll-area"; import { Alert, AlertDescription } from "@/components/ui/alert"; import { cn } from "@/lib/utils"; +import { getCategoryLabelsByCodes } from "@/lib/api/tableCategoryValue"; +import { DynamicFormApi } from "@/lib/api/dynamicForm"; import { RackStructureComponentProps, RackLineCondition, @@ -31,6 +33,13 @@ import { RackStructureContext, } from "./types"; +// 기존 위치 데이터 타입 +interface ExistingLocation { + row_num: string; + level_num: string; + location_code: string; +} + // 고유 ID 생성 const generateId = () => `cond_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; @@ -185,6 +194,7 @@ export const RackStructureComponent: React.FC = ({ onChange, onConditionsChange, isPreview = false, + tableName, }) => { // 조건 목록 const [conditions, setConditions] = useState( @@ -200,6 +210,11 @@ export const RackStructureComponent: React.FC = ({ // 미리보기 데이터 const [previewData, setPreviewData] = useState([]); const [isPreviewGenerated, setIsPreviewGenerated] = useState(false); + + // 기존 데이터 중복 체크 관련 상태 + const [existingLocations, setExistingLocations] = useState([]); + const [isCheckingDuplicates, setIsCheckingDuplicates] = useState(false); + const [duplicateErrors, setDuplicateErrors] = useState<{ row: number; existingLevels: number[] }[]>([]); // 설정값 const maxConditions = config.maxConditions || 10; @@ -208,6 +223,60 @@ export const RackStructureComponent: React.FC = ({ const readonly = config.readonly || isPreview; const fieldMapping = config.fieldMapping || {}; + // 카테고리 라벨 캐시 상태 + const [categoryLabels, setCategoryLabels] = useState>({}); + + // 카테고리 코드인지 확인 + const isCategoryCode = (value: string | undefined): boolean => { + return typeof value === "string" && value.startsWith("CATEGORY_"); + }; + + // 카테고리 라벨 조회 (비동기) + useEffect(() => { + const loadCategoryLabels = async () => { + if (!formData) return; + + // 카테고리 코드인 값들만 수집 + const valuesToLookup: string[] = []; + const fieldsToCheck = [ + fieldMapping.floorField ? formData[fieldMapping.floorField] : undefined, + fieldMapping.zoneField ? formData[fieldMapping.zoneField] : undefined, + fieldMapping.locationTypeField ? formData[fieldMapping.locationTypeField] : undefined, + fieldMapping.statusField ? formData[fieldMapping.statusField] : undefined, + ]; + + for (const value of fieldsToCheck) { + if (value && isCategoryCode(value) && !categoryLabels[value]) { + valuesToLookup.push(value); + } + } + + if (valuesToLookup.length === 0) return; + + try { + // 카테고리 코드로 라벨 일괄 조회 + const response = await getCategoryLabelsByCodes(valuesToLookup); + if (response.success && response.data) { + console.log("✅ 카테고리 라벨 조회 완료:", response.data); + setCategoryLabels((prev) => ({ ...prev, ...response.data })); + } + } catch (error) { + console.error("카테고리 라벨 조회 실패:", error); + } + }; + + loadCategoryLabels(); + }, [formData, fieldMapping]); + + // 카테고리 코드를 라벨로 변환하는 헬퍼 함수 + const getCategoryLabel = useCallback((value: string | undefined): string | undefined => { + if (!value) return undefined; + if (isCategoryCode(value)) { + return categoryLabels[value] || value; + } + return value; + }, [categoryLabels]); + // 필드 매핑을 통해 formData에서 컨텍스트 추출 const context: RackStructureContext = useMemo(() => { // propContext가 있으면 우선 사용 @@ -216,27 +285,33 @@ export const RackStructureComponent: React.FC = ({ // formData와 fieldMapping을 사용하여 컨텍스트 생성 if (!formData) return {}; - return { + const rawFloor = fieldMapping.floorField ? formData[fieldMapping.floorField] : undefined; + const rawZone = fieldMapping.zoneField ? formData[fieldMapping.zoneField] : undefined; + const rawLocationType = fieldMapping.locationTypeField ? formData[fieldMapping.locationTypeField] : undefined; + const rawStatus = fieldMapping.statusField ? formData[fieldMapping.statusField] : undefined; + + const ctx = { warehouseCode: fieldMapping.warehouseCodeField ? formData[fieldMapping.warehouseCodeField] : undefined, warehouseName: fieldMapping.warehouseNameField ? formData[fieldMapping.warehouseNameField] : undefined, - floor: fieldMapping.floorField - ? formData[fieldMapping.floorField]?.toString() - : undefined, - zone: fieldMapping.zoneField - ? formData[fieldMapping.zoneField] - : undefined, - locationType: fieldMapping.locationTypeField - ? formData[fieldMapping.locationTypeField] - : undefined, - status: fieldMapping.statusField - ? formData[fieldMapping.statusField] - : undefined, + // 카테고리 값은 라벨로 변환 + floor: getCategoryLabel(rawFloor?.toString()), + zone: getCategoryLabel(rawZone), + locationType: getCategoryLabel(rawLocationType), + status: getCategoryLabel(rawStatus), }; - }, [propContext, formData, fieldMapping]); + + console.log("🏗️ [RackStructure] context 생성:", { + fieldMapping, + rawValues: { rawFloor, rawZone, rawLocationType, rawStatus }, + context: ctx, + }); + + return ctx; + }, [propContext, formData, fieldMapping, getCategoryLabel]); // 필수 필드 검증 const missingFields = useMemo(() => { @@ -283,6 +358,154 @@ export const RackStructureComponent: React.FC = ({ setConditions((prev) => prev.filter((cond) => cond.id !== id)); }, []); + // 열 범위 중복 검사 + const rowOverlapErrors = useMemo(() => { + const errors: { conditionIndex: number; overlappingWith: number; overlappingRows: number[] }[] = []; + + for (let i = 0; i < conditions.length; i++) { + const cond1 = conditions[i]; + if (cond1.startRow <= 0 || cond1.endRow < cond1.startRow) continue; + + for (let j = i + 1; j < conditions.length; j++) { + const cond2 = conditions[j]; + if (cond2.startRow <= 0 || cond2.endRow < cond2.startRow) continue; + + // 범위 겹침 확인 + const overlapStart = Math.max(cond1.startRow, cond2.startRow); + const overlapEnd = Math.min(cond1.endRow, cond2.endRow); + + if (overlapStart <= overlapEnd) { + // 겹치는 열 목록 + const overlappingRows: number[] = []; + for (let r = overlapStart; r <= overlapEnd; r++) { + overlappingRows.push(r); + } + + errors.push({ + conditionIndex: i, + overlappingWith: j, + overlappingRows, + }); + } + } + } + + return errors; + }, [conditions]); + + // 중복 열이 있는지 확인 + const hasRowOverlap = rowOverlapErrors.length > 0; + + // 기존 데이터 조회를 위한 값 추출 (useMemo 객체 참조 문제 방지) + const warehouseCodeForQuery = context.warehouseCode; + const floorForQuery = context.floor; + const zoneForQuery = context.zone; + + // 기존 데이터 조회 (창고/층/구역이 변경될 때마다) + useEffect(() => { + const loadExistingLocations = async () => { + console.log("🏗️ [RackStructure] 기존 데이터 조회 체크:", { + warehouseCode: warehouseCodeForQuery, + floor: floorForQuery, + zone: zoneForQuery, + }); + + // 필수 조건이 충족되지 않으면 기존 데이터 초기화 + if (!warehouseCodeForQuery || !floorForQuery || !zoneForQuery) { + console.log("⚠️ [RackStructure] 필수 조건 미충족 - 조회 스킵"); + setExistingLocations([]); + setDuplicateErrors([]); + return; + } + + setIsCheckingDuplicates(true); + try { + // warehouse_location 테이블에서 해당 창고/층/구역의 기존 데이터 조회 + const filterParams = { + warehouse_id: warehouseCodeForQuery, + floor: floorForQuery, + zone: zoneForQuery, + }; + console.log("🔍 기존 위치 데이터 조회 시작:", filterParams); + + const response = await DynamicFormApi.getTableData("warehouse_location", { + filters: filterParams, + page: 1, + pageSize: 1000, // 충분히 큰 값 + }); + + console.log("🔍 기존 위치 데이터 응답:", response); + + // API 응답 구조: { success: true, data: [...] } 또는 { success: true, data: { data: [...] } } + const dataArray = Array.isArray(response.data) + ? response.data + : (response.data?.data || []); + + if (response.success && dataArray.length > 0) { + const existing = dataArray.map((item: any) => ({ + row_num: item.row_num, + level_num: item.level_num, + location_code: item.location_code, + })); + setExistingLocations(existing); + console.log("✅ 기존 위치 데이터 조회 완료:", existing.length, "개", existing); + } else { + console.log("⚠️ 기존 위치 데이터 없음 또는 조회 실패"); + setExistingLocations([]); + } + } catch (error) { + console.error("기존 위치 데이터 조회 실패:", error); + setExistingLocations([]); + } finally { + setIsCheckingDuplicates(false); + } + }; + + loadExistingLocations(); + }, [warehouseCodeForQuery, floorForQuery, zoneForQuery]); + + // 조건 변경 시 기존 데이터와 중복 체크 + useEffect(() => { + if (existingLocations.length === 0) { + setDuplicateErrors([]); + return; + } + + // 현재 조건에서 생성될 열 목록 + const plannedRows = new Map(); // row -> levels + conditions.forEach((cond) => { + if (cond.startRow > 0 && cond.endRow >= cond.startRow && cond.levels > 0) { + for (let row = cond.startRow; row <= cond.endRow; row++) { + const levels: number[] = []; + for (let level = 1; level <= cond.levels; level++) { + levels.push(level); + } + plannedRows.set(row, levels); + } + } + }); + + // 기존 데이터와 중복 체크 + const errors: { row: number; existingLevels: number[] }[] = []; + plannedRows.forEach((levels, row) => { + const existingForRow = existingLocations.filter( + (loc) => parseInt(loc.row_num) === row + ); + if (existingForRow.length > 0) { + const existingLevels = existingForRow.map((loc) => parseInt(loc.level_num)); + const duplicateLevels = levels.filter((l) => existingLevels.includes(l)); + if (duplicateLevels.length > 0) { + errors.push({ row, existingLevels: duplicateLevels }); + } + } + }); + + setDuplicateErrors(errors); + }, [conditions, existingLocations]); + + // 기존 데이터와 중복이 있는지 확인 + const hasDuplicateWithExisting = duplicateErrors.length > 0; + // 통계 계산 const statistics = useMemo(() => { let totalLocations = 0; @@ -312,11 +535,12 @@ export const RackStructureComponent: React.FC = ({ const floor = context?.floor || "1"; const zone = context?.zone || "A"; - // 코드 생성 (예: WH001-1A-01-1) + // 코드 생성 (예: WH001-1층D구역-01-1) const code = `${warehouseCode}-${floor}${zone}-${row.toString().padStart(2, "0")}-${level}`; - // 이름 생성 (예: A구역-01열-1단) - const name = `${zone}구역-${row.toString().padStart(2, "0")}열-${level}단`; + // 이름 생성 - zone에 이미 "구역"이 포함되어 있으면 그대로 사용 + const zoneName = zone.includes("구역") ? zone : `${zone}구역`; + const name = `${zoneName}-${row.toString().padStart(2, "0")}열-${level}단`; return { code, name }; }, @@ -325,12 +549,39 @@ export const RackStructureComponent: React.FC = ({ // 미리보기 생성 const generatePreview = useCallback(() => { + console.log("🔍 [generatePreview] 검증 시작:", { + missingFields, + hasRowOverlap, + hasDuplicateWithExisting, + duplicateErrorsCount: duplicateErrors.length, + existingLocationsCount: existingLocations.length, + }); + // 필수 필드 검증 if (missingFields.length > 0) { alert(`다음 필드를 먼저 입력해주세요: ${missingFields.join(", ")}`); return; } + // 열 범위 중복 검증 + if (hasRowOverlap) { + const overlapInfo = rowOverlapErrors.map((err) => { + const rows = err.overlappingRows.join(", "); + return `조건 ${err.conditionIndex + 1}과 조건 ${err.overlappingWith + 1}의 ${rows}열`; + }).join("\n"); + alert(`열 범위가 중복됩니다:\n${overlapInfo}\n\n중복된 열을 수정해주세요.`); + return; + } + + // 기존 데이터와 중복 검증 - duplicateErrors 직접 체크 + if (duplicateErrors.length > 0) { + const duplicateInfo = duplicateErrors.map((err) => { + return `${err.row}열 ${err.existingLevels.join(", ")}단`; + }).join(", "); + alert(`이미 등록된 위치가 있습니다:\n${duplicateInfo}\n\n해당 열/단을 제외하고 등록하거나, 기존 데이터를 삭제해주세요.`); + return; + } + const locations: GeneratedLocation[] = []; conditions.forEach((cond) => { @@ -338,15 +589,17 @@ export const RackStructureComponent: React.FC = ({ for (let row = cond.startRow; row <= cond.endRow; row++) { for (let level = 1; level <= cond.levels; level++) { const { code, name } = generateLocationCode(row, level); + // 테이블 컬럼명과 동일하게 생성 locations.push({ - rowNum: row, - levelNum: level, - locationCode: code, - locationName: name, - locationType: context?.locationType || "선반", + row_num: String(row), + level_num: String(level), + location_code: code, + location_name: name, + location_type: context?.locationType || "선반", status: context?.status || "사용", - // 추가 필드 - warehouseCode: context?.warehouseCode, + // 추가 필드 (테이블 컬럼명과 동일) + warehouse_id: context?.warehouseCode, + warehouse_name: context?.warehouseName, floor: context?.floor, zone: context?.zone, }); @@ -357,14 +610,14 @@ export const RackStructureComponent: React.FC = ({ // 정렬: 열 -> 단 순서 locations.sort((a, b) => { - if (a.rowNum !== b.rowNum) return a.rowNum - b.rowNum; - return a.levelNum - b.levelNum; + if (a.row_num !== b.row_num) return parseInt(a.row_num) - parseInt(b.row_num); + return parseInt(a.level_num) - parseInt(b.level_num); }); setPreviewData(locations); setIsPreviewGenerated(true); onChange?.(locations); - }, [conditions, context, generateLocationCode, onChange, missingFields]); + }, [conditions, context, generateLocationCode, onChange, missingFields, hasRowOverlap, duplicateErrors, existingLocations, rowOverlapErrors]); // 템플릿 저장 const saveTemplate = useCallback(() => { @@ -448,6 +701,66 @@ export const RackStructureComponent: React.FC = ({ )} + {/* 열 범위 중복 경고 */} + {hasRowOverlap && ( + + + + 열 범위가 중복됩니다! +
    + {rowOverlapErrors.map((err, idx) => ( +
  • + 조건 {err.conditionIndex + 1}과 조건 {err.overlappingWith + 1}: {err.overlappingRows.join(", ")}열 중복 +
  • + ))} +
+ + 중복된 열 범위를 수정해주세요. + +
+
+ )} + + {/* 기존 데이터 중복 경고 */} + {hasDuplicateWithExisting && ( + + + + 이미 등록된 위치가 있습니다! +
    + {duplicateErrors.map((err, idx) => ( +
  • + {err.row}열: {err.existingLevels.join(", ")}단 (이미 등록됨) +
  • + ))} +
+ + 해당 열/단을 제외하거나 기존 데이터를 삭제해주세요. + +
+
+ )} + + {/* 기존 데이터 로딩 중 표시 */} + {isCheckingDuplicates && ( + + + + 기존 위치 데이터를 확인하는 중... + + + )} + + {/* 기존 데이터 존재 알림 */} + {!isCheckingDuplicates && existingLocations.length > 0 && !hasDuplicateWithExisting && ( + + + + 해당 창고/층/구역에 {existingLocations.length}개의 위치가 이미 등록되어 있습니다. + + + )} + {/* 현재 매핑된 값 표시 */} {(context.warehouseCode || context.warehouseName || context.floor || context.zone) && (
@@ -548,10 +861,11 @@ export const RackStructureComponent: React.FC = ({ variant="outline" size="sm" onClick={generatePreview} + disabled={hasDuplicateWithExisting || hasRowOverlap || missingFields.length > 0 || isCheckingDuplicates} className="h-8 gap-1" > - 미리보기 생성 + {isCheckingDuplicates ? "확인 중..." : hasDuplicateWithExisting ? "중복 있음" : "미리보기 생성"} @@ -595,15 +909,15 @@ export const RackStructureComponent: React.FC = ({ {previewData.map((loc, idx) => ( {idx + 1} - {loc.locationCode} - {loc.locationName} - {context?.floor || "1"} - {context?.zone || "A"} + {loc.location_code} + {loc.location_name} + {loc.floor || context?.floor || "1"} + {loc.zone || context?.zone || "A"} - {loc.rowNum.toString().padStart(2, "0")} + {loc.row_num.padStart(2, "0")} - {loc.levelNum} - {loc.locationType} + {loc.level_num} + {loc.location_type} - ))} diff --git a/frontend/lib/registry/components/rack-structure/RackStructureRenderer.tsx b/frontend/lib/registry/components/rack-structure/RackStructureRenderer.tsx index ab832f51..e33658b5 100644 --- a/frontend/lib/registry/components/rack-structure/RackStructureRenderer.tsx +++ b/frontend/lib/registry/components/rack-structure/RackStructureRenderer.tsx @@ -14,24 +14,40 @@ export class RackStructureRenderer extends AutoRegisteringComponentRenderer { static componentDefinition = RackStructureDefinition; render(): React.ReactElement { - const { formData, isPreview, config } = this.props as any; + const { formData, isPreview, config, tableName, onFormDataChange } = this.props as Record; return ( } + tableName={tableName as string} + onChange={(locations) => + this.handleLocationsChange( + locations, + onFormDataChange as ((fieldName: string, value: unknown) => void) | undefined, + ) + } + isPreview={isPreview as boolean} /> ); } /** * 생성된 위치 데이터 변경 핸들러 + * formData에 _rackStructureLocations 키로 저장하여 저장 액션에서 감지 */ - protected handleLocationsChange = (locations: GeneratedLocation[]) => { - // 생성된 위치 데이터를 formData에 저장 + protected handleLocationsChange = ( + locations: GeneratedLocation[], + onFormDataChange?: (fieldName: string, value: unknown) => void, + ) => { + // 생성된 위치 데이터를 컴포넌트에 저장 this.updateComponent({ generatedLocations: locations }); + + // formData에도 저장하여 저장 액션에서 감지할 수 있도록 함 + if (onFormDataChange) { + console.log("📦 [RackStructure] 미리보기 데이터를 formData에 저장:", locations.length, "개"); + onFormDataChange("_rackStructureLocations", locations); + } }; } diff --git a/frontend/lib/registry/components/rack-structure/types.ts b/frontend/lib/registry/components/rack-structure/types.ts index 485a2208..5ab7bd7e 100644 --- a/frontend/lib/registry/components/rack-structure/types.ts +++ b/frontend/lib/registry/components/rack-structure/types.ts @@ -18,18 +18,19 @@ export interface RackStructureTemplate { createdAt?: string; } -// 생성될 위치 데이터 +// 생성될 위치 데이터 (테이블 컬럼명과 동일하게 매핑) export interface GeneratedLocation { - rowNum: number; // 열 번호 - levelNum: number; // 단 번호 - locationCode: string; // 위치 코드 (예: WH001-1A-01-1) - locationName: string; // 위치명 (예: A구역-01열-1단) - locationType?: string; // 위치 유형 - status?: string; // 사용 여부 + row_num: string; // 열 번호 (varchar) + level_num: string; // 단 번호 (varchar) + location_code: string; // 위치 코드 (예: WH001-1A-01-1) + location_name: string; // 위치명 (예: A구역-01열-1단) + location_type?: string; // 위치 유형 + status?: string; // 사용 여부 // 추가 필드 (상위 폼에서 매핑된 값) - warehouseCode?: string; - floor?: string; - zone?: string; + warehouse_id?: string; // 창고 ID/코드 + warehouse_name?: string; // 창고명 + floor?: string; // 층 + zone?: string; // 구역 } // 필드 매핑 설정 (상위 폼의 어떤 필드를 사용할지) diff --git a/frontend/lib/utils/buttonActions.ts b/frontend/lib/utils/buttonActions.ts index 275efbb5..c5e86849 100644 --- a/frontend/lib/utils/buttonActions.ts +++ b/frontend/lib/utils/buttonActions.ts @@ -114,7 +114,7 @@ export interface ButtonActionConfig { geolocationExtraValue?: string | number | boolean; // 추가로 변경할 값 (예: "active") geolocationExtraKeyField?: string; // 다른 테이블의 키 필드 (예: "vehicle_id") geolocationExtraKeySourceField?: string; // 현재 폼에서 키 값을 가져올 필드 (예: "vehicle_id") - + // 🆕 두 번째 테이블 설정 (위치정보 + 상태변경을 각각 다른 테이블에) geolocationSecondTableEnabled?: boolean; // 두 번째 테이블 사용 여부 geolocationSecondTableName?: string; // 두 번째 테이블명 (예: "vehicles") @@ -152,7 +152,7 @@ export interface ButtonActionConfig { updateTableName?: string; // 대상 테이블명 (다른 테이블 UPDATE 시) updateKeyField?: string; // 키 필드명 (WHERE 조건에 사용) updateKeySourceField?: string; // 키 값 소스 (폼 필드명 또는 __userId__ 등 특수 키워드) - + // 🆕 필드 값 변경 + 위치정보 수집 (update_field 액션에서 사용) updateWithGeolocation?: boolean; // 위치정보도 함께 수집할지 여부 updateGeolocationLatField?: string; // 위도 저장 필드 @@ -262,7 +262,7 @@ export interface ButtonActionContext { // 🆕 컴포넌트별 설정 (parentDataMapping 등) componentConfigs?: Record; // 컴포넌트 ID → 컴포넌트 설정 - + // 🆕 분할 패널 부모 데이터 (좌측 화면에서 선택된 데이터) splitPanelParentData?: Record; } @@ -276,10 +276,7 @@ export interface ButtonActionContext { * - __screenId__ : 현재 화면 ID * - __tableName__ : 현재 테이블명 */ -export function resolveSpecialKeyword( - sourceField: string | undefined, - context: ButtonActionContext -): any { +export function resolveSpecialKeyword(sourceField: string | undefined, context: ButtonActionContext): any { if (!sourceField) return undefined; // 특수 키워드 처리 @@ -416,6 +413,81 @@ export class ButtonActionExecutor { console.log("📦 [handleSave] beforeFormSave 이벤트 후 formData:", context.formData); + // 🆕 렉 구조 컴포넌트 일괄 저장 감지 + let rackStructureLocations: any[] | undefined; + let rackStructureFieldKey = "_rackStructureLocations"; + let hasEmptyRackStructureField = false; + + // formData에서 렉 구조 데이터 또는 빈 배열 찾기 + for (const [key, value] of Object.entries(context.formData || {})) { + // 배열인 경우만 체크 + if (Array.isArray(value)) { + if (value.length > 0 && value[0]) { + const firstItem = value[0]; + const isNewFormat = + firstItem.location_code && + firstItem.location_name && + firstItem.row_num !== undefined && + firstItem.level_num !== undefined; + const isOldFormat = + firstItem.locationCode && + firstItem.locationName && + firstItem.rowNum !== undefined && + firstItem.levelNum !== undefined; + + if (isNewFormat || isOldFormat) { + console.log("🏗️ [handleSave] 렉 구조 데이터 감지 - 필드:", key); + rackStructureLocations = value; + rackStructureFieldKey = key; + break; + } + } else if (value.length === 0 && key.startsWith("comp_")) { + // comp_로 시작하는 빈 배열은 렉 구조 컴포넌트일 가능성 있음 + // allComponents에서 확인 + const rackStructureComponentInLayout = context.allComponents?.find( + (comp: any) => + comp.type === "component" && comp.componentId === "rack-structure" && comp.columnName === key, + ); + if (rackStructureComponentInLayout) { + console.log("🏗️ [handleSave] 렉 구조 컴포넌트 감지 (미리보기 없음) - 필드:", key); + hasEmptyRackStructureField = true; + rackStructureFieldKey = key; + } + } + } + } + + // 렉 구조 컴포넌트가 있지만 미리보기 데이터가 없는 경우 + if (hasEmptyRackStructureField && (!rackStructureLocations || rackStructureLocations.length === 0)) { + alert("미리보기를 먼저 생성해주세요.\n\n렉 구조 조건을 설정한 후 '미리보기 생성' 버튼을 클릭하세요."); + return false; + } + + // 🆕 렉 구조 등록 화면 감지 (warehouse_location 테이블 + floor/zone 필드 있음 + 렉 구조 데이터 없음) + // 이 경우 일반 저장을 차단하고 미리보기 생성을 요구 + const isRackStructureScreen = + context.tableName === "warehouse_location" && + context.formData?.floor && + context.formData?.zone && + !rackStructureLocations; + + if (isRackStructureScreen) { + console.log("🏗️ [handleSave] 렉 구조 등록 화면 감지 - 미리보기 데이터 없음"); + alert( + "렉 구조 등록 화면입니다.\n\n" + + "미리보기를 먼저 생성해주세요.\n" + + "- 중복된 위치가 있으면 미리보기가 생성되지 않습니다.\n" + + "- 기존 데이터를 삭제하거나 다른 열/단을 선택해주세요.", + ); + return false; + } + + // 렉 구조 데이터가 있으면 일괄 저장 + if (rackStructureLocations && rackStructureLocations.length > 0) { + console.log("🏗️ [handleSave] 렉 구조 컴포넌트 감지 - 일괄 저장 시작:", rackStructureLocations.length, "개"); + return await this.handleRackStructureBatchSave(config, context, rackStructureLocations, rackStructureFieldKey); + } + // 🆕 SelectedItemsDetailInput 배치 저장 처리 (fieldGroups 구조) console.log("🔍 [handleSave] formData 구조 확인:", { isFormDataArray: Array.isArray(context.formData), @@ -585,12 +657,12 @@ export class ButtonActionExecutor { if (Object.keys(fieldsWithNumbering).length > 0) { console.log("🎯 채번 규칙 할당 시작 (allocateCode 호출)"); const { allocateNumberingCode } = await import("@/lib/api/numberingRule"); - + for (const [fieldName, ruleId] of Object.entries(fieldsWithNumbering)) { try { console.log(`🔄 ${fieldName} 필드에 대해 allocateCode 호출: ${ruleId}`); const allocateResult = await allocateNumberingCode(ruleId); - + if (allocateResult.success && allocateResult.data?.generatedCode) { const newCode = allocateResult.data.generatedCode; console.log(`✅ ${fieldName} 새 코드 할당: ${formData[fieldName]} → ${newCode}`); @@ -691,8 +763,8 @@ export class ButtonActionExecutor { } // 🆕 v3.9: RepeatScreenModal의 외부 테이블 데이터 저장 처리 - const repeatScreenModalKeys = Object.keys(context.formData).filter((key) => - key.startsWith("_repeatScreenModal_") && key !== "_repeatScreenModal_aggregations" + const repeatScreenModalKeys = Object.keys(context.formData).filter( + (key) => key.startsWith("_repeatScreenModal_") && key !== "_repeatScreenModal_aggregations", ); // RepeatScreenModal 데이터가 있으면 해당 테이블에 대한 메인 저장은 건너뜀 @@ -749,7 +821,7 @@ export class ButtonActionExecutor { console.log(`📝 [handleSave] ${targetTable} INSERT:`, dataWithMeta); const insertResult = await apiClient.post( `/table-management/tables/${targetTable}/add`, - dataWithMeta + dataWithMeta, ); console.log(`✅ [handleSave] ${targetTable} INSERT 완료:`, insertResult.data); } else if (id) { @@ -757,10 +829,10 @@ export class ButtonActionExecutor { const originalData = { id }; const updatedData = { ...dataWithMeta, id }; console.log(`📝 [handleSave] ${targetTable} UPDATE:`, { originalData, updatedData }); - const updateResult = await apiClient.put( - `/table-management/tables/${targetTable}/edit`, - { originalData, updatedData } - ); + const updateResult = await apiClient.put(`/table-management/tables/${targetTable}/edit`, { + originalData, + updatedData, + }); console.log(`✅ [handleSave] ${targetTable} UPDATE 완료:`, updateResult.data); } } catch (error: any) { @@ -794,12 +866,14 @@ export class ButtonActionExecutor { [joinKey.targetField]: sourceValue, }; - console.log(`📊 [handleSave] ${targetTable}.${targetColumn} = ${aggregatedValue} (조인: ${joinKey.sourceField} = ${sourceValue})`); - - const updateResult = await apiClient.put( - `/table-management/tables/${targetTable}/edit`, - { originalData, updatedData } + console.log( + `📊 [handleSave] ${targetTable}.${targetColumn} = ${aggregatedValue} (조인: ${joinKey.sourceField} = ${sourceValue})`, ); + + const updateResult = await apiClient.put(`/table-management/tables/${targetTable}/edit`, { + originalData, + updatedData, + }); console.log(`✅ [handleSave] ${targetTable} 집계 저장 완료:`, updateResult.data); } catch (error: any) { console.error(`❌ [handleSave] ${targetTable} 집계 저장 실패:`, error.response?.data || error.message); @@ -856,7 +930,7 @@ export class ButtonActionExecutor { // 복합키인 경우 로그 출력 if (primaryKeys.length > 1) { - console.log(`🔗 복합 기본키 감지:`, primaryKeys); + console.log("🔗 복합 기본키 감지:", primaryKeys); console.log(`📍 첫 번째 키 (${primaryKeyColumn}) 값을 사용: ${value}`); } @@ -908,6 +982,184 @@ export class ButtonActionExecutor { return await this.handleSave(config, context); } + /** + * 🆕 렉 구조 컴포넌트 일괄 저장 처리 + * 미리보기에서 생성된 위치 데이터를 일괄 INSERT + */ + private static async handleRackStructureBatchSave( + config: ButtonActionConfig, + context: ButtonActionContext, + locations: any[], + rackStructureFieldKey: string = "_rackStructureLocations", + ): Promise { + const { tableName, screenId, userId, companyCode } = context; + + console.log("🏗️ [handleRackStructureBatchSave] 렉 구조 일괄 저장 시작:", { + locationsCount: locations.length, + tableName, + screenId, + rackStructureFieldKey, + }); + + if (!tableName) { + throw new Error("테이블명이 지정되지 않았습니다."); + } + + if (locations.length === 0) { + throw new Error("저장할 위치 데이터가 없습니다. 먼저 미리보기를 생성해주세요."); + } + + console.log("🏗️ [handleRackStructureBatchSave] 렉 구조 데이터 예시:", locations[0]); + + // 저장 전 중복 체크 + const firstLocation = locations[0]; + const warehouseId = firstLocation.warehouse_id || firstLocation.warehouseCode; + const floor = firstLocation.floor; + const zone = firstLocation.zone; + + if (warehouseId && floor && zone) { + console.log("🔍 [handleRackStructureBatchSave] 기존 데이터 중복 체크:", { warehouseId, floor, zone }); + + try { + const existingResponse = await DynamicFormApi.getTableData(tableName, { + filters: { + warehouse_id: warehouseId, + floor: floor, + zone: zone, + }, + page: 1, + pageSize: 1000, + }); + + // API 응답 구조에 따라 데이터 추출 + const responseData = existingResponse.data as any; + const existingData = responseData?.data || responseData || []; + + if (Array.isArray(existingData) && existingData.length > 0) { + // 중복되는 위치 확인 + const existingSet = new Set(existingData.map((loc: any) => `${loc.row_num}-${loc.level_num}`)); + + const duplicates = locations.filter((loc) => { + const key = `${loc.row_num || loc.rowNum}-${loc.level_num || loc.levelNum}`; + return existingSet.has(key); + }); + + if (duplicates.length > 0) { + const duplicateInfo = duplicates + .slice(0, 5) + .map((d) => `${d.row_num || d.rowNum}열 ${d.level_num || d.levelNum}단`) + .join(", "); + + const moreCount = duplicates.length > 5 ? ` 외 ${duplicates.length - 5}개` : ""; + + alert( + `이미 등록된 위치가 있습니다!\n\n중복 위치: ${duplicateInfo}${moreCount}\n\n해당 위치를 제외하거나 기존 데이터를 삭제해주세요.`, + ); + return false; + } + } + } catch (checkError) { + console.warn("⚠️ [handleRackStructureBatchSave] 중복 체크 실패 (저장 계속 진행):", checkError); + } + } + + // 각 위치 데이터를 그대로 저장 (렉 구조 컴포넌트에서 이미 테이블 컬럼명으로 생성됨) + const recordsToInsert = locations.map((loc) => { + // 렉 구조 컴포넌트에서 생성된 데이터를 그대로 사용 + // 새로운 형식(스네이크 케이스)과 기존 형식(카멜 케이스) 모두 지원 + const record: Record = { + // 렉 구조에서 생성된 필드 (이미 테이블 컬럼명과 동일) + location_code: loc.location_code || loc.locationCode, + location_name: loc.location_name || loc.locationName, + row_num: loc.row_num || String(loc.rowNum), + level_num: loc.level_num || String(loc.levelNum), + // 창고 정보 (렉 구조 컴포넌트에서 전달) + warehouse_id: loc.warehouse_id || loc.warehouseCode, + warehouse_name: loc.warehouse_name || loc.warehouseName, + // 위치 정보 (렉 구조 컴포넌트에서 전달) + floor: loc.floor, + zone: loc.zone, + location_type: loc.location_type || loc.locationType, + status: loc.status || "사용", + // 사용자 정보 추가 + writer: userId, + company_code: companyCode, + }; + + return record; + }); + + console.log("🏗️ [handleRackStructureBatchSave] 저장할 레코드 수:", recordsToInsert.length); + console.log("🏗️ [handleRackStructureBatchSave] 첫 번째 레코드 예시:", recordsToInsert[0]); + + // 일괄 INSERT 실행 + try { + let successCount = 0; + let errorCount = 0; + const errors: string[] = []; + + for (let i = 0; i < recordsToInsert.length; i++) { + const record = recordsToInsert[i]; + try { + console.log(`🏗️ [handleRackStructureBatchSave] 저장 중 (${i + 1}/${recordsToInsert.length}):`, record); + + const result = await DynamicFormApi.saveFormData({ + screenId, + tableName, + data: record, + }); + + console.log(`🏗️ [handleRackStructureBatchSave] API 응답 (${i + 1}):`, result); + + if (result.success) { + successCount++; + } else { + errorCount++; + const errorMsg = result.message || result.error || "알 수 없는 오류"; + errors.push(errorMsg); + console.error(`❌ [handleRackStructureBatchSave] 저장 실패 (${i + 1}):`, errorMsg); + } + } catch (error: any) { + errorCount++; + const errorMsg = error.message || "저장 중 오류 발생"; + errors.push(errorMsg); + console.error(`❌ [handleRackStructureBatchSave] 예외 발생 (${i + 1}):`, error); + } + } + + console.log("🏗️ [handleRackStructureBatchSave] 저장 완료:", { + successCount, + errorCount, + errors: errors.slice(0, 5), // 처음 5개 오류만 로그 + }); + + if (errorCount > 0) { + if (successCount > 0) { + alert(`${successCount}개 저장 완료, ${errorCount}개 저장 실패\n\n오류: ${errors.slice(0, 3).join("\n")}`); + } else { + throw new Error(`저장 실패: ${errors[0]}`); + } + } else { + alert(`${successCount}개의 위치가 성공적으로 등록되었습니다.`); + } + + // 성공 후 새로고침 + if (context.onRefresh) { + context.onRefresh(); + } + + // 모달 닫기 + if (context.onClose) { + context.onClose(); + } + + return successCount > 0; + } catch (error: any) { + console.error("🏗️ [handleRackStructureBatchSave] 일괄 저장 오류:", error); + throw error; + } + } + /** * 🆕 배치 저장 액션 처리 (SelectedItemsDetailInput용 - 새로운 데이터 구조) * ItemData[] → 각 품목의 details 배열을 개별 레코드로 저장 @@ -919,7 +1171,7 @@ export class ButtonActionExecutor { ): Promise { const { formData, tableName, screenId, selectedRowsData, originalData } = context; - console.log(`🔍 [handleBatchSave] context 확인:`, { + console.log("🔍 [handleBatchSave] context 확인:", { hasSelectedRowsData: !!selectedRowsData, selectedRowsCount: selectedRowsData?.length || 0, hasOriginalData: !!originalData, @@ -1137,7 +1389,7 @@ export class ButtonActionExecutor { try { // 플로우 선택 데이터 우선 사용 - let dataToDelete = flowSelectedData && flowSelectedData.length > 0 ? flowSelectedData : selectedRowsData; + const dataToDelete = flowSelectedData && flowSelectedData.length > 0 ? flowSelectedData : selectedRowsData; console.log("🔍 handleDelete - 데이터 소스 확인:", { hasFlowSelectedData: !!(flowSelectedData && flowSelectedData.length > 0), @@ -1207,7 +1459,7 @@ export class ButtonActionExecutor { if (idField) deleteId = rowData[idField]; } - console.log(`🔍 폴백 방법으로 ID 추출:`, deleteId); + console.log("🔍 폴백 방법으로 ID 추출:", deleteId); } console.log("선택된 행 데이터:", rowData); @@ -1237,7 +1489,7 @@ export class ButtonActionExecutor { } else { console.log("🔄 테이블 데이터 삭제 완료, 테이블 새로고침 호출"); context.onRefresh?.(); // 테이블 새로고침 - + // 🆕 분할 패널 등 전역 테이블 새로고침 이벤트 발생 window.dispatchEvent(new CustomEvent("refreshTable")); console.log("🔄 refreshTable 전역 이벤트 발생"); @@ -1264,11 +1516,11 @@ export class ButtonActionExecutor { } context.onRefresh?.(); - + // 🆕 분할 패널 등 전역 테이블 새로고침 이벤트 발생 window.dispatchEvent(new CustomEvent("refreshTable")); console.log("🔄 refreshTable 전역 이벤트 발생 (단일 삭제)"); - + toast.success(config.successMessage || "삭제되었습니다."); return true; } catch (error) { @@ -1550,12 +1802,12 @@ export class ButtonActionExecutor { // 🆕 부모 화면의 선택된 데이터 가져오기 (excludeFilter에서 사용) const rawParentData = dataRegistry[dataSourceId]?.[0]?.originalData || dataRegistry[dataSourceId]?.[0] || {}; - + // 🆕 필드 매핑 적용 (소스 컬럼 → 타겟 컬럼) - let parentData = { ...rawParentData }; + const parentData = { ...rawParentData }; if (config.fieldMappings && Array.isArray(config.fieldMappings) && config.fieldMappings.length > 0) { console.log("🔄 [openModalWithData] 필드 매핑 적용:", config.fieldMappings); - + config.fieldMappings.forEach((mapping: { sourceField: string; targetField: string }) => { if (mapping.sourceField && mapping.targetField && rawParentData[mapping.sourceField] !== undefined) { // 타겟 필드에 소스 필드 값 복사 @@ -1564,7 +1816,7 @@ export class ButtonActionExecutor { } }); } - + console.log("📦 [openModalWithData] 부모 데이터 전달:", { dataSourceId, rawParentData, @@ -1688,7 +1940,7 @@ export class ButtonActionExecutor { const { selectedRowsData, flowSelectedData } = context; // 플로우 선택 데이터 우선 사용 - let dataToEdit = flowSelectedData && flowSelectedData.length > 0 ? flowSelectedData : selectedRowsData; + const dataToEdit = flowSelectedData && flowSelectedData.length > 0 ? flowSelectedData : selectedRowsData; // 선택된 데이터가 없는 경우 if (!dataToEdit || dataToEdit.length === 0) { @@ -1868,7 +2120,7 @@ export class ButtonActionExecutor { const { selectedRowsData, flowSelectedData } = context; // 플로우 선택 데이터 우선 사용 - let dataToCopy = flowSelectedData && flowSelectedData.length > 0 ? flowSelectedData : selectedRowsData; + const dataToCopy = flowSelectedData && flowSelectedData.length > 0 ? flowSelectedData : selectedRowsData; console.log("📋 handleCopy - 데이터 소스 확인:", { hasFlowSelectedData: !!(flowSelectedData && flowSelectedData.length > 0), @@ -1980,7 +2232,7 @@ export class ButtonActionExecutor { }); if (resetFieldName) { - toast.success(`복사본이 생성되었습니다. 품목코드는 저장 시 자동으로 생성됩니다.`); + toast.success("복사본이 생성되었습니다. 품목코드는 저장 시 자동으로 생성됩니다."); } else { console.warn("⚠️ 품목코드 필드를 찾을 수 없습니다. 전체 데이터를 복사합니다."); console.warn("⚠️ 사용 가능한 필드:", Object.keys(copiedData)); @@ -2753,7 +3005,7 @@ export class ButtonActionExecutor { } else { console.warn(`⚠️ 매핑 실패: ${sourceField} → ${targetField} (값을 찾을 수 없음)`); console.warn(` - valueType: ${valueType}, defaultValue: ${defaultValue}`); - console.warn(` - 소스 데이터 키들:`, Object.keys(sourceData)); + console.warn(" - 소스 데이터 키들:", Object.keys(sourceData)); console.warn(` - sourceData[${sourceField}] =`, sourceData[sourceField]); return; // 값이 없으면 해당 필드는 스킵 } @@ -2791,7 +3043,7 @@ export class ButtonActionExecutor { if (result.success) { console.log("✅ 삽입 성공:", result); - toast.success(`데이터가 타겟 테이블에 성공적으로 삽입되었습니다.`); + toast.success("데이터가 타겟 테이블에 성공적으로 삽입되었습니다."); } else { throw new Error(result.message || "삽입 실패"); } @@ -3020,7 +3272,7 @@ export class ButtonActionExecutor { const layoutResponse = await apiClient.get(`/screen-management/screens/${context.screenId}/layout`); if (layoutResponse.data?.success && layoutResponse.data?.data) { - let layoutData = layoutResponse.data.data; + const layoutData = layoutResponse.data.data; // components가 문자열이면 파싱 if (typeof layoutData.components === "string") { @@ -3455,13 +3707,13 @@ export class ButtonActionExecutor { const totalRows = preview.totalAffectedRows; const confirmMerge = confirm( - `⚠️ 코드 병합 확인\n\n` + + "⚠️ 코드 병합 확인\n\n" + `${oldValue} → ${newValue}\n\n` + - `영향받는 데이터:\n` + + "영향받는 데이터:\n" + `- 테이블 수: ${preview.preview.length}개\n` + `- 총 행 수: ${totalRows}개\n\n` + `데이터는 삭제되지 않고, "${columnName}" 컬럼 값만 변경됩니다.\n\n` + - `계속하시겠습니까?`, + "계속하시겠습니까?", ); if (!confirmMerge) { @@ -3486,7 +3738,7 @@ export class ButtonActionExecutor { if (response.data.success) { const data = response.data.data; toast.success( - `코드 병합 완료!\n` + `${data.affectedTables.length}개 테이블, ${data.totalRowsUpdated}개 행 업데이트`, + "코드 병합 완료!\n" + `${data.affectedTables.length}개 테이블, ${data.totalRowsUpdated}개 행 업데이트`, ); // 화면 새로고침 @@ -3532,9 +3784,10 @@ export class ButtonActionExecutor { } // Trip ID 생성 - const tripId = config.trackingAutoGenerateTripId !== false - ? `TRIP_${Date.now()}_${context.userId || "unknown"}` - : context.formData?.[config.trackingTripIdField || "trip_id"] || `TRIP_${Date.now()}`; + const tripId = + config.trackingAutoGenerateTripId !== false + ? `TRIP_${Date.now()}_${context.userId || "unknown"}` + : context.formData?.[config.trackingTripIdField || "trip_id"] || `TRIP_${Date.now()}`; this.currentTripId = tripId; this.trackingContext = context; @@ -3565,7 +3818,7 @@ export class ButtonActionExecutor { const keyValue = resolveSpecialKeyword(config.trackingStatusKeySourceField || "__userId__", context); if (keyValue) { - await apiClient.put(`/dynamic-form/update-field`, { + await apiClient.put("/dynamic-form/update-field", { tableName: statusTableName, keyField: keyField, keyValue: keyValue, @@ -3591,9 +3844,11 @@ export class ButtonActionExecutor { toast.success(config.successMessage || `위치 추적이 시작되었습니다. (${interval / 1000}초 간격)`); // 추적 시작 이벤트 발생 (UI 업데이트용) - window.dispatchEvent(new CustomEvent("trackingStarted", { - detail: { tripId, interval } - })); + window.dispatchEvent( + new CustomEvent("trackingStarted", { + detail: { tripId, interval }, + }), + ); return true; } catch (error: any) { @@ -3623,26 +3878,36 @@ export class ButtonActionExecutor { const tripId = this.currentTripId; // 마지막 위치 저장 (trip_status를 completed로) - const departure = this.trackingContext?.formData?.[this.trackingConfig?.trackingDepartureField || "departure"] || null; + const departure = + this.trackingContext?.formData?.[this.trackingConfig?.trackingDepartureField || "departure"] || null; const arrival = this.trackingContext?.formData?.[this.trackingConfig?.trackingArrivalField || "arrival"] || null; const departureName = this.trackingContext?.formData?.["departure_name"] || null; const destinationName = this.trackingContext?.formData?.["destination_name"] || null; - const vehicleId = this.trackingContext?.formData?.[this.trackingConfig?.trackingVehicleIdField || "vehicle_id"] || null; + const vehicleId = + this.trackingContext?.formData?.[this.trackingConfig?.trackingVehicleIdField || "vehicle_id"] || null; - await this.saveLocationToHistory(tripId, departure, arrival, departureName, destinationName, vehicleId, "completed"); + await this.saveLocationToHistory( + tripId, + departure, + arrival, + departureName, + destinationName, + vehicleId, + "completed", + ); // 🆕 거리/시간 계산 및 저장 if (tripId) { try { const tripStats = await this.calculateTripStats(tripId); console.log("📊 운행 통계:", tripStats); - + // 운행 통계를 두 테이블에 저장 if (tripStats) { const distanceMeters = Math.round(tripStats.totalDistanceKm * 1000); // km → m const timeMinutes = tripStats.totalTimeMinutes; const userId = this.trackingUserId || context.userId; - + console.log("💾 운행 통계 DB 저장 시도:", { tripId, userId, @@ -3651,34 +3916,37 @@ export class ButtonActionExecutor { startTime: tripStats.startTime, endTime: tripStats.endTime, }); - + const { apiClient } = await import("@/lib/api/client"); - + // 1️⃣ vehicle_location_history 마지막 레코드에 통계 저장 (이력용) try { - const lastRecordResponse = await apiClient.post(`/table-management/tables/vehicle_location_history/data`, { - page: 1, - size: 1, - search: { trip_id: tripId }, - sortBy: "recorded_at", - sortOrder: "desc", - autoFilter: true, - }); - + const lastRecordResponse = await apiClient.post( + "/table-management/tables/vehicle_location_history/data", + { + page: 1, + size: 1, + search: { trip_id: tripId }, + sortBy: "recorded_at", + sortOrder: "desc", + autoFilter: true, + }, + ); + const lastRecordData = lastRecordResponse.data?.data?.data || lastRecordResponse.data?.data?.rows || []; if (lastRecordData.length > 0) { const lastRecordId = lastRecordData[0].id; console.log("📍 마지막 레코드 ID:", lastRecordId); - + const historyUpdates = [ { field: "trip_distance", value: distanceMeters }, { field: "trip_time", value: timeMinutes }, { field: "trip_start", value: tripStats.startTime }, { field: "trip_end", value: tripStats.endTime }, ]; - + for (const update of historyUpdates) { - await apiClient.put(`/dynamic-form/update-field`, { + await apiClient.put("/dynamic-form/update-field", { tableName: "vehicle_location_history", keyField: "id", keyValue: lastRecordId, @@ -3693,7 +3961,7 @@ export class ButtonActionExecutor { } catch (historyError) { console.warn("⚠️ vehicle_location_history 저장 실패:", historyError); } - + // 2️⃣ vehicles 테이블에도 마지막 운행 통계 업데이트 (최신 정보용) if (userId) { try { @@ -3703,9 +3971,9 @@ export class ButtonActionExecutor { { field: "last_trip_start", value: tripStats.startTime }, { field: "last_trip_end", value: tripStats.endTime }, ]; - + for (const update of vehicleUpdates) { - await apiClient.put(`/dynamic-form/update-field`, { + await apiClient.put("/dynamic-form/update-field", { tableName: "vehicles", keyField: "user_id", keyValue: userId, @@ -3718,19 +3986,23 @@ export class ButtonActionExecutor { console.warn("⚠️ vehicles 테이블 저장 실패:", vehicleError); } } - + // 이벤트로 통계 전달 (UI에서 표시용) - window.dispatchEvent(new CustomEvent("tripCompleted", { - detail: { - tripId, - totalDistanceKm: tripStats.totalDistanceKm, - totalTimeMinutes: tripStats.totalTimeMinutes, - startTime: tripStats.startTime, - endTime: tripStats.endTime, - } - })); - - toast.success(`운행 종료! 총 ${tripStats.totalDistanceKm.toFixed(1)}km, ${tripStats.totalTimeMinutes}분 소요`); + window.dispatchEvent( + new CustomEvent("tripCompleted", { + detail: { + tripId, + totalDistanceKm: tripStats.totalDistanceKm, + totalTimeMinutes: tripStats.totalTimeMinutes, + startTime: tripStats.startTime, + endTime: tripStats.endTime, + }, + }), + ); + + toast.success( + `운행 종료! 총 ${tripStats.totalDistanceKm.toFixed(1)}km, ${tripStats.totalTimeMinutes}분 소요`, + ); } } catch (statsError) { console.warn("⚠️ 운행 통계 계산 실패:", statsError); @@ -3746,10 +4018,13 @@ export class ButtonActionExecutor { const { apiClient } = await import("@/lib/api/client"); const statusTableName = effectiveConfig.trackingStatusTableName || effectiveContext.tableName; const keyField = effectiveConfig.trackingStatusKeyField || "user_id"; - const keyValue = resolveSpecialKeyword(effectiveConfig.trackingStatusKeySourceField || "__userId__", effectiveContext); + const keyValue = resolveSpecialKeyword( + effectiveConfig.trackingStatusKeySourceField || "__userId__", + effectiveContext, + ); if (keyValue) { - await apiClient.put(`/dynamic-form/update-field`, { + await apiClient.put("/dynamic-form/update-field", { tableName: statusTableName, keyField: keyField, keyValue: keyValue, @@ -3771,9 +4046,11 @@ export class ButtonActionExecutor { toast.success(config.successMessage || "위치 추적이 종료되었습니다."); // 추적 종료 이벤트 발생 (UI 업데이트용) - window.dispatchEvent(new CustomEvent("trackingStopped", { - detail: { tripId } - })); + window.dispatchEvent( + new CustomEvent("trackingStopped", { + detail: { tripId }, + }), + ); // 화면 새로고침 context.onRefresh?.(); @@ -3798,8 +4075,8 @@ export class ButtonActionExecutor { try { // vehicle_location_history에서 해당 trip의 모든 위치 조회 const { apiClient } = await import("@/lib/api/client"); - - const response = await apiClient.post(`/table-management/tables/vehicle_location_history/data`, { + + const response = await apiClient.post("/table-management/tables/vehicle_location_history/data", { page: 1, size: 10000, search: { trip_id: tripId }, @@ -3814,7 +4091,7 @@ export class ButtonActionExecutor { // 응답 형식: data.data.data 또는 data.data.rows const rows = response.data?.data?.data || response.data?.data?.rows || []; - + if (!rows.length) { console.log("📊 통계 계산: 데이터 없음"); return null; @@ -3834,13 +4111,13 @@ export class ButtonActionExecutor { for (let i = 1; i < locations.length; i++) { const prev = locations[i - 1]; const curr = locations[i]; - + if (prev.latitude && prev.longitude && curr.latitude && curr.longitude) { const distance = this.calculateDistance( parseFloat(prev.latitude), parseFloat(prev.longitude), parseFloat(curr.latitude), - parseFloat(curr.longitude) + parseFloat(curr.longitude), ); totalDistanceM += distance; } @@ -3874,12 +4151,11 @@ export class ButtonActionExecutor { */ private static calculateDistance(lat1: number, lon1: number, lat2: number, lon2: number): number { const R = 6371000; // 지구 반경 (미터) - const dLat = (lat2 - lat1) * Math.PI / 180; - const dLon = (lon2 - lon1) * Math.PI / 180; - const a = + const dLat = ((lat2 - lat1) * Math.PI) / 180; + const dLon = ((lon2 - lon1) * Math.PI) / 180; + const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + - Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * - Math.sin(dLon / 2) * Math.sin(dLon / 2); + Math.cos((lat1 * Math.PI) / 180) * Math.cos((lat2 * Math.PI) / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2); const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return R * c; } @@ -3895,7 +4171,7 @@ export class ButtonActionExecutor { departureName: string | null, destinationName: string | null, vehicleId: number | null, - tripStatus: string = "active" + tripStatus: string = "active", ): Promise { return new Promise((resolve, reject) => { navigator.geolocation.getCurrentPosition( @@ -3925,7 +4201,7 @@ export class ButtonActionExecutor { console.log("📍 [saveLocationToHistory] 위치 저장:", locationData); // 1. vehicle_location_history에 저장 - const response = await apiClient.post(`/dynamic-form/location-history`, locationData); + const response = await apiClient.post("/dynamic-form/location-history", locationData); if (response.data?.success) { console.log("✅ 위치 이력 저장 성공:", response.data.data); @@ -3943,7 +4219,7 @@ export class ButtonActionExecutor { if (keyValue) { try { // latitude 업데이트 - await apiClient.put(`/dynamic-form/update-field`, { + await apiClient.put("/dynamic-form/update-field", { tableName: vehiclesTableName, keyField, keyValue, @@ -3952,7 +4228,7 @@ export class ButtonActionExecutor { }); // longitude 업데이트 - await apiClient.put(`/dynamic-form/update-field`, { + await apiClient.put("/dynamic-form/update-field", { tableName: vehiclesTableName, keyField, keyValue, @@ -3982,7 +4258,7 @@ export class ButtonActionExecutor { enableHighAccuracy: true, timeout: 10000, maximumAge: 0, - } + }, ); }); } @@ -4172,14 +4448,14 @@ export class ButtonActionExecutor { if (keyValue && targetTableName) { try { const { apiClient } = await import("@/lib/api/client"); - + // 위치 정보 필드들 업데이트 (위도, 경도, 정확도, 타임스탬프) const fieldsToUpdate = { ...updates }; - + // formData에서 departure, arrival만 포함 (테이블에 있을 가능성 높은 필드만) if (context.formData?.departure) fieldsToUpdate.departure = context.formData.departure; if (context.formData?.arrival) fieldsToUpdate.arrival = context.formData.arrival; - + // 추가 필드 변경 (status 등) if (config.geolocationExtraField && config.geolocationExtraValue !== undefined) { fieldsToUpdate[config.geolocationExtraField] = config.geolocationExtraValue; @@ -4191,7 +4467,7 @@ export class ButtonActionExecutor { let successCount = 0; for (const [field, value] of Object.entries(fieldsToUpdate)) { try { - const response = await apiClient.put(`/dynamic-form/update-field`, { + const response = await apiClient.put("/dynamic-form/update-field", { tableName: targetTableName, keyField, keyValue, @@ -4210,10 +4486,15 @@ export class ButtonActionExecutor { // 🆕 연속 위치 추적 시작 (공차 상태에서도 위치 기록) if (config.emptyVehicleTracking !== false) { await this.startEmptyVehicleTracking(config, context, { - latitude, longitude, accuracy, speed, heading, altitude + latitude, + longitude, + accuracy, + speed, + heading, + altitude, }); } - + toast.success(config.successMessage || "공차 등록이 완료되었습니다. 위치 추적을 시작합니다."); } catch (saveError) { console.error("❌ 위치정보 자동 저장 실패:", saveError); @@ -4261,9 +4542,16 @@ export class ButtonActionExecutor { * 공차 상태에서 연속 위치 추적 시작 */ private static async startEmptyVehicleTracking( - config: ButtonActionConfig, + config: ButtonActionConfig, context: ButtonActionContext, - initialPosition: { latitude: number; longitude: number; accuracy: number | null; speed: number | null; heading: number | null; altitude: number | null } + initialPosition: { + latitude: number; + longitude: number; + accuracy: number | null; + speed: number | null; + heading: number | null; + altitude: number | null; + }, ): Promise { try { // 기존 추적이 있으면 중지 @@ -4273,7 +4561,7 @@ export class ButtonActionExecutor { } const { apiClient } = await import("@/lib/api/client"); - + // Trip ID 생성 (공차용) const tripId = `EMPTY-${Date.now()}-${Math.random().toString(36).substring(2, 10)}`; this.emptyVehicleTripId = tripId; @@ -4315,7 +4603,7 @@ export class ButtonActionExecutor { this.emptyVehicleWatchId = navigator.geolocation.watchPosition( async (position) => { const { latitude, longitude, accuracy, speed, heading, altitude } = position.coords; - + try { await apiClient.post("/dynamic-form/location-history", { tripId: this.emptyVehicleTripId, @@ -4345,7 +4633,7 @@ export class ButtonActionExecutor { enableHighAccuracy: true, timeout: trackingInterval, maximumAge: 0, - } + }, ); console.log("🚗 공차 위치 추적 시작:", { tripId, watchId: this.emptyVehicleWatchId }); @@ -4435,26 +4723,30 @@ export class ButtonActionExecutor { * 운행알림 및 종료 액션 처리 * - 위치 수집 + 상태 변경 + 연속 추적 (시작/종료) */ - private static async handleOperationControl(config: ButtonActionConfig, context: ButtonActionContext): Promise { + private static async handleOperationControl( + config: ButtonActionConfig, + context: ButtonActionContext, + ): Promise { try { console.log("🔄 운행알림/종료 액션 실행:", { config, context }); // 🆕 출발지/도착지 필수 체크 (운행 시작 모드일 때만) // updateTrackingMode가 "start"이거나 updateTargetValue가 "active"/"inactive"인 경우 - const isStartMode = config.updateTrackingMode === "start" || - config.updateTargetValue === "active" || - config.updateTargetValue === "inactive"; - + const isStartMode = + config.updateTrackingMode === "start" || + config.updateTargetValue === "active" || + config.updateTargetValue === "inactive"; + if (isStartMode) { // 출발지/도착지 필드명 (기본값: departure, destination) const departureField = config.trackingDepartureField || "departure"; const destinationField = config.trackingArrivalField || "destination"; - + const departure = context.formData?.[departureField]; const destination = context.formData?.[destinationField]; - + console.log("📍 출발지/도착지 체크:", { departureField, destinationField, departure, destination }); - + if (!departure || departure === "" || !destination || destination === "") { toast.error("출발지와 도착지를 먼저 선택해주세요."); return false; @@ -4570,7 +4862,7 @@ export class ButtonActionExecutor { } } catch (geoError: any) { toast.dismiss(loadingToastId); - + // GeolocationPositionError 처리 if (geoError.code === 1) { toast.error("위치 정보 접근이 거부되었습니다."); @@ -4602,11 +4894,11 @@ export class ButtonActionExecutor { const keyField = config.updateKeyField; const keySourceField = config.updateKeySourceField; const targetTableName = config.updateTableName || tableName; - + if (keyField && keySourceField) { // 특수 키워드 변환 (예: __userId__ → 실제 사용자 ID) const keyValue = resolveSpecialKeyword(keySourceField, context); - + console.log("🔄 필드 값 변경 - 키 필드 사용:", { targetTable: targetTableName, keyField, @@ -4614,43 +4906,45 @@ export class ButtonActionExecutor { keyValue, updates, }); - + if (!keyValue) { console.warn("⚠️ 키 값이 없어서 업데이트를 건너뜁니다:", { keySourceField, keyValue }); toast.error("레코드를 식별할 키 값이 없습니다."); return false; } - + try { // 각 필드에 대해 개별 UPDATE 호출 const { apiClient } = await import("@/lib/api/client"); - + for (const [field, value] of Object.entries(updates)) { console.log(`🔄 DB UPDATE: ${targetTableName}.${field} = ${value} WHERE ${keyField} = ${keyValue}`); - - const response = await apiClient.put(`/dynamic-form/update-field`, { + + const response = await apiClient.put("/dynamic-form/update-field", { tableName: targetTableName, keyField: keyField, keyValue: keyValue, updateField: field, updateValue: value, }); - + if (!response.data?.success) { console.error(`❌ ${field} 업데이트 실패:`, response.data); toast.error(`${field} 업데이트에 실패했습니다.`); return false; } } - + console.log("✅ 모든 필드 업데이트 성공"); toast.success(config.successMessage || "상태가 변경되었습니다."); - + // 테이블 새로고침 이벤트 발생 - window.dispatchEvent(new CustomEvent("refreshTableData", { - detail: { tableName: targetTableName } - })); - + window.dispatchEvent( + new CustomEvent("refreshTableData", { + detail: { tableName: targetTableName }, + }), + ); + return true; } catch (apiError) { console.error("❌ 필드 값 변경 API 호출 실패:", apiError); @@ -4658,7 +4952,7 @@ export class ButtonActionExecutor { return false; } } - + // onSave 콜백이 있으면 사용 if (onSave) { console.log("🔄 필드 값 변경 후 자동 저장 (onSave 콜백)"); From a278ceca3fecd0f0d514239761015615abc744a9 Mon Sep 17 00:00:00 2001 From: SeongHyun Kim Date: Mon, 8 Dec 2025 17:54:11 +0900 Subject: [PATCH 11/18] =?UTF-8?q?feat(universal-form-modal):=20=EB=B2=94?= =?UTF-8?q?=EC=9A=A9=20=EB=8B=A4=EC=A4=91=20=ED=85=8C=EC=9D=B4=EB=B8=94=20?= =?UTF-8?q?=EC=A0=80=EC=9E=A5=20=EA=B8=B0=EB=8A=A5=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/tableManagementController.ts | 296 ++++ .../src/routes/tableManagementRoutes.ts | 14 + .../lib/registry/DynamicComponentRenderer.tsx | 3 + .../SplitPanelLayout2ConfigPanel.tsx | 114 +- .../UniversalFormModalComponent.tsx | 276 ++-- .../UniversalFormModalConfigPanel.tsx | 1229 ++++++++++++----- .../components/universal-form-modal/types.ts | 97 +- 7 files changed, 1482 insertions(+), 547 deletions(-) diff --git a/backend-node/src/controllers/tableManagementController.ts b/backend-node/src/controllers/tableManagementController.ts index 4a80b007..ce6a73b9 100644 --- a/backend-node/src/controllers/tableManagementController.ts +++ b/backend-node/src/controllers/tableManagementController.ts @@ -1811,3 +1811,299 @@ export async function getCategoryColumnsByMenu( }); } } + +/** + * 범용 다중 테이블 저장 API + * + * 메인 테이블과 서브 테이블(들)에 트랜잭션으로 데이터를 저장합니다. + * + * 요청 본문: + * { + * mainTable: { tableName: string, primaryKeyColumn: string }, + * mainData: Record, + * subTables: Array<{ + * tableName: string, + * linkColumn: { mainField: string, subColumn: string }, + * items: Record[], + * options?: { + * saveMainAsFirst?: boolean, + * mainFieldMappings?: Array<{ formField: string, targetColumn: string }>, + * mainMarkerColumn?: string, + * mainMarkerValue?: any, + * subMarkerValue?: any, + * deleteExistingBefore?: boolean, + * } + * }>, + * isUpdate?: boolean + * } + */ +export async function multiTableSave( + req: AuthenticatedRequest, + res: Response +): Promise { + const pool = require("../database/db").getPool(); + const client = await pool.connect(); + + try { + const { mainTable, mainData, subTables, isUpdate } = req.body; + const companyCode = req.user?.companyCode || "*"; + + logger.info("=== 다중 테이블 저장 시작 ===", { + mainTable, + mainDataKeys: Object.keys(mainData || {}), + subTablesCount: subTables?.length || 0, + isUpdate, + companyCode, + }); + + // 유효성 검사 + if (!mainTable?.tableName || !mainTable?.primaryKeyColumn) { + res.status(400).json({ + success: false, + message: "메인 테이블 설정이 올바르지 않습니다.", + }); + return; + } + + if (!mainData || Object.keys(mainData).length === 0) { + res.status(400).json({ + success: false, + message: "저장할 메인 데이터가 없습니다.", + }); + return; + } + + await client.query("BEGIN"); + + // 1. 메인 테이블 저장 + const mainTableName = mainTable.tableName; + const pkColumn = mainTable.primaryKeyColumn; + const pkValue = mainData[pkColumn]; + + // company_code 자동 추가 (최고 관리자가 아닌 경우) + if (companyCode !== "*" && !mainData.company_code) { + mainData.company_code = companyCode; + } + + let mainResult: any; + + if (isUpdate && pkValue) { + // UPDATE + const updateColumns = Object.keys(mainData) + .filter(col => col !== pkColumn) + .map((col, idx) => `"${col}" = $${idx + 1}`) + .join(", "); + const updateValues = Object.keys(mainData) + .filter(col => col !== pkColumn) + .map(col => mainData[col]); + + // updated_at 컬럼 존재 여부 확인 + const hasUpdatedAt = await client.query(` + SELECT 1 FROM information_schema.columns + WHERE table_name = $1 AND column_name = 'updated_at' + `, [mainTableName]); + const updatedAtClause = hasUpdatedAt.rowCount && hasUpdatedAt.rowCount > 0 ? ", updated_at = NOW()" : ""; + + const updateQuery = ` + UPDATE "${mainTableName}" + SET ${updateColumns}${updatedAtClause} + WHERE "${pkColumn}" = $${updateValues.length + 1} + ${companyCode !== "*" ? `AND company_code = $${updateValues.length + 2}` : ""} + RETURNING * + `; + + const updateParams = companyCode !== "*" + ? [...updateValues, pkValue, companyCode] + : [...updateValues, pkValue]; + + logger.info("메인 테이블 UPDATE:", { query: updateQuery, paramsCount: updateParams.length }); + mainResult = await client.query(updateQuery, updateParams); + } else { + // INSERT + const columns = Object.keys(mainData).map(col => `"${col}"`).join(", "); + const placeholders = Object.keys(mainData).map((_, idx) => `$${idx + 1}`).join(", "); + const values = Object.values(mainData); + + // updated_at 컬럼 존재 여부 확인 + const hasUpdatedAt = await client.query(` + SELECT 1 FROM information_schema.columns + WHERE table_name = $1 AND column_name = 'updated_at' + `, [mainTableName]); + const updatedAtClause = hasUpdatedAt.rowCount && hasUpdatedAt.rowCount > 0 ? ", updated_at = NOW()" : ""; + + const updateSetClause = Object.keys(mainData) + .filter(col => col !== pkColumn) + .map(col => `"${col}" = EXCLUDED."${col}"`) + .join(", "); + + const insertQuery = ` + INSERT INTO "${mainTableName}" (${columns}) + VALUES (${placeholders}) + ON CONFLICT ("${pkColumn}") DO UPDATE SET + ${updateSetClause}${updatedAtClause} + RETURNING * + `; + + logger.info("메인 테이블 INSERT/UPSERT:", { query: insertQuery, paramsCount: values.length }); + mainResult = await client.query(insertQuery, values); + } + + if (mainResult.rowCount === 0) { + throw new Error("메인 테이블 저장 실패"); + } + + const savedMainData = mainResult.rows[0]; + const savedPkValue = savedMainData[pkColumn]; + logger.info("메인 테이블 저장 완료:", { pkColumn, savedPkValue }); + + // 2. 서브 테이블 저장 + const subTableResults: any[] = []; + + for (const subTableConfig of subTables || []) { + const { tableName, linkColumn, items, options } = subTableConfig; + + if (!tableName || !items || items.length === 0) { + logger.info(`서브 테이블 ${tableName} 스킵: 데이터 없음`); + continue; + } + + logger.info(`서브 테이블 ${tableName} 저장 시작:`, { + itemsCount: items.length, + linkColumn, + options, + }); + + // 기존 데이터 삭제 옵션 + if (options?.deleteExistingBefore && linkColumn?.subColumn) { + const deleteQuery = options?.deleteOnlySubItems && options?.mainMarkerColumn + ? `DELETE FROM "${tableName}" WHERE "${linkColumn.subColumn}" = $1 AND "${options.mainMarkerColumn}" = $2` + : `DELETE FROM "${tableName}" WHERE "${linkColumn.subColumn}" = $1`; + + const deleteParams = options?.deleteOnlySubItems && options?.mainMarkerColumn + ? [savedPkValue, options.subMarkerValue ?? false] + : [savedPkValue]; + + logger.info(`서브 테이블 ${tableName} 기존 데이터 삭제:`, { deleteQuery, deleteParams }); + await client.query(deleteQuery, deleteParams); + } + + // 메인 데이터도 서브 테이블에 저장 (옵션) + if (options?.saveMainAsFirst && options?.mainFieldMappings && linkColumn?.subColumn) { + const mainSubItem: Record = { + [linkColumn.subColumn]: savedPkValue, + }; + + // 메인 필드 매핑 적용 + for (const mapping of options.mainFieldMappings) { + if (mapping.formField && mapping.targetColumn) { + mainSubItem[mapping.targetColumn] = mainData[mapping.formField]; + } + } + + // 메인 마커 설정 + if (options.mainMarkerColumn) { + mainSubItem[options.mainMarkerColumn] = options.mainMarkerValue ?? true; + } + + // company_code 추가 + if (companyCode !== "*") { + mainSubItem.company_code = companyCode; + } + + const mainSubColumns = Object.keys(mainSubItem).map(col => `"${col}"`).join(", "); + const mainSubPlaceholders = Object.keys(mainSubItem).map((_, idx) => `$${idx + 1}`).join(", "); + const mainSubValues = Object.values(mainSubItem); + + // UPSERT 쿼리 (PK가 있다면) + const mainSubInsertQuery = ` + INSERT INTO "${tableName}" (${mainSubColumns}) + VALUES (${mainSubPlaceholders}) + ON CONFLICT ("${linkColumn.subColumn}"${options.mainMarkerColumn ? `, "${options.mainMarkerColumn}"` : ""}) + DO UPDATE SET + ${Object.keys(mainSubItem) + .filter(col => col !== linkColumn.subColumn && col !== options.mainMarkerColumn) + .map(col => `"${col}" = EXCLUDED."${col}"`) + .join(", ") || "updated_at = NOW()"} + RETURNING * + `; + + try { + logger.info(`서브 테이블 ${tableName} 메인 데이터 저장:`, { mainSubInsertQuery, mainSubValues }); + const mainSubResult = await client.query(mainSubInsertQuery, mainSubValues); + subTableResults.push({ tableName, type: "main", data: mainSubResult.rows[0] }); + } catch (err: any) { + // ON CONFLICT 실패 시 일반 INSERT 시도 + logger.warn(`서브 테이블 ${tableName} UPSERT 실패, 일반 INSERT 시도:`, err.message); + const simpleInsertQuery = ` + INSERT INTO "${tableName}" (${mainSubColumns}) + VALUES (${mainSubPlaceholders}) + RETURNING * + `; + const simpleResult = await client.query(simpleInsertQuery, mainSubValues); + subTableResults.push({ tableName, type: "main", data: simpleResult.rows[0] }); + } + } + + // 서브 아이템들 저장 + for (const item of items) { + // 연결 컬럼 값 설정 + if (linkColumn?.subColumn) { + item[linkColumn.subColumn] = savedPkValue; + } + + // company_code 추가 + if (companyCode !== "*" && !item.company_code) { + item.company_code = companyCode; + } + + const subColumns = Object.keys(item).map(col => `"${col}"`).join(", "); + const subPlaceholders = Object.keys(item).map((_, idx) => `$${idx + 1}`).join(", "); + const subValues = Object.values(item); + + const subInsertQuery = ` + INSERT INTO "${tableName}" (${subColumns}) + VALUES (${subPlaceholders}) + RETURNING * + `; + + logger.info(`서브 테이블 ${tableName} 아이템 저장:`, { subInsertQuery, subValuesCount: subValues.length }); + const subResult = await client.query(subInsertQuery, subValues); + subTableResults.push({ tableName, type: "sub", data: subResult.rows[0] }); + } + + logger.info(`서브 테이블 ${tableName} 저장 완료`); + } + + await client.query("COMMIT"); + + logger.info("=== 다중 테이블 저장 완료 ===", { + mainTable: mainTableName, + mainPk: savedPkValue, + subTableResultsCount: subTableResults.length, + }); + + res.json({ + success: true, + message: "다중 테이블 저장이 완료되었습니다.", + data: { + main: savedMainData, + subTables: subTableResults, + }, + }); + } catch (error: any) { + await client.query("ROLLBACK"); + + logger.error("다중 테이블 저장 실패:", { + message: error.message, + stack: error.stack, + }); + + res.status(500).json({ + success: false, + message: error.message || "다중 테이블 저장에 실패했습니다.", + error: error.message, + }); + } finally { + client.release(); + } +} diff --git a/backend-node/src/routes/tableManagementRoutes.ts b/backend-node/src/routes/tableManagementRoutes.ts index 5ea98489..d0716d59 100644 --- a/backend-node/src/routes/tableManagementRoutes.ts +++ b/backend-node/src/routes/tableManagementRoutes.ts @@ -24,6 +24,7 @@ import { getLogData, toggleLogTable, getCategoryColumnsByMenu, // 🆕 메뉴별 카테고리 컬럼 조회 + multiTableSave, // 🆕 범용 다중 테이블 저장 } from "../controllers/tableManagementController"; const router = express.Router(); @@ -198,4 +199,17 @@ router.post("/tables/:tableName/log/toggle", toggleLogTable); */ router.get("/menu/:menuObjid/category-columns", getCategoryColumnsByMenu); +// ======================================== +// 범용 다중 테이블 저장 API +// ======================================== + +/** + * 다중 테이블 저장 (메인 + 서브 테이블) + * POST /api/table-management/multi-table-save + * + * 메인 테이블과 서브 테이블(들)에 트랜잭션으로 데이터를 저장합니다. + * 사원+부서, 주문+주문상세 등 1:N 관계 데이터 저장에 사용됩니다. + */ +router.post("/multi-table-save", multiTableSave); + export default router; diff --git a/frontend/lib/registry/DynamicComponentRenderer.tsx b/frontend/lib/registry/DynamicComponentRenderer.tsx index 8609623b..816483fc 100644 --- a/frontend/lib/registry/DynamicComponentRenderer.tsx +++ b/frontend/lib/registry/DynamicComponentRenderer.tsx @@ -448,6 +448,9 @@ export const DynamicComponentRenderer: React.FC = isDesignMode: props.isDesignMode !== undefined ? props.isDesignMode : false, // 🆕 그룹 데이터 전달 (EditModal → ConditionalContainer → ModalRepeaterTable) groupedData: props.groupedData, + // 🆕 UniversalFormModal용 initialData 전달 + // originalData를 사용 (최초 전달된 값, formData는 계속 변경되므로 사용하면 안됨) + initialData: originalData || formData, }; // 렌더러가 클래스인지 함수인지 확인 diff --git a/frontend/lib/registry/components/split-panel-layout2/SplitPanelLayout2ConfigPanel.tsx b/frontend/lib/registry/components/split-panel-layout2/SplitPanelLayout2ConfigPanel.tsx index c875316a..37e16c6d 100644 --- a/frontend/lib/registry/components/split-panel-layout2/SplitPanelLayout2ConfigPanel.tsx +++ b/frontend/lib/registry/components/split-panel-layout2/SplitPanelLayout2ConfigPanel.tsx @@ -729,7 +729,7 @@ export const SplitPanelLayout2ConfigPanel: React.FC -
- 컬럼 {index + 1} - -
+
+
+ 컬럼 {index + 1} + +
{/* 테이블 선택 */}
@@ -1156,7 +1156,7 @@ export const SplitPanelLayout2ConfigPanel: React.FC컬럼 updateDisplayColumn("right", index, "label", e.target.value)} - placeholder="라벨명 (미입력 시 컬럼명 사용)" - className="h-8 text-xs" - /> -
+ updateDisplayColumn("right", index, "label", e.target.value)} + placeholder="라벨명 (미입력 시 컬럼명 사용)" + className="h-8 text-xs" + /> +
{/* 표시 위치 */} -
+
- -
+
+
); })} {(config.rightPanel?.displayColumns || []).length === 0 && ( @@ -1273,14 +1273,14 @@ export const SplitPanelLayout2ConfigPanel: React.FC t.table_name === selectedTableName)?.table_comment || selectedTableName; return ( -
+
- -
+ +
); })} {(config.rightPanel?.displayColumns || []).length === 0 && ( diff --git a/frontend/lib/registry/components/universal-form-modal/UniversalFormModalComponent.tsx b/frontend/lib/registry/components/universal-form-modal/UniversalFormModalComponent.tsx index 3938645d..4eab9f72 100644 --- a/frontend/lib/registry/components/universal-form-modal/UniversalFormModalComponent.tsx +++ b/frontend/lib/registry/components/universal-form-modal/UniversalFormModalComponent.tsx @@ -1,6 +1,6 @@ "use client"; -import React, { useState, useEffect, useCallback, useMemo } from "react"; +import React, { useState, useEffect, useCallback, useMemo, useRef } from "react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; @@ -115,10 +115,37 @@ export function UniversalFormModalComponent({ itemId: string; }>({ open: false, sectionId: "", itemId: "" }); - // 초기화 + // 초기 데이터를 한 번만 캡처 (컴포넌트 마운트 시) + const capturedInitialData = useRef | undefined>(undefined); + const hasInitialized = useRef(false); + + // 초기화 - 최초 마운트 시에만 실행 useEffect(() => { + // 이미 초기화되었으면 스킵 + if (hasInitialized.current) { + console.log("[UniversalFormModal] 이미 초기화됨, 스킵"); + return; + } + + // 최초 initialData 캡처 (이후 변경되어도 이 값 사용) + if (initialData && Object.keys(initialData).length > 0) { + capturedInitialData.current = JSON.parse(JSON.stringify(initialData)); // 깊은 복사 + console.log("[UniversalFormModal] initialData 캡처:", capturedInitialData.current); + } + + hasInitialized.current = true; initializeForm(); - }, [config, initialData]); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); // 빈 의존성 배열 - 마운트 시 한 번만 실행 + + // config 변경 시에만 재초기화 (initialData 변경은 무시) + useEffect(() => { + if (!hasInitialized.current) return; // 최초 초기화 전이면 스킵 + + console.log("[UniversalFormModal] config 변경 감지, 재초기화"); + initializeForm(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [config]); // 필드 레벨 linkedFieldGroup 데이터 로드 useEffect(() => { @@ -149,6 +176,10 @@ export function UniversalFormModalComponent({ // 폼 초기화 const initializeForm = useCallback(async () => { + // 캡처된 initialData 사용 (props로 전달된 initialData가 아닌) + const effectiveInitialData = capturedInitialData.current || initialData; + console.log("[UniversalFormModal] 폼 초기화 시작, effectiveInitialData:", effectiveInitialData); + const newFormData: FormDataState = {}; const newRepeatSections: { [sectionId: string]: RepeatSectionItem[] } = {}; const newCollapsed = new Set(); @@ -174,11 +205,15 @@ export function UniversalFormModalComponent({ // 기본값 설정 let value = field.defaultValue ?? ""; - // 부모에서 전달받은 값 적용 - if (field.receiveFromParent && initialData) { + // 부모에서 전달받은 값 적용 (receiveFromParent 또는 effectiveInitialData에 해당 값이 있으면) + if (effectiveInitialData) { const parentField = field.parentFieldName || field.columnName; - if (initialData[parentField] !== undefined) { - value = initialData[parentField]; + if (effectiveInitialData[parentField] !== undefined) { + // receiveFromParent가 true이거나, effectiveInitialData에 값이 있으면 적용 + if (field.receiveFromParent || value === "" || value === undefined) { + value = effectiveInitialData[parentField]; + console.log(`[UniversalFormModal] 필드 ${field.columnName}: initialData에서 값 적용 = ${value}`); + } } } @@ -190,11 +225,12 @@ export function UniversalFormModalComponent({ setFormData(newFormData); setRepeatSections(newRepeatSections); setCollapsedSections(newCollapsed); - setOriginalData(initialData || {}); + setOriginalData(effectiveInitialData || {}); // 채번규칙 자동 생성 await generateNumberingValues(newFormData); - }, [config, initialData]); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [config]); // initialData는 의존성에서 제거 (capturedInitialData.current 사용) // 반복 섹션 아이템 생성 const createRepeatItem = (section: FormSectionConfig, index: number): RepeatSectionItem => { @@ -344,15 +380,30 @@ export function UniversalFormModalComponent({ if (optionConfig.type === "static") { options = optionConfig.staticOptions || []; } else if (optionConfig.type === "table" && optionConfig.tableName) { - const response = await apiClient.get(`/table-management/tables/${optionConfig.tableName}/data`, { - params: { limit: 1000 }, + // POST 방식으로 테이블 데이터 조회 (autoFilter 포함) + const response = await apiClient.post(`/table-management/tables/${optionConfig.tableName}/data`, { + page: 1, + size: 1000, + autoFilter: { enabled: true, filterColumn: "company_code" }, }); - if (response.data?.success && response.data?.data) { - options = response.data.data.map((row: any) => ({ - value: String(row[optionConfig.valueColumn || "id"]), - label: String(row[optionConfig.labelColumn || "name"]), - })); + + // 응답 데이터 파싱 + let dataArray: any[] = []; + if (response.data?.success) { + const responseData = response.data?.data; + if (responseData?.data && Array.isArray(responseData.data)) { + dataArray = responseData.data; + } else if (Array.isArray(responseData)) { + dataArray = responseData; + } else if (responseData?.rows && Array.isArray(responseData.rows)) { + dataArray = responseData.rows; + } } + + options = dataArray.map((row: any) => ({ + value: String(row[optionConfig.valueColumn || "id"]), + label: String(row[optionConfig.labelColumn || "name"]), + })); } else if (optionConfig.type === "code" && optionConfig.codeCategory) { const response = await apiClient.get(`/common-code/${optionConfig.codeCategory}`); if (response.data?.success && response.data?.data) { @@ -444,7 +495,7 @@ export function UniversalFormModalComponent({ return { valid: missingFields.length === 0, missingFields }; }, [config.sections, formData]); - // 단일 행 저장 + // 단일 행 저장 const saveSingleRow = useCallback(async () => { const dataToSave = { ...formData }; @@ -532,9 +583,9 @@ export function UniversalFormModalComponent({ // 메인 섹션 필드 데이터 (메인 행에만 적용되는 부서/직급 등) const mainSectionData: any = {}; mainSectionFields.forEach((fieldName) => { - if (formData[fieldName] !== undefined) { - mainSectionData[fieldName] = formData[fieldName]; - } + if (formData[fieldName] !== undefined) { + mainSectionData[fieldName] = formData[fieldName]; + } }); console.log("[UniversalFormModal] 공통 데이터:", commonData); @@ -612,84 +663,113 @@ export function UniversalFormModalComponent({ console.log(`[UniversalFormModal] ${rowsToSave.length}개 행 저장 완료`); }, [config.sections, config.saveConfig, formData, repeatSections]); - // 커스텀 API 저장 (사원+부서 통합 저장 등) + // 다중 테이블 저장 (범용) + const saveWithMultiTable = useCallback(async () => { + const { customApiSave } = config.saveConfig; + if (!customApiSave?.multiTable) return; + + const { multiTable } = customApiSave; + console.log("[UniversalFormModal] 다중 테이블 저장 시작:", multiTable); + console.log("[UniversalFormModal] 현재 formData:", formData); + console.log("[UniversalFormModal] 현재 repeatSections:", repeatSections); + + // 1. 메인 테이블 데이터 구성 + const mainData: Record = {}; + config.sections.forEach((section) => { + if (section.repeatable) return; // 반복 섹션은 제외 + section.fields.forEach((field) => { + const value = formData[field.columnName]; + if (value !== undefined && value !== null && value !== "") { + mainData[field.columnName] = value; + } + }); + }); + + // 2. 서브 테이블 데이터 구성 + const subTablesData: Array<{ + tableName: string; + linkColumn: { mainField: string; subColumn: string }; + items: Record[]; + options?: { + saveMainAsFirst?: boolean; + mainFieldMappings?: Array<{ formField: string; targetColumn: string }>; + mainMarkerColumn?: string; + mainMarkerValue?: any; + subMarkerValue?: any; + deleteExistingBefore?: boolean; + }; + }> = []; + + for (const subTableConfig of multiTable.subTables || []) { + if (!subTableConfig.enabled || !subTableConfig.tableName || !subTableConfig.repeatSectionId) { + continue; + } + + const subItems: Record[] = []; + const repeatData = repeatSections[subTableConfig.repeatSectionId] || []; + + // 반복 섹션 데이터를 필드 매핑에 따라 변환 + for (const item of repeatData) { + const mappedItem: Record = {}; + + // 연결 컬럼 값 설정 + if (subTableConfig.linkColumn?.mainField && subTableConfig.linkColumn?.subColumn) { + mappedItem[subTableConfig.linkColumn.subColumn] = mainData[subTableConfig.linkColumn.mainField]; + } + + // 필드 매핑에 따라 데이터 변환 + for (const mapping of subTableConfig.fieldMappings || []) { + if (mapping.formField && mapping.targetColumn) { + mappedItem[mapping.targetColumn] = item[mapping.formField]; + } + } + + // 메인/서브 구분 컬럼 설정 (서브 데이터는 서브 마커 값) + if (subTableConfig.options?.mainMarkerColumn) { + mappedItem[subTableConfig.options.mainMarkerColumn] = subTableConfig.options?.subMarkerValue ?? false; + } + + if (Object.keys(mappedItem).length > 0) { + subItems.push(mappedItem); + } + } + + subTablesData.push({ + tableName: subTableConfig.tableName, + linkColumn: subTableConfig.linkColumn, + items: subItems, + options: subTableConfig.options, + }); + } + + // 3. 범용 다중 테이블 저장 API 호출 + console.log("[UniversalFormModal] 다중 테이블 저장 데이터:", { + mainTable: multiTable.mainTable, + mainData, + subTablesData, + }); + + const response = await apiClient.post("/table-management/multi-table-save", { + mainTable: multiTable.mainTable, + mainData, + subTables: subTablesData, + isUpdate: !!initialData?.[multiTable.mainTable.primaryKeyColumn], + }); + + if (!response.data?.success) { + throw new Error(response.data?.message || "다중 테이블 저장 실패"); + } + + console.log("[UniversalFormModal] 다중 테이블 저장 완료:", response.data); + }, [config.sections, config.saveConfig, formData, repeatSections, initialData]); + + // 커스텀 API 저장 const saveWithCustomApi = useCallback(async () => { const { customApiSave } = config.saveConfig; if (!customApiSave) return; console.log("[UniversalFormModal] 커스텀 API 저장 시작:", customApiSave.apiType); - const saveUserWithDeptApi = async () => { - const { mainDeptFields, subDeptSectionId, subDeptFields } = customApiSave; - - // 1. userInfo 데이터 구성 - const userInfo: Record = {}; - - // 모든 필드에서 user_info에 해당하는 데이터 추출 - config.sections.forEach((section) => { - if (section.repeatable) return; // 반복 섹션은 제외 - - section.fields.forEach((field) => { - const value = formData[field.columnName]; - if (value !== undefined && value !== null && value !== "") { - userInfo[field.columnName] = value; - } - }); - }); - - // 2. mainDept 데이터 구성 - let mainDept: { dept_code: string; dept_name?: string; position_name?: string } | undefined; - - if (mainDeptFields) { - const deptCode = formData[mainDeptFields.deptCodeField || "dept_code"]; - if (deptCode) { - mainDept = { - dept_code: deptCode, - dept_name: formData[mainDeptFields.deptNameField || "dept_name"], - position_name: formData[mainDeptFields.positionNameField || "position_name"], - }; - } - } - - // 3. subDepts 데이터 구성 (반복 섹션에서) - const subDepts: Array<{ dept_code: string; dept_name?: string; position_name?: string }> = []; - - if (subDeptSectionId && repeatSections[subDeptSectionId]) { - const subDeptItems = repeatSections[subDeptSectionId]; - const deptCodeField = subDeptFields?.deptCodeField || "dept_code"; - const deptNameField = subDeptFields?.deptNameField || "dept_name"; - const positionNameField = subDeptFields?.positionNameField || "position_name"; - - subDeptItems.forEach((item) => { - const deptCode = item[deptCodeField]; - if (deptCode) { - subDepts.push({ - dept_code: deptCode, - dept_name: item[deptNameField], - position_name: item[positionNameField], - }); - } - }); - } - - // 4. API 호출 - console.log("[UniversalFormModal] 사원+부서 저장 데이터:", { userInfo, mainDept, subDepts }); - - const { saveUserWithDept } = await import("@/lib/api/user"); - const response = await saveUserWithDept({ - userInfo: userInfo as any, - mainDept, - subDepts, - isUpdate: !!initialData?.user_id, // 초기 데이터가 있으면 수정 모드 - }); - - if (!response.success) { - throw new Error(response.message || "사원 저장 실패"); - } - - console.log("[UniversalFormModal] 사원+부서 저장 완료:", response.data); - }; - const saveWithGenericCustomApi = async () => { if (!customApiSave.customEndpoint) { throw new Error("커스텀 API 엔드포인트가 설정되지 않았습니다."); @@ -720,8 +800,8 @@ export function UniversalFormModalComponent({ }; switch (customApiSave.apiType) { - case "user-with-dept": - await saveUserWithDeptApi(); + case "multi-table": + await saveWithMultiTable(); break; case "custom": await saveWithGenericCustomApi(); @@ -729,10 +809,16 @@ export function UniversalFormModalComponent({ default: throw new Error(`지원하지 않는 API 타입: ${customApiSave.apiType}`); } - }, [config.sections, config.saveConfig, formData, repeatSections, initialData]); + }, [config.saveConfig, formData, repeatSections, saveWithMultiTable]); // 저장 처리 const handleSave = useCallback(async () => { + console.log("[UniversalFormModal] 저장 시작, saveConfig:", { + tableName: config.saveConfig.tableName, + customApiSave: config.saveConfig.customApiSave, + multiRowSave: config.saveConfig.multiRowSave, + }); + // 커스텀 API 저장 모드가 아닌 경우에만 테이블명 체크 if (!config.saveConfig.customApiSave?.enabled && !config.saveConfig.tableName) { toast.error("저장할 테이블이 설정되지 않았습니다."); diff --git a/frontend/lib/registry/components/universal-form-modal/UniversalFormModalConfigPanel.tsx b/frontend/lib/registry/components/universal-form-modal/UniversalFormModalConfigPanel.tsx index 8552cd6f..eb52a10f 100644 --- a/frontend/lib/registry/components/universal-form-modal/UniversalFormModalConfigPanel.tsx +++ b/frontend/lib/registry/components/universal-form-modal/UniversalFormModalConfigPanel.tsx @@ -108,6 +108,25 @@ export function UniversalFormModalConfigPanel({ config, onChange }: UniversalFor // eslint-disable-next-line react-hooks/exhaustive-deps }, [config.sections]); + // 다중 테이블 저장 설정의 메인/서브 테이블 컬럼 로드 + useEffect(() => { + const customApiSave = config.saveConfig.customApiSave; + if (customApiSave?.enabled && customApiSave?.multiTable) { + // 메인 테이블 컬럼 로드 + const mainTableName = customApiSave.multiTable.mainTable?.tableName; + if (mainTableName && !tableColumns[mainTableName]) { + loadTableColumns(mainTableName); + } + // 서브 테이블들 컬럼 로드 + customApiSave.multiTable.subTables?.forEach((subTable) => { + if (subTable.tableName && !tableColumns[subTable.tableName]) { + loadTableColumns(subTable.tableName); + } + }); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [config.saveConfig.customApiSave]); + const loadTables = async () => { try { const response = await apiClient.get("/table-management/tables"); @@ -425,58 +444,58 @@ export function UniversalFormModalConfigPanel({ config, onChange }: UniversalFor
) : ( <> - - - - - - - - - 테이블을 찾을 수 없습니다 - - {tables.map((t) => ( - { - updateSaveConfig({ tableName: t.name }); - setTableSelectOpen(false); - }} - className="text-xs" - > - - {t.name} - {t.label !== t.name && ( - ({t.label}) - )} - - ))} - - - - - - {config.saveConfig.tableName && ( -

- 컬럼 {currentColumns.length}개 로드됨 -

+ + + + + + + + + 테이블을 찾을 수 없습니다 + + {tables.map((t) => ( + { + updateSaveConfig({ tableName: t.name }); + setTableSelectOpen(false); + }} + className="text-xs" + > + + {t.name} + {t.label !== t.name && ( + ({t.label}) + )} + + ))} + + + + + + {config.saveConfig.tableName && ( +

+ 컬럼 {currentColumns.length}개 로드됨 +

)} )} @@ -592,29 +611,41 @@ export function UniversalFormModalConfigPanel({ config, onChange }: UniversalFor
)} - {/* 커스텀 API 저장 설정 */} -
-
- 전용 API 저장 + {/* 다중 테이블 저장 설정 (범용) */} +
+
+ 다중 테이블 저장 updateSaveConfig({ - customApiSave: { ...config.saveConfig.customApiSave, enabled: checked, apiType: "user-with-dept" }, + customApiSave: { + ...config.saveConfig.customApiSave, + enabled: checked, + apiType: "multi-table", + multiTable: checked ? { + enabled: true, + mainTable: { tableName: config.saveConfig.tableName || "", primaryKeyColumn: "" }, + subTables: [], + } : undefined, + }, }) } />
- 테이블 직접 저장 대신 전용 백엔드 API를 사용합니다. 복잡한 비즈니스 로직(다중 테이블, 트랜잭션)에 적합합니다. + + 메인 테이블 + 서브 테이블(반복 섹션)에 트랜잭션으로 저장합니다. +
예: 사원+부서, 주문+주문상세, 프로젝트+멤버 등 +
{config.saveConfig.customApiSave?.enabled && ( -
+
{/* API 타입 선택 */}
- +
- {/* 사원+부서 통합 저장 설정 */} - {config.saveConfig.customApiSave?.apiType === "user-with-dept" && ( -
-

- user_info와 user_dept 테이블에 트랜잭션으로 저장합니다. - 메인 부서 변경 시 기존 메인은 겸직으로 자동 전환됩니다. -

- - {/* 메인 부서 필드 매핑 */} -
- -
-
- 부서코드: - -
-
- 부서명: - -
-
- 직급: - -
+ {/* 다중 테이블 저장 설정 */} + {config.saveConfig.customApiSave?.apiType === "multi-table" && ( +
+ {/* 메인 테이블 설정 */} +
+ + 비반복 섹션의 데이터가 저장될 메인 테이블입니다. + +
+ + + + + + + + + + 테이블을 찾을 수 없습니다 + + {tables.map((table) => ( + { + updateSaveConfig({ + customApiSave: { + ...config.saveConfig.customApiSave, + multiTable: { + ...config.saveConfig.customApiSave?.multiTable, + enabled: true, + mainTable: { + ...config.saveConfig.customApiSave?.multiTable?.mainTable, + tableName: table.name, + }, + subTables: config.saveConfig.customApiSave?.multiTable?.subTables || [], + }, + }, + }); + // 테이블 컬럼 로드 + if (!tableColumns[table.name]) { + loadTableColumns(table.name); + } + }} + className="text-[10px]" + > + +
+ {table.label || table.name} + {table.label && {table.name}} +
+
+ ))} +
+
+
+
+
-
- - {/* 겸직 부서 반복 섹션 */} -
- - + updateSaveConfig({ + customApiSave: { + ...config.saveConfig.customApiSave, + multiTable: { + ...config.saveConfig.customApiSave?.multiTable, + enabled: true, + mainTable: { + ...config.saveConfig.customApiSave?.multiTable?.mainTable, + tableName: config.saveConfig.customApiSave?.multiTable?.mainTable?.tableName || "", + primaryKeyColumn: value === "_none_" ? "" : value, + }, + subTables: config.saveConfig.customApiSave?.multiTable?.subTables || [], + }, + }, + }) + } + > + + + + + 선택 안함 + {(tableColumns[config.saveConfig.customApiSave?.multiTable?.mainTable?.tableName || ""] || []).map((col) => ( + + {col.label || col.name} ))} - - + + + 서브 테이블과 연결할 때 사용할 PK 컬럼 +
- {/* 겸직 부서 필드 매핑 */} - {config.saveConfig.customApiSave?.subDeptSectionId && ( -
- -
-
- 부서코드: - { + const newSubTables = [...(config.saveConfig.customApiSave?.multiTable?.subTables || [])]; + newSubTables[subIndex] = { ...newSubTables[subIndex], repeatSectionId: value === "_none_" ? "" : value }; + updateSaveConfig({ + customApiSave: { + ...config.saveConfig.customApiSave, + multiTable: { + ...config.saveConfig.customApiSave?.multiTable, + enabled: true, + mainTable: config.saveConfig.customApiSave?.multiTable?.mainTable || { tableName: "", primaryKeyColumn: "" }, + subTables: newSubTables, + }, + }, + }); + }} + > + + + 선택 안함 {config.sections - .find((s) => s.id === config.saveConfig.customApiSave?.subDeptSectionId) - ?.fields.map((field) => ( - - {field.label} + .filter((s) => s.repeatable) + .map((section) => ( + + 반복 섹션: {section.title} ))}
-
- 부서명: - { + const newSubTables = [...(config.saveConfig.customApiSave?.multiTable?.subTables || [])]; + newSubTables[subIndex] = { + ...newSubTables[subIndex], + linkColumn: { ...newSubTables[subIndex].linkColumn, mainField: value === "_none_" ? "" : value }, + }; + updateSaveConfig({ + customApiSave: { + ...config.saveConfig.customApiSave, + multiTable: { + ...config.saveConfig.customApiSave?.multiTable, + enabled: true, + mainTable: config.saveConfig.customApiSave?.multiTable?.mainTable || { tableName: "", primaryKeyColumn: "" }, + subTables: newSubTables, + }, }, - }, - }) - } - > - - - - - {config.sections - .find((s) => s.id === config.saveConfig.customApiSave?.subDeptSectionId) - ?.fields.map((field) => ( - - {field.label} + }); + }} + > + + + + + 선택 + {/* 메인 테이블의 컬럼 목록에서 선택 */} + {(tableColumns[config.saveConfig.customApiSave?.multiTable?.mainTable?.tableName || ""] || []).map((col) => ( + + {col.label || col.name} ))} - - + + +
+ {/* 서브 테이블 컬럼 선택 (FK 컬럼) */} + +
+ 메인 테이블과 서브 테이블을 연결할 컬럼
-
- 직급: - { + const newSubTables = [...(config.saveConfig.customApiSave?.multiTable?.subTables || [])]; + const newMappings = [...(newSubTables[subIndex].fieldMappings || [])]; + newMappings[mapIndex] = { ...newMappings[mapIndex], formField: value === "_none_" ? "" : value }; + newSubTables[subIndex] = { ...newSubTables[subIndex], fieldMappings: newMappings }; + updateSaveConfig({ + customApiSave: { + ...config.saveConfig.customApiSave, + multiTable: { + ...config.saveConfig.customApiSave?.multiTable, + enabled: true, + mainTable: config.saveConfig.customApiSave?.multiTable?.mainTable || { tableName: "", primaryKeyColumn: "" }, + subTables: newSubTables, + }, + }, + }); + }} + > + + + + + 선택 + {sectionFields + .filter((f) => f.columnName && f.columnName.trim() !== "") + .map((field) => ( + + {field.label} + + ))} + + +
+ +
+ ); + })} +
+ )} + + {/* 추가 옵션 */} +
+ +
+ { + const newSubTables = [...(config.saveConfig.customApiSave?.multiTable?.subTables || [])]; + newSubTables[subIndex] = { + ...newSubTables[subIndex], + options: { ...newSubTables[subIndex].options, saveMainAsFirst: !!checked }, + }; + updateSaveConfig({ + customApiSave: { + ...config.saveConfig.customApiSave, + multiTable: { + ...config.saveConfig.customApiSave?.multiTable, + enabled: true, + mainTable: config.saveConfig.customApiSave?.multiTable?.mainTable || { tableName: "", primaryKeyColumn: "" }, + subTables: newSubTables, + }, }, - }, - }) - } - > - - - - - {config.sections - .find((s) => s.id === config.saveConfig.customApiSave?.subDeptSectionId) - ?.fields.map((field) => ( - - {field.label} - - ))} - - + }); + }} + className="shrink-0" + /> + +
+ + {subTable.options?.saveMainAsFirst && ( +
+ + + 메인/서브 구분용 컬럼 (예: is_primary) +
+ )} + +
+ { + const newSubTables = [...(config.saveConfig.customApiSave?.multiTable?.subTables || [])]; + newSubTables[subIndex] = { + ...newSubTables[subIndex], + options: { ...newSubTables[subIndex].options, deleteExistingBefore: !!checked }, + }; + updateSaveConfig({ + customApiSave: { + ...config.saveConfig.customApiSave, + multiTable: { + ...config.saveConfig.customApiSave?.multiTable, + enabled: true, + mainTable: config.saveConfig.customApiSave?.multiTable?.mainTable || { tableName: "", primaryKeyColumn: "" }, + subTables: newSubTables, + }, + }, + }); + }} + className="shrink-0" + /> + +
-
- )} + ))} + + {(config.saveConfig.customApiSave?.multiTable?.subTables || []).length === 0 && ( +

+ 서브 테이블을 추가하세요 +

+ )} +
)} {/* 커스텀 API 설정 */} {config.saveConfig.customApiSave?.apiType === "custom" && (
-
+
- - updateSaveConfig({ + onChange={(e) => + updateSaveConfig({ customApiSave: { ...config.saveConfig.customApiSave, customEndpoint: e.target.value }, - }) - } + }) + } placeholder="/api/custom/endpoint" - className="h-6 text-[10px] mt-1" - /> -
-
+ className="h-6 text-[10px] mt-1" + /> +
+
-
+
)}
@@ -1571,9 +1983,9 @@ export function UniversalFormModalConfigPanel({ config, onChange }: UniversalFor {/* 다중 컬럼 저장 (select 타입만) */} {selectedField.fieldType === "select" && ( -
-
- 다중 컬럼 저장 +
+
+ 다중 컬럼 저장 @@ -1592,10 +2004,10 @@ export function UniversalFormModalConfigPanel({ config, onChange }: UniversalFor {selectedField.linkedFieldGroup?.enabled && ( -
+
{/* 소스 테이블 */} -
- +
+ { + const updatedMappings = (selectedField.linkedFieldGroup?.mappings || []).map((m, i) => + i === mappingIndex ? { ...m, sourceColumn: value } : m + ); + updateField(selectedSection.id, selectedField.id, { + linkedFieldGroup: { + ...selectedField.linkedFieldGroup, + mappings: updatedMappings, + }, + }); + }} + > + + + + + {(tableColumns[selectedField.linkedFieldGroup?.sourceTable || ""] || []).map((col) => ( + + {col.label || col.name} + + ))} + + +
+
+ {/* 저장할 테이블 선택 */} +
+ + +
+ {/* 저장할 컬럼 선택 */} +
+ + +
-
- - -
-
- - -
-
- ))} + ); + })} {(selectedField.linkedFieldGroup?.mappings || []).length === 0 && (

diff --git a/frontend/lib/registry/components/universal-form-modal/types.ts b/frontend/lib/registry/components/universal-form-modal/types.ts index 04f7df0e..75dcf4fd 100644 --- a/frontend/lib/registry/components/universal-form-modal/types.ts +++ b/frontend/lib/registry/components/universal-form-modal/types.ts @@ -108,6 +108,7 @@ export interface FormFieldConfig { // 연동 필드 매핑 설정 export interface LinkedFieldMapping { sourceColumn: string; // 소스 테이블 컬럼 (예: "dept_code") + targetTable?: string; // 저장할 테이블 (선택, 없으면 자동 결정) targetColumn: string; // 저장할 컬럼 (예: "position_code") } @@ -194,42 +195,92 @@ export interface SaveConfig { }; } +/** + * 서브 테이블 필드 매핑 + * 폼 필드(columnName)를 서브 테이블의 컬럼에 매핑합니다. + */ +export interface SubTableFieldMapping { + formField: string; // 폼 필드의 columnName + targetColumn: string; // 서브 테이블의 컬럼명 +} + +/** + * 서브 테이블 저장 설정 + * 반복 섹션의 데이터를 별도 테이블에 저장하는 설정입니다. + */ +export interface SubTableSaveConfig { + enabled: boolean; + tableName: string; // 서브 테이블명 (예: user_dept, order_items) + repeatSectionId: string; // 연결할 반복 섹션 ID + + // 연결 설정 (메인 테이블과 서브 테이블 연결) + linkColumn: { + mainField: string; // 메인 테이블의 연결 필드 (예: user_id) + subColumn: string; // 서브 테이블의 연결 컬럼 (예: user_id) + }; + + // 필드 매핑 (반복 섹션 필드 → 서브 테이블 컬럼) + fieldMappings: SubTableFieldMapping[]; + + // 추가 옵션 + options?: { + // 메인 데이터도 서브 테이블에 저장 (1:N에서 메인도 저장할 때) + saveMainAsFirst?: boolean; + mainFieldMappings?: SubTableFieldMapping[]; // 메인 데이터용 필드 매핑 + mainMarkerColumn?: string; // 메인 여부 표시 컬럼 (예: is_primary) + mainMarkerValue?: any; // 메인일 때 값 (예: true) + subMarkerValue?: any; // 서브일 때 값 (예: false) + + // 저장 전 기존 데이터 삭제 + deleteExistingBefore?: boolean; + deleteOnlySubItems?: boolean; // 메인 항목은 유지하고 서브만 삭제 + }; +} + +/** + * 다중 테이블 저장 설정 (범용) + * + * 메인 테이블 + 서브 테이블(들)에 트랜잭션으로 저장합니다. + * + * ## 사용 예시 + * + * ### 사원 + 부서 (user_info + user_dept) + * - 메인 테이블: user_info (사원 정보) + * - 서브 테이블: user_dept (부서 관계, 메인 부서 + 겸직 부서) + * + * ### 주문 + 주문상세 (orders + order_items) + * - 메인 테이블: orders (주문 정보) + * - 서브 테이블: order_items (주문 상품 목록) + */ +export interface MultiTableSaveConfig { + enabled: boolean; + + // 메인 테이블 설정 + mainTable: { + tableName: string; // 메인 테이블명 + primaryKeyColumn: string; // PK 컬럼명 + }; + + // 서브 테이블 설정 (여러 개 가능) + subTables: SubTableSaveConfig[]; +} + /** * 커스텀 API 저장 설정 * * 테이블 직접 저장 대신 전용 백엔드 API를 호출합니다. * 복잡한 비즈니스 로직(다중 테이블 저장, 트랜잭션 등)에 사용합니다. - * - * ## 지원하는 API 타입 - * - `user-with-dept`: 사원 + 부서 통합 저장 (/api/admin/users/with-dept) - * - * ## 데이터 매핑 설정 - * - `userInfoFields`: user_info 테이블에 저장할 필드 매핑 - * - `mainDeptFields`: 메인 부서 정보 필드 매핑 - * - `subDeptSectionId`: 겸직 부서 반복 섹션 ID */ export interface CustomApiSaveConfig { enabled: boolean; - apiType: "user-with-dept" | "custom"; // 확장 가능한 API 타입 + apiType: "multi-table" | "custom"; // API 타입 - // user-with-dept 전용 설정 - userInfoFields?: string[]; // user_info에 저장할 필드 목록 (columnName) - mainDeptFields?: { - deptCodeField?: string; // 메인 부서코드 필드명 - deptNameField?: string; // 메인 부서명 필드명 - positionNameField?: string; // 메인 직급 필드명 - }; - subDeptSectionId?: string; // 겸직 부서 반복 섹션 ID - subDeptFields?: { - deptCodeField?: string; // 겸직 부서코드 필드명 - deptNameField?: string; // 겸직 부서명 필드명 - positionNameField?: string; // 겸직 직급 필드명 - }; + // 다중 테이블 저장 설정 (범용) + multiTable?: MultiTableSaveConfig; // 커스텀 API 전용 설정 customEndpoint?: string; // 커스텀 API 엔드포인트 customMethod?: "POST" | "PUT"; // HTTP 메서드 - customDataTransform?: string; // 데이터 변환 함수명 (추후 확장) } // 모달 설정 From 92a7e0eb3a104187c4271b3803b80c513300e9e6 Mon Sep 17 00:00:00 2001 From: kjs Date: Mon, 8 Dec 2025 17:56:56 +0900 Subject: [PATCH 12/18] =?UTF-8?q?=EB=A0=89=EA=B5=AC=EC=A1=B0=20=EC=A4=91?= =?UTF-8?q?=EB=B3=B5=EB=93=B1=EB=A1=9D=20=EB=B0=A9=EC=A7=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../rack-structure/RackStructureComponent.tsx | 39 +++++++++++-------- 1 file changed, 23 insertions(+), 16 deletions(-) diff --git a/frontend/lib/registry/components/rack-structure/RackStructureComponent.tsx b/frontend/lib/registry/components/rack-structure/RackStructureComponent.tsx index 7ddd6326..d80fd2c7 100644 --- a/frontend/lib/registry/components/rack-structure/RackStructureComponent.tsx +++ b/frontend/lib/registry/components/rack-structure/RackStructureComponent.tsx @@ -25,6 +25,7 @@ import { Alert, AlertDescription } from "@/components/ui/alert"; import { cn } from "@/lib/utils"; import { getCategoryLabelsByCodes } from "@/lib/api/tableCategoryValue"; import { DynamicFormApi } from "@/lib/api/dynamicForm"; +import { apiClient } from "@/lib/api/client"; import { RackStructureComponentProps, RackLineCondition, @@ -398,8 +399,8 @@ export const RackStructureComponent: React.FC = ({ // 기존 데이터 조회를 위한 값 추출 (useMemo 객체 참조 문제 방지) const warehouseCodeForQuery = context.warehouseCode; - const floorForQuery = context.floor; - const zoneForQuery = context.zone; + const floorForQuery = context.floor; // 라벨 값 (예: "1층") + const zoneForQuery = context.zone; // 라벨 값 (예: "A구역") // 기존 데이터 조회 (창고/층/구역이 변경될 때마다) useEffect(() => { @@ -411,6 +412,7 @@ export const RackStructureComponent: React.FC = ({ }); // 필수 조건이 충족되지 않으면 기존 데이터 초기화 + // DB에는 라벨 값(예: "1층", "A구역")으로 저장되어 있으므로 라벨 값 사용 if (!warehouseCodeForQuery || !floorForQuery || !zoneForQuery) { console.log("⚠️ [RackStructure] 필수 조건 미충족 - 조회 스킵"); setExistingLocations([]); @@ -421,27 +423,32 @@ export const RackStructureComponent: React.FC = ({ setIsCheckingDuplicates(true); try { // warehouse_location 테이블에서 해당 창고/층/구역의 기존 데이터 조회 - const filterParams = { - warehouse_id: warehouseCodeForQuery, - floor: floorForQuery, - zone: zoneForQuery, + // DB에는 라벨 값으로 저장되어 있으므로 라벨 값으로 필터링 + // equals 연산자를 사용하여 정확한 일치 검색 (ILIKE가 아닌 = 연산자 사용) + const searchParams = { + warehouse_id: { value: warehouseCodeForQuery, operator: "equals" }, + floor: { value: floorForQuery, operator: "equals" }, + zone: { value: zoneForQuery, operator: "equals" }, }; - console.log("🔍 기존 위치 데이터 조회 시작:", filterParams); + console.log("🔍 기존 위치 데이터 조회 시작 (정확한 일치):", searchParams); - const response = await DynamicFormApi.getTableData("warehouse_location", { - filters: filterParams, + // 직접 apiClient 사용하여 정확한 형식으로 요청 + // 백엔드는 search를 객체로 받아서 각 필드를 WHERE 조건으로 처리 + const response = await apiClient.post(`/table-management/tables/warehouse_location/data`, { page: 1, - pageSize: 1000, // 충분히 큰 값 + size: 1000, // 충분히 큰 값 + search: searchParams, // 백엔드가 기대하는 형식 (equals 연산자로 정확한 일치) }); - console.log("🔍 기존 위치 데이터 응답:", response); + console.log("🔍 기존 위치 데이터 응답:", response.data); - // API 응답 구조: { success: true, data: [...] } 또는 { success: true, data: { data: [...] } } - const dataArray = Array.isArray(response.data) - ? response.data - : (response.data?.data || []); + // API 응답 구조: { success: true, data: { data: [...], total, ... } } + const responseData = response.data?.data || response.data; + const dataArray = Array.isArray(responseData) + ? responseData + : (responseData?.data || []); - if (response.success && dataArray.length > 0) { + if (dataArray.length > 0) { const existing = dataArray.map((item: any) => ({ row_num: item.row_num, level_num: item.level_num, From 5b456765ad6764993348b3c410e1367f583a7e9f Mon Sep 17 00:00:00 2001 From: leeheejin Date: Mon, 8 Dec 2025 18:16:59 +0900 Subject: [PATCH 13/18] =?UTF-8?q?=EB=8C=80=EC=8B=9C=EB=B3=B4=EB=93=9C=20?= =?UTF-8?q?=ED=86=B5=EA=B3=84=EC=B9=B4=EB=93=9C=20=EC=9C=84=EC=A0=AF?= =?UTF-8?q?=EC=97=90=20=EC=86=8C=EC=88=98=EC=A0=90=20=EC=9E=90=EB=A6=BF?= =?UTF-8?q?=EC=88=98=20=ED=91=9C=EC=8B=9C=20=ED=95=A0=20=EC=88=98=20?= =?UTF-8?q?=EC=9E=88=EB=8A=94=20=EA=B8=B0=EB=8A=A5=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../widget-sections/CustomMetricSection.tsx | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/frontend/components/admin/dashboard/widget-sections/CustomMetricSection.tsx b/frontend/components/admin/dashboard/widget-sections/CustomMetricSection.tsx index 97c0f395..7a3d10ea 100644 --- a/frontend/components/admin/dashboard/widget-sections/CustomMetricSection.tsx +++ b/frontend/components/admin/dashboard/widget-sections/CustomMetricSection.tsx @@ -233,7 +233,29 @@ export function CustomMetricSection({ queryResult, config, onConfigChange }: Cus />

- {/* 6. 자동 새로고침 간격 */} + {/* 6. 소수점 자릿수 */} +
+ + +

+ 표시할 소수점 자릿수 (평균, 비율 등에 유용) +

+
+ + {/* 7. 자동 새로고침 간격 */}
onUpdate({ partType: value as CodePartType })} + onValueChange={(value) => { + const newPartType = value as CodePartType; + // 타입 변경 시 해당 타입의 기본 autoConfig 설정 + const defaultAutoConfig: Record = { + sequence: { sequenceLength: 3, startFrom: 1 }, + number: { numberLength: 4, numberValue: 1 }, + date: { dateFormat: "YYYYMMDD" }, + text: { textValue: "CODE" }, + }; + onUpdate({ + partType: newPartType, + autoConfig: defaultAutoConfig[newPartType] || {} + }); + }} disabled={isPreview} > diff --git a/frontend/components/numbering-rule/NumberingRuleDesigner.tsx b/frontend/components/numbering-rule/NumberingRuleDesigner.tsx index 0cb6635d..3a20b883 100644 --- a/frontend/components/numbering-rule/NumberingRuleDesigner.tsx +++ b/frontend/components/numbering-rule/NumberingRuleDesigner.tsx @@ -196,10 +196,31 @@ export const NumberingRuleDesigner: React.FC = ({ try { const existing = savedRules.find((r) => r.ruleId === currentRule.ruleId); + // 파트별 기본 autoConfig 정의 + const defaultAutoConfigs: Record = { + sequence: { sequenceLength: 3, startFrom: 1 }, + number: { numberLength: 4, numberValue: 1 }, + date: { dateFormat: "YYYYMMDD" }, + text: { textValue: "" }, + }; + + // 저장 전에 각 파트의 autoConfig에 기본값 채우기 + const partsWithDefaults = currentRule.parts.map((part) => { + if (part.generationMethod === "auto") { + const defaults = defaultAutoConfigs[part.partType] || {}; + return { + ...part, + autoConfig: { ...defaults, ...part.autoConfig }, + }; + } + return part; + }); + // 저장 전에 현재 화면의 테이블명과 menuObjid 자동 설정 // 메뉴 기반으로 채번규칙 관리 (menuObjid로 필터링) const ruleToSave = { ...currentRule, + parts: partsWithDefaults, scopeType: "menu" as const, // 메뉴 기반 채번규칙 tableName: currentTableName || currentRule.tableName || null, // 현재 테이블명 (참고용) menuObjid: menuObjid || currentRule.menuObjid || null, // 메뉴 OBJID (필터링 기준) diff --git a/frontend/lib/registry/components/universal-form-modal/UniversalFormModalComponent.tsx b/frontend/lib/registry/components/universal-form-modal/UniversalFormModalComponent.tsx index eda2f94d..11b3aa43 100644 --- a/frontend/lib/registry/components/universal-form-modal/UniversalFormModalComponent.tsx +++ b/frontend/lib/registry/components/universal-form-modal/UniversalFormModalComponent.tsx @@ -23,7 +23,7 @@ import { ChevronDown, ChevronUp, Plus, Trash2, RefreshCw } from "lucide-react"; import { toast } from "sonner"; import { cn } from "@/lib/utils"; import { apiClient } from "@/lib/api/client"; -import { generateNumberingCode } from "@/lib/api/numberingRule"; +import { generateNumberingCode, allocateNumberingCode } from "@/lib/api/numberingRule"; import { UniversalFormModalComponentProps, @@ -123,14 +123,12 @@ export function UniversalFormModalComponent({ useEffect(() => { // 이미 초기화되었으면 스킵 if (hasInitialized.current) { - console.log("[UniversalFormModal] 이미 초기화됨, 스킵"); return; } // 최초 initialData 캡처 (이후 변경되어도 이 값 사용) if (initialData && Object.keys(initialData).length > 0) { capturedInitialData.current = JSON.parse(JSON.stringify(initialData)); // 깊은 복사 - console.log("[UniversalFormModal] initialData 캡처:", capturedInitialData.current); } hasInitialized.current = true; @@ -142,7 +140,6 @@ export function UniversalFormModalComponent({ useEffect(() => { if (!hasInitialized.current) return; // 최초 초기화 전이면 스킵 - console.log("[UniversalFormModal] config 변경 감지, 재초기화"); initializeForm(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [config]); @@ -164,7 +161,6 @@ export function UniversalFormModalComponent({ // 각 테이블 데이터 로드 for (const tableName of tablesToLoad) { if (!linkedFieldDataCache[tableName]) { - console.log(`[UniversalFormModal] linkedFieldGroup 데이터 로드: ${tableName}`); await loadLinkedFieldData(tableName); } } @@ -178,7 +174,6 @@ export function UniversalFormModalComponent({ const initializeForm = useCallback(async () => { // 캡처된 initialData 사용 (props로 전달된 initialData가 아닌) const effectiveInitialData = capturedInitialData.current || initialData; - console.log("[UniversalFormModal] 폼 초기화 시작, effectiveInitialData:", effectiveInitialData); const newFormData: FormDataState = {}; const newRepeatSections: { [sectionId: string]: RepeatSectionItem[] } = {}; @@ -212,7 +207,6 @@ export function UniversalFormModalComponent({ // receiveFromParent가 true이거나, effectiveInitialData에 값이 있으면 적용 if (field.receiveFromParent || value === "" || value === undefined) { value = effectiveInitialData[parentField]; - console.log(`[UniversalFormModal] 필드 ${field.columnName}: initialData에서 값 적용 = ${value}`); } } } @@ -506,18 +500,26 @@ export function UniversalFormModalComponent({ } }); - // 저장 시점 채번규칙 처리 + // 저장 시점 채번규칙 처리 (allocateNumberingCode로 실제 순번 증가) for (const section of config.sections) { for (const field of section.fields) { if ( field.numberingRule?.enabled && - field.numberingRule?.generateOnSave && - field.numberingRule?.ruleId && - !dataToSave[field.columnName] + field.numberingRule?.ruleId ) { - const response = await generateNumberingCode(field.numberingRule.ruleId); - if (response.success && response.data?.generatedCode) { - dataToSave[field.columnName] = response.data.generatedCode; + // generateOnSave: 저장 시 새로 생성 + // generateOnOpen: 열 때 미리보기로 표시했지만, 저장 시 실제 순번 할당 필요 + if (field.numberingRule.generateOnSave && !dataToSave[field.columnName]) { + const response = await allocateNumberingCode(field.numberingRule.ruleId); + if (response.success && response.data?.generatedCode) { + dataToSave[field.columnName] = response.data.generatedCode; + } + } else if (field.numberingRule.generateOnOpen && dataToSave[field.columnName]) { + // generateOnOpen인 경우, 미리보기 값이 있더라도 실제 순번 할당 + const response = await allocateNumberingCode(field.numberingRule.ruleId); + if (response.success && response.data?.generatedCode) { + dataToSave[field.columnName] = response.data.generatedCode; + } } } } @@ -542,7 +544,6 @@ export function UniversalFormModalComponent({ if (commonFields.length === 0) { const nonRepeatableSections = config.sections.filter((s) => !s.repeatable); commonFields = nonRepeatableSections.flatMap((s) => s.fields.map((f) => f.columnName)); - console.log("[UniversalFormModal] 공통 필드 자동 설정:", commonFields); } // 반복 섹션 ID가 설정되지 않은 경우, 첫 번째 반복 섹션 사용 @@ -550,22 +551,9 @@ export function UniversalFormModalComponent({ const repeatableSection = config.sections.find((s) => s.repeatable); if (repeatableSection) { repeatSectionId = repeatableSection.id; - console.log("[UniversalFormModal] 반복 섹션 자동 설정:", repeatSectionId); } } - // 디버깅: 설정 확인 - console.log("[UniversalFormModal] 다중 행 저장 설정:", { - commonFields, - repeatSectionId, - mainSectionFields, - typeColumn, - mainTypeValue, - subTypeValue, - repeatSections, - formData, - }); - // 반복 섹션 데이터 const repeatItems = repeatSections[repeatSectionId] || []; @@ -588,10 +576,6 @@ export function UniversalFormModalComponent({ } }); - console.log("[UniversalFormModal] 공통 데이터:", commonData); - console.log("[UniversalFormModal] 메인 섹션 데이터:", mainSectionData); - console.log("[UniversalFormModal] 반복 항목:", repeatItems); - // 메인 행 (공통 데이터 + 메인 섹션 필드) const mainRow: any = { ...commonData, ...mainSectionData }; if (typeColumn) { @@ -623,16 +607,20 @@ export function UniversalFormModalComponent({ if (section.repeatable) continue; for (const field of section.fields) { - if (field.numberingRule?.enabled && field.numberingRule?.generateOnSave && field.numberingRule?.ruleId) { - const response = await generateNumberingCode(field.numberingRule.ruleId); - if (response.success && response.data?.generatedCode) { - // 모든 행에 동일한 채번 값 적용 (공통 필드인 경우) - if (commonFields.includes(field.columnName)) { - rowsToSave.forEach((row) => { - row[field.columnName] = response.data?.generatedCode; - }); - } else { - rowsToSave[0][field.columnName] = response.data?.generatedCode; + if (field.numberingRule?.enabled && field.numberingRule?.ruleId) { + // generateOnSave 또는 generateOnOpen 모두 저장 시 실제 순번 할당 + const shouldAllocate = field.numberingRule.generateOnSave || field.numberingRule.generateOnOpen; + if (shouldAllocate) { + const response = await allocateNumberingCode(field.numberingRule.ruleId); + if (response.success && response.data?.generatedCode) { + // 모든 행에 동일한 채번 값 적용 (공통 필드인 경우) + if (commonFields.includes(field.columnName)) { + rowsToSave.forEach((row) => { + row[field.columnName] = response.data?.generatedCode; + }); + } else { + rowsToSave[0][field.columnName] = response.data?.generatedCode; + } } } } @@ -640,16 +628,11 @@ export function UniversalFormModalComponent({ } // 모든 행 저장 - console.log("[UniversalFormModal] 저장할 행들:", rowsToSave); - console.log("[UniversalFormModal] 저장 테이블:", config.saveConfig.tableName); - for (let i = 0; i < rowsToSave.length; i++) { const row = rowsToSave[i]; - console.log(`[UniversalFormModal] ${i + 1}번째 행 저장 시도:`, row); // 빈 객체 체크 if (Object.keys(row).length === 0) { - console.warn(`[UniversalFormModal] ${i + 1}번째 행이 비어있습니다. 건너뜁니다.`); continue; } @@ -659,8 +642,6 @@ export function UniversalFormModalComponent({ throw new Error(response.data?.message || `${i + 1}번째 행 저장 실패`); } } - - console.log(`[UniversalFormModal] ${rowsToSave.length}개 행 저장 완료`); }, [config.sections, config.saveConfig, formData, repeatSections]); // 다중 테이블 저장 (범용) @@ -669,9 +650,6 @@ export function UniversalFormModalComponent({ if (!customApiSave?.multiTable) return; const { multiTable } = customApiSave; - console.log("[UniversalFormModal] 다중 테이블 저장 시작:", multiTable); - console.log("[UniversalFormModal] 현재 formData:", formData); - console.log("[UniversalFormModal] 현재 repeatSections:", repeatSections); // 1. 메인 테이블 데이터 구성 const mainData: Record = {}; @@ -685,6 +663,35 @@ export function UniversalFormModalComponent({ }); }); + // 1-1. 채번규칙 처리 (저장 시점에 실제 순번 할당) + for (const section of config.sections) { + if (section.repeatable) continue; + + for (const field of section.fields) { + // 채번규칙이 활성화된 필드 처리 + if ( + field.numberingRule?.enabled && + field.numberingRule?.ruleId + ) { + // 신규 생성이거나 값이 없는 경우에만 채번 + const isNewRecord = !initialData?.[multiTable.mainTable.primaryKeyColumn]; + const hasNoValue = !mainData[field.columnName]; + + if (isNewRecord || hasNoValue) { + try { + // allocateNumberingCode로 실제 순번 증가 + const response = await allocateNumberingCode(field.numberingRule.ruleId); + if (response.success && response.data?.generatedCode) { + mainData[field.columnName] = response.data.generatedCode; + } + } catch (error) { + console.error(`채번규칙 할당 실패 (${field.columnName}):`, error); + } + } + } + } + } + // 2. 서브 테이블 데이터 구성 const subTablesData: Array<{ tableName: string; @@ -770,8 +777,6 @@ export function UniversalFormModalComponent({ mainFieldMappings = mainFieldMappings.filter((m, idx, arr) => arr.findIndex(x => x.targetColumn === m.targetColumn) === idx ); - - console.log("[UniversalFormModal] 메인 필드 매핑 생성:", mainFieldMappings); } subTablesData.push({ @@ -786,12 +791,6 @@ export function UniversalFormModalComponent({ } // 3. 범용 다중 테이블 저장 API 호출 - console.log("[UniversalFormModal] 다중 테이블 저장 데이터:", { - mainTable: multiTable.mainTable, - mainData, - subTablesData, - }); - const response = await apiClient.post("/table-management/multi-table-save", { mainTable: multiTable.mainTable, mainData, @@ -802,8 +801,6 @@ export function UniversalFormModalComponent({ if (!response.data?.success) { throw new Error(response.data?.message || "다중 테이블 저장 실패"); } - - console.log("[UniversalFormModal] 다중 테이블 저장 완료:", response.data); }, [config.sections, config.saveConfig, formData, repeatSections, initialData]); // 커스텀 API 저장 @@ -811,8 +808,6 @@ export function UniversalFormModalComponent({ const { customApiSave } = config.saveConfig; if (!customApiSave) return; - console.log("[UniversalFormModal] 커스텀 API 저장 시작:", customApiSave.apiType); - const saveWithGenericCustomApi = async () => { if (!customApiSave.customEndpoint) { throw new Error("커스텀 API 엔드포인트가 설정되지 않았습니다."); @@ -856,12 +851,6 @@ export function UniversalFormModalComponent({ // 저장 처리 const handleSave = useCallback(async () => { - console.log("[UniversalFormModal] 저장 시작, saveConfig:", { - tableName: config.saveConfig.tableName, - customApiSave: config.saveConfig.customApiSave, - multiRowSave: config.saveConfig.multiRowSave, - }); - // 커스텀 API 저장 모드가 아닌 경우에만 테이블명 체크 if (!config.saveConfig.customApiSave?.enabled && !config.saveConfig.tableName) { toast.error("저장할 테이블이 설정되지 않았습니다."); diff --git a/frontend/lib/registry/components/universal-form-modal/UniversalFormModalConfigPanel.tsx b/frontend/lib/registry/components/universal-form-modal/UniversalFormModalConfigPanel.tsx index eb52a10f..e503ebfb 100644 --- a/frontend/lib/registry/components/universal-form-modal/UniversalFormModalConfigPanel.tsx +++ b/frontend/lib/registry/components/universal-form-modal/UniversalFormModalConfigPanel.tsx @@ -728,7 +728,7 @@ export function UniversalFormModalConfigPanel({ config, onChange }: UniversalFor
{table.label || table.name} {table.label && {table.name}} -
+
))} @@ -743,7 +743,7 @@ export function UniversalFormModalConfigPanel({ config, onChange }: UniversalFor + + + + + {regionOptions.map((option) => ( + + {option.label} + + ))} + + + {/* 이동경로 날짜 선택 */} {selectedUserId && (
@@ -1442,8 +1461,8 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) { ); })} - {/* 마커 렌더링 */} - {markers.map((marker) => { + {/* 마커 렌더링 (지역 필터 적용) */} + {filterVehiclesByRegion(markers, selectedRegion).map((marker) => { // 마커의 소스에 해당하는 데이터 소스 찾기 const sourceDataSource = dataSources?.find((ds) => ds.name === marker.source) || dataSources?.[0]; const markerType = sourceDataSource?.markerType || "circle"; @@ -1771,7 +1790,12 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) { {/* 하단 정보 */} {(markers.length > 0 || polygons.length > 0) && (
- {markers.length > 0 && `마커 ${markers.length}개`} + {markers.length > 0 && ( + <> + 마커 {filterVehiclesByRegion(markers, selectedRegion).length}개 + {selectedRegion !== "all" && ` (전체 ${markers.length}개)`} + + )} {markers.length > 0 && polygons.length > 0 && " · "} {polygons.length > 0 && `영역 ${polygons.length}개`}
diff --git a/frontend/lib/constants/regionBounds.ts b/frontend/lib/constants/regionBounds.ts new file mode 100644 index 00000000..2b0f15ba --- /dev/null +++ b/frontend/lib/constants/regionBounds.ts @@ -0,0 +1,238 @@ +/** + * 전국 시/도별 좌표 범위 (경계 좌표) + * 차량 위치 필터링에 사용 + */ + +export interface RegionBounds { + south: number; // 최남단 위도 + north: number; // 최북단 위도 + west: number; // 최서단 경도 + east: number; // 최동단 경도 +} + +export interface RegionOption { + value: string; + label: string; + bounds?: RegionBounds; +} + +// 전국 시/도별 좌표 범위 +export const regionBounds: Record = { + // 서울특별시 + seoul: { + south: 37.413, + north: 37.715, + west: 126.734, + east: 127.183, + }, + // 부산광역시 + busan: { + south: 34.879, + north: 35.389, + west: 128.758, + east: 129.314, + }, + // 대구광역시 + daegu: { + south: 35.601, + north: 36.059, + west: 128.349, + east: 128.761, + }, + // 인천광역시 + incheon: { + south: 37.166, + north: 37.592, + west: 126.349, + east: 126.775, + }, + // 광주광역시 + gwangju: { + south: 35.053, + north: 35.267, + west: 126.652, + east: 127.013, + }, + // 대전광역시 + daejeon: { + south: 36.197, + north: 36.488, + west: 127.246, + east: 127.538, + }, + // 울산광역시 + ulsan: { + south: 35.360, + north: 35.710, + west: 128.958, + east: 129.464, + }, + // 세종특별자치시 + sejong: { + south: 36.432, + north: 36.687, + west: 127.044, + east: 127.364, + }, + // 경기도 + gyeonggi: { + south: 36.893, + north: 38.284, + west: 126.387, + east: 127.839, + }, + // 강원도 (강원특별자치도) + gangwon: { + south: 37.017, + north: 38.613, + west: 127.085, + east: 129.359, + }, + // 충청북도 + chungbuk: { + south: 36.012, + north: 37.261, + west: 127.282, + east: 128.657, + }, + // 충청남도 + chungnam: { + south: 35.972, + north: 37.029, + west: 125.927, + east: 127.380, + }, + // 전라북도 (전북특별자치도) + jeonbuk: { + south: 35.287, + north: 36.133, + west: 126.392, + east: 127.923, + }, + // 전라남도 + jeonnam: { + south: 33.959, + north: 35.507, + west: 125.979, + east: 127.921, + }, + // 경상북도 + gyeongbuk: { + south: 35.571, + north: 37.144, + west: 128.113, + east: 130.922, + }, + // 경상남도 + gyeongnam: { + south: 34.599, + north: 35.906, + west: 127.555, + east: 129.224, + }, + // 제주특별자치도 + jeju: { + south: 33.106, + north: 33.959, + west: 126.117, + east: 126.978, + }, +}; + +// 지역 선택 옵션 (드롭다운용) +export const regionOptions: RegionOption[] = [ + { value: "all", label: "전체" }, + { value: "seoul", label: "서울특별시", bounds: regionBounds.seoul }, + { value: "busan", label: "부산광역시", bounds: regionBounds.busan }, + { value: "daegu", label: "대구광역시", bounds: regionBounds.daegu }, + { value: "incheon", label: "인천광역시", bounds: regionBounds.incheon }, + { value: "gwangju", label: "광주광역시", bounds: regionBounds.gwangju }, + { value: "daejeon", label: "대전광역시", bounds: regionBounds.daejeon }, + { value: "ulsan", label: "울산광역시", bounds: regionBounds.ulsan }, + { value: "sejong", label: "세종특별자치시", bounds: regionBounds.sejong }, + { value: "gyeonggi", label: "경기도", bounds: regionBounds.gyeonggi }, + { value: "gangwon", label: "강원특별자치도", bounds: regionBounds.gangwon }, + { value: "chungbuk", label: "충청북도", bounds: regionBounds.chungbuk }, + { value: "chungnam", label: "충청남도", bounds: regionBounds.chungnam }, + { value: "jeonbuk", label: "전북특별자치도", bounds: regionBounds.jeonbuk }, + { value: "jeonnam", label: "전라남도", bounds: regionBounds.jeonnam }, + { value: "gyeongbuk", label: "경상북도", bounds: regionBounds.gyeongbuk }, + { value: "gyeongnam", label: "경상남도", bounds: regionBounds.gyeongnam }, + { value: "jeju", label: "제주특별자치도", bounds: regionBounds.jeju }, +]; + +/** + * 좌표가 특정 지역 범위 내에 있는지 확인 + */ +export function isInRegion( + latitude: number, + longitude: number, + region: string +): boolean { + if (region === "all") return true; + + const bounds = regionBounds[region]; + if (!bounds) return false; + + return ( + latitude >= bounds.south && + latitude <= bounds.north && + longitude >= bounds.west && + longitude <= bounds.east + ); +} + +/** + * 좌표로 지역 찾기 (해당하는 첫 번째 지역 반환) + */ +export function findRegionByCoords( + latitude: number, + longitude: number +): string | null { + for (const [region, bounds] of Object.entries(regionBounds)) { + if ( + latitude >= bounds.south && + latitude <= bounds.north && + longitude >= bounds.west && + longitude <= bounds.east + ) { + return region; + } + } + return null; +} + +/** + * 차량 목록을 지역별로 필터링 + */ +export function filterVehiclesByRegion< + T extends { latitude?: number; longitude?: number; lat?: number; lng?: number } +>(vehicles: T[], region: string): T[] { + if (region === "all") return vehicles; + + const bounds = regionBounds[region]; + if (!bounds) return vehicles; + + return vehicles.filter((v) => { + const lat = v.latitude ?? v.lat; + const lng = v.longitude ?? v.lng; + + if (lat === undefined || lng === undefined) return false; + + return ( + lat >= bounds.south && + lat <= bounds.north && + lng >= bounds.west && + lng <= bounds.east + ); + }); +} + +/** + * 지역명(한글) 가져오기 + */ +export function getRegionLabel(regionValue: string): string { + const option = regionOptions.find((opt) => opt.value === regionValue); + return option?.label ?? regionValue; +} +