patientService = $patientService; } public function createReport(array $data): Report { DB::beginTransaction(); try { $report = Report::create([ 'rf_department_id' => $data['departmentId'], 'rf_user_id' => Auth::id(), 'sent_at' => now() ]); $this->saveMetrics($report, $data['metrics'] ?? []); $this->saveUnwantedEvents($report, $data['unwantedEvents'] ?? []); $this->saveObservationPatients($report, $data['observationPatients'] ?? []); $this->savePatientSnapshots($report, $data); DB::commit(); return $report; } catch (\Exception $e) { DB::rollBack(); throw $e; } } private function saveMetrics(Report $report, array $metrics): void { foreach ($metrics as $key => $value) { MetrikaResult::create([ 'rf_report_id' => $report->report_id, 'rf_metrika_item_id' => (int) str_replace('metrika_item_', '', $key), 'value' => $value ]); } } private function saveUnwantedEvents(Report $report, array $unwantedEvents): void { foreach ($unwantedEvents as $event) { if (isset($event['unwanted_event_id'])) { UnwantedEvent::updateOrCreate( ['unwanted_event_id' => $event['unwanted_event_id']], $this->formatUnwantedEventData($report, $event) ); } else { UnwantedEvent::create($this->formatUnwantedEventData($report, $event)); } } } private function formatUnwantedEventData(Report $report, array $event): array { return [ 'rf_report_id' => $report->report_id, 'comment' => $event['comment'] ?? '', 'title' => $event['title'] ?? '', 'is_visible' => $event['is_visible'] ?? true, ]; } private function saveObservationPatients(Report $report, array $observationPatients): void { foreach ($observationPatients as $patient) { ObservationPatient::create([ 'rf_department_id' => $report->rf_department_id, 'rf_report_id' => $report->report_id, 'rf_medicalhistory_id' => $patient['id'], 'comment' => $patient['comment'] ?? null ]); } } private function savePatientSnapshots(Report $report, array $data): void { $snapshotTypes = [ 'plan' => $this->patientService->getPlanPatients( false, $data['branchId'], $data['startDate'], $data['endDate'], false, true ), 'emergency' => $this->patientService->getEmergencyPatients( false, $data['branchId'], $data['startDate'], $data['endDate'], false, true ) ]; foreach ($snapshotTypes as $type => $patientIds) { foreach ($patientIds as $patientId) { MedicalHistorySnapshot::create([ 'rf_report_id' => $report->report_id, 'rf_medicalhistory_id' => $patientId, 'patient_type' => $type ]); } } } }