diff --git a/app/Http/Controllers/Api/V1/ItemsBomController.php b/app/Http/Controllers/Api/V1/ItemsBomController.php index de217429..71d3b429 100644 --- a/app/Http/Controllers/Api/V1/ItemsBomController.php +++ b/app/Http/Controllers/Api/V1/ItemsBomController.php @@ -446,12 +446,13 @@ private function expandBomItems(array $bom): array 'child_item_type' => $childItem?->item_type, 'unit' => $childItem?->unit, 'quantity' => $entry['quantity'] ?? 1, + 'category' => $entry['category'] ?? null, ]; })->toArray(); } /** - * BOM 트리 구조 빌드 (재귀) + * BOM 트리 구조 빌드 (재귀, category 필드가 있으면 3단계 그룹화) */ private function buildBomTree(Item $item, int $maxDepth, int $currentDepth): array { @@ -478,14 +479,47 @@ private function buildBomTree(Item $item, int $maxDepth, int $currentDepth): arr ->get() ->keyBy('id'); - foreach ($bom as $entry) { - $childItemId = $entry['child_item_id'] ?? null; - $childItem = $childItems[$childItemId] ?? null; + // category 필드가 있으면 카테고리별 그룹 노드 생성 (3단계) + $hasCategory = collect($bom)->contains(fn ($b) => ! empty($b['category'])); - if ($childItem) { - $childTree = $this->buildBomTree($childItem, $maxDepth, $currentDepth + 1); - $childTree['quantity'] = $entry['quantity'] ?? 1; - $result['children'][] = $childTree; + if ($hasCategory) { + $grouped = []; + foreach ($bom as $entry) { + $cat = $entry['category'] ?? '기타'; + $grouped[$cat][] = $entry; + } + + foreach ($grouped as $catName => $catEntries) { + $catChildren = []; + foreach ($catEntries as $entry) { + $childItem = $childItems[$entry['child_item_id'] ?? null] ?? null; + if ($childItem) { + $childTree = $this->buildBomTree($childItem, $maxDepth, $currentDepth + 2); + $childTree['quantity'] = $entry['quantity'] ?? 1; + $catChildren[] = $childTree; + } + } + if (! empty($catChildren)) { + $result['children'][] = [ + 'id' => 0, + 'code' => '', + 'name' => $catName, + 'item_type' => 'CAT', + 'unit' => '', + 'depth' => $currentDepth + 1, + 'count' => count($catChildren), + 'children' => $catChildren, + ]; + } + } + } else { + foreach ($bom as $entry) { + $childItem = $childItems[$entry['child_item_id'] ?? null] ?? null; + if ($childItem) { + $childTree = $this->buildBomTree($childItem, $maxDepth, $currentDepth + 1); + $childTree['quantity'] = $entry['quantity'] ?? 1; + $result['children'][] = $childTree; + } } }