diff --git a/backend-node/src/app.ts b/backend-node/src/app.ts index 8a01bdaf..39262f81 100644 --- a/backend-node/src/app.ts +++ b/backend-node/src/app.ts @@ -31,6 +31,7 @@ import layoutRoutes from "./routes/layoutRoutes"; import dataRoutes from "./routes/dataRoutes"; import testButtonDataflowRoutes from "./routes/testButtonDataflowRoutes"; import externalDbConnectionRoutes from "./routes/externalDbConnectionRoutes"; +import entityReferenceRoutes from "./routes/entityReferenceRoutes"; // import userRoutes from './routes/userRoutes'; // import menuRoutes from './routes/menuRoutes'; @@ -125,6 +126,7 @@ app.use("/api/screen", screenStandardRoutes); app.use("/api/data", dataRoutes); app.use("/api/test-button-dataflow", testButtonDataflowRoutes); app.use("/api/external-db-connections", externalDbConnectionRoutes); +app.use("/api/entity-reference", entityReferenceRoutes); // app.use('/api/users', userRoutes); // app.use('/api/menus', menuRoutes); diff --git a/backend-node/src/controllers/dataflowDiagramController.ts b/backend-node/src/controllers/dataflowDiagramController.ts index 7e955e78..e18ef615 100644 --- a/backend-node/src/controllers/dataflowDiagramController.ts +++ b/backend-node/src/controllers/dataflowDiagramController.ts @@ -143,16 +143,36 @@ export const createDataflowDiagram = async (req: Request, res: Response) => { message: "관계도가 성공적으로 생성되었습니다.", }); } catch (error) { - logger.error("관계도 생성 실패:", error); + // 디버깅을 위한 에러 정보 출력 + logger.error("에러 디버깅:", { + errorType: typeof error, + errorCode: (error as any)?.code, + errorMessage: error instanceof Error ? error.message : "Unknown error", + errorName: (error as any)?.name, + errorMeta: (error as any)?.meta, + }); - // 중복 이름 에러 처리 - if (error instanceof Error && error.message.includes("unique constraint")) { + // 중복 이름 에러인지 먼저 확인 (로그 출력 전에) + const isDuplicateError = + (error && typeof error === "object" && (error as any).code === "P2002") || // Prisma unique constraint error code + (error instanceof Error && + (error.message.includes("unique constraint") || + error.message.includes("Unique constraint") || + error.message.includes("duplicate key") || + error.message.includes("UNIQUE constraint failed") || + error.message.includes("unique_diagram_name_per_company"))); + + if (isDuplicateError) { + // 중복 에러는 콘솔에 로그 출력하지 않음 return res.status(409).json({ success: false, - message: "이미 존재하는 관계도 이름입니다.", + message: "중복된 이름입니다.", }); } + // 다른 에러만 로그 출력 + logger.error("관계도 생성 실패:", error); + return res.status(500).json({ success: false, message: "관계도 생성 중 오류가 발생했습니다.", @@ -214,6 +234,25 @@ export const updateDataflowDiagram = async (req: Request, res: Response) => { message: "관계도가 성공적으로 수정되었습니다.", }); } catch (error) { + // 중복 이름 에러인지 먼저 확인 (로그 출력 전에) + const isDuplicateError = + (error && typeof error === "object" && (error as any).code === "P2002") || // Prisma unique constraint error code + (error instanceof Error && + (error.message.includes("unique constraint") || + error.message.includes("Unique constraint") || + error.message.includes("duplicate key") || + error.message.includes("UNIQUE constraint failed") || + error.message.includes("unique_diagram_name_per_company"))); + + if (isDuplicateError) { + // 중복 에러는 콘솔에 로그 출력하지 않음 + return res.status(409).json({ + success: false, + message: "중복된 이름입니다.", + }); + } + + // 다른 에러만 로그 출력 logger.error("관계도 수정 실패:", error); return res.status(500).json({ success: false, diff --git a/backend-node/src/controllers/entityReferenceController.ts b/backend-node/src/controllers/entityReferenceController.ts new file mode 100644 index 00000000..af360b6c --- /dev/null +++ b/backend-node/src/controllers/entityReferenceController.ts @@ -0,0 +1,208 @@ +import { Request, Response } from "express"; +import { PrismaClient } from "@prisma/client"; +import { logger } from "../utils/logger"; + +const prisma = new PrismaClient(); + +export interface EntityReferenceOption { + value: string; + label: string; +} + +export interface EntityReferenceData { + options: EntityReferenceOption[]; + referenceInfo: { + referenceTable: string; + referenceColumn: string; + displayColumn: string | null; + }; +} + +export interface CodeReferenceData { + options: EntityReferenceOption[]; + codeCategory: string; +} + +export class EntityReferenceController { + /** + * 엔티티 참조 데이터 조회 + * GET /api/entity-reference/:tableName/:columnName + */ + static async getEntityReferenceData(req: Request, res: Response) { + try { + const { tableName, columnName } = req.params; + const { limit = 100, search } = req.query; + + logger.info(`엔티티 참조 데이터 조회 요청: ${tableName}.${columnName}`, { + limit, + search, + }); + + // 컬럼 정보 조회 + const columnInfo = await prisma.column_labels.findFirst({ + where: { + table_name: tableName, + column_name: columnName, + }, + }); + + if (!columnInfo) { + return res.status(404).json({ + success: false, + message: `컬럼 정보를 찾을 수 없습니다: ${tableName}.${columnName}`, + }); + } + + // webType 확인 + if (columnInfo.web_type !== "entity") { + return res.status(400).json({ + success: false, + message: `컬럼 '${tableName}.${columnName}'은 entity 타입이 아닙니다. webType: ${columnInfo.web_type}`, + }); + } + + // column_labels에서 직접 참조 정보 가져오기 + const referenceTable = columnInfo.reference_table; + const referenceColumn = columnInfo.reference_column; + const displayColumn = columnInfo.display_column || "name"; + + // entity 타입인데 참조 테이블 정보가 없으면 오류 + if (!referenceTable || !referenceColumn) { + return res.status(400).json({ + success: false, + message: `Entity 타입 컬럼 '${tableName}.${columnName}'에 참조 테이블 정보가 설정되지 않았습니다. column_labels에서 reference_table과 reference_column을 확인해주세요.`, + }); + } + + // 참조 테이블이 실제로 존재하는지 확인 + try { + await prisma.$queryRawUnsafe(`SELECT 1 FROM ${referenceTable} LIMIT 1`); + logger.info( + `Entity 참조 설정: ${tableName}.${columnName} -> ${referenceTable}.${referenceColumn} (display: ${displayColumn})` + ); + } catch (error) { + logger.error( + `참조 테이블 '${referenceTable}'이 존재하지 않습니다:`, + error + ); + return res.status(400).json({ + success: false, + message: `참조 테이블 '${referenceTable}'이 존재하지 않습니다. column_labels의 reference_table 설정을 확인해주세요.`, + }); + } + + // 동적 쿼리로 참조 데이터 조회 + let query = `SELECT ${referenceColumn}, ${displayColumn} as display_name FROM ${referenceTable}`; + const queryParams: any[] = []; + + // 검색 조건 추가 + if (search) { + query += ` WHERE ${displayColumn} ILIKE $1`; + queryParams.push(`%${search}%`); + } + + query += ` ORDER BY ${displayColumn} LIMIT $${queryParams.length + 1}`; + queryParams.push(Number(limit)); + + logger.info(`실행할 쿼리: ${query}`, { + queryParams, + referenceTable, + referenceColumn, + displayColumn, + }); + + const referenceData = await prisma.$queryRawUnsafe(query, ...queryParams); + + // 옵션 형태로 변환 + const options: EntityReferenceOption[] = (referenceData as any[]).map( + (row) => ({ + value: String(row[referenceColumn]), + label: String(row.display_name || row[referenceColumn]), + }) + ); + + logger.info(`엔티티 참조 데이터 조회 완료: ${options.length}개 항목`); + + return res.json({ + success: true, + data: { + options, + referenceInfo: { + referenceTable, + referenceColumn, + displayColumn, + }, + }, + }); + } catch (error) { + logger.error("엔티티 참조 데이터 조회 실패:", error); + return res.status(500).json({ + success: false, + message: "엔티티 참조 데이터 조회 중 오류가 발생했습니다.", + }); + } + } + + /** + * 공통 코드 데이터 조회 + * GET /api/entity-reference/code/:codeCategory + */ + static async getCodeData(req: Request, res: Response) { + try { + const { codeCategory } = req.params; + const { limit = 100, search } = req.query; + + logger.info(`공통 코드 데이터 조회 요청: ${codeCategory}`, { + limit, + search, + }); + + // code_info 테이블에서 코드 데이터 조회 + let whereCondition: any = { + code_category: codeCategory, + is_active: "Y", + }; + + if (search) { + whereCondition.code_name = { + contains: String(search), + mode: "insensitive", + }; + } + + const codeData = await prisma.code_info.findMany({ + where: whereCondition, + select: { + code_value: true, + code_name: true, + }, + orderBy: { + code_name: "asc", + }, + take: Number(limit), + }); + + // 옵션 형태로 변환 + const options: EntityReferenceOption[] = codeData.map((code) => ({ + value: code.code_value, + label: code.code_name, + })); + + logger.info(`공통 코드 데이터 조회 완료: ${options.length}개 항목`); + + return res.json({ + success: true, + data: { + options, + codeCategory, + }, + }); + } catch (error) { + logger.error("공통 코드 데이터 조회 실패:", error); + return res.status(500).json({ + success: false, + message: "공통 코드 데이터 조회 중 오류가 발생했습니다.", + }); + } + } +} diff --git a/backend-node/src/routes/entityReferenceRoutes.ts b/backend-node/src/routes/entityReferenceRoutes.ts new file mode 100644 index 00000000..996d569c --- /dev/null +++ b/backend-node/src/routes/entityReferenceRoutes.ts @@ -0,0 +1,27 @@ +import { Router } from "express"; +import { EntityReferenceController } from "../controllers/entityReferenceController"; +import { authenticateToken } from "../middleware/authMiddleware"; + +const router = Router(); + +/** + * GET /api/entity-reference/code/:codeCategory + * 공통 코드 데이터 조회 + */ +router.get( + "/code/:codeCategory", + authenticateToken, + EntityReferenceController.getCodeData +); + +/** + * GET /api/entity-reference/:tableName/:columnName + * 엔티티 참조 데이터 조회 + */ +router.get( + "/:tableName/:columnName", + authenticateToken, + EntityReferenceController.getEntityReferenceData +); + +export default router; diff --git a/backend-node/src/services/dataflowControlService.ts b/backend-node/src/services/dataflowControlService.ts index a04e5eee..d706935f 100644 --- a/backend-node/src/services/dataflowControlService.ts +++ b/backend-node/src/services/dataflowControlService.ts @@ -19,6 +19,7 @@ export interface ControlAction { id: string; name: string; actionType: "insert" | "update" | "delete"; + logicalOperator?: "AND" | "OR"; // 액션 간 논리 연산자 (첫 번째 액션 제외) conditions: ControlCondition[]; fieldMappings: { sourceField?: string; @@ -136,17 +137,41 @@ export class DataflowControlService { }; } - // 액션 실행 + // 액션 실행 (논리 연산자 지원) const executedActions = []; const errors = []; + let previousActionSuccess = false; + let shouldSkipRemainingActions = false; + + for (let i = 0; i < targetPlan.actions.length; i++) { + const action = targetPlan.actions[i]; - for (const action of targetPlan.actions) { try { + // 논리 연산자에 따른 실행 여부 결정 + if ( + i > 0 && + action.logicalOperator === "OR" && + previousActionSuccess + ) { + console.log( + `⏭️ OR 조건으로 인해 액션 건너뛰기: ${action.name} (이전 액션 성공)` + ); + continue; + } + + if (shouldSkipRemainingActions && action.logicalOperator === "AND") { + console.log( + `⏭️ 이전 액션 실패로 인해 AND 체인 액션 건너뛰기: ${action.name}` + ); + continue; + } + console.log(`⚡ 액션 실행: ${action.name} (${action.actionType})`); console.log(`📋 액션 상세 정보:`, { actionId: action.id, actionName: action.name, actionType: action.actionType, + logicalOperator: action.logicalOperator, conditions: action.conditions, fieldMappings: action.fieldMappings, }); @@ -163,6 +188,10 @@ export class DataflowControlService { console.log( `⚠️ 액션 조건 미충족: ${actionConditionResult.reason}` ); + previousActionSuccess = false; + if (action.logicalOperator === "AND") { + shouldSkipRemainingActions = true; + } continue; } } @@ -173,11 +202,19 @@ export class DataflowControlService { actionName: action.name, result: actionResult, }); + + previousActionSuccess = true; + shouldSkipRemainingActions = false; // 성공했으므로 다시 실행 가능 } catch (error) { console.error(`❌ 액션 실행 오류: ${action.name}`, error); const errorMessage = error instanceof Error ? error.message : String(error); errors.push(`액션 '${action.name}' 실행 오류: ${errorMessage}`); + + previousActionSuccess = false; + if (action.logicalOperator === "AND") { + shouldSkipRemainingActions = true; + } } } diff --git a/frontend/app/(main)/admin/external-connections/page.tsx b/frontend/app/(main)/admin/external-connections/page.tsx index 2b6b27a5..a4021493 100644 --- a/frontend/app/(main)/admin/external-connections/page.tsx +++ b/frontend/app/(main)/admin/external-connections/page.tsx @@ -4,7 +4,7 @@ import React, { useState, useEffect } from "react"; import { Plus, Search, Pencil, Trash2, Database } 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 { Card, CardContent } from "@/components/ui/card"; import { Badge } from "@/components/ui/badge"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; @@ -23,6 +23,7 @@ import { ExternalDbConnectionAPI, ExternalDbConnection, ExternalDbConnectionFilter, + ConnectionTestRequest, } from "@/lib/api/externalDbConnection"; import { ExternalDbConnectionModal } from "@/components/admin/ExternalDbConnectionModal"; @@ -56,6 +57,8 @@ export default function ExternalConnectionsPage() { const [supportedDbTypes, setSupportedDbTypes] = useState>([]); const [deleteDialogOpen, setDeleteDialogOpen] = useState(false); const [connectionToDelete, setConnectionToDelete] = useState(null); + const [testingConnections, setTestingConnections] = useState>(new Set()); + const [testResults, setTestResults] = useState>(new Map()); // 데이터 로딩 const loadConnections = async () => { @@ -160,6 +163,57 @@ export default function ExternalConnectionsPage() { setConnectionToDelete(null); }; + // 연결 테스트 + const handleTestConnection = async (connection: ExternalDbConnection) => { + if (!connection.id) return; + + setTestingConnections((prev) => new Set(prev).add(connection.id!)); + + try { + const testData: ConnectionTestRequest = { + db_type: connection.db_type, + host: connection.host, + port: connection.port, + database_name: connection.database_name, + username: connection.username, + password: connection.password, + connection_timeout: connection.connection_timeout, + ssl_enabled: connection.ssl_enabled, + }; + + const result = await ExternalDbConnectionAPI.testConnection(testData); + + setTestResults((prev) => new Map(prev).set(connection.id!, result.success)); + + if (result.success) { + toast({ + title: "연결 성공", + description: `${connection.connection_name} 연결이 성공했습니다.`, + }); + } else { + toast({ + title: "연결 실패", + description: `${connection.connection_name} 연결에 실패했습니다.`, + variant: "destructive", + }); + } + } catch (error) { + console.error("연결 테스트 오류:", error); + setTestResults((prev) => new Map(prev).set(connection.id!, false)); + toast({ + title: "연결 테스트 오류", + description: "연결 테스트 중 오류가 발생했습니다.", + variant: "destructive", + }); + } finally { + setTestingConnections((prev) => { + const newSet = new Set(prev); + newSet.delete(connection.id!); + return newSet; + }); + } + }; + // 모달 저장 처리 const handleModalSave = () => { setIsModalOpen(false); @@ -264,6 +318,7 @@ export default function ExternalConnectionsPage() { 사용자 상태 생성일 + 연결 테스트 작업 @@ -271,14 +326,7 @@ export default function ExternalConnectionsPage() { {connections.map((connection) => ( -
-
{connection.connection_name}
- {connection.description && ( -
- {connection.description} -
- )} -
+
{connection.connection_name}
@@ -298,6 +346,27 @@ export default function ExternalConnectionsPage() { {connection.created_date ? new Date(connection.created_date).toLocaleDateString() : "N/A"} + +
+ + {testResults.has(connection.id!) && ( + + {testResults.get(connection.id!) ? "성공" : "실패"} + + )} +
+
- - - - + + + + + + + + + + + + 연결 생성 완료 + + + {createdConnectionName} 연결이 생성되었습니다. +
+ + 생성된 연결은 데이터플로우 다이어그램에서 확인할 수 있습니다. + +
+
+ + 확인 + +
+
+ ); }; diff --git a/frontend/components/dataflow/DataFlowDesigner.tsx b/frontend/components/dataflow/DataFlowDesigner.tsx index f3a5372f..d1eb0003 100644 --- a/frontend/components/dataflow/DataFlowDesigner.tsx +++ b/frontend/components/dataflow/DataFlowDesigner.tsx @@ -606,10 +606,10 @@ export const DataFlowDesigner: React.FC = ({ // 관계도 저장 함수 const handleSaveDiagram = useCallback( - async (diagramName: string) => { + async (diagramName: string): Promise<{ success: boolean; error?: string }> => { if (nodes.length === 0) { toast.error("저장할 테이블이 없습니다."); - return; + return { success: false, error: "저장할 테이블이 없습니다." }; } setIsSaving(true); @@ -669,6 +669,7 @@ export const DataFlowDesigner: React.FC = ({ id: action.id as string, name: action.name as string, actionType: action.actionType as "insert" | "update" | "delete" | "upsert", + logicalOperator: action.logicalOperator as "AND" | "OR" | undefined, // 논리 연산자 추가 fieldMappings: ((action.fieldMappings as Record[]) || []).map( (mapping: Record) => { // eslint-disable-next-line @typescript-eslint/no-unused-vars @@ -704,12 +705,49 @@ export const DataFlowDesigner: React.FC = ({ setCurrentDiagramName(newDiagram.diagram_name); } - toast.success(`관계도 "${diagramName}"가 성공적으로 저장되었습니다.`); setHasUnsavedChanges(false); - setShowSaveModal(false); + // 성공 모달은 SaveDiagramModal에서 처리하므로 여기서는 toast 제거 + return { success: true }; } catch (error) { - console.error("관계도 저장 실패:", error); - toast.error("관계도 저장 중 오류가 발생했습니다."); + // 에러 메시지 분석 + let errorMessage = "관계도 저장 중 오류가 발생했습니다."; + let isDuplicateError = false; + + // Axios 에러 처리 + if (error && typeof error === "object" && "response" in error) { + const axiosError = error as any; + if (axiosError.response?.status === 409) { + // 중복 이름 에러 (409 Conflict) + errorMessage = "중복된 이름입니다."; + isDuplicateError = true; + } else if (axiosError.response?.data?.message) { + // 백엔드에서 제공한 에러 메시지 사용 + if (axiosError.response.data.message.includes("중복된 이름입니다")) { + errorMessage = "중복된 이름입니다."; + isDuplicateError = true; + } else { + errorMessage = axiosError.response.data.message; + } + } + } else if (error instanceof Error) { + if ( + error.message.includes("중복") || + error.message.includes("duplicate") || + error.message.includes("already exists") + ) { + errorMessage = "중복된 이름입니다."; + isDuplicateError = true; + } else { + errorMessage = error.message; + } + } + + // 중복 에러가 아닌 경우만 콘솔에 로그 출력 + if (!isDuplicateError) { + console.error("관계도 저장 실패:", error); + } + + return { success: false, error: errorMessage }; } finally { setIsSaving(false); } diff --git a/frontend/components/dataflow/SaveDiagramModal.tsx b/frontend/components/dataflow/SaveDiagramModal.tsx index a2385efc..02ae7f99 100644 --- a/frontend/components/dataflow/SaveDiagramModal.tsx +++ b/frontend/components/dataflow/SaveDiagramModal.tsx @@ -2,17 +2,27 @@ import React, { useState, useEffect } from "react"; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"; +import { + AlertDialog, + AlertDialogAction, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@/components/ui/alert-dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Badge } from "@/components/ui/badge"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { CheckCircle } from "lucide-react"; import { JsonRelationship } from "@/lib/api/dataflow"; interface SaveDiagramModalProps { isOpen: boolean; onClose: () => void; - onSave: (diagramName: string) => void; + onSave: (diagramName: string) => Promise<{ success: boolean; error?: string }>; relationships: JsonRelationship[]; defaultName?: string; isLoading?: boolean; @@ -28,13 +38,15 @@ const SaveDiagramModal: React.FC = ({ }) => { const [diagramName, setDiagramName] = useState(defaultName); const [nameError, setNameError] = useState(""); + const [showSuccessModal, setShowSuccessModal] = useState(false); + const [savedDiagramName, setSavedDiagramName] = useState(""); // defaultName이 변경될 때마다 diagramName 업데이트 useEffect(() => { setDiagramName(defaultName); }, [defaultName]); - const handleSave = () => { + const handleSave = async () => { const trimmedName = diagramName.trim(); if (!trimmedName) { @@ -53,7 +65,39 @@ const SaveDiagramModal: React.FC = ({ } setNameError(""); - onSave(trimmedName); + + try { + // 부모에게 저장 요청하고 결과 받기 + const result = await onSave(trimmedName); + + if (result.success) { + // 성공 시 성공 모달 표시 + setSavedDiagramName(trimmedName); + setShowSuccessModal(true); + } else { + // 실패 시 에러 메시지 표시 + if ( + result.error?.includes("중복된 이름입니다") || + result.error?.includes("중복") || + result.error?.includes("duplicate") || + result.error?.includes("already exists") + ) { + setNameError("중복된 이름입니다."); + } else { + setNameError(result.error || "저장 중 오류가 발생했습니다."); + } + } + } catch (error) { + // 중복 에러가 아닌 경우만 콘솔에 로그 출력 + const isDuplicateError = + error && typeof error === "object" && "response" in error && (error as any).response?.status === 409; + + if (!isDuplicateError) { + console.error("저장 오류:", error); + } + + setNameError("저장 중 오류가 발생했습니다."); + } }; const handleClose = () => { @@ -64,6 +108,12 @@ const SaveDiagramModal: React.FC = ({ } }; + const handleSuccessModalClose = () => { + setShowSuccessModal(false); + setSavedDiagramName(""); + handleClose(); // 원래 모달도 닫기 + }; + const handleKeyPress = (e: React.KeyboardEvent) => { if (e.key === "Enter" && !isLoading) { handleSave(); @@ -76,136 +126,160 @@ const SaveDiagramModal: React.FC = ({ ).sort(); return ( - - - - 📊 관계도 저장 - + <> + + + + 📊 관계도 저장 + -
- {/* 관계도 이름 입력 */} -
- - { - setDiagramName(e.target.value); - if (nameError) setNameError(""); - }} - onKeyPress={handleKeyPress} - placeholder="예: 사용자-부서 관계도" - disabled={isLoading} - className={nameError ? "border-red-500 focus:border-red-500" : ""} - /> - {nameError &&

{nameError}

} -
+
+ {/* 관계도 이름 입력 */} +
+ + { + setDiagramName(e.target.value); + if (nameError) setNameError(""); + }} + onKeyPress={handleKeyPress} + placeholder="예: 사용자-부서 관계도" + disabled={isLoading} + className={nameError ? "border-red-500 focus:border-red-500" : ""} + /> + {nameError &&

{nameError}

} +
- {/* 관계 요약 정보 */} -
-
-
{relationships.length}
-
관계 수
-
-
-
{connectedTables.length}
-
연결된 테이블
-
-
-
- {relationships.reduce((sum, rel) => sum + rel.fromColumns.length, 0)} + {/* 관계 요약 정보 */} +
+
+
{relationships.length}
+
관계 수
-
연결된 컬럼
-
-
- - {/* 연결된 테이블 목록 */} - {connectedTables.length > 0 && ( - - - 연결된 테이블 - - -
- {connectedTables.map((table) => ( - - {table} - - ))} +
+
{connectedTables.length}
+
연결된 테이블
+
+
+
+ {relationships.reduce((sum, rel) => sum + rel.fromColumns.length, 0)}
- - - )} +
연결된 컬럼
+
+
- {/* 관계 목록 미리보기 */} - {relationships.length > 0 && ( - - - 관계 목록 - - -
- {relationships.map((relationship, index) => ( -
-
-
- - {relationship.connectionType || "simple-key"} - - - {relationship.relationshipName || `${relationship.fromTable} → ${relationship.toTable}`} - -
-
- {relationship.fromTable} → {relationship.toTable} -
-
- - {relationship.connectionType} + {/* 연결된 테이블 목록 */} + {connectedTables.length > 0 && ( + + + 연결된 테이블 + + +
+ {connectedTables.map((table) => ( + + {table} -
- ))} -
- - - )} - - {/* 관계가 없는 경우 안내 */} - {relationships.length === 0 && ( -
-
📭
-
생성된 관계가 없습니다.
-
테이블을 추가하고 컬럼을 연결해서 관계를 생성해보세요.
-
- )} -
- - - -
+ + )} - - - -
+ + {/* 관계 목록 미리보기 */} + {relationships.length > 0 && ( + + + 관계 목록 + + +
+ {relationships.map((relationship, index) => ( +
+
+
+ + {relationship.connectionType || "simple-key"} + + + {relationship.relationshipName || `${relationship.fromTable} → ${relationship.toTable}`} + +
+
+ {relationship.fromTable} → {relationship.toTable} +
+
+ + {relationship.connectionType} + +
+ ))} +
+
+
+ )} + + {/* 관계가 없는 경우 안내 */} + {relationships.length === 0 && ( +
+
📭
+
생성된 관계가 없습니다.
+
테이블을 추가하고 컬럼을 연결해서 관계를 생성해보세요.
+
+ )} +
+ + + + + + + + + {/* 저장 성공 알림 모달 */} + + + + + + 관계도 저장 완료 + + + {savedDiagramName} 관계도가 성공적으로 저장되었습니다. +
+ + 저장된 관계도는 관리 메뉴에서 확인하고 수정할 수 있습니다. + +
+
+ + 확인 + +
+
+ ); }; diff --git a/frontend/components/dataflow/condition/ConditionRenderer.tsx b/frontend/components/dataflow/condition/ConditionRenderer.tsx index 17c38bf9..0b58bc02 100644 --- a/frontend/components/dataflow/condition/ConditionRenderer.tsx +++ b/frontend/components/dataflow/condition/ConditionRenderer.tsx @@ -7,10 +7,12 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@ import { Trash2 } from "lucide-react"; import { ConditionNode, ColumnInfo } from "@/lib/api/dataflow"; import { getInputTypeForDataType } from "@/utils/connectionUtils"; +import { WebTypeInput } from "./WebTypeInput"; interface ConditionRendererProps { conditions: ConditionNode[]; fromTableColumns: ColumnInfo[]; + fromTableName?: string; onUpdateCondition: (index: number, field: keyof ConditionNode, value: string) => void; onRemoveCondition: (index: number) => void; getCurrentGroupLevel: (index: number) => number; @@ -19,41 +21,43 @@ interface ConditionRendererProps { export const ConditionRenderer: React.FC = ({ conditions, fromTableColumns, + fromTableName, onUpdateCondition, onRemoveCondition, getCurrentGroupLevel, }) => { const renderConditionValue = (condition: ConditionNode, index: number) => { const selectedColumn = fromTableColumns.find((col) => col.columnName === condition.field); - const dataType = selectedColumn?.dataType?.toLowerCase() || "string"; - const inputType = getInputTypeForDataType(dataType); - if (dataType.includes("bool")) { - return ( - - ); - } else { + if (!selectedColumn) { + // 컬럼이 선택되지 않은 경우 기본 input return ( onUpdateCondition(index, "value", e.target.value)} className="h-8 flex-1 text-xs" /> ); } + + // 테이블명 정보를 포함한 컬럼 객체 생성 + const columnWithTableName = { + ...selectedColumn, + tableName: fromTableName, + }; + + // WebType 기반 input 사용 + return ( + onUpdateCondition(index, "value", value)} + className="h-8 flex-1 text-xs" + placeholder="값" + /> + ); }; return ( diff --git a/frontend/components/dataflow/condition/ConditionalSettings.tsx b/frontend/components/dataflow/condition/ConditionalSettings.tsx index a863e36b..882ff09c 100644 --- a/frontend/components/dataflow/condition/ConditionalSettings.tsx +++ b/frontend/components/dataflow/condition/ConditionalSettings.tsx @@ -10,6 +10,7 @@ import { ConditionRenderer } from "./ConditionRenderer"; interface ConditionalSettingsProps { conditions: ConditionNode[]; fromTableColumns: ColumnInfo[]; + fromTableName?: string; onAddCondition: () => void; onAddGroupStart: () => void; onAddGroupEnd: () => void; @@ -21,6 +22,7 @@ interface ConditionalSettingsProps { export const ConditionalSettings: React.FC = ({ conditions, fromTableColumns, + fromTableName, onAddCondition, onAddGroupStart, onAddGroupEnd, @@ -57,6 +59,7 @@ export const ConditionalSettings: React.FC = ({ void; + className?: string; + placeholder?: string; + tableName?: string; // 테이블명을 별도로 전달받음 +} + +export const WebTypeInput: React.FC = ({ + column, + value, + onChange, + className = "", + placeholder, + tableName, +}) => { + // tableName은 props 또는 column.tableName에서 가져옴 + const effectiveTableName = tableName || (column as ColumnInfo & { tableName?: string }).tableName; + const webType = column.webType || "text"; + const [entityOptions, setEntityOptions] = useState([]); + const [codeOptions, setCodeOptions] = useState([]); + const [loading, setLoading] = useState(false); + + // detailSettings 안전하게 파싱 (메모이제이션) + const { detailSettings, fallbackCodeCategory } = useMemo(() => { + let parsedSettings: Record = {}; + let fallbackCategory = ""; + + if (column.detailSettings && typeof column.detailSettings === "string") { + // JSON 형태인지 확인 ('{' 또는 '[' 로 시작하는지) + const trimmed = column.detailSettings.trim(); + if (trimmed.startsWith("{") || trimmed.startsWith("[")) { + try { + parsedSettings = JSON.parse(column.detailSettings); + } catch { + parsedSettings = {}; + } + } else { + // JSON이 아닌 일반 문자열인 경우, code 타입이면 codeCategory로 사용 + if (webType === "code") { + // "공통코드: 상태" 형태에서 실제 코드 추출 시도 + if (column.detailSettings.includes(":")) { + const parts = column.detailSettings.split(":"); + if (parts.length >= 2) { + fallbackCategory = parts[1].trim(); + } else { + fallbackCategory = column.detailSettings; + } + } else { + fallbackCategory = column.detailSettings; + } + } + parsedSettings = {}; + } + } else if (column.detailSettings && typeof column.detailSettings === "object") { + parsedSettings = column.detailSettings; + } + + return { detailSettings: parsedSettings, fallbackCodeCategory: fallbackCategory }; + }, [column.detailSettings, webType]); + + const loadEntityData = useCallback(async () => { + try { + setLoading(true); + + // entity 타입은 반드시 effectiveTableName과 columnName이 있어야 함 + if (!effectiveTableName || !column.columnName) { + throw new Error("Entity 타입에는 tableName과 columnName이 필요합니다."); + } + + const data = await EntityReferenceAPI.getEntityReferenceData(effectiveTableName, column.columnName, { + limit: 100, + }); + setEntityOptions(data.options); + } catch { + setEntityOptions([]); + } finally { + setLoading(false); + } + }, [effectiveTableName, column.columnName]); + + const loadCodeData = useCallback(async () => { + try { + setLoading(true); + const codeCategory = column.codeCategory || (detailSettings.codeCategory as string) || fallbackCodeCategory; + if (codeCategory) { + const data = await EntityReferenceAPI.getCodeReferenceData(codeCategory, { limit: 100 }); + setCodeOptions(data.options); + } + } catch { + setCodeOptions([]); + } finally { + setLoading(false); + } + }, [column.codeCategory, detailSettings.codeCategory, fallbackCodeCategory]); + + // webType에 따른 데이터 로드 + useEffect(() => { + // 디버깅: entity 타입 필드 정보 확인 + if (column.columnName === "manager_name" || webType === "entity") { + console.log("🔍 Entity 필드 디버깅:", { + columnName: column.columnName, + webType: webType, + tableName: tableName, + effectiveTableName: effectiveTableName, + referenceTable: column.referenceTable, + referenceColumn: column.referenceColumn, + displayColumn: (column as any).displayColumn, + shouldLoadEntity: webType === "entity" && effectiveTableName && column.columnName, + }); + } + + if (webType === "entity" && effectiveTableName && column.columnName) { + // entity 타입: 다른 테이블 참조 + console.log("🚀 Entity 데이터 로드 시작:", effectiveTableName, column.columnName); + loadEntityData(); + } else if (webType === "code" && (column.codeCategory || detailSettings.codeCategory || fallbackCodeCategory)) { + // code 타입: code_info 테이블에서 공통 코드 조회 + loadCodeData(); + } + // text 타입: 일반 텍스트 입력 + // file 타입: 파일 업로드 + }, [ + webType, + effectiveTableName, + column.columnName, + column.codeCategory, + column.referenceTable, + column.referenceColumn, + (column as any).displayColumn, + tableName, + fallbackCodeCategory, + detailSettings.codeCategory, + loadEntityData, + loadCodeData, + ]); + + // 날짜/시간 타입일 때 기본값으로 현재 날짜/시간 설정 + useEffect(() => { + const dateTimeTypes = ["date", "datetime", "timestamp"]; + + // 컬럼명이나 데이터 타입으로 날짜 필드 판단 + const isDateColumn = + dateTimeTypes.includes(webType) || + column.columnName?.toLowerCase().includes("date") || + column.columnName?.toLowerCase().includes("time") || + column.columnName === "regdate" || + column.columnName === "created_at" || + column.columnName === "updated_at"; + + if (isDateColumn && (!value || value === "")) { + const now = new Date(); + let formattedValue = ""; + + if (webType === "date") { + // 데이터베이스 타입이나 컬럼명으로 시간 포함 여부 판단 + const isTimestampType = + column.dataType?.toLowerCase().includes("timestamp") || + column.columnName?.toLowerCase().includes("time") || + column.columnName === "regdate" || + column.columnName === "created_at" || + column.columnName === "updated_at"; + + if (isTimestampType) { + formattedValue = format(now, "yyyy-MM-dd HH:mm:ss"); + } else { + formattedValue = format(now, "yyyy-MM-dd"); + } + } else { + // 컬럼명 기반 판단 시에도 시간 포함 + formattedValue = format(now, "yyyy-MM-dd HH:mm:ss"); + } + + onChange(formattedValue); + } + }, [webType, value, onChange, column.columnName, column.dataType]); + + // 공통 props + const commonProps = { + value: value || "", + className, + }; + + // WebType별 렌더링 (column_labels의 webType을 정확히 따름) + const actualWebType = webType; + + switch (actualWebType) { + case "text": + return ( + onChange(e.target.value)} + /> + ); + + case "number": + return ( + onChange(e.target.value)} + min={detailSettings.min as number} + max={detailSettings.max as number} + step={(detailSettings.step as string) || "any"} + /> + ); + + case "date": + // 데이터베이스 타입이나 컬럼명으로 시간 포함 여부 판단 + const isTimestampType = + column.dataType?.toLowerCase().includes("timestamp") || + column.columnName?.toLowerCase().includes("time") || + column.columnName === "regdate" || + column.columnName === "created_at" || + column.columnName === "updated_at"; + + if (isTimestampType) { + // timestamp 타입이면 datetime-local input 사용 (시간까지 입력 가능) + const datetimeValue = value ? value.replace(" ", "T").substring(0, 16) : ""; + return ( + { + const inputValue = e.target.value; + // datetime-local 형식 (YYYY-MM-DDTHH:mm)을 DB 형식 (YYYY-MM-DD HH:mm:ss)으로 변환 + const formattedValue = inputValue ? `${inputValue.replace("T", " ")}:00` : ""; + onChange(formattedValue); + }} + placeholder={placeholder || "날짜와 시간 선택"} + /> + ); + } else { + // 순수 date 타입이면 달력 팝업 사용 + const dateValue = value ? new Date(value) : undefined; + return ( + + + + + + onChange(date ? format(date, "yyyy-MM-dd") : "")} + initialFocus + /> + + + ); + } + + case "textarea": + return ( +