ERP-node/frontend/lib/registry/components/table-list/TableListComponent.tsx

1508 lines
59 KiB
TypeScript

"use client";
import React, { useState, useEffect, useMemo } from "react";
import { TableListConfig, ColumnConfig } from "./types";
import { tableTypeApi } from "@/lib/api/screen";
import { entityJoinApi } from "@/lib/api/entityJoin";
import { codeCache } from "@/lib/caching/codeCache";
import { useEntityJoinOptimization } from "@/lib/hooks/useEntityJoinOptimization";
import { Button } from "@/components/ui/button";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import {
ChevronLeft,
ChevronRight,
ChevronsLeft,
ChevronsRight,
RefreshCw,
ArrowUpDown,
ArrowUp,
ArrowDown,
TableIcon,
} from "lucide-react";
import { Checkbox } from "@/components/ui/checkbox";
import { cn } from "@/lib/utils";
import { AdvancedSearchFilters } from "@/components/screen/filters/AdvancedSearchFilters";
import { Separator } from "@/components/ui/separator";
import { SingleTableWithSticky } from "./SingleTableWithSticky";
export interface TableListComponentProps {
component: any;
isDesignMode?: boolean;
isSelected?: boolean;
isInteractive?: boolean;
onClick?: () => void;
onDragStart?: (e: React.DragEvent) => void;
onDragEnd?: (e: React.DragEvent) => void;
className?: string;
style?: React.CSSProperties;
formData?: Record<string, any>;
onFormDataChange?: (data: any) => void;
config?: TableListConfig;
// 추가 props (DOM에 전달되지 않음)
size?: { width: number; height: number };
position?: { x: number; y: number; z?: number };
componentConfig?: any;
selectedScreen?: any;
onZoneComponentDrop?: any;
onZoneClick?: any;
tableName?: string;
onRefresh?: () => void;
onClose?: () => void;
screenId?: string;
// 선택된 행 정보 전달 핸들러
onSelectedRowsChange?: (selectedRows: any[], selectedRowsData: any[]) => void;
// 테이블 새로고침 키
refreshKey?: number;
}
/**
* TableList 컴포넌트
* 데이터베이스 테이블의 데이터를 목록으로 표시하는 컴포넌트
*/
export const TableListComponent: React.FC<TableListComponentProps> = ({
component,
isDesignMode = false,
isSelected = false,
onClick,
onDragStart,
onDragEnd,
config,
className,
style,
onFormDataChange,
componentConfig,
onSelectedRowsChange,
refreshKey,
}) => {
// 컴포넌트 설정
const tableConfig = {
...config,
...component.config,
...componentConfig,
} as TableListConfig;
// 🎯 디버깅: 초기 컬럼 설정 확인
console.log(
"🔍 초기 tableConfig.columns:",
tableConfig.columns?.map((c) => c.columnName),
);
// 상태 관리
const [data, setData] = useState<Record<string, any>[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [currentPage, setCurrentPage] = useState(1);
const [totalPages, setTotalPages] = useState(0);
const [totalItems, setTotalItems] = useState(0);
const [searchTerm] = useState("");
const [sortColumn, setSortColumn] = useState<string | null>(null);
const [sortDirection, setSortDirection] = useState<"asc" | "desc">("asc");
const [columnLabels, setColumnLabels] = useState<Record<string, string>>({});
const [tableLabel, setTableLabel] = useState<string>("");
const [localPageSize, setLocalPageSize] = useState<number>(tableConfig.pagination?.pageSize || 20); // 로컬 페이지 크기 상태
const [displayColumns, setDisplayColumns] = useState<ColumnConfig[]>([]); // 🎯 표시할 컬럼 (Entity 조인 적용됨)
// 🎯 조인 컬럼 매핑 상태
const [joinColumnMapping, setJoinColumnMapping] = useState<Record<string, string>>({});
const [columnMeta, setColumnMeta] = useState<Record<string, { webType?: string; codeCategory?: string }>>({}); // 🎯 컬럼 메타정보 (웹타입, 코드카테고리)
// 고급 필터 관련 state
const [searchValues, setSearchValues] = useState<Record<string, any>>({});
// 체크박스 상태 관리
const [selectedRows, setSelectedRows] = useState<Set<string>>(new Set()); // 선택된 행들의 키 집합
const [isAllSelected, setIsAllSelected] = useState(false); // 전체 선택 상태
// 🎯 Entity 조인 최적화 훅 사용
const { optimizedConvertCode } = useEntityJoinOptimization(columnMeta, {
enableBatchLoading: true,
preloadCommonCodes: true,
maxBatchSize: 5,
});
// 높이 계산 함수 (메모이제이션)
const optimalHeight = useMemo(() => {
// 50개 이상일 때는 20개 기준으로 높이 고정하고 스크롤 생성
// 50개 미만일 때는 실제 데이터 개수에 맞춰서 스크롤 없이 표시
const actualDataCount = Math.min(data.length, localPageSize);
const displayPageSize = localPageSize >= 50 ? 20 : Math.max(actualDataCount, 5);
const headerHeight = 50; // 테이블 헤더
const rowHeight = 42; // 각 행 높이
const searchHeight = tableConfig.filter?.enabled ? 80 : 0; // 검색 영역
const footerHeight = tableConfig.showFooter ? 60 : 0; // 페이지네이션
const titleHeight = tableConfig.showHeader ? 60 : 0; // 제목 영역
const padding = 40; // 여백
const calculatedHeight =
titleHeight + searchHeight + headerHeight + displayPageSize * rowHeight + footerHeight + padding;
console.log("🔍 테이블 높이 계산:", {
actualDataCount,
localPageSize,
displayPageSize,
willHaveScroll: localPageSize >= 50,
titleHeight,
searchHeight,
headerHeight,
rowHeight,
footerHeight,
padding,
calculatedHeight,
finalHeight: `${calculatedHeight}px`,
});
// 추가 디버깅: 실제 데이터 상황
console.log("🔍 실제 데이터 상황:", {
actualDataLength: data.length,
localPageSize,
currentPage,
totalItems,
totalPages,
});
return calculatedHeight;
}, [data.length, localPageSize, tableConfig.filter?.enabled, tableConfig.showFooter, tableConfig.showHeader]);
// 스타일 계산
const componentStyle: React.CSSProperties = {
width: "100%",
height: `${optimalHeight}px`, // 20개 데이터를 모두 보여주는 높이
minHeight: `${optimalHeight}px`, // 최소 높이 보장
...component.style,
...style,
display: "flex",
flexDirection: "column",
boxSizing: "border-box", // 패딩/보더 포함한 크기 계산
};
// 디자인 모드 스타일
if (isDesignMode) {
componentStyle.border = "1px dashed #cbd5e1";
componentStyle.borderColor = isSelected ? "#3b82f6" : "#cbd5e1";
// minHeight 제거 - 실제 데이터에 맞는 높이 사용
}
// 컬럼 라벨 정보 가져오기
const fetchColumnLabels = async () => {
if (!tableConfig.selectedTable) return;
try {
const response = await tableTypeApi.getColumns(tableConfig.selectedTable);
// API 응답 구조 확인 및 컬럼 배열 추출
const columns = Array.isArray(response) ? response : (response as any).columns || [];
const labels: Record<string, string> = {};
const meta: Record<string, { webType?: string; codeCategory?: string }> = {};
columns.forEach((column: any) => {
// 🎯 Entity 조인된 컬럼의 경우 표시 컬럼명 사용
let displayLabel = column.displayName || column.columnName;
// Entity 타입인 경우
if (column.webType === "entity") {
// 우선 기준 테이블의 컬럼 라벨을 사용
displayLabel = column.displayName || column.columnName;
console.log(
`🎯 Entity 조인 컬럼 라벨 설정: ${column.columnName} → "${displayLabel}" (기준 테이블 라벨 사용)`,
);
}
labels[column.columnName] = displayLabel;
// 🎯 웹타입과 코드카테고리 정보 저장
meta[column.columnName] = {
webType: column.webType,
codeCategory: column.codeCategory,
};
});
setColumnLabels(labels);
setColumnMeta(meta);
console.log("🔍 컬럼 라벨 설정 완료:", labels);
console.log("🔍 컬럼 메타정보 설정 완료:", meta);
} catch (error) {
console.log("컬럼 라벨 정보를 가져올 수 없습니다:", error);
}
};
// 🎯 전역 코드 캐시 사용으로 함수 제거 (codeCache.convertCodeToName 사용)
// 테이블 라벨명 가져오기
const fetchTableLabel = async () => {
if (!tableConfig.selectedTable) return;
try {
const tables = await tableTypeApi.getTables();
const table = tables.find((t: any) => t.tableName === tableConfig.selectedTable);
if (table && table.displayName && table.displayName !== table.tableName) {
setTableLabel(table.displayName);
} else {
setTableLabel(tableConfig.selectedTable);
}
} catch (error) {
console.log("테이블 라벨 정보를 가져올 수 없습니다:", error);
setTableLabel(tableConfig.selectedTable);
}
};
// 테이블 데이터 가져오기
const fetchTableData = async () => {
if (!tableConfig.selectedTable) {
setData([]);
return;
}
setLoading(true);
setError(null);
try {
// 🎯 Entity 조인 API 사용 - Entity 조인이 포함된 데이터 조회
console.log("🔗 Entity 조인 데이터 조회 시작:", tableConfig.selectedTable);
// Entity 조인 컬럼 추출 (isEntityJoin === true인 컬럼들)
const entityJoinColumns = tableConfig.columns?.filter((col) => col.isEntityJoin && col.entityJoinInfo) || [];
// 🎯 조인 탭에서 추가한 컬럼들도 포함 (실제로 존재하는 컬럼만)
const joinTabColumns =
tableConfig.columns?.filter(
(col) =>
!col.isEntityJoin &&
col.columnName.includes("_") &&
(col.columnName.includes("dept_code_") ||
col.columnName.includes("_dept_code") ||
col.columnName.includes("_company_") ||
col.columnName.includes("_user_")), // 조인 탭에서 추가한 컬럼 패턴들
) || [];
console.log(
"🔍 조인 탭 컬럼들:",
joinTabColumns.map((c) => c.columnName),
);
const additionalJoinColumns = [
...entityJoinColumns.map((col) => ({
sourceTable: col.entityJoinInfo!.sourceTable,
sourceColumn: col.entityJoinInfo!.sourceColumn,
joinAlias: col.entityJoinInfo!.joinAlias,
})),
// 🎯 조인 탭에서 추가한 컬럼들도 추가 (실제로 존재하는 컬럼만)
...joinTabColumns
.filter((col) => {
// 조인 컬럼인지 확인 (언더스코어가 포함된 컬럼)
const isJoinColumn = col.columnName.includes("_") && col.columnName !== "__checkbox__";
if (!isJoinColumn) {
console.log(`🔍 조인 탭 컬럼 제외: ${col.columnName} (조인 컬럼이 아님)`);
}
return isJoinColumn;
})
.map((col) => {
// 동적으로 조인 컬럼 정보 추출
console.log(`🔍 조인 컬럼 분석: ${col.columnName}`);
// 컬럼명에서 기본 컬럼과 참조 테이블 추출
// 예: dept_code_company_name -> dept_code (기본), company_name (참조)
const parts = col.columnName.split("_");
let sourceColumn = "";
let referenceTable = "";
// dept_code로 시작하는 경우
if (col.columnName.startsWith("dept_code_")) {
sourceColumn = "dept_code";
referenceTable = "dept_info";
}
// 다른 패턴들도 추가 가능
else {
// 기본적으로 첫 번째 부분을 소스 컬럼으로 사용
sourceColumn = parts[0];
referenceTable = tableConfig.selectedTable || "unknown";
}
console.log(`🔗 조인 설정: ${col.columnName} -> ${sourceColumn} (${referenceTable})`);
return {
sourceTable: referenceTable,
sourceColumn: sourceColumn,
joinAlias: col.columnName,
};
}),
];
// 🎯 화면별 엔티티 표시 설정 생성
const screenEntityConfigs: Record<string, any> = {};
entityJoinColumns.forEach((col) => {
if (col.entityDisplayConfig) {
const sourceColumn = col.entityJoinInfo!.sourceColumn;
screenEntityConfigs[sourceColumn] = {
displayColumns: col.entityDisplayConfig.displayColumns,
separator: col.entityDisplayConfig.separator || " - ",
};
}
});
console.log("🔗 Entity 조인 컬럼:", entityJoinColumns);
console.log("🔗 조인 탭 컬럼:", joinTabColumns);
console.log("🔗 추가 Entity 조인 컬럼:", additionalJoinColumns);
console.log("🎯 화면별 엔티티 설정:", screenEntityConfigs);
const result = await entityJoinApi.getTableDataWithJoins(tableConfig.selectedTable, {
page: currentPage,
size: localPageSize,
search: (() => {
// 고급 필터 값이 있으면 우선 사용
const hasAdvancedFilters = Object.values(searchValues).some((value) => {
if (typeof value === "string") return value.trim() !== "";
if (typeof value === "object" && value !== null) {
return Object.values(value).some((v) => v !== "" && v !== null && v !== undefined);
}
return value !== null && value !== undefined && value !== "";
});
if (hasAdvancedFilters) {
console.log("🔍 고급 검색 필터 사용:", searchValues);
console.log("🔍 고급 검색 필터 상세:", JSON.stringify(searchValues, null, 2));
return searchValues;
}
// 고급 필터가 없으면 기존 단순 검색 사용
if (searchTerm?.trim()) {
// 스마트한 단일 컬럼 선택 로직 (서버가 OR 검색을 지원하지 않음)
let searchColumn = sortColumn; // 정렬된 컬럼 우선
if (!searchColumn) {
// 1순위: name 관련 컬럼 (가장 검색에 적합)
const nameColumns = visibleColumns.filter(
(col) =>
col.columnName.toLowerCase().includes("name") ||
col.columnName.toLowerCase().includes("title") ||
col.columnName.toLowerCase().includes("subject"),
);
// 2순위: text/varchar 타입 컬럼
const textColumns = visibleColumns.filter((col) => col.dataType === "text" || col.dataType === "varchar");
// 3순위: description 관련 컬럼
const descColumns = visibleColumns.filter(
(col) =>
col.columnName.toLowerCase().includes("desc") ||
col.columnName.toLowerCase().includes("comment") ||
col.columnName.toLowerCase().includes("memo"),
);
// 우선순위에 따라 선택
if (nameColumns.length > 0) {
searchColumn = nameColumns[0].columnName;
} else if (textColumns.length > 0) {
searchColumn = textColumns[0].columnName;
} else if (descColumns.length > 0) {
searchColumn = descColumns[0].columnName;
} else {
// 마지막 대안: 첫 번째 컬럼
searchColumn = visibleColumns[0]?.columnName || "id";
}
}
console.log("🔍 기존 검색 방식 사용:", { [searchColumn]: searchTerm });
return { [searchColumn]: searchTerm };
}
return undefined;
})(),
sortBy: sortColumn || undefined,
sortOrder: sortDirection,
enableEntityJoin: true, // 🎯 Entity 조인 활성화
additionalJoinColumns: additionalJoinColumns.length > 0 ? additionalJoinColumns : undefined, // 추가 조인 컬럼
screenEntityConfigs: Object.keys(screenEntityConfigs).length > 0 ? screenEntityConfigs : undefined, // 🎯 화면별 엔티티 설정
});
if (result) {
console.log("🎯 API 응답 결과:", result);
console.log("🎯 데이터 개수:", result.data?.length || 0);
console.log("🎯 전체 페이지:", result.totalPages);
console.log("🎯 총 아이템:", result.total);
// 🚨 데이터 샘플 확인 (첫 번째 행의 모든 컬럼과 값)
if (result.data && result.data.length > 0) {
console.log("🔍 첫 번째 행 데이터 샘플:", result.data[0]);
Object.entries(result.data[0]).forEach(([key, value]) => {
console.log(` 📊 ${key}: "${value}" (타입: ${typeof value})`);
});
}
setData(result.data || []);
setTotalPages(result.totalPages || 1);
setTotalItems(result.total || 0);
// 🎯 Entity 조인 정보 로깅
if (result.entityJoinInfo) {
console.log("🔗 Entity 조인 적용됨:", {
strategy: result.entityJoinInfo.strategy,
joinConfigs: result.entityJoinInfo.joinConfigs,
performance: result.entityJoinInfo.performance,
});
} else {
console.log("🔗 Entity 조인 없음");
}
// 🎯 코드 컬럼들의 캐시 미리 로드 (전역 캐시 사용)
const codeColumns = Object.entries(columnMeta).filter(
([, meta]) => meta.webType === "code" && meta.codeCategory,
);
if (codeColumns.length > 0) {
console.log(
"📋 코드 컬럼 감지:",
codeColumns.map(([col, meta]) => `${col}(${meta.codeCategory})`),
);
// 필요한 코드 카테고리들을 추출하여 배치 로드
const categoryList = codeColumns.map(([, meta]) => meta.codeCategory).filter(Boolean) as string[];
try {
await codeCache.preloadCodes(categoryList);
console.log("📋 모든 코드 캐시 로드 완료 (전역 캐시)");
} catch (error) {
console.error("❌ 코드 캐시 로드 중 오류:", error);
}
}
// 🎯 Entity 조인된 컬럼 처리 - 사용자가 설정한 컬럼들만 사용
let processedColumns = [...(tableConfig.columns || [])];
// 초기 컬럼이 있으면 먼저 설정
if (processedColumns.length > 0) {
console.log(
"🔍 사용자 설정 컬럼들:",
processedColumns.map((c) => c.columnName),
);
// 🎯 API 응답과 비교하여 존재하지 않는 컬럼 필터링
if (result.data.length > 0) {
const actualApiColumns = Object.keys(result.data[0]);
console.log("🔍 API 응답의 실제 컬럼들:", actualApiColumns);
// 🎯 조인 컬럼 매핑 테이블 동적 생성 (사용자 설정 → API 응답)
const newJoinColumnMapping: Record<string, string> = {};
// 사용자가 설정한 컬럼들과 실제 API 응답 컬럼들을 동적으로 매핑
processedColumns.forEach((userColumn) => {
// 체크박스는 제외
if (userColumn.columnName === "__checkbox__") return;
console.log(`🔍 컬럼 매핑 분석: "${userColumn.columnName}"`, {
displayName: userColumn.displayName,
isEntityJoin: userColumn.isEntityJoin,
entityJoinInfo: userColumn.entityJoinInfo,
available: actualApiColumns,
});
// 사용자 설정 컬럼명이 API 응답에 정확히 있는지 확인
if (actualApiColumns.includes(userColumn.columnName)) {
// 직접 매칭되는 경우
newJoinColumnMapping[userColumn.columnName] = userColumn.columnName;
console.log(`✅ 정확 매핑: ${userColumn.columnName}${userColumn.columnName}`);
} else {
// Entity 조인된 컬럼이거나 조인 탭에서 추가한 컬럼인 경우
let foundMatch = false;
// 1. Entity 조인 정보가 있는 경우 aliasColumn 우선 확인
if (userColumn.entityJoinInfo?.joinAlias) {
const aliasColumn = userColumn.entityJoinInfo.joinAlias;
if (actualApiColumns.includes(aliasColumn)) {
newJoinColumnMapping[userColumn.columnName] = aliasColumn;
console.log(`🔗 Entity 별칭 매핑: ${userColumn.columnName}${aliasColumn}`);
foundMatch = true;
}
}
// 2. 정확한 이름 매칭 (예: dept_code_company_name)
if (!foundMatch) {
const exactMatches = actualApiColumns.filter((apiCol) => apiCol === userColumn.columnName);
if (exactMatches.length > 0) {
newJoinColumnMapping[userColumn.columnName] = exactMatches[0];
console.log(`🎯 정확 이름 매핑: ${userColumn.columnName}${exactMatches[0]}`);
foundMatch = true;
}
}
// 3. 조인 컬럼 검증 및 처리
if (!foundMatch) {
// 🚨 조인 컬럼인지 확인 (더 정확한 감지 로직)
const hasUnderscore = userColumn.columnName.includes("_");
let isJoinColumn = false;
let baseColumnName = "";
if (hasUnderscore) {
// 가능한 모든 기본 컬럼명을 확인 (dept_code_company_name -> dept_code, dept 순으로)
const parts = userColumn.columnName.split("_");
for (let i = parts.length - 1; i >= 1; i--) {
const possibleBase = parts.slice(0, i).join("_");
if (actualApiColumns.includes(possibleBase)) {
baseColumnName = possibleBase;
isJoinColumn = true;
break;
}
}
}
console.log(`🔍 조인 컬럼 검사: "${userColumn.columnName}"`, {
hasUnderscore,
baseColumnName,
isJoinColumn,
});
if (isJoinColumn) {
console.log(`🔍 조인 컬럼 기본 컬럼 확인: "${baseColumnName}"`, {
existsInApi: actualApiColumns.includes(baseColumnName),
actualApiColumns: actualApiColumns.slice(0, 10), // 처음 10개만 표시
});
console.warn(
`⚠️ 조인 실패: "${userColumn.columnName}" - 백엔드에서 Entity 조인이 실행되지 않음. 기본 컬럼값 표시합니다.`,
);
// 조인 실패 시 기본 컬럼값을 표시하도록 매핑
newJoinColumnMapping[userColumn.columnName] = baseColumnName;
foundMatch = true;
} else {
// 일반 컬럼인 경우 부분 매칭 시도
const partialMatches = actualApiColumns.filter(
(apiCol) => apiCol.includes(userColumn.columnName) || userColumn.columnName.includes(apiCol),
);
if (partialMatches.length > 0) {
const bestMatch = partialMatches.reduce((best, current) =>
Math.abs(current.length - userColumn.columnName.length) <
Math.abs(best.length - userColumn.columnName.length)
? current
: best,
);
newJoinColumnMapping[userColumn.columnName] = bestMatch;
console.log(`🔍 부분 매핑: ${userColumn.columnName}${bestMatch}`);
foundMatch = true;
}
}
}
// 4. 매칭 실패한 경우 원본 유지 (하지만 경고 표시)
if (!foundMatch) {
newJoinColumnMapping[userColumn.columnName] = userColumn.columnName;
console.warn(
`⚠️ 매핑 실패: "${userColumn.columnName}" - 사용 가능한 컬럼: [${actualApiColumns.join(", ")}]`,
);
}
}
});
// 🎯 조인 컬럼 매핑 상태 업데이트
setJoinColumnMapping(newJoinColumnMapping);
console.log("🔍 조인 컬럼 매핑 테이블:", newJoinColumnMapping);
console.log("🔍 실제 API 응답 컬럼들:", actualApiColumns);
// 🎯 컬럼명 매핑 및 유효성 검사
const validColumns = processedColumns
.map((col) => {
// 체크박스는 그대로 유지
if (col.columnName === "__checkbox__") return col;
// 조인 컬럼 매핑 적용
const mappedColumnName = newJoinColumnMapping[col.columnName] || col.columnName;
console.log(`🔍 컬럼 매핑 처리: ${col.columnName}${mappedColumnName}`);
// API 응답에 존재하는지 확인
const existsInApi = actualApiColumns.includes(mappedColumnName);
if (!existsInApi) {
console.log(`🔍 제거될 컬럼: ${col.columnName}${mappedColumnName} (API에 존재하지 않음)`);
return null;
}
// 컬럼명이 변경된 경우 업데이트
if (mappedColumnName !== col.columnName) {
console.log(`🔄 컬럼명 매핑: ${col.columnName}${mappedColumnName}`);
return {
...col,
columnName: mappedColumnName,
};
}
console.log(`✅ 컬럼 유지: ${col.columnName}`);
return col;
})
.filter((col) => col !== null) as ColumnConfig[];
if (validColumns.length !== processedColumns.length) {
console.log(
"🔍 필터링된 컬럼들:",
validColumns.map((c) => c.columnName),
);
console.log(
"🔍 제거된 컬럼들:",
processedColumns
.filter((col) => {
const mappedName = newJoinColumnMapping[col.columnName] || col.columnName;
return !actualApiColumns.includes(mappedName) && col.columnName !== "__checkbox__";
})
.map((c) => c.columnName),
);
processedColumns = validColumns;
}
}
}
if (result.entityJoinInfo?.joinConfigs) {
result.entityJoinInfo.joinConfigs.forEach((joinConfig) => {
// 원본 컬럼을 조인된 컬럼으로 교체
let originalColumnIndex = processedColumns.findIndex((col) => col.columnName === joinConfig.sourceColumn);
if (originalColumnIndex !== -1) {
console.log(`🔄 컬럼 교체: ${joinConfig.sourceColumn}${joinConfig.aliasColumn}`);
const originalColumn = processedColumns[originalColumnIndex];
// 🚨 중복 방지: 이미 같은 aliasColumn이 있는지 확인
const existingAliasIndex = processedColumns.findIndex((col) => col.columnName === joinConfig.aliasColumn);
if (existingAliasIndex !== -1 && existingAliasIndex !== originalColumnIndex) {
console.warn(`🚨 중복 컬럼 발견: ${joinConfig.aliasColumn}이 이미 존재합니다. 중복 제거합니다.`);
processedColumns.splice(existingAliasIndex, 1);
// 인덱스 재조정
if (existingAliasIndex < originalColumnIndex) {
originalColumnIndex--;
}
}
processedColumns[originalColumnIndex] = {
...originalColumn,
columnName: joinConfig.aliasColumn, // dept_code → dept_code_name
displayName:
columnLabels[originalColumn.columnName] || originalColumn.displayName || originalColumn.columnName, // 올바른 라벨 사용
// isEntityJoined: true, // 🎯 임시 주석 처리 (타입 에러 해결 후 복원)
} as ColumnConfig;
console.log(
`✅ 조인 컬럼 라벨 유지: ${joinConfig.sourceColumn} → "${columnLabels[originalColumn.columnName] || originalColumn.displayName || originalColumn.columnName}"`,
);
}
});
}
// 🎯 컬럼 설정이 없으면 API 응답 기반으로 생성
if ((!processedColumns || processedColumns.length === 0) && result.data.length > 0) {
const autoColumns: ColumnConfig[] = Object.keys(result.data[0]).map((key, index) => ({
columnName: key,
displayName: columnLabels[key] || key,
visible: true,
sortable: true,
searchable: true,
align: "left",
format: "text",
order: index,
}));
console.log(
"🎯 자동 생성된 컬럼들:",
autoColumns.map((c) => c.columnName),
);
// 컴포넌트 설정 업데이트 (부모 컴포넌트에 알림)
if (onFormDataChange) {
onFormDataChange({
...component,
config: {
...tableConfig,
columns: autoColumns,
},
});
}
processedColumns = autoColumns;
}
// 🚨 processedColumns에서 중복 제거
const uniqueProcessedColumns = processedColumns.filter(
(column, index, self) => self.findIndex((c) => c.columnName === column.columnName) === index,
);
if (uniqueProcessedColumns.length !== processedColumns.length) {
console.error("🚨 processedColumns에서 중복 발견:");
console.error(
"원본:",
processedColumns.map((c) => c.columnName),
);
console.error(
"중복 제거 후:",
uniqueProcessedColumns.map((c) => c.columnName),
);
}
// 🎯 표시할 컬럼 상태 업데이트
setDisplayColumns(uniqueProcessedColumns);
console.log("🎯 displayColumns 업데이트됨:", uniqueProcessedColumns);
console.log("🎯 데이터 개수:", result.data?.length || 0);
console.log("🎯 전체 데이터:", result.data);
}
} catch (err) {
console.error("테이블 데이터 로딩 오류:", err);
setError(err instanceof Error ? err.message : "데이터를 불러오는 중 오류가 발생했습니다.");
setData([]);
} finally {
setLoading(false);
}
};
// 페이지 변경
const handlePageChange = (newPage: number) => {
setCurrentPage(newPage);
};
// 정렬 변경
const handleSort = (column: string) => {
if (sortColumn === column) {
setSortDirection(sortDirection === "asc" ? "desc" : "asc");
} else {
setSortColumn(column);
setSortDirection("asc");
}
};
// 고급 필터 핸들러
const handleSearchValueChange = (columnName: string, value: any) => {
setSearchValues((prev) => ({
...prev,
[columnName]: value,
}));
};
const handleAdvancedSearch = () => {
setCurrentPage(1);
fetchTableData();
};
const handleClearAdvancedFilters = () => {
setSearchValues({});
setCurrentPage(1);
fetchTableData();
};
// 새로고침
const handleRefresh = () => {
fetchTableData();
};
// 체크박스 핸들러들
const getRowKey = (row: any, index: number) => {
// 기본키가 있으면 사용, 없으면 인덱스 사용
return row.id || row.objid || row.pk || index.toString();
};
const handleRowSelection = (rowKey: string, checked: boolean) => {
const newSelectedRows = new Set(selectedRows);
if (checked) {
newSelectedRows.add(rowKey);
} else {
newSelectedRows.delete(rowKey);
}
setSelectedRows(newSelectedRows);
setIsAllSelected(newSelectedRows.size === data.length && data.length > 0);
// 선택된 실제 데이터를 상위 컴포넌트로 전달
const selectedKeys = Array.from(newSelectedRows);
const selectedData = selectedKeys
.map((key) => {
// rowKey를 사용하여 데이터 찾기 (ID 기반 또는 인덱스 기반)
return data.find((row, index) => {
const currentRowKey = getRowKey(row, index);
return currentRowKey === key;
});
})
.filter(Boolean);
console.log("🔍 handleRowSelection 디버그:", {
rowKey,
checked,
selectedKeys,
selectedData,
dataCount: data.length,
});
onSelectedRowsChange?.(selectedKeys, selectedData);
if (tableConfig.onSelectionChange) {
tableConfig.onSelectionChange(selectedData);
}
};
const handleSelectAll = (checked: boolean) => {
if (checked) {
const allKeys = data.map((row, index) => getRowKey(row, index));
setSelectedRows(new Set(allKeys));
setIsAllSelected(true);
// 선택된 실제 데이터를 상위 컴포넌트로 전달
onSelectedRowsChange?.(allKeys, data);
if (tableConfig.onSelectionChange) {
tableConfig.onSelectionChange(data);
}
} else {
setSelectedRows(new Set());
setIsAllSelected(false);
// 빈 선택을 상위 컴포넌트로 전달
onSelectedRowsChange?.([], []);
if (tableConfig.onSelectionChange) {
tableConfig.onSelectionChange([]);
}
}
};
// 효과
useEffect(() => {
if (tableConfig.selectedTable) {
fetchColumnLabels();
fetchTableLabel();
}
}, [tableConfig.selectedTable]);
// 컬럼 라벨이 로드되면 기존 컬럼의 displayName을 업데이트
useEffect(() => {
if (Object.keys(columnLabels).length > 0 && tableConfig.columns && tableConfig.columns.length > 0) {
const updatedColumns = tableConfig.columns.map((col) => ({
...col,
displayName: columnLabels[col.columnName] || col.displayName,
}));
// 부모 컴포넌트에 업데이트된 컬럼 정보 전달
if (onFormDataChange) {
onFormDataChange({
...component,
componentConfig: {
...tableConfig,
columns: updatedColumns,
},
});
}
}
}, [columnLabels]);
useEffect(() => {
if (tableConfig.autoLoad && !isDesignMode) {
fetchTableData();
}
}, [
tableConfig.selectedTable,
localPageSize,
currentPage,
searchTerm,
sortColumn,
sortDirection,
columnLabels,
searchValues,
]);
// refreshKey 변경 시 테이블 데이터 새로고침
useEffect(() => {
if (refreshKey && refreshKey > 0 && !isDesignMode) {
console.log("🔄 refreshKey 변경 감지, 테이블 데이터 새로고침:", refreshKey);
// 선택된 행 상태 초기화
setSelectedRows(new Set());
setIsAllSelected(false);
// 부모 컴포넌트에 빈 선택 상태 전달
console.log("🔄 선택 상태 초기화 - 빈 배열 전달");
onSelectedRowsChange?.([], []);
// 테이블 데이터 새로고침
fetchTableData();
}
}, [refreshKey]);
// 표시할 컬럼 계산 (Entity 조인 적용됨 + 체크박스 컬럼 추가 + 숨김 기능)
const visibleColumns = useMemo(() => {
// 기본값 처리: checkbox 설정이 없으면 기본값 사용
const checkboxConfig = tableConfig.checkbox || {
enabled: true,
multiple: true,
position: "left",
selectAll: true,
};
let columns: ColumnConfig[] = [];
// displayColumns가 있으면 우선 사용 (Entity 조인 적용된 컬럼들)
if (displayColumns && displayColumns.length > 0) {
console.log("🎯 displayColumns 사용:", displayColumns);
const filteredColumns = displayColumns.filter((col) => {
// 디자인 모드에서는 숨김 컬럼도 표시 (연하게), 실제 화면에서는 완전히 숨김
if (isDesignMode) {
return col.visible; // 디자인 모드에서는 visible만 체크
} else {
return col.visible && !col.hidden; // 실제 화면에서는 visible이면서 hidden이 아닌 것만
}
});
console.log("🎯 필터링된 컬럼:", filteredColumns);
columns = filteredColumns.sort((a, b) => a.order - b.order);
} else if (tableConfig.columns && tableConfig.columns.length > 0) {
// displayColumns가 없으면 기본 컬럼 사용
console.log("🎯 tableConfig.columns 사용:", tableConfig.columns);
columns = tableConfig.columns
.filter((col) => {
// 디자인 모드에서는 숨김 컬럼도 표시 (연하게), 실제 화면에서는 완전히 숨김
if (isDesignMode) {
return col.visible; // 디자인 모드에서는 visible만 체크
} else {
return col.visible && !col.hidden; // 실제 화면에서는 visible이면서 hidden이 아닌 것만
}
})
.sort((a, b) => a.order - b.order);
} else {
console.log("🎯 사용할 컬럼이 없음");
return [];
}
// 체크박스가 활성화되고 실제 데이터 컬럼이 있는 경우에만 체크박스 컬럼을 추가
if (checkboxConfig.enabled && columns.length > 0) {
const checkboxColumn: ColumnConfig = {
columnName: "__checkbox__",
displayName: "",
visible: true,
sortable: false,
searchable: false,
width: 50,
align: "center",
order: -1, // 가장 앞에 위치
fixed: checkboxConfig.position === "left" ? "left" : false,
fixedOrder: 0, // 가장 앞에 고정
};
// 체크박스 위치에 따라 추가
if (checkboxConfig.position === "left") {
columns.unshift(checkboxColumn);
} else {
columns.push(checkboxColumn);
}
}
console.log("🎯 최종 visibleColumns:", columns);
console.log("🎯 visibleColumns 개수:", columns.length);
console.log(
"🎯 visibleColumns 컬럼명들:",
columns.map((c) => c.columnName),
);
// 🚨 중복 키 검사
const columnNames = columns.map((c) => c.columnName);
const duplicates = columnNames.filter((name, index) => columnNames.indexOf(name) !== index);
if (duplicates.length > 0) {
console.error("🚨 중복된 컬럼명 발견:", duplicates);
console.error("🚨 전체 컬럼명 목록:", columnNames);
// 중복 제거
const uniqueColumns = columns.filter(
(column, index, self) => self.findIndex((c) => c.columnName === column.columnName) === index,
);
console.log(
"🔧 중복 제거 후 컬럼들:",
uniqueColumns.map((c) => c.columnName),
);
return uniqueColumns;
}
return columns;
}, [displayColumns, tableConfig.columns, tableConfig.checkbox, isDesignMode]);
// columnsByPosition은 SingleTableWithSticky에서 사용하지 않으므로 제거
// 기존 테이블에서만 필요한 경우 다시 추가 가능
// 가로 스크롤이 필요한지 계산
const needsHorizontalScroll = useMemo(() => {
if (!tableConfig.horizontalScroll?.enabled) {
console.log("🚫 가로 스크롤 비활성화됨");
return false;
}
const maxVisible = tableConfig.horizontalScroll.maxVisibleColumns || 8;
const totalColumns = visibleColumns.length;
const result = totalColumns > maxVisible;
console.log(
`🔍 가로 스크롤 계산: ${totalColumns}개 컬럼 > ${maxVisible}개 최대 = ${result ? "스크롤 필요" : "스크롤 불필요"}`,
);
console.log("📊 가로 스크롤 설정:", tableConfig.horizontalScroll);
console.log(
"📋 현재 컬럼들:",
visibleColumns.map((c) => c.columnName),
);
return result;
}, [visibleColumns.length, tableConfig.horizontalScroll]);
// 컬럼 너비 계산 - 내용 길이에 맞게 자동 조정
const getColumnWidth = (column: ColumnConfig) => {
if (column.width) return column.width;
// 체크박스 컬럼인 경우 고정 너비
if (column.columnName === "__checkbox__") {
return 50;
}
// 컬럼 헤더 텍스트 길이 기반으로 계산
const headerText = columnLabels[column.columnName] || column.displayName || column.columnName;
const headerLength = headerText.length;
// 데이터 셀의 최대 길이 추정 (실제 데이터가 있다면 더 정확하게 계산 가능)
const estimatedContentLength = Math.max(headerLength, 10); // 최소 10자
// 문자당 약 8px 정도로 계산하고, 패딩 및 여백 고려
const calculatedWidth = estimatedContentLength * 8 + 40; // 40px는 패딩과 여백
// 최소 너비만 보장하고, 최대 너비 제한은 제거
const minWidth = 80;
return Math.max(minWidth, calculatedWidth);
};
// 체크박스 헤더 렌더링
const renderCheckboxHeader = () => {
// 기본값 처리: checkbox 설정이 없으면 기본값 사용
const checkboxConfig = tableConfig.checkbox || {
enabled: true,
multiple: true,
position: "left",
selectAll: true,
};
if (!checkboxConfig.enabled || !checkboxConfig.selectAll) {
return null;
}
return <Checkbox checked={isAllSelected} onCheckedChange={handleSelectAll} aria-label="전체 선택" />;
};
// 체크박스 셀 렌더링
const renderCheckboxCell = (row: any, index: number) => {
// 기본값 처리: checkbox 설정이 없으면 기본값 사용
const checkboxConfig = tableConfig.checkbox || {
enabled: true,
multiple: true,
position: "left",
selectAll: true,
};
if (!checkboxConfig.enabled) {
return null;
}
const rowKey = getRowKey(row, index);
const isSelected = selectedRows.has(rowKey);
return (
<Checkbox
checked={isSelected}
onCheckedChange={(checked) => handleRowSelection(rowKey, checked as boolean)}
aria-label={`${index + 1} 선택`}
/>
);
};
// 🎯 값 포맷팅 (전역 코드 캐시 사용)
const formatCellValue = useMemo(() => {
return (value: any, format?: string, columnName?: string) => {
if (value === null || value === undefined) return "";
// 디버깅: 모든 값 변환 시도를 로깅
if (
columnName &&
(columnName === "contract_type" || columnName === "domestic_foreign" || columnName === "status")
) {
console.log(`🔍 값 변환 시도: ${columnName}="${value}"`, {
columnMeta: columnMeta[columnName],
hasColumnMeta: !!columnMeta[columnName],
webType: columnMeta[columnName]?.webType,
codeCategory: columnMeta[columnName]?.codeCategory,
globalColumnMeta: Object.keys(columnMeta),
});
}
// 🎯 코드 컬럼인 경우 최적화된 코드명 변환 사용
if (columnName && columnMeta[columnName]?.webType === "code" && columnMeta[columnName]?.codeCategory) {
const categoryCode = columnMeta[columnName].codeCategory!;
const convertedValue = optimizedConvertCode(categoryCode, String(value));
if (convertedValue !== String(value)) {
console.log(`🔄 코드 변환 성공: ${columnName}[${categoryCode}] ${value}${convertedValue}`);
} else {
console.log(`⚠️ 코드 변환 실패: ${columnName}[${categoryCode}] ${value}${convertedValue} (값 동일)`);
}
value = convertedValue;
}
switch (format) {
case "number":
return typeof value === "number" ? value.toLocaleString() : value;
case "currency":
return typeof value === "number" ? `${value.toLocaleString()}` : value;
case "date":
return value instanceof Date ? value.toLocaleDateString() : value;
case "boolean":
return value ? "예" : "아니오";
default:
return String(value);
}
};
}, [columnMeta, optimizedConvertCode]); // 최적화된 변환 함수 의존성 추가
// 이벤트 핸들러
const handleClick = (e: React.MouseEvent) => {
e.stopPropagation();
onClick?.();
};
// 행 클릭 핸들러
const handleRowClick = (row: any) => {
if (tableConfig.onRowClick) {
tableConfig.onRowClick(row);
}
};
// DOM에 전달할 수 있는 기본 props만 정의
const domProps = {
onClick: handleClick,
onDragStart,
onDragEnd,
};
// 디자인 모드에서의 플레이스홀더
if (isDesignMode && !tableConfig.selectedTable) {
return (
<div style={componentStyle} className={className} {...domProps}>
<div className="flex h-full items-center justify-center rounded-lg border-2 border-dashed border-gray-300">
<div className="text-center text-gray-500">
<TableIcon className="mx-auto mb-2 h-8 w-8" />
<div className="text-sm font-medium"> </div>
<div className="text-xs text-gray-400"> </div>
</div>
</div>
</div>
);
}
return (
<div style={componentStyle} className={cn("rounded-lg border bg-white shadow-sm", className)} {...domProps}>
{/* 헤더 */}
{tableConfig.showHeader && (
<div className="flex items-center justify-between border-b p-4">
<div className="flex items-center space-x-4">
{(tableConfig.title || tableLabel) && (
<h3 className="text-lg font-medium">{tableConfig.title || tableLabel}</h3>
)}
</div>
<div className="flex items-center space-x-2">
{/* 선택된 항목 정보 표시 */}
{selectedRows.size > 0 && (
<div className="mr-4 flex items-center space-x-2">
<span className="text-sm text-gray-600">{selectedRows.size} </span>
</div>
)}
{/* 검색 - 기존 방식은 주석처리 */}
{/* {tableConfig.filter?.enabled && tableConfig.filter?.quickSearch && (
<div className="flex items-center space-x-2">
<div className="relative">
<Search className="absolute top-1/2 left-2 h-4 w-4 -translate-y-1/2 transform text-gray-400" />
<Input
placeholder="검색..."
value={searchTerm}
onChange={(e) => handleSearch(e.target.value)}
className="w-64 pl-8"
/>
</div>
{tableConfig.filter?.showColumnSelector && (
<select
value={selectedSearchColumn}
onChange={(e) => setSelectedSearchColumn(e.target.value)}
className="min-w-[120px] rounded border px-2 py-1 text-sm"
>
<option value="">자동 선택</option>
{visibleColumns.map((column) => (
<option key={column.columnName} value={column.columnName}>
{columnLabels[column.columnName] || column.displayName || column.columnName}
</option>
))}
</select>
)}
</div>
)} */}
{/* 새로고침 */}
<Button variant="outline" size="sm" onClick={handleRefresh} disabled={loading}>
<RefreshCw className={cn("h-4 w-4", loading && "animate-spin")} />
</Button>
</div>
</div>
)}
{/* 고급 검색 필터 - 항상 표시 (컬럼 정보 기반 자동 생성) */}
{tableConfig.filter?.enabled && visibleColumns && visibleColumns.length > 0 && (
<>
<Separator className="my-1" />
<AdvancedSearchFilters
filters={tableConfig.filter?.filters || []} // 설정된 필터 사용, 없으면 자동 생성
searchValues={searchValues}
onSearchValueChange={handleSearchValueChange}
onSearch={handleAdvancedSearch}
onClearFilters={handleClearAdvancedFilters}
tableColumns={visibleColumns.map((col) => ({
columnName: col.columnName,
webType: (columnMeta[col.columnName]?.webType as any) || "text",
displayName: columnLabels[col.columnName] || col.displayName || col.columnName,
codeCategory: columnMeta[col.columnName]?.codeCategory,
isVisible: col.visible,
// 추가 메타데이터 전달 (필터 자동 생성용)
web_type: columnMeta[col.columnName]?.webType || "text",
column_name: col.columnName,
column_label: columnLabels[col.columnName] || col.displayName || col.columnName,
code_category: columnMeta[col.columnName]?.codeCategory,
}))}
tableName={tableConfig.selectedTable}
/>
</>
)}
{/* 테이블 컨텐츠 */}
<div className={`w-full ${localPageSize >= 50 ? "flex-1 overflow-auto" : ""}`}>
{loading ? (
<div className="flex h-full items-center justify-center">
<div className="text-center">
<RefreshCw className="mx-auto mb-2 h-8 w-8 animate-spin text-gray-400" />
<div className="text-sm text-gray-500"> ...</div>
</div>
</div>
) : error ? (
<div className="flex h-full items-center justify-center">
<div className="text-center text-red-500">
<div className="text-sm"> </div>
<div className="mt-1 text-xs text-gray-400">{error}</div>
</div>
</div>
) : needsHorizontalScroll ? (
// 가로 스크롤이 필요한 경우 - 단일 테이블에서 sticky 컬럼 사용
<SingleTableWithSticky
visibleColumns={visibleColumns}
data={data}
columnLabels={columnLabels}
sortColumn={sortColumn}
sortDirection={sortDirection}
tableConfig={tableConfig}
isDesignMode={isDesignMode}
isAllSelected={isAllSelected}
handleSort={handleSort}
handleSelectAll={handleSelectAll}
handleRowClick={handleRowClick}
renderCheckboxCell={renderCheckboxCell}
formatCellValue={formatCellValue}
getColumnWidth={getColumnWidth}
joinColumnMapping={joinColumnMapping}
/>
) : (
// 기존 테이블 (가로 스크롤이 필요 없는 경우)
<Table>
<TableHeader className={tableConfig.stickyHeader ? "sticky top-0 z-10 bg-white" : ""}>
<TableRow style={{ minHeight: "40px !important", height: "40px !important", lineHeight: "1" }}>
{visibleColumns.map((column, colIndex) => (
<TableHead
key={`header-${colIndex}-${column.columnName}`}
style={{
width: column.width ? `${column.width}px` : undefined,
minHeight: "40px !important",
height: "40px !important",
verticalAlign: "middle",
lineHeight: "1",
boxSizing: "border-box",
}}
className={cn(
column.columnName === "__checkbox__"
? "h-10 text-center align-middle"
: "h-10 cursor-pointer align-middle whitespace-nowrap select-none",
`text-${column.align}`,
column.sortable && "hover:bg-gray-50",
)}
onClick={() => column.sortable && handleSort(column.columnName)}
>
{column.columnName === "__checkbox__" ? (
renderCheckboxHeader()
) : (
<div className="flex items-center space-x-1">
<span>{columnLabels[column.columnName] || column.displayName}</span>
{column.sortable && (
<div className="flex flex-col">
{sortColumn === column.columnName ? (
sortDirection === "asc" ? (
<ArrowUp className="h-3 w-3" />
) : (
<ArrowDown className="h-3 w-3" />
)
) : (
<ArrowUpDown className="h-3 w-3 text-gray-400" />
)}
</div>
)}
</div>
)}
</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody>
{data.length === 0 ? (
<TableRow>
<TableCell colSpan={visibleColumns.length} className="py-8 text-center text-gray-500">
</TableCell>
</TableRow>
) : (
data.map((row, index) => (
<TableRow
key={`row-${index}-${getRowKey(row, index)}`}
className={cn(
"h-10 cursor-pointer leading-none",
tableConfig.tableStyle?.hoverEffect && "hover:bg-gray-50",
tableConfig.tableStyle?.alternateRows && index % 2 === 1 && "bg-gray-50/50",
)}
style={{ minHeight: "40px", height: "40px", lineHeight: "1" }}
onClick={() => handleRowClick(row)}
>
{visibleColumns.map((column, colIndex) => (
<TableCell
key={`cell-${index}-${colIndex}-${column.columnName}`}
className={cn("h-10 align-middle whitespace-nowrap", `text-${column.align}`)}
style={{ minHeight: "40px", height: "40px", verticalAlign: "middle" }}
>
{column.columnName === "__checkbox__"
? renderCheckboxCell(row, index)
: (() => {
// 🎯 매핑된 컬럼명으로 데이터 찾기
const mappedColumnName = joinColumnMapping[column.columnName] || column.columnName;
// 조인 컬럼 매핑 정보 로깅
if (column.columnName !== mappedColumnName && index === 0) {
console.log(`🔗 조인 컬럼 매핑: ${column.columnName}${mappedColumnName}`);
}
const cellValue = row[mappedColumnName];
if (index === 0) {
// 첫 번째 행만 로그 출력
console.log(`🔍 셀 데이터 [${column.columnName}${mappedColumnName}]:`, cellValue);
// 🚨 조인된 컬럼인 경우 추가 디버깅
if (column.columnName !== mappedColumnName) {
console.log(" 🔗 조인 컬럼 분석:");
console.log(` 👤 사용자 설정 컬럼: "${column.columnName}"`);
console.log(` 📡 매핑된 API 컬럼: "${mappedColumnName}"`);
console.log(` 📋 컬럼 라벨: "${column.displayName}"`);
console.log(` 💾 실제 데이터: "${cellValue}"`);
console.log(
` 🔄 원본 컬럼 데이터 (${column.columnName}): "${row[column.columnName]}"`,
);
}
}
return formatCellValue(cellValue, column.format, column.columnName) || "\u00A0";
})()}
</TableCell>
))}
</TableRow>
))
)}
</TableBody>
</Table>
)}
</div>
{/* 푸터/페이지네이션 */}
{tableConfig.showFooter && tableConfig.pagination?.enabled && (
<div className="flex items-center justify-between border-t p-4">
<div className="text-sm text-gray-500">
{tableConfig.pagination?.showPageInfo && (
<span>
{totalItems.toLocaleString()} {(currentPage - 1) * localPageSize + 1}-
{Math.min(currentPage * localPageSize, totalItems)}
</span>
)}
</div>
<div className="flex items-center space-x-2">
{/* 페이지 크기 선택 */}
{tableConfig.pagination?.showSizeSelector && (
<select
value={localPageSize}
onChange={(e) => {
const newPageSize = parseInt(e.target.value);
// 로컬 상태만 업데이트 (데이터베이스에 저장하지 않음)
setLocalPageSize(newPageSize);
// 페이지를 1로 리셋
setCurrentPage(1);
// 데이터는 useEffect에서 자동으로 다시 로드됨
}}
className="rounded border px-2 py-1 text-sm"
>
{tableConfig.pagination?.pageSizeOptions?.map((size) => (
<option key={size} value={size}>
{size}
</option>
))}
</select>
)}
{/* 페이지네이션 버튼 */}
<div className="flex items-center space-x-1">
<Button variant="outline" size="sm" onClick={() => handlePageChange(1)} disabled={currentPage === 1}>
<ChevronsLeft className="h-4 w-4" />
</Button>
<Button
variant="outline"
size="sm"
onClick={() => handlePageChange(currentPage - 1)}
disabled={currentPage === 1}
>
<ChevronLeft className="h-4 w-4" />
</Button>
<span className="px-3 py-1 text-sm">
{currentPage} / {totalPages}
</span>
<Button
variant="outline"
size="sm"
onClick={() => handlePageChange(currentPage + 1)}
disabled={currentPage === totalPages}
>
<ChevronRight className="h-4 w-4" />
</Button>
<Button
variant="outline"
size="sm"
onClick={() => handlePageChange(totalPages)}
disabled={currentPage === totalPages}
>
<ChevronsRight className="h-4 w-4" />
</Button>
</div>
</div>
</div>
)}
</div>
);
};
/**
* TableList 래퍼 컴포넌트
* 추가적인 로직이나 상태 관리가 필요한 경우 사용
*/
export const TableListWrapper: React.FC<TableListComponentProps> = (props) => {
return <TableListComponent {...props} />;
};