Deploy Ladill Care / deploy (push) Successful in 37s
Give nurses, lab techs, pharmacists, and GPs broad access to day-to-day modules, keep restricted specialties for specialists (with support nurses), and let GPs view results or refer without full clinical edit. Co-authored-by: Cursor <cursoragent@cursor.com>
893 lines
38 KiB
PHP
893 lines
38 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,
|
|
): RedirectResponse {
|
|
$definition = $modules->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($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',
|
|
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'], 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',
|
|
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) {
|
|
}
|
|
}
|
|
|
|
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($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.queue.index')
|
|
->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);
|
|
$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'])
|
|
->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') && $canManageSpecialty;
|
|
$canManageQueue = $permissions->can($member, 'appointments.manage') && $canManageSpecialty;
|
|
$branchLabel = $branchId
|
|
? (string) (\App\Models\Branch::owned($owner)->whereKey($branchId)->value('name') ?? '')
|
|
: '';
|
|
|
|
$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 = [];
|
|
$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);
|
|
}
|
|
} elseif ($section === 'workspace') {
|
|
$first = $openVisits->first();
|
|
if ($first?->patient) {
|
|
$first->load([
|
|
'patient.allergies',
|
|
'patient.emergencyContacts',
|
|
'patient.attachments',
|
|
'appointment.practitioner',
|
|
'appointment.consultation.investigationRequests.investigationType',
|
|
'bill.lineItems',
|
|
'consultations.investigationRequests.investigationType',
|
|
]);
|
|
$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 ($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 ($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,
|
|
'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,
|
|
'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,
|
|
'queueStubs' => $modules->queueStubsFor($organization, $module),
|
|
'branchId' => $branchId,
|
|
'branchLabel' => $branchLabel,
|
|
'practitionerScope' => $practitionerScope,
|
|
'lockToPractitioner' => $practitionerScope !== null,
|
|
'canConsult' => $canConsult,
|
|
'canManageQueue' => $canManageQueue,
|
|
'canManageSpecialty' => $canManageSpecialty,
|
|
'canReferSpecialty' => $canReferSpecialty,
|
|
'specialtyAccessLevel' => $specialtyAccessLevel,
|
|
'queueIntegration' => $branchId
|
|
? $queueBridge->listMeta($organization, $module, $branchId)
|
|
: ['enabled' => false],
|
|
'currency' => strtoupper((string) config('care.billing.currency', config('care.currency', 'GHS'))),
|
|
]);
|
|
}
|
|
}
|