Add full Eye Care (ophthalmology) specialty clinical suite.
Deploy Ladill Care / deploy (push) Successful in 35s
Deploy Ladill Care / deploy (push) Successful in 35s
Mirror Emergency/Blood Bank depth with stages, workspace tabs, workflow/analytics services, reports/print, demo clinical seed, and feature tests. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,211 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Care;
|
||||
|
||||
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\SpecialtyClinicalRecord;
|
||||
use App\Models\Visit;
|
||||
use App\Services\Care\Ophthalmology\OphthalmologyAnalyticsService;
|
||||
use App\Services\Care\Ophthalmology\OphthalmologyWorkflowService;
|
||||
use App\Services\Care\SpecialtyClinicalRecordService;
|
||||
use App\Services\Care\SpecialtyModuleService;
|
||||
use App\Services\Care\SpecialtyShellService;
|
||||
use App\Services\Care\SpecialtyVisitStageService;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class OphthalmologyWorkspaceController extends Controller
|
||||
{
|
||||
use ScopesToAccount;
|
||||
|
||||
protected function assertOphthalmologyAccess(Request $request, SpecialtyModuleService $modules): void
|
||||
{
|
||||
$organization = $this->organization($request);
|
||||
abort_unless($modules->memberCanAccess($organization, $this->member($request), 'ophthalmology'), 403);
|
||||
}
|
||||
|
||||
protected function assertOphthalmologyManage(Request $request, SpecialtyModuleService $modules): void
|
||||
{
|
||||
$organization = $this->organization($request);
|
||||
abort_unless($modules->memberCanManage($organization, $this->member($request), 'ophthalmology'), 403);
|
||||
}
|
||||
|
||||
protected function assertVisit(Request $request, Visit $visit): void
|
||||
{
|
||||
abort_unless($visit->organization_id === $this->organization($request)->id, 404);
|
||||
$this->authorizeBranch($request, (int) $visit->branch_id);
|
||||
}
|
||||
|
||||
public function setStage(
|
||||
Request $request,
|
||||
Visit $visit,
|
||||
SpecialtyModuleService $modules,
|
||||
SpecialtyVisitStageService $stages,
|
||||
): RedirectResponse {
|
||||
$this->authorizeAbility($request, 'consultations.manage');
|
||||
$this->assertOphthalmologyManage($request, $modules);
|
||||
$this->assertVisit($request, $visit);
|
||||
|
||||
$validated = $request->validate([
|
||||
'stage' => ['required', 'string', 'max:32'],
|
||||
]);
|
||||
|
||||
try {
|
||||
$stages->setStage(
|
||||
$this->organization($request),
|
||||
$visit,
|
||||
'ophthalmology',
|
||||
$validated['stage'],
|
||||
$this->ownerRef($request),
|
||||
$this->actorRef($request),
|
||||
);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
return back()->with('error', $e->getMessage());
|
||||
}
|
||||
|
||||
return redirect()
|
||||
->route('care.specialty.workspace', ['module' => 'ophthalmology', 'visit' => $visit, 'tab' => 'overview'])
|
||||
->with('success', 'Visit stage updated.');
|
||||
}
|
||||
|
||||
public function saveProcedure(
|
||||
Request $request,
|
||||
Visit $visit,
|
||||
SpecialtyModuleService $modules,
|
||||
SpecialtyClinicalRecordService $clinical,
|
||||
SpecialtyVisitStageService $stages,
|
||||
OphthalmologyWorkflowService $workflow,
|
||||
): RedirectResponse {
|
||||
$this->authorizeAbility($request, 'consultations.manage');
|
||||
$this->assertOphthalmologyManage($request, $modules);
|
||||
$this->assertVisit($request, $visit);
|
||||
|
||||
$organization = $this->organization($request);
|
||||
$owner = $this->ownerRef($request);
|
||||
|
||||
$payload = (array) $request->input('payload', []);
|
||||
foreach ($clinical->fieldsFor('ophthalmology', 'eye_procedure') as $field) {
|
||||
if (($field['type'] ?? '') === 'boolean') {
|
||||
$payload[$field['name']] = $request->boolean('payload.'.$field['name']);
|
||||
}
|
||||
}
|
||||
$request->merge(['payload' => $payload, 'tab' => 'treat']);
|
||||
|
||||
$validated = $request->validate(array_merge([
|
||||
'tab' => ['required', 'string'],
|
||||
], $clinical->validationRules('ophthalmology', 'eye_procedure')));
|
||||
|
||||
$record = $clinical->upsert(
|
||||
$organization,
|
||||
$visit,
|
||||
'ophthalmology',
|
||||
'eye_procedure',
|
||||
$clinical->payloadFromRequest($validated),
|
||||
$owner,
|
||||
$owner,
|
||||
OphthalmologyWorkflowService::STAGE_TREATMENT,
|
||||
SpecialtyClinicalRecord::STATUS_COMPLETED,
|
||||
);
|
||||
|
||||
try {
|
||||
$stages->setStage(
|
||||
$organization,
|
||||
$visit,
|
||||
'ophthalmology',
|
||||
OphthalmologyWorkflowService::STAGE_TREATMENT,
|
||||
$owner,
|
||||
$owner,
|
||||
);
|
||||
} catch (\InvalidArgumentException) {
|
||||
// Stage already treatment or map empty.
|
||||
}
|
||||
|
||||
if ($workflow->shouldCompleteVisit($record->payload ?? [])) {
|
||||
try {
|
||||
$stages->setStage(
|
||||
$organization,
|
||||
$visit,
|
||||
'ophthalmology',
|
||||
OphthalmologyWorkflowService::STAGE_COMPLETED,
|
||||
$owner,
|
||||
$owner,
|
||||
);
|
||||
} catch (\InvalidArgumentException) {
|
||||
}
|
||||
|
||||
$visit->refresh();
|
||||
if ($visit->status !== Visit::STATUS_COMPLETED) {
|
||||
$visit->update([
|
||||
'status' => Visit::STATUS_COMPLETED,
|
||||
'completed_at' => $visit->completed_at ?? now(),
|
||||
]);
|
||||
}
|
||||
|
||||
$appointment = $visit->appointment;
|
||||
if ($appointment && $appointment->status !== \App\Models\Appointment::STATUS_COMPLETED) {
|
||||
$appointment->update([
|
||||
'status' => \App\Models\Appointment::STATUS_COMPLETED,
|
||||
'completed_at' => $appointment->completed_at ?? now(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
return redirect()
|
||||
->route('care.specialty.workspace', ['module' => 'ophthalmology', 'visit' => $visit, 'tab' => 'treat'])
|
||||
->with('success', 'Procedure / treatment saved.');
|
||||
}
|
||||
|
||||
public function reports(
|
||||
Request $request,
|
||||
SpecialtyModuleService $modules,
|
||||
SpecialtyShellService $shell,
|
||||
OphthalmologyAnalyticsService $analytics,
|
||||
): View {
|
||||
$this->authorizeAbility($request, 'consultations.view');
|
||||
$this->assertOphthalmologyAccess($request, $modules);
|
||||
|
||||
$organization = $this->organization($request);
|
||||
$branchScope = app(\App\Services\Care\OrganizationResolver::class)->branchScope($this->member($request));
|
||||
|
||||
$report = $analytics->report(
|
||||
$organization,
|
||||
$this->ownerRef($request),
|
||||
$branchScope,
|
||||
$request->query('from'),
|
||||
$request->query('to'),
|
||||
);
|
||||
|
||||
return view('care.specialty.ophthalmology.reports', [
|
||||
'moduleKey' => 'ophthalmology',
|
||||
'definition' => $modules->definition('ophthalmology'),
|
||||
'shellNav' => $shell->navItems('ophthalmology'),
|
||||
'report' => $report,
|
||||
'currency' => strtoupper((string) config('care.billing.currency', config('care.currency', 'GHS'))),
|
||||
]);
|
||||
}
|
||||
|
||||
public function printSummary(
|
||||
Request $request,
|
||||
Visit $visit,
|
||||
SpecialtyModuleService $modules,
|
||||
SpecialtyClinicalRecordService $clinical,
|
||||
): View {
|
||||
$this->authorizeAbility($request, 'consultations.view');
|
||||
$this->assertOphthalmologyAccess($request, $modules);
|
||||
$this->assertVisit($request, $visit);
|
||||
|
||||
$visit->loadMissing(['patient', 'appointment.practitioner', 'branch']);
|
||||
|
||||
return view('care.specialty.ophthalmology.print', [
|
||||
'visit' => $visit,
|
||||
'patient' => $visit->patient,
|
||||
'refraction' => $clinical->findForVisit($visit, 'ophthalmology', 'refraction'),
|
||||
'exam' => $clinical->findForVisit($visit, 'ophthalmology', 'eye_exam'),
|
||||
'investigation' => $clinical->findForVisit($visit, 'ophthalmology', 'eye_investigation'),
|
||||
'plan' => $clinical->findForVisit($visit, 'ophthalmology', 'eye_plan'),
|
||||
'procedure' => $clinical->findForVisit($visit, 'ophthalmology', 'eye_procedure'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -153,6 +153,7 @@ class SpecialtyModuleController extends Controller
|
||||
'dentistry' => 'odontogram',
|
||||
'emergency' => 'triage',
|
||||
'blood_bank' => 'requests',
|
||||
'ophthalmology' => 'refraction',
|
||||
default => (collect(array_keys($shellTabs))
|
||||
->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null)
|
||||
?? 'clinical_notes'),
|
||||
@@ -210,7 +211,7 @@ class SpecialtyModuleController extends Controller
|
||||
} catch (\InvalidArgumentException) {
|
||||
// Stage map may be empty for some modules.
|
||||
}
|
||||
} elseif ($nextStage && in_array($visit->specialty_stage, ['waiting', 'arrival', 'request'], true)) {
|
||||
} 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();
|
||||
@@ -224,6 +225,7 @@ class SpecialtyModuleController extends Controller
|
||||
'dentistry' => 'odontogram',
|
||||
'emergency' => 'triage',
|
||||
'blood_bank' => 'requests',
|
||||
'ophthalmology' => 'refraction',
|
||||
default => (collect(array_keys($shellTabs))
|
||||
->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null)
|
||||
?? 'clinical_notes'),
|
||||
@@ -356,6 +358,57 @@ class SpecialtyModuleController extends Controller
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return redirect()
|
||||
->route('care.specialty.workspace', [
|
||||
'module' => $module,
|
||||
@@ -749,6 +802,13 @@ class SpecialtyModuleController extends Controller
|
||||
$bloodBankTransfusion = null;
|
||||
$bloodBankStageCodes = [];
|
||||
$bloodBankStageFlow = [];
|
||||
$ophthalmologyRefraction = null;
|
||||
$ophthalmologyExam = null;
|
||||
$ophthalmologyInvestigation = null;
|
||||
$ophthalmologyPlan = null;
|
||||
$ophthalmologyProcedure = null;
|
||||
$ophthalmologyStageCodes = [];
|
||||
$ophthalmologyStageFlow = [];
|
||||
$activeTab = (string) $request->query('tab', array_key_first($shell->workspaceTabs($module)) ?: 'overview');
|
||||
$clinical = app(SpecialtyClinicalRecordService::class);
|
||||
|
||||
@@ -855,6 +915,16 @@ class SpecialtyModuleController extends Controller
|
||||
$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 ($patientHeader !== null) {
|
||||
$patientHeader['clinical_alerts'] = $clinicalAlerts;
|
||||
}
|
||||
@@ -940,6 +1010,13 @@ class SpecialtyModuleController extends Controller
|
||||
'bloodBankTransfusion' => $bloodBankTransfusion,
|
||||
'bloodBankStageCodes' => $bloodBankStageCodes,
|
||||
'bloodBankStageFlow' => $bloodBankStageFlow,
|
||||
'ophthalmologyRefraction' => $ophthalmologyRefraction,
|
||||
'ophthalmologyExam' => $ophthalmologyExam,
|
||||
'ophthalmologyInvestigation' => $ophthalmologyInvestigation,
|
||||
'ophthalmologyPlan' => $ophthalmologyPlan,
|
||||
'ophthalmologyProcedure' => $ophthalmologyProcedure,
|
||||
'ophthalmologyStageCodes' => $ophthalmologyStageCodes,
|
||||
'ophthalmologyStageFlow' => $ophthalmologyStageFlow,
|
||||
'queueStubs' => $modules->queueStubsFor($organization, $module),
|
||||
'branchId' => $branchId,
|
||||
'branchLabel' => $branchLabel,
|
||||
|
||||
@@ -1014,6 +1014,7 @@ class DemoTenantSeeder
|
||||
|
||||
$this->seedDentistryClinicalDemo($organization, $ownerRef);
|
||||
$this->seedBloodBankInventoryDemo($organization, $ownerRef);
|
||||
$this->seedOphthalmologyClinicalDemo($organization, $ownerRef);
|
||||
|
||||
return $count;
|
||||
}
|
||||
@@ -1113,6 +1114,134 @@ class DemoTenantSeeder
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Seed refraction + eye exam (+ optional plan) on open ophthalmology visits.
|
||||
*/
|
||||
private function seedOphthalmologyClinicalDemo(Organization $organization, string $ownerRef): void
|
||||
{
|
||||
$branchIds = Branch::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->pluck('id');
|
||||
|
||||
if ($branchIds->isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$departmentIds = Department::owned($ownerRef)
|
||||
->whereIn('branch_id', $branchIds)
|
||||
->where('type', 'ophthalmology')
|
||||
->where('is_active', true)
|
||||
->pluck('id');
|
||||
|
||||
if ($departmentIds->isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$appointments = Appointment::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->whereIn('department_id', $departmentIds)
|
||||
->whereIn('status', [Appointment::STATUS_WAITING, Appointment::STATUS_CHECKED_IN])
|
||||
->whereNotNull('visit_id')
|
||||
->with('visit')
|
||||
->orderBy('branch_id')
|
||||
->orderBy('id')
|
||||
->get();
|
||||
|
||||
if ($appointments->isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$clinical = app(SpecialtyClinicalRecordService::class);
|
||||
$index = 0;
|
||||
|
||||
foreach ($appointments as $appointment) {
|
||||
$visit = $appointment->visit;
|
||||
if (! $visit) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$elevated = $index === 0;
|
||||
$clinical->upsert(
|
||||
$organization,
|
||||
$visit,
|
||||
'ophthalmology',
|
||||
'refraction',
|
||||
[
|
||||
'va_od' => $elevated ? '6/60' : '6/9',
|
||||
'va_os' => $elevated ? '6/36' : '6/6',
|
||||
'va_od_near' => 'N8',
|
||||
'va_os_near' => 'N6',
|
||||
'sphere_od' => $elevated ? '-2.50' : '-0.75',
|
||||
'cylinder_od' => '-0.50',
|
||||
'axis_od' => '90',
|
||||
'sphere_os' => $elevated ? '-1.75' : '-0.50',
|
||||
'cylinder_os' => '-0.25',
|
||||
'axis_os' => '85',
|
||||
'add' => '+1.50',
|
||||
'pd' => 62,
|
||||
'notes' => 'Demo refraction for eye care suite.',
|
||||
],
|
||||
$ownerRef,
|
||||
$ownerRef,
|
||||
'refraction',
|
||||
);
|
||||
|
||||
$clinical->upsert(
|
||||
$organization,
|
||||
$visit,
|
||||
'ophthalmology',
|
||||
'eye_exam',
|
||||
[
|
||||
'chief_complaint' => $elevated ? 'Blurry vision and headache' : 'Routine eye exam',
|
||||
'history' => $elevated
|
||||
? 'Gradual reduction in vision over 2 weeks; intermittent haloes.'
|
||||
: 'Annual review; no acute symptoms.',
|
||||
'va_od' => $elevated ? '6/60' : '6/9',
|
||||
'va_os' => $elevated ? '6/36' : '6/6',
|
||||
'iop_od' => $elevated ? 32 : 16,
|
||||
'iop_os' => $elevated ? 28 : 15,
|
||||
'pupils' => 'Equal, reactive',
|
||||
'extraocular' => 'Full',
|
||||
'anterior_segment' => $elevated ? 'Quiet; possible early cataract OD' : 'Quiet',
|
||||
'fundus' => $elevated ? 'Cup:disc elevated OD; review for glaucoma' : 'Healthy discs',
|
||||
'findings' => $elevated
|
||||
? 'Elevated IOP with reduced acuity — urgent glaucoma work-up.'
|
||||
: 'Normal examination; refraction updated.',
|
||||
],
|
||||
$ownerRef,
|
||||
$ownerRef,
|
||||
'exam',
|
||||
);
|
||||
|
||||
if ($elevated) {
|
||||
$clinical->upsert(
|
||||
$organization,
|
||||
$visit,
|
||||
'ophthalmology',
|
||||
'eye_plan',
|
||||
[
|
||||
'diagnosis' => 'Suspected primary open-angle glaucoma',
|
||||
'laterality' => 'OU',
|
||||
'plan' => 'Start topical IOP-lowering drops; arrange OCT and visual fields.',
|
||||
'medications' => 'Latanoprost 0.005% OU nocte',
|
||||
'procedure_planned' => false,
|
||||
'follow_up' => '2 weeks',
|
||||
'advice' => 'Return sooner if vision worsens or severe eye pain.',
|
||||
],
|
||||
$ownerRef,
|
||||
$ownerRef,
|
||||
'plan',
|
||||
);
|
||||
}
|
||||
|
||||
if (! $visit->specialty_stage) {
|
||||
$visit->update(['specialty_stage' => $elevated ? 'plan' : 'exam']);
|
||||
}
|
||||
|
||||
$index++;
|
||||
}
|
||||
}
|
||||
|
||||
private function seedDentistryClinicalDemo(Organization $organization, string $ownerRef): void
|
||||
{
|
||||
// Specialty departments are provisioned without organization_id; scope via branches.
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Care\Ophthalmology;
|
||||
|
||||
use App\Models\Appointment;
|
||||
use App\Models\Bill;
|
||||
use App\Models\BillLineItem;
|
||||
use App\Models\Organization;
|
||||
use App\Models\SpecialtyClinicalRecord;
|
||||
use App\Models\Visit;
|
||||
use App\Services\Care\SpecialtyShellService;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class OphthalmologyAnalyticsService
|
||||
{
|
||||
public function __construct(
|
||||
protected SpecialtyShellService $shell,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* arrivals_today: int,
|
||||
* completed_today: int,
|
||||
* elevated_iop_open: int,
|
||||
* diagnosis_breakdown: Collection,
|
||||
* procedure_breakdown: Collection,
|
||||
* avg_los_minutes: ?float,
|
||||
* revenue_by_service: Collection,
|
||||
* from: string,
|
||||
* to: string
|
||||
* }
|
||||
*/
|
||||
public function report(
|
||||
Organization $organization,
|
||||
string $ownerRef,
|
||||
?int $branchId = null,
|
||||
?string $from = null,
|
||||
?string $to = null,
|
||||
): array {
|
||||
$todayStart = now()->startOfDay();
|
||||
$rangeFrom = $from ? Carbon::parse($from)->startOfDay() : now()->startOfMonth();
|
||||
$rangeTo = $to ? Carbon::parse($to)->endOfDay() : now()->endOfDay();
|
||||
|
||||
$departmentIds = $this->shell->departmentIds($organization, 'ophthalmology', $ownerRef, $branchId);
|
||||
|
||||
$appointmentBase = Appointment::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->when($departmentIds !== [], fn ($q) => $q->whereIn('department_id', $departmentIds))
|
||||
->when($departmentIds === [], fn ($q) => $q->whereRaw('1 = 0'))
|
||||
->when($branchId, fn ($q) => $q->where('branch_id', $branchId));
|
||||
|
||||
$arrivalsToday = (clone $appointmentBase)
|
||||
->where('checked_in_at', '>=', $todayStart)
|
||||
->count();
|
||||
|
||||
$completedToday = (clone $appointmentBase)
|
||||
->where('status', Appointment::STATUS_COMPLETED)
|
||||
->where('completed_at', '>=', $todayStart)
|
||||
->count();
|
||||
|
||||
$visitIds = (clone $appointmentBase)->whereNotNull('visit_id')->pluck('visit_id');
|
||||
|
||||
$openVisitIds = Visit::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->whereIn('id', $visitIds->isEmpty() ? [0] : $visitIds)
|
||||
->whereIn('status', [Visit::STATUS_OPEN, Visit::STATUS_IN_PROGRESS])
|
||||
->pluck('id');
|
||||
|
||||
$elevatedIopOpen = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'ophthalmology')
|
||||
->where('record_type', 'eye_exam')
|
||||
->whereIn('visit_id', $openVisitIds->isEmpty() ? [0] : $openVisitIds)
|
||||
->get()
|
||||
->filter(function (SpecialtyClinicalRecord $r) {
|
||||
$iopOd = (float) ($r->payload['iop_od'] ?? 0);
|
||||
$iopOs = (float) ($r->payload['iop_os'] ?? 0);
|
||||
|
||||
return $iopOd >= 24 || $iopOs >= 24;
|
||||
})
|
||||
->count();
|
||||
|
||||
$planRecords = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'ophthalmology')
|
||||
->where('record_type', 'eye_plan')
|
||||
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
|
||||
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
|
||||
->get();
|
||||
|
||||
$diagnosisBreakdown = $planRecords
|
||||
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['diagnosis'] ?? 'Unknown'))
|
||||
->map(fn (Collection $rows, string $diagnosis) => [
|
||||
'diagnosis' => $diagnosis,
|
||||
'total' => $rows->count(),
|
||||
])
|
||||
->values()
|
||||
->sortByDesc('total')
|
||||
->values();
|
||||
|
||||
$procedureRecords = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'ophthalmology')
|
||||
->where('record_type', 'eye_procedure')
|
||||
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
|
||||
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
|
||||
->get();
|
||||
|
||||
$procedureBreakdown = $procedureRecords
|
||||
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['procedure'] ?? 'Unknown'))
|
||||
->map(fn (Collection $rows, string $procedure) => [
|
||||
'procedure' => $procedure,
|
||||
'total' => $rows->count(),
|
||||
])
|
||||
->values()
|
||||
->sortByDesc('total')
|
||||
->values();
|
||||
|
||||
$completedVisits = Visit::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->whereIn('id', $visitIds->isEmpty() ? [0] : $visitIds)
|
||||
->where('status', Visit::STATUS_COMPLETED)
|
||||
->whereBetween('completed_at', [$rangeFrom, $rangeTo])
|
||||
->whereNotNull('checked_in_at')
|
||||
->whereNotNull('completed_at')
|
||||
->get();
|
||||
|
||||
$avgLos = null;
|
||||
if ($completedVisits->isNotEmpty()) {
|
||||
$avgLos = round($completedVisits->avg(function (Visit $visit) {
|
||||
return $visit->checked_in_at->diffInMinutes($visit->completed_at);
|
||||
}), 1);
|
||||
}
|
||||
|
||||
$serviceLabels = collect($this->shell->provisionedServices($organization, 'ophthalmology'))
|
||||
->pluck('label')
|
||||
->filter()
|
||||
->values()
|
||||
->all();
|
||||
|
||||
$revenueByService = BillLineItem::query()
|
||||
->where('owner_ref', $ownerRef)
|
||||
->where('source_type', 'specialty_service')
|
||||
->whereIn('description', $serviceLabels ?: ['__none__'])
|
||||
->whereBetween('created_at', [$rangeFrom, $rangeTo])
|
||||
->whereHas('bill', function ($q) use ($organization, $visitIds) {
|
||||
$q->where('organization_id', $organization->id)
|
||||
->whereIn('visit_id', $visitIds->isEmpty() ? [0] : $visitIds)
|
||||
->whereNotIn('status', [Bill::STATUS_VOID]);
|
||||
})
|
||||
->selectRaw('description, count(*) as total, sum(total_minor) as amount_minor')
|
||||
->groupBy('description')
|
||||
->orderByDesc('amount_minor')
|
||||
->get();
|
||||
|
||||
return [
|
||||
'arrivals_today' => $arrivalsToday,
|
||||
'completed_today' => $completedToday,
|
||||
'elevated_iop_open' => $elevatedIopOpen,
|
||||
'diagnosis_breakdown' => $diagnosisBreakdown,
|
||||
'procedure_breakdown' => $procedureBreakdown,
|
||||
'avg_los_minutes' => $avgLos,
|
||||
'revenue_by_service' => $revenueByService,
|
||||
'from' => $rangeFrom->toDateString(),
|
||||
'to' => $rangeTo->toDateString(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Care\Ophthalmology;
|
||||
|
||||
/**
|
||||
* Map eye-care clinical progress onto ophthalmology visit stages.
|
||||
*/
|
||||
class OphthalmologyWorkflowService
|
||||
{
|
||||
public const STAGE_CHECK_IN = 'check_in';
|
||||
|
||||
public const STAGE_HISTORY = 'history';
|
||||
|
||||
public const STAGE_REFRACTION = 'refraction';
|
||||
|
||||
public const STAGE_EXAM = 'exam';
|
||||
|
||||
public const STAGE_INVESTIGATION = 'investigation';
|
||||
|
||||
public const STAGE_PLAN = 'plan';
|
||||
|
||||
public const STAGE_TREATMENT = 'treatment';
|
||||
|
||||
public const STAGE_COMPLETED = 'completed';
|
||||
|
||||
/**
|
||||
* Suggested stage after a refraction / VA payload is saved.
|
||||
*
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromRefraction(array $payload): string
|
||||
{
|
||||
$vaOd = trim((string) ($payload['va_od'] ?? ''));
|
||||
$vaOs = trim((string) ($payload['va_os'] ?? ''));
|
||||
|
||||
if ($vaOd !== '' || $vaOs !== '') {
|
||||
return self::STAGE_REFRACTION;
|
||||
}
|
||||
|
||||
return self::STAGE_HISTORY;
|
||||
}
|
||||
|
||||
/**
|
||||
* Suggested stage after an eye exam payload is saved.
|
||||
*
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromExam(array $payload): string
|
||||
{
|
||||
$findings = strtolower((string) ($payload['findings'] ?? ''));
|
||||
if (str_contains($findings, 'oct')
|
||||
|| str_contains($findings, 'field')
|
||||
|| str_contains($findings, 'imaging')
|
||||
|| str_contains($findings, 'investigate')) {
|
||||
return self::STAGE_INVESTIGATION;
|
||||
}
|
||||
|
||||
return self::STAGE_EXAM;
|
||||
}
|
||||
|
||||
/**
|
||||
* Suggested stage after a diagnosis/plan payload is saved.
|
||||
*
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromPlan(array $payload): string
|
||||
{
|
||||
if (! empty($payload['procedure_planned'])) {
|
||||
return self::STAGE_TREATMENT;
|
||||
}
|
||||
|
||||
return self::STAGE_PLAN;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a procedure payload should close the visit episode.
|
||||
*
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function shouldCompleteVisit(array $payload): bool
|
||||
{
|
||||
$outcome = strtolower((string) ($payload['outcome'] ?? ''));
|
||||
|
||||
return str_contains($outcome, 'completed');
|
||||
}
|
||||
|
||||
/**
|
||||
* Default stage progression for action buttons.
|
||||
*
|
||||
* @return array<string, array{next: string, label: string}>
|
||||
*/
|
||||
public function stageFlow(): array
|
||||
{
|
||||
return [
|
||||
self::STAGE_CHECK_IN => ['next' => self::STAGE_HISTORY, 'label' => 'Start history'],
|
||||
self::STAGE_HISTORY => ['next' => self::STAGE_REFRACTION, 'label' => 'Move to VA / refraction'],
|
||||
self::STAGE_REFRACTION => ['next' => self::STAGE_EXAM, 'label' => 'Move to examination'],
|
||||
self::STAGE_EXAM => ['next' => self::STAGE_INVESTIGATION, 'label' => 'Move to investigations'],
|
||||
self::STAGE_INVESTIGATION => ['next' => self::STAGE_PLAN, 'label' => 'Move to diagnosis & plan'],
|
||||
self::STAGE_PLAN => ['next' => self::STAGE_TREATMENT, 'label' => 'Move to treatment'],
|
||||
self::STAGE_TREATMENT => ['next' => self::STAGE_COMPLETED, 'label' => 'Complete visit'],
|
||||
self::STAGE_COMPLETED => ['next' => self::STAGE_COMPLETED, 'label' => 'Completed'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -249,6 +249,52 @@ class SpecialtyClinicalRecordService
|
||||
}
|
||||
}
|
||||
|
||||
if ($moduleKey === 'ophthalmology' && in_array($recordType, ['eye_exam', 'refraction'], true)) {
|
||||
$iopOd = isset($payload['iop_od']) ? (float) $payload['iop_od'] : null;
|
||||
$iopOs = isset($payload['iop_os']) ? (float) $payload['iop_os'] : null;
|
||||
if (($iopOd !== null && $iopOd >= 30) || ($iopOs !== null && $iopOs >= 30)) {
|
||||
$alerts[] = [
|
||||
'code' => 'eye.critical_iop',
|
||||
'severity' => 'critical',
|
||||
'message' => 'Critical IOP (≥30 mmHg) — urgent glaucoma / acute review.',
|
||||
];
|
||||
} elseif (($iopOd !== null && $iopOd >= 24) || ($iopOs !== null && $iopOs >= 24)) {
|
||||
$alerts[] = [
|
||||
'code' => 'eye.elevated_iop',
|
||||
'severity' => 'warning',
|
||||
'message' => 'Elevated IOP (≥24 mmHg).',
|
||||
];
|
||||
}
|
||||
|
||||
foreach (['va_od', 'va_os'] as $vaKey) {
|
||||
$va = strtolower(trim((string) ($payload[$vaKey] ?? '')));
|
||||
if ($va === '') {
|
||||
continue;
|
||||
}
|
||||
if (preg_match('/\b(cf|hm|pl|nlp|counting|hand\s*motion|perception)\b/i', $va)
|
||||
|| preg_match('/^6\/(60|90|120)\b/', $va)
|
||||
|| preg_match('/^20\/(200|400)\b/', $va)) {
|
||||
$alerts[] = [
|
||||
'code' => 'eye.low_vision',
|
||||
'severity' => 'warning',
|
||||
'message' => 'Low visual acuity recorded ('.$vaKey.').',
|
||||
];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($moduleKey === 'ophthalmology' && $recordType === 'eye_procedure') {
|
||||
$outcome = strtolower((string) ($payload['outcome'] ?? ''));
|
||||
if (str_contains($outcome, 'complication') || str_contains($outcome, 'aborted')) {
|
||||
$alerts[] = [
|
||||
'code' => 'eye.procedure_concern',
|
||||
'severity' => 'warning',
|
||||
'message' => 'Procedure outcome needs review (complication or aborted).',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $alerts;
|
||||
}
|
||||
|
||||
|
||||
@@ -270,7 +270,7 @@ class SpecialtyShellService
|
||||
) {
|
||||
$code = (string) ($stage['code'] ?? '');
|
||||
|
||||
if (in_array($moduleKey, ['dentistry', 'emergency', 'blood_bank'], true) && $visitIds->isNotEmpty()) {
|
||||
if (in_array($moduleKey, ['dentistry', 'emergency', 'blood_bank', 'ophthalmology'], true) && $visitIds->isNotEmpty()) {
|
||||
$count = Visit::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->whereIn('id', $visitIds)
|
||||
@@ -300,6 +300,7 @@ class SpecialtyShellService
|
||||
$clinicalOpen = match ($moduleKey) {
|
||||
'emergency' => $clinical->countOpenByType($organization, 'emergency', 'triage', $branchScope),
|
||||
'blood_bank' => $clinical->countOpenByType($organization, 'blood_bank', 'blood_request', $branchScope),
|
||||
'ophthalmology' => $clinical->countOpenByType($organization, 'ophthalmology', 'eye_exam', $branchScope),
|
||||
'dentistry' => \App\Models\DentalPlanItem::query()
|
||||
->whereHas('plan', function ($q) use ($organization, $ownerRef) {
|
||||
$q->owned($ownerRef)
|
||||
|
||||
@@ -96,6 +96,14 @@ class SpecialtyVisitStageService
|
||||
: ($stages[1] ?? ($stages[0] ?? null));
|
||||
}
|
||||
|
||||
if ($moduleKey === 'ophthalmology') {
|
||||
$stages = $this->allowedStages($moduleKey);
|
||||
|
||||
return in_array(\App\Services\Care\Ophthalmology\OphthalmologyWorkflowService::STAGE_HISTORY, $stages, true)
|
||||
? \App\Services\Care\Ophthalmology\OphthalmologyWorkflowService::STAGE_HISTORY
|
||||
: ($stages[1] ?? ($stages[0] ?? null));
|
||||
}
|
||||
|
||||
$stages = $this->allowedStages($moduleKey);
|
||||
foreach (['chair', 'in_care', 'exam', 'assessment', 'treatment'] as $preferred) {
|
||||
if (in_array($preferred, $stages, true)) {
|
||||
|
||||
Reference in New Issue
Block a user