get(); $allHosts = ModuleHost::with(['datastore', 'network'])->get()->groupBy('module_datacenter_id'); $allFolders = ModuleFolder::all()->groupBy('module_datacenter_id'); $tree = $vcenters->map(function ($vc) use ($allHosts, $allFolders) { $dcGroups = ($vc->datacenters ?? collect())->groupBy('datacenter_id'); $datacenters = $dcGroups->map(function ($dcGroup) use ($allHosts, $allFolders) { $dc = $dcGroup->first(); $dcIds = $dcGroup->pluck('id'); $uniqueHosts = $dcIds->flatMap(fn($id) => $allHosts->get($id) ?? collect()) ->unique('host_id')->values(); $dcNetworks = $uniqueHosts ->flatMap(fn($host) => $host->network ?? collect()) ->unique('network') ->map(fn($net) => [ 'id' => 'network-' . $net->id, 'name' => $net->name, 'type' => 'network', 'meta' => ['db_id' => $net->id, 'network_id' => $net->network, 'net_type' => $net->type], ]); $dcHosts = $uniqueHosts->map(function ($host) { $datastores = ($host->datastore ?? collect()) ->unique('datastore') ->map(fn($ds) => [ 'id' => 'datastore-' . $ds->id, 'name' => $ds->name, 'type' => 'datastore', 'meta' => [ 'db_id' => $ds->id, 'datastore_id' => $ds->datastore, 'store_type' => $ds->type, 'space_gb' => $ds->space ? round($ds->space / 1024, 1) : null, 'status' => $ds->status, ], ]); return [ 'id' => 'host-' . $host->id, 'name' => $host->name, 'type' => 'host', 'meta' => ['db_id' => $host->id, 'host_id' => $host->host_id, 'console' => $host->console], 'children' => array_values($datastores->toArray()), ]; }); $dcFolders = $dcIds ->flatMap(fn($id) => $allFolders->get($id) ?? collect()) ->unique('folder') ->map(fn($f) => [ 'id' => 'folder-' . $f->id, 'name' => $f->name, 'type' => 'folder', 'meta' => ['db_id' => $f->id, 'folder_id' => $f->folder, 'folder_type' => $f->type], ]); return [ 'id' => 'datacenter-' . $dc->id, 'name' => $dc->name, 'type' => 'datacenter', 'meta' => ['db_id' => $dc->id, 'datacenter_id' => $dc->datacenter_id], 'children' => array_values($dcFolders->concat($dcNetworks)->concat($dcHosts)->toArray()), ]; })->values(); return [ 'id' => 'vcenter-' . $vc->id, 'name' => $vc->host, 'type' => 'vcenter', 'meta' => ['db_id' => $vc->id, 'host' => $vc->host, 'status' => $vc->status], 'children' => array_values($datacenters->toArray()), ]; }); return response()->json(['error' => false, 'data' => $tree->values()]); } }