Форматирование

This commit is contained in:
brusnitsyn
2026-04-24 16:46:10 +09:00
parent fd0e6ee817
commit 63daa62888
87 changed files with 1380 additions and 791 deletions

View File

@@ -10,34 +10,30 @@ use App\Models\MedicalHistorySnapshot;
use App\Models\MetrikaGroup;
use App\Models\MetrikaResult;
use App\Models\MisLpuDoctor;
use App\Models\MisMKB;
use App\Models\MisMedicalHistory;
use App\Models\MisMigrationPatient;
use App\Models\MisMKB;
use App\Models\MisStationarBranch;
use App\Models\MisSurgicalOperation;
use App\Models\ObservationPatient;
use App\Models\Report;
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\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Str;
use Inertia\Inertia;
class ReportController extends Controller
{
public function __construct(
protected MisPatientService $misPatientService,
protected ReportService $reportService,
protected DateRangeService $dateRangeService)
{ }
protected DateRangeService $dateRangeService) {}
public function index(Request $request)
{
@@ -122,8 +118,9 @@ class ReportController extends Controller
$count = 0;
foreach ($reports as $report) {
foreach ($report->metrikaResults as $metrikaResult) {
if ($metrikaResult->rf_metrika_item_id === $metrikaItemId)
if ($metrikaResult->rf_metrika_item_id === $metrikaItemId) {
$count += intval($metrikaResult->value) ?? 0;
}
}
}
@@ -163,7 +160,7 @@ class ReportController extends Controller
'startAt' => 'required|integer',
'endAt' => 'required|integer',
'userId' => 'required|integer',
'reportId' => 'nullable'
'reportId' => 'nullable',
]);
$metrics = $data['metrics'];
$observationPatients = $data['observationPatients'];
@@ -175,7 +172,7 @@ class ReportController extends Controller
$metriks = [];
foreach ($metrics as $key => $value) {
$metrika = new MetrikaResult;
$metrikaId = (int)Str::replace('metrika_item_', '', $key);
$metrikaId = (int) Str::replace('metrika_item_', '', $key);
$metrika->rf_metrika_item_id = $metrikaId;
$metrika->value = $value;
@@ -238,7 +235,7 @@ class ReportController extends Controller
if (isset($data['reportId']) && $data['reportId']) {
$report = Report::updateOrCreate(
[
'report_id' => $data['reportId']
'report_id' => $data['reportId'],
],
[
'rf_department_id' => $data['departmentId'],
@@ -294,7 +291,7 @@ class ReportController extends Controller
MetrikaResult::updateOrCreate(
[
'rf_report_id' => $report->report_id,
'rf_metrika_item_id' => 16
'rf_metrika_item_id' => 16,
],
[
'rf_report_id' => $report->report_id,
@@ -307,7 +304,7 @@ class ReportController extends Controller
MetrikaResult::updateOrCreate(
[
'rf_report_id' => $report->report_id,
'rf_metrika_item_id' => $metrika->rf_metrika_item_id
'rf_metrika_item_id' => $metrika->rf_metrika_item_id,
],
[
'rf_report_id' => $report->report_id,
@@ -322,14 +319,14 @@ class ReportController extends Controller
ObservationPatient::updateOrCreate(
[
'rf_medicalhistory_id' => $observationPatient['id'],
'rf_department_id' => $data['departmentId']
'rf_department_id' => $data['departmentId'],
],
[
'rf_department_id' => $data['departmentId'],
'rf_report_id' => $report->report_id,
'rf_medicalhistory_id' => $observationPatient['id'],
'rf_mkab_id' => null,
'comment' => $observationPatient['comment'] ?? null
'comment' => $observationPatient['comment'] ?? null,
]
);
}
@@ -341,7 +338,7 @@ class ReportController extends Controller
MetrikaResult::updateOrCreate(
[
'rf_report_id' => $report->report_id,
'rf_metrika_item_id' => 14
'rf_metrika_item_id' => 14,
],
[
'rf_report_id' => $report->report_id,
@@ -352,18 +349,18 @@ class ReportController extends Controller
// Сохраняем снимок для каждого типа пациентов
// Планово
//$this->getPlanOrEmergencyPatients('plan', false, $branchId, $dateRange->startSql(), $dateRange->endSql(), false, false, true);
// $this->getPlanOrEmergencyPatients('plan', false, $branchId, $dateRange->startSql(), $dateRange->endSql(), false, false, true);
foreach ($planIds as $id) {
MedicalHistorySnapshot::create([
'rf_report_id' => $report->report_id,
'rf_medicalhistory_id' => $id,
'patient_type' => 'plan'
'patient_type' => 'plan',
]);
}
MetrikaResult::updateOrCreate(
[
'rf_report_id' => $report->report_id,
'rf_metrika_item_id' => 4
'rf_metrika_item_id' => 4,
],
[
'rf_report_id' => $report->report_id,
@@ -372,19 +369,19 @@ class ReportController extends Controller
]
);
//$this->getPlanOrEmergencyPatients('emergency', false, $branchId, $startDate, $endDate, false, false, true);
// $this->getPlanOrEmergencyPatients('emergency', false, $branchId, $startDate, $endDate, false, false, true);
// Экстренно
foreach ($emergencyIds as $id) {
MedicalHistorySnapshot::create([
'rf_report_id' => $report->report_id,
'rf_medicalhistory_id' => $id,
'patient_type' => 'emergency'
'patient_type' => 'emergency',
]);
}
MetrikaResult::updateOrCreate(
[
'rf_report_id' => $report->report_id,
'rf_metrika_item_id' => 12
'rf_metrika_item_id' => 12,
],
[
'rf_report_id' => $report->report_id,
@@ -393,12 +390,12 @@ class ReportController extends Controller
]
);
//$this->getDischargedPatients($branchId, $startDate, $endDate, true);
// $this->getDischargedPatients($branchId, $startDate, $endDate, true);
foreach ($dischargedIds as $id) {
MedicalHistorySnapshot::create([
'rf_report_id' => $report->report_id,
'rf_medicalhistory_id' => $id,
'patient_type' => 'discharged'
'patient_type' => 'discharged',
]);
}
MetrikaResult::updateOrCreate(
@@ -413,12 +410,12 @@ class ReportController extends Controller
]
);
//$this->getTransferredPatients($branchId, $startDate, $endDate, true);
// $this->getTransferredPatients($branchId, $startDate, $endDate, true);
foreach ($transferredIds as $id) {
MedicalHistorySnapshot::create([
'rf_report_id' => $report->report_id,
'rf_medicalhistory_id' => $id,
'patient_type' => 'transferred'
'patient_type' => 'transferred',
]);
}
MetrikaResult::updateOrCreate(
@@ -433,12 +430,12 @@ class ReportController extends Controller
]
);
//$this->getDeceasedOutcomePatients($branchId, $startDate, $endDate, false, true);
// $this->getDeceasedOutcomePatients($branchId, $startDate, $endDate, false, true);
foreach ($deceasedIds as $id) {
MedicalHistorySnapshot::create([
'rf_report_id' => $report->report_id,
'rf_medicalhistory_id' => $id,
'patient_type' => 'deceased'
'patient_type' => 'deceased',
]);
}
MetrikaResult::updateOrCreate(
@@ -453,22 +450,22 @@ class ReportController extends Controller
]
);
// $recipientIds = $this->getPlanOrEmergencyPatients(
// null,
// $isHeadOrAdmin,
// $branchId,
// $startDate,
// $endDate,
// false,
// true,
// true,
// today: true
// );
// $recipientIds = $this->getPlanOrEmergencyPatients(
// null,
// $isHeadOrAdmin,
// $branchId,
// $startDate,
// $endDate,
// false,
// true,
// true,
// today: true
// );
foreach ($recipientIds as $id) {
MedicalHistorySnapshot::create([
'rf_report_id' => $report->report_id,
'rf_medicalhistory_id' => $id,
'patient_type' => 'recipient'
'patient_type' => 'recipient',
]);
}
MetrikaResult::updateOrCreate(
@@ -484,19 +481,19 @@ class ReportController extends Controller
);
// 7. Находящиеся на лечении
// $currentIds = $this->getCurrentPatients($branchId, false, true);
// foreach ($currentIds as $id) {
// MedicalHistorySnapshot::create([
// 'rf_report_id' => $report->report_id,
// 'rf_medicalhistory_id' => $id,
// 'patient_type' => 'current'
// ]);
// }
// $currentIds = $this->getCurrentPatients($branchId, false, true);
// foreach ($currentIds as $id) {
// MedicalHistorySnapshot::create([
// 'rf_report_id' => $report->report_id,
// 'rf_medicalhistory_id' => $id,
// 'patient_type' => 'current'
// ]);
// }
\DB::commit();
return response()->json([
'message' => 'success'
'message' => 'success',
]);
}
@@ -529,6 +526,10 @@ class ReportController extends Controller
$dateRange
));
if ($this->resolveBaseStatus($validated['status']) === 'reanimation') {
$this->attachReanimationIndicators($patients, (int) $department->department_id);
}
if ($search !== '') {
$needle = mb_strtolower($search);
$patients = $patients->filter(function ($patient) use ($needle) {
@@ -557,6 +558,58 @@ class ReportController extends Controller
]);
}
public function saveReanimationIndicator(Request $request)
{
$user = Auth::user();
$data = $request->validate([
'departmentId' => 'nullable|integer',
'medical_history_id' => 'required|integer',
'indicator' => 'required|string|max:100',
'comment' => 'nullable|string|max:1000',
'startAt' => 'nullable',
'endAt' => 'nullable',
]);
$departmentId = (int) ($data['departmentId'] ?? $user->department->department_id);
$department = Department::where('department_id', $departmentId)->firstOrFail();
$dateRange = $this->dateRangeService->getDateRangeFromRequest($request, $user);
$reportId = $this->getReportsForDateRange(
$department->department_id,
$dateRange->startSql(),
$dateRange->endSql()
)->pluck('report_id')->last();
$indicator = $this->reportService->saveReanimationIndicator(
$user,
$department->department_id,
(int) $data['medical_history_id'],
trim($data['indicator']),
isset($data['comment']) ? trim((string) $data['comment']) : null,
$reportId ? (int) $reportId : null
);
return response()->json($indicator, 201);
}
public function getReanimationIndicatorHistory(Request $request)
{
$user = Auth::user();
$data = $request->validate([
'departmentId' => 'nullable|integer',
'medical_history_id' => 'required|integer',
'limit' => 'nullable|integer|min:1|max:200',
]);
$departmentId = (int) ($data['departmentId'] ?? $user->department->department_id);
$history = $this->reportService->getReanimationIndicatorsHistory(
$departmentId,
(int) $data['medical_history_id'],
(int) ($data['limit'] ?? 50)
);
return response()->json($history);
}
public function getPatientsCount(Request $request)
{
$user = Auth::user();
@@ -565,7 +618,7 @@ class ReportController extends Controller
'status' => 'required|string',
'startAt' => 'nullable',
'endAt' => 'nullable',
'departmentId' => 'nullable'
'departmentId' => 'nullable',
]);
$dateRange = $this->dateRangeService->getDateRangeFromRequest($request, $user);
@@ -680,7 +733,7 @@ class ReportController extends Controller
// Врач: используем currentlyInTreatment + фильтр по дате
$query = MisMigrationPatient::currentlyInTreatment($branchId)
->when($today, function ($query) use ($startDate, $endDate) {
// return $query->whereBetween('DateIngoing', [$startDate, $endDate]);
// return $query->whereBetween('DateIngoing', [$startDate, $endDate]);
return $query->where('DateIngoing', '>=', $startDate)
->where('DateIngoing', '<=', $endDate);
});
@@ -690,30 +743,33 @@ class ReportController extends Controller
$medicalHistoryIds = $query->pluck('rf_MedicalHistoryID')->toArray();
if (empty($medicalHistoryIds)) {
if ($returnedCount) return 0;
if ($returnedCount) {
return 0;
}
return collect();
}
// Получаем истории
$query = MisMedicalHistory::whereIn('MedicalHistoryID', $medicalHistoryIds)
->with(['surgicalOperations' => function ($query) use ($startDate, $endDate) {
// $query->whereBetween('Date', [$startDate, $endDate]);
// $query->whereBetween('Date', [$startDate, $endDate]);
$query->where('Date', '>=', $startDate)
->where('Date', '<=', $endDate);
}])
->orderBy('DateRecipient', 'DESC');
// Выбираем план или экстренность
if (!$all && !$isOutcomeStatus) {
if (! $all && ! $isOutcomeStatus) {
if ($status === 'plan') {
$query->plan();
} else if ($status === 'emergency') {
} elseif ($status === 'emergency') {
$query->emergency();
}
}
// Для врача добавляем условие "в отделении"
if (!$isHeadOrAdmin && !$isOutcomeStatus) {
if (! $isHeadOrAdmin && ! $isOutcomeStatus) {
$query->currentlyHospitalized();
}
@@ -721,8 +777,11 @@ class ReportController extends Controller
return $query->select('MedicalHistoryID')
->pluck('MedicalHistoryID')->values();
} else {
if ($returnedCount) return $query->count();
else return $query->get();
if ($returnedCount) {
return $query->count();
} else {
return $query->get();
}
}
}
@@ -748,12 +807,12 @@ class ReportController extends Controller
*/
private function getOutcomeTypeName($visitResultId): string
{
return match($visitResultId) {
return match ($visitResultId) {
1, 7, 8, 9, 10, 11, 48, 49, 124 => 'Выписка',
2, 3, 4, 12, 13, 14 => 'Перевод',
5, 6, 15, 16 => 'Умер',
// Добавьте другие коды по мере необходимости
default => 'Другое (' . $visitResultId . ')'
default => 'Другое ('.$visitResultId.')'
};
}
@@ -773,11 +832,14 @@ class ReportController extends Controller
return $query->pluck('MedicalHistoryID')->values();
}
if ($returnedCount) return $query->count();
else return $query
->with(['surgicalOperations'])
->orderBy('DateRecipient', 'DESC')
->get();
if ($returnedCount) {
return $query->count();
} else {
return $query
->with(['surgicalOperations'])
->orderBy('DateRecipient', 'DESC')
->get();
}
}
private function buildOutcomeMedicalHistoryQuery(
@@ -785,8 +847,7 @@ class ReportController extends Controller
string $startDate,
string $endDate,
?array $visitResultIds = null
)
{
) {
$startDateOnly = Carbon::parse($startDate)->toDateString();
$endDateOnly = Carbon::parse($endDate)->toDateString();
@@ -797,7 +858,7 @@ class ReportController extends Controller
->whereHas('migrations', function ($migrationQuery) use ($branchId, $visitResultIds) {
$migrationQuery->where('rf_StationarBranchID', $branchId);
if ($visitResultIds !== null && !empty($visitResultIds)) {
if ($visitResultIds !== null && ! empty($visitResultIds)) {
$migrationQuery->whereIn('rf_kl_VisitResultID', $visitResultIds);
}
});
@@ -809,10 +870,10 @@ class ReportController extends Controller
private function getSurgicalPatients(string $status, bool $isHeadOrAdmin, $branchId, $startDate, $endDate, bool $returnedCount = false)
{
$query = MisSurgicalOperation::where('rf_StationarBranchID', $branchId)
->completed()
->completed()
// ->whereBetween('Date', [$startDate, $endDate])
->where('Date', '>=', $startDate)
->where('Date', '<=', $endDate)
->where('Date', '>=', $startDate)
->where('Date', '<=', $endDate)
->orderBy('Date', 'DESC');
if ($status === 'plan') {
@@ -821,9 +882,11 @@ class ReportController extends Controller
$query->whereIn('rf_TypeSurgOperationInTimeID', [4, 5]);
}
if ($returnedCount) return $query->count();
else return $query->get();
if ($returnedCount) {
return $query->count();
} else {
return $query->get();
}
}
/**
@@ -831,36 +894,44 @@ class ReportController extends Controller
*/
private function getCurrentPatients($branchId, bool $returnedCount = false, bool $onlyIds = false)
{
// $currentCount = MisMedicalHistory::whereIn('MedicalHistoryID', $medicalHistoryIds)
// ->currentlyHospitalized()
// ->orderBy('DateRecipient', 'DESC')
// ->count();
// $currentCount = MisMedicalHistory::whereIn('MedicalHistoryID', $medicalHistoryIds)
// ->currentlyHospitalized()
// ->orderBy('DateRecipient', 'DESC')
// ->count();
$medicalHistoryIds = MisMigrationPatient::currentlyInTreatment($branchId)
->pluck('rf_MedicalHistoryID')
->unique()
->toArray();
if (empty($medicalHistoryIds)) {
if ($returnedCount) return 0;
if ($returnedCount) {
return 0;
}
return collect();
}
if ($onlyIds) return $medicalHistoryIds;
if ($onlyIds) {
return $medicalHistoryIds;
}
$patients = MisMedicalHistory::whereIn('MedicalHistoryID', $medicalHistoryIds)
->currentlyHospitalized()
->with(['surgicalOperations'])
->orderBy('DateRecipient', 'DESC');
if ($returnedCount) return $patients->count();
else return $patients->get();
if ($returnedCount) {
return $patients->count();
} else {
return $patients->get();
}
}
public function removeObservation(
Request $request,
) {
$data = $request->validate([
'id' => 'required|string'
'id' => 'required|string',
]);
$this->reportService->removeObservationPatient($data['id']);
@@ -1028,7 +1099,7 @@ class ReportController extends Controller
'id' => $item->MKBID,
'code' => $item->DS,
'name' => $item->NAME,
'label' => trim(($item->DS ? "{$item->DS} " : '') . ($item->NAME ?? '')),
'label' => trim(($item->DS ? "{$item->DS} " : '').($item->NAME ?? '')),
])
->values();
@@ -1056,15 +1127,13 @@ class ReportController extends Controller
'id' => $item->ServiceMedicalID,
'code' => $item->ServiceMedicalCode,
'name' => $item->ServiceMedicalName,
'label' => trim(($item->ServiceMedicalCode ? "{$item->ServiceMedicalCode} " : '') . ($item->ServiceMedicalName ?? '')),
'label' => trim(($item->ServiceMedicalCode ? "{$item->ServiceMedicalCode} " : '').($item->ServiceMedicalName ?? '')),
])
->values();
return response()->json($items);
}
// api/report/unwanted-event
public function removeUnwantedEvent(UnwantedEvent $unwantedEvent, Request $request)
{
@@ -1090,7 +1159,7 @@ class ReportController extends Controller
->get();
return response()->json([
...$users
...$users,
])->setStatusCode(200);
}
@@ -1099,22 +1168,67 @@ class ReportController extends Controller
*/
private function getReportsForDateRange($departmentId, $startDate, $endDate)
{
if (Carbon::parse($startDate)->diffInDays(Carbon::parse($endDate)) > 1.0)
if (Carbon::parse($startDate)->diffInDays(Carbon::parse($endDate)) > 1.0) {
return Report::where('rf_department_id', $departmentId)
->withinPeriod($startDate, $endDate)
->orderBy('period_end', 'ASC')
->get();
else
} else {
return Report::where('rf_department_id', $departmentId)
->exactPeriod($startDate, $endDate)
->orderBy('period_end', 'ASC')
->get();
->exactPeriod($startDate, $endDate)
->orderBy('period_end', 'ASC')
->get();
}
}
private function resolveBaseStatus(string $status): string
{
if (str_starts_with($status, 'mis-')) {
return substr($status, 4);
}
if (str_starts_with($status, 'special-')) {
return substr($status, 8);
}
return $status;
}
private function attachReanimationIndicators(Collection $patients, int $departmentId): void
{
if ($patients->isEmpty()) {
return;
}
$medicalHistoryIds = $patients
->map(function ($patient) {
return (int) ($patient->medicalHistoryId ?? $patient->MedicalHistoryID ?? 0);
})
->filter()
->unique()
->values()
->all();
if (empty($medicalHistoryIds)) {
return;
}
$latestIndicators = $this->reportService->getLatestReanimationIndicators($departmentId, $medicalHistoryIds);
$patients->transform(function ($patient) use ($latestIndicators) {
$medicalHistoryId = (int) ($patient->medicalHistoryId ?? $patient->MedicalHistoryID ?? 0);
$indicator = $medicalHistoryId ? $latestIndicators->get($medicalHistoryId) : null;
$patient->reanimation_indicator = $indicator?->indicator;
$patient->reanimation_comment = $indicator?->comment;
return $patient;
});
}
public function checkReport(Request $request)
{
$request->validate([
'department_id' => 'required|integer|exists:departments,department_id'
'department_id' => 'required|integer|exists:departments,department_id',
]);
$report = Report::where('rf_department_id', $request->department_id)
@@ -1123,7 +1237,7 @@ class ReportController extends Controller
return response()->json([
'report_id' => $report?->report_id,
'exists' => (bool) $report
'exists' => (bool) $report,
]);
}
}