Add full Ambulance and Child Welfare specialty clinical suites.
Deploy Ladill Care / deploy (push) Successful in 54s

EMS clinic workflow (dispatch → scene → transport → handover) plus completed CWC suite, with shell stages, clinical records, reports/print, demo seed, and suite tests.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
isaacclad
2026-07-19 22:25:52 +00:00
co-authored by Cursor
parent 8c18ecc5c9
commit c0e5d8ef00
32 changed files with 2672 additions and 22 deletions
@@ -0,0 +1,214 @@
<?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\Ambulance\AmbulanceAnalyticsService;
use App\Services\Care\Ambulance\AmbulanceWorkflowService;
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 AmbulanceWorkspaceController extends Controller
{
use ScopesToAccount;
protected function assertAmbulanceAccess(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanAccess($organization, $this->member($request), 'ambulance'), 403);
}
protected function assertAmbulanceManage(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanManage($organization, $this->member($request), 'ambulance'), 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->assertAmbulanceManage($request, $modules);
$this->assertVisit($request, $visit);
$validated = $request->validate([
'stage' => ['required', 'string', 'max:32'],
]);
try {
$stages->setStage(
$this->organization($request),
$visit,
'ambulance',
$validated['stage'],
$this->ownerRef($request),
$this->actorRef($request),
);
} catch (\InvalidArgumentException $e) {
return back()->with('error', $e->getMessage());
}
return redirect()
->route('care.specialty.workspace', [
'module' => 'ambulance',
'visit' => $visit,
'tab' => $shell->workspaceTabForStage('ambulance', $validated['stage']),
])
->with('success', 'Visit stage updated.');
}
public function saveHandover(
Request $request,
Visit $visit,
SpecialtyModuleService $modules,
SpecialtyClinicalRecordService $clinical,
SpecialtyVisitStageService $stages,
AmbulanceWorkflowService $workflow,
): RedirectResponse {
$this->authorizeAbility($request, 'consultations.manage');
$this->assertAmbulanceManage($request, $modules);
$this->assertVisit($request, $visit);
$organization = $this->organization($request);
$owner = $this->ownerRef($request);
$payload = (array) $request->input('payload', []);
foreach ($clinical->fieldsFor('ambulance', 'amb_handover') as $field) {
if (($field['type'] ?? '') === 'boolean') {
$payload[$field['name']] = $request->boolean('payload.'.$field['name']);
}
}
$request->merge(['payload' => $payload, 'tab' => 'handover']);
$validated = $request->validate(array_merge([
'tab' => ['required', 'string'],
], $clinical->validationRules('ambulance', 'amb_handover')));
$record = $clinical->upsert(
$organization,
$visit,
'ambulance',
'amb_handover',
$clinical->payloadFromRequest($validated),
$owner,
$owner,
AmbulanceWorkflowService::STAGE_HANDOVER,
SpecialtyClinicalRecord::STATUS_COMPLETED,
);
try {
$stages->setStage(
$organization,
$visit,
'ambulance',
AmbulanceWorkflowService::STAGE_HANDOVER,
$owner,
$owner,
);
} catch (\InvalidArgumentException) {
}
if ($workflow->shouldCompleteVisit($record->payload ?? [])) {
try {
$stages->setStage(
$organization,
$visit,
'ambulance',
AmbulanceWorkflowService::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' => 'ambulance', 'visit' => $visit, 'tab' => 'handover'])
->with('success', 'Handover saved.');
}
public function reports(
Request $request,
SpecialtyModuleService $modules,
SpecialtyShellService $shell,
AmbulanceAnalyticsService $analytics,
): View {
$this->authorizeAbility($request, 'consultations.view');
$this->assertAmbulanceAccess($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.ambulance.reports', [
'moduleKey' => 'ambulance',
'definition' => $modules->definition('ambulance'),
'shellNav' => $shell->navItems('ambulance'),
'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->assertAmbulanceAccess($request, $modules);
$this->assertVisit($request, $visit);
$visit->loadMissing(['patient', 'appointment.practitioner', 'branch']);
return view('care.specialty.ambulance.print', [
'visit' => $visit,
'patient' => $visit->patient,
'dispatch' => $clinical->findForVisit($visit, 'ambulance', 'amb_dispatch'),
'scene' => $clinical->findForVisit($visit, 'ambulance', 'amb_scene'),
'enRoute' => $clinical->findForVisit($visit, 'ambulance', 'amb_en_route'),
'handover' => $clinical->findForVisit($visit, 'ambulance', 'amb_handover'),
]);
}
}
@@ -0,0 +1,214 @@
<?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\ChildWelfare\ChildWelfareAnalyticsService;
use App\Services\Care\ChildWelfare\ChildWelfareWorkflowService;
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 ChildWelfareWorkspaceController extends Controller
{
use ScopesToAccount;
protected function assertChildWelfareAccess(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanAccess($organization, $this->member($request), 'child_welfare'), 403);
}
protected function assertChildWelfareManage(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanManage($organization, $this->member($request), 'child_welfare'), 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->assertChildWelfareManage($request, $modules);
$this->assertVisit($request, $visit);
$validated = $request->validate([
'stage' => ['required', 'string', 'max:32'],
]);
try {
$stages->setStage(
$this->organization($request),
$visit,
'child_welfare',
$validated['stage'],
$this->ownerRef($request),
$this->actorRef($request),
);
} catch (\InvalidArgumentException $e) {
return back()->with('error', $e->getMessage());
}
return redirect()
->route('care.specialty.workspace', [
'module' => 'child_welfare',
'visit' => $visit,
'tab' => $shell->workspaceTabForStage('child_welfare', $validated['stage']),
])
->with('success', 'Visit stage updated.');
}
public function saveFollowUp(
Request $request,
Visit $visit,
SpecialtyModuleService $modules,
SpecialtyClinicalRecordService $clinical,
SpecialtyVisitStageService $stages,
ChildWelfareWorkflowService $workflow,
): RedirectResponse {
$this->authorizeAbility($request, 'consultations.manage');
$this->assertChildWelfareManage($request, $modules);
$this->assertVisit($request, $visit);
$organization = $this->organization($request);
$owner = $this->ownerRef($request);
$payload = (array) $request->input('payload', []);
foreach ($clinical->fieldsFor('child_welfare', 'cwc_followup') as $field) {
if (($field['type'] ?? '') === 'boolean') {
$payload[$field['name']] = $request->boolean('payload.'.$field['name']);
}
}
$request->merge(['payload' => $payload, 'tab' => 'followup']);
$validated = $request->validate(array_merge([
'tab' => ['required', 'string'],
], $clinical->validationRules('child_welfare', 'cwc_followup')));
$record = $clinical->upsert(
$organization,
$visit,
'child_welfare',
'cwc_followup',
$clinical->payloadFromRequest($validated),
$owner,
$owner,
ChildWelfareWorkflowService::STAGE_FOLLOWUP,
SpecialtyClinicalRecord::STATUS_COMPLETED,
);
try {
$stages->setStage(
$organization,
$visit,
'child_welfare',
ChildWelfareWorkflowService::STAGE_FOLLOWUP,
$owner,
$owner,
);
} catch (\InvalidArgumentException) {
}
if ($workflow->shouldCompleteVisit($record->payload ?? [])) {
try {
$stages->setStage(
$organization,
$visit,
'child_welfare',
ChildWelfareWorkflowService::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' => 'child_welfare', 'visit' => $visit, 'tab' => 'followup'])
->with('success', 'Intervention / follow-up saved.');
}
public function reports(
Request $request,
SpecialtyModuleService $modules,
SpecialtyShellService $shell,
ChildWelfareAnalyticsService $analytics,
): View {
$this->authorizeAbility($request, 'consultations.view');
$this->assertChildWelfareAccess($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.child-welfare.reports', [
'moduleKey' => 'child_welfare',
'definition' => $modules->definition('child_welfare'),
'shellNav' => $shell->navItems('child_welfare'),
'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->assertChildWelfareAccess($request, $modules);
$this->assertVisit($request, $visit);
$visit->loadMissing(['patient', 'appointment.practitioner', 'branch']);
return view('care.specialty.child-welfare.print', [
'visit' => $visit,
'patient' => $visit->patient,
'intake' => $clinical->findForVisit($visit, 'child_welfare', 'cwc_intake'),
'assessment' => $clinical->findForVisit($visit, 'child_welfare', 'cwc_assessment'),
'plan' => $clinical->findForVisit($visit, 'child_welfare', 'cwc_plan'),
'followup' => $clinical->findForVisit($visit, 'child_welfare', 'cwc_followup'),
]);
}
}
@@ -171,6 +171,8 @@ class SpecialtyModuleController extends Controller
'dermatology' => 'history',
'podiatry' => 'history',
'fertility' => 'history',
'child_welfare' => 'intake',
'ambulance' => 'dispatch',
default => (collect(array_keys($shellTabs))
->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null)
?? 'clinical_notes'),
@@ -260,6 +262,8 @@ class SpecialtyModuleController extends Controller
'dermatology' => 'history',
'podiatry' => 'history',
'fertility' => 'history',
'child_welfare' => 'intake',
'ambulance' => 'dispatch',
default => (collect(array_keys($shellTabs))
->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null)
?? 'clinical_notes'),
@@ -1127,6 +1131,70 @@ class SpecialtyModuleController extends Controller
}
}
if ($module === 'child_welfare' && in_array($recordType, ['cwc_intake', 'cwc_assessment', 'cwc_plan'], true)) {
$workflow = app(\App\Services\Care\ChildWelfare\ChildWelfareWorkflowService::class);
$stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
$suggested = match ($recordType) {
'cwc_intake' => $workflow->stageFromIntake($record->payload ?? []),
'cwc_assessment' => $workflow->stageFromAssessment($record->payload ?? []),
'cwc_plan' => $workflow->stageFromPlan($record->payload ?? []),
default => null,
};
$current = $visit->specialty_stage;
$early = ['check_in', 'waiting', null, ''];
$order = [
'check_in' => 0,
'intake' => 1,
'assessment' => 2,
'plan' => 3,
'followup' => 4,
'completed' => 5,
];
if ($suggested && (! $current || in_array($current, $early, true))) {
try {
$stageService->setStage($organization, $visit, 'child_welfare', $suggested, $this->ownerRef($request), $this->ownerRef($request));
} catch (\InvalidArgumentException) {
}
} elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
try {
$stageService->setStage($organization, $visit, 'child_welfare', $suggested, $this->ownerRef($request), $this->ownerRef($request));
} catch (\InvalidArgumentException) {
}
}
}
if ($module === 'ambulance' && in_array($recordType, ['amb_dispatch', 'amb_scene', 'amb_en_route'], true)) {
$workflow = app(\App\Services\Care\Ambulance\AmbulanceWorkflowService::class);
$stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
$suggested = match ($recordType) {
'amb_dispatch' => $workflow->stageFromDispatch($record->payload ?? []),
'amb_scene' => $workflow->stageFromScene($record->payload ?? []),
'amb_en_route' => $workflow->stageFromEnRoute($record->payload ?? []),
default => null,
};
$current = $visit->specialty_stage;
$early = ['check_in', 'waiting', null, ''];
$order = [
'check_in' => 0,
'dispatch' => 1,
'on_scene' => 2,
'transport' => 3,
'handover' => 4,
'completed' => 5,
];
if ($suggested && (! $current || in_array($current, $early, true))) {
try {
$stageService->setStage($organization, $visit, 'ambulance', $suggested, $this->ownerRef($request), $this->ownerRef($request));
} catch (\InvalidArgumentException) {
}
} elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
try {
$stageService->setStage($organization, $visit, 'ambulance', $suggested, $this->ownerRef($request), $this->ownerRef($request));
} catch (\InvalidArgumentException) {
}
}
}
return redirect()
->route('care.specialty.workspace', [
'module' => $module,
@@ -1644,6 +1712,18 @@ class SpecialtyModuleController extends Controller
$fertilityCycle = null;
$fertilityStageCodes = [];
$fertilityStageFlow = [];
$childWelfareIntake = null;
$childWelfareAssessment = null;
$childWelfarePlan = null;
$childWelfareFollowup = null;
$childWelfareStageCodes = [];
$childWelfareStageFlow = [];
$ambulanceDispatch = null;
$ambulanceScene = null;
$ambulanceEnRoute = null;
$ambulanceHandover = null;
$ambulanceStageCodes = [];
$ambulanceStageFlow = [];
$activeTab = (string) $request->query('tab', array_key_first($shell->workspaceTabs($module)) ?: 'overview');
$clinical = app(SpecialtyClinicalRecordService::class);
@@ -1926,6 +2006,24 @@ class SpecialtyModuleController extends Controller
$fertilityStageFlow = app(\App\Services\Care\Fertility\FertilityWorkflowService::class)->stageFlow();
}
if ($module === 'child_welfare') {
$childWelfareIntake = $clinical->findForVisit($workspaceVisit, 'child_welfare', 'cwc_intake');
$childWelfareAssessment = $clinical->findForVisit($workspaceVisit, 'child_welfare', 'cwc_assessment');
$childWelfarePlan = $clinical->findForVisit($workspaceVisit, 'child_welfare', 'cwc_plan');
$childWelfareFollowup = $clinical->findForVisit($workspaceVisit, 'child_welfare', 'cwc_followup');
$childWelfareStageCodes = collect($shell->stages('child_welfare'))->pluck('code')->all();
$childWelfareStageFlow = app(\App\Services\Care\ChildWelfare\ChildWelfareWorkflowService::class)->stageFlow();
}
if ($module === 'ambulance') {
$ambulanceDispatch = $clinical->findForVisit($workspaceVisit, 'ambulance', 'amb_dispatch');
$ambulanceScene = $clinical->findForVisit($workspaceVisit, 'ambulance', 'amb_scene');
$ambulanceEnRoute = $clinical->findForVisit($workspaceVisit, 'ambulance', 'amb_en_route');
$ambulanceHandover = $clinical->findForVisit($workspaceVisit, 'ambulance', 'amb_handover');
$ambulanceStageCodes = collect($shell->stages('ambulance'))->pluck('code')->all();
$ambulanceStageFlow = app(\App\Services\Care\Ambulance\AmbulanceWorkflowService::class)->stageFlow();
}
if ($patientHeader !== null) {
$patientHeader['clinical_alerts'] = $clinicalAlerts;
}
@@ -2135,6 +2233,18 @@ class SpecialtyModuleController extends Controller
'fertilityCycle' => $fertilityCycle,
'fertilityStageCodes' => $fertilityStageCodes,
'fertilityStageFlow' => $fertilityStageFlow,
'childWelfareIntake' => $childWelfareIntake,
'childWelfareAssessment' => $childWelfareAssessment,
'childWelfarePlan' => $childWelfarePlan,
'childWelfareFollowup' => $childWelfareFollowup,
'childWelfareStageCodes' => $childWelfareStageCodes,
'childWelfareStageFlow' => $childWelfareStageFlow,
'ambulanceDispatch' => $ambulanceDispatch,
'ambulanceScene' => $ambulanceScene,
'ambulanceEnRoute' => $ambulanceEnRoute,
'ambulanceHandover' => $ambulanceHandover,
'ambulanceStageCodes' => $ambulanceStageCodes,
'ambulanceStageFlow' => $ambulanceStageFlow,
'queueStubs' => $modules->queueStubsFor($organization, $module),
'branchId' => $branchId,
'branchLabel' => $branchLabel,
@@ -0,0 +1,168 @@
<?php
namespace App\Services\Care\Ambulance;
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 AmbulanceAnalyticsService
{
public function __construct(
protected SpecialtyShellService $shell,
) {}
/**
* @return array{
* arrivals_today: int,
* completed_today: int,
* urgent_open: int,
* call_nature_breakdown: Collection,
* outcome_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, 'ambulance', $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');
$urgentOpen = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'ambulance')
->where('record_type', 'amb_scene')
->whereIn('visit_id', $openVisitIds->isEmpty() ? [0] : $openVisitIds)
->get()
->filter(function (SpecialtyClinicalRecord $r) {
$acuity = (string) ($r->payload['acuity'] ?? '');
return in_array($acuity, ['Critical', 'Urgent'], true);
})
->count();
$dispatchRecords = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'ambulance')
->where('record_type', 'amb_dispatch')
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
->get();
$callNatureBreakdown = $dispatchRecords
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['call_nature'] ?? 'Unknown'))
->map(fn (Collection $rows, string $nature) => [
'call_nature' => $nature,
'total' => $rows->count(),
])
->values()
->sortByDesc('total')
->values();
$handoverRecords = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'ambulance')
->where('record_type', 'amb_handover')
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
->get();
$outcomeBreakdown = $handoverRecords
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['outcome'] ?? 'Unknown'))
->map(fn (Collection $rows, string $outcome) => [
'outcome' => $outcome,
'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, 'ambulance'))
->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,
'urgent_open' => $urgentOpen,
'call_nature_breakdown' => $callNatureBreakdown,
'outcome_breakdown' => $outcomeBreakdown,
'avg_los_minutes' => $avgLos,
'revenue_by_service' => $revenueByService,
'from' => $rangeFrom->toDateString(),
'to' => $rangeTo->toDateString(),
];
}
}
@@ -0,0 +1,85 @@
<?php
namespace App\Services\Care\Ambulance;
/**
* Map ambulance / EMS clinical progress onto visit stages.
*/
class AmbulanceWorkflowService
{
public const STAGE_CHECK_IN = 'check_in';
public const STAGE_DISPATCH = 'dispatch';
public const STAGE_ON_SCENE = 'on_scene';
public const STAGE_TRANSPORT = 'transport';
public const STAGE_HANDOVER = 'handover';
public const STAGE_COMPLETED = 'completed';
/**
* @param array<string, mixed> $payload
*/
public function stageFromDispatch(array $payload): string
{
if (! empty($payload['call_nature']) || ! empty($payload['location'])) {
return self::STAGE_DISPATCH;
}
return self::STAGE_CHECK_IN;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromScene(array $payload): string
{
if (! empty($payload['scene_findings']) || ! empty($payload['chief_complaint'])) {
return self::STAGE_ON_SCENE;
}
return self::STAGE_DISPATCH;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromEnRoute(array $payload): string
{
if (! empty($payload['interventions']) || ! empty($payload['destination'])) {
return self::STAGE_TRANSPORT;
}
return self::STAGE_ON_SCENE;
}
/**
* @param array<string, mixed> $payload
*/
public function shouldCompleteVisit(array $payload): bool
{
$outcome = strtolower((string) ($payload['outcome'] ?? ''));
return str_contains($outcome, 'completed')
|| str_contains($outcome, 'handed over')
|| str_contains($outcome, 'cancelled')
|| str_contains($outcome, 'refused');
}
/**
* @return array<string, array{next: string, label: string}>
*/
public function stageFlow(): array
{
return [
self::STAGE_CHECK_IN => ['next' => self::STAGE_DISPATCH, 'label' => 'Start dispatch'],
self::STAGE_DISPATCH => ['next' => self::STAGE_ON_SCENE, 'label' => 'Move to on scene'],
self::STAGE_ON_SCENE => ['next' => self::STAGE_TRANSPORT, 'label' => 'Move to transport'],
self::STAGE_TRANSPORT => ['next' => self::STAGE_HANDOVER, 'label' => 'Move to handover'],
self::STAGE_HANDOVER => ['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\ChildWelfare;
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 ChildWelfareAnalyticsService
{
public function __construct(
protected SpecialtyShellService $shell,
) {}
/**
* @return array{
* arrivals_today: int,
* completed_today: int,
* safeguarding_open: int,
* growth_breakdown: Collection,
* outcome_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, 'child_welfare', $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');
$safeguardingOpen = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'child_welfare')
->where('record_type', 'cwc_assessment')
->whereIn('visit_id', $openVisitIds->isEmpty() ? [0] : $openVisitIds)
->get()
->filter(function (SpecialtyClinicalRecord $r) {
$flag = strtolower((string) ($r->payload['safeguarding_flag'] ?? ''));
return in_array($flag, ['concern', 'escalated'], true);
})
->count();
$assessmentRecords = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'child_welfare')
->where('record_type', 'cwc_assessment')
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
->get();
$growthBreakdown = $assessmentRecords
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['growth_status'] ?? 'Unknown'))
->map(fn (Collection $rows, string $status) => [
'status' => $status,
'total' => $rows->count(),
])
->values()
->sortByDesc('total')
->values();
$followupRecords = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'child_welfare')
->where('record_type', 'cwc_followup')
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
->get();
$outcomeBreakdown = $followupRecords
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['outcome'] ?? 'Unknown'))
->map(fn (Collection $rows, string $outcome) => [
'outcome' => $outcome,
'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, 'child_welfare'))
->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,
'safeguarding_open' => $safeguardingOpen,
'growth_breakdown' => $growthBreakdown,
'outcome_breakdown' => $outcomeBreakdown,
'avg_los_minutes' => $avgLos,
'revenue_by_service' => $revenueByService,
'from' => $rangeFrom->toDateString(),
'to' => $rangeTo->toDateString(),
];
}
}
@@ -0,0 +1,86 @@
<?php
namespace App\Services\Care\ChildWelfare;
/**
* Map child welfare / CWC clinical progress onto visit stages.
*/
class ChildWelfareWorkflowService
{
public const STAGE_CHECK_IN = 'check_in';
public const STAGE_INTAKE = 'intake';
public const STAGE_ASSESSMENT = 'assessment';
public const STAGE_PLAN = 'plan';
public const STAGE_FOLLOWUP = 'followup';
public const STAGE_COMPLETED = 'completed';
/**
* @param array<string, mixed> $payload
*/
public function stageFromIntake(array $payload): string
{
$history = trim((string) ($payload['history'] ?? ''));
if ($history !== '' || ! empty($payload['visit_reason'])) {
return self::STAGE_INTAKE;
}
return self::STAGE_CHECK_IN;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromAssessment(array $payload): string
{
if (! empty($payload['exam_findings']) || ! empty($payload['assessment_summary'])) {
return self::STAGE_ASSESSMENT;
}
return self::STAGE_INTAKE;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromPlan(array $payload): string
{
$goals = trim((string) ($payload['goals'] ?? ''));
if ($goals !== '') {
return self::STAGE_PLAN;
}
return self::STAGE_ASSESSMENT;
}
/**
* @param array<string, mixed> $payload
*/
public function shouldCompleteVisit(array $payload): bool
{
$outcome = strtolower((string) ($payload['outcome'] ?? ''));
return str_contains($outcome, 'completed')
|| str_contains($outcome, 'referred')
|| str_contains($outcome, 'lost to follow-up');
}
/**
* @return array<string, array{next: string, label: string}>
*/
public function stageFlow(): array
{
return [
self::STAGE_CHECK_IN => ['next' => self::STAGE_INTAKE, 'label' => 'Start intake'],
self::STAGE_INTAKE => ['next' => self::STAGE_ASSESSMENT, 'label' => 'Move to assessment'],
self::STAGE_ASSESSMENT => ['next' => self::STAGE_PLAN, 'label' => 'Move to care plan'],
self::STAGE_PLAN => ['next' => self::STAGE_FOLLOWUP, 'label' => 'Move to intervention / follow-up'],
self::STAGE_FOLLOWUP => ['next' => self::STAGE_COMPLETED, 'label' => 'Complete visit'],
self::STAGE_COMPLETED => ['next' => self::STAGE_COMPLETED, 'label' => 'Completed'],
];
}
}
+249 -1
View File
@@ -882,7 +882,8 @@ class DemoTenantSeeder
'dermatology' => ['Skin rash', 'Mole review', 'Dermatology procedure'],
'podiatry' => ['Diabetic foot care', 'Nail procedure', 'Foot pain'],
'fertility' => ['Fertility consult', 'Cycle review', 'IVF follow-up'],
'child_welfare' => ['Growth monitoring', 'Immunization CWC', 'Well-baby visit'],
'child_welfare' => ['Growth monitoring', 'Well-child CWC', 'Nutrition follow-up'],
'ambulance' => ['Chest pain response', 'Trauma pickup', 'Facility transfer'],
];
$count = 0;
@@ -1032,6 +1033,8 @@ class DemoTenantSeeder
$this->seedDermatologyClinicalDemo($organization, $ownerRef);
$this->seedPodiatryClinicalDemo($organization, $ownerRef);
$this->seedFertilityClinicalDemo($organization, $ownerRef);
$this->seedChildWelfareClinicalDemo($organization, $ownerRef);
$this->seedAmbulanceClinicalDemo($organization, $ownerRef);
return $count;
}
@@ -3010,6 +3013,251 @@ class DemoTenantSeeder
}
}
private function seedChildWelfareClinicalDemo(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', 'child_welfare')
->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;
}
$concern = $index === 0;
$clinical->upsert(
$organization,
$visit,
'child_welfare',
'cwc_intake',
[
'visit_reason' => $concern ? 'Growth monitoring' : 'Routine well-child',
'caregiver' => $concern ? 'Mother — Ama Mensah' : 'Father — Kojo Boateng',
'history' => $concern
? 'Weight faltering over 2 months; reduced appetite; breast milk + porridge'
: 'Well since last CWC; no illness; immunizations on track',
'birth_history' => $concern ? 'Term SVD; birth weight 2.8 kg' : 'Term SVD; birth weight 3.2 kg',
'immunization_status' => $concern ? 'Catch-up needed' : 'Up to date',
'feeding' => $concern ? 'Breastfeeding + thin porridge twice daily' : 'Breastfeeding; complementary feeds started',
'social_context' => $concern ? 'Single caregiver; food insecurity reported' : 'Stable household',
'safeguarding_notes' => $concern ? 'Nutrition concern; monitor home situation — clinical record access only' : '',
'allergies' => 'NKDA',
],
$ownerRef,
$ownerRef,
'intake',
);
$clinical->upsert(
$organization,
$visit,
'child_welfare',
'cwc_assessment',
[
'age_months' => $concern ? 18 : 9,
'weight_kg' => $concern ? 8.1 : 8.6,
'height_cm' => $concern ? 76 : 70,
'head_circumference_cm' => $concern ? 45 : 44,
'muac_cm' => $concern ? 11.2 : 13.5,
'growth_status' => $concern ? 'Underweight' : 'Normal',
'nutrition_risk' => $concern ? 'High' : 'Low',
'development' => $concern ? 'Walks with support; 34 words' : 'Sits well; babbling',
'exam_findings' => $concern
? 'Thin; dry skin; no oedema; alert'
: 'Well nourished; soft fontanelle; clear chest',
'safeguarding_flag' => $concern ? 'Concern' : 'None',
'assessment_summary' => $concern
? 'Underweight with high nutrition risk — counselling and close follow-up'
: 'Healthy well-child visit; continue routine CWC schedule',
],
$ownerRef,
$ownerRef,
'assessment',
);
if ($concern) {
$clinical->upsert(
$organization,
$visit,
'child_welfare',
'cwc_plan',
[
'goals' => 'Restore weight gain; improve dietary diversity; complete catch-up immunizations',
'interventions' => 'Nutrition counselling; RUTF if eligible; growth recheck',
'counseling' => 'Feeding frequency; hygiene; danger signs',
'referrals' => 'Consider nutrition clinic if no weight gain in 2 weeks',
'medications' => 'Vitamin A if due; deworming per schedule',
'follow_up' => '2 weeks CWC',
'advice' => 'Return sooner if fever, diarrhoea, or poor feeding',
],
$ownerRef,
$ownerRef,
'plan',
);
}
if (! $visit->specialty_stage) {
$visit->update(['specialty_stage' => $concern ? 'plan' : 'assessment']);
}
$index++;
}
}
private function seedAmbulanceClinicalDemo(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', 'ambulance')
->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;
}
$critical = $index === 0;
$clinical->upsert(
$organization,
$visit,
'ambulance',
'amb_dispatch',
[
'call_nature' => $critical ? 'Medical emergency' : 'Transfer',
'priority' => $critical ? 'Immediate' : 'Routine',
'location' => $critical ? 'Kaneshie Market Road' : 'Ridge Hospital ward 3',
'caller_info' => $critical ? 'Bystander — 024XXXXXXX' : 'Ward nurse',
'crew' => $critical ? 'Paramedic + EMT' : 'EMT crew',
'vehicle' => $critical ? 'AMB-01' : 'AMB-02',
'dispatch_notes' => $critical
? 'Chest pain, diaphoretic; request ALS response'
: 'Stable inter-facility transfer for imaging',
'eta_minutes' => $critical ? 8 : 20,
],
$ownerRef,
$ownerRef,
'dispatch',
);
$clinical->upsert(
$organization,
$visit,
'ambulance',
'amb_scene',
[
'chief_complaint' => $critical ? 'Chest pain' : 'Inter-facility transfer',
'acuity' => $critical ? 'Critical' : 'Stable',
'mechanism' => $critical ? 'Sudden onset at rest' : 'Scheduled transfer',
'airway_ok' => true,
'breathing_ok' => $critical ? false : true,
'circulation_ok' => $critical ? false : true,
'gcs' => 15,
'vitals_summary' => $critical
? 'BP 88/54, HR 118, SpO2 91% on air, RR 28'
: 'BP 124/78, HR 82, SpO2 98%, RR 16',
'scene_findings' => $critical
? 'Pale, diaphoretic, ongoing central chest pain radiating to left arm'
: 'Patient comfortable on stretcher; IV in situ',
'hazards' => $critical ? 'Busy roadside' : 'None',
],
$ownerRef,
$ownerRef,
'on_scene',
);
if ($critical) {
$clinical->upsert(
$organization,
$visit,
'ambulance',
'amb_en_route',
[
'destination' => 'Korle Bu Teaching Hospital ED',
'interventions' => 'Oxygen via NRB; aspirin; IV access; cardiac monitoring',
'medications' => 'Aspirin 300 mg PO',
'response_to_treatment' => 'Pain partially eased; SpO2 improved to 95%',
'monitoring' => 'Continuous ECG; vitals q5min',
'deterioration' => false,
'eta_facility' => '12 minutes',
'notes' => 'Pre-alerted ED resus',
],
$ownerRef,
$ownerRef,
'transport',
);
}
if (! $visit->specialty_stage) {
$visit->update(['specialty_stage' => $critical ? 'transport' : 'on_scene']);
}
$index++;
}
}
private function seedDentistryClinicalDemo(Organization $organization, string $ownerRef): void
{
// Specialty departments are provisioned without organization_id; scope via branches.
@@ -430,6 +430,34 @@ class SpecialtyClinicalRecordService
}
}
if ($moduleKey === 'ambulance' && $recordType === 'amb_scene') {
$acuity = (string) ($payload['acuity'] ?? '');
if (in_array($acuity, ['Critical', 'Urgent'], true)) {
$alerts[] = [
'code' => 'amb.acuity_high',
'severity' => $acuity === 'Critical' ? 'critical' : 'warning',
'message' => 'Scene acuity: '.$acuity.'.',
];
}
if (array_key_exists('circulation_ok', $payload) && in_array($payload['circulation_ok'], [false, 0, '0'], true)) {
$alerts[] = [
'code' => 'amb.circulation_unstable',
'severity' => 'critical',
'message' => 'Circulation marked unstable on scene.',
];
}
}
if ($moduleKey === 'ambulance' && $recordType === 'amb_en_route') {
if (! empty($payload['deterioration'])) {
$alerts[] = [
'code' => 'amb.deterioration',
'severity' => 'critical',
'message' => 'Patient deterioration noted en route.',
];
}
}
if ($moduleKey === 'podiatry' && $recordType === 'foot_exam') {
$risk = (string) ($payload['diabetes'] ?? '');
if (in_array($risk, ['High', 'Active ulcer'], true)) {
@@ -633,6 +661,39 @@ class SpecialtyClinicalRecordService
}
}
if ($moduleKey === 'child_welfare' && $recordType === 'cwc_assessment') {
$flag = strtolower((string) ($payload['safeguarding_flag'] ?? ''));
if ($flag === 'escalated') {
$alerts[] = [
'code' => 'cwc.safeguarding',
'severity' => 'critical',
'message' => 'Safeguarding escalated — follow facility protocol.',
];
} elseif ($flag === 'concern') {
$alerts[] = [
'code' => 'cwc.safeguarding',
'severity' => 'warning',
'message' => 'Safeguarding concern recorded on CWC assessment.',
];
}
$nutrition = strtolower((string) ($payload['nutrition_risk'] ?? ''));
if ($nutrition === 'high') {
$alerts[] = [
'code' => 'cwc.nutrition_risk',
'severity' => 'warning',
'message' => 'High nutrition risk on child welfare assessment.',
];
}
$growth = strtolower((string) ($payload['growth_status'] ?? ''));
if (in_array($growth, ['wasted', 'underweight'], true)) {
$alerts[] = [
'code' => 'cwc.growth',
'severity' => 'warning',
'message' => 'Abnormal growth status: '.$payload['growth_status'].'.',
];
}
}
return $alerts;
}
+9 -1
View File
@@ -29,6 +29,8 @@ use App\Services\Care\Infusion\InfusionWorkflowService;
use App\Services\Care\Dermatology\DermatologyWorkflowService;
use App\Services\Care\Podiatry\PodiatryWorkflowService;
use App\Services\Care\Fertility\FertilityWorkflowService;
use App\Services\Care\ChildWelfare\ChildWelfareWorkflowService;
use App\Services\Care\Ambulance\AmbulanceWorkflowService;
use Illuminate\Support\Collection;
/**
@@ -90,6 +92,8 @@ class SpecialtyShellService
'dermatology' => 'care.specialty.dermatology.stage',
'podiatry' => 'care.specialty.podiatry.stage',
'fertility' => 'care.specialty.fertility.stage',
'child_welfare' => 'care.specialty.child-welfare.stage',
'ambulance' => 'care.specialty.ambulance.stage',
default => null,
};
}
@@ -122,6 +126,8 @@ class SpecialtyShellService
'dermatology' => app(DermatologyWorkflowService::class)->stageFlow(),
'podiatry' => app(PodiatryWorkflowService::class)->stageFlow(),
'fertility' => app(FertilityWorkflowService::class)->stageFlow(),
'child_welfare' => app(ChildWelfareWorkflowService::class)->stageFlow(),
'ambulance' => app(AmbulanceWorkflowService::class)->stageFlow(),
'dentistry' => [
'waiting' => ['next' => 'chair', 'label' => 'Seat at chair'],
'chair' => ['next' => 'procedure', 'label' => 'Start procedure'],
@@ -421,7 +427,7 @@ class SpecialtyShellService
) {
$code = (string) ($stage['code'] ?? '');
if (in_array($moduleKey, ['dentistry', 'emergency', 'blood_bank', 'ophthalmology', 'physiotherapy', 'maternity', 'radiology', 'cardiology', 'psychiatry', 'pediatrics', 'orthopedics', 'ent', 'oncology', 'renal', 'surgery', 'vaccination', 'pathology', 'infusion', 'dermatology', 'podiatry', 'fertility'], true) && $visitIds->isNotEmpty()) {
if (in_array($moduleKey, ['dentistry', 'emergency', 'blood_bank', 'ophthalmology', 'physiotherapy', 'maternity', 'radiology', 'cardiology', 'psychiatry', 'pediatrics', 'orthopedics', 'ent', 'oncology', 'renal', 'surgery', 'vaccination', 'pathology', 'infusion', 'dermatology', 'podiatry', 'fertility', 'child_welfare', 'ambulance'], true) && $visitIds->isNotEmpty()) {
$count = Visit::owned($ownerRef)
->where('organization_id', $organization->id)
->whereIn('id', $visitIds)
@@ -469,6 +475,8 @@ class SpecialtyShellService
'dermatology' => $clinical->countOpenByType($organization, 'dermatology', 'skin_exam', $branchScope),
'podiatry' => $clinical->countOpenByType($organization, 'podiatry', 'foot_exam', $branchScope),
'fertility' => $clinical->countOpenByType($organization, 'fertility', 'fert_exam', $branchScope),
'child_welfare' => $clinical->countOpenByType($organization, 'child_welfare', 'cwc_assessment', $branchScope),
'ambulance' => $clinical->countOpenByType($organization, 'ambulance', 'amb_scene', $branchScope),
'dentistry' => \App\Models\DentalPlanItem::query()
->whereHas('plan', function ($q) use ($organization, $ownerRef) {
$q->owned($ownerRef)
@@ -192,6 +192,22 @@ class SpecialtyVisitStageService
: ($stages[1] ?? ($stages[0] ?? null));
}
if ($moduleKey === 'child_welfare') {
$stages = $this->allowedStages($moduleKey);
return in_array(\App\Services\Care\ChildWelfare\ChildWelfareWorkflowService::STAGE_INTAKE, $stages, true)
? \App\Services\Care\ChildWelfare\ChildWelfareWorkflowService::STAGE_INTAKE
: ($stages[1] ?? ($stages[0] ?? null));
}
if ($moduleKey === 'ambulance') {
$stages = $this->allowedStages($moduleKey);
return in_array(\App\Services\Care\Ambulance\AmbulanceWorkflowService::STAGE_DISPATCH, $stages, true)
? \App\Services\Care\Ambulance\AmbulanceWorkflowService::STAGE_DISPATCH
: ($stages[1] ?? ($stages[0] ?? null));
}
$stages = $this->allowedStages($moduleKey);
foreach (['chair', 'in_care', 'exam', 'assessment', 'treatment'] as $preferred) {
if (in_array($preferred, $stages, true)) {
+1
View File
@@ -214,6 +214,7 @@ final class DemoWorld
'podiatry' => 'Dr. Kofi Podiatry',
'fertility' => 'Dr. Abena Fertility',
'child_welfare' => 'Dr. Efua Child Welfare',
'ambulance' => 'Dr. Kojo Ambulance',
];
public const STAFF = [