getHistoricalCurrentMedicalHistoryIds($type, $branchId, $dateRange); } $typeIds = match ($type) { 'plan' => self::PLAN_STATUSES, 'emergency' => self::EMERGENCY_STATUSES, default => null }; return MisMigrationPatient::currentlyInTreatment($branchId) ->whereHas('medicalHistory', function ($q) use ($typeIds) { $q->whereIn('rf_EmerSignID', $typeIds); }) ->pluck('rf_MedicalHistoryID') ->toArray(); } public function getHistoricalCurrentMedicalHistoryIds(?string $type, int $branchId, DateRange $dateRange): array { $endAt = $dateRange->endSql(); $typeIds = match ($type) { 'plan' => self::PLAN_STATUSES, 'emergency' => self::EMERGENCY_STATUSES, default => null }; $lastMovementSubquery = DB::table('stt_migrationpatient as mp') ->selectRaw(' mp."rf_MedicalHistoryID", mp."rf_StationarBranchID", mp."DateIngoing", mp."SystemDate", mp."MigrationPatientID", row_number() over ( partition by mp."rf_MedicalHistoryID" order by mp."DateIngoing" desc, mp."SystemDate" desc, mp."MigrationPatientID" desc ) as rn ') ->where('mp.rf_MedicalHistoryID', '<>', 0) ->where('mp.DateIngoing', '<', $endAt); return DB::query() ->fromSub($lastMovementSubquery, 'last_mp') ->leftJoin('stt_medicalhistory as mh', 'mh.MedicalHistoryID', '=', 'last_mp.rf_MedicalHistoryID') ->where('last_mp.rn', 1) ->where('last_mp.rf_StationarBranchID', $branchId) ->where(function ($q) use ($endAt) { $q->whereNull('mh.DateExtract') ->orWhere('mh.DateExtract', '>=', $endAt) ->orWhereDate('mh.DateExtract', '1900-01-01') ->orWhereDate('mh.DateExtract', '2222-01-01'); }) ->where(function ($q) use ($endAt) { $q->whereNull('mh.DateDeath') ->orWhere('mh.DateDeath', '>=', $endAt) ->orWhereDate('mh.DateDeath', '1900-01-01') ->orWhereDate('mh.DateDeath', '2222-01-01'); }) ->when($typeIds, function ($q) use ($typeIds) { $q->whereIn('mh.rf_EmerSignID', $typeIds); }) ->pluck('last_mp.rf_MedicalHistoryID') ->toArray(); } }