* переписал функции прототипов в сервисы

* оптимизация доставки контента до клиента
* переписал запросы выборок
* убрал из подсчета переведенных
* добавил сохранение метрикам для вывода в дашборд
This commit is contained in:
brusnitsyn
2026-02-04 17:05:13 +09:00
parent 9ee33bc517
commit eab78a0291
16 changed files with 1644 additions and 737 deletions

View File

@@ -18,6 +18,7 @@ use App\Models\UnwantedEvent;
use App\Models\User;
use App\Services\DateRangeService;
use App\Services\MisPatientService;
use App\Services\ReportService;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
@@ -28,14 +29,11 @@ use Inertia\Inertia;
class ReportController extends Controller
{
protected MisPatientService $misPatientService;
protected DateRangeService $dateService;
public function __construct(MisPatientService $misPatientService, DateRangeService $dateRangeService)
{
$this->misPatientService = $misPatientService;
$this->dateService = $dateRangeService;
}
public function __construct(
protected MisPatientService $misPatientService,
protected ReportService $reportService,
protected DateRangeService $dateRangeService)
{ }
public function index(Request $request)
{
@@ -614,78 +612,20 @@ class ReportController extends Controller
public function getPatients(Request $request)
{
$user = Auth::user();
$data = $request->validate([
'status' => 'required|string', // plan emergency observation deceased
$validated = $request->validate([
'status' => 'required|string',
'startAt' => 'nullable',
'endAt' => 'nullable',
]);
// Получаем базовые данные
$status = $data['status'];
$model = new MisMedicalHistory();
$misDepartmentId = $request->user()->department->rf_mis_department_id;
$userDepartmentId = $request->user()->department->department_id;
$branchId = MisStationarBranch::where('rf_DepartmentID', $misDepartmentId)->value('StationarBranchID');
$dateRange = $this->dateRangeService->getDateRangeFromRequest($request, $user);
if (!$branchId) {
return response()->json([]);
}
// Определяем даты в зависимости от роли
[$startDate, $endDate] = $this->getDateRangeForRole($user, $data['startAt'] ?? null, $data['endAt'] ?? null);
// Для заведующего/админа ищем отчет по endDate (дате просмотра)
$reportIds = [];
$reports = $this->getReportsForDateRange($user->rf_department_id, $startDate, $endDate);
$reportIds = $reports->pluck('report_id')->toArray();
// Определяем, используем ли мы снапшоты
$useSnapshots = ($user->isAdmin() || $user->isHeadOfDepartment()) || Carbon::parse($endDate)->isToday() === false;
// Обработка каждого статуса
if ($useSnapshots) {
// Используем снапшоты: получаем ID пациентов, затем данные из реплики
$patients = match($status) {
'plan', 'emergency' => $this->getPatientsFromSnapshotsUsingReplica($status, $reportIds, $branchId, $startDate, $endDate),
'observation' => $this->getObservationPatientsFromSnapshotsUsingReplica($userDepartmentId, $reportIds),
'outcome-discharged' => $this->getOutcomePatientsFromSnapshotsUsingReplica('discharged', $reportIds, $branchId, $startDate, $endDate),
'outcome-transferred' => $this->getOutcomePatientsFromSnapshotsUsingReplica('transferred', $reportIds, $branchId, $startDate, $endDate),
'outcome-deceased' => $this->getOutcomePatientsFromSnapshotsUsingReplica('deceased', $reportIds, $branchId, $startDate, $endDate),
default => collect()
};
} else {
// // Используем реплику для врачей или когда нет отчетов
$isHeadOrAdmin = $user->isHeadOfDepartment() || $user->isAdmin();
$patients = match($status) {
'plan', 'emergency' => $this->getPlanOrEmergencyPatients($status, $isHeadOrAdmin, $branchId, $startDate, $endDate),
'observation' => $this->getObservationPatients($userDepartmentId),
'outcome-discharged' => $this->getDischargedPatients($branchId, $startDate, $endDate),
'outcome-transferred' => $this->getTransferredPatients($branchId, $startDate, $endDate),
'outcome-deceased' => $this->getDeceasedOutcomePatients($branchId, $startDate, $endDate),
default => 0
};
}
// Если есть пациенты, добавляем дополнительные данные
if ($patients->isNotEmpty()) {
$patients = $patients->map(function ($item, $index) use ($branchId, $startDate, $endDate) {
$item->num = $index + 1;
$item->misStationarBranchId = $branchId;
$item->startDate = $startDate;
$item->endDate = $endDate;
return $item;
});
// Загружаем связи
$patients->load(['migrations' => function ($query) use ($startDate, $endDate, $branchId) {
$query->whereHas('diagnosis', function ($q) {
$q->where('rf_DiagnosTypeID', 3);
})
->with('diagnosis.mkb')
->where('rf_StationarBranchID', $branchId);
}]);
}
$patients = $this->reportService->getPatientsByStatus(
Auth::user(),
$validated['status'],
$dateRange
);
return response()->json(FormattedPatientResource::collection($patients));
}
@@ -693,81 +633,20 @@ class ReportController extends Controller
public function getPatientsCount(Request $request)
{
$user = Auth::user();
$data = $request->validate([
'status' => 'required|string', // plan emergency observation deceased
$validated = $request->validate([
'status' => 'required|string',
'startAt' => 'nullable',
'endAt' => 'nullable',
]);
// Получаем базовые данные
$status = $data['status'];
$model = new MisMedicalHistory();
$misDepartmentId = $request->user()->department->rf_mis_department_id;
$userDepartmentId = $request->user()->department->department_id;
$branchId = MisStationarBranch::where('rf_DepartmentID', $misDepartmentId)->value('StationarBranchID');
$dateRange = $this->dateRangeService->getDateRangeFromRequest($request, $user);
if (!$branchId) {
return response()->json([]);
}
// Определяем даты в зависимости от роли
[$startDate, $endDate] = $this->getDateRangeForRole($user, $data['startAt'] ?? null, $data['endAt'] ?? null);
// Для заведующего/админа ищем отчеты по промежутку дат
$reportIds = [];
$reports = $this->getReportsForDateRange($user->rf_department_id, $startDate, $endDate);
$reportIds = $reports->pluck('report_id')->toArray();
// Определяем, используем ли мы снапшоты
$useSnapshots = ($user->isAdmin() || $user->isHeadOfDepartment()) || Carbon::parse($endDate)->isToday() === false;
if ($useSnapshots) {
// Считаем из снапшотов
$patientTypeMap = [
'plan' => 'plan',
'emergency' => 'emergency',
'observation' => 'observation',
'outcome' => null,
'outcome-discharged' => 'discharged',
'outcome-transferred' => 'transferred',
'outcome-deceased' => 'deceased'
];
$patientType = $patientTypeMap[$status] ?? null;
if ($status === 'outcome') {
// Считаем уникальных пациентов по всем типам исходов
$count = MedicalHistorySnapshot::whereIn('rf_report_id', $reportIds)
->whereIn('patient_type', ['discharged', 'transferred', 'deceased'])
->distinct('rf_medicalhistory_id')
->count('rf_medicalhistory_id');
} elseif ($patientType) {
$count = MedicalHistorySnapshot::whereIn('rf_report_id', $reportIds)
->where('patient_type', $patientType)
->distinct('rf_medicalhistory_id')
->count('rf_medicalhistory_id');
} else {
$count = 0;
}
} else {
// Определяем, является ли пользователь заведующим/администратором
$isHeadOrAdmin = $user->isHeadOfDepartment() || $user->isAdmin();
$isOutcomeOrObservation = in_array($status, ['outcome', 'observation']);
if ($isOutcomeOrObservation)
{
switch ($status) {
case 'observation':
$count = ObservationPatient::where('rf_department_id', $userDepartmentId)->count();
break;
case 'outcome':
$count = $this->getAllOutcomePatients($branchId, $startDate, $endDate, true);
break;
}
} else {
$count = $this->getPlanOrEmergencyPatients($status, $isHeadOrAdmin, $branchId, $startDate, $endDate, true);
}
}
$count = $this->reportService->getPatientsCountByStatus(
Auth::user(),
$validated['status'],
$dateRange,
);
return response()->json($count);
}