Add full Pediatrics, Orthopedics, and ENT specialty clinical suites.
Deploy Ladill Care / deploy (push) Successful in 43s

Mirror Cardiology-depth stage flows, workspace tabs, reports/print, clinical
alerts, demo seeds, and PHPUnit coverage for child health, fracture clinic,
and ENT pathways.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
isaacclad
2026-07-19 19:12:38 +00:00
co-authored by Cursor
parent 8e23cdeae3
commit dc86b51ed5
36 changed files with 4021 additions and 38 deletions
@@ -0,0 +1,215 @@
<?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\Ent\EntAnalyticsService;
use App\Services\Care\Ent\EntWorkflowService;
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 EntWorkspaceController extends Controller
{
use ScopesToAccount;
protected function assertEntAccess(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanAccess($organization, $this->member($request), 'ent'), 403);
}
protected function assertEntManage(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanManage($organization, $this->member($request), 'ent'), 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,
SpecialtyShellService $shell,
): RedirectResponse {
$this->authorizeAbility($request, 'consultations.manage');
$this->assertEntManage($request, $modules);
$this->assertVisit($request, $visit);
$validated = $request->validate([
'stage' => ['required', 'string', 'max:32'],
]);
try {
$stages->setStage(
$this->organization($request),
$visit,
'ent',
$validated['stage'],
$this->ownerRef($request),
$this->actorRef($request),
);
} catch (\InvalidArgumentException $e) {
return back()->with('error', $e->getMessage());
}
return redirect()
->route('care.specialty.workspace', [
'module' => 'ent',
'visit' => $visit,
'tab' => $shell->workspaceTabForStage('ent', $validated['stage']),
])
->with('success', 'Visit stage updated.');
}
public function saveProcedure(
Request $request,
Visit $visit,
SpecialtyModuleService $modules,
SpecialtyClinicalRecordService $clinical,
SpecialtyVisitStageService $stages,
EntWorkflowService $workflow,
): RedirectResponse {
$this->authorizeAbility($request, 'consultations.manage');
$this->assertEntManage($request, $modules);
$this->assertVisit($request, $visit);
$organization = $this->organization($request);
$owner = $this->ownerRef($request);
$payload = (array) $request->input('payload', []);
foreach ($clinical->fieldsFor('ent', 'ent_procedure') as $field) {
if (($field['type'] ?? '') === 'boolean') {
$payload[$field['name']] = $request->boolean('payload.'.$field['name']);
}
}
$request->merge(['payload' => $payload, 'tab' => 'procedure']);
$validated = $request->validate(array_merge([
'tab' => ['required', 'string'],
], $clinical->validationRules('ent', 'ent_procedure')));
$record = $clinical->upsert(
$organization,
$visit,
'ent',
'ent_procedure',
$clinical->payloadFromRequest($validated),
$owner,
$owner,
EntWorkflowService::STAGE_PROCEDURE,
SpecialtyClinicalRecord::STATUS_COMPLETED,
);
try {
$stages->setStage(
$organization,
$visit,
'ent',
EntWorkflowService::STAGE_PROCEDURE,
$owner,
$owner,
);
} catch (\InvalidArgumentException) {
}
if ($workflow->shouldCompleteVisit($record->payload ?? [])) {
try {
$stages->setStage(
$organization,
$visit,
'ent',
EntWorkflowService::STAGE_COMPLETED,
$owner,
$owner,
);
} catch (\InvalidArgumentException) {
}
$visit->refresh();
if ($visit->status !== Visit::STATUS_COMPLETED) {
$visit->update([
'status' => Visit::STATUS_COMPLETED,
'completed_at' => $visit->completed_at ?? now(),
]);
}
$appointment = $visit->appointment;
if ($appointment && $appointment->status !== \App\Models\Appointment::STATUS_COMPLETED) {
$appointment->update([
'status' => \App\Models\Appointment::STATUS_COMPLETED,
'completed_at' => $appointment->completed_at ?? now(),
]);
}
}
return redirect()
->route('care.specialty.workspace', ['module' => 'ent', 'visit' => $visit, 'tab' => 'procedure'])
->with('success', 'ENT procedure saved.');
}
public function reports(
Request $request,
SpecialtyModuleService $modules,
SpecialtyShellService $shell,
EntAnalyticsService $analytics,
): View {
$this->authorizeAbility($request, 'consultations.view');
$this->assertEntAccess($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.ent.reports', [
'moduleKey' => 'ent',
'definition' => $modules->definition('ent'),
'shellNav' => $shell->navItems('ent'),
'report' => $report,
'currency' => strtoupper((string) config('care.billing.currency', config('care.currency', 'GHS'))),
]);
}
public function printSummary(
Request $request,
Visit $visit,
SpecialtyModuleService $modules,
SpecialtyClinicalRecordService $clinical,
): View {
$this->authorizeAbility($request, 'consultations.view');
$this->assertEntAccess($request, $modules);
$this->assertVisit($request, $visit);
$visit->loadMissing(['patient', 'appointment.practitioner', 'branch']);
return view('care.specialty.ent.print', [
'visit' => $visit,
'patient' => $visit->patient,
'history' => $clinical->findForVisit($visit, 'ent', 'ent_history'),
'exam' => $clinical->findForVisit($visit, 'ent', 'ent_exam'),
'investigation' => $clinical->findForVisit($visit, 'ent', 'ent_investigation'),
'plan' => $clinical->findForVisit($visit, 'ent', 'ent_plan'),
'procedure' => $clinical->findForVisit($visit, 'ent', 'ent_procedure'),
]);
}
}
@@ -0,0 +1,215 @@
<?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\Orthopedics\OrthopedicsAnalyticsService;
use App\Services\Care\Orthopedics\OrthopedicsWorkflowService;
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 OrthopedicsWorkspaceController extends Controller
{
use ScopesToAccount;
protected function assertOrthopedicsAccess(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanAccess($organization, $this->member($request), 'orthopedics'), 403);
}
protected function assertOrthopedicsManage(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanManage($organization, $this->member($request), 'orthopedics'), 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,
SpecialtyShellService $shell,
): RedirectResponse {
$this->authorizeAbility($request, 'consultations.manage');
$this->assertOrthopedicsManage($request, $modules);
$this->assertVisit($request, $visit);
$validated = $request->validate([
'stage' => ['required', 'string', 'max:32'],
]);
try {
$stages->setStage(
$this->organization($request),
$visit,
'orthopedics',
$validated['stage'],
$this->ownerRef($request),
$this->actorRef($request),
);
} catch (\InvalidArgumentException $e) {
return back()->with('error', $e->getMessage());
}
return redirect()
->route('care.specialty.workspace', [
'module' => 'orthopedics',
'visit' => $visit,
'tab' => $shell->workspaceTabForStage('orthopedics', $validated['stage']),
])
->with('success', 'Visit stage updated.');
}
public function saveProcedure(
Request $request,
Visit $visit,
SpecialtyModuleService $modules,
SpecialtyClinicalRecordService $clinical,
SpecialtyVisitStageService $stages,
OrthopedicsWorkflowService $workflow,
): RedirectResponse {
$this->authorizeAbility($request, 'consultations.manage');
$this->assertOrthopedicsManage($request, $modules);
$this->assertVisit($request, $visit);
$organization = $this->organization($request);
$owner = $this->ownerRef($request);
$payload = (array) $request->input('payload', []);
foreach ($clinical->fieldsFor('orthopedics', 'ortho_procedure') as $field) {
if (($field['type'] ?? '') === 'boolean') {
$payload[$field['name']] = $request->boolean('payload.'.$field['name']);
}
}
$request->merge(['payload' => $payload, 'tab' => 'procedure']);
$validated = $request->validate(array_merge([
'tab' => ['required', 'string'],
], $clinical->validationRules('orthopedics', 'ortho_procedure')));
$record = $clinical->upsert(
$organization,
$visit,
'orthopedics',
'ortho_procedure',
$clinical->payloadFromRequest($validated),
$owner,
$owner,
OrthopedicsWorkflowService::STAGE_PROCEDURE,
SpecialtyClinicalRecord::STATUS_COMPLETED,
);
try {
$stages->setStage(
$organization,
$visit,
'orthopedics',
OrthopedicsWorkflowService::STAGE_PROCEDURE,
$owner,
$owner,
);
} catch (\InvalidArgumentException) {
}
if ($workflow->shouldCompleteVisit($record->payload ?? [])) {
try {
$stages->setStage(
$organization,
$visit,
'orthopedics',
OrthopedicsWorkflowService::STAGE_COMPLETED,
$owner,
$owner,
);
} catch (\InvalidArgumentException) {
}
$visit->refresh();
if ($visit->status !== Visit::STATUS_COMPLETED) {
$visit->update([
'status' => Visit::STATUS_COMPLETED,
'completed_at' => $visit->completed_at ?? now(),
]);
}
$appointment = $visit->appointment;
if ($appointment && $appointment->status !== \App\Models\Appointment::STATUS_COMPLETED) {
$appointment->update([
'status' => \App\Models\Appointment::STATUS_COMPLETED,
'completed_at' => $appointment->completed_at ?? now(),
]);
}
}
return redirect()
->route('care.specialty.workspace', ['module' => 'orthopedics', 'visit' => $visit, 'tab' => 'procedure'])
->with('success', 'Procedure / cast saved.');
}
public function reports(
Request $request,
SpecialtyModuleService $modules,
SpecialtyShellService $shell,
OrthopedicsAnalyticsService $analytics,
): View {
$this->authorizeAbility($request, 'consultations.view');
$this->assertOrthopedicsAccess($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.orthopedics.reports', [
'moduleKey' => 'orthopedics',
'definition' => $modules->definition('orthopedics'),
'shellNav' => $shell->navItems('orthopedics'),
'report' => $report,
'currency' => strtoupper((string) config('care.billing.currency', config('care.currency', 'GHS'))),
]);
}
public function printSummary(
Request $request,
Visit $visit,
SpecialtyModuleService $modules,
SpecialtyClinicalRecordService $clinical,
): View {
$this->authorizeAbility($request, 'consultations.view');
$this->assertOrthopedicsAccess($request, $modules);
$this->assertVisit($request, $visit);
$visit->loadMissing(['patient', 'appointment.practitioner', 'branch']);
return view('care.specialty.orthopedics.print', [
'visit' => $visit,
'patient' => $visit->patient,
'history' => $clinical->findForVisit($visit, 'orthopedics', 'ortho_history'),
'exam' => $clinical->findForVisit($visit, 'orthopedics', 'ortho_exam'),
'imaging' => $clinical->findForVisit($visit, 'orthopedics', 'ortho_imaging'),
'plan' => $clinical->findForVisit($visit, 'orthopedics', 'ortho_plan'),
'procedure' => $clinical->findForVisit($visit, 'orthopedics', 'ortho_procedure'),
]);
}
}
@@ -0,0 +1,215 @@
<?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\Pediatrics\PediatricsAnalyticsService;
use App\Services\Care\Pediatrics\PediatricsWorkflowService;
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 PediatricsWorkspaceController extends Controller
{
use ScopesToAccount;
protected function assertPediatricsAccess(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanAccess($organization, $this->member($request), 'pediatrics'), 403);
}
protected function assertPediatricsManage(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanManage($organization, $this->member($request), 'pediatrics'), 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,
SpecialtyShellService $shell,
): RedirectResponse {
$this->authorizeAbility($request, 'consultations.manage');
$this->assertPediatricsManage($request, $modules);
$this->assertVisit($request, $visit);
$validated = $request->validate([
'stage' => ['required', 'string', 'max:32'],
]);
try {
$stages->setStage(
$this->organization($request),
$visit,
'pediatrics',
$validated['stage'],
$this->ownerRef($request),
$this->actorRef($request),
);
} catch (\InvalidArgumentException $e) {
return back()->with('error', $e->getMessage());
}
return redirect()
->route('care.specialty.workspace', [
'module' => 'pediatrics',
'visit' => $visit,
'tab' => $shell->workspaceTabForStage('pediatrics', $validated['stage']),
])
->with('success', 'Visit stage updated.');
}
public function saveTreatment(
Request $request,
Visit $visit,
SpecialtyModuleService $modules,
SpecialtyClinicalRecordService $clinical,
SpecialtyVisitStageService $stages,
PediatricsWorkflowService $workflow,
): RedirectResponse {
$this->authorizeAbility($request, 'consultations.manage');
$this->assertPediatricsManage($request, $modules);
$this->assertVisit($request, $visit);
$organization = $this->organization($request);
$owner = $this->ownerRef($request);
$payload = (array) $request->input('payload', []);
foreach ($clinical->fieldsFor('pediatrics', 'ped_treatment') as $field) {
if (($field['type'] ?? '') === 'boolean') {
$payload[$field['name']] = $request->boolean('payload.'.$field['name']);
}
}
$request->merge(['payload' => $payload, 'tab' => 'treatment']);
$validated = $request->validate(array_merge([
'tab' => ['required', 'string'],
], $clinical->validationRules('pediatrics', 'ped_treatment')));
$record = $clinical->upsert(
$organization,
$visit,
'pediatrics',
'ped_treatment',
$clinical->payloadFromRequest($validated),
$owner,
$owner,
PediatricsWorkflowService::STAGE_TREATMENT,
SpecialtyClinicalRecord::STATUS_COMPLETED,
);
try {
$stages->setStage(
$organization,
$visit,
'pediatrics',
PediatricsWorkflowService::STAGE_TREATMENT,
$owner,
$owner,
);
} catch (\InvalidArgumentException) {
}
if ($workflow->shouldCompleteVisit($record->payload ?? [])) {
try {
$stages->setStage(
$organization,
$visit,
'pediatrics',
PediatricsWorkflowService::STAGE_COMPLETED,
$owner,
$owner,
);
} catch (\InvalidArgumentException) {
}
$visit->refresh();
if ($visit->status !== Visit::STATUS_COMPLETED) {
$visit->update([
'status' => Visit::STATUS_COMPLETED,
'completed_at' => $visit->completed_at ?? now(),
]);
}
$appointment = $visit->appointment;
if ($appointment && $appointment->status !== \App\Models\Appointment::STATUS_COMPLETED) {
$appointment->update([
'status' => \App\Models\Appointment::STATUS_COMPLETED,
'completed_at' => $appointment->completed_at ?? now(),
]);
}
}
return redirect()
->route('care.specialty.workspace', ['module' => 'pediatrics', 'visit' => $visit, 'tab' => 'treatment'])
->with('success', 'Treatment / immunization saved.');
}
public function reports(
Request $request,
SpecialtyModuleService $modules,
SpecialtyShellService $shell,
PediatricsAnalyticsService $analytics,
): View {
$this->authorizeAbility($request, 'consultations.view');
$this->assertPediatricsAccess($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.pediatrics.reports', [
'moduleKey' => 'pediatrics',
'definition' => $modules->definition('pediatrics'),
'shellNav' => $shell->navItems('pediatrics'),
'report' => $report,
'currency' => strtoupper((string) config('care.billing.currency', config('care.currency', 'GHS'))),
]);
}
public function printSummary(
Request $request,
Visit $visit,
SpecialtyModuleService $modules,
SpecialtyClinicalRecordService $clinical,
): View {
$this->authorizeAbility($request, 'consultations.view');
$this->assertPediatricsAccess($request, $modules);
$this->assertVisit($request, $visit);
$visit->loadMissing(['patient', 'appointment.practitioner', 'branch']);
return view('care.specialty.pediatrics.print', [
'visit' => $visit,
'patient' => $visit->patient,
'history' => $clinical->findForVisit($visit, 'pediatrics', 'ped_history'),
'exam' => $clinical->findForVisit($visit, 'pediatrics', 'pediatric_exam'),
'investigation' => $clinical->findForVisit($visit, 'pediatrics', 'ped_investigation'),
'plan' => $clinical->findForVisit($visit, 'pediatrics', 'ped_plan'),
'treatment' => $clinical->findForVisit($visit, 'pediatrics', 'ped_treatment'),
]);
}
}
@@ -159,6 +159,9 @@ class SpecialtyModuleController extends Controller
'radiology' => 'protocol',
'cardiology' => 'history',
'psychiatry' => 'history',
'pediatrics' => 'history',
'orthopedics' => 'history',
'ent' => 'history',
default => (collect(array_keys($shellTabs))
->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null)
?? 'clinical_notes'),
@@ -236,6 +239,9 @@ class SpecialtyModuleController extends Controller
'radiology' => 'protocol',
'cardiology' => 'history',
'psychiatry' => 'history',
'pediatrics' => 'history',
'orthopedics' => 'history',
'ent' => 'history',
default => (collect(array_keys($shellTabs))
->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null)
?? 'clinical_notes'),
@@ -656,6 +662,150 @@ class SpecialtyModuleController extends Controller
}
}
if ($module === 'pediatrics' && in_array($recordType, ['ped_history', 'pediatric_exam', 'ped_investigation', 'ped_plan'], true)) {
$workflow = app(\App\Services\Care\Pediatrics\PediatricsWorkflowService::class);
$stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
$suggested = match ($recordType) {
'ped_history' => $workflow->stageFromHistory($record->payload ?? []),
'pediatric_exam' => $workflow->stageFromExam($record->payload ?? []),
'ped_investigation' => $workflow->stageFromInvestigation($record->payload ?? []),
'ped_plan' => $workflow->stageFromPlan($record->payload ?? []),
default => null,
};
$current = $visit->specialty_stage;
$early = ['check_in', 'waiting', null, ''];
$order = [
'check_in' => 0,
'history' => 1,
'exam' => 2,
'investigation' => 3,
'plan' => 4,
'treatment' => 5,
'completed' => 6,
];
if ($suggested && (! $current || in_array($current, $early, true))) {
try {
$stageService->setStage(
$organization,
$visit,
'pediatrics',
$suggested,
$this->ownerRef($request),
$this->ownerRef($request),
);
} catch (\InvalidArgumentException) {
}
} elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
try {
$stageService->setStage(
$organization,
$visit,
'pediatrics',
$suggested,
$this->ownerRef($request),
$this->ownerRef($request),
);
} catch (\InvalidArgumentException) {
}
}
}
if ($module === 'orthopedics' && in_array($recordType, ['ortho_history', 'ortho_exam', 'ortho_imaging', 'ortho_plan'], true)) {
$workflow = app(\App\Services\Care\Orthopedics\OrthopedicsWorkflowService::class);
$stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
$suggested = match ($recordType) {
'ortho_history' => $workflow->stageFromHistory($record->payload ?? []),
'ortho_exam' => $workflow->stageFromExam($record->payload ?? []),
'ortho_imaging' => $workflow->stageFromImaging($record->payload ?? []),
'ortho_plan' => $workflow->stageFromPlan($record->payload ?? []),
default => null,
};
$current = $visit->specialty_stage;
$early = ['check_in', 'waiting', null, ''];
$order = [
'check_in' => 0,
'history' => 1,
'exam' => 2,
'imaging' => 3,
'plan' => 4,
'procedure' => 5,
'completed' => 6,
];
if ($suggested && (! $current || in_array($current, $early, true))) {
try {
$stageService->setStage(
$organization,
$visit,
'orthopedics',
$suggested,
$this->ownerRef($request),
$this->ownerRef($request),
);
} catch (\InvalidArgumentException) {
}
} elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
try {
$stageService->setStage(
$organization,
$visit,
'orthopedics',
$suggested,
$this->ownerRef($request),
$this->ownerRef($request),
);
} catch (\InvalidArgumentException) {
}
}
}
if ($module === 'ent' && in_array($recordType, ['ent_history', 'ent_exam', 'ent_investigation', 'ent_plan'], true)) {
$workflow = app(\App\Services\Care\Ent\EntWorkflowService::class);
$stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
$suggested = match ($recordType) {
'ent_history' => $workflow->stageFromHistory($record->payload ?? []),
'ent_exam' => $workflow->stageFromExam($record->payload ?? []),
'ent_investigation' => $workflow->stageFromInvestigation($record->payload ?? []),
'ent_plan' => $workflow->stageFromPlan($record->payload ?? []),
default => null,
};
$current = $visit->specialty_stage;
$early = ['check_in', 'waiting', null, ''];
$order = [
'check_in' => 0,
'history' => 1,
'exam' => 2,
'investigation' => 3,
'plan' => 4,
'procedure' => 5,
'completed' => 6,
];
if ($suggested && (! $current || in_array($current, $early, true))) {
try {
$stageService->setStage(
$organization,
$visit,
'ent',
$suggested,
$this->ownerRef($request),
$this->ownerRef($request),
);
} catch (\InvalidArgumentException) {
}
} elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
try {
$stageService->setStage(
$organization,
$visit,
'ent',
$suggested,
$this->ownerRef($request),
$this->ownerRef($request),
);
} catch (\InvalidArgumentException) {
}
}
}
return redirect()
->route('care.specialty.workspace', [
'module' => $module,
@@ -1091,6 +1241,27 @@ class SpecialtyModuleController extends Controller
$psychiatryFollowup = null;
$psychiatryStageCodes = [];
$psychiatryStageFlow = [];
$pediatricsHistory = null;
$pediatricsExam = null;
$pediatricsInvestigation = null;
$pediatricsPlan = null;
$pediatricsTreatment = null;
$pediatricsStageCodes = [];
$pediatricsStageFlow = [];
$orthopedicsHistory = null;
$orthopedicsExam = null;
$orthopedicsImaging = null;
$orthopedicsPlan = null;
$orthopedicsProcedure = null;
$orthopedicsStageCodes = [];
$orthopedicsStageFlow = [];
$entHistory = null;
$entExam = null;
$entInvestigation = null;
$entPlan = null;
$entProcedure = null;
$entStageCodes = [];
$entStageFlow = [];
$activeTab = (string) $request->query('tab', array_key_first($shell->workspaceTabs($module)) ?: 'overview');
$clinical = app(SpecialtyClinicalRecordService::class);
@@ -1255,6 +1426,36 @@ class SpecialtyModuleController extends Controller
$psychiatryStageFlow = app(\App\Services\Care\Psychiatry\PsychiatryWorkflowService::class)->stageFlow();
}
if ($module === 'pediatrics') {
$pediatricsHistory = $clinical->findForVisit($workspaceVisit, 'pediatrics', 'ped_history');
$pediatricsExam = $clinical->findForVisit($workspaceVisit, 'pediatrics', 'pediatric_exam');
$pediatricsInvestigation = $clinical->findForVisit($workspaceVisit, 'pediatrics', 'ped_investigation');
$pediatricsPlan = $clinical->findForVisit($workspaceVisit, 'pediatrics', 'ped_plan');
$pediatricsTreatment = $clinical->findForVisit($workspaceVisit, 'pediatrics', 'ped_treatment');
$pediatricsStageCodes = collect($shell->stages('pediatrics'))->pluck('code')->all();
$pediatricsStageFlow = app(\App\Services\Care\Pediatrics\PediatricsWorkflowService::class)->stageFlow();
}
if ($module === 'orthopedics') {
$orthopedicsHistory = $clinical->findForVisit($workspaceVisit, 'orthopedics', 'ortho_history');
$orthopedicsExam = $clinical->findForVisit($workspaceVisit, 'orthopedics', 'ortho_exam');
$orthopedicsImaging = $clinical->findForVisit($workspaceVisit, 'orthopedics', 'ortho_imaging');
$orthopedicsPlan = $clinical->findForVisit($workspaceVisit, 'orthopedics', 'ortho_plan');
$orthopedicsProcedure = $clinical->findForVisit($workspaceVisit, 'orthopedics', 'ortho_procedure');
$orthopedicsStageCodes = collect($shell->stages('orthopedics'))->pluck('code')->all();
$orthopedicsStageFlow = app(\App\Services\Care\Orthopedics\OrthopedicsWorkflowService::class)->stageFlow();
}
if ($module === 'ent') {
$entHistory = $clinical->findForVisit($workspaceVisit, 'ent', 'ent_history');
$entExam = $clinical->findForVisit($workspaceVisit, 'ent', 'ent_exam');
$entInvestigation = $clinical->findForVisit($workspaceVisit, 'ent', 'ent_investigation');
$entPlan = $clinical->findForVisit($workspaceVisit, 'ent', 'ent_plan');
$entProcedure = $clinical->findForVisit($workspaceVisit, 'ent', 'ent_procedure');
$entStageCodes = collect($shell->stages('ent'))->pluck('code')->all();
$entStageFlow = app(\App\Services\Care\Ent\EntWorkflowService::class)->stageFlow();
}
if ($patientHeader !== null) {
$patientHeader['clinical_alerts'] = $clinicalAlerts;
}
@@ -1382,6 +1583,27 @@ class SpecialtyModuleController extends Controller
'psychiatryFollowup' => $psychiatryFollowup,
'psychiatryStageCodes' => $psychiatryStageCodes,
'psychiatryStageFlow' => $psychiatryStageFlow,
'pediatricsHistory' => $pediatricsHistory,
'pediatricsExam' => $pediatricsExam,
'pediatricsInvestigation' => $pediatricsInvestigation,
'pediatricsPlan' => $pediatricsPlan,
'pediatricsTreatment' => $pediatricsTreatment,
'pediatricsStageCodes' => $pediatricsStageCodes,
'pediatricsStageFlow' => $pediatricsStageFlow,
'orthopedicsHistory' => $orthopedicsHistory,
'orthopedicsExam' => $orthopedicsExam,
'orthopedicsImaging' => $orthopedicsImaging,
'orthopedicsPlan' => $orthopedicsPlan,
'orthopedicsProcedure' => $orthopedicsProcedure,
'orthopedicsStageCodes' => $orthopedicsStageCodes,
'orthopedicsStageFlow' => $orthopedicsStageFlow,
'entHistory' => $entHistory,
'entExam' => $entExam,
'entInvestigation' => $entInvestigation,
'entPlan' => $entPlan,
'entProcedure' => $entProcedure,
'entStageCodes' => $entStageCodes,
'entStageFlow' => $entStageFlow,
'queueStubs' => $modules->queueStubsFor($organization, $module),
'branchId' => $branchId,
'branchLabel' => $branchLabel,
+366
View File
@@ -1020,6 +1020,9 @@ class DemoTenantSeeder
$this->seedRadiologyClinicalDemo($organization, $ownerRef);
$this->seedCardiologyClinicalDemo($organization, $ownerRef);
$this->seedPsychiatryClinicalDemo($organization, $ownerRef);
$this->seedPediatricsClinicalDemo($organization, $ownerRef);
$this->seedOrthopedicsClinicalDemo($organization, $ownerRef);
$this->seedEntClinicalDemo($organization, $ownerRef);
return $count;
}
@@ -1856,6 +1859,369 @@ class DemoTenantSeeder
}
}
private function seedPediatricsClinicalDemo(Organization $organization, string $ownerRef): void
{
$branchIds = Branch::owned($ownerRef)
->where('organization_id', $organization->id)
->pluck('id');
if ($branchIds->isEmpty()) {
return;
}
$departmentIds = Department::owned($ownerRef)
->whereIn('branch_id', $branchIds)
->where('type', 'pediatrics')
->where('is_active', true)
->pluck('id');
if ($departmentIds->isEmpty()) {
return;
}
$appointments = Appointment::owned($ownerRef)
->where('organization_id', $organization->id)
->whereIn('department_id', $departmentIds)
->whereIn('status', [Appointment::STATUS_WAITING, Appointment::STATUS_CHECKED_IN])
->whereNotNull('visit_id')
->with('visit')
->orderBy('branch_id')
->orderBy('id')
->get();
if ($appointments->isEmpty()) {
return;
}
$clinical = app(SpecialtyClinicalRecordService::class);
$index = 0;
foreach ($appointments as $appointment) {
$visit = $appointment->visit;
if (! $visit) {
continue;
}
$highRisk = $index === 0;
$clinical->upsert(
$organization,
$visit,
'pediatrics',
'ped_history',
[
'history' => $highRisk
? 'Fever and poor feeding for 3 days; reduced urine output'
: 'Mild cough for 1 week; eating well',
'birth_history' => $highRisk ? 'Term; birth weight 2.8 kg' : 'Term; uneventful',
'past_medical' => $highRisk ? 'Prior admission for pneumonia' : 'None',
'medications' => 'None',
'allergies' => 'NKDA',
'feeding' => $highRisk ? 'Breast + formula; intake reduced' : 'Age-appropriate diet',
'social' => 'Lives with parents',
],
$ownerRef,
$ownerRef,
'history',
);
$clinical->upsert(
$organization,
$visit,
'pediatrics',
'pediatric_exam',
[
'chief_complaint' => $highRisk ? 'Fever / possible sepsis' : 'Cough review',
'age_months' => $highRisk ? 18 : 48,
'weight_kg' => $highRisk ? 8.2 : 16.5,
'height_cm' => $highRisk ? 76 : 102,
'head_circumference_cm' => $highRisk ? 45 : null,
'temperature_c' => $highRisk ? 39.2 : 36.8,
'growth_concern' => $highRisk ? 'Underweight' : 'None',
'developmental' => $highRisk ? 'Walks; few words' : 'Age-appropriate',
'immunization_status' => $highRisk ? 'Up to date except measles' : 'Up to date',
'examination' => $highRisk
? 'Irritable; mild dehydration; clear chest; no rash'
: 'Well; mild rhinitis; chest clear',
],
$ownerRef,
$ownerRef,
'exam',
);
if ($highRisk) {
$clinical->upsert(
$organization,
$visit,
'pediatrics',
'ped_plan',
[
'diagnosis' => 'Febrile illness — rule out serious bacterial infection',
'plan' => 'Labs; oral fluids; antipyretic; review same day if worse',
'medications' => 'Paracetamol PRN',
'treatment_planned' => true,
'follow_up' => '24 hours or sooner if red flags',
'advice' => 'Hydration; fever advice; return if lethargy or poor feeding',
],
$ownerRef,
$ownerRef,
'plan',
);
}
if (! $visit->specialty_stage) {
$visit->update(['specialty_stage' => $highRisk ? 'plan' : 'exam']);
}
$index++;
}
}
private function seedOrthopedicsClinicalDemo(Organization $organization, string $ownerRef): void
{
$branchIds = Branch::owned($ownerRef)
->where('organization_id', $organization->id)
->pluck('id');
if ($branchIds->isEmpty()) {
return;
}
$departmentIds = Department::owned($ownerRef)
->whereIn('branch_id', $branchIds)
->where('type', 'orthopedics')
->where('is_active', true)
->pluck('id');
if ($departmentIds->isEmpty()) {
return;
}
$appointments = Appointment::owned($ownerRef)
->where('organization_id', $organization->id)
->whereIn('department_id', $departmentIds)
->whereIn('status', [Appointment::STATUS_WAITING, Appointment::STATUS_CHECKED_IN])
->whereNotNull('visit_id')
->with('visit')
->orderBy('branch_id')
->orderBy('id')
->get();
if ($appointments->isEmpty()) {
return;
}
$clinical = app(SpecialtyClinicalRecordService::class);
$index = 0;
foreach ($appointments as $appointment) {
$visit = $appointment->visit;
if (! $visit) {
continue;
}
$highRisk = $index === 0;
$clinical->upsert(
$organization,
$visit,
'orthopedics',
'ortho_history',
[
'history' => $highRisk
? 'Fall from height; right wrist pain and deformity'
: 'Left knee pain after football twist',
'mechanism' => $highRisk ? 'FOOSH from ladder' : 'Twisting injury',
'past_ortho' => $highRisk ? 'Prior ankle sprain' : 'None',
'medications' => 'None',
'allergies' => 'NKDA',
'comorbidities' => $highRisk ? 'Diabetes' : 'None',
],
$ownerRef,
$ownerRef,
'history',
);
$clinical->upsert(
$organization,
$visit,
'orthopedics',
'ortho_exam',
[
'chief_complaint' => $highRisk ? 'Wrist deformity after fall' : 'Knee pain',
'side' => $highRisk ? 'Right' : 'Left',
'region' => $highRisk ? 'Distal radius' : 'Knee',
'rom' => $highRisk ? 'Limited wrist flexion/extension' : 'Full ROM; pain on twist',
'neurovascular' => $highRisk ? 'Sensory deficit' : 'Intact',
'swelling' => $highRisk ? 'Dinner-fork deformity' : 'Mild effusion',
'exam_findings' => $highRisk ? 'Closed injury; soft compartments' : 'McMurray negative; stable ligaments',
'fracture_classification' => $highRisk ? 'Colles-type distal radius' : 'Soft tissue strain',
],
$ownerRef,
$ownerRef,
'exam',
);
if ($highRisk) {
$clinical->upsert(
$organization,
$visit,
'orthopedics',
'ortho_imaging',
[
'modality' => 'X-ray',
'region' => 'Right wrist',
'findings' => 'Displaced distal radius fracture; ulnar styloid intact',
'impression' => 'Extra-articular distal radius fracture',
'notes' => 'AP and lateral views',
],
$ownerRef,
$ownerRef,
'imaging',
);
$clinical->upsert(
$organization,
$visit,
'orthopedics',
'ortho_plan',
[
'diagnosis' => 'Displaced distal radius fracture',
'plan' => 'Closed reduction and cast; elevate; analgesia',
'weight_bearing' => 'N/A — upper limb',
'procedure_planned' => true,
'follow_up' => '1 week with cast check / x-ray',
'advice' => 'Elevation; watch for numbness or colour change',
],
$ownerRef,
$ownerRef,
'plan',
);
}
if (! $visit->specialty_stage) {
$visit->update(['specialty_stage' => $highRisk ? 'plan' : 'exam']);
}
$index++;
}
}
private function seedEntClinicalDemo(Organization $organization, string $ownerRef): void
{
$branchIds = Branch::owned($ownerRef)
->where('organization_id', $organization->id)
->pluck('id');
if ($branchIds->isEmpty()) {
return;
}
$departmentIds = Department::owned($ownerRef)
->whereIn('branch_id', $branchIds)
->where('type', 'ent')
->where('is_active', true)
->pluck('id');
if ($departmentIds->isEmpty()) {
return;
}
$appointments = Appointment::owned($ownerRef)
->where('organization_id', $organization->id)
->whereIn('department_id', $departmentIds)
->whereIn('status', [Appointment::STATUS_WAITING, Appointment::STATUS_CHECKED_IN])
->whereNotNull('visit_id')
->with('visit')
->orderBy('branch_id')
->orderBy('id')
->get();
if ($appointments->isEmpty()) {
return;
}
$clinical = app(SpecialtyClinicalRecordService::class);
$index = 0;
foreach ($appointments as $appointment) {
$visit = $appointment->visit;
if (! $visit) {
continue;
}
$highRisk = $index === 0;
$clinical->upsert(
$organization,
$visit,
'ent',
'ent_history',
[
'history' => $highRisk
? 'Progressive sore throat and muffled voice; difficulty swallowing'
: 'Recurrent ear discharge for 2 months',
'ear_symptoms' => $highRisk ? 'None' : 'Left otorrhoea; mild hearing loss',
'nose_symptoms' => 'None',
'throat_symptoms' => $highRisk ? 'Severe odynophagia; drooling' : 'None',
'past_ent' => $highRisk ? 'Prior tonsillitis' : 'Recurrent otitis media',
'medications' => $highRisk ? 'None recent' : 'Topical drops PRN',
'allergies' => 'NKDA',
],
$ownerRef,
$ownerRef,
'history',
);
$clinical->upsert(
$organization,
$visit,
'ent',
'ent_exam',
[
'chief_complaint' => $highRisk ? 'Sore throat / possible peritonsillar abscess' : 'Chronic ear discharge',
'ear_findings' => $highRisk ? 'Normal TMs' : 'Left canal moist; TM perforated',
'nose_findings' => 'Normal',
'throat_findings' => $highRisk
? 'Trismus; unilateral tonsillar bulge; uvula deviation'
: 'Oropharynx normal',
'hearing' => $highRisk ? 'Grossly normal' : 'Reduced left whispered voice',
'neck' => $highRisk ? 'Tender cervical nodes' : 'No lymphadenopathy',
'airway_concern' => $highRisk,
'exam_summary' => $highRisk
? 'Findings consistent with peritonsillar abscess — airway vigilance'
: 'Chronic otitis media with perforation',
],
$ownerRef,
$ownerRef,
'exam',
);
if ($highRisk) {
$clinical->upsert(
$organization,
$visit,
'ent',
'ent_plan',
[
'diagnosis' => 'Suspected peritonsillar abscess',
'plan' => 'IV antibiotics; needle aspiration / I&D; airway monitoring',
'medications' => 'IV antibiotics per protocol; analgesia',
'procedure_planned' => true,
'follow_up' => 'Inpatient review post-drainage',
'advice' => 'NPO until airway safe; urgent escalation if stridor',
],
$ownerRef,
$ownerRef,
'plan',
);
}
if (! $visit->specialty_stage) {
$visit->update(['specialty_stage' => $highRisk ? 'plan' : 'exam']);
}
$index++;
}
}
private function seedDentistryClinicalDemo(Organization $organization, string $ownerRef): void
{
// Specialty departments are provisioned without organization_id; scope via branches.
@@ -0,0 +1,164 @@
<?php
namespace App\Services\Care\Ent;
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 EntAnalyticsService
{
public function __construct(
protected SpecialtyShellService $shell,
) {}
/**
* @return array{
* arrivals_today: int,
* completed_today: int,
* airway_open: int,
* diagnosis_breakdown: Collection,
* procedure_breakdown: Collection,
* avg_los_minutes: ?float,
* revenue_by_service: Collection,
* from: string,
* to: string
* }
*/
public function report(
Organization $organization,
string $ownerRef,
?int $branchId = null,
?string $from = null,
?string $to = null,
): array {
$todayStart = now()->startOfDay();
$rangeFrom = $from ? Carbon::parse($from)->startOfDay() : now()->startOfMonth();
$rangeTo = $to ? Carbon::parse($to)->endOfDay() : now()->endOfDay();
$departmentIds = $this->shell->departmentIds($organization, 'ent', $ownerRef, $branchId);
$appointmentBase = Appointment::owned($ownerRef)
->where('organization_id', $organization->id)
->when($departmentIds !== [], fn ($q) => $q->whereIn('department_id', $departmentIds))
->when($departmentIds === [], fn ($q) => $q->whereRaw('1 = 0'))
->when($branchId, fn ($q) => $q->where('branch_id', $branchId));
$arrivalsToday = (clone $appointmentBase)
->where('checked_in_at', '>=', $todayStart)
->count();
$completedToday = (clone $appointmentBase)
->where('status', Appointment::STATUS_COMPLETED)
->where('completed_at', '>=', $todayStart)
->count();
$visitIds = (clone $appointmentBase)->whereNotNull('visit_id')->pluck('visit_id');
$openVisitIds = Visit::owned($ownerRef)
->where('organization_id', $organization->id)
->whereIn('id', $visitIds->isEmpty() ? [0] : $visitIds)
->whereIn('status', [Visit::STATUS_OPEN, Visit::STATUS_IN_PROGRESS])
->pluck('id');
$airwayOpen = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'ent')
->where('record_type', 'ent_exam')
->whereIn('visit_id', $openVisitIds->isEmpty() ? [0] : $openVisitIds)
->get()
->filter(fn (SpecialtyClinicalRecord $r) => ! empty($r->payload['airway_concern']))
->count();
$planRecords = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'ent')
->where('record_type', 'ent_plan')
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
->get();
$diagnosisBreakdown = $planRecords
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['diagnosis'] ?? 'Unknown'))
->map(fn (Collection $rows, string $diagnosis) => [
'diagnosis' => $diagnosis,
'total' => $rows->count(),
])
->values()
->sortByDesc('total')
->values();
$procedureRecords = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'ent')
->where('record_type', 'ent_procedure')
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
->get();
$procedureBreakdown = $procedureRecords
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['procedure'] ?? 'Unknown'))
->map(fn (Collection $rows, string $procedure) => [
'procedure' => $procedure,
'total' => $rows->count(),
])
->values()
->sortByDesc('total')
->values();
$completedVisits = Visit::owned($ownerRef)
->where('organization_id', $organization->id)
->whereIn('id', $visitIds->isEmpty() ? [0] : $visitIds)
->where('status', Visit::STATUS_COMPLETED)
->whereBetween('completed_at', [$rangeFrom, $rangeTo])
->whereNotNull('checked_in_at')
->whereNotNull('completed_at')
->get();
$avgLos = null;
if ($completedVisits->isNotEmpty()) {
$avgLos = round($completedVisits->avg(function (Visit $visit) {
return $visit->checked_in_at->diffInMinutes($visit->completed_at);
}), 1);
}
$serviceLabels = collect($this->shell->provisionedServices($organization, 'ent'))
->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,
'airway_open' => $airwayOpen,
'diagnosis_breakdown' => $diagnosisBreakdown,
'procedure_breakdown' => $procedureBreakdown,
'avg_los_minutes' => $avgLos,
'revenue_by_service' => $revenueByService,
'from' => $rangeFrom->toDateString(),
'to' => $rangeTo->toDateString(),
];
}
}
@@ -0,0 +1,107 @@
<?php
namespace App\Services\Care\Ent;
/**
* Map ENT clinical progress onto visit stages.
*/
class EntWorkflowService
{
public const STAGE_CHECK_IN = 'check_in';
public const STAGE_HISTORY = 'history';
public const STAGE_EXAM = 'exam';
public const STAGE_INVESTIGATION = 'investigation';
public const STAGE_PLAN = 'plan';
public const STAGE_PROCEDURE = 'procedure';
public const STAGE_COMPLETED = 'completed';
/**
* @param array<string, mixed> $payload
*/
public function stageFromHistory(array $payload): string
{
$history = trim((string) ($payload['history'] ?? ''));
if ($history !== '') {
return self::STAGE_HISTORY;
}
return self::STAGE_CHECK_IN;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromExam(array $payload): string
{
if (! empty($payload['chief_complaint'])
|| ! empty($payload['ear_findings'])
|| ! empty($payload['nose_findings'])
|| ! empty($payload['throat_findings'])) {
return self::STAGE_EXAM;
}
return self::STAGE_HISTORY;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromInvestigation(array $payload): string
{
$findings = trim((string) ($payload['findings'] ?? ''));
if ($findings !== '') {
return self::STAGE_INVESTIGATION;
}
return self::STAGE_EXAM;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromPlan(array $payload): string
{
if (! empty($payload['procedure_planned'])) {
return self::STAGE_PROCEDURE;
}
$plan = trim((string) ($payload['plan'] ?? ''));
if ($plan !== '') {
return self::STAGE_PLAN;
}
return self::STAGE_INVESTIGATION;
}
/**
* @param array<string, mixed> $payload
*/
public function shouldCompleteVisit(array $payload): bool
{
$outcome = strtolower((string) ($payload['outcome'] ?? ''));
return str_contains($outcome, 'completed');
}
/**
* @return array<string, array{next: string, label: string}>
*/
public function stageFlow(): array
{
return [
self::STAGE_CHECK_IN => ['next' => self::STAGE_HISTORY, 'label' => 'Start history'],
self::STAGE_HISTORY => ['next' => self::STAGE_EXAM, 'label' => 'Move to exam'],
self::STAGE_EXAM => ['next' => self::STAGE_INVESTIGATION, 'label' => 'Move to investigations'],
self::STAGE_INVESTIGATION => ['next' => self::STAGE_PLAN, 'label' => 'Move to diagnosis & plan'],
self::STAGE_PLAN => ['next' => self::STAGE_PROCEDURE, 'label' => 'Move to procedure'],
self::STAGE_PROCEDURE => ['next' => self::STAGE_COMPLETED, 'label' => 'Complete visit'],
self::STAGE_COMPLETED => ['next' => self::STAGE_COMPLETED, 'label' => 'Completed'],
];
}
}
@@ -0,0 +1,168 @@
<?php
namespace App\Services\Care\Orthopedics;
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 OrthopedicsAnalyticsService
{
public function __construct(
protected SpecialtyShellService $shell,
) {}
/**
* @return array{
* arrivals_today: int,
* completed_today: int,
* nv_compromise_open: int,
* diagnosis_breakdown: Collection,
* procedure_breakdown: Collection,
* avg_los_minutes: ?float,
* revenue_by_service: Collection,
* from: string,
* to: string
* }
*/
public function report(
Organization $organization,
string $ownerRef,
?int $branchId = null,
?string $from = null,
?string $to = null,
): array {
$todayStart = now()->startOfDay();
$rangeFrom = $from ? Carbon::parse($from)->startOfDay() : now()->startOfMonth();
$rangeTo = $to ? Carbon::parse($to)->endOfDay() : now()->endOfDay();
$departmentIds = $this->shell->departmentIds($organization, 'orthopedics', $ownerRef, $branchId);
$appointmentBase = Appointment::owned($ownerRef)
->where('organization_id', $organization->id)
->when($departmentIds !== [], fn ($q) => $q->whereIn('department_id', $departmentIds))
->when($departmentIds === [], fn ($q) => $q->whereRaw('1 = 0'))
->when($branchId, fn ($q) => $q->where('branch_id', $branchId));
$arrivalsToday = (clone $appointmentBase)
->where('checked_in_at', '>=', $todayStart)
->count();
$completedToday = (clone $appointmentBase)
->where('status', Appointment::STATUS_COMPLETED)
->where('completed_at', '>=', $todayStart)
->count();
$visitIds = (clone $appointmentBase)->whereNotNull('visit_id')->pluck('visit_id');
$openVisitIds = Visit::owned($ownerRef)
->where('organization_id', $organization->id)
->whereIn('id', $visitIds->isEmpty() ? [0] : $visitIds)
->whereIn('status', [Visit::STATUS_OPEN, Visit::STATUS_IN_PROGRESS])
->pluck('id');
$nvCompromiseOpen = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'orthopedics')
->where('record_type', 'ortho_exam')
->whereIn('visit_id', $openVisitIds->isEmpty() ? [0] : $openVisitIds)
->get()
->filter(function (SpecialtyClinicalRecord $r) {
$nv = strtolower((string) ($r->payload['neurovascular'] ?? ''));
return str_contains($nv, 'deficit') || str_contains($nv, 'compromise');
})
->count();
$planRecords = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'orthopedics')
->where('record_type', 'ortho_plan')
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
->get();
$diagnosisBreakdown = $planRecords
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['diagnosis'] ?? 'Unknown'))
->map(fn (Collection $rows, string $diagnosis) => [
'diagnosis' => $diagnosis,
'total' => $rows->count(),
])
->values()
->sortByDesc('total')
->values();
$procedureRecords = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'orthopedics')
->where('record_type', 'ortho_procedure')
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
->get();
$procedureBreakdown = $procedureRecords
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['procedure'] ?? 'Unknown'))
->map(fn (Collection $rows, string $procedure) => [
'procedure' => $procedure,
'total' => $rows->count(),
])
->values()
->sortByDesc('total')
->values();
$completedVisits = Visit::owned($ownerRef)
->where('organization_id', $organization->id)
->whereIn('id', $visitIds->isEmpty() ? [0] : $visitIds)
->where('status', Visit::STATUS_COMPLETED)
->whereBetween('completed_at', [$rangeFrom, $rangeTo])
->whereNotNull('checked_in_at')
->whereNotNull('completed_at')
->get();
$avgLos = null;
if ($completedVisits->isNotEmpty()) {
$avgLos = round($completedVisits->avg(function (Visit $visit) {
return $visit->checked_in_at->diffInMinutes($visit->completed_at);
}), 1);
}
$serviceLabels = collect($this->shell->provisionedServices($organization, 'orthopedics'))
->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,
'nv_compromise_open' => $nvCompromiseOpen,
'diagnosis_breakdown' => $diagnosisBreakdown,
'procedure_breakdown' => $procedureBreakdown,
'avg_los_minutes' => $avgLos,
'revenue_by_service' => $revenueByService,
'from' => $rangeFrom->toDateString(),
'to' => $rangeTo->toDateString(),
];
}
}
@@ -0,0 +1,104 @@
<?php
namespace App\Services\Care\Orthopedics;
/**
* Map orthopedics clinical progress onto visit stages.
*/
class OrthopedicsWorkflowService
{
public const STAGE_CHECK_IN = 'check_in';
public const STAGE_HISTORY = 'history';
public const STAGE_EXAM = 'exam';
public const STAGE_IMAGING = 'imaging';
public const STAGE_PLAN = 'plan';
public const STAGE_PROCEDURE = 'procedure';
public const STAGE_COMPLETED = 'completed';
/**
* @param array<string, mixed> $payload
*/
public function stageFromHistory(array $payload): string
{
$history = trim((string) ($payload['history'] ?? ''));
if ($history !== '') {
return self::STAGE_HISTORY;
}
return self::STAGE_CHECK_IN;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromExam(array $payload): string
{
if (! empty($payload['region']) || ! empty($payload['chief_complaint'])) {
return self::STAGE_EXAM;
}
return self::STAGE_HISTORY;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromImaging(array $payload): string
{
$findings = trim((string) ($payload['findings'] ?? ''));
if ($findings !== '') {
return self::STAGE_IMAGING;
}
return self::STAGE_EXAM;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromPlan(array $payload): string
{
if (! empty($payload['procedure_planned'])) {
return self::STAGE_PROCEDURE;
}
$plan = trim((string) ($payload['plan'] ?? ''));
if ($plan !== '') {
return self::STAGE_PLAN;
}
return self::STAGE_IMAGING;
}
/**
* @param array<string, mixed> $payload
*/
public function shouldCompleteVisit(array $payload): bool
{
$outcome = strtolower((string) ($payload['outcome'] ?? ''));
return str_contains($outcome, 'completed');
}
/**
* @return array<string, array{next: string, label: string}>
*/
public function stageFlow(): array
{
return [
self::STAGE_CHECK_IN => ['next' => self::STAGE_HISTORY, 'label' => 'Start history'],
self::STAGE_HISTORY => ['next' => self::STAGE_EXAM, 'label' => 'Move to exam'],
self::STAGE_EXAM => ['next' => self::STAGE_IMAGING, 'label' => 'Move to imaging'],
self::STAGE_IMAGING => ['next' => self::STAGE_PLAN, 'label' => 'Move to diagnosis & plan'],
self::STAGE_PLAN => ['next' => self::STAGE_PROCEDURE, 'label' => 'Move to procedure / cast'],
self::STAGE_PROCEDURE => ['next' => self::STAGE_COMPLETED, 'label' => 'Complete visit'],
self::STAGE_COMPLETED => ['next' => self::STAGE_COMPLETED, 'label' => 'Completed'],
];
}
}
@@ -0,0 +1,168 @@
<?php
namespace App\Services\Care\Pediatrics;
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 PediatricsAnalyticsService
{
public function __construct(
protected SpecialtyShellService $shell,
) {}
/**
* @return array{
* arrivals_today: int,
* completed_today: int,
* growth_concern_open: int,
* diagnosis_breakdown: Collection,
* treatment_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, 'pediatrics', $ownerRef, $branchId);
$appointmentBase = Appointment::owned($ownerRef)
->where('organization_id', $organization->id)
->when($departmentIds !== [], fn ($q) => $q->whereIn('department_id', $departmentIds))
->when($departmentIds === [], fn ($q) => $q->whereRaw('1 = 0'))
->when($branchId, fn ($q) => $q->where('branch_id', $branchId));
$arrivalsToday = (clone $appointmentBase)
->where('checked_in_at', '>=', $todayStart)
->count();
$completedToday = (clone $appointmentBase)
->where('status', Appointment::STATUS_COMPLETED)
->where('completed_at', '>=', $todayStart)
->count();
$visitIds = (clone $appointmentBase)->whereNotNull('visit_id')->pluck('visit_id');
$openVisitIds = Visit::owned($ownerRef)
->where('organization_id', $organization->id)
->whereIn('id', $visitIds->isEmpty() ? [0] : $visitIds)
->whereIn('status', [Visit::STATUS_OPEN, Visit::STATUS_IN_PROGRESS])
->pluck('id');
$growthConcernOpen = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'pediatrics')
->where('record_type', 'pediatric_exam')
->whereIn('visit_id', $openVisitIds->isEmpty() ? [0] : $openVisitIds)
->get()
->filter(function (SpecialtyClinicalRecord $r) {
$concern = (string) ($r->payload['growth_concern'] ?? '');
return $concern !== '' && $concern !== 'None';
})
->count();
$planRecords = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'pediatrics')
->where('record_type', 'ped_plan')
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
->get();
$diagnosisBreakdown = $planRecords
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['diagnosis'] ?? 'Unknown'))
->map(fn (Collection $rows, string $diagnosis) => [
'diagnosis' => $diagnosis,
'total' => $rows->count(),
])
->values()
->sortByDesc('total')
->values();
$treatmentRecords = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'pediatrics')
->where('record_type', 'ped_treatment')
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
->get();
$treatmentBreakdown = $treatmentRecords
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['treatment'] ?? 'Unknown'))
->map(fn (Collection $rows, string $treatment) => [
'treatment' => $treatment,
'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, 'pediatrics'))
->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,
'growth_concern_open' => $growthConcernOpen,
'diagnosis_breakdown' => $diagnosisBreakdown,
'treatment_breakdown' => $treatmentBreakdown,
'avg_los_minutes' => $avgLos,
'revenue_by_service' => $revenueByService,
'from' => $rangeFrom->toDateString(),
'to' => $rangeTo->toDateString(),
];
}
}
@@ -0,0 +1,104 @@
<?php
namespace App\Services\Care\Pediatrics;
/**
* Map pediatrics clinical progress onto visit stages.
*/
class PediatricsWorkflowService
{
public const STAGE_CHECK_IN = 'check_in';
public const STAGE_HISTORY = 'history';
public const STAGE_EXAM = 'exam';
public const STAGE_INVESTIGATION = 'investigation';
public const STAGE_PLAN = 'plan';
public const STAGE_TREATMENT = 'treatment';
public const STAGE_COMPLETED = 'completed';
/**
* @param array<string, mixed> $payload
*/
public function stageFromHistory(array $payload): string
{
$history = trim((string) ($payload['history'] ?? ''));
if ($history !== '') {
return self::STAGE_HISTORY;
}
return self::STAGE_CHECK_IN;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromExam(array $payload): string
{
if (! empty($payload['examination']) || ! empty($payload['chief_complaint'])) {
return self::STAGE_EXAM;
}
return self::STAGE_HISTORY;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromInvestigation(array $payload): string
{
$findings = trim((string) ($payload['findings'] ?? ''));
if ($findings !== '') {
return self::STAGE_INVESTIGATION;
}
return self::STAGE_EXAM;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromPlan(array $payload): string
{
if (! empty($payload['treatment_planned'])) {
return self::STAGE_TREATMENT;
}
$plan = trim((string) ($payload['plan'] ?? ''));
if ($plan !== '') {
return self::STAGE_PLAN;
}
return self::STAGE_INVESTIGATION;
}
/**
* @param array<string, mixed> $payload
*/
public function shouldCompleteVisit(array $payload): bool
{
$outcome = strtolower((string) ($payload['outcome'] ?? ''));
return str_contains($outcome, 'completed');
}
/**
* @return array<string, array{next: string, label: string}>
*/
public function stageFlow(): array
{
return [
self::STAGE_CHECK_IN => ['next' => self::STAGE_HISTORY, 'label' => 'Start history'],
self::STAGE_HISTORY => ['next' => self::STAGE_EXAM, 'label' => 'Move to exam / growth'],
self::STAGE_EXAM => ['next' => self::STAGE_INVESTIGATION, 'label' => 'Move to investigations'],
self::STAGE_INVESTIGATION => ['next' => self::STAGE_PLAN, 'label' => 'Move to diagnosis & plan'],
self::STAGE_PLAN => ['next' => self::STAGE_TREATMENT, 'label' => 'Move to treatment'],
self::STAGE_TREATMENT => ['next' => self::STAGE_COMPLETED, 'label' => 'Complete visit'],
self::STAGE_COMPLETED => ['next' => self::STAGE_COMPLETED, 'label' => 'Completed'],
];
}
}
@@ -419,6 +419,58 @@ class SpecialtyClinicalRecordService
}
}
if ($moduleKey === 'pediatrics' && $recordType === 'pediatric_exam') {
$concern = (string) ($payload['growth_concern'] ?? '');
if ($concern !== '' && $concern !== 'None') {
$alerts[] = [
'code' => 'ped.growth_concern',
'severity' => in_array($concern, ['Wasting', 'Underweight'], true) ? 'critical' : 'warning',
'message' => 'Growth concern: '.$concern.'.',
];
}
$temp = (float) ($payload['temperature_c'] ?? 0);
if ($temp >= 39.0) {
$alerts[] = [
'code' => 'ped.fever_high',
'severity' => 'critical',
'message' => 'High fever recorded ('.$temp.'°C).',
];
} elseif ($temp >= 38.0) {
$alerts[] = [
'code' => 'ped.fever',
'severity' => 'warning',
'message' => 'Fever recorded ('.$temp.'°C).',
];
}
}
if ($moduleKey === 'orthopedics' && $recordType === 'ortho_exam') {
$nv = strtolower((string) ($payload['neurovascular'] ?? ''));
if (str_contains($nv, 'vascular compromise')) {
$alerts[] = [
'code' => 'ort.nv_vascular',
'severity' => 'critical',
'message' => 'Vascular compromise on ortho exam.',
];
} elseif (str_contains($nv, 'deficit')) {
$alerts[] = [
'code' => 'ort.nv_deficit',
'severity' => 'warning',
'message' => 'Neurovascular deficit recorded.',
];
}
}
if ($moduleKey === 'ent' && $recordType === 'ent_exam') {
if (! empty($payload['airway_concern'])) {
$alerts[] = [
'code' => 'ent.airway_concern',
'severity' => 'critical',
'message' => 'Airway concern flagged on ENT exam.',
];
}
}
if ($moduleKey === 'psychiatry' && $recordType === 'risk_assessment') {
$level = strtolower((string) ($payload['overall_risk'] ?? ''));
if (str_contains($level, 'imminent')) {
+13 -1
View File
@@ -17,6 +17,9 @@ use App\Services\Care\Maternity\MaternityWorkflowService;
use App\Services\Care\Radiology\RadiologyWorkflowService;
use App\Services\Care\Cardiology\CardiologyWorkflowService;
use App\Services\Care\Psychiatry\PsychiatryWorkflowService;
use App\Services\Care\Pediatrics\PediatricsWorkflowService;
use App\Services\Care\Orthopedics\OrthopedicsWorkflowService;
use App\Services\Care\Ent\EntWorkflowService;
use Illuminate\Support\Collection;
/**
@@ -66,6 +69,9 @@ class SpecialtyShellService
'radiology' => 'care.specialty.radiology.stage',
'cardiology' => 'care.specialty.cardiology.stage',
'psychiatry' => 'care.specialty.psychiatry.stage',
'pediatrics' => 'care.specialty.pediatrics.stage',
'orthopedics' => 'care.specialty.orthopedics.stage',
'ent' => 'care.specialty.ent.stage',
default => null,
};
}
@@ -86,6 +92,9 @@ class SpecialtyShellService
'radiology' => app(RadiologyWorkflowService::class)->stageFlow(),
'cardiology' => app(CardiologyWorkflowService::class)->stageFlow(),
'psychiatry' => app(PsychiatryWorkflowService::class)->stageFlow(),
'pediatrics' => app(PediatricsWorkflowService::class)->stageFlow(),
'orthopedics' => app(OrthopedicsWorkflowService::class)->stageFlow(),
'ent' => app(EntWorkflowService::class)->stageFlow(),
'dentistry' => [
'waiting' => ['next' => 'chair', 'label' => 'Seat at chair'],
'chair' => ['next' => 'procedure', 'label' => 'Start procedure'],
@@ -385,7 +394,7 @@ class SpecialtyShellService
) {
$code = (string) ($stage['code'] ?? '');
if (in_array($moduleKey, ['dentistry', 'emergency', 'blood_bank', 'ophthalmology', 'physiotherapy', 'maternity', 'radiology', 'cardiology', 'psychiatry'], true) && $visitIds->isNotEmpty()) {
if (in_array($moduleKey, ['dentistry', 'emergency', 'blood_bank', 'ophthalmology', 'physiotherapy', 'maternity', 'radiology', 'cardiology', 'psychiatry', 'pediatrics', 'orthopedics', 'ent'], true) && $visitIds->isNotEmpty()) {
$count = Visit::owned($ownerRef)
->where('organization_id', $organization->id)
->whereIn('id', $visitIds)
@@ -421,6 +430,9 @@ class SpecialtyShellService
'radiology' => $clinical->countOpenByType($organization, 'radiology', 'imaging_request', $branchScope),
'cardiology' => $clinical->countOpenByType($organization, 'cardiology', 'cardiac_exam', $branchScope),
'psychiatry' => $clinical->countOpenByType($organization, 'psychiatry', 'mental_status', $branchScope),
'pediatrics' => $clinical->countOpenByType($organization, 'pediatrics', 'pediatric_exam', $branchScope),
'orthopedics' => $clinical->countOpenByType($organization, 'orthopedics', 'ortho_exam', $branchScope),
'ent' => $clinical->countOpenByType($organization, 'ent', 'ent_exam', $branchScope),
'dentistry' => \App\Models\DentalPlanItem::query()
->whereHas('plan', function ($q) use ($organization, $ownerRef) {
$q->owned($ownerRef)
@@ -144,6 +144,30 @@ class SpecialtyVisitStageService
: ($stages[1] ?? ($stages[0] ?? null));
}
if ($moduleKey === 'pediatrics') {
$stages = $this->allowedStages($moduleKey);
return in_array(\App\Services\Care\Pediatrics\PediatricsWorkflowService::STAGE_HISTORY, $stages, true)
? \App\Services\Care\Pediatrics\PediatricsWorkflowService::STAGE_HISTORY
: ($stages[1] ?? ($stages[0] ?? null));
}
if ($moduleKey === 'orthopedics') {
$stages = $this->allowedStages($moduleKey);
return in_array(\App\Services\Care\Orthopedics\OrthopedicsWorkflowService::STAGE_HISTORY, $stages, true)
? \App\Services\Care\Orthopedics\OrthopedicsWorkflowService::STAGE_HISTORY
: ($stages[1] ?? ($stages[0] ?? null));
}
if ($moduleKey === 'ent') {
$stages = $this->allowedStages($moduleKey);
return in_array(\App\Services\Care\Ent\EntWorkflowService::STAGE_HISTORY, $stages, true)
? \App\Services\Care\Ent\EntWorkflowService::STAGE_HISTORY
: ($stages[1] ?? ($stages[0] ?? null));
}
$stages = $this->allowedStages($moduleKey);
foreach (['chair', 'in_care', 'exam', 'assessment', 'treatment'] as $preferred) {
if (in_array($preferred, $stages, true)) {