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

665 lines
24 KiB
TypeScript
Raw Normal View History

2025-09-15 11:43:59 +09:00
"use client";
import React, { useState, useEffect, useMemo } from "react";
import { ComponentRendererProps } from "@/types/component";
import { TableListConfig, ColumnConfig, TableDataResponse } from "./types";
import { tableTypeApi } from "@/lib/api/screen";
2025-09-16 15:13:00 +09:00
import { entityJoinApi } from "@/lib/api/entityJoin";
2025-09-15 11:43:59 +09:00
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import {
ChevronLeft,
ChevronRight,
ChevronsLeft,
ChevronsRight,
Search,
RefreshCw,
ArrowUpDown,
ArrowUp,
ArrowDown,
TableIcon,
} from "lucide-react";
import { cn } from "@/lib/utils";
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;
}
/**
* TableList
*
*/
export const TableListComponent: React.FC<TableListComponentProps> = ({
component,
isDesignMode = false,
isSelected = false,
isInteractive = false,
onClick,
onDragStart,
onDragEnd,
config,
className,
style,
formData,
onFormDataChange,
screenId,
size,
position,
componentConfig,
selectedScreen,
onZoneComponentDrop,
onZoneClick,
tableName,
onRefresh,
onClose,
}) => {
// 컴포넌트 설정
const tableConfig = {
...config,
...component.config,
...componentConfig,
} as TableListConfig;
// 상태 관리
const [data, setData] = useState<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, setSearchTerm] = 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 [selectedSearchColumn, setSelectedSearchColumn] = useState<string>(""); // 선택된 검색 컬럼
2025-09-16 15:13:00 +09:00
const [displayColumns, setDisplayColumns] = useState<ColumnConfig[]>([]); // 🎯 표시할 컬럼 (Entity 조인 적용됨)
2025-09-15 11:43:59 +09:00
// 높이 계산 함수
const calculateOptimalHeight = () => {
// 50개 이상일 때는 20개 기준으로 높이 고정
const displayPageSize = localPageSize >= 50 ? 20 : localPageSize;
const headerHeight = 48; // 테이블 헤더
const rowHeight = 40; // 각 행 높이 (normal)
const searchHeight = tableConfig.filter?.enabled ? 48 : 0; // 검색 영역
const footerHeight = tableConfig.showFooter ? 56 : 0; // 페이지네이션
const padding = 8; // 여백
return headerHeight + displayPageSize * rowHeight + searchHeight + footerHeight + padding;
};
// 스타일 계산
const componentStyle: React.CSSProperties = {
width: "100%",
height:
tableConfig.height === "fixed"
? `${tableConfig.fixedHeight || calculateOptimalHeight()}px`
: tableConfig.height === "auto"
? `${calculateOptimalHeight()}px`
: "100%",
...component.style,
...style,
display: "flex",
flexDirection: "column",
};
// 디자인 모드 스타일
if (isDesignMode) {
componentStyle.border = "1px dashed #cbd5e1";
componentStyle.borderColor = isSelected ? "#3b82f6" : "#cbd5e1";
componentStyle.minHeight = "200px";
}
// 컬럼 라벨 정보 가져오기
const fetchColumnLabels = async () => {
if (!tableConfig.selectedTable) return;
try {
const columns = await tableTypeApi.getColumns(tableConfig.selectedTable);
const labels: Record<string, string> = {};
columns.forEach((column: any) => {
labels[column.columnName] = column.displayName || column.columnName;
});
setColumnLabels(labels);
} catch (error) {
console.log("컬럼 라벨 정보를 가져올 수 없습니다:", error);
}
};
// 테이블 라벨명 가져오기
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 {
2025-09-16 15:13:00 +09:00
// 🎯 Entity 조인 API 사용 - Entity 조인이 포함된 데이터 조회
console.log("🔗 Entity 조인 데이터 조회 시작:", tableConfig.selectedTable);
const result = await entityJoinApi.getTableDataWithJoins(tableConfig.selectedTable, {
2025-09-15 11:43:59 +09:00
page: currentPage,
size: localPageSize,
2025-09-16 15:13:00 +09:00
search: searchTerm?.trim()
2025-09-15 11:43:59 +09:00
? (() => {
// 스마트한 단일 컬럼 선택 로직 (서버가 OR 검색을 지원하지 않음)
let searchColumn = selectedSearchColumn || 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);
console.log("🔍 검색어:", searchTerm);
console.log(
"🔍 사용 가능한 컬럼들:",
visibleColumns.map((col) => `${col.columnName}(${col.dataType || "unknown"})`),
);
return { [searchColumn]: searchTerm };
})()
2025-09-16 15:13:00 +09:00
: undefined,
2025-09-15 11:43:59 +09:00
sortBy: sortColumn || undefined,
sortOrder: sortDirection,
2025-09-16 15:13:00 +09:00
enableEntityJoin: true, // 🎯 Entity 조인 활성화
2025-09-15 11:43:59 +09:00
});
if (result) {
setData(result.data || []);
setTotalPages(result.totalPages || 1);
setTotalItems(result.total || 0);
2025-09-16 15:13:00 +09:00
// 🎯 Entity 조인 정보 로깅
if (result.entityJoinInfo) {
console.log("🔗 Entity 조인 적용됨:", {
strategy: result.entityJoinInfo.strategy,
joinConfigs: result.entityJoinInfo.joinConfigs,
performance: result.entityJoinInfo.performance,
});
} else {
console.log("🔗 Entity 조인 없음");
}
// 🎯 Entity 조인된 컬럼 처리
let processedColumns = [...(tableConfig.columns || [])];
// 초기 컬럼이 있으면 먼저 설정
if (processedColumns.length > 0) {
setDisplayColumns(processedColumns);
}
if (result.entityJoinInfo?.joinConfigs) {
result.entityJoinInfo.joinConfigs.forEach((joinConfig) => {
// 원본 컬럼을 조인된 컬럼으로 교체
const originalColumnIndex = processedColumns.findIndex((col) => col.columnName === joinConfig.sourceColumn);
if (originalColumnIndex !== -1) {
console.log(`🔄 컬럼 교체: ${joinConfig.sourceColumn}${joinConfig.aliasColumn}`);
processedColumns[originalColumnIndex] = {
...processedColumns[originalColumnIndex],
columnName: joinConfig.aliasColumn, // dept_code → dept_code_name
displayName: processedColumns[originalColumnIndex].displayName || joinConfig.aliasColumn,
// isEntityJoined: true, // 🎯 임시 주석 처리 (타입 에러 해결 후 복원)
} as ColumnConfig;
}
});
}
2025-09-15 11:43:59 +09:00
// 컬럼 정보가 없으면 첫 번째 데이터 행에서 추출
2025-09-16 15:13:00 +09:00
if ((!processedColumns || processedColumns.length === 0) && result.data.length > 0) {
2025-09-15 11:43:59 +09:00
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,
}));
// 컴포넌트 설정 업데이트 (부모 컴포넌트에 알림)
if (onFormDataChange) {
onFormDataChange({
...component,
config: {
...tableConfig,
columns: autoColumns,
},
});
}
2025-09-16 15:13:00 +09:00
processedColumns = autoColumns;
2025-09-15 11:43:59 +09:00
}
2025-09-16 15:13:00 +09:00
// 🎯 표시할 컬럼 상태 업데이트
setDisplayColumns(processedColumns);
2025-09-15 11:43:59 +09:00
}
} 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 handleSearch = (term: string) => {
setSearchTerm(term);
setCurrentPage(1); // 검색 시 첫 페이지로 이동
};
// 새로고침
const handleRefresh = () => {
fetchTableData();
};
// 효과
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]);
2025-09-16 15:13:00 +09:00
// 표시할 컬럼 계산 (Entity 조인 적용됨)
2025-09-15 11:43:59 +09:00
const visibleColumns = useMemo(() => {
2025-09-16 15:13:00 +09:00
if (!displayColumns || displayColumns.length === 0) {
// displayColumns가 아직 설정되지 않은 경우 기본 컬럼 사용
if (!tableConfig.columns) return [];
return tableConfig.columns.filter((col) => col.visible).sort((a, b) => a.order - b.order);
}
return displayColumns.filter((col) => col.visible).sort((a, b) => a.order - b.order);
}, [displayColumns, tableConfig.columns]);
2025-09-15 11:43:59 +09:00
// 값 포맷팅
const formatCellValue = (value: any, format?: string) => {
if (value === null || value === undefined) return "";
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);
}
};
// 이벤트 핸들러
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">
{/* 검색 */}
{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>
)}
{/* 테이블 컨텐츠 */}
<div className={`flex-1 ${localPageSize >= 50 ? "overflow-auto" : "overflow-hidden"}`}>
{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>
) : (
<Table>
<TableHeader className={tableConfig.stickyHeader ? "sticky top-0 z-10 bg-white" : ""}>
<TableRow>
{visibleColumns.map((column) => (
<TableHead
key={column.columnName}
style={{ width: column.width ? `${column.width}px` : undefined }}
className={cn(
"cursor-pointer select-none",
`text-${column.align}`,
column.sortable && "hover:bg-gray-50",
)}
onClick={() => column.sortable && handleSort(column.columnName)}
>
<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={index}
className={cn(
"cursor-pointer",
tableConfig.tableStyle?.hoverEffect && "hover:bg-gray-50",
tableConfig.tableStyle?.alternateRows && index % 2 === 1 && "bg-gray-50/50",
)}
onClick={() => handleRowClick(row)}
>
{visibleColumns.map((column) => (
<TableCell key={column.columnName} className={`text-${column.align}`}>
{formatCellValue(row[column.columnName], column.format)}
</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} />;
};