Files
ladill-care/app/Http/Controllers/Care/SpecialtyModuleController.php
T
isaaccladandCursor cfa71c2c15
Deploy Ladill Care / deploy (push) Successful in 52s
Add full Physiotherapy and Maternity specialty clinical suites.
Mirror Eye Care depth with stages, workspace tabs, clinical JSON, stage Move→tab routing, reports/print, demo seeds, and suite feature tests.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-19 16:39:22 +00:00

1198 lines
54 KiB
PHP

<?php
namespace App\Http\Controllers\Care;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Http\Controllers\Controller;
use App\Models\Appointment;
use App\Models\Department;
use App\Models\InvestigationType;
use App\Models\PatientAttachment;
use App\Models\Visit;
use App\Services\Care\AppointmentService;
use App\Services\Care\CareQueueBridge;
use App\Services\Care\CareQueueSessionAdvance;
use App\Services\Care\ConsultationService;
use App\Services\Care\OrganizationResolver;
use App\Services\Care\SpecialtyClinicalRecordService;
use App\Services\Care\SpecialtyModuleService;
use App\Services\Care\SpecialtyShellService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
class SpecialtyModuleController extends Controller
{
use ScopesToAccount;
public function show(
Request $request,
string $module,
SpecialtyModuleService $modules,
SpecialtyShellService $shell,
CareQueueBridge $queueBridge,
): View {
// Everyone lands on the specialty list/index — never auto-open a patient.
return $this->renderShell($request, $module, 'visits', $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|RedirectResponse {
// Bare /workspace (no visit) is the old auto-open entry — send users to the list.
if ($visit === null) {
return redirect()->route('care.specialty.show', $module);
}
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($modules->memberCanManage($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($modules->memberCanManage($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 = match ($module) {
'dentistry' => 'odontogram',
'emergency' => 'triage',
'blood_bank' => 'requests',
'ophthalmology' => 'refraction',
'physiotherapy' => 'assessment',
'maternity' => 'history',
default => (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;
if ($visit) {
$stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
$nextStage = $stageService->stageOnConsultationStart($module);
if ($nextStage && ! $visit->specialty_stage) {
try {
$stageService->setStage(
$organization,
$visit,
$module,
$nextStage,
$owner,
$owner,
);
$visit = $visit->fresh();
} catch (\InvalidArgumentException) {
// Stage map may be empty for some modules.
}
} elseif ($nextStage && in_array($visit->specialty_stage, ['waiting', 'arrival', 'request', 'check_in'], true)) {
try {
$stageService->setStage($organization, $visit, $module, $nextStage, $owner, $owner);
$visit = $visit->fresh();
} catch (\InvalidArgumentException) {
}
}
}
$clinical = app(SpecialtyClinicalRecordService::class);
$shellTabs = app(SpecialtyShellService::class)->workspaceTabs($module);
$preferredTab = match ($module) {
'dentistry' => 'odontogram',
'emergency' => 'triage',
'blood_bank' => 'requests',
'ophthalmology' => 'refraction',
'physiotherapy' => 'assessment',
'maternity' => 'history',
default => (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($modules->memberCanManage($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,
);
if ($module === 'emergency' && $recordType === 'triage') {
$workflow = app(\App\Services\Care\Emergency\EmergencyWorkflowService::class);
$stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
$suggested = $workflow->stageFromTriage($record->payload ?? []);
$current = $visit->specialty_stage;
if (! $current || in_array($current, ['arrival', 'waiting'], true)) {
try {
$stageService->setStage(
$organization,
$visit,
'emergency',
$suggested,
$this->ownerRef($request),
$this->ownerRef($request),
);
} catch (\InvalidArgumentException) {
}
}
}
if ($module === 'emergency' && $recordType === 'observation') {
$stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
try {
$stageService->setStage(
$organization,
$visit,
'emergency',
\App\Services\Care\Emergency\EmergencyWorkflowService::STAGE_OBSERVATION,
$this->ownerRef($request),
$this->ownerRef($request),
);
} catch (\InvalidArgumentException) {
}
}
if ($module === 'blood_bank' && $recordType === 'blood_request') {
$workflow = app(\App\Services\Care\BloodBank\BloodBankWorkflowService::class);
$stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
$suggested = $workflow->stageFromRequest($record->payload ?? []);
$current = $visit->specialty_stage;
if (! $current || in_array($current, ['request', 'waiting'], true)) {
try {
$stageService->setStage(
$organization,
$visit,
'blood_bank',
$suggested,
$this->ownerRef($request),
$this->ownerRef($request),
);
} catch (\InvalidArgumentException) {
}
} elseif ($suggested !== $current && in_array($suggested, ['crossmatch', 'issue'], true)) {
// Advance when cross-match / issue status progresses on an existing request.
$order = ['request' => 0, 'crossmatch' => 1, 'issue' => 2, 'transfusion' => 3, 'completed' => 4];
if (($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
try {
$stageService->setStage(
$organization,
$visit,
'blood_bank',
$suggested,
$this->ownerRef($request),
$this->ownerRef($request),
);
} catch (\InvalidArgumentException) {
}
}
}
}
if ($module === 'ophthalmology' && in_array($recordType, ['refraction', 'eye_exam', 'eye_investigation', 'eye_plan'], true)) {
$workflow = app(\App\Services\Care\Ophthalmology\OphthalmologyWorkflowService::class);
$stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
$suggested = match ($recordType) {
'refraction' => $workflow->stageFromRefraction($record->payload ?? []),
'eye_exam' => $workflow->stageFromExam($record->payload ?? []),
'eye_investigation' => \App\Services\Care\Ophthalmology\OphthalmologyWorkflowService::STAGE_INVESTIGATION,
'eye_plan' => $workflow->stageFromPlan($record->payload ?? []),
default => null,
};
$current = $visit->specialty_stage;
$early = ['check_in', 'history', 'waiting', null, ''];
if ($suggested && (! $current || in_array($current, $early, true))) {
try {
$stageService->setStage(
$organization,
$visit,
'ophthalmology',
$suggested,
$this->ownerRef($request),
$this->ownerRef($request),
);
} catch (\InvalidArgumentException) {
}
} elseif ($suggested && $suggested !== $current) {
$order = [
'check_in' => 0,
'history' => 1,
'refraction' => 2,
'exam' => 3,
'investigation' => 4,
'plan' => 5,
'treatment' => 6,
'completed' => 7,
];
if (($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
try {
$stageService->setStage(
$organization,
$visit,
'ophthalmology',
$suggested,
$this->ownerRef($request),
$this->ownerRef($request),
);
} catch (\InvalidArgumentException) {
}
}
}
}
if ($module === 'physiotherapy' && in_array($recordType, ['pt_assessment', 'pt_plan', 'pt_session', 'pt_home_program'], true)) {
$workflow = app(\App\Services\Care\Physiotherapy\PhysiotherapyWorkflowService::class);
$stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
$suggested = match ($recordType) {
'pt_assessment' => $workflow->stageFromAssessment($record->payload ?? []),
'pt_plan' => $workflow->stageFromPlan($record->payload ?? []),
'pt_session' => $workflow->stageFromSession($record->payload ?? []),
'pt_home_program' => $workflow->stageFromHomeProgram($record->payload ?? []),
default => null,
};
$current = $visit->specialty_stage;
$early = ['check_in', 'waiting', null, ''];
$order = [
'check_in' => 0,
'assessment' => 1,
'treatment_plan' => 2,
'session' => 3,
'progress' => 4,
'completed' => 5,
];
if ($suggested && (! $current || in_array($current, $early, true))) {
try {
$stageService->setStage(
$organization,
$visit,
'physiotherapy',
$suggested,
$this->ownerRef($request),
$this->ownerRef($request),
);
} catch (\InvalidArgumentException) {
}
} elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
try {
$stageService->setStage(
$organization,
$visit,
'physiotherapy',
$suggested,
$this->ownerRef($request),
$this->ownerRef($request),
);
} catch (\InvalidArgumentException) {
}
}
}
if ($module === 'maternity' && in_array($recordType, ['anc_history', 'obstetric_exam', 'fetal_notes', 'mat_investigation', 'mat_plan'], true)) {
$workflow = app(\App\Services\Care\Maternity\MaternityWorkflowService::class);
$stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
$suggested = match ($recordType) {
'anc_history' => $workflow->stageFromHistory($record->payload ?? []),
'obstetric_exam' => $workflow->stageFromExam($record->payload ?? []),
'fetal_notes' => $workflow->stageFromFetal($record->payload ?? []),
'mat_investigation' => \App\Services\Care\Maternity\MaternityWorkflowService::STAGE_INVESTIGATION,
'mat_plan' => $workflow->stageFromPlan($record->payload ?? []),
default => null,
};
$current = $visit->specialty_stage;
$early = ['check_in', 'waiting', null, ''];
$order = [
'check_in' => 0,
'history' => 1,
'exam' => 2,
'investigation' => 3,
'plan' => 4,
'postnatal' => 5,
'completed' => 6,
];
if ($suggested && (! $current || in_array($current, $early, true))) {
try {
$stageService->setStage(
$organization,
$visit,
'maternity',
$suggested,
$this->ownerRef($request),
$this->ownerRef($request),
);
} catch (\InvalidArgumentException) {
}
} elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
try {
$stageService->setStage(
$organization,
$visit,
'maternity',
$suggested,
$this->ownerRef($request),
$this->ownerRef($request),
);
} catch (\InvalidArgumentException) {
}
}
}
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);
// Viewing docs is workspace GET (memberCanAccess / memberCanView). Upload needs manage.
abort_unless($modules->memberCanAccess($organization, $member, $module), 403);
abort_unless($modules->memberCanManage($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($modules->memberCanManage($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.'.');
}
/**
* Refer a patient into this specialty queue (walk-in) without full clinical edit access.
*/
public function refer(
Request $request,
string $module,
SpecialtyModuleService $modules,
AppointmentService $appointments,
): RedirectResponse {
$definition = $modules->definition($module);
abort_unless($definition, 404);
$organization = $this->organization($request);
$member = $this->member($request);
abort_unless($modules->memberCanRefer($organization, $member, $module), 403);
$owner = $this->ownerRef($request);
$branchScope = app(OrganizationResolver::class)->branchScope($member);
$validated = $request->validate([
'patient_id' => ['required', 'integer', 'exists:care_patients,id'],
'branch_id' => ['nullable', 'integer', 'exists:care_branches,id'],
'reason' => ['nullable', 'string', 'max:500'],
'notes' => ['nullable', 'string', 'max:2000'],
]);
$branchId = (int) ($validated['branch_id'] ?? $branchScope ?? 0);
abort_unless($branchId > 0, 422);
$this->authorizeBranch($request, $branchId);
$department = Department::owned($owner)
->where('type', $definition['department_type'] ?? 'general')
->where('branch_id', $branchId)
->where('is_active', true)
->orderBy('id')
->first();
if (! $department) {
return back()->with('error', 'No active '.($definition['label'] ?? $module).' department at this branch.');
}
$patient = \App\Models\Patient::owned($owner)
->where('organization_id', $organization->id)
->findOrFail((int) $validated['patient_id']);
$appointment = $appointments->walkIn($organization, $owner, [
'patient_id' => $patient->id,
'branch_id' => $branchId,
'department_id' => $department->id,
'reason' => $validated['reason'] ?? ('Referral to '.($definition['label'] ?? $module)),
'notes' => $validated['notes'] ?? null,
], $owner);
\App\Services\Care\AuditLogger::record(
$owner,
'specialty.referral',
$organization->id,
$owner,
Appointment::class,
$appointment->id,
['module' => $module, 'department_id' => $department->id],
);
return redirect()
->route('care.specialty.show', $module)
->with('success', 'Referred '.$patient->fullName().' to '.($definition['label'] ?? $module).'.');
}
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);
$canManageSpecialty = $modules->memberCanManage($organization, $member, $module);
$canViewSpecialty = $modules->memberCanView($organization, $member, $module);
$canReferSpecialty = $modules->memberCanRefer($organization, $member, $module);
$specialtyAccessLevel = $modules->memberAccessLevel($organization, $member, $module);
$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.currentStageAdvance.stage'])
->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);
// Ability-based for every role (doctor, nurse, receptionist, lab, pharmacist, …).
// Module canManage alone is not enough — flags must match what mutate routes authorize.
$canConsult = $permissions->can($member, 'consultations.manage') && $canManageSpecialty;
$canAdvanceStage = $canConsult
|| ($module === 'blood_bank'
&& $canManageSpecialty
&& $permissions->can($member, 'blood_bank.manage'));
$canStartConsultation = $canConsult;
$canCallNext = $canManageSpecialty;
$canManageClinical = $canManageSpecialty;
$canManageVitals = $canManageSpecialty && (
$permissions->can($member, 'vitals.manage')
|| $permissions->can($member, 'consultations.manage')
);
$canManageQueue = $permissions->can($member, 'appointments.manage') && $canManageSpecialty;
$canAccessPatientQueue = $permissions->canAccessPatientQueue($member);
$canBookAppointments = $permissions->can($member, 'appointments.manage');
$canViewPatients = $permissions->can($member, 'patients.view');
$canViewAppointments = $permissions->can($member, 'appointments.view');
$branchLabel = $branchId
? (string) (\App\Models\Branch::owned($owner)->whereKey($branchId)->value('name') ?? '')
: '';
$done = Appointment::owned($owner)
->where('organization_id', $organization->id)
->where('status', Appointment::STATUS_COMPLETED)
->whereDate('completed_at', today())
->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'])
->orderByDesc('completed_at')
->limit(20)
->get();
$workspaceVisit = null;
$patientHeader = null;
$timeline = [];
$clinicalRecord = null;
$clinicalFields = [];
$clinicalAlerts = [];
$visitDocuments = collect();
$investigationTypes = collect();
$dentalChart = null;
$dentalTeethMap = [];
$dentalPlan = null;
$dentalPlanHistory = collect();
$dentalProcedures = collect();
$dentalImages = collect();
$dentalVisitNote = null;
$dentalCatalog = [];
$dentalRows = [];
$dentalConditions = [];
$dentalStatuses = [];
$dentalSurfaces = [];
$dentalModalities = [];
$dentalDentitions = [];
$dentalPerioExam = null;
$dentalPerioSurfaces = [];
$dentalLabCases = collect();
$dentalLabCaseTypes = [];
$dentalLabCaseStatuses = [];
$dentalRecalls = collect();
$dentalStageCodes = [];
$emergencyTriage = null;
$emergencyClinicalNote = null;
$emergencyObservation = null;
$emergencyDisposition = null;
$emergencyVitals = collect();
$emergencyLatestVitals = null;
$emergencyStageCodes = [];
$emergencyStageFlow = [];
$bloodBankRequest = null;
$bloodBankInventory = null;
$bloodBankIssue = null;
$bloodBankTransfusion = null;
$bloodBankStageCodes = [];
$bloodBankStageFlow = [];
$ophthalmologyRefraction = null;
$ophthalmologyExam = null;
$ophthalmologyInvestigation = null;
$ophthalmologyPlan = null;
$ophthalmologyProcedure = null;
$ophthalmologyStageCodes = [];
$ophthalmologyStageFlow = [];
$physiotherapyAssessment = null;
$physiotherapyPlan = null;
$physiotherapySession = null;
$physiotherapyHomeProgram = null;
$physiotherapyStageCodes = [];
$physiotherapyStageFlow = [];
$maternityHistory = null;
$maternityExam = null;
$maternityFetal = null;
$maternityInvestigation = null;
$maternityPlan = null;
$maternityPostnatal = null;
$maternityStageCodes = [];
$maternityStageFlow = [];
$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.investigationRequests.investigationType',
'bill.lineItems',
'consultations.investigationRequests.investigationType',
]);
$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);
}
}
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 ($module === 'dentistry' && $workspaceVisit->patient) {
$chartService = app(\App\Services\Care\Dentistry\DentalChartService::class);
$planService = app(\App\Services\Care\Dentistry\DentalTreatmentPlanService::class);
$analytics = app(\App\Services\Care\Dentistry\DentalAnalyticsService::class);
$perioService = app(\App\Services\Care\Dentistry\DentalPerioService::class);
$labService = app(\App\Services\Care\Dentistry\DentalLabCaseService::class);
$recallService = app(\App\Services\Care\Dentistry\DentalRecallService::class);
$dentalChart = $chartService->chartForPatient($organization, $workspaceVisit->patient, $owner);
$dentalTeethMap = $chartService->teethMap($dentalChart);
$dentalPlan = $planService->activePlanForPatient($organization, $workspaceVisit->patient, $owner);
$dentalPlanHistory = $planService->plansForPatient($organization, $workspaceVisit->patient, $owner);
$dentalProcedures = \App\Models\DentalProcedure::owned($owner)
->where('visit_id', $workspaceVisit->id)
->orderByDesc('id')
->get();
$dentalImages = \App\Models\DentalImage::owned($owner)
->where(function ($q) use ($workspaceVisit) {
$q->where('visit_id', $workspaceVisit->id)
->orWhere(function ($q2) use ($workspaceVisit) {
$q2->where('patient_id', $workspaceVisit->patient_id)
->whereNull('visit_id');
});
})
->with('attachment')
->orderByDesc('id')
->limit(40)
->get();
$dentalVisitNote = \App\Models\DentalVisitNote::owned($owner)
->where('visit_id', $workspaceVisit->id)
->first();
$dentalCatalog = $shell->provisionedServices($organization, 'dentistry');
$dentition = $dentalChart->dentition ?: \App\Services\Care\Dentistry\DentalCatalog::DENTITION_ADULT;
$dentalRows = \App\Services\Care\Dentistry\DentalCatalog::odontogramRows($dentition);
$dentalConditions = \App\Services\Care\Dentistry\DentalCatalog::conditions();
$dentalStatuses = \App\Services\Care\Dentistry\DentalCatalog::toothStatuses();
$dentalSurfaces = \App\Services\Care\Dentistry\DentalCatalog::surfaces();
$dentalModalities = \App\Services\Care\Dentistry\DentalCatalog::modalities();
$dentalDentitions = \App\Services\Care\Dentistry\DentalCatalog::dentitions();
$dentalPerioExam = $perioService->latestForPatient($organization, $workspaceVisit->patient, $owner);
$dentalPerioSurfaces = \App\Services\Care\Dentistry\DentalCatalog::perioSurfaces();
$dentalLabCases = $labService->casesForPatient($organization, $workspaceVisit->patient, $owner);
$dentalLabCaseTypes = \App\Services\Care\Dentistry\DentalCatalog::labCaseTypes();
$dentalLabCaseStatuses = \App\Services\Care\Dentistry\DentalCatalog::labCaseStatuses();
$dentalRecalls = $recallService->recallsForPatient($organization, $workspaceVisit->patient, $owner);
$dentalStageCodes = collect($shell->stages('dentistry'))->pluck('code')->all();
$clinicalAlerts = array_merge(
$clinicalAlerts,
$analytics->alertsForPatient($organization, $workspaceVisit->patient, $owner),
);
}
if ($module === 'emergency') {
$emergencyTriage = $clinical->findForVisit($workspaceVisit, 'emergency', 'triage');
$emergencyClinicalNote = $clinical->findForVisit($workspaceVisit, 'emergency', 'clinical_note');
$emergencyObservation = $clinical->findForVisit($workspaceVisit, 'emergency', 'observation');
$emergencyDisposition = $clinical->findForVisit($workspaceVisit, 'emergency', 'disposition');
$vitalsService = app(\App\Services\Care\Emergency\EmergencyVitalsService::class);
$emergencyVitals = $vitalsService->forVisit($workspaceVisit);
$emergencyLatestVitals = $vitalsService->latestForVisit($workspaceVisit);
$emergencyStageCodes = collect($shell->stages('emergency'))->pluck('code')->all();
$emergencyStageFlow = app(\App\Services\Care\Emergency\EmergencyWorkflowService::class)->stageFlow();
}
if ($module === 'blood_bank') {
$bloodBankRequest = $clinical->findForVisit($workspaceVisit, 'blood_bank', 'blood_request');
$bloodBankInventory = $clinical->findForVisit($workspaceVisit, 'blood_bank', 'inventory_note');
$bloodBankIssue = $clinical->findForVisit($workspaceVisit, 'blood_bank', 'issue_note');
$bloodBankTransfusion = $clinical->findForVisit($workspaceVisit, 'blood_bank', 'transfusion_note');
$bloodBankStageCodes = collect($shell->stages('blood_bank'))->pluck('code')->all();
$bloodBankStageFlow = app(\App\Services\Care\BloodBank\BloodBankWorkflowService::class)->stageFlow();
}
if ($module === 'ophthalmology') {
$ophthalmologyRefraction = $clinical->findForVisit($workspaceVisit, 'ophthalmology', 'refraction');
$ophthalmologyExam = $clinical->findForVisit($workspaceVisit, 'ophthalmology', 'eye_exam');
$ophthalmologyInvestigation = $clinical->findForVisit($workspaceVisit, 'ophthalmology', 'eye_investigation');
$ophthalmologyPlan = $clinical->findForVisit($workspaceVisit, 'ophthalmology', 'eye_plan');
$ophthalmologyProcedure = $clinical->findForVisit($workspaceVisit, 'ophthalmology', 'eye_procedure');
$ophthalmologyStageCodes = collect($shell->stages('ophthalmology'))->pluck('code')->all();
$ophthalmologyStageFlow = app(\App\Services\Care\Ophthalmology\OphthalmologyWorkflowService::class)->stageFlow();
}
if ($module === 'physiotherapy') {
$physiotherapyAssessment = $clinical->findForVisit($workspaceVisit, 'physiotherapy', 'pt_assessment');
$physiotherapyPlan = $clinical->findForVisit($workspaceVisit, 'physiotherapy', 'pt_plan');
$physiotherapySession = $clinical->findForVisit($workspaceVisit, 'physiotherapy', 'pt_session');
$physiotherapyHomeProgram = $clinical->findForVisit($workspaceVisit, 'physiotherapy', 'pt_home_program');
$physiotherapyStageCodes = collect($shell->stages('physiotherapy'))->pluck('code')->all();
$physiotherapyStageFlow = app(\App\Services\Care\Physiotherapy\PhysiotherapyWorkflowService::class)->stageFlow();
}
if ($module === 'maternity') {
$maternityHistory = $clinical->findForVisit($workspaceVisit, 'maternity', 'anc_history');
$maternityExam = $clinical->findForVisit($workspaceVisit, 'maternity', 'obstetric_exam');
$maternityFetal = $clinical->findForVisit($workspaceVisit, 'maternity', 'fetal_notes');
$maternityInvestigation = $clinical->findForVisit($workspaceVisit, 'maternity', 'mat_investigation');
$maternityPlan = $clinical->findForVisit($workspaceVisit, 'maternity', 'mat_plan');
$maternityPostnatal = $clinical->findForVisit($workspaceVisit, 'maternity', 'postnatal_note');
$maternityStageCodes = collect($shell->stages('maternity'))->pluck('code')->all();
$maternityStageFlow = app(\App\Services\Care\Maternity\MaternityWorkflowService::class)->stageFlow();
}
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();
if ($activeTab === 'orders' && $canConsult) {
$investigationTypes = InvestigationType::query()
->where('organization_id', $organization->id)
->where('is_active', true)
->orderBy('name')
->get();
}
}
return view('care.specialty.shell', [
'organization' => $organization,
'moduleKey' => $module,
'definition' => $shellDefinition,
'section' => $section,
'navItems' => $shell->navItems($module),
'waiting' => $waiting,
'queue' => $waiting,
'inConsultation' => $inConsultation,
'done' => $done,
'openVisits' => $openVisits,
'visitHistory' => $visitHistory,
'kpis' => $kpis,
'stages' => $shell->stages($module),
'specialtyStageFlow' => $shell->stageFlow($module),
'specialtyStageRoute' => $shell->stageAdvanceRoute($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,
'investigationTypes' => $investigationTypes,
'dentalChart' => $dentalChart,
'dentalTeethMap' => $dentalTeethMap,
'dentalPlan' => $dentalPlan,
'dentalPlanHistory' => $dentalPlanHistory,
'dentalProcedures' => $dentalProcedures,
'dentalImages' => $dentalImages,
'dentalVisitNote' => $dentalVisitNote,
'dentalCatalog' => $dentalCatalog,
'dentalRows' => $dentalRows,
'dentalConditions' => $dentalConditions,
'dentalStatuses' => $dentalStatuses,
'dentalSurfaces' => $dentalSurfaces,
'dentalModalities' => $dentalModalities,
'dentalDentitions' => $dentalDentitions,
'dentalPerioExam' => $dentalPerioExam,
'dentalPerioSurfaces' => $dentalPerioSurfaces,
'dentalLabCases' => $dentalLabCases,
'dentalLabCaseTypes' => $dentalLabCaseTypes,
'dentalLabCaseStatuses' => $dentalLabCaseStatuses,
'dentalRecalls' => $dentalRecalls,
'dentalStageCodes' => $dentalStageCodes,
'emergencyTriage' => $emergencyTriage,
'emergencyClinicalNote' => $emergencyClinicalNote,
'emergencyObservation' => $emergencyObservation,
'emergencyDisposition' => $emergencyDisposition,
'emergencyVitals' => $emergencyVitals,
'emergencyLatestVitals' => $emergencyLatestVitals,
'emergencyStageCodes' => $emergencyStageCodes,
'emergencyStageFlow' => $emergencyStageFlow,
'bloodBankRequest' => $bloodBankRequest,
'bloodBankInventory' => $bloodBankInventory,
'bloodBankIssue' => $bloodBankIssue,
'bloodBankTransfusion' => $bloodBankTransfusion,
'bloodBankStageCodes' => $bloodBankStageCodes,
'bloodBankStageFlow' => $bloodBankStageFlow,
'ophthalmologyRefraction' => $ophthalmologyRefraction,
'ophthalmologyExam' => $ophthalmologyExam,
'ophthalmologyInvestigation' => $ophthalmologyInvestigation,
'ophthalmologyPlan' => $ophthalmologyPlan,
'ophthalmologyProcedure' => $ophthalmologyProcedure,
'ophthalmologyStageCodes' => $ophthalmologyStageCodes,
'ophthalmologyStageFlow' => $ophthalmologyStageFlow,
'physiotherapyAssessment' => $physiotherapyAssessment,
'physiotherapyPlan' => $physiotherapyPlan,
'physiotherapySession' => $physiotherapySession,
'physiotherapyHomeProgram' => $physiotherapyHomeProgram,
'physiotherapyStageCodes' => $physiotherapyStageCodes,
'physiotherapyStageFlow' => $physiotherapyStageFlow,
'maternityHistory' => $maternityHistory,
'maternityExam' => $maternityExam,
'maternityFetal' => $maternityFetal,
'maternityInvestigation' => $maternityInvestigation,
'maternityPlan' => $maternityPlan,
'maternityPostnatal' => $maternityPostnatal,
'maternityStageCodes' => $maternityStageCodes,
'maternityStageFlow' => $maternityStageFlow,
'queueStubs' => $modules->queueStubsFor($organization, $module),
'branchId' => $branchId,
'branchLabel' => $branchLabel,
'practitionerScope' => $practitionerScope,
'lockToPractitioner' => $practitionerScope !== null,
'canConsult' => $canConsult,
'canAdvanceStage' => $canAdvanceStage,
'canStartConsultation' => $canStartConsultation,
'canCallNext' => $canCallNext,
'canManageClinical' => $canManageClinical,
'canManageVitals' => $canManageVitals,
'canManageQueue' => $canManageQueue,
'canAccessPatientQueue' => $canAccessPatientQueue,
'canBookAppointments' => $canBookAppointments,
'canViewPatients' => $canViewPatients,
'canViewAppointments' => $canViewAppointments,
'canManageSpecialty' => $canManageSpecialty,
'canViewSpecialty' => $canViewSpecialty,
'canReferSpecialty' => $canReferSpecialty,
'specialtyAccessLevel' => $specialtyAccessLevel,
'queueIntegration' => $branchId
? $queueBridge->listMeta($organization, $module, $branchId)
: ['enabled' => false],
'currency' => strtoupper((string) config('care.billing.currency', config('care.currency', 'GHS'))),
]);
}
}