From 7b0bbc91c8133cf529d081cc763cac024eba74a6 Mon Sep 17 00:00:00 2001 From: dohyeons Date: Tue, 4 Nov 2025 15:32:49 +0900 Subject: [PATCH 01/37] =?UTF-8?q?=EB=B6=84=ED=95=A0=20=ED=8C=A8=EB=84=90?= =?UTF-8?q?=20=EB=84=88=EB=B9=84=20=EC=A1=B0=EC=A0=88=20=EC=95=88=EB=90=98?= =?UTF-8?q?=EB=8A=94=EA=B1=B0=20=EA=B0=9C=EC=84=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../split-panel-layout/SplitPanelLayoutComponent.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/frontend/lib/registry/components/split-panel-layout/SplitPanelLayoutComponent.tsx b/frontend/lib/registry/components/split-panel-layout/SplitPanelLayoutComponent.tsx index b9875736..7506ee65 100644 --- a/frontend/lib/registry/components/split-panel-layout/SplitPanelLayoutComponent.tsx +++ b/frontend/lib/registry/components/split-panel-layout/SplitPanelLayoutComponent.tsx @@ -57,7 +57,7 @@ export const SplitPanelLayoutComponent: React.FC ? { // 반응형 모드: position relative, 그리드 컨테이너가 제공하는 크기 사용 position: "relative", - // width 제거 - 그리드 컬럼이 결정 + width: "100%", // 🆕 부모 컨테이너 너비에 맞춤 height: `${component.style?.height || 600}px`, border: "1px solid #e5e7eb", } @@ -66,7 +66,7 @@ export const SplitPanelLayoutComponent: React.FC position: "absolute", left: `${component.style?.positionX || 0}px`, top: `${component.style?.positionY || 0}px`, - width: `${component.style?.width || 1000}px`, + width: "100%", // 🆕 부모 컨테이너 너비에 맞춤 (그리드 기반) height: `${component.style?.height || 600}px`, zIndex: component.style?.positionZ || 1, cursor: isDesignMode ? "pointer" : "default", @@ -272,7 +272,7 @@ export const SplitPanelLayoutComponent: React.FC onClick?.(e); } }} - className={`flex overflow-hidden rounded-lg bg-white shadow-sm ${isPreview ? "w-full" : ""}`} + className="flex w-full overflow-hidden rounded-lg bg-white shadow-sm" > {/* 좌측 패널 */}
Date: Tue, 4 Nov 2025 15:52:41 +0900 Subject: [PATCH 02/37] =?UTF-8?q?=EC=9D=B4=EB=AF=B8=EC=A7=80=20=EC=BB=B4?= =?UTF-8?q?=ED=8F=AC=EB=84=8C=ED=8A=B8=20=EC=98=A4=EB=A5=98=EB=82=98?= =?UTF-8?q?=EB=8A=94=EA=B1=B0=20=ED=95=B4=EA=B2=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/components/screen/panels/FileComponentConfigPanel.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/components/screen/panels/FileComponentConfigPanel.tsx b/frontend/components/screen/panels/FileComponentConfigPanel.tsx index 8db01ad0..f14c861f 100644 --- a/frontend/components/screen/panels/FileComponentConfigPanel.tsx +++ b/frontend/components/screen/panels/FileComponentConfigPanel.tsx @@ -12,7 +12,7 @@ import { Plus, X, Upload, File, Image, FileText, Download, Trash2 } from "lucide import { Button } from "@/components/ui/button"; import { FileInfo, FileUploadResponse } from "@/lib/registry/components/file-upload/types"; import { uploadFiles, downloadFile, deleteFile } from "@/lib/api/file"; -import { formatFileSize } from "@/lib/utils"; +import { formatFileSize, cn } from "@/lib/utils"; import { toast } from "sonner"; interface FileComponentConfigPanelProps { From 01e03dedbfad766772aa2de316c003b25beca10c Mon Sep 17 00:00:00 2001 From: dohyeons Date: Tue, 4 Nov 2025 16:26:53 +0900 Subject: [PATCH 03/37] =?UTF-8?q?=ED=8C=8C=EC=9D=BC=20=EC=97=85=EB=A1=9C?= =?UTF-8?q?=EB=93=9C=20=EC=BB=B4=ED=8F=AC=EB=84=8C=ED=8A=B8=20=EB=86=92?= =?UTF-8?q?=EC=9D=B4=20=EC=A1=B0=EC=A0=88=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../components/screen/RealtimePreviewDynamic.tsx | 15 ++++++++++++--- .../file-upload/FileUploadComponent.tsx | 3 ++- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/frontend/components/screen/RealtimePreviewDynamic.tsx b/frontend/components/screen/RealtimePreviewDynamic.tsx index 72739e71..129d2487 100644 --- a/frontend/components/screen/RealtimePreviewDynamic.tsx +++ b/frontend/components/screen/RealtimePreviewDynamic.tsx @@ -222,9 +222,11 @@ export const RealtimePreviewDynamic: React.FC = ({ return `${actualHeight}px`; } - // 1순위: style.height가 있으면 우선 사용 + // 1순위: style.height가 있으면 우선 사용 (문자열 그대로 또는 숫자+px) if (componentStyle?.height) { - return componentStyle.height; + return typeof componentStyle.height === 'number' + ? `${componentStyle.height}px` + : componentStyle.height; } // 2순위: size.height (픽셀) @@ -232,7 +234,14 @@ export const RealtimePreviewDynamic: React.FC = ({ return `${Math.max(size?.height || 200, 200)}px`; } - return `${size?.height || 40}px`; + // 3순위: size.height가 있으면 사용 + if (size?.height) { + return typeof size.height === 'number' + ? `${size.height}px` + : size.height; + } + + return "40px"; }; const baseStyle = { diff --git a/frontend/lib/registry/components/file-upload/FileUploadComponent.tsx b/frontend/lib/registry/components/file-upload/FileUploadComponent.tsx index 1af4b869..5eea6d60 100644 --- a/frontend/lib/registry/components/file-upload/FileUploadComponent.tsx +++ b/frontend/lib/registry/components/file-upload/FileUploadComponent.tsx @@ -901,6 +901,8 @@ const FileUploadComponent: React.FC = ({
= ({
{/* 파일 업로드 영역 - 주석처리 */} {/* {!isDesignMode && ( From 958aeb2d539f9cde83b621c54e0047f07b1b069a Mon Sep 17 00:00:00 2001 From: dohyeons Date: Tue, 4 Nov 2025 17:32:46 +0900 Subject: [PATCH 04/37] =?UTF-8?q?=ED=8C=8C=EC=9D=BC=20=EC=97=85=EB=A1=9C?= =?UTF-8?q?=EB=93=9C=20=EC=AA=BD=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../file-upload/FileManagerModal.tsx | 29 +- .../file-upload/FileUploadComponent.tsx | 298 ++++++++++-------- .../registry/components/file-upload/types.ts | 3 + 3 files changed, 194 insertions(+), 136 deletions(-) diff --git a/frontend/lib/registry/components/file-upload/FileManagerModal.tsx b/frontend/lib/registry/components/file-upload/FileManagerModal.tsx index f8c76ca0..cfed8223 100644 --- a/frontend/lib/registry/components/file-upload/FileManagerModal.tsx +++ b/frontend/lib/registry/components/file-upload/FileManagerModal.tsx @@ -17,7 +17,8 @@ import { Music, Archive, Presentation, - X + X, + Star } from "lucide-react"; import { formatFileSize } from "@/lib/utils"; import { FileViewerModal } from "./FileViewerModal"; @@ -30,6 +31,7 @@ interface FileManagerModalProps { onFileDownload: (file: FileInfo) => void; onFileDelete: (file: FileInfo) => void; onFileView: (file: FileInfo) => void; + onSetRepresentative?: (file: FileInfo) => void; // 대표 이미지 설정 콜백 config: FileUploadConfig; isDesignMode?: boolean; } @@ -42,6 +44,7 @@ export const FileManagerModal: React.FC = ({ onFileDownload, onFileDelete, onFileView, + onSetRepresentative, config, isDesignMode = false, }) => { @@ -228,14 +231,32 @@ export const FileManagerModal: React.FC = ({ {getFileIcon(file.fileExt)}
-

- {file.realFileName} -

+
+ + {file.realFileName} + + {file.isRepresentative && ( + + 대표 + + )} +

{formatFileSize(file.fileSize)} • {file.fileExt.toUpperCase()}

+ {onSetRepresentative && ( + + )} + return ( + <> + {isImage && representativeImageUrl ? ( +
+ {representativeFile.realFileName}
-
- - {uploadedFiles.length > 0 ? ( -
- {uploadedFiles.map((file) => ( -
-
{getFileIcon(file.fileExt)}
- handleFileView(file)} - style={{ textShadow: "none" }} - > - {file.realFileName} - - - {formatFileSize(file.fileSize)} - -
- ))} -
- 💡 파일명 클릭으로 미리보기 또는 "전체 자세히보기"로 파일 관리 -
+ ) : isImage && !representativeImageUrl ? ( +
+
+

이미지 로딩 중...

) : ( -
- -

- 업로드된 파일이 없습니다 -

-

- 상세설정에서 파일을 업로드하세요 +

+ {getFileIcon(representativeFile.fileExt)} +

+ {representativeFile.realFileName}

+ + 대표 파일 +
)} -
+ + {/* 우측 하단 자세히보기 버튼 */} +
+ +
+ + ); + })() : ( +
+ +

업로드된 파일이 없습니다

+
)} - - {/* 도움말 텍스트 */} - {safeComponentConfig.helperText && ( -

{safeComponentConfig.helperText}

- )}
{/* 파일뷰어 모달 */} @@ -1098,6 +1131,7 @@ const FileUploadComponent: React.FC = ({ onFileDownload={handleFileDownload} onFileDelete={handleFileDelete} onFileView={handleFileView} + onSetRepresentative={handleSetRepresentative} config={safeComponentConfig} isDesignMode={isDesignMode} /> diff --git a/frontend/lib/registry/components/file-upload/types.ts b/frontend/lib/registry/components/file-upload/types.ts index 15eceab7..109561b4 100644 --- a/frontend/lib/registry/components/file-upload/types.ts +++ b/frontend/lib/registry/components/file-upload/types.ts @@ -30,6 +30,9 @@ export interface FileInfo { type?: string; // docType과 동일 uploadedAt?: string; // regdate와 동일 _file?: File; // 로컬 파일 객체 (업로드 전) + + // 대표 이미지 설정 + isRepresentative?: boolean; // 대표 이미지로 설정 여부 } /** From acaa3414d275d3df1bdc3f477d75b5bb71797c09 Mon Sep 17 00:00:00 2001 From: dohyeons Date: Tue, 4 Nov 2025 17:57:28 +0900 Subject: [PATCH 05/37] =?UTF-8?q?=ED=8C=8C=EC=9D=BC=20=EC=97=85=EB=A1=9C?= =?UTF-8?q?=EB=93=9C=20=ED=9A=8C=EC=82=AC=EB=B3=84=EB=A1=9C=20=EB=B3=B4?= =?UTF-8?q?=EC=9D=B4=EB=8F=84=EB=A1=9D=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/controllers/fileController.ts | 126 +++++++++++++----- frontend/lib/api/file.ts | 2 + .../file-upload/FileUploadComponent.tsx | 113 ++++++++-------- 3 files changed, 154 insertions(+), 87 deletions(-) diff --git a/backend-node/src/controllers/fileController.ts b/backend-node/src/controllers/fileController.ts index d138bce3..dfceca89 100644 --- a/backend-node/src/controllers/fileController.ts +++ b/backend-node/src/controllers/fileController.ts @@ -232,13 +232,20 @@ export const uploadFiles = async ( // 자동 연결 로직 - target_objid 자동 생성 let finalTargetObjid = targetObjid; - if (autoLink === "true" && linkedTable && recordId) { + + // 🔑 템플릿 파일(screen_files:)이나 temp_ 파일은 autoLink 무시 + const isTemplateFile = targetObjid && (targetObjid.startsWith('screen_files:') || targetObjid.startsWith('temp_')); + + if (!isTemplateFile && autoLink === "true" && linkedTable && recordId) { // 가상 파일 컬럼의 경우 컬럼명도 포함한 target_objid 생성 if (isVirtualFileColumn === "true" && columnName) { finalTargetObjid = `${linkedTable}:${recordId}:${columnName}`; } else { finalTargetObjid = `${linkedTable}:${recordId}`; } + console.log("📎 autoLink 적용:", { original: targetObjid, final: finalTargetObjid }); + } else if (isTemplateFile) { + console.log("🎨 템플릿 파일이므로 targetObjid 유지:", targetObjid); } const savedFiles = []; @@ -363,6 +370,38 @@ export const deleteFile = async ( const { objid } = req.params; const { writer = "system" } = req.body; + // 🔒 멀티테넌시: 현재 사용자의 회사 코드 + const companyCode = req.user?.companyCode; + + // 파일 정보 조회 + const fileRecord = await queryOne( + `SELECT * FROM attach_file_info WHERE objid = $1`, + [parseInt(objid)] + ); + + if (!fileRecord) { + res.status(404).json({ + success: false, + message: "파일을 찾을 수 없습니다.", + }); + return; + } + + // 🔒 멀티테넌시: 회사 코드 일치 여부 확인 (최고 관리자 제외) + if (companyCode !== "*" && fileRecord.company_code !== companyCode) { + console.warn("⚠️ 다른 회사 파일 삭제 시도:", { + userId: req.user?.userId, + userCompanyCode: companyCode, + fileCompanyCode: fileRecord.company_code, + objid, + }); + res.status(403).json({ + success: false, + message: "접근 권한이 없습니다.", + }); + return; + } + // 파일 상태를 DELETED로 변경 (논리적 삭제) await query( "UPDATE attach_file_info SET status = $1 WHERE objid = $2", @@ -510,6 +549,9 @@ export const getComponentFiles = async ( const { screenId, componentId, tableName, recordId, columnName } = req.query; + // 🔒 멀티테넌시: 현재 사용자의 회사 코드 가져오기 + const companyCode = req.user?.companyCode; + console.log("📂 [getComponentFiles] API 호출:", { screenId, componentId, @@ -517,6 +559,7 @@ export const getComponentFiles = async ( recordId, columnName, user: req.user?.userId, + companyCode, // 🔒 멀티테넌시 로그 }); if (!screenId || !componentId) { @@ -534,32 +577,16 @@ export const getComponentFiles = async ( templateTargetObjid, }); - // 모든 파일 조회해서 실제 저장된 target_objid 패턴 확인 - const allFiles = await query( - `SELECT target_objid, real_file_name, regdate - FROM attach_file_info - WHERE status = $1 - ORDER BY regdate DESC - LIMIT 10`, - ["ACTIVE"] - ); - console.log( - "🗂️ [getComponentFiles] 최근 저장된 파일들의 target_objid:", - allFiles.map((f) => ({ - target_objid: f.target_objid, - name: f.real_file_name, - })) - ); - + // 🔒 멀티테넌시: 회사별 필터링 추가 const templateFiles = await query( `SELECT * FROM attach_file_info - WHERE target_objid = $1 AND status = $2 + WHERE target_objid = $1 AND status = $2 AND company_code = $3 ORDER BY regdate DESC`, - [templateTargetObjid, "ACTIVE"] + [templateTargetObjid, "ACTIVE", companyCode] ); console.log( - "📁 [getComponentFiles] 템플릿 파일 결과:", + "📁 [getComponentFiles] 템플릿 파일 결과 (회사별 필터링):", templateFiles.length ); @@ -567,11 +594,12 @@ export const getComponentFiles = async ( let dataFiles: any[] = []; if (tableName && recordId && columnName) { const dataTargetObjid = `${tableName}:${recordId}:${columnName}`; + // 🔒 멀티테넌시: 회사별 필터링 추가 dataFiles = await query( `SELECT * FROM attach_file_info - WHERE target_objid = $1 AND status = $2 + WHERE target_objid = $1 AND status = $2 AND company_code = $3 ORDER BY regdate DESC`, - [dataTargetObjid, "ACTIVE"] + [dataTargetObjid, "ACTIVE", companyCode] ); } @@ -643,6 +671,9 @@ export const previewFile = async ( const { objid } = req.params; const { serverFilename } = req.query; + // 🔒 멀티테넌시: 현재 사용자의 회사 코드 + const companyCode = req.user?.companyCode; + const fileRecord = await queryOne( "SELECT * FROM attach_file_info WHERE objid = $1 LIMIT 1", [parseInt(objid)] @@ -656,13 +687,28 @@ export const previewFile = async ( return; } + // 🔒 멀티테넌시: 회사 코드 일치 여부 확인 (최고 관리자 제외) + if (companyCode !== "*" && fileRecord.company_code !== companyCode) { + console.warn("⚠️ 다른 회사 파일 접근 시도:", { + userId: req.user?.userId, + userCompanyCode: companyCode, + fileCompanyCode: fileRecord.company_code, + objid, + }); + res.status(403).json({ + success: false, + message: "접근 권한이 없습니다.", + }); + return; + } + // 파일 경로에서 회사코드와 날짜 폴더 추출 const filePathParts = fileRecord.file_path!.split("/"); - let companyCode = filePathParts[2] || "DEFAULT"; + let fileCompanyCode = filePathParts[2] || "DEFAULT"; // company_* 처리 (실제 회사 코드로 변환) - if (companyCode === "company_*") { - companyCode = "company_*"; // 실제 디렉토리명 유지 + if (fileCompanyCode === "company_*") { + fileCompanyCode = "company_*"; // 실제 디렉토리명 유지 } const fileName = fileRecord.saved_file_name!; @@ -674,7 +720,7 @@ export const previewFile = async ( } const companyUploadDir = getCompanyUploadDir( - companyCode, + fileCompanyCode, dateFolder || undefined ); const filePath = path.join(companyUploadDir, fileName); @@ -762,6 +808,9 @@ export const downloadFile = async ( try { const { objid } = req.params; + // 🔒 멀티테넌시: 현재 사용자의 회사 코드 + const companyCode = req.user?.companyCode; + const fileRecord = await queryOne( `SELECT * FROM attach_file_info WHERE objid = $1`, [parseInt(objid)] @@ -775,13 +824,28 @@ export const downloadFile = async ( return; } + // 🔒 멀티테넌시: 회사 코드 일치 여부 확인 (최고 관리자 제외) + if (companyCode !== "*" && fileRecord.company_code !== companyCode) { + console.warn("⚠️ 다른 회사 파일 다운로드 시도:", { + userId: req.user?.userId, + userCompanyCode: companyCode, + fileCompanyCode: fileRecord.company_code, + objid, + }); + res.status(403).json({ + success: false, + message: "접근 권한이 없습니다.", + }); + return; + } + // 파일 경로에서 회사코드와 날짜 폴더 추출 (예: /uploads/company_*/2025/09/05/timestamp_filename.ext) const filePathParts = fileRecord.file_path!.split("/"); - let companyCode = filePathParts[2] || "DEFAULT"; // /uploads/company_*/2025/09/05/filename.ext에서 company_* 추출 + let fileCompanyCode = filePathParts[2] || "DEFAULT"; // /uploads/company_*/2025/09/05/filename.ext에서 company_* 추출 // company_* 처리 (실제 회사 코드로 변환) - if (companyCode === "company_*") { - companyCode = "company_*"; // 실제 디렉토리명 유지 + if (fileCompanyCode === "company_*") { + fileCompanyCode = "company_*"; // 실제 디렉토리명 유지 } const fileName = fileRecord.saved_file_name!; @@ -794,7 +858,7 @@ export const downloadFile = async ( } const companyUploadDir = getCompanyUploadDir( - companyCode, + fileCompanyCode, dateFolder || undefined ); const filePath = path.join(companyUploadDir, fileName); diff --git a/frontend/lib/api/file.ts b/frontend/lib/api/file.ts index 70564f5b..8cba4e60 100644 --- a/frontend/lib/api/file.ts +++ b/frontend/lib/api/file.ts @@ -42,6 +42,7 @@ export const uploadFiles = async (params: { autoLink?: boolean; columnName?: string; isVirtualFileColumn?: boolean; + companyCode?: string; // 🔒 멀티테넌시: 회사 코드 }): Promise => { const formData = new FormData(); @@ -64,6 +65,7 @@ export const uploadFiles = async (params: { if (params.autoLink !== undefined) formData.append("autoLink", params.autoLink.toString()); if (params.columnName) formData.append("columnName", params.columnName); if (params.isVirtualFileColumn !== undefined) formData.append("isVirtualFileColumn", params.isVirtualFileColumn.toString()); + if (params.companyCode) formData.append("companyCode", params.companyCode); // 🔒 멀티테넌시 const response = await apiClient.post("/files/upload", formData, { headers: { diff --git a/frontend/lib/registry/components/file-upload/FileUploadComponent.tsx b/frontend/lib/registry/components/file-upload/FileUploadComponent.tsx index b68cf529..f79bb12b 100644 --- a/frontend/lib/registry/components/file-upload/FileUploadComponent.tsx +++ b/frontend/lib/registry/components/file-upload/FileUploadComponent.tsx @@ -204,24 +204,37 @@ const FileUploadComponent: React.FC = ({ // 템플릿 파일과 데이터 파일을 조회하는 함수 const loadComponentFiles = useCallback(async () => { - if (!component?.id) return; + if (!component?.id) return false; try { - let screenId = - formData?.screenId || - (typeof window !== "undefined" && window.location.pathname.includes("/screens/") - ? parseInt(window.location.pathname.split("/screens/")[1]) - : null); - - // 디자인 모드인 경우 기본 화면 ID 사용 - if (!screenId && isDesignMode) { - screenId = 40; // 기본 화면 ID - console.log("📂 디자인 모드: 기본 화면 ID 사용 (40)"); + // 1. formData에서 screenId 가져오기 + let screenId = formData?.screenId; + + // 2. URL에서 screenId 추출 (/screens/:id 패턴) + if (!screenId && typeof window !== "undefined") { + const pathname = window.location.pathname; + const screenMatch = pathname.match(/\/screens\/(\d+)/); + if (screenMatch) { + screenId = parseInt(screenMatch[1]); + console.log("📂 URL에서 화면 ID 추출:", screenId); + } } + // 3. 디자인 모드인 경우 임시 화면 ID 사용 + if (!screenId && isDesignMode) { + screenId = 999999; // 디자인 모드 임시 ID + console.log("📂 디자인 모드: 임시 화면 ID 사용 (999999)"); + } + + // 4. 화면 ID가 없으면 컴포넌트 ID만으로 조회 시도 if (!screenId) { - console.log("📂 화면 ID 없음, 기존 파일 로직 사용"); - return false; // 기존 로직 사용 + console.warn("⚠️ 화면 ID 없음, 컴포넌트 ID만으로 파일 조회:", { + componentId: component.id, + pathname: window.location.pathname, + formData: formData, + }); + // screenId를 0으로 설정하여 컴포넌트 ID로만 조회 + screenId = 0; } const params = { @@ -229,7 +242,7 @@ const FileUploadComponent: React.FC = ({ componentId: component.id, tableName: formData?.tableName || component.tableName, recordId: formData?.id, - columnName: component.columnName, + columnName: component.columnName || component.id, // 🔑 columnName이 없으면 component.id 사용 }; console.log("📂 컴포넌트 파일 조회:", params); @@ -319,7 +332,7 @@ const FileUploadComponent: React.FC = ({ return false; // 기존 로직 사용 }, [component.id, component.tableName, component.columnName, formData?.screenId, formData?.tableName, formData?.id]); - // 컴포넌트 파일 동기화 + // 컴포넌트 파일 동기화 (DB 우선, localStorage는 보조) useEffect(() => { const componentFiles = (component as any)?.uploadedFiles || []; const lastUpdate = (component as any)?.lastFileUpdate; @@ -332,15 +345,15 @@ const FileUploadComponent: React.FC = ({ currentUploadedFiles: uploadedFiles.length, }); - // 먼저 새로운 템플릿 파일 조회 시도 - loadComponentFiles().then((useNewLogic) => { - if (useNewLogic) { - console.log("✅ 새로운 템플릿 파일 로직 사용"); - return; // 새로운 로직이 성공했으면 기존 로직 스킵 + // 🔒 항상 DB에서 최신 파일 목록을 조회 (멀티테넌시 격리) + loadComponentFiles().then((dbLoadSuccess) => { + if (dbLoadSuccess) { + console.log("✅ DB에서 파일 로드 성공 (멀티테넌시 적용)"); + return; // DB 로드 성공 시 localStorage 무시 } - // 기존 로직 사용 - console.log("📂 기존 파일 로직 사용"); + // DB 로드 실패 시에만 기존 로직 사용 (하위 호환성) + console.log("📂 DB 로드 실패, 기존 로직 사용"); // 전역 상태에서 최신 파일 정보 가져오기 const globalFileState = typeof window !== "undefined" ? (window as any).globalFileState || {} : {}; @@ -358,34 +371,6 @@ const FileUploadComponent: React.FC = ({ lastUpdate: lastUpdate, }); - // localStorage에서 백업 파일 복원 (새로고침 시 중요!) - try { - const backupKey = `fileUpload_${component.id}`; - const backupFiles = localStorage.getItem(backupKey); - if (backupFiles) { - const parsedFiles = JSON.parse(backupFiles); - if (parsedFiles.length > 0 && currentFiles.length === 0) { - console.log("🔄 localStorage에서 파일 복원:", { - componentId: component.id, - restoredFiles: parsedFiles.length, - files: parsedFiles.map((f: any) => ({ objid: f.objid, name: f.realFileName })), - }); - setUploadedFiles(parsedFiles); - - // 전역 상태에도 복원 - if (typeof window !== "undefined") { - (window as any).globalFileState = { - ...(window as any).globalFileState, - [component.id]: parsedFiles, - }; - } - return; - } - } - } catch (e) { - console.warn("localStorage 백업 복원 실패:", e); - } - // 최신 파일과 현재 파일 비교 if (JSON.stringify(currentFiles) !== JSON.stringify(uploadedFiles)) { console.log("🔄 useEffect에서 파일 목록 변경 감지:", { @@ -535,24 +520,39 @@ const FileUploadComponent: React.FC = ({ // targetObjid 생성 - 템플릿 vs 데이터 파일 구분 const tableName = formData?.tableName || component.tableName || "default_table"; const recordId = formData?.id; - const screenId = formData?.screenId; const columnName = component.columnName || component.id; + + // screenId 추출 (우선순위: formData > URL) + let screenId = formData?.screenId; + if (!screenId && typeof window !== "undefined") { + const pathname = window.location.pathname; + const screenMatch = pathname.match(/\/screens\/(\d+)/); + if (screenMatch) { + screenId = parseInt(screenMatch[1]); + } + } let targetObjid; - if (recordId && tableName) { - // 실제 데이터 파일 + // 우선순위: 1) 실제 데이터 (recordId가 숫자/문자열이고 temp_가 아님) > 2) 템플릿 (screenId) > 3) 기본값 + const isRealRecord = recordId && typeof recordId !== 'undefined' && !String(recordId).startsWith('temp_'); + + if (isRealRecord && tableName) { + // 실제 데이터 파일 (진짜 레코드 ID가 있을 때만) targetObjid = `${tableName}:${recordId}:${columnName}`; console.log("📁 실제 데이터 파일 업로드:", targetObjid); } else if (screenId) { - // 템플릿 파일 - targetObjid = `screen_${screenId}:${component.id}`; - console.log("🎨 템플릿 파일 업로드:", targetObjid); + // 🔑 템플릿 파일 (백엔드 조회 형식과 동일하게) + targetObjid = `screen_files:${screenId}:${component.id}:${columnName}`; + console.log("🎨 템플릿 파일 업로드:", { targetObjid, screenId, componentId: component.id, columnName }); } else { // 기본값 (화면관리에서 사용) targetObjid = `temp_${component.id}`; console.log("📝 기본 파일 업로드:", targetObjid); } + // 🔒 현재 사용자의 회사 코드 가져오기 (멀티테넌시 격리) + const userCompanyCode = (window as any).__user__?.companyCode; + const uploadData = { // 🎯 formData에서 백엔드 API 설정 가져오기 autoLink: formData?.autoLink || true, @@ -562,6 +562,7 @@ const FileUploadComponent: React.FC = ({ isVirtualFileColumn: formData?.isVirtualFileColumn || true, docType: component.fileConfig?.docType || "DOCUMENT", docTypeName: component.fileConfig?.docTypeName || "일반 문서", + companyCode: userCompanyCode, // 🔒 멀티테넌시: 회사 코드 명시적 전달 // 호환성을 위한 기존 필드들 tableName: tableName, fieldName: columnName, From 63b6e894356faa2859ee5f2f213b5d2ae92b80b7 Mon Sep 17 00:00:00 2001 From: dohyeons Date: Tue, 4 Nov 2025 18:02:20 +0900 Subject: [PATCH 06/37] =?UTF-8?q?=EB=94=94=EB=B2=84=EA=B9=85=EC=9A=A9=20co?= =?UTF-8?q?nsole.log=20=EC=82=AD=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/controllers/fileController.ts | 3 - .../file-upload/FileUploadComponent.tsx | 77 ------------------- 2 files changed, 80 deletions(-) diff --git a/backend-node/src/controllers/fileController.ts b/backend-node/src/controllers/fileController.ts index dfceca89..2feb6bfd 100644 --- a/backend-node/src/controllers/fileController.ts +++ b/backend-node/src/controllers/fileController.ts @@ -243,9 +243,6 @@ export const uploadFiles = async ( } else { finalTargetObjid = `${linkedTable}:${recordId}`; } - console.log("📎 autoLink 적용:", { original: targetObjid, final: finalTargetObjid }); - } else if (isTemplateFile) { - console.log("🎨 템플릿 파일이므로 targetObjid 유지:", targetObjid); } const savedFiles = []; diff --git a/frontend/lib/registry/components/file-upload/FileUploadComponent.tsx b/frontend/lib/registry/components/file-upload/FileUploadComponent.tsx index f79bb12b..2ae20180 100644 --- a/frontend/lib/registry/components/file-upload/FileUploadComponent.tsx +++ b/frontend/lib/registry/components/file-upload/FileUploadComponent.tsx @@ -148,12 +148,6 @@ const FileUploadComponent: React.FC = ({ // 현재 컴포넌트와 일치하고 화면설계 모드에서 온 이벤트인 경우 if (event.detail.componentId === component.id && event.detail.source === "designMode") { - console.log("✅✅✅ 화면설계 모드 → 실제 화면 파일 동기화 시작:", { - componentId: component.id, - filesCount: event.detail.files?.length || 0, - action: event.detail.action, - }); - // 파일 상태 업데이트 const newFiles = event.detail.files || []; setUploadedFiles(newFiles); @@ -216,14 +210,12 @@ const FileUploadComponent: React.FC = ({ const screenMatch = pathname.match(/\/screens\/(\d+)/); if (screenMatch) { screenId = parseInt(screenMatch[1]); - console.log("📂 URL에서 화면 ID 추출:", screenId); } } // 3. 디자인 모드인 경우 임시 화면 ID 사용 if (!screenId && isDesignMode) { screenId = 999999; // 디자인 모드 임시 ID - console.log("📂 디자인 모드: 임시 화면 ID 사용 (999999)"); } // 4. 화면 ID가 없으면 컴포넌트 ID만으로 조회 시도 @@ -245,18 +237,9 @@ const FileUploadComponent: React.FC = ({ columnName: component.columnName || component.id, // 🔑 columnName이 없으면 component.id 사용 }; - console.log("📂 컴포넌트 파일 조회:", params); - const response = await getComponentFiles(params); if (response.success) { - console.log("📁 파일 조회 결과:", { - templateFiles: response.templateFiles.length, - dataFiles: response.dataFiles.length, - totalFiles: response.totalFiles.length, - summary: response.summary, - actualFiles: response.totalFiles, - }); // 파일 데이터 형식 통일 const formattedFiles = response.totalFiles.map((file: any) => ({ @@ -271,7 +254,6 @@ const FileUploadComponent: React.FC = ({ ...file, })); - console.log("📁 형식 변환된 파일 데이터:", formattedFiles); // 🔄 localStorage의 기존 파일과 서버 파일 병합 let finalFiles = formattedFiles; @@ -287,13 +269,6 @@ const FileUploadComponent: React.FC = ({ finalFiles = [...formattedFiles, ...additionalFiles]; - console.log("🔄 파일 병합 완료:", { - 서버파일: formattedFiles.length, - 로컬파일: parsedBackupFiles.length, - 추가파일: additionalFiles.length, - 최종파일: finalFiles.length, - 최종파일목록: finalFiles.map((f: any) => ({ objid: f.objid, name: f.realFileName })), - }); } } catch (e) { console.warn("파일 병합 중 오류:", e); @@ -319,7 +294,6 @@ const FileUploadComponent: React.FC = ({ try { const backupKey = `fileUpload_${component.id}`; localStorage.setItem(backupKey, JSON.stringify(finalFiles)); - console.log("💾 localStorage 백업 업데이트 완료:", finalFiles.length); } catch (e) { console.warn("localStorage 백업 업데이트 실패:", e); } @@ -348,12 +322,10 @@ const FileUploadComponent: React.FC = ({ // 🔒 항상 DB에서 최신 파일 목록을 조회 (멀티테넌시 격리) loadComponentFiles().then((dbLoadSuccess) => { if (dbLoadSuccess) { - console.log("✅ DB에서 파일 로드 성공 (멀티테넌시 적용)"); return; // DB 로드 성공 시 localStorage 무시 } // DB 로드 실패 시에만 기존 로직 사용 (하위 호환성) - console.log("📂 DB 로드 실패, 기존 로직 사용"); // 전역 상태에서 최신 파일 정보 가져오기 const globalFileState = typeof window !== "undefined" ? (window as any).globalFileState || {} : {}; @@ -362,23 +334,9 @@ const FileUploadComponent: React.FC = ({ // 최신 파일 정보 사용 (전역 상태 > 컴포넌트 속성) const currentFiles = globalFiles.length > 0 ? globalFiles : componentFiles; - console.log("🔄 FileUploadComponent 파일 동기화:", { - componentId: component.id, - componentFiles: componentFiles.length, - globalFiles: globalFiles.length, - currentFiles: currentFiles.length, - uploadedFiles: uploadedFiles.length, - lastUpdate: lastUpdate, - }); // 최신 파일과 현재 파일 비교 if (JSON.stringify(currentFiles) !== JSON.stringify(uploadedFiles)) { - console.log("🔄 useEffect에서 파일 목록 변경 감지:", { - currentFiles: currentFiles.length, - uploadedFiles: uploadedFiles.length, - currentFilesData: currentFiles.map((f: any) => ({ objid: f.objid, name: f.realFileName })), - uploadedFilesData: uploadedFiles.map((f) => ({ objid: f.objid, name: f.realFileName })), - }); setUploadedFiles(currentFiles); setForceUpdate((prev) => prev + 1); } @@ -476,28 +434,15 @@ const FileUploadComponent: React.FC = ({ const duplicates: string[] = []; const uniqueFiles: File[] = []; - console.log("🔍 중복 파일 체크:", { - uploadedFiles: uploadedFiles.length, - existingFileNames: existingFileNames, - newFiles: files.map((f) => f.name.toLowerCase()), - }); - files.forEach((file) => { const fileName = file.name.toLowerCase(); if (existingFileNames.includes(fileName)) { duplicates.push(file.name); - console.log("❌ 중복 파일 발견:", file.name); } else { uniqueFiles.push(file); - console.log("✅ 새로운 파일:", file.name); } }); - console.log("🔍 중복 체크 결과:", { - duplicates: duplicates, - uniqueFiles: uniqueFiles.map((f) => f.name), - }); - if (duplicates.length > 0) { toast.error(`중복된 파일이 있습니다: ${duplicates.join(", ")}`, { description: "같은 이름의 파일이 이미 업로드되어 있습니다.", @@ -543,7 +488,6 @@ const FileUploadComponent: React.FC = ({ } else if (screenId) { // 🔑 템플릿 파일 (백엔드 조회 형식과 동일하게) targetObjid = `screen_files:${screenId}:${component.id}:${columnName}`; - console.log("🎨 템플릿 파일 업로드:", { targetObjid, screenId, componentId: component.id, columnName }); } else { // 기본값 (화면관리에서 사용) targetObjid = `temp_${component.id}`; @@ -569,30 +513,16 @@ const FileUploadComponent: React.FC = ({ targetObjid: targetObjid, // InteractiveDataTable 호환을 위한 targetObjid 추가 }; - console.log("📤 파일 업로드 시작:", { - originalFiles: files.length, - filesToUpload: filesToUpload.length, - files: filesToUpload.map((f) => ({ name: f.name, size: f.size })), - uploadData, - }); const response = await uploadFiles({ files: filesToUpload, ...uploadData, }); - console.log("📤 파일 업로드 API 응답:", response); if (response.success) { // FileUploadResponse 타입에 맞게 files 배열 사용 const fileData = response.files || (response as any).data || []; - console.log("📁 파일 데이터 확인:", { - hasFiles: !!response.files, - hasData: !!(response as any).data, - fileDataLength: fileData.length, - fileData: fileData, - responseKeys: Object.keys(response), - }); if (fileData.length === 0) { throw new Error("업로드된 파일 데이터를 받지 못했습니다."); @@ -617,15 +547,8 @@ const FileUploadComponent: React.FC = ({ ...file, })); - console.log("📁 변환된 파일 데이터:", newFiles); const updatedFiles = [...uploadedFiles, ...newFiles]; - console.log("🔄 파일 상태 업데이트:", { - 이전파일수: uploadedFiles.length, - 새파일수: newFiles.length, - 총파일수: updatedFiles.length, - updatedFiles: updatedFiles.map((f) => ({ objid: f.objid, name: f.realFileName })), - }); setUploadedFiles(updatedFiles); setUploadStatus("success"); From 573a300a4a6aebb8d2ab9b2a069bc4c11587d9d6 Mon Sep 17 00:00:00 2001 From: kjs Date: Wed, 5 Nov 2025 15:23:57 +0900 Subject: [PATCH 07/37] =?UTF-8?q?=EC=B9=B4=ED=85=8C=EA=B3=A0=EB=A6=AC=20?= =?UTF-8?q?=EA=B8=B0=EB=8A=A5=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend-node/src/app.ts | 2 + .../tableCategoryValueController.ts | 246 ++ .../src/routes/tableCategoryValueRoutes.ts | 50 + backend-node/src/services/dataService.ts | 257 +- .../src/services/tableCategoryValueService.ts | 497 ++++ backend-node/src/types/tableCategoryValue.ts | 48 + .../screen/InteractiveScreenViewerDynamic.tsx | 2 +- .../components/screen/RealtimePreview.tsx | 2 +- .../screen/RealtimePreviewDynamic.tsx | 3 +- .../screen/panels/UnifiedPropertiesPanel.tsx | 7 +- .../screen/widgets/CategoryWidget.tsx | 81 + .../screen/widgets/types/ButtonWidget.tsx | 2 +- .../table-category/CategoryColumnList.tsx | 187 ++ .../table-category/CategoryValueAddDialog.tsx | 170 ++ .../CategoryValueEditDialog.tsx | 175 ++ .../table-category/CategoryValueManager.tsx | 378 +++ frontend/constants/tableManagement.ts | 7 + frontend/lib/api/tableCategoryValue.ts | 128 + .../lib/registry/DynamicComponentRenderer.tsx | 6 + .../registry/components/category-manager.tsx | 69 + .../CategoryManagerConfigPanel.tsx | 117 + .../CategoryManagerRenderer.tsx | 76 + frontend/lib/registry/components/index.ts | 1 + frontend/types/input-types.ts | 20 +- frontend/types/tableCategoryValue.ts | 48 + frontend/types/unified-core.ts | 3 +- 동적_테이블_접근_시스템_개선_완료.md | 377 +++ 카테고리_관리_컴포넌트_구현_계획서.md | 2320 +++++++++++++++++ 카테고리_시스템_구현_계획서.md | 1524 +++++++++++ 카테고리_시스템_재구현_계획서.md | 666 +++++ 카테고리_시스템_재구현_완료_보고서.md | 629 +++++ 카테고리_시스템_최종_완료_보고서.md | 483 ++++ 카테고리_컴포넌트_DB_호환성_분석.md | 361 +++ 카테고리_컴포넌트_구현_완료.md | 471 ++++ 카테고리_타입_구현_완료.md | 295 +++ 35 files changed, 9577 insertions(+), 131 deletions(-) create mode 100644 backend-node/src/controllers/tableCategoryValueController.ts create mode 100644 backend-node/src/routes/tableCategoryValueRoutes.ts create mode 100644 backend-node/src/services/tableCategoryValueService.ts create mode 100644 backend-node/src/types/tableCategoryValue.ts create mode 100644 frontend/components/screen/widgets/CategoryWidget.tsx create mode 100644 frontend/components/table-category/CategoryColumnList.tsx create mode 100644 frontend/components/table-category/CategoryValueAddDialog.tsx create mode 100644 frontend/components/table-category/CategoryValueEditDialog.tsx create mode 100644 frontend/components/table-category/CategoryValueManager.tsx create mode 100644 frontend/lib/api/tableCategoryValue.ts create mode 100644 frontend/lib/registry/components/category-manager.tsx create mode 100644 frontend/lib/registry/components/category-manager/CategoryManagerConfigPanel.tsx create mode 100644 frontend/lib/registry/components/category-manager/CategoryManagerRenderer.tsx create mode 100644 frontend/types/tableCategoryValue.ts create mode 100644 동적_테이블_접근_시스템_개선_완료.md create mode 100644 카테고리_관리_컴포넌트_구현_계획서.md create mode 100644 카테고리_시스템_구현_계획서.md create mode 100644 카테고리_시스템_재구현_계획서.md create mode 100644 카테고리_시스템_재구현_완료_보고서.md create mode 100644 카테고리_시스템_최종_완료_보고서.md create mode 100644 카테고리_컴포넌트_DB_호환성_분석.md create mode 100644 카테고리_컴포넌트_구현_완료.md create mode 100644 카테고리_타입_구현_완료.md diff --git a/backend-node/src/app.ts b/backend-node/src/app.ts index 131b9e1a..c5af1bfe 100644 --- a/backend-node/src/app.ts +++ b/backend-node/src/app.ts @@ -66,6 +66,7 @@ import tableHistoryRoutes from "./routes/tableHistoryRoutes"; // 테이블 변 import roleRoutes from "./routes/roleRoutes"; // 권한 그룹 관리 import numberingRuleController from "./controllers/numberingRuleController"; // 채번 규칙 관리 import departmentRoutes from "./routes/departmentRoutes"; // 부서 관리 +import tableCategoryValueRoutes from "./routes/tableCategoryValueRoutes"; // 카테고리 값 관리 import { BatchSchedulerService } from "./services/batchSchedulerService"; // import collectionRoutes from "./routes/collectionRoutes"; // 임시 주석 // import batchRoutes from "./routes/batchRoutes"; // 임시 주석 @@ -226,6 +227,7 @@ app.use("/api/table-history", tableHistoryRoutes); // 테이블 변경 이력 app.use("/api/roles", roleRoutes); // 권한 그룹 관리 app.use("/api/numbering-rules", numberingRuleController); // 채번 규칙 관리 app.use("/api/departments", departmentRoutes); // 부서 관리 +app.use("/api/table-categories", tableCategoryValueRoutes); // 카테고리 값 관리 // app.use("/api/collections", collectionRoutes); // 임시 주석 // app.use("/api/batch", batchRoutes); // 임시 주석 // app.use('/api/users', userRoutes); diff --git a/backend-node/src/controllers/tableCategoryValueController.ts b/backend-node/src/controllers/tableCategoryValueController.ts new file mode 100644 index 00000000..75837300 --- /dev/null +++ b/backend-node/src/controllers/tableCategoryValueController.ts @@ -0,0 +1,246 @@ +import { Request, Response } from "express"; +import tableCategoryValueService from "../services/tableCategoryValueService"; +import { logger } from "../utils/logger"; + +/** + * 테이블의 카테고리 컬럼 목록 조회 + */ +export const getCategoryColumns = async (req: Request, res: Response) => { + try { + const companyCode = req.user!.companyCode; + const { tableName } = req.params; + + const columns = await tableCategoryValueService.getCategoryColumns( + tableName, + companyCode + ); + + return res.json({ + success: true, + data: columns, + }); + } catch (error: any) { + logger.error(`카테고리 컬럼 조회 실패: ${error.message}`); + return res.status(500).json({ + success: false, + message: "카테고리 컬럼 조회 중 오류가 발생했습니다", + error: error.message, + }); + } +}; + +/** + * 카테고리 값 목록 조회 (메뉴 스코프 적용) + */ +export const getCategoryValues = async (req: Request, res: Response) => { + try { + const companyCode = req.user!.companyCode; + const { tableName, columnName } = req.params; + const menuId = parseInt(req.query.menuId as string, 10); + const includeInactive = req.query.includeInactive === "true"; + + if (!menuId || isNaN(menuId)) { + return res.status(400).json({ + success: false, + message: "menuId 파라미터가 필요합니다", + }); + } + + const values = await tableCategoryValueService.getCategoryValues( + tableName, + columnName, + menuId, + companyCode, + includeInactive + ); + + return res.json({ + success: true, + data: values, + }); + } catch (error: any) { + logger.error(`카테고리 값 조회 실패: ${error.message}`); + return res.status(500).json({ + success: false, + message: "카테고리 값 조회 중 오류가 발생했습니다", + error: error.message, + }); + } +}; + +/** + * 카테고리 값 추가 + */ +export const addCategoryValue = async (req: Request, res: Response) => { + try { + const companyCode = req.user!.companyCode; + const userId = req.user!.userId; + const value = req.body; + + const newValue = await tableCategoryValueService.addCategoryValue( + value, + companyCode, + userId + ); + + return res.status(201).json({ + success: true, + data: newValue, + }); + } catch (error: any) { + logger.error(`카테고리 값 추가 실패: ${error.message}`); + return res.status(500).json({ + success: false, + message: error.message || "카테고리 값 추가 중 오류가 발생했습니다", + error: error.message, + }); + } +}; + +/** + * 카테고리 값 수정 + */ +export const updateCategoryValue = async (req: Request, res: Response) => { + try { + const companyCode = req.user!.companyCode; + const userId = req.user!.userId; + const valueId = parseInt(req.params.valueId); + const updates = req.body; + + if (isNaN(valueId)) { + return res.status(400).json({ + success: false, + message: "유효하지 않은 값 ID입니다", + }); + } + + const updatedValue = await tableCategoryValueService.updateCategoryValue( + valueId, + updates, + companyCode, + userId + ); + + return res.json({ + success: true, + data: updatedValue, + }); + } catch (error: any) { + logger.error(`카테고리 값 수정 실패: ${error.message}`); + return res.status(500).json({ + success: false, + message: "카테고리 값 수정 중 오류가 발생했습니다", + error: error.message, + }); + } +}; + +/** + * 카테고리 값 삭제 + */ +export const deleteCategoryValue = async (req: Request, res: Response) => { + try { + const companyCode = req.user!.companyCode; + const userId = req.user!.userId; + const valueId = parseInt(req.params.valueId); + + if (isNaN(valueId)) { + return res.status(400).json({ + success: false, + message: "유효하지 않은 값 ID입니다", + }); + } + + await tableCategoryValueService.deleteCategoryValue( + valueId, + companyCode, + userId + ); + + return res.json({ + success: true, + message: "카테고리 값이 삭제되었습니다", + }); + } catch (error: any) { + logger.error(`카테고리 값 삭제 실패: ${error.message}`); + return res.status(500).json({ + success: false, + message: error.message || "카테고리 값 삭제 중 오류가 발생했습니다", + error: error.message, + }); + } +}; + +/** + * 카테고리 값 일괄 삭제 + */ +export const bulkDeleteCategoryValues = async ( + req: Request, + res: Response +) => { + try { + const companyCode = req.user!.companyCode; + const userId = req.user!.userId; + const { valueIds } = req.body; + + if (!Array.isArray(valueIds) || valueIds.length === 0) { + return res.status(400).json({ + success: false, + message: "삭제할 값 ID 목록이 필요합니다", + }); + } + + await tableCategoryValueService.bulkDeleteCategoryValues( + valueIds, + companyCode, + userId + ); + + return res.json({ + success: true, + message: `${valueIds.length}개의 카테고리 값이 삭제되었습니다`, + }); + } catch (error: any) { + logger.error(`카테고리 값 일괄 삭제 실패: ${error.message}`); + return res.status(500).json({ + success: false, + message: "카테고리 값 일괄 삭제 중 오류가 발생했습니다", + error: error.message, + }); + } +}; + +/** + * 카테고리 값 순서 변경 + */ +export const reorderCategoryValues = async (req: Request, res: Response) => { + try { + const companyCode = req.user!.companyCode; + const { orderedValueIds } = req.body; + + if (!Array.isArray(orderedValueIds) || orderedValueIds.length === 0) { + return res.status(400).json({ + success: false, + message: "순서 정보가 필요합니다", + }); + } + + await tableCategoryValueService.reorderCategoryValues( + orderedValueIds, + companyCode + ); + + return res.json({ + success: true, + message: "카테고리 값 순서가 변경되었습니다", + }); + } catch (error: any) { + logger.error(`카테고리 값 순서 변경 실패: ${error.message}`); + return res.status(500).json({ + success: false, + message: "카테고리 값 순서 변경 중 오류가 발생했습니다", + error: error.message, + }); + } +}; + diff --git a/backend-node/src/routes/tableCategoryValueRoutes.ts b/backend-node/src/routes/tableCategoryValueRoutes.ts new file mode 100644 index 00000000..cc2ba05f --- /dev/null +++ b/backend-node/src/routes/tableCategoryValueRoutes.ts @@ -0,0 +1,50 @@ +import { Router } from "express"; +import * as tableCategoryValueController from "../controllers/tableCategoryValueController"; +import { authenticateToken } from "../middleware/authMiddleware"; + +const router = Router(); + +// 모든 라우트에 인증 미들웨어 적용 +router.use(authenticateToken); + +// 테이블의 카테고리 컬럼 목록 조회 +router.get( + "/:tableName/columns", + tableCategoryValueController.getCategoryColumns +); + +// 카테고리 값 목록 조회 +router.get( + "/:tableName/:columnName/values", + tableCategoryValueController.getCategoryValues +); + +// 카테고리 값 추가 +router.post("/values", tableCategoryValueController.addCategoryValue); + +// 카테고리 값 수정 +router.put( + "/values/:valueId", + tableCategoryValueController.updateCategoryValue +); + +// 카테고리 값 삭제 +router.delete( + "/values/:valueId", + tableCategoryValueController.deleteCategoryValue +); + +// 카테고리 값 일괄 삭제 +router.post( + "/values/bulk-delete", + tableCategoryValueController.bulkDeleteCategoryValues +); + +// 카테고리 값 순서 변경 +router.post( + "/values/reorder", + tableCategoryValueController.reorderCategoryValues +); + +export default router; + diff --git a/backend-node/src/services/dataService.ts b/backend-node/src/services/dataService.ts index 3de082d7..462ebb4d 100644 --- a/backend-node/src/services/dataService.ts +++ b/backend-node/src/services/dataService.ts @@ -1,3 +1,18 @@ +/** + * 동적 데이터 서비스 + * + * 주요 특징: + * 1. 화이트리스트 제거 - 모든 테이블에 동적으로 접근 가능 + * 2. 블랙리스트 방식 - 시스템 중요 테이블만 접근 금지 + * 3. 자동 회사별 필터링 - company_code 컬럼 자동 감지 및 필터 적용 + * 4. SQL 인젝션 방지 - 정규식 기반 테이블명/컬럼명 검증 + * + * 보안: + * - 테이블명은 영문, 숫자, 언더스코어만 허용 + * - 시스템 테이블(pg_*, information_schema 등) 접근 금지 + * - company_code 컬럼이 있는 테이블은 자동으로 회사별 격리 + * - 최고 관리자(company_code = "*")만 전체 데이터 조회 가능 + */ import { query, queryOne } from "../database/db"; interface GetTableDataParams { @@ -17,65 +32,72 @@ interface ServiceResponse { } /** - * 안전한 테이블명 목록 (화이트리스트) - * SQL 인젝션 방지를 위해 허용된 테이블만 접근 가능 + * 접근 금지 테이블 목록 (블랙리스트) + * 시스템 중요 테이블 및 보안상 접근 금지할 테이블 */ -const ALLOWED_TABLES = [ - "company_mng", - "user_info", - "dept_info", - "code_info", - "code_category", - "menu_info", - "approval", - "approval_kind", - "board", - "comm_code", - "product_mng", - "part_mng", - "material_mng", - "order_mng_master", - "inventory_mng", - "contract_mgmt", - "project_mgmt", - "screen_definitions", - "screen_layouts", - "layout_standards", - "component_standards", - "web_type_standards", - "button_action_standards", - "template_standards", - "grid_standards", - "style_templates", - "multi_lang_key_master", - "multi_lang_text", - "language_master", - "table_labels", - "column_labels", - "dynamic_form_data", - "work_history", // 작업 이력 테이블 - "delivery_status", // 배송 현황 테이블 +const BLOCKED_TABLES = [ + "pg_catalog", + "pg_statistic", + "pg_database", + "pg_user", + "information_schema", + "session_tokens", // 세션 토큰 테이블 + "password_history", // 패스워드 이력 ]; /** - * 회사별 필터링이 필요한 테이블 목록 + * 테이블 이름 검증 정규식 + * SQL 인젝션 방지: 영문, 숫자, 언더스코어만 허용 */ -const COMPANY_FILTERED_TABLES = [ - "company_mng", - "user_info", - "dept_info", - "approval", - "board", - "product_mng", - "part_mng", - "material_mng", - "order_mng_master", - "inventory_mng", - "contract_mgmt", - "project_mgmt", -]; +const TABLE_NAME_REGEX = /^[a-zA-Z_][a-zA-Z0-9_]*$/; class DataService { + /** + * 테이블 접근 검증 (공통 메서드) + */ + private async validateTableAccess( + tableName: string + ): Promise<{ valid: boolean; error?: ServiceResponse }> { + // 1. 테이블명 형식 검증 (SQL 인젝션 방지) + if (!TABLE_NAME_REGEX.test(tableName)) { + return { + valid: false, + error: { + success: false, + message: `유효하지 않은 테이블명입니다: ${tableName}`, + error: "INVALID_TABLE_NAME", + }, + }; + } + + // 2. 블랙리스트 검증 + if (BLOCKED_TABLES.includes(tableName)) { + return { + valid: false, + error: { + success: false, + message: `접근이 금지된 테이블입니다: ${tableName}`, + error: "TABLE_ACCESS_DENIED", + }, + }; + } + + // 3. 테이블 존재 여부 확인 + const tableExists = await this.checkTableExists(tableName); + if (!tableExists) { + return { + valid: false, + error: { + success: false, + message: `테이블을 찾을 수 없습니다: ${tableName}`, + error: "TABLE_NOT_FOUND", + }, + }; + } + + return { valid: true }; + } + /** * 테이블 데이터 조회 */ @@ -92,23 +114,10 @@ class DataService { } = params; try { - // 테이블명 화이트리스트 검증 - if (!ALLOWED_TABLES.includes(tableName)) { - return { - success: false, - message: `접근이 허용되지 않은 테이블입니다: ${tableName}`, - error: "TABLE_NOT_ALLOWED", - }; - } - - // 테이블 존재 여부 확인 - const tableExists = await this.checkTableExists(tableName); - if (!tableExists) { - return { - success: false, - message: `테이블을 찾을 수 없습니다: ${tableName}`, - error: "TABLE_NOT_FOUND", - }; + // 테이블 접근 검증 + const validation = await this.validateTableAccess(tableName); + if (!validation.valid) { + return validation.error!; } // 동적 SQL 쿼리 생성 @@ -119,13 +128,14 @@ class DataService { // WHERE 조건 생성 const whereConditions: string[] = []; - // 회사별 필터링 추가 - if (COMPANY_FILTERED_TABLES.includes(tableName) && userCompany) { - // 슈퍼관리자(*)가 아닌 경우에만 회사 필터 적용 - if (userCompany !== "*") { + // 4. 회사별 필터링 자동 적용 (company_code 컬럼이 있는 경우) + if (userCompany && userCompany !== "*") { + const hasCompanyCode = await this.checkColumnExists(tableName, "company_code"); + if (hasCompanyCode) { whereConditions.push(`company_code = $${paramIndex}`); queryParams.push(userCompany); paramIndex++; + console.log(`🏢 회사별 필터링 적용: ${tableName}.company_code = ${userCompany}`); } } @@ -213,13 +223,10 @@ class DataService { */ async getTableColumns(tableName: string): Promise> { try { - // 테이블명 화이트리스트 검증 - if (!ALLOWED_TABLES.includes(tableName)) { - return { - success: false, - message: `접근이 허용되지 않은 테이블입니다: ${tableName}`, - error: "TABLE_NOT_ALLOWED", - }; + // 테이블 접근 검증 + const validation = await this.validateTableAccess(tableName); + if (!validation.valid) { + return validation.error!; } const columns = await this.getTableColumnsSimple(tableName); @@ -276,6 +283,31 @@ class DataService { } } + /** + * 특정 컬럼 존재 여부 확인 + */ + private async checkColumnExists( + tableName: string, + columnName: string + ): Promise { + try { + const result = await query<{ exists: boolean }>( + `SELECT EXISTS ( + SELECT FROM information_schema.columns + WHERE table_schema = 'public' + AND table_name = $1 + AND column_name = $2 + )`, + [tableName, columnName] + ); + + return result[0]?.exists || false; + } catch (error) { + console.error("컬럼 존재 확인 오류:", error); + return false; + } + } + /** * 테이블 컬럼 정보 조회 (간단 버전) */ @@ -324,13 +356,10 @@ class DataService { id: string | number ): Promise> { try { - // 테이블명 화이트리스트 검증 - if (!ALLOWED_TABLES.includes(tableName)) { - return { - success: false, - message: `접근이 허용되지 않은 테이블입니다: ${tableName}`, - error: "TABLE_NOT_ALLOWED", - }; + // 테이블 접근 검증 + const validation = await this.validateTableAccess(tableName); + if (!validation.valid) { + return validation.error!; } // Primary Key 컬럼 찾기 @@ -383,21 +412,16 @@ class DataService { leftValue?: string | number ): Promise> { try { - // 테이블명 화이트리스트 검증 - if (!ALLOWED_TABLES.includes(leftTable)) { - return { - success: false, - message: `접근이 허용되지 않은 테이블입니다: ${leftTable}`, - error: "TABLE_NOT_ALLOWED", - }; + // 왼쪽 테이블 접근 검증 + const leftValidation = await this.validateTableAccess(leftTable); + if (!leftValidation.valid) { + return leftValidation.error!; } - if (!ALLOWED_TABLES.includes(rightTable)) { - return { - success: false, - message: `접근이 허용되지 않은 테이블입니다: ${rightTable}`, - error: "TABLE_NOT_ALLOWED", - }; + // 오른쪽 테이블 접근 검증 + const rightValidation = await this.validateTableAccess(rightTable); + if (!rightValidation.valid) { + return rightValidation.error!; } let queryText = ` @@ -440,13 +464,10 @@ class DataService { data: Record ): Promise> { try { - // 테이블명 화이트리스트 검증 - if (!ALLOWED_TABLES.includes(tableName)) { - return { - success: false, - message: `접근이 허용되지 않은 테이블입니다: ${tableName}`, - error: "TABLE_NOT_ALLOWED", - }; + // 테이블 접근 검증 + const validation = await this.validateTableAccess(tableName); + if (!validation.valid) { + return validation.error!; } const columns = Object.keys(data); @@ -485,13 +506,10 @@ class DataService { data: Record ): Promise> { try { - // 테이블명 화이트리스트 검증 - if (!ALLOWED_TABLES.includes(tableName)) { - return { - success: false, - message: `접근이 허용되지 않은 테이블입니다: ${tableName}`, - error: "TABLE_NOT_ALLOWED", - }; + // 테이블 접근 검증 + const validation = await this.validateTableAccess(tableName); + if (!validation.valid) { + return validation.error!; } // Primary Key 컬럼 찾기 @@ -554,13 +572,10 @@ class DataService { id: string | number ): Promise> { try { - // 테이블명 화이트리스트 검증 - if (!ALLOWED_TABLES.includes(tableName)) { - return { - success: false, - message: `접근이 허용되지 않은 테이블입니다: ${tableName}`, - error: "TABLE_NOT_ALLOWED", - }; + // 테이블 접근 검증 + const validation = await this.validateTableAccess(tableName); + if (!validation.valid) { + return validation.error!; } // Primary Key 컬럼 찾기 diff --git a/backend-node/src/services/tableCategoryValueService.ts b/backend-node/src/services/tableCategoryValueService.ts new file mode 100644 index 00000000..a459e24b --- /dev/null +++ b/backend-node/src/services/tableCategoryValueService.ts @@ -0,0 +1,497 @@ +import { getPool } from "../database/db"; +import { logger } from "../utils/logger"; +import { + TableCategoryValue, + CategoryColumn, +} from "../types/tableCategoryValue"; + +class TableCategoryValueService { + /** + * 메뉴의 형제 메뉴 ID 목록 조회 + * (같은 부모를 가진 메뉴들) + */ + async getSiblingMenuIds(menuId: number): Promise { + try { + const pool = getPool(); + + // 1. 현재 메뉴의 부모 ID 조회 (menu_info는 objid와 parent_obj_id 사용) + const parentQuery = ` + SELECT parent_obj_id FROM menu_info WHERE objid = $1 + `; + const parentResult = await pool.query(parentQuery, [menuId]); + + if (parentResult.rows.length === 0) { + logger.warn(`메뉴 ID ${menuId}를 찾을 수 없습니다`); + return [menuId]; + } + + const parentId = parentResult.rows[0].parent_obj_id; + + // 최상위 메뉴인 경우 (parent_obj_id가 null 또는 0) + if (!parentId || parentId === 0) { + logger.info(`메뉴 ${menuId}는 최상위 메뉴입니다`); + return [menuId]; + } + + // 2. 같은 부모를 가진 형제 메뉴들 조회 + const siblingsQuery = ` + SELECT objid FROM menu_info WHERE parent_obj_id = $1 + `; + const siblingsResult = await pool.query(siblingsQuery, [parentId]); + + const siblingIds = siblingsResult.rows.map((row) => Number(row.objid)); + + logger.info(`메뉴 ${menuId}의 형제 메뉴 ${siblingIds.length}개 조회`, { + menuId, + parentId, + siblings: siblingIds, + }); + + return siblingIds; + } catch (error: any) { + logger.error(`형제 메뉴 조회 실패: ${error.message}`); + // 에러 시 현재 메뉴만 반환 + return [menuId]; + } + } + /** + * 테이블의 카테고리 타입 컬럼 목록 조회 + */ + async getCategoryColumns( + tableName: string, + companyCode: string + ): Promise { + try { + logger.info("카테고리 컬럼 목록 조회", { tableName, companyCode }); + + const pool = getPool(); + const query = ` + SELECT + tc.table_name AS "tableName", + tc.column_name AS "columnName", + tc.column_name AS "columnLabel", + COUNT(cv.value_id) AS "valueCount" + FROM table_type_columns tc + LEFT JOIN table_column_category_values cv + ON tc.table_name = cv.table_name + AND tc.column_name = cv.column_name + AND cv.is_active = true + AND (cv.company_code = $2 OR cv.company_code = '*') + WHERE tc.table_name = $1 + AND tc.input_type = 'category' + GROUP BY tc.table_name, tc.column_name, tc.display_order + ORDER BY tc.display_order, tc.column_name + `; + + const result = await pool.query(query, [tableName, companyCode]); + + logger.info(`카테고리 컬럼 ${result.rows.length}개 조회 완료`, { + tableName, + companyCode, + }); + + return result.rows; + } catch (error: any) { + logger.error(`카테고리 컬럼 조회 실패: ${error.message}`); + throw error; + } + } + + /** + * 특정 컬럼의 카테고리 값 목록 조회 (메뉴 스코프 적용) + */ + async getCategoryValues( + tableName: string, + columnName: string, + menuId: number, + companyCode: string, + includeInactive: boolean = false + ): Promise { + try { + logger.info("카테고리 값 목록 조회", { + tableName, + columnName, + menuId, + companyCode, + includeInactive, + }); + + // 1. 메뉴 스코프 확인: 형제 메뉴들의 카테고리도 포함 + const siblingMenuIds = await this.getSiblingMenuIds(menuId); + + const pool = getPool(); + let query = ` + SELECT + value_id AS "valueId", + table_name AS "tableName", + column_name AS "columnName", + value_code AS "valueCode", + value_label AS "valueLabel", + value_order AS "valueOrder", + parent_value_id AS "parentValueId", + depth, + description, + color, + icon, + is_active AS "isActive", + is_default AS "isDefault", + menu_objid AS "menuId", + company_code AS "companyCode", + created_at AS "createdAt", + updated_at AS "updatedAt", + created_by AS "createdBy", + updated_by AS "updatedBy" + FROM table_column_category_values + WHERE table_name = $1 + AND column_name = $2 + AND menu_objid = ANY($3) + AND (company_code = $4 OR company_code = '*') + `; + + const params: any[] = [tableName, columnName, siblingMenuIds, companyCode]; + + if (!includeInactive) { + query += ` AND is_active = true`; + } + + query += ` ORDER BY value_order, value_label`; + + const result = await pool.query(query, params); + + // 계층 구조로 변환 + const values = this.buildHierarchy(result.rows); + + logger.info(`카테고리 값 ${result.rows.length}개 조회 완료`, { + tableName, + columnName, + menuId, + siblingMenuIds, + }); + + return values; + } catch (error: any) { + logger.error(`카테고리 값 조회 실패: ${error.message}`); + throw error; + } + } + + /** + * 카테고리 값 추가 + */ + async addCategoryValue( + value: TableCategoryValue, + companyCode: string, + userId: string + ): Promise { + const pool = getPool(); + + try { + // 중복 코드 체크 + const duplicateQuery = ` + SELECT value_id + FROM table_column_category_values + WHERE table_name = $1 + AND column_name = $2 + AND value_code = $3 + AND (company_code = $4 OR company_code = '*') + `; + + const duplicateResult = await pool.query(duplicateQuery, [ + value.tableName, + value.columnName, + value.valueCode, + companyCode, + ]); + + if (duplicateResult.rows.length > 0) { + throw new Error("이미 존재하는 코드입니다"); + } + + const insertQuery = ` + INSERT INTO table_column_category_values ( + table_name, column_name, value_code, value_label, value_order, + parent_value_id, depth, description, color, icon, + is_active, is_default, menu_objid, company_code, created_by + ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15) + RETURNING + value_id AS "valueId", + table_name AS "tableName", + column_name AS "columnName", + value_code AS "valueCode", + value_label AS "valueLabel", + value_order AS "valueOrder", + parent_value_id AS "parentValueId", + depth, + description, + color, + icon, + is_active AS "isActive", + is_default AS "isDefault", + menu_objid AS "menuId", + company_code AS "companyCode", + created_at AS "createdAt", + created_by AS "createdBy" + `; + + const result = await pool.query(insertQuery, [ + value.tableName, + value.columnName, + value.valueCode, + value.valueLabel, + value.valueOrder || 0, + value.parentValueId || null, + value.depth || 1, + value.description || null, + value.color || null, + value.icon || null, + value.isActive !== false, + value.isDefault || false, + value.menuId, // menuId 추가 + companyCode, + userId, + ]); + + logger.info("카테고리 값 추가 완료", { + valueId: result.rows[0].valueId, + tableName: value.tableName, + columnName: value.columnName, + }); + + return result.rows[0]; + } catch (error: any) { + logger.error(`카테고리 값 추가 실패: ${error.message}`); + throw error; + } + } + + /** + * 카테고리 값 수정 + */ + async updateCategoryValue( + valueId: number, + updates: Partial, + companyCode: string, + userId: string + ): Promise { + const pool = getPool(); + + try { + const setClauses: string[] = []; + const values: any[] = []; + let paramIndex = 1; + + if (updates.valueLabel !== undefined) { + setClauses.push(`value_label = $${paramIndex++}`); + values.push(updates.valueLabel); + } + + if (updates.valueOrder !== undefined) { + setClauses.push(`value_order = $${paramIndex++}`); + values.push(updates.valueOrder); + } + + if (updates.description !== undefined) { + setClauses.push(`description = $${paramIndex++}`); + values.push(updates.description); + } + + if (updates.color !== undefined) { + setClauses.push(`color = $${paramIndex++}`); + values.push(updates.color); + } + + if (updates.icon !== undefined) { + setClauses.push(`icon = $${paramIndex++}`); + values.push(updates.icon); + } + + if (updates.isActive !== undefined) { + setClauses.push(`is_active = $${paramIndex++}`); + values.push(updates.isActive); + } + + if (updates.isDefault !== undefined) { + setClauses.push(`is_default = $${paramIndex++}`); + values.push(updates.isDefault); + } + + setClauses.push(`updated_at = NOW()`); + setClauses.push(`updated_by = $${paramIndex++}`); + values.push(userId); + + values.push(valueId, companyCode); + + const updateQuery = ` + UPDATE table_column_category_values + SET ${setClauses.join(", ")} + WHERE value_id = $${paramIndex++} + AND (company_code = $${paramIndex++} OR company_code = '*') + RETURNING + value_id AS "valueId", + table_name AS "tableName", + column_name AS "columnName", + value_code AS "valueCode", + value_label AS "valueLabel", + value_order AS "valueOrder", + description, + color, + icon, + is_active AS "isActive", + is_default AS "isDefault", + menu_objid AS "menuId", + updated_at AS "updatedAt", + updated_by AS "updatedBy" + `; + + const result = await pool.query(updateQuery, values); + + if (result.rowCount === 0) { + throw new Error("카테고리 값을 찾을 수 없습니다"); + } + + logger.info("카테고리 값 수정 완료", { valueId, companyCode }); + + return result.rows[0]; + } catch (error: any) { + logger.error(`카테고리 값 수정 실패: ${error.message}`); + throw error; + } + } + + /** + * 카테고리 값 삭제 (비활성화) + */ + async deleteCategoryValue( + valueId: number, + companyCode: string, + userId: string + ): Promise { + const pool = getPool(); + + try { + // 하위 값 체크 + const checkQuery = ` + SELECT COUNT(*) as count + FROM table_column_category_values + WHERE parent_value_id = $1 + AND (company_code = $2 OR company_code = '*') + AND is_active = true + `; + + const checkResult = await pool.query(checkQuery, [valueId, companyCode]); + + if (parseInt(checkResult.rows[0].count) > 0) { + throw new Error("하위 카테고리 값이 있어 삭제할 수 없습니다"); + } + + // 비활성화 + const deleteQuery = ` + UPDATE table_column_category_values + SET is_active = false, updated_at = NOW(), updated_by = $3 + WHERE value_id = $1 + AND (company_code = $2 OR company_code = '*') + `; + + await pool.query(deleteQuery, [valueId, companyCode, userId]); + + logger.info("카테고리 값 삭제(비활성화) 완료", { + valueId, + companyCode, + }); + } catch (error: any) { + logger.error(`카테고리 값 삭제 실패: ${error.message}`); + throw error; + } + } + + /** + * 카테고리 값 일괄 삭제 + */ + async bulkDeleteCategoryValues( + valueIds: number[], + companyCode: string, + userId: string + ): Promise { + const pool = getPool(); + + try { + const deleteQuery = ` + UPDATE table_column_category_values + SET is_active = false, updated_at = NOW(), updated_by = $3 + WHERE value_id = ANY($1::int[]) + AND (company_code = $2 OR company_code = '*') + `; + + await pool.query(deleteQuery, [valueIds, companyCode, userId]); + + logger.info("카테고리 값 일괄 삭제 완료", { + count: valueIds.length, + companyCode, + }); + } catch (error: any) { + logger.error(`카테고리 값 일괄 삭제 실패: ${error.message}`); + throw error; + } + } + + /** + * 카테고리 값 순서 변경 + */ + async reorderCategoryValues( + orderedValueIds: number[], + companyCode: string + ): Promise { + const pool = getPool(); + const client = await pool.connect(); + + try { + await client.query("BEGIN"); + + for (let i = 0; i < orderedValueIds.length; i++) { + const updateQuery = ` + UPDATE table_column_category_values + SET value_order = $1, updated_at = NOW() + WHERE value_id = $2 + AND (company_code = $3 OR company_code = '*') + `; + + await client.query(updateQuery, [ + i + 1, + orderedValueIds[i], + companyCode, + ]); + } + + await client.query("COMMIT"); + + logger.info("카테고리 값 순서 변경 완료", { + count: orderedValueIds.length, + companyCode, + }); + } catch (error: any) { + await client.query("ROLLBACK"); + logger.error(`카테고리 값 순서 변경 실패: ${error.message}`); + throw error; + } finally { + client.release(); + } + } + + /** + * 계층 구조 변환 헬퍼 + */ + private buildHierarchy( + values: TableCategoryValue[], + parentId: number | null = null + ): TableCategoryValue[] { + return values + .filter((v) => v.parentValueId === parentId) + .map((v) => ({ + ...v, + children: this.buildHierarchy(values, v.valueId!), + })); + } +} + +export default new TableCategoryValueService(); + diff --git a/backend-node/src/types/tableCategoryValue.ts b/backend-node/src/types/tableCategoryValue.ts new file mode 100644 index 00000000..ee1c4c2f --- /dev/null +++ b/backend-node/src/types/tableCategoryValue.ts @@ -0,0 +1,48 @@ +/** + * 테이블 컬럼별 카테고리 값 타입 정의 + */ + +export interface TableCategoryValue { + valueId?: number; + tableName: string; + columnName: string; + + // 값 정보 + valueCode: string; + valueLabel: string; + valueOrder?: number; + + // 계층 구조 + parentValueId?: number; + depth?: number; + + // 추가 정보 + description?: string; + color?: string; + icon?: string; + isActive?: boolean; + isDefault?: boolean; + + // 하위 항목 (조회 시) + children?: TableCategoryValue[]; + + // 메뉴 스코프 + menuId: number; + + // 멀티테넌시 + companyCode?: string; + + // 메타 + createdAt?: string; + updatedAt?: string; + createdBy?: string; + updatedBy?: string; +} + +export interface CategoryColumn { + tableName: string; + columnName: string; + columnLabel: string; + valueCount?: number; // 값 개수 +} + diff --git a/frontend/components/screen/InteractiveScreenViewerDynamic.tsx b/frontend/components/screen/InteractiveScreenViewerDynamic.tsx index c3e09f2e..882dfd70 100644 --- a/frontend/components/screen/InteractiveScreenViewerDynamic.tsx +++ b/frontend/components/screen/InteractiveScreenViewerDynamic.tsx @@ -615,7 +615,7 @@ export const InteractiveScreenViewerDynamic: React.FC = ({ const isFlowWidget = type === "flow" || (type === "component" && (component as any).componentConfig?.type === "flow-widget"); // 높이 결정 로직 - let finalHeight = size?.height || 40; + let finalHeight = size?.height || 10; if (isFlowWidget && actualHeight) { finalHeight = actualHeight; } diff --git a/frontend/components/screen/RealtimePreviewDynamic.tsx b/frontend/components/screen/RealtimePreviewDynamic.tsx index 1f11182f..af733601 100644 --- a/frontend/components/screen/RealtimePreviewDynamic.tsx +++ b/frontend/components/screen/RealtimePreviewDynamic.tsx @@ -271,7 +271,8 @@ export const RealtimePreviewDynamic: React.FC = ({ return `${Math.max(size?.height || 200, 200)}px`; } - return `${size?.height || 40}px`; + // size.height가 있으면 그대로 사용, 없으면 최소 10px + return `${size?.height || 10}px`; }; const baseStyle = { diff --git a/frontend/components/screen/panels/UnifiedPropertiesPanel.tsx b/frontend/components/screen/panels/UnifiedPropertiesPanel.tsx index f2e50db8..cc06b555 100644 --- a/frontend/components/screen/panels/UnifiedPropertiesPanel.tsx +++ b/frontend/components/screen/panels/UnifiedPropertiesPanel.tsx @@ -364,14 +364,13 @@ export const UnifiedPropertiesPanel: React.FC = ({ value={selectedComponent.size?.height || 0} onChange={(e) => { const value = parseInt(e.target.value) || 0; - const roundedValue = Math.max(10, Math.round(value / 10) * 10); - handleUpdate("size.height", roundedValue); + // 최소값 제한 없이, 1px 단위로 조절 가능 + handleUpdate("size.height", Math.max(1, value)); }} - step={10} + step={1} placeholder="10" className="h-6 w-full px-2 py-0 text-xs" style={{ fontSize: "12px" }} - style={{ fontSize: "12px" }} />
diff --git a/frontend/components/screen/widgets/CategoryWidget.tsx b/frontend/components/screen/widgets/CategoryWidget.tsx new file mode 100644 index 00000000..685340b5 --- /dev/null +++ b/frontend/components/screen/widgets/CategoryWidget.tsx @@ -0,0 +1,81 @@ +"use client"; + +import React, { useState } from "react"; +import { CategoryColumnList } from "@/components/table-category/CategoryColumnList"; +import { CategoryValueManager } from "@/components/table-category/CategoryValueManager"; + +interface CategoryWidgetProps { + widgetId: string; + menuId?: number; // 현재 화면의 menuId (선택사항) + tableName: string; // 현재 화면의 테이블 + selectedScreen?: any; // 화면 정보 전체 (menuId 추출용) +} + +/** + * 카테고리 관리 위젯 (좌우 분할) + * - 좌측: 현재 테이블의 카테고리 타입 컬럼 목록 + * - 우측: 선택된 컬럼의 카테고리 값 관리 + */ +export function CategoryWidget({ + widgetId, + menuId: propMenuId, + tableName, + selectedScreen, +}: CategoryWidgetProps) { + const [selectedColumn, setSelectedColumn] = useState<{ + columnName: string; + columnLabel: string; + } | null>(null); + + // menuId 추출: props > selectedScreen > 기본값(1) + const menuId = + propMenuId || + selectedScreen?.menuId || + selectedScreen?.menu_id || + 1; // 기본값 + + // menuId가 없으면 경고 메시지 표시 + if (!menuId || menuId === 1) { + console.warn("⚠️ CategoryWidget: menuId가 제공되지 않아 기본값(1)을 사용합니다", { + propMenuId, + selectedScreen, + }); + } + + return ( +
+ {/* 좌측: 카테고리 컬럼 리스트 (30%) */} +
+ + setSelectedColumn({ columnName, columnLabel }) + } + /> +
+ + {/* 우측: 카테고리 값 관리 (70%) */} +
+ {selectedColumn ? ( + + ) : ( +
+
+

+ 좌측에서 관리할 카테고리 컬럼을 선택하세요 +

+
+
+ )} +
+
+ ); +} + diff --git a/frontend/components/screen/widgets/types/ButtonWidget.tsx b/frontend/components/screen/widgets/types/ButtonWidget.tsx index 6bc9e1ff..808cf5d0 100644 --- a/frontend/components/screen/widgets/types/ButtonWidget.tsx +++ b/frontend/components/screen/widgets/types/ButtonWidget.tsx @@ -30,7 +30,7 @@ export const ButtonWidget: React.FC = ({ type="button" onClick={handleClick} disabled={disabled || readonly} - className={`rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white transition-colors duration-200 hover:bg-blue-700 focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:outline-none disabled:cursor-not-allowed disabled:bg-gray-300 disabled:text-gray-500 ${className || ""} `} + className={`flex items-center justify-center rounded-md bg-blue-600 px-4 text-sm font-medium text-white transition-colors duration-200 hover:bg-blue-700 focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:outline-none disabled:cursor-not-allowed disabled:bg-gray-300 disabled:text-gray-500 ${className || ""} `} style={{ ...style, width: "100%", diff --git a/frontend/components/table-category/CategoryColumnList.tsx b/frontend/components/table-category/CategoryColumnList.tsx new file mode 100644 index 00000000..3cc8cb11 --- /dev/null +++ b/frontend/components/table-category/CategoryColumnList.tsx @@ -0,0 +1,187 @@ +"use client"; + +import React, { useState, useEffect } from "react"; +import { apiClient } from "@/lib/api/client"; +import { FolderTree, Loader2 } from "lucide-react"; + +interface CategoryColumn { + columnName: string; + columnLabel: string; + inputType: string; +} + +interface CategoryColumnListProps { + tableName: string; + menuId: number; + selectedColumn: string | null; + onColumnSelect: (columnName: string, columnLabel: string) => void; +} + +/** + * 카테고리 컬럼 목록 (좌측 패널) + * - 현재 테이블에서 input_type='category'인 컬럼들을 표시 + */ +export function CategoryColumnList({ + tableName, + menuId, + selectedColumn, + onColumnSelect, +}: CategoryColumnListProps) { + const [columns, setColumns] = useState([]); + const [isLoading, setIsLoading] = useState(false); + + useEffect(() => { + loadCategoryColumns(); + }, [tableName, menuId]); + + const loadCategoryColumns = async () => { + setIsLoading(true); + try { + // table_type_columns에서 input_type = 'category'인 컬럼 조회 + const response = await apiClient.get( + `/table-management/tables/${tableName}/columns` + ); + + console.log("🔍 테이블 컬럼 API 응답:", { + tableName, + response: response.data, + type: typeof response.data, + isArray: Array.isArray(response.data), + }); + + // API 응답 구조 파싱 (여러 가능성 대응) + let allColumns: any[] = []; + + if (Array.isArray(response.data)) { + // response.data가 직접 배열인 경우 + allColumns = response.data; + } else if (response.data.data && response.data.data.columns && Array.isArray(response.data.data.columns)) { + // response.data.data.columns가 배열인 경우 (table-management API) + allColumns = response.data.data.columns; + } else if (response.data.data && Array.isArray(response.data.data)) { + // response.data.data가 배열인 경우 + allColumns = response.data.data; + } else if (response.data.columns && Array.isArray(response.data.columns)) { + // response.data.columns가 배열인 경우 + allColumns = response.data.columns; + } else { + console.warn("⚠️ 예상하지 못한 API 응답 구조:", response.data); + allColumns = []; + } + + console.log("🔍 파싱된 컬럼 목록:", { + totalColumns: allColumns.length, + sample: allColumns.slice(0, 3), + }); + + // category 타입만 필터링 + const categoryColumns = allColumns.filter( + (col: any) => col.inputType === "category" || col.input_type === "category" + ); + + console.log("✅ 카테고리 컬럼:", { + count: categoryColumns.length, + columns: categoryColumns.map((c: any) => ({ + name: c.columnName || c.column_name, + type: c.inputType || c.input_type, + })), + }); + + setColumns( + categoryColumns.map((col: any) => ({ + columnName: col.columnName || col.column_name, + columnLabel: col.columnLabel || col.column_label || col.displayName || col.columnName || col.column_name, + inputType: col.inputType || col.input_type, + })) + ); + + // 첫 번째 컬럼 자동 선택 + if (categoryColumns.length > 0 && !selectedColumn) { + const firstCol = categoryColumns[0]; + const colName = firstCol.columnName || firstCol.column_name; + const colLabel = firstCol.columnLabel || firstCol.column_label || firstCol.displayName || colName; + onColumnSelect(colName, colLabel); + } + } catch (error) { + console.error("❌ 카테고리 컬럼 조회 실패:", error); + setColumns([]); + } finally { + setIsLoading(false); + } + }; + + if (isLoading) { + return ( +
+ +
+ ); + } + + if (columns.length === 0) { + return ( +
+

카테고리 컬럼

+
+ +

+ 카테고리 타입 컬럼이 없습니다 +

+

+ 테이블 타입 관리에서 컬럼의 입력 타입을 '카테고리'로 + 설정하세요 +

+
+
+ ); + } + + return ( +
+
+

카테고리 컬럼

+

+ 관리할 카테고리 컬럼을 선택하세요 +

+
+ +
+ {columns.map((column) => ( +
+ onColumnSelect( + column.columnName, + column.columnLabel || column.columnName + ) + } + className={`cursor-pointer rounded-lg border p-4 transition-all ${ + selectedColumn === column.columnName + ? "border-primary bg-primary/10 shadow-sm" + : "hover:bg-muted/50" + }`} + > +
+ +
+

+ {column.columnLabel || column.columnName} +

+

+ {column.columnName} +

+
+
+
+ ))} +
+
+ ); +} + diff --git a/frontend/components/table-category/CategoryValueAddDialog.tsx b/frontend/components/table-category/CategoryValueAddDialog.tsx new file mode 100644 index 00000000..b511ae7a --- /dev/null +++ b/frontend/components/table-category/CategoryValueAddDialog.tsx @@ -0,0 +1,170 @@ +"use client"; + +import React, { useState } from "react"; +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogFooter, + DialogDescription, +} from "@/components/ui/dialog"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Textarea } from "@/components/ui/textarea"; +import { Checkbox } from "@/components/ui/checkbox"; +import { TableCategoryValue } from "@/types/tableCategoryValue"; + +interface CategoryValueAddDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + onAdd: (value: TableCategoryValue) => void; + columnLabel: string; +} + +export const CategoryValueAddDialog: React.FC< + CategoryValueAddDialogProps +> = ({ open, onOpenChange, onAdd, columnLabel }) => { + const [valueCode, setValueCode] = useState(""); + const [valueLabel, setValueLabel] = useState(""); + const [description, setDescription] = useState(""); + const [color, setColor] = useState("#3b82f6"); + const [isDefault, setIsDefault] = useState(false); + + const handleSubmit = () => { + if (!valueCode || !valueLabel) { + return; + } + + onAdd({ + tableName: "", + columnName: "", + valueCode: valueCode.toUpperCase(), + valueLabel, + description, + color, + isDefault, + }); + + // 초기화 + setValueCode(""); + setValueLabel(""); + setDescription(""); + setColor("#3b82f6"); + setIsDefault(false); + }; + + return ( + + + + + 새 카테고리 값 추가 + + + {columnLabel}에 새로운 값을 추가합니다 + + + +
+
+ + setValueCode(e.target.value.toUpperCase())} + className="h-8 text-xs sm:h-10 sm:text-sm" + /> +

+ 영문 대문자와 언더스코어만 사용 (DB 저장값) +

+
+ +
+ + setValueLabel(e.target.value)} + className="h-8 text-xs sm:h-10 sm:text-sm" + /> +

+ 사용자에게 표시될 이름 +

+
+ +
+ +