Add full Vaccination, Pathology, and Infusion specialty clinical suites.
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:
isaacclad
2026-07-19 21:39:15 +00:00
co-authored by Cursor
parent b7e5a7d9ad
commit 7b722c71d0
34 changed files with 3508 additions and 24 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\Infusion\InfusionAnalyticsService;
use App\Services\Care\Infusion\InfusionWorkflowService;
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 InfusionWorkspaceController extends Controller
{
use ScopesToAccount;
protected function assertInfusionAccess(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanAccess($organization, $this->member($request), 'infusion'), 403);
}
protected function assertInfusionManage(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanManage($organization, $this->member($request), 'infusion'), 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->assertInfusionManage($request, $modules);
$this->assertVisit($request, $visit);
$validated = $request->validate([
'stage' => ['required', 'string', 'max:32'],
]);
try {
$stages->setStage(
$this->organization($request),
$visit,
'infusion',
$validated['stage'],
$this->ownerRef($request),
$this->actorRef($request),
);
} catch (\InvalidArgumentException $e) {
return back()->with('error', $e->getMessage());
}
return redirect()
->route('care.specialty.workspace', [
'module' => 'infusion',
'visit' => $visit,
'tab' => $shell->workspaceTabForStage('infusion', $validated['stage']),
])
->with('success', 'Visit stage updated.');
}
public function saveMonitoring(
Request $request,
Visit $visit,
SpecialtyModuleService $modules,
SpecialtyClinicalRecordService $clinical,
SpecialtyVisitStageService $stages,
InfusionWorkflowService $workflow,
): RedirectResponse {
$this->authorizeAbility($request, 'consultations.manage');
$this->assertInfusionManage($request, $modules);
$this->assertVisit($request, $visit);
$organization = $this->organization($request);
$owner = $this->ownerRef($request);
$payload = (array) $request->input('payload', []);
foreach ($clinical->fieldsFor('infusion', 'infusion_monitoring') as $field) {
if (($field['type'] ?? '') === 'boolean') {
$payload[$field['name']] = $request->boolean('payload.'.$field['name']);
}
}
$request->merge(['payload' => $payload, 'tab' => 'monitoring']);
$validated = $request->validate(array_merge([
'tab' => ['required', 'string'],
], $clinical->validationRules('infusion', 'infusion_monitoring')));
$record = $clinical->upsert(
$organization,
$visit,
'infusion',
'infusion_monitoring',
$clinical->payloadFromRequest($validated),
$owner,
$owner,
InfusionWorkflowService::STAGE_MONITORING,
SpecialtyClinicalRecord::STATUS_COMPLETED,
);
try {
$stages->setStage(
$organization,
$visit,
'infusion',
InfusionWorkflowService::STAGE_MONITORING,
$owner,
$owner,
);
} catch (\InvalidArgumentException) {
}
if ($workflow->shouldCompleteVisit($record->payload ?? [])) {
try {
$stages->setStage(
$organization,
$visit,
'infusion',
InfusionWorkflowService::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' => 'infusion', 'visit' => $visit, 'tab' => 'monitoring'])
->with('success', 'Infusion monitoring saved.');
}
public function reports(
Request $request,
SpecialtyModuleService $modules,
SpecialtyShellService $shell,
InfusionAnalyticsService $analytics,
): View {
$this->authorizeAbility($request, 'consultations.view');
$this->assertInfusionAccess($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.infusion.reports', [
'moduleKey' => 'infusion',
'definition' => $modules->definition('infusion'),
'shellNav' => $shell->navItems('infusion'),
'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->assertInfusionAccess($request, $modules);
$this->assertVisit($request, $visit);
$visit->loadMissing(['patient', 'appointment.practitioner', 'branch']);
return view('care.specialty.infusion.print', [
'visit' => $visit,
'patient' => $visit->patient,
'assessment' => $clinical->findForVisit($visit, 'infusion', 'infusion_assessment'),
'protocol' => $clinical->findForVisit($visit, 'infusion', 'infusion_protocol'),
'session' => $clinical->findForVisit($visit, 'infusion', 'infusion_session'),
'monitoring' => $clinical->findForVisit($visit, 'infusion', 'infusion_monitoring'),
]);
}
}
@@ -0,0 +1,215 @@
<?php
namespace App\Http\Controllers\Care;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Http\Controllers\Controller;
use App\Models\SpecialtyClinicalRecord;
use App\Models\Visit;
use App\Services\Care\Pathology\PathologyAnalyticsService;
use App\Services\Care\Pathology\PathologyWorkflowService;
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 PathologyWorkspaceController extends Controller
{
use ScopesToAccount;
protected function assertPathologyAccess(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanAccess($organization, $this->member($request), 'pathology'), 403);
}
protected function assertPathologyManage(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanManage($organization, $this->member($request), 'pathology'), 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->assertPathologyManage($request, $modules);
$this->assertVisit($request, $visit);
$validated = $request->validate([
'stage' => ['required', 'string', 'max:32'],
]);
try {
$stages->setStage(
$this->organization($request),
$visit,
'pathology',
$validated['stage'],
$this->ownerRef($request),
$this->actorRef($request),
);
} catch (\InvalidArgumentException $e) {
return back()->with('error', $e->getMessage());
}
return redirect()
->route('care.specialty.workspace', [
'module' => 'pathology',
'visit' => $visit,
'tab' => $shell->workspaceTabForStage('pathology', $validated['stage']),
])
->with('success', 'Visit stage updated.');
}
public function saveVerification(
Request $request,
Visit $visit,
SpecialtyModuleService $modules,
SpecialtyClinicalRecordService $clinical,
SpecialtyVisitStageService $stages,
PathologyWorkflowService $workflow,
): RedirectResponse {
$this->authorizeAbility($request, 'consultations.manage');
$this->assertPathologyManage($request, $modules);
$this->assertVisit($request, $visit);
$organization = $this->organization($request);
$owner = $this->ownerRef($request);
$payload = (array) $request->input('payload', []);
foreach ($clinical->fieldsFor('pathology', 'path_verification') as $field) {
if (($field['type'] ?? '') === 'boolean') {
$payload[$field['name']] = $request->boolean('payload.'.$field['name']);
}
}
$request->merge(['payload' => $payload, 'tab' => 'verification']);
$validated = $request->validate(array_merge([
'tab' => ['required', 'string'],
], $clinical->validationRules('pathology', 'path_verification')));
$record = $clinical->upsert(
$organization,
$visit,
'pathology',
'path_verification',
$clinical->payloadFromRequest($validated),
$owner,
$owner,
PathologyWorkflowService::STAGE_VERIFIED,
SpecialtyClinicalRecord::STATUS_COMPLETED,
);
try {
$stages->setStage(
$organization,
$visit,
'pathology',
PathologyWorkflowService::STAGE_VERIFIED,
$owner,
$owner,
);
} catch (\InvalidArgumentException) {
}
if ($workflow->shouldCompleteVisit($record->payload ?? [])) {
try {
$stages->setStage(
$organization,
$visit,
'pathology',
PathologyWorkflowService::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' => 'pathology', 'visit' => $visit, 'tab' => 'verification'])
->with('success', 'Pathology verification saved.');
}
public function reports(
Request $request,
SpecialtyModuleService $modules,
SpecialtyShellService $shell,
PathologyAnalyticsService $analytics,
): View {
$this->authorizeAbility($request, 'consultations.view');
$this->assertPathologyAccess($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.pathology.reports', [
'moduleKey' => 'pathology',
'definition' => $modules->definition('pathology'),
'shellNav' => $shell->navItems('pathology'),
'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->assertPathologyAccess($request, $modules);
$this->assertVisit($request, $visit);
$visit->loadMissing(['patient', 'appointment.practitioner', 'branch']);
return view('care.specialty.pathology.print', [
'visit' => $visit,
'patient' => $visit->patient,
'requestRecord' => $clinical->findForVisit($visit, 'pathology', 'path_request'),
'specimen' => $clinical->findForVisit($visit, 'pathology', 'path_specimen'),
'processing' => $clinical->findForVisit($visit, 'pathology', 'path_processing'),
'report' => $clinical->findForVisit($visit, 'pathology', 'path_report'),
'verification' => $clinical->findForVisit($visit, 'pathology', 'path_verification'),
]);
}
}
@@ -165,6 +165,9 @@ class SpecialtyModuleController extends Controller
'oncology' => 'history',
'renal' => 'history',
'surgery' => 'history',
'vaccination' => 'eligibility',
'pathology' => 'request',
'infusion' => 'assessment',
default => (collect(array_keys($shellTabs))
->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null)
?? 'clinical_notes'),
@@ -248,6 +251,9 @@ class SpecialtyModuleController extends Controller
'oncology' => 'history',
'renal' => 'history',
'surgery' => 'history',
'vaccination' => 'eligibility',
'pathology' => 'request',
'infusion' => 'assessment',
default => (collect(array_keys($shellTabs))
->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null)
?? 'clinical_notes'),
@@ -915,6 +921,104 @@ class SpecialtyModuleController extends Controller
}
}
if ($module === 'vaccination' && in_array($recordType, ['vax_eligibility', 'vax_consent', 'vax_admin'], true)) {
$workflow = app(\App\Services\Care\Vaccination\VaccinationWorkflowService::class);
$stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
$suggested = match ($recordType) {
'vax_eligibility' => $workflow->stageFromEligibility($record->payload ?? []),
'vax_consent' => $workflow->stageFromConsent($record->payload ?? []),
'vax_admin' => $workflow->stageFromAdmin($record->payload ?? []),
default => null,
};
$current = $visit->specialty_stage;
$early = ['check_in', 'waiting', null, ''];
$order = [
'check_in' => 0,
'eligibility' => 1,
'consent' => 2,
'administer' => 3,
'observation' => 4,
'completed' => 5,
];
if ($suggested && (! $current || in_array($current, $early, true))) {
try {
$stageService->setStage($organization, $visit, 'vaccination', $suggested, $this->ownerRef($request), $this->ownerRef($request));
} catch (\InvalidArgumentException) {
}
} elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
try {
$stageService->setStage($organization, $visit, 'vaccination', $suggested, $this->ownerRef($request), $this->ownerRef($request));
} catch (\InvalidArgumentException) {
}
}
}
if ($module === 'pathology' && in_array($recordType, ['path_request', 'path_specimen', 'path_processing', 'path_report'], true)) {
$workflow = app(\App\Services\Care\Pathology\PathologyWorkflowService::class);
$stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
$suggested = match ($recordType) {
'path_request' => $workflow->stageFromRequest($record->payload ?? []),
'path_specimen' => $workflow->stageFromSpecimen($record->payload ?? []),
'path_processing' => $workflow->stageFromProcessing($record->payload ?? []),
'path_report' => $workflow->stageFromReport($record->payload ?? []),
default => null,
};
$current = $visit->specialty_stage;
$early = ['check_in', 'waiting', null, ''];
$order = [
'check_in' => 0,
'request' => 1,
'specimen' => 2,
'processing' => 3,
'report' => 4,
'verified' => 5,
'completed' => 6,
];
if ($suggested && (! $current || in_array($current, $early, true))) {
try {
$stageService->setStage($organization, $visit, 'pathology', $suggested, $this->ownerRef($request), $this->ownerRef($request));
} catch (\InvalidArgumentException) {
}
} elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
try {
$stageService->setStage($organization, $visit, 'pathology', $suggested, $this->ownerRef($request), $this->ownerRef($request));
} catch (\InvalidArgumentException) {
}
}
}
if ($module === 'infusion' && in_array($recordType, ['infusion_assessment', 'infusion_protocol', 'infusion_session'], true)) {
$workflow = app(\App\Services\Care\Infusion\InfusionWorkflowService::class);
$stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
$suggested = match ($recordType) {
'infusion_assessment' => $workflow->stageFromAssessment($record->payload ?? []),
'infusion_protocol' => $workflow->stageFromProtocol($record->payload ?? []),
'infusion_session' => $workflow->stageFromSession($record->payload ?? []),
default => null,
};
$current = $visit->specialty_stage;
$early = ['check_in', 'waiting', null, ''];
$order = [
'check_in' => 0,
'assessment' => 1,
'protocol' => 2,
'session' => 3,
'monitoring' => 4,
'completed' => 5,
];
if ($suggested && (! $current || in_array($current, $early, true))) {
try {
$stageService->setStage($organization, $visit, 'infusion', $suggested, $this->ownerRef($request), $this->ownerRef($request));
} catch (\InvalidArgumentException) {
}
} elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
try {
$stageService->setStage($organization, $visit, 'infusion', $suggested, $this->ownerRef($request), $this->ownerRef($request));
} catch (\InvalidArgumentException) {
}
}
}
return redirect()
->route('care.specialty.workspace', [
'module' => $module,
@@ -1392,6 +1496,25 @@ class SpecialtyModuleController extends Controller
$surgeryPostop = null;
$surgeryStageCodes = [];
$surgeryStageFlow = [];
$vaccinationEligibility = null;
$vaccinationConsent = null;
$vaccinationAdmin = null;
$vaccinationObservation = null;
$vaccinationStageCodes = [];
$vaccinationStageFlow = [];
$pathologyRequest = null;
$pathologySpecimen = null;
$pathologyProcessing = null;
$pathologyReport = null;
$pathologyVerification = null;
$pathologyStageCodes = [];
$pathologyStageFlow = [];
$infusionAssessment = null;
$infusionProtocol = null;
$infusionSession = null;
$infusionMonitoring = null;
$infusionStageCodes = [];
$infusionStageFlow = [];
$activeTab = (string) $request->query('tab', array_key_first($shell->workspaceTabs($module)) ?: 'overview');
$clinical = app(SpecialtyClinicalRecordService::class);
@@ -1616,6 +1739,34 @@ class SpecialtyModuleController extends Controller
$surgeryStageFlow = app(\App\Services\Care\Surgery\SurgeryWorkflowService::class)->stageFlow();
}
if ($module === 'vaccination') {
$vaccinationEligibility = $clinical->findForVisit($workspaceVisit, 'vaccination', 'vax_eligibility');
$vaccinationConsent = $clinical->findForVisit($workspaceVisit, 'vaccination', 'vax_consent');
$vaccinationAdmin = $clinical->findForVisit($workspaceVisit, 'vaccination', 'vax_admin');
$vaccinationObservation = $clinical->findForVisit($workspaceVisit, 'vaccination', 'vax_observation');
$vaccinationStageCodes = collect($shell->stages('vaccination'))->pluck('code')->all();
$vaccinationStageFlow = app(\App\Services\Care\Vaccination\VaccinationWorkflowService::class)->stageFlow();
}
if ($module === 'pathology') {
$pathologyRequest = $clinical->findForVisit($workspaceVisit, 'pathology', 'path_request');
$pathologySpecimen = $clinical->findForVisit($workspaceVisit, 'pathology', 'path_specimen');
$pathologyProcessing = $clinical->findForVisit($workspaceVisit, 'pathology', 'path_processing');
$pathologyReport = $clinical->findForVisit($workspaceVisit, 'pathology', 'path_report');
$pathologyVerification = $clinical->findForVisit($workspaceVisit, 'pathology', 'path_verification');
$pathologyStageCodes = collect($shell->stages('pathology'))->pluck('code')->all();
$pathologyStageFlow = app(\App\Services\Care\Pathology\PathologyWorkflowService::class)->stageFlow();
}
if ($module === 'infusion') {
$infusionAssessment = $clinical->findForVisit($workspaceVisit, 'infusion', 'infusion_assessment');
$infusionProtocol = $clinical->findForVisit($workspaceVisit, 'infusion', 'infusion_protocol');
$infusionSession = $clinical->findForVisit($workspaceVisit, 'infusion', 'infusion_session');
$infusionMonitoring = $clinical->findForVisit($workspaceVisit, 'infusion', 'infusion_monitoring');
$infusionStageCodes = collect($shell->stages('infusion'))->pluck('code')->all();
$infusionStageFlow = app(\App\Services\Care\Infusion\InfusionWorkflowService::class)->stageFlow();
}
if ($patientHeader !== null) {
$patientHeader['clinical_alerts'] = $clinicalAlerts;
}
@@ -1785,6 +1936,25 @@ class SpecialtyModuleController extends Controller
'surgeryPostop' => $surgeryPostop,
'surgeryStageCodes' => $surgeryStageCodes,
'surgeryStageFlow' => $surgeryStageFlow,
'vaccinationEligibility' => $vaccinationEligibility,
'vaccinationConsent' => $vaccinationConsent,
'vaccinationAdmin' => $vaccinationAdmin,
'vaccinationObservation' => $vaccinationObservation,
'vaccinationStageCodes' => $vaccinationStageCodes,
'vaccinationStageFlow' => $vaccinationStageFlow,
'pathologyRequest' => $pathologyRequest,
'pathologySpecimen' => $pathologySpecimen,
'pathologyProcessing' => $pathologyProcessing,
'pathologyReport' => $pathologyReport,
'pathologyVerification' => $pathologyVerification,
'pathologyStageCodes' => $pathologyStageCodes,
'pathologyStageFlow' => $pathologyStageFlow,
'infusionAssessment' => $infusionAssessment,
'infusionProtocol' => $infusionProtocol,
'infusionSession' => $infusionSession,
'infusionMonitoring' => $infusionMonitoring,
'infusionStageCodes' => $infusionStageCodes,
'infusionStageFlow' => $infusionStageFlow,
'queueStubs' => $modules->queueStubsFor($organization, $module),
'branchId' => $branchId,
'branchLabel' => $branchLabel,
@@ -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\SpecialtyClinicalRecordService;
use App\Services\Care\SpecialtyModuleService;
use App\Services\Care\SpecialtyShellService;
use App\Services\Care\SpecialtyVisitStageService;
use App\Services\Care\Vaccination\VaccinationAnalyticsService;
use App\Services\Care\Vaccination\VaccinationWorkflowService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
class VaccinationWorkspaceController extends Controller
{
use ScopesToAccount;
protected function assertVaccinationAccess(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanAccess($organization, $this->member($request), 'vaccination'), 403);
}
protected function assertVaccinationManage(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanManage($organization, $this->member($request), 'vaccination'), 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->assertVaccinationManage($request, $modules);
$this->assertVisit($request, $visit);
$validated = $request->validate([
'stage' => ['required', 'string', 'max:32'],
]);
try {
$stages->setStage(
$this->organization($request),
$visit,
'vaccination',
$validated['stage'],
$this->ownerRef($request),
$this->actorRef($request),
);
} catch (\InvalidArgumentException $e) {
return back()->with('error', $e->getMessage());
}
return redirect()
->route('care.specialty.workspace', [
'module' => 'vaccination',
'visit' => $visit,
'tab' => $shell->workspaceTabForStage('vaccination', $validated['stage']),
])
->with('success', 'Visit stage updated.');
}
public function saveObservation(
Request $request,
Visit $visit,
SpecialtyModuleService $modules,
SpecialtyClinicalRecordService $clinical,
SpecialtyVisitStageService $stages,
VaccinationWorkflowService $workflow,
): RedirectResponse {
$this->authorizeAbility($request, 'consultations.manage');
$this->assertVaccinationManage($request, $modules);
$this->assertVisit($request, $visit);
$organization = $this->organization($request);
$owner = $this->ownerRef($request);
$payload = (array) $request->input('payload', []);
foreach ($clinical->fieldsFor('vaccination', 'vax_observation') as $field) {
if (($field['type'] ?? '') === 'boolean') {
$payload[$field['name']] = $request->boolean('payload.'.$field['name']);
}
}
$request->merge(['payload' => $payload, 'tab' => 'observation']);
$validated = $request->validate(array_merge([
'tab' => ['required', 'string'],
], $clinical->validationRules('vaccination', 'vax_observation')));
$record = $clinical->upsert(
$organization,
$visit,
'vaccination',
'vax_observation',
$clinical->payloadFromRequest($validated),
$owner,
$owner,
VaccinationWorkflowService::STAGE_OBSERVATION,
SpecialtyClinicalRecord::STATUS_COMPLETED,
);
try {
$stages->setStage(
$organization,
$visit,
'vaccination',
VaccinationWorkflowService::STAGE_OBSERVATION,
$owner,
$owner,
);
} catch (\InvalidArgumentException) {
}
if ($workflow->shouldCompleteVisit($record->payload ?? [])) {
try {
$stages->setStage(
$organization,
$visit,
'vaccination',
VaccinationWorkflowService::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' => 'vaccination', 'visit' => $visit, 'tab' => 'observation'])
->with('success', 'Vaccination observation saved.');
}
public function reports(
Request $request,
SpecialtyModuleService $modules,
SpecialtyShellService $shell,
VaccinationAnalyticsService $analytics,
): View {
$this->authorizeAbility($request, 'consultations.view');
$this->assertVaccinationAccess($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.vaccination.reports', [
'moduleKey' => 'vaccination',
'definition' => $modules->definition('vaccination'),
'shellNav' => $shell->navItems('vaccination'),
'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->assertVaccinationAccess($request, $modules);
$this->assertVisit($request, $visit);
$visit->loadMissing(['patient', 'appointment.practitioner', 'branch']);
return view('care.specialty.vaccination.print', [
'visit' => $visit,
'patient' => $visit->patient,
'eligibility' => $clinical->findForVisit($visit, 'vaccination', 'vax_eligibility'),
'consent' => $clinical->findForVisit($visit, 'vaccination', 'vax_consent'),
'admin' => $clinical->findForVisit($visit, 'vaccination', 'vax_admin'),
'observation' => $clinical->findForVisit($visit, 'vaccination', 'vax_observation'),
]);
}
}
+224
View File
@@ -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' => 'A1A2',
'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')) {
+13 -1
View File
@@ -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'],
];
}
}