definition($module); abort_unless($definition, 404); abort_unless( $modules->memberCanAccess($this->organization($request), $this->member($request), $module), 403, ); // Specialty patient flow lives on Queue; clinical depth opens from Queue Start. return redirect()->route('care.queue.index'); } public function visits( Request $request, string $module, SpecialtyModuleService $modules, SpecialtyShellService $shell, CareQueueBridge $queueBridge, ): RedirectResponse { $definition = $modules->definition($module); abort_unless($definition, 404); abort_unless( $modules->memberCanAccess($this->organization($request), $this->member($request), $module), 403, ); return redirect()->route('care.queue.index'); } public function history( Request $request, string $module, SpecialtyModuleService $modules, SpecialtyShellService $shell, CareQueueBridge $queueBridge, ): View { return $this->renderShell($request, $module, 'history', $modules, $shell, $queueBridge); } public function billing( Request $request, string $module, SpecialtyModuleService $modules, SpecialtyShellService $shell, CareQueueBridge $queueBridge, ): View { return $this->renderShell($request, $module, 'billing', $modules, $shell, $queueBridge); } public function workspace( Request $request, string $module, SpecialtyModuleService $modules, SpecialtyShellService $shell, CareQueueBridge $queueBridge, ?Visit $visit = null, ): View { return $this->renderShell($request, $module, 'workspace', $modules, $shell, $queueBridge, $visit); } public function addService( Request $request, string $module, Visit $visit, SpecialtyModuleService $modules, SpecialtyShellService $shell, ): RedirectResponse { $definition = $modules->definition($module); abort_unless($definition, 404); $organization = $this->organization($request); $member = $this->member($request); abort_unless($modules->memberCanAccess($organization, $member, $module), 403); abort_unless($visit->organization_id === $organization->id, 404); $validated = $request->validate([ 'service_code' => ['required', 'string', 'max:64'], ]); try { $bill = $shell->addCatalogServiceToVisit( $organization, $visit, $module, $validated['service_code'], $this->ownerRef($request), $this->ownerRef($request), ); } catch (\Throwable $e) { return back()->with('error', $e->getMessage()); } return back()->with('success', 'Added to invoice '.$bill->invoice_number.'.'); } public function startConsultation( Request $request, string $module, Visit $visit, SpecialtyModuleService $modules, AppointmentService $appointments, ConsultationService $consultations, ): RedirectResponse { $this->authorizeAbility($request, 'consultations.manage'); $definition = $modules->definition($module); abort_unless($definition, 404); $organization = $this->organization($request); $member = $this->member($request); abort_unless($modules->memberCanAccess($organization, $member, $module), 403); abort_unless($visit->organization_id === $organization->id, 404); $this->authorizeBranch($request, (int) $visit->branch_id); $visit->loadMissing(['appointment.consultation', 'appointment.practitioner']); $appointment = $visit->appointment; if (! $appointment || $appointment->organization_id !== $organization->id) { return back()->with('error', 'This visit has no appointment to start a consultation from.'); } $owner = $this->ownerRef($request); $openConsultation = $appointment->consultation; if ($openConsultation && $openConsultation->status !== \App\Models\Consultation::STATUS_COMPLETED) { $clinical = app(SpecialtyClinicalRecordService::class); $shellTabs = app(SpecialtyShellService::class)->workspaceTabs($module); $preferredTab = collect(array_keys($shellTabs)) ->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null) ?? 'clinical_notes'; return redirect() ->route('care.specialty.workspace', [ 'module' => $module, 'visit' => $visit, 'tab' => $preferredTab, ]) ->with('success', 'Encounter already in progress.'); } try { if (in_array($appointment->status, [ Appointment::STATUS_WAITING, Appointment::STATUS_CHECKED_IN, ], true)) { $appointments->startConsultation( $appointment, $owner, $appointment->practitioner_id, $owner, ); $appointment = $appointment->fresh(['practitioner', 'visit']); } elseif ($appointment->status !== Appointment::STATUS_IN_CONSULTATION) { return back()->with('error', 'This appointment cannot start a consultation from its current status.'); } $consultations->startFromAppointment( $appointment, $owner, $owner, ); } catch (\InvalidArgumentException $e) { return back()->with('error', $e->getMessage()); } $visit = $visit->fresh() ?? $appointment->visit; $clinical = app(SpecialtyClinicalRecordService::class); $shellTabs = app(SpecialtyShellService::class)->workspaceTabs($module); $preferredTab = collect(array_keys($shellTabs)) ->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null) ?? 'clinical_notes'; return redirect() ->route('care.specialty.workspace', [ 'module' => $module, 'visit' => $visit, 'tab' => $preferredTab, ]) ->with('success', 'Encounter started.'); } public function saveClinical( Request $request, string $module, Visit $visit, SpecialtyModuleService $modules, SpecialtyClinicalRecordService $clinical, ): RedirectResponse { $definition = $modules->definition($module); abort_unless($definition, 404); $organization = $this->organization($request); $member = $this->member($request); abort_unless($modules->memberCanAccess($organization, $member, $module), 403); abort_unless($visit->organization_id === $organization->id, 404); $tab = (string) $request->input('tab', ''); $recordType = $clinical->recordTypeForTab($module, $tab); abort_unless($recordType, 422); // Normalize checkbox booleans before validation. $payload = (array) $request->input('payload', []); foreach ($clinical->fieldsFor($module, $recordType) as $field) { if (($field['type'] ?? '') === 'boolean') { $payload[$field['name']] = $request->boolean('payload.'.$field['name']); } } $request->merge(['payload' => $payload]); $validated = $request->validate(array_merge([ 'tab' => ['required', 'string'], 'stage_code' => ['nullable', 'string', 'max:64'], 'status' => ['nullable', 'in:draft,active,completed'], ], $clinical->validationRules($module, $recordType))); $record = $clinical->upsert( $organization, $visit, $module, $recordType, $clinical->payloadFromRequest($validated), $this->ownerRef($request), $this->ownerRef($request), $validated['stage_code'] ?? null, $validated['status'] ?? \App\Models\SpecialtyClinicalRecord::STATUS_ACTIVE, ); return redirect() ->route('care.specialty.workspace', [ 'module' => $module, 'visit' => $visit, 'tab' => $tab, ]) ->with('success', 'Saved '.$record->record_type.' record.'); } public function uploadDocument( Request $request, string $module, Visit $visit, SpecialtyModuleService $modules, ): RedirectResponse { $definition = $modules->definition($module); abort_unless($definition, 404); $organization = $this->organization($request); $member = $this->member($request); abort_unless($modules->memberCanAccess($organization, $member, $module), 403); abort_unless($visit->organization_id === $organization->id, 404); abort_unless($visit->patient_id, 422); $validated = $request->validate([ 'attachment' => ['required', 'file', 'max:10240', 'mimes:pdf,jpeg,jpg,png,webp'], ]); $file = $validated['attachment']; $path = $file->store("care/patients/{$visit->patient_id}/attachments", 'public'); PatientAttachment::create([ 'owner_ref' => $this->ownerRef($request), 'patient_id' => $visit->patient_id, 'file_path' => $path, 'original_name' => $file->getClientOriginalName(), 'mime_type' => $file->getMimeType(), 'document_type' => 'specialty_'.$module, 'uploaded_by' => $this->ownerRef($request), ]); return redirect() ->route('care.specialty.workspace', [ 'module' => $module, 'visit' => $visit, 'tab' => 'documents', ]) ->with('success', 'Document uploaded.'); } public function callNext( Request $request, string $module, SpecialtyModuleService $modules, CareQueueBridge $queueBridge, CareQueueSessionAdvance $advance, ): RedirectResponse { $definition = $modules->definition($module); abort_unless($definition, 404); $organization = $this->organization($request); $member = $this->member($request); $owner = $this->ownerRef($request); abort_unless($modules->memberCanAccess($organization, $member, $module), 403); abort_unless($queueBridge->isEnabled($organization), 404); $resolver = app(OrganizationResolver::class); $branchScope = $resolver->branchScope($member); $practitionerScope = $resolver->practitionerScope($organization, $member); $branchId = (int) ($request->input('branch_id') ?: $branchScope); $practitionerId = null; if ($practitionerScope !== null) { abort_unless($practitionerScope !== [], 422); $practitionerId = $practitionerScope[0]; $pracBranch = (int) \App\Models\Practitioner::owned($owner) ->whereKey($practitionerId) ->value('branch_id'); if ($pracBranch > 0) { $branchId = $pracBranch; } } abort_unless($branchId > 0, 422); if ($request->filled('appointment_id')) { $current = Appointment::owned($owner) ->where('organization_id', $organization->id) ->findOrFail((int) $request->input('appointment_id')); $advance->endCurrentEncounter($current, $owner, $owner); } $result = $queueBridge->callNext($organization, $module, $branchId, $member, $practitionerId); $ticket = $result['ticket'] ?? null; if (! $ticket) { $departmentIds = Department::owned($owner) ->where('type', $definition['department_type'] ?? 'general') ->where('is_active', true) ->when($branchScope, fn ($q) => $q->where('branch_id', $branchScope)) ->pluck('id'); $waitingAtBranch = Appointment::owned($owner) ->where('organization_id', $organization->id) ->where('branch_id', $branchId) ->whereIn('status', [Appointment::STATUS_WAITING, Appointment::STATUS_CHECKED_IN]) ->when($departmentIds->isNotEmpty(), fn ($q) => $q->whereIn('department_id', $departmentIds)) ->when($departmentIds->isEmpty(), fn ($q) => $q->whereRaw('1 = 0')) ->count(); $waitingOrg = Appointment::owned($owner) ->where('organization_id', $organization->id) ->whereIn('status', [Appointment::STATUS_WAITING, Appointment::STATUS_CHECKED_IN]) ->when($departmentIds->isNotEmpty(), fn ($q) => $q->whereIn('department_id', $departmentIds)) ->when($departmentIds->isEmpty(), fn ($q) => $q->whereRaw('1 = 0')) ->count(); $branchName = \App\Models\Branch::owned($owner)->whereKey($branchId)->value('name') ?: 'this branch'; if ($waitingAtBranch > 0) { return back()->with( 'info', "{$waitingAtBranch} patient(s) are waiting at {$branchName}, but none have a callable ticket at a service desk yet. Use Start on the queue, or check in again so a ticket is issued." ); } if ($waitingOrg > $waitingAtBranch) { return back()->with( 'info', "No patients waiting at {$branchName}. {$waitingOrg} are waiting at other branches — switch branch or open History." ); } return back()->with('info', 'No patients waiting in this queue.'); } $entity = $result['entity'] ?? null; if ($entity instanceof Appointment) { return $advance->redirectToOpenedPatient( $entity, $ticket, 'care.queue.index', ); } $name = $ticket['customer_name'] ?? 'patient'; return back()->with('success', 'Called '.$ticket['ticket_number'].' — '.$name.'.'); } protected function renderShell( Request $request, string $module, string $section, SpecialtyModuleService $modules, SpecialtyShellService $shell, CareQueueBridge $queueBridge, ?Visit $visit = null, ): View { $definition = $modules->definition($module); abort_unless($definition, 404); $organization = $this->organization($request); $member = $this->member($request); abort_unless($modules->memberCanAccess($organization, $member, $module), 403); $owner = $this->ownerRef($request); $resolver = app(OrganizationResolver::class); $branchScope = $resolver->branchScope($member); $practitionerScope = $resolver->practitionerScope($organization, $member); $departments = Department::owned($owner) ->where('type', $definition['department_type'] ?? 'general') ->where('is_active', true) ->when($branchScope, fn ($q) => $q->where('branch_id', $branchScope)) ->with('branch') ->orderBy('name') ->get(); $departmentIds = $departments->pluck('id')->all(); $branchId = (int) ($branchScope ?: $departments->first()?->branch_id); if ($practitionerScope !== null && $practitionerScope !== []) { $pracBranch = (int) \App\Models\Practitioner::owned($owner) ->whereKey($practitionerScope[0]) ->value('branch_id'); if ($pracBranch > 0) { $branchId = $pracBranch; } } // Match Call next: when the member has no branch scope (e.g. hospital admin), // KPIs / waiting lists use the same branch as queue ops so WAITING isn't org-wide // while Call next is local. $kpiBranch = $branchScope ?? ($branchId > 0 ? $branchId : null); $waiting = Appointment::owned($owner) ->where('organization_id', $organization->id) ->whereIn('status', [Appointment::STATUS_WAITING, Appointment::STATUS_CHECKED_IN]) ->when($departmentIds !== [], fn ($q) => $q->whereIn('department_id', $departmentIds)) ->when($departmentIds === [], fn ($q) => $q->whereRaw('1 = 0')) ->when($kpiBranch, fn ($q) => $q->where('branch_id', $kpiBranch)) ->when( $practitionerScope !== null, fn ($q) => $q->whereIn('practitioner_id', $practitionerScope ?: [0]), ) ->with(['patient', 'practitioner', 'department', 'visit']) ->orderBy('queue_position') ->orderBy('checked_in_at') ->limit(50) ->get(); $inConsultation = Appointment::owned($owner) ->where('organization_id', $organization->id) ->where('status', Appointment::STATUS_IN_CONSULTATION) ->when($departmentIds !== [], fn ($q) => $q->whereIn('department_id', $departmentIds)) ->when($departmentIds === [], fn ($q) => $q->whereRaw('1 = 0')) ->when($kpiBranch, fn ($q) => $q->where('branch_id', $kpiBranch)) ->when( $practitionerScope !== null, fn ($q) => $q->whereIn('practitioner_id', $practitionerScope ?: [0]), ) ->with(['patient', 'practitioner', 'consultation', 'visit']) ->orderBy('started_at') ->limit(50) ->get(); $shellDefinition = $shell->definition($module); $kpis = $shell->kpis($organization, $module, $owner, $kpiBranch, $practitionerScope); $openVisits = $shell->openVisits($organization, $module, $owner, $kpiBranch, $practitionerScope); $visitHistory = $section === 'history' ? $shell->visitHistory($organization, $module, $owner, $kpiBranch, $practitionerScope) : collect(); $services = $shell->provisionedServices($organization, $module); $permissions = app(\App\Services\Care\CarePermissions::class); $canConsult = $permissions->can($member, 'consultations.manage'); $canManageQueue = $permissions->can($member, 'appointments.manage'); $branchLabel = $branchId ? (string) (\App\Models\Branch::owned($owner)->whereKey($branchId)->value('name') ?? '') : ''; $workspaceVisit = null; $patientHeader = null; $timeline = []; $clinicalRecord = null; $clinicalFields = []; $clinicalAlerts = []; $visitDocuments = collect(); $activeTab = (string) $request->query('tab', array_key_first($shell->workspaceTabs($module)) ?: 'overview'); $clinical = app(SpecialtyClinicalRecordService::class); if ($visit) { abort_unless($visit->organization_id === $organization->id, 404); $visit->load([ 'patient.allergies', 'patient.emergencyContacts', 'patient.attachments', 'appointment.practitioner', 'appointment.consultation', 'bill.lineItems', 'consultations', ]); $workspaceVisit = $visit; if ($visit->patient) { $patientHeader = array_merge( ['patient' => $visit->patient, 'visit' => $visit, 'appointment' => $visit->appointment], $shell->patientHeaderMeta($visit->patient), ); $timeline = $shell->patientTimeline($visit->patient); } } elseif ($section === 'workspace') { $first = $openVisits->first(); if ($first?->patient) { $first->load([ 'patient.allergies', 'patient.emergencyContacts', 'patient.attachments', 'appointment.practitioner', 'appointment.consultation', 'bill.lineItems', 'consultations', ]); $workspaceVisit = $first; $patientHeader = array_merge( ['patient' => $first->patient, 'visit' => $first, 'appointment' => $first->appointment], $shell->patientHeaderMeta($first->patient), ); $timeline = $shell->patientTimeline($first->patient); } } if ($workspaceVisit && $section === 'workspace') { $recordType = $clinical->recordTypeForTab($module, $activeTab); if ($recordType) { $clinicalRecord = $clinical->findForVisit($workspaceVisit, $module, $recordType); $clinicalFields = $clinical->fieldsFor($module, $recordType); } $clinicalAlerts = $clinical->alertsForVisit($workspaceVisit, $module); if ($patientHeader !== null) { $patientHeader['clinical_alerts'] = $clinicalAlerts; } $visitDocuments = $workspaceVisit->patient ? $workspaceVisit->patient->attachments() ->where(function ($q) use ($module) { $q->where('document_type', 'specialty_'.$module) ->orWhere('document_type', 'other') ->orWhereNull('document_type'); }) ->orderByDesc('id') ->limit(20) ->get() : collect(); } return view('care.specialty.shell', [ 'organization' => $organization, 'moduleKey' => $module, 'definition' => $shellDefinition, 'section' => $section, 'navItems' => $shell->navItems($module), 'waiting' => $waiting, 'queue' => $waiting, 'inConsultation' => $inConsultation, 'openVisits' => $openVisits, 'visitHistory' => $visitHistory, 'kpis' => $kpis, 'stages' => $shell->stages($module), 'services' => $services, 'workspaceTabs' => $shell->workspaceTabs($module), 'actions' => $shell->actions($module), 'activeTab' => $activeTab, 'workspaceVisit' => $workspaceVisit, 'patientHeader' => $patientHeader, 'timeline' => $timeline, 'clinicalRecord' => $clinicalRecord, 'clinicalFields' => $clinicalFields, 'clinicalAlerts' => $clinicalAlerts, 'visitDocuments' => $visitDocuments, 'queueStubs' => $modules->queueStubsFor($organization, $module), 'branchId' => $branchId, 'branchLabel' => $branchLabel, 'practitionerScope' => $practitionerScope, 'lockToPractitioner' => $practitionerScope !== null, 'canConsult' => $canConsult, 'canManageQueue' => $canManageQueue, 'queueIntegration' => $branchId ? $queueBridge->listMeta($organization, $module, $branchId) : ['enabled' => false], 'currency' => strtoupper((string) config('care.billing.currency', config('care.currency', 'GHS'))), ]); } }