diff --git a/backend-node/package-lock.json b/backend-node/package-lock.json index 5b5eb7d7..f826a86a 100644 --- a/backend-node/package-lock.json +++ b/backend-node/package-lock.json @@ -12,6 +12,7 @@ "@types/mssql": "^9.1.8", "axios": "^1.11.0", "bcryptjs": "^2.4.3", + "bwip-js": "^4.8.0", "compression": "^1.7.4", "cors": "^2.8.5", "docx": "^9.5.1", @@ -4540,6 +4541,15 @@ "node": ">=10.16.0" } }, + "node_modules/bwip-js": { + "version": "4.8.0", + "resolved": "https://registry.npmjs.org/bwip-js/-/bwip-js-4.8.0.tgz", + "integrity": "sha512-gUDkDHSTv8/DJhomSIbO0fX/Dx0MO/sgllLxJyJfu4WixCQe9nfGJzmHm64ZCbxo+gUYQEsQcRmqcwcwPRwUkg==", + "license": "MIT", + "bin": { + "bwip-js": "bin/bwip-js.js" + } + }, "node_modules/bytes": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", diff --git a/backend-node/package.json b/backend-node/package.json index e078043c..e9ce3729 100644 --- a/backend-node/package.json +++ b/backend-node/package.json @@ -26,6 +26,7 @@ "@types/mssql": "^9.1.8", "axios": "^1.11.0", "bcryptjs": "^2.4.3", + "bwip-js": "^4.8.0", "compression": "^1.7.4", "cors": "^2.8.5", "docx": "^9.5.1", 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/controllers/reportController.ts b/backend-node/src/controllers/reportController.ts index a2e8e8a9..c6605d3e 100644 --- a/backend-node/src/controllers/reportController.ts +++ b/backend-node/src/controllers/reportController.ts @@ -27,7 +27,12 @@ import { BorderStyle, PageOrientation, convertMillimetersToTwip, + Header, + Footer, + HeadingLevel, } from "docx"; +import { WatermarkConfig } from "../types/report"; +import bwipjs from "bwip-js"; export class ReportController { /** @@ -1326,6 +1331,82 @@ export class ReportController { ); } + // Barcode 컴포넌트 (바코드 이미지가 미리 생성되어 전달된 경우) + else if (component.type === "barcode" && component.barcodeImageBase64) { + try { + const base64Data = + component.barcodeImageBase64.split(",")[1] || component.barcodeImageBase64; + const imageBuffer = Buffer.from(base64Data, "base64"); + result.push( + new ParagraphRef({ + children: [ + new ImageRunRef({ + data: imageBuffer, + transformation: { + width: Math.round(component.width * 0.75), + height: Math.round(component.height * 0.75), + }, + type: "png", + }), + ], + }) + ); + } catch (e) { + // 바코드 이미지 생성 실패 시 텍스트로 대체 + const barcodeValue = component.barcodeValue || "BARCODE"; + result.push( + new ParagraphRef({ + children: [ + new TextRunRef({ + text: `[${barcodeValue}]`, + size: pxToHalfPtFn(12), + font: "맑은 고딕", + }), + ], + }) + ); + } + } + + // Checkbox 컴포넌트 + else if (component.type === "checkbox") { + // 체크 상태 결정 (쿼리 바인딩 또는 고정값) + let isChecked = component.checkboxChecked === true; + if (component.checkboxFieldName && component.queryId && queryResultsMapRef[component.queryId]) { + const qResult = queryResultsMapRef[component.queryId]; + if (qResult.rows && qResult.rows.length > 0) { + const row = qResult.rows[0]; + const val = row[component.checkboxFieldName]; + // truthy/falsy 값 판정 + if (val === true || val === "true" || val === "Y" || val === 1 || val === "1") { + isChecked = true; + } else { + isChecked = false; + } + } + } + + const checkboxSymbol = isChecked ? "☑" : "☐"; + const checkboxLabel = component.checkboxLabel || ""; + const labelPosition = component.checkboxLabelPosition || "right"; + const displayText = labelPosition === "left" + ? `${checkboxLabel} ${checkboxSymbol}` + : `${checkboxSymbol} ${checkboxLabel}`; + + result.push( + new ParagraphRef({ + children: [ + new TextRunRef({ + text: displayText.trim(), + size: pxToHalfPtFn(component.fontSize || 14), + font: "맑은 고딕", + color: (component.fontColor || "#374151").replace("#", ""), + }), + ], + }) + ); + } + // Divider - 테이블 셀로 감싸서 정확한 너비 적용 else if ( component.type === "divider" && @@ -1354,6 +1435,135 @@ export class ReportController { return result; }; + // 바코드 이미지 생성 헬퍼 함수 + const generateBarcodeImage = async ( + component: any, + queryResultsMapRef: Record[] }> + ): Promise => { + try { + const barcodeType = component.barcodeType || "CODE128"; + const barcodeColor = (component.barcodeColor || "#000000").replace("#", ""); + const barcodeBackground = (component.barcodeBackground || "#ffffff").replace("#", ""); + + // 바코드 값 결정 (쿼리 바인딩 또는 고정값) + let barcodeValue = component.barcodeValue || "SAMPLE123"; + + // QR코드 다중 필드 모드 + if ( + barcodeType === "QR" && + component.qrUseMultiField && + component.qrDataFields && + component.qrDataFields.length > 0 && + component.queryId && + queryResultsMapRef[component.queryId] + ) { + const qResult = queryResultsMapRef[component.queryId]; + if (qResult.rows && qResult.rows.length > 0) { + // 모든 행 포함 모드 + if (component.qrIncludeAllRows) { + const allRowsData: Record[] = []; + qResult.rows.forEach((row) => { + const rowData: Record = {}; + component.qrDataFields!.forEach((field: { fieldName: string; label: string }) => { + if (field.fieldName && field.label) { + const val = row[field.fieldName]; + rowData[field.label] = val !== null && val !== undefined ? String(val) : ""; + } + }); + allRowsData.push(rowData); + }); + barcodeValue = JSON.stringify(allRowsData); + } else { + // 단일 행 (첫 번째 행만) + const row = qResult.rows[0]; + const jsonData: Record = {}; + component.qrDataFields.forEach((field: { fieldName: string; label: string }) => { + if (field.fieldName && field.label) { + const val = row[field.fieldName]; + jsonData[field.label] = val !== null && val !== undefined ? String(val) : ""; + } + }); + barcodeValue = JSON.stringify(jsonData); + } + } + } + // 단일 필드 바인딩 + else if (component.barcodeFieldName && component.queryId && queryResultsMapRef[component.queryId]) { + const qResult = queryResultsMapRef[component.queryId]; + if (qResult.rows && qResult.rows.length > 0) { + // QR코드 + 모든 행 포함 + if (barcodeType === "QR" && component.qrIncludeAllRows) { + const allValues = qResult.rows + .map((row) => { + const val = row[component.barcodeFieldName!]; + return val !== null && val !== undefined ? String(val) : ""; + }) + .filter((v) => v !== ""); + barcodeValue = JSON.stringify(allValues); + } else { + // 단일 행 (첫 번째 행만) + const row = qResult.rows[0]; + const val = row[component.barcodeFieldName]; + if (val !== null && val !== undefined) { + barcodeValue = String(val); + } + } + } + } + + // bwip-js 바코드 타입 매핑 + const bcidMap: Record = { + "CODE128": "code128", + "CODE39": "code39", + "EAN13": "ean13", + "EAN8": "ean8", + "UPC": "upca", + "QR": "qrcode", + }; + + const bcid = bcidMap[barcodeType] || "code128"; + const isQR = barcodeType === "QR"; + + // 바코드 옵션 설정 + const options: any = { + bcid: bcid, + text: barcodeValue, + scale: 3, + includetext: !isQR && component.showBarcodeText !== false, + textxalign: "center", + barcolor: barcodeColor, + backgroundcolor: barcodeBackground, + }; + + // QR 코드 옵션 + if (isQR) { + options.eclevel = component.qrErrorCorrectionLevel || "M"; + } + + // 바코드 이미지 생성 + const png = await bwipjs.toBuffer(options); + const base64 = png.toString("base64"); + return `data:image/png;base64,${base64}`; + } catch (error) { + console.error("바코드 생성 오류:", error); + return null; + } + }; + + // 모든 페이지의 바코드 컴포넌트에 대해 이미지 생성 + for (const page of layoutConfig.pages) { + if (page.components) { + for (const component of page.components) { + if (component.type === "barcode") { + const barcodeImage = await generateBarcodeImage(component, queryResultsMap); + if (barcodeImage) { + component.barcodeImageBase64 = barcodeImage; + } + } + } + } + } + // 섹션 생성 (페이지별) const sortedPages = layoutConfig.pages.sort( (a: any, b: any) => a.page_order - b.page_order @@ -2624,6 +2834,129 @@ export class ReportController { lastBottomY = adjustedY + component.height; } + // Barcode 컴포넌트 + else if (component.type === "barcode") { + if (component.barcodeImageBase64) { + try { + const base64Data = + component.barcodeImageBase64.split(",")[1] || component.barcodeImageBase64; + const imageBuffer = Buffer.from(base64Data, "base64"); + + // spacing을 위한 빈 paragraph + if (spacingBefore > 0) { + children.push( + new Paragraph({ + spacing: { before: spacingBefore, after: 0 }, + children: [], + }) + ); + } + + children.push( + new Paragraph({ + indent: { left: indentLeft }, + children: [ + new ImageRun({ + data: imageBuffer, + transformation: { + width: Math.round(component.width * 0.75), + height: Math.round(component.height * 0.75), + }, + type: "png", + }), + ], + }) + ); + } catch (imgError) { + console.error("바코드 이미지 오류:", imgError); + // 바코드 이미지 생성 실패 시 텍스트로 대체 + const barcodeValue = component.barcodeValue || "BARCODE"; + children.push( + new Paragraph({ + spacing: { before: spacingBefore, after: 0 }, + indent: { left: indentLeft }, + children: [ + new TextRun({ + text: `[${barcodeValue}]`, + size: pxToHalfPt(12), + font: "맑은 고딕", + }), + ], + }) + ); + } + } else { + // 바코드 이미지가 없는 경우 텍스트로 대체 + const barcodeValue = component.barcodeValue || "BARCODE"; + children.push( + new Paragraph({ + spacing: { before: spacingBefore, after: 0 }, + indent: { left: indentLeft }, + children: [ + new TextRun({ + text: `[${barcodeValue}]`, + size: pxToHalfPt(12), + font: "맑은 고딕", + }), + ], + }) + ); + } + lastBottomY = adjustedY + component.height; + } + + // Checkbox 컴포넌트 + else if (component.type === "checkbox") { + // 체크 상태 결정 (쿼리 바인딩 또는 고정값) + let isChecked = component.checkboxChecked === true; + if (component.checkboxFieldName && component.queryId && queryResultsMap[component.queryId]) { + const qResult = queryResultsMap[component.queryId]; + if (qResult.rows && qResult.rows.length > 0) { + const row = qResult.rows[0]; + const val = row[component.checkboxFieldName]; + // truthy/falsy 값 판정 + if (val === true || val === "true" || val === "Y" || val === 1 || val === "1") { + isChecked = true; + } else { + isChecked = false; + } + } + } + + const checkboxSymbol = isChecked ? "☑" : "☐"; + const checkboxLabel = component.checkboxLabel || ""; + const labelPosition = component.checkboxLabelPosition || "right"; + const displayText = labelPosition === "left" + ? `${checkboxLabel} ${checkboxSymbol}` + : `${checkboxSymbol} ${checkboxLabel}`; + + // spacing을 위한 빈 paragraph + if (spacingBefore > 0) { + children.push( + new Paragraph({ + spacing: { before: spacingBefore, after: 0 }, + children: [], + }) + ); + } + + children.push( + new Paragraph({ + indent: { left: indentLeft }, + children: [ + new TextRun({ + text: displayText.trim(), + size: pxToHalfPt(component.fontSize || 14), + font: "맑은 고딕", + color: (component.fontColor || "#374151").replace("#", ""), + }), + ], + }) + ); + + lastBottomY = adjustedY + component.height; + } + // Table 컴포넌트 else if (component.type === "table" && component.queryId) { const queryResult = queryResultsMap[component.queryId]; @@ -2734,6 +3067,36 @@ export class ReportController { children.push(new Paragraph({ children: [] })); } + // 워터마크 헤더 생성 (전체 페이지 공유 워터마크) + const watermark: WatermarkConfig | undefined = layoutConfig.watermark; + let headers: { default?: Header } | undefined; + + if (watermark?.enabled && watermark.type === "text" && watermark.text) { + // 워터마크 색상을 hex로 변환 (alpha 적용) + const opacity = watermark.opacity ?? 0.3; + const fontColor = watermark.fontColor || "#CCCCCC"; + // hex 색상에서 # 제거 + const cleanColor = fontColor.replace("#", ""); + + headers = { + default: new Header({ + children: [ + new Paragraph({ + alignment: AlignmentType.CENTER, + children: [ + new TextRun({ + text: watermark.text, + size: (watermark.fontSize || 48) * 2, // Word는 half-point 사용 + color: cleanColor, + bold: true, + }), + ], + }), + ], + }), + }; + } + return { properties: { page: { @@ -2753,6 +3116,7 @@ export class ReportController { }, }, }, + headers, children, }; }); diff --git a/backend-node/src/routes/commonCodeRoutes.ts b/backend-node/src/routes/commonCodeRoutes.ts index e6869e82..3885d12a 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..ac9768a1 100644 --- a/backend-node/src/services/menuCopyService.ts +++ b/backend-node/src/services/menuCopyService.ts @@ -938,7 +938,9 @@ export class MenuCopyService { copiedCategoryMappings = await this.copyCategoryMappingsAndValues( menuObjids, menuIdMap, + sourceCompanyCode, targetCompanyCode, + Array.from(screenIds), userId, client ); @@ -2569,11 +2571,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 +2704,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 +2775,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 +2830,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/backend-node/src/types/report.ts b/backend-node/src/types/report.ts index 2fe1cfd3..27254b0d 100644 --- a/backend-node/src/types/report.ts +++ b/backend-node/src/types/report.ts @@ -116,6 +116,22 @@ export interface UpdateReportRequest { useYn?: string; } +// 워터마크 설정 +export interface WatermarkConfig { + enabled: boolean; + type: "text" | "image"; + // 텍스트 워터마크 + text?: string; + fontSize?: number; + fontColor?: string; + // 이미지 워터마크 + imageUrl?: string; + // 공통 설정 + opacity: number; // 0~1 + style: "diagonal" | "center" | "tile"; + rotation?: number; // 대각선일 때 각도 (기본 -45) +} + // 페이지 설정 export interface PageConfig { page_id: string; @@ -136,6 +152,7 @@ export interface PageConfig { // 레이아웃 설정 export interface ReportLayoutConfig { pages: PageConfig[]; + watermark?: WatermarkConfig; // 전체 페이지 공유 워터마크 } // 레이아웃 저장 요청 @@ -166,3 +183,113 @@ export interface CreateTemplateRequest { layoutConfig?: any; defaultQueries?: any; } + +// 컴포넌트 설정 (프론트엔드와 동기화) +export interface ComponentConfig { + id: string; + type: string; + x: number; + y: number; + width: number; + height: number; + zIndex: number; + fontSize?: number; + fontFamily?: string; + fontWeight?: string; + fontColor?: string; + backgroundColor?: string; + borderWidth?: number; + borderColor?: string; + borderRadius?: number; + textAlign?: string; + padding?: number; + queryId?: string; + fieldName?: string; + defaultValue?: string; + format?: string; + visible?: boolean; + printable?: boolean; + conditional?: string; + locked?: boolean; + groupId?: string; + // 이미지 전용 + imageUrl?: string; + objectFit?: "contain" | "cover" | "fill" | "none"; + // 구분선 전용 + orientation?: "horizontal" | "vertical"; + lineStyle?: "solid" | "dashed" | "dotted" | "double"; + lineWidth?: number; + lineColor?: string; + // 서명/도장 전용 + showLabel?: boolean; + labelText?: string; + labelPosition?: "top" | "left" | "bottom" | "right"; + showUnderline?: boolean; + personName?: string; + // 테이블 전용 + tableColumns?: Array<{ + field: string; + header: string; + width?: number; + align?: "left" | "center" | "right"; + }>; + headerBackgroundColor?: string; + headerTextColor?: string; + showBorder?: boolean; + rowHeight?: number; + // 페이지 번호 전용 + pageNumberFormat?: "number" | "numberTotal" | "koreanNumber"; + // 카드 컴포넌트 전용 + cardTitle?: string; + cardItems?: Array<{ + label: string; + value: string; + fieldName?: string; + }>; + labelWidth?: number; + showCardBorder?: boolean; + showCardTitle?: boolean; + titleFontSize?: number; + labelFontSize?: number; + valueFontSize?: number; + titleColor?: string; + labelColor?: string; + valueColor?: string; + // 계산 컴포넌트 전용 + calcItems?: Array<{ + label: string; + value: number | string; + operator: "+" | "-" | "x" | "÷"; + fieldName?: string; + }>; + resultLabel?: string; + resultColor?: string; + resultFontSize?: number; + showCalcBorder?: boolean; + numberFormat?: "none" | "comma" | "currency"; + currencySuffix?: string; + // 바코드 컴포넌트 전용 + barcodeType?: "CODE128" | "CODE39" | "EAN13" | "EAN8" | "UPC" | "QR"; + barcodeValue?: string; + barcodeFieldName?: string; + showBarcodeText?: boolean; + barcodeColor?: string; + barcodeBackground?: string; + barcodeMargin?: number; + qrErrorCorrectionLevel?: "L" | "M" | "Q" | "H"; + // QR코드 다중 필드 (JSON 형식) + qrDataFields?: Array<{ + fieldName: string; + label: string; + }>; + qrUseMultiField?: boolean; + qrIncludeAllRows?: boolean; + // 체크박스 컴포넌트 전용 + checkboxChecked?: boolean; // 체크 상태 (고정값) + checkboxFieldName?: string; // 쿼리 필드 바인딩 (truthy/falsy 값) + checkboxLabel?: string; // 체크박스 옆 레이블 텍스트 + checkboxSize?: number; // 체크박스 크기 (px) + checkboxColor?: string; // 체크 색상 + checkboxBorderColor?: string; // 테두리 색상 + checkboxLabelPosition?: "left" | "right"; // 레이블 위치 +} 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/app/globals.css b/frontend/app/globals.css index be16f68d..06b7bd27 100644 --- a/frontend/app/globals.css +++ b/frontend/app/globals.css @@ -1,5 +1,5 @@ -/* ===== 서명용 손글씨 폰트 ===== */ -@import url("https://fonts.googleapis.com/css2?family=Allura&family=Dancing+Script:wght@700&family=Great+Vibes&family=Pacifico&family=Satisfy&family=Caveat:wght@700&family=Permanent+Marker&family=Shadows+Into+Light&family=Kalam:wght@700&family=Patrick+Hand&family=Indie+Flower&family=Amatic+SC:wght@700&family=Covered+By+Your+Grace&family=Nanum+Brush+Script&family=Nanum+Pen+Script&family=Gaegu:wght@700&family=Gugi&family=Single+Day&family=Stylish&family=Sunflower:wght@700&family=Dokdo&display=swap"); +/* ===== 서명용 손글씨 폰트 (완전한 한글 지원 폰트) ===== */ +@import url("https://fonts.googleapis.com/css2?family=Allura&family=Dancing+Script:wght@700&family=Great+Vibes&family=Pacifico&family=Satisfy&family=Caveat:wght@700&family=Permanent+Marker&family=Shadows+Into+Light&family=Kalam:wght@700&family=Patrick+Hand&family=Indie+Flower&family=Amatic+SC:wght@700&family=Covered+By+Your+Grace&family=Nanum+Brush+Script&family=Nanum+Pen+Script&family=Gaegu:wght@700&family=Hi+Melody&family=Gamja+Flower&family=Poor+Story&family=Do+Hyeon&family=Jua&display=swap"); /* ===== Tailwind CSS & Animations ===== */ @import "tailwindcss"; 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 && ( - - )}
- {/* 설명 */} + {/* 설명 (선택) */}
- +