feat: Enhance table data addition with inserted ID response

- Updated the `addTableData` method in `TableManagementService` to return the inserted ID after adding data to the table.
- Modified the `addTableData` controller to log the inserted ID and include it in the API response, improving client-side data handling.
- Enhanced the `BomTreeComponent` to support additional configurations and improve data loading logic.
- Updated the `ButtonActionExecutor` to handle deferred saves with level-based grouping, ensuring proper ID mapping during master-detail saves.
This commit is contained in:
DDD1542 2026-02-25 13:59:51 +09:00
parent 2b175a21f4
commit ed9e36c213
6 changed files with 1413 additions and 322 deletions

View File

@ -922,13 +922,14 @@ export async function addTableData(
}
// 데이터 추가
await tableManagementService.addTableData(tableName, data);
const result = await tableManagementService.addTableData(tableName, data);
logger.info(`테이블 데이터 추가 완료: ${tableName}`);
logger.info(`테이블 데이터 추가 완료: ${tableName}, id: ${result.insertedId}`);
const response: ApiResponse<null> = {
const response: ApiResponse<{ id: string | null }> = {
success: true,
message: "테이블 데이터를 성공적으로 추가했습니다.",
data: { id: result.insertedId },
};
res.status(201).json(response);

View File

@ -2438,7 +2438,7 @@ export class TableManagementService {
async addTableData(
tableName: string,
data: Record<string, any>
): Promise<{ skippedColumns: string[]; savedColumns: string[] }> {
): Promise<{ skippedColumns: string[]; savedColumns: string[]; insertedId: string | null }> {
try {
logger.info(`=== 테이블 데이터 추가 시작: ${tableName} ===`);
logger.info(`추가할 데이터:`, data);
@ -2551,19 +2551,21 @@ export class TableManagementService {
const insertQuery = `
INSERT INTO "${tableName}" (${columnNames})
VALUES (${placeholders})
RETURNING id
`;
logger.info(`실행할 쿼리: ${insertQuery}`);
logger.info(`쿼리 파라미터:`, values);
await query(insertQuery, values);
const insertResult = await query(insertQuery, values) as any[];
const insertedId = insertResult?.[0]?.id ?? null;
logger.info(`테이블 데이터 추가 완료: ${tableName}`);
logger.info(`테이블 데이터 추가 완료: ${tableName}, id: ${insertedId}`);
// 무시된 컬럼과 저장된 컬럼 정보 반환
return {
skippedColumns,
savedColumns: existingColumns,
insertedId,
};
} catch (error) {
logger.error(`테이블 데이터 추가 오류: ${tableName}`, error);

View File

@ -217,6 +217,7 @@ export const V2PropertiesPanel: React.FC<V2PropertiesPanelProps> = ({
"v2-biz": require("@/components/v2/config-panels/V2BizConfigPanel").V2BizConfigPanel,
"v2-hierarchy": require("@/components/v2/config-panels/V2HierarchyConfigPanel").V2HierarchyConfigPanel,
"v2-bom-item-editor": require("@/components/v2/config-panels/V2BomItemEditorConfigPanel").V2BomItemEditorConfigPanel,
"v2-bom-tree": require("@/components/v2/config-panels/V2BomTreeConfigPanel").V2BomTreeConfigPanel,
};
const V2ConfigPanel = v2ConfigPanels[componentId];
@ -240,7 +241,7 @@ export const V2PropertiesPanel: React.FC<V2PropertiesPanelProps> = ({
if (componentId === "v2-list") {
extraProps.currentTableName = currentTableName;
}
if (componentId === "v2-bom-item-editor") {
if (componentId === "v2-bom-item-editor" || componentId === "v2-bom-tree") {
extraProps.currentTableName = currentTableName;
extraProps.screenTableName = selectedComponent.tableName || currentTable?.tableName || currentTableName;
}

View File

@ -0,0 +1,935 @@
"use client";
/**
* BOM
*
* V2BomItemEditorConfigPanel :
* - : 디테일 + +
* - : 소스 + +
*/
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 TreeColumnConfig {
key: string;
title: string;
width?: string;
visible?: boolean;
hidden?: boolean;
isSourceDisplay?: boolean;
}
interface BomTreeConfig {
detailTable?: string;
foreignKey?: string;
parentKey?: string;
dataSource?: {
sourceTable?: string;
foreignKey?: string;
referenceKey?: string;
displayColumn?: string;
};
columns: TreeColumnConfig[];
features?: {
showExpandAll?: boolean;
showHeader?: boolean;
showQuantity?: boolean;
showLossRate?: boolean;
};
}
interface V2BomTreeConfigPanelProps {
config: BomTreeConfig;
onChange: (config: BomTreeConfig) => void;
currentTableName?: string;
screenTableName?: string;
}
export function V2BomTreeConfigPanel({
config: propConfig,
onChange,
currentTableName: propCurrentTableName,
screenTableName,
}: V2BomTreeConfigPanelProps) {
const currentTableName = screenTableName || propCurrentTableName;
const config: BomTreeConfig = useMemo(
() => ({
columns: [],
...propConfig,
dataSource: { ...propConfig?.dataSource },
features: {
showExpandAll: true,
showHeader: true,
showQuantity: true,
showLossRate: true,
...propConfig?.features,
},
}),
[propConfig],
);
const [detailTableColumns, setDetailTableColumns] = 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<BomTreeConfig>) => {
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;
if (!baseTable) {
setRelatedTables([]);
return;
}
setLoadingRelations(true);
try {
const { apiClient } = await import("@/lib/api/client");
const response = await apiClient.get(
`/table-management/columns/${baseTable}/referenced-by`,
);
if (response.data.success && response.data.data) {
setRelatedTables(
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",
})),
);
}
} catch (error) {
console.error("연관 테이블 로드 실패:", error);
setRelatedTables([]);
} finally {
setLoadingRelations(false);
}
};
loadRelatedTables();
}, [currentTableName]);
// 디테일 테이블 선택
const handleDetailTableSelect = useCallback(
(tableName: string) => {
const relation = relatedTables.find((r) => r.tableName === tableName);
updateConfig({
detailTable: tableName,
foreignKey: relation?.foreignKeyColumn || config.foreignKey,
});
},
[relatedTables, config.foreignKey, updateConfig],
);
// 디테일 테이블 컬럼 로드
useEffect(() => {
const loadColumns = async () => {
if (!config.detailTable) {
setDetailTableColumns([]);
setEntityColumns([]);
return;
}
setLoadingColumns(true);
try {
const columnData = await tableTypeApi.getColumns(config.detailTable);
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,
});
}
}
}
setDetailTableColumns(cols);
setEntityColumns(entityCols);
} catch (error) {
console.error("컬럼 로드 실패:", error);
setDetailTableColumns([]);
setEntityColumns([]);
} finally {
setLoadingColumns(false);
}
};
loadColumns();
}, [config.detailTable]);
// 소스(엔티티) 테이블 컬럼 로드
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 toggleDetailColumn = (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: TreeColumnConfig = {
key: column.columnName,
title: column.displayName,
width: "auto",
visible: true,
};
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: TreeColumnConfig = {
key: column.columnName,
title: column.displayName,
width: "auto",
visible: true,
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 TreeColumnConfig, value: any) => {
updateConfig({
columns: config.columns.map((col) => (col.key === key ? { ...col, [field]: value } : col)),
});
};
// FK/시스템 컬럼 제외한 표시 가능 컬럼
const displayableColumns = useMemo(() => {
const fkColumn = config.dataSource?.foreignKey;
const systemCols = ["id", "created_at", "updated_at", "created_by", "updated_by", "company_code", "created_date"];
return detailTableColumns.filter(
(col) => col.columnName !== fkColumn && col.inputType !== "entity" && !systemCols.includes(col.columnName),
);
}, [detailTableColumns, config.dataSource?.foreignKey]);
// FK 후보 컬럼
const fkCandidateColumns = useMemo(() => {
const systemCols = ["created_at", "updated_at", "created_by", "updated_by", "company_code", "created_date"];
return detailTableColumns.filter((c) => !systemCols.includes(c.columnName));
}, [detailTableColumns]);
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.detailTable ? "border-orange-300 bg-orange-50" : "border-gray-300 bg-gray-50",
)}
>
<div className="flex items-center gap-2">
<Database
className={cn("h-4 w-4", config.detailTable ? "text-orange-600" : "text-gray-400")}
/>
<div className="flex-1">
<p className={cn("text-sm font-medium", config.detailTable ? "text-orange-700" : "text-gray-500")}>
{config.detailTable
? allTables.find((t) => t.tableName === config.detailTable)?.displayName || config.detailTable
: "미설정"}
</p>
{config.detailTable && config.foreignKey && (
<p className="mt-0.5 text-[10px] text-orange-600">
FK: {config.foreignKey} &rarr; {currentTableName || "메인 테이블"}.id
</p>
)}
</div>
</div>
</div>
<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>
{relatedTables.length > 0 && (
<CommandGroup heading="연관 테이블 (FK 자동 설정)">
{relatedTables.map((rel) => (
<CommandItem
key={rel.tableName}
value={`${rel.tableName} ${rel.tableLabel}`}
onSelect={() => {
handleDetailTableSelect(rel.tableName);
setTableComboboxOpen(false);
}}
className="text-xs"
>
<Check
className={cn(
"mr-2 h-3 w-3",
config.detailTable === 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="전체 테이블">
{allTables
.filter((t) => !relatedTables.some((r) => r.tableName === t.tableName))
.map((table) => (
<CommandItem
key={table.tableName}
value={`${table.tableName} ${table.displayName}`}
onSelect={() => {
handleDetailTableSelect(table.tableName);
setTableComboboxOpen(false);
}}
className="text-xs"
>
<Check
className={cn(
"mr-2 h-3 w-3",
config.detailTable === 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>
</div>
<Separator />
{/* 트리 구조 설정 */}
<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와 - FK를
</p>
{fkCandidateColumns.length > 0 ? (
<div className="space-y-2">
<div className="space-y-1">
<Label className="text-[10px]">FK ( )</Label>
<Select
value={config.foreignKey || ""}
onValueChange={(value) => updateConfig({ foreignKey: value })}
>
<SelectTrigger className="h-8 text-xs">
<SelectValue placeholder="FK 컬럼 선택" />
</SelectTrigger>
<SelectContent>
{fkCandidateColumns.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>
<div className="space-y-1">
<Label className="text-[10px]"> ( FK)</Label>
<Select
value={config.parentKey || ""}
onValueChange={(value) => updateConfig({ parentKey: value })}
>
<SelectTrigger className="h-8 text-xs">
<SelectValue placeholder="부모 키 컬럼 선택" />
</SelectTrigger>
<SelectContent>
{fkCandidateColumns.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>
</div>
) : (
<div className="rounded border border-gray-200 bg-gray-50 p-2">
<p className="text-[10px] text-gray-500">
{loadingColumns ? "로딩 중..." : "디테일 테이블을 먼저 선택하세요"}
</p>
</div>
)}
</div>
<Separator />
{/* 엔티티 선택 (품목 참조) */}
<div className="space-y-2">
<Label className="text-xs font-medium"> ( )</Label>
<p className="text-muted-foreground text-[10px]">
</p>
{entityColumns.length > 0 ? (
<Select
value={config.dataSource?.foreignKey || ""}
onValueChange={handleEntityColumnSelect}
disabled={!config.detailTable}
>
<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
? "로딩 중..."
: !config.detailTable
? "디테일 테이블을 먼저 선택하세요"
: "엔티티 타입 컬럼이 없습니다"}
</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>FK : {config.dataSource.foreignKey}</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="tree-showExpandAll"
checked={config.features?.showExpandAll ?? true}
onCheckedChange={(checked) => updateFeatures("showExpandAll", !!checked)}
/>
<label htmlFor="tree-showExpandAll" className="text-xs">
/
</label>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="tree-showHeader"
checked={config.features?.showHeader ?? true}
onCheckedChange={(checked) => updateFeatures("showHeader", !!checked)}
/>
<label htmlFor="tree-showHeader" className="text-xs">
</label>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="tree-showQuantity"
checked={config.features?.showQuantity ?? true}
onCheckedChange={(checked) => updateFeatures("showQuantity", !!checked)}
/>
<label htmlFor="tree-showQuantity" className="text-xs">
</label>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="tree-showLossRate"
checked={config.features?.showLossRate ?? true}
onCheckedChange={(checked) => updateFeatures("showLossRate", !!checked)}
/>
<label htmlFor="tree-showLossRate" 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">
{detailTableColumns.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" />
({config.detailTable || "미선택"}) -
</div>
{loadingColumns ? (
<p className="text-muted-foreground py-2 text-xs"> ...</p>
) : displayableColumns.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">
{displayableColumns.map((column) => (
<div
key={`detail-${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={() => toggleDetailColumn(column)}
>
<Checkbox
checked={isColumnAdded(column.columnName)}
onCheckedChange={() => toggleDetailColumn(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>
)}
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => {
if (col.isSourceDisplay) {
toggleSourceDisplayColumn({ columnName: col.key, displayName: col.title });
} else {
toggleDetailColumn({ 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>
);
}
V2BomTreeConfigPanel.displayName = "V2BomTreeConfigPanel";
export default V2BomTreeConfigPanel;

View File

@ -1,47 +1,39 @@
"use client";
import React, { useState, useEffect, useCallback, useMemo } from "react";
import { ChevronRight, ChevronDown, Package, Layers, Box, AlertCircle } from "lucide-react";
import {
ChevronRight,
ChevronDown,
Package,
Layers,
Box,
AlertCircle,
Expand,
Shrink,
Loader2,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { entityJoinApi } from "@/lib/api/entityJoin";
import { Button } from "@/components/ui/button";
/**
* BOM
*/
interface BomTreeNode {
id: string;
bom_id: string;
parent_detail_id: string | null;
seq_no: string;
level: string;
child_item_id: string;
child_item_code: string;
child_item_name: string;
child_item_type: string;
quantity: string;
unit: string;
loss_rate: string;
remark: string;
[key: string]: any;
children: BomTreeNode[];
}
/**
* BOM
*/
interface BomHeaderInfo {
id: string;
bom_number: string;
item_code: string;
item_name: string;
item_type: string;
base_qty: string;
unit: string;
version: string;
revision: string;
status: string;
effective_date: string;
expired_date: string;
remark: string;
[key: string]: any;
}
interface TreeColumnDef {
key: string;
title: string;
width?: string;
visible?: boolean;
hidden?: boolean;
isSourceDisplay?: boolean;
}
interface BomTreeComponentProps {
@ -54,10 +46,9 @@ interface BomTreeComponentProps {
[key: string]: any;
}
/**
* BOM
* BOM BOM
*/
// 컬럼은 설정 패널에서만 추가 (하드코딩 금지)
const EMPTY_COLUMNS: TreeColumnDef[] = [];
export function BomTreeComponent({
component,
formData,
@ -73,18 +64,14 @@ export function BomTreeComponent({
const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null);
const config = component?.componentConfig || {};
const overrides = component?.overrides || {};
// 선택된 BOM 헤더에서 bom_id 추출
const selectedBomId = useMemo(() => {
// SplitPanel에서 좌측 선택 시 formData나 selectedRowsData로 전달됨
if (selectedRowsData && selectedRowsData.length > 0) {
return selectedRowsData[0]?.id;
}
if (selectedRowsData && selectedRowsData.length > 0) return selectedRowsData[0]?.id;
if (formData?.id) return formData.id;
return null;
}, [formData, selectedRowsData]);
// 선택된 BOM 헤더 정보 추출 (조인 필드명 매핑 포함)
const selectedHeaderData = useMemo(() => {
const raw = selectedRowsData?.[0] || (formData?.id ? formData : null);
if (!raw) return null;
@ -96,12 +83,45 @@ export function BomTreeComponent({
} as BomHeaderInfo;
}, [formData, selectedRowsData]);
// BOM 디테일 데이터 로드
const detailTable = config.detailTable || "bom_detail";
const foreignKey = config.foreignKey || "bom_id";
const sourceFk = "child_item_id";
const detailTable = overrides.detailTable || config.detailTable || "bom_detail";
const foreignKey = overrides.foreignKey || config.foreignKey || "bom_id";
const parentKey = overrides.parentKey || config.parentKey || "parent_detail_id";
const sourceFk = config.dataSource?.foreignKey || "child_item_id";
const loadBomDetails = useCallback(async (bomId: string) => {
const displayColumns = useMemo(() => {
const configured = config.columns as TreeColumnDef[] | undefined;
if (configured && configured.length > 0) return configured.filter((c) => !c.hidden);
return EMPTY_COLUMNS;
}, [config.columns]);
const features = config.features || {};
// ─── 데이터 로드 ───
// BOM 헤더 데이터로 가상 0레벨 루트 노드 생성
const buildVirtualRoot = useCallback((headerData: BomHeaderInfo | null, children: BomTreeNode[]): BomTreeNode | null => {
if (!headerData) return null;
return {
id: `__root_${headerData.id}`,
_isVirtualRoot: true,
level: "0",
child_item_name: headerData.item_name || "",
child_item_code: headerData.item_code || headerData.bom_number || "",
child_item_type: headerData.item_type || "",
item_name: headerData.item_name || "",
item_number: headerData.item_code || "",
quantity: "-",
base_qty: headerData.base_qty || "",
unit: headerData.unit || "",
revision: headerData.revision || "",
loss_rate: "",
process_type: "",
remark: headerData.remark || "",
children,
};
}, []);
const loadBomDetails = useCallback(async (bomId: string, headerData: BomHeaderInfo | null) => {
if (!bomId) return;
setLoading(true);
try {
@ -116,72 +136,73 @@ export function BomTreeComponent({
const rows = (result.data || []).map((row: Record<string, any>) => {
const mapped = { ...row };
// 엔티티 조인 필드 매핑: child_item_id_item_name → child_item_name 등
for (const key of Object.keys(row)) {
if (key.startsWith(`${sourceFk}_`)) {
const shortKey = key.replace(`${sourceFk}_`, "");
const aliasKey = `child_${shortKey}`;
if (!mapped[aliasKey]) mapped[aliasKey] = row[key];
if (!mapped[shortKey]) mapped[shortKey] = row[key];
}
}
mapped.child_item_name = row[`${sourceFk}_item_name`] || row.child_item_name || "";
mapped.child_item_code = row[`${sourceFk}_item_number`] || row.child_item_code || "";
mapped.child_item_type = row[`${sourceFk}_type`] || row[`${sourceFk}_division`] || row.child_item_type || "";
return mapped;
});
const tree = buildTree(rows);
setTreeData(tree);
const firstLevelIds = new Set<string>(tree.map((n: BomTreeNode) => n.id));
setExpandedNodes(firstLevelIds);
const detailTree = buildTree(rows);
// BOM 헤더를 가상 0레벨 루트로 삽입
const virtualRoot = buildVirtualRoot(headerData, detailTree);
if (virtualRoot) {
setTreeData([virtualRoot]);
setExpandedNodes(new Set([virtualRoot.id]));
} else {
setTreeData(detailTree);
const firstLevelIds = new Set<string>(detailTree.map((n: BomTreeNode) => n.id));
setExpandedNodes(firstLevelIds);
}
} catch (error) {
console.error("[BomTree] 데이터 로드 실패:", error);
} finally {
setLoading(false);
}
}, [detailTable, foreignKey]);
}, [detailTable, foreignKey, sourceFk, buildVirtualRoot]);
// 평면 데이터 -> 트리 구조 변환
const buildTree = (flatData: any[]): BomTreeNode[] => {
const nodeMap = new Map<string, BomTreeNode>();
const roots: BomTreeNode[] = [];
// 모든 노드를 맵에 등록
flatData.forEach((item) => {
nodeMap.set(item.id, { ...item, children: [] });
});
// 부모-자식 관계 설정
flatData.forEach((item) => nodeMap.set(item.id, { ...item, children: [] }));
flatData.forEach((item) => {
const node = nodeMap.get(item.id)!;
if (item.parent_detail_id && nodeMap.has(item.parent_detail_id)) {
nodeMap.get(item.parent_detail_id)!.children.push(node);
if (item[parentKey] && nodeMap.has(item[parentKey])) {
nodeMap.get(item[parentKey])!.children.push(node);
} else {
roots.push(node);
}
});
return roots;
};
// 선택된 BOM 변경 시 데이터 로드
useEffect(() => {
if (selectedBomId) {
setHeaderInfo(selectedHeaderData);
loadBomDetails(selectedBomId);
loadBomDetails(selectedBomId, selectedHeaderData);
} else {
setHeaderInfo(null);
setTreeData([]);
}
}, [selectedBomId, selectedHeaderData, loadBomDetails]);
// 노드 펼치기/접기 토글
const toggleNode = useCallback((nodeId: string) => {
setExpandedNodes((prev) => {
const next = new Set(prev);
if (next.has(nodeId)) {
next.delete(nodeId);
} else {
next.add(nodeId);
}
if (next.has(nodeId)) next.delete(nodeId);
else next.add(nodeId);
return next;
});
}, []);
// 전체 펼치기
const expandAll = useCallback(() => {
const allIds = new Set<string>();
const collectIds = (nodes: BomTreeNode[]) => {
@ -194,270 +215,381 @@ export function BomTreeComponent({
setExpandedNodes(allIds);
}, [treeData]);
// 전체 접기
const collapseAll = useCallback(() => {
setExpandedNodes(new Set());
}, []);
const collapseAll = useCallback(() => setExpandedNodes(new Set()), []);
// ─── 유틸 ───
// 품목 구분 라벨
const getItemTypeLabel = (type: string) => {
switch (type) {
case "product": return "제품";
case "semi": return "반제품";
case "material": return "원자재";
case "part": return "부품";
default: return type || "-";
}
const map: Record<string, string> = { product: "제품", semi: "반제품", material: "원자재", part: "부품" };
return map[type] || type || "-";
};
// 품목 구분 아이콘 & 색상
const getItemTypeStyle = (type: string) => {
switch (type) {
case "product":
return { icon: Package, color: "text-blue-600", bg: "bg-blue-50" };
case "semi":
return { icon: Layers, color: "text-amber-600", bg: "bg-amber-50" };
case "material":
return { icon: Box, color: "text-emerald-600", bg: "bg-emerald-50" };
default:
return { icon: Box, color: "text-gray-500", bg: "bg-gray-50" };
}
const getItemTypeBadge = (type: string) => {
const map: Record<string, string> = {
product: "bg-blue-50 text-blue-600 ring-blue-200",
semi: "bg-amber-50 text-amber-600 ring-amber-200",
material: "bg-emerald-50 text-emerald-600 ring-emerald-200",
part: "bg-purple-50 text-purple-600 ring-purple-200",
};
return map[type] || "bg-gray-50 text-gray-500 ring-gray-200";
};
// 디자인 모드 미리보기
const getItemIcon = (type: string) => {
const map: Record<string, any> = { product: Package, semi: Layers };
return map[type] || Box;
};
const getItemIconColor = (type: string) => {
const map: Record<string, string> = {
product: "text-blue-500",
semi: "text-amber-500",
material: "text-emerald-500",
part: "text-purple-500",
};
return map[type] || "text-gray-400";
};
// ─── 셀 렌더링 ───
const renderCellValue = (node: BomTreeNode, col: TreeColumnDef, depth: number) => {
const value = node[col.key];
if (col.key === "child_item_type" || col.key === "item_type") {
const label = getItemTypeLabel(String(value || ""));
return (
<span className={cn(
"inline-flex items-center rounded-md px-1.5 py-0.5 text-[10px] font-medium ring-1 ring-inset",
getItemTypeBadge(String(value || "")),
)}>
{label}
</span>
);
}
if (col.key === "level") {
return (
<span className="inline-flex h-5 w-5 items-center justify-center rounded bg-gray-100 text-[10px] font-medium text-gray-600">
{value ?? depth}
</span>
);
}
if (col.key === "child_item_code") {
return <span className="font-mono text-xs text-gray-700">{value || "-"}</span>;
}
if (col.key === "child_item_name") {
return <span className="font-medium text-gray-900">{value || "-"}</span>;
}
if (col.key === "quantity" || col.key === "base_qty") {
return (
<span className="font-medium tabular-nums text-gray-800">
{value != null && value !== "" && value !== "0" ? value : "-"}
</span>
);
}
if (col.key === "loss_rate") {
const num = Number(value);
if (!num) return <span className="text-gray-300">-</span>;
return <span className="tabular-nums text-amber-600">{value}%</span>;
}
if (col.key === "revision") {
return (
<span className="tabular-nums text-gray-600">
{value != null && value !== "" && value !== "0" ? value : "-"}
</span>
);
}
if (col.key === "unit") {
return <span className="text-gray-500">{value || "-"}</span>;
}
return <span className="text-gray-600">{value ?? "-"}</span>;
};
// ─── 디자인 모드 ───
if (isDesignMode) {
const configuredColumns = (config.columns || []).filter((c: TreeColumnDef) => !c.hidden);
return (
<div className="flex h-full flex-col rounded-md border bg-white p-4">
<div className="mb-3 flex items-center gap-2">
<Layers className="h-4 w-4 text-primary" />
<span className="text-sm font-medium">BOM </span>
<div className="flex h-full flex-col overflow-hidden rounded-lg border bg-white shadow-sm">
<div className="flex items-center gap-2 border-b bg-gray-50/80 px-4 py-2.5">
<Package className="h-4 w-4 text-primary" />
<span className="text-sm font-semibold">BOM </span>
<span className="rounded-md bg-gray-100 px-1.5 py-0.5 text-[10px] text-gray-500">{detailTable}</span>
{config.dataSource?.sourceTable && (
<span className="rounded-md bg-blue-50 px-1.5 py-0.5 text-[10px] text-blue-500">
{config.dataSource.sourceTable}
</span>
)}
</div>
<div className="flex-1 space-y-1 rounded border border-dashed border-gray-300 p-3">
<div className="flex items-center gap-2 text-xs text-gray-500">
<ChevronDown className="h-3 w-3" />
<Package className="h-3 w-3 text-blue-500" />
<span> A ()</span>
<span className="ml-auto text-gray-400">수량: 1</span>
{configuredColumns.length === 0 ? (
<div className="flex flex-1 flex-col items-center justify-center gap-2 p-6">
<AlertCircle className="h-8 w-8 text-gray-200" />
<p className="text-sm font-medium text-gray-400"> </p>
<p className="text-[11px] text-gray-300"> &gt; </p>
</div>
<div className="ml-5 flex items-center gap-2 text-xs text-gray-500">
<ChevronRight className="h-3 w-3" />
<Layers className="h-3 w-3 text-amber-500" />
<span> B ()</span>
<span className="ml-auto text-gray-400">수량: 2</span>
) : (
<div className="flex-1 overflow-hidden">
<table className="w-full text-xs">
<thead>
<tr className="border-b bg-gray-50">
<th className="w-10 border-r border-gray-100 px-2 py-2"></th>
{configuredColumns.map((col: TreeColumnDef) => (
<th
key={col.key}
className="border-r border-gray-100 px-3 py-2 text-left text-[11px] font-semibold text-gray-600"
style={{ width: col.width }}
>
{col.title || col.key}
</th>
))}
</tr>
</thead>
<tbody className="text-gray-400">
<tr className="border-b bg-white">
<td className="border-r border-gray-50 px-2 py-2">
<ChevronDown className="h-3.5 w-3.5 text-gray-300" />
</td>
{configuredColumns.map((col: TreeColumnDef, i: number) => (
<td key={col.key} className="border-r border-gray-50 px-3 py-2">
{col.key === "level" ? "0" : col.key.includes("type") ? (
<span className="rounded-md bg-blue-50 px-1.5 py-0.5 text-[10px] text-blue-500 ring-1 ring-inset ring-blue-200"></span>
) : col.key.includes("quantity") || col.key.includes("qty") ? "30" : `예시${i + 1}`}
</td>
))}
</tr>
<tr className="border-b bg-gray-50/30">
<td className="border-r border-gray-50 px-2 py-2 pl-7">
<span className="inline-block h-1 w-1 rounded-full bg-gray-300" />
</td>
{configuredColumns.map((col: TreeColumnDef, i: number) => (
<td key={col.key} className="border-r border-gray-50 px-3 py-2 text-gray-300">
{col.key === "level" ? "1" : col.key.includes("type") ? (
<span className="rounded-md bg-amber-50 px-1.5 py-0.5 text-[10px] text-amber-500 ring-1 ring-inset ring-amber-200"></span>
) : col.key.includes("quantity") || col.key.includes("qty") ? "3" : `예시${i + 1}`}
</td>
))}
</tr>
</tbody>
</table>
</div>
<div className="ml-5 flex items-center gap-2 text-xs text-gray-500">
<span className="ml-3.5" />
<Box className="h-3 w-3 text-emerald-500" />
<span> C ()</span>
<span className="ml-auto text-gray-400">수량: 5</span>
</div>
</div>
)}
</div>
);
}
// 선택 안 된 상태
// ─── 미선택 상태 ───
if (!selectedBomId) {
return (
<div className="flex h-full items-center justify-center">
<div className="text-muted-foreground text-center text-sm">
<p className="mb-2"> BOM을 </p>
<p className="text-xs"> BOM의 </p>
<div className="flex h-full items-center justify-center bg-gray-50/30">
<div className="text-center">
<Package className="mx-auto mb-3 h-10 w-10 text-gray-200" />
<p className="text-sm font-medium text-gray-400">BOM을 </p>
<p className="mt-1 text-xs text-gray-300"> BOM을 </p>
</div>
</div>
);
}
// ─── 트리 평탄화 ───
const flattenedRows = useMemo(() => {
const rows: { node: BomTreeNode; depth: number }[] = [];
const traverse = (nodes: BomTreeNode[], depth: number) => {
for (const node of nodes) {
rows.push({ node, depth });
if (node.children.length > 0 && expandedNodes.has(node.id)) {
traverse(node.children, depth + 1);
}
}
};
traverse(treeData, 0);
return rows;
}, [treeData, expandedNodes]);
// ─── 메인 렌더링 ───
return (
<div className="flex h-full flex-col">
<div className="flex h-full flex-col bg-white">
{/* 헤더 정보 */}
{headerInfo && (
<div className="border-b bg-gray-50/80 px-4 py-3">
<div className="mb-2 flex items-center gap-2">
<Package className="h-4 w-4 text-primary" />
<h3 className="text-sm font-semibold">{headerInfo.item_name || "-"}</h3>
<span className="rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary">
{headerInfo.bom_number || "-"}
</span>
<span className={cn(
"ml-1 rounded px-1.5 py-0.5 text-[10px] font-medium",
headerInfo.status === "active" ? "bg-emerald-100 text-emerald-700" : "bg-gray-100 text-gray-500"
{features.showHeader !== false && headerInfo && (
<div className="border-b px-5 py-3">
<div className="flex items-center gap-2.5">
<div className={cn(
"flex h-8 w-8 items-center justify-center rounded-lg",
getItemTypeBadge(headerInfo.item_type).split(" ").slice(0, 1).join(" "),
)}>
{headerInfo.status === "active" ? "사용" : "미사용"}
</span>
</div>
<div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground">
<span>: <b className="text-foreground">{headerInfo.item_code || "-"}</b></span>
<span>: <b className="text-foreground">{getItemTypeLabel(headerInfo.item_type)}</b></span>
<span>: <b className="text-foreground">{headerInfo.base_qty || "1"} {headerInfo.unit || ""}</b></span>
<span>: <b className="text-foreground">v{headerInfo.version || "1.0"} ( {headerInfo.revision || "1"})</b></span>
<Package className={cn("h-4 w-4", getItemIconColor(headerInfo.item_type))} />
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<h3 className="truncate text-sm font-semibold text-gray-900">
{headerInfo.item_name || "-"}
</h3>
<span className={cn(
"inline-flex items-center rounded-md px-1.5 py-0.5 text-[10px] font-medium ring-1 ring-inset",
getItemTypeBadge(headerInfo.item_type),
)}>
{getItemTypeLabel(headerInfo.item_type)}
</span>
<span className={cn(
"rounded-md px-1.5 py-0.5 text-[10px] font-medium ring-1 ring-inset",
headerInfo.status === "active"
? "bg-emerald-50 text-emerald-600 ring-emerald-200"
: "bg-gray-50 text-gray-400 ring-gray-200",
)}>
{headerInfo.status === "active" ? "사용" : "미사용"}
</span>
</div>
<div className="mt-0.5 flex gap-3 text-[11px] text-gray-400">
<span> <b className="text-gray-600">{headerInfo.item_code || "-"}</b></span>
<span> <b className="text-gray-600">{headerInfo.base_qty || "1"}</b></span>
<span> <b className="text-gray-600">v{headerInfo.version || "1"} ( {headerInfo.revision || "1"})</b></span>
</div>
</div>
</div>
</div>
)}
{/* 트리 툴바 */}
<div className="flex items-center gap-2 border-b px-4 py-2">
<span className="text-xs font-medium text-muted-foreground">BOM </span>
<span className="rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary">
{treeData.length}
{/* 툴바 */}
<div className="flex items-center border-b bg-gray-50/50 px-5 py-1.5">
<span className="text-xs font-medium text-gray-500">BOM </span>
<span className="ml-2 rounded-full bg-primary/10 px-2 py-0.5 text-[10px] font-semibold text-primary">
{flattenedRows.length}
</span>
<div className="ml-auto flex gap-1">
<button
onClick={expandAll}
className="rounded px-2 py-0.5 text-[10px] text-muted-foreground hover:bg-gray-100"
>
</button>
<button
onClick={collapseAll}
className="rounded px-2 py-0.5 text-[10px] text-muted-foreground hover:bg-gray-100"
>
</button>
</div>
{features.showExpandAll !== false && (
<div className="ml-auto flex gap-1">
<Button variant="ghost" size="sm" onClick={expandAll} className="h-6 gap-1 px-2 text-[10px] text-gray-400 hover:text-gray-600">
<Expand className="h-3 w-3" />
</Button>
<Button variant="ghost" size="sm" onClick={collapseAll} className="h-6 gap-1 px-2 text-[10px] text-gray-400 hover:text-gray-600">
<Shrink className="h-3 w-3" />
</Button>
</div>
)}
</div>
{/* 트리 컨텐츠 */}
<div className="flex-1 overflow-auto px-2 py-2">
{/* 테이블 */}
<div className="flex-1 overflow-auto">
{loading ? (
<div className="flex h-32 items-center justify-center">
<div className="text-muted-foreground text-sm"> ...</div>
<div className="flex h-40 items-center justify-center">
<Loader2 className="h-5 w-5 animate-spin text-primary" />
</div>
) : displayColumns.length === 0 ? (
<div className="flex h-40 flex-col items-center justify-center gap-2">
<AlertCircle className="h-6 w-6 text-gray-200" />
<p className="text-xs text-gray-400"> </p>
<p className="text-[10px] text-gray-300"> </p>
</div>
) : treeData.length === 0 ? (
<div className="flex h-32 flex-col items-center justify-center gap-2">
<AlertCircle className="h-5 w-5 text-muted-foreground" />
<p className="text-xs text-muted-foreground"> </p>
<div className="flex h-40 flex-col items-center justify-center gap-2">
<Box className="h-8 w-8 text-gray-200" />
<p className="text-xs text-gray-400"> </p>
</div>
) : (
<div className="space-y-0.5">
{treeData.map((node) => (
<TreeNodeRow
key={node.id}
node={node}
depth={0}
expandedNodes={expandedNodes}
selectedNodeId={selectedNodeId}
onToggle={toggleNode}
onSelect={setSelectedNodeId}
getItemTypeLabel={getItemTypeLabel}
getItemTypeStyle={getItemTypeStyle}
/>
))}
</div>
<table className="w-full border-collapse text-xs">
<thead className="sticky top-0 z-10">
<tr className="border-b bg-gray-50">
<th className="w-10 px-2 py-2.5"></th>
{displayColumns.map((col) => {
const centered = ["quantity", "loss_rate", "level", "base_qty", "revision", "seq_no"].includes(col.key);
return (
<th
key={col.key}
className={cn(
"px-3 py-2.5 text-[11px] font-semibold text-gray-500",
centered ? "text-center" : "text-left",
)}
style={{ width: col.width || "auto" }}
>
{col.title}
</th>
);
})}
</tr>
</thead>
<tbody>
{flattenedRows.map(({ node, depth }, rowIdx) => {
const hasChildren = node.children.length > 0;
const isExpanded = expandedNodes.has(node.id);
const isSelected = selectedNodeId === node.id;
const isRoot = !!node._isVirtualRoot;
const itemType = node.child_item_type || node.item_type || "";
const ItemIcon = getItemIcon(itemType);
return (
<tr
key={node.id}
className={cn(
"group cursor-pointer border-b transition-colors",
isRoot
? "border-gray-200 bg-blue-50/40 font-medium hover:bg-blue-50/60"
: isSelected
? "border-gray-100 bg-primary/5"
: rowIdx % 2 === 0
? "border-gray-100 bg-white hover:bg-gray-50/80"
: "border-gray-100 bg-gray-50/30 hover:bg-gray-50/80",
)}
onClick={() => {
setSelectedNodeId(node.id);
if (hasChildren) toggleNode(node.id);
}}
>
<td className="px-1 py-2" style={{ paddingLeft: `${depth * 20 + 8}px` }}>
<div className="flex items-center gap-1">
<span className="flex h-4 w-4 flex-shrink-0 items-center justify-center">
{hasChildren ? (
isExpanded ? (
<ChevronDown className={cn("h-3.5 w-3.5 transition-transform", isRoot ? "text-blue-500" : "text-gray-400")} />
) : (
<ChevronRight className={cn("h-3.5 w-3.5 transition-transform", isRoot ? "text-blue-500" : "text-gray-400")} />
)
) : (
<span className="h-1 w-1 rounded-full bg-gray-300" />
)}
</span>
<span className={cn(
"flex h-5 w-5 items-center justify-center rounded",
getItemTypeBadge(itemType).split(" ").slice(0, 1).join(" "),
)}>
<ItemIcon className={cn(isRoot ? "h-3.5 w-3.5" : "h-3 w-3", getItemIconColor(itemType))} />
</span>
</div>
</td>
{displayColumns.map((col) => {
const centered = ["quantity", "loss_rate", "level", "base_qty", "revision", "seq_no"].includes(col.key);
return (
<td
key={col.key}
className={cn(
"px-3 py-2",
centered ? "text-center" : "text-left",
)}
>
{renderCellValue(node, col, depth)}
</td>
);
})}
</tr>
);
})}
</tbody>
</table>
)}
</div>
</div>
);
}
/**
* ( )
*/
interface TreeNodeRowProps {
node: BomTreeNode;
depth: number;
expandedNodes: Set<string>;
selectedNodeId: string | null;
onToggle: (id: string) => void;
onSelect: (id: string) => void;
getItemTypeLabel: (type: string) => string;
getItemTypeStyle: (type: string) => { icon: any; color: string; bg: string };
}
function TreeNodeRow({
node,
depth,
expandedNodes,
selectedNodeId,
onToggle,
onSelect,
getItemTypeLabel,
getItemTypeStyle,
}: TreeNodeRowProps) {
const isExpanded = expandedNodes.has(node.id);
const hasChildren = node.children.length > 0;
const isSelected = selectedNodeId === node.id;
const style = getItemTypeStyle(node.child_item_type);
const ItemIcon = style.icon;
return (
<>
<div
className={cn(
"group flex cursor-pointer items-center gap-1.5 rounded-md px-2 py-1.5 transition-colors",
isSelected ? "bg-primary/10" : "hover:bg-gray-50"
)}
style={{ paddingLeft: `${depth * 20 + 8}px` }}
onClick={() => {
onSelect(node.id);
if (hasChildren) onToggle(node.id);
}}
>
{/* 펼치기/접기 화살표 */}
<span className="flex h-4 w-4 flex-shrink-0 items-center justify-center">
{hasChildren ? (
isExpanded ? (
<ChevronDown className="h-3.5 w-3.5 text-gray-400" />
) : (
<ChevronRight className="h-3.5 w-3.5 text-gray-400" />
)
) : (
<span className="h-1 w-1 rounded-full bg-gray-300" />
)}
</span>
{/* 품목 타입 아이콘 */}
<span className={cn("flex h-5 w-5 flex-shrink-0 items-center justify-center rounded", style.bg)}>
<ItemIcon className={cn("h-3 w-3", style.color)} />
</span>
{/* 품목 정보 */}
<div className="flex min-w-0 flex-1 items-center gap-2">
<span className="truncate text-xs font-medium text-foreground">
{node.child_item_name || "-"}
</span>
<span className="flex-shrink-0 text-[10px] text-muted-foreground">
{node.child_item_code || ""}
</span>
<span className={cn(
"flex-shrink-0 rounded px-1 py-0.5 text-[10px]",
style.bg, style.color
)}>
{getItemTypeLabel(node.child_item_type)}
</span>
</div>
{/* 수량/단위 */}
<div className="flex flex-shrink-0 items-center gap-2 text-[11px]">
<span className="text-muted-foreground">
: <b className="text-foreground">{node.quantity || "0"}</b> {node.unit || ""}
</span>
{node.loss_rate && node.loss_rate !== "0" && (
<span className="text-amber-600">
: {node.loss_rate}%
</span>
)}
</div>
</div>
{/* 하위 노드 재귀 렌더링 */}
{hasChildren && isExpanded && (
<div>
{node.children.map((child) => (
<TreeNodeRow
key={child.id}
node={child}
depth={depth + 1}
expandedNodes={expandedNodes}
selectedNodeId={selectedNodeId}
onToggle={onToggle}
onSelect={onSelect}
getItemTypeLabel={getItemTypeLabel}
getItemTypeStyle={getItemTypeStyle}
/>
))}
</div>
)}
</>
);
}
export default BomTreeComponent;

View File

@ -1791,7 +1791,7 @@ export class ButtonActionExecutor {
// 🔧 formData를 리피터에 전달하여 각 행에 병합 저장
const savedId = saveResult?.data?.id || saveResult?.data?.data?.id || formData.id || context.formData?.id;
// _deferSave 데이터 처리 (마스터-디테일 순차 저장: 메인 저장 후 디테일 저장)
// _deferSave 데이터 처리 (마스터-디테일 순차 저장: 레벨별 저장 + temp→real ID 매핑)
if (savedId) {
for (const [fieldKey, fieldValue] of Object.entries(context.formData)) {
let parsedData = fieldValue;
@ -1804,27 +1804,47 @@ export class ButtonActionExecutor {
const targetTable = parsedData[0]?._targetTable;
if (!targetTable) continue;
for (const item of parsedData) {
const { _targetTable: _, _isNew, _deferSave: __, _fkColumn: fkCol, tempId: ___, ...data } = item;
if (!data.id || data.id === "") delete data.id;
// 레벨별 그룹핑 (레벨 0 먼저 저장 → 레벨 1 → ...)
const maxLevel = Math.max(...parsedData.map((item: any) => Number(item.level) || 0));
const tempIdToRealId = new Map<string, string>();
// FK 주입
if (fkCol) data[fkCol] = savedId;
for (let lvl = 0; lvl <= maxLevel; lvl++) {
const levelItems = parsedData.filter((item: any) => (Number(item.level) || 0) === lvl);
// 시스템 필드 추가
data.created_by = context.userId;
data.updated_by = context.userId;
data.company_code = context.companyCode;
for (const item of levelItems) {
const { _targetTable: _, _isNew, _deferSave: __, _fkColumn: fkCol, tempId, ...data } = item;
if (!data.id || data.id === "") delete data.id;
try {
const isNew = _isNew || !item.id || item.id === "";
if (isNew) {
await apiClient.post(`/table-management/tables/${targetTable}/add`, data);
} else {
await apiClient.put(`/table-management/tables/${targetTable}/${item.id}`, data);
// FK 주입 (bom_id 등)
if (fkCol) data[fkCol] = savedId;
// parent_detail_id의 temp 참조를 실제 ID로 교체
if (data.parent_detail_id && tempIdToRealId.has(data.parent_detail_id)) {
data.parent_detail_id = tempIdToRealId.get(data.parent_detail_id);
}
// 시스템 필드 추가
data.created_by = context.userId;
data.updated_by = context.userId;
data.company_code = context.companyCode;
try {
const isNew = _isNew || !item.id || item.id === "";
if (isNew) {
const res = await apiClient.post(`/table-management/tables/${targetTable}/add`, data);
const newId = res.data?.data?.id || res.data?.id;
if (newId && tempId) {
tempIdToRealId.set(tempId, newId);
}
} else {
await apiClient.put(`/table-management/tables/${targetTable}/${item.id}`, data);
if (item.id && tempId) {
tempIdToRealId.set(tempId, item.id);
}
}
} catch (err: any) {
console.error(`[handleSave] 디테일 저장 실패 (${targetTable}):`, err.response?.data || err.message);
}
} catch (err: any) {
console.error(`[handleSave] 디테일 저장 실패 (${targetTable}):`, err.response?.data || err.message);
}
}
}