diff --git a/backend-node/src/controllers/commonCodeController.ts b/backend-node/src/controllers/commonCodeController.ts index b0db2059..5b6b1453 100644 --- a/backend-node/src/controllers/commonCodeController.ts +++ b/backend-node/src/controllers/commonCodeController.ts @@ -94,7 +94,9 @@ export class CommonCodeController { sortOrder: code.sort_order, isActive: code.is_active, useYn: code.is_active, - companyCode: code.company_code, // 추가 + companyCode: code.company_code, + parentCodeValue: code.parent_code_value, // 계층구조: 부모 코드값 + depth: code.depth, // 계층구조: 깊이 // 기존 필드명도 유지 (하위 호환성) code_category: code.code_category, @@ -103,7 +105,9 @@ export class CommonCodeController { code_name_eng: code.code_name_eng, sort_order: code.sort_order, is_active: code.is_active, - company_code: code.company_code, // 추가 + company_code: code.company_code, + parent_code_value: code.parent_code_value, // 계층구조: 부모 코드값 + // depth는 위에서 이미 정의됨 (snake_case와 camelCase 동일) created_date: code.created_date, created_by: code.created_by, updated_date: code.updated_date, @@ -286,19 +290,17 @@ export class CommonCodeController { }); } - if (!menuObjid) { - return res.status(400).json({ - success: false, - message: "메뉴 OBJID는 필수입니다.", - }); - } + // menuObjid가 없으면 공통코드관리 메뉴의 기본 OBJID 사용 (전역 코드) + // 공통코드관리 메뉴 OBJID: 1757401858940 + const DEFAULT_CODE_MANAGEMENT_MENU_OBJID = 1757401858940; + const effectiveMenuObjid = menuObjid ? Number(menuObjid) : DEFAULT_CODE_MANAGEMENT_MENU_OBJID; const code = await this.commonCodeService.createCode( categoryCode, codeData, userId, companyCode, - Number(menuObjid) + effectiveMenuObjid ); return res.status(201).json({ @@ -588,4 +590,129 @@ export class CommonCodeController { }); } } + + /** + * 계층구조 코드 조회 + * GET /api/common-codes/categories/:categoryCode/hierarchy + * Query: parentCodeValue (optional), depth (optional), menuObjid (optional) + */ + async getHierarchicalCodes(req: AuthenticatedRequest, res: Response) { + try { + const { categoryCode } = req.params; + const { parentCodeValue, depth, menuObjid } = req.query; + const userCompanyCode = req.user?.companyCode; + const menuObjidNum = menuObjid ? Number(menuObjid) : undefined; + + // parentCodeValue가 빈 문자열이면 최상위 코드 조회 + const parentValue = parentCodeValue === '' || parentCodeValue === undefined + ? null + : parentCodeValue as string; + + const codes = await this.commonCodeService.getHierarchicalCodes( + categoryCode, + parentValue, + depth ? parseInt(depth as string) : undefined, + userCompanyCode, + menuObjidNum + ); + + // 프론트엔드 형식으로 변환 + const transformedData = codes.map((code: any) => ({ + codeValue: code.code_value, + codeName: code.code_name, + codeNameEng: code.code_name_eng, + description: code.description, + sortOrder: code.sort_order, + isActive: code.is_active, + parentCodeValue: code.parent_code_value, + depth: code.depth, + // 기존 필드도 유지 + code_category: code.code_category, + code_value: code.code_value, + code_name: code.code_name, + code_name_eng: code.code_name_eng, + sort_order: code.sort_order, + is_active: code.is_active, + parent_code_value: code.parent_code_value, + })); + + return res.json({ + success: true, + data: transformedData, + message: `계층구조 코드 조회 성공 (${categoryCode})`, + }); + } catch (error) { + logger.error(`계층구조 코드 조회 실패 (${req.params.categoryCode}):`, error); + return res.status(500).json({ + success: false, + message: "계층구조 코드 조회 중 오류가 발생했습니다.", + error: error instanceof Error ? error.message : "Unknown error", + }); + } + } + + /** + * 코드 트리 조회 + * GET /api/common-codes/categories/:categoryCode/tree + */ + async getCodeTree(req: AuthenticatedRequest, res: Response) { + try { + const { categoryCode } = req.params; + const { menuObjid } = req.query; + const userCompanyCode = req.user?.companyCode; + const menuObjidNum = menuObjid ? Number(menuObjid) : undefined; + + const result = await this.commonCodeService.getCodeTree( + categoryCode, + userCompanyCode, + menuObjidNum + ); + + return res.json({ + success: true, + data: result, + message: `코드 트리 조회 성공 (${categoryCode})`, + }); + } catch (error) { + logger.error(`코드 트리 조회 실패 (${req.params.categoryCode}):`, error); + return res.status(500).json({ + success: false, + message: "코드 트리 조회 중 오류가 발생했습니다.", + error: error instanceof Error ? error.message : "Unknown error", + }); + } + } + + /** + * 자식 코드 존재 여부 확인 + * GET /api/common-codes/categories/:categoryCode/codes/:codeValue/has-children + */ + async hasChildren(req: AuthenticatedRequest, res: Response) { + try { + const { categoryCode, codeValue } = req.params; + const companyCode = req.user?.companyCode; + + const hasChildren = await this.commonCodeService.hasChildren( + categoryCode, + codeValue, + companyCode + ); + + return res.json({ + success: true, + data: { hasChildren }, + message: "자식 코드 확인 완료", + }); + } catch (error) { + logger.error( + `자식 코드 확인 실패 (${req.params.categoryCode}.${req.params.codeValue}):`, + error + ); + return res.status(500).json({ + success: false, + message: "자식 코드 확인 중 오류가 발생했습니다.", + error: error instanceof Error ? error.message : "Unknown error", + }); + } + } } diff --git a/backend-node/src/routes/cascadingAutoFillRoutes.ts b/backend-node/src/routes/cascadingAutoFillRoutes.ts index 92036080..a5107448 100644 --- a/backend-node/src/routes/cascadingAutoFillRoutes.ts +++ b/backend-node/src/routes/cascadingAutoFillRoutes.ts @@ -54,3 +54,4 @@ export default router; + diff --git a/backend-node/src/routes/cascadingConditionRoutes.ts b/backend-node/src/routes/cascadingConditionRoutes.ts index ed11d3d1..22cd2d2b 100644 --- a/backend-node/src/routes/cascadingConditionRoutes.ts +++ b/backend-node/src/routes/cascadingConditionRoutes.ts @@ -50,3 +50,4 @@ export default router; + diff --git a/backend-node/src/routes/cascadingHierarchyRoutes.ts b/backend-node/src/routes/cascadingHierarchyRoutes.ts index d74929cb..79a1c6e8 100644 --- a/backend-node/src/routes/cascadingHierarchyRoutes.ts +++ b/backend-node/src/routes/cascadingHierarchyRoutes.ts @@ -66,3 +66,4 @@ export default router; + diff --git a/backend-node/src/routes/cascadingMutualExclusionRoutes.ts b/backend-node/src/routes/cascadingMutualExclusionRoutes.ts index ce2fbcac..352a05b5 100644 --- a/backend-node/src/routes/cascadingMutualExclusionRoutes.ts +++ b/backend-node/src/routes/cascadingMutualExclusionRoutes.ts @@ -54,3 +54,4 @@ export default router; + diff --git a/backend-node/src/routes/commonCodeRoutes.ts b/backend-node/src/routes/commonCodeRoutes.ts index 6772a6e9..d1205e51 100644 --- a/backend-node/src/routes/commonCodeRoutes.ts +++ b/backend-node/src/routes/commonCodeRoutes.ts @@ -46,6 +46,21 @@ router.put("/categories/:categoryCode/codes/reorder", (req, res) => commonCodeController.reorderCodes(req, res) ); +// 계층구조 코드 조회 (구체적인 경로를 먼저 배치) +router.get("/categories/:categoryCode/hierarchy", (req, res) => + commonCodeController.getHierarchicalCodes(req, res) +); + +// 코드 트리 조회 +router.get("/categories/:categoryCode/tree", (req, res) => + commonCodeController.getCodeTree(req, res) +); + +// 자식 코드 존재 여부 확인 +router.get("/categories/:categoryCode/codes/:codeValue/has-children", (req, res) => + commonCodeController.hasChildren(req, res) +); + router.put("/categories/:categoryCode/codes/:codeValue", (req, res) => commonCodeController.updateCode(req, res) ); diff --git a/backend-node/src/services/commonCodeService.ts b/backend-node/src/services/commonCodeService.ts index db19adc3..7c0d917a 100644 --- a/backend-node/src/services/commonCodeService.ts +++ b/backend-node/src/services/commonCodeService.ts @@ -25,6 +25,8 @@ export interface CodeInfo { is_active: string; company_code: string; menu_objid?: number | null; // 메뉴 기반 코드 관리용 + parent_code_value?: string | null; // 계층구조: 부모 코드값 + depth?: number; // 계층구조: 깊이 (1, 2, 3단계) created_date?: Date | null; created_by?: string | null; updated_date?: Date | null; @@ -61,6 +63,8 @@ export interface CreateCodeData { description?: string; sortOrder?: number; isActive?: string; + parentCodeValue?: string; // 계층구조: 부모 코드값 + depth?: number; // 계층구조: 깊이 (1, 2, 3단계) } export class CommonCodeService { @@ -405,11 +409,22 @@ export class CommonCodeService { menuObjid: number ) { try { + // 계층구조: depth 계산 (부모가 있으면 부모의 depth + 1, 없으면 1) + let depth = 1; + if (data.parentCodeValue) { + const parentCode = await queryOne( + `SELECT depth FROM code_info + WHERE code_category = $1 AND code_value = $2 AND company_code = $3`, + [categoryCode, data.parentCodeValue, companyCode] + ); + depth = parentCode ? (parentCode.depth || 1) + 1 : 1; + } + const code = await queryOne( `INSERT INTO code_info (code_category, code_value, code_name, code_name_eng, description, sort_order, - 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()) + is_active, menu_objid, company_code, parent_code_value, depth, created_by, updated_by, created_date, updated_date) + VALUES ($1, $2, $3, $4, $5, $6, 'Y', $7, $8, $9, $10, $11, $12, NOW(), NOW()) RETURNING *`, [ categoryCode, @@ -420,13 +435,15 @@ export class CommonCodeService { data.sortOrder || 0, menuObjid, companyCode, + data.parentCodeValue || null, + depth, createdBy, createdBy, ] ); logger.info( - `코드 생성 완료: ${categoryCode}.${data.codeValue} (메뉴: ${menuObjid}, 회사: ${companyCode})` + `코드 생성 완료: ${categoryCode}.${data.codeValue} (메뉴: ${menuObjid}, 회사: ${companyCode}, 부모: ${data.parentCodeValue || '없음'}, 깊이: ${depth})` ); return code; } catch (error) { @@ -491,6 +508,24 @@ export class CommonCodeService { updateFields.push(`is_active = $${paramIndex++}`); values.push(activeValue); } + // 계층구조: 부모 코드값 수정 + if (data.parentCodeValue !== undefined) { + updateFields.push(`parent_code_value = $${paramIndex++}`); + values.push(data.parentCodeValue || null); + + // depth도 함께 업데이트 + let newDepth = 1; + if (data.parentCodeValue) { + const parentCode = await queryOne( + `SELECT depth FROM code_info + WHERE code_category = $1 AND code_value = $2`, + [categoryCode, data.parentCodeValue] + ); + newDepth = parentCode ? (parentCode.depth || 1) + 1 : 1; + } + updateFields.push(`depth = $${paramIndex++}`); + values.push(newDepth); + } // WHERE 절 구성 let whereClause = `WHERE code_category = $${paramIndex++} AND code_value = $${paramIndex}`; @@ -847,4 +882,170 @@ export class CommonCodeService { throw error; } } + + /** + * 계층구조 코드 조회 (특정 depth 또는 부모코드 기준) + * @param categoryCode 카테고리 코드 + * @param parentCodeValue 부모 코드값 (없으면 최상위 코드만 조회) + * @param depth 특정 깊이만 조회 (선택) + */ + async getHierarchicalCodes( + categoryCode: string, + parentCodeValue?: string | null, + depth?: number, + userCompanyCode?: string, + menuObjid?: number + ) { + try { + const whereConditions: string[] = ["code_category = $1", "is_active = 'Y'"]; + const values: any[] = [categoryCode]; + let paramIndex = 2; + + // 부모 코드값 필터링 + if (parentCodeValue === null || parentCodeValue === undefined) { + // 최상위 코드 (부모가 없는 코드) + whereConditions.push("(parent_code_value IS NULL OR parent_code_value = '')"); + } else if (parentCodeValue !== '') { + whereConditions.push(`parent_code_value = $${paramIndex}`); + values.push(parentCodeValue); + paramIndex++; + } + + // 특정 깊이 필터링 + if (depth !== undefined) { + whereConditions.push(`depth = $${paramIndex}`); + values.push(depth); + paramIndex++; + } + + // 메뉴별 필터링 (형제 메뉴 포함) + if (menuObjid) { + const { getSiblingMenuObjids } = await import('./menuService'); + const siblingMenuObjids = await getSiblingMenuObjids(menuObjid); + whereConditions.push(`menu_objid = ANY($${paramIndex})`); + values.push(siblingMenuObjids); + paramIndex++; + } + + // 회사별 필터링 + if (userCompanyCode && userCompanyCode !== "*") { + whereConditions.push(`company_code = $${paramIndex}`); + values.push(userCompanyCode); + paramIndex++; + } + + const whereClause = `WHERE ${whereConditions.join(" AND ")}`; + + const codes = await query( + `SELECT * FROM code_info + ${whereClause} + ORDER BY sort_order ASC, code_value ASC`, + values + ); + + logger.info( + `계층구조 코드 조회: ${categoryCode}, 부모: ${parentCodeValue || '최상위'}, 깊이: ${depth || '전체'} - ${codes.length}개` + ); + + return codes; + } catch (error) { + logger.error(`계층구조 코드 조회 중 오류 (${categoryCode}):`, error); + throw error; + } + } + + /** + * 계층구조 코드 트리 전체 조회 (카테고리 기준) + */ + async getCodeTree( + categoryCode: string, + userCompanyCode?: string, + menuObjid?: number + ) { + try { + const whereConditions: string[] = ["code_category = $1", "is_active = 'Y'"]; + 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++; + } + + // 회사별 필터링 + if (userCompanyCode && userCompanyCode !== "*") { + whereConditions.push(`company_code = $${paramIndex}`); + values.push(userCompanyCode); + paramIndex++; + } + + const whereClause = `WHERE ${whereConditions.join(" AND ")}`; + + const allCodes = await query( + `SELECT * FROM code_info + ${whereClause} + ORDER BY depth ASC, sort_order ASC, code_value ASC`, + values + ); + + // 트리 구조로 변환 + const buildTree = (codes: CodeInfo[], parentValue: string | null = null): any[] => { + return codes + .filter(code => { + const codeParent = code.parent_code_value || null; + return codeParent === parentValue; + }) + .map(code => ({ + ...code, + children: buildTree(codes, code.code_value) + })); + }; + + const tree = buildTree(allCodes); + + logger.info( + `코드 트리 조회 완료: ${categoryCode} - 전체 ${allCodes.length}개` + ); + + return { + flat: allCodes, + tree + }; + } catch (error) { + logger.error(`코드 트리 조회 중 오류 (${categoryCode}):`, error); + throw error; + } + } + + /** + * 자식 코드가 있는지 확인 + */ + async hasChildren( + categoryCode: string, + codeValue: string, + companyCode?: string + ): Promise { + try { + let sql = `SELECT COUNT(*) as count FROM code_info + WHERE code_category = $1 AND parent_code_value = $2`; + const values: any[] = [categoryCode, codeValue]; + + if (companyCode && companyCode !== "*") { + sql += ` AND company_code = $3`; + values.push(companyCode); + } + + const result = await queryOne<{ count: string }>(sql, values); + const count = parseInt(result?.count || "0"); + + return count > 0; + } catch (error) { + logger.error(`자식 코드 확인 중 오류 (${categoryCode}.${codeValue}):`, error); + throw error; + } + } } diff --git a/backend-node/src/services/menuCopyService.ts b/backend-node/src/services/menuCopyService.ts index eb230454..075a8229 100644 --- a/backend-node/src/services/menuCopyService.ts +++ b/backend-node/src/services/menuCopyService.ts @@ -279,11 +279,90 @@ export class MenuCopyService { logger.debug(` 📐 분할 패널 우측 화면 참조 발견: ${numId}`); } } + + // 5) 모달 화면 ID (addModalScreenId, editModalScreenId, modalScreenId) + if (props?.componentConfig?.addModalScreenId) { + const addModalScreenId = props.componentConfig.addModalScreenId; + const numId = + typeof addModalScreenId === "number" + ? addModalScreenId + : parseInt(addModalScreenId); + if (!isNaN(numId) && numId > 0) { + referenced.push(numId); + logger.debug(` 📋 추가 모달 화면 참조 발견: ${numId}`); + } + } + + if (props?.componentConfig?.editModalScreenId) { + const editModalScreenId = props.componentConfig.editModalScreenId; + const numId = + typeof editModalScreenId === "number" + ? editModalScreenId + : parseInt(editModalScreenId); + if (!isNaN(numId) && numId > 0) { + referenced.push(numId); + logger.debug(` 📝 수정 모달 화면 참조 발견: ${numId}`); + } + } + + if (props?.componentConfig?.modalScreenId) { + const modalScreenId = props.componentConfig.modalScreenId; + const numId = + typeof modalScreenId === "number" + ? modalScreenId + : parseInt(modalScreenId); + if (!isNaN(numId) && numId > 0) { + referenced.push(numId); + logger.debug(` 🔲 모달 화면 참조 발견: ${numId}`); + } + } + + // 6) 재귀적으로 모든 properties에서 화면 ID 추출 (깊은 탐색) + this.extractScreenIdsFromObject(props, referenced); } return referenced; } + /** + * 객체 내부에서 화면 ID를 재귀적으로 추출 + */ + private extractScreenIdsFromObject(obj: any, referenced: number[]): void { + if (!obj || typeof obj !== "object") return; + + if (Array.isArray(obj)) { + for (const item of obj) { + this.extractScreenIdsFromObject(item, referenced); + } + return; + } + + for (const key of Object.keys(obj)) { + const value = obj[key]; + + // 화면 ID 키 패턴 확인 + if ( + key === "screenId" || + key === "targetScreenId" || + key === "leftScreenId" || + key === "rightScreenId" || + key === "addModalScreenId" || + key === "editModalScreenId" || + key === "modalScreenId" + ) { + const numId = typeof value === "number" ? value : parseInt(value); + if (!isNaN(numId) && numId > 0 && !referenced.includes(numId)) { + referenced.push(numId); + } + } + + // 재귀 탐색 + if (typeof value === "object" && value !== null) { + this.extractScreenIdsFromObject(value, referenced); + } + } + } + /** * 화면 수집 (중복 제거, 재귀적 참조 추적) */ @@ -483,7 +562,8 @@ export class MenuCopyService { properties: any, screenIdMap: Map, flowIdMap: Map, - numberingRuleIdMap?: Map + numberingRuleIdMap?: Map, + menuIdMap?: Map ): any { if (!properties) return properties; @@ -496,7 +576,8 @@ export class MenuCopyService { screenIdMap, flowIdMap, "", - numberingRuleIdMap + numberingRuleIdMap, + menuIdMap ); return updated; @@ -510,7 +591,8 @@ export class MenuCopyService { screenIdMap: Map, flowIdMap: Map, path: string = "", - numberingRuleIdMap?: Map + numberingRuleIdMap?: Map, + menuIdMap?: Map ): void { if (!obj || typeof obj !== "object") return; @@ -522,7 +604,8 @@ export class MenuCopyService { screenIdMap, flowIdMap, `${path}[${index}]`, - numberingRuleIdMap + numberingRuleIdMap, + menuIdMap ); }); return; @@ -533,13 +616,16 @@ export class MenuCopyService { const value = obj[key]; const currentPath = path ? `${path}.${key}` : key; - // screen_id, screenId, targetScreenId, leftScreenId, rightScreenId 매핑 (숫자 또는 숫자 문자열) + // screen_id, screenId, targetScreenId, leftScreenId, rightScreenId, addModalScreenId, editModalScreenId, modalScreenId 매핑 (숫자 또는 숫자 문자열) if ( key === "screen_id" || key === "screenId" || key === "targetScreenId" || key === "leftScreenId" || - key === "rightScreenId" + key === "rightScreenId" || + key === "addModalScreenId" || + key === "editModalScreenId" || + key === "modalScreenId" ) { const numValue = typeof value === "number" ? value : parseInt(value); if (!isNaN(numValue) && numValue > 0) { @@ -549,6 +635,11 @@ export class MenuCopyService { logger.info( ` 🔗 화면 참조 업데이트 (${currentPath}): ${value} → ${newId}` ); + } else { + // 매핑이 없으면 경고 로그 (복사되지 않은 화면 참조) + logger.warn( + ` ⚠️ 화면 매핑 없음 (${currentPath}): ${value} - 원본 화면이 복사되지 않았을 수 있음` + ); } } } @@ -573,9 +664,9 @@ export class MenuCopyService { } } - // numberingRuleId 매핑 (문자열) + // numberingRuleId, ruleId 매핑 (문자열) - 채번규칙 참조 if ( - key === "numberingRuleId" && + (key === "numberingRuleId" || key === "ruleId") && numberingRuleIdMap && typeof value === "string" && value @@ -595,6 +686,25 @@ export class MenuCopyService { } } + // selectedMenuObjid 매핑 (메뉴 objid 참조) + if (key === "selectedMenuObjid" && menuIdMap) { + const numValue = typeof value === "number" ? value : parseInt(value); + if (!isNaN(numValue) && numValue > 0) { + const newId = menuIdMap.get(numValue); + if (newId) { + obj[key] = typeof value === "number" ? newId : String(newId); + logger.info( + ` 🔗 메뉴 참조 업데이트 (${currentPath}): ${value} → ${newId}` + ); + } else { + // 매핑이 없으면 경고 로그 (복사되지 않은 메뉴 참조) + logger.warn( + ` ⚠️ 메뉴 매핑 없음 (${currentPath}): ${value} - 원본 메뉴가 복사되지 않았을 수 있음` + ); + } + } + } + // 재귀 호출 if (typeof value === "object" && value !== null) { this.recursiveUpdateReferences( @@ -602,7 +712,8 @@ export class MenuCopyService { screenIdMap, flowIdMap, currentPath, - numberingRuleIdMap + numberingRuleIdMap, + menuIdMap ); } } @@ -938,7 +1049,9 @@ export class MenuCopyService { copiedCategoryMappings = await this.copyCategoryMappingsAndValues( menuObjids, menuIdMap, + sourceCompanyCode, targetCompanyCode, + Array.from(screenIds), userId, client ); @@ -979,7 +1092,8 @@ export class MenuCopyService { userId, client, screenNameConfig, - numberingRuleIdMap + numberingRuleIdMap, + menuIdMap ); // === 6단계: 화면-메뉴 할당 === @@ -1313,7 +1427,8 @@ export class MenuCopyService { removeText?: string; addPrefix?: string; }, - numberingRuleIdMap?: Map + numberingRuleIdMap?: Map, + menuIdMap?: Map ): Promise> { const screenIdMap = new Map(); @@ -1599,7 +1714,8 @@ export class MenuCopyService { layout.properties, screenIdMap, flowIdMap, - numberingRuleIdMap + numberingRuleIdMap, + menuIdMap ); layoutValues.push( @@ -2569,11 +2685,16 @@ export class MenuCopyService { /** * 카테고리 매핑 + 값 복사 (최적화: 배치 조회) + * + * 화면에서 사용하는 table_name + column_name 조합을 기준으로 카테고리 값 복사 + * menu_objid 기준이 아닌 화면 컴포넌트 기준으로 복사하여 누락 방지 */ private async copyCategoryMappingsAndValues( menuObjids: number[], menuIdMap: Map, + sourceCompanyCode: string, targetCompanyCode: string, + screenIds: number[], userId: string, client: PoolClient ): Promise { @@ -2697,12 +2818,70 @@ export class MenuCopyService { ); } - // 4. 모든 원본 카테고리 값 한 번에 조회 + // 4. 화면에서 사용하는 카테고리 컬럼 조합 수집 + // 복사된 화면의 레이아웃에서 webType='category'인 컴포넌트의 tableName, columnName 추출 + const categoryColumnsResult = await client.query( + `SELECT DISTINCT + sl.properties->>'tableName' as table_name, + sl.properties->>'columnName' as column_name + FROM screen_layouts sl + JOIN screen_definitions sd ON sl.screen_id = sd.screen_id + WHERE sd.screen_id = ANY($1) + AND sl.properties->'componentConfig'->>'webType' = 'category' + AND sl.properties->>'tableName' IS NOT NULL + AND sl.properties->>'columnName' IS NOT NULL`, + [screenIds] + ); + + // 카테고리 매핑에서 사용하는 table_name, column_name도 추가 + const mappingColumnsResult = await client.query( + `SELECT DISTINCT table_name, logical_column_name as column_name + FROM category_column_mapping + WHERE menu_objid = ANY($1)`, + [menuObjids] + ); + + // 두 결과 합치기 + const categoryColumns = new Set(); + for (const row of categoryColumnsResult.rows) { + if (row.table_name && row.column_name) { + categoryColumns.add(`${row.table_name}|${row.column_name}`); + } + } + for (const row of mappingColumnsResult.rows) { + if (row.table_name && row.column_name) { + categoryColumns.add(`${row.table_name}|${row.column_name}`); + } + } + + logger.info( + ` 📋 화면에서 사용하는 카테고리 컬럼: ${categoryColumns.size}개` + ); + + if (categoryColumns.size === 0) { + logger.info(`✅ 카테고리 매핑 + 값 복사 완료: ${copiedCount}개`); + return copiedCount; + } + + // 5. 원본 회사의 카테고리 값 조회 (table_name + column_name 기준) + // menu_objid 조건 대신 table_name + column_name + 원본 회사 코드로 조회 + const columnConditions = Array.from(categoryColumns).map((col, i) => { + const [tableName, columnName] = col.split("|"); + return `(table_name = $${i * 2 + 2} AND column_name = $${i * 2 + 3})`; + }); + + const columnParams: string[] = []; + for (const col of categoryColumns) { + const [tableName, columnName] = col.split("|"); + columnParams.push(tableName, columnName); + } + const allValuesResult = await client.query( `SELECT * FROM table_column_category_values - WHERE menu_objid = ANY($1) + WHERE company_code = $1 + AND (${columnConditions.join(" OR ")}) ORDER BY depth NULLS FIRST, parent_value_id NULLS FIRST, value_order`, - [menuObjids] + [sourceCompanyCode, ...columnParams] ); if (allValuesResult.rows.length === 0) { @@ -2710,6 +2889,8 @@ export class MenuCopyService { return copiedCount; } + logger.info(` 📋 원본 카테고리 값: ${allValuesResult.rows.length}개 발견`); + // 5. 대상 회사에 이미 존재하는 값 한 번에 조회 const existingValuesResult = await client.query( `SELECT value_id, table_name, column_name, value_code @@ -2763,8 +2944,12 @@ export class MenuCopyService { ) .join(", "); + // 기본 menu_objid: 매핑이 없을 경우 첫 번째 복사된 메뉴 사용 + const defaultMenuObjid = menuIdMap.values().next().value || 0; + const valueParams = values.flatMap((v) => { - const newMenuObjid = menuIdMap.get(v.menu_objid); + // 원본 menu_objid가 매핑에 있으면 사용, 없으면 기본값 사용 + const newMenuObjid = menuIdMap.get(v.menu_objid) ?? defaultMenuObjid; const newParentId = v.parent_value_id ? valueIdMap.get(v.parent_value_id) || null : null; diff --git a/docs/노드플로우_개선사항.md b/docs/노드플로우_개선사항.md index c2c44be0..c9349b94 100644 --- a/docs/노드플로우_개선사항.md +++ b/docs/노드플로우_개선사항.md @@ -586,3 +586,4 @@ const result = await executeNodeFlow(flowId, { + diff --git a/docs/메일발송_기능_사용_가이드.md b/docs/메일발송_기능_사용_가이드.md index 4ffb7655..42900211 100644 --- a/docs/메일발송_기능_사용_가이드.md +++ b/docs/메일발송_기능_사용_가이드.md @@ -359,3 +359,4 @@ + diff --git a/docs/즉시저장_버튼_액션_구현_계획서.md b/docs/즉시저장_버튼_액션_구현_계획서.md index 1de42fb2..c392eece 100644 --- a/docs/즉시저장_버튼_액션_구현_계획서.md +++ b/docs/즉시저장_버튼_액션_구현_계획서.md @@ -345,3 +345,4 @@ const getComponentValue = (componentId: string) => { + diff --git a/frontend/app/(main)/admin/cascading-management/page.tsx b/frontend/app/(main)/admin/cascading-management/page.tsx index 5b5f6b37..c36d8ae0 100644 --- a/frontend/app/(main)/admin/cascading-management/page.tsx +++ b/frontend/app/(main)/admin/cascading-management/page.tsx @@ -3,7 +3,7 @@ import React, { useState, useEffect } from "react"; import { useSearchParams, useRouter } from "next/navigation"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; -import { Link2, Layers, Filter, FormInput, Ban, Tags } from "lucide-react"; +import { Link2, Layers, Filter, FormInput, Ban, Tags, Columns } from "lucide-react"; // 탭별 컴포넌트 import CascadingRelationsTab from "./tabs/CascadingRelationsTab"; @@ -12,6 +12,7 @@ import HierarchyTab from "./tabs/HierarchyTab"; import ConditionTab from "./tabs/ConditionTab"; import MutualExclusionTab from "./tabs/MutualExclusionTab"; import CategoryValueCascadingTab from "./tabs/CategoryValueCascadingTab"; +import HierarchyColumnTab from "./tabs/HierarchyColumnTab"; export default function CascadingManagementPage() { const searchParams = useSearchParams(); @@ -21,7 +22,7 @@ export default function CascadingManagementPage() { // URL 쿼리 파라미터에서 탭 설정 useEffect(() => { const tab = searchParams.get("tab"); - if (tab && ["relations", "hierarchy", "condition", "autofill", "exclusion", "category-value"].includes(tab)) { + if (tab && ["relations", "hierarchy", "condition", "autofill", "exclusion", "category-value", "hierarchy-column"].includes(tab)) { setActiveTab(tab); } }, [searchParams]); diff --git a/frontend/app/(main)/admin/cascading-management/tabs/HierarchyColumnTab.tsx b/frontend/app/(main)/admin/cascading-management/tabs/HierarchyColumnTab.tsx new file mode 100644 index 00000000..d0d77230 --- /dev/null +++ b/frontend/app/(main)/admin/cascading-management/tabs/HierarchyColumnTab.tsx @@ -0,0 +1,626 @@ +"use client"; + +import React, { useState, useEffect, useCallback } from "react"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Badge } from "@/components/ui/badge"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { Plus, Pencil, Trash2, Database, RefreshCw, Layers } from "lucide-react"; +import { toast } from "sonner"; +import { LoadingSpinner } from "@/components/common/LoadingSpinner"; +import { + hierarchyColumnApi, + HierarchyColumnGroup, + CreateHierarchyGroupRequest, +} from "@/lib/api/hierarchyColumn"; +import { commonCodeApi } from "@/lib/api/commonCode"; +import apiClient from "@/lib/api/client"; + +interface TableInfo { + tableName: string; + displayName?: string; +} + +interface ColumnInfo { + columnName: string; + displayName?: string; + dataType?: string; +} + +interface CategoryInfo { + categoryCode: string; + categoryName: string; +} + +export default function HierarchyColumnTab() { + // 상태 + const [groups, setGroups] = useState([]); + const [loading, setLoading] = useState(true); + const [modalOpen, setModalOpen] = useState(false); + const [deleteDialogOpen, setDeleteDialogOpen] = useState(false); + const [selectedGroup, setSelectedGroup] = useState(null); + const [isEditing, setIsEditing] = useState(false); + + // 폼 상태 + const [formData, setFormData] = useState({ + groupCode: "", + groupName: "", + description: "", + codeCategory: "", + tableName: "", + maxDepth: 3, + mappings: [ + { depth: 1, levelLabel: "대분류", columnName: "", placeholder: "대분류 선택", isRequired: true }, + { depth: 2, levelLabel: "중분류", columnName: "", placeholder: "중분류 선택", isRequired: false }, + { depth: 3, levelLabel: "소분류", columnName: "", placeholder: "소분류 선택", isRequired: false }, + ], + }); + + // 참조 데이터 + const [tables, setTables] = useState([]); + const [columns, setColumns] = useState([]); + const [categories, setCategories] = useState([]); + const [loadingTables, setLoadingTables] = useState(false); + const [loadingColumns, setLoadingColumns] = useState(false); + const [loadingCategories, setLoadingCategories] = useState(false); + + // 그룹 목록 로드 + const loadGroups = useCallback(async () => { + setLoading(true); + try { + const response = await hierarchyColumnApi.getAll(); + if (response.success && response.data) { + setGroups(response.data); + } else { + toast.error(response.error || "계층구조 그룹 로드 실패"); + } + } catch (error) { + console.error("계층구조 그룹 로드 에러:", error); + toast.error("계층구조 그룹을 로드하는 중 오류가 발생했습니다."); + } finally { + setLoading(false); + } + }, []); + + // 테이블 목록 로드 + const loadTables = useCallback(async () => { + setLoadingTables(true); + try { + const response = await apiClient.get("/table-management/tables"); + if (response.data?.success && response.data?.data) { + setTables(response.data.data); + } + } catch (error) { + console.error("테이블 로드 에러:", error); + } finally { + setLoadingTables(false); + } + }, []); + + // 카테고리 목록 로드 + const loadCategories = useCallback(async () => { + setLoadingCategories(true); + try { + const response = await commonCodeApi.categories.getList(); + if (response.success && response.data) { + setCategories( + response.data.map((cat: any) => ({ + categoryCode: cat.categoryCode || cat.category_code, + categoryName: cat.categoryName || cat.category_name, + })) + ); + } + } catch (error) { + console.error("카테고리 로드 에러:", error); + } finally { + setLoadingCategories(false); + } + }, []); + + // 테이블 선택 시 컬럼 로드 + const loadColumns = useCallback(async (tableName: string) => { + if (!tableName) { + setColumns([]); + return; + } + setLoadingColumns(true); + try { + const response = await apiClient.get(`/table-management/tables/${tableName}/columns`); + if (response.data?.success && response.data?.data) { + setColumns(response.data.data); + } + } catch (error) { + console.error("컬럼 로드 에러:", error); + } finally { + setLoadingColumns(false); + } + }, []); + + // 초기 로드 + useEffect(() => { + loadGroups(); + loadTables(); + loadCategories(); + }, [loadGroups, loadTables, loadCategories]); + + // 테이블 선택 변경 시 컬럼 로드 + useEffect(() => { + if (formData.tableName) { + loadColumns(formData.tableName); + } + }, [formData.tableName, loadColumns]); + + // 폼 초기화 + const resetForm = () => { + setFormData({ + groupCode: "", + groupName: "", + description: "", + codeCategory: "", + tableName: "", + maxDepth: 3, + mappings: [ + { depth: 1, levelLabel: "대분류", columnName: "", placeholder: "대분류 선택", isRequired: true }, + { depth: 2, levelLabel: "중분류", columnName: "", placeholder: "중분류 선택", isRequired: false }, + { depth: 3, levelLabel: "소분류", columnName: "", placeholder: "소분류 선택", isRequired: false }, + ], + }); + setSelectedGroup(null); + setIsEditing(false); + }; + + // 모달 열기 (신규) + const openCreateModal = () => { + resetForm(); + setModalOpen(true); + }; + + // 모달 열기 (수정) + const openEditModal = (group: HierarchyColumnGroup) => { + setSelectedGroup(group); + setIsEditing(true); + + // 매핑 데이터 변환 + const mappings = [1, 2, 3].map((depth) => { + const existing = group.mappings?.find((m) => m.depth === depth); + return { + depth, + levelLabel: existing?.level_label || (depth === 1 ? "대분류" : depth === 2 ? "중분류" : "소분류"), + columnName: existing?.column_name || "", + placeholder: existing?.placeholder || `${depth === 1 ? "대분류" : depth === 2 ? "중분류" : "소분류"} 선택`, + isRequired: existing?.is_required === "Y", + }; + }); + + setFormData({ + groupCode: group.group_code, + groupName: group.group_name, + description: group.description || "", + codeCategory: group.code_category, + tableName: group.table_name, + maxDepth: group.max_depth, + mappings, + }); + + // 컬럼 로드 + loadColumns(group.table_name); + setModalOpen(true); + }; + + // 삭제 확인 열기 + const openDeleteDialog = (group: HierarchyColumnGroup) => { + setSelectedGroup(group); + setDeleteDialogOpen(true); + }; + + // 저장 + const handleSave = async () => { + // 필수 필드 검증 + if (!formData.groupCode || !formData.groupName || !formData.codeCategory || !formData.tableName) { + toast.error("필수 필드를 모두 입력해주세요."); + return; + } + + // 최소 1개 컬럼 매핑 검증 + const validMappings = formData.mappings + .filter((m) => m.depth <= formData.maxDepth && m.columnName) + .map((m) => ({ + depth: m.depth, + levelLabel: m.levelLabel, + columnName: m.columnName, + placeholder: m.placeholder, + isRequired: m.isRequired, + })); + + if (validMappings.length === 0) { + toast.error("최소 하나의 컬럼 매핑이 필요합니다."); + return; + } + + try { + if (isEditing && selectedGroup) { + // 수정 + const response = await hierarchyColumnApi.update(selectedGroup.group_id, { + groupName: formData.groupName, + description: formData.description, + maxDepth: formData.maxDepth, + mappings: validMappings, + }); + + if (response.success) { + toast.success("계층구조 그룹이 수정되었습니다."); + setModalOpen(false); + loadGroups(); + } else { + toast.error(response.error || "수정 실패"); + } + } else { + // 생성 + const request: CreateHierarchyGroupRequest = { + groupCode: formData.groupCode, + groupName: formData.groupName, + description: formData.description, + codeCategory: formData.codeCategory, + tableName: formData.tableName, + maxDepth: formData.maxDepth, + mappings: validMappings, + }; + + const response = await hierarchyColumnApi.create(request); + + if (response.success) { + toast.success("계층구조 그룹이 생성되었습니다."); + setModalOpen(false); + loadGroups(); + } else { + toast.error(response.error || "생성 실패"); + } + } + } catch (error) { + console.error("저장 에러:", error); + toast.error("저장 중 오류가 발생했습니다."); + } + }; + + // 삭제 + const handleDelete = async () => { + if (!selectedGroup) return; + + try { + const response = await hierarchyColumnApi.delete(selectedGroup.group_id); + if (response.success) { + toast.success("계층구조 그룹이 삭제되었습니다."); + setDeleteDialogOpen(false); + loadGroups(); + } else { + toast.error(response.error || "삭제 실패"); + } + } catch (error) { + console.error("삭제 에러:", error); + toast.error("삭제 중 오류가 발생했습니다."); + } + }; + + // 매핑 컬럼 변경 + const handleMappingChange = (depth: number, field: string, value: any) => { + setFormData((prev) => ({ + ...prev, + mappings: prev.mappings.map((m) => + m.depth === depth ? { ...m, [field]: value } : m + ), + })); + }; + + return ( +
+ {/* 헤더 */} +
+
+

계층구조 컬럼 그룹

+

+ 공통코드 계층구조를 테이블 컬럼에 매핑하여 대분류/중분류/소분류를 각각 별도 컬럼에 저장합니다. +

+
+
+ + +
+
+ + {/* 그룹 목록 */} + {loading ? ( +
+ + 로딩 중... +
+ ) : groups.length === 0 ? ( + + + +

계층구조 컬럼 그룹이 없습니다.

+ +
+
+ ) : ( +
+ {groups.map((group) => ( + + +
+
+ {group.group_name} + {group.group_code} +
+
+ + +
+
+
+ +
+ + {group.table_name} +
+
+ {group.code_category} + {group.max_depth}단계 +
+ {group.mappings && group.mappings.length > 0 && ( +
+ {group.mappings.map((mapping) => ( +
+ + {mapping.level_label} + + {mapping.column_name} +
+ ))} +
+ )} +
+
+ ))} +
+ )} + + {/* 생성/수정 모달 */} + + + + {isEditing ? "계층구조 그룹 수정" : "계층구조 그룹 생성"} + + 공통코드 계층구조를 테이블 컬럼에 매핑합니다. + + + +
+ {/* 기본 정보 */} +
+
+ + setFormData({ ...formData, groupCode: e.target.value.toUpperCase() })} + placeholder="예: ITEM_CAT_HIERARCHY" + disabled={isEditing} + /> +
+
+ + setFormData({ ...formData, groupName: e.target.value })} + placeholder="예: 품목분류 계층" + /> +
+
+ +
+ + setFormData({ ...formData, description: e.target.value })} + placeholder="계층구조에 대한 설명" + /> +
+ +
+
+ + +
+
+ + +
+
+ +
+ + +
+ + {/* 컬럼 매핑 */} +
+ +

+ 각 계층 레벨에 저장할 컬럼을 선택합니다. +

+ + {formData.mappings + .filter((m) => m.depth <= formData.maxDepth) + .map((mapping) => ( +
+
+ + {mapping.depth}단계 + + handleMappingChange(mapping.depth, "levelLabel", e.target.value)} + className="h-8 text-xs" + placeholder="라벨" + /> +
+ + handleMappingChange(mapping.depth, "placeholder", e.target.value)} + className="h-8 text-xs" + placeholder="플레이스홀더" + /> +
+ handleMappingChange(mapping.depth, "isRequired", e.target.checked)} + className="h-4 w-4" + /> + 필수 +
+
+ ))} +
+
+ + + + + +
+
+ + {/* 삭제 확인 다이얼로그 */} + + + + 계층구조 그룹 삭제 + + "{selectedGroup?.group_name}" 그룹을 삭제하시겠습니까? +
+ 이 작업은 되돌릴 수 없습니다. +
+
+ + + + +
+
+
+ ); +} + diff --git a/frontend/app/(main)/admin/tableMng/page.tsx b/frontend/app/(main)/admin/tableMng/page.tsx index b554dff1..0b5ff573 100644 --- a/frontend/app/(main)/admin/tableMng/page.tsx +++ b/frontend/app/(main)/admin/tableMng/page.tsx @@ -56,6 +56,7 @@ interface ColumnTypeInfo { referenceColumn?: string; displayColumn?: string; // 🎯 Entity 조인에서 표시할 컬럼명 categoryMenus?: number[]; // 🆕 Category 타입: 선택된 2레벨 메뉴 OBJID 배열 + hierarchyRole?: "large" | "medium" | "small"; // 🆕 계층구조 역할 } interface SecondLevelMenu { @@ -292,11 +293,27 @@ export default function TableManagementPage() { }); // 컬럼 데이터에 기본값 설정 - const processedColumns = (data.columns || data).map((col: any) => ({ - ...col, - inputType: col.inputType || "text", // 기본값: text - categoryMenus: col.categoryMenus || [], // 카테고리 메뉴 매핑 정보 - })); + const processedColumns = (data.columns || data).map((col: any) => { + // detailSettings에서 hierarchyRole 추출 + let hierarchyRole: "large" | "medium" | "small" | undefined = undefined; + if (col.detailSettings && typeof col.detailSettings === "string") { + try { + const parsed = JSON.parse(col.detailSettings); + if (parsed.hierarchyRole === "large" || parsed.hierarchyRole === "medium" || parsed.hierarchyRole === "small") { + hierarchyRole = parsed.hierarchyRole; + } + } catch { + // JSON 파싱 실패 시 무시 + } + } + + return { + ...col, + inputType: col.inputType || "text", // 기본값: text + categoryMenus: col.categoryMenus || [], // 카테고리 메뉴 매핑 정보 + hierarchyRole, // 계층구조 역할 + }; + }); if (page === 1) { setColumns(processedColumns); @@ -367,18 +384,40 @@ export default function TableManagementPage() { let referenceTable = col.referenceTable; let referenceColumn = col.referenceColumn; let displayColumn = col.displayColumn; + let hierarchyRole = col.hierarchyRole; if (settingType === "code") { if (value === "none") { newDetailSettings = ""; codeCategory = undefined; codeValue = undefined; + hierarchyRole = undefined; // 코드 선택 해제 시 계층 역할도 초기화 } else { - const codeOption = commonCodeOptions.find((option) => option.value === value); - newDetailSettings = codeOption ? `공통코드: ${codeOption.label}` : ""; + // 기존 hierarchyRole 유지하면서 JSON 형식으로 저장 + const existingHierarchyRole = hierarchyRole; + newDetailSettings = JSON.stringify({ + codeCategory: value, + hierarchyRole: existingHierarchyRole + }); codeCategory = value; codeValue = value; } + } else if (settingType === "hierarchy_role") { + // 계층구조 역할 변경 - JSON 형식으로 저장 + hierarchyRole = value === "none" ? undefined : (value as "large" | "medium" | "small"); + // detailSettings를 JSON으로 업데이트 + let existingSettings: Record = {}; + if (typeof col.detailSettings === "string" && col.detailSettings.trim().startsWith("{")) { + try { + existingSettings = JSON.parse(col.detailSettings); + } catch { + existingSettings = {}; + } + } + newDetailSettings = JSON.stringify({ + ...existingSettings, + hierarchyRole: hierarchyRole, + }); } else if (settingType === "entity") { if (value === "none") { newDetailSettings = ""; @@ -415,6 +454,7 @@ export default function TableManagementPage() { referenceTable, referenceColumn, displayColumn, + hierarchyRole, }; } return col; @@ -487,6 +527,26 @@ export default function TableManagementPage() { console.log("🔧 Entity 설정 JSON 생성:", entitySettings); } + // 🎯 Code 타입인 경우 hierarchyRole을 detailSettings에 포함 + if (column.inputType === "code" && column.hierarchyRole) { + let existingSettings: Record = {}; + if (typeof finalDetailSettings === "string" && finalDetailSettings.trim().startsWith("{")) { + try { + existingSettings = JSON.parse(finalDetailSettings); + } catch { + existingSettings = {}; + } + } + + const codeSettings = { + ...existingSettings, + hierarchyRole: column.hierarchyRole, + }; + + finalDetailSettings = JSON.stringify(codeSettings); + console.log("🔧 Code 계층 역할 설정 JSON 생성:", codeSettings); + } + const columnSetting = { columnName: column.columnName, // 실제 DB 컬럼명 (변경 불가) columnLabel: column.displayName, // 사용자가 입력한 표시명 @@ -1229,23 +1289,44 @@ export default function TableManagementPage() { {/* 입력 타입이 'code'인 경우 공통코드 선택 */} {column.inputType === "code" && ( - + <> + + {/* 계층구조 역할 선택 */} + {column.codeCategory && column.codeCategory !== "none" && ( + + )} + )} {/* 입력 타입이 'category'인 경우 2레벨 메뉴 다중 선택 */} {column.inputType === "category" && ( diff --git a/frontend/components/admin/CodeDetailPanel.tsx b/frontend/components/admin/CodeDetailPanel.tsx index 62f33cd2..3110a5ee 100644 --- a/frontend/components/admin/CodeDetailPanel.tsx +++ b/frontend/components/admin/CodeDetailPanel.tsx @@ -1,6 +1,6 @@ "use client"; -import { useState } from "react"; +import { useState, useMemo } from "react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Badge } from "@/components/ui/badge"; @@ -45,15 +45,124 @@ export function CodeDetailPanel({ categoryCode }: CodeDetailPanelProps) { const reorderCodesMutation = useReorderCodes(); // 드래그앤드롭을 위해 필터링된 코드 목록 사용 - const { filteredItems: filteredCodes } = useSearchAndFilter(codes, { + const { filteredItems: filteredCodesRaw } = useSearchAndFilter(codes, { searchFields: ["code_name", "code_value"], }); + // 계층 구조로 정렬 (부모 → 자식 순서) + const filteredCodes = useMemo(() => { + if (!filteredCodesRaw || filteredCodesRaw.length === 0) return []; + + // 코드를 계층 순서로 정렬하는 함수 + const sortHierarchically = (codes: CodeInfo[]): CodeInfo[] => { + const result: CodeInfo[] = []; + const codeMap = new Map(); + const childrenMap = new Map(); + + // 코드 맵 생성 + codes.forEach((code) => { + const codeValue = code.codeValue || code.code_value || ""; + const parentValue = code.parentCodeValue || code.parent_code_value; + codeMap.set(codeValue, code); + + if (parentValue) { + if (!childrenMap.has(parentValue)) { + childrenMap.set(parentValue, []); + } + childrenMap.get(parentValue)!.push(code); + } + }); + + // 재귀적으로 트리 구조 순회 + const traverse = (parentValue: string | null, depth: number) => { + const children = parentValue + ? childrenMap.get(parentValue) || [] + : codes.filter((c) => !c.parentCodeValue && !c.parent_code_value); + + // 정렬 순서로 정렬 + children + .sort((a, b) => (a.sortOrder || a.sort_order || 0) - (b.sortOrder || b.sort_order || 0)) + .forEach((code) => { + result.push(code); + const codeValue = code.codeValue || code.code_value || ""; + traverse(codeValue, depth + 1); + }); + }; + + traverse(null, 1); + + // 트리에 포함되지 않은 코드들도 추가 (orphan 코드) + codes.forEach((code) => { + if (!result.includes(code)) { + result.push(code); + } + }); + + return result; + }; + + return sortHierarchically(filteredCodesRaw); + }, [filteredCodesRaw]); + // 모달 상태 const [showFormModal, setShowFormModal] = useState(false); const [editingCode, setEditingCode] = useState(null); const [showDeleteModal, setShowDeleteModal] = useState(false); const [deletingCode, setDeletingCode] = useState(null); + const [defaultParentCode, setDefaultParentCode] = useState(undefined); + + // 트리 접기/펼치기 상태 (코드값 Set) + const [collapsedCodes, setCollapsedCodes] = useState>(new Set()); + + // 자식 정보 계산 + const childrenMap = useMemo(() => { + const map = new Map(); + codes.forEach((code) => { + const parentValue = code.parentCodeValue || code.parent_code_value; + if (parentValue) { + if (!map.has(parentValue)) { + map.set(parentValue, []); + } + map.get(parentValue)!.push(code); + } + }); + return map; + }, [codes]); + + // 접기/펼치기 토글 + const toggleExpand = (codeValue: string) => { + setCollapsedCodes((prev) => { + const newSet = new Set(prev); + if (newSet.has(codeValue)) { + newSet.delete(codeValue); + } else { + newSet.add(codeValue); + } + return newSet; + }); + }; + + // 특정 코드가 표시되어야 하는지 확인 (부모가 접혀있으면 숨김) + const isCodeVisible = (code: CodeInfo): boolean => { + const parentValue = code.parentCodeValue || code.parent_code_value; + if (!parentValue) return true; // 최상위 코드는 항상 표시 + + // 부모가 접혀있으면 숨김 + if (collapsedCodes.has(parentValue)) return false; + + // 부모의 부모도 확인 (재귀적으로) + const parentCode = codes.find((c) => (c.codeValue || c.code_value) === parentValue); + if (parentCode) { + return isCodeVisible(parentCode); + } + + return true; + }; + + // 표시할 코드 목록 (접힌 상태 반영) + const visibleCodes = useMemo(() => { + return filteredCodes.filter(isCodeVisible); + }, [filteredCodes, collapsedCodes, codes]); // 드래그 앤 드롭 훅 사용 const dragAndDrop = useDragAndDrop({ @@ -73,12 +182,21 @@ export function CodeDetailPanel({ categoryCode }: CodeDetailPanelProps) { // 새 코드 생성 const handleNewCode = () => { setEditingCode(null); + setDefaultParentCode(undefined); setShowFormModal(true); }; // 코드 수정 const handleEditCode = (code: CodeInfo) => { setEditingCode(code); + setDefaultParentCode(undefined); + setShowFormModal(true); + }; + + // 하위 코드 추가 + const handleAddChild = (parentCode: CodeInfo) => { + setEditingCode(null); + setDefaultParentCode(parentCode.codeValue || parentCode.code_value || ""); setShowFormModal(true); }; @@ -110,7 +228,7 @@ export function CodeDetailPanel({ categoryCode }: CodeDetailPanelProps) { if (!categoryCode) { return (
-

카테고리를 선택하세요

+

카테고리를 선택하세요

); } @@ -119,7 +237,7 @@ export function CodeDetailPanel({ categoryCode }: CodeDetailPanelProps) { return (
-

코드를 불러오는 중 오류가 발생했습니다.

+

코드를 불러오는 중 오류가 발생했습니다.

@@ -135,7 +253,7 @@ export function CodeDetailPanel({ categoryCode }: CodeDetailPanelProps) { {/* 검색 + 버튼 */}
- + setShowActiveOnly(e.target.checked)} - className="h-4 w-4 rounded border-input" + className="border-input h-4 w-4 rounded" /> -
@@ -170,9 +288,9 @@ export function CodeDetailPanel({ categoryCode }: CodeDetailPanelProps) {
- ) : filteredCodes.length === 0 ? ( + ) : visibleCodes.length === 0 ? (
-

+

{codes.length === 0 ? "코드가 없습니다." : "검색 결과가 없습니다."}

@@ -180,23 +298,35 @@ export function CodeDetailPanel({ categoryCode }: CodeDetailPanelProps) { <> code.codeValue || code.code_value)} + items={visibleCodes.map((code) => code.codeValue || code.code_value)} strategy={verticalListSortingStrategy} > - {filteredCodes.map((code, index) => ( - handleEditCode(code)} - onDelete={() => handleDeleteCode(code)} - /> - ))} + {visibleCodes.map((code, index) => { + const codeValue = code.codeValue || code.code_value || ""; + const children = childrenMap.get(codeValue) || []; + const hasChildren = children.length > 0; + const isExpanded = !collapsedCodes.has(codeValue); + + return ( + handleEditCode(code)} + onDelete={() => handleDeleteCode(code)} + onAddChild={() => handleAddChild(code)} + hasChildren={hasChildren} + childCount={children.length} + isExpanded={isExpanded} + onToggleExpand={() => toggleExpand(codeValue)} + /> + ); + })} {dragAndDrop.activeItem ? ( -
+
{(() => { const activeCode = dragAndDrop.activeItem; if (!activeCode) return null; @@ -204,24 +334,20 @@ export function CodeDetailPanel({ categoryCode }: CodeDetailPanelProps) {
-

- {activeCode.codeName || activeCode.code_name} -

+

{activeCode.codeName || activeCode.code_name}

{activeCode.isActive === "Y" || activeCode.is_active === "Y" ? "활성" : "비활성"}
-

+

{activeCode.codeValue || activeCode.code_value}

{activeCode.description && ( -

{activeCode.description}

+

{activeCode.description}

)}
@@ -236,13 +362,13 @@ export function CodeDetailPanel({ categoryCode }: CodeDetailPanelProps) { {isFetchingNextPage && (
- 코드를 더 불러오는 중... + 코드를 더 불러오는 중...
)} {/* 모든 코드 로드 완료 메시지 */} {!hasNextPage && codes.length > 0 && ( -
모든 코드를 불러왔습니다.
+
모든 코드를 불러왔습니다.
)} )} @@ -255,10 +381,12 @@ export function CodeDetailPanel({ categoryCode }: CodeDetailPanelProps) { onClose={() => { setShowFormModal(false); setEditingCode(null); + setDefaultParentCode(undefined); }} categoryCode={categoryCode} editingCode={editingCode} codes={codes} + defaultParentCode={defaultParentCode} /> )} diff --git a/frontend/components/admin/CodeFormModal.tsx b/frontend/components/admin/CodeFormModal.tsx index 977e9e84..b5a8847b 100644 --- a/frontend/components/admin/CodeFormModal.tsx +++ b/frontend/components/admin/CodeFormModal.tsx @@ -24,6 +24,7 @@ interface CodeFormModalProps { categoryCode: string; editingCode?: CodeInfo | null; codes: CodeInfo[]; + defaultParentCode?: string; // 하위 코드 추가 시 기본 부모 코드 } // 에러 메시지를 안전하게 문자열로 변환하는 헬퍼 함수 @@ -33,28 +34,32 @@ const getErrorMessage = (error: FieldError | undefined): string => { return error.message || ""; }; -export function CodeFormModal({ isOpen, onClose, categoryCode, editingCode, codes }: CodeFormModalProps) { +// 코드값 자동 생성 함수 (UUID 기반 짧은 코드) +const generateCodeValue = (): string => { + const timestamp = Date.now().toString(36).toUpperCase(); + const random = Math.random().toString(36).substring(2, 6).toUpperCase(); + return `${timestamp}${random}`; +}; + +export function CodeFormModal({ + isOpen, + onClose, + categoryCode, + editingCode, + codes, + defaultParentCode, +}: CodeFormModalProps) { const createCodeMutation = useCreateCode(); const updateCodeMutation = useUpdateCode(); const isEditing = !!editingCode; - // 검증 상태 관리 + // 검증 상태 관리 (코드명만 중복 검사) const [validationStates, setValidationStates] = useState({ - codeValue: { enabled: false, value: "" }, codeName: { enabled: false, value: "" }, - codeNameEng: { enabled: false, value: "" }, }); - // 중복 검사 훅들 - const codeValueCheck = useCheckCodeDuplicate( - categoryCode, - "codeValue", - validationStates.codeValue.value, - isEditing ? editingCode?.codeValue || editingCode?.code_value : undefined, - validationStates.codeValue.enabled, - ); - + // 코드명 중복 검사 const codeNameCheck = useCheckCodeDuplicate( categoryCode, "codeName", @@ -63,22 +68,11 @@ export function CodeFormModal({ isOpen, onClose, categoryCode, editingCode, code validationStates.codeName.enabled, ); - const codeNameEngCheck = useCheckCodeDuplicate( - categoryCode, - "codeNameEng", - validationStates.codeNameEng.value, - isEditing ? editingCode?.codeValue || editingCode?.code_value : undefined, - validationStates.codeNameEng.enabled, - ); - // 중복 검사 결과 확인 - const hasDuplicateErrors = - (codeValueCheck.data?.isDuplicate && validationStates.codeValue.enabled) || - (codeNameCheck.data?.isDuplicate && validationStates.codeName.enabled) || - (codeNameEngCheck.data?.isDuplicate && validationStates.codeNameEng.enabled); + const hasDuplicateErrors = codeNameCheck.data?.isDuplicate && validationStates.codeName.enabled; // 중복 검사 로딩 중인지 확인 - const isDuplicateChecking = codeValueCheck.isLoading || codeNameCheck.isLoading || codeNameEngCheck.isLoading; + const isDuplicateChecking = codeNameCheck.isLoading; // 폼 스키마 선택 (생성/수정에 따라) const schema = isEditing ? updateCodeSchema : createCodeSchema; @@ -92,6 +86,7 @@ export function CodeFormModal({ isOpen, onClose, categoryCode, editingCode, code codeNameEng: "", description: "", sortOrder: 1, + parentCodeValue: "" as string | undefined, ...(isEditing && { isActive: "Y" as const }), }, }); @@ -101,30 +96,40 @@ export function CodeFormModal({ isOpen, onClose, categoryCode, editingCode, code if (isOpen) { if (isEditing && editingCode) { // 수정 모드: 기존 데이터 로드 (codeValue는 표시용으로만 설정) + const parentValue = editingCode.parentCodeValue || editingCode.parent_code_value || ""; + form.reset({ codeName: editingCode.codeName || editingCode.code_name, codeNameEng: editingCode.codeNameEng || editingCode.code_name_eng || "", description: editingCode.description || "", sortOrder: editingCode.sortOrder || editingCode.sort_order, - isActive: (editingCode.isActive || editingCode.is_active) as "Y" | "N", // 타입 캐스팅 + isActive: (editingCode.isActive || editingCode.is_active) as "Y" | "N", + parentCodeValue: parentValue, }); // codeValue는 별도로 설정 (표시용) form.setValue("codeValue" as any, editingCode.codeValue || editingCode.code_value); } else { // 새 코드 모드: 자동 순서 계산 - const maxSortOrder = codes.length > 0 ? Math.max(...codes.map((c) => c.sortOrder || c.sort_order)) : 0; + const maxSortOrder = codes.length > 0 ? Math.max(...codes.map((c) => c.sortOrder || c.sort_order || 0)) : 0; + + // 기본 부모 코드가 있으면 설정 (하위 코드 추가 시) + const parentValue = defaultParentCode || ""; + + // 코드값 자동 생성 + const autoCodeValue = generateCodeValue(); form.reset({ - codeValue: "", + codeValue: autoCodeValue, codeName: "", codeNameEng: "", description: "", sortOrder: maxSortOrder + 1, + parentCodeValue: parentValue, }); } } - }, [isOpen, isEditing, editingCode, codes]); + }, [isOpen, isEditing, editingCode, codes, defaultParentCode]); const handleSubmit = form.handleSubmit(async (data) => { try { @@ -132,7 +137,7 @@ export function CodeFormModal({ isOpen, onClose, categoryCode, editingCode, code // 수정 await updateCodeMutation.mutateAsync({ categoryCode, - codeValue: editingCode.codeValue || editingCode.code_value, + codeValue: editingCode.codeValue || editingCode.code_value || "", data: data as UpdateCodeData, }); } else { @@ -156,50 +161,38 @@ export function CodeFormModal({ isOpen, onClose, categoryCode, editingCode, code - {isEditing ? "코드 수정" : "새 코드"} + + {isEditing ? "코드 수정" : defaultParentCode ? "하위 코드 추가" : "새 코드"} +
- {/* 코드값 */} -
- - { - const value = e.target.value.trim(); - if (value && !isEditing) { - setValidationStates((prev) => ({ - ...prev, - codeValue: { enabled: true, value }, - })); - } - }} - /> - {(form.formState.errors as any)?.codeValue && ( -

{getErrorMessage((form.formState.errors as any)?.codeValue)}

- )} - {!isEditing && !(form.formState.errors as any)?.codeValue && ( - - )} -
+ {/* 코드값 (자동 생성, 수정 시에만 표시) */} + {isEditing && ( +
+ +
+ {form.watch("codeValue")} +
+

코드값은 변경할 수 없습니다

+
+ )} {/* 코드명 */}
- + { const value = e.target.value.trim(); if (value) { @@ -211,7 +204,9 @@ export function CodeFormModal({ isOpen, onClose, categoryCode, editingCode, code }} /> {form.formState.errors.codeName && ( -

{getErrorMessage(form.formState.errors.codeName)}

+

+ {getErrorMessage(form.formState.errors.codeName)} +

)} {!form.formState.errors.codeName && ( - {/* 영문명 */} + {/* 영문명 (선택) */}
- + { - const value = e.target.value.trim(); - if (value) { - setValidationStates((prev) => ({ - ...prev, - codeNameEng: { enabled: true, value }, - })); - } - }} + placeholder="코드 영문명을 입력하세요 (선택사항)" + className="h-8 text-xs sm:h-10 sm:text-sm" /> - {form.formState.errors.codeNameEng && ( -

{getErrorMessage(form.formState.errors.codeNameEng)}

- )} - {!form.formState.errors.codeNameEng && ( - - )}
- {/* 설명 */} + {/* 설명 (선택) */}
- +