renderShell($request, $module, 'overview', $modules, $shell, $queueBridge); } public function visits( Request $request, string $module, SpecialtyModuleService $modules, SpecialtyShellService $shell, CareQueueBridge $queueBridge, ): View { return $this->renderShell($request, $module, 'visits', $modules, $shell, $queueBridge); } 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 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, ): 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($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($this->ownerRef($request)) ->whereKey($practitionerId) ->value('branch_id'); if ($pracBranch > 0) { $branchId = $pracBranch; } } abort_unless($branchId > 0, 422); $result = $queueBridge->callNext($organization, $module, $branchId, $member, $practitionerId); $ticket = $result['ticket'] ?? null; if (! $ticket) { return back()->with('info', 'No patients waiting in this specialty queue.'); } return back()->with('success', 'Called '.$ticket['ticket_number'].'.'); } 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(); $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($branchScope, fn ($q) => $q->where('branch_id', $branchScope)) ->when( $practitionerScope !== null, fn ($q) => $q->whereIn('practitioner_id', $practitionerScope ?: [0]), ) ->with(['patient', 'practitioner', 'department', 'visit']) ->orderBy('queue_position') ->orderBy('checked_in_at') ->limit(25) ->get(); $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; } } $shellDefinition = $shell->definition($module); $kpis = $shell->kpis($organization, $module, $owner, $branchScope, $practitionerScope); $openVisits = $shell->openVisits($organization, $module, $owner, $branchScope, $practitionerScope); $visitHistory = $section === 'history' ? $shell->visitHistory($organization, $module, $owner, $branchScope, $practitionerScope) : collect(); $services = $shell->provisionedServices($organization, $module); $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', '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', '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), 'departments' => $departments, 'waiting' => $waiting, '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, 'queueIntegration' => $branchId ? $queueBridge->listMeta($organization, $module, $branchId) : ['enabled' => false], 'currency' => strtoupper((string) config('care.billing.currency', config('care.currency', 'GHS'))), ]); } }