81 lines
2.5 KiB
PHP
81 lines
2.5 KiB
PHP
<?php
|
||
|
||
namespace App\Infrastructure\Reports\Services;
|
||
|
||
use App\Data\UnifiedPatientData;
|
||
use App\Domain\Reports\ValueObjects\MetrikaConfig;
|
||
use App\Models\MedicalHistorySnapshot;
|
||
use App\Models\MetrikaResult;
|
||
use App\Models\Report;
|
||
use Illuminate\Support\Collection;
|
||
|
||
class SnapshotPersistenceService
|
||
{
|
||
/**
|
||
* Сохранить метрики, полученные из снапшотов, с идемпотентным upsert.
|
||
*
|
||
* @param array<int, int|float|string|null> $metrics
|
||
*/
|
||
public function saveMetrics(Report $report, array $metrics): void
|
||
{
|
||
foreach ($metrics as $metrikaItemId => $value) {
|
||
MetrikaResult::updateOrCreate(
|
||
[
|
||
'rf_report_id' => $report->report_id,
|
||
'rf_metrika_item_id' => $metrikaItemId,
|
||
],
|
||
[
|
||
'value' => $value,
|
||
]
|
||
);
|
||
}
|
||
}
|
||
|
||
public function createSnapshotsForType(Report $report, string $type, Collection $patients): void
|
||
{
|
||
foreach ($patients as $patient) {
|
||
if (! $patient instanceof UnifiedPatientData) {
|
||
continue;
|
||
}
|
||
|
||
MedicalHistorySnapshot::updateOrCreate(
|
||
[
|
||
'rf_report_id' => $report->report_id,
|
||
'patient_uid' => $patient->patientUid,
|
||
'patient_type' => $type,
|
||
],
|
||
[
|
||
'rf_report_id' => $report->report_id,
|
||
'patient_type' => $type,
|
||
...$patient->toSnapshotPayload($type),
|
||
]
|
||
);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Удалить ранее построенные снапшоты перед полной перестройкой состояния отчёта.
|
||
*/
|
||
public function clearReportSnapshots(Report $report): void
|
||
{
|
||
MedicalHistorySnapshot::query()
|
||
->where('rf_report_id', $report->report_id)
|
||
->delete();
|
||
}
|
||
|
||
/**
|
||
* Сопоставить типы snapshot-пациентов с идентификаторами сохраняемых метрик.
|
||
*
|
||
* @return array<string, int>
|
||
*/
|
||
public function snapshotMetricMap(): array
|
||
{
|
||
return [
|
||
'plan' => MetrikaConfig::PLAN,
|
||
'emergency' => MetrikaConfig::EMERGENCY,
|
||
'discharged' => MetrikaConfig::DISCHARGED,
|
||
'transferred' => MetrikaConfig::TRANSFERRED,
|
||
];
|
||
}
|
||
}
|