Add full Vaccination, Pathology, and Infusion specialty clinical suites.
Deploy Ladill Care / deploy (push) Successful in 34s
Deploy Ladill Care / deploy (push) Successful in 34s
Mirror Oncology-depth stage flows, workspace controllers, clinical forms, reports/print, demo seed, and suite tests. Pathology stays clinic specialty complementary to the Lab app. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -1026,6 +1026,9 @@ class DemoTenantSeeder
|
||||
$this->seedOncologyClinicalDemo($organization, $ownerRef);
|
||||
$this->seedRenalClinicalDemo($organization, $ownerRef);
|
||||
$this->seedSurgeryClinicalDemo($organization, $ownerRef);
|
||||
$this->seedVaccinationClinicalDemo($organization, $ownerRef);
|
||||
$this->seedPathologyClinicalDemo($organization, $ownerRef);
|
||||
$this->seedInfusionClinicalDemo($organization, $ownerRef);
|
||||
|
||||
return $count;
|
||||
}
|
||||
@@ -2445,6 +2448,227 @@ class DemoTenantSeeder
|
||||
}
|
||||
}
|
||||
|
||||
private function seedVaccinationClinicalDemo(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', 'vaccination')
|
||||
->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;
|
||||
}
|
||||
$alertCase = $index === 0;
|
||||
$clinical->upsert($organization, $visit, 'vaccination', 'vax_eligibility', [
|
||||
'vaccine' => $alertCase ? 'Yellow fever' : 'Tetanus toxoid',
|
||||
'schedule' => $alertCase ? 'Travel' : 'Routine EPI',
|
||||
'prior_doses' => $alertCase ? 'None documented' : 'Primary series complete',
|
||||
'indications' => $alertCase ? 'Travel certificate required' : 'Antenatal TT booster',
|
||||
'contraindications' => true,
|
||||
'allergy_history' => 'NKDA',
|
||||
'fever_today' => $alertCase,
|
||||
'pregnancy' => ! $alertCase,
|
||||
'cleared' => ! $alertCase,
|
||||
], $ownerRef, $ownerRef, 'eligibility');
|
||||
$clinical->upsert($organization, $visit, 'vaccination', 'vax_consent', [
|
||||
'information_given' => true,
|
||||
'consent_obtained' => ! $alertCase,
|
||||
'consent_type' => 'Verbal',
|
||||
'consented_by' => 'Patient',
|
||||
'risks_discussed' => true,
|
||||
'notes' => $alertCase ? 'Defer pending fever resolution' : 'Consent for TT booster',
|
||||
], $ownerRef, $ownerRef, $alertCase ? 'eligibility' : 'consent');
|
||||
if (! $alertCase) {
|
||||
$clinical->upsert($organization, $visit, 'vaccination', 'vax_admin', [
|
||||
'vaccine' => 'Tetanus toxoid',
|
||||
'dose' => '0.5 mL',
|
||||
'site' => 'Left arm',
|
||||
'batch' => 'TT-DEMO-'.($index + 1),
|
||||
'expiry' => now()->addYear()->toDateString(),
|
||||
'route' => 'IM',
|
||||
'administered_by' => 'Demo nurse',
|
||||
'adverse_events' => 'None immediate',
|
||||
'next_due' => now()->addMonths(6)->toDateString(),
|
||||
'outcome' => 'Completed — observe',
|
||||
], $ownerRef, $ownerRef, 'administer');
|
||||
}
|
||||
if (! $visit->specialty_stage) {
|
||||
$visit->update(['specialty_stage' => $alertCase ? 'eligibility' : 'administer']);
|
||||
}
|
||||
$index++;
|
||||
}
|
||||
}
|
||||
|
||||
private function seedPathologyClinicalDemo(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', 'pathology')
|
||||
->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;
|
||||
}
|
||||
$urgent = $index === 0;
|
||||
$clinical->upsert($organization, $visit, 'pathology', 'path_request', [
|
||||
'specimen_type' => $urgent ? 'Breast core biopsy' : 'Cervical cytology',
|
||||
'site' => $urgent ? 'Left breast' : 'Cervix',
|
||||
'clinical_history' => $urgent
|
||||
? 'Palpable mass; BIRADS 4; rule out malignancy'
|
||||
: 'Routine Pap smear; previous NILM',
|
||||
'urgency' => $urgent ? 'Urgent' : 'Routine',
|
||||
'tests_requested' => $urgent ? 'Histo + IHC if indicated' : 'Pap smear',
|
||||
'requesting_clinician' => 'Demo clinician',
|
||||
], $ownerRef, $ownerRef, 'request');
|
||||
$clinical->upsert($organization, $visit, 'pathology', 'path_specimen', [
|
||||
'received_at' => now()->subHours(2)->format('Y-m-d H:i'),
|
||||
'container_label' => 'PATH-DEMO-'.($index + 1),
|
||||
'adequacy' => $urgent ? 'Adequate' : 'Adequate',
|
||||
'fixative' => $urgent ? '10% formalin' : 'Liquid-based cytology',
|
||||
'notes' => 'Received sealed and labelled',
|
||||
], $ownerRef, $ownerRef, 'specimen');
|
||||
if ($urgent) {
|
||||
$clinical->upsert($organization, $visit, 'pathology', 'path_processing', [
|
||||
'gross' => 'Two cores, 1.2 cm aggregate',
|
||||
'blocks' => 'A1–A2',
|
||||
'stains' => 'H&E',
|
||||
'status' => 'Ready for reporting',
|
||||
'notes' => 'Priority processing',
|
||||
], $ownerRef, $ownerRef, 'processing');
|
||||
}
|
||||
if (! $visit->specialty_stage) {
|
||||
$visit->update(['specialty_stage' => $urgent ? 'processing' : 'specimen']);
|
||||
}
|
||||
$index++;
|
||||
}
|
||||
}
|
||||
|
||||
private function seedInfusionClinicalDemo(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', 'infusion')
|
||||
->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;
|
||||
}
|
||||
$notFit = $index === 0;
|
||||
$clinical->upsert($organization, $visit, 'infusion', 'infusion_assessment', [
|
||||
'indication' => $notFit ? 'IV iron — symptomatic anaemia' : 'IV antibiotics — cellulitis',
|
||||
'history' => $notFit
|
||||
? 'Hb 7.8; prior infusion reaction reported'
|
||||
: 'Day 3 of outpatient IV ceftriaxone',
|
||||
'allergies' => $notFit ? 'Possible iron sucrose reaction' : 'NKDA',
|
||||
'baseline_vitals' => $notFit ? 'BP 88/54; HR 112' : 'BP 118/74; HR 78',
|
||||
'access_plan' => 'Peripheral IV',
|
||||
'fit_for_infusion' => ! $notFit,
|
||||
], $ownerRef, $ownerRef, 'assessment');
|
||||
if (! $notFit) {
|
||||
$clinical->upsert($organization, $visit, 'infusion', 'infusion_protocol', [
|
||||
'medication' => 'Ceftriaxone',
|
||||
'dose' => '2 g',
|
||||
'diluent' => '100 mL NS',
|
||||
'rate' => '30 minutes',
|
||||
'duration' => '30 min',
|
||||
'premeds' => 'None',
|
||||
'ordered_by' => 'Demo clinician',
|
||||
], $ownerRef, $ownerRef, 'protocol');
|
||||
$clinical->upsert($organization, $visit, 'infusion', 'infusion_session', [
|
||||
'medication' => 'Ceftriaxone',
|
||||
'dose' => '2 g',
|
||||
'rate' => '30 min',
|
||||
'access' => 'Left forearm PIV',
|
||||
'start_time' => now()->subMinutes(20)->format('H:i'),
|
||||
'end_time' => '',
|
||||
'vitals' => 'Stable mid-infusion',
|
||||
'reactions' => 'None',
|
||||
'notes' => 'Infusing without incident',
|
||||
'outcome' => 'In progress',
|
||||
], $ownerRef, $ownerRef, 'session');
|
||||
}
|
||||
if (! $visit->specialty_stage) {
|
||||
$visit->update(['specialty_stage' => $notFit ? 'assessment' : 'session']);
|
||||
}
|
||||
$index++;
|
||||
}
|
||||
}
|
||||
|
||||
private function seedDentistryClinicalDemo(Organization $organization, string $ownerRef): void
|
||||
{
|
||||
// Specialty departments are provisioned without organization_id; scope via branches.
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Care\Infusion;
|
||||
|
||||
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 InfusionAnalyticsService
|
||||
{
|
||||
public function __construct(
|
||||
protected SpecialtyShellService $shell,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* arrivals_today: int,
|
||||
* completed_today: int,
|
||||
* sessions_open: int,
|
||||
* medication_breakdown: Collection,
|
||||
* reaction_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, 'infusion', $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');
|
||||
|
||||
$sessionsOpen = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'infusion')
|
||||
->where('record_type', 'infusion_session')
|
||||
->whereIn('visit_id', $openVisitIds->isEmpty() ? [0] : $openVisitIds)
|
||||
->where('status', '!=', SpecialtyClinicalRecord::STATUS_COMPLETED)
|
||||
->count();
|
||||
|
||||
$sessionRecords = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'infusion')
|
||||
->where('record_type', 'infusion_session')
|
||||
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
|
||||
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
|
||||
->get();
|
||||
|
||||
$medicationBreakdown = $sessionRecords
|
||||
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['medication'] ?? 'Unknown'))
|
||||
->map(fn (Collection $rows, string $medication) => [
|
||||
'medication' => $medication,
|
||||
'total' => $rows->count(),
|
||||
])
|
||||
->values()
|
||||
->sortByDesc('total')
|
||||
->values();
|
||||
|
||||
$monitoringRecords = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'infusion')
|
||||
->where('record_type', 'infusion_monitoring')
|
||||
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
|
||||
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
|
||||
->get();
|
||||
|
||||
$reactionBreakdown = $monitoringRecords
|
||||
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['reaction'] ?? 'None'))
|
||||
->map(fn (Collection $rows, string $reaction) => [
|
||||
'reaction' => $reaction,
|
||||
'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, 'infusion'))
|
||||
->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,
|
||||
'sessions_open' => $sessionsOpen,
|
||||
'medication_breakdown' => $medicationBreakdown,
|
||||
'reaction_breakdown' => $reactionBreakdown,
|
||||
'avg_los_minutes' => $avgLos,
|
||||
'revenue_by_service' => $revenueByService,
|
||||
'from' => $rangeFrom->toDateString(),
|
||||
'to' => $rangeTo->toDateString(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Care\Infusion;
|
||||
|
||||
/**
|
||||
* Map infusion centre clinical progress onto visit stages.
|
||||
*/
|
||||
class InfusionWorkflowService
|
||||
{
|
||||
public const STAGE_CHECK_IN = 'check_in';
|
||||
|
||||
public const STAGE_ASSESSMENT = 'assessment';
|
||||
|
||||
public const STAGE_PROTOCOL = 'protocol';
|
||||
|
||||
public const STAGE_SESSION = 'session';
|
||||
|
||||
public const STAGE_MONITORING = 'monitoring';
|
||||
|
||||
public const STAGE_COMPLETED = 'completed';
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromAssessment(array $payload): string
|
||||
{
|
||||
if (! empty($payload['indication']) || ! empty($payload['fit_for_infusion'])) {
|
||||
return self::STAGE_ASSESSMENT;
|
||||
}
|
||||
|
||||
return self::STAGE_CHECK_IN;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromProtocol(array $payload): string
|
||||
{
|
||||
if (! empty($payload['medication']) && ! empty($payload['dose'])) {
|
||||
return self::STAGE_PROTOCOL;
|
||||
}
|
||||
|
||||
return self::STAGE_ASSESSMENT;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromSession(array $payload): string
|
||||
{
|
||||
$outcome = strtolower((string) ($payload['outcome'] ?? ''));
|
||||
if (str_contains($outcome, 'observe') || str_contains($outcome, 'completed') || ! empty($payload['end_time'])) {
|
||||
return self::STAGE_MONITORING;
|
||||
}
|
||||
|
||||
if (! empty($payload['notes']) || ! empty($payload['start_time'])) {
|
||||
return self::STAGE_SESSION;
|
||||
}
|
||||
|
||||
return self::STAGE_PROTOCOL;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromMonitoring(array $payload): string
|
||||
{
|
||||
if ($this->shouldCompleteVisit($payload)) {
|
||||
return self::STAGE_COMPLETED;
|
||||
}
|
||||
|
||||
if (! empty($payload['outcome']) || ! empty($payload['post_vitals'])) {
|
||||
return self::STAGE_MONITORING;
|
||||
}
|
||||
|
||||
return self::STAGE_SESSION;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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_ASSESSMENT, 'label' => 'Start assessment'],
|
||||
self::STAGE_ASSESSMENT => ['next' => self::STAGE_PROTOCOL, 'label' => 'Move to protocol'],
|
||||
self::STAGE_PROTOCOL => ['next' => self::STAGE_SESSION, 'label' => 'Move to infusion session'],
|
||||
self::STAGE_SESSION => ['next' => self::STAGE_MONITORING, 'label' => 'Move to monitoring'],
|
||||
self::STAGE_MONITORING => ['next' => self::STAGE_COMPLETED, 'label' => 'Complete visit'],
|
||||
self::STAGE_COMPLETED => ['next' => self::STAGE_COMPLETED, 'label' => 'Completed'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Care\Pathology;
|
||||
|
||||
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 PathologyAnalyticsService
|
||||
{
|
||||
public function __construct(
|
||||
protected SpecialtyShellService $shell,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* arrivals_today: int,
|
||||
* completed_today: int,
|
||||
* reports_open: int,
|
||||
* diagnosis_breakdown: Collection,
|
||||
* specimen_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, 'pathology', $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');
|
||||
|
||||
$reportsOpen = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'pathology')
|
||||
->where('record_type', 'path_report')
|
||||
->whereIn('visit_id', $openVisitIds->isEmpty() ? [0] : $openVisitIds)
|
||||
->where('status', '!=', SpecialtyClinicalRecord::STATUS_COMPLETED)
|
||||
->count();
|
||||
|
||||
$reportRecords = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'pathology')
|
||||
->where('record_type', 'path_report')
|
||||
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
|
||||
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
|
||||
->get();
|
||||
|
||||
$diagnosisBreakdown = $reportRecords
|
||||
->groupBy(fn (SpecialtyClinicalRecord $r) => \Illuminate\Support\Str::limit((string) ($r->payload['diagnosis'] ?? 'Unknown'), 60))
|
||||
->map(fn (Collection $rows, string $diagnosis) => [
|
||||
'diagnosis' => $diagnosis,
|
||||
'total' => $rows->count(),
|
||||
])
|
||||
->values()
|
||||
->sortByDesc('total')
|
||||
->values();
|
||||
|
||||
$requestRecords = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'pathology')
|
||||
->where('record_type', 'path_request')
|
||||
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
|
||||
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
|
||||
->get();
|
||||
|
||||
$specimenBreakdown = $requestRecords
|
||||
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['specimen_type'] ?? 'Unknown'))
|
||||
->map(fn (Collection $rows, string $specimen) => [
|
||||
'specimen' => $specimen,
|
||||
'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, 'pathology'))
|
||||
->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,
|
||||
'reports_open' => $reportsOpen,
|
||||
'diagnosis_breakdown' => $diagnosisBreakdown,
|
||||
'specimen_breakdown' => $specimenBreakdown,
|
||||
'avg_los_minutes' => $avgLos,
|
||||
'revenue_by_service' => $revenueByService,
|
||||
'from' => $rangeFrom->toDateString(),
|
||||
'to' => $rangeTo->toDateString(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Care\Pathology;
|
||||
|
||||
/**
|
||||
* Map clinic pathology specialty progress onto visit stages.
|
||||
*/
|
||||
class PathologyWorkflowService
|
||||
{
|
||||
public const STAGE_CHECK_IN = 'check_in';
|
||||
|
||||
public const STAGE_REQUEST = 'request';
|
||||
|
||||
public const STAGE_SPECIMEN = 'specimen';
|
||||
|
||||
public const STAGE_PROCESSING = 'processing';
|
||||
|
||||
public const STAGE_REPORT = 'report';
|
||||
|
||||
public const STAGE_VERIFIED = 'verified';
|
||||
|
||||
public const STAGE_COMPLETED = 'completed';
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromRequest(array $payload): string
|
||||
{
|
||||
if (! empty($payload['specimen_type']) || ! empty($payload['clinical_history'])) {
|
||||
return self::STAGE_REQUEST;
|
||||
}
|
||||
|
||||
return self::STAGE_CHECK_IN;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromSpecimen(array $payload): string
|
||||
{
|
||||
if (! empty($payload['container_label'])) {
|
||||
return self::STAGE_SPECIMEN;
|
||||
}
|
||||
|
||||
return self::STAGE_REQUEST;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromProcessing(array $payload): string
|
||||
{
|
||||
$status = strtolower((string) ($payload['status'] ?? ''));
|
||||
if (str_contains($status, 'ready')) {
|
||||
return self::STAGE_REPORT;
|
||||
}
|
||||
|
||||
if (! empty($payload['status']) || ! empty($payload['gross'])) {
|
||||
return self::STAGE_PROCESSING;
|
||||
}
|
||||
|
||||
return self::STAGE_SPECIMEN;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromReport(array $payload): string
|
||||
{
|
||||
if (! empty($payload['diagnosis']) && ! empty($payload['microscopy'])) {
|
||||
return self::STAGE_REPORT;
|
||||
}
|
||||
|
||||
return self::STAGE_PROCESSING;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromVerification(array $payload): string
|
||||
{
|
||||
if ($this->shouldCompleteVisit($payload)) {
|
||||
return self::STAGE_COMPLETED;
|
||||
}
|
||||
|
||||
if (! empty($payload['verified'])) {
|
||||
return self::STAGE_VERIFIED;
|
||||
}
|
||||
|
||||
return self::STAGE_REPORT;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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_REQUEST, 'label' => 'Start request'],
|
||||
self::STAGE_REQUEST => ['next' => self::STAGE_SPECIMEN, 'label' => 'Move to specimen'],
|
||||
self::STAGE_SPECIMEN => ['next' => self::STAGE_PROCESSING, 'label' => 'Move to processing'],
|
||||
self::STAGE_PROCESSING => ['next' => self::STAGE_REPORT, 'label' => 'Move to report'],
|
||||
self::STAGE_REPORT => ['next' => self::STAGE_VERIFIED, 'label' => 'Move to verification'],
|
||||
self::STAGE_VERIFIED => ['next' => self::STAGE_COMPLETED, 'label' => 'Complete visit'],
|
||||
self::STAGE_COMPLETED => ['next' => self::STAGE_COMPLETED, 'label' => 'Completed'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -483,6 +483,77 @@ class SpecialtyClinicalRecordService
|
||||
}
|
||||
}
|
||||
|
||||
if ($moduleKey === 'vaccination' && $recordType === 'vax_eligibility') {
|
||||
if (empty($payload['cleared']) && ! empty($payload['vaccine'])) {
|
||||
$alerts[] = [
|
||||
'code' => 'vax.not_cleared',
|
||||
'severity' => 'critical',
|
||||
'message' => 'Vaccine requested but patient is not cleared to vaccinate.',
|
||||
];
|
||||
}
|
||||
if (! empty($payload['fever_today'])) {
|
||||
$alerts[] = [
|
||||
'code' => 'vax.fever',
|
||||
'severity' => 'warning',
|
||||
'message' => 'Fever recorded on vaccination eligibility screen.',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
if ($moduleKey === 'vaccination' && $recordType === 'vax_observation') {
|
||||
$aefi = strtolower((string) ($payload['aefi'] ?? ''));
|
||||
if (str_contains($aefi, 'severe')) {
|
||||
$alerts[] = [
|
||||
'code' => 'vax.aefi_severe',
|
||||
'severity' => 'critical',
|
||||
'message' => 'Severe AEFI recorded — escalate and document follow-up.',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
if ($moduleKey === 'pathology' && $recordType === 'path_request') {
|
||||
$urgency = strtolower((string) ($payload['urgency'] ?? ''));
|
||||
if (str_contains($urgency, 'urgent') || str_contains($urgency, 'intra')) {
|
||||
$alerts[] = [
|
||||
'code' => 'path.urgent',
|
||||
'severity' => 'warning',
|
||||
'message' => 'Urgent / intra-op pathology request — prioritise processing.',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
if ($moduleKey === 'pathology' && $recordType === 'path_specimen') {
|
||||
$adequacy = strtolower((string) ($payload['adequacy'] ?? ''));
|
||||
if (str_contains($adequacy, 'inadequate')) {
|
||||
$alerts[] = [
|
||||
'code' => 'path.inadequate',
|
||||
'severity' => 'critical',
|
||||
'message' => 'Specimen marked inadequate — notify requesting clinician.',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
if ($moduleKey === 'infusion' && $recordType === 'infusion_assessment') {
|
||||
if (empty($payload['fit_for_infusion']) && ! empty($payload['indication'])) {
|
||||
$alerts[] = [
|
||||
'code' => 'inf.not_fit',
|
||||
'severity' => 'critical',
|
||||
'message' => 'Indication recorded but patient not marked fit for infusion.',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
if ($moduleKey === 'infusion' && in_array($recordType, ['infusion_session', 'infusion_monitoring'], true)) {
|
||||
$reaction = strtolower((string) ($payload['reactions'] ?? $payload['reaction'] ?? ''));
|
||||
if (str_contains($reaction, 'severe') || str_contains($reaction, 'stop')) {
|
||||
$alerts[] = [
|
||||
'code' => 'inf.reaction',
|
||||
'severity' => 'critical',
|
||||
'message' => 'Infusion reaction / stop flagged — review interventions.',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
if ($moduleKey === 'renal' && $recordType === 'renal_exam') {
|
||||
$fluid = strtolower((string) ($payload['fluid_status'] ?? ''));
|
||||
if (str_contains($fluid, 'overload')) {
|
||||
|
||||
@@ -23,6 +23,9 @@ use App\Services\Care\Ent\EntWorkflowService;
|
||||
use App\Services\Care\Oncology\OncologyWorkflowService;
|
||||
use App\Services\Care\Renal\RenalWorkflowService;
|
||||
use App\Services\Care\Surgery\SurgeryWorkflowService;
|
||||
use App\Services\Care\Vaccination\VaccinationWorkflowService;
|
||||
use App\Services\Care\Pathology\PathologyWorkflowService;
|
||||
use App\Services\Care\Infusion\InfusionWorkflowService;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
@@ -78,6 +81,9 @@ class SpecialtyShellService
|
||||
'oncology' => 'care.specialty.oncology.stage',
|
||||
'renal' => 'care.specialty.renal.stage',
|
||||
'surgery' => 'care.specialty.surgery.stage',
|
||||
'vaccination' => 'care.specialty.vaccination.stage',
|
||||
'pathology' => 'care.specialty.pathology.stage',
|
||||
'infusion' => 'care.specialty.infusion.stage',
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
@@ -104,6 +110,9 @@ class SpecialtyShellService
|
||||
'oncology' => app(OncologyWorkflowService::class)->stageFlow(),
|
||||
'renal' => app(RenalWorkflowService::class)->stageFlow(),
|
||||
'surgery' => app(SurgeryWorkflowService::class)->stageFlow(),
|
||||
'vaccination' => app(VaccinationWorkflowService::class)->stageFlow(),
|
||||
'pathology' => app(PathologyWorkflowService::class)->stageFlow(),
|
||||
'infusion' => app(InfusionWorkflowService::class)->stageFlow(),
|
||||
'dentistry' => [
|
||||
'waiting' => ['next' => 'chair', 'label' => 'Seat at chair'],
|
||||
'chair' => ['next' => 'procedure', 'label' => 'Start procedure'],
|
||||
@@ -403,7 +412,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'], 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'], true) && $visitIds->isNotEmpty()) {
|
||||
$count = Visit::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->whereIn('id', $visitIds)
|
||||
@@ -445,6 +454,9 @@ class SpecialtyShellService
|
||||
'oncology' => $clinical->countOpenByType($organization, 'oncology', 'onc_staging', $branchScope),
|
||||
'renal' => $clinical->countOpenByType($organization, 'renal', 'renal_exam', $branchScope),
|
||||
'surgery' => $clinical->countOpenByType($organization, 'surgery', 'surg_exam', $branchScope),
|
||||
'vaccination' => $clinical->countOpenByType($organization, 'vaccination', 'vax_eligibility', $branchScope),
|
||||
'pathology' => $clinical->countOpenByType($organization, 'pathology', 'path_request', $branchScope),
|
||||
'infusion' => $clinical->countOpenByType($organization, 'infusion', 'infusion_assessment', $branchScope),
|
||||
'dentistry' => \App\Models\DentalPlanItem::query()
|
||||
->whereHas('plan', function ($q) use ($organization, $ownerRef) {
|
||||
$q->owned($ownerRef)
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Care\Vaccination;
|
||||
|
||||
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 VaccinationAnalyticsService
|
||||
{
|
||||
public function __construct(
|
||||
protected SpecialtyShellService $shell,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* arrivals_today: int,
|
||||
* completed_today: int,
|
||||
* observation_open: int,
|
||||
* vaccine_breakdown: Collection,
|
||||
* aefi_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, 'vaccination', $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');
|
||||
|
||||
$observationOpen = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'vaccination')
|
||||
->where('record_type', 'vax_observation')
|
||||
->whereIn('visit_id', $openVisitIds->isEmpty() ? [0] : $openVisitIds)
|
||||
->where('status', '!=', SpecialtyClinicalRecord::STATUS_COMPLETED)
|
||||
->count();
|
||||
|
||||
$adminRecords = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'vaccination')
|
||||
->where('record_type', 'vax_admin')
|
||||
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
|
||||
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
|
||||
->get();
|
||||
|
||||
$vaccineBreakdown = $adminRecords
|
||||
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['vaccine'] ?? 'Unknown'))
|
||||
->map(fn (Collection $rows, string $vaccine) => [
|
||||
'vaccine' => $vaccine,
|
||||
'total' => $rows->count(),
|
||||
])
|
||||
->values()
|
||||
->sortByDesc('total')
|
||||
->values();
|
||||
|
||||
$observationRecords = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'vaccination')
|
||||
->where('record_type', 'vax_observation')
|
||||
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
|
||||
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
|
||||
->get();
|
||||
|
||||
$aefiBreakdown = $observationRecords
|
||||
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['aefi'] ?? 'None'))
|
||||
->map(fn (Collection $rows, string $aefi) => [
|
||||
'aefi' => $aefi,
|
||||
'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, 'vaccination'))
|
||||
->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,
|
||||
'observation_open' => $observationOpen,
|
||||
'vaccine_breakdown' => $vaccineBreakdown,
|
||||
'aefi_breakdown' => $aefiBreakdown,
|
||||
'avg_los_minutes' => $avgLos,
|
||||
'revenue_by_service' => $revenueByService,
|
||||
'from' => $rangeFrom->toDateString(),
|
||||
'to' => $rangeTo->toDateString(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Care\Vaccination;
|
||||
|
||||
/**
|
||||
* Map vaccination clinical progress onto visit stages.
|
||||
*/
|
||||
class VaccinationWorkflowService
|
||||
{
|
||||
public const STAGE_CHECK_IN = 'check_in';
|
||||
|
||||
public const STAGE_ELIGIBILITY = 'eligibility';
|
||||
|
||||
public const STAGE_CONSENT = 'consent';
|
||||
|
||||
public const STAGE_ADMINISTER = 'administer';
|
||||
|
||||
public const STAGE_OBSERVATION = 'observation';
|
||||
|
||||
public const STAGE_COMPLETED = 'completed';
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromEligibility(array $payload): string
|
||||
{
|
||||
if (! empty($payload['cleared']) || ! empty($payload['vaccine'])) {
|
||||
return self::STAGE_ELIGIBILITY;
|
||||
}
|
||||
|
||||
return self::STAGE_CHECK_IN;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromConsent(array $payload): string
|
||||
{
|
||||
if (! empty($payload['consent_obtained'])) {
|
||||
return self::STAGE_ADMINISTER;
|
||||
}
|
||||
|
||||
if (! empty($payload['information_given'])) {
|
||||
return self::STAGE_CONSENT;
|
||||
}
|
||||
|
||||
return self::STAGE_ELIGIBILITY;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromAdmin(array $payload): string
|
||||
{
|
||||
$outcome = strtolower((string) ($payload['outcome'] ?? ''));
|
||||
if (str_contains($outcome, 'completed') || ! empty($payload['batch'])) {
|
||||
return self::STAGE_OBSERVATION;
|
||||
}
|
||||
|
||||
return self::STAGE_ADMINISTER;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromObservation(array $payload): string
|
||||
{
|
||||
if ($this->shouldCompleteVisit($payload)) {
|
||||
return self::STAGE_COMPLETED;
|
||||
}
|
||||
|
||||
$aefi = strtolower((string) ($payload['aefi'] ?? ''));
|
||||
if ($aefi !== '' || ! empty($payload['outcome'])) {
|
||||
return self::STAGE_OBSERVATION;
|
||||
}
|
||||
|
||||
return self::STAGE_ADMINISTER;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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_ELIGIBILITY, 'label' => 'Start eligibility'],
|
||||
self::STAGE_ELIGIBILITY => ['next' => self::STAGE_CONSENT, 'label' => 'Move to consent'],
|
||||
self::STAGE_CONSENT => ['next' => self::STAGE_ADMINISTER, 'label' => 'Move to administer'],
|
||||
self::STAGE_ADMINISTER => ['next' => self::STAGE_OBSERVATION, 'label' => 'Move to observation'],
|
||||
self::STAGE_OBSERVATION => ['next' => self::STAGE_COMPLETED, 'label' => 'Complete visit'],
|
||||
self::STAGE_COMPLETED => ['next' => self::STAGE_COMPLETED, 'label' => 'Completed'],
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user