From c5b065ac81bcb2b4b4d16e55be1df623aee4bbc8 Mon Sep 17 00:00:00 2001 From: kjs Date: Mon, 10 Nov 2025 18:38:56 +0900 Subject: [PATCH 01/13] =?UTF-8?q?=EB=A6=AC=EC=8A=A4=ED=8A=B8=20=EC=8A=A4?= =?UTF-8?q?=ED=81=AC=EB=A1=A4=20=EC=A0=9C=EA=B1=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lib/registry/components/table-list/TableListComponent.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/lib/registry/components/table-list/TableListComponent.tsx b/frontend/lib/registry/components/table-list/TableListComponent.tsx index 6e03a9d0..795c5bbb 100644 --- a/frontend/lib/registry/components/table-list/TableListComponent.tsx +++ b/frontend/lib/registry/components/table-list/TableListComponent.tsx @@ -1992,7 +1992,7 @@ export const TableListComponent: React.FC = ({ > {/* 스크롤 영역 */}
{/* 테이블 */} -- 2.43.0 From bab960b50ee5582768fca4b3d921e0264f0118e2 Mon Sep 17 00:00:00 2001 From: kjs Date: Tue, 11 Nov 2025 10:29:47 +0900 Subject: [PATCH 02/13] =?UTF-8?q?feat:=20=EC=97=91=EC=85=80=20=EB=8B=A4?= =?UTF-8?q?=EC=9A=B4=EB=A1=9C=EB=93=9C=20=ED=8C=8C=EC=9D=BC=EB=AA=85?= =?UTF-8?q?=EC=9D=84=20=EB=A9=94=EB=89=B4=20=EC=9D=B4=EB=A6=84=EC=9C=BC?= =?UTF-8?q?=EB=A1=9C=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 메뉴 클릭 시 localStorage에 메뉴 이름 저장 (useMenu, AppLayout) - 엑셀 다운로드 시 localStorage의 메뉴 이름을 파일명으로 사용 - 백엔드 카테고리 컬럼 조회 쿼리 파라미터 버그 수정 - API 호출 시 불필요한 autoFilter 파라미터 제거 파일명 형식: {메뉴이름}_{날짜}.xlsx 예시: 품목등록테스트_2025-11-11.xlsx --- .../src/services/tableCategoryValueService.ts | 4 +++- frontend/components/layout/AppLayout.tsx | 6 ++++++ frontend/hooks/useMenu.ts | 6 ++++++ frontend/lib/utils/buttonActions.ts | 16 +++++++++++++--- 4 files changed, 28 insertions(+), 4 deletions(-) diff --git a/backend-node/src/services/tableCategoryValueService.ts b/backend-node/src/services/tableCategoryValueService.ts index 8a20aac1..7646dead 100644 --- a/backend-node/src/services/tableCategoryValueService.ts +++ b/backend-node/src/services/tableCategoryValueService.ts @@ -62,7 +62,9 @@ class TableCategoryValueService { logger.info("회사별 카테고리 컬럼 조회", { companyCode }); } - const result = await pool.query(query, [tableName, companyCode]); + // 쿼리 파라미터는 company_code에 따라 다름 + const params = companyCode === "*" ? [tableName] : [tableName, companyCode]; + const result = await pool.query(query, params); logger.info(`카테고리 컬럼 ${result.rows.length}개 조회 완료`, { tableName, diff --git a/frontend/components/layout/AppLayout.tsx b/frontend/components/layout/AppLayout.tsx index 1ad00044..51c070cd 100644 --- a/frontend/components/layout/AppLayout.tsx +++ b/frontend/components/layout/AppLayout.tsx @@ -259,6 +259,12 @@ function AppLayoutInner({ children }: AppLayoutProps) { if (menu.hasChildren) { toggleMenu(menu.id); } else { + // 메뉴 이름 저장 (엑셀 다운로드 파일명에 사용) + const menuName = menu.label || menu.name || "메뉴"; + if (typeof window !== "undefined") { + localStorage.setItem("currentMenuName", menuName); + } + // 먼저 할당된 화면이 있는지 확인 (URL 유무와 관계없이) try { const menuObjid = menu.objid || menu.id; diff --git a/frontend/hooks/useMenu.ts b/frontend/hooks/useMenu.ts index bab8a68f..48c93ce7 100644 --- a/frontend/hooks/useMenu.ts +++ b/frontend/hooks/useMenu.ts @@ -160,6 +160,12 @@ export const useMenu = (user: any, authLoading: boolean) => { if (menu.children && menu.children.length > 0) { toggleMenu(String(menu.OBJID)); } else { + // 메뉴 이름 저장 (엑셀 다운로드 파일명에 사용) + const menuName = menu.MENU_NAME_KOR || menu.menuNameKor || menu.TRANSLATED_NAME || "메뉴"; + if (typeof window !== "undefined") { + localStorage.setItem("currentMenuName", menuName); + } + // 먼저 할당된 화면이 있는지 확인 (URL 유무와 관계없이) try { const menuObjid = menu.OBJID || menu.objid; diff --git a/frontend/lib/utils/buttonActions.ts b/frontend/lib/utils/buttonActions.ts index 6f6a8f4d..ef3b3747 100644 --- a/frontend/lib/utils/buttonActions.ts +++ b/frontend/lib/utils/buttonActions.ts @@ -1970,7 +1970,7 @@ export class ButtonActionExecutor { sortOrder: (context.sortOrder || storedData?.sortOrder || "asc") as "asc" | "desc", search: filterConditions, // ✅ 필터 조건 enableEntityJoin: true, // ✅ Entity 조인 - autoFilter: true, // ✅ company_code 자동 필터링 (멀티테넌시) + // autoFilter는 entityJoinApi.getTableDataWithJoins 내부에서 자동으로 적용됨 }; // 🔒 멀티테넌시 준수: autoFilter로 company_code 자동 적용 @@ -2027,8 +2027,18 @@ export class ButtonActionExecutor { return false; } - // 파일명 생성 - const fileName = config.excelFileName || `${context.tableName || "데이터"}_${new Date().toISOString().split("T")[0]}.xlsx`; + // 파일명 생성 (메뉴 이름 우선 사용) + let defaultFileName = context.tableName || "데이터"; + + // localStorage에서 메뉴 이름 가져오기 + if (typeof window !== "undefined") { + const menuName = localStorage.getItem("currentMenuName"); + if (menuName) { + defaultFileName = menuName; + } + } + + const fileName = config.excelFileName || `${defaultFileName}_${new Date().toISOString().split("T")[0]}.xlsx`; const sheetName = config.excelSheetName || "Sheet1"; const includeHeaders = config.excelIncludeHeaders !== false; -- 2.43.0 From 532c80a86b4fff84a1a65487c6e831c5ed5e3b8a Mon Sep 17 00:00:00 2001 From: kjs Date: Tue, 11 Nov 2025 11:37:26 +0900 Subject: [PATCH 03/13] =?UTF-8?q?=EB=B6=84=ED=95=A0=ED=8C=A8=EB=84=90=20?= =?UTF-8?q?=ED=85=8C=EC=9D=B4=EB=B8=94=20=EB=A6=AC=EC=8A=A4=ED=8A=B8=20?= =?UTF-8?q?=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../SplitPanelLayoutComponent.tsx | 329 +++++- .../SplitPanelLayoutConfigPanel.tsx | 429 ++++++-- .../components/split-panel-layout/types.ts | 29 + 카테고리_메뉴기반_전환_계획서.md | 977 ++++++++++++++++++ 4 files changed, 1662 insertions(+), 102 deletions(-) create mode 100644 카테고리_메뉴기반_전환_계획서.md diff --git a/frontend/lib/registry/components/split-panel-layout/SplitPanelLayoutComponent.tsx b/frontend/lib/registry/components/split-panel-layout/SplitPanelLayoutComponent.tsx index dbb99963..60936930 100644 --- a/frontend/lib/registry/components/split-panel-layout/SplitPanelLayoutComponent.tsx +++ b/frontend/lib/registry/components/split-panel-layout/SplitPanelLayoutComponent.tsx @@ -48,6 +48,8 @@ export const SplitPanelLayoutComponent: React.FC const [isLoadingRight, setIsLoadingRight] = useState(false); const [rightTableColumns, setRightTableColumns] = useState([]); // 우측 테이블 컬럼 정보 const [expandedItems, setExpandedItems] = useState>(new Set()); // 펼쳐진 항목들 + const [leftColumnLabels, setLeftColumnLabels] = useState>({}); // 좌측 컬럼 라벨 + const [rightColumnLabels, setRightColumnLabels] = useState>({}); // 우측 컬럼 라벨 const { toast } = useToast(); // 추가 모달 상태 @@ -270,6 +272,32 @@ export const SplitPanelLayoutComponent: React.FC [rightTableColumns], ); + // 좌측 테이블 컬럼 라벨 로드 + useEffect(() => { + const loadLeftColumnLabels = async () => { + const leftTableName = componentConfig.leftPanel?.tableName; + if (!leftTableName || isDesignMode) return; + + try { + const columnsResponse = await tableTypeApi.getColumns(leftTableName); + const labels: Record = {}; + columnsResponse.forEach((col: any) => { + const columnName = col.columnName || col.column_name; + const label = col.columnLabel || col.column_label || col.displayName || columnName; + if (columnName) { + labels[columnName] = label; + } + }); + setLeftColumnLabels(labels); + console.log("✅ 좌측 컬럼 라벨 로드:", labels); + } catch (error) { + console.error("좌측 테이블 컬럼 라벨 로드 실패:", error); + } + }; + + loadLeftColumnLabels(); + }, [componentConfig.leftPanel?.tableName, isDesignMode]); + // 우측 테이블 컬럼 정보 로드 useEffect(() => { const loadRightTableColumns = async () => { @@ -279,6 +307,18 @@ export const SplitPanelLayoutComponent: React.FC try { const columnsResponse = await tableTypeApi.getColumns(rightTableName); setRightTableColumns(columnsResponse || []); + + // 우측 컬럼 라벨도 함께 로드 + const labels: Record = {}; + columnsResponse.forEach((col: any) => { + const columnName = col.columnName || col.column_name; + const label = col.columnLabel || col.column_label || col.displayName || columnName; + if (columnName) { + labels[columnName] = label; + } + }); + setRightColumnLabels(labels); + console.log("✅ 우측 컬럼 라벨 로드:", labels); } catch (error) { console.error("우측 테이블 컬럼 정보 로드 실패:", error); } @@ -784,46 +824,157 @@ export const SplitPanelLayoutComponent: React.FC )} - {/* 좌측 데이터 목록 */} -
- {isDesignMode ? ( - // 디자인 모드: 샘플 데이터 - <> -
handleLeftItemSelect({ id: 1, name: "항목 1" })} - className={`hover:bg-accent cursor-pointer rounded-md p-3 transition-colors ${ - selectedLeftItem?.id === 1 ? "bg-primary/10 text-primary" : "" - }`} - > -
항목 1
-
설명 텍스트
+ {/* 좌측 데이터 목록/테이블 */} + {componentConfig.leftPanel?.displayMode === "table" ? ( + // 테이블 모드 +
+ {isDesignMode ? ( + // 디자인 모드: 샘플 테이블 +
+ + + + + + + + + + + + + + + + + + + + +
컬럼 1컬럼 2컬럼 3
데이터 1-1데이터 1-2데이터 1-3
데이터 2-1데이터 2-2데이터 2-3
-
handleLeftItemSelect({ id: 2, name: "항목 2" })} - className={`hover:bg-accent cursor-pointer rounded-md p-3 transition-colors ${ - selectedLeftItem?.id === 2 ? "bg-primary/10 text-primary" : "" - }`} - > -
항목 2
-
설명 텍스트
+ ) : isLoadingLeft ? ( +
+ + 데이터를 불러오는 중...
-
handleLeftItemSelect({ id: 3, name: "항목 3" })} - className={`hover:bg-accent cursor-pointer rounded-md p-3 transition-colors ${ - selectedLeftItem?.id === 3 ? "bg-primary/10 text-primary" : "" - }`} - > -
항목 3
-
설명 텍스트
+ ) : ( + (() => { + const filteredData = leftSearchQuery + ? leftData.filter((item) => { + const searchLower = leftSearchQuery.toLowerCase(); + return Object.entries(item).some(([key, value]) => { + if (value === null || value === undefined) return false; + return String(value).toLowerCase().includes(searchLower); + }); + }) + : leftData; + + const displayColumns = componentConfig.leftPanel?.columns || []; + const columnsToShow = displayColumns.length > 0 + ? displayColumns.map(col => ({ + ...col, + label: leftColumnLabels[col.name] || col.label || col.name + })) + : Object.keys(filteredData[0] || {}).filter(key => key !== 'children' && key !== 'level').slice(0, 5).map(key => ({ + name: key, + label: leftColumnLabels[key] || key, + width: 150, + align: "left" as const + })); + + return ( +
+ + + + {columnsToShow.map((col, idx) => ( + + ))} + + + + {filteredData.map((item, idx) => { + const sourceColumn = componentConfig.leftPanel?.itemAddConfig?.sourceColumn || 'id'; + const itemId = item[sourceColumn] || item.id || item.ID || idx; + const isSelected = selectedLeftItem && (selectedLeftItem[sourceColumn] === itemId || selectedLeftItem === item); + + return ( + handleLeftItemSelect(item)} + className={`hover:bg-accent cursor-pointer transition-colors ${ + isSelected ? "bg-primary/10" : "" + }`} + > + {columnsToShow.map((col, colIdx) => ( + + ))} + + ); + })} + +
+ {col.label} +
+ {item[col.name] !== null && item[col.name] !== undefined + ? String(item[col.name]) + : "-"} +
+
+ ); + })() + )} +
+ ) : ( + // 목록 모드 (기존) +
+ {isDesignMode ? ( + // 디자인 모드: 샘플 데이터 + <> +
handleLeftItemSelect({ id: 1, name: "항목 1" })} + className={`hover:bg-accent cursor-pointer rounded-md p-3 transition-colors ${ + selectedLeftItem?.id === 1 ? "bg-primary/10 text-primary" : "" + }`} + > +
항목 1
+
설명 텍스트
+
+
handleLeftItemSelect({ id: 2, name: "항목 2" })} + className={`hover:bg-accent cursor-pointer rounded-md p-3 transition-colors ${ + selectedLeftItem?.id === 2 ? "bg-primary/10 text-primary" : "" + }`} + > +
항목 2
+
설명 텍스트
+
+
handleLeftItemSelect({ id: 3, name: "항목 3" })} + className={`hover:bg-accent cursor-pointer rounded-md p-3 transition-colors ${ + selectedLeftItem?.id === 3 ? "bg-primary/10 text-primary" : "" + }`} + > +
항목 3
+
설명 텍스트
+
+ + ) : isLoadingLeft ? ( + // 로딩 중 +
+ + 데이터를 불러오는 중...
- - ) : isLoadingLeft ? ( - // 로딩 중 -
- - 데이터를 불러오는 중... -
- ) : ( + ) : ( (() => { // 검색 필터링 (클라이언트 사이드) const filteredLeftData = leftSearchQuery @@ -1001,7 +1152,8 @@ export const SplitPanelLayoutComponent: React.FC ); })() )} -
+
+ )}
@@ -1081,6 +1233,107 @@ export const SplitPanelLayoutComponent: React.FC }) : rightData; + // 테이블 모드 체크 + const isTableMode = componentConfig.rightPanel?.displayMode === "table"; + + if (isTableMode) { + // 테이블 모드 렌더링 + const displayColumns = componentConfig.rightPanel?.columns || []; + const columnsToShow = displayColumns.length > 0 + ? displayColumns.map(col => ({ + ...col, + label: rightColumnLabels[col.name] || col.label || col.name + })) + : Object.keys(filteredData[0] || {}).filter(key => !key.toLowerCase().includes("password")).slice(0, 5).map(key => ({ + name: key, + label: rightColumnLabels[key] || key, + width: 150, + align: "left" as const + })); + + return ( +
+
+ {filteredData.length}개의 관련 데이터 + {rightSearchQuery && filteredData.length !== rightData.length && ( + (전체 {rightData.length}개 중) + )} +
+
+ + + + {columnsToShow.map((col, idx) => ( + + ))} + {!isDesignMode && ( + + )} + + + + {filteredData.map((item, idx) => { + const itemId = item.id || item.ID || idx; + + return ( + + {columnsToShow.map((col, colIdx) => ( + + ))} + {!isDesignMode && ( + + )} + + ); + })} + +
+ {col.label} + 작업
+ {item[col.name] !== null && item[col.name] !== undefined + ? String(item[col.name]) + : "-"} + +
+ + +
+
+
+
+ ); + } + + // 목록 모드 (기존) return filteredData.length > 0 ? (
diff --git a/frontend/lib/registry/components/split-panel-layout/SplitPanelLayoutConfigPanel.tsx b/frontend/lib/registry/components/split-panel-layout/SplitPanelLayoutConfigPanel.tsx index 35e711fa..0b37ee26 100644 --- a/frontend/lib/registry/components/split-panel-layout/SplitPanelLayoutConfigPanel.tsx +++ b/frontend/lib/registry/components/split-panel-layout/SplitPanelLayoutConfigPanel.tsx @@ -353,6 +353,32 @@ export const SplitPanelLayoutConfigPanel: React.FC
+
+ + +
+
)} + {/* 좌측 패널 표시 컬럼 설정 */} +
+
+ + +
+

+ 좌측 패널에 표시할 컬럼을 선택하세요. 선택하지 않으면 모든 컬럼이 표시됩니다. +

+ + {/* 선택된 컬럼 목록 */} +
+ {(config.leftPanel?.columns || []).length === 0 ? ( +
+

설정된 컬럼이 없습니다

+

+ 컬럼을 추가하지 않으면 모든 컬럼이 표시됩니다 +

+
+ ) : ( + (config.leftPanel?.columns || []).map((col, index) => { + const isTableMode = config.leftPanel?.displayMode === "table"; + + return ( +
+
+
+ + + + + + + + 컬럼을 찾을 수 없습니다. + + {leftTableColumns.map((column) => ( + { + const newColumns = [...(config.leftPanel?.columns || [])]; + newColumns[index] = { + ...newColumns[index], + name: value, + label: column.columnLabel || value, + }; + updateLeftPanel({ columns: newColumns }); + }} + className="text-xs" + > + + {column.columnLabel || column.columnName} + + ({column.columnName}) + + + ))} + + + + +
+ +
+ + {/* 테이블 모드 전용 옵션 */} + {isTableMode && ( +
+
+ + { + const newColumns = [...(config.leftPanel?.columns || [])]; + newColumns[index] = { + ...newColumns[index], + width: parseInt(e.target.value) || 100, + }; + updateLeftPanel({ columns: newColumns }); + }} + className="h-7 text-xs" + /> +
+
+ + +
+
+ +
+
+ )} +
+ ); + }) + )} +
+
+ {/* 좌측 패널 추가 모달 컬럼 설정 */} {config.leftPanel?.showAdd && (
@@ -895,6 +1100,32 @@ export const SplitPanelLayoutConfigPanel: React.FC )} +
+ + +
+ {/* 컬럼 매핑 - 조인 모드에서만 표시 */} {relationshipType !== "detail" && (
@@ -1057,75 +1288,145 @@ export const SplitPanelLayoutConfigPanel: React.FC
) : ( - (config.rightPanel?.columns || []).map((col, index) => ( + (config.rightPanel?.columns || []).map((col, index) => { + const isTableMode = config.rightPanel?.displayMode === "table"; + + return (
-
- - - - - - - - 컬럼을 찾을 수 없습니다. - - {rightTableColumns.map((column) => ( - { - const newColumns = [...(config.rightPanel?.columns || [])]; - newColumns[index] = { - ...newColumns[index], - name: value, - label: column.columnLabel || value, - }; - updateRightPanel({ columns: newColumns }); - }} - className="text-xs" - > - - {column.columnLabel || column.columnName} - - ({column.columnName}) - - - ))} - - - - +
+
+ + + + + + + + 컬럼을 찾을 수 없습니다. + + {rightTableColumns.map((column) => ( + { + const newColumns = [...(config.rightPanel?.columns || [])]; + newColumns[index] = { + ...newColumns[index], + name: value, + label: column.columnLabel || value, + }; + updateRightPanel({ columns: newColumns }); + }} + className="text-xs" + > + + {column.columnLabel || column.columnName} + + ({column.columnName}) + + + ))} + + + + +
+
- + + {/* 테이블 모드 전용 옵션 */} + {isTableMode && ( +
+
+ + { + const newColumns = [...(config.rightPanel?.columns || [])]; + newColumns[index] = { + ...newColumns[index], + width: parseInt(e.target.value) || 100, + }; + updateRightPanel({ columns: newColumns }); + }} + className="h-7 text-xs" + /> +
+
+ + +
+
+ +
+
+ )}
- )) + ); + }) )}
diff --git a/frontend/lib/registry/components/split-panel-layout/types.ts b/frontend/lib/registry/components/split-panel-layout/types.ts index df43221a..6f6421e5 100644 --- a/frontend/lib/registry/components/split-panel-layout/types.ts +++ b/frontend/lib/registry/components/split-panel-layout/types.ts @@ -8,6 +8,7 @@ export interface SplitPanelLayoutConfig { title: string; tableName?: string; // 데이터베이스 테이블명 dataSource?: string; // API 엔드포인트 + displayMode?: "list" | "table"; // 표시 모드: 목록 또는 테이블 showSearch?: boolean; showAdd?: boolean; showEdit?: boolean; // 수정 버튼 @@ -16,6 +17,8 @@ export interface SplitPanelLayoutConfig { name: string; label: string; width?: number; + sortable?: boolean; // 정렬 가능 여부 (테이블 모드) + align?: "left" | "center" | "right"; // 정렬 (테이블 모드) }>; // 추가 모달에서 입력받을 컬럼 설정 addModalColumns?: Array<{ @@ -38,6 +41,17 @@ export interface SplitPanelLayoutConfig { // 현재 항목의 어떤 컬럼 값을 parentColumn에 넣을지 (예: dept_code) sourceColumn: string; }; + // 테이블 모드 설정 + tableConfig?: { + showCheckbox?: boolean; // 체크박스 표시 여부 + showRowNumber?: boolean; // 행 번호 표시 여부 + rowHeight?: number; // 행 높이 + headerHeight?: number; // 헤더 높이 + striped?: boolean; // 줄무늬 배경 + bordered?: boolean; // 테두리 표시 + hoverable?: boolean; // 호버 효과 + stickyHeader?: boolean; // 헤더 고정 + }; }; // 우측 패널 설정 @@ -45,6 +59,7 @@ export interface SplitPanelLayoutConfig { title: string; tableName?: string; dataSource?: string; + displayMode?: "list" | "table"; // 표시 모드: 목록 또는 테이블 showSearch?: boolean; showAdd?: boolean; showEdit?: boolean; // 수정 버튼 @@ -53,6 +68,8 @@ export interface SplitPanelLayoutConfig { name: string; label: string; width?: number; + sortable?: boolean; // 정렬 가능 여부 (테이블 모드) + align?: "left" | "center" | "right"; // 정렬 (테이블 모드) }>; // 추가 모달에서 입력받을 컬럼 설정 addModalColumns?: Array<{ @@ -76,6 +93,18 @@ export interface SplitPanelLayoutConfig { leftPanelColumn?: string; // 좌측 패널의 어떤 컬럼값을 가져올지 targetColumn?: string; // targetTable의 어떤 컬럼에 넣을지 }; + + // 테이블 모드 설정 + tableConfig?: { + showCheckbox?: boolean; // 체크박스 표시 여부 + showRowNumber?: boolean; // 행 번호 표시 여부 + rowHeight?: number; // 행 높이 + headerHeight?: number; // 헤더 높이 + striped?: boolean; // 줄무늬 배경 + bordered?: boolean; // 테두리 표시 + hoverable?: boolean; // 호버 효과 + stickyHeader?: boolean; // 헤더 고정 + }; }; // 레이아웃 설정 diff --git a/카테고리_메뉴기반_전환_계획서.md b/카테고리_메뉴기반_전환_계획서.md new file mode 100644 index 00000000..ddc5b023 --- /dev/null +++ b/카테고리_메뉴기반_전환_계획서.md @@ -0,0 +1,977 @@ +# 카테고리 컴포넌트 메뉴 기반 전환 계획서 + +## 📋 현재 문제점 + +### 테이블 기반 스코프의 한계 + +**현재 상황**: + +- 카테고리와 채번 컴포넌트가 **테이블 기준**으로 데이터를 불러옴 +- `table_column_category_values` 테이블에서 `table_name + column_name`으로 카테고리 조회 + +**문제 발생**: + +``` +영업관리 (menu_id: 200) +├── 고객관리 (menu_id: 201) - 테이블: customer_info +├── 계약관리 (menu_id: 202) - 테이블: contract_info +├── 주문관리 (menu_id: 203) - 테이블: order_info +└── 영업관리 공통코드 (menu_id: 204) - 어떤 테이블 선택? +``` + +**문제**: + +- 영업관리 전체에서 사용할 공통 코드/카테고리를 관리하고 싶은데 +- 각 하위 메뉴가 서로 다른 테이블을 사용하므로 +- 특정 테이블 하나를 선택하면 다른 메뉴에서 사용할 수 없음 + +### 예시: 영업관리 공통 코드 관리 불가 + +**원하는 동작**: + +- "영업관리 > 공통코드 관리" 메뉴에서 카테고리 생성 +- 이 카테고리는 영업관리의 **모든 하위 메뉴**에서 사용 가능 +- 고객관리, 계약관리, 주문관리 화면 모두에서 같은 카테고리 공유 + +**현재 동작**: + +- 테이블별로 카테고리가 격리됨 +- `customer_info` 테이블의 카테고리는 `contract_info`에서 사용 불가 +- 각 테이블마다 동일한 카테고리를 중복 생성해야 함 (비효율) + +--- + +## ✅ 해결 방안: 메뉴 기반 스코프 + +### 핵심 개념 + +**메뉴 계층 구조를 카테고리 스코프로 사용**: + +- 카테고리를 생성할 때 `menu_id`를 기록 +- 같은 부모 메뉴를 가진 **형제 메뉴들**이 카테고리를 공유 +- 테이블과 무관하게 메뉴 구조에 따라 스코프 결정 + +### 메뉴 스코프 규칙 + +``` +영업관리 (parent_id: 0, menu_id: 200) +├── 고객관리 (parent_id: 200, menu_id: 201) +├── 계약관리 (parent_id: 200, menu_id: 202) +├── 주문관리 (parent_id: 200, menu_id: 203) +└── 공통코드 관리 (parent_id: 200, menu_id: 204) ← 여기서 카테고리 생성 +``` + +**스코프 규칙**: + +- 204번 메뉴에서 카테고리 생성 → `menu_id = 204`로 저장 +- 형제 메뉴 (201, 202, 203, 204)에서 **모두 사용 가능** +- 다른 부모의 메뉴 (예: 구매관리)에서는 사용 불가 + +--- + +## 📐 데이터베이스 설계 + +### 기존 테이블 수정 + +```sql +-- table_column_category_values 테이블에 menu_id 추가 +ALTER TABLE table_column_category_values +ADD COLUMN menu_id INTEGER; + +-- 외래키 추가 +ALTER TABLE table_column_category_values +ADD CONSTRAINT fk_category_value_menu +FOREIGN KEY (menu_id) REFERENCES menu_info(menu_id); + +-- UNIQUE 제약조건 수정 (menu_id 추가) +ALTER TABLE table_column_category_values +DROP CONSTRAINT IF EXISTS unique_category_value; + +ALTER TABLE table_column_category_values +ADD CONSTRAINT unique_category_value +UNIQUE (table_name, column_name, value_code, menu_id, company_code); + +-- 인덱스 추가 +CREATE INDEX idx_category_value_menu +ON table_column_category_values(menu_id, table_name, column_name, company_code); +``` + +### 필드 설명 + +| 필드 | 설명 | 예시 | +| -------------- | ------------------------ | --------------------- | +| `table_name` | 어떤 테이블의 컬럼인지 | `customer_info` | +| `column_name` | 어떤 컬럼의 값인지 | `customer_type` | +| `menu_id` | 어느 메뉴에서 생성했는지 | `204` (공통코드 관리) | +| `company_code` | 멀티테넌시 | `COMPANY_A` | + +--- + +## 🔧 백엔드 구현 + +### 1. 메뉴 스코프 로직 추가 + +#### 형제 메뉴 조회 함수 + +```typescript +// backend-node/src/services/menuService.ts + +/** + * 메뉴의 형제 메뉴 ID 목록 조회 + * (같은 부모를 가진 메뉴들) + */ +export async function getSiblingMenuIds(menuId: number): Promise { + const pool = getPool(); + + // 1. 현재 메뉴의 부모 찾기 + const parentQuery = ` + SELECT parent_id FROM menu_info WHERE menu_id = $1 + `; + const parentResult = await pool.query(parentQuery, [menuId]); + + if (parentResult.rows.length === 0) { + return [menuId]; // 메뉴가 없으면 자기 자신만 + } + + const parentId = parentResult.rows[0].parent_id; + + if (!parentId || parentId === 0) { + // 최상위 메뉴인 경우 자기 자신만 + return [menuId]; + } + + // 2. 같은 부모를 가진 형제 메뉴들 조회 + const siblingsQuery = ` + SELECT menu_id FROM menu_info WHERE parent_id = $1 + `; + const siblingsResult = await pool.query(siblingsQuery, [parentId]); + + return siblingsResult.rows.map((row) => row.menu_id); +} +``` + +### 2. 카테고리 값 조회 API 수정 + +#### 서비스 로직 수정 + +```typescript +// backend-node/src/services/tableCategoryValueService.ts + +/** + * 카테고리 값 목록 조회 (메뉴 스코프 적용) + */ +async getCategoryValues( + tableName: string, + columnName: string, + menuId: number, // ← 추가 + companyCode: string, + includeInactive: boolean = false +): Promise { + logger.info("카테고리 값 조회 (메뉴 스코프)", { + tableName, + columnName, + menuId, + companyCode, + }); + + const pool = getPool(); + + // 1. 형제 메뉴 ID 조회 + const siblingMenuIds = await getSiblingMenuIds(menuId); + + logger.info("형제 메뉴 ID 목록", { menuId, siblingMenuIds }); + + // 2. 카테고리 값 조회 + let query: string; + let params: any[]; + + if (companyCode === "*") { + // 최고 관리자: 모든 회사 데이터 조회 + 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", + company_code AS "companyCode", + menu_id AS "menuId", + created_at AS "createdAt", + created_by AS "createdBy" + FROM table_column_category_values + WHERE table_name = $1 + AND column_name = $2 + AND menu_id = ANY($3) -- ← 형제 메뉴 포함 + ${!includeInactive ? 'AND is_active = true' : ''} + ORDER BY value_order, value_label + `; + params = [tableName, columnName, siblingMenuIds]; + } else { + // 일반 회사: 자신의 데이터만 조회 + 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", + company_code AS "companyCode", + menu_id AS "menuId", + created_at AS "createdAt", + created_by AS "createdBy" + FROM table_column_category_values + WHERE table_name = $1 + AND column_name = $2 + AND menu_id = ANY($3) -- ← 형제 메뉴 포함 + AND company_code = $4 -- ← 회사별 필터링 + ${!includeInactive ? 'AND is_active = true' : ''} + ORDER BY value_order, value_label + `; + params = [tableName, columnName, siblingMenuIds, companyCode]; + } + + const result = await pool.query(query, params); + + logger.info(`카테고리 값 ${result.rows.length}개 조회 완료`); + + return result.rows; +} +``` + +### 3. 카테고리 값 추가 API 수정 + +```typescript +/** + * 카테고리 값 추가 (menu_id 저장) + */ +async addCategoryValue( + value: TableCategoryValue, + menuId: number, // ← 추가 + companyCode: string, + userId: string +): Promise { + logger.info("카테고리 값 추가 (메뉴 스코프)", { + tableName: value.tableName, + columnName: value.columnName, + valueCode: value.valueCode, + menuId, + companyCode, + }); + + const pool = getPool(); + + const query = ` + 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, + company_code, menu_id, -- ← menu_id 추가 + 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", + company_code AS "companyCode", + menu_id AS "menuId", + created_at AS "createdAt", + created_by AS "createdBy" + `; + + const result = await pool.query(query, [ + 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, + companyCode, + menuId, // ← 카테고리 관리 화면의 menu_id + userId, + ]); + + logger.info("카테고리 값 추가 성공", { + valueId: result.rows[0].valueId, + menuId, + }); + + return result.rows[0]; +} +``` + +### 4. 컨트롤러 수정 + +```typescript +// backend-node/src/controllers/tableCategoryValueController.ts + +/** + * 카테고리 값 목록 조회 + */ +export async function getCategoryValues( + req: AuthenticatedRequest, + res: Response +): Promise { + try { + const { tableName, columnName } = req.params; + const { menuId, includeInactive } = req.query; // ← menuId 추가 + const companyCode = req.user!.companyCode; + + if (!menuId) { + res.status(400).json({ + success: false, + message: "menuId는 필수입니다", + }); + return; + } + + const service = new TableCategoryValueService(); + const values = await service.getCategoryValues( + tableName, + columnName, + Number(menuId), // ← menuId 전달 + companyCode, + includeInactive === "true" + ); + + res.json({ + success: true, + data: values, + }); + } catch (error: any) { + logger.error("카테고리 값 조회 실패:", error); + res.status(500).json({ + success: false, + message: "카테고리 값 조회 중 오류 발생", + error: error.message, + }); + } +} + +/** + * 카테고리 값 추가 + */ +export async function addCategoryValue( + req: AuthenticatedRequest, + res: Response +): Promise { + try { + const { menuId, ...value } = req.body; // ← menuId 추가 + const companyCode = req.user!.companyCode; + const userId = req.user!.userId; + + if (!menuId) { + res.status(400).json({ + success: false, + message: "menuId는 필수입니다", + }); + return; + } + + const service = new TableCategoryValueService(); + const newValue = await service.addCategoryValue( + value, + menuId, // ← menuId 전달 + companyCode, + userId + ); + + res.json({ + success: true, + data: newValue, + }); + } catch (error: any) { + logger.error("카테고리 값 추가 실패:", error); + res.status(500).json({ + success: false, + message: "카테고리 값 추가 중 오류 발생", + error: error.message, + }); + } +} +``` + +--- + +## 🎨 프론트엔드 구현 + +### 1. API 클라이언트 수정 + +```typescript +// frontend/lib/api/tableCategoryValue.ts + +/** + * 카테고리 값 목록 조회 (메뉴 스코프) + */ +export async function getCategoryValues( + tableName: string, + columnName: string, + menuId: number, // ← 추가 + includeInactive: boolean = false +) { + try { + const response = await apiClient.get<{ + success: boolean; + data: TableCategoryValue[]; + }>(`/table-categories/${tableName}/${columnName}/values`, { + params: { + menuId, // ← menuId 쿼리 파라미터 추가 + includeInactive, + }, + }); + return response.data; + } catch (error: any) { + console.error("카테고리 값 조회 실패:", error); + return { success: false, error: error.message }; + } +} + +/** + * 카테고리 값 추가 + */ +export async function addCategoryValue( + value: TableCategoryValue, + menuId: number // ← 추가 +) { + try { + const response = await apiClient.post<{ + success: boolean; + data: TableCategoryValue; + }>("/table-categories/values", { + ...value, + menuId, // ← menuId 포함 + }); + return response.data; + } catch (error: any) { + console.error("카테고리 값 추가 실패:", error); + return { success: false, error: error.message }; + } +} +``` + +### 2. CategoryColumnList 컴포넌트 수정 + +```typescript +// frontend/components/table-category/CategoryColumnList.tsx + +interface CategoryColumnListProps { + tableName: string; + menuId: number; // ← 추가 + selectedColumn: string | null; + onColumnSelect: (columnName: string, columnLabel: string) => void; +} + +export function CategoryColumnList({ + tableName, + menuId, // ← 추가 + selectedColumn, + onColumnSelect, +}: CategoryColumnListProps) { + const [columns, setColumns] = useState([]); + const [isLoading, setIsLoading] = useState(false); + + useEffect(() => { + loadCategoryColumns(); + }, [tableName, menuId]); // ← menuId 의존성 추가 + + const loadCategoryColumns = async () => { + setIsLoading(true); + try { + // table_type_columns에서 input_type='category'인 컬럼 조회 + const response = await apiClient.get( + `/table-management/tables/${tableName}/columns` + ); + + const allColumns = Array.isArray(response.data) + ? response.data + : response.data.data?.columns || []; + + // category 타입만 필터링 + const categoryColumns = allColumns.filter( + (col: any) => + col.inputType === "category" || col.input_type === "category" + ); + + const columnsWithCount = await Promise.all( + categoryColumns.map(async (col: any) => { + const colName = col.columnName || col.column_name; + const colLabel = col.columnLabel || col.column_label || colName; + + // 각 컬럼의 값 개수 가져오기 (menuId 전달) + let valueCount = 0; + try { + const valuesResult = await getCategoryValues( + tableName, + colName, + menuId, // ← menuId 전달 + false + ); + if (valuesResult.success && valuesResult.data) { + valueCount = valuesResult.data.length; + } + } catch (error) { + console.error(`항목 개수 조회 실패 (${colName}):`, error); + } + + return { + columnName: colName, + columnLabel: colLabel, + inputType: col.inputType || col.input_type, + valueCount, + }; + }) + ); + + setColumns(columnsWithCount); + + // 첫 번째 컬럼 자동 선택 + if (columnsWithCount.length > 0 && !selectedColumn) { + const firstCol = columnsWithCount[0]; + onColumnSelect(firstCol.columnName, firstCol.columnLabel); + } + } catch (error) { + console.error("❌ 카테고리 컬럼 조회 실패:", error); + setColumns([]); + } finally { + setIsLoading(false); + } + }; + + // ... 나머지 렌더링 로직 +} +``` + +### 3. CategoryValueManager 컴포넌트 수정 + +```typescript +// frontend/components/table-category/CategoryValueManager.tsx + +interface CategoryValueManagerProps { + tableName: string; + columnName: string; + menuId: number; // ← 추가 + columnLabel?: string; + onValueCountChange?: (count: number) => void; +} + +export function CategoryValueManager({ + tableName, + columnName, + menuId, // ← 추가 + columnLabel, + onValueCountChange, +}: CategoryValueManagerProps) { + const [values, setValues] = useState([]); + const [isLoading, setIsLoading] = useState(false); + + useEffect(() => { + loadCategoryValues(); + }, [tableName, columnName, menuId]); // ← menuId 의존성 추가 + + const loadCategoryValues = async () => { + setIsLoading(true); + try { + const response = await getCategoryValues( + tableName, + columnName, + menuId, // ← menuId 전달 + false + ); + + if (response.success && response.data) { + setValues(response.data); + onValueCountChange?.(response.data.length); + } + } catch (error) { + console.error("카테고리 값 조회 실패:", error); + } finally { + setIsLoading(false); + } + }; + + const handleAddValue = async (newValue: TableCategoryValue) => { + try { + const response = await addCategoryValue( + { + ...newValue, + tableName, + columnName, + }, + menuId // ← menuId 전달 + ); + + if (response.success) { + loadCategoryValues(); + toast.success("카테고리 값이 추가되었습니다"); + } + } catch (error) { + console.error("카테고리 값 추가 실패:", error); + toast.error("카테고리 값 추가 중 오류가 발생했습니다"); + } + }; + + // ... 나머지 CRUD 로직 (menuId를 항상 포함) +} +``` + +### 4. 화면관리 시스템에서 menuId 전달 + +#### 화면 디자이너에서 menuId 추출 + +```typescript +// frontend/components/screen/ScreenDesigner.tsx + +export function ScreenDesigner() { + const [selectedScreen, setSelectedScreen] = useState(null); + + // 선택된 화면의 menuId 추출 + const currentMenuId = selectedScreen?.menuId; + + // CategoryWidget 렌더링 시 menuId 전달 + return ( +
+ {/* ... */} + +
+ ); +} +``` + +#### CategoryWidget 컴포넌트 (신규 또는 수정) + +```typescript +// frontend/components/screen/widgets/CategoryWidget.tsx + +interface CategoryWidgetProps { + tableName: string; + menuId: number; // ← 추가 +} + +export function CategoryWidget({ tableName, menuId }: CategoryWidgetProps) { + const [selectedColumn, setSelectedColumn] = useState(null); + const [selectedColumnLabel, setSelectedColumnLabel] = useState(""); + + const handleColumnSelect = (columnName: string, columnLabel: string) => { + setSelectedColumn(columnName); + setSelectedColumnLabel(columnLabel); + }; + + return ( +
+ {/* 좌측: 카테고리 컬럼 리스트 */} +
+ +
+ + {/* 우측: 카테고리 값 관리 */} +
+ {selectedColumn ? ( + + ) : ( +
+

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

+
+ )} +
+
+ ); +} +``` + +--- + +## 🔄 기존 데이터 마이그레이션 + +### 마이그레이션 스크립트 + +```sql +-- db/migrations/047_add_menu_id_to_category_values.sql + +-- 1. menu_id 컬럼 추가 (NULL 허용) +ALTER TABLE table_column_category_values +ADD COLUMN IF NOT EXISTS menu_id INTEGER; + +-- 2. 기존 데이터에 임시 menu_id 설정 +-- (관리자가 수동으로 올바른 menu_id로 변경해야 함) +UPDATE table_column_category_values +SET menu_id = 1 +WHERE menu_id IS NULL; + +-- 3. menu_id를 NOT NULL로 변경 +ALTER TABLE table_column_category_values +ALTER COLUMN menu_id SET NOT NULL; + +-- 4. 외래키 추가 +ALTER TABLE table_column_category_values +ADD CONSTRAINT fk_category_value_menu +FOREIGN KEY (menu_id) REFERENCES menu_info(menu_id); + +-- 5. UNIQUE 제약조건 재생성 +ALTER TABLE table_column_category_values +DROP CONSTRAINT IF EXISTS unique_category_value; + +ALTER TABLE table_column_category_values +ADD CONSTRAINT unique_category_value +UNIQUE (table_name, column_name, value_code, menu_id, company_code); + +-- 6. 인덱스 추가 +CREATE INDEX idx_category_value_menu +ON table_column_category_values(menu_id, table_name, column_name, company_code); + +COMMENT ON COLUMN table_column_category_values.menu_id IS '카테고리를 생성한 메뉴 ID (형제 메뉴에서 공유)'; +``` + +--- + +## 📊 사용 시나리오 + +### 시나리오: 영업관리 공통코드 관리 + +#### 1단계: 메뉴 구조 + +``` +영업관리 (parent_id: 0, menu_id: 200) +├── 고객관리 (parent_id: 200, menu_id: 201) - customer_info 테이블 +├── 계약관리 (parent_id: 200, menu_id: 202) - contract_info 테이블 +├── 주문관리 (parent_id: 200, menu_id: 203) - order_info 테이블 +└── 공통코드 관리 (parent_id: 200, menu_id: 204) - 카테고리 관리 전용 +``` + +#### 2단계: 카테고리 관리 화면 생성 + +1. **메뉴 등록**: 영업관리 > 공통코드 관리 (menu_id: 204) +2. **화면 생성**: 화면관리 시스템에서 화면 생성 +3. **테이블 선택**: 영업관리에서 사용할 **아무 테이블** (예: `customer_info`) + - 테이블 선택은 컬럼 목록을 가져오기 위한 것일 뿐 + - 실제 스코프는 `menu_id`로 결정됨 +4. **위젯 배치**: 카테고리 관리 위젯 드래그앤드롭 + +#### 3단계: 카테고리 값 등록 + +1. **좌측 패널**: `customer_info` 테이블의 카테고리 컬럼 표시 + + - `customer_type` (고객 유형) + - `customer_grade` (고객 등급) + +2. **컬럼 선택**: `customer_type` 클릭 + +3. **우측 패널**: 카테고리 값 관리 + - 추가 버튼 클릭 + - 코드: `REGULAR`, 라벨: `일반 고객` + - 색상: `#3b82f6` + - **저장 시 `menu_id = 204`로 자동 저장됨** + +#### 4단계: 다른 화면에서 사용 + +##### ✅ 형제 메뉴에서 사용 가능 + +**고객관리 화면** (menu_id: 201): + +- `customer_type` 컬럼을 category-select 위젯으로 배치 +- 드롭다운에 `일반 고객`, `VIP 고객` 등 표시됨 ✅ +- **이유**: 201과 204는 같은 부모(200)를 가진 형제 메뉴 + +**계약관리 화면** (menu_id: 202): + +- `contract_info` 테이블에 `customer_type` 컬럼이 있다면 +- 동일한 카테고리 값 사용 가능 ✅ +- **이유**: 202와 204도 형제 메뉴 + +**주문관리 화면** (menu_id: 203): + +- `order_info` 테이블에 `customer_type` 컬럼이 있다면 +- 동일한 카테고리 값 사용 가능 ✅ +- **이유**: 203과 204도 형제 메뉴 + +##### ❌ 다른 부모 메뉴에서 사용 불가 + +**구매관리 > 발주관리** (parent_id: 300): + +- `purchase_orders` 테이블에 `customer_type` 컬럼이 있어도 +- 영업관리의 카테고리는 표시되지 않음 ❌ +- **이유**: 다른 부모 메뉴이므로 스코프가 다름 +- 구매관리는 자체 카테고리를 별도로 생성해야 함 + +--- + +## 📝 구현 순서 + +### Phase 1: 데이터베이스 마이그레이션 (30분) + +1. ✅ 마이그레이션 파일 작성 (`047_add_menu_id_to_category_values.sql`) +2. ⏳ DB 마이그레이션 실행 +3. ⏳ 기존 데이터 임시 menu_id 설정 (관리자 수동 정리 필요) + +### Phase 2: 백엔드 구현 (2-3시간) + +4. ⏳ `menuService.ts`에 `getSiblingMenuIds()` 함수 추가 +5. ⏳ `tableCategoryValueService.ts`에 menu_id 로직 추가 + - `getCategoryValues()` 메서드에 menuId 파라미터 추가 + - `addCategoryValue()` 메서드에 menuId 파라미터 추가 +6. ⏳ `tableCategoryValueController.ts` 수정 + - 쿼리 파라미터에서 menuId 추출 + - 서비스 호출 시 menuId 전달 +7. ⏳ 백엔드 테스트 + +### Phase 3: 프론트엔드 API 클라이언트 (30분) + +8. ⏳ `frontend/lib/api/tableCategoryValue.ts` 수정 + - `getCategoryValues()` 함수에 menuId 파라미터 추가 + - `addCategoryValue()` 함수에 menuId 파라미터 추가 + +### Phase 4: 프론트엔드 컴포넌트 (2-3시간) + +9. ⏳ `CategoryColumnList.tsx` 수정 + - props에 `menuId` 추가 + - `getCategoryValues()` 호출 시 menuId 전달 +10. ⏳ `CategoryValueManager.tsx` 수정 + - props에 `menuId` 추가 + - 모든 API 호출 시 menuId 전달 +11. ⏳ `CategoryWidget.tsx` 수정 또는 신규 생성 + - `menuId` prop 추가 + - 하위 컴포넌트에 menuId 전달 + +### Phase 5: 화면관리 시스템 통합 (1-2시간) + +12. ⏳ 화면 정보에서 menuId 추출 로직 추가 +13. ⏳ CategoryWidget에 menuId 전달 +14. ⏳ 카테고리 관리 화면 테스트 + +### Phase 6: 테스트 및 문서화 (1시간) + +15. ⏳ 전체 플로우 테스트 +16. ⏳ 메뉴 스코프 동작 검증 +17. ⏳ 사용 가이드 작성 + +--- + +## 🧪 테스트 체크리스트 + +### 백엔드 테스트 + +- [ ] `getSiblingMenuIds()` 함수가 올바른 형제 메뉴 반환 +- [ ] 최상위 메뉴의 경우 자기 자신만 반환 +- [ ] 카테고리 값 조회 시 형제 메뉴의 값도 포함 +- [ ] 다른 부모 메뉴의 카테고리는 조회되지 않음 +- [ ] 멀티테넌시 필터링 정상 작동 + +### 프론트엔드 테스트 + +- [ ] 카테고리 컬럼 목록 정상 표시 +- [ ] 카테고리 값 목록 정상 표시 (형제 메뉴 포함) +- [ ] 카테고리 값 추가 시 menuId 포함 +- [ ] 카테고리 값 수정/삭제 정상 작동 + +### 통합 테스트 + +- [ ] 영업관리 > 공통코드 관리에서 카테고리 생성 +- [ ] 영업관리 > 고객관리에서 카테고리 사용 가능 +- [ ] 영업관리 > 계약관리에서 카테고리 사용 가능 +- [ ] 구매관리에서는 영업관리 카테고리 사용 불가 + +--- + +## 📦 예상 소요 시간 + +| Phase | 작업 내용 | 예상 시간 | +| ---------------- | ------------------- | ------------ | +| Phase 1 | DB 마이그레이션 | 30분 | +| Phase 2 | 백엔드 구현 | 2-3시간 | +| Phase 3 | API 클라이언트 | 30분 | +| Phase 4 | 프론트엔드 컴포넌트 | 2-3시간 | +| Phase 5 | 화면관리 통합 | 1-2시간 | +| Phase 6 | 테스트 및 문서 | 1시간 | +| **총 예상 시간** | | **7-11시간** | + +--- + +## 💡 이점 + +### 1. 메뉴별 독립 관리 + +- 영업관리, 구매관리, 생산관리 등 각 부서별 카테고리 독립 관리 +- 부서 간 카테고리 충돌 방지 + +### 2. 형제 메뉴 간 공유 + +- 같은 부서의 화면들이 카테고리 공유 +- 중복 생성 불필요 + +### 3. 테이블 독립성 + +- 테이블이 달라도 같은 카테고리 사용 가능 +- 테이블 구조 변경에 영향 없음 + +### 4. 직관적인 관리 + +- 메뉴 구조가 곧 카테고리 스코프 +- 이해하기 쉬운 권한 체계 + +--- + +## 🚀 다음 단계 + +### 1. 계획 승인 후 즉시 구현 시작 + +이 계획서를 검토하고 승인받으면 바로 구현을 시작합니다. + +### 2. 채번규칙 시스템도 동일하게 전환 + +카테고리 시스템 전환이 완료되면, 채번규칙 시스템도 동일한 메뉴 기반 스코프로 전환합니다. + +### 3. 공통 유틸리티 함수 재사용 + +`getSiblingMenuIds()` 함수는 카테고리와 채번규칙 모두에서 재사용 가능합니다. + +--- + +이 계획서대로 구현하면 영업관리 전체의 공통코드를 효과적으로 관리할 수 있습니다. +바로 구현을 시작할까요? -- 2.43.0 From 668b45d4eac4af7637b23545aa2d51255a2ab93b Mon Sep 17 00:00:00 2001 From: kjs Date: Tue, 11 Nov 2025 14:32:00 +0900 Subject: [PATCH 04/13] =?UTF-8?q?feat:=20=EC=B1=84=EB=B2=88=EA=B7=9C?= =?UTF-8?q?=EC=B9=99=20=EB=A9=94=EB=89=B4=20=EC=8A=A4=EC=BD=94=ED=94=84=20?= =?UTF-8?q?=EC=A0=84=ED=99=98=20=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ 주요 변경사항: - 백엔드: menuService.ts 추가 (형제 메뉴 조회 유틸리티) - 백엔드: numberingRuleService.getAvailableRulesForMenu() 메뉴 스코프 적용 - 백엔드: tableCategoryValueService 메뉴 스코프 준비 (menuObjid 파라미터 추가) - 프론트엔드: TextInputConfigPanel에 부모 메뉴 선택 UI 추가 - 프론트엔드: 메뉴별 채번규칙 필터링 (형제 메뉴 공유) 🔧 기술 세부사항: - getSiblingMenuObjids(): 같은 부모를 가진 형제 메뉴 OBJID 조회 - 채번규칙 우선순위: menu (형제) > table > global - 사용자 메뉴(menu_type='1') 레벨 2만 부모 메뉴로 선택 가능 📝 다음 단계: - 카테고리 컴포넌트도 메뉴 스코프로 전환 예정 --- .../controllers/numberingRuleController.ts | 14 +- .../tableCategoryValueController.ts | 40 +- backend-node/src/services/menuService.ts | 159 +++ .../src/services/numberingRuleService.ts | 174 +-- .../src/services/tableCategoryValueService.ts | 228 ++-- .../app/(main)/screens/[screenId]/page.tsx | 7 +- .../numbering-rule/NumberingRuleDesigner.tsx | 16 +- .../screen/RealtimePreviewDynamic.tsx | 3 + .../webtype-configs/TextTypeConfigPanel.tsx | 188 ++- .../screen/widgets/CategoryWidget.tsx | 7 +- .../table-category/CategoryColumnList.tsx | 7 +- .../table-category/CategoryValueManager.tsx | 28 +- frontend/lib/api/tableCategoryValue.ts | 32 +- .../lib/registry/DynamicComponentRenderer.tsx | 3 + .../text-input/TextInputConfigPanel.tsx | 196 +++- 카테고리_채번_메뉴스코프_전환_통합_계획서.md | 1004 +++++++++++++++++ 16 files changed, 1838 insertions(+), 268 deletions(-) create mode 100644 backend-node/src/services/menuService.ts create mode 100644 카테고리_채번_메뉴스코프_전환_통합_계획서.md diff --git a/backend-node/src/controllers/numberingRuleController.ts b/backend-node/src/controllers/numberingRuleController.ts index 556d09df..1b2e2197 100644 --- a/backend-node/src/controllers/numberingRuleController.ts +++ b/backend-node/src/controllers/numberingRuleController.ts @@ -27,12 +27,24 @@ router.get("/available/:menuObjid?", authenticateToken, async (req: Authenticate const companyCode = req.user!.companyCode; const menuObjid = req.params.menuObjid ? parseInt(req.params.menuObjid) : undefined; + logger.info("📥 메뉴별 채번 규칙 조회 요청", { companyCode, menuObjid }); + try { const rules = await numberingRuleService.getAvailableRulesForMenu(companyCode, menuObjid); + + logger.info("✅ 메뉴별 채번 규칙 조회 성공 (컨트롤러)", { + companyCode, + menuObjid, + rulesCount: rules.length + }); + return res.json({ success: true, data: rules }); } catch (error: any) { - logger.error("메뉴별 사용 가능한 규칙 조회 실패", { + logger.error("❌ 메뉴별 사용 가능한 규칙 조회 실패 (컨트롤러)", { error: error.message, + errorCode: error.code, + errorStack: error.stack, + companyCode, menuObjid, }); return res.status(500).json({ success: false, error: error.message }); diff --git a/backend-node/src/controllers/tableCategoryValueController.ts b/backend-node/src/controllers/tableCategoryValueController.ts index 865f7672..ffb6a5a4 100644 --- a/backend-node/src/controllers/tableCategoryValueController.ts +++ b/backend-node/src/controllers/tableCategoryValueController.ts @@ -32,18 +32,31 @@ export const getCategoryColumns = async (req: AuthenticatedRequest, res: Respons /** * 카테고리 값 목록 조회 (메뉴 스코프 적용) + * + * Query Parameters: + * - menuObjid: 메뉴 OBJID (선택사항, 제공 시 형제 메뉴의 카테고리 값 포함) + * - includeInactive: 비활성 값 포함 여부 */ export const getCategoryValues = async (req: AuthenticatedRequest, res: Response) => { try { const companyCode = req.user!.companyCode; const { tableName, columnName } = req.params; const includeInactive = req.query.includeInactive === "true"; + const menuObjid = req.query.menuObjid ? Number(req.query.menuObjid) : undefined; + + logger.info("카테고리 값 조회 요청", { + tableName, + columnName, + menuObjid, + companyCode, + }); const values = await tableCategoryValueService.getCategoryValues( tableName, columnName, companyCode, - includeInactive + includeInactive, + menuObjid // ← menuObjid 전달 ); return res.json({ @@ -61,18 +74,37 @@ export const getCategoryValues = async (req: AuthenticatedRequest, res: Response }; /** - * 카테고리 값 추가 + * 카테고리 값 추가 (메뉴 스코프) + * + * Body: + * - menuObjid: 메뉴 OBJID (필수) + * - 나머지 카테고리 값 정보 */ export const addCategoryValue = async (req: AuthenticatedRequest, res: Response) => { try { const companyCode = req.user!.companyCode; const userId = req.user!.userId; - const value = req.body; + const { menuObjid, ...value } = req.body; + + if (!menuObjid) { + return res.status(400).json({ + success: false, + message: "menuObjid는 필수입니다", + }); + } + + logger.info("카테고리 값 추가 요청", { + tableName: value.tableName, + columnName: value.columnName, + menuObjid, + companyCode, + }); const newValue = await tableCategoryValueService.addCategoryValue( value, companyCode, - userId + userId, + Number(menuObjid) // ← menuObjid 전달 ); return res.status(201).json({ diff --git a/backend-node/src/services/menuService.ts b/backend-node/src/services/menuService.ts new file mode 100644 index 00000000..9a9be99c --- /dev/null +++ b/backend-node/src/services/menuService.ts @@ -0,0 +1,159 @@ +import { getPool } from "../database/db"; +import { logger } from "../utils/logger"; + +/** + * 메뉴 관련 유틸리티 서비스 + * + * 메뉴 스코프 기반 데이터 공유를 위한 형제 메뉴 조회 기능 제공 + */ + +/** + * 메뉴의 형제 메뉴 OBJID 목록 조회 + * (같은 부모를 가진 메뉴들) + * + * 메뉴 스코프 규칙: + * - 같은 부모를 가진 형제 메뉴들은 카테고리/채번규칙을 공유 + * - 최상위 메뉴(parent_obj_id = 0)는 자기 자신만 반환 + * - 메뉴를 찾을 수 없으면 안전하게 자기 자신만 반환 + * + * @param menuObjid 현재 메뉴의 OBJID + * @returns 형제 메뉴 OBJID 배열 (자기 자신 포함, 정렬됨) + * + * @example + * // 영업관리 (200) + * // ├── 고객관리 (201) + * // ├── 계약관리 (202) + * // └── 주문관리 (203) + * + * await getSiblingMenuObjids(201); + * // 결과: [201, 202, 203] - 모두 같은 부모(200)를 가진 형제 + */ +export async function getSiblingMenuObjids(menuObjid: number): Promise { + const pool = getPool(); + + try { + logger.info("형제 메뉴 조회 시작", { menuObjid }); + + // 1. 현재 메뉴의 부모 찾기 + const parentQuery = ` + SELECT parent_obj_id FROM menu_info WHERE objid = $1 + `; + const parentResult = await pool.query(parentQuery, [menuObjid]); + + if (parentResult.rows.length === 0) { + logger.warn("메뉴를 찾을 수 없음, 자기 자신만 반환", { menuObjid }); + return [menuObjid]; // 메뉴가 없으면 안전하게 자기 자신만 반환 + } + + const parentObjId = parentResult.rows[0].parent_obj_id; + + if (!parentObjId || parentObjId === 0) { + // 최상위 메뉴인 경우 자기 자신만 반환 + logger.info("최상위 메뉴 (형제 없음)", { menuObjid, parentObjId }); + return [menuObjid]; + } + + // 2. 같은 부모를 가진 형제 메뉴들 조회 + const siblingsQuery = ` + SELECT objid FROM menu_info + WHERE parent_obj_id = $1 + ORDER BY objid + `; + const siblingsResult = await pool.query(siblingsQuery, [parentObjId]); + + const siblingObjids = siblingsResult.rows.map((row) => Number(row.objid)); + + logger.info("형제 메뉴 조회 완료", { + menuObjid, + parentObjId, + siblingCount: siblingObjids.length, + siblings: siblingObjids, + }); + + return siblingObjids; + } catch (error: any) { + logger.error("형제 메뉴 조회 실패", { + menuObjid, + error: error.message, + stack: error.stack + }); + // 에러 발생 시 안전하게 자기 자신만 반환 + return [menuObjid]; + } +} + +/** + * 여러 메뉴의 형제 메뉴 OBJID 합집합 조회 + * + * 여러 메뉴에 속한 모든 형제 메뉴를 중복 제거하여 반환 + * + * @param menuObjids 메뉴 OBJID 배열 + * @returns 모든 형제 메뉴 OBJID 배열 (중복 제거, 정렬됨) + * + * @example + * // 서로 다른 부모를 가진 메뉴들의 형제를 모두 조회 + * await getAllSiblingMenuObjids([201, 301]); + * // 201의 형제: [201, 202, 203] + * // 301의 형제: [301, 302] + * // 결과: [201, 202, 203, 301, 302] + */ +export async function getAllSiblingMenuObjids( + menuObjids: number[] +): Promise { + if (!menuObjids || menuObjids.length === 0) { + logger.warn("getAllSiblingMenuObjids: 빈 배열 입력"); + return []; + } + + const allSiblings = new Set(); + + for (const objid of menuObjids) { + const siblings = await getSiblingMenuObjids(objid); + siblings.forEach((s) => allSiblings.add(s)); + } + + const result = Array.from(allSiblings).sort((a, b) => a - b); + + logger.info("여러 메뉴의 형제 조회 완료", { + inputMenus: menuObjids, + resultCount: result.length, + result, + }); + + return result; +} + +/** + * 메뉴 정보 조회 + * + * @param menuObjid 메뉴 OBJID + * @returns 메뉴 정보 (없으면 null) + */ +export async function getMenuInfo(menuObjid: number): Promise { + const pool = getPool(); + + try { + const query = ` + SELECT + objid, + parent_obj_id AS "parentObjId", + menu_name_kor AS "menuNameKor", + menu_name_eng AS "menuNameEng", + menu_url AS "menuUrl", + company_code AS "companyCode" + FROM menu_info + WHERE objid = $1 + `; + const result = await pool.query(query, [menuObjid]); + + if (result.rows.length === 0) { + return null; + } + + return result.rows[0]; + } catch (error: any) { + logger.error("메뉴 정보 조회 실패", { menuObjid, error: error.message }); + return null; + } +} + diff --git a/backend-node/src/services/numberingRuleService.ts b/backend-node/src/services/numberingRuleService.ts index 98230b65..2c89f188 100644 --- a/backend-node/src/services/numberingRuleService.ts +++ b/backend-node/src/services/numberingRuleService.ts @@ -4,6 +4,7 @@ import { getPool } from "../database/db"; import { logger } from "../utils/logger"; +import { getSiblingMenuObjids } from "./menuService"; interface NumberingRulePart { id?: number; @@ -150,22 +151,33 @@ class NumberingRuleService { } /** - * 현재 메뉴에서 사용 가능한 규칙 목록 조회 + * 현재 메뉴에서 사용 가능한 규칙 목록 조회 (메뉴 스코프) + * + * 메뉴 스코프 규칙: + * - menuObjid가 제공되면 형제 메뉴의 채번 규칙 포함 + * - 우선순위: menu (형제 메뉴) > table > global */ async getAvailableRulesForMenu( companyCode: string, menuObjid?: number ): Promise { try { - logger.info("메뉴별 사용 가능한 채번 규칙 조회 시작", { + logger.info("메뉴별 사용 가능한 채번 규칙 조회 시작 (메뉴 스코프)", { companyCode, menuObjid, }); const pool = getPool(); + // 1. 형제 메뉴 OBJID 조회 + let siblingObjids: number[] = []; + if (menuObjid) { + siblingObjids = await getSiblingMenuObjids(menuObjid); + logger.info("형제 메뉴 OBJID 목록", { menuObjid, siblingObjids }); + } + // menuObjid가 없으면 global 규칙만 반환 - if (!menuObjid) { + if (!menuObjid || siblingObjids.length === 0) { let query: string; let params: any[]; @@ -261,35 +273,13 @@ class NumberingRuleService { return result.rows; } - // 현재 메뉴의 상위 계층 조회 (2레벨 메뉴 찾기) - const menuHierarchyQuery = ` - WITH RECURSIVE menu_path AS ( - SELECT objid, objid_parent, menu_level - FROM menu_info - WHERE objid = $1 - - UNION ALL - - SELECT mi.objid, mi.objid_parent, mi.menu_level - FROM menu_info mi - INNER JOIN menu_path mp ON mi.objid = mp.objid_parent - ) - SELECT objid, menu_level - FROM menu_path - WHERE menu_level = 2 - LIMIT 1 - `; - - const hierarchyResult = await pool.query(menuHierarchyQuery, [menuObjid]); - const level2MenuObjid = - hierarchyResult.rowCount > 0 ? hierarchyResult.rows[0].objid : null; - - // 사용 가능한 규칙 조회 (멀티테넌시 적용) + // 2. 메뉴 스코프: 형제 메뉴의 채번 규칙 조회 + // 우선순위: menu (형제 메뉴) > table > global let query: string; let params: any[]; if (companyCode === "*") { - // 최고 관리자: 모든 규칙 조회 + // 최고 관리자: 모든 규칙 조회 (형제 메뉴 포함) query = ` SELECT rule_id AS "ruleId", @@ -309,12 +299,20 @@ class NumberingRuleService { FROM numbering_rules WHERE scope_type = 'global' - OR (scope_type = 'menu' AND menu_objid = $1) - ORDER BY scope_type DESC, created_at DESC + OR scope_type = 'table' + OR (scope_type = 'menu' AND menu_objid = ANY($1)) + ORDER BY + CASE scope_type + WHEN 'menu' THEN 1 + WHEN 'table' THEN 2 + WHEN 'global' THEN 3 + END, + created_at DESC `; - params = [level2MenuObjid]; + params = [siblingObjids]; + logger.info("최고 관리자: 형제 메뉴 포함 채번 규칙 조회", { siblingObjids }); } else { - // 일반 회사: 자신의 규칙만 조회 + // 일반 회사: 자신의 규칙만 조회 (형제 메뉴 포함) query = ` SELECT rule_id AS "ruleId", @@ -335,58 +333,91 @@ class NumberingRuleService { WHERE company_code = $1 AND ( scope_type = 'global' - OR (scope_type = 'menu' AND menu_objid = $2) + OR scope_type = 'table' + OR (scope_type = 'menu' AND menu_objid = ANY($2)) ) - ORDER BY scope_type DESC, created_at DESC + ORDER BY + CASE scope_type + WHEN 'menu' THEN 1 + WHEN 'table' THEN 2 + WHEN 'global' THEN 3 + END, + created_at DESC `; - params = [companyCode, level2MenuObjid]; + params = [companyCode, siblingObjids]; + logger.info("회사별: 형제 메뉴 포함 채번 규칙 조회", { companyCode, siblingObjids }); } + logger.info("🔍 채번 규칙 쿼리 실행", { + queryPreview: query.substring(0, 200), + paramsTypes: params.map(p => typeof p), + paramsValues: params, + }); + const result = await pool.query(query, params); + logger.info("✅ 채번 규칙 쿼리 성공", { rowCount: result.rows.length }); + // 파트 정보 추가 for (const rule of result.rows) { - let partsQuery: string; - let partsParams: any[]; - - if (companyCode === "*") { - partsQuery = ` - SELECT - id, - part_order AS "order", - part_type AS "partType", - generation_method AS "generationMethod", - auto_config AS "autoConfig", - manual_config AS "manualConfig" - FROM numbering_rule_parts - WHERE rule_id = $1 - ORDER BY part_order - `; - partsParams = [rule.ruleId]; - } else { - partsQuery = ` - SELECT - id, - part_order AS "order", - part_type AS "partType", - generation_method AS "generationMethod", - auto_config AS "autoConfig", - manual_config AS "manualConfig" - FROM numbering_rule_parts - WHERE rule_id = $1 AND company_code = $2 - ORDER BY part_order - `; - partsParams = [rule.ruleId, companyCode]; - } + try { + let partsQuery: string; + let partsParams: any[]; + + if (companyCode === "*") { + partsQuery = ` + SELECT + id, + part_order AS "order", + part_type AS "partType", + generation_method AS "generationMethod", + auto_config AS "autoConfig", + manual_config AS "manualConfig" + FROM numbering_rule_parts + WHERE rule_id = $1 + ORDER BY part_order + `; + partsParams = [rule.ruleId]; + } else { + partsQuery = ` + SELECT + id, + part_order AS "order", + part_type AS "partType", + generation_method AS "generationMethod", + auto_config AS "autoConfig", + manual_config AS "manualConfig" + FROM numbering_rule_parts + WHERE rule_id = $1 AND company_code = $2 + ORDER BY part_order + `; + partsParams = [rule.ruleId, companyCode]; + } - const partsResult = await pool.query(partsQuery, partsParams); - rule.parts = partsResult.rows; + const partsResult = await pool.query(partsQuery, partsParams); + rule.parts = partsResult.rows; + + logger.info("✅ 규칙 파트 조회 성공", { + ruleId: rule.ruleId, + ruleName: rule.ruleName, + partsCount: partsResult.rows.length, + }); + } catch (partError: any) { + logger.error("❌ 규칙 파트 조회 실패", { + ruleId: rule.ruleId, + ruleName: rule.ruleName, + error: partError.message, + errorCode: partError.code, + errorStack: partError.stack, + }); + throw partError; + } } logger.info("메뉴별 사용 가능한 채번 규칙 조회 완료", { companyCode, menuObjid, - level2MenuObjid, + siblingCount: siblingObjids.length, count: result.rowCount, }); @@ -394,8 +425,11 @@ class NumberingRuleService { } catch (error: any) { logger.error("메뉴별 채번 규칙 조회 실패", { error: error.message, + errorCode: error.code, + errorStack: error.stack, companyCode, menuObjid, + siblingObjids: siblingObjids || [], }); throw error; } diff --git a/backend-node/src/services/tableCategoryValueService.ts b/backend-node/src/services/tableCategoryValueService.ts index 7646dead..29cad453 100644 --- a/backend-node/src/services/tableCategoryValueService.ts +++ b/backend-node/src/services/tableCategoryValueService.ts @@ -1,5 +1,6 @@ import { getPool } from "../database/db"; import { logger } from "../utils/logger"; +import { getSiblingMenuObjids } from "./menuService"; import { TableCategoryValue, CategoryColumn, @@ -79,84 +80,164 @@ class TableCategoryValueService { } /** - * 특정 컬럼의 카테고리 값 목록 조회 (테이블 스코프) + * 특정 컬럼의 카테고리 값 목록 조회 (메뉴 스코프) + * + * 메뉴 스코프 규칙: + * - menuObjid가 제공되면 해당 메뉴와 형제 메뉴의 카테고리 값을 조회 + * - menuObjid가 없으면 테이블 스코프로 동작 (하위 호환성) */ async getCategoryValues( tableName: string, columnName: string, companyCode: string, - includeInactive: boolean = false + includeInactive: boolean = false, + menuObjid?: number ): Promise { try { - logger.info("카테고리 값 목록 조회", { + logger.info("카테고리 값 목록 조회 (메뉴 스코프)", { tableName, columnName, companyCode, includeInactive, + menuObjid, }); const pool = getPool(); - // 멀티테넌시: 최고 관리자만 company_code="*" 데이터를 볼 수 있음 + // 1. 메뉴 스코프: 형제 메뉴 OBJID 조회 + let siblingObjids: number[] = []; + if (menuObjid) { + siblingObjids = await getSiblingMenuObjids(menuObjid); + logger.info("형제 메뉴 OBJID 목록", { menuObjid, siblingObjids }); + } + + // 2. 카테고리 값 조회 (형제 메뉴 포함) let query: string; let params: any[]; if (companyCode === "*") { // 최고 관리자: 모든 카테고리 값 조회 - 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", - 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 - `; - params = [tableName, columnName]; + if (menuObjid && siblingObjids.length > 0) { + // 메뉴 스코프 적용 + 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", + company_code AS "companyCode", + menu_objid AS "menuObjid", + 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) + `; + params = [tableName, columnName, siblingObjids]; + } else { + // 테이블 스코프 (하위 호환성) + 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", + company_code AS "companyCode", + menu_objid AS "menuObjid", + 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 + `; + params = [tableName, columnName]; + } logger.info("최고 관리자 카테고리 값 조회"); } else { // 일반 회사: 자신의 카테고리 값만 조회 - 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", - 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 company_code = $3 - `; - params = [tableName, columnName, companyCode]; + if (menuObjid && siblingObjids.length > 0) { + // 메뉴 스코프 적용 + 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", + company_code AS "companyCode", + menu_objid AS "menuObjid", + 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 + `; + params = [tableName, columnName, siblingObjids, companyCode]; + } else { + // 테이블 스코프 (하위 호환성) + 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", + company_code AS "companyCode", + menu_objid AS "menuObjid", + 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 company_code = $3 + `; + params = [tableName, columnName, companyCode]; + } logger.info("회사별 카테고리 값 조회", { companyCode }); } @@ -175,6 +256,8 @@ class TableCategoryValueService { tableName, columnName, companyCode, + menuObjid, + scopeType: menuObjid ? "menu" : "table", }); return values; @@ -185,17 +268,31 @@ class TableCategoryValueService { } /** - * 카테고리 값 추가 + * 카테고리 값 추가 (메뉴 스코프) + * + * @param value 카테고리 값 정보 + * @param companyCode 회사 코드 + * @param userId 생성자 ID + * @param menuObjid 메뉴 OBJID (필수) */ async addCategoryValue( value: TableCategoryValue, companyCode: string, - userId: string + userId: string, + menuObjid: number ): Promise { const pool = getPool(); try { - // 중복 코드 체크 (멀티테넌시 적용) + logger.info("카테고리 값 추가 (메뉴 스코프)", { + tableName: value.tableName, + columnName: value.columnName, + valueCode: value.valueCode, + menuObjid, + companyCode, + }); + + // 중복 코드 체크 (멀티테넌시 + 메뉴 스코프) let duplicateQuery: string; let duplicateParams: any[]; @@ -207,8 +304,9 @@ class TableCategoryValueService { WHERE table_name = $1 AND column_name = $2 AND value_code = $3 + AND menu_objid = $4 `; - duplicateParams = [value.tableName, value.columnName, value.valueCode]; + duplicateParams = [value.tableName, value.columnName, value.valueCode, menuObjid]; } else { // 일반 회사: 자신의 회사에서만 중복 체크 duplicateQuery = ` @@ -217,9 +315,10 @@ class TableCategoryValueService { WHERE table_name = $1 AND column_name = $2 AND value_code = $3 - AND company_code = $4 + AND menu_objid = $4 + AND company_code = $5 `; - duplicateParams = [value.tableName, value.columnName, value.valueCode, companyCode]; + duplicateParams = [value.tableName, value.columnName, value.valueCode, menuObjid, companyCode]; } const duplicateResult = await pool.query(duplicateQuery, duplicateParams); @@ -232,8 +331,8 @@ class TableCategoryValueService { 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, company_code, created_by - ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14) + is_active, is_default, company_code, menu_objid, 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", @@ -249,6 +348,7 @@ class TableCategoryValueService { is_active AS "isActive", is_default AS "isDefault", company_code AS "companyCode", + menu_objid AS "menuObjid", created_at AS "createdAt", created_by AS "createdBy" `; @@ -267,6 +367,7 @@ class TableCategoryValueService { value.isActive !== false, value.isDefault || false, companyCode, + menuObjid, // ← 메뉴 OBJID 저장 userId, ]); @@ -274,6 +375,7 @@ class TableCategoryValueService { valueId: result.rows[0].valueId, tableName: value.tableName, columnName: value.columnName, + menuObjid, }); return result.rows[0]; diff --git a/frontend/app/(main)/screens/[screenId]/page.tsx b/frontend/app/(main)/screens/[screenId]/page.tsx index d7ea2039..5c2c587b 100644 --- a/frontend/app/(main)/screens/[screenId]/page.tsx +++ b/frontend/app/(main)/screens/[screenId]/page.tsx @@ -1,7 +1,7 @@ "use client"; import React, { useEffect, useState } from "react"; -import { useParams } from "next/navigation"; +import { useParams, useSearchParams } from "next/navigation"; import { Button } from "@/components/ui/button"; import { Loader2 } from "lucide-react"; import { screenApi } from "@/lib/api/screen"; @@ -21,8 +21,12 @@ import { useResponsive } from "@/lib/hooks/useResponsive"; // 🆕 반응형 감 export default function ScreenViewPage() { const params = useParams(); + const searchParams = useSearchParams(); const router = useRouter(); const screenId = parseInt(params.screenId as string); + + // URL 쿼리에서 menuObjid 가져오기 (메뉴 스코프) + const menuObjid = searchParams.get("menuObjid") ? parseInt(searchParams.get("menuObjid")!) : undefined; // 🆕 현재 로그인한 사용자 정보 const { user, userName, companyCode } = useAuth(); @@ -404,6 +408,7 @@ export default function ScreenViewPage() { userId={user?.userId} userName={userName} companyCode={companyCode} + menuObjid={menuObjid} selectedRowsData={selectedRowsData} sortBy={tableSortBy} sortOrder={tableSortOrder} diff --git a/frontend/components/numbering-rule/NumberingRuleDesigner.tsx b/frontend/components/numbering-rule/NumberingRuleDesigner.tsx index 738aad79..252f5403 100644 --- a/frontend/components/numbering-rule/NumberingRuleDesigner.tsx +++ b/frontend/components/numbering-rule/NumberingRuleDesigner.tsx @@ -26,6 +26,7 @@ interface NumberingRuleDesignerProps { isPreview?: boolean; className?: string; currentTableName?: string; // 현재 화면의 테이블명 (자동 감지용) + menuObjid?: number; // 현재 메뉴 OBJID (메뉴 스코프) } export const NumberingRuleDesigner: React.FC = ({ @@ -36,6 +37,7 @@ export const NumberingRuleDesigner: React.FC = ({ isPreview = false, className = "", currentTableName, + menuObjid, }) => { const [savedRules, setSavedRules] = useState([]); const [selectedRuleId, setSelectedRuleId] = useState(null); @@ -53,7 +55,7 @@ export const NumberingRuleDesigner: React.FC = ({ const loadRules = useCallback(async () => { setLoading(true); try { - const response = await getNumberingRules(); + const response = await getNumberingRules(menuObjid); if (response.success && response.data) { setSavedRules(response.data); } else { @@ -64,7 +66,7 @@ export const NumberingRuleDesigner: React.FC = ({ } finally { setLoading(false); } - }, []); + }, [menuObjid]); useEffect(() => { if (currentRule) { @@ -145,7 +147,7 @@ export const NumberingRuleDesigner: React.FC = ({ "currentRule.tableName": currentRule.tableName, "ruleToSave.tableName": ruleToSave.tableName, "ruleToSave.scopeType": ruleToSave.scopeType, - ruleToSave + ruleToSave, }); let response; @@ -214,7 +216,7 @@ export const NumberingRuleDesigner: React.FC = ({ const handleNewRule = useCallback(() => { console.log("📋 새 규칙 생성 - currentTableName:", currentTableName); - + const newRule: NumberingRuleConfig = { ruleId: `rule-${Date.now()}`, ruleName: "새 채번 규칙", @@ -227,7 +229,7 @@ export const NumberingRuleDesigner: React.FC = ({ }; console.log("📋 생성된 규칙 정보:", newRule); - + setSelectedRuleId(newRule.ruleId); setCurrentRule(newRule); @@ -273,7 +275,7 @@ export const NumberingRuleDesigner: React.FC = ({ savedRules.map((rule) => ( handleSelectRule(rule)} @@ -356,7 +358,7 @@ export const NumberingRuleDesigner: React.FC = ({ {currentTableName && (
-
+
{currentTableName}

diff --git a/frontend/components/screen/RealtimePreviewDynamic.tsx b/frontend/components/screen/RealtimePreviewDynamic.tsx index fa5dc755..1f220586 100644 --- a/frontend/components/screen/RealtimePreviewDynamic.tsx +++ b/frontend/components/screen/RealtimePreviewDynamic.tsx @@ -41,6 +41,7 @@ interface RealtimePreviewProps { userId?: string; // 🆕 현재 사용자 ID userName?: string; // 🆕 현재 사용자 이름 companyCode?: string; // 🆕 현재 사용자의 회사 코드 + menuObjid?: number; // 🆕 현재 메뉴 OBJID (메뉴 스코프) selectedRowsData?: any[]; onSelectedRowsChange?: (selectedRows: any[], selectedRowsData: any[]) => void; flowSelectedData?: any[]; @@ -107,6 +108,7 @@ export const RealtimePreviewDynamic: React.FC = ({ userId, // 🆕 사용자 ID userName, // 🆕 사용자 이름 companyCode, // 🆕 회사 코드 + menuObjid, // 🆕 메뉴 OBJID selectedRowsData, onSelectedRowsChange, flowSelectedData, @@ -344,6 +346,7 @@ export const RealtimePreviewDynamic: React.FC = ({ userId={userId} userName={userName} companyCode={companyCode} + menuObjid={menuObjid} selectedRowsData={selectedRowsData} onSelectedRowsChange={onSelectedRowsChange} flowSelectedData={flowSelectedData} diff --git a/frontend/components/screen/panels/webtype-configs/TextTypeConfigPanel.tsx b/frontend/components/screen/panels/webtype-configs/TextTypeConfigPanel.tsx index 2e1f5087..cef462b9 100644 --- a/frontend/components/screen/panels/webtype-configs/TextTypeConfigPanel.tsx +++ b/frontend/components/screen/panels/webtype-configs/TextTypeConfigPanel.tsx @@ -14,7 +14,7 @@ interface TextTypeConfigPanelProps { config: TextTypeConfig; onConfigChange: (config: TextTypeConfig) => void; tableName?: string; // 화면의 테이블명 (선택) - menuObjid?: number; // 메뉴 objid (선택) + menuObjid?: number; // 메뉴 objid (선택) - 사용자가 선택한 부모 메뉴 } export const TextTypeConfigPanel: React.FC = ({ @@ -44,6 +44,10 @@ export const TextTypeConfigPanel: React.FC = ({ // 채번 규칙 목록 상태 const [numberingRules, setNumberingRules] = useState([]); const [loadingRules, setLoadingRules] = useState(false); + + // 부모 메뉴 목록 상태 (채번규칙 사용을 위한 선택) + const [parentMenus, setParentMenus] = useState([]); + const [selectedMenuObjid, setSelectedMenuObjid] = useState(menuObjid); // 로컬 상태로 실시간 입력 관리 const [localValues, setLocalValues] = useState({ @@ -60,31 +64,61 @@ export const TextTypeConfigPanel: React.FC = ({ numberingRuleId: safeConfig.numberingRuleId, }); - // 채번 규칙 목록 로드 + // 부모 메뉴 목록 로드 (최상위 메뉴 또는 레벨 2 메뉴) + useEffect(() => { + const loadParentMenus = async () => { + try { + const { apiClient } = await import("@/lib/api/client"); + + // 관리자 메뉴와 사용자 메뉴 모두 가져오기 + const [adminResponse, userResponse] = await Promise.all([ + apiClient.get("/admin/menus", { params: { menuType: "0" } }), + apiClient.get("/admin/menus", { params: { menuType: "1" } }) + ]); + + const allMenus = [ + ...(adminResponse.data?.data || []), + ...(userResponse.data?.data || []) + ]; + + // 레벨 2 이하 메뉴만 선택 가능 (부모가 있는 메뉴) + const parentMenuList = allMenus.filter((menu: any) => { + const level = menu.lev || menu.LEV || 0; + return level >= 2; // 레벨 2 이상만 표시 (형제 메뉴가 있을 가능성) + }); + + setParentMenus(parentMenuList); + console.log("✅ 부모 메뉴 목록 로드:", parentMenuList.length); + } catch (error) { + console.error("❌ 부모 메뉴 목록 로드 실패:", error); + } + }; + + loadParentMenus(); + }, []); + + // 채번 규칙 목록 로드 (선택된 메뉴 기준) useEffect(() => { const loadRules = async () => { console.log("🔄 채번 규칙 로드 시작:", { autoValueType: localValues.autoValueType, + selectedMenuObjid, tableName, - hasTableName: !!tableName, }); + // 메뉴를 선택하지 않으면 로드하지 않음 + if (!selectedMenuObjid) { + console.warn("⚠️ 메뉴를 선택해야 채번 규칙을 조회할 수 있습니다"); + setNumberingRules([]); + return; + } + setLoadingRules(true); try { - let response; - - // 테이블명이 있으면 테이블 기반 필터링 사용 - if (tableName) { - console.log("📋 테이블 기반 채번 규칙 조회 API 호출:", { tableName }); - response = await getAvailableNumberingRulesForScreen(tableName); - console.log("📋 API 응답:", response); - } else { - // 테이블명이 없으면 빈 배열 (테이블 필수) - console.warn("⚠️ 테이블명이 없어 채번 규칙을 조회할 수 없습니다"); - setNumberingRules([]); - setLoadingRules(false); - return; - } + // 선택된 메뉴의 채번 규칙 조회 (메뉴 스코프) + console.log("📋 메뉴 기반 채번 규칙 조회 API 호출:", { menuObjid: selectedMenuObjid }); + const response = await getAvailableNumberingRules(selectedMenuObjid); + console.log("📋 API 응답:", response); if (response.success && response.data) { setNumberingRules(response.data); @@ -93,7 +127,7 @@ export const TextTypeConfigPanel: React.FC = ({ rules: response.data.map((r: any) => ({ ruleId: r.ruleId, ruleName: r.ruleName, - tableName: r.tableName, + menuObjid: selectedMenuObjid, })), }); } else { @@ -115,7 +149,7 @@ export const TextTypeConfigPanel: React.FC = ({ } else { console.log("⏭️ autoValueType !== 'numbering_rule', 규칙 로드 스킵:", localValues.autoValueType); } - }, [localValues.autoValueType, tableName]); + }, [localValues.autoValueType, selectedMenuObjid]); // config가 변경될 때 로컬 상태 동기화 useEffect(() => { @@ -314,37 +348,95 @@ export const TextTypeConfigPanel: React.FC = ({

+ {(() => { + console.log("🔍 메뉴 선택 UI 렌더링 체크:", { + autoValueType: localValues.autoValueType, + isNumberingRule: localValues.autoValueType === "numbering_rule", + parentMenusCount: parentMenus.length, + selectedMenuObjid, + }); + return null; + })()} + {localValues.autoValueType === "numbering_rule" && ( -
- - setSelectedMenuObjid(parseInt(value))} + > + + + + + {parentMenus.length === 0 ? ( + + 사용 가능한 메뉴가 없습니다 - )) - )} - - -

- 현재 메뉴에서 사용 가능한 채번 규칙만 표시됩니다 -

-
+ ) : ( + parentMenus.map((menu) => { + const objid = menu.objid || menu.OBJID; + const menuName = menu.menu_name_kor || menu.MENU_NAME_KOR; + return ( + + {menuName} + + ); + }) + )} + + +

+ 이 필드가 어느 메뉴에서 사용될 것인지 선택하세요 +

+
+ + {/* 채번 규칙 선택 */} +
+ + +

+ 선택한 메뉴와 형제 메뉴에서 사용 가능한 채번 규칙만 표시됩니다 +

+
+ )} {localValues.autoValueType === "custom" && ( diff --git a/frontend/components/screen/widgets/CategoryWidget.tsx b/frontend/components/screen/widgets/CategoryWidget.tsx index 54c8f98b..3e1c7f7b 100644 --- a/frontend/components/screen/widgets/CategoryWidget.tsx +++ b/frontend/components/screen/widgets/CategoryWidget.tsx @@ -8,14 +8,15 @@ import { GripVertical } from "lucide-react"; interface CategoryWidgetProps { widgetId: string; tableName: string; // 현재 화면의 테이블 + menuObjid?: number; // 현재 메뉴 OBJID (메뉴 스코프) } /** * 카테고리 관리 위젯 (좌우 분할) * - 좌측: 현재 테이블의 카테고리 타입 컬럼 목록 - * - 우측: 선택된 컬럼의 카테고리 값 관리 (테이블 스코프) + * - 우측: 선택된 컬럼의 카테고리 값 관리 (메뉴 스코프) */ -export function CategoryWidget({ widgetId, tableName }: CategoryWidgetProps) { +export function CategoryWidget({ widgetId, tableName, menuObjid }: CategoryWidgetProps) { const [selectedColumn, setSelectedColumn] = useState<{ columnName: string; columnLabel: string; @@ -69,6 +70,7 @@ export function CategoryWidget({ widgetId, tableName }: CategoryWidgetProps) { onColumnSelect={(columnName, columnLabel) => setSelectedColumn({ columnName, columnLabel }) } + menuObjid={menuObjid} />
@@ -87,6 +89,7 @@ export function CategoryWidget({ widgetId, tableName }: CategoryWidgetProps) { tableName={tableName} columnName={selectedColumn.columnName} columnLabel={selectedColumn.columnLabel} + menuObjid={menuObjid} /> ) : (
diff --git a/frontend/components/table-category/CategoryColumnList.tsx b/frontend/components/table-category/CategoryColumnList.tsx index 7b7ebd32..db6af71c 100644 --- a/frontend/components/table-category/CategoryColumnList.tsx +++ b/frontend/components/table-category/CategoryColumnList.tsx @@ -16,13 +16,14 @@ interface CategoryColumnListProps { tableName: string; selectedColumn: string | null; onColumnSelect: (columnName: string, columnLabel: string) => void; + menuObjid?: number; // 현재 메뉴 OBJID (메뉴 스코프) } /** * 카테고리 컬럼 목록 (좌측 패널) - * - 현재 테이블에서 input_type='category'인 컬럼들을 표시 (테이블 스코프) + * - 현재 테이블에서 input_type='category'인 컬럼들을 표시 (메뉴 스코프) */ -export function CategoryColumnList({ tableName, selectedColumn, onColumnSelect }: CategoryColumnListProps) { +export function CategoryColumnList({ tableName, selectedColumn, onColumnSelect, menuObjid }: CategoryColumnListProps) { const [columns, setColumns] = useState([]); const [isLoading, setIsLoading] = useState(false); @@ -89,7 +90,7 @@ export function CategoryColumnList({ tableName, selectedColumn, onColumnSelect } // 각 컬럼의 값 개수 가져오기 let valueCount = 0; try { - const valuesResult = await getCategoryValues(tableName, colName, false); + const valuesResult = await getCategoryValues(tableName, colName, false, menuObjid); if (valuesResult.success && valuesResult.data) { valueCount = valuesResult.data.length; } diff --git a/frontend/components/table-category/CategoryValueManager.tsx b/frontend/components/table-category/CategoryValueManager.tsx index 0b7eecc3..dfcbd045 100644 --- a/frontend/components/table-category/CategoryValueManager.tsx +++ b/frontend/components/table-category/CategoryValueManager.tsx @@ -29,6 +29,7 @@ interface CategoryValueManagerProps { columnName: string; columnLabel: string; onValueCountChange?: (count: number) => void; + menuObjid?: number; // 현재 메뉴 OBJID (메뉴 스코프) } export const CategoryValueManager: React.FC = ({ @@ -36,6 +37,7 @@ export const CategoryValueManager: React.FC = ({ columnName, columnLabel, onValueCountChange, + menuObjid, }) => { const { toast } = useToast(); const [values, setValues] = useState([]); @@ -81,7 +83,7 @@ export const CategoryValueManager: React.FC = ({ setIsLoading(true); try { // includeInactive: true로 비활성 값도 포함 - const response = await getCategoryValues(tableName, columnName, true); + const response = await getCategoryValues(tableName, columnName, true, menuObjid); if (response.success && response.data) { setValues(response.data); setFilteredValues(response.data); @@ -101,11 +103,23 @@ export const CategoryValueManager: React.FC = ({ const handleAddValue = async (newValue: TableCategoryValue) => { try { - const response = await addCategoryValue({ - ...newValue, - tableName, - columnName, - }); + if (!menuObjid) { + toast({ + title: "오류", + description: "메뉴 정보가 없습니다. 카테고리 값을 추가할 수 없습니다.", + variant: "destructive", + }); + return; + } + + const response = await addCategoryValue( + { + ...newValue, + tableName, + columnName, + }, + menuObjid + ); if (response.success && response.data) { await loadCategoryValues(); @@ -128,7 +142,7 @@ export const CategoryValueManager: React.FC = ({ title: "오류", description: error.message || "카테고리 값 추가에 실패했습니다", variant: "destructive", - }); + }); } }; diff --git a/frontend/lib/api/tableCategoryValue.ts b/frontend/lib/api/tableCategoryValue.ts index ec927ac9..ee42c859 100644 --- a/frontend/lib/api/tableCategoryValue.ts +++ b/frontend/lib/api/tableCategoryValue.ts @@ -21,19 +21,30 @@ export async function getCategoryColumns(tableName: string) { } /** - * 카테고리 값 목록 조회 (테이블 스코프) + * 카테고리 값 목록 조회 (메뉴 스코프) + * + * @param tableName 테이블명 + * @param columnName 컬럼명 + * @param includeInactive 비활성 값 포함 여부 + * @param menuObjid 메뉴 OBJID (선택사항, 제공 시 형제 메뉴의 카테고리 값 포함) */ export async function getCategoryValues( tableName: string, columnName: string, - includeInactive: boolean = false + includeInactive: boolean = false, + menuObjid?: number ) { try { + const params: any = { includeInactive }; + if (menuObjid) { + params.menuObjid = menuObjid; + } + const response = await apiClient.get<{ success: boolean; data: TableCategoryValue[]; }>(`/table-categories/${tableName}/${columnName}/values`, { - params: { includeInactive }, + params, }); return response.data; } catch (error: any) { @@ -43,14 +54,23 @@ export async function getCategoryValues( } /** - * 카테고리 값 추가 + * 카테고리 값 추가 (메뉴 스코프) + * + * @param value 카테고리 값 정보 + * @param menuObjid 메뉴 OBJID (필수) */ -export async function addCategoryValue(value: TableCategoryValue) { +export async function addCategoryValue( + value: TableCategoryValue, + menuObjid: number +) { try { const response = await apiClient.post<{ success: boolean; data: TableCategoryValue; - }>("/table-categories/values", value); + }>("/table-categories/values", { + ...value, + menuObjid, // ← menuObjid 포함 + }); return response.data; } catch (error: any) { console.error("카테고리 값 추가 실패:", error); diff --git a/frontend/lib/registry/DynamicComponentRenderer.tsx b/frontend/lib/registry/DynamicComponentRenderer.tsx index 19d61cb0..1791e9b0 100644 --- a/frontend/lib/registry/DynamicComponentRenderer.tsx +++ b/frontend/lib/registry/DynamicComponentRenderer.tsx @@ -98,6 +98,7 @@ export interface DynamicComponentRendererProps { screenId?: number; tableName?: string; menuId?: number; // 🆕 메뉴 ID (카테고리 관리 등에 필요) + menuObjid?: number; // 🆕 메뉴 OBJID (메뉴 스코프 - 카테고리/채번) selectedScreen?: any; // 🆕 화면 정보 전체 (menuId 등 추출용) userId?: string; // 🆕 현재 사용자 ID userName?: string; // 🆕 현재 사용자 이름 @@ -224,6 +225,7 @@ export const DynamicComponentRenderer: React.FC = onFormDataChange, tableName, menuId, // 🆕 메뉴 ID + menuObjid, // 🆕 메뉴 OBJID (메뉴 스코프) selectedScreen, // 🆕 화면 정보 onRefresh, onClose, @@ -319,6 +321,7 @@ export const DynamicComponentRenderer: React.FC = onChange: handleChange, // 개선된 onChange 핸들러 전달 tableName, menuId, // 🆕 메뉴 ID + menuObjid, // 🆕 메뉴 OBJID (메뉴 스코프) selectedScreen, // 🆕 화면 정보 onRefresh, onClose, diff --git a/frontend/lib/registry/components/text-input/TextInputConfigPanel.tsx b/frontend/lib/registry/components/text-input/TextInputConfigPanel.tsx index f487b320..817baf57 100644 --- a/frontend/lib/registry/components/text-input/TextInputConfigPanel.tsx +++ b/frontend/lib/registry/components/text-input/TextInputConfigPanel.tsx @@ -15,32 +15,65 @@ export interface TextInputConfigPanelProps { config: TextInputConfig; onChange: (config: Partial) => void; screenTableName?: string; // 🆕 현재 화면의 테이블명 + menuObjid?: number; // 🆕 메뉴 OBJID (사용자 선택) } /** * TextInput 설정 패널 * 컴포넌트의 설정값들을 편집할 수 있는 UI 제공 */ -export const TextInputConfigPanel: React.FC = ({ config, onChange, screenTableName }) => { +export const TextInputConfigPanel: React.FC = ({ config, onChange, screenTableName, menuObjid }) => { // 채번 규칙 목록 상태 const [numberingRules, setNumberingRules] = useState([]); const [loadingRules, setLoadingRules] = useState(false); + + // 부모 메뉴 목록 상태 (채번규칙 사용을 위한 선택) + const [parentMenus, setParentMenus] = useState([]); + const [selectedMenuObjid, setSelectedMenuObjid] = useState(menuObjid); + const [loadingMenus, setLoadingMenus] = useState(false); - // 채번 규칙 목록 로드 + // 부모 메뉴 목록 로드 (사용자 메뉴의 레벨 2만) + useEffect(() => { + const loadMenus = async () => { + setLoadingMenus(true); + try { + const { apiClient } = await import("@/lib/api/client"); + const response = await apiClient.get("/admin/menus"); + + if (response.data.success && response.data.data) { + const allMenus = response.data.data; + + // 사용자 메뉴(menu_type='1')의 레벨 2만 필터링 + const level2UserMenus = allMenus.filter((menu: any) => + menu.menu_type === '1' && menu.lev === 2 + ); + + setParentMenus(level2UserMenus); + console.log("✅ 부모 메뉴 로드 완료:", level2UserMenus.length, "개", level2UserMenus); + } + } catch (error) { + console.error("부모 메뉴 로드 실패:", error); + } finally { + setLoadingMenus(false); + } + }; + loadMenus(); + }, []); + + // 채번 규칙 목록 로드 (선택된 메뉴 기준) useEffect(() => { const loadRules = async () => { + // 메뉴가 선택되지 않았으면 로드하지 않음 + if (!selectedMenuObjid) { + console.log("⚠️ 메뉴가 선택되지 않아 채번 규칙을 로드하지 않습니다"); + setNumberingRules([]); + return; + } + setLoadingRules(true); try { - let response; - - // 🆕 테이블명이 있으면 테이블 기반 필터링, 없으면 전체 조회 - if (screenTableName) { - console.log("🔍 TextInputConfigPanel: 테이블 기반 채번 규칙 로드", { screenTableName }); - response = await getAvailableNumberingRulesForScreen(screenTableName); - } else { - console.log("🔍 TextInputConfigPanel: 전체 채번 규칙 로드 (테이블명 없음)"); - response = await getAvailableNumberingRules(); - } + console.log("🔍 선택된 메뉴 기반 채번 규칙 로드", { selectedMenuObjid }); + const response = await getAvailableNumberingRules(selectedMenuObjid); if (response.success && response.data) { setNumberingRules(response.data); @@ -48,6 +81,7 @@ export const TextInputConfigPanel: React.FC = ({ conf } } catch (error) { console.error("채번 규칙 목록 로드 실패:", error); + setNumberingRules([]); } finally { setLoadingRules(false); } @@ -57,7 +91,7 @@ export const TextInputConfigPanel: React.FC = ({ conf if (config.autoGeneration?.type === "numbering_rule") { loadRules(); } - }, [config.autoGeneration?.type, screenTableName]); + }, [config.autoGeneration?.type, selectedMenuObjid]); const handleChange = (key: keyof TextInputConfig, value: any) => { onChange({ [key]: value }); @@ -157,50 +191,100 @@ export const TextInputConfigPanel: React.FC = ({ conf {/* 채번 규칙 선택 */} {config.autoGeneration?.type === "numbering_rule" && ( -
- - { + const menuObjid = parseInt(value); + setSelectedMenuObjid(menuObjid); + console.log("✅ 메뉴 선택됨:", menuObjid); + }} + disabled={loadingMenus} + > + + + + + {parentMenus.length === 0 ? ( + + 사용 가능한 메뉴가 없습니다 - )) - )} - - -

- 현재 메뉴에서 사용 가능한 채번 규칙만 표시됩니다 -

-
+ ) : ( + parentMenus.map((menu) => ( + + {menu.menu_name_kor} + {menu.menu_name_eng && ( + + ({menu.menu_name_eng}) + + )} + + )) + )} + + +

+ 이 입력 필드가 어느 메뉴에 속할지 선택하세요 (해당 메뉴의 채번규칙이 적용됩니다) +

+
+ + {/* 채번 규칙 선택 (메뉴 선택 후) */} + {selectedMenuObjid ? ( +
+ + +

+ 선택된 메뉴 및 형제 메뉴에서 사용 가능한 채번 규칙만 표시됩니다 +

+
+ ) : ( +
+ 먼저 대상 메뉴를 선택하세요 +
+ )} + )}
)} diff --git a/카테고리_채번_메뉴스코프_전환_통합_계획서.md b/카테고리_채번_메뉴스코프_전환_통합_계획서.md new file mode 100644 index 00000000..ac8b0d79 --- /dev/null +++ b/카테고리_채번_메뉴스코프_전환_통합_계획서.md @@ -0,0 +1,1004 @@ +# 카테고리 및 채번규칙 메뉴 스코프 전환 통합 계획서 + +## 📋 현재 문제점 분석 + +### 테이블 기반 스코프의 근본적 한계 + +**현재 상황**: +- 카테고리 시스템: `table_column_category_values` 테이블에서 `table_name + column_name`으로 데이터 조회 +- 채번규칙 시스템: `numbering_rules` 테이블에서 `table_name`으로 데이터 조회 + +**발생하는 문제**: + +``` +영업관리 (menu_objid: 200) +├── 고객관리 (menu_objid: 201) - 테이블: customer_info +├── 계약관리 (menu_objid: 202) - 테이블: contract_info +├── 주문관리 (menu_objid: 203) - 테이블: order_info +└── 공통코드 관리 (menu_objid: 204) - 어떤 테이블 선택? +``` + +**문제 1**: 형제 메뉴 간 코드 공유 불가 +- 고객관리, 계약관리, 주문관리가 모두 다른 테이블 사용 +- 각 화면마다 **동일한 카테고리/채번규칙을 중복 생성**해야 함 +- "고객 유형" 같은 공통 카테고리를 3번 만들어야 함 + +**문제 2**: 공통코드 관리 화면 불가능 +- 영업관리 전체에서 사용할 공통코드를 관리하려면 +- 특정 테이블 하나를 선택해야 하는데 +- 그러면 다른 테이블을 사용하는 형제 메뉴에서 접근 불가 + +**문제 3**: 비효율적인 유지보수 +- 같은 코드를 여러 테이블에 중복 관리 +- 하나의 값을 수정하려면 모든 테이블에서 수정 필요 +- 데이터 불일치 발생 가능 + +--- + +## ✅ 해결 방안: 메뉴 기반 스코프 + +### 핵심 개념 + +**메뉴 계층 구조를 데이터 스코프로 사용**: +- 카테고리/채번규칙 생성 시 `menu_objid`를 기록 +- 같은 부모 메뉴를 가진 **형제 메뉴들**이 데이터를 공유 +- 테이블과 무관하게 메뉴 구조에 따라 스코프 결정 + +### 메뉴 스코프 규칙 + +``` +영업관리 (parent_id: 0, menu_objid: 200) +├── 고객관리 (parent_id: 200, menu_objid: 201) +├── 계약관리 (parent_id: 200, menu_objid: 202) +├── 주문관리 (parent_id: 200, menu_objid: 203) +└── 공통코드 관리 (parent_id: 200, menu_objid: 204) ← 여기서 생성 +``` + +**스코프 규칙**: +1. 204번 메뉴에서 카테고리 생성 → `menu_objid = 204`로 저장 +2. 형제 메뉴 (201, 202, 203, 204)에서 **모두 사용 가능** +3. 다른 부모의 메뉴 (예: 구매관리)에서는 사용 불가 + +### 이점 + +✅ **형제 메뉴 간 코드 공유**: 한 번 생성하면 모든 형제 메뉴에서 사용 +✅ **공통코드 관리 화면 가능**: 전용 메뉴에서 일괄 관리 +✅ **테이블 독립성**: 테이블이 달라도 같은 카테고리 사용 가능 +✅ **직관적인 관리**: 메뉴 구조가 곧 데이터 스코프 +✅ **유지보수 용이**: 한 곳에서 수정하면 모든 형제 메뉴에 반영 + +--- + +## 📐 데이터베이스 설계 + +### 1. 카테고리 시스템 마이그레이션 + +#### 기존 상태 +```sql +-- table_column_category_values 테이블 +table_name | column_name | value_code | company_code +customer_info | customer_type | REGULAR | COMPANY_A +customer_info | customer_type | VIP | COMPANY_A +``` + +**문제**: `contract_info` 테이블에서는 이 카테고리를 사용할 수 없음 + +#### 변경 후 +```sql +-- table_column_category_values 테이블에 menu_objid 추가 +table_name | column_name | value_code | menu_objid | company_code +customer_info | customer_type | REGULAR | 204 | COMPANY_A +customer_info | customer_type | VIP | 204 | COMPANY_A +``` + +**해결**: menu_objid=204의 형제 메뉴(201,202,203,204)에서 모두 사용 가능 + +#### 마이그레이션 SQL + +```sql +-- db/migrations/048_convert_category_to_menu_scope.sql + +-- 1. menu_objid 컬럼 추가 (NULL 허용) +ALTER TABLE table_column_category_values +ADD COLUMN IF NOT EXISTS menu_objid NUMERIC; + +COMMENT ON COLUMN table_column_category_values.menu_objid +IS '카테고리를 생성한 메뉴 OBJID (형제 메뉴에서 공유)'; + +-- 2. 기존 데이터에 임시 menu_objid 설정 +-- 첫 번째 메뉴의 objid를 가져와서 설정 +DO $$ +DECLARE + first_menu_objid NUMERIC; +BEGIN + SELECT objid INTO first_menu_objid FROM menu_info LIMIT 1; + + IF first_menu_objid IS NOT NULL THEN + UPDATE table_column_category_values + SET menu_objid = first_menu_objid + WHERE menu_objid IS NULL; + + RAISE NOTICE '기존 카테고리 데이터의 menu_objid를 %로 설정했습니다', first_menu_objid; + RAISE NOTICE '관리자가 수동으로 올바른 menu_objid로 변경해야 합니다'; + END IF; +END $$; + +-- 3. menu_objid를 NOT NULL로 변경 +ALTER TABLE table_column_category_values +ALTER COLUMN menu_objid SET NOT NULL; + +-- 4. 외래키 추가 +ALTER TABLE table_column_category_values +ADD CONSTRAINT fk_category_value_menu +FOREIGN KEY (menu_objid) REFERENCES menu_info(objid) +ON DELETE CASCADE; + +-- 5. 기존 UNIQUE 제약조건 삭제 +ALTER TABLE table_column_category_values +DROP CONSTRAINT IF EXISTS unique_category_value; + +ALTER TABLE table_column_category_values +DROP CONSTRAINT IF EXISTS table_column_category_values_table_name_column_name_value_key; + +-- 6. 새로운 UNIQUE 제약조건 추가 (menu_objid 포함) +ALTER TABLE table_column_category_values +ADD CONSTRAINT unique_category_value +UNIQUE (table_name, column_name, value_code, menu_objid, company_code); + +-- 7. 인덱스 추가 (성능 최적화) +CREATE INDEX IF NOT EXISTS idx_category_value_menu +ON table_column_category_values(menu_objid, table_name, column_name, company_code); + +CREATE INDEX IF NOT EXISTS idx_category_value_company +ON table_column_category_values(company_code, table_name, column_name); +``` + +### 2. 채번규칙 시스템 마이그레이션 + +#### 기존 상태 +```sql +-- numbering_rules 테이블 +rule_id | table_name | scope_type | company_code +ITEM_CODE | item_info | table | COMPANY_A +``` + +**문제**: `item_info` 테이블을 사용하는 화면에서만 이 규칙 사용 가능 + +#### 변경 후 +```sql +-- numbering_rules 테이블 (menu_objid 추가) +rule_id | table_name | scope_type | menu_objid | company_code +ITEM_CODE | item_info | menu | 204 | COMPANY_A +``` + +**해결**: menu_objid=204의 형제 메뉴에서 모두 사용 가능 + +#### 마이그레이션 SQL + +```sql +-- db/migrations/049_convert_numbering_to_menu_scope.sql + +-- 1. menu_objid 컬럼 추가 (이미 존재하면 스킵) +ALTER TABLE numbering_rules +ADD COLUMN IF NOT EXISTS menu_objid NUMERIC; + +COMMENT ON COLUMN numbering_rules.menu_objid +IS '채번규칙을 생성한 메뉴 OBJID (형제 메뉴에서 공유)'; + +-- 2. 기존 데이터 마이그레이션 +DO $$ +DECLARE + first_menu_objid NUMERIC; +BEGIN + SELECT objid INTO first_menu_objid FROM menu_info LIMIT 1; + + IF first_menu_objid IS NOT NULL THEN + -- scope_type='table'이고 menu_objid가 NULL인 규칙들을 + -- scope_type='menu'로 변경하고 임시 menu_objid 설정 + UPDATE numbering_rules + SET scope_type = 'menu', + menu_objid = first_menu_objid + WHERE scope_type = 'table' + AND menu_objid IS NULL; + + RAISE NOTICE '기존 채번규칙의 scope_type을 menu로 변경하고 menu_objid를 %로 설정했습니다', first_menu_objid; + RAISE NOTICE '관리자가 수동으로 올바른 menu_objid로 변경해야 합니다'; + END IF; +END $$; + +-- 3. 제약조건 수정 +-- menu 타입은 menu_objid 필수 +ALTER TABLE numbering_rules +DROP CONSTRAINT IF EXISTS check_menu_scope_requires_menu_objid; + +ALTER TABLE numbering_rules +ADD CONSTRAINT check_menu_scope_requires_menu_objid +CHECK ( + (scope_type != 'menu') OR + (scope_type = 'menu' AND menu_objid IS NOT NULL) +); + +-- 4. 외래키 추가 (menu_objid → menu_info.objid) +ALTER TABLE numbering_rules +DROP CONSTRAINT IF EXISTS fk_numbering_rule_menu; + +ALTER TABLE numbering_rules +ADD CONSTRAINT fk_numbering_rule_menu +FOREIGN KEY (menu_objid) REFERENCES menu_info(objid) +ON DELETE CASCADE; + +-- 5. 인덱스 추가 (성능 최적화) +CREATE INDEX IF NOT EXISTS idx_numbering_rules_menu +ON numbering_rules(menu_objid, company_code); +``` + +--- + +## 🔧 백엔드 구현 + +### 1. 공통 유틸리티: 형제 메뉴 조회 + +```typescript +// backend-node/src/services/menuService.ts (신규 파일) + +import { getPool } from "../database/db"; +import { logger } from "../utils/logger"; + +/** + * 메뉴의 형제 메뉴 OBJID 목록 조회 + * (같은 부모를 가진 메뉴들) + * + * @param menuObjid 현재 메뉴의 OBJID + * @returns 형제 메뉴 OBJID 배열 (자기 자신 포함) + */ +export async function getSiblingMenuObjids(menuObjid: number): Promise { + const pool = getPool(); + + try { + logger.info("형제 메뉴 조회 시작", { menuObjid }); + + // 1. 현재 메뉴의 부모 찾기 + const parentQuery = ` + SELECT parent_id FROM menu_info WHERE objid = $1 + `; + const parentResult = await pool.query(parentQuery, [menuObjid]); + + if (parentResult.rows.length === 0) { + logger.warn("메뉴를 찾을 수 없음", { menuObjid }); + return [menuObjid]; // 메뉴가 없으면 자기 자신만 + } + + const parentId = parentResult.rows[0].parent_id; + + if (!parentId || parentId === 0) { + // 최상위 메뉴인 경우 자기 자신만 + logger.info("최상위 메뉴 (형제 없음)", { menuObjid }); + return [menuObjid]; + } + + // 2. 같은 부모를 가진 형제 메뉴들 조회 + const siblingsQuery = ` + SELECT objid FROM menu_info WHERE parent_id = $1 ORDER BY objid + `; + const siblingsResult = await pool.query(siblingsQuery, [parentId]); + + const siblingObjids = siblingsResult.rows.map((row) => row.objid); + + logger.info("형제 메뉴 조회 완료", { + menuObjid, + parentId, + siblingCount: siblingObjids.length, + siblings: siblingObjids, + }); + + return siblingObjids; + } catch (error: any) { + logger.error("형제 메뉴 조회 실패", { menuObjid, error: error.message }); + // 에러 발생 시 안전하게 자기 자신만 반환 + return [menuObjid]; + } +} + +/** + * 여러 메뉴의 형제 메뉴 OBJID 합집합 조회 + * + * @param menuObjids 메뉴 OBJID 배열 + * @returns 모든 형제 메뉴 OBJID 배열 (중복 제거) + */ +export async function getAllSiblingMenuObjids( + menuObjids: number[] +): Promise { + if (!menuObjids || menuObjids.length === 0) { + return []; + } + + const allSiblings = new Set(); + + for (const objid of menuObjids) { + const siblings = await getSiblingMenuObjids(objid); + siblings.forEach((s) => allSiblings.add(s)); + } + + return Array.from(allSiblings).sort((a, b) => a - b); +} +``` + +### 2. 카테고리 서비스 수정 + +```typescript +// backend-node/src/services/tableCategoryValueService.ts + +import { getSiblingMenuObjids } from "./menuService"; + +class TableCategoryValueService { + /** + * 카테고리 값 목록 조회 (메뉴 스코프 적용) + */ + async getCategoryValues( + tableName: string, + columnName: string, + menuObjid: number, // ← 추가 + companyCode: string, + includeInactive: boolean = false + ): Promise { + logger.info("카테고리 값 조회 (메뉴 스코프)", { + tableName, + columnName, + menuObjid, + companyCode, + }); + + const pool = getPool(); + + // 1. 형제 메뉴 OBJID 조회 + const siblingObjids = await getSiblingMenuObjids(menuObjid); + + logger.info("형제 메뉴 OBJID 목록", { menuObjid, siblingObjids }); + + // 2. 카테고리 값 조회 (형제 메뉴 포함) + let query: string; + let params: any[]; + + if (companyCode === "*") { + // 최고 관리자: 모든 회사 데이터 조회 + 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", + company_code AS "companyCode", + menu_objid AS "menuObjid", + created_at AS "createdAt", + created_by AS "createdBy" + FROM table_column_category_values + WHERE table_name = $1 + AND column_name = $2 + AND menu_objid = ANY($3) -- ← 형제 메뉴 포함 + ${!includeInactive ? 'AND is_active = true' : ''} + ORDER BY value_order, value_label + `; + params = [tableName, columnName, siblingObjids]; + } else { + // 일반 회사: 자신의 데이터만 조회 + 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", + company_code AS "companyCode", + menu_objid AS "menuObjid", + created_at AS "createdAt", + created_by AS "createdBy" + FROM table_column_category_values + WHERE table_name = $1 + AND column_name = $2 + AND menu_objid = ANY($3) -- ← 형제 메뉴 포함 + AND company_code = $4 -- ← 회사별 필터링 + ${!includeInactive ? 'AND is_active = true' : ''} + ORDER BY value_order, value_label + `; + params = [tableName, columnName, siblingObjids, companyCode]; + } + + const result = await pool.query(query, params); + + logger.info(`카테고리 값 ${result.rows.length}개 조회 완료`); + + return result.rows; + } + + /** + * 카테고리 값 추가 (menu_objid 저장) + */ + async addCategoryValue( + value: TableCategoryValue, + menuObjid: number, // ← 추가 + companyCode: string, + userId: string + ): Promise { + logger.info("카테고리 값 추가 (메뉴 스코프)", { + tableName: value.tableName, + columnName: value.columnName, + valueCode: value.valueCode, + menuObjid, + companyCode, + }); + + const pool = getPool(); + + const query = ` + 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, + company_code, menu_objid, -- ← menu_objid 추가 + 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", + company_code AS "companyCode", + menu_objid AS "menuObjid", + created_at AS "createdAt", + created_by AS "createdBy" + `; + + const result = await pool.query(query, [ + 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, + companyCode, + menuObjid, // ← 카테고리 관리 화면의 menu_objid + userId, + ]); + + logger.info("카테고리 값 추가 성공", { + valueId: result.rows[0].valueId, + menuObjid, + }); + + return result.rows[0]; + } + + // 수정, 삭제 메서드도 동일하게 menuObjid 파라미터 추가 +} + +export default TableCategoryValueService; +``` + +### 3. 채번규칙 서비스 수정 + +```typescript +// backend-node/src/services/numberingRuleService.ts + +import { getSiblingMenuObjids } from "./menuService"; + +class NumberingRuleService { + /** + * 화면용 채번 규칙 조회 (메뉴 스코프 적용) + */ + async getAvailableRulesForScreen( + companyCode: string, + tableName: string, + menuObjid?: number + ): Promise { + logger.info("화면용 채번 규칙 조회 (메뉴 스코프)", { + companyCode, + tableName, + menuObjid, + }); + + const pool = getPool(); + + // 1. 형제 메뉴 OBJID 조회 + let siblingObjids: number[] = []; + if (menuObjid) { + siblingObjids = await getSiblingMenuObjids(menuObjid); + logger.info("형제 메뉴 OBJID 목록", { menuObjid, siblingObjids }); + } + + // 2. 채번 규칙 조회 (우선순위: menu > table > global) + let query: string; + let params: any[]; + + if (companyCode === "*") { + // 최고 관리자: 모든 회사 데이터 조회 (company_code="*" 제외) + query = ` + SELECT + rule_id AS "ruleId", + rule_name AS "ruleName", + description, + separator, + reset_period AS "resetPeriod", + current_sequence AS "currentSequence", + table_name AS "tableName", + column_name AS "columnName", + company_code AS "companyCode", + menu_objid AS "menuObjid", + scope_type AS "scopeType", + created_at AS "createdAt", + updated_at AS "updatedAt", + created_by AS "createdBy" + FROM numbering_rules + WHERE company_code != '*' + AND ( + ${ + siblingObjids.length > 0 + ? `(scope_type = 'menu' AND menu_objid = ANY($1)) OR` + : "" + } + (scope_type = 'table' AND table_name = $${siblingObjids.length > 0 ? 2 : 1}) + OR (scope_type = 'global' AND table_name IS NULL) + ) + ORDER BY + CASE scope_type + WHEN 'menu' THEN 1 + WHEN 'table' THEN 2 + WHEN 'global' THEN 3 + END, + created_at DESC + `; + params = siblingObjids.length > 0 ? [siblingObjids, tableName] : [tableName]; + } else { + // 일반 회사: 자신의 규칙만 조회 + query = ` + SELECT + rule_id AS "ruleId", + rule_name AS "ruleName", + description, + separator, + reset_period AS "resetPeriod", + current_sequence AS "currentSequence", + table_name AS "tableName", + column_name AS "columnName", + company_code AS "companyCode", + menu_objid AS "menuObjid", + scope_type AS "scopeType", + created_at AS "createdAt", + updated_at AS "updatedAt", + created_by AS "createdBy" + FROM numbering_rules + WHERE company_code = $1 + AND ( + ${ + siblingObjids.length > 0 + ? `(scope_type = 'menu' AND menu_objid = ANY($2)) OR` + : "" + } + (scope_type = 'table' AND table_name = $${siblingObjids.length > 0 ? 3 : 2}) + OR (scope_type = 'global' AND table_name IS NULL) + ) + ORDER BY + CASE scope_type + WHEN 'menu' THEN 1 + WHEN 'table' THEN 2 + WHEN 'global' THEN 3 + END, + created_at DESC + `; + params = siblingObjids.length > 0 + ? [companyCode, siblingObjids, tableName] + : [companyCode, tableName]; + } + + const result = await pool.query(query, params); + + // 각 규칙의 파트 정보 로드 + for (const rule of result.rows) { + const partsQuery = ` + SELECT + id, + part_order AS "order", + part_type AS "partType", + generation_method AS "generationMethod", + auto_config AS "autoConfig", + manual_config AS "manualConfig" + FROM numbering_rule_parts + WHERE rule_id = $1 + AND company_code = $2 + ORDER BY part_order + `; + + const partsResult = await pool.query(partsQuery, [ + rule.ruleId, + companyCode === "*" ? rule.companyCode : companyCode, + ]); + + rule.parts = partsResult.rows; + } + + logger.info(`화면용 채번 규칙 조회 완료: ${result.rows.length}개`); + + return result.rows; + } +} + +export default NumberingRuleService; +``` + +### 4. 컨트롤러 수정 + +```typescript +// backend-node/src/controllers/tableCategoryValueController.ts + +/** + * 카테고리 값 목록 조회 + */ +export async function getCategoryValues( + req: AuthenticatedRequest, + res: Response +): Promise { + try { + const { tableName, columnName } = req.params; + const { menuObjid, includeInactive } = req.query; // ← menuObjid 추가 + const companyCode = req.user!.companyCode; + + if (!menuObjid) { + res.status(400).json({ + success: false, + message: "menuObjid는 필수입니다", + }); + return; + } + + const service = new TableCategoryValueService(); + const values = await service.getCategoryValues( + tableName, + columnName, + Number(menuObjid), // ← menuObjid 전달 + companyCode, + includeInactive === "true" + ); + + res.json({ + success: true, + data: values, + }); + } catch (error: any) { + logger.error("카테고리 값 조회 실패:", error); + res.status(500).json({ + success: false, + message: "카테고리 값 조회 중 오류 발생", + error: error.message, + }); + } +} + +/** + * 카테고리 값 추가 + */ +export async function addCategoryValue( + req: AuthenticatedRequest, + res: Response +): Promise { + try { + const { menuObjid, ...value } = req.body; // ← menuObjid 추가 + const companyCode = req.user!.companyCode; + const userId = req.user!.userId; + + if (!menuObjid) { + res.status(400).json({ + success: false, + message: "menuObjid는 필수입니다", + }); + return; + } + + const service = new TableCategoryValueService(); + const newValue = await service.addCategoryValue( + value, + menuObjid, // ← menuObjid 전달 + companyCode, + userId + ); + + res.json({ + success: true, + data: newValue, + }); + } catch (error: any) { + logger.error("카테고리 값 추가 실패:", error); + res.status(500).json({ + success: false, + message: "카테고리 값 추가 중 오류 발생", + error: error.message, + }); + } +} +``` + +--- + +## 🎨 프론트엔드 구현 + +### 1. API 클라이언트 수정 + +```typescript +// frontend/lib/api/tableCategoryValue.ts + +/** + * 카테고리 값 목록 조회 (메뉴 스코프) + */ +export async function getCategoryValues( + tableName: string, + columnName: string, + menuObjid: number, // ← 추가 + includeInactive: boolean = false +) { + try { + const response = await apiClient.get<{ + success: boolean; + data: TableCategoryValue[]; + }>(`/table-categories/${tableName}/${columnName}/values`, { + params: { + menuObjid, // ← menuObjid 쿼리 파라미터 추가 + includeInactive, + }, + }); + return response.data; + } catch (error: any) { + console.error("카테고리 값 조회 실패:", error); + return { success: false, error: error.message }; + } +} + +/** + * 카테고리 값 추가 + */ +export async function addCategoryValue( + value: TableCategoryValue, + menuObjid: number // ← 추가 +) { + try { + const response = await apiClient.post<{ + success: boolean; + data: TableCategoryValue; + }>("/table-categories/values", { + ...value, + menuObjid, // ← menuObjid 포함 + }); + return response.data; + } catch (error: any) { + console.error("카테고리 값 추가 실패:", error); + return { success: false, error: error.message }; + } +} +``` + +### 2. 화면관리 시스템에서 menuObjid 전달 + +```typescript +// frontend/components/screen/ScreenDesigner.tsx + +export function ScreenDesigner() { + const [selectedScreen, setSelectedScreen] = useState(null); + + // 선택된 화면의 menuObjid 추출 + const currentMenuObjid = selectedScreen?.menuObjid; + + return ( +
+ {/* 모든 카테고리/채번 관련 컴포넌트에 menuObjid 전달 */} + +
+ ); +} +``` + +### 3. 컴포넌트 props 수정 + +모든 카테고리/채번 관련 컴포넌트에 `menuObjid: number` prop 추가: + +- `CategoryColumnList` +- `CategoryValueManager` +- `NumberingRuleSelector` +- `TextTypeConfigPanel` + +--- + +## 📊 사용 시나리오 + +### 시나리오: 영업관리 공통코드 관리 + +#### 1단계: 메뉴 구조 + +``` +영업관리 (parent_id: 0, menu_objid: 200) +├── 고객관리 (parent_id: 200, menu_objid: 201) - customer_info 테이블 +├── 계약관리 (parent_id: 200, menu_objid: 202) - contract_info 테이블 +├── 주문관리 (parent_id: 200, menu_objid: 203) - order_info 테이블 +└── 공통코드 관리 (parent_id: 200, menu_objid: 204) - 카테고리 관리 전용 +``` + +#### 2단계: 카테고리 생성 + +1. **메뉴 등록**: 영업관리 > 공통코드 관리 (menu_objid: 204) +2. **화면 생성**: 화면관리 시스템에서 화면 생성 +3. **테이블 선택**: `customer_info` (어떤 테이블이든 상관없음) +4. **카테고리 값 추가**: + - 컬럼: `customer_type` + - 값: `REGULAR (일반 고객)`, `VIP (VIP 고객)` + - **저장 시 `menu_objid = 204`로 자동 저장** + +#### 3단계: 형제 메뉴에서 사용 + +**고객관리 화면** (menu_objid: 201): +- ✅ `customer_type` 드롭다운에 `일반 고객`, `VIP 고객` 표시 +- **이유**: 201과 204는 같은 부모(200)를 가진 형제 메뉴 + +**계약관리 화면** (menu_objid: 202): +- ✅ `customer_type` 컬럼에 동일한 카테고리 사용 가능 +- **이유**: 202와 204도 형제 메뉴 + +**구매관리 > 발주관리** (parent_id: 300): +- ❌ 영업관리의 카테고리는 표시되지 않음 +- **이유**: 다른 부모 메뉴이므로 스코프가 다름 + +--- + +## 📝 구현 순서 + +### Phase 1: 데이터베이스 마이그레이션 (1시간) + +- [ ] `048_convert_category_to_menu_scope.sql` 작성 및 실행 +- [ ] `049_convert_numbering_to_menu_scope.sql` 작성 및 실행 +- [ ] 기존 데이터 확인 및 임시 menu_objid 정리 계획 수립 + +### Phase 2: 백엔드 구현 (3-4시간) + +- [ ] `menuService.ts` 신규 파일 생성 (`getSiblingMenuObjids()` 함수) +- [ ] `tableCategoryValueService.ts` 수정 (menuObjid 파라미터 추가) +- [ ] `numberingRuleService.ts` 수정 (menuObjid 파라미터 추가) +- [ ] 컨트롤러 수정 (쿼리 파라미터에서 menuObjid 추출) +- [ ] 백엔드 테스트 + +### Phase 3: 프론트엔드 API 클라이언트 (1시간) + +- [ ] `tableCategoryValue.ts` API 클라이언트 수정 +- [ ] `numberingRule.ts` API 클라이언트 수정 + +### Phase 4: 프론트엔드 컴포넌트 (3-4시간) + +- [ ] `CategoryColumnList.tsx` 수정 (menuObjid prop 추가) +- [ ] `CategoryValueManager.tsx` 수정 (menuObjid prop 추가) +- [ ] `NumberingRuleSelector.tsx` 수정 (menuObjid prop 추가) +- [ ] `TextTypeConfigPanel.tsx` 수정 (menuObjid prop 추가) +- [ ] 모든 컴포넌트에서 API 호출 시 menuObjid 전달 + +### Phase 5: 화면관리 시스템 통합 (2시간) + +- [ ] `ScreenDesigner.tsx`에서 menuObjid 추출 및 전달 +- [ ] 카테고리 관리 화면 테스트 +- [ ] 채번규칙 설정 화면 테스트 + +### Phase 6: 테스트 및 문서화 (2시간) + +- [ ] 전체 플로우 테스트 +- [ ] 메뉴 스코프 동작 검증 +- [ ] 사용 가이드 작성 + +**총 예상 시간**: 12-15시간 + +--- + +## 🧪 테스트 체크리스트 + +### 데이터베이스 테스트 + +- [ ] 마이그레이션 정상 실행 확인 +- [ ] menu_objid 외래키 제약조건 확인 +- [ ] UNIQUE 제약조건 확인 (menu_objid 포함) +- [ ] 인덱스 생성 확인 + +### 백엔드 테스트 + +- [ ] `getSiblingMenuObjids()` 함수가 올바른 형제 메뉴 반환 +- [ ] 최상위 메뉴의 경우 자기 자신만 반환 +- [ ] 카테고리 값 조회 시 형제 메뉴의 값도 포함 +- [ ] 다른 부모 메뉴의 카테고리는 조회되지 않음 +- [ ] 멀티테넌시 필터링 정상 작동 + +### 프론트엔드 테스트 + +- [ ] 카테고리 컬럼 목록 정상 표시 +- [ ] 카테고리 값 목록 정상 표시 (형제 메뉴 포함) +- [ ] 카테고리 값 추가 시 menuObjid 포함 +- [ ] 채번규칙 목록 정상 표시 (형제 메뉴 포함) +- [ ] 모든 CRUD 작업 정상 작동 + +### 통합 테스트 + +- [ ] 영업관리 > 공통코드 관리에서 카테고리 생성 +- [ ] 영업관리 > 고객관리에서 카테고리 사용 가능 +- [ ] 영업관리 > 계약관리에서 카테고리 사용 가능 +- [ ] 구매관리에서는 영업관리 카테고리 사용 불가 +- [ ] 채번규칙도 동일하게 동작하는지 확인 + +--- + +## 💡 이점 요약 + +### 1. 형제 메뉴 간 데이터 공유 +- 같은 부서의 화면들이 카테고리/채번규칙 공유 +- 중복 생성 불필요 + +### 2. 공통코드 관리 화면 가능 +- 전용 메뉴에서 일괄 관리 +- 한 곳에서 수정하면 모든 형제 메뉴에 반영 + +### 3. 테이블 독립성 +- 테이블이 달라도 같은 카테고리 사용 가능 +- 테이블 구조 변경에 영향 없음 + +### 4. 직관적인 관리 +- 메뉴 구조가 곧 데이터 스코프 +- 이해하기 쉬운 권한 체계 + +### 5. 유지보수 용이 +- 한 곳에서 수정하면 자동 반영 +- 데이터 불일치 방지 + +--- + +## 🚀 다음 단계 + +### 1. 계획 승인 +이 계획서를 검토하고 승인받으면 바로 구현을 시작합니다. + +### 2. 단계별 구현 +Phase 1부터 순차적으로 구현하여 안정성 확보 + +### 3. 점진적 마이그레이션 +기존 데이터를 점진적으로 올바른 menu_objid로 정리 + +--- + +**이 계획서대로 구현하면 테이블 기반 스코프의 한계를 완전히 극복하고, 메뉴 구조 기반의 직관적인 데이터 관리 시스템을 구축할 수 있습니다.** + +구현을 시작할까요? + -- 2.43.0 From 23911d3dd857c1d866991d49c573154b2a63edbd Mon Sep 17 00:00:00 2001 From: kjs Date: Tue, 11 Nov 2025 14:44:22 +0900 Subject: [PATCH 05/13] =?UTF-8?q?feat:=20=EC=B9=B4=ED=85=8C=EA=B3=A0?= =?UTF-8?q?=EB=A6=AC=20=EC=BB=B4=ED=8F=AC=EB=84=8C=ED=8A=B8=20=EB=A9=94?= =?UTF-8?q?=EB=89=B4=20=EC=8A=A4=EC=BD=94=ED=94=84=20=EC=A0=84=ED=99=98=20?= =?UTF-8?q?=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ 구현 내용: 1. 백엔드 API 추가 - GET /api/table-management/menu/:menuObjid/category-columns - 형제 메뉴들의 테이블에서 카테고리 타입 컬럼 조회 - menuService.getSiblingMenuObjids() 재사용 2. 프론트엔드 CategoryWidget 수정 - menuObjid를 props로 받아 CategoryColumnList에 전달 - effectiveMenuObjid로 props.menuObjid도 처리 - 선택된 컬럼에 tableName 포함하여 상태 관리 3. CategoryColumnList 수정 - menuObjid 기반으로 형제 메뉴의 모든 카테고리 컬럼 조회 - 테이블명+컬럼명 함께 표시 - onColumnSelect에 tableName 전달 4. 메뉴 네비게이션 수정 - AppLayout.tsx: 화면 이동 시 menuObjid를 URL 쿼리 파라미터로 전달 - useMenu.ts: 동일하게 menuObjid 전달 - page.tsx: 자식 컴포넌트에도 menuObjid 전달 🎯 효과: - 이제 형제 메뉴들이 서로 다른 테이블을 사용해도 카테고리 공유 가능 - 메뉴 클릭 → 화면 이동 시 자동으로 menuObjid 전달 - 카테고리 위젯이 형제 메뉴의 모든 카테고리 컬럼 표시 --- .../controllers/tableManagementController.ts | 93 +++++++++++++ .../src/routes/tableManagementRoutes.ts | 11 ++ .../app/(main)/screens/[screenId]/page.tsx | 1 + frontend/components/layout/AppLayout.tsx | 12 +- .../screen/widgets/CategoryWidget.tsx | 52 +++++-- .../table-category/CategoryColumnList.tsx | 128 +++++++++--------- frontend/hooks/useMenu.ts | 3 +- 7 files changed, 218 insertions(+), 82 deletions(-) diff --git a/backend-node/src/controllers/tableManagementController.ts b/backend-node/src/controllers/tableManagementController.ts index 8b1f859d..45d888e1 100644 --- a/backend-node/src/controllers/tableManagementController.ts +++ b/backend-node/src/controllers/tableManagementController.ts @@ -1599,3 +1599,96 @@ export async function toggleLogTable( res.status(500).json(response); } } + +/** + * 메뉴의 형제 메뉴들이 사용하는 모든 테이블의 카테고리 타입 컬럼 조회 + * + * @route GET /api/table-management/menu/:menuObjid/category-columns + * @description 형제 메뉴들의 화면에서 사용하는 테이블의 input_type='category' 컬럼 조회 + */ +export async function getCategoryColumnsByMenu( + req: AuthenticatedRequest, + res: Response +): Promise { + try { + const { menuObjid } = req.params; + const companyCode = req.user?.companyCode; + + logger.info("📥 메뉴별 카테고리 컬럼 조회 요청", { menuObjid, companyCode }); + + if (!menuObjid) { + return res.status(400).json({ + success: false, + message: "메뉴 OBJID가 필요합니다.", + }); + } + + // 1. 형제 메뉴 조회 + const { getSiblingMenuObjids } = await import("../services/menuService"); + const siblingObjids = await getSiblingMenuObjids(parseInt(menuObjid)); + + logger.info("✅ 형제 메뉴 조회 완료", { siblingObjids }); + + // 2. 형제 메뉴들이 사용하는 테이블 조회 + const { getPool } = await import("../database/db"); + const pool = getPool(); + + const tablesQuery = ` + SELECT DISTINCT table_name + FROM screen_definitions + WHERE menu_objid = ANY($1) + AND company_code = $2 + AND table_name IS NOT NULL + `; + + const tablesResult = await pool.query(tablesQuery, [siblingObjids, companyCode]); + const tableNames = tablesResult.rows.map((row: any) => row.table_name); + + logger.info("✅ 형제 메뉴 테이블 조회 완료", { tableNames }); + + if (tableNames.length === 0) { + return res.json({ + success: true, + data: [], + message: "형제 메뉴에 연결된 테이블이 없습니다.", + }); + } + + // 3. 테이블들의 카테고리 타입 컬럼 조회 + const columnsQuery = ` + SELECT + table_name AS "tableName", + column_name AS "columnName", + column_label AS "columnLabel", + input_type AS "inputType" + FROM table_type_columns + WHERE table_name = ANY($1) + AND company_code = $2 + AND input_type = 'category' + ORDER BY table_name, column_name + `; + + const columnsResult = await pool.query(columnsQuery, [tableNames, companyCode]); + + logger.info("✅ 카테고리 컬럼 조회 완료", { + columnCount: columnsResult.rows.length + }); + + res.json({ + success: true, + data: columnsResult.rows, + message: "카테고리 컬럼 조회 성공", + }); + } catch (error: any) { + logger.error("❌ 메뉴별 카테고리 컬럼 조회 실패", { + error: error.message, + errorStack: error.stack, + }); + + res.status(500).json({ + success: false, + message: "카테고리 컬럼 조회에 실패했습니다.", + error: error.message, + }); + } +} diff --git a/backend-node/src/routes/tableManagementRoutes.ts b/backend-node/src/routes/tableManagementRoutes.ts index 0ec8c162..5ea98489 100644 --- a/backend-node/src/routes/tableManagementRoutes.ts +++ b/backend-node/src/routes/tableManagementRoutes.ts @@ -23,6 +23,7 @@ import { getLogConfig, getLogData, toggleLogTable, + getCategoryColumnsByMenu, // 🆕 메뉴별 카테고리 컬럼 조회 } from "../controllers/tableManagementController"; const router = express.Router(); @@ -187,4 +188,14 @@ router.get("/tables/:tableName/log", getLogData); */ router.post("/tables/:tableName/log/toggle", toggleLogTable); +// ======================================== +// 메뉴 기반 카테고리 관리 API +// ======================================== + +/** + * 메뉴의 형제 메뉴들이 사용하는 모든 테이블의 카테고리 타입 컬럼 조회 + * GET /api/table-management/menu/:menuObjid/category-columns + */ +router.get("/menu/:menuObjid/category-columns", getCategoryColumnsByMenu); + export default router; diff --git a/frontend/app/(main)/screens/[screenId]/page.tsx b/frontend/app/(main)/screens/[screenId]/page.tsx index 5c2c587b..6fc7bab8 100644 --- a/frontend/app/(main)/screens/[screenId]/page.tsx +++ b/frontend/app/(main)/screens/[screenId]/page.tsx @@ -473,6 +473,7 @@ export default function ScreenViewPage() { userId={user?.userId} userName={userName} companyCode={companyCode} + menuObjid={menuObjid} selectedRowsData={selectedRowsData} sortBy={tableSortBy} sortOrder={tableSortOrder} diff --git a/frontend/components/layout/AppLayout.tsx b/frontend/components/layout/AppLayout.tsx index 51c070cd..e87dc73d 100644 --- a/frontend/components/layout/AppLayout.tsx +++ b/frontend/components/layout/AppLayout.tsx @@ -274,10 +274,14 @@ function AppLayoutInner({ children }: AppLayoutProps) { // 할당된 화면이 있으면 첫 번째 화면으로 이동 const firstScreen = assignedScreens[0]; - // 관리자 모드 상태를 쿼리 파라미터로 전달 - const screenPath = isAdminMode - ? `/screens/${firstScreen.screenId}?mode=admin` - : `/screens/${firstScreen.screenId}`; + // 관리자 모드 상태와 menuObjid를 쿼리 파라미터로 전달 + const params = new URLSearchParams(); + if (isAdminMode) { + params.set("mode", "admin"); + } + params.set("menuObjid", menuObjid.toString()); + + const screenPath = `/screens/${firstScreen.screenId}?${params.toString()}`; router.push(screenPath); if (isMobile) { diff --git a/frontend/components/screen/widgets/CategoryWidget.tsx b/frontend/components/screen/widgets/CategoryWidget.tsx index 3e1c7f7b..2974ed60 100644 --- a/frontend/components/screen/widgets/CategoryWidget.tsx +++ b/frontend/components/screen/widgets/CategoryWidget.tsx @@ -6,20 +6,52 @@ import { CategoryValueManager } from "@/components/table-category/CategoryValueM import { GripVertical } from "lucide-react"; interface CategoryWidgetProps { - widgetId: string; - tableName: string; // 현재 화면의 테이블 - menuObjid?: number; // 현재 메뉴 OBJID (메뉴 스코프) + widgetId?: string; + tableName?: string; // 현재 화면의 테이블 (옵션 - 형제 메뉴 전체 표시) + menuObjid?: number; // 현재 메뉴 OBJID (메뉴 스코프) - 필수 + component?: any; // DynamicComponentRenderer에서 전달되는 컴포넌트 정보 + [key: string]: any; // 추가 props 허용 } /** * 카테고리 관리 위젯 (좌우 분할) - * - 좌측: 현재 테이블의 카테고리 타입 컬럼 목록 + * - 좌측: 형제 메뉴들의 모든 카테고리 타입 컬럼 목록 (메뉴 스코프) * - 우측: 선택된 컬럼의 카테고리 값 관리 (메뉴 스코프) */ -export function CategoryWidget({ widgetId, tableName, menuObjid }: CategoryWidgetProps) { +export function CategoryWidget({ widgetId, tableName, menuObjid, component, ...props }: CategoryWidgetProps) { + // menuObjid가 없으면 경고 로그 + React.useEffect(() => { + console.log("🔍 CategoryWidget 받은 props:", { + widgetId, + tableName, + menuObjid, + hasComponent: !!component, + propsKeys: Object.keys(props), + propsMenuObjid: props.menuObjid, + allProps: { widgetId, tableName, menuObjid, ...props }, + }); + + if (!menuObjid && !props.menuObjid) { + console.warn("⚠️ CategoryWidget: menuObjid가 전달되지 않았습니다", { + component, + props, + allAvailableProps: { widgetId, tableName, menuObjid, ...props } + }); + } else { + console.log("✅ CategoryWidget 렌더링", { + widgetId, + tableName, + menuObjid: menuObjid || props.menuObjid + }); + } + }, [menuObjid, widgetId, tableName, component, props]); + // menuObjid 우선순위: 직접 전달된 값 > props에서 추출한 값 + const effectiveMenuObjid = menuObjid || props.menuObjid; + const [selectedColumn, setSelectedColumn] = useState<{ columnName: string; columnLabel: string; + tableName: string; } | null>(null); const [leftWidth, setLeftWidth] = useState(15); // 초기값 15% @@ -67,10 +99,10 @@ export function CategoryWidget({ widgetId, tableName, menuObjid }: CategoryWidge - setSelectedColumn({ columnName, columnLabel }) + onColumnSelect={(columnName, columnLabel, tableName) => + setSelectedColumn({ columnName, columnLabel, tableName }) } - menuObjid={menuObjid} + menuObjid={effectiveMenuObjid} />
@@ -86,10 +118,10 @@ export function CategoryWidget({ widgetId, tableName, menuObjid }: CategoryWidge
{selectedColumn ? ( ) : (
diff --git a/frontend/components/table-category/CategoryColumnList.tsx b/frontend/components/table-category/CategoryColumnList.tsx index db6af71c..0e25643e 100644 --- a/frontend/components/table-category/CategoryColumnList.tsx +++ b/frontend/components/table-category/CategoryColumnList.tsx @@ -6,6 +6,7 @@ import { getCategoryValues } from "@/lib/api/tableCategoryValue"; import { FolderTree, Loader2 } from "lucide-react"; interface CategoryColumn { + tableName: string; columnName: string; columnLabel: string; inputType: string; @@ -13,95 +14,84 @@ interface CategoryColumn { } interface CategoryColumnListProps { - tableName: string; + tableName: string; // 현재 화면의 테이블 (사용하지 않음 - 형제 메뉴 전체 표시) selectedColumn: string | null; - onColumnSelect: (columnName: string, columnLabel: string) => void; - menuObjid?: number; // 현재 메뉴 OBJID (메뉴 스코프) + onColumnSelect: (columnName: string, columnLabel: string, tableName: string) => void; + menuObjid?: number; // 현재 메뉴 OBJID (필수) } /** * 카테고리 컬럼 목록 (좌측 패널) - * - 현재 테이블에서 input_type='category'인 컬럼들을 표시 (메뉴 스코프) + * - 형제 메뉴들의 모든 카테고리 타입 컬럼을 표시 (메뉴 스코프) */ export function CategoryColumnList({ tableName, selectedColumn, onColumnSelect, menuObjid }: CategoryColumnListProps) { const [columns, setColumns] = useState([]); const [isLoading, setIsLoading] = useState(false); useEffect(() => { - loadCategoryColumns(); - }, [tableName]); + if (menuObjid) { + loadCategoryColumnsByMenu(); + } else { + console.warn("⚠️ menuObjid가 없어서 카테고리 컬럼을 로드할 수 없습니다"); + setColumns([]); + } + }, [menuObjid]); - const loadCategoryColumns = async () => { + const loadCategoryColumnsByMenu = async () => { setIsLoading(true); try { - // table_type_columns에서 input_type = 'category'인 컬럼 조회 - const response = await apiClient.get(`/table-management/tables/${tableName}/columns`); + console.log("🔍 형제 메뉴의 카테고리 컬럼 조회 시작", { menuObjid }); + + // 새 API: 형제 메뉴들의 카테고리 컬럼 조회 + const response = await apiClient.get(`/table-management/menu/${menuObjid}/category-columns`); - console.log("🔍 테이블 컬럼 API 응답:", { - tableName, + console.log("✅ 메뉴별 카테고리 컬럼 API 응답:", { + menuObjid, response: response.data, - type: typeof response.data, - isArray: Array.isArray(response.data), }); - // API 응답 구조 파싱 (여러 가능성 대응) - let allColumns: any[] = []; + let categoryColumns: 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; + if (response.data.success && response.data.data) { + categoryColumns = response.data.data; + } else if (Array.isArray(response.data)) { + categoryColumns = response.data; } else { console.warn("⚠️ 예상하지 못한 API 응답 구조:", response.data); - allColumns = []; + categoryColumns = []; } - 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("✅ 카테고리 컬럼:", { + console.log("✅ 카테고리 컬럼 파싱 완료:", { count: categoryColumns.length, columns: categoryColumns.map((c: any) => ({ - name: c.columnName || c.column_name, - type: c.inputType || c.input_type, + table: c.tableName, + column: c.columnName, + label: c.columnLabel, })), }); + // 각 컬럼의 값 개수 가져오기 const columnsWithCount = await Promise.all( categoryColumns.map(async (col: any) => { - const colName = col.columnName || col.column_name; - const colLabel = col.columnLabel || col.column_label || col.displayName || colName; + const colTable = col.tableName; + const colName = col.columnName; + const colLabel = col.columnLabel || colName; - // 각 컬럼의 값 개수 가져오기 let valueCount = 0; try { - const valuesResult = await getCategoryValues(tableName, colName, false, menuObjid); + const valuesResult = await getCategoryValues(colTable, colName, false, menuObjid); if (valuesResult.success && valuesResult.data) { valueCount = valuesResult.data.length; } } catch (error) { - console.error(`항목 개수 조회 실패 (${colName}):`, error); + console.error(`항목 개수 조회 실패 (${colTable}.${colName}):`, error); } return { + tableName: colTable, columnName: colName, columnLabel: colLabel, - inputType: col.inputType || col.input_type, + inputType: col.inputType, valueCount, }; }), @@ -112,7 +102,7 @@ export function CategoryColumnList({ tableName, selectedColumn, onColumnSelect, // 첫 번째 컬럼 자동 선택 if (columnsWithCount.length > 0 && !selectedColumn) { const firstCol = columnsWithCount[0]; - onColumnSelect(firstCol.columnName, firstCol.columnLabel); + onColumnSelect(firstCol.columnName, firstCol.columnLabel, firstCol.tableName); } } catch (error) { console.error("❌ 카테고리 컬럼 조회 실패:", error); @@ -153,27 +143,31 @@ export function CategoryColumnList({ tableName, selectedColumn, onColumnSelect,
- {columns.map((column) => ( -
onColumnSelect(column.columnName, column.columnLabel || column.columnName)} - className={`cursor-pointer rounded-lg border px-4 py-2 transition-all ${ - selectedColumn === column.columnName ? "border-primary bg-primary/10 shadow-sm" : "hover:bg-muted/50" - }`} - > -
- -
-

{column.columnLabel || column.columnName}

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

{column.columnLabel || column.columnName}

+

{column.tableName}

+
+ + {column.valueCount !== undefined ? `${column.valueCount}개` : "..."} +
- - {column.valueCount !== undefined ? `${column.valueCount}개` : "..."} -
-
- ))} + ); + })}
); diff --git a/frontend/hooks/useMenu.ts b/frontend/hooks/useMenu.ts index 48c93ce7..2258f6c4 100644 --- a/frontend/hooks/useMenu.ts +++ b/frontend/hooks/useMenu.ts @@ -176,7 +176,8 @@ export const useMenu = (user: any, authLoading: boolean) => { if (assignedScreens.length > 0) { // 할당된 화면이 있으면 첫 번째 화면으로 이동 const firstScreen = assignedScreens[0]; - router.push(`/screens/${firstScreen.screenId}`); + // menuObjid를 쿼리 파라미터로 전달 + router.push(`/screens/${firstScreen.screenId}?menuObjid=${menuObjid}`); return; } } -- 2.43.0 From e7ecd0a8634b2266eff40839504ac7a52e2eb118 Mon Sep 17 00:00:00 2001 From: kjs Date: Tue, 11 Nov 2025 14:47:25 +0900 Subject: [PATCH 06/13] =?UTF-8?q?fix:=20screen=5Fmenu=5Fassignments?= =?UTF-8?q?=EB=A5=BC=20=ED=86=B5=ED=95=B4=20=EB=A9=94=EB=89=B4=EB=B3=84=20?= =?UTF-8?q?=ED=85=8C=EC=9D=B4=EB=B8=94=20=EC=A1=B0=ED=9A=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ❌ 문제: - screen_definitions 테이블에 menu_objid 컬럼이 없음 - SQL 쿼리 실행 실패 (500 에러) ✅ 수정: - screen_menu_assignments와 screen_definitions를 JOIN하여 조회 - menu_objid → screen_id → table_name 경로로 데이터 조회 🎯 쿼리 구조: SELECT DISTINCT sd.table_name FROM screen_menu_assignments sma INNER JOIN screen_definitions sd ON sma.screen_id = sd.screen_id WHERE sma.menu_objid = ANY($1) AND sma.company_code = $2 AND sd.table_name IS NOT NULL --- .../src/controllers/tableManagementController.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/backend-node/src/controllers/tableManagementController.ts b/backend-node/src/controllers/tableManagementController.ts index 45d888e1..aaa5d124 100644 --- a/backend-node/src/controllers/tableManagementController.ts +++ b/backend-node/src/controllers/tableManagementController.ts @@ -1634,11 +1634,12 @@ export async function getCategoryColumnsByMenu( const pool = getPool(); const tablesQuery = ` - SELECT DISTINCT table_name - FROM screen_definitions - WHERE menu_objid = ANY($1) - AND company_code = $2 - AND table_name IS NOT NULL + SELECT DISTINCT sd.table_name + FROM screen_menu_assignments sma + INNER JOIN screen_definitions sd ON sma.screen_id = sd.screen_id + WHERE sma.menu_objid = ANY($1) + AND sma.company_code = $2 + AND sd.table_name IS NOT NULL `; const tablesResult = await pool.query(tablesQuery, [siblingObjids, companyCode]); -- 2.43.0 From abdb6b17f892f7623821e52e4b239b85e9fb4182 Mon Sep 17 00:00:00 2001 From: kjs Date: Tue, 11 Nov 2025 14:48:42 +0900 Subject: [PATCH 07/13] =?UTF-8?q?debug:=20=EC=B9=B4=ED=85=8C=EA=B3=A0?= =?UTF-8?q?=EB=A6=AC=20=EC=BB=AC=EB=9F=BC=20=EC=A1=B0=ED=9A=8C=20=EC=83=81?= =?UTF-8?q?=EC=84=B8=20=EB=A1=9C=EA=B9=85=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 테이블 조회 완료 후 count 추가 - 카테고리 컬럼 쿼리 실행 전/후 로깅 - 에러 발생 시 전체 스택 트레이스 출력 --- .../src/controllers/tableManagementController.ts | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/backend-node/src/controllers/tableManagementController.ts b/backend-node/src/controllers/tableManagementController.ts index aaa5d124..90d6131f 100644 --- a/backend-node/src/controllers/tableManagementController.ts +++ b/backend-node/src/controllers/tableManagementController.ts @@ -1645,7 +1645,7 @@ export async function getCategoryColumnsByMenu( const tablesResult = await pool.query(tablesQuery, [siblingObjids, companyCode]); const tableNames = tablesResult.rows.map((row: any) => row.table_name); - logger.info("✅ 형제 메뉴 테이블 조회 완료", { tableNames }); + logger.info("✅ 형제 메뉴 테이블 조회 완료", { tableNames, count: tableNames.length }); if (tableNames.length === 0) { return res.json({ @@ -1656,6 +1656,8 @@ export async function getCategoryColumnsByMenu( } // 3. 테이블들의 카테고리 타입 컬럼 조회 + logger.info("🔍 카테고리 컬럼 쿼리 준비", { tableNames, companyCode }); + const columnsQuery = ` SELECT table_name AS "tableName", @@ -1669,7 +1671,9 @@ export async function getCategoryColumnsByMenu( ORDER BY table_name, column_name `; + logger.info("🔍 카테고리 컬럼 쿼리 실행 중..."); const columnsResult = await pool.query(columnsQuery, [tableNames, companyCode]); + logger.info("✅ 카테고리 컬럼 쿼리 완료", { rowCount: columnsResult.rows.length }); logger.info("✅ 카테고리 컬럼 조회 완료", { columnCount: columnsResult.rows.length @@ -1681,15 +1685,16 @@ export async function getCategoryColumnsByMenu( message: "카테고리 컬럼 조회 성공", }); } catch (error: any) { - logger.error("❌ 메뉴별 카테고리 컬럼 조회 실패", { - error: error.message, - errorStack: error.stack, - }); + logger.error("❌ 메뉴별 카테고리 컬럼 조회 실패"); + logger.error("에러 메시지:", error.message); + logger.error("에러 스택:", error.stack); + logger.error("에러 전체:", error); res.status(500).json({ success: false, message: "카테고리 컬럼 조회에 실패했습니다.", error: error.message, + stack: error.stack, // 디버깅용 }); } } -- 2.43.0 From 6ebe551caaeb34e6503b0fd19e0dc041fb2c3953 Mon Sep 17 00:00:00 2001 From: kjs Date: Tue, 11 Nov 2025 15:00:03 +0900 Subject: [PATCH 08/13] =?UTF-8?q?feat:=20=EC=B9=B4=ED=85=8C=EA=B3=A0?= =?UTF-8?q?=EB=A6=AC=20=EC=BB=B4=ED=8F=AC=EB=84=8C=ED=8A=B8=20=EB=A9=94?= =?UTF-8?q?=EB=89=B4=20=EC=8A=A4=EC=BD=94=ED=94=84=20=EC=A0=84=ED=99=98=20?= =?UTF-8?q?=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 형제 메뉴의 카테고리 컬럼 조회 API 구현 - column_labels 테이블에서 컬럼 라벨 조회 - table_labels 테이블에서 테이블 라벨 조회 - 프론트엔드: 테이블명 대신 테이블 라벨 표시 - 카테고리 값 조회/추가 시 menuObjid 전달 --- .../controllers/tableManagementController.ts | 32 +++++++++++++------ .../table-category/CategoryColumnList.tsx | 4 ++- 2 files changed, 25 insertions(+), 11 deletions(-) diff --git a/backend-node/src/controllers/tableManagementController.ts b/backend-node/src/controllers/tableManagementController.ts index 90d6131f..3f599fa5 100644 --- a/backend-node/src/controllers/tableManagementController.ts +++ b/backend-node/src/controllers/tableManagementController.ts @@ -1655,20 +1655,32 @@ export async function getCategoryColumnsByMenu( }); } - // 3. 테이블들의 카테고리 타입 컬럼 조회 + // 3. 테이블들의 카테고리 타입 컬럼 조회 (테이블 라벨 포함) logger.info("🔍 카테고리 컬럼 쿼리 준비", { tableNames, companyCode }); const columnsQuery = ` SELECT - table_name AS "tableName", - column_name AS "columnName", - column_label AS "columnLabel", - input_type AS "inputType" - FROM table_type_columns - WHERE table_name = ANY($1) - AND company_code = $2 - AND input_type = 'category' - ORDER BY table_name, column_name + ttc.table_name AS "tableName", + COALESCE( + tl.table_label, + initcap(replace(ttc.table_name, '_', ' ')) + ) AS "tableLabel", + ttc.column_name AS "columnName", + COALESCE( + cl.column_label, + initcap(replace(ttc.column_name, '_', ' ')) + ) AS "columnLabel", + ttc.input_type AS "inputType" + FROM table_type_columns ttc + LEFT JOIN column_labels cl + ON ttc.table_name = cl.table_name + AND ttc.column_name = cl.column_name + LEFT JOIN table_labels tl + ON ttc.table_name = tl.table_name + WHERE ttc.table_name = ANY($1) + AND ttc.company_code = $2 + AND ttc.input_type = 'category' + ORDER BY ttc.table_name, ttc.column_name `; logger.info("🔍 카테고리 컬럼 쿼리 실행 중..."); diff --git a/frontend/components/table-category/CategoryColumnList.tsx b/frontend/components/table-category/CategoryColumnList.tsx index 0e25643e..08a33d90 100644 --- a/frontend/components/table-category/CategoryColumnList.tsx +++ b/frontend/components/table-category/CategoryColumnList.tsx @@ -7,6 +7,7 @@ import { FolderTree, Loader2 } from "lucide-react"; interface CategoryColumn { tableName: string; + tableLabel?: string; // 테이블 라벨 추가 columnName: string; columnLabel: string; inputType: string; @@ -89,6 +90,7 @@ export function CategoryColumnList({ tableName, selectedColumn, onColumnSelect, return { tableName: colTable, + tableLabel: col.tableLabel || colTable, // 테이블 라벨 추가 columnName: colName, columnLabel: colLabel, inputType: col.inputType, @@ -159,7 +161,7 @@ export function CategoryColumnList({ tableName, selectedColumn, onColumnSelect, />

{column.columnLabel || column.columnName}

-

{column.tableName}

+

{column.tableLabel || column.tableName}

{column.valueCount !== undefined ? `${column.valueCount}개` : "..."} -- 2.43.0 From 32d4575fb51fb46ba373d486b67549574bfd3655 Mon Sep 17 00:00:00 2001 From: kjs Date: Tue, 11 Nov 2025 15:25:07 +0900 Subject: [PATCH 09/13] =?UTF-8?q?feat:=20=EC=BD=94=EB=93=9C=20=EC=BB=B4?= =?UTF-8?q?=ED=8F=AC=EB=84=8C=ED=8A=B8=EC=97=90=20=EB=A9=94=EB=89=B4=20?= =?UTF-8?q?=EC=8A=A4=EC=BD=94=ED=94=84=20=EC=A0=81=EC=9A=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - useCodeOptions 훅에 menuObjid 파라미터 추가 - commonCodeApi.codes.getList에 menuObjid 전달 - SelectBasicComponent에서 menuObjid 받아서 useCodeOptions로 전달 - InteractiveScreenViewer에서 DynamicWebTypeRenderer로 menuObjid 전달 - 화면 페이지에서 RealtimePreview로 menuObjid 전달 이제 코드 위젯도 카테고리처럼 형제 메뉴별로 격리됩니다. --- .../src/controllers/commonCodeController.ts | 34 +++++++++++--- .../src/services/commonCodeService.ts | 45 ++++++++++++++----- .../app/(main)/screens/[screenId]/page.tsx | 2 + .../screen/InteractiveScreenViewer.tsx | 3 ++ .../screen/RealtimePreviewDynamic.tsx | 2 +- frontend/hooks/queries/useCodes.ts | 15 ++++--- frontend/lib/api/commonCode.ts | 3 +- .../select-basic/SelectBasicComponent.tsx | 4 +- 8 files changed, 84 insertions(+), 24 deletions(-) diff --git a/backend-node/src/controllers/commonCodeController.ts b/backend-node/src/controllers/commonCodeController.ts index 616e0c6c..b0db2059 100644 --- a/backend-node/src/controllers/commonCodeController.ts +++ b/backend-node/src/controllers/commonCodeController.ts @@ -20,8 +20,9 @@ export class CommonCodeController { */ async getCategories(req: AuthenticatedRequest, res: Response) { try { - const { search, isActive, page = "1", size = "20" } = req.query; + const { search, isActive, page = "1", size = "20", menuObjid } = req.query; const userCompanyCode = req.user?.companyCode; + const menuObjidNum = menuObjid ? Number(menuObjid) : undefined; const categories = await this.commonCodeService.getCategories( { @@ -35,7 +36,8 @@ export class CommonCodeController { page: parseInt(page as string), size: parseInt(size as string), }, - userCompanyCode + userCompanyCode, + menuObjidNum ); return res.json({ @@ -61,8 +63,9 @@ export class CommonCodeController { async getCodes(req: AuthenticatedRequest, res: Response) { try { const { categoryCode } = req.params; - const { search, isActive, page, size } = req.query; + const { search, isActive, page, size, menuObjid } = req.query; const userCompanyCode = req.user?.companyCode; + const menuObjidNum = menuObjid ? Number(menuObjid) : undefined; const result = await this.commonCodeService.getCodes( categoryCode, @@ -77,7 +80,8 @@ export class CommonCodeController { page: page ? parseInt(page as string) : undefined, size: size ? parseInt(size as string) : undefined, }, - userCompanyCode + userCompanyCode, + menuObjidNum ); // 프론트엔드가 기대하는 형식으로 데이터 변환 @@ -131,6 +135,7 @@ export class CommonCodeController { const categoryData: CreateCategoryData = req.body; const userId = req.user?.userId || "SYSTEM"; const companyCode = req.user?.companyCode || "*"; + const menuObjid = req.body.menuObjid; // 입력값 검증 if (!categoryData.categoryCode || !categoryData.categoryName) { @@ -140,10 +145,18 @@ export class CommonCodeController { }); } + if (!menuObjid) { + return res.status(400).json({ + success: false, + message: "메뉴 OBJID는 필수입니다.", + }); + } + const category = await this.commonCodeService.createCategory( categoryData, userId, - companyCode + companyCode, + Number(menuObjid) ); return res.status(201).json({ @@ -263,6 +276,7 @@ export class CommonCodeController { const codeData: CreateCodeData = req.body; const userId = req.user?.userId || "SYSTEM"; const companyCode = req.user?.companyCode || "*"; + const menuObjid = req.body.menuObjid; // 입력값 검증 if (!codeData.codeValue || !codeData.codeName) { @@ -272,11 +286,19 @@ export class CommonCodeController { }); } + if (!menuObjid) { + return res.status(400).json({ + success: false, + message: "메뉴 OBJID는 필수입니다.", + }); + } + const code = await this.commonCodeService.createCode( categoryCode, codeData, userId, - companyCode + companyCode, + Number(menuObjid) ); return res.status(201).json({ diff --git a/backend-node/src/services/commonCodeService.ts b/backend-node/src/services/commonCodeService.ts index 8c02a60d..7bf40b7d 100644 --- a/backend-node/src/services/commonCodeService.ts +++ b/backend-node/src/services/commonCodeService.ts @@ -66,7 +66,7 @@ export class CommonCodeService { /** * 카테고리 목록 조회 */ - async getCategories(params: GetCategoriesParams, userCompanyCode?: string) { + async getCategories(params: GetCategoriesParams, userCompanyCode?: string, menuObjid?: number) { try { const { search, isActive, page = 1, size = 20 } = params; @@ -74,6 +74,16 @@ export class CommonCodeService { const values: any[] = []; let paramIndex = 1; + // 메뉴별 필터링 (형제 메뉴 포함) + if (menuObjid) { + const { getSiblingMenuObjids } = await import('./menuService'); + const siblingMenuObjids = await getSiblingMenuObjids(menuObjid); + whereConditions.push(`menu_objid = ANY($${paramIndex})`); + values.push(siblingMenuObjids); + paramIndex++; + logger.info(`메뉴별 코드 카테고리 필터링: ${menuObjid}, 형제 메뉴: ${siblingMenuObjids.join(', ')}`); + } + // 회사별 필터링 (최고 관리자가 아닌 경우) if (userCompanyCode && userCompanyCode !== "*") { whereConditions.push(`company_code = $${paramIndex}`); @@ -142,7 +152,8 @@ export class CommonCodeService { async getCodes( categoryCode: string, params: GetCodesParams, - userCompanyCode?: string + userCompanyCode?: string, + menuObjid?: number ) { try { const { search, isActive, page = 1, size = 20 } = params; @@ -151,6 +162,16 @@ export class CommonCodeService { const values: any[] = [categoryCode]; let paramIndex = 2; + // 메뉴별 필터링 (형제 메뉴 포함) + if (menuObjid) { + const { getSiblingMenuObjids } = await import('./menuService'); + const siblingMenuObjids = await getSiblingMenuObjids(menuObjid); + whereConditions.push(`menu_objid = ANY($${paramIndex})`); + values.push(siblingMenuObjids); + paramIndex++; + logger.info(`메뉴별 코드 필터링: ${menuObjid}, 형제 메뉴: ${siblingMenuObjids.join(', ')}`); + } + // 회사별 필터링 (최고 관리자가 아닌 경우) if (userCompanyCode && userCompanyCode !== "*") { whereConditions.push(`company_code = $${paramIndex}`); @@ -212,14 +233,15 @@ export class CommonCodeService { async createCategory( data: CreateCategoryData, createdBy: string, - companyCode: string + companyCode: string, + menuObjid: number ) { try { const category = await queryOne( `INSERT INTO code_category (category_code, category_name, category_name_eng, description, sort_order, - is_active, company_code, created_by, updated_by, created_date, updated_date) - VALUES ($1, $2, $3, $4, $5, 'Y', $6, $7, $8, NOW(), NOW()) + is_active, menu_objid, company_code, created_by, updated_by, created_date, updated_date) + VALUES ($1, $2, $3, $4, $5, 'Y', $6, $7, $8, $9, NOW(), NOW()) RETURNING *`, [ data.categoryCode, @@ -227,6 +249,7 @@ export class CommonCodeService { data.categoryNameEng || null, data.description || null, data.sortOrder || 0, + menuObjid, companyCode, createdBy, createdBy, @@ -234,7 +257,7 @@ export class CommonCodeService { ); logger.info( - `카테고리 생성 완료: ${data.categoryCode} (회사: ${companyCode})` + `카테고리 생성 완료: ${data.categoryCode} (메뉴: ${menuObjid}, 회사: ${companyCode})` ); return category; } catch (error) { @@ -352,14 +375,15 @@ export class CommonCodeService { categoryCode: string, data: CreateCodeData, createdBy: string, - companyCode: string + companyCode: string, + menuObjid: number ) { try { const code = await queryOne( `INSERT INTO code_info (code_category, code_value, code_name, code_name_eng, description, sort_order, - is_active, company_code, created_by, updated_by, created_date, updated_date) - VALUES ($1, $2, $3, $4, $5, $6, 'Y', $7, $8, $9, NOW(), NOW()) + is_active, menu_objid, company_code, created_by, updated_by, created_date, updated_date) + VALUES ($1, $2, $3, $4, $5, $6, 'Y', $7, $8, $9, $10, NOW(), NOW()) RETURNING *`, [ categoryCode, @@ -368,6 +392,7 @@ export class CommonCodeService { data.codeNameEng || null, data.description || null, data.sortOrder || 0, + menuObjid, companyCode, createdBy, createdBy, @@ -375,7 +400,7 @@ export class CommonCodeService { ); logger.info( - `코드 생성 완료: ${categoryCode}.${data.codeValue} (회사: ${companyCode})` + `코드 생성 완료: ${categoryCode}.${data.codeValue} (메뉴: ${menuObjid}, 회사: ${companyCode})` ); return code; } catch (error) { diff --git a/frontend/app/(main)/screens/[screenId]/page.tsx b/frontend/app/(main)/screens/[screenId]/page.tsx index 6fc7bab8..1ca88d51 100644 --- a/frontend/app/(main)/screens/[screenId]/page.tsx +++ b/frontend/app/(main)/screens/[screenId]/page.tsx @@ -403,6 +403,7 @@ export default function ScreenViewPage() { isSelected={false} isDesignMode={false} onClick={() => {}} + menuObjid={menuObjid} screenId={screenId} tableName={screen?.tableName} userId={user?.userId} @@ -468,6 +469,7 @@ export default function ScreenViewPage() { isSelected={false} isDesignMode={false} onClick={() => {}} + menuObjid={menuObjid} screenId={screenId} tableName={screen?.tableName} userId={user?.userId} diff --git a/frontend/components/screen/InteractiveScreenViewer.tsx b/frontend/components/screen/InteractiveScreenViewer.tsx index 472049ff..9eab7004 100644 --- a/frontend/components/screen/InteractiveScreenViewer.tsx +++ b/frontend/components/screen/InteractiveScreenViewer.tsx @@ -57,6 +57,7 @@ interface InteractiveScreenViewerProps { id: number; tableName?: string; }; + menuObjid?: number; // 🆕 메뉴 OBJID (코드 스코프용) // 새로운 검증 관련 옵션들 enableEnhancedValidation?: boolean; tableColumns?: ColumnInfo[]; @@ -76,6 +77,7 @@ export const InteractiveScreenViewer: React.FC = ( onFormDataChange, hideLabel = false, screenInfo, + menuObjid, // 🆕 메뉴 OBJID enableEnhancedValidation = false, tableColumns = [], showValidationPanel = false, @@ -1117,6 +1119,7 @@ export const InteractiveScreenViewer: React.FC = ( required: required, placeholder: config?.placeholder || "코드를 선택하세요...", className: "w-full h-full", + menuObjid: menuObjid, // 🆕 메뉴 OBJID 전달 }} config={{ ...config, diff --git a/frontend/components/screen/RealtimePreviewDynamic.tsx b/frontend/components/screen/RealtimePreviewDynamic.tsx index 1f220586..9ae2db82 100644 --- a/frontend/components/screen/RealtimePreviewDynamic.tsx +++ b/frontend/components/screen/RealtimePreviewDynamic.tsx @@ -41,7 +41,7 @@ interface RealtimePreviewProps { userId?: string; // 🆕 현재 사용자 ID userName?: string; // 🆕 현재 사용자 이름 companyCode?: string; // 🆕 현재 사용자의 회사 코드 - menuObjid?: number; // 🆕 현재 메뉴 OBJID (메뉴 스코프) + menuObjid?: number; // 🆕 메뉴 OBJID (코드/카테고리 스코프용) selectedRowsData?: any[]; onSelectedRowsChange?: (selectedRows: any[], selectedRowsData: any[]) => void; flowSelectedData?: any[]; diff --git a/frontend/hooks/queries/useCodes.ts b/frontend/hooks/queries/useCodes.ts index 14c6ee5d..0b95f907 100644 --- a/frontend/hooks/queries/useCodes.ts +++ b/frontend/hooks/queries/useCodes.ts @@ -51,14 +51,19 @@ export function useTableCodeCategory(tableName?: string, columnName?: string) { } // 코드 옵션 조회 (select용) -export function useCodeOptions(codeCategory?: string, enabled: boolean = true) { +export function useCodeOptions(codeCategory?: string, enabled: boolean = true, menuObjid?: number) { const query = useQuery({ - queryKey: queryKeys.codes.options(codeCategory || ""), + queryKey: menuObjid + ? [...queryKeys.codes.options(codeCategory || ""), 'menu', menuObjid] + : queryKeys.codes.options(codeCategory || ""), queryFn: async () => { if (!codeCategory || codeCategory === "none") return []; - console.log(`🔍 [React Query] 코드 옵션 조회: ${codeCategory}`); - const response = await commonCodeApi.codes.getList(codeCategory, { isActive: true }); + console.log(`🔍 [React Query] 코드 옵션 조회: ${codeCategory} (menuObjid: ${menuObjid})`); + const response = await commonCodeApi.codes.getList(codeCategory, { + isActive: true, + menuObjid + }); if (response.success && response.data) { const options = response.data.map((code: any) => { @@ -73,7 +78,7 @@ export function useCodeOptions(codeCategory?: string, enabled: boolean = true) { }; }); - console.log(`✅ [React Query] 코드 옵션 결과: ${codeCategory} (${options.length}개)`); + console.log(`✅ [React Query] 코드 옵션 결과: ${codeCategory} (${options.length}개, menuObjid: ${menuObjid})`); return options; } diff --git a/frontend/lib/api/commonCode.ts b/frontend/lib/api/commonCode.ts index 2f465880..c51edb11 100644 --- a/frontend/lib/api/commonCode.ts +++ b/frontend/lib/api/commonCode.ts @@ -66,13 +66,14 @@ export const commonCodeApi = { /** * 카테고리별 코드 목록 조회 */ - async getList(categoryCode: string, params?: GetCodesQuery): Promise> { + async getList(categoryCode: string, params?: GetCodesQuery & { menuObjid?: number }): Promise> { const searchParams = new URLSearchParams(); if (params?.search) searchParams.append("search", params.search); if (params?.isActive !== undefined) searchParams.append("isActive", params.isActive.toString()); if (params?.page !== undefined) searchParams.append("page", params.page.toString()); if (params?.size !== undefined) searchParams.append("size", params.size.toString()); + if (params?.menuObjid !== undefined) searchParams.append("menuObjid", params.menuObjid.toString()); const queryString = searchParams.toString(); const url = `/common-codes/categories/${categoryCode}/codes${queryString ? `?${queryString}` : ""}`; diff --git a/frontend/lib/registry/components/select-basic/SelectBasicComponent.tsx b/frontend/lib/registry/components/select-basic/SelectBasicComponent.tsx index c105e5ec..14580ce8 100644 --- a/frontend/lib/registry/components/select-basic/SelectBasicComponent.tsx +++ b/frontend/lib/registry/components/select-basic/SelectBasicComponent.tsx @@ -23,6 +23,7 @@ export interface SelectBasicComponentProps { onDragStart?: () => void; onDragEnd?: () => void; value?: any; // 외부에서 전달받는 값 + menuObjid?: number; // 🆕 메뉴 OBJID (코드 스코프용) [key: string]: any; } @@ -46,6 +47,7 @@ const SelectBasicComponent: React.FC = ({ onDragStart, onDragEnd, value: externalValue, // 명시적으로 value prop 받기 + menuObjid, // 🆕 메뉴 OBJID ...props }) => { // 🚨 최우선 디버깅: 컴포넌트가 실행되는지 확인 @@ -132,7 +134,7 @@ const SelectBasicComponent: React.FC = ({ options: codeOptions, isLoading: isLoadingCodes, isFetching, - } = useCodeOptions(codeCategory, isCodeCategoryValid); + } = useCodeOptions(codeCategory, isCodeCategoryValid, menuObjid); // React Query 상태 디버깅 useEffect(() => { -- 2.43.0 From 6534d03ecd7a2d7667b71f095d52dcfe8b33652d Mon Sep 17 00:00:00 2001 From: kjs Date: Tue, 11 Nov 2025 16:28:17 +0900 Subject: [PATCH 10/13] =?UTF-8?q?feat:=20=ED=99=94=EB=A9=B4=20=ED=8E=B8?= =?UTF-8?q?=EC=A7=91=EA=B8=B0=EC=97=90=EC=84=9C=20=EB=A9=94=EB=89=B4=20?= =?UTF-8?q?=EA=B8=B0=EB=B0=98=20=EB=8D=B0=EC=9D=B4=ED=84=B0=20=EC=8A=A4?= =?UTF-8?q?=EC=BD=94=ED=94=84=20=EC=A0=81=EC=9A=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 백엔드: screenManagementService에 getMenuByScreen 함수 추가 - 백엔드: GET /api/screen-management/screens/:id/menu 엔드포인트 추가 - 프론트엔드: screenApi.getScreenMenu() 함수 추가 - ScreenDesigner: 화면 로드 시 menu_objid 자동 조회 - ScreenDesigner: menuObjid를 RealtimePreview와 UnifiedPropertiesPanel에 전달 - UnifiedPropertiesPanel: menuObjid를 DynamicComponentConfigPanel에 전달 이로써 화면 편집기에서 코드/카테고리/채번규칙이 해당 화면이 할당된 메뉴 기준으로 필터링됨 --- .../controllers/numberingRuleController.ts | 23 +++- .../controllers/screenManagementController.ts | 23 ++++ .../src/routes/screenManagementRoutes.ts | 2 + .../src/services/commonCodeService.ts | 39 ++++++- .../src/services/numberingRuleService.ts | 24 ++-- .../src/services/screenManagementService.ts | 33 ++++++ .../numbering-rule/NumberingRuleDesigner.tsx | 32 ++++-- .../screen/InteractiveScreenViewer.tsx | 9 +- frontend/components/screen/ScreenDesigner.tsx | 14 +++ .../screen/panels/UnifiedPropertiesPanel.tsx | 5 + frontend/hooks/queries/useCodes.ts | 25 ++++- frontend/lib/api/screen.ts | 6 + .../numbering-rule/NumberingRuleComponent.tsx | 10 +- .../select-basic/SelectBasicComponent.tsx | 106 ++---------------- 14 files changed, 226 insertions(+), 125 deletions(-) diff --git a/backend-node/src/controllers/numberingRuleController.ts b/backend-node/src/controllers/numberingRuleController.ts index 1b2e2197..d00db2c4 100644 --- a/backend-node/src/controllers/numberingRuleController.ts +++ b/backend-node/src/controllers/numberingRuleController.ts @@ -112,6 +112,17 @@ router.post("/", authenticateToken, async (req: AuthenticatedRequest, res: Respo const userId = req.user!.userId; const ruleConfig = req.body; + logger.info("🔍 [POST /numbering-rules] 채번 규칙 생성 요청:", { + companyCode, + userId, + ruleId: ruleConfig.ruleId, + ruleName: ruleConfig.ruleName, + scopeType: ruleConfig.scopeType, + menuObjid: ruleConfig.menuObjid, + tableName: ruleConfig.tableName, + partsCount: ruleConfig.parts?.length, + }); + try { if (!ruleConfig.ruleId || !ruleConfig.ruleName) { return res.status(400).json({ success: false, error: "규칙 ID와 규칙명은 필수입니다" }); @@ -122,12 +133,22 @@ router.post("/", authenticateToken, async (req: AuthenticatedRequest, res: Respo } const newRule = await numberingRuleService.createRule(ruleConfig, companyCode, userId); + + logger.info("✅ [POST /numbering-rules] 채번 규칙 생성 성공:", { + ruleId: newRule.ruleId, + menuObjid: newRule.menuObjid, + }); + return res.status(201).json({ success: true, data: newRule }); } catch (error: any) { if (error.code === "23505") { return res.status(409).json({ success: false, error: "이미 존재하는 규칙 ID입니다" }); } - logger.error("규칙 생성 실패", { error: error.message }); + logger.error("❌ [POST /numbering-rules] 규칙 생성 실패:", { + error: error.message, + stack: error.stack, + code: error.code, + }); return res.status(500).json({ success: false, error: error.message }); } }); diff --git a/backend-node/src/controllers/screenManagementController.ts b/backend-node/src/controllers/screenManagementController.ts index f7900b94..95277664 100644 --- a/backend-node/src/controllers/screenManagementController.ts +++ b/backend-node/src/controllers/screenManagementController.ts @@ -60,6 +60,29 @@ export const getScreen = async ( } }; +// 화면에 할당된 메뉴 조회 +export const getScreenMenu = async ( + req: AuthenticatedRequest, + res: Response +): Promise => { + try { + const { id } = req.params; + const { companyCode } = req.user as any; + + const menuInfo = await screenManagementService.getMenuByScreen( + parseInt(id), + companyCode + ); + + res.json({ success: true, data: menuInfo }); + } catch (error) { + console.error("화면 메뉴 조회 실패:", error); + res + .status(500) + .json({ success: false, message: "화면 메뉴 조회에 실패했습니다." }); + } +}; + // 화면 생성 export const createScreen = async ( req: AuthenticatedRequest, diff --git a/backend-node/src/routes/screenManagementRoutes.ts b/backend-node/src/routes/screenManagementRoutes.ts index 3fed9129..e307ccc5 100644 --- a/backend-node/src/routes/screenManagementRoutes.ts +++ b/backend-node/src/routes/screenManagementRoutes.ts @@ -3,6 +3,7 @@ import { authenticateToken } from "../middleware/authMiddleware"; import { getScreens, getScreen, + getScreenMenu, createScreen, updateScreen, updateScreenInfo, @@ -33,6 +34,7 @@ router.use(authenticateToken); // 화면 관리 router.get("/screens", getScreens); router.get("/screens/:id", getScreen); +router.get("/screens/:id/menu", getScreenMenu); // 화면에 할당된 메뉴 조회 router.post("/screens", createScreen); router.put("/screens/:id", updateScreen); router.put("/screens/:id/info", updateScreenInfo); // 화면 정보만 수정 diff --git a/backend-node/src/services/commonCodeService.ts b/backend-node/src/services/commonCodeService.ts index 7bf40b7d..40c05861 100644 --- a/backend-node/src/services/commonCodeService.ts +++ b/backend-node/src/services/commonCodeService.ts @@ -158,6 +158,17 @@ export class CommonCodeService { try { const { search, isActive, page = 1, size = 20 } = params; + logger.info(`🔍 [getCodes] 코드 조회 시작:`, { + categoryCode, + menuObjid, + hasMenuObjid: !!menuObjid, + userCompanyCode, + search, + isActive, + page, + size, + }); + const whereConditions: string[] = ["code_category = $1"]; const values: any[] = [categoryCode]; let paramIndex = 2; @@ -169,7 +180,13 @@ export class CommonCodeService { whereConditions.push(`menu_objid = ANY($${paramIndex})`); values.push(siblingMenuObjids); paramIndex++; - logger.info(`메뉴별 코드 필터링: ${menuObjid}, 형제 메뉴: ${siblingMenuObjids.join(', ')}`); + logger.info(`📋 [getCodes] 메뉴별 코드 필터링:`, { + menuObjid, + siblingMenuObjids, + siblingCount: siblingMenuObjids.length, + }); + } else { + logger.warn(`⚠️ [getCodes] menuObjid 없음 - 전역 코드 조회`); } // 회사별 필터링 (최고 관리자가 아닌 경우) @@ -199,6 +216,13 @@ export class CommonCodeService { const offset = (page - 1) * size; + logger.info(`📝 [getCodes] 실행할 쿼리:`, { + whereClause, + values, + whereConditions, + paramIndex, + }); + // 코드 조회 const codes = await query( `SELECT * FROM code_info @@ -217,9 +241,20 @@ export class CommonCodeService { const total = parseInt(countResult?.count || "0"); logger.info( - `코드 조회 완료: ${categoryCode} - ${codes.length}개, 전체: ${total}개 (회사: ${userCompanyCode || "전체"})` + `✅ [getCodes] 코드 조회 완료: ${categoryCode} - ${codes.length}개, 전체: ${total}개 (회사: ${userCompanyCode || "전체"}, menuObjid: ${menuObjid || "없음"})` ); + logger.info(`📊 [getCodes] 조회된 코드 상세:`, { + categoryCode, + menuObjid, + codes: codes.map((c) => ({ + code_value: c.code_value, + code_name: c.code_name, + menu_objid: c.menu_objid, + company_code: c.company_code, + })), + }); + return { data: codes, total }; } catch (error) { logger.error(`코드 조회 중 오류 (${categoryCode}):`, error); diff --git a/backend-node/src/services/numberingRuleService.ts b/backend-node/src/services/numberingRuleService.ts index 2c89f188..4fb27e52 100644 --- a/backend-node/src/services/numberingRuleService.ts +++ b/backend-node/src/services/numberingRuleService.ts @@ -301,16 +301,18 @@ class NumberingRuleService { scope_type = 'global' OR scope_type = 'table' OR (scope_type = 'menu' AND menu_objid = ANY($1)) + OR (scope_type = 'table' AND menu_objid = ANY($1)) -- ⚠️ 임시: table 스코프도 menu_objid로 필터링 + OR (scope_type = 'table' AND menu_objid IS NULL) -- ⚠️ 임시: 기존 규칙(menu_objid NULL) 포함 ORDER BY - CASE scope_type - WHEN 'menu' THEN 1 - WHEN 'table' THEN 2 - WHEN 'global' THEN 3 + CASE + WHEN scope_type = 'menu' OR (scope_type = 'table' AND menu_objid = ANY($1)) THEN 1 + WHEN scope_type = 'table' THEN 2 + WHEN scope_type = 'global' THEN 3 END, created_at DESC `; params = [siblingObjids]; - logger.info("최고 관리자: 형제 메뉴 포함 채번 규칙 조회", { siblingObjids }); + logger.info("최고 관리자: 형제 메뉴 포함 채번 규칙 조회 (기존 규칙 포함)", { siblingObjids }); } else { // 일반 회사: 자신의 규칙만 조회 (형제 메뉴 포함) query = ` @@ -335,17 +337,19 @@ class NumberingRuleService { scope_type = 'global' OR scope_type = 'table' OR (scope_type = 'menu' AND menu_objid = ANY($2)) + OR (scope_type = 'table' AND menu_objid = ANY($2)) -- ⚠️ 임시: table 스코프도 menu_objid로 필터링 + OR (scope_type = 'table' AND menu_objid IS NULL) -- ⚠️ 임시: 기존 규칙(menu_objid NULL) 포함 ) ORDER BY - CASE scope_type - WHEN 'menu' THEN 1 - WHEN 'table' THEN 2 - WHEN 'global' THEN 3 + CASE + WHEN scope_type = 'menu' OR (scope_type = 'table' AND menu_objid = ANY($2)) THEN 1 + WHEN scope_type = 'table' THEN 2 + WHEN scope_type = 'global' THEN 3 END, created_at DESC `; params = [companyCode, siblingObjids]; - logger.info("회사별: 형제 메뉴 포함 채번 규칙 조회", { companyCode, siblingObjids }); + logger.info("회사별: 형제 메뉴 포함 채번 규칙 조회 (기존 규칙 포함)", { companyCode, siblingObjids }); } logger.info("🔍 채번 규칙 쿼리 실행", { diff --git a/backend-node/src/services/screenManagementService.ts b/backend-node/src/services/screenManagementService.ts index f3c3d133..9c125578 100644 --- a/backend-node/src/services/screenManagementService.ts +++ b/backend-node/src/services/screenManagementService.ts @@ -1547,6 +1547,39 @@ export class ScreenManagementService { return screens.map((screen) => this.mapToScreenDefinition(screen)); } + /** + * 화면에 할당된 메뉴 조회 (첫 번째 할당만 반환) + * 화면 편집기에서 menuObjid를 가져오기 위해 사용 + */ + async getMenuByScreen( + screenId: number, + companyCode: string + ): Promise<{ menuObjid: number; menuName?: string } | null> { + const result = await queryOne<{ + menu_objid: string; + menu_name_kor?: string; + }>( + `SELECT sma.menu_objid, mi.menu_name_kor + FROM screen_menu_assignments sma + LEFT JOIN menu_info mi ON sma.menu_objid = mi.objid + WHERE sma.screen_id = $1 + AND sma.company_code = $2 + AND sma.is_active = 'Y' + ORDER BY sma.created_at ASC + LIMIT 1`, + [screenId, companyCode] + ); + + if (!result) { + return null; + } + + return { + menuObjid: parseInt(result.menu_objid), + menuName: result.menu_name_kor, + }; + } + /** * 화면-메뉴 할당 해제 (✅ Raw Query 전환 완료) */ diff --git a/frontend/components/numbering-rule/NumberingRuleDesigner.tsx b/frontend/components/numbering-rule/NumberingRuleDesigner.tsx index 252f5403..0bd49982 100644 --- a/frontend/components/numbering-rule/NumberingRuleDesigner.tsx +++ b/frontend/components/numbering-rule/NumberingRuleDesigner.tsx @@ -12,7 +12,7 @@ import { NumberingRuleConfig, NumberingRulePart } from "@/types/numbering-rule"; import { NumberingRuleCard } from "./NumberingRuleCard"; import { NumberingRulePreview } from "./NumberingRulePreview"; import { - getNumberingRules, + getAvailableNumberingRules, createNumberingRule, updateNumberingRule, deleteNumberingRule, @@ -55,7 +55,20 @@ export const NumberingRuleDesigner: React.FC = ({ const loadRules = useCallback(async () => { setLoading(true); try { - const response = await getNumberingRules(menuObjid); + console.log("🔍 [NumberingRuleDesigner] 채번 규칙 목록 로드 시작:", { + menuObjid, + hasMenuObjid: !!menuObjid, + }); + + const response = await getAvailableNumberingRules(menuObjid); + + console.log("📦 [NumberingRuleDesigner] 채번 규칙 API 응답:", { + menuObjid, + success: response.success, + rulesCount: response.data?.length || 0, + rules: response.data, + }); + if (response.success && response.data) { setSavedRules(response.data); } else { @@ -135,17 +148,21 @@ export const NumberingRuleDesigner: React.FC = ({ try { const existing = savedRules.find((r) => r.ruleId === currentRule.ruleId); - // 저장 전에 현재 화면의 테이블명 자동 설정 + // 저장 전에 현재 화면의 테이블명과 menuObjid 자동 설정 const ruleToSave = { ...currentRule, - scopeType: "table" as const, // 항상 table로 고정 + scopeType: "table" as const, // ⚠️ 임시: DB 제약 조건 때문에 table 유지 tableName: currentTableName || currentRule.tableName || "", // 현재 테이블명 자동 설정 + menuObjid: menuObjid || currentRule.menuObjid || null, // 🆕 메뉴 OBJID 설정 (필터링용) }; console.log("💾 채번 규칙 저장:", { currentTableName, + menuObjid, "currentRule.tableName": currentRule.tableName, + "currentRule.menuObjid": currentRule.menuObjid, "ruleToSave.tableName": ruleToSave.tableName, + "ruleToSave.menuObjid": ruleToSave.menuObjid, "ruleToSave.scopeType": ruleToSave.scopeType, ruleToSave, }); @@ -215,7 +232,7 @@ export const NumberingRuleDesigner: React.FC = ({ ); const handleNewRule = useCallback(() => { - console.log("📋 새 규칙 생성 - currentTableName:", currentTableName); + console.log("📋 새 규칙 생성:", { currentTableName, menuObjid }); const newRule: NumberingRuleConfig = { ruleId: `rule-${Date.now()}`, @@ -224,8 +241,9 @@ export const NumberingRuleDesigner: React.FC = ({ separator: "-", resetPeriod: "none", currentSequence: 1, - scopeType: "table", // 기본값을 table로 설정 + scopeType: "table", // ⚠️ 임시: DB 제약 조건 때문에 table 유지 tableName: currentTableName || "", // 현재 화면의 테이블명 자동 설정 + menuObjid: menuObjid || null, // 🆕 메뉴 OBJID 설정 (필터링용) }; console.log("📋 생성된 규칙 정보:", newRule); @@ -234,7 +252,7 @@ export const NumberingRuleDesigner: React.FC = ({ setCurrentRule(newRule); toast.success("새 규칙이 생성되었습니다"); - }, [currentTableName]); + }, [currentTableName, menuObjid]); return (
diff --git a/frontend/components/screen/InteractiveScreenViewer.tsx b/frontend/components/screen/InteractiveScreenViewer.tsx index 9eab7004..d408fc93 100644 --- a/frontend/components/screen/InteractiveScreenViewer.tsx +++ b/frontend/components/screen/InteractiveScreenViewer.tsx @@ -1092,15 +1092,12 @@ export const InteractiveScreenViewer: React.FC = ( const widget = comp as WidgetComponent; const config = widget.webTypeConfig as CodeTypeConfig | undefined; - console.log("🔍 InteractiveScreenViewer - Code 위젯 (공통코드 선택):", { + console.log(`🔍 [InteractiveScreenViewer] Code 위젯 렌더링:`, { componentId: widget.id, - widgetType: widget.widgetType, columnName: widget.columnName, - fieldName, - currentValue, - formData, - config, codeCategory: config?.codeCategory, + menuObjid, + hasMenuObjid: !!menuObjid, }); // code 타입은 공통코드 선택박스로 처리 diff --git a/frontend/components/screen/ScreenDesigner.tsx b/frontend/components/screen/ScreenDesigner.tsx index 54f26a8d..fc412291 100644 --- a/frontend/components/screen/ScreenDesigner.tsx +++ b/frontend/components/screen/ScreenDesigner.tsx @@ -143,6 +143,9 @@ export default function ScreenDesigner({ selectedScreen, onBackToList }: ScreenD }); const [isSaving, setIsSaving] = useState(false); + // 🆕 화면에 할당된 메뉴 OBJID + const [menuObjid, setMenuObjid] = useState(undefined); + // 메뉴 할당 모달 상태 const [showMenuAssignmentModal, setShowMenuAssignmentModal] = useState(false); @@ -880,6 +883,15 @@ export default function ScreenDesigner({ selectedScreen, onBackToList }: ScreenD const loadLayout = async () => { try { + // 🆕 화면에 할당된 메뉴 조회 + const menuInfo = await screenApi.getScreenMenu(selectedScreen.screenId); + if (menuInfo) { + setMenuObjid(menuInfo.menuObjid); + console.log("🔗 화면에 할당된 메뉴:", menuInfo); + } else { + console.warn("⚠️ 화면에 할당된 메뉴가 없습니다"); + } + const response = await screenApi.getLayout(selectedScreen.screenId); if (response) { // 🔄 마이그레이션 필요 여부 확인 @@ -4205,6 +4217,7 @@ export default function ScreenDesigner({ selectedScreen, onBackToList }: ScreenD currentResolution={screenResolution} onResolutionChange={handleResolutionChange} allComponents={layout.components} // 🆕 플로우 위젯 감지용 + menuObjid={menuObjid} // 🆕 메뉴 OBJID 전달 /> @@ -4497,6 +4510,7 @@ export default function ScreenDesigner({ selectedScreen, onBackToList }: ScreenD onDragStart={(e) => startComponentDrag(component, e)} onDragEnd={endDrag} selectedScreen={selectedScreen} + menuObjid={menuObjid} // 🆕 메뉴 OBJID 전달 // onZoneComponentDrop 제거 onZoneClick={handleZoneClick} // 설정 변경 핸들러 (테이블 페이지 크기 등 설정을 상세설정에 반영) diff --git a/frontend/components/screen/panels/UnifiedPropertiesPanel.tsx b/frontend/components/screen/panels/UnifiedPropertiesPanel.tsx index 84297aa7..aa63e451 100644 --- a/frontend/components/screen/panels/UnifiedPropertiesPanel.tsx +++ b/frontend/components/screen/panels/UnifiedPropertiesPanel.tsx @@ -84,6 +84,8 @@ interface UnifiedPropertiesPanelProps { onResolutionChange?: (resolution: { name: string; width: number; height: number }) => void; // 🆕 플로우 위젯 감지용 allComponents?: ComponentData[]; + // 🆕 메뉴 OBJID (코드/카테고리 스코프용) + menuObjid?: number; } export const UnifiedPropertiesPanel: React.FC = ({ @@ -98,6 +100,7 @@ export const UnifiedPropertiesPanel: React.FC = ({ currentTableName, dragState, onStyleChange, + menuObjid, currentResolution, onResolutionChange, allComponents = [], // 🆕 기본값 빈 배열 @@ -685,6 +688,7 @@ export const UnifiedPropertiesPanel: React.FC = ({ screenTableName={selectedComponent.tableName || currentTable?.tableName || currentTableName} tableColumns={currentTable?.columns || []} tables={tables} + menuObjid={menuObjid} // 🆕 메뉴 OBJID 전달 onChange={(newConfig) => { console.log("🔄 DynamicComponentConfigPanel onChange:", newConfig); // 개별 속성별로 업데이트하여 다른 속성과의 충돌 방지 @@ -848,6 +852,7 @@ export const UnifiedPropertiesPanel: React.FC = ({ screenTableName={widget.tableName || currentTable?.tableName || currentTableName} tableColumns={currentTable?.columns || []} tables={tables} + menuObjid={menuObjid} // 🆕 메뉴 OBJID 전달 onChange={(newConfig) => { console.log("🔄 DynamicComponentConfigPanel onChange (widget):", newConfig); // 전체 componentConfig를 업데이트 diff --git a/frontend/hooks/queries/useCodes.ts b/frontend/hooks/queries/useCodes.ts index 0b95f907..470a4a60 100644 --- a/frontend/hooks/queries/useCodes.ts +++ b/frontend/hooks/queries/useCodes.ts @@ -33,7 +33,6 @@ export function useTableCodeCategory(tableName?: string, columnName?: string) { queryFn: async () => { if (!tableName || !columnName) return null; - console.log(`🔍 [React Query] 테이블 코드 카테고리 조회: ${tableName}.${columnName}`); const columns = await tableTypeApi.getColumns(tableName); const targetColumn = columns.find((col) => col.columnName === columnName); @@ -41,7 +40,6 @@ export function useTableCodeCategory(tableName?: string, columnName?: string) { ? targetColumn.codeCategory : null; - console.log(`✅ [React Query] 테이블 코드 카테고리 결과: ${tableName}.${columnName} -> ${codeCategory}`); return codeCategory; }, enabled: !!(tableName && columnName), @@ -59,12 +57,25 @@ export function useCodeOptions(codeCategory?: string, enabled: boolean = true, m queryFn: async () => { if (!codeCategory || codeCategory === "none") return []; - console.log(`🔍 [React Query] 코드 옵션 조회: ${codeCategory} (menuObjid: ${menuObjid})`); + console.log(`🔍 [useCodeOptions] 코드 옵션 조회 시작:`, { + codeCategory, + menuObjid, + hasMenuObjid: !!menuObjid, + }); + const response = await commonCodeApi.codes.getList(codeCategory, { isActive: true, menuObjid }); + console.log(`📦 [useCodeOptions] API 응답:`, { + codeCategory, + menuObjid, + success: response.success, + dataCount: response.data?.length || 0, + rawData: response.data, + }); + if (response.success && response.data) { const options = response.data.map((code: any) => { const actualValue = code.code || code.CODE || code.value || code.code_value || code.codeValue; @@ -78,7 +89,13 @@ export function useCodeOptions(codeCategory?: string, enabled: boolean = true, m }; }); - console.log(`✅ [React Query] 코드 옵션 결과: ${codeCategory} (${options.length}개, menuObjid: ${menuObjid})`); + console.log(`✅ [useCodeOptions] 옵션 변환 완료:`, { + codeCategory, + menuObjid, + optionsCount: options.length, + options, + }); + return options; } diff --git a/frontend/lib/api/screen.ts b/frontend/lib/api/screen.ts index d1d07d96..736e61b0 100644 --- a/frontend/lib/api/screen.ts +++ b/frontend/lib/api/screen.ts @@ -46,6 +46,12 @@ export const screenApi = { } as ScreenDefinition; }, + // 화면에 할당된 메뉴 조회 + getScreenMenu: async (screenId: number): Promise<{ menuObjid: number; menuName?: string } | null> => { + const response = await apiClient.get(`/screen-management/screens/${screenId}/menu`); + return response.data?.data || null; + }, + // 화면 생성 createScreen: async (screenData: CreateScreenRequest): Promise => { const response = await apiClient.post("/screen-management/screens", screenData); diff --git a/frontend/lib/registry/components/numbering-rule/NumberingRuleComponent.tsx b/frontend/lib/registry/components/numbering-rule/NumberingRuleComponent.tsx index 0c2e795c..6f1048f9 100644 --- a/frontend/lib/registry/components/numbering-rule/NumberingRuleComponent.tsx +++ b/frontend/lib/registry/components/numbering-rule/NumberingRuleComponent.tsx @@ -9,6 +9,7 @@ interface NumberingRuleWrapperProps { onChange?: (config: NumberingRuleComponentConfig) => void; isPreview?: boolean; tableName?: string; // 현재 화면의 테이블명 + menuObjid?: number; // 🆕 메뉴 OBJID } export const NumberingRuleWrapper: React.FC = ({ @@ -16,8 +17,14 @@ export const NumberingRuleWrapper: React.FC = ({ onChange, isPreview = false, tableName, + menuObjid, }) => { - console.log("📋 NumberingRuleWrapper: 테이블명 전달", { tableName, config }); + console.log("📋 NumberingRuleWrapper: 테이블명 + menuObjid 전달", { + tableName, + menuObjid, + hasMenuObjid: !!menuObjid, + config + }); return (
@@ -26,6 +33,7 @@ export const NumberingRuleWrapper: React.FC = ({ isPreview={isPreview} className="h-full" currentTableName={tableName} // 테이블명 전달 + menuObjid={menuObjid} // 🆕 메뉴 OBJID 전달 />
); diff --git a/frontend/lib/registry/components/select-basic/SelectBasicComponent.tsx b/frontend/lib/registry/components/select-basic/SelectBasicComponent.tsx index 14580ce8..2597a143 100644 --- a/frontend/lib/registry/components/select-basic/SelectBasicComponent.tsx +++ b/frontend/lib/registry/components/select-basic/SelectBasicComponent.tsx @@ -50,17 +50,6 @@ const SelectBasicComponent: React.FC = ({ menuObjid, // 🆕 메뉴 OBJID ...props }) => { - // 🚨 최우선 디버깅: 컴포넌트가 실행되는지 확인 - console.log("🚨🚨🚨 SelectBasicComponent 실행됨!!!", { - componentId: component?.id, - componentType: component?.type, - webType: component?.webType, - tableName: component?.tableName, - columnName: component?.columnName, - screenId, - timestamp: new Date().toISOString(), - }); - const [isOpen, setIsOpen] = useState(false); // webTypeConfig 또는 componentConfig 사용 (DynamicWebTypeRenderer 호환성) @@ -79,30 +68,6 @@ const SelectBasicComponent: React.FC = ({ // autocomplete의 경우 검색어 관리 const [searchQuery, setSearchQuery] = useState(""); - console.log("🔍 SelectBasicComponent 초기화 (React Query):", { - componentId: component.id, - externalValue, - componentConfigValue: componentConfig?.value, - webTypeConfigValue: (props as any).webTypeConfig?.value, - configValue: config?.value, - finalSelectedValue: externalValue || config?.value || "", - tableName: component.tableName, - columnName: component.columnName, - staticCodeCategory: config?.codeCategory, - // React Query 디버깅 정보 - timestamp: new Date().toISOString(), - mountCount: ++(window as any).selectMountCount || ((window as any).selectMountCount = 1), - }); - - // 언마운트 시 로깅 - useEffect(() => { - const componentId = component.id; - console.log(`🔍 [${componentId}] SelectBasicComponent 마운트됨`); - - return () => { - console.log(`🔍 [${componentId}] SelectBasicComponent 언마운트됨`); - }; - }, [component.id]); const selectRef = useRef(null); @@ -117,11 +82,6 @@ const SelectBasicComponent: React.FC = ({ // 코드 카테고리 결정: 동적 카테고리 > 설정 카테고리 (메모이제이션) const codeCategory = useMemo(() => { const category = dynamicCodeCategory || staticCodeCategory; - console.log(`🔑 [${component.id}] 코드 카테고리 결정:`, { - dynamicCodeCategory, - staticCodeCategory, - finalCategory: category, - }); return category; }, [dynamicCodeCategory, staticCodeCategory, component.id]); @@ -136,32 +96,25 @@ const SelectBasicComponent: React.FC = ({ isFetching, } = useCodeOptions(codeCategory, isCodeCategoryValid, menuObjid); - // React Query 상태 디버깅 + // 디버깅: menuObjid가 제대로 전달되는지 확인 useEffect(() => { - console.log(`🎯 [${component.id}] React Query 상태:`, { - codeCategory, - isCodeCategoryValid, - codeOptionsLength: codeOptions.length, - isLoadingCodes, - isFetching, - cacheStatus: isFetching ? "FETCHING" : "FROM_CACHE", - }); - }, [component.id, codeCategory, isCodeCategoryValid, codeOptions.length, isLoadingCodes, isFetching]); + if (codeCategory && codeCategory !== "none") { + console.log(`🎯 [SelectBasicComponent ${component.id}] 코드 옵션 로드:`, { + codeCategory, + menuObjid, + hasMenuObjid: !!menuObjid, + isCodeCategoryValid, + codeOptionsCount: codeOptions.length, + isLoading: isLoadingCodes, + }); + } + }, [component.id, codeCategory, menuObjid, codeOptions.length, isLoadingCodes, isCodeCategoryValid]); // 외부 value prop 변경 시 selectedValue 업데이트 useEffect(() => { const newValue = externalValue || config?.value || ""; // 값이 실제로 다른 경우에만 업데이트 (빈 문자열도 유효한 값으로 처리) if (newValue !== selectedValue) { - console.log(`🔄 SelectBasicComponent value 업데이트: "${selectedValue}" → "${newValue}"`); - console.log("🔍 업데이트 조건 분석:", { - externalValue, - componentConfigValue: componentConfig?.value, - configValue: config?.value, - newValue, - selectedValue, - shouldUpdate: newValue !== selectedValue, - }); setSelectedValue(newValue); } }, [externalValue, config?.value]); @@ -190,23 +143,12 @@ const SelectBasicComponent: React.FC = ({ const labelMatch = options.find((option) => option.label === selectedValue); if (labelMatch) { newLabel = labelMatch.label; - console.log(`🔍 [${component.id}] 코드명으로 매치 발견: "${selectedValue}" → "${newLabel}"`); } else { // 2) selectedValue가 코드값인 경우라면 원래 로직대로 라벨을 찾되, 없으면 원값 표시 newLabel = selectedValue; // 코드값 그대로 표시 (예: "555") - console.log(`🔍 [${component.id}] 코드값 원본 유지: "${selectedValue}"`); } } - console.log(`🏷️ [${component.id}] 라벨 업데이트:`, { - selectedValue, - selectedOption: selectedOption ? { value: selectedOption.value, label: selectedOption.label } : null, - newLabel, - optionsCount: options.length, - allOptionsValues: options.map((o) => o.value), - allOptionsLabels: options.map((o) => o.label), - }); - if (newLabel !== selectedLabel) { setSelectedLabel(newLabel); } @@ -216,15 +158,6 @@ const SelectBasicComponent: React.FC = ({ const handleToggle = () => { if (isDesignMode) return; - console.log(`🖱️ [${component.id}] 드롭다운 토글 (React Query): ${isOpen} → ${!isOpen}`); - console.log(`📊 [${component.id}] 현재 상태:`, { - codeCategory, - isLoadingCodes, - codeOptionsLength: codeOptions.length, - tableName: component.tableName, - columnName: component.columnName, - }); - // React Query가 자동으로 캐시 관리하므로 수동 새로고침 불필요 setIsOpen(!isOpen); }; @@ -242,17 +175,8 @@ const SelectBasicComponent: React.FC = ({ // 인터랙티브 모드에서 폼 데이터 업데이트 (TextInputComponent와 동일한 로직) if (isInteractive && onFormDataChange && component.columnName) { - console.log(`📤 SelectBasicComponent -> onFormDataChange 호출: ${component.columnName} = "${value}"`); onFormDataChange(component.columnName, value); - } else { - console.log("❌ SelectBasicComponent onFormDataChange 조건 미충족:", { - isInteractive, - hasOnFormDataChange: !!onFormDataChange, - hasColumnName: !!component.columnName, - }); } - - console.log(`✅ [${component.id}] 옵션 선택:`, { value, label }); }; // 외부 클릭 시 드롭다운 닫기 @@ -280,12 +204,6 @@ const SelectBasicComponent: React.FC = ({ // 모든 옵션 가져오기 const getAllOptions = () => { const configOptions = config.options || []; - console.log(`🔧 [${component.id}] 옵션 병합:`, { - codeOptionsLength: codeOptions.length, - codeOptions: codeOptions.map((o: Option) => ({ value: o.value, label: o.label })), - configOptionsLength: configOptions.length, - configOptions: configOptions.map((o: Option) => ({ value: o.value, label: o.label })), - }); return [...codeOptions, ...configOptions]; }; -- 2.43.0 From 84f3ae4e6f0ea317d2ba7a2e666904bbac4e07ba Mon Sep 17 00:00:00 2001 From: kjs Date: Tue, 11 Nov 2025 17:42:14 +0900 Subject: [PATCH 11/13] =?UTF-8?q?fix:=20screenManagementService=EC=97=90?= =?UTF-8?q?=EC=84=9C=20queryOne=20import=20=EB=88=84=EB=9D=BD=20=EC=88=98?= =?UTF-8?q?=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - queryOne 함수를 db.ts에서 import하여 getMenuByScreen 함수가 정상 작동하도록 수정 --- backend-node/src/services/screenManagementService.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend-node/src/services/screenManagementService.ts b/backend-node/src/services/screenManagementService.ts index 9c125578..50e62420 100644 --- a/backend-node/src/services/screenManagementService.ts +++ b/backend-node/src/services/screenManagementService.ts @@ -1,5 +1,5 @@ // ✅ Prisma → Raw Query 전환 (Phase 2.1) -import { query, transaction } from "../database/db"; +import { query, queryOne, transaction } from "../database/db"; import { ScreenDefinition, CreateScreenRequest, -- 2.43.0 From 35ec16084fe950cf6156f90d7754662a6085ba35 Mon Sep 17 00:00:00 2001 From: kjs Date: Tue, 11 Nov 2025 18:24:24 +0900 Subject: [PATCH 12/13] =?UTF-8?q?feat:=20=EC=B1=84=EB=B2=88=20=EA=B7=9C?= =?UTF-8?q?=EC=B9=99=20=EB=B0=8F=20=EC=BD=94=EB=93=9C=20=EB=A9=94=EB=89=B4?= =?UTF-8?q?=EB=B3=84=20=EA=B2=A9=EB=A6=AC=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **주요 변경사항:** 1. **메뉴 스코프 변경 (getSiblingMenuObjids)** - 기존: 형제 메뉴 + 모든 형제의 자식 메뉴 포함 - 변경: 자신 + 자신의 자식 메뉴만 포함 - 결과: 각 2레벨 메뉴가 완전히 독립적으로 격리됨 2. **채번 규칙 메뉴 선택 상태 유지** - useState 초기값 함수에서 저장된 selectedMenuObjid 복원 - 속성창 닫았다 열어도 선택한 메뉴와 채번 규칙 유지 - config.autoGeneration.selectedMenuObjid에 저장 3. **로그 정리** - 프론트엔드: 디버깅 로그 제거 - 백엔드: info 레벨 로그를 debug 레벨로 변경 - 운영 환경에서 불필요한 로그 출력 최소화 **영향:** - 영업관리 메뉴: 영업관리의 채번 규칙/코드만 조회 - 기준정보 메뉴: 기준정보의 채번 규칙/코드만 조회 - 각 메뉴 그룹이 독립적으로 데이터 관리 가능 --- .../controllers/numberingRuleController.ts | 2 +- backend-node/src/services/menuService.ts | 58 ++++++++----------- .../src/services/numberingRuleService.ts | 2 +- .../src/services/screenManagementService.ts | 2 +- .../text-input/TextInputConfigPanel.tsx | 30 ++++++---- .../lib/utils/getComponentConfigPanel.tsx | 3 + 6 files changed, 48 insertions(+), 49 deletions(-) diff --git a/backend-node/src/controllers/numberingRuleController.ts b/backend-node/src/controllers/numberingRuleController.ts index d00db2c4..55c19353 100644 --- a/backend-node/src/controllers/numberingRuleController.ts +++ b/backend-node/src/controllers/numberingRuleController.ts @@ -27,7 +27,7 @@ router.get("/available/:menuObjid?", authenticateToken, async (req: Authenticate const companyCode = req.user!.companyCode; const menuObjid = req.params.menuObjid ? parseInt(req.params.menuObjid) : undefined; - logger.info("📥 메뉴별 채번 규칙 조회 요청", { companyCode, menuObjid }); + logger.info("메뉴별 채번 규칙 조회 요청", { menuObjid, companyCode }); try { const rules = await numberingRuleService.getAvailableRulesForMenu(companyCode, menuObjid); diff --git a/backend-node/src/services/menuService.ts b/backend-node/src/services/menuService.ts index 9a9be99c..b22beb88 100644 --- a/backend-node/src/services/menuService.ts +++ b/backend-node/src/services/menuService.ts @@ -8,71 +8,59 @@ import { logger } from "../utils/logger"; */ /** - * 메뉴의 형제 메뉴 OBJID 목록 조회 - * (같은 부모를 가진 메뉴들) + * 메뉴의 형제 메뉴 및 자식 메뉴 OBJID 목록 조회 + * (같은 부모를 가진 메뉴들 + 자식 메뉴들) * * 메뉴 스코프 규칙: * - 같은 부모를 가진 형제 메뉴들은 카테고리/채번규칙을 공유 + * - 자식 메뉴의 데이터도 부모 메뉴에서 조회 가능 (3레벨까지만 존재) * - 최상위 메뉴(parent_obj_id = 0)는 자기 자신만 반환 * - 메뉴를 찾을 수 없으면 안전하게 자기 자신만 반환 * * @param menuObjid 현재 메뉴의 OBJID - * @returns 형제 메뉴 OBJID 배열 (자기 자신 포함, 정렬됨) + * @returns 형제 메뉴 + 자식 메뉴 OBJID 배열 (자기 자신 포함, 정렬됨) * * @example * // 영업관리 (200) * // ├── 고객관리 (201) + * // │ └── 고객등록 (211) * // ├── 계약관리 (202) * // └── 주문관리 (203) * * await getSiblingMenuObjids(201); - * // 결과: [201, 202, 203] - 모두 같은 부모(200)를 가진 형제 + * // 결과: [201, 202, 203, 211] - 형제(202, 203) + 자식(211) */ export async function getSiblingMenuObjids(menuObjid: number): Promise { const pool = getPool(); try { - logger.info("형제 메뉴 조회 시작", { menuObjid }); + logger.debug("메뉴 스코프 조회 시작", { menuObjid }); - // 1. 현재 메뉴의 부모 찾기 - const parentQuery = ` - SELECT parent_obj_id FROM menu_info WHERE objid = $1 - `; - const parentResult = await pool.query(parentQuery, [menuObjid]); + // 1. 현재 메뉴 자신을 포함 + const menuObjids = [menuObjid]; - if (parentResult.rows.length === 0) { - logger.warn("메뉴를 찾을 수 없음, 자기 자신만 반환", { menuObjid }); - return [menuObjid]; // 메뉴가 없으면 안전하게 자기 자신만 반환 - } - - const parentObjId = parentResult.rows[0].parent_obj_id; - - if (!parentObjId || parentObjId === 0) { - // 최상위 메뉴인 경우 자기 자신만 반환 - logger.info("최상위 메뉴 (형제 없음)", { menuObjid, parentObjId }); - return [menuObjid]; - } - - // 2. 같은 부모를 가진 형제 메뉴들 조회 - const siblingsQuery = ` + // 2. 현재 메뉴의 자식 메뉴들 조회 + const childrenQuery = ` SELECT objid FROM menu_info - WHERE parent_obj_id = $1 + WHERE parent_obj_id = $1 ORDER BY objid `; - const siblingsResult = await pool.query(siblingsQuery, [parentObjId]); + const childrenResult = await pool.query(childrenQuery, [menuObjid]); - const siblingObjids = siblingsResult.rows.map((row) => Number(row.objid)); + const childObjids = childrenResult.rows.map((row) => Number(row.objid)); - logger.info("형제 메뉴 조회 완료", { - menuObjid, - parentObjId, - siblingCount: siblingObjids.length, - siblings: siblingObjids, + // 3. 자신 + 자식을 합쳐서 정렬 + const allObjids = Array.from(new Set([...menuObjids, ...childObjids])).sort((a, b) => a - b); + + logger.debug("메뉴 스코프 조회 완료", { + menuObjid, + childCount: childObjids.length, + totalCount: allObjids.length }); - return siblingObjids; + return allObjids; } catch (error: any) { - logger.error("형제 메뉴 조회 실패", { + logger.error("메뉴 스코프 조회 실패", { menuObjid, error: error.message, stack: error.stack diff --git a/backend-node/src/services/numberingRuleService.ts b/backend-node/src/services/numberingRuleService.ts index 4fb27e52..db76bbee 100644 --- a/backend-node/src/services/numberingRuleService.ts +++ b/backend-node/src/services/numberingRuleService.ts @@ -360,7 +360,7 @@ class NumberingRuleService { const result = await pool.query(query, params); - logger.info("✅ 채번 규칙 쿼리 성공", { rowCount: result.rows.length }); + logger.debug("채번 규칙 쿼리 성공", { ruleCount: result.rows.length }); // 파트 정보 추가 for (const rule of result.rows) { diff --git a/backend-node/src/services/screenManagementService.ts b/backend-node/src/services/screenManagementService.ts index 50e62420..85081cd3 100644 --- a/backend-node/src/services/screenManagementService.ts +++ b/backend-node/src/services/screenManagementService.ts @@ -1565,7 +1565,7 @@ export class ScreenManagementService { WHERE sma.screen_id = $1 AND sma.company_code = $2 AND sma.is_active = 'Y' - ORDER BY sma.created_at ASC + ORDER BY sma.created_date ASC LIMIT 1`, [screenId, companyCode] ); diff --git a/frontend/lib/registry/components/text-input/TextInputConfigPanel.tsx b/frontend/lib/registry/components/text-input/TextInputConfigPanel.tsx index 817baf57..69088e96 100644 --- a/frontend/lib/registry/components/text-input/TextInputConfigPanel.tsx +++ b/frontend/lib/registry/components/text-input/TextInputConfigPanel.tsx @@ -29,7 +29,12 @@ export const TextInputConfigPanel: React.FC = ({ conf // 부모 메뉴 목록 상태 (채번규칙 사용을 위한 선택) const [parentMenus, setParentMenus] = useState([]); - const [selectedMenuObjid, setSelectedMenuObjid] = useState(menuObjid); + + // useState 초기값에서 저장된 값 복원 (우선순위: 저장된 값 > menuObjid prop) + const [selectedMenuObjid, setSelectedMenuObjid] = useState(() => { + return config.autoGeneration?.selectedMenuObjid || menuObjid; + }); + const [loadingMenus, setLoadingMenus] = useState(false); // 부모 메뉴 목록 로드 (사용자 메뉴의 레벨 2만) @@ -49,7 +54,6 @@ export const TextInputConfigPanel: React.FC = ({ conf ); setParentMenus(level2UserMenus); - console.log("✅ 부모 메뉴 로드 완료:", level2UserMenus.length, "개", level2UserMenus); } } catch (error) { console.error("부모 메뉴 로드 실패:", error); @@ -63,21 +67,23 @@ export const TextInputConfigPanel: React.FC = ({ conf // 채번 규칙 목록 로드 (선택된 메뉴 기준) useEffect(() => { const loadRules = async () => { + // autoGeneration.type이 numbering_rule이 아니면 로드하지 않음 + if (config.autoGeneration?.type !== "numbering_rule") { + return; + } + // 메뉴가 선택되지 않았으면 로드하지 않음 if (!selectedMenuObjid) { - console.log("⚠️ 메뉴가 선택되지 않아 채번 규칙을 로드하지 않습니다"); setNumberingRules([]); return; } setLoadingRules(true); try { - console.log("🔍 선택된 메뉴 기반 채번 규칙 로드", { selectedMenuObjid }); const response = await getAvailableNumberingRules(selectedMenuObjid); if (response.success && response.data) { setNumberingRules(response.data); - console.log("✅ 채번 규칙 로드 완료:", response.data.length, "개"); } } catch (error) { console.error("채번 규칙 목록 로드 실패:", error); @@ -87,11 +93,8 @@ export const TextInputConfigPanel: React.FC = ({ conf } }; - // autoGeneration.type이 numbering_rule일 때만 로드 - if (config.autoGeneration?.type === "numbering_rule") { - loadRules(); - } - }, [config.autoGeneration?.type, selectedMenuObjid]); + loadRules(); + }, [selectedMenuObjid, config.autoGeneration?.type]); const handleChange = (key: keyof TextInputConfig, value: any) => { onChange({ [key]: value }); @@ -202,7 +205,12 @@ export const TextInputConfigPanel: React.FC = ({ conf onValueChange={(value) => { const menuObjid = parseInt(value); setSelectedMenuObjid(menuObjid); - console.log("✅ 메뉴 선택됨:", menuObjid); + + // 컴포넌트 설정에 저장하여 언마운트 시에도 유지 + handleChange("autoGeneration", { + ...config.autoGeneration, + selectedMenuObjid: menuObjid, + }); }} disabled={loadingMenus} > diff --git a/frontend/lib/utils/getComponentConfigPanel.tsx b/frontend/lib/utils/getComponentConfigPanel.tsx index 9093a480..b4af1632 100644 --- a/frontend/lib/utils/getComponentConfigPanel.tsx +++ b/frontend/lib/utils/getComponentConfigPanel.tsx @@ -107,6 +107,7 @@ export interface ComponentConfigPanelProps { screenTableName?: string; // 화면에서 지정한 테이블명 tableColumns?: any[]; // 테이블 컬럼 정보 tables?: any[]; // 전체 테이블 목록 + menuObjid?: number; // 🆕 메뉴 OBJID (코드/카테고리/채번규칙 스코프용) } export const DynamicComponentConfigPanel: React.FC = ({ @@ -116,6 +117,7 @@ export const DynamicComponentConfigPanel: React.FC = screenTableName, tableColumns, tables, + menuObjid, }) => { // 모든 useState를 최상단에 선언 (Hooks 규칙) const [ConfigPanelComponent, setConfigPanelComponent] = React.useState | null>(null); @@ -259,6 +261,7 @@ export const DynamicComponentConfigPanel: React.FC = tables={tables} // 기본 테이블 목록 (현재 화면의 테이블만) allTables={componentId === "repeater-field-group" ? allTablesList : tables} // RepeaterConfigPanel만 전체 테이블 onTableChange={handleTableChange} // 테이블 변경 핸들러 전달 + menuObjid={menuObjid} // 🆕 메뉴 OBJID 전달 /> ); }; -- 2.43.0 From fef2f4a132e019d4facf703f68b1bf95582b875e Mon Sep 17 00:00:00 2001 From: kjs Date: Tue, 11 Nov 2025 18:27:27 +0900 Subject: [PATCH 13/13] =?UTF-8?q?fix:=20=ED=99=94=EB=A9=B4=20=ED=8E=B8?= =?UTF-8?q?=EC=A7=91=EA=B8=B0=EC=97=90=EC=84=9C=20=EB=B2=84=ED=8A=BC=20?= =?UTF-8?q?=EC=8A=A4=ED=83=80=EC=9D=BC=20=EC=8B=A4=EC=8B=9C=EA=B0=84=20?= =?UTF-8?q?=EB=B0=98=EC=98=81=20=EB=AC=B8=EC=A0=9C=20=ED=95=B4=EA=B2=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **문제:** - 화면 편집기에서 버튼의 스타일(색상, 폰트 등)을 변경해도 실시간으로 반영되지 않음 - 저장 후 실제 화면에서는 정상적으로 보임 **원인:** - ButtonPrimaryComponent에서 isInteractive 모드일 때만 component.style을 적용 - 디자인 모드(isDesignMode)에서는 사용자 정의 스타일이 무시됨 **해결:** - buttonElementStyle에 component.style을 항상 적용하도록 수정 - width/height는 레이아웃 충돌 방지를 위해 제외 유지 - 디자인 모드와 인터랙티브 모드 모두에서 스타일 실시간 반영 **영향:** - 화면 편집기에서 버튼 스타일 변경 시 즉시 미리보기 가능 - 저장하지 않아도 시각적 피드백 제공 --- .../components/button-primary/ButtonPrimaryComponent.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/frontend/lib/registry/components/button-primary/ButtonPrimaryComponent.tsx b/frontend/lib/registry/components/button-primary/ButtonPrimaryComponent.tsx index c66d11c4..183581ca 100644 --- a/frontend/lib/registry/components/button-primary/ButtonPrimaryComponent.tsx +++ b/frontend/lib/registry/components/button-primary/ButtonPrimaryComponent.tsx @@ -552,8 +552,8 @@ export const ButtonPrimaryComponent: React.FC = ({ margin: "0", lineHeight: "1.25", boxShadow: componentConfig.disabled ? "none" : "0 1px 2px 0 rgba(0, 0, 0, 0.05)", - // isInteractive 모드에서는 사용자 스타일 우선 적용 (width/height 제외) - ...(isInteractive && component.style ? Object.fromEntries( + // 디자인 모드와 인터랙티브 모드 모두에서 사용자 스타일 적용 (width/height 제외) + ...(component.style ? Object.fromEntries( Object.entries(component.style).filter(([key]) => key !== 'width' && key !== 'height') ) : {}), }; -- 2.43.0