Ship full Emergency specialty suite on the shared shell.
Deploy Ladill Care / deploy (push) Successful in 34s
Deploy Ladill Care / deploy (push) Successful in 34s
Add ED visit stages, triage-driven routing, vitals, observation, disposition, reports, and print summary so Emergency matches Dentistry’s operational depth without a parallel EHR. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,234 @@
|
||||
<?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\Emergency\EmergencyAnalyticsService;
|
||||
use App\Services\Care\Emergency\EmergencyVitalsService;
|
||||
use App\Services\Care\Emergency\EmergencyWorkflowService;
|
||||
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 EmergencyWorkspaceController extends Controller
|
||||
{
|
||||
use ScopesToAccount;
|
||||
|
||||
protected function assertEmergencyAccess(Request $request, SpecialtyModuleService $modules): void
|
||||
{
|
||||
$organization = $this->organization($request);
|
||||
abort_unless($modules->memberCanAccess($organization, $this->member($request), 'emergency'), 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->assertEmergencyAccess($request, $modules);
|
||||
$this->assertVisit($request, $visit);
|
||||
|
||||
$validated = $request->validate([
|
||||
'stage' => ['required', 'string', 'max:32'],
|
||||
]);
|
||||
|
||||
try {
|
||||
$stages->setStage(
|
||||
$this->organization($request),
|
||||
$visit,
|
||||
'emergency',
|
||||
$validated['stage'],
|
||||
$this->ownerRef($request),
|
||||
$this->actorRef($request),
|
||||
);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
return back()->with('error', $e->getMessage());
|
||||
}
|
||||
|
||||
return redirect()
|
||||
->route('care.specialty.workspace', ['module' => 'emergency', 'visit' => $visit, 'tab' => 'overview'])
|
||||
->with('success', 'Visit stage updated.');
|
||||
}
|
||||
|
||||
public function saveVitals(
|
||||
Request $request,
|
||||
Visit $visit,
|
||||
SpecialtyModuleService $modules,
|
||||
EmergencyVitalsService $vitals,
|
||||
): RedirectResponse {
|
||||
$this->authorizeAbility($request, 'consultations.manage');
|
||||
$this->assertEmergencyAccess($request, $modules);
|
||||
$this->assertVisit($request, $visit);
|
||||
|
||||
$validated = $request->validate([
|
||||
'bp_systolic' => ['nullable', 'integer', 'min:0', 'max:300'],
|
||||
'bp_diastolic' => ['nullable', 'integer', 'min:0', 'max:200'],
|
||||
'pulse' => ['nullable', 'integer', 'min:0', 'max:300'],
|
||||
'temperature' => ['nullable', 'numeric', 'min:30', 'max:45'],
|
||||
'spo2' => ['nullable', 'integer', 'min:0', 'max:100'],
|
||||
'respiratory_rate' => ['nullable', 'integer', 'min:0', 'max:80'],
|
||||
'weight_kg' => ['nullable', 'numeric', 'min:0', 'max:500'],
|
||||
'height_cm' => ['nullable', 'numeric', 'min:0', 'max:300'],
|
||||
]);
|
||||
|
||||
try {
|
||||
$vitals->record(
|
||||
$this->organization($request),
|
||||
$visit,
|
||||
$this->ownerRef($request),
|
||||
$validated,
|
||||
$this->actorRef($request),
|
||||
);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
return back()->with('error', $e->getMessage());
|
||||
}
|
||||
|
||||
return redirect()
|
||||
->route('care.specialty.workspace', ['module' => 'emergency', 'visit' => $visit, 'tab' => 'vitals'])
|
||||
->with('success', 'Vitals recorded.');
|
||||
}
|
||||
|
||||
public function saveDisposition(
|
||||
Request $request,
|
||||
Visit $visit,
|
||||
SpecialtyModuleService $modules,
|
||||
SpecialtyClinicalRecordService $clinical,
|
||||
SpecialtyVisitStageService $stages,
|
||||
EmergencyWorkflowService $workflow,
|
||||
): RedirectResponse {
|
||||
$this->authorizeAbility($request, 'consultations.manage');
|
||||
$this->assertEmergencyAccess($request, $modules);
|
||||
$this->assertVisit($request, $visit);
|
||||
|
||||
$organization = $this->organization($request);
|
||||
$owner = $this->ownerRef($request);
|
||||
|
||||
$payload = (array) $request->input('payload', []);
|
||||
foreach ($clinical->fieldsFor('emergency', 'disposition') as $field) {
|
||||
if (($field['type'] ?? '') === 'boolean') {
|
||||
$payload[$field['name']] = $request->boolean('payload.'.$field['name']);
|
||||
}
|
||||
}
|
||||
$request->merge(['payload' => $payload, 'tab' => 'disposition']);
|
||||
|
||||
$validated = $request->validate(array_merge([
|
||||
'tab' => ['required', 'string'],
|
||||
], $clinical->validationRules('emergency', 'disposition')));
|
||||
|
||||
$record = $clinical->upsert(
|
||||
$organization,
|
||||
$visit,
|
||||
'emergency',
|
||||
'disposition',
|
||||
$clinical->payloadFromRequest($validated),
|
||||
$owner,
|
||||
$owner,
|
||||
EmergencyWorkflowService::STAGE_DISPOSITION,
|
||||
SpecialtyClinicalRecord::STATUS_COMPLETED,
|
||||
);
|
||||
|
||||
try {
|
||||
$stages->setStage(
|
||||
$organization,
|
||||
$visit,
|
||||
'emergency',
|
||||
EmergencyWorkflowService::STAGE_DISPOSITION,
|
||||
$owner,
|
||||
$owner,
|
||||
);
|
||||
} catch (\InvalidArgumentException) {
|
||||
// Stage already disposition or map empty.
|
||||
}
|
||||
|
||||
if ($workflow->shouldCompleteVisit($record->payload ?? [])) {
|
||||
$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' => 'emergency', 'visit' => $visit, 'tab' => 'disposition'])
|
||||
->with('success', 'Disposition saved.');
|
||||
}
|
||||
|
||||
public function reports(
|
||||
Request $request,
|
||||
SpecialtyModuleService $modules,
|
||||
SpecialtyShellService $shell,
|
||||
EmergencyAnalyticsService $analytics,
|
||||
): View {
|
||||
$this->authorizeAbility($request, 'consultations.view');
|
||||
$this->assertEmergencyAccess($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.emergency.reports', [
|
||||
'moduleKey' => 'emergency',
|
||||
'definition' => $modules->definition('emergency'),
|
||||
'shellNav' => $shell->navItems('emergency'),
|
||||
'report' => $report,
|
||||
'currency' => strtoupper((string) config('care.billing.currency', config('care.currency', 'GHS'))),
|
||||
]);
|
||||
}
|
||||
|
||||
public function printSummary(
|
||||
Request $request,
|
||||
Visit $visit,
|
||||
SpecialtyModuleService $modules,
|
||||
SpecialtyClinicalRecordService $clinical,
|
||||
EmergencyVitalsService $vitals,
|
||||
): View {
|
||||
$this->authorizeAbility($request, 'consultations.view');
|
||||
$this->assertEmergencyAccess($request, $modules);
|
||||
$this->assertVisit($request, $visit);
|
||||
|
||||
$visit->loadMissing(['patient', 'appointment.practitioner', 'branch']);
|
||||
|
||||
return view('care.specialty.emergency.print', [
|
||||
'visit' => $visit,
|
||||
'patient' => $visit->patient,
|
||||
'triage' => $clinical->findForVisit($visit, 'emergency', 'triage'),
|
||||
'clinicalNote' => $clinical->findForVisit($visit, 'emergency', 'clinical_note'),
|
||||
'observation' => $clinical->findForVisit($visit, 'emergency', 'observation'),
|
||||
'disposition' => $clinical->findForVisit($visit, 'emergency', 'disposition'),
|
||||
'vitals' => $vitals->forVisit($visit),
|
||||
'latestVitals' => $vitals->latestForVisit($visit),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -156,11 +156,13 @@ class SpecialtyModuleController extends Controller
|
||||
if ($openConsultation && $openConsultation->status !== \App\Models\Consultation::STATUS_COMPLETED) {
|
||||
$clinical = app(SpecialtyClinicalRecordService::class);
|
||||
$shellTabs = app(SpecialtyShellService::class)->workspaceTabs($module);
|
||||
$preferredTab = $module === 'dentistry'
|
||||
? 'odontogram'
|
||||
: (collect(array_keys($shellTabs))
|
||||
$preferredTab = match ($module) {
|
||||
'dentistry' => 'odontogram',
|
||||
'emergency' => 'triage',
|
||||
default => (collect(array_keys($shellTabs))
|
||||
->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null)
|
||||
?? 'clinical_notes');
|
||||
?? 'clinical_notes'),
|
||||
};
|
||||
|
||||
return redirect()
|
||||
->route('care.specialty.workspace', [
|
||||
@@ -214,7 +216,7 @@ class SpecialtyModuleController extends Controller
|
||||
} catch (\InvalidArgumentException) {
|
||||
// Stage map may be empty for some modules.
|
||||
}
|
||||
} elseif ($nextStage && $visit->specialty_stage === 'waiting') {
|
||||
} elseif ($nextStage && in_array($visit->specialty_stage, ['waiting', 'arrival'], true)) {
|
||||
try {
|
||||
$stageService->setStage($organization, $visit, $module, $nextStage, $owner, $owner);
|
||||
$visit = $visit->fresh();
|
||||
@@ -224,11 +226,13 @@ class SpecialtyModuleController extends Controller
|
||||
}
|
||||
$clinical = app(SpecialtyClinicalRecordService::class);
|
||||
$shellTabs = app(SpecialtyShellService::class)->workspaceTabs($module);
|
||||
$preferredTab = $module === 'dentistry'
|
||||
? 'odontogram'
|
||||
: (collect(array_keys($shellTabs))
|
||||
$preferredTab = match ($module) {
|
||||
'dentistry' => 'odontogram',
|
||||
'emergency' => 'triage',
|
||||
default => (collect(array_keys($shellTabs))
|
||||
->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null)
|
||||
?? 'clinical_notes');
|
||||
?? 'clinical_notes'),
|
||||
};
|
||||
|
||||
return redirect()
|
||||
->route('care.specialty.workspace', [
|
||||
@@ -285,6 +289,41 @@ class SpecialtyModuleController extends Controller
|
||||
$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,
|
||||
@@ -555,6 +594,14 @@ class SpecialtyModuleController extends Controller
|
||||
$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);
|
||||
|
||||
@@ -659,6 +706,18 @@ class SpecialtyModuleController extends Controller
|
||||
);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -729,6 +788,14 @@ class SpecialtyModuleController extends Controller
|
||||
'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,
|
||||
|
||||
@@ -292,11 +292,12 @@ class CareQueueProvisioner
|
||||
string $context,
|
||||
$priorByKey,
|
||||
): array {
|
||||
if ($context !== 'dentistry') {
|
||||
$stages = app(SpecialtyShellService::class)->stages($context);
|
||||
$hasQueuePoints = collect($stages)->contains(fn ($s) => is_string($s['queue_point'] ?? null) && $s['queue_point'] !== '');
|
||||
if (! $hasQueuePoints) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$stages = app(SpecialtyShellService::class)->stages($context);
|
||||
$seen = [];
|
||||
$points = [];
|
||||
foreach ($stages as $stage) {
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Care\Emergency;
|
||||
|
||||
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 EmergencyAnalyticsService
|
||||
{
|
||||
public function __construct(
|
||||
protected SpecialtyShellService $shell,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* arrivals_today: int,
|
||||
* completed_today: int,
|
||||
* high_acuity_open: int,
|
||||
* acuity_distribution: Collection,
|
||||
* disposition_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, 'emergency', $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');
|
||||
|
||||
$triageRecords = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'emergency')
|
||||
->where('record_type', 'triage')
|
||||
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
|
||||
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
|
||||
->get();
|
||||
|
||||
$acuityDistribution = $triageRecords
|
||||
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['acuity'] ?? 'Unknown'))
|
||||
->map(fn (Collection $rows, string $acuity) => [
|
||||
'acuity' => $acuity,
|
||||
'total' => $rows->count(),
|
||||
])
|
||||
->values()
|
||||
->sortBy('acuity')
|
||||
->values();
|
||||
|
||||
$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');
|
||||
|
||||
$highAcuityOpen = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'emergency')
|
||||
->where('record_type', 'triage')
|
||||
->whereIn('visit_id', $openVisitIds->isEmpty() ? [0] : $openVisitIds)
|
||||
->get()
|
||||
->filter(function (SpecialtyClinicalRecord $r) {
|
||||
$acuity = (string) ($r->payload['acuity'] ?? '');
|
||||
|
||||
return str_starts_with($acuity, '1') || str_starts_with($acuity, '2');
|
||||
})
|
||||
->count();
|
||||
|
||||
$dispositionRecords = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'emergency')
|
||||
->where('record_type', 'disposition')
|
||||
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
|
||||
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
|
||||
->get();
|
||||
|
||||
$dispositionBreakdown = $dispositionRecords
|
||||
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['disposition'] ?? 'Unknown'))
|
||||
->map(fn (Collection $rows, string $disposition) => [
|
||||
'disposition' => $disposition,
|
||||
'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, 'emergency'))
|
||||
->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,
|
||||
'high_acuity_open' => $highAcuityOpen,
|
||||
'acuity_distribution' => $acuityDistribution,
|
||||
'disposition_breakdown' => $dispositionBreakdown,
|
||||
'avg_los_minutes' => $avgLos,
|
||||
'revenue_by_service' => $revenueByService,
|
||||
'from' => $rangeFrom->toDateString(),
|
||||
'to' => $rangeTo->toDateString(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Care\Emergency;
|
||||
|
||||
use App\Models\Appointment;
|
||||
use App\Models\Consultation;
|
||||
use App\Models\Organization;
|
||||
use App\Models\Visit;
|
||||
use App\Models\VitalSign;
|
||||
use App\Services\Care\ConsultationService;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class EmergencyVitalsService
|
||||
{
|
||||
public function __construct(
|
||||
protected ConsultationService $consultations,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return Collection<int, VitalSign>
|
||||
*/
|
||||
public function forVisit(Visit $visit): Collection
|
||||
{
|
||||
$consultationIds = Consultation::owned($visit->owner_ref)
|
||||
->where('visit_id', $visit->id)
|
||||
->pluck('id');
|
||||
|
||||
if ($consultationIds->isEmpty()) {
|
||||
return collect();
|
||||
}
|
||||
|
||||
return VitalSign::owned($visit->owner_ref)
|
||||
->whereIn('consultation_id', $consultationIds)
|
||||
->orderByDesc('recorded_at')
|
||||
->orderByDesc('id')
|
||||
->get();
|
||||
}
|
||||
|
||||
public function latestForVisit(Visit $visit): ?VitalSign
|
||||
{
|
||||
return $this->forVisit($visit)->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $vitals
|
||||
*/
|
||||
public function record(
|
||||
Organization $organization,
|
||||
Visit $visit,
|
||||
string $ownerRef,
|
||||
array $vitals,
|
||||
?string $actorRef = null,
|
||||
): VitalSign {
|
||||
$consultation = $this->ensureConsultation($visit, $ownerRef, $actorRef);
|
||||
|
||||
$saved = $this->consultations->saveVitals(
|
||||
$consultation,
|
||||
$ownerRef,
|
||||
$vitals,
|
||||
$actorRef,
|
||||
);
|
||||
|
||||
if (! $saved) {
|
||||
throw new \InvalidArgumentException('Enter at least one vital sign value.');
|
||||
}
|
||||
|
||||
return $saved;
|
||||
}
|
||||
|
||||
protected function ensureConsultation(Visit $visit, string $ownerRef, ?string $actorRef): Consultation
|
||||
{
|
||||
$existing = Consultation::owned($ownerRef)
|
||||
->where('visit_id', $visit->id)
|
||||
->where('status', '!=', Consultation::STATUS_COMPLETED)
|
||||
->orderByDesc('id')
|
||||
->first();
|
||||
|
||||
if ($existing) {
|
||||
return $existing;
|
||||
}
|
||||
|
||||
$completed = Consultation::owned($ownerRef)
|
||||
->where('visit_id', $visit->id)
|
||||
->orderByDesc('id')
|
||||
->first();
|
||||
|
||||
if ($completed) {
|
||||
return $completed;
|
||||
}
|
||||
|
||||
$visit->loadMissing('appointment', 'patient');
|
||||
$appointment = $visit->appointment;
|
||||
if (! $appointment instanceof Appointment) {
|
||||
$appointment = Appointment::query()->where('visit_id', $visit->id)->first();
|
||||
}
|
||||
|
||||
if ($appointment) {
|
||||
try {
|
||||
return $this->consultations->startFromAppointment($appointment, $ownerRef, $actorRef);
|
||||
} catch (\InvalidArgumentException) {
|
||||
// Fall through to draft consultation.
|
||||
}
|
||||
}
|
||||
|
||||
return Consultation::create([
|
||||
'owner_ref' => $ownerRef,
|
||||
'visit_id' => $visit->id,
|
||||
'appointment_id' => $appointment?->id,
|
||||
'practitioner_id' => $appointment?->practitioner_id,
|
||||
'patient_id' => $visit->patient_id,
|
||||
'status' => Consultation::STATUS_DRAFT,
|
||||
'started_at' => now(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Care\Emergency;
|
||||
|
||||
/**
|
||||
* Map triage acuity / intent onto Emergency visit stages.
|
||||
*/
|
||||
class EmergencyWorkflowService
|
||||
{
|
||||
public const STAGE_ARRIVAL = 'arrival';
|
||||
|
||||
public const STAGE_RESUS = 'resus';
|
||||
|
||||
public const STAGE_TREATMENT = 'treatment';
|
||||
|
||||
public const STAGE_OBSERVATION = 'observation';
|
||||
|
||||
public const STAGE_DISPOSITION = 'disposition';
|
||||
|
||||
/**
|
||||
* Suggested next visit stage after a triage payload is saved.
|
||||
*
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromTriage(array $payload): string
|
||||
{
|
||||
$acuity = (string) ($payload['acuity'] ?? '');
|
||||
$intent = strtolower((string) ($payload['disposition_intent'] ?? ''));
|
||||
|
||||
if (str_starts_with($acuity, '1') || str_starts_with($acuity, '2') || str_contains($intent, 'resus')) {
|
||||
return self::STAGE_RESUS;
|
||||
}
|
||||
|
||||
if (str_contains($intent, 'observation')) {
|
||||
return self::STAGE_OBSERVATION;
|
||||
}
|
||||
|
||||
if (str_contains($intent, 'discharge') || str_contains($intent, 'admit') || str_contains($intent, 'transfer')) {
|
||||
return self::STAGE_TREATMENT;
|
||||
}
|
||||
|
||||
if (str_contains($intent, 'treatment')) {
|
||||
return self::STAGE_TREATMENT;
|
||||
}
|
||||
|
||||
return self::STAGE_TREATMENT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a disposition payload should close the visit episode.
|
||||
*
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function shouldCompleteVisit(array $payload): bool
|
||||
{
|
||||
$disposition = strtolower((string) ($payload['disposition'] ?? ''));
|
||||
|
||||
return $disposition !== '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Default stage progression for action buttons.
|
||||
*
|
||||
* @return array<string, array{next: string, label: string}>
|
||||
*/
|
||||
public function stageFlow(): array
|
||||
{
|
||||
return [
|
||||
self::STAGE_ARRIVAL => ['next' => self::STAGE_TREATMENT, 'label' => 'Move to treatment'],
|
||||
self::STAGE_RESUS => ['next' => self::STAGE_TREATMENT, 'label' => 'Move to treatment bay'],
|
||||
self::STAGE_TREATMENT => ['next' => self::STAGE_OBSERVATION, 'label' => 'Move to observation'],
|
||||
self::STAGE_OBSERVATION => ['next' => self::STAGE_DISPOSITION, 'label' => 'Ready for disposition'],
|
||||
self::STAGE_DISPOSITION => ['next' => self::STAGE_DISPOSITION, 'label' => 'Complete disposition'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -270,13 +270,13 @@ class SpecialtyShellService
|
||||
) {
|
||||
$code = (string) ($stage['code'] ?? '');
|
||||
|
||||
if ($moduleKey === 'dentistry' && $visitIds->isNotEmpty()) {
|
||||
if (in_array($moduleKey, ['dentistry', 'emergency'], true) && $visitIds->isNotEmpty()) {
|
||||
$count = Visit::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->whereIn('id', $visitIds)
|
||||
->where('specialty_stage', $code)
|
||||
->when(
|
||||
$code !== 'completed',
|
||||
! in_array($code, ['completed', 'disposition'], true),
|
||||
fn ($q) => $q->whereIn('status', [Visit::STATUS_OPEN, Visit::STATUS_IN_PROGRESS]),
|
||||
)
|
||||
->count();
|
||||
|
||||
@@ -7,6 +7,7 @@ use App\Models\CareQueueTicket;
|
||||
use App\Models\Organization;
|
||||
use App\Models\Visit;
|
||||
use App\Services\Care\AuditLogger;
|
||||
use App\Services\Care\Emergency\EmergencyWorkflowService;
|
||||
|
||||
/**
|
||||
* Persist specialty visit stages (dentistry chair → recovery) and re-route queue tickets.
|
||||
@@ -79,8 +80,16 @@ class SpecialtyVisitStageService
|
||||
|
||||
public function stageOnConsultationStart(string $moduleKey): ?string
|
||||
{
|
||||
if ($moduleKey === 'emergency') {
|
||||
$stages = $this->allowedStages($moduleKey);
|
||||
|
||||
return in_array(EmergencyWorkflowService::STAGE_TREATMENT, $stages, true)
|
||||
? EmergencyWorkflowService::STAGE_TREATMENT
|
||||
: ($stages[1] ?? ($stages[0] ?? null));
|
||||
}
|
||||
|
||||
$stages = $this->allowedStages($moduleKey);
|
||||
foreach (['chair', 'in_care', 'exam', 'assessment'] as $preferred) {
|
||||
foreach (['chair', 'in_care', 'exam', 'assessment', 'treatment'] as $preferred) {
|
||||
if (in_array($preferred, $stages, true)) {
|
||||
return $preferred;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user