feature/screen-management #294

Merged
kjs merged 11 commits from feature/screen-management into main 2025-12-16 18:02:37 +09:00
57 changed files with 4914 additions and 623 deletions

View File

@ -424,18 +424,16 @@ export class EntityJoinController {
config.referenceTable
);
// 현재 display_column으로 사용 중인 컬럼 제외
// 현재 display_column 정보 (참고용으로만 사용, 필터링하지 않음)
const currentDisplayColumn =
config.displayColumn || config.displayColumns[0];
const availableColumns = columns.filter(
(col) => col.columnName !== currentDisplayColumn
);
// 모든 컬럼 표시 (기본 표시 컬럼도 포함)
return {
joinConfig: config,
tableName: config.referenceTable,
currentDisplayColumn: currentDisplayColumn,
availableColumns: availableColumns.map((col) => ({
availableColumns: columns.map((col) => ({
columnName: col.columnName,
columnLabel: col.displayName || col.columnName,
dataType: col.dataType,

View File

@ -51,3 +51,4 @@ router.get("/data/:groupCode", getAutoFillData);
export default router;

View File

@ -47,3 +47,4 @@ router.get("/filtered-options/:relationCode", getFilteredOptions);
export default router;

View File

@ -63,3 +63,4 @@ router.get("/:groupCode/options/:levelOrder", getLevelOptions);
export default router;

View File

@ -51,3 +51,4 @@ router.get("/options/:exclusionCode", getExcludedOptions);
export default router;

View File

@ -332,6 +332,8 @@ export class MenuCopyService {
/**
*
* - flowId
* - dataflowConfig.flowConfig.flowId selectedDiagramId
*/
private async collectFlows(
screenIds: Set<number>,
@ -340,6 +342,7 @@ export class MenuCopyService {
logger.info(`🔄 플로우 수집 시작: ${screenIds.size}개 화면`);
const flowIds = new Set<number>();
const flowDetails: Array<{ flowId: number; flowName: string; screenId: number }> = [];
for (const screenId of screenIds) {
const layoutsResult = await client.query<ScreenLayout>(
@ -352,13 +355,35 @@ export class MenuCopyService {
// webTypeConfig.dataflowConfig.flowConfig.flowId
const flowId = props?.webTypeConfig?.dataflowConfig?.flowConfig?.flowId;
if (flowId) {
flowIds.add(flowId);
const flowName = props?.webTypeConfig?.dataflowConfig?.flowConfig?.flowName || "Unknown";
if (flowId && typeof flowId === "number" && flowId > 0) {
if (!flowIds.has(flowId)) {
flowIds.add(flowId);
flowDetails.push({ flowId, flowName, screenId });
logger.info(` 📎 화면 ${screenId}에서 플로우 발견: id=${flowId}, name="${flowName}"`);
}
}
// selectedDiagramId도 확인 (flowId와 동일할 수 있지만 다를 수도 있음)
const selectedDiagramId = props?.webTypeConfig?.dataflowConfig?.selectedDiagramId;
if (selectedDiagramId && typeof selectedDiagramId === "number" && selectedDiagramId > 0) {
if (!flowIds.has(selectedDiagramId)) {
flowIds.add(selectedDiagramId);
flowDetails.push({ flowId: selectedDiagramId, flowName: "SelectedDiagram", screenId });
logger.info(` 📎 화면 ${screenId}에서 selectedDiagramId 발견: id=${selectedDiagramId}`);
}
}
}
}
logger.info(`✅ 플로우 수집 완료: ${flowIds.size}`);
if (flowIds.size > 0) {
logger.info(`✅ 플로우 수집 완료: ${flowIds.size}`);
logger.info(` 📋 수집된 flowIds: [${Array.from(flowIds).join(", ")}]`);
} else {
logger.info(`📭 수집된 플로우 없음 (화면에 플로우 참조가 없음)`);
}
return flowIds;
}
@ -473,15 +498,21 @@ export class MenuCopyService {
}
}
// flowId 매핑 (숫자 또는 숫자 문자열)
if (key === "flowId") {
// flowId, selectedDiagramId 매핑 (숫자 또는 숫자 문자열)
// selectedDiagramId는 dataflowConfig에서 flowId와 동일한 값을 참조하므로 함께 변환
if (key === "flowId" || key === "selectedDiagramId") {
const numValue = typeof value === "number" ? value : parseInt(value);
if (!isNaN(numValue)) {
if (!isNaN(numValue) && numValue > 0) {
const newId = flowIdMap.get(numValue);
if (newId) {
obj[key] = typeof value === "number" ? newId : String(newId); // 원래 타입 유지
logger.debug(
` 🔗 플로우 참조 업데이트 (${currentPath}): ${value}${newId}`
logger.info(
` 🔗 플로우 참조 업데이트 (${currentPath}): ${value}${newId}`
);
} else {
// 매핑이 없으면 경고 로그
logger.warn(
` ⚠️ 플로우 매핑 없음 (${currentPath}): ${value} - 원본 플로우가 복사되지 않았을 수 있음`
);
}
}
@ -742,6 +773,8 @@ export class MenuCopyService {
/**
*
* - + (ID )
* -
*/
private async copyFlows(
flowIds: Set<number>,
@ -757,10 +790,11 @@ export class MenuCopyService {
}
logger.info(`🔄 플로우 복사 중: ${flowIds.size}`);
logger.info(` 📋 복사 대상 flowIds: [${Array.from(flowIds).join(", ")}]`);
for (const originalFlowId of flowIds) {
try {
// 1) flow_definition 조회
// 1) 원본 flow_definition 조회
const flowDefResult = await client.query<FlowDefinition>(
`SELECT * FROM flow_definition WHERE id = $1`,
[originalFlowId]
@ -772,8 +806,29 @@ export class MenuCopyService {
}
const flowDef = flowDefResult.rows[0];
logger.info(` 🔍 원본 플로우 발견: id=${originalFlowId}, name="${flowDef.name}", table="${flowDef.table_name}", company="${flowDef.company_code}"`);
// 2) flow_definition 복사
// 2) 대상 회사에 이미 같은 이름+테이블의 플로우가 있는지 확인
const existingFlowResult = await client.query<{ id: number }>(
`SELECT id FROM flow_definition
WHERE company_code = $1 AND name = $2 AND table_name = $3
LIMIT 1`,
[targetCompanyCode, flowDef.name, flowDef.table_name]
);
let newFlowId: number;
if (existingFlowResult.rows.length > 0) {
// 기존 플로우가 있으면 재사용
newFlowId = existingFlowResult.rows[0].id;
flowIdMap.set(originalFlowId, newFlowId);
logger.info(
` ♻️ 기존 플로우 재사용: ${originalFlowId}${newFlowId} (${flowDef.name})`
);
continue; // 스텝/연결 복사 생략 (기존 것 사용)
}
// 3) 새 flow_definition 복사
const newFlowResult = await client.query<{ id: number }>(
`INSERT INTO flow_definition (
name, description, table_name, is_active,
@ -792,11 +847,11 @@ export class MenuCopyService {
]
);
const newFlowId = newFlowResult.rows[0].id;
newFlowId = newFlowResult.rows[0].id;
flowIdMap.set(originalFlowId, newFlowId);
logger.info(
` ✅ 플로우 복사: ${originalFlowId}${newFlowId} (${flowDef.name})`
` ✅ 플로우 신규 복사: ${originalFlowId}${newFlowId} (${flowDef.name})`
);
// 3) flow_step 복사

View File

@ -1751,7 +1751,7 @@ export class ScreenManagementService {
// 기타
label: "text-display",
code: "select-basic",
entity: "select-basic",
entity: "entity-search-input", // 엔티티는 entity-search-input 사용
category: "select-basic",
};

View File

@ -1447,7 +1447,8 @@ export class TableManagementService {
tableName,
columnName,
actualValue,
paramIndex
paramIndex,
operator // operator 전달 (equals면 직접 매칭)
);
default:
@ -1676,7 +1677,8 @@ export class TableManagementService {
tableName: string,
columnName: string,
value: any,
paramIndex: number
paramIndex: number,
operator: string = "contains" // 연결 필터에서 "equals"로 전달되면 직접 매칭
): Promise<{
whereClause: string;
values: any[];
@ -1688,7 +1690,7 @@ export class TableManagementService {
columnName
);
// 🆕 배열 처리: IN 절 사용
// 배열 처리: IN 절 사용
if (Array.isArray(value)) {
if (value.length === 0) {
// 빈 배열이면 항상 false 조건
@ -1720,13 +1722,35 @@ export class TableManagementService {
}
if (typeof value === "string" && value.trim() !== "") {
const displayColumn = entityTypeInfo.displayColumn || "name";
// equals 연산자인 경우: 직접 값 매칭 (연결 필터에서 코드 값으로 필터링 시 사용)
if (operator === "equals") {
logger.info(
`🔍 [buildEntitySearchCondition] equals 연산자 - 직접 매칭: ${columnName} = ${value}`
);
return {
whereClause: `${columnName} = $${paramIndex}`,
values: [value],
paramCount: 1,
};
}
// contains 연산자 (기본): 참조 테이블의 표시 컬럼으로 검색
const referenceColumn = entityTypeInfo.referenceColumn || "id";
const referenceTable = entityTypeInfo.referenceTable;
// displayColumn이 비어있거나 "none"이면 참조 테이블에서 자동 감지 (entityJoinService와 동일한 로직)
let displayColumn = entityTypeInfo.displayColumn;
if (!displayColumn || displayColumn === "none" || displayColumn === "") {
displayColumn = await this.findDisplayColumnForTable(referenceTable, referenceColumn);
logger.info(
`🔍 [buildEntitySearchCondition] displayColumn 자동 감지: ${referenceTable} -> ${displayColumn}`
);
}
// 참조 테이블의 표시 컬럼으로 검색
return {
whereClause: `EXISTS (
SELECT 1 FROM ${entityTypeInfo.referenceTable} ref
SELECT 1 FROM ${referenceTable} ref
WHERE ref.${referenceColumn} = ${columnName}
AND ref.${displayColumn} ILIKE $${paramIndex}
)`,
@ -1754,6 +1778,66 @@ export class TableManagementService {
}
}
/**
* (entityJoinService와 )
* : *_name > name > label/*_label > title > referenceColumn
*/
private async findDisplayColumnForTable(
tableName: string,
referenceColumn?: string
): Promise<string> {
try {
const result = await query<{ column_name: string }>(
`SELECT column_name
FROM information_schema.columns
WHERE table_name = $1
AND table_schema = 'public'
ORDER BY ordinal_position`,
[tableName]
);
const allColumns = result.map((r) => r.column_name);
// entityJoinService와 동일한 우선순위
// 1. *_name 컬럼 (item_name, customer_name, process_name 등) - company_name 제외
const nameColumn = allColumns.find(
(col) => col.endsWith("_name") && col !== "company_name"
);
if (nameColumn) {
return nameColumn;
}
// 2. name 컬럼
if (allColumns.includes("name")) {
return "name";
}
// 3. label 또는 *_label 컬럼
const labelColumn = allColumns.find(
(col) => col === "label" || col.endsWith("_label")
);
if (labelColumn) {
return labelColumn;
}
// 4. title 컬럼
if (allColumns.includes("title")) {
return "title";
}
// 5. 참조 컬럼 (referenceColumn)
if (referenceColumn && allColumns.includes(referenceColumn)) {
return referenceColumn;
}
// 6. 기본값: 첫 번째 비-id 컬럼 또는 id
return allColumns.find((col) => col !== "id") || "id";
} catch (error) {
logger.error(`표시 컬럼 감지 실패: ${tableName}`, error);
return referenceColumn || "id"; // 오류 시 기본값
}
}
/**
*
*/

View File

@ -583,3 +583,4 @@ const result = await executeNodeFlow(flowId, {

View File

@ -356,3 +356,4 @@
- [ ] 발송 버튼의 데이터 소스가 올바르게 설정되어 있는가?

View File

@ -0,0 +1,345 @@
# 즉시 저장(quickInsert) 버튼 액션 구현 계획서
## 1. 개요
### 1.1 목적
화면에서 entity 타입 선택박스로 데이터를 선택한 후, 버튼 클릭 시 특정 테이블에 즉시 INSERT하는 기능 구현
### 1.2 사용 사례
- **공정별 설비 관리**: 좌측에서 공정 선택 → 우측에서 설비 선택 → "설비 추가" 버튼 클릭 → `process_equipment` 테이블에 즉시 저장
### 1.3 화면 구성 예시
```
┌─────────────────────────────────────────────────────────────┐
│ [entity 선택박스] [버튼: quickInsert] │
│ ┌─────────────────────────────┐ ┌──────────────┐ │
│ │ MCT-01 - 머시닝센터 #1 ▼ │ │ + 설비 추가 │ │
│ └─────────────────────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────┘
```
---
## 2. 기술 설계
### 2.1 버튼 액션 타입 추가
```typescript
// types/screen-management.ts
type ButtonActionType =
| "save"
| "cancel"
| "delete"
| "edit"
| "add"
| "search"
| "reset"
| "submit"
| "close"
| "popup"
| "navigate"
| "custom"
| "quickInsert" // 🆕 즉시 저장
```
### 2.2 quickInsert 설정 구조
```typescript
interface QuickInsertColumnMapping {
targetColumn: string; // 저장할 테이블의 컬럼명
sourceType: "component" | "leftPanel" | "fixed" | "currentUser";
// sourceType별 추가 설정
sourceComponentId?: string; // component: 값을 가져올 컴포넌트 ID
sourceColumn?: string; // leftPanel: 좌측 선택 데이터의 컬럼명
fixedValue?: any; // fixed: 고정값
userField?: string; // currentUser: 사용자 정보 필드 (userId, userName, companyCode)
}
interface QuickInsertConfig {
targetTable: string; // 저장할 테이블명
columnMappings: QuickInsertColumnMapping[];
// 저장 후 동작
afterInsert?: {
refreshRightPanel?: boolean; // 우측 패널 새로고침
clearComponents?: string[]; // 초기화할 컴포넌트 ID 목록
showSuccessMessage?: boolean; // 성공 메시지 표시
successMessage?: string; // 커스텀 성공 메시지
};
// 중복 체크 (선택사항)
duplicateCheck?: {
enabled: boolean;
columns: string[]; // 중복 체크할 컬럼들
errorMessage?: string; // 중복 시 에러 메시지
};
}
interface ButtonComponentConfig {
// 기존 설정들...
actionType: ButtonActionType;
// 🆕 quickInsert 전용 설정
quickInsertConfig?: QuickInsertConfig;
}
```
### 2.3 데이터 흐름
```
1. 사용자가 entity 선택박스에서 설비 선택
└─ equipment_code = "EQ-001" (내부값)
└─ 표시: "MCT-01 - 머시닝센터 #1"
2. 사용자가 "설비 추가" 버튼 클릭
3. quickInsert 핸들러 실행
├─ columnMappings 순회
│ ├─ equipment_code: component에서 값 가져오기 → "EQ-001"
│ └─ process_code: leftPanel에서 값 가져오기 → "PRC-001"
└─ INSERT 데이터 구성
{
equipment_code: "EQ-001",
process_code: "PRC-001",
company_code: "COMPANY_7", // 자동 추가
writer: "wace" // 자동 추가
}
4. API 호출: POST /api/table-management/tables/process_equipment/add
5. 성공 시
├─ 성공 메시지 표시
├─ 우측 패널(카드/테이블) 새로고침
└─ 선택박스 초기화
```
---
## 3. 구현 계획
### 3.1 Phase 1: 타입 정의 및 설정 UI
| 작업 | 파일 | 설명 |
|------|------|------|
| 1-1 | `frontend/types/screen-management.ts` | QuickInsertConfig 타입 추가 |
| 1-2 | `frontend/components/screen/config-panels/ButtonConfigPanel.tsx` | quickInsert 설정 UI 추가 |
### 3.2 Phase 2: 버튼 액션 핸들러 구현
| 작업 | 파일 | 설명 |
|------|------|------|
| 2-1 | `frontend/components/screen/InteractiveScreenViewerDynamic.tsx` | quickInsert 핸들러 추가 |
| 2-2 | 컴포넌트 값 수집 로직 | 같은 화면의 다른 컴포넌트에서 값 가져오기 |
### 3.3 Phase 3: 테스트 및 검증
| 작업 | 설명 |
|------|------|
| 3-1 | 공정별 설비 화면에서 테스트 |
| 3-2 | 중복 저장 방지 테스트 |
| 3-3 | 에러 처리 테스트 |
---
## 4. 상세 구현
### 4.1 ButtonConfigPanel 설정 UI
```
┌─────────────────────────────────────────────────────────────┐
│ 버튼 액션 타입 │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ 즉시 저장 (quickInsert) ▼ │ │
│ └─────────────────────────────────────────────────────────┘ │
│ │
│ ─────────────── 즉시 저장 설정 ─────────────── │
│ │
│ 대상 테이블 * │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ process_equipment ▼ │ │
│ └─────────────────────────────────────────────────────────┘ │
│ │
│ 컬럼 매핑 [+ 추가] │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ 매핑 #1 [삭제] │ │
│ │ 대상 컬럼: equipment_code │ │
│ │ 값 소스: 컴포넌트 선택 │ │
│ │ 컴포넌트: [equipment-select ▼] │ │
│ └─────────────────────────────────────────────────────────┘ │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ 매핑 #2 [삭제] │ │
│ │ 대상 컬럼: process_code │ │
│ │ 값 소스: 좌측 패널 데이터 │ │
│ │ 소스 컬럼: process_code │ │
│ └─────────────────────────────────────────────────────────┘ │
│ │
│ ─────────────── 저장 후 동작 ─────────────── │
│ │
│ ☑ 우측 패널 새로고침 │
│ ☑ 선택박스 초기화 │
│ ☑ 성공 메시지 표시 │
│ │
│ ─────────────── 중복 체크 (선택) ─────────────── │
│ │
│ ☐ 중복 체크 활성화 │
│ 체크 컬럼: equipment_code, process_code │
│ 에러 메시지: 이미 등록된 설비입니다. │
└─────────────────────────────────────────────────────────────┘
```
### 4.2 핸들러 구현 (의사 코드)
```typescript
const handleQuickInsert = async (config: QuickInsertConfig) => {
// 1. 컬럼 매핑에서 값 수집
const insertData: Record<string, any> = {};
for (const mapping of config.columnMappings) {
let value: any;
switch (mapping.sourceType) {
case "component":
// 같은 화면의 컴포넌트에서 값 가져오기
value = getComponentValue(mapping.sourceComponentId);
break;
case "leftPanel":
// 분할 패널 좌측 선택 데이터에서 값 가져오기
value = splitPanelContext?.selectedLeftData?.[mapping.sourceColumn];
break;
case "fixed":
value = mapping.fixedValue;
break;
case "currentUser":
value = user?.[mapping.userField];
break;
}
if (value !== undefined && value !== null && value !== "") {
insertData[mapping.targetColumn] = value;
}
}
// 2. 필수값 검증
if (Object.keys(insertData).length === 0) {
toast.error("저장할 데이터가 없습니다.");
return;
}
// 3. 중복 체크 (설정된 경우)
if (config.duplicateCheck?.enabled) {
const isDuplicate = await checkDuplicate(
config.targetTable,
config.duplicateCheck.columns,
insertData
);
if (isDuplicate) {
toast.error(config.duplicateCheck.errorMessage || "이미 존재하는 데이터입니다.");
return;
}
}
// 4. API 호출
try {
await tableTypeApi.addTableData(config.targetTable, insertData);
// 5. 성공 후 동작
if (config.afterInsert?.showSuccessMessage) {
toast.success(config.afterInsert.successMessage || "저장되었습니다.");
}
if (config.afterInsert?.refreshRightPanel) {
// 우측 패널 새로고침 트리거
onRefresh?.();
}
if (config.afterInsert?.clearComponents) {
// 지정된 컴포넌트 초기화
for (const componentId of config.afterInsert.clearComponents) {
clearComponentValue(componentId);
}
}
} catch (error) {
toast.error("저장에 실패했습니다.");
}
};
```
---
## 5. 컴포넌트 간 통신 방안
### 5.1 문제점
- 버튼 컴포넌트에서 같은 화면의 entity 선택박스 값을 가져와야 함
- 현재는 각 컴포넌트가 독립적으로 동작
### 5.2 해결 방안: formData 활용
현재 `InteractiveScreenViewerDynamic`에서 `formData` 상태로 모든 입력값을 관리하고 있음.
```typescript
// InteractiveScreenViewerDynamic.tsx
const [localFormData, setLocalFormData] = useState<Record<string, any>>({});
// entity 선택박스에서 값 변경 시
const handleFormDataChange = (fieldName: string, value: any) => {
setLocalFormData(prev => ({ ...prev, [fieldName]: value }));
};
// 버튼 클릭 시 formData에서 값 가져오기
const getComponentValue = (componentId: string) => {
// componentId로 컴포넌트의 columnName 찾기
const component = allComponents.find(c => c.id === componentId);
if (component?.columnName) {
return formData[component.columnName];
}
return undefined;
};
```
---
## 6. 테스트 시나리오
### 6.1 정상 케이스
1. 좌측 테이블에서 공정 "PRC-001" 선택
2. 우측 설비 선택박스에서 "MCT-01" 선택
3. "설비 추가" 버튼 클릭
4. `process_equipment` 테이블에 데이터 저장 확인
5. 우측 카드/테이블에 새 항목 표시 확인
### 6.2 에러 케이스
1. 좌측 미선택 상태에서 버튼 클릭 → "좌측에서 항목을 선택해주세요" 메시지
2. 설비 미선택 상태에서 버튼 클릭 → "설비를 선택해주세요" 메시지
3. 중복 데이터 저장 시도 → "이미 등록된 설비입니다" 메시지
### 6.3 엣지 케이스
1. 동일 설비 연속 추가 시도
2. 네트워크 오류 시 재시도
3. 권한 없는 사용자의 저장 시도
---
## 7. 일정
| Phase | 작업 | 예상 시간 |
|-------|------|----------|
| Phase 1 | 타입 정의 및 설정 UI | 1시간 |
| Phase 2 | 버튼 액션 핸들러 구현 | 1시간 |
| Phase 3 | 테스트 및 검증 | 30분 |
| **합계** | | **2시간 30분** |
---
## 8. 향후 확장 가능성
1. **다중 행 추가**: 여러 설비를 한 번에 선택하여 추가
2. **수정 모드**: 기존 데이터 수정 기능
3. **조건부 저장**: 특정 조건 만족 시에만 저장
4. **연쇄 저장**: 한 번의 클릭으로 여러 테이블에 저장

View File

@ -76,7 +76,6 @@ export const EmbeddedScreen = forwardRef<EmbeddedScreenHandle, EmbeddedScreenPro
// 필드 값 변경 핸들러
const handleFieldChange = useCallback((fieldName: string, value: any) => {
console.log("📝 [EmbeddedScreen] 필드 값 변경:", { fieldName, value });
setFormData((prev) => ({
...prev,
[fieldName]: value,
@ -88,10 +87,9 @@ export const EmbeddedScreen = forwardRef<EmbeddedScreenHandle, EmbeddedScreenPro
loadScreenData();
}, [embedding.childScreenId]);
// 🆕 initialFormData 변경 시 formData 업데이트 (수정 모드)
// initialFormData 변경 시 formData 업데이트 (수정 모드)
useEffect(() => {
if (initialFormData && Object.keys(initialFormData).length > 0) {
console.log("📝 [EmbeddedScreen] 초기 폼 데이터 설정:", initialFormData);
setFormData(initialFormData);
}
}, [initialFormData]);
@ -135,12 +133,6 @@ export const EmbeddedScreen = forwardRef<EmbeddedScreenHandle, EmbeddedScreenPro
});
}
console.log("🔗 [EmbeddedScreen] 우측 폼 데이터 교체:", {
allColumnNames,
selectedLeftDataKeys: selectedLeftData ? Object.keys(selectedLeftData) : [],
initializedFormDataKeys: Object.keys(initializedFormData),
});
setFormData(initializedFormData);
setFormDataVersion((v) => v + 1); // 🆕 버전 증가로 컴포넌트 강제 리렌더링
}, [position, splitPanelContext, selectedLeftData, layout]);
@ -160,13 +152,6 @@ export const EmbeddedScreen = forwardRef<EmbeddedScreenHandle, EmbeddedScreenPro
// 화면 정보 로드 (screenApi.getScreen은 직접 ScreenDefinition 객체를 반환)
const screenData = await screenApi.getScreen(embedding.childScreenId);
console.log("📋 [EmbeddedScreen] 화면 정보 API 응답:", {
screenId: embedding.childScreenId,
hasData: !!screenData,
tableName: screenData?.tableName,
screenName: screenData?.name || screenData?.screenName,
position,
});
if (screenData) {
setScreenInfo(screenData);
} else {

View File

@ -27,29 +27,12 @@ export function ScreenSplitPanel({ screenId, config, initialFormData }: ScreenSp
// config에서 splitRatio 추출 (기본값 50)
const configSplitRatio = config?.splitRatio ?? 50;
console.log("🎯 [ScreenSplitPanel] 렌더링됨!", {
screenId,
config,
leftScreenId: config?.leftScreenId,
rightScreenId: config?.rightScreenId,
configSplitRatio,
parentDataMapping: config?.parentDataMapping,
configKeys: config ? Object.keys(config) : [],
});
// 🆕 initialFormData 별도 로그 (명확한 확인)
console.log("📝 [ScreenSplitPanel] initialFormData 확인:", {
hasInitialFormData: !!initialFormData,
initialFormDataKeys: initialFormData ? Object.keys(initialFormData) : [],
initialFormData: initialFormData,
});
// 드래그로 조절 가능한 splitRatio 상태
const [splitRatio, setSplitRatio] = useState(configSplitRatio);
// config.splitRatio가 변경되면 동기화 (설정 패널에서 변경 시)
React.useEffect(() => {
console.log("📐 [ScreenSplitPanel] splitRatio 동기화:", { configSplitRatio, currentSplitRatio: splitRatio });
setSplitRatio(configSplitRatio);
}, [configSplitRatio]);

View File

@ -55,6 +55,7 @@ import { useScreenPreview } from "@/contexts/ScreenPreviewContext";
import { useTableOptions } from "@/contexts/TableOptionsContext";
import { TableFilter, ColumnVisibility } from "@/types/table-options";
import { useSplitPanelContext } from "@/contexts/SplitPanelContext";
import { useScreenContextOptional } from "@/contexts/ScreenContext";
import { useCascadingDropdown } from "@/hooks/useCascadingDropdown";
import { CascadingDropdownConfig } from "@/types/screen-management";
@ -184,6 +185,8 @@ export const InteractiveDataTable: React.FC<InteractiveDataTableProps> = ({
const { user } = useAuth(); // 사용자 정보 가져오기
const { registerTable, unregisterTable } = useTableOptions(); // Context 훅
const splitPanelContext = useSplitPanelContext(); // 분할 패널 컨텍스트
const screenContext = useScreenContextOptional(); // 화면 컨텍스트 (좌측/우측 위치 확인용)
const splitPanelPosition = screenContext?.splitPanelPosition; // 분할 패널 내 위치
const [data, setData] = useState<Record<string, any>[]>([]);
const [loading, setLoading] = useState(false);
@ -308,6 +311,41 @@ export const InteractiveDataTable: React.FC<InteractiveDataTableProps> = ({
};
}, [currentPage, searchValues, loadData, component.tableName]);
// 🆕 RelatedDataButtons 선택 이벤트 리스너 (버튼 선택 시 테이블 필터링)
const [relatedButtonFilter, setRelatedButtonFilter] = useState<{
filterColumn: string;
filterValue: any;
} | null>(null);
useEffect(() => {
const handleRelatedButtonSelect = (event: CustomEvent) => {
const { targetTable, filterColumn, filterValue } = event.detail || {};
// 이 테이블이 대상 테이블인지 확인
if (targetTable === component.tableName) {
console.log("📌 [InteractiveDataTable] RelatedDataButtons 필터 적용:", {
tableName: component.tableName,
filterColumn,
filterValue,
});
setRelatedButtonFilter({ filterColumn, filterValue });
}
};
window.addEventListener("related-button-select" as any, handleRelatedButtonSelect);
return () => {
window.removeEventListener("related-button-select" as any, handleRelatedButtonSelect);
};
}, [component.tableName]);
// relatedButtonFilter 변경 시 데이터 다시 로드
useEffect(() => {
if (relatedButtonFilter) {
loadData(1, searchValues);
}
}, [relatedButtonFilter]);
// 카테고리 타입 컬럼의 값 매핑 로드
useEffect(() => {
const loadCategoryMappings = async () => {
@ -702,10 +740,17 @@ export const InteractiveDataTable: React.FC<InteractiveDataTableProps> = ({
return;
}
// 🆕 RelatedDataButtons 필터 적용
let relatedButtonFilterValues: Record<string, any> = {};
if (relatedButtonFilter) {
relatedButtonFilterValues[relatedButtonFilter.filterColumn] = relatedButtonFilter.filterValue;
}
// 검색 파라미터와 연결 필터 병합
const mergedSearchParams = {
...searchParams,
...linkedFilterValues,
...relatedButtonFilterValues, // 🆕 RelatedDataButtons 필터 추가
};
console.log("🔍 데이터 조회 시작:", {
@ -713,6 +758,7 @@ export const InteractiveDataTable: React.FC<InteractiveDataTableProps> = ({
page,
pageSize,
linkedFilterValues,
relatedButtonFilterValues,
mergedSearchParams,
});
@ -819,7 +865,7 @@ export const InteractiveDataTable: React.FC<InteractiveDataTableProps> = ({
setLoading(false);
}
},
[component.tableName, pageSize, component.autoFilter, splitPanelContext?.selectedLeftData], // 🆕 autoFilter, 연결필터 추가
[component.tableName, pageSize, component.autoFilter, splitPanelContext?.selectedLeftData, relatedButtonFilter], // 🆕 autoFilter, 연결필터, RelatedDataButtons 필터 추가
);
// 현재 사용자 정보 로드
@ -947,7 +993,18 @@ export const InteractiveDataTable: React.FC<InteractiveDataTableProps> = ({
}
return newSet;
});
}, []);
// 분할 패널 좌측에서 선택 시 컨텍스트에 데이터 저장 (연결 필터용)
if (splitPanelContext && splitPanelPosition === "left" && !splitPanelContext.disableAutoDataTransfer) {
if (isSelected && data[rowIndex]) {
splitPanelContext.setSelectedLeftData(data[rowIndex]);
console.log("🔗 [InteractiveDataTable] 좌측 선택 데이터 저장:", data[rowIndex]);
} else if (!isSelected) {
splitPanelContext.setSelectedLeftData(null);
console.log("🔗 [InteractiveDataTable] 좌측 선택 데이터 초기화");
}
}
}, [data, splitPanelContext, splitPanelPosition]);
// 전체 선택/해제 핸들러
const handleSelectAll = useCallback(

View File

@ -584,6 +584,219 @@ export const InteractiveScreenViewerDynamic: React.FC<InteractiveScreenViewerPro
}
};
// 🆕 즉시 저장(quickInsert) 액션 핸들러
const handleQuickInsertAction = async () => {
// componentConfig에서 quickInsertConfig 가져오기
const quickInsertConfig = (comp as any).componentConfig?.action?.quickInsertConfig;
if (!quickInsertConfig?.targetTable) {
toast.error("대상 테이블이 설정되지 않았습니다.");
return;
}
// 1. 대상 테이블의 컬럼 목록 조회 (자동 매핑용)
let targetTableColumns: string[] = [];
try {
const { default: apiClient } = await import("@/lib/api/client");
const columnsResponse = await apiClient.get(
`/table-management/tables/${quickInsertConfig.targetTable}/columns`
);
if (columnsResponse.data?.success && columnsResponse.data?.data) {
const columnsData = columnsResponse.data.data.columns || columnsResponse.data.data;
targetTableColumns = columnsData.map((col: any) => col.columnName || col.column_name || col.name);
console.log("📍 대상 테이블 컬럼 목록:", targetTableColumns);
}
} catch (error) {
console.error("대상 테이블 컬럼 조회 실패:", error);
}
// 2. 컬럼 매핑에서 값 수집
const insertData: Record<string, any> = {};
const columnMappings = quickInsertConfig.columnMappings || [];
for (const mapping of columnMappings) {
let value: any;
switch (mapping.sourceType) {
case "component":
// 같은 화면의 컴포넌트에서 값 가져오기
// 방법1: sourceColumnName 사용
if (mapping.sourceColumnName && formData[mapping.sourceColumnName] !== undefined) {
value = formData[mapping.sourceColumnName];
console.log(`📍 컴포넌트 값 (sourceColumnName): ${mapping.sourceColumnName} = ${value}`);
}
// 방법2: sourceComponentId로 컴포넌트 찾아서 columnName 사용
else if (mapping.sourceComponentId) {
const sourceComp = allComponents.find((c: any) => c.id === mapping.sourceComponentId);
if (sourceComp) {
const fieldName = (sourceComp as any).columnName || sourceComp.id;
value = formData[fieldName];
console.log(`📍 컴포넌트 값 (컴포넌트 조회): ${fieldName} = ${value}`);
}
}
break;
case "leftPanel":
// 분할 패널 좌측 선택 데이터에서 값 가져오기
if (mapping.sourceColumn && splitPanelContext?.selectedLeftData) {
value = splitPanelContext.selectedLeftData[mapping.sourceColumn];
}
break;
case "fixed":
value = mapping.fixedValue;
break;
case "currentUser":
if (mapping.userField) {
switch (mapping.userField) {
case "userId":
value = user?.userId;
break;
case "userName":
value = userName;
break;
case "companyCode":
value = user?.companyCode;
break;
case "deptCode":
value = authUser?.deptCode;
break;
}
}
break;
}
if (value !== undefined && value !== null && value !== "") {
insertData[mapping.targetColumn] = value;
}
}
// 3. 좌측 패널 선택 데이터에서 자동 매핑 (컬럼명이 같고 대상 테이블에 있는 경우)
if (splitPanelContext?.selectedLeftData && targetTableColumns.length > 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'];
if (systemColumns.includes(key)) {
continue;
}
// _label, _name 으로 끝나는 표시용 컬럼 제외
if (key.endsWith('_label') || key.endsWith('_name')) {
continue;
}
// 값이 있으면 자동 추가
if (val !== undefined && val !== null && val !== '') {
insertData[key] = val;
console.log(`📍 자동 매핑 추가: ${key} = ${val}`);
}
}
}
console.log("🚀 quickInsert 최종 데이터:", insertData);
// 4. 필수값 검증
if (Object.keys(insertData).length === 0) {
toast.error("저장할 데이터가 없습니다. 값을 선택해주세요.");
return;
}
// 5. 중복 체크 (설정된 경우)
if (quickInsertConfig.duplicateCheck?.enabled && quickInsertConfig.duplicateCheck?.columns?.length > 0) {
try {
const { default: apiClient } = await import("@/lib/api/client");
// 중복 체크를 위한 검색 조건 구성
const searchConditions: Record<string, any> = {};
for (const col of quickInsertConfig.duplicateCheck.columns) {
if (insertData[col] !== undefined) {
searchConditions[col] = { value: insertData[col], operator: "equals" };
}
}
console.log("📍 중복 체크 조건:", searchConditions);
// 기존 데이터 조회
const checkResponse = await apiClient.post(
`/table-management/tables/${quickInsertConfig.targetTable}/data`,
{
page: 1,
pageSize: 1,
search: searchConditions,
}
);
console.log("📍 중복 체크 응답:", checkResponse.data);
// data 배열이 있고 길이가 0보다 크면 중복
const existingData = checkResponse.data?.data?.data || checkResponse.data?.data || [];
if (Array.isArray(existingData) && existingData.length > 0) {
toast.error(quickInsertConfig.duplicateCheck.errorMessage || "이미 존재하는 데이터입니다.");
return;
}
} catch (error) {
console.error("중복 체크 오류:", error);
// 중복 체크 실패 시 계속 진행
}
}
// 6. API 호출
try {
const { default: apiClient } = await import("@/lib/api/client");
const response = await apiClient.post(
`/table-management/tables/${quickInsertConfig.targetTable}/add`,
insertData
);
if (response.data?.success) {
// 7. 성공 후 동작
if (quickInsertConfig.afterInsert?.showSuccessMessage !== false) {
toast.success(quickInsertConfig.afterInsert?.successMessage || "저장되었습니다.");
}
// 데이터 새로고침 (테이블리스트, 카드 디스플레이)
if (quickInsertConfig.afterInsert?.refreshData !== false) {
console.log("📍 데이터 새로고침 이벤트 발송");
if (typeof window !== "undefined") {
window.dispatchEvent(new CustomEvent("refreshTable"));
window.dispatchEvent(new CustomEvent("refreshCardDisplay"));
}
}
// 지정된 컴포넌트 초기화
if (quickInsertConfig.afterInsert?.clearComponents?.length > 0) {
for (const componentId of quickInsertConfig.afterInsert.clearComponents) {
const targetComp = allComponents.find((c: any) => c.id === componentId);
if (targetComp) {
const fieldName = (targetComp as any).columnName || targetComp.id;
onFormDataChange?.(fieldName, "");
}
}
}
} else {
toast.error(response.data?.message || "저장에 실패했습니다.");
}
} catch (error: any) {
console.error("quickInsert 오류:", error);
toast.error(error.response?.data?.message || error.message || "저장 중 오류가 발생했습니다.");
}
};
const handleClick = async () => {
try {
const actionType = config?.actionType || "save";
@ -604,6 +817,9 @@ export const InteractiveScreenViewerDynamic: React.FC<InteractiveScreenViewerPro
case "custom":
await handleCustomAction();
break;
case "quickInsert":
await handleQuickInsertAction();
break;
default:
// console.log("🔘 기본 버튼 클릭");
}

View File

@ -101,6 +101,46 @@ export const SaveModal: React.FC<SaveModalProps> = ({
};
}, [onClose]);
// 필수 항목 검증
const validateRequiredFields = (): { isValid: boolean; missingFields: string[] } => {
const missingFields: string[] = [];
components.forEach((component) => {
// 컴포넌트의 required 속성 확인 (여러 위치에서 체크)
const isRequired =
component.required === true ||
component.style?.required === true ||
component.componentConfig?.required === true;
const columnName = component.columnName || component.style?.columnName;
const label = component.label || component.style?.label || columnName;
console.log("🔍 필수 항목 검증:", {
componentId: component.id,
columnName,
label,
isRequired,
"component.required": component.required,
"style.required": component.style?.required,
"componentConfig.required": component.componentConfig?.required,
value: formData[columnName || ""],
});
if (isRequired && columnName) {
const value = formData[columnName];
// 값이 비어있는지 확인 (null, undefined, 빈 문자열, 공백만 있는 문자열)
if (value === null || value === undefined || (typeof value === "string" && value.trim() === "")) {
missingFields.push(label || columnName);
}
}
});
return {
isValid: missingFields.length === 0,
missingFields,
};
};
// 저장 핸들러
const handleSave = async () => {
if (!screenData || !screenId) return;
@ -111,6 +151,13 @@ export const SaveModal: React.FC<SaveModalProps> = ({
return;
}
// ✅ 필수 항목 검증
const validation = validateRequiredFields();
if (!validation.isValid) {
toast.error(`필수 항목을 입력해주세요: ${validation.missingFields.join(", ")}`);
return;
}
try {
setIsSaving(true);

View File

@ -16,6 +16,7 @@ import { apiClient } from "@/lib/api/client";
import { ButtonDataflowConfigPanel } from "./ButtonDataflowConfigPanel";
import { ImprovedButtonControlConfigPanel } from "./ImprovedButtonControlConfigPanel";
import { FlowVisibilityConfigPanel } from "./FlowVisibilityConfigPanel";
import { QuickInsertConfigSection } from "./QuickInsertConfigSection";
// 🆕 제목 블록 타입
interface TitleBlock {
@ -642,9 +643,11 @@ export const ButtonConfigPanel: React.FC<ButtonConfigPanelProps> = ({
<SelectItem value="edit"></SelectItem>
<SelectItem value="copy"> ( )</SelectItem>
<SelectItem value="navigate"> </SelectItem>
<SelectItem value="transferData">📦 </SelectItem>
<SelectItem value="openModalWithData"> + 🆕</SelectItem>
<SelectItem value="transferData"> </SelectItem>
<SelectItem value="openModalWithData"> + </SelectItem>
<SelectItem value="openRelatedModal"> </SelectItem>
<SelectItem value="modal"> </SelectItem>
<SelectItem value="quickInsert"> </SelectItem>
<SelectItem value="control"> </SelectItem>
<SelectItem value="view_table_history"> </SelectItem>
<SelectItem value="excel_download"> </SelectItem>
@ -3068,6 +3071,16 @@ export const ButtonConfigPanel: React.FC<ButtonConfigPanelProps> = ({
</div>
)}
{/* 🆕 즉시 저장(quickInsert) 액션 설정 */}
{component.componentConfig?.action?.type === "quickInsert" && (
<QuickInsertConfigSection
component={component}
onUpdateProperty={onUpdateProperty}
allComponents={allComponents}
currentTableName={currentTableName}
/>
)}
{/* 제어 기능 섹션 */}
<div className="mt-8 border-t border-border pt-6">
<ImprovedButtonControlConfigPanel component={component} onUpdateProperty={onUpdateProperty} />

View File

@ -189,6 +189,33 @@ export const EntityConfigPanel: React.FC<WebTypeConfigPanelProps> = ({
<div className="space-y-3">
<h4 className="text-sm font-medium"> </h4>
{/* UI 모드 선택 */}
<div className="space-y-2">
<Label htmlFor="uiMode" className="text-xs">
UI
</Label>
<Select
value={(localConfig as any).uiMode || "combo"}
onValueChange={(value) => updateConfig("uiMode" as any, value)}
>
<SelectTrigger className="text-xs">
<SelectValue placeholder="모드 선택" />
</SelectTrigger>
<SelectContent>
<SelectItem value="select"> (Select)</SelectItem>
<SelectItem value="modal"> (Modal)</SelectItem>
<SelectItem value="combo"> + (Combo)</SelectItem>
<SelectItem value="autocomplete"> (Autocomplete)</SelectItem>
</SelectContent>
</Select>
<p className="text-[10px] text-muted-foreground">
{(localConfig as any).uiMode === "select" && "검색 가능한 드롭다운 형태로 표시됩니다."}
{(localConfig as any).uiMode === "modal" && "모달 팝업에서 데이터를 검색하고 선택합니다."}
{((localConfig as any).uiMode === "combo" || !(localConfig as any).uiMode) && "입력 필드와 검색 버튼이 함께 표시됩니다."}
{(localConfig as any).uiMode === "autocomplete" && "입력하면서 자동완성 목록이 표시됩니다."}
</p>
</div>
<div className="space-y-2">
<Label htmlFor="entityType" className="text-xs">

View File

@ -0,0 +1,658 @@
"use client";
import React, { useState, useEffect, useCallback } from "react";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { Check, ChevronsUpDown, Plus, X, Search } from "lucide-react";
import { cn } from "@/lib/utils";
import { ComponentData } from "@/types/screen";
import { QuickInsertConfig, QuickInsertColumnMapping } from "@/types/screen-management";
import { apiClient } from "@/lib/api/client";
interface QuickInsertConfigSectionProps {
component: ComponentData;
onUpdateProperty: (path: string, value: any) => void;
allComponents?: ComponentData[];
currentTableName?: string;
}
interface TableOption {
name: string;
label: string;
}
interface ColumnOption {
name: string;
label: string;
}
export const QuickInsertConfigSection: React.FC<QuickInsertConfigSectionProps> = ({
component,
onUpdateProperty,
allComponents = [],
currentTableName,
}) => {
// 현재 설정 가져오기
const config: QuickInsertConfig = component.componentConfig?.action?.quickInsertConfig || {
targetTable: "",
columnMappings: [],
afterInsert: {
refreshData: true,
clearComponents: [],
showSuccessMessage: true,
successMessage: "저장되었습니다.",
},
duplicateCheck: {
enabled: false,
columns: [],
errorMessage: "이미 존재하는 데이터입니다.",
},
};
// 테이블 목록 상태
const [tables, setTables] = useState<TableOption[]>([]);
const [tablesLoading, setTablesLoading] = useState(false);
const [tablePopoverOpen, setTablePopoverOpen] = useState(false);
const [tableSearch, setTableSearch] = useState("");
// 대상 테이블 컬럼 목록 상태
const [targetColumns, setTargetColumns] = useState<ColumnOption[]>([]);
const [targetColumnsLoading, setTargetColumnsLoading] = useState(false);
// 매핑별 Popover 상태
const [targetColumnPopoverOpen, setTargetColumnPopoverOpen] = useState<Record<number, boolean>>({});
const [targetColumnSearch, setTargetColumnSearch] = useState<Record<number, string>>({});
const [sourceComponentPopoverOpen, setSourceComponentPopoverOpen] = useState<Record<number, boolean>>({});
const [sourceComponentSearch, setSourceComponentSearch] = useState<Record<number, string>>({});
// 테이블 목록 로드
useEffect(() => {
const loadTables = async () => {
setTablesLoading(true);
try {
const response = await apiClient.get("/table-management/tables");
if (response.data?.success && response.data?.data) {
setTables(
response.data.data.map((t: any) => ({
name: t.tableName,
label: t.displayName || t.tableName,
}))
);
}
} catch (error) {
console.error("테이블 목록 로드 실패:", error);
} finally {
setTablesLoading(false);
}
};
loadTables();
}, []);
// 대상 테이블 선택 시 컬럼 로드
useEffect(() => {
const loadTargetColumns = async () => {
if (!config.targetTable) {
setTargetColumns([]);
return;
}
setTargetColumnsLoading(true);
try {
const response = await apiClient.get(`/table-management/tables/${config.targetTable}/columns`);
if (response.data?.success && response.data?.data) {
// columns가 배열인지 확인 (data.columns 또는 data 직접)
const columns = response.data.data.columns || response.data.data;
setTargetColumns(
(Array.isArray(columns) ? columns : []).map((col: any) => ({
name: col.columnName || col.column_name,
label: col.displayName || col.columnLabel || col.column_label || col.columnName || col.column_name,
}))
);
}
} catch (error) {
console.error("컬럼 목록 로드 실패:", error);
setTargetColumns([]);
} finally {
setTargetColumnsLoading(false);
}
};
loadTargetColumns();
}, [config.targetTable]);
// 설정 업데이트 헬퍼
const updateConfig = useCallback(
(updates: Partial<QuickInsertConfig>) => {
const newConfig = { ...config, ...updates };
onUpdateProperty("componentConfig.action.quickInsertConfig", newConfig);
},
[config, onUpdateProperty]
);
// 컬럼 매핑 추가
const addMapping = () => {
const newMapping: QuickInsertColumnMapping = {
targetColumn: "",
sourceType: "component",
sourceComponentId: "",
};
updateConfig({
columnMappings: [...(config.columnMappings || []), newMapping],
});
};
// 컬럼 매핑 삭제
const removeMapping = (index: number) => {
const newMappings = [...(config.columnMappings || [])];
newMappings.splice(index, 1);
updateConfig({ columnMappings: newMappings });
};
// 컬럼 매핑 업데이트
const updateMapping = (index: number, updates: Partial<QuickInsertColumnMapping>) => {
const newMappings = [...(config.columnMappings || [])];
newMappings[index] = { ...newMappings[index], ...updates };
updateConfig({ columnMappings: newMappings });
};
// 필터링된 테이블 목록
const filteredTables = tables.filter(
(t) =>
t.name.toLowerCase().includes(tableSearch.toLowerCase()) ||
t.label.toLowerCase().includes(tableSearch.toLowerCase())
);
// 컴포넌트 목록 (entity 타입 우선)
const availableComponents = allComponents.filter((comp: any) => {
// entity 타입 또는 select 타입 컴포넌트 필터링
const widgetType = comp.widgetType || comp.componentType || "";
return widgetType === "entity" || widgetType === "select" || widgetType === "text";
});
return (
<div className="mt-4 space-y-4 rounded-lg border bg-green-50 p-4 dark:bg-green-950/20">
<h4 className="text-sm font-medium text-foreground"> </h4>
<p className="text-xs text-muted-foreground">
.
</p>
{/* 대상 테이블 선택 */}
<div>
<Label> *</Label>
<Popover open={tablePopoverOpen} onOpenChange={setTablePopoverOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={tablePopoverOpen}
className="h-8 w-full justify-between text-xs"
disabled={tablesLoading}
>
{config.targetTable
? tables.find((t) => t.name === config.targetTable)?.label || config.targetTable
: "테이블을 선택하세요..."}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="p-0" align="start" style={{ width: "var(--radix-popover-trigger-width)" }}>
<Command>
<CommandInput
placeholder="테이블 검색..."
value={tableSearch}
onValueChange={setTableSearch}
className="text-xs"
/>
<CommandList>
<CommandEmpty className="text-xs"> .</CommandEmpty>
<CommandGroup>
{filteredTables.map((table) => (
<CommandItem
key={table.name}
value={`${table.label} ${table.name}`}
onSelect={() => {
updateConfig({ targetTable: table.name, columnMappings: [] });
setTablePopoverOpen(false);
setTableSearch("");
}}
className="text-xs"
>
<Check
className={cn("mr-2 h-4 w-4", config.targetTable === table.name ? "opacity-100" : "opacity-0")}
/>
<div className="flex flex-col">
<span className="font-medium">{table.label}</span>
<span className="text-[10px] text-muted-foreground">{table.name}</span>
</div>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
</div>
{/* 컬럼 매핑 */}
{config.targetTable && (
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label> </Label>
<Button type="button" variant="outline" size="sm" onClick={addMapping} className="h-6 text-xs">
<Plus className="mr-1 h-3 w-3" />
</Button>
</div>
{(config.columnMappings || []).length === 0 ? (
<div className="rounded border-2 border-dashed py-4 text-center text-xs text-muted-foreground">
</div>
) : (
<div className="space-y-2">
{(config.columnMappings || []).map((mapping, index) => (
<Card key={index} className="p-3">
<div className="space-y-2">
<div className="flex items-center justify-between">
<span className="text-xs font-medium"> #{index + 1}</span>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => removeMapping(index)}
className="h-5 w-5 p-0 text-destructive hover:text-destructive"
>
<X className="h-3 w-3" />
</Button>
</div>
{/* 대상 컬럼 */}
<div>
<Label className="text-xs"> ( )</Label>
<Popover
open={targetColumnPopoverOpen[index] || false}
onOpenChange={(open) => setTargetColumnPopoverOpen((prev) => ({ ...prev, [index]: open }))}
>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
className="h-7 w-full justify-between text-xs"
disabled={targetColumnsLoading}
>
{mapping.targetColumn
? targetColumns.find((c) => c.name === mapping.targetColumn)?.label || mapping.targetColumn
: "컬럼 선택..."}
<ChevronsUpDown className="ml-2 h-3 w-3 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="p-0" align="start" style={{ width: "var(--radix-popover-trigger-width)" }}>
<Command>
<CommandInput
placeholder="컬럼 검색..."
value={targetColumnSearch[index] || ""}
onValueChange={(v) => setTargetColumnSearch((prev) => ({ ...prev, [index]: v }))}
className="text-xs"
/>
<CommandList>
<CommandEmpty className="text-xs"> .</CommandEmpty>
<CommandGroup>
{targetColumns
.filter(
(c) =>
c.name.toLowerCase().includes((targetColumnSearch[index] || "").toLowerCase()) ||
c.label.toLowerCase().includes((targetColumnSearch[index] || "").toLowerCase())
)
.map((col) => (
<CommandItem
key={col.name}
value={`${col.label} ${col.name}`}
onSelect={() => {
updateMapping(index, { targetColumn: col.name });
setTargetColumnPopoverOpen((prev) => ({ ...prev, [index]: false }));
setTargetColumnSearch((prev) => ({ ...prev, [index]: "" }));
}}
className="text-xs"
>
<Check
className={cn(
"mr-2 h-3 w-3",
mapping.targetColumn === col.name ? "opacity-100" : "opacity-0"
)}
/>
<div className="flex flex-col">
<span>{col.label}</span>
<span className="text-[10px] text-muted-foreground">{col.name}</span>
</div>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
</div>
{/* 값 소스 타입 */}
<div>
<Label className="text-xs"> </Label>
<Select
value={mapping.sourceType}
onValueChange={(value: "component" | "leftPanel" | "fixed" | "currentUser") => {
updateMapping(index, {
sourceType: value,
sourceComponentId: undefined,
sourceColumn: undefined,
fixedValue: undefined,
userField: undefined,
});
}}
>
<SelectTrigger className="h-7 text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="component" className="text-xs">
</SelectItem>
<SelectItem value="leftPanel" className="text-xs">
</SelectItem>
<SelectItem value="fixed" className="text-xs">
</SelectItem>
<SelectItem value="currentUser" className="text-xs">
</SelectItem>
</SelectContent>
</Select>
</div>
{/* 소스 타입별 추가 설정 */}
{mapping.sourceType === "component" && (
<div>
<Label className="text-xs"> </Label>
<Popover
open={sourceComponentPopoverOpen[index] || false}
onOpenChange={(open) => setSourceComponentPopoverOpen((prev) => ({ ...prev, [index]: open }))}
>
<PopoverTrigger asChild>
<Button variant="outline" role="combobox" className="h-7 w-full justify-between text-xs">
{mapping.sourceComponentId
? (() => {
const comp = allComponents.find((c: any) => c.id === mapping.sourceComponentId);
return comp?.label || comp?.columnName || mapping.sourceComponentId;
})()
: "컴포넌트 선택..."}
<ChevronsUpDown className="ml-2 h-3 w-3 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="p-0" align="start" style={{ width: "var(--radix-popover-trigger-width)" }}>
<Command>
<CommandInput
placeholder="컴포넌트 검색..."
value={sourceComponentSearch[index] || ""}
onValueChange={(v) => setSourceComponentSearch((prev) => ({ ...prev, [index]: v }))}
className="text-xs"
/>
<CommandList>
<CommandEmpty className="text-xs"> .</CommandEmpty>
<CommandGroup>
{availableComponents
.filter((comp: any) => {
const search = (sourceComponentSearch[index] || "").toLowerCase();
const label = (comp.label || "").toLowerCase();
const colName = (comp.columnName || "").toLowerCase();
return label.includes(search) || colName.includes(search);
})
.map((comp: any) => (
<CommandItem
key={comp.id}
value={comp.id}
onSelect={() => {
// sourceComponentId와 함께 sourceColumnName도 저장 (formData 접근용)
updateMapping(index, {
sourceComponentId: comp.id,
sourceColumnName: comp.columnName || undefined,
});
setSourceComponentPopoverOpen((prev) => ({ ...prev, [index]: false }));
setSourceComponentSearch((prev) => ({ ...prev, [index]: "" }));
}}
className="text-xs"
>
<Check
className={cn(
"mr-2 h-3 w-3",
mapping.sourceComponentId === comp.id ? "opacity-100" : "opacity-0"
)}
/>
<div className="flex flex-col">
<span>{comp.label || comp.columnName || comp.id}</span>
<span className="text-[10px] text-muted-foreground">
{comp.widgetType || comp.componentType}
</span>
</div>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
</div>
)}
{mapping.sourceType === "leftPanel" && (
<div>
<Label className="text-xs"> </Label>
<Input
placeholder="예: process_code"
value={mapping.sourceColumn || ""}
onChange={(e) => updateMapping(index, { sourceColumn: e.target.value })}
className="h-7 text-xs"
/>
<p className="mt-1 text-[10px] text-muted-foreground">
</p>
</div>
)}
{mapping.sourceType === "fixed" && (
<div>
<Label className="text-xs"></Label>
<Input
placeholder="고정값 입력"
value={mapping.fixedValue || ""}
onChange={(e) => updateMapping(index, { fixedValue: e.target.value })}
className="h-7 text-xs"
/>
</div>
)}
{mapping.sourceType === "currentUser" && (
<div>
<Label className="text-xs"> </Label>
<Select
value={mapping.userField || ""}
onValueChange={(value: "userId" | "userName" | "companyCode" | "deptCode") => {
updateMapping(index, { userField: value });
}}
>
<SelectTrigger className="h-7 text-xs">
<SelectValue placeholder="필드 선택..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="userId" className="text-xs">
ID
</SelectItem>
<SelectItem value="userName" className="text-xs">
</SelectItem>
<SelectItem value="companyCode" className="text-xs">
</SelectItem>
<SelectItem value="deptCode" className="text-xs">
</SelectItem>
</SelectContent>
</Select>
</div>
)}
</div>
</Card>
))}
</div>
)}
</div>
)}
{/* 저장 후 동작 설정 */}
{config.targetTable && (
<div className="space-y-3 rounded border bg-background p-3">
<Label className="text-xs font-medium"> </Label>
<div className="flex items-center justify-between">
<Label className="text-xs font-normal"> </Label>
<Switch
checked={config.afterInsert?.refreshData ?? true}
onCheckedChange={(checked) => {
updateConfig({
afterInsert: { ...config.afterInsert, refreshData: checked },
});
}}
/>
</div>
<p className="text-[10px] text-muted-foreground -mt-2">
,
</p>
<div className="flex items-center justify-between">
<Label className="text-xs font-normal"> </Label>
<Switch
checked={config.afterInsert?.showSuccessMessage ?? true}
onCheckedChange={(checked) => {
updateConfig({
afterInsert: { ...config.afterInsert, showSuccessMessage: checked },
});
}}
/>
</div>
{config.afterInsert?.showSuccessMessage && (
<div>
<Label className="text-xs"> </Label>
<Input
placeholder="저장되었습니다."
value={config.afterInsert?.successMessage || ""}
onChange={(e) => {
updateConfig({
afterInsert: { ...config.afterInsert, successMessage: e.target.value },
});
}}
className="h-7 text-xs"
/>
</div>
)}
</div>
)}
{/* 중복 체크 설정 */}
{config.targetTable && (
<div className="space-y-3 rounded border bg-background p-3">
<div className="flex items-center justify-between">
<Label className="text-xs font-medium"> </Label>
<Switch
checked={config.duplicateCheck?.enabled ?? false}
onCheckedChange={(checked) => {
updateConfig({
duplicateCheck: { ...config.duplicateCheck, enabled: checked },
});
}}
/>
</div>
{config.duplicateCheck?.enabled && (
<>
<div>
<Label className="text-xs"> </Label>
<div className="mt-1 max-h-40 overflow-y-auto rounded border bg-background p-2">
{targetColumns.length === 0 ? (
<p className="text-[10px] text-muted-foreground"> ...</p>
) : (
<div className="space-y-1">
{targetColumns.map((col) => {
const isChecked = (config.duplicateCheck?.columns || []).includes(col.name);
return (
<div
key={col.name}
className="flex cursor-pointer items-center gap-2 rounded px-1 py-0.5 hover:bg-muted"
onClick={() => {
const currentColumns = config.duplicateCheck?.columns || [];
const newColumns = isChecked
? currentColumns.filter((c) => c !== col.name)
: [...currentColumns, col.name];
updateConfig({
duplicateCheck: { ...config.duplicateCheck, columns: newColumns },
});
}}
>
<input
type="checkbox"
checked={isChecked}
onChange={() => {}}
className="h-3 w-3 flex-shrink-0"
/>
<span className="flex-1 text-xs whitespace-nowrap">
{col.label}{col.label !== col.name && ` (${col.name})`}
</span>
</div>
);
})}
</div>
)}
</div>
<p className="mt-1 text-[10px] text-muted-foreground">
</p>
</div>
<div>
<Label className="text-xs"> </Label>
<Input
placeholder="이미 존재하는 데이터입니다."
value={config.duplicateCheck?.errorMessage || ""}
onChange={(e) => {
updateConfig({
duplicateCheck: { ...config.duplicateCheck, errorMessage: e.target.value },
});
}}
className="h-7 text-xs"
/>
</div>
</>
)}
</div>
)}
{/* 사용 안내 */}
<div className="rounded-md bg-green-100 p-3 dark:bg-green-900/30">
<p className="text-xs text-green-900 dark:text-green-100">
<strong> :</strong>
<br />
1.
<br />
2.
<br />
3.
</p>
</div>
</div>
);
};
export default QuickInsertConfigSection;

View File

@ -943,6 +943,18 @@ export const UnifiedPropertiesPanel: React.FC<UnifiedPropertiesPanelProps> = ({
<Label className="text-xs"></Label>
</div>
)}
{/* 숨김 옵션 */}
<div className="flex items-center space-x-2">
<Checkbox
checked={selectedComponent.hidden === true || selectedComponent.componentConfig?.hidden === true}
onCheckedChange={(checked) => {
handleUpdate("hidden", checked);
handleUpdate("componentConfig.hidden", checked);
}}
className="h-4 w-4"
/>
<Label className="text-xs"></Label>
</div>
</div>
</div>
);

View File

@ -25,12 +25,6 @@ export function TabsWidget({ component, className, style, menuObjid }: TabsWidge
persistSelection = false,
} = component;
console.log("🎨 TabsWidget 렌더링:", {
componentId: component.id,
tabs,
tabsLength: tabs.length,
component,
});
const storageKey = `tabs-${component.id}-selected`;
@ -67,15 +61,7 @@ export function TabsWidget({ component, className, style, menuObjid }: TabsWidge
// 초기 로드 시 선택된 탭의 화면 불러오기
useEffect(() => {
const currentTab = visibleTabs.find((t) => t.id === selectedTab);
console.log("🔄 초기 탭 로드:", {
selectedTab,
currentTab,
hasScreenId: !!currentTab?.screenId,
screenId: currentTab?.screenId,
});
if (currentTab && currentTab.screenId && !screenLayouts[currentTab.screenId]) {
console.log("📥 초기 화면 로딩 시작:", currentTab.screenId);
loadScreenLayout(currentTab.screenId);
}
}, [selectedTab, visibleTabs]);
@ -83,26 +69,20 @@ export function TabsWidget({ component, className, style, menuObjid }: TabsWidge
// 화면 레이아웃 로드
const loadScreenLayout = async (screenId: number) => {
if (screenLayouts[screenId]) {
console.log("✅ 이미 로드된 화면:", screenId);
return; // 이미 로드됨
}
console.log("📥 화면 레이아웃 로딩 시작:", screenId);
setLoadingScreens((prev) => ({ ...prev, [screenId]: true }));
try {
const { apiClient } = await import("@/lib/api/client");
const response = await apiClient.get(`/screen-management/screens/${screenId}/layout`);
console.log("📦 API 응답:", { screenId, success: response.data.success, hasData: !!response.data.data });
if (response.data.success && response.data.data) {
console.log("✅ 화면 레이아웃 로드 완료:", screenId);
setScreenLayouts((prev) => ({ ...prev, [screenId]: response.data.data }));
} else {
console.error("❌ 화면 레이아웃 로드 실패 - success false");
}
} catch (error) {
console.error(`화면 레이아웃 로드 실패 ${screenId}:`, error);
console.error(`화면 레이아웃 로드 실패 ${screenId}:`, error);
} finally {
setLoadingScreens((prev) => ({ ...prev, [screenId]: false }));
}
@ -110,10 +90,9 @@ export function TabsWidget({ component, className, style, menuObjid }: TabsWidge
// 탭 변경 핸들러
const handleTabChange = (tabId: string) => {
console.log("🔄 탭 변경:", tabId);
setSelectedTab(tabId);
// 🆕 마운트된 탭 목록에 추가 (한 번 마운트되면 유지)
// 마운트된 탭 목록에 추가 (한 번 마운트되면 유지)
setMountedTabs(prev => {
if (prev.has(tabId)) return prev;
const newSet = new Set(prev);
@ -123,10 +102,7 @@ export function TabsWidget({ component, className, style, menuObjid }: TabsWidge
// 해당 탭의 화면 로드
const tab = visibleTabs.find((t) => t.id === tabId);
console.log("🔍 선택된 탭 정보:", { tab, hasScreenId: !!tab?.screenId, screenId: tab?.screenId });
if (tab && tab.screenId && !screenLayouts[tab.screenId]) {
console.log("📥 탭 변경 시 화면 로딩:", tab.screenId);
loadScreenLayout(tab.screenId);
}
};
@ -157,7 +133,6 @@ export function TabsWidget({ component, className, style, menuObjid }: TabsWidge
};
if (visibleTabs.length === 0) {
console.log("⚠️ 보이는 탭이 없음");
return (
<div className="flex h-full w-full items-center justify-center rounded border-2 border-dashed border-gray-300 bg-gray-50">
<p className="text-muted-foreground text-sm"> </p>
@ -165,13 +140,6 @@ export function TabsWidget({ component, className, style, menuObjid }: TabsWidge
);
}
console.log("🎨 TabsWidget 최종 렌더링:", {
visibleTabsCount: visibleTabs.length,
selectedTab,
screenLayoutsKeys: Object.keys(screenLayouts),
loadingScreensKeys: Object.keys(loadingScreens),
});
return (
<div className="flex h-full w-full flex-col pt-4" style={style}>
<Tabs
@ -233,14 +201,6 @@ export function TabsWidget({ component, className, style, menuObjid }: TabsWidge
const layoutData = screenLayouts[tab.screenId];
const { components = [], screenResolution } = layoutData;
// 비활성 탭은 로그 생략
if (isActive) {
console.log("🎯 렌더링할 화면 데이터:", {
screenId: tab.screenId,
componentsCount: components.length,
screenResolution,
});
}
const designWidth = screenResolution?.width || 1920;
const designHeight = screenResolution?.height || 1080;

View File

@ -282,10 +282,6 @@ export function SplitPanelProvider({
* 🆕
*/
const handleSetSelectedLeftData = useCallback((data: Record<string, any> | null) => {
logger.info(`[SplitPanelContext] 좌측 선택 데이터 설정:`, {
hasData: !!data,
dataKeys: data ? Object.keys(data) : [],
});
setSelectedLeftData(data);
}, []);
@ -323,11 +319,6 @@ export function SplitPanelProvider({
}
}
logger.info(`[SplitPanelContext] 매핑된 부모 데이터 (자동+명시적):`, {
autoMappedKeys: Object.keys(selectedLeftData),
explicitMappings: parentDataMapping.length,
finalKeys: Object.keys(mappedData),
});
return mappedData;
}, [selectedLeftData, parentDataMapping]);
@ -350,7 +341,6 @@ export function SplitPanelProvider({
}
}
logger.info(`[SplitPanelContext] 연결 필터 값:`, filterValues);
return filterValues;
}, [selectedLeftData, linkedFilters]);

View File

@ -83,14 +83,8 @@ export const TableOptionsProvider: React.FC<{ children: ReactNode }> = ({
const updatedTable = { ...table, dataCount: count };
const newMap = new Map(prev);
newMap.set(tableId, updatedTable);
console.log("🔄 [TableOptionsContext] 데이터 건수 업데이트:", {
tableId,
count,
updated: true,
});
return newMap;
}
console.warn("⚠️ [TableOptionsContext] 테이블을 찾을 수 없음:", tableId);
return prev;
});
}, []);

View File

@ -193,3 +193,4 @@ export function applyAutoFillToFormData(
}

View File

@ -26,7 +26,14 @@ export const dataApi = {
size: number;
totalPages: number;
}> => {
const response = await apiClient.get(`/data/${tableName}`, { params });
// filters를 평탄화하여 쿼리 파라미터로 전달 (백엔드 ...filters 형식에 맞춤)
const { filters, ...restParams } = params || {};
const flattenedParams = {
...restParams,
...(filters || {}), // filters 객체를 평탄화
};
const response = await apiClient.get(`/data/${tableName}`, { params: flattenedParams });
const raw = response.data || {};
const items: any[] = (raw.data ?? raw.items ?? raw.rows ?? []) as any[];

View File

@ -226,43 +226,6 @@ export const DynamicComponentRenderer: React.FC<DynamicComponentRendererProps> =
// 1. 새 컴포넌트 시스템에서 먼저 조회
const newComponent = ComponentRegistry.getComponent(componentType);
// 🔍 디버깅: screen-split-panel 조회 결과 확인
if (componentType === "screen-split-panel") {
console.log("🔍 [DynamicComponentRenderer] screen-split-panel 조회:", {
componentType,
found: !!newComponent,
componentId: component.id,
componentConfig: component.componentConfig,
hasFormData: !!props.formData,
formDataKeys: props.formData ? Object.keys(props.formData) : [],
registeredComponents: ComponentRegistry.getAllComponents().map(c => c.id),
});
}
// 🔍 디버깅: select-basic 조회 결과 확인
if (componentType === "select-basic") {
console.log("🔍 [DynamicComponentRenderer] select-basic 조회:", {
componentType,
found: !!newComponent,
componentId: component.id,
componentConfig: component.componentConfig,
});
}
// 🔍 디버깅: text-input 컴포넌트 조회 결과 확인
if (componentType === "text-input" || component.id?.includes("text") || (component as any).webType === "text") {
console.log("🔍 [DynamicComponentRenderer] text-input 조회:", {
componentType,
componentId: component.id,
componentLabel: component.label,
componentConfig: component.componentConfig,
webTypeConfig: (component as any).webTypeConfig,
autoGeneration: (component as any).autoGeneration,
found: !!newComponent,
registeredComponents: ComponentRegistry.getAllComponents().map(c => c.id),
});
}
if (newComponent) {
// 새 컴포넌트 시스템으로 렌더링
try {
@ -324,19 +287,6 @@ export const DynamicComponentRenderer: React.FC<DynamicComponentRendererProps> =
currentValue = formData?.[fieldName] || "";
}
// 🆕 디버깅: text-input 값 추출 확인
if (componentType === "text-input" && formData && Object.keys(formData).length > 0) {
console.log("🔍 [DynamicComponentRenderer] text-input 값 추출:", {
componentId: component.id,
componentLabel: component.label,
columnName: (component as any).columnName,
fieldName,
currentValue,
hasFormData: !!formData,
formDataKeys: Object.keys(formData).slice(0, 10), // 처음 10개만
});
}
// onChange 핸들러 - 컴포넌트 타입에 따라 다르게 처리
const handleChange = (value: any) => {
// autocomplete-search-input, entity-search-input은 자체적으로 onFormDataChange를 호출하므로 중복 저장 방지
@ -369,6 +319,11 @@ export const DynamicComponentRenderer: React.FC<DynamicComponentRendererProps> =
// 숨김 값 추출
const hiddenValue = component.hidden || component.componentConfig?.hidden;
// 숨김 처리: 인터랙티브 모드(실제 뷰)에서만 숨김, 디자인 모드에서는 표시
if (hiddenValue && isInteractive) {
return null;
}
// size.width와 size.height를 style.width와 style.height로 변환
const finalStyle: React.CSSProperties = {
...component.style,
@ -415,7 +370,10 @@ export const DynamicComponentRenderer: React.FC<DynamicComponentRendererProps> =
userId, // 🆕 사용자 ID
userName, // 🆕 사용자 이름
companyCode, // 🆕 회사 코드
mode,
// 🆕 화면 모드 (edit/view)와 컴포넌트 UI 모드 구분
screenMode: mode,
// componentConfig.mode가 있으면 유지 (entity-search-input의 UI 모드)
mode: component.componentConfig?.mode || mode,
isInModal,
readonly: component.readonly,
// 🆕 disabledFields 체크 또는 기존 readonly

View File

@ -388,16 +388,6 @@ export const ButtonPrimaryComponent: React.FC<ButtonPrimaryComponentProps> = ({
};
}
// 🔍 디버깅: processedConfig.action 확인
console.log("[ButtonPrimaryComponent] processedConfig.action 생성 완료", {
actionType: processedConfig.action?.type,
enableDataflowControl: processedConfig.action?.enableDataflowControl,
dataflowTiming: processedConfig.action?.dataflowTiming,
dataflowConfig: processedConfig.action?.dataflowConfig,
webTypeConfigRaw: component.webTypeConfig,
componentText: component.text,
});
// 스타일 계산
// height: 100%로 부모(RealtimePreviewDynamic의 내부 div)의 높이를 따라감
// width는 항상 100%로 고정 (부모 컨테이너가 gridColumns로 크기 제어)
@ -839,10 +829,6 @@ export const ButtonPrimaryComponent: React.FC<ButtonPrimaryComponentProps> = ({
groupedData.length > 0
) {
effectiveSelectedRowsData = groupedData;
console.log("🔗 [ButtonPrimaryComponent] groupedData에서 부모창 데이터 가져옴:", {
count: groupedData.length,
data: groupedData,
});
}
// modalDataStore에서 선택된 데이터 가져오기 (분할 패널 등에서 선택한 데이터)
@ -858,12 +844,6 @@ export const ButtonPrimaryComponent: React.FC<ButtonPrimaryComponentProps> = ({
// originalData가 있으면 그것을 사용, 없으면 item 자체 사용 (하위 호환성)
return item.originalData || item;
});
console.log("🔗 [ButtonPrimaryComponent] modalDataStore에서 선택된 데이터 가져옴:", {
tableName: effectiveTableName,
count: modalData.length,
rawData: modalData,
extractedData: effectiveSelectedRowsData,
});
}
} catch (error) {
console.warn("modalDataStore 접근 실패:", error);
@ -928,17 +908,7 @@ export const ButtonPrimaryComponent: React.FC<ButtonPrimaryComponentProps> = ({
}
}
// 🆕 디버깅: tableName 확인
console.log("🔍 [ButtonPrimaryComponent] context 생성:", {
propsTableName: tableName,
contextTableName: screenContext?.tableName,
effectiveTableName,
propsScreenId: screenId,
contextScreenId: screenContext?.screenId,
effectiveScreenId,
});
// 🆕 분할 패널 부모 데이터 가져오기 (우측 화면에서 저장 시 좌측 선택 데이터 포함)
// 분할 패널 부모 데이터 가져오기 (우측 화면에서 저장 시 좌측 선택 데이터 포함)
// 조건 완화: splitPanelContext가 있고 selectedLeftData가 있으면 가져옴
// (탭 안에서도 분할 패널 컨텍스트에 접근 가능하도록)
let splitPanelParentData: Record<string, any> | undefined;
@ -947,13 +917,6 @@ export const ButtonPrimaryComponent: React.FC<ButtonPrimaryComponentProps> = ({
// 좌측 화면이 아닌 경우에만 부모 데이터 포함 (좌측에서 저장 시 자신의 데이터를 부모로 포함하면 안됨)
if (splitPanelPosition !== "left") {
splitPanelParentData = splitPanelContext.getMappedParentData();
if (Object.keys(splitPanelParentData).length > 0) {
console.log("🔗 [ButtonPrimaryComponent] 분할 패널 부모 데이터 포함:", {
splitPanelParentData,
splitPanelPosition,
isInTab: !splitPanelPosition, // splitPanelPosition이 없으면 탭 안
});
}
}
}
@ -966,22 +929,11 @@ export const ButtonPrimaryComponent: React.FC<ButtonPrimaryComponentProps> = ({
// (일반 폼 필드는 props.formData, RepeaterFieldGroup은 screenContext.formData에 있음)
let effectiveFormData = { ...propsFormData, ...screenContextFormData };
// 🆕 분할 패널 우측이고 formData가 비어있으면 splitPanelParentData 사용
// 분할 패널 우측이고 formData가 비어있으면 splitPanelParentData 사용
if (splitPanelPosition === "right" && Object.keys(effectiveFormData).length === 0 && splitPanelParentData) {
effectiveFormData = { ...splitPanelParentData };
console.log("🔍 [ButtonPrimary] 분할 패널 우측 - splitPanelParentData 사용:", Object.keys(effectiveFormData));
}
console.log("🔍 [ButtonPrimary] formData 선택:", {
hasScreenContextFormData: Object.keys(screenContextFormData).length > 0,
screenContextKeys: Object.keys(screenContextFormData),
hasPropsFormData: Object.keys(propsFormData).length > 0,
propsFormDataKeys: Object.keys(propsFormData),
hasSplitPanelParentData: !!splitPanelParentData && Object.keys(splitPanelParentData).length > 0,
splitPanelPosition,
effectiveFormDataKeys: Object.keys(effectiveFormData),
});
const context: ButtonActionContext = {
formData: effectiveFormData,
originalData: originalData, // 🔧 빈 객체 대신 undefined 유지 (UPDATE 판단에 사용)
@ -1012,6 +964,11 @@ export const ButtonPrimaryComponent: React.FC<ButtonPrimaryComponentProps> = ({
componentConfigs,
// 🆕 분할 패널 부모 데이터 (좌측 화면에서 선택된 데이터)
splitPanelParentData,
// 🆕 분할 패널 컨텍스트 (quickInsert 등에서 좌측 패널 데이터 접근용)
splitPanelContext: splitPanelContext ? {
selectedLeftData: splitPanelContext.selectedLeftData,
refreshRightPanel: splitPanelContext.refreshRightPanel,
} : undefined,
} as ButtonActionContext;
// 확인이 필요한 액션인지 확인

View File

@ -4,6 +4,7 @@ import React, { useEffect, useState, useMemo, useCallback, useRef } from "react"
import { ComponentRendererProps } from "@/types/component";
import { CardDisplayConfig } from "./types";
import { tableTypeApi } from "@/lib/api/screen";
import { entityJoinApi } from "@/lib/api/entityJoin";
import { getFullImageUrl, apiClient } from "@/lib/api/client";
import { filterDOMProps } from "@/lib/utils/domPropsFilter";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
@ -61,20 +62,34 @@ export const CardDisplayComponent: React.FC<CardDisplayComponentProps> = ({
// 테이블 데이터 상태 관리
const [loadedTableData, setLoadedTableData] = useState<any[]>([]);
const [loadedTableColumns, setLoadedTableColumns] = useState<any[]>([]);
const [loading, setLoading] = useState(false);
const [loading, setLoading] = useState(true); // 초기 로딩 상태를 true로 설정
const [initialLoadDone, setInitialLoadDone] = useState(false); // 초기 로드 완료 여부
const [hasEverSelectedLeftData, setHasEverSelectedLeftData] = useState(false); // 좌측 데이터 선택 이력
// 필터 상태 (검색 필터 위젯에서 전달받은 필터)
const [filters, setFiltersInternal] = useState<TableFilter[]>([]);
// 필터 상태 변경 래퍼 (로깅용)
// 새로고침 트리거 (refreshCardDisplay 이벤트 수신 시 증가)
const [refreshKey, setRefreshKey] = useState(0);
// refreshCardDisplay 이벤트 리스너
useEffect(() => {
const handleRefreshCardDisplay = () => {
console.log("📍 [CardDisplay] refreshCardDisplay 이벤트 수신 - 데이터 새로고침");
setRefreshKey((prev) => prev + 1);
};
window.addEventListener("refreshCardDisplay", handleRefreshCardDisplay);
return () => {
window.removeEventListener("refreshCardDisplay", handleRefreshCardDisplay);
};
}, []);
// 필터 상태 변경 래퍼
const setFilters = useCallback((newFilters: TableFilter[]) => {
console.log("🎴 [CardDisplay] setFilters 호출됨:", {
componentId: component.id,
filtersCount: newFilters.length,
filters: newFilters,
});
setFiltersInternal(newFilters);
}, [component.id]);
}, []);
// 카테고리 매핑 상태 (카테고리 코드 -> 라벨/색상)
const [columnMeta, setColumnMeta] = useState<
@ -108,6 +123,58 @@ export const CardDisplayComponent: React.FC<CardDisplayComponentProps> = ({
setEditModalOpen(true);
};
// 삭제 핸들러
const handleCardDelete = async (data: any, index: number) => {
// 사용자 확인
if (!confirm("정말로 이 항목을 삭제하시겠습니까?")) {
return;
}
try {
const tableNameToUse = tableName || component.componentConfig?.tableName;
if (!tableNameToUse) {
alert("테이블 정보가 없습니다.");
return;
}
// 삭제할 데이터를 배열로 감싸기 (API가 배열을 기대함)
const deleteData = [data];
// API 호출로 데이터 삭제 (POST 방식으로 변경 - DELETE는 body 전달이 불안정)
// 백엔드 API는 DELETE /api/table-management/tables/:tableName/delete 이지만
// axios에서 DELETE body 전달 문제가 있어 직접 request 설정 사용
const response = await apiClient.request({
method: 'DELETE',
url: `/table-management/tables/${tableNameToUse}/delete`,
data: deleteData,
headers: {
'Content-Type': 'application/json',
},
});
if (response.data.success) {
alert("삭제되었습니다.");
// 로컬 상태에서 삭제된 항목 제거
setLoadedTableData(prev => prev.filter((item, idx) => idx !== index));
// 선택된 항목이면 선택 해제
const cardKey = getCardKey(data, index);
if (selectedRows.has(cardKey)) {
const newSelectedRows = new Set(selectedRows);
newSelectedRows.delete(cardKey);
setSelectedRows(newSelectedRows);
}
} else {
alert(`삭제 실패: ${response.data.message || response.data.error || "알 수 없는 오류"}`);
}
} catch (error: any) {
const errorMessage = error.response?.data?.message || error.message || "알 수 없는 오류";
alert(`삭제 중 오류가 발생했습니다: ${errorMessage}`);
}
};
// 편집 폼 데이터 변경 핸들러
const handleEditFormChange = (key: string, value: string) => {
setEditData((prev: any) => ({
@ -135,8 +202,7 @@ export const CardDisplayComponent: React.FC<CardDisplayComponentProps> = ({
// loadTableData();
} catch (error) {
console.error("❌ 편집 저장 실패:", error);
alert("❌ 저장에 실패했습니다.");
alert("저장에 실패했습니다.");
}
};
@ -145,6 +211,25 @@ export const CardDisplayComponent: React.FC<CardDisplayComponentProps> = ({
const loadTableData = async () => {
// 디자인 모드에서는 테이블 데이터를 로드하지 않음
if (isDesignMode) {
setLoading(false);
setInitialLoadDone(true);
return;
}
// 우측 패널인 경우, 좌측 데이터가 선택되지 않으면 데이터 로드하지 않음 (깜빡임 방지)
// splitPanelPosition이 "right"이면 분할 패널 내부이므로 연결 필터가 있을 가능성이 높음
const isRightPanelEarly = splitPanelPosition === "right";
const hasSelectedLeftDataEarly = splitPanelContext?.selectedLeftData &&
Object.keys(splitPanelContext.selectedLeftData).length > 0;
if (isRightPanelEarly && !hasSelectedLeftDataEarly) {
// 우측 패널이고 좌측 데이터가 선택되지 않은 경우 - 기존 데이터 유지 (깜빡임 방지)
// 초기 로드가 아닌 경우에는 데이터를 지우지 않음
if (!initialLoadDone) {
setLoadedTableData([]);
}
setLoading(false);
setInitialLoadDone(true);
return;
}
@ -152,18 +237,107 @@ export const CardDisplayComponent: React.FC<CardDisplayComponentProps> = ({
const tableNameToUse = tableName || component.componentConfig?.tableName || 'user_info'; // 기본 테이블명 설정
if (!tableNameToUse) {
setLoading(false);
setInitialLoadDone(true);
return;
}
// 연결 필터 확인 (분할 패널 내부일 때)
let linkedFilterValues: Record<string, any> = {};
let hasLinkedFiltersConfigured = false;
let hasSelectedLeftData = false;
if (splitPanelContext) {
// 연결 필터 설정 여부 확인 (현재 테이블에 해당하는 필터가 있는지)
const linkedFiltersConfig = splitPanelContext.linkedFilters || [];
hasLinkedFiltersConfigured = linkedFiltersConfig.some(
(filter) => filter.targetColumn?.startsWith(tableNameToUse + ".") ||
filter.targetColumn === tableNameToUse
);
// 좌측 데이터 선택 여부 확인
hasSelectedLeftData = splitPanelContext.selectedLeftData &&
Object.keys(splitPanelContext.selectedLeftData).length > 0;
linkedFilterValues = splitPanelContext.getLinkedFilterValues();
// 현재 테이블에 해당하는 필터만 추출 (테이블명.컬럼명 형식에서)
// 연결 필터는 코드 값이므로 정확한 매칭(equals)을 사용해야 함
const tableSpecificFilters: Record<string, any> = {};
for (const [key, value] of Object.entries(linkedFilterValues)) {
// key가 "테이블명.컬럼명" 형식인 경우
if (key.includes(".")) {
const [tblName, columnName] = key.split(".");
if (tblName === tableNameToUse) {
// 연결 필터는 코드 값이므로 equals 연산자 사용
tableSpecificFilters[columnName] = { value, operator: "equals" };
hasLinkedFiltersConfigured = true;
}
} else {
// 테이블명 없이 컬럼명만 있는 경우 그대로 사용 (equals)
tableSpecificFilters[key] = { value, operator: "equals" };
}
}
linkedFilterValues = tableSpecificFilters;
}
// 우측 패널이고 연결 필터가 설정되어 있지만 좌측에서 데이터가 선택되지 않은 경우 빈 데이터 표시
// 또는 우측 패널이고 linkedFilters 설정이 있으면 좌측 선택 필수
// splitPanelPosition은 screenContext에서 가져오거나, splitPanelContext에서 screenId로 확인
const isRightPanelFromContext = splitPanelPosition === "right";
const isRightPanelFromSplitContext = screenId && splitPanelContext?.getPositionByScreenId
? splitPanelContext.getPositionByScreenId(screenId as number) === "right"
: false;
const isRightPanel = isRightPanelFromContext || isRightPanelFromSplitContext;
const hasLinkedFiltersInConfig = splitPanelContext?.linkedFilters && splitPanelContext.linkedFilters.length > 0;
if (isRightPanel && (hasLinkedFiltersConfigured || hasLinkedFiltersInConfig) && !hasSelectedLeftData) {
setLoadedTableData([]);
setLoading(false);
setInitialLoadDone(true);
return;
}
try {
setLoading(true);
// API 호출 파라미터에 연결 필터 추가 (search 객체 안에 넣어야 함)
const apiParams: Record<string, any> = {
page: 1,
size: 50, // 카드 표시용으로 적당한 개수
search: Object.keys(linkedFilterValues).length > 0 ? linkedFilterValues : undefined,
};
// 조인 컬럼 설정 가져오기 (componentConfig에서)
const joinColumnsConfig = component.componentConfig?.joinColumns || [];
const entityJoinColumns = joinColumnsConfig
.filter((col: any) => col.isJoinColumn)
.map((col: any) => ({
columnName: col.columnName,
sourceColumn: col.sourceColumn,
referenceTable: col.referenceTable,
referenceColumn: col.referenceColumn,
displayColumn: col.referenceColumn,
label: col.label,
joinAlias: col.columnName, // 백엔드에서 필요한 joinAlias 추가
sourceTable: tableNameToUse, // 기준 테이블
}));
// 테이블 데이터, 컬럼 정보, 입력 타입 정보를 병렬로 로드
const [dataResponse, columnsResponse, inputTypesResponse] = await Promise.all([
tableTypeApi.getTableData(tableNameToUse, {
page: 1,
size: 50, // 카드 표시용으로 적당한 개수
}),
// 조인 컬럼이 있으면 entityJoinApi 사용
let dataResponse;
if (entityJoinColumns.length > 0) {
console.log("🔗 [CardDisplay] 엔티티 조인 API 사용:", entityJoinColumns);
dataResponse = await entityJoinApi.getTableDataWithJoins(tableNameToUse, {
...apiParams,
additionalJoinColumns: entityJoinColumns,
});
} else {
dataResponse = await tableTypeApi.getTableData(tableNameToUse, apiParams);
}
const [columnsResponse, inputTypesResponse] = await Promise.all([
tableTypeApi.getColumns(tableNameToUse),
tableTypeApi.getColumnInputTypes(tableNameToUse),
]);
@ -180,7 +354,6 @@ export const CardDisplayComponent: React.FC<CardDisplayComponentProps> = ({
codeCategory: item.codeCategory || item.code_category,
};
});
console.log("📋 [CardDisplay] 컬럼 메타 정보:", meta);
setColumnMeta(meta);
// 카테고리 타입 컬럼 찾기 및 매핑 로드
@ -188,17 +361,14 @@ export const CardDisplayComponent: React.FC<CardDisplayComponentProps> = ({
.filter(([_, m]) => m.inputType === "category")
.map(([columnName]) => columnName);
console.log("📋 [CardDisplay] 카테고리 컬럼:", categoryColumns);
if (categoryColumns.length > 0) {
const mappings: Record<string, Record<string, { label: string; color?: string }>> = {};
for (const columnName of categoryColumns) {
try {
console.log(`📋 [CardDisplay] 카테고리 매핑 로드 시작: ${tableNameToUse}/${columnName}`);
const response = await apiClient.get(`/table-categories/${tableNameToUse}/${columnName}/values`);
console.log(`📋 [CardDisplay] 카테고리 API 응답 [${columnName}]:`, response.data);
if (response.data.success && response.data.data) {
const mapping: Record<string, { label: string; color?: string }> = {};
@ -210,29 +380,27 @@ export const CardDisplayComponent: React.FC<CardDisplayComponentProps> = ({
const rawColor = item.color ?? item.badge_color;
const color = (rawColor && rawColor !== "none") ? rawColor : undefined;
mapping[code] = { label, color };
console.log(`📋 [CardDisplay] 매핑 추가: ${code} -> ${label} (color: ${color})`);
});
mappings[columnName] = mapping;
}
} catch (error) {
console.error(`❌ CardDisplay: 카테고리 매핑 로드 실패 [${columnName}]`, error);
// 카테고리 매핑 로드 실패 시 무시
}
}
console.log("📋 [CardDisplay] 최종 카테고리 매핑:", mappings);
setCategoryMappings(mappings);
}
} catch (error) {
console.error(`❌ CardDisplay: 데이터 로딩 실패`, error);
setLoadedTableData([]);
setLoadedTableColumns([]);
} finally {
setLoading(false);
setInitialLoadDone(true);
}
};
loadTableData();
}, [isDesignMode, tableName, component.componentConfig?.tableName]);
}, [isDesignMode, tableName, component.componentConfig?.tableName, splitPanelContext?.selectedLeftData, splitPanelPosition, refreshKey]);
// 컴포넌트 설정 (기본값 보장)
const componentConfig = {
@ -272,8 +440,34 @@ export const CardDisplayComponent: React.FC<CardDisplayComponentProps> = ({
componentStyle.borderColor = isSelected ? "hsl(var(--ring))" : "hsl(var(--border))";
}
// 우측 패널 + 좌측 미선택 상태 체크를 위한 값들 (displayData 외부에서 계산)
const isRightPanelForDisplay = splitPanelPosition === "right" ||
(screenId && splitPanelContext?.getPositionByScreenId?.(screenId as number) === "right");
const hasLinkedFiltersForDisplay = splitPanelContext?.linkedFilters && splitPanelContext.linkedFilters.length > 0;
const selectedLeftDataForDisplay = splitPanelContext?.selectedLeftData;
const hasSelectedLeftDataForDisplay = selectedLeftDataForDisplay &&
Object.keys(selectedLeftDataForDisplay).length > 0;
// 좌측 데이터가 한 번이라도 선택된 적이 있으면 기록
useEffect(() => {
if (hasSelectedLeftDataForDisplay) {
setHasEverSelectedLeftData(true);
}
}, [hasSelectedLeftDataForDisplay]);
// 우측 패널이고 연결 필터가 있고, 좌측 데이터가 한 번도 선택된 적이 없는 경우에만 "선택해주세요" 표시
// 한 번이라도 선택된 적이 있으면 깜빡임 방지를 위해 기존 데이터 유지
const shouldHideDataForRightPanel = isRightPanelForDisplay &&
!hasEverSelectedLeftData &&
!hasSelectedLeftDataForDisplay;
// 표시할 데이터 결정 (로드된 테이블 데이터 우선 사용)
const displayData = useMemo(() => {
// 우측 패널이고 linkedFilters가 설정되어 있지만 좌측 데이터가 선택되지 않은 경우 빈 배열 반환
if (shouldHideDataForRightPanel) {
return [];
}
// 로드된 테이블 데이터가 있으면 항상 우선 사용 (dataSource 설정 무시)
if (loadedTableData.length > 0) {
return loadedTableData;
@ -290,7 +484,7 @@ export const CardDisplayComponent: React.FC<CardDisplayComponentProps> = ({
// 데이터가 없으면 빈 배열 반환
return [];
}, [componentConfig.dataSource, loadedTableData, tableData, componentConfig.staticData]);
}, [shouldHideDataForRightPanel, loadedTableData, tableData, componentConfig.staticData]);
// 실제 사용할 테이블 컬럼 정보 (로드된 컬럼 우선 사용)
const actualTableColumns = loadedTableColumns.length > 0 ? loadedTableColumns : tableColumns;
@ -335,13 +529,8 @@ export const CardDisplayComponent: React.FC<CardDisplayComponentProps> = ({
additionalData: {},
}));
useModalDataStore.getState().setData(tableNameToUse, modalItems);
console.log("[CardDisplay] modalDataStore에 데이터 저장:", {
dataSourceId: tableNameToUse,
count: modalItems.length,
});
} else if (tableNameToUse && selectedRowsData.length === 0) {
useModalDataStore.getState().clearData(tableNameToUse);
console.log("[CardDisplay] modalDataStore 데이터 제거:", tableNameToUse);
}
// 분할 패널 컨텍스트에 선택된 데이터 저장 (좌측 화면인 경우)
@ -349,13 +538,8 @@ export const CardDisplayComponent: React.FC<CardDisplayComponentProps> = ({
if (splitPanelContext && splitPanelPosition === "left" && !splitPanelContext.disableAutoDataTransfer) {
if (checked) {
splitPanelContext.setSelectedLeftData(data);
console.log("[CardDisplay] 분할 패널 좌측 데이터 저장:", {
data,
parentDataMapping: splitPanelContext.parentDataMapping,
});
} else {
splitPanelContext.setSelectedLeftData(null);
console.log("[CardDisplay] 분할 패널 좌측 데이터 초기화");
}
}
}, [displayData, getCardKey, onFormDataChange, componentConfig.dataSource?.tableName, tableName, splitPanelContext, splitPanelPosition]);
@ -422,21 +606,38 @@ export const CardDisplayComponent: React.FC<CardDisplayComponentProps> = ({
}, [categoryMappings]);
// 필터가 변경되면 데이터 다시 로드 (테이블 리스트와 동일한 패턴)
// 초기 로드 여부 추적
const isInitialLoadRef = useRef(true);
// 초기 로드 여부 추적 - 마운트 카운터 사용 (Strict Mode 대응)
const mountCountRef = useRef(0);
useEffect(() => {
mountCountRef.current += 1;
const currentMount = mountCountRef.current;
if (!tableNameToUse || isDesignMode) return;
// 초기 로드는 별도 useEffect에서 처리하므로 스킵
if (isInitialLoadRef.current) {
isInitialLoadRef.current = false;
// 우측 패널이고 linkedFilters가 설정되어 있지만 좌측 데이터가 선택되지 않은 경우 스킵
const isRightPanel = splitPanelPosition === "right" ||
(screenId && splitPanelContext?.getPositionByScreenId?.(screenId as number) === "right");
const hasLinkedFiltersInConfig = splitPanelContext?.linkedFilters && splitPanelContext.linkedFilters.length > 0;
const hasSelectedLeftData = splitPanelContext?.selectedLeftData &&
Object.keys(splitPanelContext.selectedLeftData).length > 0;
// 우측 패널이고 좌측 데이터가 선택되지 않은 경우 - 기존 데이터 유지 (깜빡임 방지)
if (isRightPanel && !hasSelectedLeftData) {
// 데이터를 지우지 않고 로딩만 false로 설정
setLoading(false);
return;
}
// 첫 2번의 마운트는 초기 로드 useEffect에서 처리 (Strict Mode에서 2번 호출됨)
// 필터 변경이 아닌 경우 스킵
if (currentMount <= 2 && filters.length === 0) {
return;
}
const loadFilteredData = async () => {
try {
setLoading(true);
// 로딩 상태를 true로 설정하지 않음 - 기존 데이터 유지하면서 새 데이터 로드 (깜빡임 방지)
// 필터 값을 검색 파라미터로 변환
const searchParams: Record<string, any> = {};
@ -446,12 +647,6 @@ export const CardDisplayComponent: React.FC<CardDisplayComponentProps> = ({
}
});
console.log("🔍 [CardDisplay] 필터 적용 데이터 로드:", {
tableName: tableNameToUse,
filtersCount: filters.length,
searchParams,
});
// search 파라미터로 검색 조건 전달 (API 스펙에 맞게)
const dataResponse = await tableTypeApi.getTableData(tableNameToUse, {
page: 1,
@ -466,16 +661,14 @@ export const CardDisplayComponent: React.FC<CardDisplayComponentProps> = ({
tableOptionsContext.updateTableDataCount(tableId, dataResponse.data?.length || 0);
}
} catch (error) {
console.error("❌ [CardDisplay] 필터 적용 실패:", error);
} finally {
setLoading(false);
// 필터 적용 실패 시 무시
}
};
// 필터 변경 시 항상 데이터 다시 로드 (빈 필터 = 전체 데이터)
loadFilteredData();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [filters, tableNameToUse, isDesignMode, tableId]);
}, [filters, tableNameToUse, isDesignMode, tableId, splitPanelContext?.selectedLeftData, splitPanelPosition]);
// 컬럼 고유 값 조회 함수 (select 타입 필터용)
const getColumnUniqueValues = useCallback(async (columnName: string): Promise<Array<{ label: string; value: string }>> => {
@ -498,7 +691,6 @@ export const CardDisplayComponent: React.FC<CardDisplayComponentProps> = ({
label: mapping?.[value]?.label || value,
}));
} catch (error) {
console.error(`❌ [CardDisplay] 고유 값 조회 실패: ${columnName}`, error);
return [];
}
}, [tableNameToUse]);
@ -545,10 +737,6 @@ export const CardDisplayComponent: React.FC<CardDisplayComponentProps> = ({
// onFilterChange는 ref를 통해 최신 함수를 호출하는 래퍼 사용
const onFilterChangeWrapper = (newFilters: TableFilter[]) => {
console.log("🎴 [CardDisplay] onFilterChange 래퍼 호출:", {
tableId,
filtersCount: newFilters.length,
});
setFiltersRef.current(newFilters);
};
@ -568,20 +756,12 @@ export const CardDisplayComponent: React.FC<CardDisplayComponentProps> = ({
getColumnUniqueValues: getColumnUniqueValuesWrapper,
};
console.log("📋 [CardDisplay] TableOptionsContext에 등록:", {
tableId,
tableName: tableNameToUse,
columnsCount: columns.length,
dataCount: loadedTableData.length,
});
registerTableRef.current(registration);
const unregister = unregisterTableRef.current;
const currentTableId = tableId;
return () => {
console.log("📋 [CardDisplay] TableOptionsContext에서 해제:", currentTableId);
unregister(currentTableId);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
@ -593,8 +773,34 @@ export const CardDisplayComponent: React.FC<CardDisplayComponentProps> = ({
columnsKey, // 컬럼 변경 시에만 재등록
]);
// 로딩 중인 경우 로딩 표시
if (loading) {
// 우측 패널이고 좌측 데이터가 한 번도 선택된 적이 없는 경우에만 "선택해주세요" 표시
// 한 번이라도 선택된 적이 있으면 로딩 중에도 기존 데이터 유지 (깜빡임 방지)
if (shouldHideDataForRightPanel) {
return (
<div
className={className}
style={{
...componentStyle,
...style,
display: "flex",
alignItems: "center",
justifyContent: "center",
padding: "20px",
background: "#f8fafc",
borderRadius: "12px",
}}
>
<div className="text-muted-foreground text-center">
<div className="text-lg mb-2"> </div>
<div className="text-sm text-gray-400"> </div>
</div>
</div>
);
}
// 로딩 중이고 데이터가 없는 경우에만 로딩 표시
// 데이터가 있으면 로딩 중에도 기존 데이터 유지 (깜빡임 방지)
if (loading && displayData.length === 0 && !hasEverSelectedLeftData) {
return (
<div
className={className}
@ -957,6 +1163,17 @@ export const CardDisplayComponent: React.FC<CardDisplayComponentProps> = ({
</button>
)}
{(componentConfig.cardStyle?.showDeleteButton ?? false) && (
<button
className="text-xs text-red-500 hover:text-red-700 transition-colors"
onClick={(e) => {
e.stopPropagation();
handleCardDelete(data, index);
}}
>
</button>
)}
</div>
)}
</div>

View File

@ -1,6 +1,21 @@
"use client";
import React from "react";
import React, { useState, useEffect } from "react";
import { entityJoinApi } from "@/lib/api/entityJoin";
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Trash2 } from "lucide-react";
interface CardDisplayConfigPanelProps {
config: any;
@ -9,9 +24,32 @@ interface CardDisplayConfigPanelProps {
tableColumns?: any[];
}
interface EntityJoinColumn {
tableName: string;
columnName: string;
columnLabel: string;
dataType: string;
joinAlias: string;
suggestedLabel: string;
}
interface JoinTable {
tableName: string;
currentDisplayColumn: string;
joinConfig?: {
sourceColumn: string;
};
availableColumns: Array<{
columnName: string;
columnLabel: string;
dataType: string;
description?: string;
}>;
}
/**
* CardDisplay
* UI
* UI +
*/
export const CardDisplayConfigPanel: React.FC<CardDisplayConfigPanelProps> = ({
config,
@ -19,6 +57,40 @@ export const CardDisplayConfigPanel: React.FC<CardDisplayConfigPanelProps> = ({
screenTableName,
tableColumns = [],
}) => {
// 엔티티 조인 컬럼 상태
const [entityJoinColumns, setEntityJoinColumns] = useState<{
availableColumns: EntityJoinColumn[];
joinTables: JoinTable[];
}>({ availableColumns: [], joinTables: [] });
const [loadingEntityJoins, setLoadingEntityJoins] = useState(false);
// 엔티티 조인 컬럼 정보 가져오기
useEffect(() => {
const fetchEntityJoinColumns = async () => {
const tableName = config.tableName || screenTableName;
if (!tableName) {
setEntityJoinColumns({ availableColumns: [], joinTables: [] });
return;
}
setLoadingEntityJoins(true);
try {
const result = await entityJoinApi.getEntityJoinColumns(tableName);
setEntityJoinColumns({
availableColumns: result.availableColumns || [],
joinTables: result.joinTables || [],
});
} catch (error) {
console.error("Entity 조인 컬럼 조회 오류:", error);
setEntityJoinColumns({ availableColumns: [], joinTables: [] });
} finally {
setLoadingEntityJoins(false);
}
};
fetchEntityJoinColumns();
}, [config.tableName, screenTableName]);
const handleChange = (key: string, value: any) => {
onChange({ ...config, [key]: value });
};
@ -28,7 +100,6 @@ export const CardDisplayConfigPanel: React.FC<CardDisplayConfigPanelProps> = ({
let newConfig = { ...config };
let current = newConfig;
// 중첩 객체 생성
for (let i = 0; i < keys.length - 1; i++) {
if (!current[keys[i]]) {
current[keys[i]] = {};
@ -40,6 +111,47 @@ export const CardDisplayConfigPanel: React.FC<CardDisplayConfigPanelProps> = ({
onChange(newConfig);
};
// 컬럼 선택 시 조인 컬럼이면 joinColumns 설정도 함께 업데이트
const handleColumnSelect = (path: string, columnName: string) => {
const joinColumn = entityJoinColumns.availableColumns.find(
(col) => col.joinAlias === columnName
);
if (joinColumn) {
const joinColumnsConfig = config.joinColumns || [];
const existingJoinColumn = joinColumnsConfig.find(
(jc: any) => jc.columnName === columnName
);
if (!existingJoinColumn) {
const joinTableInfo = entityJoinColumns.joinTables?.find(
(jt) => jt.tableName === joinColumn.tableName
);
const newJoinColumnConfig = {
columnName: joinColumn.joinAlias,
label: joinColumn.suggestedLabel || joinColumn.columnLabel,
sourceColumn: joinTableInfo?.joinConfig?.sourceColumn || "",
referenceTable: joinColumn.tableName,
referenceColumn: joinColumn.columnName,
isJoinColumn: true,
};
onChange({
...config,
columnMapping: {
...config.columnMapping,
[path.split(".")[1]]: columnName,
},
joinColumns: [...joinColumnsConfig, newJoinColumnConfig],
});
return;
}
}
handleNestedChange(path, columnName);
};
// 표시 컬럼 추가
const addDisplayColumn = () => {
const currentColumns = config.columnMapping?.displayColumns || [];
@ -58,122 +170,198 @@ export const CardDisplayConfigPanel: React.FC<CardDisplayConfigPanelProps> = ({
const updateDisplayColumn = (index: number, value: string) => {
const currentColumns = [...(config.columnMapping?.displayColumns || [])];
currentColumns[index] = value;
const joinColumn = entityJoinColumns.availableColumns.find(
(col) => col.joinAlias === value
);
if (joinColumn) {
const joinColumnsConfig = config.joinColumns || [];
const existingJoinColumn = joinColumnsConfig.find(
(jc: any) => jc.columnName === value
);
if (!existingJoinColumn) {
const joinTableInfo = entityJoinColumns.joinTables?.find(
(jt) => jt.tableName === joinColumn.tableName
);
const newJoinColumnConfig = {
columnName: joinColumn.joinAlias,
label: joinColumn.suggestedLabel || joinColumn.columnLabel,
sourceColumn: joinTableInfo?.joinConfig?.sourceColumn || "",
referenceTable: joinColumn.tableName,
referenceColumn: joinColumn.columnName,
isJoinColumn: true,
};
onChange({
...config,
columnMapping: {
...config.columnMapping,
displayColumns: currentColumns,
},
joinColumns: [...joinColumnsConfig, newJoinColumnConfig],
});
return;
}
}
handleNestedChange("columnMapping.displayColumns", currentColumns);
};
// 테이블별로 조인 컬럼 그룹화
const joinColumnsByTable: Record<string, EntityJoinColumn[]> = {};
entityJoinColumns.availableColumns.forEach((col) => {
if (!joinColumnsByTable[col.tableName]) {
joinColumnsByTable[col.tableName] = [];
}
joinColumnsByTable[col.tableName].push(col);
});
// 컬럼 선택 셀렉트 박스 렌더링 (Shadcn UI)
const renderColumnSelect = (
value: string,
onChangeHandler: (value: string) => void,
placeholder: string = "컬럼을 선택하세요"
) => {
return (
<Select
value={value || "__none__"}
onValueChange={(val) => onChangeHandler(val === "__none__" ? "" : val)}
>
<SelectTrigger className="h-8 text-xs">
<SelectValue placeholder={placeholder} />
</SelectTrigger>
<SelectContent>
{/* 선택 안함 옵션 */}
<SelectItem value="__none__" className="text-xs text-muted-foreground">
</SelectItem>
{/* 기본 테이블 컬럼 */}
{tableColumns.length > 0 && (
<SelectGroup>
<SelectLabel className="text-xs font-semibold text-muted-foreground">
</SelectLabel>
{tableColumns.map((column) => (
<SelectItem
key={column.columnName}
value={column.columnName}
className="text-xs"
>
{column.columnLabel || column.columnName}
</SelectItem>
))}
</SelectGroup>
)}
{/* 조인 테이블별 컬럼 */}
{Object.entries(joinColumnsByTable).map(([tableName, columns]) => (
<SelectGroup key={tableName}>
<SelectLabel className="text-xs font-semibold text-blue-600">
{tableName} ()
</SelectLabel>
{columns.map((col) => (
<SelectItem
key={col.joinAlias}
value={col.joinAlias}
className="text-xs"
>
{col.suggestedLabel || col.columnLabel}
</SelectItem>
))}
</SelectGroup>
))}
</SelectContent>
</Select>
);
};
return (
<div className="space-y-4">
<div className="text-sm font-medium text-gray-700"> </div>
<div className="text-sm font-medium"> </div>
{/* 테이블이 선택된 경우 컬럼 매핑 설정 */}
{tableColumns && tableColumns.length > 0 && (
<div className="space-y-3">
<h5 className="text-xs font-medium text-gray-700"> </h5>
<h5 className="text-xs font-medium text-muted-foreground"> </h5>
<div>
<label className="mb-1 block text-xs font-medium text-gray-600"> </label>
<select
value={config.columnMapping?.titleColumn || ""}
onChange={(e) => handleNestedChange("columnMapping.titleColumn", e.target.value)}
className="w-full rounded border border-gray-300 px-2 py-1 text-sm"
>
<option value=""> </option>
{tableColumns.map((column) => (
<option key={column.columnName} value={column.columnName}>
{column.columnLabel || column.columnName} ({column.dataType})
</option>
))}
</select>
{loadingEntityJoins && (
<div className="text-xs text-muted-foreground"> ...</div>
)}
<div className="space-y-1">
<Label className="text-xs"> </Label>
{renderColumnSelect(
config.columnMapping?.titleColumn || "",
(value) => handleColumnSelect("columnMapping.titleColumn", value)
)}
</div>
<div>
<label className="mb-1 block text-xs font-medium text-gray-600"> </label>
<select
value={config.columnMapping?.subtitleColumn || ""}
onChange={(e) => handleNestedChange("columnMapping.subtitleColumn", e.target.value)}
className="w-full rounded border border-gray-300 px-2 py-1 text-sm"
>
<option value=""> </option>
{tableColumns.map((column) => (
<option key={column.columnName} value={column.columnName}>
{column.columnLabel || column.columnName} ({column.dataType})
</option>
))}
</select>
<div className="space-y-1">
<Label className="text-xs"> </Label>
{renderColumnSelect(
config.columnMapping?.subtitleColumn || "",
(value) => handleColumnSelect("columnMapping.subtitleColumn", value)
)}
</div>
<div>
<label className="mb-1 block text-xs font-medium text-gray-600"> </label>
<select
value={config.columnMapping?.descriptionColumn || ""}
onChange={(e) => handleNestedChange("columnMapping.descriptionColumn", e.target.value)}
className="w-full rounded border border-gray-300 px-2 py-1 text-sm"
>
<option value=""> </option>
{tableColumns.map((column) => (
<option key={column.columnName} value={column.columnName}>
{column.columnLabel || column.columnName} ({column.dataType})
</option>
))}
</select>
<div className="space-y-1">
<Label className="text-xs"> </Label>
{renderColumnSelect(
config.columnMapping?.descriptionColumn || "",
(value) => handleColumnSelect("columnMapping.descriptionColumn", value)
)}
</div>
<div>
<label className="mb-1 block text-xs font-medium text-gray-600"> </label>
<select
value={config.columnMapping?.imageColumn || ""}
onChange={(e) => handleNestedChange("columnMapping.imageColumn", e.target.value)}
className="w-full rounded border border-gray-300 px-2 py-1 text-sm"
>
<option value=""> </option>
{tableColumns.map((column) => (
<option key={column.columnName} value={column.columnName}>
{column.columnLabel || column.columnName} ({column.dataType})
</option>
))}
</select>
<div className="space-y-1">
<Label className="text-xs"> </Label>
{renderColumnSelect(
config.columnMapping?.imageColumn || "",
(value) => handleColumnSelect("columnMapping.imageColumn", value)
)}
</div>
{/* 동적 표시 컬럼 추가 */}
<div>
<div className="mb-2 flex items-center justify-between">
<label className="text-xs font-medium text-gray-600"> </label>
<button
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-xs"> </Label>
<Button
type="button"
variant="outline"
size="sm"
onClick={addDisplayColumn}
className="rounded bg-blue-500 px-2 py-1 text-xs text-white hover:bg-blue-600"
className="h-6 px-2 text-xs"
>
+
</button>
</Button>
</div>
<div className="space-y-2">
{(config.columnMapping?.displayColumns || []).map((column: string, index: number) => (
<div key={index} className="flex items-center space-x-2">
<select
value={column}
onChange={(e) => updateDisplayColumn(index, e.target.value)}
className="flex-1 rounded border border-gray-300 px-2 py-1 text-sm"
>
<option value=""> </option>
{tableColumns.map((col) => (
<option key={col.columnName} value={col.columnName}>
{col.columnLabel || col.columnName} ({col.dataType})
</option>
))}
</select>
<button
<div key={index} className="flex items-center gap-2">
<div className="flex-1">
{renderColumnSelect(
column,
(value) => updateDisplayColumn(index, value)
)}
</div>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => removeDisplayColumn(index)}
className="rounded bg-red-500 px-2 py-1 text-xs text-white hover:bg-red-600"
className="h-8 w-8 p-0 text-destructive hover:bg-destructive/10 hover:text-destructive"
>
</button>
<Trash2 className="h-4 w-4" />
</Button>
</div>
))}
{(!config.columnMapping?.displayColumns || config.columnMapping.displayColumns.length === 0) && (
<div className="rounded border border-dashed border-gray-300 py-2 text-center text-xs text-gray-500">
<div className="rounded-md border border-dashed border-muted-foreground/30 py-3 text-center text-xs text-muted-foreground">
"컬럼 추가"
</div>
)}
@ -184,173 +372,166 @@ export const CardDisplayConfigPanel: React.FC<CardDisplayConfigPanelProps> = ({
{/* 카드 스타일 설정 */}
<div className="space-y-3">
<h5 className="text-xs font-medium text-gray-700"> </h5>
<h5 className="text-xs font-medium text-muted-foreground"> </h5>
<div className="grid grid-cols-2 gap-2">
<div>
<label className="mb-1 block text-xs font-medium text-gray-600"> </label>
<input
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1">
<Label className="text-xs"> </Label>
<Input
type="number"
min="1"
max="6"
value={config.cardsPerRow || 3}
onChange={(e) => handleChange("cardsPerRow", parseInt(e.target.value))}
className="w-full rounded border border-gray-300 px-2 py-1 text-sm"
className="h-8 text-xs"
/>
</div>
<div>
<label className="mb-1 block text-xs font-medium text-gray-600"> (px)</label>
<input
<div className="space-y-1">
<Label className="text-xs"> (px)</Label>
<Input
type="number"
min="0"
max="50"
value={config.cardSpacing || 16}
onChange={(e) => handleChange("cardSpacing", parseInt(e.target.value))}
className="w-full rounded border border-gray-300 px-2 py-1 text-sm"
className="h-8 text-xs"
/>
</div>
</div>
<div className="space-y-2">
<div className="flex items-center space-x-2">
<input
type="checkbox"
<Checkbox
id="showTitle"
checked={config.cardStyle?.showTitle ?? true}
onChange={(e) => handleNestedChange("cardStyle.showTitle", e.target.checked)}
className="rounded border-gray-300"
onCheckedChange={(checked) => handleNestedChange("cardStyle.showTitle", checked)}
/>
<label htmlFor="showTitle" className="text-xs text-gray-600">
<Label htmlFor="showTitle" className="text-xs font-normal">
</label>
</Label>
</div>
<div className="flex items-center space-x-2">
<input
type="checkbox"
<Checkbox
id="showSubtitle"
checked={config.cardStyle?.showSubtitle ?? true}
onChange={(e) => handleNestedChange("cardStyle.showSubtitle", e.target.checked)}
className="rounded border-gray-300"
onCheckedChange={(checked) => handleNestedChange("cardStyle.showSubtitle", checked)}
/>
<label htmlFor="showSubtitle" className="text-xs text-gray-600">
<Label htmlFor="showSubtitle" className="text-xs font-normal">
</label>
</Label>
</div>
<div className="flex items-center space-x-2">
<input
type="checkbox"
<Checkbox
id="showDescription"
checked={config.cardStyle?.showDescription ?? true}
onChange={(e) => handleNestedChange("cardStyle.showDescription", e.target.checked)}
className="rounded border-gray-300"
onCheckedChange={(checked) => handleNestedChange("cardStyle.showDescription", checked)}
/>
<label htmlFor="showDescription" className="text-xs text-gray-600">
<Label htmlFor="showDescription" className="text-xs font-normal">
</label>
</Label>
</div>
<div className="flex items-center space-x-2">
<input
type="checkbox"
<Checkbox
id="showImage"
checked={config.cardStyle?.showImage ?? false}
onChange={(e) => handleNestedChange("cardStyle.showImage", e.target.checked)}
className="rounded border-gray-300"
onCheckedChange={(checked) => handleNestedChange("cardStyle.showImage", checked)}
/>
<label htmlFor="showImage" className="text-xs text-gray-600">
<Label htmlFor="showImage" className="text-xs font-normal">
</label>
</Label>
</div>
<div className="flex items-center space-x-2">
<input
type="checkbox"
<Checkbox
id="showActions"
checked={config.cardStyle?.showActions ?? true}
onChange={(e) => handleNestedChange("cardStyle.showActions", e.target.checked)}
className="rounded border-gray-300"
onCheckedChange={(checked) => handleNestedChange("cardStyle.showActions", checked)}
/>
<label htmlFor="showActions" className="text-xs text-gray-600">
<Label htmlFor="showActions" className="text-xs font-normal">
</label>
</Label>
</div>
{/* 개별 버튼 설정 (액션 버튼이 활성화된 경우에만 표시) */}
{/* 개별 버튼 설정 */}
{(config.cardStyle?.showActions ?? true) && (
<div className="ml-4 space-y-2 border-l-2 border-gray-200 pl-3">
<div className="ml-5 space-y-2 border-l-2 border-muted pl-3">
<div className="flex items-center space-x-2">
<input
type="checkbox"
<Checkbox
id="showViewButton"
checked={config.cardStyle?.showViewButton ?? true}
onChange={(e) => handleNestedChange("cardStyle.showViewButton", e.target.checked)}
className="rounded border-gray-300"
onCheckedChange={(checked) => handleNestedChange("cardStyle.showViewButton", checked)}
/>
<label htmlFor="showViewButton" className="text-xs text-gray-600">
<Label htmlFor="showViewButton" className="text-xs font-normal">
</label>
</Label>
</div>
<div className="flex items-center space-x-2">
<input
type="checkbox"
<Checkbox
id="showEditButton"
checked={config.cardStyle?.showEditButton ?? true}
onChange={(e) => handleNestedChange("cardStyle.showEditButton", e.target.checked)}
className="rounded border-gray-300"
onCheckedChange={(checked) => handleNestedChange("cardStyle.showEditButton", checked)}
/>
<label htmlFor="showEditButton" className="text-xs text-gray-600">
<Label htmlFor="showEditButton" className="text-xs font-normal">
</label>
</Label>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="showDeleteButton"
checked={config.cardStyle?.showDeleteButton ?? false}
onCheckedChange={(checked) => handleNestedChange("cardStyle.showDeleteButton", checked)}
/>
<Label htmlFor="showDeleteButton" className="text-xs font-normal">
</Label>
</div>
</div>
)}
</div>
<div>
<label className="mb-1 block text-xs font-medium text-gray-600"> </label>
<input
<div className="space-y-1">
<Label className="text-xs"> </Label>
<Input
type="number"
min="10"
max="500"
value={config.cardStyle?.maxDescriptionLength || 100}
onChange={(e) => handleNestedChange("cardStyle.maxDescriptionLength", parseInt(e.target.value))}
className="w-full rounded border border-gray-300 px-2 py-1 text-sm"
className="h-8 text-xs"
/>
</div>
</div>
{/* 공통 설정 */}
<div className="space-y-3">
<h5 className="text-xs font-medium text-gray-700"> </h5>
<h5 className="text-xs font-medium text-muted-foreground"> </h5>
<div className="flex items-center space-x-2">
<input
type="checkbox"
<Checkbox
id="disabled"
checked={config.disabled || false}
onChange={(e) => handleChange("disabled", e.target.checked)}
className="rounded border-gray-300"
onCheckedChange={(checked) => handleChange("disabled", checked)}
/>
<label htmlFor="disabled" className="text-xs text-gray-600">
<Label htmlFor="disabled" className="text-xs font-normal">
</label>
</Label>
</div>
<div className="flex items-center space-x-2">
<input
type="checkbox"
<Checkbox
id="readonly"
checked={config.readonly || false}
onChange={(e) => handleChange("readonly", e.target.checked)}
className="rounded border-gray-300"
onCheckedChange={(checked) => handleChange("readonly", checked)}
/>
<label htmlFor="readonly" className="text-xs text-gray-600">
<Label htmlFor="readonly" className="text-xs font-normal">
</label>
</Label>
</div>
</div>
</div>

View File

@ -16,6 +16,7 @@ export interface CardStyleConfig {
showActions?: boolean; // 액션 버튼 표시 여부 (전체)
showViewButton?: boolean; // 상세보기 버튼 표시 여부
showEditButton?: boolean; // 편집 버튼 표시 여부
showDeleteButton?: boolean; // 삭제 버튼 표시 여부
}
/**

View File

@ -3,17 +3,21 @@
import React, { useState, useEffect } from "react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Search, X } from "lucide-react";
import { Search, X, Check, ChevronsUpDown } from "lucide-react";
import { EntitySearchModal } from "./EntitySearchModal";
import { EntitySearchInputProps, EntitySearchResult } from "./types";
import { cn } from "@/lib/utils";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { dynamicFormApi } from "@/lib/api/dynamicForm";
export function EntitySearchInputComponent({
tableName,
displayField,
valueField,
searchFields = [displayField],
mode = "combo",
mode: modeProp,
uiMode, // EntityConfigPanel에서 저장되는 값
placeholder = "검색...",
disabled = false,
filterCondition = {},
@ -24,31 +28,144 @@ export function EntitySearchInputComponent({
showAdditionalInfo = false,
additionalFields = [],
className,
}: EntitySearchInputProps) {
style,
// 🆕 추가 props
component,
isInteractive,
onFormDataChange,
}: EntitySearchInputProps & {
uiMode?: string;
component?: any;
isInteractive?: boolean;
onFormDataChange?: (fieldName: string, value: any) => void;
}) {
// uiMode가 있으면 우선 사용, 없으면 modeProp 사용, 기본값 "combo"
const mode = (uiMode || modeProp || "combo") as "select" | "modal" | "combo" | "autocomplete";
const [modalOpen, setModalOpen] = useState(false);
const [selectOpen, setSelectOpen] = useState(false);
const [displayValue, setDisplayValue] = useState("");
const [selectedData, setSelectedData] = useState<EntitySearchResult | null>(null);
const [options, setOptions] = useState<EntitySearchResult[]>([]);
const [isLoadingOptions, setIsLoadingOptions] = useState(false);
const [optionsLoaded, setOptionsLoaded] = useState(false);
// value가 변경되면 표시값 업데이트
// filterCondition을 문자열로 변환하여 비교 (객체 참조 문제 해결)
const filterConditionKey = JSON.stringify(filterCondition || {});
// select 모드일 때 옵션 로드 (한 번만)
useEffect(() => {
if (value && selectedData) {
setDisplayValue(selectedData[displayField] || "");
} else {
setDisplayValue("");
setSelectedData(null);
if (mode === "select" && tableName && !optionsLoaded) {
loadOptions();
setOptionsLoaded(true);
}
}, [value, displayField]);
}, [mode, tableName, filterConditionKey, optionsLoaded]);
const loadOptions = async () => {
if (!tableName) return;
setIsLoadingOptions(true);
try {
const response = await dynamicFormApi.getTableData(tableName, {
page: 1,
pageSize: 100, // 최대 100개까지 로드
filters: filterCondition,
});
if (response.success && response.data) {
setOptions(response.data);
}
} catch (error) {
console.error("옵션 로드 실패:", error);
} finally {
setIsLoadingOptions(false);
}
};
// value가 변경되면 표시값 업데이트 (외래키 값으로 데이터 조회)
useEffect(() => {
const loadDisplayValue = async () => {
if (value && selectedData) {
// 이미 selectedData가 있으면 표시값만 업데이트
setDisplayValue(selectedData[displayField] || "");
} else if (value && mode === "select" && options.length > 0) {
// select 모드에서 value가 있고 options가 로드된 경우
const found = options.find((opt) => opt[valueField] === value);
if (found) {
setSelectedData(found);
setDisplayValue(found[displayField] || "");
}
} else if (value && !selectedData && tableName) {
// value는 있지만 selectedData가 없는 경우 (초기 로드 시)
// API로 해당 데이터 조회
try {
console.log("🔍 [EntitySearchInput] 초기값 조회:", { value, tableName, valueField });
const response = await dynamicFormApi.getTableData(tableName, {
filters: { [valueField]: value },
pageSize: 1,
});
if (response.success && response.data) {
// 데이터 추출 (중첩 구조 처리)
const responseData = response.data as any;
const dataArray = Array.isArray(responseData)
? responseData
: responseData?.data
? Array.isArray(responseData.data)
? responseData.data
: [responseData.data]
: [];
if (dataArray.length > 0) {
const foundData = dataArray[0];
setSelectedData(foundData);
setDisplayValue(foundData[displayField] || "");
console.log("✅ [EntitySearchInput] 초기값 로드 완료:", foundData);
} else {
// 데이터를 찾지 못한 경우 value 자체를 표시
console.log("⚠️ [EntitySearchInput] 초기값 데이터 없음, value 표시:", value);
setDisplayValue(String(value));
}
} else {
console.log("⚠️ [EntitySearchInput] API 응답 실패, value 표시:", value);
setDisplayValue(String(value));
}
} catch (error) {
console.error("❌ [EntitySearchInput] 초기값 조회 실패:", error);
// 에러 시 value 자체를 표시
setDisplayValue(String(value));
}
} else if (!value) {
setDisplayValue("");
setSelectedData(null);
}
};
loadDisplayValue();
}, [value, displayField, options, mode, valueField, tableName, selectedData]);
const handleSelect = (newValue: any, fullData: EntitySearchResult) => {
setSelectedData(fullData);
setDisplayValue(fullData[displayField] || "");
onChange?.(newValue, fullData);
// 🆕 onFormDataChange 호출 (formData에 값 저장)
if (isInteractive && onFormDataChange && component?.columnName) {
onFormDataChange(component.columnName, newValue);
console.log("📤 EntitySearchInput -> onFormDataChange:", component.columnName, newValue);
}
};
const handleClear = () => {
setDisplayValue("");
setSelectedData(null);
onChange?.(null, null);
// 🆕 onFormDataChange 호출 (formData에서 값 제거)
if (isInteractive && onFormDataChange && component?.columnName) {
onFormDataChange(component.columnName, null);
console.log("📤 EntitySearchInput -> onFormDataChange (clear):", component.columnName, null);
}
};
const handleOpenModal = () => {
@ -57,10 +174,101 @@ export function EntitySearchInputComponent({
}
};
const handleSelectOption = (option: EntitySearchResult) => {
handleSelect(option[valueField], option);
setSelectOpen(false);
};
// 높이 계산 (style에서 height가 있으면 사용, 없으면 기본값)
const componentHeight = style?.height;
const inputStyle: React.CSSProperties = componentHeight ? { height: componentHeight } : {};
// select 모드: 검색 가능한 드롭다운
if (mode === "select") {
return (
<div className={cn("relative flex flex-col", className)} style={style}>
{/* 라벨 렌더링 */}
{component?.label && component?.style?.labelDisplay !== false && (
<label className="text-muted-foreground absolute -top-6 left-0 text-sm font-medium">
{component.label}
{component.required && <span className="text-destructive">*</span>}
</label>
)}
<Popover open={selectOpen} onOpenChange={setSelectOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={selectOpen}
disabled={disabled || isLoadingOptions}
className={cn(
"w-full justify-between font-normal",
!componentHeight && "h-8 text-xs sm:h-10 sm:text-sm",
!value && "text-muted-foreground",
)}
style={inputStyle}
>
{isLoadingOptions ? "로딩 중..." : displayValue || placeholder}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="p-0" style={{ width: "var(--radix-popover-trigger-width)" }} align="start">
<Command>
<CommandInput placeholder={`${displayField} 검색...`} className="text-xs sm:text-sm" />
<CommandList>
<CommandEmpty className="py-4 text-center text-xs sm:text-sm"> .</CommandEmpty>
<CommandGroup>
{options.map((option, index) => (
<CommandItem
key={option[valueField] || index}
value={`${option[displayField] || ""}-${option[valueField] || ""}`}
onSelect={() => handleSelectOption(option)}
className="text-xs sm:text-sm"
>
<Check
className={cn("mr-2 h-4 w-4", value === option[valueField] ? "opacity-100" : "opacity-0")}
/>
<div className="flex flex-col">
<span className="font-medium">{option[displayField]}</span>
{valueField !== displayField && (
<span className="text-muted-foreground text-[10px]">{option[valueField]}</span>
)}
</div>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
{/* 추가 정보 표시 */}
{showAdditionalInfo && selectedData && additionalFields.length > 0 && (
<div className="text-muted-foreground mt-1 space-y-1 px-2 text-xs">
{additionalFields.map((field) => (
<div key={field} className="flex gap-2">
<span className="font-medium">{field}:</span>
<span>{selectedData[field] || "-"}</span>
</div>
))}
</div>
)}
</div>
);
}
// modal, combo, autocomplete 모드
return (
<div className={cn("space-y-2", className)}>
<div className={cn("relative flex flex-col", className)} style={style}>
{/* 라벨 렌더링 */}
{component?.label && component?.style?.labelDisplay !== false && (
<label className="text-muted-foreground absolute -top-6 left-0 text-sm font-medium">
{component.label}
{component.required && <span className="text-destructive">*</span>}
</label>
)}
{/* 입력 필드 */}
<div className="flex gap-2">
<div className="flex h-full gap-2">
<div className="relative flex-1">
<Input
value={displayValue}
@ -68,7 +276,8 @@ export function EntitySearchInputComponent({
placeholder={placeholder}
disabled={disabled}
readOnly={mode === "modal" || mode === "combo"}
className="h-8 text-xs sm:h-10 sm:text-sm pr-8"
className={cn("w-full pr-8", !componentHeight && "h-8 text-xs sm:h-10 sm:text-sm")}
style={inputStyle}
/>
{displayValue && !disabled && (
<Button
@ -76,19 +285,21 @@ export function EntitySearchInputComponent({
variant="ghost"
size="sm"
onClick={handleClear}
className="absolute right-1 top-1/2 -translate-y-1/2 h-6 w-6 p-0"
className="absolute top-1/2 right-1 h-6 w-6 -translate-y-1/2 p-0"
>
<X className="h-3 w-3" />
</Button>
)}
</div>
{/* 모달 버튼: modal 또는 combo 모드일 때만 표시 */}
{(mode === "modal" || mode === "combo") && (
<Button
type="button"
onClick={handleOpenModal}
disabled={disabled}
className="h-8 text-xs sm:h-10 sm:text-sm"
className={cn(!componentHeight && "h-8 text-xs sm:h-10 sm:text-sm")}
style={inputStyle}
>
<Search className="h-4 w-4" />
</Button>
@ -97,7 +308,7 @@ export function EntitySearchInputComponent({
{/* 추가 정보 표시 */}
{showAdditionalInfo && selectedData && additionalFields.length > 0 && (
<div className="text-xs text-muted-foreground space-y-1 px-2">
<div className="text-muted-foreground mt-1 space-y-1 px-2 text-xs">
{additionalFields.map((field) => (
<div key={field} className="flex gap-2">
<span className="font-medium">{field}:</span>
@ -107,20 +318,21 @@ export function EntitySearchInputComponent({
</div>
)}
{/* 검색 모달 */}
<EntitySearchModal
open={modalOpen}
onOpenChange={setModalOpen}
tableName={tableName}
displayField={displayField}
valueField={valueField}
searchFields={searchFields}
filterCondition={filterCondition}
modalTitle={modalTitle}
modalColumns={modalColumns}
onSelect={handleSelect}
/>
{/* 검색 모달: modal 또는 combo 모드일 때만 렌더링 */}
{(mode === "modal" || mode === "combo") && (
<EntitySearchModal
open={modalOpen}
onOpenChange={setModalOpen}
tableName={tableName}
displayField={displayField}
valueField={valueField}
searchFields={searchFields}
filterCondition={filterCondition}
modalTitle={modalTitle}
modalColumns={modalColumns}
onSelect={handleSelect}
/>
)}
</div>
);
}

View File

@ -302,7 +302,7 @@ export function EntitySearchInputConfigPanel({
<Label className="text-xs sm:text-sm">UI </Label>
<Select
value={localConfig.mode || "combo"}
onValueChange={(value: "autocomplete" | "modal" | "combo") =>
onValueChange={(value: "select" | "autocomplete" | "modal" | "combo") =>
updateConfig({ mode: value })
}
>
@ -310,11 +310,18 @@ export function EntitySearchInputConfigPanel({
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="select"> ( )</SelectItem>
<SelectItem value="combo"> ( + )</SelectItem>
<SelectItem value="modal"></SelectItem>
<SelectItem value="autocomplete"></SelectItem>
</SelectContent>
</Select>
<p className="text-[10px] text-muted-foreground">
{localConfig.mode === "select" && "검색 가능한 드롭다운 형태로 표시됩니다."}
{localConfig.mode === "modal" && "모달 팝업에서 데이터를 검색하고 선택합니다."}
{(localConfig.mode === "combo" || !localConfig.mode) && "입력 필드와 검색 버튼이 함께 표시됩니다."}
{localConfig.mode === "autocomplete" && "입력하면서 자동완성 목록이 표시됩니다."}
</p>
</div>
<div className="space-y-2">

View File

@ -4,7 +4,7 @@ export interface EntitySearchInputConfig {
valueField: string;
searchFields?: string[];
filterCondition?: Record<string, any>;
mode?: "autocomplete" | "modal" | "combo";
mode?: "select" | "autocomplete" | "modal" | "combo";
placeholder?: string;
modalTitle?: string;
modalColumns?: string[];

View File

@ -11,7 +11,11 @@ export interface EntitySearchInputProps {
searchFields?: string[]; // 검색 대상 필드들 (기본: [displayField])
// UI 모드
mode?: "autocomplete" | "modal" | "combo"; // 기본: "combo"
// - select: 드롭다운 선택 (검색 가능한 콤보박스)
// - modal: 모달 팝업에서 선택
// - combo: 입력 + 모달 버튼 (기본)
// - autocomplete: 입력하면서 자동완성
mode?: "select" | "autocomplete" | "modal" | "combo"; // 기본: "combo"
placeholder?: string;
disabled?: boolean;
@ -33,6 +37,7 @@ export interface EntitySearchInputProps {
// 스타일
className?: string;
style?: React.CSSProperties;
}
export interface EntitySearchResult {

View File

@ -85,6 +85,9 @@ import "./tax-invoice-list/TaxInvoiceListRenderer"; // 세금계산서 목록,
// 🆕 메일 수신자 선택 컴포넌트
import "./mail-recipient-selector/MailRecipientSelectorRenderer"; // 내부 인원 선택 + 외부 이메일 입력
// 🆕 연관 데이터 버튼 컴포넌트
import "./related-data-buttons/RelatedDataButtonsRenderer"; // 좌측 선택 데이터 기반 연관 테이블 버튼 표시
/**
*
*/

View File

@ -0,0 +1,162 @@
# RelatedDataButtons 컴포넌트
좌측 패널에서 선택한 데이터를 기반으로 연관 테이블의 데이터를 버튼으로 표시하는 컴포넌트
## 개요
- **ID**: `related-data-buttons`
- **카테고리**: data
- **웹타입**: container
- **버전**: 1.0.0
## 사용 사례
### 품목별 라우팅 버전 관리
```
┌─────────────────────────────────────────────────────┐
│ 알루미늄 프레임 [+ 라우팅 버전 추가] │
│ ITEM001 │
│ ┌──────────────┐ ┌─────────┐ │
│ │ 기본 라우팅 ★ │ │ 개선버전 │ │
│ └──────────────┘ └─────────┘ │
└─────────────────────────────────────────────────────┘
```
## 데이터 흐름
```
1. 좌측 패널: item_info 선택
↓ SplitPanelContext.selectedLeftData
2. RelatedDataButtons: item_code로 item_routing_version 조회
↓ 버튼 클릭 시 이벤트 발생
3. 하위 테이블: routing_version_id로 item_routing_detail 필터링
```
## 설정 옵션
### 소스 매핑 (sourceMapping)
| 속성 | 타입 | 설명 |
|------|------|------|
| sourceTable | string | 좌측 패널 테이블명 (예: item_info) |
| sourceColumn | string | 필터에 사용할 컬럼 (예: item_code) |
### 헤더 표시 (headerDisplay)
| 속성 | 타입 | 설명 |
|------|------|------|
| show | boolean | 헤더 표시 여부 |
| titleColumn | string | 제목으로 표시할 컬럼 (예: item_name) |
| subtitleColumn | string | 부제목으로 표시할 컬럼 (예: item_code) |
### 버튼 데이터 소스 (buttonDataSource)
| 속성 | 타입 | 설명 |
|------|------|------|
| tableName | string | 조회할 테이블명 (예: item_routing_version) |
| filterColumn | string | 필터링할 컬럼명 (예: item_code) |
| displayColumn | string | 버튼에 표시할 컬럼명 (예: version_name) |
| valueColumn | string | 선택 시 전달할 값 컬럼 (기본: id) |
| orderColumn | string | 정렬 컬럼 |
| orderDirection | "ASC" \| "DESC" | 정렬 방향 |
### 버튼 스타일 (buttonStyle)
| 속성 | 타입 | 설명 |
|------|------|------|
| variant | string | 기본 버튼 스타일 (default, outline, secondary, ghost) |
| activeVariant | string | 선택 시 버튼 스타일 |
| size | string | 버튼 크기 (sm, default, lg) |
| defaultIndicator.column | string | 기본 버전 판단 컬럼 |
| defaultIndicator.showStar | boolean | 별표 아이콘 표시 여부 |
### 추가 버튼 (addButton)
| 속성 | 타입 | 설명 |
|------|------|------|
| show | boolean | 추가 버튼 표시 여부 |
| label | string | 버튼 라벨 |
| position | "header" \| "inline" | 버튼 위치 |
| modalScreenId | number | 연결할 모달 화면 ID |
### 이벤트 설정 (events)
| 속성 | 타입 | 설명 |
|------|------|------|
| targetTable | string | 필터링할 하위 테이블명 |
| targetFilterColumn | string | 하위 테이블의 필터 컬럼명 |
## 이벤트
### related-button-select
버튼 선택 시 발생하는 커스텀 이벤트
```typescript
window.addEventListener("related-button-select", (e: CustomEvent) => {
const { targetTable, filterColumn, filterValue, selectedData } = e.detail;
// 하위 테이블 필터링 처리
});
```
## 사용 예시
### 품목별 라우팅 버전 화면
```typescript
const config: RelatedDataButtonsConfig = {
sourceMapping: {
sourceTable: "item_info",
sourceColumn: "item_code",
},
headerDisplay: {
show: true,
titleColumn: "item_name",
subtitleColumn: "item_code",
},
buttonDataSource: {
tableName: "item_routing_version",
filterColumn: "item_code",
displayColumn: "version_name",
valueColumn: "id",
},
buttonStyle: {
variant: "outline",
activeVariant: "default",
defaultIndicator: {
column: "is_default",
showStar: true,
},
},
events: {
targetTable: "item_routing_detail",
targetFilterColumn: "routing_version_id",
},
addButton: {
show: true,
label: "+ 라우팅 버전 추가",
position: "header",
},
autoSelectFirst: true,
};
```
## 분할 패널과 함께 사용
```
┌─────────────────┬──────────────────────────────────────────────┐
│ │ [RelatedDataButtons 컴포넌트] │
│ 품목 목록 │ 품목명 표시 + 버전 버튼들 │
│ (좌측 패널) ├──────────────────────────────────────────────┤
│ │ [DataTable 컴포넌트] │
│ item_info │ 공정 순서 테이블 (item_routing_detail) │
│ │ related-button-select 이벤트로 필터링 │
└─────────────────┴──────────────────────────────────────────────┘
```
## 개발자 정보
- **생성일**: 2024-12
- **경로**: `lib/registry/components/related-data-buttons/`

View File

@ -0,0 +1,412 @@
"use client";
import React, { useState, useEffect, useCallback, useRef } from "react";
import { Button } from "@/components/ui/button";
import { Plus, Star, Loader2, ExternalLink } from "lucide-react";
import { cn } from "@/lib/utils";
import { useSplitPanelContext } from "@/contexts/SplitPanelContext";
import { dataApi } from "@/lib/api/data";
import type { RelatedDataButtonsConfig, ButtonItem } from "./types";
// 전역 상태: 현재 선택된 버튼 데이터를 외부에서 접근 가능하게
declare global {
interface Window {
__relatedButtonsSelectedData?: {
selectedItem: ButtonItem | null;
masterData: Record<string, any> | null;
config: RelatedDataButtonsConfig | null;
};
}
}
interface RelatedDataButtonsComponentProps {
config: RelatedDataButtonsConfig;
className?: string;
style?: React.CSSProperties;
}
export const RelatedDataButtonsComponent: React.FC<RelatedDataButtonsComponentProps> = ({
config,
className,
style,
}) => {
const [buttons, setButtons] = useState<ButtonItem[]>([]);
const [selectedId, setSelectedId] = useState<string | null>(null);
const [selectedItem, setSelectedItem] = useState<ButtonItem | null>(null);
const [loading, setLoading] = useState(false);
const [masterData, setMasterData] = useState<Record<string, any> | null>(null);
// SplitPanel Context 연결
const splitPanelContext = useSplitPanelContext();
// 선택된 데이터를 전역 상태에 저장 (외부 버튼에서 접근용)
useEffect(() => {
window.__relatedButtonsSelectedData = {
selectedItem,
masterData,
config,
};
console.log("🔄 [RelatedDataButtons] 전역 상태 업데이트:", {
selectedItem,
hasConfig: !!config,
modalLink: config?.modalLink,
});
}, [selectedItem, masterData, config]);
// 좌측 패널에서 선택된 데이터 감지
useEffect(() => {
if (!splitPanelContext?.selectedLeftData) {
setMasterData(null);
setButtons([]);
setSelectedId(null);
return;
}
setMasterData(splitPanelContext.selectedLeftData);
}, [splitPanelContext?.selectedLeftData]);
// 버튼 데이터 로드
const loadButtons = useCallback(async () => {
if (!masterData || !config.buttonDataSource?.tableName) {
return;
}
const filterValue = masterData[config.sourceMapping.sourceColumn];
if (!filterValue) {
setButtons([]);
return;
}
setLoading(true);
try {
const { tableName, filterColumn, displayColumn, valueColumn, orderColumn, orderDirection } = config.buttonDataSource;
const response = await dataApi.getTableData(tableName, {
filters: { [filterColumn]: filterValue },
sortBy: orderColumn || "created_date",
sortOrder: (orderDirection?.toLowerCase() || "asc") as "asc" | "desc",
size: 50,
});
if (response.data && response.data.length > 0) {
const defaultConfig = config.buttonStyle?.defaultIndicator;
const items: ButtonItem[] = response.data.map((row: Record<string, any>) => {
let isDefault = false;
if (defaultConfig?.column) {
const val = row[defaultConfig.column];
const checkValue = defaultConfig.value || "Y";
isDefault = val === checkValue || val === true || val === "true";
}
return {
id: row.id || row[valueColumn || "id"],
displayText: row[displayColumn] || row.id,
value: row[valueColumn || "id"],
isDefault,
rawData: row,
};
});
setButtons(items);
// 자동 선택: 기본 항목 또는 첫 번째 항목
if (config.autoSelectFirst && items.length > 0) {
const defaultItem = items.find(item => item.isDefault);
const targetItem = defaultItem || items[0];
setSelectedId(targetItem.id);
setSelectedItem(targetItem);
emitSelection(targetItem);
}
}
} catch (error) {
console.error("RelatedDataButtons 데이터 로드 실패:", error);
setButtons([]);
} finally {
setLoading(false);
}
}, [masterData, config.buttonDataSource, config.sourceMapping, config.buttonStyle, config.autoSelectFirst]);
// masterData 변경 시 버튼 로드
useEffect(() => {
if (masterData) {
setSelectedId(null); // 마스터 변경 시 선택 초기화
setSelectedItem(null);
loadButtons();
}
}, [masterData, loadButtons]);
// 선택 이벤트 발생
const emitSelection = useCallback((item: ButtonItem) => {
if (!config.events?.targetTable || !config.events?.targetFilterColumn) {
return;
}
// 커스텀 이벤트 발생 (하위 테이블 필터링용)
window.dispatchEvent(new CustomEvent("related-button-select", {
detail: {
targetTable: config.events.targetTable,
filterColumn: config.events.targetFilterColumn,
filterValue: item.value,
selectedData: item.rawData,
},
}));
console.log("📌 RelatedDataButtons 선택 이벤트:", {
targetTable: config.events.targetTable,
filterColumn: config.events.targetFilterColumn,
filterValue: item.value,
});
}, [config.events]);
// 버튼 클릭 핸들러
const handleButtonClick = useCallback((item: ButtonItem) => {
setSelectedId(item.id);
setSelectedItem(item);
emitSelection(item);
}, [emitSelection]);
// 모달 열기 (선택된 버튼 데이터 전달)
const openModalWithSelectedData = useCallback((targetScreenId: number) => {
if (!selectedItem) {
console.warn("선택된 버튼이 없습니다.");
return;
}
// 데이터 매핑 적용
const initialData: Record<string, any> = {};
if (config.modalLink?.dataMapping) {
config.modalLink.dataMapping.forEach(mapping => {
if (mapping.sourceField === "value") {
initialData[mapping.targetField] = selectedItem.value;
} else if (mapping.sourceField === "id") {
initialData[mapping.targetField] = selectedItem.id;
} else if (selectedItem.rawData[mapping.sourceField] !== undefined) {
initialData[mapping.targetField] = selectedItem.rawData[mapping.sourceField];
}
});
} else {
// 기본 매핑: id를 routing_version_id로 전달
initialData["routing_version_id"] = selectedItem.value || selectedItem.id;
}
console.log("📤 RelatedDataButtons 모달 열기:", {
targetScreenId,
selectedItem,
initialData,
});
window.dispatchEvent(new CustomEvent("open-screen-modal", {
detail: {
screenId: targetScreenId,
initialData,
onSuccess: () => {
loadButtons(); // 모달 성공 후 새로고침
},
},
}));
}, [selectedItem, config.modalLink, loadButtons]);
// 외부 버튼에서 모달 열기 요청 수신
useEffect(() => {
const handleExternalModalOpen = (event: CustomEvent) => {
const { targetScreenId, componentId } = event.detail || {};
// componentId가 지정되어 있고 현재 컴포넌트가 아니면 무시
if (componentId && componentId !== config.sourceMapping?.sourceTable) {
return;
}
if (targetScreenId && selectedItem) {
openModalWithSelectedData(targetScreenId);
}
};
window.addEventListener("related-buttons-open-modal" as any, handleExternalModalOpen);
return () => {
window.removeEventListener("related-buttons-open-modal" as any, handleExternalModalOpen);
};
}, [selectedItem, config.sourceMapping, openModalWithSelectedData]);
// 내부 모달 링크 버튼 클릭
const handleModalLinkClick = useCallback(() => {
if (!config.modalLink?.targetScreenId) {
console.warn("모달 링크 설정이 없습니다.");
return;
}
openModalWithSelectedData(config.modalLink.targetScreenId);
}, [config.modalLink, openModalWithSelectedData]);
// 추가 버튼 클릭
const handleAddClick = useCallback(() => {
if (!config.addButton?.modalScreenId) return;
const filterValue = masterData?.[config.sourceMapping.sourceColumn];
window.dispatchEvent(new CustomEvent("open-screen-modal", {
detail: {
screenId: config.addButton.modalScreenId,
initialData: {
[config.buttonDataSource.filterColumn]: filterValue,
},
onSuccess: () => {
loadButtons(); // 모달 성공 후 새로고침
},
},
}));
}, [config.addButton, config.buttonDataSource.filterColumn, config.sourceMapping.sourceColumn, masterData, loadButtons]);
// 버튼 variant 계산
const getButtonVariant = useCallback((item: ButtonItem): "default" | "outline" | "secondary" | "ghost" => {
if (selectedId === item.id) {
return config.buttonStyle?.activeVariant || "default";
}
return config.buttonStyle?.variant || "outline";
}, [selectedId, config.buttonStyle]);
// 마스터 데이터 없음
if (!masterData) {
return (
<div className={cn("rounded-lg border bg-card p-4", className)} style={style}>
<p className="text-sm text-muted-foreground text-center">
</p>
</div>
);
}
const headerConfig = config.headerDisplay;
const addButtonConfig = config.addButton;
const modalLinkConfig = config.modalLink;
return (
<div className={cn("rounded-lg border bg-card", className)} style={style}>
{/* 헤더 영역 */}
{headerConfig?.show !== false && (
<div className="flex items-start justify-between p-4 pb-3">
<div>
{/* 제목 (품목명 등) */}
{headerConfig?.titleColumn && masterData[headerConfig.titleColumn] && (
<h3 className="text-lg font-semibold">
{masterData[headerConfig.titleColumn]}
</h3>
)}
{/* 부제목 (품목코드 등) */}
{headerConfig?.subtitleColumn && masterData[headerConfig.subtitleColumn] && (
<p className="text-sm text-muted-foreground">
{masterData[headerConfig.subtitleColumn]}
</p>
)}
</div>
<div className="flex items-center gap-2">
{/* 모달 링크 버튼 (헤더 위치) */}
{modalLinkConfig?.enabled && modalLinkConfig?.triggerType === "button" && modalLinkConfig?.buttonPosition === "header" && (
<Button
variant="outline"
size="sm"
onClick={handleModalLinkClick}
disabled={!selectedItem}
title={!selectedItem ? "버튼을 먼저 선택하세요" : ""}
>
<ExternalLink className="mr-1 h-4 w-4" />
{modalLinkConfig.buttonLabel || "상세 추가"}
</Button>
)}
{/* 헤더 위치 추가 버튼 */}
{addButtonConfig?.show && addButtonConfig?.position === "header" && (
<Button
variant="default"
size="sm"
onClick={handleAddClick}
className="bg-blue-600 hover:bg-blue-700"
>
<Plus className="mr-1 h-4 w-4" />
{addButtonConfig.label || "버전 추가"}
</Button>
)}
</div>
</div>
)}
{/* 버튼 영역 */}
<div className="px-4 pb-4">
{loading ? (
<div className="flex items-center justify-center py-4">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
) : buttons.length === 0 ? (
<div className="flex items-center gap-2">
<p className="text-sm text-muted-foreground">
{config.emptyMessage || "데이터가 없습니다"}
</p>
{/* 인라인 추가 버튼 (데이터 없을 때) */}
{addButtonConfig?.show && addButtonConfig?.position !== "header" && (
<Button
variant="outline"
size="sm"
onClick={handleAddClick}
className="border-dashed"
>
<Plus className="mr-1 h-4 w-4" />
{addButtonConfig.label || "추가"}
</Button>
)}
</div>
) : (
<div className="flex flex-wrap items-center gap-2">
{buttons.map((item) => (
<Button
key={item.id}
variant={getButtonVariant(item)}
size={config.buttonStyle?.size || "default"}
onClick={() => handleButtonClick(item)}
className={cn(
"relative",
selectedId === item.id && "ring-2 ring-primary ring-offset-1"
)}
>
{/* 기본 버전 별표 */}
{item.isDefault && config.buttonStyle?.defaultIndicator?.showStar && (
<Star className="mr-1.5 h-3.5 w-3.5 fill-yellow-400 text-yellow-400" />
)}
{item.displayText}
</Button>
))}
{/* 모달 링크 버튼 (인라인 위치) */}
{modalLinkConfig?.enabled && modalLinkConfig?.triggerType === "button" && modalLinkConfig?.buttonPosition !== "header" && (
<Button
variant="outline"
size={config.buttonStyle?.size || "default"}
onClick={handleModalLinkClick}
disabled={!selectedItem}
title={!selectedItem ? "버튼을 먼저 선택하세요" : ""}
>
<ExternalLink className="mr-1 h-4 w-4" />
{modalLinkConfig.buttonLabel || "상세 추가"}
</Button>
)}
{/* 인라인 추가 버튼 */}
{addButtonConfig?.show && addButtonConfig?.position !== "header" && (
<Button
variant="outline"
size={config.buttonStyle?.size || "default"}
onClick={handleAddClick}
className="border-dashed"
>
<Plus className="mr-1 h-4 w-4" />
{addButtonConfig.label || "추가"}
</Button>
)}
</div>
)}
</div>
</div>
);
};
export default RelatedDataButtonsComponent;

View File

@ -0,0 +1,874 @@
"use client";
import React, { useState, useEffect, useCallback, useMemo } from "react";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Button } from "@/components/ui/button";
import { Check, ChevronsUpDown } from "lucide-react";
import { cn } from "@/lib/utils";
import { tableManagementApi, getTableColumns } from "@/lib/api/tableManagement";
import { screenApi } from "@/lib/api/screen";
import type { RelatedDataButtonsConfig } from "./types";
// 화면 정보 타입
interface ScreenInfo {
screenId: number;
screenName: string;
tableName?: string;
}
// 화면 선택 컴포넌트
interface ScreenSelectorProps {
value?: number;
onChange: (screenId: number | undefined, tableName?: string) => void;
placeholder?: string;
}
const ScreenSelector: React.FC<ScreenSelectorProps> = ({ value, onChange, placeholder = "화면 선택" }) => {
const [open, setOpen] = useState(false);
const [screens, setScreens] = useState<ScreenInfo[]>([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
const loadScreens = async () => {
setLoading(true);
try {
const response = await screenApi.getScreens({ size: 500 });
if (response.data) {
setScreens(response.data.map((s: any) => ({
screenId: s.screenId,
screenName: s.screenName || s.name || `화면 ${s.screenId}`,
tableName: s.tableName || s.table_name,
})));
}
} catch (error) {
console.error("화면 목록 로드 실패:", error);
} finally {
setLoading(false);
}
};
loadScreens();
}, []);
const selectedScreen = screens.find(s => s.screenId === value);
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button variant="outline" role="combobox" className="w-full justify-between text-xs h-9">
{loading ? "로딩중..." : selectedScreen ? `${selectedScreen.screenName} (${selectedScreen.screenId})` : placeholder}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-full p-0" align="start">
<Command>
<CommandInput placeholder="화면 검색..." className="text-xs" />
<CommandList>
<CommandEmpty className="text-xs py-2 text-center"> .</CommandEmpty>
<CommandGroup className="max-h-[200px] overflow-auto">
{screens.map((screen) => (
<CommandItem
key={screen.screenId}
value={`${screen.screenName} ${screen.screenId}`}
onSelect={() => {
onChange(screen.screenId, screen.tableName);
setOpen(false);
}}
className="text-xs"
>
<Check className={cn("mr-2 h-4 w-4", value === screen.screenId ? "opacity-100" : "opacity-0")} />
<span className="truncate">{screen.screenName}</span>
<span className="ml-auto text-muted-foreground">({screen.screenId})</span>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
};
interface TableInfo {
tableName: string;
displayName?: string;
}
interface ColumnInfo {
columnName: string;
columnLabel?: string;
}
interface RelatedDataButtonsConfigPanelProps {
config: RelatedDataButtonsConfig;
onChange: (config: RelatedDataButtonsConfig) => void;
tables?: TableInfo[];
}
export const RelatedDataButtonsConfigPanel: React.FC<RelatedDataButtonsConfigPanelProps> = ({
config,
onChange,
tables: propTables = [],
}) => {
const [allTables, setAllTables] = useState<TableInfo[]>([]);
const [sourceTableColumns, setSourceTableColumns] = useState<ColumnInfo[]>([]);
const [buttonTableColumns, setButtonTableColumns] = useState<ColumnInfo[]>([]);
const [targetModalTableColumns, setTargetModalTableColumns] = useState<ColumnInfo[]>([]); // 대상 모달 테이블 컬럼
const [targetModalTableName, setTargetModalTableName] = useState<string>(""); // 대상 모달 테이블명
const [eventTargetTableColumns, setEventTargetTableColumns] = useState<ColumnInfo[]>([]); // 하위 테이블 연동 대상 테이블 컬럼
// Popover 상태
const [sourceTableOpen, setSourceTableOpen] = useState(false);
const [buttonTableOpen, setButtonTableOpen] = useState(false);
// 전체 테이블 로드
useEffect(() => {
const loadTables = async () => {
try {
const response = await tableManagementApi.getTableList();
if (response.success && response.data) {
setAllTables(response.data.map((t: any) => ({
tableName: t.tableName || t.table_name,
displayName: t.tableLabel || t.table_label || t.displayName,
})));
}
} catch (error) {
console.error("테이블 목록 로드 실패:", error);
}
};
loadTables();
}, []);
// 소스 테이블 컬럼 로드
useEffect(() => {
const loadColumns = async () => {
if (!config.sourceMapping?.sourceTable) {
setSourceTableColumns([]);
return;
}
try {
const response = await getTableColumns(config.sourceMapping.sourceTable);
if (response.success && response.data?.columns) {
setSourceTableColumns(response.data.columns.map((c: any) => ({
columnName: c.columnName || c.column_name,
columnLabel: c.columnLabel || c.column_label || c.displayName,
})));
}
} catch (error) {
console.error("소스 테이블 컬럼 로드 실패:", error);
}
};
loadColumns();
}, [config.sourceMapping?.sourceTable]);
// 버튼 테이블 컬럼 로드
useEffect(() => {
const loadColumns = async () => {
if (!config.buttonDataSource?.tableName) {
setButtonTableColumns([]);
return;
}
try {
const response = await getTableColumns(config.buttonDataSource.tableName);
if (response.success && response.data?.columns) {
setButtonTableColumns(response.data.columns.map((c: any) => ({
columnName: c.columnName || c.column_name,
columnLabel: c.columnLabel || c.column_label || c.displayName,
})));
}
} catch (error) {
console.error("버튼 테이블 컬럼 로드 실패:", error);
}
};
loadColumns();
}, [config.buttonDataSource?.tableName]);
// 대상 모달 화면의 테이블명 로드 (초기 로드 및 screenId 변경 시)
useEffect(() => {
const loadTargetScreenTable = async () => {
if (!config.modalLink?.targetScreenId) {
setTargetModalTableName("");
return;
}
try {
const screenInfo = await screenApi.getScreen(config.modalLink.targetScreenId);
if (screenInfo?.tableName) {
setTargetModalTableName(screenInfo.tableName);
}
} catch (error) {
console.error("대상 모달 화면 정보 로드 실패:", error);
}
};
loadTargetScreenTable();
}, [config.modalLink?.targetScreenId]);
// 대상 모달 테이블 컬럼 로드
useEffect(() => {
const loadColumns = async () => {
if (!targetModalTableName) {
setTargetModalTableColumns([]);
return;
}
try {
const response = await getTableColumns(targetModalTableName);
if (response.success && response.data?.columns) {
setTargetModalTableColumns(response.data.columns.map((c: any) => ({
columnName: c.columnName || c.column_name,
columnLabel: c.columnLabel || c.column_label || c.displayName,
})));
}
} catch (error) {
console.error("대상 모달 테이블 컬럼 로드 실패:", error);
}
};
loadColumns();
}, [targetModalTableName]);
// 하위 테이블 연동 대상 테이블 컬럼 로드
useEffect(() => {
const loadColumns = async () => {
if (!config.events?.targetTable) {
setEventTargetTableColumns([]);
return;
}
try {
const response = await getTableColumns(config.events.targetTable);
if (response.success && response.data?.columns) {
setEventTargetTableColumns(response.data.columns.map((c: any) => ({
columnName: c.columnName || c.column_name,
columnLabel: c.columnLabel || c.column_label || c.displayName,
})));
}
} catch (error) {
console.error("하위 테이블 연동 대상 테이블 컬럼 로드 실패:", error);
}
};
loadColumns();
}, [config.events?.targetTable]);
// 설정 업데이트 헬퍼
const updateConfig = useCallback((updates: Partial<RelatedDataButtonsConfig>) => {
onChange({ ...config, ...updates });
}, [config, onChange]);
const updateSourceMapping = useCallback((updates: Partial<RelatedDataButtonsConfig["sourceMapping"]>) => {
onChange({
...config,
sourceMapping: { ...config.sourceMapping, ...updates },
});
}, [config, onChange]);
const updateHeaderDisplay = useCallback((updates: Partial<NonNullable<RelatedDataButtonsConfig["headerDisplay"]>>) => {
onChange({
...config,
headerDisplay: { ...config.headerDisplay, ...updates } as any,
});
}, [config, onChange]);
const updateButtonDataSource = useCallback((updates: Partial<RelatedDataButtonsConfig["buttonDataSource"]>) => {
onChange({
...config,
buttonDataSource: { ...config.buttonDataSource, ...updates },
});
}, [config, onChange]);
const updateButtonStyle = useCallback((updates: Partial<NonNullable<RelatedDataButtonsConfig["buttonStyle"]>>) => {
onChange({
...config,
buttonStyle: { ...config.buttonStyle, ...updates },
});
}, [config, onChange]);
const updateAddButton = useCallback((updates: Partial<NonNullable<RelatedDataButtonsConfig["addButton"]>>) => {
onChange({
...config,
addButton: { ...config.addButton, ...updates },
});
}, [config, onChange]);
const updateEvents = useCallback((updates: Partial<NonNullable<RelatedDataButtonsConfig["events"]>>) => {
onChange({
...config,
events: { ...config.events, ...updates },
});
}, [config, onChange]);
const updateModalLink = useCallback((updates: Partial<NonNullable<RelatedDataButtonsConfig["modalLink"]>>) => {
onChange({
...config,
modalLink: { ...config.modalLink, ...updates },
});
}, [config, onChange]);
const tables = allTables.length > 0 ? allTables : propTables;
return (
<div className="space-y-6">
{/* 소스 매핑 (좌측 패널 연결) */}
<div className="space-y-3">
<Label className="text-sm font-semibold"> ( )</Label>
<div className="space-y-2">
<Label className="text-xs"></Label>
<Popover open={sourceTableOpen} onOpenChange={setSourceTableOpen}>
<PopoverTrigger asChild>
<Button variant="outline" role="combobox" className="w-full justify-between">
{config.sourceMapping?.sourceTable || "테이블 선택"}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-full p-0">
<Command>
<CommandInput placeholder="테이블 검색..." />
<CommandEmpty> .</CommandEmpty>
<CommandGroup className="max-h-[200px] overflow-auto">
{tables.map((table) => (
<CommandItem
key={table.tableName}
value={`${table.displayName || ""} ${table.tableName}`}
onSelect={() => {
updateSourceMapping({ sourceTable: table.tableName });
setSourceTableOpen(false);
}}
>
<Check className={cn("mr-2 h-4 w-4", config.sourceMapping?.sourceTable === table.tableName ? "opacity-100" : "opacity-0")} />
{table.displayName || table.tableName}
{table.displayName && <span className="ml-2 text-xs text-gray-500">({table.tableName})</span>}
</CommandItem>
))}
</CommandGroup>
</Command>
</PopoverContent>
</Popover>
</div>
<div className="space-y-2">
<Label className="text-xs"> ( )</Label>
<Select
value={config.sourceMapping?.sourceColumn || ""}
onValueChange={(value) => updateSourceMapping({ sourceColumn: value })}
>
<SelectTrigger>
<SelectValue placeholder="컬럼 선택" />
</SelectTrigger>
<SelectContent>
{sourceTableColumns.map((col) => (
<SelectItem key={col.columnName} value={col.columnName}>
{col.columnLabel || col.columnName}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
{/* 헤더 표시 설정 */}
<div className="space-y-3">
<div className="flex items-center justify-between">
<Label className="text-sm font-semibold"> </Label>
<Switch
checked={config.headerDisplay?.show !== false}
onCheckedChange={(checked) => updateHeaderDisplay({ show: checked })}
/>
</div>
{config.headerDisplay?.show !== false && (
<div className="space-y-2 pl-2 border-l-2 border-gray-200">
<div className="space-y-1">
<Label className="text-xs"> </Label>
<Select
value={config.headerDisplay?.titleColumn || ""}
onValueChange={(value) => updateHeaderDisplay({ titleColumn: value })}
>
<SelectTrigger>
<SelectValue placeholder="제목 컬럼 선택" />
</SelectTrigger>
<SelectContent>
{sourceTableColumns.map((col) => (
<SelectItem key={col.columnName} value={col.columnName}>
{col.columnLabel || col.columnName}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-1">
<Label className="text-xs"> ()</Label>
<Select
value={config.headerDisplay?.subtitleColumn || "__none__"}
onValueChange={(value) => updateHeaderDisplay({ subtitleColumn: value === "__none__" ? "" : value })}
>
<SelectTrigger>
<SelectValue placeholder="부제목 컬럼 선택" />
</SelectTrigger>
<SelectContent>
<SelectItem value="__none__"></SelectItem>
{sourceTableColumns.map((col) => (
<SelectItem key={col.columnName} value={col.columnName}>
{col.columnLabel || col.columnName}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
)}
</div>
{/* 버튼 데이터 소스 */}
<div className="space-y-3">
<Label className="text-sm font-semibold"> </Label>
<div className="space-y-2">
<Label className="text-xs"></Label>
<Popover open={buttonTableOpen} onOpenChange={setButtonTableOpen}>
<PopoverTrigger asChild>
<Button variant="outline" role="combobox" className="w-full justify-between">
{config.buttonDataSource?.tableName || "테이블 선택"}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-full p-0">
<Command>
<CommandInput placeholder="테이블 검색..." />
<CommandEmpty> .</CommandEmpty>
<CommandGroup className="max-h-[200px] overflow-auto">
{tables.map((table) => (
<CommandItem
key={table.tableName}
value={`${table.displayName || ""} ${table.tableName}`}
onSelect={() => {
updateButtonDataSource({ tableName: table.tableName });
setButtonTableOpen(false);
}}
>
<Check className={cn("mr-2 h-4 w-4", config.buttonDataSource?.tableName === table.tableName ? "opacity-100" : "opacity-0")} />
{table.displayName || table.tableName}
{table.displayName && <span className="ml-2 text-xs text-gray-500">({table.tableName})</span>}
</CommandItem>
))}
</CommandGroup>
</Command>
</PopoverContent>
</Popover>
</div>
<div className="grid grid-cols-2 gap-2">
<div className="space-y-1">
<Label className="text-xs"> </Label>
<Select
value={config.buttonDataSource?.filterColumn || ""}
onValueChange={(value) => updateButtonDataSource({ filterColumn: value })}
>
<SelectTrigger>
<SelectValue placeholder="선택" />
</SelectTrigger>
<SelectContent>
{buttonTableColumns.map((col) => (
<SelectItem key={col.columnName} value={col.columnName}>
{col.columnLabel || col.columnName}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-1">
<Label className="text-xs"> </Label>
<Select
value={config.buttonDataSource?.displayColumn || ""}
onValueChange={(value) => updateButtonDataSource({ displayColumn: value })}
>
<SelectTrigger>
<SelectValue placeholder="선택" />
</SelectTrigger>
<SelectContent>
{buttonTableColumns.map((col) => (
<SelectItem key={col.columnName} value={col.columnName}>
{col.columnLabel || col.columnName}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</div>
{/* 버튼 스타일 */}
<div className="space-y-3">
<Label className="text-sm font-semibold"> </Label>
<div className="grid grid-cols-2 gap-2">
<div className="space-y-1">
<Label className="text-xs"> </Label>
<Select
value={config.buttonStyle?.variant || "outline"}
onValueChange={(value: any) => updateButtonStyle({ variant: value })}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="default">Default</SelectItem>
<SelectItem value="outline">Outline</SelectItem>
<SelectItem value="secondary">Secondary</SelectItem>
<SelectItem value="ghost">Ghost</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1">
<Label className="text-xs"> </Label>
<Select
value={config.buttonStyle?.activeVariant || "default"}
onValueChange={(value: any) => updateButtonStyle({ activeVariant: value })}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="default">Default</SelectItem>
<SelectItem value="outline">Outline</SelectItem>
<SelectItem value="secondary">Secondary</SelectItem>
</SelectContent>
</Select>
</div>
</div>
{/* 기본 표시 설정 */}
<div className="space-y-2">
<Label className="text-xs"> </Label>
<Select
value={config.buttonStyle?.defaultIndicator?.column || "__none__"}
onValueChange={(value) => updateButtonStyle({
defaultIndicator: {
...config.buttonStyle?.defaultIndicator,
column: value === "__none__" ? "" : value,
showStar: config.buttonStyle?.defaultIndicator?.showStar ?? true,
},
})}
>
<SelectTrigger>
<SelectValue placeholder="없음" />
</SelectTrigger>
<SelectContent>
<SelectItem value="__none__"></SelectItem>
{buttonTableColumns.map((col) => (
<SelectItem key={col.columnName} value={col.columnName}>
{col.columnLabel || col.columnName}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{config.buttonStyle?.defaultIndicator?.column && (
<div className="flex items-center gap-4">
<div className="flex items-center gap-2">
<Switch
checked={config.buttonStyle?.defaultIndicator?.showStar ?? true}
onCheckedChange={(checked) => updateButtonStyle({
defaultIndicator: {
...config.buttonStyle?.defaultIndicator,
column: config.buttonStyle?.defaultIndicator?.column || "",
showStar: checked,
},
})}
/>
<Label className="text-xs"> </Label>
</div>
</div>
)}
</div>
{/* 이벤트 설정 (하위 테이블 연동) */}
<div className="space-y-3">
<Label className="text-sm font-semibold"> </Label>
<div className="space-y-2">
<Label className="text-xs"> </Label>
<Popover>
<PopoverTrigger asChild>
<Button variant="outline" role="combobox" className="w-full justify-between">
{config.events?.targetTable || "테이블 선택"}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-full p-0">
<Command>
<CommandInput placeholder="테이블 검색..." />
<CommandEmpty> .</CommandEmpty>
<CommandGroup className="max-h-[200px] overflow-auto">
{tables.map((table) => (
<CommandItem
key={table.tableName}
value={`${table.displayName || ""} ${table.tableName}`}
onSelect={() => {
updateEvents({ targetTable: table.tableName });
}}
>
<Check className={cn("mr-2 h-4 w-4", config.events?.targetTable === table.tableName ? "opacity-100" : "opacity-0")} />
{table.displayName || table.tableName}
</CommandItem>
))}
</CommandGroup>
</Command>
</PopoverContent>
</Popover>
</div>
<div className="space-y-2">
<Label className="text-xs"> ( )</Label>
<Select
value={config.events?.targetFilterColumn || ""}
onValueChange={(value) => updateEvents({ targetFilterColumn: value })}
>
<SelectTrigger>
<SelectValue placeholder="컬럼 선택" />
</SelectTrigger>
<SelectContent>
{eventTargetTableColumns.map((col) => (
<SelectItem key={col.columnName} value={col.columnName}>
{col.columnLabel || col.columnName}
</SelectItem>
))}
</SelectContent>
</Select>
{eventTargetTableColumns.length === 0 && config.events?.targetTable && (
<p className="text-xs text-muted-foreground"> ...</p>
)}
{!config.events?.targetTable && (
<p className="text-xs text-muted-foreground"> </p>
)}
</div>
</div>
{/* 추가 버튼 설정 */}
<div className="space-y-3">
<div className="flex items-center justify-between">
<Label className="text-sm font-semibold"> </Label>
<Switch
checked={config.addButton?.show ?? false}
onCheckedChange={(checked) => updateAddButton({ show: checked })}
/>
</div>
{config.addButton?.show && (
<div className="space-y-2 pl-2 border-l-2 border-gray-200">
<div className="space-y-1">
<Label className="text-xs"> </Label>
<Input
value={config.addButton?.label || ""}
onChange={(e) => updateAddButton({ label: e.target.value })}
placeholder="+ 버전 추가"
/>
</div>
<div className="space-y-1">
<Label className="text-xs"></Label>
<Select
value={config.addButton?.position || "header"}
onValueChange={(value: any) => updateAddButton({ position: value })}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="header"> </SelectItem>
<SelectItem value="inline"> </SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1">
<Label className="text-xs"> </Label>
<ScreenSelector
value={config.addButton?.modalScreenId}
onChange={(screenId) => updateAddButton({ modalScreenId: screenId })}
placeholder="화면 선택"
/>
</div>
</div>
)}
</div>
{/* 모달 연동 설정 (선택된 버튼 데이터를 모달로 전달) */}
<div className="space-y-3">
<div className="flex items-center justify-between">
<Label className="text-sm font-semibold"> ( )</Label>
<Switch
checked={config.modalLink?.enabled ?? false}
onCheckedChange={(checked) => updateModalLink({ enabled: checked })}
/>
</div>
{config.modalLink?.enabled && (
<div className="space-y-2 pl-2 border-l-2 border-gray-200">
<div className="space-y-1">
<Label className="text-xs"> </Label>
<Select
value={config.modalLink?.triggerType || "external"}
onValueChange={(value: any) => updateModalLink({ triggerType: value })}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="external"> ( )</SelectItem>
<SelectItem value="button"> ( )</SelectItem>
</SelectContent>
</Select>
</div>
{config.modalLink?.triggerType === "button" && (
<>
<div className="space-y-1">
<Label className="text-xs"> </Label>
<Input
value={config.modalLink?.buttonLabel || ""}
onChange={(e) => updateModalLink({ buttonLabel: e.target.value })}
placeholder="공정 추가"
/>
</div>
<div className="space-y-1">
<Label className="text-xs"> </Label>
<Select
value={config.modalLink?.buttonPosition || "header"}
onValueChange={(value: any) => updateModalLink({ buttonPosition: value })}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="header"> </SelectItem>
<SelectItem value="inline"> </SelectItem>
</SelectContent>
</Select>
</div>
</>
)}
<div className="space-y-1">
<Label className="text-xs"> </Label>
<ScreenSelector
value={config.modalLink?.targetScreenId}
onChange={(screenId, tableName) => {
updateModalLink({ targetScreenId: screenId });
if (tableName) {
setTargetModalTableName(tableName);
}
}}
placeholder="화면 선택"
/>
{targetModalTableName && (
<p className="text-xs text-muted-foreground mt-1">
: {targetModalTableName}
</p>
)}
</div>
<div className="space-y-2 pt-2 border-t">
<Label className="text-xs font-medium"> </Label>
<p className="text-xs text-muted-foreground">
.
</p>
<div className="grid grid-cols-2 gap-2">
<div className="space-y-1">
<Label className="text-xs"> </Label>
<Select
value={config.modalLink?.dataMapping?.[0]?.sourceField === "id" ? "__id__" :
config.modalLink?.dataMapping?.[0]?.sourceField === "value" ? "__value__" :
config.modalLink?.dataMapping?.[0]?.sourceField || "__id__"}
onValueChange={(value) => updateModalLink({
dataMapping: [{
sourceField: value === "__id__" ? "id" : value === "__value__" ? "value" : value,
targetField: config.modalLink?.dataMapping?.[0]?.targetField || ""
}]
})}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="__id__">ID ( )</SelectItem>
<SelectItem value="__value__"> (valueColumn)</SelectItem>
{buttonTableColumns
.filter(col => col.columnName !== "id") // id 중복 제거
.map((col) => (
<SelectItem key={col.columnName} value={col.columnName}>
{col.columnLabel || col.columnName}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-1">
<Label className="text-xs"> </Label>
<Select
value={config.modalLink?.dataMapping?.[0]?.targetField || "__none__"}
onValueChange={(value) => updateModalLink({
dataMapping: [{
sourceField: config.modalLink?.dataMapping?.[0]?.sourceField || "id",
targetField: value === "__none__" ? "" : value
}]
})}
>
<SelectTrigger>
<SelectValue placeholder="컬럼 선택" />
</SelectTrigger>
<SelectContent>
<SelectItem value="__none__"> </SelectItem>
{targetModalTableColumns.map((col) => (
<SelectItem key={col.columnName} value={col.columnName}>
{col.columnLabel || col.columnName}
</SelectItem>
))}
</SelectContent>
</Select>
{targetModalTableColumns.length === 0 && targetModalTableName && (
<p className="text-xs text-muted-foreground"> ...</p>
)}
{!targetModalTableName && (
<p className="text-xs text-muted-foreground"> </p>
)}
</div>
</div>
</div>
</div>
)}
</div>
{/* 기타 설정 */}
<div className="space-y-3">
<Label className="text-sm font-semibold"> </Label>
<div className="flex items-center gap-2">
<Switch
checked={config.autoSelectFirst ?? true}
onCheckedChange={(checked) => updateConfig({ autoSelectFirst: checked })}
/>
<Label className="text-xs"> </Label>
</div>
<div className="space-y-1">
<Label className="text-xs"> </Label>
<Input
value={config.emptyMessage || ""}
onChange={(e) => updateConfig({ emptyMessage: e.target.value })}
placeholder="데이터가 없습니다"
/>
</div>
</div>
</div>
);
};
export default RelatedDataButtonsConfigPanel;

View File

@ -0,0 +1,29 @@
"use client";
import React from "react";
import { AutoRegisteringComponentRenderer } from "../../AutoRegisteringComponentRenderer";
import { RelatedDataButtonsDefinition } from "./index";
import { RelatedDataButtonsComponent } from "./RelatedDataButtonsComponent";
/**
* RelatedDataButtons
*
*/
export class RelatedDataButtonsRenderer extends AutoRegisteringComponentRenderer {
static componentDefinition = RelatedDataButtonsDefinition;
render(): React.ReactElement {
const { component } = this.props;
return (
<RelatedDataButtonsComponent
config={component?.config || RelatedDataButtonsDefinition.defaultConfig}
className={component?.className}
style={component?.style}
/>
);
}
}
// 자동 등록 실행
RelatedDataButtonsRenderer.registerSelf();

View File

@ -0,0 +1,53 @@
import type { ComponentConfig } from "@/lib/registry/types";
export const relatedDataButtonsConfig: ComponentConfig = {
id: "related-data-buttons",
name: "연관 데이터 버튼",
description: "좌측 패널에서 선택한 데이터를 기반으로 연관 테이블의 데이터를 버튼으로 표시합니다. 예: 품목 선택 → 라우팅 버전 버튼들",
category: "data",
webType: "container",
version: "1.0.0",
icon: "LayoutList",
defaultConfig: {
sourceMapping: {
sourceTable: "",
sourceColumn: "",
},
headerDisplay: {
show: true,
titleColumn: "",
subtitleColumn: "",
},
buttonDataSource: {
tableName: "",
filterColumn: "",
displayColumn: "",
valueColumn: "id",
orderColumn: "created_date",
orderDirection: "ASC",
},
buttonStyle: {
variant: "outline",
activeVariant: "default",
size: "default",
defaultIndicator: {
column: "",
showStar: true,
},
},
addButton: {
show: false,
label: "+ 버전 추가",
position: "header",
},
events: {
targetTable: "",
targetFilterColumn: "",
},
autoSelectFirst: true,
emptyMessage: "데이터가 없습니다",
},
configPanelComponent: "RelatedDataButtonsConfigPanel",
rendererComponent: "RelatedDataButtonsRenderer",
};

View File

@ -0,0 +1,71 @@
"use client";
import React from "react";
import { createComponentDefinition } from "../../utils/createComponentDefinition";
import { ComponentCategory } from "@/types/component";
import { RelatedDataButtonsComponent } from "./RelatedDataButtonsComponent";
import { RelatedDataButtonsConfigPanel } from "./RelatedDataButtonsConfigPanel";
/**
* RelatedDataButtons
*
*/
export const RelatedDataButtonsDefinition = createComponentDefinition({
id: "related-data-buttons",
name: "연관 데이터 버튼",
nameEng: "Related Data Buttons",
description: "좌측 패널에서 선택한 데이터를 기반으로 연관 테이블의 데이터를 버튼으로 표시합니다. 예: 품목 선택 → 라우팅 버전 버튼들",
category: ComponentCategory.DATA,
webType: "container",
component: RelatedDataButtonsComponent,
defaultConfig: {
sourceMapping: {
sourceTable: "",
sourceColumn: "",
},
headerDisplay: {
show: true,
titleColumn: "",
subtitleColumn: "",
},
buttonDataSource: {
tableName: "",
filterColumn: "",
displayColumn: "",
valueColumn: "id",
orderColumn: "created_date",
orderDirection: "ASC",
},
buttonStyle: {
variant: "outline",
activeVariant: "default",
size: "default",
defaultIndicator: {
column: "",
showStar: true,
},
},
addButton: {
show: false,
label: "+ 버전 추가",
position: "header",
},
events: {
targetTable: "",
targetFilterColumn: "",
},
autoSelectFirst: true,
emptyMessage: "데이터가 없습니다",
},
defaultSize: { width: 400, height: 120 },
configPanel: RelatedDataButtonsConfigPanel,
icon: "LayoutList",
tags: ["버튼", "연관데이터", "마스터디테일", "라우팅"],
version: "1.0.0",
author: "개발팀",
});
// 타입 내보내기
export type { RelatedDataButtonsConfig, ButtonItem } from "./types";
export { RelatedDataButtonsComponent } from "./RelatedDataButtonsComponent";
export { RelatedDataButtonsConfigPanel } from "./RelatedDataButtonsConfigPanel";

View File

@ -0,0 +1,128 @@
/**
* RelatedDataButtons
*
* ,
*
*
* 예시: 품목 / +
*/
/**
* ( )
*/
export interface HeaderDisplayConfig {
show?: boolean; // 헤더 표시 여부
titleColumn: string; // 제목으로 표시할 컬럼 (예: item_name)
subtitleColumn?: string; // 부제목으로 표시할 컬럼 (예: item_code)
}
/**
*
*/
export interface ButtonDataSourceConfig {
tableName: string; // 조회할 테이블명 (예: item_routing_version)
filterColumn: string; // 필터링할 컬럼명 (예: item_code)
displayColumn: string; // 버튼에 표시할 컬럼명 (예: version_name)
valueColumn?: string; // 선택 시 전달할 값 컬럼 (기본: id)
orderColumn?: string; // 정렬 컬럼
orderDirection?: "ASC" | "DESC"; // 정렬 방향
}
/**
*
*/
export interface ButtonStyleConfig {
variant?: "default" | "outline" | "secondary" | "ghost";
activeVariant?: "default" | "outline" | "secondary";
size?: "sm" | "default" | "lg";
// 기본 버전 표시 설정
defaultIndicator?: {
column: string; // 기본 여부 판단 컬럼 (예: is_default)
value?: string; // 기본 값 (기본: "Y" 또는 true)
showStar?: boolean; // 별표 아이콘 표시
badgeText?: string; // 뱃지 텍스트 (예: "기본")
};
}
/**
*
*/
export interface AddButtonConfig {
show?: boolean;
label?: string; // 기본: "+ 버전 추가"
modalScreenId?: number;
position?: "header" | "inline"; // header: 헤더 우측, inline: 버튼들과 함께
}
/**
* ( )
*/
export interface EventConfig {
// 선택 시 하위 테이블 필터링
targetTable?: string; // 필터링할 테이블명 (예: item_routing_detail)
targetFilterColumn?: string; // 필터 컬럼명 (예: routing_version_id)
// 커스텀 이벤트
customEventName?: string;
}
/**
* ( )
*/
export interface ModalLinkConfig {
enabled?: boolean; // 모달 연동 활성화
targetScreenId?: number; // 열릴 모달 화면 ID
triggerType?: "button" | "external"; // button: 별도 버튼, external: 외부 버튼에서 호출
buttonLabel?: string; // 버튼 텍스트 (triggerType이 button일 때)
buttonPosition?: "header" | "inline"; // 버튼 위치
// 데이터 매핑: 선택된 버튼 데이터 → 모달 초기값
dataMapping?: {
sourceField: string; // 버튼 데이터의 필드명 (예: "id", "value")
targetField: string; // 모달에 전달할 필드명 (예: "routing_version_id")
}[];
}
/**
*
*/
export interface RelatedDataButtonsConfig {
// 소스 매핑 (좌측 패널 연결)
sourceMapping: {
sourceTable: string; // 좌측 패널 테이블명
sourceColumn: string; // 필터에 사용할 컬럼 (예: item_code)
};
// 헤더 표시 설정
headerDisplay?: HeaderDisplayConfig;
// 버튼 데이터 소스
buttonDataSource: ButtonDataSourceConfig;
// 버튼 스타일
buttonStyle?: ButtonStyleConfig;
// 추가 버튼
addButton?: AddButtonConfig;
// 이벤트 설정
events?: EventConfig;
// 모달 연동 설정 (선택된 버튼 데이터를 모달로 전달)
modalLink?: ModalLinkConfig;
// 자동 선택
autoSelectFirst?: boolean; // 첫 번째 (또는 기본) 항목 자동 선택
// 빈 상태 메시지
emptyMessage?: string;
}
/**
*
*/
export interface ButtonItem {
id: string;
displayText: string;
value: string;
isDefault: boolean;
rawData: Record<string, any>;
}

View File

@ -66,31 +66,10 @@ class ScreenSplitPanelRenderer extends AutoRegisteringComponentRenderer {
};
render() {
console.log("🚀 [ScreenSplitPanelRenderer] render() 호출됨!", this.props);
const { component, style = {}, componentConfig, config, screenId, formData } = this.props as any;
// componentConfig 또는 config 또는 component.componentConfig 사용
const finalConfig = componentConfig || config || component?.componentConfig || {};
console.log("🔍 [ScreenSplitPanelRenderer] 설정 분석:", {
hasComponentConfig: !!componentConfig,
hasConfig: !!config,
hasComponentComponentConfig: !!component?.componentConfig,
finalConfig,
splitRatio: finalConfig.splitRatio,
leftScreenId: finalConfig.leftScreenId,
rightScreenId: finalConfig.rightScreenId,
componentType: component?.componentType,
componentId: component?.id,
});
// 🆕 formData 별도 로그 (명확한 확인)
console.log("📝 [ScreenSplitPanelRenderer] formData 확인:", {
hasFormData: !!formData,
formDataKeys: formData ? Object.keys(formData) : [],
formData: formData,
});
return (
<div style={{ width: "100%", height: "100%", ...style }}>

View File

@ -1522,9 +1522,9 @@ export const SplitPanelLayoutConfigPanel: React.FC<SplitPanelLayoutConfigPanelPr
{availableRightTables.map((table) => (
<CommandItem
key={table.tableName}
value={table.tableName}
onSelect={(value) => {
updateRightPanel({ tableName: value });
value={`${table.displayName || ""} ${table.tableName}`}
onSelect={() => {
updateRightPanel({ tableName: table.tableName });
setRightTableOpen(false);
}}
>

View File

@ -304,6 +304,12 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
// 🆕 연결된 필터 상태 (다른 컴포넌트 값으로 필터링)
const [linkedFilterValues, setLinkedFilterValues] = useState<Record<string, any>>({});
// 🆕 RelatedDataButtons 컴포넌트에서 발생하는 필터 상태
const [relatedButtonFilter, setRelatedButtonFilter] = useState<{
filterColumn: string;
filterValue: any;
} | null>(null);
// TableOptions Context
const { registerTable, unregisterTable, updateTableDataCount } = useTableOptions();
const [filters, setFilters] = useState<TableFilter[]>([]);
@ -1268,18 +1274,9 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
});
}
console.log(`📡 [TableList] API 호출 시작 [${columnName}]:`, {
url: `/table-categories/${targetTable}/${targetColumn}/values`,
});
const response = await apiClient.get(`/table-categories/${targetTable}/${targetColumn}/values`);
console.log(`📡 [TableList] API 응답 [${columnName}]:`, {
success: response.data.success,
dataLength: response.data.data?.length,
rawData: response.data,
items: response.data.data,
});
if (response.data.success && response.data.data && Array.isArray(response.data.data)) {
const mapping: Record<string, { label: string; color?: string }> = {};
@ -1291,18 +1288,11 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
label: item.valueLabel,
color: item.color,
};
console.log(` 🔑 [${columnName}] "${key}" => "${item.valueLabel}" (색상: ${item.color})`);
});
if (Object.keys(mapping).length > 0) {
// 🆕 원래 컬럼명(item_info.material)으로 매핑 저장
mappings[columnName] = mapping;
console.log(`✅ [TableList] 카테고리 매핑 로드 완료 [${columnName}]:`, {
columnName,
mappingCount: Object.keys(mapping).length,
mappingKeys: Object.keys(mapping),
mapping,
});
} else {
console.warn(`⚠️ [TableList] 매핑 데이터가 비어있음 [${columnName}]`);
}
@ -1342,7 +1332,6 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
col.columnName,
})) || [];
console.log("🔍 [TableList] additionalJoinInfo 컬럼:", additionalJoinColumns);
// 조인 테이블별로 그룹화
const joinedTableColumns: Record<string, { columnName: string; actualColumn: string }[]> = {};
@ -1375,7 +1364,6 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
});
}
console.log("🔍 [TableList] 조인 테이블별 컬럼:", joinedTableColumns);
// 조인된 테이블별로 inputType 정보 가져오기
const newJoinedColumnMeta: Record<string, { webType?: string; codeCategory?: string; inputType?: string }> = {};
@ -1421,9 +1409,6 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
if (Object.keys(mapping).length > 0) {
mappings[col.columnName] = mapping;
console.log(`✅ [TableList] 조인 테이블 카테고리 매핑 로드 완료 [${col.columnName}]:`, {
mappingCount: Object.keys(mapping).length,
});
}
}
} catch (error) {
@ -1442,16 +1427,9 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
console.log("✅ [TableList] 조인 컬럼 메타데이터 설정:", newJoinedColumnMeta);
}
console.log("📊 [TableList] 전체 카테고리 매핑 설정:", {
mappingsCount: Object.keys(mappings).length,
mappingsKeys: Object.keys(mappings),
mappings,
});
if (Object.keys(mappings).length > 0) {
setCategoryMappings(mappings);
setCategoryMappingsKey((prev) => prev + 1);
console.log("✅ [TableList] setCategoryMappings 호출 완료");
} else {
console.warn("⚠️ [TableList] 매핑이 비어있어 상태 업데이트 스킵");
}
@ -1473,11 +1451,6 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
// ========================================
const fetchTableDataInternal = useCallback(async () => {
console.log("📡 [TableList] fetchTableDataInternal 호출됨", {
tableName: tableConfig.selectedTable,
isDesignMode,
currentPage,
});
if (!tableConfig.selectedTable || isDesignMode) {
setData([]);
@ -1501,13 +1474,6 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
let hasLinkedFiltersConfigured = false; // 연결 필터가 설정되어 있는지 여부
let hasSelectedLeftData = false; // 좌측에서 데이터가 선택되었는지 여부
console.log("🔍 [TableList] 분할 패널 컨텍스트 확인:", {
hasSplitPanelContext: !!splitPanelContext,
tableName: tableConfig.selectedTable,
selectedLeftData: splitPanelContext?.selectedLeftData,
linkedFilters: splitPanelContext?.linkedFilters,
splitPanelPosition: splitPanelPosition,
});
if (splitPanelContext) {
// 연결 필터 설정 여부 확인 (현재 테이블에 해당하는 필터가 있는지)
@ -1523,19 +1489,20 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
splitPanelContext.selectedLeftData && Object.keys(splitPanelContext.selectedLeftData).length > 0;
const allLinkedFilters = splitPanelContext.getLinkedFilterValues();
console.log("🔗 [TableList] 연결 필터 원본:", allLinkedFilters);
// 현재 테이블에 해당하는 필터만 추출 (테이블명.컬럼명 형식에서)
// 연결 필터는 코드 값이므로 정확한 매칭(equals)을 사용해야 함
for (const [key, value] of Object.entries(allLinkedFilters)) {
if (key.includes(".")) {
const [tableName, columnName] = key.split(".");
if (tableName === tableConfig.selectedTable) {
linkedFilterValues[columnName] = value;
// 연결 필터는 코드 값이므로 equals 연산자 사용
linkedFilterValues[columnName] = { value, operator: "equals" };
hasLinkedFiltersConfigured = true; // 이 테이블에 대한 필터가 있음
}
} else {
// 테이블명 없이 컬럼명만 있는 경우 그대로 사용
linkedFilterValues[key] = value;
// 테이블명 없이 컬럼명만 있는 경우 그대로 사용 (equals)
linkedFilterValues[key] = { value, operator: "equals" };
}
}
@ -1560,7 +1527,8 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
// 현재 테이블에 동일한 컬럼이 있는지 확인
if (tableColumns.includes(colName)) {
linkedFilterValues[colName] = colValue;
// 자동 컬럼 매칭도 equals 연산자 사용
linkedFilterValues[colName] = { value: colValue, operator: "equals" };
hasLinkedFiltersConfigured = true;
console.log(`🔗 [TableList] 자동 컬럼 매칭: ${colName} = ${colValue}`);
}
@ -1586,10 +1554,21 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
return;
}
// 검색 필터와 연결 필터 병합
// 🆕 RelatedDataButtons 필터 값 준비
let relatedButtonFilterValues: Record<string, any> = {};
if (relatedButtonFilter) {
relatedButtonFilterValues[relatedButtonFilter.filterColumn] = {
value: relatedButtonFilter.filterValue,
operator: "equals",
};
console.log("🔗 [TableList] RelatedDataButtons 필터 적용:", relatedButtonFilterValues);
}
// 검색 필터, 연결 필터, RelatedDataButtons 필터 병합
const filters = {
...(Object.keys(searchValues).length > 0 ? searchValues : {}),
...linkedFilterValues,
...relatedButtonFilterValues, // 🆕 RelatedDataButtons 필터 추가
};
const hasFilters = Object.keys(filters).length > 0;
@ -1652,7 +1631,6 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
};
});
console.log("🎯 [TableList] 화면별 엔티티 설정:", screenEntityConfigs);
// 🆕 제외 필터 처리 (다른 테이블에 이미 존재하는 데이터 제외)
let excludeFilterParam: any = undefined;
@ -1787,6 +1765,8 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
splitPanelPosition,
currentSplitPosition,
splitPanelContext?.selectedLeftData,
// 🆕 RelatedDataButtons 필터 추가
relatedButtonFilter,
]);
const fetchTableDataDebounced = useCallback(
@ -2143,16 +2123,6 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
// 분할 패널 컨텍스트가 있고, 좌측 화면인 경우에만 행 선택 및 데이터 전달
const effectiveSplitPosition = splitPanelPosition || currentSplitPosition;
console.log("🔗 [TableList] 셀 클릭 - 분할 패널 위치 확인:", {
rowIndex,
colIndex,
splitPanelPosition,
currentSplitPosition,
effectiveSplitPosition,
hasSplitPanelContext: !!splitPanelContext,
isCurrentlySelected,
});
if (splitPanelContext && effectiveSplitPosition === "left" && !splitPanelContext.disableAutoDataTransfer) {
// 이미 선택된 행과 다른 행을 클릭한 경우에만 처리
if (!isCurrentlySelected) {
@ -2162,10 +2132,6 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
// 분할 패널 컨텍스트에 데이터 저장
splitPanelContext.setSelectedLeftData(row);
console.log("🔗 [TableList] 셀 클릭으로 분할 패널 좌측 데이터 저장:", {
row,
parentDataMapping: splitPanelContext.parentDataMapping,
});
// onSelectedRowsChange 콜백 호출
if (onSelectedRowsChange) {
@ -2885,7 +2851,6 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
try {
localStorage.setItem(tableStateKey, JSON.stringify(state));
console.log("✅ 테이블 상태 저장:", tableStateKey);
} catch (error) {
console.error("❌ 테이블 상태 저장 실패:", error);
}
@ -2927,7 +2892,6 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
setHeaderFilters(filters);
}
console.log("✅ 테이블 상태 복원:", tableStateKey);
} catch (error) {
console.error("❌ 테이블 상태 복원 실패:", error);
}
@ -2948,7 +2912,6 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
setShowGridLines(true);
setHeaderFilters({});
toast.success("테이블 설정이 초기화되었습니다.");
console.log("✅ 테이블 상태 초기화:", tableStateKey);
} catch (error) {
console.error("❌ 테이블 상태 초기화 실패:", error);
}
@ -4820,6 +4783,37 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
};
}, [tableConfig.selectedTable, isDesignMode]);
// 🆕 RelatedDataButtons 선택 이벤트 리스너 (버튼 선택 시 테이블 필터링)
useEffect(() => {
const handleRelatedButtonSelect = (event: CustomEvent) => {
const { targetTable, filterColumn, filterValue } = event.detail || {};
// 이 테이블이 대상 테이블인지 확인
if (targetTable === tableConfig.selectedTable) {
console.log("📌 [TableList] RelatedDataButtons 필터 적용:", {
tableName: tableConfig.selectedTable,
filterColumn,
filterValue,
});
setRelatedButtonFilter({ filterColumn, filterValue });
}
};
window.addEventListener("related-button-select" as any, handleRelatedButtonSelect);
return () => {
window.removeEventListener("related-button-select" as any, handleRelatedButtonSelect);
};
}, [tableConfig.selectedTable]);
// 🆕 relatedButtonFilter 변경 시 데이터 다시 로드
useEffect(() => {
if (relatedButtonFilter && !isDesignMode) {
console.log("🔄 [TableList] RelatedDataButtons 필터 변경으로 데이터 새로고침:", relatedButtonFilter);
setRefreshTrigger((prev) => prev + 1);
}
}, [relatedButtonFilter, isDesignMode]);
// 🎯 컬럼 너비 자동 계산 (내용 기반)
const calculateOptimalColumnWidth = useCallback(
(columnName: string, displayName: string): number => {

View File

@ -115,21 +115,9 @@ export function TableSearchWidget({ component, screenId, onHeightChange }: Table
// 필터링된 결과가 없으면 모든 테이블 반환 (폴백)
if (filteredTables.length === 0) {
console.log("🔍 [TableSearchWidget] 대상 패널에 테이블 없음, 전체 테이블 사용:", {
targetPanelPosition,
allTablesCount: allTableList.length,
allTableIds: allTableList.map(t => t.tableId),
});
return allTableList;
}
console.log("🔍 [TableSearchWidget] 테이블 필터링:", {
targetPanelPosition,
allTablesCount: allTableList.length,
filteredCount: filteredTables.length,
filteredTableIds: filteredTables.map(t => t.tableId),
});
return filteredTables;
}, [allTableList, targetPanelPosition]);
@ -159,11 +147,6 @@ export function TableSearchWidget({ component, screenId, onHeightChange }: Table
// 현재 선택된 테이블이 대상 패널에 없으면 대상 패널의 첫 번째 테이블 선택
if (!selectedTableId || !isCurrentTableInTarget) {
const targetTable = tableList[0];
console.log("🔍 [TableSearchWidget] 대상 패널 테이블 자동 선택:", {
targetPanelPosition,
selectedTableId: targetTable.tableId,
tableName: targetTable.tableName,
});
setSelectedTableId(targetTable.tableId);
}
}, [tableList, selectedTableId, autoSelectFirstTable, setSelectedTableId, targetPanelPosition]);
@ -374,12 +357,6 @@ export function TableSearchWidget({ component, screenId, onHeightChange }: Table
return true;
});
console.log("🔍 [TableSearchWidget] 필터 적용:", {
currentTableId: currentTable?.tableId,
currentTableName: currentTable?.tableName,
filtersCount: filtersWithValues.length,
filtersWithValues,
});
currentTable?.onFilterChange(filtersWithValues);
};

View File

@ -23,12 +23,6 @@ const TabsWidgetWrapper: React.FC<any> = (props) => {
persistSelection: tabsConfig.persistSelection || false,
};
console.log("🎨 TabsWidget 렌더링:", {
componentId: component.id,
tabs: tabsComponent.tabs,
tabsLength: tabsComponent.tabs.length,
component,
});
// TabsWidget 동적 로드
const TabsWidget = require("@/components/screen/widgets/TabsWidget").TabsWidget;

View File

@ -55,29 +55,11 @@ export const TextareaBasicComponent: React.FC<TextareaBasicComponentProps> = ({
onClick?.();
};
// DOM에 전달하면 안 되는 React-specific props 필터링
const {
selectedScreen,
onZoneComponentDrop,
onZoneClick,
componentConfig: _componentConfig,
component: _component,
isSelected: _isSelected,
onClick: _onClick,
onDragStart: _onDragStart,
onDragEnd: _onDragEnd,
size: _size,
position: _position,
style: _style,
screenId: _screenId,
tableName: _tableName,
onRefresh: _onRefresh,
onClose: _onClose,
...domProps
} = props;
// DOM에 전달하면 안 되는 React-specific props 필터링 - 모든 커스텀 props 제거
// domProps를 사용하지 않고 필요한 props만 명시적으로 전달
return (
<div style={componentStyle} className={className} {...domProps}>
<div style={componentStyle} className={className}>
{/* 라벨 렌더링 */}
{component.label && component.style?.labelDisplay !== false && (
<label

View File

@ -17,6 +17,7 @@ export type ButtonActionType =
| "edit" // 편집
| "copy" // 복사 (품목코드 초기화)
| "navigate" // 페이지 이동
| "openRelatedModal" // 연관 데이터 버튼의 선택 데이터로 모달 열기
| "openModalWithData" // 데이터를 전달하면서 모달 열기
| "modal" // 모달 열기
| "control" // 제어 흐름
@ -28,7 +29,8 @@ export type ButtonActionType =
// | "empty_vehicle" // 공차등록 (위치 수집 + 상태 변경) - 운행알림으로 통합
| "operation_control" // 운행알림 및 종료 (위치 수집 + 상태 변경 + 연속 추적)
| "swap_fields" // 필드 값 교환 (출발지 ↔ 목적지)
| "transferData"; // 데이터 전달 (컴포넌트 간 or 화면 간)
| "transferData" // 데이터 전달 (컴포넌트 간 or 화면 간)
| "quickInsert"; // 즉시 저장 (선택한 데이터를 특정 테이블에 즉시 INSERT)
/**
*
@ -211,6 +213,37 @@ export interface ButtonActionConfig {
maxSelection?: number; // 최대 선택 개수
};
};
// 연관 데이터 버튼 모달 열기 관련
relatedModalConfig?: {
targetScreenId: number; // 열릴 모달 화면 ID
componentId?: string; // 특정 RelatedDataButtons 컴포넌트 지정 (선택사항)
};
// 즉시 저장 (Quick Insert) 관련
quickInsertConfig?: {
targetTable: string; // 저장할 테이블명
columnMappings: Array<{
targetColumn: string; // 대상 테이블의 컬럼명
sourceType: "component" | "leftPanel" | "fixed" | "currentUser"; // 값 소스 타입
sourceComponentId?: string; // 컴포넌트에서 값을 가져올 경우 컴포넌트 ID
sourceColumnName?: string; // 컴포넌트의 columnName (formData 접근용)
sourceColumn?: string; // 좌측 패널 또는 컴포넌트의 특정 컬럼
fixedValue?: any; // 고정값
userField?: "userId" | "userName" | "companyCode"; // currentUser 타입일 때 사용할 필드
}>;
duplicateCheck?: {
enabled: boolean; // 중복 체크 활성화 여부
columns?: string[]; // 중복 체크할 컬럼들
errorMessage?: string; // 중복 시 에러 메시지
};
afterInsert?: {
refreshData?: boolean; // 저장 후 데이터 새로고침 (테이블리스트, 카드 디스플레이)
clearComponents?: boolean; // 저장 후 컴포넌트 값 초기화
showSuccessMessage?: boolean; // 성공 메시지 표시 여부 (기본: true)
successMessage?: string; // 성공 메시지
};
};
}
/**
@ -265,6 +298,12 @@ export interface ButtonActionContext {
// 🆕 분할 패널 부모 데이터 (좌측 화면에서 선택된 데이터)
splitPanelParentData?: Record<string, any>;
// 🆕 분할 패널 컨텍스트 (quickInsert 등에서 좌측 패널 데이터 접근용)
splitPanelContext?: {
selectedLeftData?: Record<string, any>;
refreshRightPanel?: () => void;
};
}
/**
@ -329,6 +368,9 @@ export class ButtonActionExecutor {
case "openModalWithData":
return await this.handleOpenModalWithData(config, context);
case "openRelatedModal":
return await this.handleOpenRelatedModal(config, context);
case "modal":
return await this.handleModal(config, context);
@ -365,6 +407,9 @@ export class ButtonActionExecutor {
case "swap_fields":
return await this.handleSwapFields(config, context);
case "quickInsert":
return await this.handleQuickInsert(config, context);
default:
console.warn(`지원되지 않는 액션 타입: ${config.type}`);
return false;
@ -376,6 +421,49 @@ export class ButtonActionExecutor {
}
}
/**
*
*/
private static validateRequiredFields(context: ButtonActionContext): { isValid: boolean; missingFields: string[] } {
const missingFields: string[] = [];
const { formData, allComponents } = context;
if (!allComponents || allComponents.length === 0) {
console.log("⚠️ [validateRequiredFields] allComponents 없음 - 검증 스킵");
return { isValid: true, missingFields: [] };
}
allComponents.forEach((component: any) => {
// 컴포넌트의 required 속성 확인 (여러 위치에서 체크)
const isRequired =
component.required === true ||
component.style?.required === true ||
component.componentConfig?.required === true;
const columnName = component.columnName || component.style?.columnName;
const label = component.label || component.style?.label || columnName;
if (isRequired && columnName) {
const value = formData[columnName];
// 값이 비어있는지 확인 (null, undefined, 빈 문자열, 공백만 있는 문자열)
if (value === null || value === undefined || (typeof value === "string" && value.trim() === "")) {
console.log("🔍 [validateRequiredFields] 필수 항목 누락:", {
columnName,
label,
value,
isRequired,
});
missingFields.push(label || columnName);
}
}
});
return {
isValid: missingFields.length === 0,
missingFields,
};
}
/**
* (INSERT/UPDATE - DB )
*/
@ -415,6 +503,19 @@ export class ButtonActionExecutor {
hasOnSave: !!onSave,
});
// ✅ 필수 항목 검증
console.log("🔍 [handleSave] 필수 항목 검증 시작:", {
hasAllComponents: !!context.allComponents,
allComponentsLength: context.allComponents?.length || 0,
});
const requiredValidation = this.validateRequiredFields(context);
if (!requiredValidation.isValid) {
console.log("❌ [handleSave] 필수 항목 누락:", requiredValidation.missingFields);
toast.error(`필수 항목을 입력해주세요: ${requiredValidation.missingFields.join(", ")}`);
return false;
}
console.log("✅ [handleSave] 필수 항목 검증 통과");
// 🆕 EditModal 등에서 전달된 onSave 콜백이 있으면 우선 사용
if (onSave) {
console.log("✅ [handleSave] onSave 콜백 발견 - 콜백 실행");
@ -1778,6 +1879,100 @@ export class ButtonActionExecutor {
return false;
}
/**
*
* RelatedDataButtons
*/
private static async handleOpenRelatedModal(config: ButtonActionConfig, context: ButtonActionContext): Promise<boolean> {
// 버튼 설정에서 targetScreenId 가져오기 (여러 위치에서 확인)
const targetScreenId = config.relatedModalConfig?.targetScreenId || config.targetScreenId;
console.log("🔍 [openRelatedModal] 설정 확인:", {
config,
relatedModalConfig: config.relatedModalConfig,
targetScreenId: config.targetScreenId,
finalTargetScreenId: targetScreenId,
});
if (!targetScreenId) {
console.error("❌ [openRelatedModal] targetScreenId가 설정되지 않았습니다.");
toast.error("모달 화면 ID가 설정되지 않았습니다.");
return false;
}
// RelatedDataButtons에서 선택된 데이터 가져오기
const relatedData = window.__relatedButtonsSelectedData;
console.log("🔍 [openRelatedModal] RelatedDataButtons 데이터:", {
relatedData,
selectedItem: relatedData?.selectedItem,
config: relatedData?.config,
});
if (!relatedData?.selectedItem) {
console.warn("⚠️ [openRelatedModal] 선택된 버튼이 없습니다.");
toast.warning("먼저 버튼을 선택해주세요.");
return false;
}
const { selectedItem, config: relatedConfig } = relatedData;
// 데이터 매핑 적용
const initialData: Record<string, any> = {};
console.log("🔍 [openRelatedModal] 매핑 설정:", {
modalLink: relatedConfig?.modalLink,
dataMapping: relatedConfig?.modalLink?.dataMapping,
});
if (relatedConfig?.modalLink?.dataMapping && relatedConfig.modalLink.dataMapping.length > 0) {
relatedConfig.modalLink.dataMapping.forEach(mapping => {
console.log("🔍 [openRelatedModal] 매핑 처리:", {
mapping,
sourceField: mapping.sourceField,
targetField: mapping.targetField,
selectedItemValue: selectedItem.value,
selectedItemId: selectedItem.id,
rawDataValue: selectedItem.rawData[mapping.sourceField],
});
if (mapping.sourceField === "value") {
initialData[mapping.targetField] = selectedItem.value;
} else if (mapping.sourceField === "id") {
initialData[mapping.targetField] = selectedItem.id;
} else if (selectedItem.rawData[mapping.sourceField] !== undefined) {
initialData[mapping.targetField] = selectedItem.rawData[mapping.sourceField];
}
});
} else {
// 기본 매핑: id를 routing_version_id로 전달
console.log("🔍 [openRelatedModal] 기본 매핑 사용");
initialData["routing_version_id"] = selectedItem.value || selectedItem.id;
}
console.log("📤 [openRelatedModal] 모달 열기:", {
targetScreenId,
selectedItem,
initialData,
});
// 모달 열기 이벤트 발생 (ScreenModal은 editData를 사용)
window.dispatchEvent(new CustomEvent("openScreenModal", {
detail: {
screenId: targetScreenId,
title: config.modalTitle,
description: config.modalDescription,
editData: initialData, // ScreenModal은 editData로 폼 데이터를 받음
onSuccess: () => {
// 성공 후 데이터 새로고침
window.dispatchEvent(new CustomEvent("refreshTableData"));
},
},
}));
return true;
}
/**
*
* ( )
@ -5190,6 +5385,313 @@ export class ButtonActionExecutor {
}
}
/**
* (Quick Insert)
*
*/
private static async handleQuickInsert(config: ButtonActionConfig, context: ButtonActionContext): Promise<boolean> {
try {
console.log("⚡ Quick Insert 액션 실행:", { config, context });
const quickInsertConfig = config.quickInsertConfig;
if (!quickInsertConfig?.targetTable) {
toast.error("대상 테이블이 설정되지 않았습니다.");
return false;
}
const { formData, splitPanelContext, userId, userName, companyCode } = context;
console.log("⚡ Quick Insert 상세 정보:", {
targetTable: quickInsertConfig.targetTable,
columnMappings: quickInsertConfig.columnMappings,
formData: formData,
formDataKeys: Object.keys(formData || {}),
splitPanelContext: splitPanelContext,
selectedLeftData: splitPanelContext?.selectedLeftData,
allComponents: context.allComponents,
userId,
userName,
companyCode,
});
// 컬럼 매핑에 따라 저장할 데이터 구성
const insertData: Record<string, any> = {};
const columnMappings = quickInsertConfig.columnMappings || [];
for (const mapping of columnMappings) {
console.log(`📍 매핑 처리 시작:`, mapping);
if (!mapping.targetColumn) {
console.log(`📍 targetColumn 없음, 스킵`);
continue;
}
let value: any = undefined;
switch (mapping.sourceType) {
case "component":
console.log(`📍 component 타입 처리:`, {
sourceComponentId: mapping.sourceComponentId,
sourceColumnName: mapping.sourceColumnName,
targetColumn: mapping.targetColumn,
});
// 컴포넌트의 현재 값
if (mapping.sourceComponentId) {
// 1. sourceColumnName이 있으면 직접 사용 (가장 확실한 방법)
if (mapping.sourceColumnName) {
value = formData?.[mapping.sourceColumnName];
console.log(`📍 방법1 (sourceColumnName): ${mapping.sourceColumnName} = ${value}`);
}
// 2. 없으면 컴포넌트 ID로 직접 찾기
if (value === undefined) {
value = formData?.[mapping.sourceComponentId];
console.log(`📍 방법2 (sourceComponentId): ${mapping.sourceComponentId} = ${value}`);
}
// 3. 없으면 allComponents에서 컴포넌트를 찾아 columnName으로 시도
if (value === undefined && context.allComponents) {
const comp = context.allComponents.find((c: any) => c.id === mapping.sourceComponentId);
console.log(`📍 방법3 찾은 컴포넌트:`, comp);
if (comp?.columnName) {
value = formData?.[comp.columnName];
console.log(`📍 방법3 (allComponents): ${mapping.sourceComponentId}${comp.columnName} = ${value}`);
}
}
// 4. targetColumn과 같은 이름의 키가 formData에 있으면 사용 (폴백)
if (value === undefined && mapping.targetColumn && formData?.[mapping.targetColumn] !== undefined) {
value = formData[mapping.targetColumn];
console.log(`📍 방법4 (targetColumn 폴백): ${mapping.targetColumn} = ${value}`);
}
// 5. 그래도 없으면 formData의 모든 키를 확인하고 로깅
if (value === undefined) {
console.log("📍 방법5: formData에서 값을 찾지 못함. formData 키들:", Object.keys(formData || {}));
}
// sourceColumn이 지정된 경우 해당 속성 추출
if (mapping.sourceColumn && value && typeof value === "object") {
value = value[mapping.sourceColumn];
console.log(`📍 sourceColumn 추출: ${mapping.sourceColumn} = ${value}`);
}
}
break;
case "leftPanel":
console.log(`📍 leftPanel 타입 처리:`, {
sourceColumn: mapping.sourceColumn,
selectedLeftData: splitPanelContext?.selectedLeftData,
});
// 좌측 패널 선택 데이터
if (mapping.sourceColumn && splitPanelContext?.selectedLeftData) {
value = splitPanelContext.selectedLeftData[mapping.sourceColumn];
console.log(`📍 leftPanel 값: ${mapping.sourceColumn} = ${value}`);
}
break;
case "fixed":
console.log(`📍 fixed 타입 처리: fixedValue = ${mapping.fixedValue}`);
// 고정값
value = mapping.fixedValue;
break;
case "currentUser":
console.log(`📍 currentUser 타입 처리: userField = ${mapping.userField}`);
// 현재 사용자 정보
switch (mapping.userField) {
case "userId":
value = userId;
break;
case "userName":
value = userName;
break;
case "companyCode":
value = companyCode;
break;
}
console.log(`📍 currentUser 값: ${value}`);
break;
default:
console.log(`📍 알 수 없는 sourceType: ${mapping.sourceType}`);
}
console.log(`📍 매핑 결과: targetColumn=${mapping.targetColumn}, value=${value}, type=${typeof value}`);
if (value !== undefined && value !== null && value !== "") {
insertData[mapping.targetColumn] = value;
console.log(`📍 insertData에 추가됨: ${mapping.targetColumn} = ${value}`);
} else {
console.log(`📍 값이 비어있어서 insertData에 추가 안됨`);
}
}
// 🆕 좌측 패널 선택 데이터에서 자동 매핑 (대상 테이블에 존재하는 컬럼만)
if (splitPanelContext?.selectedLeftData) {
const leftData = splitPanelContext.selectedLeftData;
console.log("📍 좌측 패널 자동 매핑 시작:", leftData);
// 대상 테이블의 컬럼 목록 조회
let targetTableColumns: string[] = [];
try {
const columnsResponse = await apiClient.get(
`/table-management/tables/${quickInsertConfig.targetTable}/columns`
);
if (columnsResponse.data?.success && columnsResponse.data?.data) {
const columnsData = columnsResponse.data.data.columns || columnsResponse.data.data;
targetTableColumns = columnsData.map((col: any) => col.columnName || col.column_name || col.name);
console.log("📍 대상 테이블 컬럼 목록:", targetTableColumns);
}
} catch (error) {
console.error("대상 테이블 컬럼 조회 실패:", error);
}
for (const [key, val] of Object.entries(leftData)) {
// 이미 매핑된 컬럼은 스킵
if (insertData[key] !== undefined) {
console.log(`📍 자동 매핑 스킵 (이미 존재): ${key}`);
continue;
}
// 대상 테이블에 해당 컬럼이 없으면 스킵
if (targetTableColumns.length > 0 && !targetTableColumns.includes(key)) {
console.log(`📍 자동 매핑 스킵 (대상 테이블에 없는 컬럼): ${key}`);
continue;
}
// 시스템 컬럼 제외 (id, created_date, updated_date, writer 등)
const systemColumns = ['id', 'created_date', 'updated_date', 'writer', 'writer_name'];
if (systemColumns.includes(key)) {
console.log(`📍 자동 매핑 스킵 (시스템 컬럼): ${key}`);
continue;
}
// _label, _name 으로 끝나는 표시용 컬럼 제외
if (key.endsWith('_label') || key.endsWith('_name')) {
console.log(`📍 자동 매핑 스킵 (표시용 컬럼): ${key}`);
continue;
}
// 값이 있으면 자동 추가
if (val !== undefined && val !== null && val !== '') {
insertData[key] = val;
console.log(`📍 자동 매핑 추가: ${key} = ${val}`);
}
}
}
console.log("⚡ Quick Insert 최종 데이터:", insertData, "키 개수:", Object.keys(insertData).length);
// 필수 데이터 검증
if (Object.keys(insertData).length === 0) {
toast.error("저장할 데이터가 없습니다.");
return false;
}
// 중복 체크
console.log("📍 중복 체크 설정:", {
enabled: quickInsertConfig.duplicateCheck?.enabled,
columns: quickInsertConfig.duplicateCheck?.columns,
});
if (quickInsertConfig.duplicateCheck?.enabled && quickInsertConfig.duplicateCheck?.columns?.length > 0) {
const duplicateCheckData: Record<string, any> = {};
for (const col of quickInsertConfig.duplicateCheck.columns) {
if (insertData[col] !== undefined) {
// 백엔드가 { value, operator } 형식을 기대하므로 변환
duplicateCheckData[col] = { value: insertData[col], operator: "equals" };
}
}
console.log("📍 중복 체크 조건:", duplicateCheckData);
if (Object.keys(duplicateCheckData).length > 0) {
try {
const checkResponse = await apiClient.post(
`/table-management/tables/${quickInsertConfig.targetTable}/data`,
{
page: 1,
pageSize: 1,
search: duplicateCheckData,
}
);
console.log("📍 중복 체크 응답:", checkResponse.data);
// 응답 구조: { success: true, data: { data: [...], total: N } } 또는 { success: true, data: [...] }
const existingData = checkResponse.data?.data?.data || checkResponse.data?.data || [];
console.log("📍 기존 데이터:", existingData, "길이:", Array.isArray(existingData) ? existingData.length : 0);
if (Array.isArray(existingData) && existingData.length > 0) {
toast.error(quickInsertConfig.duplicateCheck.errorMessage || "이미 존재하는 데이터입니다.");
return false;
}
} catch (error) {
console.error("중복 체크 오류:", error);
// 중복 체크 실패해도 저장은 시도
}
}
} else {
console.log("📍 중복 체크 비활성화 또는 컬럼 미설정");
}
// 데이터 저장
const response = await apiClient.post(
`/table-management/tables/${quickInsertConfig.targetTable}/add`,
insertData
);
if (response.data?.success) {
console.log("✅ Quick Insert 저장 성공");
// 저장 후 동작 설정 로그
console.log("📍 afterInsert 설정:", quickInsertConfig.afterInsert);
// 🆕 데이터 새로고침 (테이블리스트, 카드 디스플레이 컴포넌트 새로고침)
// refreshData가 명시적으로 false가 아니면 기본적으로 새로고침 실행
const shouldRefresh = quickInsertConfig.afterInsert?.refreshData !== false;
console.log("📍 데이터 새로고침 여부:", shouldRefresh);
if (shouldRefresh) {
console.log("📍 데이터 새로고침 이벤트 발송");
// 전역 이벤트로 테이블/카드 컴포넌트들에게 새로고침 알림
if (typeof window !== "undefined") {
window.dispatchEvent(new CustomEvent("refreshTable"));
window.dispatchEvent(new CustomEvent("refreshCardDisplay"));
console.log("✅ refreshTable, refreshCardDisplay 이벤트 발송 완료");
}
}
// 컴포넌트 값 초기화
if (quickInsertConfig.afterInsert?.clearComponents && context.onFormDataChange) {
for (const mapping of columnMappings) {
if (mapping.sourceType === "component" && mapping.sourceComponentId) {
// sourceColumnName이 있으면 그것을 사용, 없으면 sourceComponentId 사용
const fieldName = mapping.sourceColumnName || mapping.sourceComponentId;
context.onFormDataChange(fieldName, null);
console.log(`📍 컴포넌트 값 초기화: ${fieldName}`);
}
}
}
if (quickInsertConfig.afterInsert?.showSuccessMessage !== false) {
toast.success(quickInsertConfig.afterInsert?.successMessage || "저장되었습니다.");
}
return true;
} else {
toast.error(response.data?.message || "저장에 실패했습니다.");
return false;
}
} catch (error: any) {
console.error("❌ Quick Insert 오류:", error);
toast.error(error.response?.data?.message || "저장 중 오류가 발생했습니다.");
return false;
}
}
/**
* (: status를 active로 )
* 🆕
@ -5643,4 +6145,9 @@ export const DEFAULT_BUTTON_ACTIONS: Record<ButtonActionType, Partial<ButtonActi
successMessage: "필드 값이 교환되었습니다.",
errorMessage: "필드 값 교환 중 오류가 발생했습니다.",
},
quickInsert: {
type: "quickInsert",
successMessage: "저장되었습니다.",
errorMessage: "저장 중 오류가 발생했습니다.",
},
};

View File

@ -54,7 +54,7 @@ export const WEB_TYPE_COMPONENT_MAPPING: Record<string, string> = {
// 기타
label: "text-display",
code: "select-basic", // 코드 타입은 선택상자 사용
entity: "select-basic", // 엔티티 타입은 선택상자 사용
entity: "entity-search-input", // 엔티티 타입은 전용 검색 입력 사용
category: "select-basic", // 카테고리 타입은 선택상자 사용
};

View File

@ -8,10 +8,11 @@
import { WebType } from "./unified-core";
/**
* 9
*
*/
export type BaseInputType =
| "text" // 텍스트
| "textarea" // 텍스트 에리어 (여러 줄)
| "number" // 숫자
| "date" // 날짜
| "code" // 코드
@ -34,16 +35,18 @@ export interface DetailTypeOption {
*
*/
export const INPUT_TYPE_DETAIL_TYPES: Record<BaseInputType, DetailTypeOption[]> = {
// 텍스트 → text, email, tel, url, textarea, password
// 텍스트 → text, email, tel, url, password
text: [
{ value: "text", label: "일반 텍스트", description: "기본 텍스트 입력" },
{ value: "email", label: "이메일", description: "이메일 주소 입력" },
{ value: "tel", label: "전화번호", description: "전화번호 입력" },
{ value: "url", label: "URL", description: "웹사이트 주소 입력" },
{ value: "textarea", label: "여러 줄 텍스트", description: "긴 텍스트 입력" },
{ value: "password", label: "비밀번호", description: "비밀번호 입력 (마스킹)" },
],
// 텍스트 에리어 → textarea
textarea: [{ value: "textarea", label: "텍스트 에리어", description: "여러 줄 텍스트 입력" }],
// 숫자 → number, decimal, currency, percentage
number: [
{ value: "number", label: "정수", description: "정수 숫자 입력" },
@ -102,8 +105,13 @@ export const INPUT_TYPE_DETAIL_TYPES: Record<BaseInputType, DetailTypeOption[]>
*
*/
export function getBaseInputType(webType: WebType): BaseInputType {
// textarea (별도 타입으로 분리)
if (webType === "textarea") {
return "textarea";
}
// text 계열
if (["text", "email", "tel", "url", "textarea", "password"].includes(webType)) {
if (["text", "email", "tel", "url", "password"].includes(webType)) {
return "text";
}
@ -167,6 +175,7 @@ export function getDefaultDetailType(baseInputType: BaseInputType): WebType {
*/
export const BASE_INPUT_TYPE_OPTIONS: Array<{ value: BaseInputType; label: string; description: string }> = [
{ value: "text", label: "텍스트", description: "텍스트 입력 필드" },
{ value: "textarea", label: "텍스트 에리어", description: "여러 줄 텍스트 입력" },
{ value: "number", label: "숫자", description: "숫자 입력 필드" },
{ value: "date", label: "날짜", description: "날짜/시간 선택" },
{ value: "code", label: "코드", description: "공통 코드 선택" },

View File

@ -5,9 +5,10 @@
* 주의: .
*/
// 9개 핵심 입력 타입
// 핵심 입력 타입
export type InputType =
| "text" // 텍스트
| "textarea" // 텍스트 에리어 (여러 줄 입력)
| "number" // 숫자
| "date" // 날짜
| "code" // 코드
@ -42,6 +43,13 @@ export const INPUT_TYPE_OPTIONS: InputTypeOption[] = [
category: "basic",
icon: "Type",
},
{
value: "textarea",
label: "텍스트 에리어",
description: "여러 줄 텍스트 입력",
category: "basic",
icon: "AlignLeft",
},
{
value: "number",
label: "숫자",
@ -130,6 +138,11 @@ export const INPUT_TYPE_DEFAULT_CONFIGS: Record<InputType, Record<string, any>>
maxLength: 500,
placeholder: "텍스트를 입력하세요",
},
textarea: {
maxLength: 2000,
rows: 4,
placeholder: "내용을 입력하세요",
},
number: {
min: 0,
step: 1,
@ -163,13 +176,17 @@ export const INPUT_TYPE_DEFAULT_CONFIGS: Record<InputType, Record<string, any>>
radio: {
inline: false,
},
image: {
placeholder: "이미지를 선택하세요",
accept: "image/*",
},
};
// 레거시 웹 타입 → 입력 타입 매핑
export const WEB_TYPE_TO_INPUT_TYPE: Record<string, InputType> = {
// 텍스트 관련
text: "text",
textarea: "text",
textarea: "textarea",
email: "text",
tel: "text",
url: "text",
@ -204,6 +221,7 @@ export const WEB_TYPE_TO_INPUT_TYPE: Record<string, InputType> = {
// 입력 타입 → 웹 타입 역매핑 (화면관리 시스템 호환용)
export const INPUT_TYPE_TO_WEB_TYPE: Record<InputType, string> = {
text: "text",
textarea: "textarea",
number: "number",
date: "date",
code: "code",
@ -212,6 +230,7 @@ export const INPUT_TYPE_TO_WEB_TYPE: Record<InputType, string> = {
select: "select",
checkbox: "checkbox",
radio: "radio",
image: "image",
};
// 입력 타입 변환 함수
@ -226,6 +245,11 @@ export const INPUT_TYPE_VALIDATION_RULES: Record<InputType, Record<string, any>>
trim: true,
maxLength: 500,
},
textarea: {
type: "string",
trim: true,
maxLength: 2000,
},
number: {
type: "number",
allowFloat: true,
@ -258,4 +282,8 @@ export const INPUT_TYPE_VALIDATION_RULES: Record<InputType, Record<string, any>>
type: "string",
options: true,
},
image: {
type: "string",
required: false,
},
};

View File

@ -363,6 +363,8 @@ export interface EntityTypeConfig {
placeholder?: string;
displayFormat?: "simple" | "detailed" | "custom"; // 표시 형식
separator?: string; // 여러 컬럼 표시 시 구분자 (기본: ' - ')
// UI 모드
uiMode?: "select" | "modal" | "combo" | "autocomplete"; // 기본: "combo"
}
/**
@ -428,6 +430,111 @@ export interface ButtonTypeConfig {
// ButtonActionType과 관련된 설정은 control-management.ts에서 정의
}
// ===== 즉시 저장(quickInsert) 설정 =====
/**
*
*
*/
export interface QuickInsertColumnMapping {
/** 저장할 테이블의 대상 컬럼명 */
targetColumn: string;
/** 값 소스 타입 */
sourceType: "component" | "leftPanel" | "fixed" | "currentUser";
// sourceType별 추가 설정
/** component: 값을 가져올 컴포넌트 ID */
sourceComponentId?: string;
/** component: 컴포넌트의 columnName (formData 접근용) */
sourceColumnName?: string;
/** leftPanel: 좌측 선택 데이터의 컬럼명 */
sourceColumn?: string;
/** fixed: 고정값 */
fixedValue?: any;
/** currentUser: 사용자 정보 필드 */
userField?: "userId" | "userName" | "companyCode" | "deptCode";
}
/**
*
*/
export interface QuickInsertAfterAction {
/** 데이터 새로고침 (테이블리스트, 카드 디스플레이 컴포넌트) */
refreshData?: boolean;
/** 초기화할 컴포넌트 ID 목록 */
clearComponents?: string[];
/** 성공 메시지 표시 여부 */
showSuccessMessage?: boolean;
/** 커스텀 성공 메시지 */
successMessage?: string;
}
/**
*
*/
export interface QuickInsertDuplicateCheck {
/** 중복 체크 활성화 */
enabled: boolean;
/** 중복 체크할 컬럼들 */
columns: string[];
/** 중복 시 에러 메시지 */
errorMessage?: string;
}
/**
* (quickInsert)
*
* entity ,
* INSERT하는
*
* @example
* ```typescript
* const config: QuickInsertConfig = {
* targetTable: "process_equipment",
* columnMappings: [
* {
* targetColumn: "equipment_code",
* sourceType: "component",
* sourceComponentId: "equipment-select"
* },
* {
* targetColumn: "process_code",
* sourceType: "leftPanel",
* sourceColumn: "process_code"
* }
* ],
* afterInsert: {
* refreshData: true,
* clearComponents: ["equipment-select"],
* showSuccessMessage: true
* }
* };
* ```
*/
export interface QuickInsertConfig {
/** 저장할 대상 테이블명 */
targetTable: string;
/** 컬럼 매핑 설정 */
columnMappings: QuickInsertColumnMapping[];
/** 저장 후 동작 설정 */
afterInsert?: QuickInsertAfterAction;
/** 중복 체크 설정 (선택사항) */
duplicateCheck?: QuickInsertDuplicateCheck;
}
/**
*
*

View File

@ -71,7 +71,9 @@ export type ButtonActionType =
// 제어관리 전용
| "control"
// 데이터 전달
| "transferData"; // 선택된 데이터를 다른 컴포넌트/화면으로 전달
| "transferData" // 선택된 데이터를 다른 컴포넌트/화면으로 전달
// 즉시 저장
| "quickInsert"; // 선택한 데이터를 특정 테이블에 즉시 INSERT
/**
*
@ -328,6 +330,7 @@ export const isButtonActionType = (value: string): value is ButtonActionType =>
"newWindow",
"control",
"transferData",
"quickInsert",
];
return actionTypes.includes(value as ButtonActionType);
};

View File

@ -1685,3 +1685,4 @@ const 출고등록_설정: ScreenSplitPanel = {

View File

@ -532,3 +532,4 @@ const { data: config } = await getScreenSplitPanel(screenId);

View File

@ -519,3 +519,4 @@ function ScreenViewPage() {