diff --git a/backend-node/src/app.ts b/backend-node/src/app.ts index 97564672..d819d3a8 100644 --- a/backend-node/src/app.ts +++ b/backend-node/src/app.ts @@ -70,7 +70,7 @@ import departmentRoutes from "./routes/departmentRoutes"; // 부서 관리 import tableCategoryValueRoutes from "./routes/tableCategoryValueRoutes"; // 카테고리 값 관리 import codeMergeRoutes from "./routes/codeMergeRoutes"; // 코드 병합 import numberingRuleRoutes from "./routes/numberingRuleRoutes"; // 채번 규칙 관리 -import entitySearchRoutes from "./routes/entitySearchRoutes"; // 엔티티 검색 +import entitySearchRoutes, { entityOptionsRouter } from "./routes/entitySearchRoutes"; // 엔티티 검색 및 옵션 import screenEmbeddingRoutes from "./routes/screenEmbeddingRoutes"; // 화면 임베딩 및 데이터 전달 import screenGroupRoutes from "./routes/screenGroupRoutes"; // 화면 그룹 관리 import vehicleTripRoutes from "./routes/vehicleTripRoutes"; // 차량 운행 이력 관리 @@ -251,6 +251,7 @@ app.use("/api/table-categories", tableCategoryValueRoutes); // 카테고리 값 app.use("/api/code-merge", codeMergeRoutes); // 코드 병합 app.use("/api/numbering-rules", numberingRuleRoutes); // 채번 규칙 관리 app.use("/api/entity-search", entitySearchRoutes); // 엔티티 검색 +app.use("/api/entity", entityOptionsRouter); // 엔티티 옵션 (UnifiedSelect용) app.use("/api/driver", driverRoutes); // 공차중계 운전자 관리 app.use("/api/tax-invoice", taxInvoiceRoutes); // 세금계산서 관리 app.use("/api/cascading-relations", cascadingRelationRoutes); // 연쇄 드롭다운 관계 관리 diff --git a/backend-node/src/controllers/entitySearchController.ts b/backend-node/src/controllers/entitySearchController.ts index 4d911c57..06de789d 100644 --- a/backend-node/src/controllers/entitySearchController.ts +++ b/backend-node/src/controllers/entitySearchController.ts @@ -3,6 +3,101 @@ import { AuthenticatedRequest } from "../types/auth"; import { getPool } from "../database/db"; import { logger } from "../utils/logger"; +/** + * 엔티티 옵션 조회 API (UnifiedSelect용) + * GET /api/entity/:tableName/options + * + * Query Params: + * - value: 값 컬럼 (기본: id) + * - label: 표시 컬럼 (기본: name) + */ +export async function getEntityOptions(req: AuthenticatedRequest, res: Response) { + try { + const { tableName } = req.params; + const { value = "id", label = "name" } = req.query; + + // tableName 유효성 검증 + if (!tableName || tableName === "undefined" || tableName === "null") { + logger.warn("엔티티 옵션 조회 실패: 테이블명이 없음", { tableName }); + return res.status(400).json({ + success: false, + message: "테이블명이 지정되지 않았습니다.", + }); + } + + const companyCode = req.user!.companyCode; + const pool = getPool(); + + // 테이블의 실제 컬럼 목록 조회 + const columnsResult = await pool.query( + `SELECT column_name FROM information_schema.columns + WHERE table_schema = 'public' AND table_name = $1`, + [tableName] + ); + const existingColumns = new Set(columnsResult.rows.map((r: any) => r.column_name)); + + // 요청된 컬럼 검증 + const valueColumn = existingColumns.has(value as string) ? value : "id"; + const labelColumn = existingColumns.has(label as string) ? label : "name"; + + // 둘 다 없으면 에러 + if (!existingColumns.has(valueColumn as string)) { + return res.status(400).json({ + success: false, + message: `테이블 "${tableName}"에 값 컬럼 "${value}"이 존재하지 않습니다.`, + }); + } + + // label 컬럼이 없으면 value 컬럼을 label로도 사용 + const effectiveLabelColumn = existingColumns.has(labelColumn as string) ? labelColumn : valueColumn; + + // WHERE 조건 (멀티테넌시) + const whereConditions: string[] = []; + const params: any[] = []; + let paramIndex = 1; + + if (companyCode !== "*" && existingColumns.has("company_code")) { + whereConditions.push(`company_code = $${paramIndex}`); + params.push(companyCode); + paramIndex++; + } + + const whereClause = whereConditions.length > 0 + ? `WHERE ${whereConditions.join(" AND ")}` + : ""; + + // 쿼리 실행 (최대 500개) + const query = ` + SELECT ${valueColumn} as value, ${effectiveLabelColumn} as label + FROM ${tableName} + ${whereClause} + ORDER BY ${effectiveLabelColumn} ASC + LIMIT 500 + `; + + const result = await pool.query(query, params); + + logger.info("엔티티 옵션 조회 성공", { + tableName, + valueColumn, + labelColumn: effectiveLabelColumn, + companyCode, + rowCount: result.rowCount, + }); + + res.json({ + success: true, + data: result.rows, + }); + } catch (error: any) { + logger.error("엔티티 옵션 조회 오류", { + error: error.message, + stack: error.stack, + }); + res.status(500).json({ success: false, message: error.message }); + } +} + /** * 엔티티 검색 API * GET /api/entity-search/:tableName diff --git a/backend-node/src/controllers/tableManagementController.ts b/backend-node/src/controllers/tableManagementController.ts index 7c84898b..1f577777 100644 --- a/backend-node/src/controllers/tableManagementController.ts +++ b/backend-node/src/controllers/tableManagementController.ts @@ -97,11 +97,16 @@ export async function getColumnList( } const tableManagementService = new TableManagementService(); + + // 🔥 캐시 버스팅: _t 파라미터가 있으면 캐시 무시 + const bustCache = !!req.query._t; + const result = await tableManagementService.getColumnList( tableName, parseInt(page as string), parseInt(size as string), - companyCode // 🔥 회사 코드 전달 + companyCode, // 🔥 회사 코드 전달 + bustCache // 🔥 캐시 버스팅 옵션 ); logger.info( diff --git a/backend-node/src/routes/cascadingAutoFillRoutes.ts b/backend-node/src/routes/cascadingAutoFillRoutes.ts index a5107448..acb0cbc7 100644 --- a/backend-node/src/routes/cascadingAutoFillRoutes.ts +++ b/backend-node/src/routes/cascadingAutoFillRoutes.ts @@ -55,3 +55,5 @@ export default router; + + diff --git a/backend-node/src/routes/cascadingConditionRoutes.ts b/backend-node/src/routes/cascadingConditionRoutes.ts index 22cd2d2b..96ab25be 100644 --- a/backend-node/src/routes/cascadingConditionRoutes.ts +++ b/backend-node/src/routes/cascadingConditionRoutes.ts @@ -51,3 +51,5 @@ export default router; + + diff --git a/backend-node/src/routes/cascadingHierarchyRoutes.ts b/backend-node/src/routes/cascadingHierarchyRoutes.ts index 79a1c6e8..f77019be 100644 --- a/backend-node/src/routes/cascadingHierarchyRoutes.ts +++ b/backend-node/src/routes/cascadingHierarchyRoutes.ts @@ -67,3 +67,5 @@ export default router; + + diff --git a/backend-node/src/routes/cascadingMutualExclusionRoutes.ts b/backend-node/src/routes/cascadingMutualExclusionRoutes.ts index 352a05b5..6e4094f1 100644 --- a/backend-node/src/routes/cascadingMutualExclusionRoutes.ts +++ b/backend-node/src/routes/cascadingMutualExclusionRoutes.ts @@ -55,3 +55,5 @@ export default router; + + diff --git a/backend-node/src/routes/commonCodeRoutes.ts b/backend-node/src/routes/commonCodeRoutes.ts index d1205e51..3885d12a 100644 --- a/backend-node/src/routes/commonCodeRoutes.ts +++ b/backend-node/src/routes/commonCodeRoutes.ts @@ -73,4 +73,20 @@ router.get("/categories/:categoryCode/options", (req, res) => commonCodeController.getCodeOptions(req, res) ); +// 계층 구조 코드 조회 (트리 형태) +router.get("/categories/:categoryCode/hierarchy", (req, res) => + commonCodeController.getCodesHierarchy(req, res) +); + +// 자식 코드 조회 (연쇄 선택용) +router.get("/categories/:categoryCode/children", (req, res) => + commonCodeController.getChildCodes(req, res) +); + +// 카테고리 → 공통코드 호환 API (레거시 지원) +// 기존 카테고리 타입이 공통코드로 마이그레이션된 후에도 동작 +router.get("/category-options/:tableName/:columnName", (req, res) => + commonCodeController.getCategoryOptionsAsCode(req, res) +); + export default router; diff --git a/backend-node/src/routes/entitySearchRoutes.ts b/backend-node/src/routes/entitySearchRoutes.ts index 7677279a..f75260e9 100644 --- a/backend-node/src/routes/entitySearchRoutes.ts +++ b/backend-node/src/routes/entitySearchRoutes.ts @@ -1,6 +1,6 @@ import { Router } from "express"; import { authenticateToken } from "../middleware/authMiddleware"; -import { searchEntity } from "../controllers/entitySearchController"; +import { searchEntity, getEntityOptions } from "../controllers/entitySearchController"; const router = Router(); @@ -12,3 +12,12 @@ router.get("/:tableName", authenticateToken, searchEntity); export default router; +// 엔티티 옵션 라우터 (UnifiedSelect용) +export const entityOptionsRouter = Router(); + +/** + * 엔티티 옵션 조회 API + * GET /api/entity/:tableName/options + */ +entityOptionsRouter.get("/:tableName/options", authenticateToken, getEntityOptions); + diff --git a/backend-node/src/services/screenManagementService.ts b/backend-node/src/services/screenManagementService.ts index 92a35663..40628f12 100644 --- a/backend-node/src/services/screenManagementService.ts +++ b/backend-node/src/services/screenManagementService.ts @@ -1658,10 +1658,16 @@ export class ScreenManagementService { ? inputTypeMap.get(`${tableName}.${columnName}`) : null; + // 🆕 Unified 컴포넌트는 덮어쓰지 않음 (새로운 컴포넌트 시스템 보호) + const savedComponentType = properties?.componentType; + const isUnifiedComponent = savedComponentType?.startsWith("unified-"); + const component = { id: layout.component_id, - // 🔥 최신 componentType이 있으면 type 덮어쓰기 - type: latestTypeInfo?.componentType || layout.component_type as any, + // 🔥 최신 componentType이 있으면 type 덮어쓰기 (단, Unified 컴포넌트는 제외) + type: isUnifiedComponent + ? layout.component_type as any // Unified는 저장된 값 유지 + : (latestTypeInfo?.componentType || layout.component_type as any), position: { x: layout.position_x, y: layout.position_y, @@ -1670,8 +1676,8 @@ export class ScreenManagementService { size: { width: layout.width, height: layout.height }, parentId: layout.parent_id, ...properties, - // 🔥 최신 inputType이 있으면 widgetType, componentType 덮어쓰기 - ...(latestTypeInfo && { + // 🔥 최신 inputType이 있으면 widgetType, componentType 덮어쓰기 (단, Unified 컴포넌트는 제외) + ...(!isUnifiedComponent && latestTypeInfo && { widgetType: latestTypeInfo.inputType, inputType: latestTypeInfo.inputType, componentType: latestTypeInfo.componentType, diff --git a/backend-node/src/services/tableManagementService.ts b/backend-node/src/services/tableManagementService.ts index b714b186..70c82538 100644 --- a/backend-node/src/services/tableManagementService.ts +++ b/backend-node/src/services/tableManagementService.ts @@ -114,7 +114,8 @@ export class TableManagementService { tableName: string, page: number = 1, size: number = 50, - companyCode?: string // 🔥 회사 코드 추가 + companyCode?: string, // 🔥 회사 코드 추가 + bustCache: boolean = false // 🔥 캐시 버스팅 옵션 ): Promise<{ columns: ColumnTypeInfo[]; total: number; @@ -124,7 +125,7 @@ export class TableManagementService { }> { try { logger.info( - `컬럼 정보 조회 시작: ${tableName} (page: ${page}, size: ${size}), company: ${companyCode}` + `컬럼 정보 조회 시작: ${tableName} (page: ${page}, size: ${size}), company: ${companyCode}, bustCache: ${bustCache}` ); // 캐시 키 생성 (companyCode 포함) @@ -132,32 +133,37 @@ export class TableManagementService { CacheKeys.TABLE_COLUMNS(tableName, page, size) + `_${companyCode}`; const countCacheKey = CacheKeys.TABLE_COLUMN_COUNT(tableName); - // 캐시에서 먼저 확인 - const cachedResult = cache.get<{ - columns: ColumnTypeInfo[]; - total: number; - page: number; - size: number; - totalPages: number; - }>(cacheKey); - if (cachedResult) { - logger.info( - `컬럼 정보 캐시에서 조회: ${tableName}, ${cachedResult.columns.length}/${cachedResult.total}개` - ); + // 🔥 캐시 버스팅: bustCache가 true면 캐시 무시 + if (!bustCache) { + // 캐시에서 먼저 확인 + const cachedResult = cache.get<{ + columns: ColumnTypeInfo[]; + total: number; + page: number; + size: number; + totalPages: number; + }>(cacheKey); + if (cachedResult) { + logger.info( + `컬럼 정보 캐시에서 조회: ${tableName}, ${cachedResult.columns.length}/${cachedResult.total}개` + ); - // 디버깅: 캐시된 currency_code 확인 - const cachedCurrency = cachedResult.columns.find( - (col: any) => col.columnName === "currency_code" - ); - if (cachedCurrency) { - console.log(`💾 [캐시] currency_code:`, { - columnName: cachedCurrency.columnName, - inputType: cachedCurrency.inputType, - webType: cachedCurrency.webType, - }); + // 디버깅: 캐시된 currency_code 확인 + const cachedCurrency = cachedResult.columns.find( + (col: any) => col.columnName === "currency_code" + ); + if (cachedCurrency) { + console.log(`💾 [캐시] currency_code:`, { + columnName: cachedCurrency.columnName, + inputType: cachedCurrency.inputType, + webType: cachedCurrency.webType, + }); + } + + return cachedResult; } - - return cachedResult; + } else { + logger.info(`🔥 캐시 버스팅: ${tableName} 캐시 무시`); } // 전체 컬럼 수 조회 (캐시 확인) diff --git a/docs/phase0-component-usage-analysis.md b/docs/phase0-component-usage-analysis.md new file mode 100644 index 00000000..4c74ffd5 --- /dev/null +++ b/docs/phase0-component-usage-analysis.md @@ -0,0 +1,185 @@ +# Phase 0: 컴포넌트 사용 현황 분석 + +## 분석 일시 + +2024-12-19 + +## 분석 대상 + +- 활성화된 화면 정의 (screen_definitions.is_active = 'Y') +- 화면 레이아웃 (screen_layouts) + +--- + +## 1. 컴포넌트별 사용량 순위 + +### 상위 15개 컴포넌트 + +| 순위 | 컴포넌트 | 사용 횟수 | 사용 화면 수 | Unified 매핑 | +| :--: | :-------------------------- | :-------: | :----------: | :------------------------------ | +| 1 | button-primary | 571 | 364 | UnifiedInput (type: button) | +| 2 | text-input | 805 | 166 | **UnifiedInput (type: text)** | +| 3 | table-list | 130 | 130 | UnifiedList (viewMode: table) | +| 4 | table-search-widget | 127 | 127 | UnifiedList (searchable: true) | +| 5 | select-basic | 121 | 76 | **UnifiedSelect** | +| 6 | number-input | 86 | 34 | **UnifiedInput (type: number)** | +| 7 | date-input | 83 | 51 | **UnifiedDate** | +| 8 | file-upload | 41 | 18 | UnifiedMedia (type: file) | +| 9 | tabs-widget | 39 | 39 | UnifiedGroup (type: tabs) | +| 10 | split-panel-layout | 39 | 39 | UnifiedLayout (type: split) | +| 11 | category-manager | 38 | 38 | UnifiedBiz (type: category) | +| 12 | numbering-rule | 31 | 31 | UnifiedBiz (type: numbering) | +| 13 | selected-items-detail-input | 29 | 29 | 복합 컴포넌트 | +| 14 | modal-repeater-table | 25 | 25 | UnifiedList (modal: true) | +| 15 | image-widget | 29 | 29 | UnifiedMedia (type: image) | + +--- + +## 2. Unified 컴포넌트별 통합 대상 분석 + +### UnifiedInput (예상 통합 대상: 891개) + +| 기존 컴포넌트 | 사용 횟수 | 비율 | +| :------------ | :-------: | :---: | +| text-input | 805 | 90.3% | +| number-input | 86 | 9.7% | + +**우선순위: 1위** - 가장 많이 사용되는 컴포넌트 + +### UnifiedSelect (예상 통합 대상: 140개) + +| 기존 컴포넌트 | 사용 횟수 | widgetType | +| :------------------------ | :-------: | :--------- | +| select-basic (category) | 65 | category | +| select-basic (null) | 50 | - | +| autocomplete-search-input | 19 | entity | +| entity-search-input | 20 | entity | +| checkbox-basic | 7 | checkbox | +| radio-basic | 5 | radio | + +**우선순위: 2위** - 다양한 모드 지원 필요 + +### UnifiedDate (예상 통합 대상: 83개) + +| 기존 컴포넌트 | 사용 횟수 | +| :---------------- | :-------: | +| date-input (null) | 58 | +| date-input (date) | 23 | +| date-input (text) | 2 | + +**우선순위: 3위** + +### UnifiedList (예상 통합 대상: 283개) + +| 기존 컴포넌트 | 사용 횟수 | 비고 | +| :-------------------- | :-------: | :---------- | +| table-list | 130 | 기본 테이블 | +| table-search-widget | 127 | 검색 테이블 | +| modal-repeater-table | 25 | 모달 반복 | +| repeater-field-group | 15 | 반복 필드 | +| card-display | 11 | 카드 표시 | +| simple-repeater-table | 1 | 단순 반복 | + +**우선순위: 4위** - 핵심 데이터 표시 컴포넌트 + +### UnifiedMedia (예상 통합 대상: 70개) + +| 기존 컴포넌트 | 사용 횟수 | +| :------------ | :-------: | +| file-upload | 41 | +| image-widget | 29 | + +### UnifiedLayout (예상 통합 대상: 62개) + +| 기존 컴포넌트 | 사용 횟수 | +| :------------------ | :-------: | +| split-panel-layout | 39 | +| screen-split-panel | 21 | +| split-panel-layout2 | 2 | + +### UnifiedGroup (예상 통합 대상: 99개) + +| 기존 컴포넌트 | 사용 횟수 | +| :-------------------- | :-------: | +| tabs-widget | 39 | +| conditional-container | 23 | +| section-paper | 11 | +| section-card | 10 | +| text-display | 13 | +| universal-form-modal | 7 | +| repeat-screen-modal | 5 | + +### UnifiedBiz (예상 통합 대상: 79개) + +| 기존 컴포넌트 | 사용 횟수 | +| :--------------------- | :-------: | +| category-manager | 38 | +| numbering-rule | 31 | +| flow-widget | 8 | +| rack-structure | 2 | +| related-data-buttons | 2 | +| location-swap-selector | 2 | +| tax-invoice-list | 1 | + +--- + +## 3. 구현 우선순위 결정 + +### Phase 1 우선순위 (즉시 효과가 큰 컴포넌트) + +| 순위 | Unified 컴포넌트 | 통합 대상 수 | 영향 화면 수 | 이유 | +| :---: | :---------------- | :----------: | :----------: | :--------------- | +| **1** | **UnifiedInput** | 891개 | 200+ | 가장 많이 사용 | +| **2** | **UnifiedSelect** | 140개 | 100+ | 다양한 모드 필요 | +| **3** | **UnifiedDate** | 83개 | 51 | 비교적 단순 | + +### Phase 2 우선순위 (데이터 표시 컴포넌트) + +| 순위 | Unified 컴포넌트 | 통합 대상 수 | 이유 | +| :---: | :---------------- | :----------: | :--------------- | +| **4** | **UnifiedList** | 283개 | 핵심 데이터 표시 | +| **5** | **UnifiedLayout** | 62개 | 레이아웃 구조 | +| **6** | **UnifiedGroup** | 99개 | 콘텐츠 그룹화 | + +### Phase 3 우선순위 (특수 컴포넌트) + +| 순위 | Unified 컴포넌트 | 통합 대상 수 | 이유 | +| :---: | :------------------- | :----------: | :------------ | +| **7** | **UnifiedMedia** | 70개 | 파일/이미지 | +| **8** | **UnifiedBiz** | 79개 | 비즈니스 특화 | +| **9** | **UnifiedHierarchy** | 0개 | 신규 기능 | + +--- + +## 4. 주요 발견 사항 + +### 4.1 button-primary 분리 검토 + +- 사용량: 571개 (1위) +- 현재 계획: UnifiedInput에 포함 +- **제안**: 별도 `UnifiedButton` 컴포넌트로 분리 검토 + - 버튼은 입력과 성격이 다름 + - 액션 타입, 스타일, 권한 등 복잡한 설정 필요 + +### 4.2 conditional-container 처리 + +- 사용량: 23개 +- 현재 계획: 공통 conditional 속성으로 통합 +- **확인 필요**: 기존 화면에서 어떻게 마이그레이션할지 + +### 4.3 category 관련 컴포넌트 + +- select-basic (category): 65개 +- category-manager: 38개 +- **총 103개**의 카테고리 관련 컴포넌트 +- 카테고리 시스템 통합 중요 + +--- + +## 5. 다음 단계 + +1. [ ] 데이터 마이그레이션 전략 설계 (Phase 0-2) +2. [ ] sys_input_type JSON Schema 설계 (Phase 0-3) +3. [ ] DynamicConfigPanel 프로토타입 (Phase 0-4) +4. [ ] UnifiedInput 구현 시작 (Phase 1-1) + diff --git a/docs/phase0-migration-strategy.md b/docs/phase0-migration-strategy.md new file mode 100644 index 00000000..6ee91643 --- /dev/null +++ b/docs/phase0-migration-strategy.md @@ -0,0 +1,393 @@ +# Phase 0: 데이터 마이그레이션 전략 + +## 1. 현재 데이터 구조 분석 + +### screen_layouts.properties 구조 + +```jsonc +{ + // 기본 정보 + "type": "component", + "componentType": "text-input", // 기존 컴포넌트 타입 + + // 위치/크기 + "position": { "x": 68, "y": 80, "z": 1 }, + "size": { "width": 324, "height": 40 }, + + // 라벨 및 스타일 + "label": "품목코드", + "style": { + "labelColor": "#000000", + "labelDisplay": true, + "labelFontSize": "14px", + "labelFontWeight": "500", + "labelMarginBottom": "8px" + }, + + // 데이터 바인딩 + "tableName": "order_table", + "columnName": "part_code", + + // 필드 속성 + "required": true, + "readonly": false, + + // 컴포넌트별 설정 + "componentConfig": { + "type": "text-input", + "format": "none", + "webType": "text", + "multiline": false, + "placeholder": "텍스트를 입력하세요" + }, + + // 그리드 레이아웃 + "gridColumns": 5, + "gridRowIndex": 0, + "gridColumnStart": 1, + "gridColumnSpan": "third", + + // 기타 + "parentId": null +} +``` + +--- + +## 2. 마이그레이션 전략: 하이브리드 방식 + +### 2.1 비파괴적 전환 (권장) + +기존 필드를 유지하면서 새로운 필드를 추가하는 방식 + +```jsonc +{ + // 기존 필드 유지 (하위 호환성) + "componentType": "text-input", + "componentConfig": { ... }, + + // 신규 필드 추가 + "unifiedType": "UnifiedInput", // 새로운 통합 컴포넌트 타입 + "unifiedConfig": { // 새로운 설정 구조 + "type": "text", + "format": "none", + "placeholder": "텍스트를 입력하세요" + }, + + // 마이그레이션 메타데이터 + "_migration": { + "version": "2.0", + "migratedAt": "2024-12-19T00:00:00Z", + "migratedBy": "system", + "originalType": "text-input" + } +} +``` + +### 2.2 렌더링 로직 수정 + +```typescript +// 렌더러에서 unifiedType 우선 사용 +function renderComponent(props: ComponentProps) { + // 신규 타입이 있으면 Unified 컴포넌트 사용 + if (props.unifiedType) { + return ; + } + + // 없으면 기존 레거시 컴포넌트 사용 + return ; +} +``` + +--- + +## 3. 컴포넌트별 매핑 규칙 + +### 3.1 text-input → UnifiedInput + +```typescript +// AS-IS +{ + "componentType": "text-input", + "componentConfig": { + "type": "text-input", + "format": "none", + "webType": "text", + "multiline": false, + "placeholder": "텍스트를 입력하세요" + } +} + +// TO-BE +{ + "unifiedType": "UnifiedInput", + "unifiedConfig": { + "type": "text", // componentConfig.webType 또는 "text" + "format": "none", // componentConfig.format + "placeholder": "..." // componentConfig.placeholder + } +} +``` + +### 3.2 number-input → UnifiedInput + +```typescript +// AS-IS +{ + "componentType": "number-input", + "componentConfig": { + "type": "number-input", + "webType": "number", + "min": 0, + "max": 100, + "step": 1 + } +} + +// TO-BE +{ + "unifiedType": "UnifiedInput", + "unifiedConfig": { + "type": "number", + "min": 0, + "max": 100, + "step": 1 + } +} +``` + +### 3.3 select-basic → UnifiedSelect + +```typescript +// AS-IS (code 타입) +{ + "componentType": "select-basic", + "codeCategory": "ORDER_STATUS", + "componentConfig": { + "type": "select-basic", + "webType": "code", + "codeCategory": "ORDER_STATUS" + } +} + +// TO-BE +{ + "unifiedType": "UnifiedSelect", + "unifiedConfig": { + "mode": "dropdown", + "source": "code", + "codeGroup": "ORDER_STATUS" + } +} + +// AS-IS (entity 타입) +{ + "componentType": "select-basic", + "componentConfig": { + "type": "select-basic", + "webType": "entity", + "searchable": true, + "valueField": "id", + "displayField": "name" + } +} + +// TO-BE +{ + "unifiedType": "UnifiedSelect", + "unifiedConfig": { + "mode": "dropdown", + "source": "entity", + "searchable": true, + "valueField": "id", + "displayField": "name" + } +} +``` + +### 3.4 date-input → UnifiedDate + +```typescript +// AS-IS +{ + "componentType": "date-input", + "componentConfig": { + "type": "date-input", + "webType": "date", + "format": "YYYY-MM-DD" + } +} + +// TO-BE +{ + "unifiedType": "UnifiedDate", + "unifiedConfig": { + "type": "date", + "format": "YYYY-MM-DD" + } +} +``` + +--- + +## 4. 마이그레이션 스크립트 + +### 4.1 자동 마이그레이션 함수 + +```typescript +// lib/migration/componentMigration.ts + +interface MigrationResult { + success: boolean; + unifiedType: string; + unifiedConfig: Record; +} + +export function migrateToUnified( + componentType: string, + componentConfig: Record +): MigrationResult { + + switch (componentType) { + case 'text-input': + return { + success: true, + unifiedType: 'UnifiedInput', + unifiedConfig: { + type: componentConfig.webType || 'text', + format: componentConfig.format || 'none', + placeholder: componentConfig.placeholder + } + }; + + case 'number-input': + return { + success: true, + unifiedType: 'UnifiedInput', + unifiedConfig: { + type: 'number', + min: componentConfig.min, + max: componentConfig.max, + step: componentConfig.step + } + }; + + case 'select-basic': + return { + success: true, + unifiedType: 'UnifiedSelect', + unifiedConfig: { + mode: 'dropdown', + source: componentConfig.webType || 'static', + codeGroup: componentConfig.codeCategory, + searchable: componentConfig.searchable, + valueField: componentConfig.valueField, + displayField: componentConfig.displayField + } + }; + + case 'date-input': + return { + success: true, + unifiedType: 'UnifiedDate', + unifiedConfig: { + type: componentConfig.webType || 'date', + format: componentConfig.format + } + }; + + default: + return { + success: false, + unifiedType: '', + unifiedConfig: {} + }; + } +} +``` + +### 4.2 DB 마이그레이션 스크립트 + +```sql +-- 마이그레이션 백업 테이블 생성 +CREATE TABLE screen_layouts_backup_v2 AS +SELECT * FROM screen_layouts; + +-- 마이그레이션 실행 (text-input 예시) +UPDATE screen_layouts +SET properties = properties || jsonb_build_object( + 'unifiedType', 'UnifiedInput', + 'unifiedConfig', jsonb_build_object( + 'type', COALESCE(properties->'componentConfig'->>'webType', 'text'), + 'format', COALESCE(properties->'componentConfig'->>'format', 'none'), + 'placeholder', properties->'componentConfig'->>'placeholder' + ), + '_migration', jsonb_build_object( + 'version', '2.0', + 'migratedAt', NOW(), + 'originalType', 'text-input' + ) +) +WHERE properties->>'componentType' = 'text-input'; +``` + +--- + +## 5. 롤백 전략 + +### 5.1 롤백 스크립트 + +```sql +-- 마이그레이션 전 상태로 복원 +UPDATE screen_layouts sl +SET properties = slb.properties +FROM screen_layouts_backup_v2 slb +WHERE sl.layout_id = slb.layout_id; + +-- 또는 신규 필드만 제거 +UPDATE screen_layouts +SET properties = properties - 'unifiedType' - 'unifiedConfig' - '_migration'; +``` + +### 5.2 단계적 롤백 + +```typescript +// 특정 화면만 롤백 +async function rollbackScreen(screenId: number) { + await db.query(` + UPDATE screen_layouts sl + SET properties = properties - 'unifiedType' - 'unifiedConfig' - '_migration' + WHERE screen_id = $1 + `, [screenId]); +} +``` + +--- + +## 6. 마이그레이션 일정 + +| 단계 | 작업 | 대상 | 시점 | +|:---:|:---|:---|:---| +| 1 | 백업 테이블 생성 | 전체 | Phase 1 시작 전 | +| 2 | UnifiedInput 마이그레이션 | text-input, number-input | Phase 1 중 | +| 3 | UnifiedSelect 마이그레이션 | select-basic | Phase 1 중 | +| 4 | UnifiedDate 마이그레이션 | date-input | Phase 1 중 | +| 5 | 검증 및 테스트 | 전체 | Phase 1 완료 후 | +| 6 | 레거시 필드 제거 | 전체 | Phase 5 (추후) | + +--- + +## 7. 주의사항 + +1. **항상 백업 먼저**: 마이그레이션 전 반드시 백업 테이블 생성 +2. **점진적 전환**: 한 번에 모든 컴포넌트를 마이그레이션하지 않음 +3. **하위 호환성**: 기존 필드 유지로 롤백 가능하게 +4. **테스트 필수**: 각 마이그레이션 단계별 화면 테스트 + + diff --git a/docs/unified-components-implementation.md b/docs/unified-components-implementation.md new file mode 100644 index 00000000..663e344e --- /dev/null +++ b/docs/unified-components-implementation.md @@ -0,0 +1,192 @@ +# Unified Components 구현 완료 보고서 + +## 구현 일시 + +2024-12-19 + +## 구현된 컴포넌트 목록 (10개) + +### Phase 1: 핵심 입력 컴포넌트 + +| 컴포넌트 | 파일 | 모드/타입 | 설명 | +| :---------------- | :------------------ | :-------------------------------------------- | :---------------------- | +| **UnifiedInput** | `UnifiedInput.tsx` | text, number, password, slider, color, button | 통합 입력 컴포넌트 | +| **UnifiedSelect** | `UnifiedSelect.tsx` | dropdown, radio, check, tag, toggle, swap | 통합 선택 컴포넌트 | +| **UnifiedDate** | `UnifiedDate.tsx` | date, time, datetime + range | 통합 날짜/시간 컴포넌트 | + +### Phase 2: 레이아웃 및 그룹 컴포넌트 + +| 컴포넌트 | 파일 | 모드/타입 | 설명 | +| :---------------- | :------------------ | :-------------------------------------------------------- | :--------------------- | +| **UnifiedList** | `UnifiedList.tsx` | table, card, kanban, list | 통합 리스트 컴포넌트 | +| **UnifiedLayout** | `UnifiedLayout.tsx` | grid, split, flex, divider, screen-embed | 통합 레이아웃 컴포넌트 | +| **UnifiedGroup** | `UnifiedGroup.tsx` | tabs, accordion, section, card-section, modal, form-modal | 통합 그룹 컴포넌트 | + +### Phase 3: 미디어 및 비즈니스 컴포넌트 + +| 컴포넌트 | 파일 | 모드/타입 | 설명 | +| :------------------- | :--------------------- | :------------------------------------------------------------- | :---------------------- | +| **UnifiedMedia** | `UnifiedMedia.tsx` | file, image, video, audio | 통합 미디어 컴포넌트 | +| **UnifiedBiz** | `UnifiedBiz.tsx` | flow, rack, map, numbering, category, mapping, related-buttons | 통합 비즈니스 컴포넌트 | +| **UnifiedHierarchy** | `UnifiedHierarchy.tsx` | tree, org, bom, cascading | 통합 계층 구조 컴포넌트 | + +--- + +## 공통 인프라 + +### 설정 패널 + +- **DynamicConfigPanel**: JSON Schema 기반 동적 설정 UI 생성 + +### 렌더러 + +- **UnifiedComponentRenderer**: unifiedType에 따른 동적 컴포넌트 렌더링 + +--- + +## 파일 구조 + +``` +frontend/components/unified/ +├── index.ts # 모듈 인덱스 +├── UnifiedComponentRenderer.tsx # 동적 렌더러 +├── DynamicConfigPanel.tsx # JSON Schema 설정 패널 +├── UnifiedInput.tsx # 통합 입력 +├── UnifiedSelect.tsx # 통합 선택 +├── UnifiedDate.tsx # 통합 날짜 +├── UnifiedList.tsx # 통합 리스트 +├── UnifiedLayout.tsx # 통합 레이아웃 +├── UnifiedGroup.tsx # 통합 그룹 +├── UnifiedMedia.tsx # 통합 미디어 +├── UnifiedBiz.tsx # 통합 비즈니스 +└── UnifiedHierarchy.tsx # 통합 계층 + +frontend/types/ +└── unified-components.ts # 타입 정의 + +db/migrations/ +└── unified_component_schema.sql # DB 스키마 (미실행) +``` + +--- + +## 사용 예시 + +### 기본 사용법 + +```tsx +import { + UnifiedInput, + UnifiedSelect, + UnifiedDate, + UnifiedList, + UnifiedComponentRenderer +} from "@/components/unified"; + +// UnifiedInput 사용 + + +// UnifiedSelect 사용 + + +// UnifiedDate 사용 + + +// UnifiedList 사용 + +``` + +### 동적 렌더링 + +```tsx +import { UnifiedComponentRenderer } from "@/components/unified"; + +// unifiedType에 따라 자동으로 적절한 컴포넌트 렌더링 +; +``` + +--- + +## 주의사항 + +### 기존 컴포넌트와의 공존 + +1. **기존 컴포넌트는 그대로 유지**: 모든 레거시 컴포넌트는 정상 동작 +2. **신규 화면에서만 Unified 컴포넌트 사용**: 기존 화면에 영향 없음 +3. **마이그레이션 없음**: 자동 마이그레이션 진행하지 않음 + +### 데이터베이스 마이그레이션 + +`db/migrations/unified_component_schema.sql` 파일은 아직 실행되지 않았습니다. +필요시 수동으로 실행해야 합니다: + +```bash +psql -h localhost -U postgres -d plm_db -f db/migrations/unified_component_schema.sql +``` + +--- + +## 다음 단계 (선택) + +1. **화면 관리 에디터 통합**: Unified 컴포넌트를 화면 에디터의 컴포넌트 팔레트에 추가 +2. **기존 비즈니스 컴포넌트 연동**: UnifiedBiz의 플레이스홀더를 실제 구현으로 교체 +3. **테스트 페이지 작성**: 모든 Unified 컴포넌트 데모 페이지 +4. **문서화**: 각 컴포넌트별 상세 사용 가이드 + +--- + +## 관련 문서 + +- `PLAN_RENEWAL.md`: 리뉴얼 계획서 +- `docs/phase0-component-usage-analysis.md`: 컴포넌트 사용 현황 분석 +- `docs/phase0-migration-strategy.md`: 마이그레이션 전략 (참고용) + diff --git a/docs/노드플로우_개선사항.md b/docs/노드플로우_개선사항.md index c9349b94..a59f4499 100644 --- a/docs/노드플로우_개선사항.md +++ b/docs/노드플로우_개선사항.md @@ -587,3 +587,5 @@ const result = await executeNodeFlow(flowId, { + + diff --git a/docs/메일발송_기능_사용_가이드.md b/docs/메일발송_기능_사용_가이드.md index 42900211..ef62a60a 100644 --- a/docs/메일발송_기능_사용_가이드.md +++ b/docs/메일발송_기능_사용_가이드.md @@ -360,3 +360,5 @@ + + diff --git a/docs/즉시저장_버튼_액션_구현_계획서.md b/docs/즉시저장_버튼_액션_구현_계획서.md index c392eece..806e480d 100644 --- a/docs/즉시저장_버튼_액션_구현_계획서.md +++ b/docs/즉시저장_버튼_액션_구현_계획서.md @@ -346,3 +346,5 @@ const getComponentValue = (componentId: string) => { + + diff --git a/docs/컴포넌트_분석_및_통합_계획.md b/docs/컴포넌트_분석_및_통합_계획.md new file mode 100644 index 00000000..88be78c8 --- /dev/null +++ b/docs/컴포넌트_분석_및_통합_계획.md @@ -0,0 +1,339 @@ +# 입력 컴포넌트 분석 및 통합 계획 + +> 작성일: 2024-12-23 +> 상태: 1차 정리 완료 + +## 분석 대상 컴포넌트 목록 + +| 번호 | 컴포넌트 ID | 한글명 | 패널 표시 | 통합 대상 | +|------|-------------|--------|----------|----------| +| 1 | rack-structure | 렉 구조 설정 | 숨김 | UnifiedBiz (rack) | +| 2 | mail-recipient-selector | 메일 수신자 선택 | 숨김 | DataFlow 전용 | +| 3 | repeater-field-group | 반복 필드 그룹 | 숨김 | 현재 사용 안함 | +| 4 | universal-form-modal | 범용 폼 모달 | **유지** | 독립 유지 | +| 5 | selected-items-detail-input | 선택 항목 상세입력 | **유지** | 독립 유지 | +| 6 | entity-search-input | 엔티티 검색 입력 | 숨김 | UnifiedSelect (entity 모드) | +| 7 | image-widget | 이미지 위젯 | 숨김 | UnifiedMedia (image) | +| 8 | autocomplete-search-input | 자동완성 검색 입력 | 숨김 | UnifiedSelect (autocomplete 모드) | +| 9 | location-swap-selector | 출발지/도착지 선택 | **유지** | 독립 유지 | +| 10 | file-upload | 파일 업로드 | 숨김 | UnifiedMedia (file) | + +--- + +## 1. 렉 구조 설정 (rack-structure) + +### 현재 구현 +- **위치**: `frontend/lib/registry/components/rack-structure/` +- **주요 기능**: + - 창고 렉 위치를 열 범위와 단 수로 일괄 생성 + - 조건별 설정 (렉 라인, 열 범위, 단 수) + - 미리보기 및 통계 표시 + - 템플릿 저장/불러오기 +- **카테고리**: INPUT +- **크기**: 1200 x 800 + +### 분석 +- WMS(창고관리) 전용 특수 컴포넌트 +- 복잡한 비즈니스 로직 포함 (위치 코드 자동 생성) +- formData 컨텍스트 의존 (창고ID, 층, 구역 등) + +### 통합 방안 +- **결정**: `UnifiedBiz` 컴포넌트의 `rack` 비즈니스 타입으로 통합 +- **이유**: 비즈니스 특화 컴포넌트이므로 UnifiedBiz가 적합 +- **작업**: + - UnifiedBiz에서 bizType="rack" 선택 시 RackStructureComponent 렌더링 + - 설정 패널 통합 + +--- + +## 2. 메일 수신자 선택 (mail-recipient-selector) + +### 현재 구현 +- **위치**: `frontend/lib/registry/components/mail-recipient-selector/` +- **주요 기능**: + - 내부 인원 선택 (user_info 테이블) + - 외부 이메일 직접 입력 + - 수신자(To) / 참조(CC) 구분 +- **카테고리**: INPUT +- **크기**: 400 x 200 + +### 분석 +- 메일 발송 워크플로우 전용 컴포넌트 +- 내부 사용자 검색 + 외부 이메일 입력 복합 기능 +- DataFlow 노드에서 참조됨 (EmailActionProperties) + +### 통합 방안 +- **결정**: **독립 유지** +- **이유**: + - 메일 시스템 전용 복합 기능 + - 다른 컴포넌트와 기능이 겹치지 않음 + - DataFlow와의 긴밀한 연동 + +--- + +## 3. 반복 필드 그룹 (repeater-field-group) + +### 현재 구현 +- **위치**: `frontend/components/webtypes/RepeaterInput.tsx`, `frontend/components/webtypes/config/RepeaterConfigPanel.tsx` +- **주요 기능**: + - 동적 항목 추가/제거 + - 다양한 필드 타입 지원 (text, number, select, category, calculated 등) + - 계산식 필드 (합계, 평균 등) + - 레이아웃 옵션 (grid, table, card) + - 드래그앤드롭 순서 변경 +- **카테고리**: INPUT +- **크기**: 화면 설정에 따라 동적 + +### 분석 +- 매우 복잡한 컴포넌트 (943줄) +- 견적서, 주문서 등 반복 입력이 필요한 화면에서 핵심 역할 +- 카테고리 매핑, 계산식, 반응형 지원 + +### 통합 방안 +- **결정**: **독립 유지** +- **이유**: + - 너무 복잡하고 기능이 방대함 + - 이미 잘 동작하고 있음 + - 통합 시 오히려 유지보수 어려워짐 + +--- + +## 4. 범용 폼 모달 (universal-form-modal) + +### 현재 구현 +- **위치**: `frontend/lib/registry/components/universal-form-modal/` +- **주요 기능**: + - 섹션 기반 폼 레이아웃 + - 반복 섹션 (겸직 등록 등) + - 채번규칙 연동 + - 다중 행 저장 + - 외부 데이터 수신 +- **카테고리**: INPUT +- **크기**: 800 x 600 + +### 분석 +- ScreenModal, SaveModal과 기능 중복 가능성 +- 섹션 기반 레이아웃이 핵심 차별점 +- 복잡한 입력 시나리오 지원 + +### 통합 방안 +- **결정**: `UnifiedGroup`의 `formModal` 타입으로 통합 검토 +- **현실적 접근**: + - 당장 통합보다는 ScreenModal 시스템과의 차별화 유지 + - 향후 섹션 기반 레이아웃 기능을 ScreenModal에 반영 + +--- + +## 5. 선택 항목 상세입력 (selected-items-detail-input) + +### 현재 구현 +- **위치**: `frontend/lib/registry/components/selected-items-detail-input/` +- **주요 기능**: + - 선택된 데이터 목록 표시 + - 각 항목별 추가 필드 입력 + - 레이아웃 옵션 (grid, table) +- **카테고리**: INPUT +- **크기**: 800 x 400 + +### 분석 +- RepeatScreenModal과 연계되는 컴포넌트 +- 선택된 항목에 대한 상세 정보 일괄 입력 용도 +- 특수한 사용 사례 (품목 선택 후 수량 입력 등) + +### 통합 방안 +- **결정**: **독립 유지** +- **이유**: + - 특수한 워크플로우 지원 + - 다른 컴포넌트와 기능 중복 없음 + +--- + +## 6. 엔티티 검색 입력 (entity-search-input) + +### 현재 구현 +- **위치**: `frontend/lib/registry/components/entity-search-input/` +- **주요 기능**: + - 콤보박스 모드 (inline) + - 모달 검색 모드 + - 추가 필드 표시 옵션 +- **카테고리**: INPUT +- **크기**: 300 x 40 +- **webType**: entity + +### 분석 +- UnifiedSelect의 entity 모드와 기능 중복 +- 모달 검색 기능이 차별점 +- EntityWidget과도 유사 + +### 통합 방안 +- **결정**: `UnifiedSelect` entity 모드로 통합 +- **작업**: + - UnifiedSelect에 `searchMode: "modal" | "inline" | "autocomplete"` 옵션 추가 + - 모달 검색 UI 통합 + - 기존 entity-search-input은 deprecated 처리 + +--- + +## 7. 이미지 위젯 (image-widget) + +### 현재 구현 +- **위치**: `frontend/lib/registry/components/image-widget/` +- **주요 기능**: + - 이미지 업로드 + - 미리보기 + - 드래그앤드롭 지원 +- **카테고리**: INPUT +- **크기**: 200 x 200 +- **webType**: image + +### 분석 +- UnifiedMedia의 ImageUploader와 기능 동일 +- 이미 ImageWidget 컴포넌트 재사용 중 + +### 통합 방안 +- **결정**: `UnifiedMedia` image 타입으로 통합 완료 +- **상태**: 이미 UnifiedMedia.ImageUploader로 구현됨 +- **작업**: + - 컴포넌트 패널에서 image-widget 제거 + - UnifiedMedia 사용 권장 + +--- + +## 8. 자동완성 검색 입력 (autocomplete-search-input) + +### 현재 구현 +- **위치**: `frontend/lib/registry/components/autocomplete-search-input/` +- **주요 기능**: + - 타이핑 시 드롭다운 검색 + - 엔티티 테이블 연동 + - 추가 필드 표시 +- **카테고리**: INPUT +- **크기**: 300 x 40 +- **webType**: entity + +### 분석 +- entity-search-input과 유사하지만 UI 방식이 다름 +- Command/Popover 기반 자동완성 + +### 통합 방안 +- **결정**: `UnifiedSelect` entity 모드의 autocomplete 옵션으로 통합 +- **작업**: + - UnifiedSelect에서 `searchMode: "autocomplete"` 옵션 추가 + - 자동완성 검색 로직 통합 + +--- + +## 9. 출발지/도착지 선택 (location-swap-selector) + +### 현재 구현 +- **위치**: `frontend/lib/registry/components/location-swap-selector/` +- **주요 기능**: + - 출발지/도착지 두 개 필드 동시 관리 + - 스왑 버튼으로 교환 + - 모바일 최적화 UI + - 다양한 데이터 소스 (table, code, static) +- **카테고리**: INPUT +- **크기**: 400 x 100 + +### 분석 +- 물류/운송 시스템 전용 컴포넌트 +- 두 개의 Select를 묶은 복합 컴포넌트 +- 스왑 기능이 핵심 + +### 통합 방안 +- **결정**: **독립 유지** +- **이유**: + - 특수 용도 (물류 시스템) + - 다른 컴포넌트와 기능 중복 없음 + - 복합 필드 관리 (출발지 + 도착지) + +--- + +## 10. 파일 업로드 (file-upload) + +### 현재 구현 +- **위치**: `frontend/lib/registry/components/file-upload/` +- **주요 기능**: + - 파일 선택/업로드 + - 드래그앤드롭 + - 업로드 진행률 표시 + - 파일 목록 관리 +- **카테고리**: INPUT +- **크기**: 350 x 240 +- **webType**: file + +### 분석 +- UnifiedMedia의 FileUploader와 기능 동일 +- attach_file_info 테이블 연동 + +### 통합 방안 +- **결정**: `UnifiedMedia` file 타입으로 통합 +- **상태**: 이미 UnifiedMedia.FileUploader로 구현됨 +- **작업**: + - 컴포넌트 패널에서 file-upload 제거 + - UnifiedMedia 사용 권장 + +--- + +## 통합 우선순위 및 작업 계획 + +### Phase 1: 즉시 통합 가능 (작업 최소) + +| 컴포넌트 | 통합 대상 | 예상 작업량 | 비고 | +|----------|----------|------------|------| +| image-widget | UnifiedMedia (image) | 1일 | 이미 구현됨, 패널에서 숨기기만 | +| file-upload | UnifiedMedia (file) | 1일 | 이미 구현됨, 패널에서 숨기기만 | + +### Phase 2: 기능 통합 필요 (중간 작업) + +| 컴포넌트 | 통합 대상 | 예상 작업량 | 비고 | +|----------|----------|------------|------| +| entity-search-input | UnifiedSelect (entity) | 3일 | 모달 검색 모드 추가 | +| autocomplete-search-input | UnifiedSelect (entity) | 2일 | autocomplete 모드 추가 | +| rack-structure | UnifiedBiz (rack) | 2일 | 비즈니스 타입 연결 | + +### Phase 3: 독립 유지 (작업 없음) + +| 컴포넌트 | 이유 | +|----------|------| +| mail-recipient-selector | 메일 시스템 전용 | +| repeater-field-group | 너무 복잡, 잘 동작 중 | +| universal-form-modal | ScreenModal과 차별화 필요 | +| selected-items-detail-input | 특수 워크플로우 | +| location-swap-selector | 물류 시스템 전용 | + +--- + +## 결론 + +### 즉시 실행 가능한 작업 +1. **ComponentsPanel 정리**: + - `image-widget`, `file-upload` 숨김 처리 (UnifiedMedia 사용) + - 중복 컴포넌트 정리 + +2. **UnifiedBiz 연결**: + - `bizType: "rack"` 선택 시 `RackStructureComponent` 렌더링 연결 + +### 향후 계획 +1. UnifiedSelect에 entity 검색 모드 통합 +2. UnifiedMedia 설정 패널 강화 +3. 독립 유지 컴포넌트들의 문서화 + +--- + +## 컴포넌트 패널 정리 제안 + +### 숨길 컴포넌트 (Unified로 대체됨) +- `image-widget` → UnifiedMedia 사용 +- `file-upload` → UnifiedMedia 사용 +- `entity-search-input` → UnifiedSelect (entity 모드) 사용 예정 +- `autocomplete-search-input` → UnifiedSelect (autocomplete 모드) 사용 예정 + +### 유지할 컴포넌트 (독립 기능) +- `rack-structure` - WMS 전용 (UnifiedBiz 연결 예정) +- `mail-recipient-selector` - 메일 시스템 전용 +- `repeater-field-group` - 반복 입력 전용 +- `universal-form-modal` - 복잡한 폼 전용 +- `selected-items-detail-input` - 상세 입력 전용 +- `location-swap-selector` - 물류 시스템 전용 + diff --git a/frontend/app/(main)/admin/screenMng/screenMngList/page.tsx b/frontend/app/(main)/admin/screenMng/screenMngList/page.tsx index 512af3e8..482aaa2c 100644 --- a/frontend/app/(main)/admin/screenMng/screenMngList/page.tsx +++ b/frontend/app/(main)/admin/screenMng/screenMngList/page.tsx @@ -3,12 +3,13 @@ import { useState, useEffect, useCallback } from "react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; -import { ArrowLeft, Plus, RefreshCw, Search, LayoutGrid, LayoutList } from "lucide-react"; +import { ArrowLeft, Plus, RefreshCw, Search, LayoutGrid, LayoutList, TestTube2 } from "lucide-react"; import ScreenList from "@/components/screen/ScreenList"; import ScreenDesigner from "@/components/screen/ScreenDesigner"; import TemplateManager from "@/components/screen/TemplateManager"; import { ScreenGroupTreeView } from "@/components/screen/ScreenGroupTreeView"; import { ScreenRelationFlow } from "@/components/screen/ScreenRelationFlow"; +import { UnifiedComponentsDemo } from "@/components/unified"; import { ScrollToTop } from "@/components/common/ScrollToTop"; import { ScreenDefinition } from "@/types/screen"; import { screenApi } from "@/lib/api/screen"; @@ -16,7 +17,7 @@ import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; import CreateScreenModal from "@/components/screen/CreateScreenModal"; // 단계별 진행을 위한 타입 정의 -type Step = "list" | "design" | "template"; +type Step = "list" | "design" | "template" | "unified-test"; type ViewMode = "tree" | "table"; export default function ScreenManagementPage() { @@ -93,6 +94,15 @@ export default function ScreenManagementPage() { ); } + // Unified 컴포넌트 테스트 모드 + if (currentStep === "unified-test") { + return ( +
+ goToStep("list")} /> +
+ ); + } + return (
{/* 페이지 헤더 */} @@ -103,6 +113,15 @@ export default function ScreenManagementPage() {

화면을 그룹별로 관리하고 데이터 관계를 확인합니다

+ {/* Unified 컴포넌트 테스트 버튼 */} + {/* 뷰 모드 전환 */} setViewMode(v as ViewMode)}> diff --git a/frontend/app/(main)/screens/[screenId]/page.tsx b/frontend/app/(main)/screens/[screenId]/page.tsx index dffbd75b..dd9fcc3a 100644 --- a/frontend/app/(main)/screens/[screenId]/page.tsx +++ b/frontend/app/(main)/screens/[screenId]/page.tsx @@ -23,6 +23,7 @@ import { TableSearchWidgetHeightProvider, useTableSearchWidgetHeight } from "@/c import { ScreenContextProvider } from "@/contexts/ScreenContext"; // 컴포넌트 간 통신 import { SplitPanelProvider } from "@/lib/registry/components/split-panel-layout/SplitPanelContext"; // 분할 패널 리사이즈 import { ActiveTabProvider } from "@/contexts/ActiveTabContext"; // 활성 탭 관리 +import { evaluateConditional } from "@/lib/utils/conditionalEvaluator"; // 조건부 표시 평가 function ScreenViewPage() { const params = useParams(); @@ -218,6 +219,67 @@ function ScreenViewPage() { initAutoFill(); }, [layout, user]); + // 🆕 조건부 비활성화/숨김 시 해당 필드 값 초기화 + // 조건 필드들의 값을 추적하여 변경 시에만 실행 + const conditionalFieldValues = useMemo(() => { + if (!layout?.components) return ""; + + // 조건부 설정에 사용되는 필드들의 현재 값을 JSON 문자열로 만들어 비교 + const conditionFields = new Set(); + layout.components.forEach((component) => { + const conditional = (component as any).conditional; + if (conditional?.enabled && conditional.field) { + conditionFields.add(conditional.field); + } + }); + + const values: Record = {}; + conditionFields.forEach((field) => { + values[field] = (formData as Record)[field]; + }); + + return JSON.stringify(values); + }, [layout?.components, formData]); + + useEffect(() => { + if (!layout?.components) return; + + const fieldsToReset: string[] = []; + + layout.components.forEach((component) => { + const conditional = (component as any).conditional; + if (!conditional?.enabled) return; + + const conditionalResult = evaluateConditional( + conditional, + formData as Record, + layout.components, + ); + + // 숨김 또는 비활성화 상태인 경우 + if (!conditionalResult.visible || conditionalResult.disabled) { + const fieldName = (component as any).columnName || component.id; + const currentValue = (formData as Record)[fieldName]; + + // 값이 있으면 초기화 대상에 추가 + if (currentValue !== undefined && currentValue !== "" && currentValue !== null) { + fieldsToReset.push(fieldName); + } + } + }); + + // 초기화할 필드가 있으면 한 번에 처리 + if (fieldsToReset.length > 0) { + setFormData((prev) => { + const updated = { ...prev }; + fieldsToReset.forEach((fieldName) => { + updated[fieldName] = ""; + }); + return updated; + }); + } + }, [conditionalFieldValues, layout?.components]); + // 캔버스 비율 조정 (사용자 화면에 맞게 자동 스케일) - 초기 로딩 시에만 계산 // 브라우저 배율 조정 시 메뉴와 화면이 함께 축소/확대되도록 resize 이벤트는 감지하지 않음 useEffect(() => { @@ -469,9 +531,30 @@ function ScreenViewPage() { <> {/* 일반 컴포넌트들 */} {adjustedComponents.map((component) => { + // 조건부 표시 설정이 있는 경우에만 평가 + const conditional = (component as any).conditional; + let conditionalDisabled = false; + + if (conditional?.enabled) { + const conditionalResult = evaluateConditional( + conditional, + formData as Record, + layout?.components || [], + ); + + // 조건에 따라 숨김 처리 + if (!conditionalResult.visible) { + return null; + } + + // 조건에 따라 비활성화 처리 + conditionalDisabled = conditionalResult.disabled; + } + // 화면 관리 해상도를 사용하므로 위치 조정 불필요 return ( | null; // 탭 관련 정보 (탭 내부의 컴포넌트에서 사용) - parentTabId?: string; // 부모 탭 ID + parentTabId?: string; // 부모 탭 ID parentTabsComponentId?: string; // 부모 탭 컴포넌트 ID } @@ -334,6 +335,14 @@ export const InteractiveScreenViewerDynamic: React.FC { + // 조건부 표시 평가 + const conditionalResult = evaluateConditional(comp.conditional, formData, allComponents); + + // 조건에 따라 숨김 처리 + if (!conditionalResult.visible) { + return null; + } + // 데이터 테이블 컴포넌트 처리 if (isDataTableComponent(comp)) { return ( @@ -431,6 +440,9 @@ export const InteractiveScreenViewerDynamic: React.FC handleFormDataChange(fieldName, e.target.value)} placeholder={`${widgetType} (렌더링 오류)`} - disabled={readonly} + disabled={readonly || isConditionallyDisabled} required={required} className="h-full w-full" /> @@ -486,7 +499,7 @@ export const InteractiveScreenViewerDynamic: React.FC handleFormDataChange(fieldName, e.target.value)} placeholder={placeholder || "입력하세요"} - disabled={readonly} + disabled={readonly || isConditionallyDisabled} required={required} className="h-full w-full" /> @@ -528,6 +541,13 @@ export const InteractiveScreenViewerDynamic: React.FC { // componentConfig에서 quickInsertConfig 가져오기 const quickInsertConfig = (comp as any).componentConfig?.action?.quickInsertConfig; - + if (!quickInsertConfig?.targetTable) { toast.error("대상 테이블이 설정되지 않았습니다."); return; @@ -604,7 +624,7 @@ export const InteractiveScreenViewerDynamic: React.FC = {}; const columnMappings = quickInsertConfig.columnMappings || []; - + for (const mapping of columnMappings) { let value: any; @@ -681,31 +701,31 @@ export const InteractiveScreenViewerDynamic: React.FC 0) { const leftData = splitPanelContext.selectedLeftData; console.log("📍 좌측 패널 자동 매핑 시작:", leftData); - + for (const [key, val] of Object.entries(leftData)) { // 이미 매핑된 컬럼은 스킵 if (insertData[key] !== undefined) { continue; } - + // 대상 테이블에 해당 컬럼이 없으면 스킵 if (!targetTableColumns.includes(key)) { continue; } - + // 시스템 컬럼 제외 - const systemColumns = ['id', 'created_date', 'updated_date', 'writer', 'writer_name']; + const systemColumns = ["id", "created_date", "updated_date", "writer", "writer_name"]; if (systemColumns.includes(key)) { continue; } - + // _label, _name 으로 끝나는 표시용 컬럼 제외 - if (key.endsWith('_label') || key.endsWith('_name')) { + if (key.endsWith("_label") || key.endsWith("_name")) { continue; } - + // 값이 있으면 자동 추가 - if (val !== undefined && val !== null && val !== '') { + if (val !== undefined && val !== null && val !== "") { insertData[key] = val; console.log(`📍 자동 매핑 추가: ${key} = ${val}`); } @@ -724,7 +744,7 @@ export const InteractiveScreenViewerDynamic: React.FC 0) { try { const { default: apiClient } = await import("@/lib/api/client"); - + // 중복 체크를 위한 검색 조건 구성 const searchConditions: Record = {}; for (const col of quickInsertConfig.duplicateCheck.columns) { @@ -736,14 +756,11 @@ export const InteractiveScreenViewerDynamic: React.FC setPopupScreen(null)}> void; + + // 🆕 조건부 비활성화 상태 + conditionalDisabled?: boolean; } // 동적 위젯 타입 아이콘 (레지스트리에서 조회) @@ -93,7 +96,7 @@ const getWidgetIcon = (widgetType: WebType | undefined): React.ReactNode => { return iconMap[widgetType] || ; }; -export const RealtimePreviewDynamic: React.FC = ({ +const RealtimePreviewDynamicComponent: React.FC = ({ component, isSelected = false, isDesignMode = true, // 기본값은 편집 모드 @@ -128,6 +131,7 @@ export const RealtimePreviewDynamic: React.FC = ({ formData, onFormDataChange, onHeightChange, // 🆕 조건부 컨테이너 높이 변화 콜백 + conditionalDisabled, // 🆕 조건부 비활성화 상태 }) => { const [actualHeight, setActualHeight] = React.useState(null); const contentRef = React.useRef(null); @@ -509,6 +513,7 @@ export const RealtimePreviewDynamic: React.FC = ({ sortOrder={sortOrder} columnOrder={columnOrder} onHeightChange={onHeightChange} + conditionalDisabled={conditionalDisabled} />
@@ -532,6 +537,12 @@ export const RealtimePreviewDynamic: React.FC = ({ ); }; +// React.memo로 래핑하여 불필요한 리렌더링 방지 +export const RealtimePreviewDynamic = React.memo(RealtimePreviewDynamicComponent); + +// displayName 설정 (디버깅용) +RealtimePreviewDynamic.displayName = "RealtimePreviewDynamic"; + // 기존 RealtimePreview와의 호환성을 위한 export export { RealtimePreviewDynamic as RealtimePreview }; export default RealtimePreviewDynamic; diff --git a/frontend/components/screen/ScreenDesigner.tsx b/frontend/components/screen/ScreenDesigner.tsx index d4cab3cf..891b8a58 100644 --- a/frontend/components/screen/ScreenDesigner.tsx +++ b/frontend/components/screen/ScreenDesigner.tsx @@ -17,7 +17,7 @@ import { SCREEN_RESOLUTIONS, } from "@/types/screen"; import { generateComponentId } from "@/lib/utils/generateId"; -import { getComponentIdFromWebType } from "@/lib/utils/webTypeMapping"; +import { getComponentIdFromWebType, createUnifiedConfigFromColumn, getUnifiedConfigFromWebType } from "@/lib/utils/webTypeMapping"; import { createGroupComponent, calculateBoundingBox, @@ -938,11 +938,35 @@ export default function ScreenDesigner({ selectedScreen, onBackToList }: ScreenD : null; const tableLabel = currentTable?.displayName || tableName; - // 현재 화면의 테이블 컬럼 정보 조회 - const columnsResponse = await tableTypeApi.getColumns(tableName); + // 현재 화면의 테이블 컬럼 정보 조회 (캐시 버스팅으로 최신 데이터 가져오기) + const columnsResponse = await tableTypeApi.getColumns(tableName, true); const columns: ColumnInfo[] = (columnsResponse || []).map((col: any) => { - const widgetType = col.widgetType || col.widget_type || col.webType || col.web_type; + // widgetType 결정: inputType(entity 등) > webType > widget_type + const inputType = col.inputType || col.input_type; + const widgetType = inputType || col.widgetType || col.widget_type || col.webType || col.web_type; + + // detailSettings 파싱 (문자열이면 JSON 파싱) + let detailSettings = col.detailSettings || col.detail_settings; + if (typeof detailSettings === "string") { + try { + detailSettings = JSON.parse(detailSettings); + } catch (e) { + console.warn("detailSettings 파싱 실패:", e); + detailSettings = {}; + } + } + + // 엔티티 타입 디버깅 + if (inputType === "entity" || widgetType === "entity") { + console.log("🔍 엔티티 컬럼 감지:", { + columnName: col.columnName || col.column_name, + inputType, + widgetType, + detailSettings, + referenceTable: detailSettings?.referenceTable || col.referenceTable || col.reference_table, + }); + } return { tableName: col.tableName || tableName, @@ -950,7 +974,8 @@ export default function ScreenDesigner({ selectedScreen, onBackToList }: ScreenD columnLabel: col.displayName || col.columnLabel || col.column_label || col.columnName || col.column_name, dataType: col.dataType || col.data_type || col.dbType, webType: col.webType || col.web_type, - input_type: col.inputType || col.input_type, + input_type: inputType, + inputType: inputType, widgetType, isNullable: col.isNullable || col.is_nullable, required: col.required !== undefined ? col.required : col.isNullable === "NO" || col.is_nullable === "NO", @@ -958,10 +983,12 @@ export default function ScreenDesigner({ selectedScreen, onBackToList }: ScreenD characterMaximumLength: col.characterMaximumLength || col.character_maximum_length, codeCategory: col.codeCategory || col.code_category, codeValue: col.codeValue || col.code_value, - // 엔티티 타입용 참조 테이블 정보 - referenceTable: col.referenceTable || col.reference_table, - referenceColumn: col.referenceColumn || col.reference_column, - displayColumn: col.displayColumn || col.display_column, + // 엔티티 타입용 참조 테이블 정보 (detailSettings에서 추출) + referenceTable: detailSettings?.referenceTable || col.referenceTable || col.reference_table, + referenceColumn: detailSettings?.referenceColumn || col.referenceColumn || col.reference_column, + displayColumn: detailSettings?.displayColumn || col.displayColumn || col.display_column, + // detailSettings 전체 보존 (Unified 컴포넌트용) + detailSettings, }; }); @@ -2578,28 +2605,40 @@ export default function ScreenDesigner({ selectedScreen, onBackToList }: ScreenD const relativeX = e.clientX - containerRect.left; const relativeY = e.clientY - containerRect.top; - // 웹타입을 새로운 컴포넌트 ID로 매핑 - const componentId = getComponentIdFromWebType(column.widgetType); - // console.log(`🔄 폼 컨테이너 드롭: ${column.widgetType} → ${componentId}`); + // 🆕 Unified 컴포넌트 매핑 사용 + const unifiedMapping = createUnifiedConfigFromColumn({ + widgetType: column.widgetType, + columnName: column.columnName, + columnLabel: column.columnLabel, + codeCategory: column.codeCategory, + inputType: column.inputType, + required: column.required, + detailSettings: column.detailSettings, // 엔티티 참조 정보 전달 + // column_labels 직접 필드도 전달 + referenceTable: column.referenceTable, + referenceColumn: column.referenceColumn, + displayColumn: column.displayColumn, + }); // 웹타입별 기본 너비 계산 (10px 단위 고정) const componentWidth = getDefaultWidth(column.widgetType); - console.log("🎯 폼 컨테이너 컴포넌트 생성:", { + console.log("🎯 폼 컨테이너 Unified 컴포넌트 생성:", { widgetType: column.widgetType, + unifiedType: unifiedMapping.componentType, componentWidth, }); newComponent = { id: generateComponentId(), - type: "component", // ✅ 새로운 컴포넌트 시스템 사용 + type: "component", // ✅ Unified 컴포넌트 시스템 사용 label: column.columnLabel || column.columnName, tableName: table.tableName, columnName: column.columnName, required: column.required, readonly: false, parentId: formContainerId, // 폼 컨테이너의 자식으로 설정 - componentType: componentId, // DynamicComponentRenderer용 컴포넌트 타입 + componentType: unifiedMapping.componentType, // unified-input, unified-select 등 position: { x: relativeX, y: relativeY, z: 1 } as Position, size: { width: componentWidth, height: getDefaultHeight(column.widgetType) }, // 코드 타입인 경우 코드 카테고리 정보 추가 @@ -2615,43 +2654,47 @@ export default function ScreenDesigner({ selectedScreen, onBackToList }: ScreenD labelMarginBottom: "6px", }, componentConfig: { - type: componentId, // text-input, number-input 등 - webType: column.widgetType, // 원본 웹타입 보존 - inputType: column.inputType, // ✅ input_type 추가 (category 등) - ...getDefaultWebTypeConfig(column.widgetType), - placeholder: column.columnLabel || column.columnName, // placeholder에 라벨명 표시 - // 코드 타입인 경우 코드 카테고리 정보 추가 - ...(column.widgetType === "code" && - column.codeCategory && { - codeCategory: column.codeCategory, - }), + type: unifiedMapping.componentType, // unified-input, unified-select 등 + ...unifiedMapping.componentConfig, // Unified 컴포넌트 기본 설정 }, }; } else { return; // 폼 컨테이너를 찾을 수 없으면 드롭 취소 } } else { - // 일반 캔버스에 드롭한 경우 - 새로운 컴포넌트 시스템 사용 - const componentId = getComponentIdFromWebType(column.widgetType); - // console.log(`🔄 캔버스 드롭: ${column.widgetType} → ${componentId}`); + // 일반 캔버스에 드롭한 경우 - 🆕 Unified 컴포넌트 시스템 사용 + const unifiedMapping = createUnifiedConfigFromColumn({ + widgetType: column.widgetType, + columnName: column.columnName, + columnLabel: column.columnLabel, + codeCategory: column.codeCategory, + inputType: column.inputType, + required: column.required, + detailSettings: column.detailSettings, // 엔티티 참조 정보 전달 + // column_labels 직접 필드도 전달 + referenceTable: column.referenceTable, + referenceColumn: column.referenceColumn, + displayColumn: column.displayColumn, + }); // 웹타입별 기본 너비 계산 (10px 단위 고정) const componentWidth = getDefaultWidth(column.widgetType); - console.log("🎯 캔버스 컴포넌트 생성:", { + console.log("🎯 캔버스 Unified 컴포넌트 생성:", { widgetType: column.widgetType, + unifiedType: unifiedMapping.componentType, componentWidth, }); newComponent = { id: generateComponentId(), - type: "component", // ✅ 새로운 컴포넌트 시스템 사용 + type: "component", // ✅ Unified 컴포넌트 시스템 사용 label: column.columnLabel || column.columnName, // 컬럼 라벨 우선, 없으면 컬럼명 tableName: table.tableName, columnName: column.columnName, required: column.required, readonly: false, - componentType: componentId, // DynamicComponentRenderer용 컴포넌트 타입 + componentType: unifiedMapping.componentType, // unified-input, unified-select 등 position: { x, y, z: 1 } as Position, size: { width: componentWidth, height: getDefaultHeight(column.widgetType) }, // 코드 타입인 경우 코드 카테고리 정보 추가 @@ -2667,16 +2710,8 @@ export default function ScreenDesigner({ selectedScreen, onBackToList }: ScreenD labelMarginBottom: "8px", }, componentConfig: { - type: componentId, // text-input, number-input 등 - webType: column.widgetType, // 원본 웹타입 보존 - inputType: column.inputType, // ✅ input_type 추가 (category 등) - ...getDefaultWebTypeConfig(column.widgetType), - placeholder: column.columnLabel || column.columnName, // placeholder에 라벨명 표시 - // 코드 타입인 경우 코드 카테고리 정보 추가 - ...(column.widgetType === "code" && - column.codeCategory && { - codeCategory: column.codeCategory, - }), + type: unifiedMapping.componentType, // unified-input, unified-select 등 + ...unifiedMapping.componentConfig, // Unified 컴포넌트 기본 설정 }, }; } diff --git a/frontend/components/screen/panels/ComponentsPanel.tsx b/frontend/components/screen/panels/ComponentsPanel.tsx index 66d29fef..42f00dcb 100644 --- a/frontend/components/screen/panels/ComponentsPanel.tsx +++ b/frontend/components/screen/panels/ComponentsPanel.tsx @@ -6,7 +6,7 @@ import { Badge } from "@/components/ui/badge"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { ComponentRegistry } from "@/lib/registry/ComponentRegistry"; import { ComponentDefinition, ComponentCategory } from "@/types/component"; -import { Search, Package, Grid, Layers, Palette, Zap, MousePointer, Edit3, BarChart3, Database, Wrench } from "lucide-react"; +import { Search, Package, Grid, Layers, Palette, Zap, MousePointer, Edit3, BarChart3, Database, Wrench, Sparkles } from "lucide-react"; import { TableInfo, ColumnInfo } from "@/types/screen"; import TablesPanel from "./TablesPanel"; @@ -52,22 +52,100 @@ export function ComponentsPanel({ return components; }, []); + // Unified 컴포넌트 정의 (새로운 통합 컴포넌트 시스템) + // 입력 컴포넌트(unified-input, unified-select, unified-date)는 테이블 컬럼 드래그 시 자동 생성되므로 숨김 + const unifiedComponents: ComponentDefinition[] = useMemo(() => [ + // unified-input: 테이블 컬럼 드래그 시 자동 생성되므로 숨김 처리 + // unified-select: 테이블 컬럼 드래그 시 자동 생성되므로 숨김 처리 + // unified-date: 테이블 컬럼 드래그 시 자동 생성되므로 숨김 처리 + // unified-layout: 중첩 드래그앤드롭 기능 미구현으로 숨김 처리 + // unified-group: 중첩 드래그앤드롭 기능 미구현으로 숨김 처리 + { + id: "unified-list", + name: "통합 목록", + description: "테이블, 카드, 칸반, 리스트 등 다양한 데이터 표시 방식 지원", + category: "display" as ComponentCategory, + tags: ["table", "list", "card", "kanban", "unified"], + defaultSize: { width: 600, height: 400 }, + }, + { + id: "unified-media", + name: "통합 미디어", + description: "이미지, 비디오, 오디오, 파일 업로드 등 미디어 컴포넌트", + category: "display" as ComponentCategory, + tags: ["image", "video", "audio", "file", "unified"], + defaultSize: { width: 300, height: 200 }, + }, + { + id: "unified-biz", + name: "통합 비즈니스", + description: "플로우 다이어그램, 랙 구조, 채번규칙 등 비즈니스 컴포넌트", + category: "utility" as ComponentCategory, + tags: ["flow", "rack", "numbering", "unified"], + defaultSize: { width: 600, height: 400 }, + }, + { + id: "unified-hierarchy", + name: "통합 계층", + description: "트리, 조직도, BOM, 연쇄 선택박스 등 계층 구조 컴포넌트", + category: "data" as ComponentCategory, + tags: ["tree", "org", "bom", "cascading", "unified"], + defaultSize: { width: 400, height: 300 }, + }, + { + id: "unified-repeater", + name: "통합 반복 데이터", + description: "반복 데이터 관리 (인라인/모달/버튼 모드)", + category: "data" as ComponentCategory, + tags: ["repeater", "table", "modal", "button", "unified"], + defaultSize: { width: 600, height: 300 }, + }, + ], []); + // 카테고리별 컴포넌트 그룹화 const componentsByCategory = useMemo(() => { - // 숨길 컴포넌트 ID 목록 (기본 입력 컴포넌트들) - const hiddenInputComponents = ["text-input", "number-input", "date-input", "textarea-basic"]; + // 숨길 컴포넌트 ID 목록 + const hiddenComponents = [ + // 기본 입력 컴포넌트 (테이블 컬럼 드래그 시 자동 생성) + "text-input", + "number-input", + "date-input", + "textarea-basic", + // Unified 컴포넌트로 대체됨 + "image-widget", // → UnifiedMedia (image) + "file-upload", // → UnifiedMedia (file) + "entity-search-input", // → UnifiedSelect (entity 모드) + "autocomplete-search-input", // → UnifiedSelect (autocomplete 모드) + // UnifiedBiz로 통합 예정 + "rack-structure", // → UnifiedBiz (rack) + // DataFlow 전용 (일반 화면에서 불필요) + "mail-recipient-selector", + // 현재 사용 안함 + "repeater-field-group", + ]; return { input: allComponents.filter( - (c) => c.category === ComponentCategory.INPUT && !hiddenInputComponents.includes(c.id), + (c) => c.category === ComponentCategory.INPUT && !hiddenComponents.includes(c.id), ), - action: allComponents.filter((c) => c.category === ComponentCategory.ACTION), - display: allComponents.filter((c) => c.category === ComponentCategory.DISPLAY), - data: allComponents.filter((c) => c.category === ComponentCategory.DATA), // 🆕 데이터 카테고리 추가 - layout: allComponents.filter((c) => c.category === ComponentCategory.LAYOUT), - utility: allComponents.filter((c) => c.category === ComponentCategory.UTILITY), + action: allComponents.filter( + (c) => c.category === ComponentCategory.ACTION && !hiddenComponents.includes(c.id), + ), + display: allComponents.filter( + (c) => c.category === ComponentCategory.DISPLAY && !hiddenComponents.includes(c.id), + ), + data: allComponents.filter( + (c) => c.category === ComponentCategory.DATA && !hiddenComponents.includes(c.id), + ), + layout: allComponents.filter( + (c) => c.category === ComponentCategory.LAYOUT && !hiddenComponents.includes(c.id), + ), + utility: allComponents.filter( + (c) => c.category === ComponentCategory.UTILITY && !hiddenComponents.includes(c.id), + ), + unified: unifiedComponents, }; - }, [allComponents]); + }, [allComponents, unifiedComponents]); // 카테고리별 검색 필터링 const getFilteredComponents = (category: keyof typeof componentsByCategory) => { @@ -187,19 +265,28 @@ export function ComponentsPanel({ {/* 카테고리 탭 */} - - + + + {/* 1행: Unified, 테이블, 입력, 데이터 */} + + + Unified + - 테이블 + 테이블 - 입력 + 입력 - 데이터 + 데이터 + {/* 2행: 액션, 표시, 레이아웃, 유틸리티 */} - 액션 + 액션 - 표시 + 표시 - 레이아웃 + 레이아웃 - 유틸리티 + 유틸 + {/* Unified 컴포넌트 탭 */} + +
+

+ Unified 컴포넌트는 속성 기반으로 다양한 기능을 지원하는 새로운 컴포넌트입니다. +

+
+ {getFilteredComponents("unified").length > 0 + ? getFilteredComponents("unified").map(renderComponentCard) + : renderEmptyState()} +
+ {/* 테이블 탭 */} {tables.length > 0 && onTableDragStart ? ( diff --git a/frontend/components/screen/panels/DetailSettingsPanel.tsx b/frontend/components/screen/panels/DetailSettingsPanel.tsx index f3795634..a7fcc5e1 100644 --- a/frontend/components/screen/panels/DetailSettingsPanel.tsx +++ b/frontend/components/screen/panels/DetailSettingsPanel.tsx @@ -1,7 +1,7 @@ "use client"; import React, { useState, useEffect } from "react"; -import { Settings, Database } from "lucide-react"; +import { Settings, Database, Zap } from "lucide-react"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Label } from "@/components/ui/label"; import { Input } from "@/components/ui/input"; @@ -22,6 +22,8 @@ import { FileComponentConfigPanel } from "./FileComponentConfigPanel"; import { WebTypeConfigPanel } from "./WebTypeConfigPanel"; import { isFileComponent } from "@/lib/utils/componentTypeUtils"; import { BaseInputType, getBaseInputType, getDetailTypes, DetailTypeOption } from "@/types/input-type-mapping"; +import { ConditionalConfigPanel } from "@/components/unified/ConditionalConfigPanel"; +import { ConditionalConfig } from "@/types/unified-components"; // 새로운 컴포넌트 설정 패널들 import import { ButtonConfigPanel as NewButtonConfigPanel } from "../config-panels/ButtonConfigPanel"; @@ -1192,7 +1194,28 @@ export const DetailSettingsPanel: React.FC = ({ }} /> - {/* 🆕 테이블 데이터 자동 입력 섹션 (component 타입용) */} + {/* 조건부 표시 설정 (component 타입용) */} +
+ { + onUpdateProperty(selectedComponent.id, "conditional", newConfig); + }} + availableFields={components + .filter((c) => c.id !== selectedComponent.id && (c.type === "widget" || c.type === "component")) + .map((c) => ({ + id: c.id, + label: (c as any).label || (c as any).columnName || c.id, + type: (c as any).widgetType || (c as any).componentConfig?.webType, + options: (c as any).webTypeConfig?.options || [], + }))} + currentComponentId={selectedComponent.id} + /> +
+ + + + {/* 테이블 데이터 자동 입력 섹션 (component 타입용) */}

@@ -1400,9 +1423,29 @@ export const DetailSettingsPanel: React.FC = ({ {/* 상세 설정 영역 */}
- {console.log("🔍 [DetailSettingsPanel] widget 타입:", selectedComponent?.type, "autoFill:", widget.autoFill)} - {/* 🆕 자동 입력 섹션 */} -
+ {/* 조건부 표시 설정 */} +
+ { + onUpdateProperty(widget.id, "conditional", newConfig); + }} + availableFields={components + .filter((c) => c.id !== widget.id && (c.type === "widget" || c.type === "component")) + .map((c) => ({ + id: c.id, + label: (c as any).label || (c as any).columnName || c.id, + type: (c as any).widgetType || (c as any).componentConfig?.webType, + options: (c as any).webTypeConfig?.options || [], + }))} + currentComponentId={widget.id} + /> +
+ + + + {/* 자동 입력 섹션 */} +

🔥 테이블 데이터 자동 입력 (테스트) diff --git a/frontend/components/screen/panels/UnifiedPropertiesPanel.tsx b/frontend/components/screen/panels/UnifiedPropertiesPanel.tsx index ad34df9a..e2e9d837 100644 --- a/frontend/components/screen/panels/UnifiedPropertiesPanel.tsx +++ b/frontend/components/screen/panels/UnifiedPropertiesPanel.tsx @@ -62,6 +62,8 @@ import StyleEditor from "../StyleEditor"; import ResolutionPanel from "./ResolutionPanel"; import { Slider } from "@/components/ui/slider"; import { Grid3X3, Eye, EyeOff, Zap } from "lucide-react"; +import { ConditionalConfigPanel } from "@/components/unified/ConditionalConfigPanel"; +import { ConditionalConfig } from "@/types/unified-components"; interface UnifiedPropertiesPanelProps { selectedComponent?: ComponentData; @@ -313,6 +315,69 @@ export const UnifiedPropertiesPanel: React.FC = ({ selectedComponent.componentConfig?.id || (selectedComponent.type === "component" ? selectedComponent.id : null); // 🆕 독립 컴포넌트 (table-search-widget 등) + // 🆕 Unified 컴포넌트 직접 감지 및 설정 패널 렌더링 + if (componentId?.startsWith("unified-")) { + const unifiedConfigPanels: Record void }>> = { + "unified-input": require("@/components/unified/config-panels/UnifiedInputConfigPanel").UnifiedInputConfigPanel, + "unified-select": require("@/components/unified/config-panels/UnifiedSelectConfigPanel") + .UnifiedSelectConfigPanel, + "unified-date": require("@/components/unified/config-panels/UnifiedDateConfigPanel").UnifiedDateConfigPanel, + "unified-list": require("@/components/unified/config-panels/UnifiedListConfigPanel").UnifiedListConfigPanel, + "unified-layout": require("@/components/unified/config-panels/UnifiedLayoutConfigPanel") + .UnifiedLayoutConfigPanel, + "unified-group": require("@/components/unified/config-panels/UnifiedGroupConfigPanel").UnifiedGroupConfigPanel, + "unified-media": require("@/components/unified/config-panels/UnifiedMediaConfigPanel").UnifiedMediaConfigPanel, + "unified-biz": require("@/components/unified/config-panels/UnifiedBizConfigPanel").UnifiedBizConfigPanel, + "unified-hierarchy": require("@/components/unified/config-panels/UnifiedHierarchyConfigPanel") + .UnifiedHierarchyConfigPanel, + }; + + const UnifiedConfigPanel = unifiedConfigPanels[componentId]; + if (UnifiedConfigPanel) { + const currentConfig = selectedComponent.componentConfig || {}; + const handleUnifiedConfigChange = (newConfig: any) => { + onUpdateProperty(selectedComponent.id, "componentConfig", { ...currentConfig, ...newConfig }); + }; + + const unifiedNames: Record = { + "unified-input": "통합 입력", + "unified-select": "통합 선택", + "unified-date": "통합 날짜", + "unified-list": "통합 목록", + "unified-layout": "통합 레이아웃", + "unified-group": "통합 그룹", + "unified-media": "통합 미디어", + "unified-biz": "통합 비즈니스", + "unified-hierarchy": "통합 계층", + }; + + // 컬럼의 inputType 가져오기 (entity 타입인지 확인용) + const inputType = currentConfig.inputType || currentConfig.webType || (selectedComponent as any).inputType; + + // 현재 화면의 테이블명 가져오기 + const currentTableName = tables?.[0]?.tableName; + + // 컴포넌트별 추가 props + const extraProps: Record = {}; + if (componentId === "unified-select") { + extraProps.inputType = inputType; + } + if (componentId === "unified-list") { + extraProps.currentTableName = currentTableName; + } + + return ( +
+
+ +

{unifiedNames[componentId] || componentId} 설정

+
+ +
+ ); + } + } + if (componentId) { const definition = ComponentRegistry.getComponent(componentId); @@ -989,6 +1054,16 @@ export const UnifiedPropertiesPanel: React.FC = ({ ); } + // 🆕 3.5. Unified 컴포넌트 - 반드시 다른 체크보다 먼저 처리 + const unifiedComponentType = + (selectedComponent as any).componentType || selectedComponent.componentConfig?.type || ""; + if (unifiedComponentType.startsWith("unified-")) { + const configPanel = renderComponentConfigPanel(); + if (configPanel) { + return
{configPanel}
; + } + } + // 4. 새로운 컴포넌트 시스템 (button, card 등) const componentType = selectedComponent.componentConfig?.type || selectedComponent.type; const hasNewConfigPanel = @@ -1468,6 +1543,93 @@ export const UnifiedPropertiesPanel: React.FC = ({ {renderDetailTab()} + {/* 조건부 표시 설정 */} + {selectedComponent && ( + <> + +
+
+ +

조건부 표시

+
+
+ { + handleUpdate("conditional", newConfig); + }} + availableFields={ + allComponents + ?.filter((c) => { + // 자기 자신 제외 + if (c.id === selectedComponent.id) return false; + // widget 타입 또는 component 타입 (Unified 컴포넌트 포함) + return c.type === "widget" || c.type === "component"; + }) + .map((c) => { + const widgetType = (c as any).widgetType || (c as any).componentType || "text"; + const config = (c as any).componentConfig || (c as any).webTypeConfig || {}; + const detailSettings = (c as any).detailSettings || {}; + + // 정적 옵션 추출 (select, dropdown, radio, entity 등) + let options: Array<{ value: string; label: string }> | undefined; + + // Unified 컴포넌트의 경우 + if (config.options && Array.isArray(config.options)) { + options = config.options; + } + // 레거시 컴포넌트의 경우 + else if ((c as any).options && Array.isArray((c as any).options)) { + options = (c as any).options; + } + + // 엔티티 정보 추출 (config > detailSettings > 직접 속성 순으로 우선순위) + const entityTable = + config.entityTable || + detailSettings.referenceTable || + (c as any).entityTable || + (c as any).referenceTable; + const entityValueColumn = + config.entityValueColumn || + detailSettings.referenceColumn || + (c as any).entityValueColumn || + (c as any).referenceColumn; + const entityLabelColumn = + config.entityLabelColumn || + detailSettings.displayColumn || + (c as any).entityLabelColumn || + (c as any).displayColumn; + + // 공통코드 정보 추출 + const codeGroup = config.codeGroup || detailSettings.codeGroup || (c as any).codeGroup; + + return { + id: (c as any).columnName || c.id, + label: (c as any).label || config.label || c.id, + type: widgetType, + options, + entityTable, + entityValueColumn, + entityLabelColumn, + codeGroup, + }; + }) || [] + } + currentComponentId={selectedComponent.id} + /> +
+
+ + )} + {/* 스타일 설정 */} {selectedComponent && ( <> diff --git a/frontend/components/ui/calendar.tsx b/frontend/components/ui/calendar.tsx index 768386ec..dc549c8e 100644 --- a/frontend/components/ui/calendar.tsx +++ b/frontend/components/ui/calendar.tsx @@ -15,38 +15,48 @@ function Calendar({ className, classNames, showOutsideDays = true, ...props }: C showOutsideDays={showOutsideDays} className={cn("p-3", className)} classNames={{ - months: "flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0", - month: "space-y-4", - caption: "flex justify-center pt-1 relative items-center", + // react-day-picker v9 클래스명 + months: "flex flex-col sm:flex-row gap-4", + month: "flex flex-col gap-4", + month_caption: "flex justify-center pt-1 relative items-center h-7", caption_label: "text-sm font-medium", - nav: "space-x-1 flex items-center", - nav_button: cn( + nav: "flex items-center gap-1", + button_previous: cn( buttonVariants({ variant: "outline" }), - "h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100", + "h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100 absolute left-1", ), - nav_button_previous: "absolute left-1", - nav_button_next: "absolute right-1", - table: "w-full border-collapse space-y-1", - head_row: "flex w-full", - head_cell: + button_next: cn( + buttonVariants({ variant: "outline" }), + "h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100 absolute right-1", + ), + month_grid: "w-full border-collapse", + weekdays: "flex w-full", + weekday: "text-muted-foreground rounded-md w-9 h-9 font-normal text-[0.8rem] inline-flex items-center justify-center", - row: "flex w-full mt-2", - cell: "h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20", - day: cn(buttonVariants({ variant: "ghost" }), "h-9 w-9 p-0 font-normal aria-selected:opacity-100"), - day_range_end: "day-range-end", - day_selected: - "bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground", - day_today: "bg-accent text-accent-foreground", - day_outside: - "day-outside text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30", - day_disabled: "text-muted-foreground opacity-50", - day_range_middle: "aria-selected:bg-accent aria-selected:text-accent-foreground", - day_hidden: "invisible", + week: "flex w-full mt-2", + day: "h-9 w-9 text-center text-sm p-0 relative", + day_button: cn( + buttonVariants({ variant: "ghost" }), + "h-9 w-9 p-0 font-normal aria-selected:opacity-100", + ), + range_end: "day-range-end", + selected: + "bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground rounded-md", + today: "bg-accent text-accent-foreground rounded-md", + outside: + "text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30", + disabled: "text-muted-foreground opacity-50", + range_middle: "aria-selected:bg-accent aria-selected:text-accent-foreground", + hidden: "invisible", ...classNames, }} components={{ - IconLeft: ({ ...props }) => , - IconRight: ({ ...props }) => , + Chevron: ({ orientation }) => { + if (orientation === "left") { + return ; + } + return ; + }, }} {...props} /> diff --git a/frontend/components/unified/ConditionalConfigPanel.tsx b/frontend/components/unified/ConditionalConfigPanel.tsx new file mode 100644 index 00000000..ca60dd7f --- /dev/null +++ b/frontend/components/unified/ConditionalConfigPanel.tsx @@ -0,0 +1,493 @@ +"use client"; + +/** + * ConditionalConfigPanel + * + * 비개발자도 쉽게 조건부 표시/숨김/활성화/비활성화를 설정할 수 있는 UI + * + * 사용처: + * - 화면관리 > 상세설정 패널 + * - 화면관리 > 속성 패널 + */ + +import React, { useState, useEffect, useMemo } from "react"; +import { Label } from "@/components/ui/label"; +import { Input } from "@/components/ui/input"; +import { Switch } from "@/components/ui/switch"; +import { Button } from "@/components/ui/button"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; +import { Separator } from "@/components/ui/separator"; +import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; +import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command"; +import { Zap, Plus, Trash2, HelpCircle, Check, ChevronsUpDown } from "lucide-react"; +import { ConditionalConfig } from "@/types/unified-components"; +import { cn } from "@/lib/utils"; + +// ===== 타입 정의 ===== + +interface FieldOption { + id: string; + label: string; + type?: string; // text, number, select, checkbox, entity, code 등 + options?: Array<{ value: string; label: string }>; // select 타입일 경우 옵션들 + // 동적 옵션 로드를 위한 정보 + entityTable?: string; + entityValueColumn?: string; + entityLabelColumn?: string; + codeGroup?: string; +} + +interface ConditionalConfigPanelProps { + /** 현재 조건부 설정 */ + config?: ConditionalConfig; + /** 설정 변경 콜백 */ + onChange: (config: ConditionalConfig | undefined) => void; + /** 같은 화면에 있는 다른 필드들 (조건 필드로 선택 가능) */ + availableFields: FieldOption[]; + /** 현재 컴포넌트 ID (자기 자신은 조건 필드에서 제외) */ + currentComponentId?: string; +} + +// 연산자 옵션 +const OPERATORS: Array<{ value: ConditionalConfig["operator"]; label: string; description: string }> = [ + { value: "=", label: "같음", description: "값이 정확히 일치할 때" }, + { value: "!=", label: "다름", description: "값이 일치하지 않을 때" }, + { value: ">", label: "보다 큼", description: "값이 더 클 때 (숫자)" }, + { value: "<", label: "보다 작음", description: "값이 더 작을 때 (숫자)" }, + { value: "in", label: "포함됨", description: "여러 값 중 하나일 때" }, + { value: "notIn", label: "포함 안됨", description: "여러 값 중 아무것도 아닐 때" }, + { value: "isEmpty", label: "비어있음", description: "값이 없을 때" }, + { value: "isNotEmpty", label: "값이 있음", description: "값이 있을 때" }, +]; + +// 동작 옵션 +const ACTIONS: Array<{ value: ConditionalConfig["action"]; label: string; description: string }> = [ + { value: "show", label: "표시", description: "조건 만족 시 이 필드를 표시" }, + { value: "hide", label: "숨김", description: "조건 만족 시 이 필드를 숨김" }, + { value: "enable", label: "활성화", description: "조건 만족 시 이 필드를 활성화" }, + { value: "disable", label: "비활성화", description: "조건 만족 시 이 필드를 비활성화" }, +]; + +// ===== 컴포넌트 ===== + +export function ConditionalConfigPanel({ + config, + onChange, + availableFields, + currentComponentId, +}: ConditionalConfigPanelProps) { + // 로컬 상태 + const [enabled, setEnabled] = useState(config?.enabled ?? false); + const [field, setField] = useState(config?.field ?? ""); + const [operator, setOperator] = useState(config?.operator ?? "="); + const [value, setValue] = useState(String(config?.value ?? "")); + const [action, setAction] = useState(config?.action ?? "show"); + + // 자기 자신을 제외한 필드 목록 + const selectableFields = useMemo(() => { + return availableFields.filter((f) => f.id !== currentComponentId); + }, [availableFields, currentComponentId]); + + // 선택된 필드 정보 + const selectedField = useMemo(() => { + return selectableFields.find((f) => f.id === field); + }, [selectableFields, field]); + + // 동적 옵션 로드 상태 + const [dynamicOptions, setDynamicOptions] = useState>([]); + const [loadingOptions, setLoadingOptions] = useState(false); + + // Combobox 열림 상태 + const [comboboxOpen, setComboboxOpen] = useState(false); + + // 엔티티/공통코드 필드 선택 시 동적으로 옵션 로드 + useEffect(() => { + const loadDynamicOptions = async () => { + if (!selectedField) { + setDynamicOptions([]); + return; + } + + // 정적 옵션이 있으면 사용 + if (selectedField.options && selectedField.options.length > 0) { + setDynamicOptions([]); + return; + } + + // 엔티티 타입 (타입이 entity이거나, entityTable이 있으면 엔티티로 간주) + if (selectedField.entityTable) { + setLoadingOptions(true); + try { + const { apiClient } = await import("@/lib/api/client"); + const valueCol = selectedField.entityValueColumn || "id"; + const labelCol = selectedField.entityLabelColumn || "name"; + const response = await apiClient.get(`/entity/${selectedField.entityTable}/options`, { + params: { value: valueCol, label: labelCol }, + }); + if (response.data.success && response.data.data) { + setDynamicOptions(response.data.data); + } + } catch (error) { + console.error("엔티티 옵션 로드 실패:", error); + setDynamicOptions([]); + } finally { + setLoadingOptions(false); + } + return; + } + + // 공통코드 타입 (타입이 code이거나, codeGroup이 있으면 공통코드로 간주) + if (selectedField.codeGroup) { + setLoadingOptions(true); + try { + const { apiClient } = await import("@/lib/api/client"); + // 올바른 API 경로: /common-codes/categories/:categoryCode/options + const response = await apiClient.get(`/common-codes/categories/${selectedField.codeGroup}/options`); + if (response.data.success && response.data.data) { + setDynamicOptions( + response.data.data.map((item: { value: string; label: string }) => ({ + value: item.value, + label: item.label, + })) + ); + } + } catch (error) { + console.error("공통코드 옵션 로드 실패:", error); + setDynamicOptions([]); + } finally { + setLoadingOptions(false); + } + return; + } + + setDynamicOptions([]); + }; + + loadDynamicOptions(); + }, [selectedField?.id, selectedField?.entityTable, selectedField?.entityValueColumn, selectedField?.entityLabelColumn, selectedField?.codeGroup]); + + // 최종 옵션 (정적 + 동적) + const fieldOptions = useMemo(() => { + if (selectedField?.options && selectedField.options.length > 0) { + return selectedField.options; + } + return dynamicOptions; + }, [selectedField?.options, dynamicOptions]); + + // config prop 변경 시 로컬 상태 동기화 + useEffect(() => { + setEnabled(config?.enabled ?? false); + setField(config?.field ?? ""); + setOperator(config?.operator ?? "="); + setValue(String(config?.value ?? "")); + setAction(config?.action ?? "show"); + }, [config]); + + // 설정 변경 시 부모에게 알림 + const updateConfig = (updates: Partial) => { + const newConfig: ConditionalConfig = { + enabled: updates.enabled ?? enabled, + field: updates.field ?? field, + operator: updates.operator ?? operator, + value: updates.value ?? value, + action: updates.action ?? action, + }; + + // enabled가 false이면 undefined 반환 (설정 제거) + if (!newConfig.enabled) { + onChange(undefined); + } else { + onChange(newConfig); + } + }; + + // 활성화 토글 + const handleEnabledChange = (checked: boolean) => { + setEnabled(checked); + updateConfig({ enabled: checked }); + }; + + // 조건 필드 변경 + const handleFieldChange = (newField: string) => { + setField(newField); + setValue(""); // 필드 변경 시 값 초기화 + updateConfig({ field: newField, value: "" }); + }; + + // 연산자 변경 + const handleOperatorChange = (newOperator: ConditionalConfig["operator"]) => { + setOperator(newOperator); + // 비어있음/값이있음 연산자는 value 필요 없음 + if (newOperator === "isEmpty" || newOperator === "isNotEmpty") { + setValue(""); + updateConfig({ operator: newOperator, value: "" }); + } else { + updateConfig({ operator: newOperator }); + } + }; + + // 값 변경 + const handleValueChange = (newValue: string) => { + setValue(newValue); + + // 타입에 따라 적절한 값으로 변환 + let parsedValue: unknown = newValue; + if (selectedField?.type === "number") { + parsedValue = Number(newValue); + } else if (newValue === "true") { + parsedValue = true; + } else if (newValue === "false") { + parsedValue = false; + } + + updateConfig({ value: parsedValue }); + }; + + // 동작 변경 + const handleActionChange = (newAction: ConditionalConfig["action"]) => { + setAction(newAction); + updateConfig({ action: newAction }); + }; + + // 값 입력 필드 렌더링 (필드 타입에 따라 다르게) + const renderValueInput = () => { + // 비어있음/값이있음은 값 입력 불필요 + if (operator === "isEmpty" || operator === "isNotEmpty") { + return ( +
+ (값 입력 불필요) +
+ ); + } + + // 옵션 로딩 중 + if (loadingOptions) { + return ( +
+ 옵션 로딩 중... +
+ ); + } + + // 옵션이 있으면 검색 가능한 Combobox로 표시 + if (fieldOptions.length > 0) { + const selectedOption = fieldOptions.find((opt) => opt.value === value); + + return ( + + + + + + + + + + 검색 결과가 없습니다 + + + {fieldOptions.map((opt) => ( + { + handleValueChange(opt.value); + setComboboxOpen(false); + }} + className="text-xs" + > + + {opt.label} + + ))} + + + + + + ); + } + + // 체크박스 타입이면 true/false Select + if (selectedField?.type === "checkbox" || selectedField?.type === "boolean") { + return ( + + ); + } + + // 숫자 타입 + if (selectedField?.type === "number") { + return ( + handleValueChange(e.target.value)} + placeholder="숫자 입력" + className="h-8 text-xs" + /> + ); + } + + // 기본: 텍스트 입력 + return ( + handleValueChange(e.target.value)} + placeholder="값 입력" + className="h-8 text-xs" + /> + ); + }; + + return ( +
+ {/* 헤더 */} +
+
+ + 조건부 표시 + + + +
+ +
+ + {/* 조건 설정 영역 */} + {enabled && ( +
+ {/* 조건 필드 선택 */} +
+ + +

+ 이 필드의 값에 따라 조건이 적용됩니다 +

+
+ + {/* 연산자 선택 */} +
+ + +
+ + {/* 값 입력 */} +
+ + {renderValueInput()} +
+ + {/* 동작 선택 */} +
+ + +

+ 조건이 만족되면 이 필드를 {ACTIONS.find(a => a.value === action)?.label}합니다 +

+
+ + {/* 미리보기 */} + {field && ( +
+

설정 요약:

+

+ "{selectableFields.find(f => f.id === field)?.label || field}" 필드가{" "} + + {operator === "isEmpty" ? "비어있으면" : + operator === "isNotEmpty" ? "값이 있으면" : + `"${value}"${operator === "=" ? "이면" : + operator === "!=" ? "이 아니면" : + operator === ">" ? "보다 크면" : + operator === "<" ? "보다 작으면" : + operator === "in" ? "에 포함되면" : "에 포함되지 않으면"}`} + {" "} + → 이 필드를{" "} + + {action === "show" ? "표시" : + action === "hide" ? "숨김" : + action === "enable" ? "활성화" : "비활성화"} + +

+
+ )} +
+ )} +
+ ); +} + +export default ConditionalConfigPanel; + diff --git a/frontend/components/unified/DynamicConfigPanel.tsx b/frontend/components/unified/DynamicConfigPanel.tsx new file mode 100644 index 00000000..514bda89 --- /dev/null +++ b/frontend/components/unified/DynamicConfigPanel.tsx @@ -0,0 +1,372 @@ +"use client"; + +/** + * DynamicConfigPanel + * + * JSON Schema 기반으로 동적으로 설정 UI를 생성하는 패널 + * 모든 Unified 컴포넌트의 설정을 단일 컴포넌트로 처리 + */ + +import React, { useCallback, useMemo } from "react"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Switch } from "@/components/ui/switch"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; +import { Slider } from "@/components/ui/slider"; +import { Textarea } from "@/components/ui/textarea"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"; +import { ChevronDown } from "lucide-react"; +import { JSONSchemaProperty, UnifiedConfigSchema } from "@/types/unified-components"; +import { cn } from "@/lib/utils"; + +interface DynamicConfigPanelProps { + schema: UnifiedConfigSchema; + config: Record; + onChange: (key: string, value: unknown) => void; + className?: string; +} + +/** + * 개별 스키마 속성을 렌더링하는 컴포넌트 + */ +function SchemaField({ + name, + property, + value, + onChange, + path = [], +}: { + name: string; + property: JSONSchemaProperty; + value: unknown; + onChange: (key: string, value: unknown) => void; + path?: string[]; +}) { + const fieldPath = [...path, name].join("."); + + // 값 변경 핸들러 + const handleChange = useCallback( + (newValue: unknown) => { + onChange(fieldPath, newValue); + }, + [fieldPath, onChange] + ); + + // 타입에 따른 컴포넌트 렌더링 + const renderField = () => { + // enum이 있으면 Select 렌더링 + if (property.enum && property.enum.length > 0) { + return ( + + ); + } + + // 타입별 렌더링 + switch (property.type) { + case "string": + return ( + handleChange(e.target.value)} + placeholder={property.description} + className="h-8 text-xs" + /> + ); + + case "number": + return ( + handleChange(e.target.value ? Number(e.target.value) : undefined)} + placeholder={property.description} + className="h-8 text-xs" + /> + ); + + case "boolean": + return ( + + ); + + case "array": + // 배열은 간단한 텍스트 입력으로 처리 (쉼표 구분) + return ( +