Files
onboard/app/Domain/ReportDuty/Actions/GenerateAndSaveReportSnapshotAction.php
2026-07-31 17:19:03 +09:00

112 lines
5.5 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Domain\ReportDuty\Actions;
use App\Domain\ReportDuty\Contracts\ReportDutySnapshotRepositoryInterface;
use App\Domain\ReportDuty\Models\ReportDuty;
use App\Domain\ReportDuty\Services\ReportDutyStatisticsCalculator;
use App\Infrastructure\Services\MisPatientSnapshotProvider;
use App\Infrastructure\Services\NurseReportPatientSnapshotProvider;
use App\Services\DateRange;
use Illuminate\Support\Facades\Log;
class GenerateAndSaveReportSnapshotAction
{
public function __construct(
protected MisPatientSnapshotProvider $misProvider,
protected NurseReportPatientSnapshotProvider $nurseProvider,
protected ReportDutySnapshotRepositoryInterface $snapshotRepository,
protected ReportDutyStatisticsCalculator $statisticsCalculator,
protected SaveReportMetricsAction $saveMetricsAction,
) {}
public function execute(
ReportDuty $report,
DateRange $dateRange,
?int $departmentId = null,
?int $userId = null
): array {
$departmentId = $departmentId ?? $report->department->rf_mis_department_id ?? $report->rf_department_id;
$userId = $userId ?? $report->rf_user_id;
// 1. Определяем, есть ли отчёт медсестры за этот период
$nurseReportExists = \App\Models\ReportNurse::where('rf_department_id', $report->rf_department_id)
->where('period_start', $report->period_start)
->where('period_end', $report->period_end)
->exists();
// 2. Получаем данные пациентов через соответствующий провайдер
if ($nurseReportExists) {
$patients = $this->nurseProvider->getPatients($dateRange, $departmentId);
} else {
$patients = $this->misProvider->getPatients($dateRange, $departmentId);
}
// 3. Извлекаем миграции и реанимации из пациентов для сохранения
$migrations = collect();
$reanimations = collect();
foreach ($patients as $patient) {
// Преобразуем миграции в DTO
foreach ($patient->migrations as $migData) {
$migrations->push(new \App\Domain\ReportDuty\DTO\MigrationSnapshotData(
id: $migData['id'],
medicalHistoryId: $patient->id,
ingoingDate: $migData['ingoing_date'],
outDate: $migData['out_date'],
diagnosisId: $migData['diagnosis_id'],
diagnosisCode: $migData['diagnosis_code'],
diagnosisName: $migData['diagnosis_name'],
interruptedEventId: $migData['interrupted_event_id'],
stationarBranchId: $migData['stationar_branch_id'],
departmentId: $migData['department_id'],
visitResultId: $migData['visit_result_id'],
statCureResultId: $migData['stat_cure_result_id'],
userId: $migData['user_id'],
misUserId: $migData['mis_user_id'],
comment: $migData['comment'],
reanimations: $migData['reanimations'] ?? [],
));
}
// Реанимации будем брать из миграций, но можно и отдельно, здесь пока пропускаем
// (в репозитории они будут обработаны из миграций, но у нас нет отдельного хранилища)
}
// Заметка: реанимации сейчас хранятся внутри миграций, но в репозитории мы ожидаем их отдельно.
// Чтобы упростить, можно либо передать пустую коллекцию, либо извлечь из миграций.
// В оригинале они сохранялись в отдельной таблице. Мы можем передать пустую коллекцию,
// но если хотим сохранять реанимации, нужно их собрать из $patient->migrations['reanimations'].
// Я пока передам пустую коллекцию, так как в провайдерах реанимации не извлекаются
// (кроме МИС, но там они внутри миграций). Можно позже доработать.
// 4. Сохраняем снимок в БД
$saveResult = $this->snapshotRepository->upsertSnapshot(
$report->id,
$patients,
$migrations->lazy(),
collect()->lazy(), // пока без реанимаций
$userId,
$departmentId
);
// 5. Рассчитываем статистику
$statistics = $this->statisticsCalculator->calculate($patients, $dateRange);
// 6. Сохраняем метрики
$this->saveMetricsAction->execute($report, $statistics, 0); // staff = 0 пока
Log::info('Report snapshot generated', [
'report_id' => $report->id,
'saved_patients' => $saveResult['savedPatients'],
'saved_migrations' => $saveResult['savedMigrations'],
'statistics' => $statistics,
]);
return [
'statistics' => $statistics,
'saved' => $saveResult,
];
}
}