Add full Radiology, Cardiology, and Psychiatry specialty clinical suites.
Deploy Ladill Care / deploy (push) Successful in 49s

Mirror the Ophthalmology/Maternity shell pattern with stages, stage_tabs,
workspace clinical records, reports/print, demo seeds, and suite tests.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
isaacclad
2026-07-19 18:41:55 +00:00
co-authored by Cursor
parent b3805023b1
commit 8e23cdeae3
36 changed files with 3932 additions and 34 deletions
@@ -0,0 +1,215 @@
<?php
namespace App\Http\Controllers\Care;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Http\Controllers\Controller;
use App\Models\SpecialtyClinicalRecord;
use App\Models\Visit;
use App\Services\Care\Cardiology\CardiologyAnalyticsService;
use App\Services\Care\Cardiology\CardiologyWorkflowService;
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 CardiologyWorkspaceController extends Controller
{
use ScopesToAccount;
protected function assertCardiologyAccess(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanAccess($organization, $this->member($request), 'cardiology'), 403);
}
protected function assertCardiologyManage(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanManage($organization, $this->member($request), 'cardiology'), 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->assertCardiologyManage($request, $modules);
$this->assertVisit($request, $visit);
$validated = $request->validate([
'stage' => ['required', 'string', 'max:32'],
]);
try {
$stages->setStage(
$this->organization($request),
$visit,
'cardiology',
$validated['stage'],
$this->ownerRef($request),
$this->actorRef($request),
);
} catch (\InvalidArgumentException $e) {
return back()->with('error', $e->getMessage());
}
return redirect()
->route('care.specialty.workspace', [
'module' => 'cardiology',
'visit' => $visit,
'tab' => $shell->workspaceTabForStage('cardiology', $validated['stage']),
])
->with('success', 'Visit stage updated.');
}
public function saveProcedure(
Request $request,
Visit $visit,
SpecialtyModuleService $modules,
SpecialtyClinicalRecordService $clinical,
SpecialtyVisitStageService $stages,
CardiologyWorkflowService $workflow,
): RedirectResponse {
$this->authorizeAbility($request, 'consultations.manage');
$this->assertCardiologyManage($request, $modules);
$this->assertVisit($request, $visit);
$organization = $this->organization($request);
$owner = $this->ownerRef($request);
$payload = (array) $request->input('payload', []);
foreach ($clinical->fieldsFor('cardiology', 'cardio_procedure') as $field) {
if (($field['type'] ?? '') === 'boolean') {
$payload[$field['name']] = $request->boolean('payload.'.$field['name']);
}
}
$request->merge(['payload' => $payload, 'tab' => 'procedures']);
$validated = $request->validate(array_merge([
'tab' => ['required', 'string'],
], $clinical->validationRules('cardiology', 'cardio_procedure')));
$record = $clinical->upsert(
$organization,
$visit,
'cardiology',
'cardio_procedure',
$clinical->payloadFromRequest($validated),
$owner,
$owner,
CardiologyWorkflowService::STAGE_PROCEDURE,
SpecialtyClinicalRecord::STATUS_COMPLETED,
);
try {
$stages->setStage(
$organization,
$visit,
'cardiology',
CardiologyWorkflowService::STAGE_PROCEDURE,
$owner,
$owner,
);
} catch (\InvalidArgumentException) {
}
if ($workflow->shouldCompleteVisit($record->payload ?? [])) {
try {
$stages->setStage(
$organization,
$visit,
'cardiology',
CardiologyWorkflowService::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' => 'cardiology', 'visit' => $visit, 'tab' => 'procedures'])
->with('success', 'Procedure / intervention saved.');
}
public function reports(
Request $request,
SpecialtyModuleService $modules,
SpecialtyShellService $shell,
CardiologyAnalyticsService $analytics,
): View {
$this->authorizeAbility($request, 'consultations.view');
$this->assertCardiologyAccess($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.cardiology.reports', [
'moduleKey' => 'cardiology',
'definition' => $modules->definition('cardiology'),
'shellNav' => $shell->navItems('cardiology'),
'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->assertCardiologyAccess($request, $modules);
$this->assertVisit($request, $visit);
$visit->loadMissing(['patient', 'appointment.practitioner', 'branch']);
return view('care.specialty.cardiology.print', [
'visit' => $visit,
'patient' => $visit->patient,
'history' => $clinical->findForVisit($visit, 'cardiology', 'cardio_history'),
'exam' => $clinical->findForVisit($visit, 'cardiology', 'cardiac_exam'),
'investigation' => $clinical->findForVisit($visit, 'cardiology', 'cardio_investigation'),
'plan' => $clinical->findForVisit($visit, 'cardiology', 'cardio_plan'),
'procedure' => $clinical->findForVisit($visit, 'cardiology', 'cardio_procedure'),
]);
}
}
@@ -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\Psychiatry\PsychiatryAnalyticsService;
use App\Services\Care\Psychiatry\PsychiatryWorkflowService;
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 PsychiatryWorkspaceController extends Controller
{
use ScopesToAccount;
protected function assertPsychiatryAccess(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanAccess($organization, $this->member($request), 'psychiatry'), 403);
}
protected function assertPsychiatryManage(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanManage($organization, $this->member($request), 'psychiatry'), 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->assertPsychiatryManage($request, $modules);
$this->assertVisit($request, $visit);
$validated = $request->validate([
'stage' => ['required', 'string', 'max:32'],
]);
try {
$stages->setStage(
$this->organization($request),
$visit,
'psychiatry',
$validated['stage'],
$this->ownerRef($request),
$this->actorRef($request),
);
} catch (\InvalidArgumentException $e) {
return back()->with('error', $e->getMessage());
}
return redirect()
->route('care.specialty.workspace', [
'module' => 'psychiatry',
'visit' => $visit,
'tab' => $shell->workspaceTabForStage('psychiatry', $validated['stage']),
])
->with('success', 'Visit stage updated.');
}
public function saveFollowUp(
Request $request,
Visit $visit,
SpecialtyModuleService $modules,
SpecialtyClinicalRecordService $clinical,
SpecialtyVisitStageService $stages,
PsychiatryWorkflowService $workflow,
): RedirectResponse {
$this->authorizeAbility($request, 'consultations.manage');
$this->assertPsychiatryManage($request, $modules);
$this->assertVisit($request, $visit);
$organization = $this->organization($request);
$owner = $this->ownerRef($request);
$payload = (array) $request->input('payload', []);
foreach ($clinical->fieldsFor('psychiatry', 'psych_followup') as $field) {
if (($field['type'] ?? '') === 'boolean') {
$payload[$field['name']] = $request->boolean('payload.'.$field['name']);
}
}
$request->merge(['payload' => $payload, 'tab' => 'followup']);
$validated = $request->validate(array_merge([
'tab' => ['required', 'string'],
], $clinical->validationRules('psychiatry', 'psych_followup')));
$record = $clinical->upsert(
$organization,
$visit,
'psychiatry',
'psych_followup',
$clinical->payloadFromRequest($validated),
$owner,
$owner,
PsychiatryWorkflowService::STAGE_REVIEW,
SpecialtyClinicalRecord::STATUS_COMPLETED,
);
try {
$stages->setStage(
$organization,
$visit,
'psychiatry',
PsychiatryWorkflowService::STAGE_REVIEW,
$owner,
$owner,
);
} catch (\InvalidArgumentException) {
}
if ($workflow->shouldCompleteVisit($record->payload ?? [])) {
try {
$stages->setStage(
$organization,
$visit,
'psychiatry',
PsychiatryWorkflowService::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' => 'psychiatry', 'visit' => $visit, 'tab' => 'followup'])
->with('success', 'Follow-up review saved.');
}
public function reports(
Request $request,
SpecialtyModuleService $modules,
SpecialtyShellService $shell,
PsychiatryAnalyticsService $analytics,
): View {
$this->authorizeAbility($request, 'consultations.view');
$this->assertPsychiatryAccess($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.psychiatry.reports', [
'moduleKey' => 'psychiatry',
'definition' => $modules->definition('psychiatry'),
'shellNav' => $shell->navItems('psychiatry'),
'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->assertPsychiatryAccess($request, $modules);
$this->assertVisit($request, $visit);
$visit->loadMissing(['patient', 'appointment.practitioner', 'branch']);
return view('care.specialty.psychiatry.print', [
'visit' => $visit,
'patient' => $visit->patient,
'history' => $clinical->findForVisit($visit, 'psychiatry', 'mental_status'),
'risk' => $clinical->findForVisit($visit, 'psychiatry', 'risk_assessment'),
'plan' => $clinical->findForVisit($visit, 'psychiatry', 'psych_plan'),
'followup' => $clinical->findForVisit($visit, 'psychiatry', 'psych_followup'),
]);
}
}
@@ -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\Radiology\RadiologyAnalyticsService;
use App\Services\Care\Radiology\RadiologyWorkflowService;
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 RadiologyWorkspaceController extends Controller
{
use ScopesToAccount;
protected function assertRadiologyAccess(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanAccess($organization, $this->member($request), 'radiology'), 403);
}
protected function assertRadiologyManage(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanManage($organization, $this->member($request), 'radiology'), 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->assertRadiologyManage($request, $modules);
$this->assertVisit($request, $visit);
$validated = $request->validate([
'stage' => ['required', 'string', 'max:32'],
]);
try {
$stages->setStage(
$this->organization($request),
$visit,
'radiology',
$validated['stage'],
$this->ownerRef($request),
$this->actorRef($request),
);
} catch (\InvalidArgumentException $e) {
return back()->with('error', $e->getMessage());
}
return redirect()
->route('care.specialty.workspace', [
'module' => 'radiology',
'visit' => $visit,
'tab' => $shell->workspaceTabForStage('radiology', $validated['stage']),
])
->with('success', 'Visit stage updated.');
}
public function saveVerification(
Request $request,
Visit $visit,
SpecialtyModuleService $modules,
SpecialtyClinicalRecordService $clinical,
SpecialtyVisitStageService $stages,
RadiologyWorkflowService $workflow,
): RedirectResponse {
$this->authorizeAbility($request, 'consultations.manage');
$this->assertRadiologyManage($request, $modules);
$this->assertVisit($request, $visit);
$organization = $this->organization($request);
$owner = $this->ownerRef($request);
$payload = (array) $request->input('payload', []);
foreach ($clinical->fieldsFor('radiology', 'imaging_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('radiology', 'imaging_verification')));
$record = $clinical->upsert(
$organization,
$visit,
'radiology',
'imaging_verification',
$clinical->payloadFromRequest($validated),
$owner,
$owner,
RadiologyWorkflowService::STAGE_VERIFIED,
SpecialtyClinicalRecord::STATUS_COMPLETED,
);
try {
$stages->setStage(
$organization,
$visit,
'radiology',
RadiologyWorkflowService::STAGE_VERIFIED,
$owner,
$owner,
);
} catch (\InvalidArgumentException) {
}
if ($workflow->shouldCompleteVisit($record->payload ?? [])) {
try {
$stages->setStage(
$organization,
$visit,
'radiology',
RadiologyWorkflowService::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' => 'radiology', 'visit' => $visit, 'tab' => 'verification'])
->with('success', 'Verification saved.');
}
public function reports(
Request $request,
SpecialtyModuleService $modules,
SpecialtyShellService $shell,
RadiologyAnalyticsService $analytics,
): View {
$this->authorizeAbility($request, 'consultations.view');
$this->assertRadiologyAccess($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.radiology.reports', [
'moduleKey' => 'radiology',
'definition' => $modules->definition('radiology'),
'shellNav' => $shell->navItems('radiology'),
'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->assertRadiologyAccess($request, $modules);
$this->assertVisit($request, $visit);
$visit->loadMissing(['patient', 'appointment.practitioner', 'branch']);
return view('care.specialty.radiology.print', [
'visit' => $visit,
'patient' => $visit->patient,
'imagingRequest' => $clinical->findForVisit($visit, 'radiology', 'imaging_request'),
'acquisition' => $clinical->findForVisit($visit, 'radiology', 'imaging_acquisition'),
'imagingReport' => $clinical->findForVisit($visit, 'radiology', 'imaging_report'),
'verification' => $clinical->findForVisit($visit, 'radiology', 'imaging_verification'),
]);
}
}
@@ -156,6 +156,9 @@ class SpecialtyModuleController extends Controller
'ophthalmology' => 'refraction',
'physiotherapy' => 'assessment',
'maternity' => 'history',
'radiology' => 'protocol',
'cardiology' => 'history',
'psychiatry' => 'history',
default => (collect(array_keys($shellTabs))
->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null)
?? 'clinical_notes'),
@@ -230,6 +233,9 @@ class SpecialtyModuleController extends Controller
'ophthalmology' => 'refraction',
'physiotherapy' => 'assessment',
'maternity' => 'history',
'radiology' => 'protocol',
'cardiology' => 'history',
'psychiatry' => 'history',
default => (collect(array_keys($shellTabs))
->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null)
?? 'clinical_notes'),
@@ -510,6 +516,146 @@ class SpecialtyModuleController extends Controller
}
}
if ($module === 'radiology' && in_array($recordType, ['imaging_request', 'imaging_acquisition', 'imaging_report'], true)) {
$workflow = app(\App\Services\Care\Radiology\RadiologyWorkflowService::class);
$stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
$suggested = match ($recordType) {
'imaging_request' => $workflow->stageFromRequest($record->payload ?? []),
'imaging_acquisition' => $workflow->stageFromAcquisition($record->payload ?? []),
'imaging_report' => $workflow->stageFromReport($record->payload ?? []),
default => null,
};
$current = $visit->specialty_stage;
$early = ['check_in', 'waiting', 'request', null, ''];
$order = [
'check_in' => 0,
'protocol' => 1,
'acquisition' => 2,
'reporting' => 3,
'verified' => 4,
'completed' => 5,
];
if ($suggested && (! $current || in_array($current, $early, true))) {
try {
$stageService->setStage(
$organization,
$visit,
'radiology',
$suggested,
$this->ownerRef($request),
$this->ownerRef($request),
);
} catch (\InvalidArgumentException) {
}
} elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
try {
$stageService->setStage(
$organization,
$visit,
'radiology',
$suggested,
$this->ownerRef($request),
$this->ownerRef($request),
);
} catch (\InvalidArgumentException) {
}
}
}
if ($module === 'cardiology' && in_array($recordType, ['cardio_history', 'cardiac_exam', 'cardio_investigation', 'cardio_plan'], true)) {
$workflow = app(\App\Services\Care\Cardiology\CardiologyWorkflowService::class);
$stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
$suggested = match ($recordType) {
'cardio_history' => $workflow->stageFromHistory($record->payload ?? []),
'cardiac_exam' => $workflow->stageFromExam($record->payload ?? []),
'cardio_investigation' => $workflow->stageFromInvestigation($record->payload ?? []),
'cardio_plan' => $workflow->stageFromPlan($record->payload ?? []),
default => null,
};
$current = $visit->specialty_stage;
$early = ['check_in', 'waiting', null, ''];
$order = [
'check_in' => 0,
'history' => 1,
'exam' => 2,
'investigation' => 3,
'plan' => 4,
'procedure' => 5,
'completed' => 6,
];
if ($suggested && (! $current || in_array($current, $early, true))) {
try {
$stageService->setStage(
$organization,
$visit,
'cardiology',
$suggested,
$this->ownerRef($request),
$this->ownerRef($request),
);
} catch (\InvalidArgumentException) {
}
} elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
try {
$stageService->setStage(
$organization,
$visit,
'cardiology',
$suggested,
$this->ownerRef($request),
$this->ownerRef($request),
);
} catch (\InvalidArgumentException) {
}
}
}
if ($module === 'psychiatry' && in_array($recordType, ['mental_status', 'risk_assessment', 'psych_plan'], true)) {
$workflow = app(\App\Services\Care\Psychiatry\PsychiatryWorkflowService::class);
$stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
$suggested = match ($recordType) {
'mental_status' => $workflow->stageFromHistory($record->payload ?? []),
'risk_assessment' => $workflow->stageFromRisk($record->payload ?? []),
'psych_plan' => $workflow->stageFromFormulation($record->payload ?? []),
default => null,
};
$current = $visit->specialty_stage;
$early = ['check_in', 'waiting', null, ''];
$order = [
'check_in' => 0,
'history' => 1,
'risk' => 2,
'formulation' => 3,
'review' => 4,
'completed' => 5,
];
if ($suggested && (! $current || in_array($current, $early, true))) {
try {
$stageService->setStage(
$organization,
$visit,
'psychiatry',
$suggested,
$this->ownerRef($request),
$this->ownerRef($request),
);
} catch (\InvalidArgumentException) {
}
} elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
try {
$stageService->setStage(
$organization,
$visit,
'psychiatry',
$suggested,
$this->ownerRef($request),
$this->ownerRef($request),
);
} catch (\InvalidArgumentException) {
}
}
}
return redirect()
->route('care.specialty.workspace', [
'module' => $module,
@@ -926,6 +1072,25 @@ class SpecialtyModuleController extends Controller
$maternityPostnatal = null;
$maternityStageCodes = [];
$maternityStageFlow = [];
$radiologyRequest = null;
$radiologyAcquisition = null;
$radiologyReport = null;
$radiologyVerification = null;
$radiologyStageCodes = [];
$radiologyStageFlow = [];
$cardiologyHistory = null;
$cardiologyExam = null;
$cardiologyInvestigation = null;
$cardiologyPlan = null;
$cardiologyProcedure = null;
$cardiologyStageCodes = [];
$cardiologyStageFlow = [];
$psychiatryHistory = null;
$psychiatryRisk = null;
$psychiatryPlan = null;
$psychiatryFollowup = null;
$psychiatryStageCodes = [];
$psychiatryStageFlow = [];
$activeTab = (string) $request->query('tab', array_key_first($shell->workspaceTabs($module)) ?: 'overview');
$clinical = app(SpecialtyClinicalRecordService::class);
@@ -1062,6 +1227,34 @@ class SpecialtyModuleController extends Controller
$maternityStageFlow = app(\App\Services\Care\Maternity\MaternityWorkflowService::class)->stageFlow();
}
if ($module === 'radiology') {
$radiologyRequest = $clinical->findForVisit($workspaceVisit, 'radiology', 'imaging_request');
$radiologyAcquisition = $clinical->findForVisit($workspaceVisit, 'radiology', 'imaging_acquisition');
$radiologyReport = $clinical->findForVisit($workspaceVisit, 'radiology', 'imaging_report');
$radiologyVerification = $clinical->findForVisit($workspaceVisit, 'radiology', 'imaging_verification');
$radiologyStageCodes = collect($shell->stages('radiology'))->pluck('code')->all();
$radiologyStageFlow = app(\App\Services\Care\Radiology\RadiologyWorkflowService::class)->stageFlow();
}
if ($module === 'cardiology') {
$cardiologyHistory = $clinical->findForVisit($workspaceVisit, 'cardiology', 'cardio_history');
$cardiologyExam = $clinical->findForVisit($workspaceVisit, 'cardiology', 'cardiac_exam');
$cardiologyInvestigation = $clinical->findForVisit($workspaceVisit, 'cardiology', 'cardio_investigation');
$cardiologyPlan = $clinical->findForVisit($workspaceVisit, 'cardiology', 'cardio_plan');
$cardiologyProcedure = $clinical->findForVisit($workspaceVisit, 'cardiology', 'cardio_procedure');
$cardiologyStageCodes = collect($shell->stages('cardiology'))->pluck('code')->all();
$cardiologyStageFlow = app(\App\Services\Care\Cardiology\CardiologyWorkflowService::class)->stageFlow();
}
if ($module === 'psychiatry') {
$psychiatryHistory = $clinical->findForVisit($workspaceVisit, 'psychiatry', 'mental_status');
$psychiatryRisk = $clinical->findForVisit($workspaceVisit, 'psychiatry', 'risk_assessment');
$psychiatryPlan = $clinical->findForVisit($workspaceVisit, 'psychiatry', 'psych_plan');
$psychiatryFollowup = $clinical->findForVisit($workspaceVisit, 'psychiatry', 'psych_followup');
$psychiatryStageCodes = collect($shell->stages('psychiatry'))->pluck('code')->all();
$psychiatryStageFlow = app(\App\Services\Care\Psychiatry\PsychiatryWorkflowService::class)->stageFlow();
}
if ($patientHeader !== null) {
$patientHeader['clinical_alerts'] = $clinicalAlerts;
}
@@ -1170,6 +1363,25 @@ class SpecialtyModuleController extends Controller
'maternityPostnatal' => $maternityPostnatal,
'maternityStageCodes' => $maternityStageCodes,
'maternityStageFlow' => $maternityStageFlow,
'radiologyRequest' => $radiologyRequest,
'radiologyAcquisition' => $radiologyAcquisition,
'radiologyReport' => $radiologyReport,
'radiologyVerification' => $radiologyVerification,
'radiologyStageCodes' => $radiologyStageCodes,
'radiologyStageFlow' => $radiologyStageFlow,
'cardiologyHistory' => $cardiologyHistory,
'cardiologyExam' => $cardiologyExam,
'cardiologyInvestigation' => $cardiologyInvestigation,
'cardiologyPlan' => $cardiologyPlan,
'cardiologyProcedure' => $cardiologyProcedure,
'cardiologyStageCodes' => $cardiologyStageCodes,
'cardiologyStageFlow' => $cardiologyStageFlow,
'psychiatryHistory' => $psychiatryHistory,
'psychiatryRisk' => $psychiatryRisk,
'psychiatryPlan' => $psychiatryPlan,
'psychiatryFollowup' => $psychiatryFollowup,
'psychiatryStageCodes' => $psychiatryStageCodes,
'psychiatryStageFlow' => $psychiatryStageFlow,
'queueStubs' => $modules->queueStubsFor($organization, $module),
'branchId' => $branchId,
'branchLabel' => $branchLabel,
@@ -0,0 +1,168 @@
<?php
namespace App\Services\Care\Cardiology;
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 CardiologyAnalyticsService
{
public function __construct(
protected SpecialtyShellService $shell,
) {}
/**
* @return array{
* arrivals_today: int,
* completed_today: int,
* high_risk_open: int,
* diagnosis_breakdown: Collection,
* procedure_breakdown: Collection,
* avg_los_minutes: ?float,
* revenue_by_service: Collection,
* from: string,
* to: string
* }
*/
public function report(
Organization $organization,
string $ownerRef,
?int $branchId = null,
?string $from = null,
?string $to = null,
): array {
$todayStart = now()->startOfDay();
$rangeFrom = $from ? Carbon::parse($from)->startOfDay() : now()->startOfMonth();
$rangeTo = $to ? Carbon::parse($to)->endOfDay() : now()->endOfDay();
$departmentIds = $this->shell->departmentIds($organization, 'cardiology', $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');
$highRiskOpen = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'cardiology')
->where('record_type', 'cardiac_exam')
->whereIn('visit_id', $openVisitIds->isEmpty() ? [0] : $openVisitIds)
->get()
->filter(function (SpecialtyClinicalRecord $r) {
$nyha = (string) ($r->payload['nyha_class'] ?? '');
return in_array($nyha, ['III', 'IV'], true);
})
->count();
$planRecords = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'cardiology')
->where('record_type', 'cardio_plan')
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
->get();
$diagnosisBreakdown = $planRecords
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['diagnosis'] ?? 'Unknown'))
->map(fn (Collection $rows, string $diagnosis) => [
'diagnosis' => $diagnosis,
'total' => $rows->count(),
])
->values()
->sortByDesc('total')
->values();
$procedureRecords = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'cardiology')
->where('record_type', 'cardio_procedure')
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
->get();
$procedureBreakdown = $procedureRecords
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['procedure'] ?? 'Unknown'))
->map(fn (Collection $rows, string $procedure) => [
'procedure' => $procedure,
'total' => $rows->count(),
])
->values()
->sortByDesc('total')
->values();
$completedVisits = Visit::owned($ownerRef)
->where('organization_id', $organization->id)
->whereIn('id', $visitIds->isEmpty() ? [0] : $visitIds)
->where('status', Visit::STATUS_COMPLETED)
->whereBetween('completed_at', [$rangeFrom, $rangeTo])
->whereNotNull('checked_in_at')
->whereNotNull('completed_at')
->get();
$avgLos = null;
if ($completedVisits->isNotEmpty()) {
$avgLos = round($completedVisits->avg(function (Visit $visit) {
return $visit->checked_in_at->diffInMinutes($visit->completed_at);
}), 1);
}
$serviceLabels = collect($this->shell->provisionedServices($organization, 'cardiology'))
->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,
'high_risk_open' => $highRiskOpen,
'diagnosis_breakdown' => $diagnosisBreakdown,
'procedure_breakdown' => $procedureBreakdown,
'avg_los_minutes' => $avgLos,
'revenue_by_service' => $revenueByService,
'from' => $rangeFrom->toDateString(),
'to' => $rangeTo->toDateString(),
];
}
}
@@ -0,0 +1,104 @@
<?php
namespace App\Services\Care\Cardiology;
/**
* Map cardiology clinical progress onto visit stages.
*/
class CardiologyWorkflowService
{
public const STAGE_CHECK_IN = 'check_in';
public const STAGE_HISTORY = 'history';
public const STAGE_EXAM = 'exam';
public const STAGE_INVESTIGATION = 'investigation';
public const STAGE_PLAN = 'plan';
public const STAGE_PROCEDURE = 'procedure';
public const STAGE_COMPLETED = 'completed';
/**
* @param array<string, mixed> $payload
*/
public function stageFromHistory(array $payload): string
{
$history = trim((string) ($payload['history'] ?? ''));
if ($history !== '') {
return self::STAGE_HISTORY;
}
return self::STAGE_CHECK_IN;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromExam(array $payload): string
{
if (! empty($payload['ecg_findings']) || ! empty($payload['chief_complaint'])) {
return self::STAGE_EXAM;
}
return self::STAGE_HISTORY;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromInvestigation(array $payload): string
{
$findings = trim((string) ($payload['findings'] ?? ''));
if ($findings !== '') {
return self::STAGE_INVESTIGATION;
}
return self::STAGE_EXAM;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromPlan(array $payload): string
{
if (! empty($payload['procedure_planned'])) {
return self::STAGE_PROCEDURE;
}
$plan = trim((string) ($payload['plan'] ?? ''));
if ($plan !== '') {
return self::STAGE_PLAN;
}
return self::STAGE_INVESTIGATION;
}
/**
* @param array<string, mixed> $payload
*/
public function shouldCompleteVisit(array $payload): bool
{
$outcome = strtolower((string) ($payload['outcome'] ?? ''));
return str_contains($outcome, 'completed');
}
/**
* @return array<string, array{next: string, label: string}>
*/
public function stageFlow(): array
{
return [
self::STAGE_CHECK_IN => ['next' => self::STAGE_HISTORY, 'label' => 'Start history'],
self::STAGE_HISTORY => ['next' => self::STAGE_EXAM, 'label' => 'Move to exam / ECG'],
self::STAGE_EXAM => ['next' => self::STAGE_INVESTIGATION, 'label' => 'Move to investigations'],
self::STAGE_INVESTIGATION => ['next' => self::STAGE_PLAN, 'label' => 'Move to diagnosis & plan'],
self::STAGE_PLAN => ['next' => self::STAGE_PROCEDURE, 'label' => 'Move to procedure'],
self::STAGE_PROCEDURE => ['next' => self::STAGE_COMPLETED, 'label' => 'Complete visit'],
self::STAGE_COMPLETED => ['next' => self::STAGE_COMPLETED, 'label' => 'Completed'],
];
}
}
+349
View File
@@ -1017,6 +1017,9 @@ class DemoTenantSeeder
$this->seedOphthalmologyClinicalDemo($organization, $ownerRef);
$this->seedPhysiotherapyClinicalDemo($organization, $ownerRef);
$this->seedMaternityClinicalDemo($organization, $ownerRef);
$this->seedRadiologyClinicalDemo($organization, $ownerRef);
$this->seedCardiologyClinicalDemo($organization, $ownerRef);
$this->seedPsychiatryClinicalDemo($organization, $ownerRef);
return $count;
}
@@ -1507,6 +1510,352 @@ class DemoTenantSeeder
}
}
private function seedRadiologyClinicalDemo(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', 'radiology')
->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,
'radiology',
'imaging_request',
[
'modality' => $urgent ? 'CT' : 'X-ray',
'body_part' => $urgent ? 'Chest' : 'Left ankle',
'clinical_info' => $urgent
? 'Shortness of breath; rule out PE / infiltrates'
: 'Trauma — query fracture after fall',
'urgency' => $urgent ? 'STAT' : 'Routine',
'contrast' => $urgent ? 'IV' : 'None',
'protocol' => $urgent ? 'CTPA protocol' : 'AP / lateral',
'referrer' => 'Demo ER / Ortho',
],
$ownerRef,
$ownerRef,
'protocol',
);
$clinical->upsert(
$organization,
$visit,
'radiology',
'imaging_acquisition',
[
'technologist' => 'Demo Tech',
'equipment' => $urgent ? 'CT 1' : 'XR Bay A',
'acquisition_status' => 'Acquired',
'contrast_given' => $urgent,
'dose_notes' => $urgent ? 'Standard CTPA dose' : 'Low dose extremity',
'quality' => 'Diagnostic',
'notes' => 'Demo acquisition for radiology suite.',
],
$ownerRef,
$ownerRef,
'acquisition',
);
if ($urgent) {
$clinical->upsert(
$organization,
$visit,
'radiology',
'imaging_report',
[
'technique' => 'CT pulmonary angiogram with IV contrast',
'comparison' => 'None available',
'findings' => 'No filling defect in main or segmental pulmonary arteries. Mild basilar atelectasis.',
'impression' => 'No CT evidence of pulmonary embolism.',
'recommendations' => 'Clinical correlation; consider alternative causes of dyspnoea.',
'critical_result' => false,
],
$ownerRef,
$ownerRef,
'reporting',
);
}
if (! $visit->specialty_stage) {
$visit->update(['specialty_stage' => $urgent ? 'reporting' : 'acquisition']);
}
$index++;
}
}
private function seedCardiologyClinicalDemo(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', 'cardiology')
->where('is_active', true)
->pluck('id');
if ($departmentIds->isEmpty()) {
return;
}
$appointments = Appointment::owned($ownerRef)
->where('organization_id', $organization->id)
->whereIn('department_id', $departmentIds)
->whereIn('status', [Appointment::STATUS_WAITING, Appointment::STATUS_CHECKED_IN])
->whereNotNull('visit_id')
->with('visit')
->orderBy('branch_id')
->orderBy('id')
->get();
if ($appointments->isEmpty()) {
return;
}
$clinical = app(SpecialtyClinicalRecordService::class);
$index = 0;
foreach ($appointments as $appointment) {
$visit = $appointment->visit;
if (! $visit) {
continue;
}
$highRisk = $index === 0;
$clinical->upsert(
$organization,
$visit,
'cardiology',
'cardio_history',
[
'history' => $highRisk
? 'Progressive dyspnoea and orthopnoea for 2 weeks'
: 'Palpitations intermittent for 1 month',
'past_cardiac' => $highRisk ? 'Prior MI 2019' : 'None',
'medications' => $highRisk ? 'Aspirin, atorvastatin, bisoprolol' : 'None',
'allergies' => 'NKDA',
'risk_factors' => $highRisk ? 'Hypertension, diabetes, smoking history' : 'Family history of AF',
'family_history' => $highRisk ? 'Father CAD' : 'Mother AF',
],
$ownerRef,
$ownerRef,
'history',
);
$clinical->upsert(
$organization,
$visit,
'cardiology',
'cardiac_exam',
[
'chief_complaint' => $highRisk ? 'Dyspnoea / heart failure symptoms' : 'Palpitations',
'nyha_class' => $highRisk ? 'III' : 'I',
'bp' => $highRisk ? '168/98' : '124/78',
'hr' => $highRisk ? 104 : 72,
'heart_sounds' => $highRisk ? 'S3; soft pansystolic murmur' : 'Normal S1 S2; no murmur',
'ecg_findings' => $highRisk
? 'Sinus tach; Q waves inferiorly; no acute STEMI'
: 'Sinus rhythm; occasional PACs',
'exam_findings' => $highRisk ? 'Bilateral basal crackles; mild ankle oedema' : 'CVD exam normal',
],
$ownerRef,
$ownerRef,
'exam',
);
if ($highRisk) {
$clinical->upsert(
$organization,
$visit,
'cardiology',
'cardio_plan',
[
'diagnosis' => 'Decompensated heart failure (NYHA III)',
'plan' => 'Diuresis; echo; review meds; admit if not improving',
'medications' => 'Increase loop diuretic; continue GDMT',
'procedure_planned' => false,
'follow_up' => '48-hour review or sooner if worse',
'advice' => 'Daily weights; fluid restriction counselling',
],
$ownerRef,
$ownerRef,
'plan',
);
}
if (! $visit->specialty_stage) {
$visit->update(['specialty_stage' => $highRisk ? 'plan' : 'exam']);
}
$index++;
}
}
private function seedPsychiatryClinicalDemo(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', 'psychiatry')
->where('is_active', true)
->pluck('id');
if ($departmentIds->isEmpty()) {
return;
}
$appointments = Appointment::owned($ownerRef)
->where('organization_id', $organization->id)
->whereIn('department_id', $departmentIds)
->whereIn('status', [Appointment::STATUS_WAITING, Appointment::STATUS_CHECKED_IN])
->whereNotNull('visit_id')
->with('visit')
->orderBy('branch_id')
->orderBy('id')
->get();
if ($appointments->isEmpty()) {
return;
}
$clinical = app(SpecialtyClinicalRecordService::class);
$index = 0;
foreach ($appointments as $appointment) {
$visit = $appointment->visit;
if (! $visit) {
continue;
}
$highRisk = $index === 0;
$clinical->upsert(
$organization,
$visit,
'psychiatry',
'mental_status',
[
'chief_complaint' => $highRisk ? 'Low mood with suicidal ideation' : 'Anxiety and poor sleep',
'history' => $highRisk
? '2-week worsening depression; sleep and appetite reduced'
: 'Generalised worry for 3 months; work stress',
'appearance' => $highRisk ? 'Dishevelled; limited eye contact' : 'Well kempt; cooperative',
'mood_affect' => $highRisk ? 'Depressed / flat' : 'Anxious / congruent',
'thought' => $highRisk ? 'Hopeless themes; no psychosis' : 'Worried ruminations; no delusions',
'perception' => 'No hallucinations',
'cognition' => 'Oriented ×3',
'insight' => $highRisk ? 'Partial' : 'Good',
'mse_summary' => $highRisk
? 'Depressed MSE with active suicidal ideation — high vigilance'
: 'Anxious MSE without psychosis or self-harm intent',
],
$ownerRef,
$ownerRef,
'history',
);
$clinical->upsert(
$organization,
$visit,
'psychiatry',
'risk_assessment',
[
'overall_risk' => $highRisk ? 'High' : 'Low',
'self_harm' => $highRisk ? 'Ideation' : 'None identified',
'harm_others' => 'None identified',
'safeguarding' => $highRisk ? 'Lives alone; limited support tonight' : 'Supportive partner',
'protective_factors' => $highRisk ? 'Engaged with clinic; no prior attempts' : 'Good insight; coping strategies',
'risk_summary' => $highRisk
? 'High risk of self-harm — safety planning and close follow-up required'
: 'Low risk; outpatient management appropriate',
'immediate_actions' => $highRisk
? 'Safety plan; remove means; same-day senior review'
: 'Psychoeducation; follow-up in clinic',
],
$ownerRef,
$ownerRef,
'risk',
);
if ($highRisk) {
$clinical->upsert(
$organization,
$visit,
'psychiatry',
'psych_plan',
[
'formulation' => 'Major depressive episode with high self-harm risk in context of isolation',
'diagnosis' => 'Major depressive disorder — severe',
'plan' => 'Crisis safety plan; consider short admission vs intensive outpatient; start/adjust antidepressant',
'medications' => 'Review current AD; discuss options',
'therapy' => 'CBT referral when risk settles',
'follow_up' => '2448 hours or sooner if crisis',
'crisis_plan' => 'Emergency contacts; crisis line; return to ED if ideation intensifies',
],
$ownerRef,
$ownerRef,
'formulation',
);
}
if (! $visit->specialty_stage) {
$visit->update(['specialty_stage' => $highRisk ? 'formulation' : 'risk']);
}
$index++;
}
}
private function seedDentistryClinicalDemo(Organization $organization, string $ownerRef): void
{
// Specialty departments are provisioned without organization_id; scope via branches.
@@ -0,0 +1,168 @@
<?php
namespace App\Services\Care\Psychiatry;
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 PsychiatryAnalyticsService
{
public function __construct(
protected SpecialtyShellService $shell,
) {}
/**
* @return array{
* arrivals_today: int,
* completed_today: int,
* high_risk_open: int,
* risk_breakdown: Collection,
* review_outcomes: 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, 'psychiatry', $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');
$highRiskOpen = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'psychiatry')
->where('record_type', 'risk_assessment')
->whereIn('visit_id', $openVisitIds->isEmpty() ? [0] : $openVisitIds)
->get()
->filter(function (SpecialtyClinicalRecord $r) {
$level = strtolower((string) ($r->payload['overall_risk'] ?? ''));
return str_contains($level, 'high') || str_contains($level, 'imminent');
})
->count();
$riskRecords = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'psychiatry')
->where('record_type', 'risk_assessment')
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
->get();
$riskBreakdown = $riskRecords
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['overall_risk'] ?? 'Unknown'))
->map(fn (Collection $rows, string $risk) => [
'risk' => $risk,
'total' => $rows->count(),
])
->values()
->sortByDesc('total')
->values();
$reviewRecords = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'psychiatry')
->where('record_type', 'psych_followup')
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
->get();
$reviewOutcomes = $reviewRecords
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['outcome'] ?? 'Unknown'))
->map(fn (Collection $rows, string $outcome) => [
'outcome' => $outcome,
'total' => $rows->count(),
])
->values()
->sortByDesc('total')
->values();
$completedVisits = Visit::owned($ownerRef)
->where('organization_id', $organization->id)
->whereIn('id', $visitIds->isEmpty() ? [0] : $visitIds)
->where('status', Visit::STATUS_COMPLETED)
->whereBetween('completed_at', [$rangeFrom, $rangeTo])
->whereNotNull('checked_in_at')
->whereNotNull('completed_at')
->get();
$avgLos = null;
if ($completedVisits->isNotEmpty()) {
$avgLos = round($completedVisits->avg(function (Visit $visit) {
return $visit->checked_in_at->diffInMinutes($visit->completed_at);
}), 1);
}
$serviceLabels = collect($this->shell->provisionedServices($organization, 'psychiatry'))
->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,
'high_risk_open' => $highRiskOpen,
'risk_breakdown' => $riskBreakdown,
'review_outcomes' => $reviewOutcomes,
'avg_los_minutes' => $avgLos,
'revenue_by_service' => $revenueByService,
'from' => $rangeFrom->toDateString(),
'to' => $rangeTo->toDateString(),
];
}
}
@@ -0,0 +1,86 @@
<?php
namespace App\Services\Care\Psychiatry;
/**
* Map psychiatry / mental health clinical progress onto visit stages.
*/
class PsychiatryWorkflowService
{
public const STAGE_CHECK_IN = 'check_in';
public const STAGE_HISTORY = 'history';
public const STAGE_RISK = 'risk';
public const STAGE_FORMULATION = 'formulation';
public const STAGE_REVIEW = 'review';
public const STAGE_COMPLETED = 'completed';
/**
* @param array<string, mixed> $payload
*/
public function stageFromHistory(array $payload): string
{
if (! empty($payload['chief_complaint']) || ! empty($payload['mse_summary'])) {
return self::STAGE_HISTORY;
}
return self::STAGE_CHECK_IN;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromRisk(array $payload): string
{
$risk = trim((string) ($payload['risk_summary'] ?? $payload['risk'] ?? ''));
if ($risk !== '') {
return self::STAGE_RISK;
}
return self::STAGE_HISTORY;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromFormulation(array $payload): string
{
$plan = trim((string) ($payload['plan'] ?? ''));
if ($plan !== '') {
return self::STAGE_FORMULATION;
}
return self::STAGE_RISK;
}
/**
* @param array<string, mixed> $payload
*/
public function shouldCompleteVisit(array $payload): bool
{
$outcome = strtolower((string) ($payload['outcome'] ?? ''));
return str_contains($outcome, 'discharged')
|| str_contains($outcome, 'follow-up arranged')
|| str_contains($outcome, 'completed');
}
/**
* @return array<string, array{next: string, label: string}>
*/
public function stageFlow(): array
{
return [
self::STAGE_CHECK_IN => ['next' => self::STAGE_HISTORY, 'label' => 'Start history / MSE'],
self::STAGE_HISTORY => ['next' => self::STAGE_RISK, 'label' => 'Move to risk assessment'],
self::STAGE_RISK => ['next' => self::STAGE_FORMULATION, 'label' => 'Move to formulation / plan'],
self::STAGE_FORMULATION => ['next' => self::STAGE_REVIEW, 'label' => 'Move to follow-up review'],
self::STAGE_REVIEW => ['next' => self::STAGE_COMPLETED, 'label' => 'Complete visit'],
self::STAGE_COMPLETED => ['next' => self::STAGE_COMPLETED, 'label' => 'Completed'],
];
}
}
@@ -0,0 +1,168 @@
<?php
namespace App\Services\Care\Radiology;
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 RadiologyAnalyticsService
{
public function __construct(
protected SpecialtyShellService $shell,
) {}
/**
* @return array{
* arrivals_today: int,
* completed_today: int,
* urgent_open: int,
* modality_breakdown: Collection,
* verification_outcomes: 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, 'radiology', $ownerRef, $branchId);
$appointmentBase = Appointment::owned($ownerRef)
->where('organization_id', $organization->id)
->when($departmentIds !== [], fn ($q) => $q->whereIn('department_id', $departmentIds))
->when($departmentIds === [], fn ($q) => $q->whereRaw('1 = 0'))
->when($branchId, fn ($q) => $q->where('branch_id', $branchId));
$arrivalsToday = (clone $appointmentBase)
->where('checked_in_at', '>=', $todayStart)
->count();
$completedToday = (clone $appointmentBase)
->where('status', Appointment::STATUS_COMPLETED)
->where('completed_at', '>=', $todayStart)
->count();
$visitIds = (clone $appointmentBase)->whereNotNull('visit_id')->pluck('visit_id');
$openVisitIds = Visit::owned($ownerRef)
->where('organization_id', $organization->id)
->whereIn('id', $visitIds->isEmpty() ? [0] : $visitIds)
->whereIn('status', [Visit::STATUS_OPEN, Visit::STATUS_IN_PROGRESS])
->pluck('id');
$urgentOpen = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'radiology')
->where('record_type', 'imaging_request')
->whereIn('visit_id', $openVisitIds->isEmpty() ? [0] : $openVisitIds)
->get()
->filter(function (SpecialtyClinicalRecord $r) {
$urgency = strtolower((string) ($r->payload['urgency'] ?? ''));
return str_contains($urgency, 'urgent') || str_contains($urgency, 'stat');
})
->count();
$requestRecords = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'radiology')
->where('record_type', 'imaging_request')
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
->get();
$modalityBreakdown = $requestRecords
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['modality'] ?? 'Unknown'))
->map(fn (Collection $rows, string $modality) => [
'modality' => $modality,
'total' => $rows->count(),
])
->values()
->sortByDesc('total')
->values();
$verificationRecords = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'radiology')
->where('record_type', 'imaging_verification')
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
->get();
$verificationOutcomes = $verificationRecords
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['verification_status'] ?? 'Unknown'))
->map(fn (Collection $rows, string $status) => [
'status' => $status,
'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, 'radiology'))
->pluck('label')
->filter()
->values()
->all();
$revenueByService = BillLineItem::query()
->where('owner_ref', $ownerRef)
->where('source_type', 'specialty_service')
->whereIn('description', $serviceLabels ?: ['__none__'])
->whereBetween('created_at', [$rangeFrom, $rangeTo])
->whereHas('bill', function ($q) use ($organization, $visitIds) {
$q->where('organization_id', $organization->id)
->whereIn('visit_id', $visitIds->isEmpty() ? [0] : $visitIds)
->whereNotIn('status', [Bill::STATUS_VOID]);
})
->selectRaw('description, count(*) as total, sum(total_minor) as amount_minor')
->groupBy('description')
->orderByDesc('amount_minor')
->get();
return [
'arrivals_today' => $arrivalsToday,
'completed_today' => $completedToday,
'urgent_open' => $urgentOpen,
'modality_breakdown' => $modalityBreakdown,
'verification_outcomes' => $verificationOutcomes,
'avg_los_minutes' => $avgLos,
'revenue_by_service' => $revenueByService,
'from' => $rangeFrom->toDateString(),
'to' => $rangeTo->toDateString(),
];
}
}
@@ -0,0 +1,85 @@
<?php
namespace App\Services\Care\Radiology;
/**
* Map imaging clinical progress onto radiology visit stages.
*/
class RadiologyWorkflowService
{
public const STAGE_CHECK_IN = 'check_in';
public const STAGE_PROTOCOL = 'protocol';
public const STAGE_ACQUISITION = 'acquisition';
public const STAGE_REPORTING = 'reporting';
public const STAGE_VERIFIED = 'verified';
public const STAGE_COMPLETED = 'completed';
/**
* @param array<string, mixed> $payload
*/
public function stageFromRequest(array $payload): string
{
if (! empty($payload['modality']) || ! empty($payload['body_part'])) {
return self::STAGE_PROTOCOL;
}
return self::STAGE_CHECK_IN;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromAcquisition(array $payload): string
{
$status = strtolower((string) ($payload['acquisition_status'] ?? ''));
if (str_contains($status, 'complete') || str_contains($status, 'acquired')) {
return self::STAGE_ACQUISITION;
}
return self::STAGE_PROTOCOL;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromReport(array $payload): string
{
$findings = trim((string) ($payload['findings'] ?? ''));
$impression = trim((string) ($payload['impression'] ?? ''));
if ($findings !== '' || $impression !== '') {
return self::STAGE_REPORTING;
}
return self::STAGE_ACQUISITION;
}
/**
* @param array<string, mixed> $payload
*/
public function shouldCompleteVisit(array $payload): bool
{
$status = strtolower((string) ($payload['verification_status'] ?? ''));
return str_contains($status, 'verified') || str_contains($status, 'final');
}
/**
* @return array<string, array{next: string, label: string}>
*/
public function stageFlow(): array
{
return [
self::STAGE_CHECK_IN => ['next' => self::STAGE_PROTOCOL, 'label' => 'Start request / protocol'],
self::STAGE_PROTOCOL => ['next' => self::STAGE_ACQUISITION, 'label' => 'Move to acquisition'],
self::STAGE_ACQUISITION => ['next' => self::STAGE_REPORTING, 'label' => 'Move to reporting'],
self::STAGE_REPORTING => ['next' => self::STAGE_VERIFIED, 'label' => 'Move to verification'],
self::STAGE_VERIFIED => ['next' => self::STAGE_COMPLETED, 'label' => 'Complete study'],
self::STAGE_COMPLETED => ['next' => self::STAGE_COMPLETED, 'label' => 'Completed'],
];
}
}
@@ -373,6 +373,77 @@ class SpecialtyClinicalRecordService
}
}
if ($moduleKey === 'radiology' && $recordType === 'imaging_request') {
$urgency = strtolower((string) ($payload['urgency'] ?? ''));
if (str_contains($urgency, 'stat')) {
$alerts[] = [
'code' => 'rad.stat',
'severity' => 'critical',
'message' => 'STAT imaging request.',
];
} elseif (str_contains($urgency, 'urgent')) {
$alerts[] = [
'code' => 'rad.urgent',
'severity' => 'warning',
'message' => 'Urgent imaging request.',
];
}
}
if ($moduleKey === 'radiology' && $recordType === 'imaging_report') {
if (! empty($payload['critical_result'])) {
$alerts[] = [
'code' => 'rad.critical_result',
'severity' => 'critical',
'message' => 'Critical / unexpected imaging finding recorded.',
];
}
}
if ($moduleKey === 'cardiology' && $recordType === 'cardiac_exam') {
$nyha = (string) ($payload['nyha_class'] ?? '');
if (in_array($nyha, ['III', 'IV'], true)) {
$alerts[] = [
'code' => 'car.nyha_high',
'severity' => $nyha === 'IV' ? 'critical' : 'warning',
'message' => 'NYHA class '.$nyha.' on cardiac exam.',
];
}
$ecg = strtolower((string) ($payload['ecg_findings'] ?? ''));
if (str_contains($ecg, 'stemi') || str_contains($ecg, 'st elevation') || str_contains($ecg, 'vt') || str_contains($ecg, 'vf')) {
$alerts[] = [
'code' => 'car.ecg_critical',
'severity' => 'critical',
'message' => 'Critical ECG findings recorded.',
];
}
}
if ($moduleKey === 'psychiatry' && $recordType === 'risk_assessment') {
$level = strtolower((string) ($payload['overall_risk'] ?? ''));
if (str_contains($level, 'imminent')) {
$alerts[] = [
'code' => 'psy.risk_imminent',
'severity' => 'critical',
'message' => 'Imminent risk — escalate immediately.',
];
} elseif (str_contains($level, 'high')) {
$alerts[] = [
'code' => 'psy.risk_high',
'severity' => 'critical',
'message' => 'High psychiatric risk recorded.',
];
}
$selfHarm = strtolower((string) ($payload['self_harm'] ?? ''));
if (str_contains($selfHarm, 'intent') || str_contains($selfHarm, 'attempt')) {
$alerts[] = [
'code' => 'psy.self_harm',
'severity' => 'critical',
'message' => 'Self-harm intent or recent attempt recorded.',
];
}
}
return $alerts;
}
+13 -1
View File
@@ -14,6 +14,9 @@ use App\Services\Care\Emergency\EmergencyWorkflowService;
use App\Services\Care\Ophthalmology\OphthalmologyWorkflowService;
use App\Services\Care\Physiotherapy\PhysiotherapyWorkflowService;
use App\Services\Care\Maternity\MaternityWorkflowService;
use App\Services\Care\Radiology\RadiologyWorkflowService;
use App\Services\Care\Cardiology\CardiologyWorkflowService;
use App\Services\Care\Psychiatry\PsychiatryWorkflowService;
use Illuminate\Support\Collection;
/**
@@ -60,6 +63,9 @@ class SpecialtyShellService
'ophthalmology' => 'care.specialty.ophthalmology.stage',
'physiotherapy' => 'care.specialty.physiotherapy.stage',
'maternity' => 'care.specialty.maternity.stage',
'radiology' => 'care.specialty.radiology.stage',
'cardiology' => 'care.specialty.cardiology.stage',
'psychiatry' => 'care.specialty.psychiatry.stage',
default => null,
};
}
@@ -77,6 +83,9 @@ class SpecialtyShellService
'ophthalmology' => app(OphthalmologyWorkflowService::class)->stageFlow(),
'physiotherapy' => app(PhysiotherapyWorkflowService::class)->stageFlow(),
'maternity' => app(MaternityWorkflowService::class)->stageFlow(),
'radiology' => app(RadiologyWorkflowService::class)->stageFlow(),
'cardiology' => app(CardiologyWorkflowService::class)->stageFlow(),
'psychiatry' => app(PsychiatryWorkflowService::class)->stageFlow(),
'dentistry' => [
'waiting' => ['next' => 'chair', 'label' => 'Seat at chair'],
'chair' => ['next' => 'procedure', 'label' => 'Start procedure'],
@@ -376,7 +385,7 @@ class SpecialtyShellService
) {
$code = (string) ($stage['code'] ?? '');
if (in_array($moduleKey, ['dentistry', 'emergency', 'blood_bank', 'ophthalmology', 'physiotherapy', 'maternity'], true) && $visitIds->isNotEmpty()) {
if (in_array($moduleKey, ['dentistry', 'emergency', 'blood_bank', 'ophthalmology', 'physiotherapy', 'maternity', 'radiology', 'cardiology', 'psychiatry'], true) && $visitIds->isNotEmpty()) {
$count = Visit::owned($ownerRef)
->where('organization_id', $organization->id)
->whereIn('id', $visitIds)
@@ -409,6 +418,9 @@ class SpecialtyShellService
'ophthalmology' => $clinical->countOpenByType($organization, 'ophthalmology', 'eye_exam', $branchScope),
'physiotherapy' => $clinical->countOpenByType($organization, 'physiotherapy', 'pt_assessment', $branchScope),
'maternity' => $clinical->countOpenByType($organization, 'maternity', 'anc_history', $branchScope),
'radiology' => $clinical->countOpenByType($organization, 'radiology', 'imaging_request', $branchScope),
'cardiology' => $clinical->countOpenByType($organization, 'cardiology', 'cardiac_exam', $branchScope),
'psychiatry' => $clinical->countOpenByType($organization, 'psychiatry', 'mental_status', $branchScope),
'dentistry' => \App\Models\DentalPlanItem::query()
->whereHas('plan', function ($q) use ($organization, $ownerRef) {
$q->owned($ownerRef)
@@ -120,6 +120,30 @@ class SpecialtyVisitStageService
: ($stages[1] ?? ($stages[0] ?? null));
}
if ($moduleKey === 'radiology') {
$stages = $this->allowedStages($moduleKey);
return in_array(\App\Services\Care\Radiology\RadiologyWorkflowService::STAGE_PROTOCOL, $stages, true)
? \App\Services\Care\Radiology\RadiologyWorkflowService::STAGE_PROTOCOL
: ($stages[1] ?? ($stages[0] ?? null));
}
if ($moduleKey === 'cardiology') {
$stages = $this->allowedStages($moduleKey);
return in_array(\App\Services\Care\Cardiology\CardiologyWorkflowService::STAGE_HISTORY, $stages, true)
? \App\Services\Care\Cardiology\CardiologyWorkflowService::STAGE_HISTORY
: ($stages[1] ?? ($stages[0] ?? null));
}
if ($moduleKey === 'psychiatry') {
$stages = $this->allowedStages($moduleKey);
return in_array(\App\Services\Care\Psychiatry\PsychiatryWorkflowService::STAGE_HISTORY, $stages, true)
? \App\Services\Care\Psychiatry\PsychiatryWorkflowService::STAGE_HISTORY
: ($stages[1] ?? ($stages[0] ?? null));
}
$stages = $this->allowedStages($moduleKey);
foreach (['chair', 'in_care', 'exam', 'assessment', 'treatment'] as $preferred) {
if (in_array($preferred, $stages, true)) {