77 lines
2.7 KiB
PHP
77 lines
2.7 KiB
PHP
<?php
|
||
|
||
namespace App\Services;
|
||
|
||
use App\Models\Report;
|
||
use Illuminate\Support\Carbon;
|
||
use Illuminate\Support\Facades\DB;
|
||
|
||
class MetrikaService
|
||
{
|
||
/**
|
||
* Рассчитать предоперационный койко-день из снапшотов
|
||
*/
|
||
public function calculatePreoperativeDaysFromSnapshots(
|
||
array $departmentIds,
|
||
string $startDate,
|
||
string $endDate
|
||
): array
|
||
{
|
||
if (empty($departmentIds)) {
|
||
return [];
|
||
}
|
||
|
||
try {
|
||
// Получаем снапшоты с операциями
|
||
$results = DB::table('medical_history_snapshots as mhs')
|
||
->join('reports as r', 'mhs.rf_report_id', '=', 'r.report_id')
|
||
->join('stt_migrationpatient as mp', 'mhs.rf_medicalhistory_id', '=', 'mp.rf_MedicalHistoryID')
|
||
->join('stt_surgicaloperation as so', 'mhs.rf_medicalhistory_id', '=', 'so.rf_MedicalHistoryID')
|
||
->whereIn('r.rf_department_id', $departmentIds)
|
||
->whereDate('r.sent_at', '>=', $startDate)
|
||
->whereDate('r.sent_at', '<=', $endDate)
|
||
->whereIn('mhs.patient_type', ['discharged', 'deceased'])
|
||
->select(
|
||
'r.rf_department_id',
|
||
'mp.rf_MedicalHistoryID',
|
||
DB::raw('MIN(mp."DateIngoing") as admission_date'),
|
||
DB::raw('MIN(so."Date") as first_operation_date')
|
||
)
|
||
->groupBy('r.rf_department_id', 'mp.rf_MedicalHistoryID')
|
||
->havingRaw('MIN(so."Date") IS NOT NULL')
|
||
->get()
|
||
->groupBy('rf_department_id');
|
||
|
||
$preoperativeDays = [];
|
||
foreach ($departmentIds as $deptId) {
|
||
if (!isset($results[$deptId]) || $results[$deptId]->isEmpty()) {
|
||
$preoperativeDays[$deptId] = 0;
|
||
continue;
|
||
}
|
||
|
||
$totalDays = 0;
|
||
$count = 0;
|
||
|
||
foreach ($results[$deptId] as $item) {
|
||
$admission = Carbon::parse($item->admission_date);
|
||
$operation = Carbon::parse($item->first_operation_date);
|
||
$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);
|
||
}
|
||
}
|
||
}
|