ERP-node/frontend/components/v2/config-panels/V2BomItemEditorConfigPanel.tsx

1089 lines
42 KiB
TypeScript

"use client";
/**
* BOM 하위품목 편집기 설정 패널
*
* V2RepeaterConfigPanel 구조를 기반으로 구현:
* - 기본 탭: 저장 테이블 + 엔티티 선택 + 트리 설정 + 기능 옵션
* - 컬럼 탭: 소스 표시 컬럼 + 저장 입력 컬럼 + 선택된 컬럼 상세
*/
import React, { useState, useEffect, useMemo, useCallback } from "react";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { Checkbox } from "@/components/ui/checkbox";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
Database,
Link2,
Trash2,
GripVertical,
ArrowRight,
ChevronDown,
ChevronRight,
Eye,
EyeOff,
Check,
ChevronsUpDown,
GitBranch,
} from "lucide-react";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { tableTypeApi } from "@/lib/api/screen";
import { tableManagementApi } from "@/lib/api/tableManagement";
import { cn } from "@/lib/utils";
// ─── 타입 (리피터와 동일한 패턴) ───
interface TableRelation {
tableName: string;
tableLabel: string;
foreignKeyColumn: string;
referenceColumn: string;
}
interface ColumnOption {
columnName: string;
displayName: string;
inputType?: string;
detailSettings?: {
codeGroup?: string;
referenceTable?: string;
referenceColumn?: string;
displayColumn?: string;
format?: string;
};
}
interface EntityColumnOption {
columnName: string;
displayName: string;
referenceTable?: string;
referenceColumn?: string;
displayColumn?: string;
}
interface BomColumnConfig {
key: string;
title: string;
width?: string;
visible?: boolean;
editable?: boolean;
hidden?: boolean;
inputType?: string;
isSourceDisplay?: boolean;
detailSettings?: {
codeGroup?: string;
referenceTable?: string;
referenceColumn?: string;
displayColumn?: string;
format?: string;
};
}
interface BomItemEditorConfig {
// 저장 테이블 설정 (리피터 패턴)
useCustomTable?: boolean;
mainTableName?: string;
foreignKeyColumn?: string;
foreignKeySourceColumn?: string;
// 트리 구조 설정
parentKeyColumn?: string;
// 엔티티 (품목 참조) 설정
dataSource?: {
sourceTable?: string;
foreignKey?: string;
referenceKey?: string;
displayColumn?: string;
};
// 컬럼 설정
columns: BomColumnConfig[];
// 기능 옵션
features?: {
showAddButton?: boolean;
showDeleteButton?: boolean;
inlineEdit?: boolean;
showRowNumber?: boolean;
maxDepth?: number;
};
}
interface V2BomItemEditorConfigPanelProps {
config: BomItemEditorConfig;
onChange: (config: BomItemEditorConfig) => void;
currentTableName?: string;
screenTableName?: string;
}
// ─── 메인 패널 ───
export function V2BomItemEditorConfigPanel({
config: propConfig,
onChange,
currentTableName: propCurrentTableName,
screenTableName,
}: V2BomItemEditorConfigPanelProps) {
const currentTableName = screenTableName || propCurrentTableName;
const config: BomItemEditorConfig = useMemo(
() => ({
columns: [],
...propConfig,
dataSource: { ...propConfig?.dataSource },
features: {
showAddButton: true,
showDeleteButton: true,
inlineEdit: false,
showRowNumber: false,
maxDepth: 3,
...propConfig?.features,
},
}),
[propConfig],
);
// ─── 상태 ───
const [currentTableColumns, setCurrentTableColumns] = useState<ColumnOption[]>([]);
const [entityColumns, setEntityColumns] = useState<EntityColumnOption[]>([]);
const [sourceTableColumns, setSourceTableColumns] = useState<ColumnOption[]>([]);
const [allTables, setAllTables] = useState<{ tableName: string; displayName: string }[]>([]);
const [relatedTables, setRelatedTables] = useState<TableRelation[]>([]);
const [loadingColumns, setLoadingColumns] = useState(false);
const [loadingSourceColumns, setLoadingSourceColumns] = useState(false);
const [loadingTables, setLoadingTables] = useState(false);
const [loadingRelations, setLoadingRelations] = useState(false);
const [tableComboboxOpen, setTableComboboxOpen] = useState(false);
const [expandedColumn, setExpandedColumn] = useState<string | null>(null);
// ─── 업데이트 헬퍼 (리피터 패턴) ───
const updateConfig = useCallback(
(updates: Partial<BomItemEditorConfig>) => {
onChange({ ...config, ...updates });
},
[config, onChange],
);
const updateFeatures = useCallback(
(field: string, value: any) => {
updateConfig({ features: { ...config.features, [field]: value } });
},
[config.features, updateConfig],
);
// ─── 전체 테이블 목록 로드 (리피터 동일) ───
useEffect(() => {
const loadTables = async () => {
setLoadingTables(true);
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.displayName || t.table_label || t.tableName || t.table_name,
})),
);
}
} catch (error) {
console.error("테이블 목록 로드 실패:", error);
} finally {
setLoadingTables(false);
}
};
loadTables();
}, []);
// ─── 연관 테이블 로드 (리피터 동일) ───
useEffect(() => {
const loadRelatedTables = async () => {
const baseTable = currentTableName || config.mainTableName;
if (!baseTable) {
setRelatedTables([]);
return;
}
setLoadingRelations(true);
try {
const { apiClient } = await import("@/lib/api/client");
const allRelations: TableRelation[] = [];
if (currentTableName) {
const response = await apiClient.get(
`/table-management/columns/${currentTableName}/referenced-by`,
);
if (response.data.success && response.data.data) {
allRelations.push(
...response.data.data.map((rel: any) => ({
tableName: rel.tableName || rel.table_name,
tableLabel: rel.tableLabel || rel.table_label || rel.tableName || rel.table_name,
foreignKeyColumn: rel.columnName || rel.column_name,
referenceColumn: rel.referenceColumn || rel.reference_column || "id",
})),
);
}
}
if (config.mainTableName && config.mainTableName !== currentTableName) {
const response2 = await apiClient.get(
`/table-management/columns/${config.mainTableName}/referenced-by`,
);
if (response2.data.success && response2.data.data) {
response2.data.data.forEach((rel: any) => {
const tn = rel.tableName || rel.table_name;
if (!allRelations.some((r) => r.tableName === tn)) {
allRelations.push({
tableName: tn,
tableLabel: rel.tableLabel || rel.table_label || tn,
foreignKeyColumn: rel.columnName || rel.column_name,
referenceColumn: rel.referenceColumn || rel.reference_column || "id",
});
}
});
}
}
setRelatedTables(allRelations);
} catch (error) {
console.error("연관 테이블 로드 실패:", error);
setRelatedTables([]);
} finally {
setLoadingRelations(false);
}
};
loadRelatedTables();
}, [currentTableName, config.mainTableName]);
// ─── 저장 테이블 선택 (리피터 동일) ───
const handleSaveTableSelect = useCallback(
(tableName: string) => {
if (!tableName || tableName === currentTableName) {
updateConfig({
useCustomTable: false,
mainTableName: undefined,
foreignKeyColumn: undefined,
foreignKeySourceColumn: undefined,
});
return;
}
const relation = relatedTables.find((r) => r.tableName === tableName);
if (relation) {
updateConfig({
useCustomTable: true,
mainTableName: tableName,
foreignKeyColumn: relation.foreignKeyColumn,
foreignKeySourceColumn: relation.referenceColumn,
});
} else {
updateConfig({
useCustomTable: true,
mainTableName: tableName,
foreignKeyColumn: undefined,
foreignKeySourceColumn: "id",
});
}
},
[currentTableName, relatedTables, updateConfig],
);
// ─── 저장 테이블 컬럼 로드 (리피터 동일) ───
const targetTableForColumns =
config.useCustomTable && config.mainTableName ? config.mainTableName : currentTableName;
useEffect(() => {
const loadColumns = async () => {
if (!targetTableForColumns) {
setCurrentTableColumns([]);
setEntityColumns([]);
return;
}
setLoadingColumns(true);
try {
const columnData = await tableTypeApi.getColumns(targetTableForColumns);
const cols: ColumnOption[] = [];
const entityCols: EntityColumnOption[] = [];
for (const c of columnData) {
let detailSettings: any = null;
if (c.detailSettings) {
try {
detailSettings =
typeof c.detailSettings === "string" ? JSON.parse(c.detailSettings) : c.detailSettings;
} catch {
// ignore
}
}
const col: ColumnOption = {
columnName: c.columnName || c.column_name,
displayName: c.displayName || c.columnLabel || c.columnName || c.column_name,
inputType: c.inputType || c.input_type,
detailSettings: detailSettings
? {
codeGroup: detailSettings.codeGroup,
referenceTable: detailSettings.referenceTable,
referenceColumn: detailSettings.referenceColumn,
displayColumn: detailSettings.displayColumn,
format: detailSettings.format,
}
: undefined,
};
cols.push(col);
if (col.inputType === "entity") {
const refTable = detailSettings?.referenceTable || c.referenceTable;
if (refTable) {
entityCols.push({
columnName: col.columnName,
displayName: col.displayName,
referenceTable: refTable,
referenceColumn: detailSettings?.referenceColumn || c.referenceColumn || "id",
displayColumn: detailSettings?.displayColumn || c.displayColumn,
});
}
}
}
setCurrentTableColumns(cols);
setEntityColumns(entityCols);
} catch (error) {
console.error("컬럼 로드 실패:", error);
setCurrentTableColumns([]);
setEntityColumns([]);
} finally {
setLoadingColumns(false);
}
};
loadColumns();
}, [targetTableForColumns]);
// ─── 소스(엔티티) 테이블 컬럼 로드 (리피터 동일) ───
useEffect(() => {
const loadSourceColumns = async () => {
const sourceTable = config.dataSource?.sourceTable;
if (!sourceTable) {
setSourceTableColumns([]);
return;
}
setLoadingSourceColumns(true);
try {
const columnData = await tableTypeApi.getColumns(sourceTable);
setSourceTableColumns(
columnData.map((c: any) => ({
columnName: c.columnName || c.column_name,
displayName: c.displayName || c.columnLabel || c.columnName || c.column_name,
inputType: c.inputType || c.input_type,
})),
);
} catch (error) {
console.error("소스 테이블 컬럼 로드 실패:", error);
setSourceTableColumns([]);
} finally {
setLoadingSourceColumns(false);
}
};
loadSourceColumns();
}, [config.dataSource?.sourceTable]);
// ─── 엔티티 컬럼 선택 시 소스 테이블 자동 설정 (리피터 동일) ───
const handleEntityColumnSelect = (columnName: string) => {
const selectedEntity = entityColumns.find((c) => c.columnName === columnName);
if (selectedEntity) {
updateConfig({
dataSource: {
...config.dataSource,
sourceTable: selectedEntity.referenceTable || "",
foreignKey: selectedEntity.columnName,
referenceKey: selectedEntity.referenceColumn || "id",
displayColumn: selectedEntity.displayColumn,
},
});
}
};
// ─── 컬럼 토글 (리피터 동일) ───
const toggleInputColumn = (column: ColumnOption) => {
const exists = config.columns.findIndex((c) => c.key === column.columnName && !c.isSourceDisplay);
if (exists >= 0) {
updateConfig({ columns: config.columns.filter((c) => c.key !== column.columnName || c.isSourceDisplay) });
} else {
const newCol: BomColumnConfig = {
key: column.columnName,
title: column.displayName,
width: "auto",
visible: true,
editable: true,
inputType: column.inputType || "text",
detailSettings: column.detailSettings,
};
updateConfig({ columns: [...config.columns, newCol] });
}
};
const toggleSourceDisplayColumn = (column: ColumnOption) => {
const exists = config.columns.some((c) => c.key === column.columnName && c.isSourceDisplay);
if (exists) {
updateConfig({ columns: config.columns.filter((c) => c.key !== column.columnName) });
} else {
const newCol: BomColumnConfig = {
key: column.columnName,
title: column.displayName,
width: "auto",
visible: true,
editable: false,
isSourceDisplay: true,
};
updateConfig({ columns: [...config.columns, newCol] });
}
};
const isColumnAdded = (columnName: string) =>
config.columns.some((c) => c.key === columnName && !c.isSourceDisplay);
const isSourceColumnSelected = (columnName: string) =>
config.columns.some((c) => c.key === columnName && c.isSourceDisplay);
const updateColumnProp = (key: string, field: keyof BomColumnConfig, value: any) => {
updateConfig({
columns: config.columns.map((col) => (col.key === key ? { ...col, [field]: value } : col)),
});
};
// FK 컬럼 제외한 입력 가능 컬럼
const inputableColumns = useMemo(() => {
const fkColumn = config.dataSource?.foreignKey;
return currentTableColumns.filter(
(col) => col.columnName !== fkColumn && col.inputType !== "entity",
);
}, [currentTableColumns, config.dataSource?.foreignKey]);
// ─── 렌더링 ───
return (
<div className="space-y-4">
<Tabs defaultValue="basic" className="w-full">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="basic" className="text-xs">
</TabsTrigger>
<TabsTrigger value="columns" className="text-xs">
</TabsTrigger>
</TabsList>
{/* ─── 기본 설정 탭 ─── */}
<TabsContent value="basic" className="mt-4 space-y-4">
{/* 저장 대상 테이블 (리피터 동일) */}
<div className="space-y-2">
<Label className="text-xs font-medium"> </Label>
<div
className={cn(
"rounded-lg border p-3",
config.useCustomTable && config.mainTableName
? "border-orange-300 bg-orange-50"
: "border-blue-300 bg-blue-50",
)}
>
<div className="flex items-center gap-2">
<Database
className={cn(
"h-4 w-4",
config.useCustomTable && config.mainTableName ? "text-orange-600" : "text-blue-600",
)}
/>
<div className="flex-1">
<p
className={cn(
"text-sm font-medium",
config.useCustomTable && config.mainTableName ? "text-orange-700" : "text-blue-700",
)}
>
{config.useCustomTable && config.mainTableName
? allTables.find((t) => t.tableName === config.mainTableName)?.displayName ||
config.mainTableName
: currentTableName || "미설정"}
</p>
{config.useCustomTable && config.mainTableName && config.foreignKeyColumn && (
<p className="mt-0.5 text-[10px] text-orange-600">
FK: {config.foreignKeyColumn} &rarr; {currentTableName}.
{config.foreignKeySourceColumn || "id"}
</p>
)}
{!config.useCustomTable && currentTableName && (
<p className="mt-0.5 text-[10px] text-blue-600"> </p>
)}
</div>
</div>
</div>
{/* 테이블 Combobox (리피터 동일) */}
<Popover open={tableComboboxOpen} onOpenChange={setTableComboboxOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={tableComboboxOpen}
disabled={loadingTables || loadingRelations}
className="h-8 w-full justify-between text-xs"
>
{loadingTables ? "로딩 중..." : "다른 테이블 선택..."}
<ChevronsUpDown className="ml-2 h-3 w-3 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent
className="p-0"
style={{ width: "var(--radix-popover-trigger-width)" }}
align="start"
>
<Command>
<CommandInput placeholder="테이블 검색..." className="text-xs" />
<CommandList className="max-h-60">
<CommandEmpty className="py-3 text-center text-xs">
.
</CommandEmpty>
{currentTableName && (
<CommandGroup heading="기본">
<CommandItem
value={currentTableName}
onSelect={() => {
handleSaveTableSelect(currentTableName);
setTableComboboxOpen(false);
}}
className="text-xs"
>
<Check
className={cn(
"mr-2 h-3 w-3",
!config.useCustomTable || !config.mainTableName
? "opacity-100"
: "opacity-0",
)}
/>
<Database className="mr-2 h-3 w-3 text-blue-500" />
<span>{currentTableName}</span>
<span className="text-muted-foreground ml-1 text-[10px]">()</span>
</CommandItem>
</CommandGroup>
)}
{relatedTables.length > 0 && (
<CommandGroup heading="연관 테이블 (FK 자동 설정)">
{relatedTables.map((rel) => (
<CommandItem
key={rel.tableName}
value={`${rel.tableName} ${rel.tableLabel}`}
onSelect={() => {
handleSaveTableSelect(rel.tableName);
setTableComboboxOpen(false);
}}
className="text-xs"
>
<Check
className={cn(
"mr-2 h-3 w-3",
config.mainTableName === rel.tableName ? "opacity-100" : "opacity-0",
)}
/>
<Link2 className="mr-2 h-3 w-3 text-orange-500" />
<span>{rel.tableLabel}</span>
<span className="text-muted-foreground ml-1 text-[10px]">
({rel.foreignKeyColumn})
</span>
</CommandItem>
))}
</CommandGroup>
)}
<CommandGroup heading="전체 테이블 (FK 직접 입력)">
{allTables
.filter(
(t) =>
t.tableName !== currentTableName &&
!relatedTables.some((r) => r.tableName === t.tableName),
)
.map((table) => (
<CommandItem
key={table.tableName}
value={`${table.tableName} ${table.displayName}`}
onSelect={() => {
handleSaveTableSelect(table.tableName);
setTableComboboxOpen(false);
}}
className="text-xs"
>
<Check
className={cn(
"mr-2 h-3 w-3",
config.mainTableName === table.tableName ? "opacity-100" : "opacity-0",
)}
/>
<Database className="mr-2 h-3 w-3 text-gray-400" />
<span>{table.displayName}</span>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
{/* FK 직접 입력 (연관 없는 테이블 선택 시) */}
{config.useCustomTable &&
config.mainTableName &&
currentTableName &&
!relatedTables.some((r) => r.tableName === config.mainTableName) && (
<div className="space-y-2 rounded border border-amber-200 bg-amber-50 p-2">
<p className="text-[10px] text-amber-700">
({currentTableName}) . FK
.
</p>
<div className="grid grid-cols-2 gap-2">
<div className="space-y-1">
<Label className="text-[10px]">FK ( )</Label>
<Input
value={config.foreignKeyColumn || ""}
onChange={(e) => updateConfig({ foreignKeyColumn: e.target.value })}
placeholder="예: bom_id"
className="h-7 text-xs"
/>
</div>
<div className="space-y-1">
<Label className="text-[10px]">PK ( )</Label>
<Input
value={config.foreignKeySourceColumn || "id"}
onChange={(e) => updateConfig({ foreignKeySourceColumn: e.target.value })}
placeholder="id"
className="h-7 text-xs"
/>
</div>
</div>
</div>
)}
</div>
<Separator />
{/* 트리 구조 설정 (BOM 전용) */}
<div className="space-y-2">
<div className="flex items-center gap-2">
<GitBranch className="h-4 w-4" />
<Label className="text-xs font-medium"> </Label>
</div>
<p className="text-muted-foreground text-[10px]">
FK
</p>
{currentTableColumns.length > 0 ? (
<Select
value={config.parentKeyColumn || ""}
onValueChange={(value) => updateConfig({ parentKeyColumn: value })}
>
<SelectTrigger className="h-8 text-xs">
<SelectValue placeholder="부모 키 컬럼 선택" />
</SelectTrigger>
<SelectContent>
{currentTableColumns.map((col) => (
<SelectItem key={col.columnName} value={col.columnName}>
<div className="flex items-center gap-2">
<span>{col.displayName}</span>
{col.displayName !== col.columnName && (
<span className="text-muted-foreground text-[10px]">
({col.columnName})
</span>
)}
</div>
</SelectItem>
))}
</SelectContent>
</Select>
) : (
<div className="rounded border border-gray-200 bg-gray-50 p-2">
<p className="text-[10px] text-gray-500">
{loadingColumns ? "로딩 중..." : "저장 테이블을 먼저 선택하세요"}
</p>
</div>
)}
{/* 최대 깊이 */}
<div className="space-y-1">
<Label className="text-[10px]"> </Label>
<Input
type="number"
min={1}
max={10}
value={config.features?.maxDepth ?? 3}
onChange={(e) => updateFeatures("maxDepth", parseInt(e.target.value) || 3)}
className="h-7 w-20 text-xs"
/>
</div>
</div>
<Separator />
{/* 엔티티 선택 (리피터 모달 모드와 동일) */}
<div className="space-y-2">
<Label className="text-xs font-medium"> ( )</Label>
<p className="text-muted-foreground text-[10px]">
(FK만 )
</p>
{entityColumns.length > 0 ? (
<Select
value={config.dataSource?.foreignKey || ""}
onValueChange={handleEntityColumnSelect}
disabled={!targetTableForColumns}
>
<SelectTrigger className="h-8 text-xs">
<SelectValue placeholder="엔티티 컬럼 선택" />
</SelectTrigger>
<SelectContent>
{entityColumns.map((col) => (
<SelectItem key={col.columnName} value={col.columnName}>
<div className="flex items-center gap-2">
<Link2 className="h-3 w-3 text-blue-500" />
<span>{col.displayName}</span>
<ArrowRight className="h-3 w-3 text-gray-400" />
<span className="text-gray-500">{col.referenceTable}</span>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
) : (
<div className="rounded border border-gray-200 bg-gray-50 p-2">
<p className="text-[10px] text-gray-500">
{loadingColumns
? "로딩 중..."
: !targetTableForColumns
? "저장 테이블을 먼저 선택하세요"
: "엔티티 타입 컬럼이 없습니다"}
</p>
</div>
)}
{config.dataSource?.sourceTable && (
<div className="space-y-1 rounded border border-green-200 bg-green-50 p-2">
<p className="text-xs font-medium text-green-700"> </p>
<div className="text-[10px] text-green-600">
<p> : {config.dataSource.sourceTable}</p>
<p> : {config.dataSource.foreignKey} (FK)</p>
</div>
</div>
)}
</div>
<Separator />
{/* 기능 옵션 */}
<div className="space-y-3">
<Label className="text-xs font-medium"> </Label>
<div className="grid grid-cols-2 gap-2">
<div className="flex items-center space-x-2">
<Checkbox
id="bom-showAddButton"
checked={config.features?.showAddButton ?? true}
onCheckedChange={(checked) => updateFeatures("showAddButton", !!checked)}
/>
<label htmlFor="bom-showAddButton" className="text-xs">
</label>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="bom-showDeleteButton"
checked={config.features?.showDeleteButton ?? true}
onCheckedChange={(checked) => updateFeatures("showDeleteButton", !!checked)}
/>
<label htmlFor="bom-showDeleteButton" className="text-xs">
</label>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="bom-inlineEdit"
checked={config.features?.inlineEdit ?? false}
onCheckedChange={(checked) => updateFeatures("inlineEdit", !!checked)}
/>
<label htmlFor="bom-inlineEdit" className="text-xs">
</label>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="bom-showRowNumber"
checked={config.features?.showRowNumber ?? false}
onCheckedChange={(checked) => updateFeatures("showRowNumber", !!checked)}
/>
<label htmlFor="bom-showRowNumber" className="text-xs">
</label>
</div>
</div>
</div>
{/* 메인 화면 테이블 참고 */}
{currentTableName && (
<>
<Separator />
<div className="space-y-2">
<Label className="text-xs font-medium"> ()</Label>
<div className="rounded border border-gray-200 bg-gray-50 p-2">
<p className="text-xs font-medium text-gray-700">{currentTableName}</p>
<p className="text-[10px] text-gray-500">
{currentTableColumns.length} / {entityColumns.length}
</p>
</div>
</div>
</>
)}
</TabsContent>
{/* ─── 컬럼 설정 탭 (리피터 동일 패턴) ─── */}
<TabsContent value="columns" className="mt-4 space-y-4">
<div className="space-y-2">
<Label className="text-xs font-medium"> </Label>
<p className="text-muted-foreground text-[10px]">
</p>
{/* 소스 테이블 컬럼 (표시용) */}
{config.dataSource?.sourceTable && (
<>
<div className="mb-1 mt-2 flex items-center gap-1 text-[10px] font-medium text-blue-600">
<Link2 className="h-3 w-3" />
({config.dataSource.sourceTable}) -
</div>
{loadingSourceColumns ? (
<p className="text-muted-foreground py-2 text-xs"> ...</p>
) : sourceTableColumns.length === 0 ? (
<p className="text-muted-foreground py-2 text-xs"> </p>
) : (
<div className="max-h-28 space-y-0.5 overflow-y-auto rounded-md border border-blue-200 bg-blue-50/30 p-2">
{sourceTableColumns.map((column) => (
<div
key={`source-${column.columnName}`}
className={cn(
"flex cursor-pointer items-center gap-2 rounded px-2 py-1 hover:bg-blue-100/50",
isSourceColumnSelected(column.columnName) && "bg-blue-100",
)}
onClick={() => toggleSourceDisplayColumn(column)}
>
<Checkbox
checked={isSourceColumnSelected(column.columnName)}
onCheckedChange={() => toggleSourceDisplayColumn(column)}
className="pointer-events-none h-3.5 w-3.5"
/>
<Link2 className="h-3 w-3 flex-shrink-0 text-blue-500" />
<span className="truncate text-xs">{column.displayName}</span>
<span className="ml-auto text-[10px] text-blue-400"></span>
</div>
))}
</div>
)}
</>
)}
{/* 저장 테이블 컬럼 (입력용) */}
<div className="mb-1 mt-3 flex items-center gap-1 text-[10px] font-medium text-gray-600">
<Database className="h-3 w-3" />
({targetTableForColumns || "미선택"}) -
</div>
{loadingColumns ? (
<p className="text-muted-foreground py-2 text-xs"> ...</p>
) : inputableColumns.length === 0 ? (
<p className="text-muted-foreground py-2 text-xs"> </p>
) : (
<div className="max-h-36 space-y-0.5 overflow-y-auto rounded-md border p-2">
{inputableColumns.map((column) => (
<div
key={`input-${column.columnName}`}
className={cn(
"hover:bg-muted/50 flex cursor-pointer items-center gap-2 rounded px-2 py-1",
isColumnAdded(column.columnName) && "bg-primary/10",
)}
onClick={() => toggleInputColumn(column)}
>
<Checkbox
checked={isColumnAdded(column.columnName)}
onCheckedChange={() => toggleInputColumn(column)}
className="pointer-events-none h-3.5 w-3.5"
/>
<Database className="text-muted-foreground h-3 w-3 flex-shrink-0" />
<span className="truncate text-xs">{column.displayName}</span>
<span className="ml-auto text-[10px] text-gray-400">{column.inputType}</span>
</div>
))}
</div>
)}
</div>
{/* 선택된 컬럼 상세 (리피터 동일 패턴) */}
{config.columns.length > 0 && (
<>
<Separator />
<div className="space-y-2">
<Label className="text-xs font-medium">
({config.columns.length})
<span className="text-muted-foreground ml-2 font-normal"> </span>
</Label>
<div className="max-h-48 space-y-1 overflow-y-auto">
{config.columns.map((col, index) => (
<div key={col.key} className="space-y-1">
<div
className={cn(
"flex items-center gap-2 rounded-md border p-2",
col.isSourceDisplay
? "border-blue-200 bg-blue-50/50"
: "border-gray-200 bg-muted/30",
col.hidden && "opacity-50",
)}
draggable
onDragStart={(e) => e.dataTransfer.setData("columnIndex", String(index))}
onDragOver={(e) => e.preventDefault()}
onDrop={(e) => {
e.preventDefault();
const fromIndex = parseInt(e.dataTransfer.getData("columnIndex"), 10);
if (fromIndex !== index) {
const newColumns = [...config.columns];
const [movedCol] = newColumns.splice(fromIndex, 1);
newColumns.splice(index, 0, movedCol);
updateConfig({ columns: newColumns });
}
}}
>
<GripVertical className="text-muted-foreground h-3 w-3 cursor-grab flex-shrink-0" />
{!col.isSourceDisplay && (
<button
type="button"
onClick={() =>
setExpandedColumn(expandedColumn === col.key ? null : col.key)
}
className="rounded p-0.5 hover:bg-gray-200"
>
{expandedColumn === col.key ? (
<ChevronDown className="h-3 w-3 text-gray-500" />
) : (
<ChevronRight className="h-3 w-3 text-gray-500" />
)}
</button>
)}
{col.isSourceDisplay ? (
<Link2
className="h-3 w-3 flex-shrink-0 text-blue-500"
title="소스 표시 (읽기 전용)"
/>
) : (
<Database className="text-muted-foreground h-3 w-3 flex-shrink-0" />
)}
<Input
value={col.title}
onChange={(e) => updateColumnProp(col.key, "title", e.target.value)}
placeholder="제목"
className="h-6 flex-1 text-xs"
/>
{!col.isSourceDisplay && (
<button
type="button"
onClick={() => updateColumnProp(col.key, "hidden", !col.hidden)}
className={cn(
"rounded p-1 hover:bg-gray-200",
col.hidden ? "text-gray-400" : "text-gray-600",
)}
title={col.hidden ? "히든 (저장만 됨)" : "표시됨"}
>
{col.hidden ? (
<EyeOff className="h-3 w-3" />
) : (
<Eye className="h-3 w-3" />
)}
</button>
)}
{!col.isSourceDisplay && (
<Checkbox
checked={col.editable ?? true}
onCheckedChange={(checked) =>
updateColumnProp(col.key, "editable", !!checked)
}
title="편집 가능"
/>
)}
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => {
if (col.isSourceDisplay) {
toggleSourceDisplayColumn({
columnName: col.key,
displayName: col.title,
});
} else {
toggleInputColumn({ columnName: col.key, displayName: col.title });
}
}}
className="text-destructive h-6 w-6 p-0"
>
<Trash2 className="h-3 w-3" />
</Button>
</div>
{/* 확장 상세 */}
{!col.isSourceDisplay && expandedColumn === col.key && (
<div className="ml-6 space-y-2 rounded-md border border-dashed border-gray-300 bg-gray-50 p-2">
<div className="space-y-1">
<Label className="text-[10px] text-gray-600"> </Label>
<Input
value={col.width || "auto"}
onChange={(e) => updateColumnProp(col.key, "width", e.target.value)}
placeholder="auto, 100px, 20%"
className="h-6 text-xs"
/>
</div>
</div>
)}
</div>
))}
</div>
</div>
</>
)}
</TabsContent>
</Tabs>
</div>
);
}
V2BomItemEditorConfigPanel.displayName = "V2BomItemEditorConfigPanel";
export default V2BomItemEditorConfigPanel;