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)) {
+91 -19
View File
@@ -47,16 +47,23 @@ return [
'postnatal' => 'postnatal_note',
],
'radiology' => [
'request' => 'imaging_request',
'report' => 'imaging_report',
'protocol' => 'imaging_request',
'acquisition' => 'imaging_acquisition',
'findings' => 'imaging_report',
'verification' => 'imaging_verification',
],
'cardiology' => [
'history' => 'cardio_history',
'exam' => 'cardiac_exam',
'clinical_notes' => 'clinical_note',
'investigations' => 'cardio_investigation',
'plan' => 'cardio_plan',
'procedures' => 'cardio_procedure',
],
'psychiatry' => [
'assessment' => 'mental_status',
'clinical_notes' => 'clinical_note',
'history' => 'mental_status',
'risk' => 'risk_assessment',
'plan' => 'psych_plan',
'followup' => 'psych_followup',
],
'pediatrics' => [
'exam' => 'pediatric_exam',
@@ -363,48 +370,113 @@ return [
['name' => 'clinical_info', 'label' => 'Clinical information', 'type' => 'textarea', 'required' => true, 'rows' => 3],
['name' => 'urgency', 'label' => 'Urgency', 'type' => 'select', 'options' => ['Routine', 'Urgent', 'STAT']],
['name' => 'contrast', 'label' => 'Contrast', 'type' => 'select', 'options' => ['None', 'IV', 'Oral', 'Both']],
['name' => 'protocol', 'label' => 'Protocol / sequences', 'type' => 'textarea', 'rows' => 2],
['name' => 'referrer', 'label' => 'Referring clinician', 'type' => 'text'],
],
'imaging_acquisition' => [
['name' => 'technologist', 'label' => 'Technologist', 'type' => 'text'],
['name' => 'equipment', 'label' => 'Equipment / room', 'type' => 'text'],
['name' => 'acquisition_status', 'label' => 'Acquisition status', 'type' => 'select', 'required' => true, 'options' => ['Scheduled', 'In progress', 'Acquired', 'Incomplete', 'Cancelled']],
['name' => 'contrast_given', 'label' => 'Contrast administered', 'type' => 'boolean'],
['name' => 'dose_notes', 'label' => 'Dose / exposure notes', 'type' => 'textarea', 'rows' => 2],
['name' => 'quality', 'label' => 'Image quality', 'type' => 'select', 'options' => ['Diagnostic', 'Limited', 'Non-diagnostic', 'Repeat needed']],
['name' => 'notes', 'label' => 'Acquisition notes', 'type' => 'textarea', 'rows' => 2],
],
'imaging_report' => [
['name' => 'technique', 'label' => 'Technique', 'type' => 'textarea', 'rows' => 2],
['name' => 'comparison', 'label' => 'Comparison', 'type' => 'text'],
['name' => 'findings', 'label' => 'Findings', 'type' => 'textarea', 'required' => true, 'rows' => 4],
['name' => 'impression', 'label' => 'Impression', 'type' => 'textarea', 'required' => true, 'rows' => 3],
['name' => 'recommendations', 'label' => 'Recommendations', 'type' => 'textarea', 'rows' => 2],
['name' => 'critical_result', 'label' => 'Critical / unexpected finding', 'type' => 'boolean'],
],
'imaging_verification' => [
['name' => 'verification_status', 'label' => 'Verification status', 'type' => 'select', 'required' => true, 'options' => ['Draft', 'Preliminary', 'Verified / final', 'Amended']],
['name' => 'verified_by', 'label' => 'Verified by', 'type' => 'text', 'required' => true],
['name' => 'critical_communicated', 'label' => 'Critical result communicated', 'type' => 'boolean'],
['name' => 'communication_notes', 'label' => 'Communication notes', 'type' => 'textarea', 'rows' => 2],
['name' => 'notes', 'label' => 'Verification notes', 'type' => 'textarea', 'rows' => 2],
],
],
'cardiology' => [
'cardio_history' => [
['name' => 'history', 'label' => 'History of present illness', 'type' => 'textarea', 'required' => true, 'rows' => 4],
['name' => 'past_cardiac', 'label' => 'Past cardiac history', 'type' => 'textarea', 'rows' => 2],
['name' => 'medications', 'label' => 'Medications', 'type' => 'textarea', 'rows' => 2],
['name' => 'allergies', 'label' => 'Allergies', 'type' => 'text'],
['name' => 'risk_factors', 'label' => 'Cardiac risk factors', 'type' => 'textarea', 'rows' => 2],
['name' => 'family_history', 'label' => 'Family history', 'type' => 'textarea', 'rows' => 2],
],
'cardiac_exam' => [
['name' => 'chief_complaint', 'label' => 'Chief complaint', 'type' => 'text', 'required' => true],
['name' => 'nyha_class', 'label' => 'NYHA class', 'type' => 'select', 'options' => ['I', 'II', 'III', 'IV', 'N/A']],
['name' => 'bp', 'label' => 'Blood pressure', 'type' => 'text'],
['name' => 'hr', 'label' => 'Heart rate', 'type' => 'number'],
['name' => 'heart_sounds', 'label' => 'Heart sounds / murmurs', 'type' => 'textarea', 'rows' => 2],
['name' => 'ecg_findings', 'label' => 'ECG findings', 'type' => 'textarea', 'rows' => 2],
['name' => 'echo_summary', 'label' => 'Echo summary', 'type' => 'textarea', 'rows' => 2],
['name' => 'risk_factors', 'label' => 'Cardiac risk factors', 'type' => 'textarea', 'rows' => 2],
['name' => 'ecg_findings', 'label' => 'ECG findings', 'type' => 'textarea', 'required' => true, 'rows' => 2],
['name' => 'exam_findings', 'label' => 'Exam findings', 'type' => 'textarea', 'rows' => 2],
],
'clinical_note' => [
['name' => 'history', 'label' => 'History of present illness', 'type' => 'textarea', 'required' => true, 'rows' => 4],
['name' => 'examination', 'label' => 'Examination', 'type' => 'textarea', 'rows' => 3],
['name' => 'working_diagnosis', 'label' => 'Working diagnosis', 'type' => 'text'],
['name' => 'plan', 'label' => 'Plan', 'type' => 'textarea', 'rows' => 3],
'cardio_investigation' => [
['name' => 'modality', 'label' => 'Investigation', 'type' => 'select', 'required' => true, 'options' => ['Echo', 'Stress test', 'Holter', 'Troponin / labs', 'CT angio', 'Other']],
['name' => 'indication', 'label' => 'Indication', 'type' => 'textarea', 'rows' => 2],
['name' => 'findings', 'label' => 'Findings', 'type' => 'textarea', 'required' => true, 'rows' => 3],
['name' => 'impression', 'label' => 'Impression', 'type' => 'textarea', 'rows' => 2],
['name' => 'recommendations', 'label' => 'Recommendations', 'type' => 'textarea', 'rows' => 2],
],
'cardio_plan' => [
['name' => 'diagnosis', 'label' => 'Diagnosis', 'type' => 'text', 'required' => true],
['name' => 'plan', 'label' => 'Plan', 'type' => 'textarea', 'required' => true, 'rows' => 3],
['name' => 'medications', 'label' => 'Medications', 'type' => 'textarea', 'rows' => 2],
['name' => 'procedure_planned', 'label' => 'Procedure / intervention planned', 'type' => 'boolean'],
['name' => 'follow_up', 'label' => 'Follow-up', 'type' => 'text'],
['name' => 'advice', 'label' => 'Patient advice', 'type' => 'textarea', 'rows' => 2],
],
'cardio_procedure' => [
['name' => 'procedure', 'label' => 'Procedure / intervention', 'type' => 'text', 'required' => true],
['name' => 'indication', 'label' => 'Indication', 'type' => 'textarea', 'rows' => 2],
['name' => 'outcome', 'label' => 'Outcome', 'type' => 'select', 'required' => true, 'options' => ['Completed uneventfully', 'Completed with complications', 'Deferred', 'Aborted']],
['name' => 'complications', 'label' => 'Complications', 'type' => 'textarea', 'rows' => 2],
['name' => 'post_procedure_plan', 'label' => 'Post-procedure plan', 'type' => 'textarea', 'rows' => 2],
['name' => 'notes', 'label' => 'Notes', 'type' => 'textarea', 'rows' => 2],
],
],
'psychiatry' => [
'mental_status' => [
['name' => 'chief_complaint', 'label' => 'Presenting complaint', 'type' => 'text', 'required' => true],
['name' => 'history', 'label' => 'History of present illness', 'type' => 'textarea', 'rows' => 3],
['name' => 'appearance', 'label' => 'Appearance / behaviour', 'type' => 'textarea', 'rows' => 2],
['name' => 'mood_affect', 'label' => 'Mood / affect', 'type' => 'text'],
['name' => 'thought', 'label' => 'Thought content / process', 'type' => 'textarea', 'rows' => 2],
['name' => 'perception', 'label' => 'Perception', 'type' => 'text'],
['name' => 'cognition', 'label' => 'Cognition / orientation', 'type' => 'text'],
['name' => 'insight', 'label' => 'Insight / judgment', 'type' => 'text'],
['name' => 'risk', 'label' => 'Risk assessment', 'type' => 'textarea', 'required' => true, 'rows' => 2],
['name' => 'mse_summary', 'label' => 'MSE summary', 'type' => 'textarea', 'required' => true, 'rows' => 3],
],
'clinical_note' => [
['name' => 'history', 'label' => 'History of present illness', 'type' => 'textarea', 'required' => true, 'rows' => 4],
['name' => 'examination', 'label' => 'Examination', 'type' => 'textarea', 'rows' => 3],
['name' => 'working_diagnosis', 'label' => 'Working diagnosis', 'type' => 'text'],
['name' => 'plan', 'label' => 'Plan', 'type' => 'textarea', 'rows' => 3],
'risk_assessment' => [
['name' => 'overall_risk', 'label' => 'Overall risk level', 'type' => 'select', 'required' => true, 'options' => ['Low', 'Moderate', 'High', 'Imminent']],
['name' => 'self_harm', 'label' => 'Self-harm / suicide risk', 'type' => 'select', 'options' => ['None identified', 'Ideation', 'Plan', 'Intent / recent attempt']],
['name' => 'harm_others', 'label' => 'Risk to others', 'type' => 'select', 'options' => ['None identified', 'Ideation', 'Plan', 'Intent']],
['name' => 'safeguarding', 'label' => 'Safeguarding concerns', 'type' => 'textarea', 'rows' => 2],
['name' => 'protective_factors', 'label' => 'Protective factors', 'type' => 'textarea', 'rows' => 2],
['name' => 'risk_summary', 'label' => 'Risk summary', 'type' => 'textarea', 'required' => true, 'rows' => 3],
['name' => 'immediate_actions', 'label' => 'Immediate actions', 'type' => 'textarea', 'rows' => 2],
],
'psych_plan' => [
['name' => 'formulation', 'label' => 'Formulation', 'type' => 'textarea', 'required' => true, 'rows' => 3],
['name' => 'diagnosis', 'label' => 'Working diagnosis', 'type' => 'text'],
['name' => 'plan', 'label' => 'Management plan', 'type' => 'textarea', 'required' => true, 'rows' => 3],
['name' => 'medications', 'label' => 'Medications', 'type' => 'textarea', 'rows' => 2],
['name' => 'therapy', 'label' => 'Therapy / psychosocial', 'type' => 'textarea', 'rows' => 2],
['name' => 'follow_up', 'label' => 'Follow-up', 'type' => 'text'],
['name' => 'crisis_plan', 'label' => 'Crisis / safety plan', 'type' => 'textarea', 'rows' => 2],
],
'psych_followup' => [
['name' => 'review_type', 'label' => 'Review type', 'type' => 'select', 'required' => true, 'options' => ['Clinic follow-up', 'Medication review', 'Crisis review', 'Discharge review']],
['name' => 'progress', 'label' => 'Progress since last contact', 'type' => 'textarea', 'required' => true, 'rows' => 3],
['name' => 'current_risk', 'label' => 'Current risk', 'type' => 'select', 'options' => ['Low', 'Moderate', 'High', 'Imminent']],
['name' => 'outcome', 'label' => 'Outcome', 'type' => 'select', 'required' => true, 'options' => ['In progress', 'Follow-up arranged', 'Discharged', 'Referred', 'Admitted']],
['name' => 'next_steps', 'label' => 'Next steps', 'type' => 'textarea', 'rows' => 2],
['name' => 'notes', 'label' => 'Notes', 'type' => 'textarea', 'rows' => 2],
],
],
'pediatrics' => [
+3 -2
View File
@@ -118,6 +118,7 @@ return [
'queue_keywords' => ['radio', 'imaging', 'x-ray', 'xray', 'ultrasound', 'ct', 'mri'],
'access' => 'general',
'roles' => ['doctor', 'nurse', 'lab_technician', 'receptionist'],
'specialist_keywords' => ['radio', 'radiolog', 'imaging'],
],
'cardiology' => [
'label' => 'Cardiology',
@@ -134,7 +135,7 @@ return [
'support_roles' => ['nurse'],
'view_roles' => ['doctor', 'nurse', 'lab_technician'],
'refer_roles' => ['doctor', 'nurse'],
'specialist_keywords' => ['cardio', 'cardiology', 'heart'],
'specialist_keywords' => ['cardio', 'cardiology', 'heart', 'ecg'],
],
'psychiatry' => [
'label' => 'Psychiatry',
@@ -151,7 +152,7 @@ return [
'support_roles' => ['nurse'],
'view_roles' => ['doctor', 'nurse'],
'refer_roles' => ['doctor', 'nurse'],
'specialist_keywords' => ['psych', 'psychiatry', 'mental'],
'specialist_keywords' => ['psych', 'psychiatry', 'mental', 'behaviour'],
],
'pediatrics' => [
'label' => 'Pediatrics',
+64 -12
View File
@@ -292,61 +292,113 @@ return [
],
'radiology' => [
'stages' => [
['code' => 'request', 'label' => 'Request received', 'queue_point' => 'waiting'],
['code' => 'imaging', 'label' => 'Imaging', 'queue_point' => 'chair'],
['code' => 'check_in', 'label' => 'Check-in', 'queue_point' => 'waiting'],
['code' => 'protocol', 'label' => 'Request / protocol', 'queue_point' => 'waiting'],
['code' => 'acquisition', 'label' => 'Acquisition', 'queue_point' => 'chair'],
['code' => 'reporting', 'label' => 'Reporting', 'queue_point' => 'chair'],
['code' => 'verified', 'label' => 'Verified', 'queue_point' => null],
['code' => 'completed', 'label' => 'Completed', 'queue_point' => null],
],
'services' => [
['code' => 'rad.xray', 'label' => 'X-ray', 'amount_minor' => 8000, 'type' => 'imaging'],
['code' => 'rad.ultrasound', 'label' => 'Ultrasound', 'amount_minor' => 15000, 'type' => 'imaging'],
['code' => 'rad.ct', 'label' => 'CT scan', 'amount_minor' => 45000, 'type' => 'imaging'],
['code' => 'rad.mri', 'label' => 'MRI', 'amount_minor' => 65000, 'type' => 'imaging'],
['code' => 'rad.fluoro', 'label' => 'Fluoroscopy', 'amount_minor' => 20000, 'type' => 'imaging'],
['code' => 'rad.contrast', 'label' => 'Contrast administration', 'amount_minor' => 5000, 'type' => 'procedure'],
['code' => 'rad.report', 'label' => 'Radiology report', 'amount_minor' => 4000, 'type' => 'consultation'],
],
'workspace_tabs' => [
'overview' => 'Overview',
'request' => 'Imaging request',
'report' => 'Report',
'protocol' => 'Request / protocol',
'acquisition' => 'Acquisition',
'findings' => 'Findings / report',
'verification' => 'Verification',
'orders' => 'Orders',
'billing' => 'Billing',
'documents' => 'Documents',
],
'stage_tabs' => [
'check_in' => 'overview',
'protocol' => 'protocol',
'acquisition' => 'acquisition',
'reporting' => 'findings',
'verified' => 'verification',
'completed' => 'overview',
],
],
'cardiology' => [
'stages' => [
['code' => 'waiting', 'label' => 'Waiting', 'queue_point' => 'waiting'],
['code' => 'exam', 'label' => 'Cardiac exam', 'queue_point' => 'chair'],
['code' => 'check_in', 'label' => 'Check-in', 'queue_point' => 'waiting'],
['code' => 'history', 'label' => 'History', 'queue_point' => 'waiting'],
['code' => 'exam', 'label' => 'Exam / ECG', 'queue_point' => 'chair'],
['code' => 'investigation', 'label' => 'Investigations', 'queue_point' => 'chair'],
['code' => 'plan', 'label' => 'Diagnosis & plan', 'queue_point' => 'chair'],
['code' => 'procedure', 'label' => 'Procedure / intervention', 'queue_point' => 'chair'],
['code' => 'completed', 'label' => 'Completed', 'queue_point' => null],
],
'services' => [
['code' => 'car.consult', 'label' => 'Cardiology consultation', 'amount_minor' => 8000, 'type' => 'consultation'],
['code' => 'car.ecg', 'label' => 'ECG', 'amount_minor' => 5000, 'type' => 'procedure'],
['code' => 'car.echo', 'label' => 'Echocardiogram', 'amount_minor' => 25000, 'type' => 'imaging'],
['code' => 'car.stress', 'label' => 'Stress test', 'amount_minor' => 18000, 'type' => 'procedure'],
['code' => 'car.holter', 'label' => 'Holter monitoring', 'amount_minor' => 15000, 'type' => 'procedure'],
['code' => 'car.procedure', 'label' => 'Cardiac procedure', 'amount_minor' => 35000, 'type' => 'procedure'],
],
'workspace_tabs' => [
'overview' => 'Overview',
'exam' => 'Cardiac exam',
'clinical_notes' => 'Clinical notes',
'history' => 'History',
'exam' => 'Exam / ECG',
'investigations' => 'Investigations',
'plan' => 'Diagnosis & plan',
'procedures' => 'Procedures',
'orders' => 'Orders',
'billing' => 'Billing',
'documents' => 'Documents',
],
'stage_tabs' => [
'check_in' => 'overview',
'history' => 'history',
'exam' => 'exam',
'investigation' => 'investigations',
'plan' => 'plan',
'procedure' => 'procedures',
'completed' => 'overview',
],
],
'psychiatry' => [
'stages' => [
['code' => 'waiting', 'label' => 'Waiting', 'queue_point' => 'waiting'],
['code' => 'assessment', 'label' => 'Mental health assessment', 'queue_point' => 'chair'],
['code' => 'check_in', 'label' => 'Check-in', 'queue_point' => 'waiting'],
['code' => 'history', 'label' => 'History / MSE', 'queue_point' => 'waiting'],
['code' => 'risk', 'label' => 'Risk assessment', 'queue_point' => 'chair'],
['code' => 'formulation', 'label' => 'Formulation / plan', 'queue_point' => 'chair'],
['code' => 'review', 'label' => 'Follow-up review', 'queue_point' => 'chair'],
['code' => 'completed', 'label' => 'Completed', 'queue_point' => null],
],
'services' => [
['code' => 'psy.consult', 'label' => 'Psychiatry consultation', 'amount_minor' => 8000, 'type' => 'consultation'],
['code' => 'psy.mse', 'label' => 'Mental state examination', 'amount_minor' => 5000, 'type' => 'consultation'],
['code' => 'psy.risk', 'label' => 'Risk assessment', 'amount_minor' => 4500, 'type' => 'consultation'],
['code' => 'psy.followup', 'label' => 'Follow-up review', 'amount_minor' => 6000, 'type' => 'consultation'],
],
'workspace_tabs' => [
'overview' => 'Overview',
'assessment' => 'Assessment',
'clinical_notes' => 'Clinical notes',
'history' => 'History / MSE',
'risk' => 'Risk',
'plan' => 'Formulation / plan',
'followup' => 'Follow-up',
'orders' => 'Orders',
'billing' => 'Billing',
'documents' => 'Documents',
],
'stage_tabs' => [
'check_in' => 'overview',
'history' => 'history',
'risk' => 'risk',
'formulation' => 'plan',
'review' => 'followup',
'completed' => 'overview',
],
],
'pediatrics' => [
'stages' => [
@@ -0,0 +1,89 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Cardiology summary · {{ $patient->fullName() }}</title>
<style>
body { font-family: system-ui, sans-serif; color: #0f172a; margin: 2rem; }
h1 { font-size: 1.25rem; margin: 0 0 .25rem; }
h2 { font-size: .95rem; margin: 1.25rem 0 .5rem; border-bottom: 1px solid #e2e8f0; padding-bottom: .25rem; }
.meta { color: #64748b; font-size: .875rem; }
dl { display: grid; grid-template-columns: 10rem 1fr; gap: .35rem .75rem; font-size: .875rem; }
dt { color: #64748b; }
dd { margin: 0; font-weight: 500; }
@media print { .no-print { display: none; } }
</style>
</head>
<body>
<p class="no-print"><a href="{{ route('care.specialty.workspace', ['module' => 'cardiology', 'visit' => $visit]) }}">Back</a></p>
<h1>{{ $patient->fullName() }}</h1>
<p class="meta">
{{ $patient->patient_number }}
· Visit #{{ $visit->id }}
· Stage {{ $visit->specialty_stage ?? '—' }}
· {{ $visit->checked_in_at?->format('d M Y H:i') ?? '—' }}
</p>
<h2>History</h2>
@if ($history)
<dl>
<dt>HPI</dt><dd>{{ $history->payload['history'] ?? '—' }}</dd>
<dt>Past cardiac</dt><dd>{{ $history->payload['past_cardiac'] ?? '—' }}</dd>
<dt>Risk factors</dt><dd>{{ $history->payload['risk_factors'] ?? '—' }}</dd>
<dt>Medications</dt><dd>{{ $history->payload['medications'] ?? '—' }}</dd>
</dl>
@else
<p class="meta">No history recorded.</p>
@endif
<h2>Exam / ECG</h2>
@if ($exam)
<dl>
<dt>Complaint</dt><dd>{{ $exam->payload['chief_complaint'] ?? '—' }}</dd>
<dt>NYHA</dt><dd>{{ $exam->payload['nyha_class'] ?? '—' }}</dd>
<dt>BP / HR</dt><dd>{{ $exam->payload['bp'] ?? '—' }} · {{ $exam->payload['hr'] ?? '—' }}</dd>
<dt>ECG</dt><dd>{{ $exam->payload['ecg_findings'] ?? '—' }}</dd>
<dt>Exam</dt><dd>{{ $exam->payload['exam_findings'] ?? '—' }}</dd>
</dl>
@else
<p class="meta">No exam recorded.</p>
@endif
<h2>Investigations</h2>
@if ($investigation)
<dl>
<dt>Investigation</dt><dd>{{ $investigation->payload['modality'] ?? '—' }}</dd>
<dt>Findings</dt><dd>{{ $investigation->payload['findings'] ?? '—' }}</dd>
<dt>Impression</dt><dd>{{ $investigation->payload['impression'] ?? '—' }}</dd>
</dl>
@else
<p class="meta">No investigation recorded.</p>
@endif
<h2>Diagnosis & plan</h2>
@if ($plan)
<dl>
<dt>Diagnosis</dt><dd>{{ $plan->payload['diagnosis'] ?? '—' }}</dd>
<dt>Plan</dt><dd>{{ $plan->payload['plan'] ?? '—' }}</dd>
<dt>Medications</dt><dd>{{ $plan->payload['medications'] ?? '—' }}</dd>
<dt>Follow-up</dt><dd>{{ $plan->payload['follow_up'] ?? '—' }}</dd>
</dl>
@else
<p class="meta">No plan recorded.</p>
@endif
<h2>Procedure</h2>
@if ($procedure)
<dl>
<dt>Procedure</dt><dd>{{ $procedure->payload['procedure'] ?? '—' }}</dd>
<dt>Outcome</dt><dd>{{ $procedure->payload['outcome'] ?? '—' }}</dd>
<dt>Plan</dt><dd>{{ $procedure->payload['post_procedure_plan'] ?? '—' }}</dd>
</dl>
@else
<p class="meta">No procedure recorded.</p>
@endif
<script>window.print();</script>
</body>
</html>
@@ -0,0 +1,88 @@
<x-app-layout title="Cardiology reports">
<div class="space-y-6">
<div class="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 class="text-xl font-semibold text-slate-900">Cardiology reports</h1>
<p class="mt-1 text-sm text-slate-500">Arrivals, NYHA IIIIV open cases, diagnoses, procedures, length of stay, and cardiology revenue.</p>
</div>
<a href="{{ route('care.specialty.show', 'cardiology') }}" class="text-sm font-medium text-indigo-600"> Specialty home</a>
</div>
<form method="GET" class="flex flex-wrap items-end gap-3 rounded-2xl border border-slate-200 bg-white p-4">
<div>
<label class="block text-xs font-medium text-slate-600">From</label>
<input type="date" name="from" value="{{ $report['from'] ?? '' }}" class="mt-1 rounded-xl border border-slate-200 px-3 py-2 text-sm">
</div>
<div>
<label class="block text-xs font-medium text-slate-600">To</label>
<input type="date" name="to" value="{{ $report['to'] ?? '' }}" class="mt-1 rounded-xl border border-slate-200 px-3 py-2 text-sm">
</div>
<button type="submit" class="rounded-xl bg-indigo-600 px-4 py-2 text-sm font-semibold text-white">Apply</button>
</form>
<div class="grid gap-4 sm:grid-cols-4">
<div class="rounded-2xl border border-slate-200 bg-white p-4">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Arrivals today</p>
<p class="mt-2 text-2xl font-semibold tabular-nums text-slate-900">{{ number_format($report['arrivals_today']) }}</p>
</div>
<div class="rounded-2xl border border-slate-200 bg-white p-4">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Completed today</p>
<p class="mt-2 text-2xl font-semibold tabular-nums text-slate-900">{{ number_format($report['completed_today']) }}</p>
</div>
<div class="rounded-2xl border border-slate-200 bg-white p-4">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">NYHA IIIIV open</p>
<p class="mt-2 text-2xl font-semibold tabular-nums text-rose-700">{{ number_format($report['high_risk_open']) }}</p>
</div>
<div class="rounded-2xl border border-slate-200 bg-white p-4">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Avg LOS (range)</p>
<p class="mt-2 text-2xl font-semibold tabular-nums text-slate-900">
{{ $report['avg_los_minutes'] !== null ? $report['avg_los_minutes'].' min' : '—' }}
</p>
</div>
</div>
<div class="grid gap-4 lg:grid-cols-2">
<section class="rounded-2xl border border-slate-200 bg-white p-5">
<h2 class="text-sm font-semibold text-slate-900">Diagnoses</h2>
<ul class="mt-3 space-y-2 text-sm">
@forelse ($report['diagnosis_breakdown'] as $row)
<li class="flex justify-between gap-3">
<span>{{ $row['diagnosis'] }}</span>
<span class="tabular-nums text-slate-600">{{ $row['total'] }}</span>
</li>
@empty
<li class="text-slate-500">No care plans in range.</li>
@endforelse
</ul>
</section>
<section class="rounded-2xl border border-slate-200 bg-white p-5">
<h2 class="text-sm font-semibold text-slate-900">Procedures</h2>
<ul class="mt-3 space-y-2 text-sm">
@forelse ($report['procedure_breakdown'] as $row)
<li class="flex justify-between gap-3">
<span>{{ $row['procedure'] }}</span>
<span class="tabular-nums text-slate-600">{{ $row['total'] }}</span>
</li>
@empty
<li class="text-slate-500">No procedures in range.</li>
@endforelse
</ul>
</section>
</div>
<section class="rounded-2xl border border-slate-200 bg-white p-5">
<h2 class="text-sm font-semibold text-slate-900">Cardiology service revenue</h2>
<ul class="mt-3 space-y-2 text-sm">
@forelse ($report['revenue_by_service'] as $row)
<li class="flex justify-between gap-3">
<span>{{ $row->description }} <span class="text-slate-400">×{{ $row->total }}</span></span>
<span class="tabular-nums">{{ $currency }} {{ number_format($row->amount_minor / 100, 2) }}</span>
</li>
@empty
<li class="text-slate-500">No billed cardiology services in range.</li>
@endforelse
</ul>
</section>
</div>
</x-app-layout>
@@ -0,0 +1,71 @@
@php
$hist = $cardiologyHistory?->payload ?? [];
$exam = $cardiologyExam?->payload ?? [];
$plan = $cardiologyPlan?->payload ?? [];
@endphp
<section class="rounded-2xl border border-slate-200 bg-white p-5">
<div class="flex flex-wrap items-start justify-between gap-3">
<div>
<h3 class="text-sm font-semibold text-slate-900">Cardiology overview</h3>
<p class="mt-0.5 text-xs text-slate-500">History, exam / ECG, investigations, and care plan for this episode.</p>
</div>
<div class="flex flex-wrap gap-3 text-sm">
<a href="{{ route('care.specialty.cardiology.print', $workspaceVisit) }}" target="_blank" class="font-medium text-indigo-600">Print summary</a>
<a href="{{ route('care.specialty.cardiology.reports') }}" class="font-medium text-indigo-600">Cardiology reports</a>
</div>
</div>
<div class="mt-4 grid gap-3 sm:grid-cols-3">
<div class="rounded-xl border border-slate-100 bg-slate-50 px-3 py-3">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Complaint</p>
<p class="mt-1 text-sm font-semibold text-slate-900">{{ $exam['chief_complaint'] ?? '—' }}</p>
<p class="mt-1 text-xs text-slate-500">NYHA {{ $exam['nyha_class'] ?? '—' }}</p>
</div>
<div class="rounded-xl border border-slate-100 bg-slate-50 px-3 py-3">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Vitals / ECG</p>
<p class="mt-1 text-sm font-semibold text-slate-900">BP {{ $exam['bp'] ?? '—' }} · HR {{ $exam['hr'] ?? '—' }}</p>
<p class="mt-1 text-xs text-slate-500">{{ \Illuminate\Support\Str::limit($exam['ecg_findings'] ?? '—', 50) }}</p>
</div>
<div class="rounded-xl border border-slate-100 bg-slate-50 px-3 py-3">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Diagnosis / plan</p>
<p class="mt-1 text-sm font-semibold text-slate-900">{{ $plan['diagnosis'] ?? 'Not set' }}</p>
<p class="mt-1 text-xs text-slate-500">{{ $plan['follow_up'] ?? '—' }}</p>
</div>
</div>
<dl class="mt-4 grid gap-3 text-sm sm:grid-cols-2">
<div>
<dt class="text-slate-500">History</dt>
<dd class="font-medium text-slate-900">{{ $hist['history'] ?? '—' }}</dd>
</div>
<div>
<dt class="text-slate-500">Plan</dt>
<dd class="font-medium text-slate-900">{{ $plan['plan'] ?? '—' }}</dd>
</div>
<div>
<dt class="text-slate-500">Queue</dt>
<dd class="font-medium text-slate-900">
{{ $workspaceVisit->appointment?->queue_ticket_number ?? '—' }}
@if ($workspaceVisit->appointment?->queue_ticket_status)
<span class="text-slate-500">({{ $workspaceVisit->appointment->queue_ticket_status }})</span>
@endif
</dd>
</div>
<div>
<dt class="text-slate-500">Checked in</dt>
<dd class="font-medium text-slate-900">{{ $workspaceVisit->checked_in_at?->format('d M Y H:i') ?? '—' }}</dd>
</div>
</dl>
@if (! empty($clinicalAlerts))
<div class="mt-4 space-y-1.5 border-t border-slate-100 pt-4">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Alerts</p>
@foreach ($clinicalAlerts as $alert)
<p class="text-sm {{ ($alert['severity'] ?? '') === 'critical' ? 'text-rose-700' : 'text-amber-800' }}">
{{ $alert['message'] ?? '' }}
</p>
@endforeach
</div>
@endif
</section>
@@ -0,0 +1,70 @@
@php
$record = $cardiologyProcedure;
$payload = $record?->payload ?? [];
$canManage = $canManageClinical ?? $canConsult ?? false;
@endphp
<section class="rounded-2xl border border-slate-200 bg-white p-5">
<div class="flex flex-wrap items-start justify-between gap-3">
<div>
<h3 class="text-sm font-semibold text-slate-900">Procedure / intervention</h3>
<p class="mt-0.5 text-xs text-slate-500">Completed interventions can close the cardiology visit.</p>
</div>
<a href="{{ route('care.specialty.cardiology.print', $workspaceVisit) }}" target="_blank" class="text-sm font-medium text-indigo-600">Print summary</a>
</div>
@if ($canManage)
<form method="POST" action="{{ route('care.specialty.cardiology.procedure', $workspaceVisit) }}" class="mt-4 space-y-4">
@csrf
<input type="hidden" name="tab" value="procedures">
<div class="grid gap-3 sm:grid-cols-2">
@foreach ($clinicalFields ?? [] as $field)
@php
$name = $field['name'];
$value = old('payload.'.$name, $payload[$name] ?? '');
$type = $field['type'] ?? 'text';
@endphp
<div @class(['sm:col-span-2' => in_array($type, ['textarea'], true)])>
<label class="block text-xs font-medium text-slate-600">
{{ $field['label'] }}
@if (! empty($field['required'])) <span class="text-rose-600">*</span> @endif
</label>
@if ($type === 'textarea')
<textarea name="payload[{{ $name }}]" rows="{{ $field['rows'] ?? 3 }}" @required(! empty($field['required']))
class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">{{ $value }}</textarea>
@elseif ($type === 'select')
<select name="payload[{{ $name }}]" @required(! empty($field['required']))
class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
<option value="">Select…</option>
@foreach ($field['options'] ?? [] as $option)
<option value="{{ $option }}" @selected((string) $value === (string) $option)>{{ $option }}</option>
@endforeach
</select>
@elseif ($type === 'boolean')
<label class="mt-2 inline-flex items-center gap-2 text-sm text-slate-700">
<input type="checkbox" name="payload[{{ $name }}]" value="1" @checked(old('payload.'.$name, ! empty($payload[$name])))>
Yes
</label>
@else
<input type="{{ $type === 'number' ? 'number' : 'text' }}" name="payload[{{ $name }}]" value="{{ $value }}"
@required(! empty($field['required']))
class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
@endif
</div>
@endforeach
</div>
<button type="submit" class="btn-primary">Save procedure</button>
</form>
@elseif ($record)
<dl class="mt-4 grid gap-3 text-sm sm:grid-cols-2">
@foreach ($clinicalFields ?? [] as $field)
<div>
<dt class="text-slate-500">{{ $field['label'] }}</dt>
<dd class="font-medium text-slate-900">{{ $payload[$field['name']] ?? '—' }}</dd>
</div>
@endforeach
</dl>
@else
<p class="mt-4 text-sm text-slate-500">No procedure recorded yet.</p>
@endif
</section>
@@ -47,6 +47,9 @@
'ophthalmology' => 'check_in',
'physiotherapy' => 'check_in',
'maternity' => 'check_in',
'radiology' => 'check_in',
'cardiology' => 'check_in',
'psychiatry' => 'check_in',
default => collect($stages ?? [])->pluck('code')->first(),
};
$defaultStartLabel = match ($moduleKey) {
@@ -56,6 +59,9 @@
'ophthalmology' => 'Start check-in',
'physiotherapy' => 'Start check-in',
'maternity' => 'Start check-in',
'radiology' => 'Start check-in',
'cardiology' => 'Start check-in',
'psychiatry' => 'Start check-in',
default => 'Start',
};
$currentStage = $workspaceVisit?->specialty_stage;
@@ -0,0 +1,81 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Psychiatry summary · {{ $patient->fullName() }}</title>
<style>
body { font-family: system-ui, sans-serif; color: #0f172a; margin: 2rem; }
h1 { font-size: 1.25rem; margin: 0 0 .25rem; }
h2 { font-size: .95rem; margin: 1.25rem 0 .5rem; border-bottom: 1px solid #e2e8f0; padding-bottom: .25rem; }
.meta { color: #64748b; font-size: .875rem; }
dl { display: grid; grid-template-columns: 10rem 1fr; gap: .35rem .75rem; font-size: .875rem; }
dt { color: #64748b; }
dd { margin: 0; font-weight: 500; }
@media print { .no-print { display: none; } }
</style>
</head>
<body>
<p class="no-print"><a href="{{ route('care.specialty.workspace', ['module' => 'psychiatry', 'visit' => $visit]) }}">Back</a></p>
<h1>{{ $patient->fullName() }}</h1>
<p class="meta">
{{ $patient->patient_number }}
· Visit #{{ $visit->id }}
· Stage {{ $visit->specialty_stage ?? '—' }}
· {{ $visit->checked_in_at?->format('d M Y H:i') ?? '—' }}
</p>
<h2>History / MSE</h2>
@if ($history)
<dl>
<dt>Presenting</dt><dd>{{ $history->payload['chief_complaint'] ?? '—' }}</dd>
<dt>History</dt><dd>{{ $history->payload['history'] ?? '—' }}</dd>
<dt>Mood / affect</dt><dd>{{ $history->payload['mood_affect'] ?? '—' }}</dd>
<dt>Thought</dt><dd>{{ $history->payload['thought'] ?? '—' }}</dd>
<dt>MSE summary</dt><dd>{{ $history->payload['mse_summary'] ?? '—' }}</dd>
</dl>
@else
<p class="meta">No MSE recorded.</p>
@endif
<h2>Risk assessment</h2>
@if ($risk)
<dl>
<dt>Overall risk</dt><dd>{{ $risk->payload['overall_risk'] ?? '—' }}</dd>
<dt>Self-harm</dt><dd>{{ $risk->payload['self_harm'] ?? '—' }}</dd>
<dt>Risk to others</dt><dd>{{ $risk->payload['harm_others'] ?? '—' }}</dd>
<dt>Summary</dt><dd>{{ $risk->payload['risk_summary'] ?? '—' }}</dd>
<dt>Actions</dt><dd>{{ $risk->payload['immediate_actions'] ?? '—' }}</dd>
</dl>
@else
<p class="meta">No risk assessment recorded.</p>
@endif
<h2>Formulation / plan</h2>
@if ($plan)
<dl>
<dt>Formulation</dt><dd>{{ $plan->payload['formulation'] ?? '—' }}</dd>
<dt>Diagnosis</dt><dd>{{ $plan->payload['diagnosis'] ?? '—' }}</dd>
<dt>Plan</dt><dd>{{ $plan->payload['plan'] ?? '—' }}</dd>
<dt>Medications</dt><dd>{{ $plan->payload['medications'] ?? '—' }}</dd>
<dt>Follow-up</dt><dd>{{ $plan->payload['follow_up'] ?? '—' }}</dd>
</dl>
@else
<p class="meta">No formulation recorded.</p>
@endif
<h2>Follow-up</h2>
@if ($followup)
<dl>
<dt>Review type</dt><dd>{{ $followup->payload['review_type'] ?? '—' }}</dd>
<dt>Progress</dt><dd>{{ $followup->payload['progress'] ?? '—' }}</dd>
<dt>Outcome</dt><dd>{{ $followup->payload['outcome'] ?? '—' }}</dd>
<dt>Next steps</dt><dd>{{ $followup->payload['next_steps'] ?? '—' }}</dd>
</dl>
@else
<p class="meta">No follow-up recorded.</p>
@endif
<script>window.print();</script>
</body>
</html>
@@ -0,0 +1,88 @@
<x-app-layout title="Psychiatry reports">
<div class="space-y-6">
<div class="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 class="text-xl font-semibold text-slate-900">Psychiatry reports</h1>
<p class="mt-1 text-sm text-slate-500">Arrivals, high-risk open cases, risk levels, review outcomes, length of stay, and psychiatry revenue.</p>
</div>
<a href="{{ route('care.specialty.show', 'psychiatry') }}" class="text-sm font-medium text-indigo-600"> Specialty home</a>
</div>
<form method="GET" class="flex flex-wrap items-end gap-3 rounded-2xl border border-slate-200 bg-white p-4">
<div>
<label class="block text-xs font-medium text-slate-600">From</label>
<input type="date" name="from" value="{{ $report['from'] ?? '' }}" class="mt-1 rounded-xl border border-slate-200 px-3 py-2 text-sm">
</div>
<div>
<label class="block text-xs font-medium text-slate-600">To</label>
<input type="date" name="to" value="{{ $report['to'] ?? '' }}" class="mt-1 rounded-xl border border-slate-200 px-3 py-2 text-sm">
</div>
<button type="submit" class="rounded-xl bg-indigo-600 px-4 py-2 text-sm font-semibold text-white">Apply</button>
</form>
<div class="grid gap-4 sm:grid-cols-4">
<div class="rounded-2xl border border-slate-200 bg-white p-4">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Arrivals today</p>
<p class="mt-2 text-2xl font-semibold tabular-nums text-slate-900">{{ number_format($report['arrivals_today']) }}</p>
</div>
<div class="rounded-2xl border border-slate-200 bg-white p-4">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Completed today</p>
<p class="mt-2 text-2xl font-semibold tabular-nums text-slate-900">{{ number_format($report['completed_today']) }}</p>
</div>
<div class="rounded-2xl border border-slate-200 bg-white p-4">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">High risk open</p>
<p class="mt-2 text-2xl font-semibold tabular-nums text-rose-700">{{ number_format($report['high_risk_open']) }}</p>
</div>
<div class="rounded-2xl border border-slate-200 bg-white p-4">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Avg LOS (range)</p>
<p class="mt-2 text-2xl font-semibold tabular-nums text-slate-900">
{{ $report['avg_los_minutes'] !== null ? $report['avg_los_minutes'].' min' : '—' }}
</p>
</div>
</div>
<div class="grid gap-4 lg:grid-cols-2">
<section class="rounded-2xl border border-slate-200 bg-white p-5">
<h2 class="text-sm font-semibold text-slate-900">Risk levels</h2>
<ul class="mt-3 space-y-2 text-sm">
@forelse ($report['risk_breakdown'] as $row)
<li class="flex justify-between gap-3">
<span>{{ $row['risk'] }}</span>
<span class="tabular-nums text-slate-600">{{ $row['total'] }}</span>
</li>
@empty
<li class="text-slate-500">No risk assessments in range.</li>
@endforelse
</ul>
</section>
<section class="rounded-2xl border border-slate-200 bg-white p-5">
<h2 class="text-sm font-semibold text-slate-900">Review outcomes</h2>
<ul class="mt-3 space-y-2 text-sm">
@forelse ($report['review_outcomes'] as $row)
<li class="flex justify-between gap-3">
<span>{{ $row['outcome'] }}</span>
<span class="tabular-nums text-slate-600">{{ $row['total'] }}</span>
</li>
@empty
<li class="text-slate-500">No follow-up reviews in range.</li>
@endforelse
</ul>
</section>
</div>
<section class="rounded-2xl border border-slate-200 bg-white p-5">
<h2 class="text-sm font-semibold text-slate-900">Psychiatry service revenue</h2>
<ul class="mt-3 space-y-2 text-sm">
@forelse ($report['revenue_by_service'] as $row)
<li class="flex justify-between gap-3">
<span>{{ $row->description }} <span class="text-slate-400">×{{ $row->total }}</span></span>
<span class="tabular-nums">{{ $currency }} {{ number_format($row->amount_minor / 100, 2) }}</span>
</li>
@empty
<li class="text-slate-500">No billed psychiatry services in range.</li>
@endforelse
</ul>
</section>
</div>
</x-app-layout>
@@ -0,0 +1,70 @@
@php
$record = $psychiatryFollowup;
$payload = $record?->payload ?? [];
$canManage = $canManageClinical ?? $canConsult ?? false;
@endphp
<section class="rounded-2xl border border-slate-200 bg-white p-5">
<div class="flex flex-wrap items-start justify-between gap-3">
<div>
<h3 class="text-sm font-semibold text-slate-900">Follow-up review</h3>
<p class="mt-0.5 text-xs text-slate-500">Discharge and follow-up outcomes can close the psychiatry visit.</p>
</div>
<a href="{{ route('care.specialty.psychiatry.print', $workspaceVisit) }}" target="_blank" class="text-sm font-medium text-indigo-600">Print summary</a>
</div>
@if ($canManage)
<form method="POST" action="{{ route('care.specialty.psychiatry.followup', $workspaceVisit) }}" class="mt-4 space-y-4">
@csrf
<input type="hidden" name="tab" value="followup">
<div class="grid gap-3 sm:grid-cols-2">
@foreach ($clinicalFields ?? [] as $field)
@php
$name = $field['name'];
$value = old('payload.'.$name, $payload[$name] ?? '');
$type = $field['type'] ?? 'text';
@endphp
<div @class(['sm:col-span-2' => in_array($type, ['textarea'], true)])>
<label class="block text-xs font-medium text-slate-600">
{{ $field['label'] }}
@if (! empty($field['required'])) <span class="text-rose-600">*</span> @endif
</label>
@if ($type === 'textarea')
<textarea name="payload[{{ $name }}]" rows="{{ $field['rows'] ?? 3 }}" @required(! empty($field['required']))
class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">{{ $value }}</textarea>
@elseif ($type === 'select')
<select name="payload[{{ $name }}]" @required(! empty($field['required']))
class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
<option value="">Select…</option>
@foreach ($field['options'] ?? [] as $option)
<option value="{{ $option }}" @selected((string) $value === (string) $option)>{{ $option }}</option>
@endforeach
</select>
@elseif ($type === 'boolean')
<label class="mt-2 inline-flex items-center gap-2 text-sm text-slate-700">
<input type="checkbox" name="payload[{{ $name }}]" value="1" @checked(old('payload.'.$name, ! empty($payload[$name])))>
Yes
</label>
@else
<input type="{{ $type === 'number' ? 'number' : 'text' }}" name="payload[{{ $name }}]" value="{{ $value }}"
@required(! empty($field['required']))
class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
@endif
</div>
@endforeach
</div>
<button type="submit" class="btn-primary">Save follow-up</button>
</form>
@elseif ($record)
<dl class="mt-4 grid gap-3 text-sm sm:grid-cols-2">
@foreach ($clinicalFields ?? [] as $field)
<div>
<dt class="text-slate-500">{{ $field['label'] }}</dt>
<dd class="font-medium text-slate-900">{{ $payload[$field['name']] ?? '—' }}</dd>
</div>
@endforeach
</dl>
@else
<p class="mt-4 text-sm text-slate-500">No follow-up review recorded yet.</p>
@endif
</section>
@@ -0,0 +1,71 @@
@php
$mse = $psychiatryHistory?->payload ?? [];
$risk = $psychiatryRisk?->payload ?? [];
$plan = $psychiatryPlan?->payload ?? [];
@endphp
<section class="rounded-2xl border border-slate-200 bg-white p-5">
<div class="flex flex-wrap items-start justify-between gap-3">
<div>
<h3 class="text-sm font-semibold text-slate-900">Psychiatry overview</h3>
<p class="mt-0.5 text-xs text-slate-500">MSE, risk, formulation, and follow-up for this episode. Clinical notes use the same access controls as other specialty records.</p>
</div>
<div class="flex flex-wrap gap-3 text-sm">
<a href="{{ route('care.specialty.psychiatry.print', $workspaceVisit) }}" target="_blank" class="font-medium text-indigo-600">Print summary</a>
<a href="{{ route('care.specialty.psychiatry.reports') }}" class="font-medium text-indigo-600">Psychiatry reports</a>
</div>
</div>
<div class="mt-4 grid gap-3 sm:grid-cols-3">
<div class="rounded-xl border border-slate-100 bg-slate-50 px-3 py-3">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Presenting</p>
<p class="mt-1 text-sm font-semibold text-slate-900">{{ $mse['chief_complaint'] ?? '—' }}</p>
<p class="mt-1 text-xs text-slate-500">{{ $mse['mood_affect'] ?? '—' }}</p>
</div>
<div class="rounded-xl border border-slate-100 bg-slate-50 px-3 py-3">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Risk</p>
<p class="mt-1 text-sm font-semibold text-slate-900">{{ $risk['overall_risk'] ?? 'Not assessed' }}</p>
<p class="mt-1 text-xs text-slate-500">{{ \Illuminate\Support\Str::limit($risk['risk_summary'] ?? '—', 50) }}</p>
</div>
<div class="rounded-xl border border-slate-100 bg-slate-50 px-3 py-3">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Plan</p>
<p class="mt-1 text-sm font-semibold text-slate-900">{{ $plan['diagnosis'] ?? 'Not set' }}</p>
<p class="mt-1 text-xs text-slate-500">{{ $plan['follow_up'] ?? '—' }}</p>
</div>
</div>
<dl class="mt-4 grid gap-3 text-sm sm:grid-cols-2">
<div>
<dt class="text-slate-500">MSE summary</dt>
<dd class="font-medium text-slate-900">{{ $mse['mse_summary'] ?? '—' }}</dd>
</div>
<div>
<dt class="text-slate-500">Management plan</dt>
<dd class="font-medium text-slate-900">{{ $plan['plan'] ?? '—' }}</dd>
</div>
<div>
<dt class="text-slate-500">Queue</dt>
<dd class="font-medium text-slate-900">
{{ $workspaceVisit->appointment?->queue_ticket_number ?? '—' }}
@if ($workspaceVisit->appointment?->queue_ticket_status)
<span class="text-slate-500">({{ $workspaceVisit->appointment->queue_ticket_status }})</span>
@endif
</dd>
</div>
<div>
<dt class="text-slate-500">Checked in</dt>
<dd class="font-medium text-slate-900">{{ $workspaceVisit->checked_in_at?->format('d M Y H:i') ?? '—' }}</dd>
</div>
</dl>
@if (! empty($clinicalAlerts))
<div class="mt-4 space-y-1.5 border-t border-slate-100 pt-4">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Alerts</p>
@foreach ($clinicalAlerts as $alert)
<p class="text-sm {{ ($alert['severity'] ?? '') === 'critical' ? 'text-rose-700' : 'text-amber-800' }}">
{{ $alert['message'] ?? '' }}
</p>
@endforeach
</div>
@endif
</section>
@@ -0,0 +1,79 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Radiology summary · {{ $patient->fullName() }}</title>
<style>
body { font-family: system-ui, sans-serif; color: #0f172a; margin: 2rem; }
h1 { font-size: 1.25rem; margin: 0 0 .25rem; }
h2 { font-size: .95rem; margin: 1.25rem 0 .5rem; border-bottom: 1px solid #e2e8f0; padding-bottom: .25rem; }
.meta { color: #64748b; font-size: .875rem; }
dl { display: grid; grid-template-columns: 10rem 1fr; gap: .35rem .75rem; font-size: .875rem; }
dt { color: #64748b; }
dd { margin: 0; font-weight: 500; }
@media print { .no-print { display: none; } }
</style>
</head>
<body>
<p class="no-print"><a href="{{ route('care.specialty.workspace', ['module' => 'radiology', 'visit' => $visit]) }}">Back</a></p>
<h1>{{ $patient->fullName() }}</h1>
<p class="meta">
{{ $patient->patient_number }}
· Visit #{{ $visit->id }}
· Stage {{ $visit->specialty_stage ?? '—' }}
· {{ $visit->checked_in_at?->format('d M Y H:i') ?? '—' }}
</p>
<h2>Request / protocol</h2>
@if ($imagingRequest)
<dl>
<dt>Modality</dt><dd>{{ $imagingRequest->payload['modality'] ?? '—' }}</dd>
<dt>Body part</dt><dd>{{ $imagingRequest->payload['body_part'] ?? '—' }}</dd>
<dt>Urgency</dt><dd>{{ $imagingRequest->payload['urgency'] ?? '—' }}</dd>
<dt>Contrast</dt><dd>{{ $imagingRequest->payload['contrast'] ?? '—' }}</dd>
<dt>Clinical info</dt><dd>{{ $imagingRequest->payload['clinical_info'] ?? '—' }}</dd>
<dt>Protocol</dt><dd>{{ $imagingRequest->payload['protocol'] ?? '—' }}</dd>
</dl>
@else
<p class="meta">No imaging request recorded.</p>
@endif
<h2>Acquisition</h2>
@if ($acquisition)
<dl>
<dt>Status</dt><dd>{{ $acquisition->payload['acquisition_status'] ?? '—' }}</dd>
<dt>Quality</dt><dd>{{ $acquisition->payload['quality'] ?? '—' }}</dd>
<dt>Technologist</dt><dd>{{ $acquisition->payload['technologist'] ?? '—' }}</dd>
<dt>Notes</dt><dd>{{ $acquisition->payload['notes'] ?? '—' }}</dd>
</dl>
@else
<p class="meta">No acquisition recorded.</p>
@endif
<h2>Findings / report</h2>
@if ($imagingReport)
<dl>
<dt>Technique</dt><dd>{{ $imagingReport->payload['technique'] ?? '—' }}</dd>
<dt>Findings</dt><dd>{{ $imagingReport->payload['findings'] ?? '—' }}</dd>
<dt>Impression</dt><dd>{{ $imagingReport->payload['impression'] ?? '—' }}</dd>
<dt>Recommendations</dt><dd>{{ $imagingReport->payload['recommendations'] ?? '—' }}</dd>
</dl>
@else
<p class="meta">No report recorded.</p>
@endif
<h2>Verification</h2>
@if ($verification)
<dl>
<dt>Status</dt><dd>{{ $verification->payload['verification_status'] ?? '—' }}</dd>
<dt>Verified by</dt><dd>{{ $verification->payload['verified_by'] ?? '—' }}</dd>
<dt>Notes</dt><dd>{{ $verification->payload['notes'] ?? '—' }}</dd>
</dl>
@else
<p class="meta">No verification recorded.</p>
@endif
<script>window.print();</script>
</body>
</html>
@@ -0,0 +1,88 @@
<x-app-layout title="Radiology reports">
<div class="space-y-6">
<div class="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 class="text-xl font-semibold text-slate-900">Radiology reports</h1>
<p class="mt-1 text-sm text-slate-500">Arrivals, urgent studies, modalities, verification outcomes, length of stay, and imaging revenue.</p>
</div>
<a href="{{ route('care.specialty.show', 'radiology') }}" class="text-sm font-medium text-indigo-600"> Specialty home</a>
</div>
<form method="GET" class="flex flex-wrap items-end gap-3 rounded-2xl border border-slate-200 bg-white p-4">
<div>
<label class="block text-xs font-medium text-slate-600">From</label>
<input type="date" name="from" value="{{ $report['from'] ?? '' }}" class="mt-1 rounded-xl border border-slate-200 px-3 py-2 text-sm">
</div>
<div>
<label class="block text-xs font-medium text-slate-600">To</label>
<input type="date" name="to" value="{{ $report['to'] ?? '' }}" class="mt-1 rounded-xl border border-slate-200 px-3 py-2 text-sm">
</div>
<button type="submit" class="rounded-xl bg-indigo-600 px-4 py-2 text-sm font-semibold text-white">Apply</button>
</form>
<div class="grid gap-4 sm:grid-cols-4">
<div class="rounded-2xl border border-slate-200 bg-white p-4">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Arrivals today</p>
<p class="mt-2 text-2xl font-semibold tabular-nums text-slate-900">{{ number_format($report['arrivals_today']) }}</p>
</div>
<div class="rounded-2xl border border-slate-200 bg-white p-4">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Completed today</p>
<p class="mt-2 text-2xl font-semibold tabular-nums text-slate-900">{{ number_format($report['completed_today']) }}</p>
</div>
<div class="rounded-2xl border border-slate-200 bg-white p-4">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Urgent open</p>
<p class="mt-2 text-2xl font-semibold tabular-nums text-rose-700">{{ number_format($report['urgent_open']) }}</p>
</div>
<div class="rounded-2xl border border-slate-200 bg-white p-4">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Avg LOS (range)</p>
<p class="mt-2 text-2xl font-semibold tabular-nums text-slate-900">
{{ $report['avg_los_minutes'] !== null ? $report['avg_los_minutes'].' min' : '—' }}
</p>
</div>
</div>
<div class="grid gap-4 lg:grid-cols-2">
<section class="rounded-2xl border border-slate-200 bg-white p-5">
<h2 class="text-sm font-semibold text-slate-900">Modalities</h2>
<ul class="mt-3 space-y-2 text-sm">
@forelse ($report['modality_breakdown'] as $row)
<li class="flex justify-between gap-3">
<span>{{ $row['modality'] }}</span>
<span class="tabular-nums text-slate-600">{{ $row['total'] }}</span>
</li>
@empty
<li class="text-slate-500">No imaging requests in range.</li>
@endforelse
</ul>
</section>
<section class="rounded-2xl border border-slate-200 bg-white p-5">
<h2 class="text-sm font-semibold text-slate-900">Verification outcomes</h2>
<ul class="mt-3 space-y-2 text-sm">
@forelse ($report['verification_outcomes'] as $row)
<li class="flex justify-between gap-3">
<span>{{ $row['status'] }}</span>
<span class="tabular-nums text-slate-600">{{ $row['total'] }}</span>
</li>
@empty
<li class="text-slate-500">No verifications in range.</li>
@endforelse
</ul>
</section>
</div>
<section class="rounded-2xl border border-slate-200 bg-white p-5">
<h2 class="text-sm font-semibold text-slate-900">Radiology service revenue</h2>
<ul class="mt-3 space-y-2 text-sm">
@forelse ($report['revenue_by_service'] as $row)
<li class="flex justify-between gap-3">
<span>{{ $row->description }} <span class="text-slate-400">×{{ $row->total }}</span></span>
<span class="tabular-nums">{{ $currency }} {{ number_format($row->amount_minor / 100, 2) }}</span>
</li>
@empty
<li class="text-slate-500">No billed radiology services in range.</li>
@endforelse
</ul>
</section>
</div>
</x-app-layout>
@@ -0,0 +1,72 @@
@php
$req = $radiologyRequest?->payload ?? [];
$acq = $radiologyAcquisition?->payload ?? [];
$rep = $radiologyReport?->payload ?? [];
$ver = $radiologyVerification?->payload ?? [];
@endphp
<section class="rounded-2xl border border-slate-200 bg-white p-5">
<div class="flex flex-wrap items-start justify-between gap-3">
<div>
<h3 class="text-sm font-semibold text-slate-900">Radiology overview</h3>
<p class="mt-0.5 text-xs text-slate-500">Request, acquisition, report, and verification for this study.</p>
</div>
<div class="flex flex-wrap gap-3 text-sm">
<a href="{{ route('care.specialty.radiology.print', $workspaceVisit) }}" target="_blank" class="font-medium text-indigo-600">Print summary</a>
<a href="{{ route('care.specialty.radiology.reports') }}" class="font-medium text-indigo-600">Radiology reports</a>
</div>
</div>
<div class="mt-4 grid gap-3 sm:grid-cols-3">
<div class="rounded-xl border border-slate-100 bg-slate-50 px-3 py-3">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Request</p>
<p class="mt-1 text-sm font-semibold text-slate-900">{{ $req['modality'] ?? '—' }} · {{ $req['body_part'] ?? '—' }}</p>
<p class="mt-1 text-xs text-slate-500">{{ $req['urgency'] ?? 'Routine' }}</p>
</div>
<div class="rounded-xl border border-slate-100 bg-slate-50 px-3 py-3">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Acquisition</p>
<p class="mt-1 text-sm font-semibold text-slate-900">{{ $acq['acquisition_status'] ?? 'Not started' }}</p>
<p class="mt-1 text-xs text-slate-500">{{ $acq['quality'] ?? '—' }}</p>
</div>
<div class="rounded-xl border border-slate-100 bg-slate-50 px-3 py-3">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Report / verify</p>
<p class="mt-1 text-sm font-semibold text-slate-900">{{ $ver['verification_status'] ?? 'Draft' }}</p>
<p class="mt-1 text-xs text-slate-500">{{ \Illuminate\Support\Str::limit($rep['impression'] ?? '—', 60) }}</p>
</div>
</div>
<dl class="mt-4 grid gap-3 text-sm sm:grid-cols-2">
<div>
<dt class="text-slate-500">Clinical info</dt>
<dd class="font-medium text-slate-900">{{ $req['clinical_info'] ?? '—' }}</dd>
</div>
<div>
<dt class="text-slate-500">Impression</dt>
<dd class="font-medium text-slate-900">{{ $rep['impression'] ?? '—' }}</dd>
</div>
<div>
<dt class="text-slate-500">Queue</dt>
<dd class="font-medium text-slate-900">
{{ $workspaceVisit->appointment?->queue_ticket_number ?? '—' }}
@if ($workspaceVisit->appointment?->queue_ticket_status)
<span class="text-slate-500">({{ $workspaceVisit->appointment->queue_ticket_status }})</span>
@endif
</dd>
</div>
<div>
<dt class="text-slate-500">Checked in</dt>
<dd class="font-medium text-slate-900">{{ $workspaceVisit->checked_in_at?->format('d M Y H:i') ?? '—' }}</dd>
</div>
</dl>
@if (! empty($clinicalAlerts))
<div class="mt-4 space-y-1.5 border-t border-slate-100 pt-4">
<p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Alerts</p>
@foreach ($clinicalAlerts as $alert)
<p class="text-sm {{ ($alert['severity'] ?? '') === 'critical' ? 'text-rose-700' : 'text-amber-800' }}">
{{ $alert['message'] ?? '' }}
</p>
@endforeach
</div>
@endif
</section>
@@ -0,0 +1,70 @@
@php
$record = $radiologyVerification;
$payload = $record?->payload ?? [];
$canManage = $canManageClinical ?? $canConsult ?? false;
@endphp
<section class="rounded-2xl border border-slate-200 bg-white p-5">
<div class="flex flex-wrap items-start justify-between gap-3">
<div>
<h3 class="text-sm font-semibold text-slate-900">Verification</h3>
<p class="mt-0.5 text-xs text-slate-500">Final / verified reports can close the imaging episode.</p>
</div>
<a href="{{ route('care.specialty.radiology.print', $workspaceVisit) }}" target="_blank" class="text-sm font-medium text-indigo-600">Print summary</a>
</div>
@if ($canManage)
<form method="POST" action="{{ route('care.specialty.radiology.verification', $workspaceVisit) }}" class="mt-4 space-y-4">
@csrf
<input type="hidden" name="tab" value="verification">
<div class="grid gap-3 sm:grid-cols-2">
@foreach ($clinicalFields ?? [] as $field)
@php
$name = $field['name'];
$value = old('payload.'.$name, $payload[$name] ?? '');
$type = $field['type'] ?? 'text';
@endphp
<div @class(['sm:col-span-2' => in_array($type, ['textarea'], true)])>
<label class="block text-xs font-medium text-slate-600">
{{ $field['label'] }}
@if (! empty($field['required'])) <span class="text-rose-600">*</span> @endif
</label>
@if ($type === 'textarea')
<textarea name="payload[{{ $name }}]" rows="{{ $field['rows'] ?? 3 }}" @required(! empty($field['required']))
class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">{{ $value }}</textarea>
@elseif ($type === 'select')
<select name="payload[{{ $name }}]" @required(! empty($field['required']))
class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
<option value="">Select…</option>
@foreach ($field['options'] ?? [] as $option)
<option value="{{ $option }}" @selected((string) $value === (string) $option)>{{ $option }}</option>
@endforeach
</select>
@elseif ($type === 'boolean')
<label class="mt-2 inline-flex items-center gap-2 text-sm text-slate-700">
<input type="checkbox" name="payload[{{ $name }}]" value="1" @checked(old('payload.'.$name, ! empty($payload[$name])))>
Yes
</label>
@else
<input type="{{ $type === 'number' ? 'number' : 'text' }}" name="payload[{{ $name }}]" value="{{ $value }}"
@required(! empty($field['required']))
class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
@endif
</div>
@endforeach
</div>
<button type="submit" class="btn-primary">Save verification</button>
</form>
@elseif ($record)
<dl class="mt-4 grid gap-3 text-sm sm:grid-cols-2">
@foreach ($clinicalFields ?? [] as $field)
<div>
<dt class="text-slate-500">{{ $field['label'] }}</dt>
<dd class="font-medium text-slate-900">{{ $payload[$field['name']] ?? '—' }}</dd>
</div>
@endforeach
</dl>
@else
<p class="mt-4 text-sm text-slate-500">No verification recorded yet.</p>
@endif
</section>
@@ -67,6 +67,12 @@
@include('care.specialty.physiotherapy.workspace-'.$activeTab)
@elseif ($moduleKey === 'maternity' && in_array($activeTab, ['overview', 'postnatal'], true))
@include('care.specialty.maternity.workspace-'.$activeTab)
@elseif ($moduleKey === 'radiology' && in_array($activeTab, ['overview', 'verification'], true))
@include('care.specialty.radiology.workspace-'.$activeTab)
@elseif ($moduleKey === 'cardiology' && in_array($activeTab, ['overview', 'procedures'], true))
@include('care.specialty.cardiology.workspace-'.$activeTab)
@elseif ($moduleKey === 'psychiatry' && in_array($activeTab, ['overview', 'followup'], true))
@include('care.specialty.psychiatry.workspace-'.$activeTab)
@elseif ($activeTab === 'billing')
<section class="rounded-2xl border border-slate-200 bg-white p-5">
<h3 class="text-sm font-semibold text-slate-900">
@@ -43,6 +43,15 @@
@if ($moduleKey === 'maternity')
<a href="{{ route('care.specialty.maternity.reports') }}" class="text-slate-600 hover:text-slate-900">Reports</a>
@endif
@if ($moduleKey === 'radiology')
<a href="{{ route('care.specialty.radiology.reports') }}" class="text-slate-600 hover:text-slate-900">Reports</a>
@endif
@if ($moduleKey === 'cardiology')
<a href="{{ route('care.specialty.cardiology.reports') }}" class="text-slate-600 hover:text-slate-900">Reports</a>
@endif
@if ($moduleKey === 'psychiatry')
<a href="{{ route('care.specialty.psychiatry.reports') }}" class="text-slate-600 hover:text-slate-900">Reports</a>
@endif
<a href="{{ route('care.specialty.history', $moduleKey) }}" class="text-slate-600 hover:text-slate-900">History</a>
@if ($canManageClinical ?? $canManageSpecialty ?? true)
<a href="{{ route('care.specialty.billing', $moduleKey) }}" class="text-slate-600 hover:text-slate-900">Billing</a>
+15
View File
@@ -44,6 +44,9 @@ use App\Http\Controllers\Care\EmergencyWorkspaceController;
use App\Http\Controllers\Care\OphthalmologyWorkspaceController;
use App\Http\Controllers\Care\PhysiotherapyWorkspaceController;
use App\Http\Controllers\Care\MaternityWorkspaceController;
use App\Http\Controllers\Care\RadiologyWorkspaceController;
use App\Http\Controllers\Care\CardiologyWorkspaceController;
use App\Http\Controllers\Care\PsychiatryWorkspaceController;
use App\Http\Controllers\Care\SpecialtyModuleController;
use App\Http\Controllers\Care\VisitWorkflowController;
use App\Http\Controllers\NotificationController;
@@ -129,6 +132,9 @@ Route::middleware(['auth', 'platform.session'])->group(function () {
Route::get('/specialty/ophthalmology/reports', [OphthalmologyWorkspaceController::class, 'reports'])->name('care.specialty.ophthalmology.reports');
Route::get('/specialty/physiotherapy/reports', [PhysiotherapyWorkspaceController::class, 'reports'])->name('care.specialty.physiotherapy.reports');
Route::get('/specialty/maternity/reports', [MaternityWorkspaceController::class, 'reports'])->name('care.specialty.maternity.reports');
Route::get('/specialty/radiology/reports', [RadiologyWorkspaceController::class, 'reports'])->name('care.specialty.radiology.reports');
Route::get('/specialty/cardiology/reports', [CardiologyWorkspaceController::class, 'reports'])->name('care.specialty.cardiology.reports');
Route::get('/specialty/psychiatry/reports', [PsychiatryWorkspaceController::class, 'reports'])->name('care.specialty.psychiatry.reports');
Route::get('/specialty/{module}/workspace/{visit?}', [SpecialtyModuleController::class, 'workspace'])->name('care.specialty.workspace');
Route::post('/specialty/{module}/workspace/{visit}/clinical', [SpecialtyModuleController::class, 'saveClinical'])->name('care.specialty.clinical.save');
Route::post('/specialty/{module}/workspace/{visit}/documents', [SpecialtyModuleController::class, 'uploadDocument'])->name('care.specialty.documents.upload');
@@ -171,6 +177,15 @@ Route::middleware(['auth', 'platform.session'])->group(function () {
Route::post('/specialty/maternity/workspace/{visit}/stage', [MaternityWorkspaceController::class, 'setStage'])->name('care.specialty.maternity.stage');
Route::post('/specialty/maternity/workspace/{visit}/postnatal', [MaternityWorkspaceController::class, 'savePostnatal'])->name('care.specialty.maternity.postnatal');
Route::get('/specialty/maternity/workspace/{visit}/print', [MaternityWorkspaceController::class, 'printSummary'])->name('care.specialty.maternity.print');
Route::post('/specialty/radiology/workspace/{visit}/stage', [RadiologyWorkspaceController::class, 'setStage'])->name('care.specialty.radiology.stage');
Route::post('/specialty/radiology/workspace/{visit}/verification', [RadiologyWorkspaceController::class, 'saveVerification'])->name('care.specialty.radiology.verification');
Route::get('/specialty/radiology/workspace/{visit}/print', [RadiologyWorkspaceController::class, 'printSummary'])->name('care.specialty.radiology.print');
Route::post('/specialty/cardiology/workspace/{visit}/stage', [CardiologyWorkspaceController::class, 'setStage'])->name('care.specialty.cardiology.stage');
Route::post('/specialty/cardiology/workspace/{visit}/procedure', [CardiologyWorkspaceController::class, 'saveProcedure'])->name('care.specialty.cardiology.procedure');
Route::get('/specialty/cardiology/workspace/{visit}/print', [CardiologyWorkspaceController::class, 'printSummary'])->name('care.specialty.cardiology.print');
Route::post('/specialty/psychiatry/workspace/{visit}/stage', [PsychiatryWorkspaceController::class, 'setStage'])->name('care.specialty.psychiatry.stage');
Route::post('/specialty/psychiatry/workspace/{visit}/followup', [PsychiatryWorkspaceController::class, 'saveFollowUp'])->name('care.specialty.psychiatry.followup');
Route::get('/specialty/psychiatry/workspace/{visit}/print', [PsychiatryWorkspaceController::class, 'printSummary'])->name('care.specialty.psychiatry.print');
Route::get('/specialty/{module}', [SpecialtyModuleController::class, 'show'])->name('care.specialty.show');
Route::post('/specialty/{module}/call-next', [SpecialtyModuleController::class, 'callNext'])->name('care.specialty.call-next');
Route::post('/specialty/{module}/refer', [SpecialtyModuleController::class, 'refer'])->name('care.specialty.refer');
+237
View File
@@ -0,0 +1,237 @@
<?php
namespace Tests\Feature;
use App\Http\Middleware\EnsurePlatformSession;
use App\Models\Appointment;
use App\Models\Branch;
use App\Models\Department;
use App\Models\Member;
use App\Models\Organization;
use App\Models\Patient;
use App\Models\SpecialtyClinicalRecord;
use App\Models\User;
use App\Models\Visit;
use App\Services\Care\SpecialtyModuleService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class CareCardiologySuiteTest extends TestCase
{
use RefreshDatabase;
protected User $owner;
protected Organization $organization;
protected Branch $branch;
protected Patient $patient;
protected Visit $visit;
protected function setUp(): void
{
parent::setUp();
$this->withoutMiddleware(EnsurePlatformSession::class);
$this->owner = User::create([
'public_id' => 'car-owner',
'name' => 'Owner',
'email' => 'car-owner@example.com',
]);
$this->organization = Organization::create([
'owner_ref' => $this->owner->public_id,
'name' => 'Cardiology Clinic',
'slug' => 'cardiology-clinic',
'settings' => [
'onboarded' => true,
'facility_type' => 'clinic',
'plan' => 'pro',
'plan_expires_at' => now()->addMonth()->toIso8601String(),
'queue_integration_enabled' => true,
],
]);
Member::create([
'owner_ref' => $this->owner->public_id,
'organization_id' => $this->organization->id,
'user_ref' => $this->owner->public_id,
'role' => 'hospital_admin',
'branch_id' => null,
]);
$this->branch = Branch::create([
'owner_ref' => $this->owner->public_id,
'organization_id' => $this->organization->id,
'name' => 'Main',
'is_active' => true,
]);
app(SpecialtyModuleService::class)->activate(
$this->organization,
$this->owner->public_id,
'cardiology',
);
$department = Department::query()
->where('branch_id', $this->branch->id)
->where('type', 'cardiology')
->firstOrFail();
$this->patient = Patient::create([
'owner_ref' => $this->owner->public_id,
'organization_id' => $this->organization->id,
'branch_id' => $this->branch->id,
'patient_number' => 'P-CAR-SUITE',
'first_name' => 'Kwesi',
'last_name' => 'Mensah',
'gender' => 'male',
'date_of_birth' => '1975-03-20',
]);
$this->visit = Visit::create([
'owner_ref' => $this->owner->public_id,
'organization_id' => $this->organization->id,
'branch_id' => $this->branch->id,
'patient_id' => $this->patient->id,
'status' => Visit::STATUS_IN_PROGRESS,
'checked_in_at' => now(),
'specialty_stage' => 'check_in',
]);
Appointment::create([
'owner_ref' => $this->owner->public_id,
'organization_id' => $this->organization->id,
'branch_id' => $this->branch->id,
'patient_id' => $this->patient->id,
'department_id' => $department->id,
'visit_id' => $this->visit->id,
'type' => Appointment::TYPE_WALK_IN,
'status' => Appointment::STATUS_IN_CONSULTATION,
'scheduled_at' => now(),
'waiting_at' => now(),
'checked_in_at' => now(),
'started_at' => now(),
]);
}
public function test_overview_and_exam_tabs_render(): void
{
$this->actingAs($this->owner)
->get(route('care.specialty.workspace', [
'module' => 'cardiology',
'visit' => $this->visit,
'tab' => 'overview',
]))
->assertOk()
->assertSee('Cardiology overview')
->assertSee('data-care-stage-bar', false)
->assertSee('Exam / ECG')
->assertSee('Start history')
->assertSee('Cardiology reports');
$this->actingAs($this->owner)
->get(route('care.specialty.workspace', [
'module' => 'cardiology',
'visit' => $this->visit,
'tab' => 'exam',
]))
->assertOk()
->assertSee('Chief complaint')
->assertSee('ECG findings');
}
public function test_exam_sets_stage_and_nyha_alert(): void
{
$this->actingAs($this->owner)
->post(route('care.specialty.clinical.save', [
'module' => 'cardiology',
'visit' => $this->visit,
]), [
'tab' => 'exam',
'payload' => [
'chief_complaint' => 'Dyspnoea',
'nyha_class' => 'III',
'bp' => '160/95',
'hr' => 98,
'ecg_findings' => 'Sinus tach; no STEMI',
'exam_findings' => 'Basal crackles',
],
])
->assertRedirect();
$this->assertSame('exam', $this->visit->fresh()->specialty_stage);
$record = SpecialtyClinicalRecord::query()
->where('visit_id', $this->visit->id)
->where('record_type', 'cardiac_exam')
->firstOrFail();
$codes = collect($record->alerts)->pluck('code')->all();
$this->assertContains('car.nyha_high', $codes);
}
public function test_stage_advance_and_procedure_completes_visit(): void
{
$this->actingAs($this->owner)
->post(route('care.specialty.cardiology.stage', $this->visit), [
'stage' => 'procedure',
])
->assertRedirect(route('care.specialty.workspace', [
'module' => 'cardiology',
'visit' => $this->visit,
'tab' => 'procedures',
]));
$this->assertSame('procedure', $this->visit->fresh()->specialty_stage);
$this->actingAs($this->owner)
->post(route('care.specialty.cardiology.procedure', $this->visit), [
'tab' => 'procedures',
'payload' => [
'procedure' => 'Cardioversion',
'indication' => 'AF with RVR',
'outcome' => 'Completed uneventfully',
'post_procedure_plan' => 'Monitor 4 hours; continue anticoagulation',
],
])
->assertRedirect(route('care.specialty.workspace', [
'module' => 'cardiology',
'visit' => $this->visit,
'tab' => 'procedures',
]));
$this->assertSame('completed', $this->visit->fresh()->specialty_stage);
$this->assertSame(Visit::STATUS_COMPLETED, $this->visit->fresh()->status);
$this->assertDatabaseHas('care_specialty_clinical_records', [
'visit_id' => $this->visit->id,
'record_type' => 'cardio_procedure',
'status' => SpecialtyClinicalRecord::STATUS_COMPLETED,
]);
}
public function test_reports_and_print(): void
{
$this->actingAs($this->owner)
->get(route('care.specialty.cardiology.reports'))
->assertOk()
->assertSee('Cardiology reports')
->assertSee('Arrivals today');
$this->actingAs($this->owner)
->get(route('care.specialty.cardiology.print', $this->visit))
->assertOk()
->assertSee('Cardiology summary')
->assertSee($this->patient->fullName());
}
public function test_list_index_does_not_auto_open_patient(): void
{
$this->actingAs($this->owner)
->get(route('care.specialty.show', 'cardiology'))
->assertOk()
->assertDontSee('Cardiology overview');
}
}
+237
View File
@@ -0,0 +1,237 @@
<?php
namespace Tests\Feature;
use App\Http\Middleware\EnsurePlatformSession;
use App\Models\Appointment;
use App\Models\Branch;
use App\Models\Department;
use App\Models\Member;
use App\Models\Organization;
use App\Models\Patient;
use App\Models\SpecialtyClinicalRecord;
use App\Models\User;
use App\Models\Visit;
use App\Services\Care\SpecialtyModuleService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class CarePsychiatrySuiteTest extends TestCase
{
use RefreshDatabase;
protected User $owner;
protected Organization $organization;
protected Branch $branch;
protected Patient $patient;
protected Visit $visit;
protected function setUp(): void
{
parent::setUp();
$this->withoutMiddleware(EnsurePlatformSession::class);
$this->owner = User::create([
'public_id' => 'psy-owner',
'name' => 'Owner',
'email' => 'psy-owner@example.com',
]);
$this->organization = Organization::create([
'owner_ref' => $this->owner->public_id,
'name' => 'Psychiatry Clinic',
'slug' => 'psychiatry-clinic',
'settings' => [
'onboarded' => true,
'facility_type' => 'clinic',
'plan' => 'pro',
'plan_expires_at' => now()->addMonth()->toIso8601String(),
'queue_integration_enabled' => true,
],
]);
Member::create([
'owner_ref' => $this->owner->public_id,
'organization_id' => $this->organization->id,
'user_ref' => $this->owner->public_id,
'role' => 'hospital_admin',
'branch_id' => null,
]);
$this->branch = Branch::create([
'owner_ref' => $this->owner->public_id,
'organization_id' => $this->organization->id,
'name' => 'Main',
'is_active' => true,
]);
app(SpecialtyModuleService::class)->activate(
$this->organization,
$this->owner->public_id,
'psychiatry',
);
$department = Department::query()
->where('branch_id', $this->branch->id)
->where('type', 'psychiatry')
->firstOrFail();
$this->patient = Patient::create([
'owner_ref' => $this->owner->public_id,
'organization_id' => $this->organization->id,
'branch_id' => $this->branch->id,
'patient_number' => 'P-PSY-SUITE',
'first_name' => 'Adwoa',
'last_name' => 'Mensah',
'gender' => 'female',
'date_of_birth' => '1988-11-02',
]);
$this->visit = Visit::create([
'owner_ref' => $this->owner->public_id,
'organization_id' => $this->organization->id,
'branch_id' => $this->branch->id,
'patient_id' => $this->patient->id,
'status' => Visit::STATUS_IN_PROGRESS,
'checked_in_at' => now(),
'specialty_stage' => 'check_in',
]);
Appointment::create([
'owner_ref' => $this->owner->public_id,
'organization_id' => $this->organization->id,
'branch_id' => $this->branch->id,
'patient_id' => $this->patient->id,
'department_id' => $department->id,
'visit_id' => $this->visit->id,
'type' => Appointment::TYPE_WALK_IN,
'status' => Appointment::STATUS_IN_CONSULTATION,
'scheduled_at' => now(),
'waiting_at' => now(),
'checked_in_at' => now(),
'started_at' => now(),
]);
}
public function test_overview_and_history_tabs_render(): void
{
$this->actingAs($this->owner)
->get(route('care.specialty.workspace', [
'module' => 'psychiatry',
'visit' => $this->visit,
'tab' => 'overview',
]))
->assertOk()
->assertSee('Psychiatry overview')
->assertSee('data-care-stage-bar', false)
->assertSee('History / MSE')
->assertSee('Start history / MSE')
->assertSee('Psychiatry reports');
$this->actingAs($this->owner)
->get(route('care.specialty.workspace', [
'module' => 'psychiatry',
'visit' => $this->visit,
'tab' => 'history',
]))
->assertOk()
->assertSee('Presenting complaint')
->assertSee('MSE summary');
}
public function test_risk_sets_stage_and_alerts(): void
{
$this->actingAs($this->owner)
->post(route('care.specialty.clinical.save', [
'module' => 'psychiatry',
'visit' => $this->visit,
]), [
'tab' => 'risk',
'payload' => [
'overall_risk' => 'High',
'self_harm' => 'Ideation',
'harm_others' => 'None identified',
'risk_summary' => 'High risk — safety planning required',
'immediate_actions' => 'Safety plan; senior review',
],
])
->assertRedirect();
$this->assertSame('risk', $this->visit->fresh()->specialty_stage);
$record = SpecialtyClinicalRecord::query()
->where('visit_id', $this->visit->id)
->where('record_type', 'risk_assessment')
->firstOrFail();
$codes = collect($record->alerts)->pluck('code')->all();
$this->assertContains('psy.risk_high', $codes);
}
public function test_stage_advance_and_followup_completes_visit(): void
{
$this->actingAs($this->owner)
->post(route('care.specialty.psychiatry.stage', $this->visit), [
'stage' => 'review',
])
->assertRedirect(route('care.specialty.workspace', [
'module' => 'psychiatry',
'visit' => $this->visit,
'tab' => 'followup',
]));
$this->assertSame('review', $this->visit->fresh()->specialty_stage);
$this->actingAs($this->owner)
->post(route('care.specialty.psychiatry.followup', $this->visit), [
'tab' => 'followup',
'payload' => [
'review_type' => 'Clinic follow-up',
'progress' => 'Mood improved; ideation resolved',
'current_risk' => 'Low',
'outcome' => 'Follow-up arranged',
'next_steps' => 'Return in 2 weeks',
],
])
->assertRedirect(route('care.specialty.workspace', [
'module' => 'psychiatry',
'visit' => $this->visit,
'tab' => 'followup',
]));
$this->assertSame('completed', $this->visit->fresh()->specialty_stage);
$this->assertSame(Visit::STATUS_COMPLETED, $this->visit->fresh()->status);
$this->assertDatabaseHas('care_specialty_clinical_records', [
'visit_id' => $this->visit->id,
'record_type' => 'psych_followup',
'status' => SpecialtyClinicalRecord::STATUS_COMPLETED,
]);
}
public function test_reports_and_print(): void
{
$this->actingAs($this->owner)
->get(route('care.specialty.psychiatry.reports'))
->assertOk()
->assertSee('Psychiatry reports')
->assertSee('Arrivals today');
$this->actingAs($this->owner)
->get(route('care.specialty.psychiatry.print', $this->visit))
->assertOk()
->assertSee('Psychiatry summary')
->assertSee($this->patient->fullName());
}
public function test_list_index_does_not_auto_open_patient(): void
{
$this->actingAs($this->owner)
->get(route('care.specialty.show', 'psychiatry'))
->assertOk()
->assertDontSee('Psychiatry overview');
}
}
+236
View File
@@ -0,0 +1,236 @@
<?php
namespace Tests\Feature;
use App\Http\Middleware\EnsurePlatformSession;
use App\Models\Appointment;
use App\Models\Branch;
use App\Models\Department;
use App\Models\Member;
use App\Models\Organization;
use App\Models\Patient;
use App\Models\SpecialtyClinicalRecord;
use App\Models\User;
use App\Models\Visit;
use App\Services\Care\SpecialtyModuleService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class CareRadiologySuiteTest extends TestCase
{
use RefreshDatabase;
protected User $owner;
protected Organization $organization;
protected Branch $branch;
protected Patient $patient;
protected Visit $visit;
protected function setUp(): void
{
parent::setUp();
$this->withoutMiddleware(EnsurePlatformSession::class);
$this->owner = User::create([
'public_id' => 'rad-owner',
'name' => 'Owner',
'email' => 'rad-owner@example.com',
]);
$this->organization = Organization::create([
'owner_ref' => $this->owner->public_id,
'name' => 'Radiology Clinic',
'slug' => 'radiology-clinic',
'settings' => [
'onboarded' => true,
'facility_type' => 'clinic',
'plan' => 'pro',
'plan_expires_at' => now()->addMonth()->toIso8601String(),
'queue_integration_enabled' => true,
],
]);
Member::create([
'owner_ref' => $this->owner->public_id,
'organization_id' => $this->organization->id,
'user_ref' => $this->owner->public_id,
'role' => 'hospital_admin',
'branch_id' => null,
]);
$this->branch = Branch::create([
'owner_ref' => $this->owner->public_id,
'organization_id' => $this->organization->id,
'name' => 'Main',
'is_active' => true,
]);
app(SpecialtyModuleService::class)->activate(
$this->organization,
$this->owner->public_id,
'radiology',
);
$department = Department::query()
->where('branch_id', $this->branch->id)
->where('type', 'radiology')
->firstOrFail();
$this->patient = Patient::create([
'owner_ref' => $this->owner->public_id,
'organization_id' => $this->organization->id,
'branch_id' => $this->branch->id,
'patient_number' => 'P-RAD-SUITE',
'first_name' => 'Ama',
'last_name' => 'Mensah',
'gender' => 'female',
'date_of_birth' => '1990-05-12',
]);
$this->visit = Visit::create([
'owner_ref' => $this->owner->public_id,
'organization_id' => $this->organization->id,
'branch_id' => $this->branch->id,
'patient_id' => $this->patient->id,
'status' => Visit::STATUS_IN_PROGRESS,
'checked_in_at' => now(),
'specialty_stage' => 'check_in',
]);
Appointment::create([
'owner_ref' => $this->owner->public_id,
'organization_id' => $this->organization->id,
'branch_id' => $this->branch->id,
'patient_id' => $this->patient->id,
'department_id' => $department->id,
'visit_id' => $this->visit->id,
'type' => Appointment::TYPE_WALK_IN,
'status' => Appointment::STATUS_IN_CONSULTATION,
'scheduled_at' => now(),
'waiting_at' => now(),
'checked_in_at' => now(),
'started_at' => now(),
]);
}
public function test_overview_and_protocol_tabs_render(): void
{
$this->actingAs($this->owner)
->get(route('care.specialty.workspace', [
'module' => 'radiology',
'visit' => $this->visit,
'tab' => 'overview',
]))
->assertOk()
->assertSee('Radiology overview')
->assertSee('data-care-stage-bar', false)
->assertSee('Check-in')
->assertSee('Start request / protocol')
->assertSee('Radiology reports');
$this->actingAs($this->owner)
->get(route('care.specialty.workspace', [
'module' => 'radiology',
'visit' => $this->visit,
'tab' => 'protocol',
]))
->assertOk()
->assertSee('Modality')
->assertSee('Body part / region');
}
public function test_request_sets_stage_and_stat_alert(): void
{
$this->actingAs($this->owner)
->post(route('care.specialty.clinical.save', [
'module' => 'radiology',
'visit' => $this->visit,
]), [
'tab' => 'protocol',
'payload' => [
'modality' => 'CT',
'body_part' => 'Chest',
'clinical_info' => 'Rule out PE',
'urgency' => 'STAT',
'contrast' => 'IV',
],
])
->assertRedirect();
$this->assertSame('protocol', $this->visit->fresh()->specialty_stage);
$record = SpecialtyClinicalRecord::query()
->where('visit_id', $this->visit->id)
->where('record_type', 'imaging_request')
->firstOrFail();
$codes = collect($record->alerts)->pluck('code')->all();
$this->assertContains('rad.stat', $codes);
}
public function test_stage_advance_and_verification_completes_visit(): void
{
$this->actingAs($this->owner)
->post(route('care.specialty.radiology.stage', $this->visit), [
'stage' => 'verified',
])
->assertRedirect(route('care.specialty.workspace', [
'module' => 'radiology',
'visit' => $this->visit,
'tab' => 'verification',
]));
$this->assertSame('verified', $this->visit->fresh()->specialty_stage);
$this->actingAs($this->owner)
->post(route('care.specialty.radiology.verification', $this->visit), [
'tab' => 'verification',
'payload' => [
'verification_status' => 'Verified / final',
'verified_by' => 'Dr. Demo Radiologist',
'critical_communicated' => false,
'notes' => 'Final report verified',
],
])
->assertRedirect(route('care.specialty.workspace', [
'module' => 'radiology',
'visit' => $this->visit,
'tab' => 'verification',
]));
$this->assertSame('completed', $this->visit->fresh()->specialty_stage);
$this->assertSame(Visit::STATUS_COMPLETED, $this->visit->fresh()->status);
$this->assertDatabaseHas('care_specialty_clinical_records', [
'visit_id' => $this->visit->id,
'record_type' => 'imaging_verification',
'status' => SpecialtyClinicalRecord::STATUS_COMPLETED,
]);
}
public function test_reports_and_print(): void
{
$this->actingAs($this->owner)
->get(route('care.specialty.radiology.reports'))
->assertOk()
->assertSee('Radiology reports')
->assertSee('Arrivals today');
$this->actingAs($this->owner)
->get(route('care.specialty.radiology.print', $this->visit))
->assertOk()
->assertSee('Radiology summary')
->assertSee($this->patient->fullName());
}
public function test_list_index_does_not_auto_open_patient(): void
{
$this->actingAs($this->owner)
->get(route('care.specialty.show', 'radiology'))
->assertOk()
->assertDontSee('Radiology overview');
}
}