whereIn('rf_department_id', $departmentIds) ->where('period_start', '>=', $startDate) ->where('period_end', '<', $endDate) ->get(['report_id', 'rf_department_id']) ->groupBy('rf_department_id'); $preoperativeDays = []; foreach ($departmentIds as $deptId) { $reportIds = $reports->get($deptId)?->pluck('report_id')->all() ?? []; if ($reportIds === []) { $preoperativeDays[$deptId] = 0; continue; } $historyIds = MedicalHistorySnapshot::query() ->whereIn('rf_report_id', $reportIds) ->whereIn('patient_type', ['discharged', 'deceased']) ->pluck('rf_medicalhistory_id') ->filter() ->unique() ->values(); if ($historyIds->isEmpty()) { $preoperativeDays[$deptId] = 0; continue; } $histories = MedicalHistory::query() ->whereIn('original_id', $historyIds) ->with(['operations']) ->get(); $totalDays = 0; $count = 0; foreach ($histories as $history) { $operationDate = $history->operations ->pluck('operation_date') ->filter() ->sort() ->first(); if (! $history->recipient_date || ! $operationDate) { continue; } $admission = Carbon::parse($history->recipient_date); $operation = Carbon::parse($operationDate); $days = $admission->diffInDays($operation); if ($days >= 0) { $totalDays += $days; $count++; } } $preoperativeDays[$deptId] = $count > 0 ? round($totalDays / $count, 1) : 0; } return $preoperativeDays; } catch (\Exception $e) { \Log::error('Error in calculatePreoperativeDaysFromSnapshots: '.$e->getMessage()); return array_fill_keys($departmentIds, 0); } } public function getMetricsForReport(Report $report): array { $metrics = []; foreach ($report->metrikaResults as $metrikaResult) { $metrikaResult->load('metrikaItem'); $metrics[] = [ 'metrika_id' => $metrikaResult->rf_metrika_item_id, 'value_id' => $metrikaResult->metrika_result_id, 'name' => $metrikaResult->metrikaItem->name, 'value' => $metrikaResult->value, ]; } return $metrics; } }