Ship full Emergency specialty suite on the shared shell.
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:
isaacclad
2026-07-18 17:48:57 +00:00
co-authored by Cursor
parent 18c24077e3
commit 7989ab9184
19 changed files with 1413 additions and 22 deletions
@@ -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) { if ($openConsultation && $openConsultation->status !== \App\Models\Consultation::STATUS_COMPLETED) {
$clinical = app(SpecialtyClinicalRecordService::class); $clinical = app(SpecialtyClinicalRecordService::class);
$shellTabs = app(SpecialtyShellService::class)->workspaceTabs($module); $shellTabs = app(SpecialtyShellService::class)->workspaceTabs($module);
$preferredTab = $module === 'dentistry' $preferredTab = match ($module) {
? 'odontogram' 'dentistry' => 'odontogram',
: (collect(array_keys($shellTabs)) 'emergency' => 'triage',
default => (collect(array_keys($shellTabs))
->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null) ->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null)
?? 'clinical_notes'); ?? 'clinical_notes'),
};
return redirect() return redirect()
->route('care.specialty.workspace', [ ->route('care.specialty.workspace', [
@@ -214,7 +216,7 @@ class SpecialtyModuleController extends Controller
} catch (\InvalidArgumentException) { } catch (\InvalidArgumentException) {
// Stage map may be empty for some modules. // 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 { try {
$stageService->setStage($organization, $visit, $module, $nextStage, $owner, $owner); $stageService->setStage($organization, $visit, $module, $nextStage, $owner, $owner);
$visit = $visit->fresh(); $visit = $visit->fresh();
@@ -224,11 +226,13 @@ class SpecialtyModuleController extends Controller
} }
$clinical = app(SpecialtyClinicalRecordService::class); $clinical = app(SpecialtyClinicalRecordService::class);
$shellTabs = app(SpecialtyShellService::class)->workspaceTabs($module); $shellTabs = app(SpecialtyShellService::class)->workspaceTabs($module);
$preferredTab = $module === 'dentistry' $preferredTab = match ($module) {
? 'odontogram' 'dentistry' => 'odontogram',
: (collect(array_keys($shellTabs)) 'emergency' => 'triage',
default => (collect(array_keys($shellTabs))
->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null) ->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null)
?? 'clinical_notes'); ?? 'clinical_notes'),
};
return redirect() return redirect()
->route('care.specialty.workspace', [ ->route('care.specialty.workspace', [
@@ -285,6 +289,41 @@ class SpecialtyModuleController extends Controller
$validated['status'] ?? \App\Models\SpecialtyClinicalRecord::STATUS_ACTIVE, $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() return redirect()
->route('care.specialty.workspace', [ ->route('care.specialty.workspace', [
'module' => $module, 'module' => $module,
@@ -555,6 +594,14 @@ class SpecialtyModuleController extends Controller
$dentalLabCaseStatuses = []; $dentalLabCaseStatuses = [];
$dentalRecalls = collect(); $dentalRecalls = collect();
$dentalStageCodes = []; $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'); $activeTab = (string) $request->query('tab', array_key_first($shell->workspaceTabs($module)) ?: 'overview');
$clinical = app(SpecialtyClinicalRecordService::class); $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) { if ($patientHeader !== null) {
$patientHeader['clinical_alerts'] = $clinicalAlerts; $patientHeader['clinical_alerts'] = $clinicalAlerts;
} }
@@ -729,6 +788,14 @@ class SpecialtyModuleController extends Controller
'dentalLabCaseStatuses' => $dentalLabCaseStatuses, 'dentalLabCaseStatuses' => $dentalLabCaseStatuses,
'dentalRecalls' => $dentalRecalls, 'dentalRecalls' => $dentalRecalls,
'dentalStageCodes' => $dentalStageCodes, 'dentalStageCodes' => $dentalStageCodes,
'emergencyTriage' => $emergencyTriage,
'emergencyClinicalNote' => $emergencyClinicalNote,
'emergencyObservation' => $emergencyObservation,
'emergencyDisposition' => $emergencyDisposition,
'emergencyVitals' => $emergencyVitals,
'emergencyLatestVitals' => $emergencyLatestVitals,
'emergencyStageCodes' => $emergencyStageCodes,
'emergencyStageFlow' => $emergencyStageFlow,
'queueStubs' => $modules->queueStubsFor($organization, $module), 'queueStubs' => $modules->queueStubsFor($organization, $module),
'branchId' => $branchId, 'branchId' => $branchId,
'branchLabel' => $branchLabel, 'branchLabel' => $branchLabel,
+3 -2
View File
@@ -292,11 +292,12 @@ class CareQueueProvisioner
string $context, string $context,
$priorByKey, $priorByKey,
): array { ): 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 []; return [];
} }
$stages = app(SpecialtyShellService::class)->stages($context);
$seen = []; $seen = [];
$points = []; $points = [];
foreach ($stages as $stage) { 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'],
];
}
}
+2 -2
View File
@@ -270,13 +270,13 @@ class SpecialtyShellService
) { ) {
$code = (string) ($stage['code'] ?? ''); $code = (string) ($stage['code'] ?? '');
if ($moduleKey === 'dentistry' && $visitIds->isNotEmpty()) { if (in_array($moduleKey, ['dentistry', 'emergency'], true) && $visitIds->isNotEmpty()) {
$count = Visit::owned($ownerRef) $count = Visit::owned($ownerRef)
->where('organization_id', $organization->id) ->where('organization_id', $organization->id)
->whereIn('id', $visitIds) ->whereIn('id', $visitIds)
->where('specialty_stage', $code) ->where('specialty_stage', $code)
->when( ->when(
$code !== 'completed', ! in_array($code, ['completed', 'disposition'], true),
fn ($q) => $q->whereIn('status', [Visit::STATUS_OPEN, Visit::STATUS_IN_PROGRESS]), fn ($q) => $q->whereIn('status', [Visit::STATUS_OPEN, Visit::STATUS_IN_PROGRESS]),
) )
->count(); ->count();
@@ -7,6 +7,7 @@ use App\Models\CareQueueTicket;
use App\Models\Organization; use App\Models\Organization;
use App\Models\Visit; use App\Models\Visit;
use App\Services\Care\AuditLogger; use App\Services\Care\AuditLogger;
use App\Services\Care\Emergency\EmergencyWorkflowService;
/** /**
* Persist specialty visit stages (dentistry chair recovery) and re-route queue tickets. * Persist specialty visit stages (dentistry chair recovery) and re-route queue tickets.
@@ -79,8 +80,16 @@ class SpecialtyVisitStageService
public function stageOnConsultationStart(string $moduleKey): ?string 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); $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)) { if (in_array($preferred, $stages, true)) {
return $preferred; return $preferred;
} }
+20
View File
@@ -14,6 +14,8 @@ return [
'emergency' => [ 'emergency' => [
'triage' => 'triage', 'triage' => 'triage',
'clinical_notes' => 'clinical_note', 'clinical_notes' => 'clinical_note',
'observation' => 'observation',
'disposition' => 'disposition',
], ],
'blood_bank' => [ 'blood_bank' => [
'requests' => 'blood_request', 'requests' => 'blood_request',
@@ -121,6 +123,24 @@ return [
['name' => 'plan', 'label' => 'Plan', 'type' => 'textarea', 'rows' => 3], ['name' => 'plan', 'label' => 'Plan', 'type' => 'textarea', 'rows' => 3],
['name' => 'procedures', 'label' => 'Procedures performed', 'type' => 'textarea', 'rows' => 2], ['name' => 'procedures', 'label' => 'Procedures performed', 'type' => 'textarea', 'rows' => 2],
], ],
'observation' => [
['name' => 'bed_label', 'label' => 'Bed / bay label', 'type' => 'text'],
['name' => 'started_at', 'label' => 'Observation started', 'type' => 'text'],
['name' => 'hours', 'label' => 'Hours observed', 'type' => 'number'],
['name' => 'monitoring_plan', 'label' => 'Monitoring plan', 'type' => 'textarea', 'rows' => 2],
['name' => 'progress', 'label' => 'Progress notes', 'type' => 'textarea', 'required' => true, 'rows' => 3],
['name' => 'ready_for_disposition', 'label' => 'Ready for disposition', 'type' => 'boolean'],
],
'disposition' => [
['name' => 'disposition', 'label' => 'Final disposition', 'type' => 'select', 'required' => true, 'options' => ['Discharge home', 'Admit to ward', 'Admit to ICU', 'Transfer to facility', 'Left against advice', 'Died', 'Absconded']],
['name' => 'condition', 'label' => 'Condition at disposition', 'type' => 'select', 'options' => ['Stable', 'Improving', 'Unstable', 'Critical', 'Deceased']],
['name' => 'destination', 'label' => 'Destination (ward / facility)', 'type' => 'text'],
['name' => 'diagnosis', 'label' => 'Discharge / transfer diagnosis', 'type' => 'text', 'required' => true],
['name' => 'advice', 'label' => 'Advice / follow-up', 'type' => 'textarea', 'rows' => 3],
['name' => 'medications', 'label' => 'Medications on discharge', 'type' => 'textarea', 'rows' => 2],
['name' => 'time', 'label' => 'Disposition time', 'type' => 'text'],
['name' => 'notes', 'label' => 'Notes', 'type' => 'textarea', 'rows' => 2],
],
], ],
'blood_bank' => [ 'blood_bank' => [
'blood_request' => [ 'blood_request' => [
+5
View File
@@ -58,12 +58,17 @@ return [
['code' => 'er.triage', 'label' => 'Emergency triage', 'amount_minor' => 0, 'type' => 'consultation'], ['code' => 'er.triage', 'label' => 'Emergency triage', 'amount_minor' => 0, 'type' => 'consultation'],
['code' => 'er.consultation', 'label' => 'Emergency consultation', 'amount_minor' => 8000, 'type' => 'consultation'], ['code' => 'er.consultation', 'label' => 'Emergency consultation', 'amount_minor' => 8000, 'type' => 'consultation'],
['code' => 'er.procedure', 'label' => 'Emergency procedure', 'amount_minor' => 15000, 'type' => 'procedure'], ['code' => 'er.procedure', 'label' => 'Emergency procedure', 'amount_minor' => 15000, 'type' => 'procedure'],
['code' => 'er.resuscitation', 'label' => 'Resuscitation', 'amount_minor' => 25000, 'type' => 'procedure'],
['code' => 'er.observation', 'label' => 'Observation bed (per hour)', 'amount_minor' => 3000, 'type' => 'misc'], ['code' => 'er.observation', 'label' => 'Observation bed (per hour)', 'amount_minor' => 3000, 'type' => 'misc'],
['code' => 'er.transfer', 'label' => 'Transfer coordination', 'amount_minor' => 5000, 'type' => 'misc'],
], ],
'workspace_tabs' => [ 'workspace_tabs' => [
'overview' => 'Overview', 'overview' => 'Overview',
'triage' => 'Triage', 'triage' => 'Triage',
'vitals' => 'Vitals',
'clinical_notes' => 'Clinical notes', 'clinical_notes' => 'Clinical notes',
'observation' => 'Observation',
'disposition' => 'Disposition',
'orders' => 'Orders', 'orders' => 'Orders',
'billing' => 'Billing', 'billing' => 'Billing',
'documents' => 'Documents', 'documents' => 'Documents',
@@ -0,0 +1,88 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ED summary · {{ $patient->fullName() }}</title>
<style>
body { font-family: system-ui, sans-serif; color: #0f172a; margin: 2rem; }
h1 { font-size: 1.25rem; margin: 0 0 .25rem; }
h2 { font-size: .95rem; margin: 1.25rem 0 .5rem; border-bottom: 1px solid #e2e8f0; padding-bottom: .25rem; }
.meta { color: #64748b; font-size: .875rem; }
dl { display: grid; grid-template-columns: 10rem 1fr; gap: .35rem .75rem; font-size: .875rem; }
dt { color: #64748b; }
dd { margin: 0; font-weight: 500; }
@media print { .no-print { display: none; } }
</style>
</head>
<body>
<p class="no-print"><a href="{{ route('care.specialty.workspace', ['module' => 'emergency', 'visit' => $visit]) }}">Back</a></p>
<h1>{{ $patient->fullName() }}</h1>
<p class="meta">
{{ $patient->patient_number }}
· Visit #{{ $visit->id }}
· Stage {{ $visit->specialty_stage ?? '—' }}
· {{ $visit->checked_in_at?->format('d M Y H:i') ?? '—' }}
</p>
<h2>Triage</h2>
@if ($triage)
<dl>
<dt>Acuity</dt><dd>{{ $triage->payload['acuity'] ?? '—' }}</dd>
<dt>Chief complaint</dt><dd>{{ $triage->payload['chief_complaint'] ?? '—' }}</dd>
<dt>Mode of arrival</dt><dd>{{ $triage->payload['mode_of_arrival'] ?? '—' }}</dd>
<dt>ABC</dt>
<dd>
A {{ ($triage->payload['airway_ok'] ?? true) ? 'OK' : 'Compromised' }}
· B {{ ($triage->payload['breathing_ok'] ?? true) ? 'OK' : 'Compromised' }}
· C {{ ($triage->payload['circulation_ok'] ?? true) ? 'OK' : 'Compromised' }}
</dd>
<dt>GCS / Pain</dt><dd>{{ $triage->payload['gcs'] ?? '—' }} / {{ $triage->payload['pain_score'] ?? '—' }}</dd>
<dt>Notes</dt><dd>{{ $triage->payload['notes'] ?? '—' }}</dd>
</dl>
@else
<p class="meta">No triage recorded.</p>
@endif
<h2>Latest vitals</h2>
@if ($latestVitals)
<dl>
<dt>BP</dt><dd>{{ $latestVitals->bp_systolic ?? '—' }}/{{ $latestVitals->bp_diastolic ?? '—' }}</dd>
<dt>Pulse</dt><dd>{{ $latestVitals->pulse ?? '—' }}</dd>
<dt>SpO₂</dt><dd>{{ $latestVitals->spo2 ?? '—' }}%</dd>
<dt>Temp</dt><dd>{{ $latestVitals->temperature ?? '—' }}</dd>
<dt>RR</dt><dd>{{ $latestVitals->respiratory_rate ?? '—' }}</dd>
<dt>Recorded</dt><dd>{{ $latestVitals->recorded_at?->format('d M Y H:i') }}</dd>
</dl>
@else
<p class="meta">No vitals recorded.</p>
@endif
<h2>Clinical note</h2>
@if ($clinicalNote)
<dl>
<dt>History</dt><dd>{{ $clinicalNote->payload['history'] ?? '—' }}</dd>
<dt>Examination</dt><dd>{{ $clinicalNote->payload['examination'] ?? '—' }}</dd>
<dt>Diagnosis</dt><dd>{{ $clinicalNote->payload['working_diagnosis'] ?? '—' }}</dd>
<dt>Plan</dt><dd>{{ $clinicalNote->payload['plan'] ?? '—' }}</dd>
</dl>
@else
<p class="meta">No clinical note.</p>
@endif
<h2>Disposition</h2>
@if ($disposition)
<dl>
<dt>Disposition</dt><dd>{{ $disposition->payload['disposition'] ?? '—' }}</dd>
<dt>Condition</dt><dd>{{ $disposition->payload['condition'] ?? '—' }}</dd>
<dt>Destination</dt><dd>{{ $disposition->payload['destination'] ?? '—' }}</dd>
<dt>Diagnosis</dt><dd>{{ $disposition->payload['diagnosis'] ?? '—' }}</dd>
<dt>Advice</dt><dd>{{ $disposition->payload['advice'] ?? '—' }}</dd>
</dl>
@else
<p class="meta">No disposition recorded.</p>
@endif
<script>window.print();</script>
</body>
</html>
@@ -0,0 +1,88 @@
<x-app-layout title="Emergency reports">
<div class="space-y-6">
<div class="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 class="text-xl font-semibold text-slate-900">Emergency reports</h1>
<p class="mt-1 text-sm text-slate-500">Arrivals, acuity mix, dispositions, length of stay, and ED service revenue.</p>
</div>
<a href="{{ route('care.queue.index') }}" class="text-sm font-medium text-indigo-600"> Back to queue</a>
</div>
<form method="GET" class="flex flex-wrap items-end gap-3 rounded-2xl border border-slate-200 bg-white p-4">
<div>
<label class="block text-xs font-medium text-slate-600">From</label>
<input type="date" name="from" value="{{ $report['from'] ?? '' }}" class="mt-1 rounded-xl border border-slate-200 px-3 py-2 text-sm">
</div>
<div>
<label class="block text-xs font-medium text-slate-600">To</label>
<input type="date" name="to" value="{{ $report['to'] ?? '' }}" class="mt-1 rounded-xl border border-slate-200 px-3 py-2 text-sm">
</div>
<button type="submit" class="rounded-xl bg-indigo-600 px-4 py-2 text-sm font-semibold text-white">Apply</button>
</form>
<div class="grid gap-4 sm:grid-cols-4">
<div class="rounded-2xl border border-slate-200 bg-white p-4">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Arrivals today</p>
<p class="mt-2 text-2xl font-semibold tabular-nums text-slate-900">{{ number_format($report['arrivals_today']) }}</p>
</div>
<div class="rounded-2xl border border-slate-200 bg-white p-4">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Completed today</p>
<p class="mt-2 text-2xl font-semibold tabular-nums text-slate-900">{{ number_format($report['completed_today']) }}</p>
</div>
<div class="rounded-2xl border border-slate-200 bg-white p-4">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">High-acuity open</p>
<p class="mt-2 text-2xl font-semibold tabular-nums text-rose-700">{{ number_format($report['high_acuity_open']) }}</p>
</div>
<div class="rounded-2xl border border-slate-200 bg-white p-4">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Avg LOS (range)</p>
<p class="mt-2 text-2xl font-semibold tabular-nums text-slate-900">
{{ $report['avg_los_minutes'] !== null ? $report['avg_los_minutes'].' min' : '—' }}
</p>
</div>
</div>
<div class="grid gap-4 lg:grid-cols-2">
<section class="rounded-2xl border border-slate-200 bg-white p-5">
<h2 class="text-sm font-semibold text-slate-900">Acuity distribution</h2>
<ul class="mt-3 space-y-2 text-sm">
@forelse ($report['acuity_distribution'] as $row)
<li class="flex justify-between gap-3">
<span>{{ $row['acuity'] }}</span>
<span class="tabular-nums text-slate-600">{{ $row['total'] }}</span>
</li>
@empty
<li class="text-slate-500">No triage records in range.</li>
@endforelse
</ul>
</section>
<section class="rounded-2xl border border-slate-200 bg-white p-5">
<h2 class="text-sm font-semibold text-slate-900">Dispositions</h2>
<ul class="mt-3 space-y-2 text-sm">
@forelse ($report['disposition_breakdown'] as $row)
<li class="flex justify-between gap-3">
<span>{{ $row['disposition'] }}</span>
<span class="tabular-nums text-slate-600">{{ $row['total'] }}</span>
</li>
@empty
<li class="text-slate-500">No dispositions in range.</li>
@endforelse
</ul>
</section>
</div>
<section class="rounded-2xl border border-slate-200 bg-white p-5">
<h2 class="text-sm font-semibold text-slate-900">ED service revenue</h2>
<ul class="mt-3 space-y-2 text-sm">
@forelse ($report['revenue_by_service'] as $row)
<li class="flex justify-between gap-3">
<span>{{ $row->description }} <span class="text-slate-400">×{{ $row->total }}</span></span>
<span class="tabular-nums">{{ $currency }} {{ number_format($row->amount_minor / 100, 2) }}</span>
</li>
@empty
<li class="text-slate-500">No ED bill lines in range.</li>
@endforelse
</ul>
</section>
</div>
</x-app-layout>
@@ -0,0 +1,68 @@
@php
$record = $emergencyDisposition;
$payload = old('payload', $record?->payload ?? []);
@endphp
<section class="rounded-2xl border border-slate-200 bg-white p-5">
<div class="flex flex-wrap items-start justify-between gap-3">
<div>
<h3 class="text-sm font-semibold text-slate-900">Disposition</h3>
<p class="mt-0.5 text-xs text-slate-500">Final disposition closes the emergency visit episode.</p>
</div>
<a href="{{ route('care.specialty.emergency.print', $workspaceVisit) }}" target="_blank" class="text-sm font-medium text-indigo-600">Print summary</a>
</div>
<form method="POST" action="{{ route('care.specialty.emergency.disposition', $workspaceVisit) }}" class="mt-4 space-y-3">
@csrf
<input type="hidden" name="tab" value="disposition">
<div class="grid gap-3 sm:grid-cols-2">
<div>
<label class="block text-xs font-medium text-slate-600">Final disposition</label>
<select name="payload[disposition]" required class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
<option value="">Select…</option>
@foreach (['Discharge home', 'Admit to ward', 'Admit to ICU', 'Transfer to facility', 'Left against advice', 'Died', 'Absconded'] as $opt)
<option value="{{ $opt }}" @selected(($payload['disposition'] ?? '') === $opt)>{{ $opt }}</option>
@endforeach
</select>
@error('payload.disposition')<p class="mt-1 text-sm text-red-600">{{ $message }}</p>@enderror
</div>
<div>
<label class="block text-xs font-medium text-slate-600">Condition</label>
<select name="payload[condition]" class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
<option value="">Select…</option>
@foreach (['Stable', 'Improving', 'Unstable', 'Critical', 'Deceased'] as $opt)
<option value="{{ $opt }}" @selected(($payload['condition'] ?? '') === $opt)>{{ $opt }}</option>
@endforeach
</select>
</div>
<div>
<label class="block text-xs font-medium text-slate-600">Destination</label>
<input type="text" name="payload[destination]" value="{{ $payload['destination'] ?? '' }}" class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
</div>
<div>
<label class="block text-xs font-medium text-slate-600">Disposition time</label>
<input type="text" name="payload[time]" value="{{ $payload['time'] ?? '' }}" placeholder="e.g. 14:30" class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
</div>
<div class="sm:col-span-2">
<label class="block text-xs font-medium text-slate-600">Diagnosis</label>
<input type="text" name="payload[diagnosis]" value="{{ $payload['diagnosis'] ?? '' }}" required class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
@error('payload.diagnosis')<p class="mt-1 text-sm text-red-600">{{ $message }}</p>@enderror
</div>
<div class="sm:col-span-2">
<label class="block text-xs font-medium text-slate-600">Advice / follow-up</label>
<textarea name="payload[advice]" rows="3" class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">{{ $payload['advice'] ?? '' }}</textarea>
</div>
<div class="sm:col-span-2">
<label class="block text-xs font-medium text-slate-600">Medications on discharge</label>
<textarea name="payload[medications]" rows="2" class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">{{ $payload['medications'] ?? '' }}</textarea>
</div>
<div class="sm:col-span-2">
<label class="block text-xs font-medium text-slate-600">Notes</label>
<textarea name="payload[notes]" rows="2" class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">{{ $payload['notes'] ?? '' }}</textarea>
</div>
</div>
<button type="submit" class="btn-primary">Save disposition &amp; complete visit</button>
</form>
</section>
@@ -0,0 +1,117 @@
@php
$triage = $emergencyTriage;
$payload = $triage?->payload ?? [];
$currentStage = $workspaceVisit->specialty_stage;
$stageFlow = $emergencyStageFlow ?? [];
$latest = $emergencyLatestVitals;
@endphp
<section class="rounded-2xl border border-slate-200 bg-white p-5">
<div class="flex flex-wrap items-start justify-between gap-3">
<div>
<h3 class="text-sm font-semibold text-slate-900">Emergency overview</h3>
<p class="mt-0.5 text-xs text-slate-500">Acuity, stage, ABC flags, and latest vitals for this visit.</p>
</div>
<div class="flex flex-wrap gap-3 text-sm">
<a href="{{ route('care.specialty.emergency.print', $workspaceVisit) }}" target="_blank" class="font-medium text-indigo-600">Print summary</a>
<a href="{{ route('care.specialty.emergency.reports') }}" class="font-medium text-indigo-600">ED reports</a>
</div>
</div>
<div class="mt-4 grid gap-3 sm:grid-cols-3">
<div class="rounded-xl border border-slate-100 bg-slate-50 px-3 py-3">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Acuity</p>
<p class="mt-1 text-sm font-semibold text-slate-900">{{ $payload['acuity'] ?? 'Not triaged' }}</p>
<p class="mt-1 text-xs text-slate-500">{{ $payload['chief_complaint'] ?? '—' }}</p>
</div>
<div class="rounded-xl border border-slate-100 bg-slate-50 px-3 py-3">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">ABC</p>
<p class="mt-1 text-sm text-slate-900">
A {{ ($payload['airway_ok'] ?? true) ? '✓' : '✗' }}
· B {{ ($payload['breathing_ok'] ?? true) ? '✓' : '✗' }}
· C {{ ($payload['circulation_ok'] ?? true) ? '✓' : '✗' }}
</p>
<p class="mt-1 text-xs text-slate-500">Pain {{ $payload['pain_score'] ?? '—' }} · GCS {{ $payload['gcs'] ?? '—' }}</p>
</div>
<div class="rounded-xl border border-slate-100 bg-slate-50 px-3 py-3">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Latest vitals</p>
@if ($latest)
<p class="mt-1 text-sm text-slate-900">
BP {{ $latest->bp_systolic ?? '—' }}/{{ $latest->bp_diastolic ?? '—' }}
· P {{ $latest->pulse ?? '—' }}
· SpO₂ {{ $latest->spo2 ?? '—' }}%
</p>
<p class="mt-1 text-xs text-slate-500">{{ $latest->recorded_at?->format('d M H:i') }}</p>
@else
<p class="mt-1 text-sm text-slate-500">None recorded</p>
@endif
</div>
</div>
<div class="mt-4 rounded-xl border border-slate-100 bg-slate-50 px-3 py-3">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Visit stage</p>
<p class="mt-1 text-sm font-medium text-slate-900">
{{ $currentStage ? ucfirst(str_replace('_', ' ', $currentStage)) : 'Not set' }}
</p>
<div class="mt-3 flex flex-wrap gap-2">
@foreach (($emergencyStageCodes ?: ['arrival', 'resus', 'treatment', 'observation', 'disposition']) as $stageCode)
<form method="POST" action="{{ route('care.specialty.emergency.stage', $workspaceVisit) }}">
@csrf
<input type="hidden" name="stage" value="{{ $stageCode }}">
<button type="submit"
@class([
'rounded-lg px-2.5 py-1 text-xs font-semibold',
'bg-indigo-600 text-white' => $currentStage === $stageCode,
'border border-slate-200 bg-white text-slate-700 hover:bg-slate-50' => $currentStage !== $stageCode,
])>
{{ ucfirst(str_replace('_', ' ', $stageCode)) }}
</button>
</form>
@endforeach
@if ($currentStage && isset($stageFlow[$currentStage]) && $stageFlow[$currentStage]['next'] !== $currentStage)
<form method="POST" action="{{ route('care.specialty.emergency.stage', $workspaceVisit) }}">
@csrf
<input type="hidden" name="stage" value="{{ $stageFlow[$currentStage]['next'] }}">
<button type="submit" class="rounded-lg bg-emerald-600 px-2.5 py-1 text-xs font-semibold text-white hover:bg-emerald-700">
{{ $stageFlow[$currentStage]['label'] }}
</button>
</form>
@endif
</div>
</div>
<dl class="mt-4 grid gap-3 text-sm sm:grid-cols-2">
<div>
<dt class="text-slate-500">Mode of arrival</dt>
<dd class="font-medium text-slate-900">{{ $payload['mode_of_arrival'] ?? '—' }}</dd>
</div>
<div>
<dt class="text-slate-500">Disposition intent</dt>
<dd class="font-medium text-slate-900">{{ $payload['disposition_intent'] ?? '—' }}</dd>
</div>
<div>
<dt class="text-slate-500">Queue</dt>
<dd class="font-medium text-slate-900">
{{ $workspaceVisit->appointment?->queue_ticket_number ?? '—' }}
@if ($workspaceVisit->appointment?->queue_ticket_status)
<span class="text-slate-500">({{ $workspaceVisit->appointment->queue_ticket_status }})</span>
@endif
</dd>
</div>
<div>
<dt class="text-slate-500">Checked in</dt>
<dd class="font-medium text-slate-900">{{ $workspaceVisit->checked_in_at?->format('d M Y H:i') ?? '—' }}</dd>
</div>
</dl>
@if (! empty($clinicalAlerts))
<div class="mt-4 space-y-1.5 border-t border-slate-100 pt-4">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Alerts</p>
@foreach ($clinicalAlerts as $alert)
<p class="text-sm {{ ($alert['severity'] ?? '') === 'critical' ? 'text-rose-700' : 'text-amber-800' }}">
{{ $alert['message'] ?? '' }}
</p>
@endforeach
</div>
@endif
</section>
@@ -0,0 +1,67 @@
<section class="rounded-2xl border border-slate-200 bg-white p-5">
<div class="flex flex-wrap items-start justify-between gap-3">
<div>
<h3 class="text-sm font-semibold text-slate-900">Vitals</h3>
<p class="mt-0.5 text-xs text-slate-500">Record BP, pulse, SpO₂, temperature, and respiratory rate on this ED visit.</p>
</div>
</div>
<form method="POST" action="{{ route('care.specialty.emergency.vitals', $workspaceVisit) }}" class="mt-4 grid gap-3 sm:grid-cols-4">
@csrf
<div>
<label class="block text-xs font-medium text-slate-600">BP systolic</label>
<input type="number" name="bp_systolic" class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
</div>
<div>
<label class="block text-xs font-medium text-slate-600">BP diastolic</label>
<input type="number" name="bp_diastolic" class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
</div>
<div>
<label class="block text-xs font-medium text-slate-600">Pulse</label>
<input type="number" name="pulse" class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
</div>
<div>
<label class="block text-xs font-medium text-slate-600">SpO₂ %</label>
<input type="number" name="spo2" class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
</div>
<div>
<label class="block text-xs font-medium text-slate-600">Temperature °C</label>
<input type="number" step="0.1" name="temperature" class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
</div>
<div>
<label class="block text-xs font-medium text-slate-600">Respiratory rate</label>
<input type="number" name="respiratory_rate" class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
</div>
<div>
<label class="block text-xs font-medium text-slate-600">Weight kg</label>
<input type="number" step="0.1" name="weight_kg" class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
</div>
<div>
<label class="block text-xs font-medium text-slate-600">Height cm</label>
<input type="number" step="0.1" name="height_cm" class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
</div>
<div class="sm:col-span-4">
<button type="submit" class="btn-primary">Save vitals</button>
</div>
</form>
<div class="mt-6 border-t border-slate-100 pt-4">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">History</p>
<ul class="mt-2 divide-y divide-slate-100 text-sm">
@forelse ($emergencyVitals as $row)
<li class="flex flex-wrap justify-between gap-2 py-2">
<span>
BP {{ $row->bp_systolic ?? '—' }}/{{ $row->bp_diastolic ?? '—' }}
· P {{ $row->pulse ?? '—' }}
· SpO₂ {{ $row->spo2 ?? '—' }}%
· T {{ $row->temperature ?? '—' }}
· RR {{ $row->respiratory_rate ?? '—' }}
</span>
<span class="text-slate-500">{{ $row->recorded_at?->format('d M Y H:i') }}</span>
</li>
@empty
<li class="py-3 text-slate-500">No vitals recorded yet.</li>
@endforelse
</ul>
</div>
</section>
@@ -22,14 +22,21 @@
&& $openConsultation->status !== \App\Models\Consultation::STATUS_COMPLETED; && $openConsultation->status !== \App\Models\Consultation::STATUS_COMPLETED;
$chartTab = collect($workspaceTabs ?? []) $chartTab = collect($workspaceTabs ?? [])
->keys() ->keys()
->first(fn ($key) => ! in_array($key, ['overview', 'timeline', 'plan', 'treat', 'notes', 'imaging', 'orders', 'billing', 'documents', 'perio', 'lab', 'recalls'], true)) ->first(fn ($key) => ! in_array($key, ['overview', 'timeline', 'plan', 'treat', 'notes', 'imaging', 'orders', 'billing', 'documents', 'perio', 'lab', 'recalls', 'vitals', 'disposition', 'observation'], true))
?: 'odontogram'; ?: ($moduleKey === 'emergency' ? 'triage' : 'odontogram');
$stageFlow = [ $stageFlow = $moduleKey === 'emergency'
'waiting' => ['next' => 'chair', 'label' => 'Seat at chair'], ? ($emergencyStageFlow ?? [
'chair' => ['next' => 'procedure', 'label' => 'Start procedure'], 'arrival' => ['next' => 'treatment', 'label' => 'Move to treatment'],
'procedure' => ['next' => 'recovery', 'label' => 'Move to recovery'], 'resus' => ['next' => 'treatment', 'label' => 'Move to treatment bay'],
'recovery' => ['next' => 'completed', 'label' => 'Complete visit'], 'treatment' => ['next' => 'observation', 'label' => 'Move to observation'],
]; 'observation' => ['next' => 'disposition', 'label' => 'Ready for disposition'],
])
: [
'waiting' => ['next' => 'chair', 'label' => 'Seat at chair'],
'chair' => ['next' => 'procedure', 'label' => 'Start procedure'],
'procedure' => ['next' => 'recovery', 'label' => 'Move to recovery'],
'recovery' => ['next' => 'completed', 'label' => 'Complete visit'],
];
$currentStage = $workspaceVisit?->specialty_stage; $currentStage = $workspaceVisit?->specialty_stage;
@endphp @endphp
@@ -63,6 +70,18 @@
<input type="hidden" name="stage" value="chair"> <input type="hidden" name="stage" value="chair">
<button type="submit" class="{{ $btnAccent }}">Seat at chair</button> <button type="submit" class="{{ $btnAccent }}">Seat at chair</button>
</form> </form>
@elseif ($moduleKey === 'emergency' && $currentStage && isset($stageFlow[$currentStage]) && ($stageFlow[$currentStage]['next'] ?? null) !== $currentStage)
<form method="POST" action="{{ route('care.specialty.emergency.stage', $workspaceVisit) }}" class="w-full" @click.stop>
@csrf
<input type="hidden" name="stage" value="{{ $stageFlow[$currentStage]['next'] }}">
<button type="submit" class="{{ $btnAccent }}">{{ $stageFlow[$currentStage]['label'] }}</button>
</form>
@elseif ($moduleKey === 'emergency' && ! $currentStage)
<form method="POST" action="{{ route('care.specialty.emergency.stage', $workspaceVisit) }}" class="w-full" @click.stop>
@csrf
<input type="hidden" name="stage" value="arrival">
<button type="submit" class="{{ $btnAccent }}">Start triage</button>
</form>
@endif @endif
@if ($canCompleteConsultation) @if ($canCompleteConsultation)
@@ -38,6 +38,8 @@
@include('care.partials.patient-timeline', ['events' => $timeline ?? []]) @include('care.partials.patient-timeline', ['events' => $timeline ?? []])
@elseif ($moduleKey === 'dentistry' && in_array($activeTab, ['odontogram', 'plan', 'treat', 'notes', 'imaging', 'overview', 'perio', 'lab', 'recalls'], true)) @elseif ($moduleKey === 'dentistry' && in_array($activeTab, ['odontogram', 'plan', 'treat', 'notes', 'imaging', 'overview', 'perio', 'lab', 'recalls'], true))
@include('care.specialty.dentistry.workspace-'.$activeTab) @include('care.specialty.dentistry.workspace-'.$activeTab)
@elseif ($moduleKey === 'emergency' && in_array($activeTab, ['overview', 'vitals', 'disposition'], true))
@include('care.specialty.emergency.workspace-'.$activeTab)
@elseif ($activeTab === 'billing') @elseif ($activeTab === 'billing')
<section class="rounded-2xl border border-slate-200 bg-white p-5"> <section class="rounded-2xl border border-slate-200 bg-white p-5">
<h3 class="text-sm font-semibold text-slate-900">Add specialty service</h3> <h3 class="text-sm font-semibold text-slate-900">Add specialty service</h3>
+6
View File
@@ -36,6 +36,7 @@ use App\Http\Controllers\Care\SettingsController;
use App\Http\Controllers\Care\SettingsGpPricingController; use App\Http\Controllers\Care\SettingsGpPricingController;
use App\Http\Controllers\Care\SettingsModulesController; use App\Http\Controllers\Care\SettingsModulesController;
use App\Http\Controllers\Care\DentistryWorkspaceController; use App\Http\Controllers\Care\DentistryWorkspaceController;
use App\Http\Controllers\Care\EmergencyWorkspaceController;
use App\Http\Controllers\Care\SpecialtyModuleController; use App\Http\Controllers\Care\SpecialtyModuleController;
use App\Http\Controllers\Care\VisitWorkflowController; use App\Http\Controllers\Care\VisitWorkflowController;
use App\Http\Controllers\NotificationController; use App\Http\Controllers\NotificationController;
@@ -114,6 +115,7 @@ Route::middleware(['auth', 'platform.session'])->group(function () {
Route::get('/specialty/{module}/history', [SpecialtyModuleController::class, 'history'])->name('care.specialty.history'); Route::get('/specialty/{module}/history', [SpecialtyModuleController::class, 'history'])->name('care.specialty.history');
Route::get('/specialty/{module}/billing', [SpecialtyModuleController::class, 'billing'])->name('care.specialty.billing'); Route::get('/specialty/{module}/billing', [SpecialtyModuleController::class, 'billing'])->name('care.specialty.billing');
Route::get('/specialty/dentistry/reports', [DentistryWorkspaceController::class, 'reports'])->name('care.specialty.dentistry.reports'); Route::get('/specialty/dentistry/reports', [DentistryWorkspaceController::class, 'reports'])->name('care.specialty.dentistry.reports');
Route::get('/specialty/emergency/reports', [EmergencyWorkspaceController::class, 'reports'])->name('care.specialty.emergency.reports');
Route::get('/specialty/{module}/workspace/{visit?}', [SpecialtyModuleController::class, 'workspace'])->name('care.specialty.workspace'); Route::get('/specialty/{module}/workspace/{visit?}', [SpecialtyModuleController::class, 'workspace'])->name('care.specialty.workspace');
Route::post('/specialty/{module}/workspace/{visit}/clinical', [SpecialtyModuleController::class, 'saveClinical'])->name('care.specialty.clinical.save'); Route::post('/specialty/{module}/workspace/{visit}/clinical', [SpecialtyModuleController::class, 'saveClinical'])->name('care.specialty.clinical.save');
Route::post('/specialty/{module}/workspace/{visit}/documents', [SpecialtyModuleController::class, 'uploadDocument'])->name('care.specialty.documents.upload'); Route::post('/specialty/{module}/workspace/{visit}/documents', [SpecialtyModuleController::class, 'uploadDocument'])->name('care.specialty.documents.upload');
@@ -139,6 +141,10 @@ Route::middleware(['auth', 'platform.session'])->group(function () {
Route::post('/specialty/dentistry/workspace/{visit}/recalls/{recall}/complete', [DentistryWorkspaceController::class, 'completeRecall'])->name('care.specialty.dentistry.recalls.complete'); Route::post('/specialty/dentistry/workspace/{visit}/recalls/{recall}/complete', [DentistryWorkspaceController::class, 'completeRecall'])->name('care.specialty.dentistry.recalls.complete');
Route::post('/specialty/dentistry/workspace/{visit}/recalls/{recall}/cancel', [DentistryWorkspaceController::class, 'cancelRecall'])->name('care.specialty.dentistry.recalls.cancel'); Route::post('/specialty/dentistry/workspace/{visit}/recalls/{recall}/cancel', [DentistryWorkspaceController::class, 'cancelRecall'])->name('care.specialty.dentistry.recalls.cancel');
Route::get('/specialty/dentistry/workspace/{visit}/print', [DentistryWorkspaceController::class, 'printChart'])->name('care.specialty.dentistry.print'); Route::get('/specialty/dentistry/workspace/{visit}/print', [DentistryWorkspaceController::class, 'printChart'])->name('care.specialty.dentistry.print');
Route::post('/specialty/emergency/workspace/{visit}/stage', [EmergencyWorkspaceController::class, 'setStage'])->name('care.specialty.emergency.stage');
Route::post('/specialty/emergency/workspace/{visit}/vitals', [EmergencyWorkspaceController::class, 'saveVitals'])->name('care.specialty.emergency.vitals');
Route::post('/specialty/emergency/workspace/{visit}/disposition', [EmergencyWorkspaceController::class, 'saveDisposition'])->name('care.specialty.emergency.disposition');
Route::get('/specialty/emergency/workspace/{visit}/print', [EmergencyWorkspaceController::class, 'printSummary'])->name('care.specialty.emergency.print');
Route::get('/specialty/{module}', [SpecialtyModuleController::class, 'show'])->name('care.specialty.show'); Route::get('/specialty/{module}', [SpecialtyModuleController::class, 'show'])->name('care.specialty.show');
Route::post('/specialty/{module}/call-next', [SpecialtyModuleController::class, 'callNext'])->name('care.specialty.call-next'); Route::post('/specialty/{module}/call-next', [SpecialtyModuleController::class, 'callNext'])->name('care.specialty.call-next');
+241
View File
@@ -0,0 +1,241 @@
<?php
namespace Tests\Feature;
use App\Http\Middleware\EnsurePlatformSession;
use App\Models\Appointment;
use App\Models\Branch;
use App\Models\Department;
use App\Models\Member;
use App\Models\Organization;
use App\Models\Patient;
use App\Models\SpecialtyClinicalRecord;
use App\Models\User;
use App\Models\Visit;
use App\Models\VitalSign;
use App\Services\Care\SpecialtyModuleService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class CareEmergencySuiteTest extends TestCase
{
use RefreshDatabase;
protected User $owner;
protected Organization $organization;
protected Branch $branch;
protected Patient $patient;
protected Visit $visit;
protected function setUp(): void
{
parent::setUp();
$this->withoutMiddleware(EnsurePlatformSession::class);
$this->owner = User::create([
'public_id' => 'er-owner',
'name' => 'Owner',
'email' => 'er-owner@example.com',
]);
$this->organization = Organization::create([
'owner_ref' => $this->owner->public_id,
'name' => 'Emergency Clinic',
'slug' => 'emergency-clinic',
'settings' => [
'onboarded' => true,
'facility_type' => 'clinic',
'plan' => 'pro',
'plan_expires_at' => now()->addMonth()->toIso8601String(),
'queue_integration_enabled' => true,
],
]);
Member::create([
'owner_ref' => $this->owner->public_id,
'organization_id' => $this->organization->id,
'user_ref' => $this->owner->public_id,
'role' => 'hospital_admin',
'branch_id' => null,
]);
$this->branch = Branch::create([
'owner_ref' => $this->owner->public_id,
'organization_id' => $this->organization->id,
'name' => 'Main',
'is_active' => true,
]);
app(SpecialtyModuleService::class)->activate(
$this->organization,
$this->owner->public_id,
'emergency',
);
$department = Department::query()
->where('branch_id', $this->branch->id)
->where('type', 'emergency')
->firstOrFail();
$this->patient = Patient::create([
'owner_ref' => $this->owner->public_id,
'organization_id' => $this->organization->id,
'branch_id' => $this->branch->id,
'patient_number' => 'P-ER-SUITE',
'first_name' => 'Kwame',
'last_name' => 'Boateng',
'gender' => 'male',
'date_of_birth' => '1988-01-01',
]);
$this->visit = Visit::create([
'owner_ref' => $this->owner->public_id,
'organization_id' => $this->organization->id,
'branch_id' => $this->branch->id,
'patient_id' => $this->patient->id,
'status' => Visit::STATUS_IN_PROGRESS,
'checked_in_at' => now(),
'specialty_stage' => 'arrival',
]);
Appointment::create([
'owner_ref' => $this->owner->public_id,
'organization_id' => $this->organization->id,
'branch_id' => $this->branch->id,
'patient_id' => $this->patient->id,
'department_id' => $department->id,
'visit_id' => $this->visit->id,
'type' => Appointment::TYPE_WALK_IN,
'status' => Appointment::STATUS_IN_CONSULTATION,
'scheduled_at' => now(),
'waiting_at' => now(),
'checked_in_at' => now(),
'started_at' => now(),
]);
}
public function test_overview_and_vitals_tabs_render(): void
{
$this->actingAs($this->owner)
->get(route('care.specialty.workspace', [
'module' => 'emergency',
'visit' => $this->visit,
'tab' => 'overview',
]))
->assertOk()
->assertSee('Emergency overview')
->assertSee('Visit stage')
->assertSee('ED reports');
$this->actingAs($this->owner)
->get(route('care.specialty.workspace', [
'module' => 'emergency',
'visit' => $this->visit,
'tab' => 'vitals',
]))
->assertOk()
->assertSee('Save vitals');
}
public function test_triage_sets_stage_and_alerts(): void
{
$this->actingAs($this->owner)
->post(route('care.specialty.clinical.save', [
'module' => 'emergency',
'visit' => $this->visit,
]), [
'tab' => 'triage',
'payload' => [
'acuity' => '1 - Resuscitation',
'chief_complaint' => 'Chest pain',
'airway_ok' => '1',
'breathing_ok' => '0',
'circulation_ok' => '1',
'pain_score' => 9,
'disposition_intent' => 'Resus',
],
])
->assertRedirect();
$this->assertSame('resus', $this->visit->fresh()->specialty_stage);
$record = SpecialtyClinicalRecord::query()
->where('visit_id', $this->visit->id)
->where('record_type', 'triage')
->firstOrFail();
$codes = collect($record->alerts)->pluck('code')->all();
$this->assertContains('er.high_acuity', $codes);
$this->assertContains('er.abc_compromise', $codes);
$this->assertContains('er.severe_pain', $codes);
}
public function test_stage_advance_and_vitals_and_disposition(): void
{
$this->actingAs($this->owner)
->post(route('care.specialty.emergency.stage', $this->visit), [
'stage' => 'treatment',
])
->assertRedirect();
$this->assertSame('treatment', $this->visit->fresh()->specialty_stage);
$this->actingAs($this->owner)
->post(route('care.specialty.emergency.vitals', $this->visit), [
'bp_systolic' => 120,
'bp_diastolic' => 80,
'pulse' => 88,
'spo2' => 98,
])
->assertRedirect(route('care.specialty.workspace', [
'module' => 'emergency',
'visit' => $this->visit,
'tab' => 'vitals',
]));
$this->assertDatabaseHas('care_vital_signs', [
'bp_systolic' => 120,
'pulse' => 88,
]);
$this->assertTrue(VitalSign::query()->where('bp_systolic', 120)->exists());
$this->actingAs($this->owner)
->post(route('care.specialty.emergency.disposition', $this->visit), [
'tab' => 'disposition',
'payload' => [
'disposition' => 'Discharge home',
'condition' => 'Stable',
'diagnosis' => 'Musculoskeletal chest wall pain',
'advice' => 'Return if worsens',
],
])
->assertRedirect();
$this->assertSame('disposition', $this->visit->fresh()->specialty_stage);
$this->assertSame(Visit::STATUS_COMPLETED, $this->visit->fresh()->status);
$this->assertDatabaseHas('care_specialty_clinical_records', [
'visit_id' => $this->visit->id,
'record_type' => 'disposition',
'status' => SpecialtyClinicalRecord::STATUS_COMPLETED,
]);
}
public function test_reports_and_print(): void
{
$this->actingAs($this->owner)
->get(route('care.specialty.emergency.reports'))
->assertOk()
->assertSee('Emergency reports')
->assertSee('Arrivals today');
$this->actingAs($this->owner)
->get(route('care.specialty.emergency.print', $this->visit))
->assertOk()
->assertSee('ED summary')
->assertSee($this->patient->fullName());
}
}