Добавил вывод метрик для врача дежурного

This commit is contained in:
brusnitsyn
2026-07-13 16:25:13 +09:00
parent d194ea3030
commit 6b3a4bfceb
5 changed files with 62 additions and 18 deletions

View File

@@ -14,12 +14,14 @@ use App\Services\DateRangeService;
use App\Services\DutyMedicalHistoryService; use App\Services\DutyMedicalHistoryService;
use App\Services\DutyReportService; use App\Services\DutyReportService;
use App\Services\MedicalHistoryService; use App\Services\MedicalHistoryService;
use App\Services\MetrikaService;
use App\Services\NurseMedicalHistoryService; use App\Services\NurseMedicalHistoryService;
use App\Services\NurseReportService; use App\Services\NurseReportService;
use App\Services\UnifiedMedicalHistoryService; use App\Services\UnifiedMedicalHistoryService;
use Barryvdh\DomPDF\Facade\Pdf; use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Carbon; use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Inertia\Inertia; use Inertia\Inertia;
@@ -31,6 +33,7 @@ class DutyReportController extends Controller
protected DutyMedicalHistoryService $dutyMedicalHistoryService, protected DutyMedicalHistoryService $dutyMedicalHistoryService,
protected DutyReportService $dutyReportService, protected DutyReportService $dutyReportService,
protected NurseMedicalHistoryService $nurseMedicalHistoryService, protected NurseMedicalHistoryService $nurseMedicalHistoryService,
protected MetrikaService $metrikaService,
) )
{} {}
@@ -59,7 +62,7 @@ class DutyReportController extends Controller
->where('period_start', '>=', $dateRange->startSql()) ->where('period_start', '>=', $dateRange->startSql())
->where('period_end', '<=', $dateRange->endSql()) ->where('period_end', '<=', $dateRange->endSql())
->orderBy('period_end', 'desc') ->orderBy('period_end', 'desc')
->with(['unwantedEvents', 'doctor']) ->with(['unwantedEvents', 'doctor', 'metrikaResult'])
->get(); ->get();
$reportsNurse = ReportNurse::where('rf_department_id', $departmentId) $reportsNurse = ReportNurse::where('rf_department_id', $departmentId)
@@ -109,7 +112,8 @@ class DutyReportController extends Controller
$latestReport = $reportsDuty->first(); $latestReport = $reportsDuty->first();
} else { }
else {
// Для прошедшего периода - данные из отчета // Для прошедшего периода - данные из отчета
$patients = $hasDutyReport $patients = $hasDutyReport
? $this->dutyMedicalHistoryService->getGroupedHistories( ? $this->dutyMedicalHistoryService->getGroupedHistories(
@@ -146,7 +150,7 @@ class DutyReportController extends Controller
'canSaveReport' => $isRangeOneDay && $user->currentRoleCan('report.create'), 'canSaveReport' => $isRangeOneDay && $user->currentRoleCan('report.create'),
'canEditPastReport' => $user->currentRoleCan('report.edit.past'), 'canEditPastReport' => $user->currentRoleCan('report.edit.past'),
'canSaveNurseReport' => $isRangeOneDay && $user->currentRoleCan('nurse.report.create'), 'canSaveNurseReport' => $isRangeOneDay && $user->currentRoleCan('nurse.report.create'),
'stats' => $this->prepareStats($patients, $nursePatients, $loaded, $bedsInDepartment), 'stats' => $this->prepareStats($reportsDuty, $patients, $nursePatients, $loaded, $bedsInDepartment),
'dates' => [ 'dates' => [
$dateRange->startDate->getTimestampMs(), $dateRange->startDate->getTimestampMs(),
$dateRange->endDate->getTimestampMs(), $dateRange->endDate->getTimestampMs(),
@@ -281,7 +285,7 @@ class DutyReportController extends Controller
/** /**
* Подготавливает статистику для отображения на фронтенде * Подготавливает статистику для отображения на фронтенде
*/ */
private function prepareStats(array $patients, array $nursePatients, int $loaded, ?int $bedsInDepartment): array private function prepareStats(Collection $reportsDuty, array $patients, array $nursePatients, int $loaded, ?int $bedsInDepartment): array
{ {
$deceased = $patients['meta']['counts']['deceased'] ?? 0; // Умершие $deceased = $patients['meta']['counts']['deceased'] ?? 0; // Умершие
$discharged = $patients['meta']['counts']['discharged'] ?? 0; // Выписанные $discharged = $patients['meta']['counts']['discharged'] ?? 0; // Выписанные
@@ -290,6 +294,8 @@ class DutyReportController extends Controller
? round(($deceased / $discharged) * 100, 2) ? round(($deceased / $discharged) * 100, 2)
: 0; : 0;
$baseMetrics = $this->metrikaService->calculateBaseStatistics($reportsDuty);
return [ return [
'nurse' => [ 'nurse' => [
'current' => !empty($nursePatients) 'current' => !empty($nursePatients)
@@ -305,13 +311,14 @@ class DutyReportController extends Controller
'duty' => [ 'duty' => [
'beds' => $bedsInDepartment ?? 0, 'beds' => $bedsInDepartment ?? 0,
'loaded' => $loaded, 'loaded' => $loaded,
'current' => $patients['meta']['counts']['in_department'] ?? 0, 'current' => $baseMetrics['current'],// $patients['meta']['counts']['in_department'] ?? 0,
'recipient' => $patients['meta']['counts']['recipient'] ?? 0, 'recipient' => $baseMetrics['recipient'] ?? 0,
'discharged' => ($patients['meta']['counts']['discharged'] ?? 0) + ($patients['meta']['counts']['deceased'] ?? 0), 'discharged' => $baseMetrics['outcome'] + ($patients['meta']['counts']['deceased'] ?? 0), //($patients['meta']['counts']['discharged'] ?? 0) + ($patients['meta']['counts']['deceased'] ?? 0),
'deceased' => $patients['meta']['counts']['deceased'] ?? 0, 'deceased' => $patients['meta']['counts']['deceased'] ?? 0,
'lethality' => $lethality, 'lethality' => $lethality,
'surgical_planned' => $patients['meta']['counts']['surgical_planned'] ?? 0, 'surgical_planned' => $patients['meta']['counts']['surgical_planned'] ?? 0,
'surgical_urgent' => $patients['meta']['counts']['surgical_urgent'] ?? 0, 'surgical_urgent' => $patients['meta']['counts']['surgical_urgent'] ?? 0,
'staff' => $baseMetrics['staff']
] ]
]; ];
} }
@@ -369,6 +376,8 @@ class DutyReportController extends Controller
'observable_out' => $dateRange->endDate, 'observable_out' => $dateRange->endDate,
'out_reason' => 'Закрыто пользователем' 'out_reason' => 'Закрыто пользователем'
]); ]);
return response()->json()->setStatusCode(200);
} }
/** /**

View File

@@ -70,6 +70,11 @@ class ReportDuty extends Model
return $this->hasMany(DutyUnwantedEvent::class, 'report_duty_id', 'id'); return $this->hasMany(DutyUnwantedEvent::class, 'report_duty_id', 'id');
} }
public function metrikaResult()
{
return $this->hasMany(DutyReportMetricResult::class, 'rf_report_id', 'id');
}
public function getLoadedDepartmentAttribute(int $patientsInDepartment) public function getLoadedDepartmentAttribute(int $patientsInDepartment)
{ {
$beds = DutyReportMetricResult::where('rf_report_id', $this->id) $beds = DutyReportMetricResult::where('rf_report_id', $this->id)

View File

@@ -928,11 +928,11 @@ class DutyReportService
$admitted = $stats['admitted'] ?? []; $admitted = $stats['admitted'] ?? [];
// === Базовые счётчики === // === Базовые счётчики ===
$patientsIsRecipient = array_key_exists('recipient', $statsOverride) $patientsIsRecipient = array_key_exists('recipient', $statsOverride) && !empty($statsOverride['recipient'])
? $statsOverride['recipient'] : $byStatus['recipient'] ?? 0; ? $statsOverride['recipient'] : $byStatus['recipient'] ?? 0;
$patientsInDepartment = array_key_exists('in_department', $statsOverride) $patientsInDepartment = array_key_exists('in_department', $statsOverride) && !empty($statsOverride['in_department'])
? $statsOverride['in_department'] : $byStatus['in_department'] ?? 0; ? $statsOverride['in_department'] : $byStatus['in_department'] ?? 0;
$patientsIsDischarged = array_key_exists('outcome', $statsOverride) $patientsIsDischarged = array_key_exists('outcome', $statsOverride) && !empty($statsOverride['outcome'])
? $statsOverride['outcome'] : $byStatus['outcome'] ?? 0; ? $statsOverride['outcome'] : $byStatus['outcome'] ?? 0;
$patientsIsTransferred = $stats['transferred'] ?? 0; $patientsIsTransferred = $stats['transferred'] ?? 0;
$patientsIsDeceased = $byStatus['deceased'] ?? 0; $patientsIsDeceased = $byStatus['deceased'] ?? 0;
@@ -977,7 +977,7 @@ class DutyReportService
$this->saveMetric($reportDuty->id, 8, $patientsInDepartment); // Пациентов в отделении $this->saveMetric($reportDuty->id, 8, $patientsInDepartment); // Пациентов в отделении
$this->saveMetric($reportDuty->id, 3, $patientsIsRecipient); // Поступило $this->saveMetric($reportDuty->id, 3, $patientsIsRecipient); // Поступило
$this->saveMetric($reportDuty->id, 15, $patientsIsDischarged); // Выписано $this->saveMetric($reportDuty->id, 15, $patientsIsDischarged); // Выписано
$this->saveMetric($reportDuty->id, 7, $patientsIsDischarged); // Выписано $this->saveMetric($reportDuty->id, 7, $patientsIsDischarged); // Выписано
$this->saveMetric($reportDuty->id, 13, $patientsIsTransferred); // Переведено $this->saveMetric($reportDuty->id, 13, $patientsIsTransferred); // Переведено
$this->saveMetric($reportDuty->id, 9, $patientsIsDeceased); // Умерло $this->saveMetric($reportDuty->id, 9, $patientsIsDeceased); // Умерло

View File

@@ -6,6 +6,8 @@ use App\Models\MedicalHistory;
use App\Models\MedicalHistorySnapshot; use App\Models\MedicalHistorySnapshot;
use App\Models\Report; use App\Models\Report;
use Illuminate\Support\Carbon; use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
class MetrikaService class MetrikaService
{ {
@@ -110,4 +112,32 @@ class MetrikaService
return $metrics; return $metrics;
} }
/**
* Подсчитывает базовую статистику для отчетов дежурного врача
* Поступило, выбыло, состоит и мед. персонал
* @param Collection $reportsDuty
* @return array
*/
public function calculateBaseStatistics(Collection $reportsDuty): array
{
$reportIds = $reportsDuty->pluck('id'); // получаем ID всех отчётов
// Один запрос, который сразу возвращает суммы по каждому типу
$totals = DB::table('duty_report_metric_results')
->whereIn('rf_report_id', $reportIds) // предполагаем внешний ключ `report_id`
->whereIn('rf_metrika_item_id', [3, 7, 8, 17])
->select('rf_metrika_item_id', DB::raw('SUM(value::integer) as total'))
->groupBy('rf_metrika_item_id')
->pluck('total', 'rf_metrika_item_id')
->toArray();
// Формируем итоговый массив с ключами, как у вас
return [
'recipient' => $totals[3] ?? 0,
'outcome' => $totals[7] ?? 0,
'current' => $totals[8] ?? 0,
'staff' => $totals[17] ?? 0,
];
}
} }

View File

@@ -120,10 +120,10 @@ const latestReportObj = ref(props.latestReport ?? {
const loading = ref(false) const loading = ref(false)
const showUnwantedEventModal = ref(false) const showUnwantedEventModal = ref(false)
const reportForm = ref({ const reportForm = ref({
recipient: props.stats.nurse.recipient, recipient: props.stats.duty.recipient,
discharged: props.stats.nurse.discharged, discharged: props.stats.duty.discharged,
current: props.stats.nurse.current, current: props.stats.duty.current,
staff: 0, staff: props.stats.duty.staff,
observables: [] observables: []
}) })
const updateReportForm = (form) => { const updateReportForm = (form) => {
@@ -199,9 +199,9 @@ const syncPageProps = (pageProps = props) => {
latestReportObj.value = pageProps.latestReport ?? { unwanted_events: [] } latestReportObj.value = pageProps.latestReport ?? { unwanted_events: [] }
reportForm.value = { reportForm.value = {
...reportForm.value, ...reportForm.value,
recipient: pageProps.stats.nurse.recipient, recipient: pageProps.stats.duty.recipient,
discharged: pageProps.stats.nurse.discharged, discharged: pageProps.stats.duty.discharged,
current: pageProps.stats.nurse.current, current: pageProps.stats.duty.current,
} }
} }