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,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)) {