* работа над функционалом автоматического заполнения

* исправил фантомный сдвиг даты
* переделал получение ФИО врачей из отделений
* добавил возможность поиска врача
* переписал сохранение отчета
This commit is contained in:
brusnitsyn
2026-02-05 17:11:43 +09:00
parent eab78a0291
commit 10fb138c30
22 changed files with 1192 additions and 654 deletions

View File

@@ -2,6 +2,7 @@
namespace App\Services;
use App\Models\Department;
use App\Models\MedicalHistorySnapshot;
use App\Models\MetrikaResult;
use App\Models\MisLpuDoctor;
@@ -46,7 +47,7 @@ class ReportService
/**
* Создать или обновить отчет
*/
public function storeReport(array $data, User $user): Report
public function storeReport(array $data, User $user, $fillableAuto = false): Report
{
DB::beginTransaction();
@@ -58,7 +59,7 @@ class ReportService
$this->saveObservationPatients($report, $data['observationPatients'] ?? [], $user->rf_department_id);
// Сохраняем снапшоты пациентов
$this->snapshotService->createPatientSnapshots($report, $user, $data['dates']);
$this->snapshotService->createPatientSnapshots($report, $user, $data['dates'], $fillableAuto);
DB::commit();
return $report;
@@ -74,17 +75,20 @@ class ReportService
public function getPatientsByStatus(
User $user,
string $status,
DateRange $dateRange
DateRange $dateRange,
bool $onlyIds = false,
bool $beforeCreate = false,
?bool $includeCurrentPatients = null
) {
$branchId = $this->getBranchId($user->department->rf_mis_department_id);
$useSnapshots = $this->shouldUseSnapshots($user, $dateRange);
$useSnapshots = $this->shouldUseSnapshots($user, $dateRange, $beforeCreate);
if ($useSnapshots) {
return $this->getPatientsFromSnapshots($user, $status, $dateRange, $branchId);
}
return $this->getPatientsFromReplica($user, $status, $dateRange, $branchId);
return $this->getPatientsFromReplica($user, $status, $dateRange, $branchId, $onlyIds, $includeCurrentPatients);
}
/**
@@ -118,9 +122,9 @@ class ReportService
/**
* Определить, нужно ли использовать снапшоты
*/
private function shouldUseSnapshots(User $user, DateRange $dateRange): bool
private function shouldUseSnapshots(User $user, DateRange $dateRange, bool $beforeCreate = false): bool
{
if ($user->isAdmin() || $user->isHeadOfDepartment()) {
if (($user->isAdmin() || $user->isHeadOfDepartment()) && !$beforeCreate) {
return true;
}
@@ -141,7 +145,8 @@ class ReportService
'rf_department_id' => $data['departmentId'],
'rf_user_id' => $user->id,
'rf_lpudoctor_id' => $data['userId'],
'sent_at' => now(),
'sent_at' => $data['sent_at'] ?? $this->dateRangeService->toSqlFormat(\Illuminate\Support\Carbon::now()),
'created_at' => $data['created_at'] ?? $this->dateRangeService->toSqlFormat(\Illuminate\Support\Carbon::now()),
];
if (isset($data['reportId']) && $data['reportId']) {
@@ -151,6 +156,13 @@ class ReportService
);
} else {
$report = Report::create($reportData);
$department = Department::where('department_id', $reportData['rf_department_id'])->first();
$beds = $department->metrikaDefault->where('rf_metrika_item_id', 1)->first();
MetrikaResult::create([
'rf_report_id' => $report->report_id,
'rf_metrika_item_id' => 1,
'value' => $beds->value
]);
}
return $report;
@@ -265,7 +277,7 @@ class ReportService
$isActiveSendButton = $this->isSendButtonActive($user, $dateRange, $reportToday, $fillableUserId);
$message = null;
if ($reportToday && $reportToday->rf_lpudoctor_id !== intval($fillableUserId)) {
if ($reportToday) {
$reportDoctor = $reportToday->lpuDoctor;
$message = "Отчет уже создан пользователем: $reportDoctor->FAM_V $reportDoctor->IM_V $reportDoctor->OT_V";
}
@@ -329,9 +341,11 @@ class ReportService
'emergency' => $this->getMetrikaResultCount(12, $reportIds),
'outcome' => $this->getMetrikaResultCount(7, $reportIds),
'deceased' => $this->getMetrikaResultCount(9, $reportIds),
'current' => $this->getMetrikaResultCount(8, $reportIds),
// 'discharged' => $this->getMetrikaResultCount('discharged', $reportIds),
'transferred' => $this->getMetrikaResultCount(13, $reportIds),
'recipient' => $this->getMetrikaResultCount(3, $reportIds),
'beds' => $this->getMetrikaResultCount(1, $reportIds)
];
// Получаем ID поступивших пациентов
@@ -350,10 +364,11 @@ class ReportService
return [
'recipientCount' => $snapshotStats['recipient'] ?? 0,
'extractCount' => $snapshotStats['outcome'] ?? 0,
'currentCount' => $this->calculateCurrentPatientsFromSnapshots($reportIds, $branchId),
'currentCount' => $snapshotStats['current'] ?? 0,//$this->calculateCurrentPatientsFromSnapshots($reportIds, $branchId),
'deadCount' => $snapshotStats['deceased'] ?? 0,
'surgicalCount' => $surgicalCount,
'recipientIds' => $recipientIds,
'beds' => $snapshotStats['beds'] ?? 0
];
}
@@ -440,6 +455,10 @@ class ReportService
false // только поступившие сегодня
);
$misBranch = MisStationarBranch::where('StationarBranchID', $branchId)->first();
$beds = Department::where('rf_mis_department_id', $misBranch->rf_DepartmentID)
->first()->metrikaDefault->where('rf_metrika_item_id', 1)->first();
return [
'recipientCount' => $recipientCount, // только поступившие сегодня
'extractCount' => $outcomeCount,
@@ -449,14 +468,20 @@ class ReportService
'recipientIds' => $recipientIds, // ID поступивших сегодня
'planCount' => $planCount, // плановые (поступившие + уже лечащиеся)
'emergencyCount' => $emergencyCount, // экстренные (поступившие + уже лечащиеся)
'beds' => $beds->value
];
}
/**
* Получить пациентов из снапшотов
*/
private function getPatientsFromSnapshots(User $user, string $status, DateRange $dateRange, int $branchId)
{
private function getPatientsFromSnapshots(
User $user,
string $status,
DateRange $dateRange,
int $branchId,
bool $onlyIds = false
) {
$reports = $this->getReportsForDateRange(
$user->rf_department_id,
$dateRange
@@ -476,21 +501,27 @@ class ReportService
$patientType = $patientTypeMap[$status] ?? null;
if ($patientType === 'observation') {
return $this->getObservationPatientsFromSnapshots($user->rf_department_id, $reportIds);
return $this->patientQueryService->getObservationPatients($user->rf_department_id, $onlyIds); //$this->getObservationPatientsFromSnapshots($user->rf_department_id, $reportIds, $onlyIds);
}
return $this->snapshotService->getPatientsFromSnapshots($patientType, $reportIds, $branchId);
return $this->snapshotService->getPatientsFromSnapshots($patientType, $reportIds, $branchId, $onlyIds);
}
/**
* Получить пациентов из реплики БД
*/
private function getPatientsFromReplica(User $user, string $status, DateRange $dateRange, int $branchId)
{
private function getPatientsFromReplica(
User $user,
string $status,
DateRange $dateRange,
int $branchId,
bool $onlyIds = false,
?bool $isIncludeCurrent = null
) {
$isHeadOrAdmin = $user->isHeadOfDepartment() || $user->isAdmin();
// Для плановых и экстренных включаем уже лечащихся
$includeCurrent = in_array($status, ['plan', 'emergency']);
$includeCurrent = $isIncludeCurrent ?? in_array($status, ['plan', 'emergency']);
return match($status) {
'plan', 'emergency' => $this->patientQueryService->getPlanOrEmergencyPatients(
@@ -499,29 +530,40 @@ class ReportService
$branchId,
$dateRange,
false,
false,
$onlyIds,
$includeCurrent
),
'observation' => $this->patientQueryService->getObservationPatients($user->rf_department_id),
'observation' => $this->patientQueryService->getObservationPatients($user->rf_department_id, $onlyIds),
'outcome' => $this->patientQueryService->getOutcomePatients(
$branchId,
$dateRange,
'without-transferred',
$onlyIds
), // Выписанные без перевода
'outcome-discharged' => $this->patientQueryService->getOutcomePatients(
$branchId,
$dateRange,
'discharged'
'discharged',
$onlyIds
),
'outcome-transferred' => $this->patientQueryService->getOutcomePatients(
$branchId,
$dateRange,
'transferred'
'transferred',
$onlyIds
),
'outcome-deceased' => $this->patientQueryService->getOutcomePatients(
$branchId,
$dateRange,
'deceased'
'deceased',
$onlyIds
),
'current' => $this->patientQueryService->getAllPatientsInDepartment(
$isHeadOrAdmin,
$branchId,
$dateRange
$dateRange,
false,
$onlyIds
),
'recipient' => $this->patientQueryService->getPlanOrEmergencyPatients(
null,
@@ -529,7 +571,7 @@ class ReportService
$branchId,
$dateRange,
false,
false,
$onlyIds,
false // только поступившие
),
default => collect()
@@ -666,8 +708,8 @@ class ReportService
return null;
}
// Если дата не сегодня, не показываем врача
if (!$dateRange->isEndDateToday()) {
// Если дата это период, не показываем врача
if (!$dateRange->isOneDay) {
return null;
}
@@ -744,7 +786,7 @@ class ReportService
/**
* Получить пациентов под наблюдением из снапшотов
*/
private function getObservationPatientsFromSnapshots(int $departmentId, array $reportIds)
private function getObservationPatientsFromSnapshots(int $departmentId, array $reportIds, bool $onlyIds = false)
{
$medicalHistoryIds = ObservationPatient::whereIn('rf_report_id', $reportIds)
->where('rf_department_id', $departmentId)
@@ -756,6 +798,10 @@ class ReportService
return collect();
}
if ($onlyIds) {
return collect($medicalHistoryIds);
}
return MisMedicalHistory::whereIn('MedicalHistoryID', $medicalHistoryIds)
->with(['observationPatient' => function($query) use ($departmentId) {
$query->where('rf_department_id', $departmentId)