Add full Physiotherapy and Maternity specialty clinical suites.
Deploy Ladill Care / deploy (push) Successful in 52s
Deploy Ladill Care / deploy (push) Successful in 52s
Mirror Eye Care depth with stages, workspace tabs, clinical JSON, stage Move→tab routing, reports/print, demo seeds, and suite feature tests. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,216 @@
|
||||
<?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\Maternity\MaternityAnalyticsService;
|
||||
use App\Services\Care\Maternity\MaternityWorkflowService;
|
||||
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 MaternityWorkspaceController extends Controller
|
||||
{
|
||||
use ScopesToAccount;
|
||||
|
||||
protected function assertMaternityAccess(Request $request, SpecialtyModuleService $modules): void
|
||||
{
|
||||
$organization = $this->organization($request);
|
||||
abort_unless($modules->memberCanAccess($organization, $this->member($request), 'maternity'), 403);
|
||||
}
|
||||
|
||||
protected function assertMaternityManage(Request $request, SpecialtyModuleService $modules): void
|
||||
{
|
||||
$organization = $this->organization($request);
|
||||
abort_unless($modules->memberCanManage($organization, $this->member($request), 'maternity'), 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->assertMaternityManage($request, $modules);
|
||||
$this->assertVisit($request, $visit);
|
||||
|
||||
$validated = $request->validate([
|
||||
'stage' => ['required', 'string', 'max:32'],
|
||||
]);
|
||||
|
||||
try {
|
||||
$stages->setStage(
|
||||
$this->organization($request),
|
||||
$visit,
|
||||
'maternity',
|
||||
$validated['stage'],
|
||||
$this->ownerRef($request),
|
||||
$this->actorRef($request),
|
||||
);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
return back()->with('error', $e->getMessage());
|
||||
}
|
||||
|
||||
return redirect()
|
||||
->route('care.specialty.workspace', [
|
||||
'module' => 'maternity',
|
||||
'visit' => $visit,
|
||||
'tab' => $shell->workspaceTabForStage('maternity', $validated['stage']),
|
||||
])
|
||||
->with('success', 'Visit stage updated.');
|
||||
}
|
||||
|
||||
public function savePostnatal(
|
||||
Request $request,
|
||||
Visit $visit,
|
||||
SpecialtyModuleService $modules,
|
||||
SpecialtyClinicalRecordService $clinical,
|
||||
SpecialtyVisitStageService $stages,
|
||||
MaternityWorkflowService $workflow,
|
||||
): RedirectResponse {
|
||||
$this->authorizeAbility($request, 'consultations.manage');
|
||||
$this->assertMaternityManage($request, $modules);
|
||||
$this->assertVisit($request, $visit);
|
||||
|
||||
$organization = $this->organization($request);
|
||||
$owner = $this->ownerRef($request);
|
||||
|
||||
$payload = (array) $request->input('payload', []);
|
||||
foreach ($clinical->fieldsFor('maternity', 'postnatal_note') as $field) {
|
||||
if (($field['type'] ?? '') === 'boolean') {
|
||||
$payload[$field['name']] = $request->boolean('payload.'.$field['name']);
|
||||
}
|
||||
}
|
||||
$request->merge(['payload' => $payload, 'tab' => 'postnatal']);
|
||||
|
||||
$validated = $request->validate(array_merge([
|
||||
'tab' => ['required', 'string'],
|
||||
], $clinical->validationRules('maternity', 'postnatal_note')));
|
||||
|
||||
$record = $clinical->upsert(
|
||||
$organization,
|
||||
$visit,
|
||||
'maternity',
|
||||
'postnatal_note',
|
||||
$clinical->payloadFromRequest($validated),
|
||||
$owner,
|
||||
$owner,
|
||||
MaternityWorkflowService::STAGE_POSTNATAL,
|
||||
SpecialtyClinicalRecord::STATUS_COMPLETED,
|
||||
);
|
||||
|
||||
try {
|
||||
$stages->setStage(
|
||||
$organization,
|
||||
$visit,
|
||||
'maternity',
|
||||
MaternityWorkflowService::STAGE_POSTNATAL,
|
||||
$owner,
|
||||
$owner,
|
||||
);
|
||||
} catch (\InvalidArgumentException) {
|
||||
}
|
||||
|
||||
if ($workflow->shouldCompleteVisit($record->payload ?? [])) {
|
||||
try {
|
||||
$stages->setStage(
|
||||
$organization,
|
||||
$visit,
|
||||
'maternity',
|
||||
MaternityWorkflowService::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' => 'maternity', 'visit' => $visit, 'tab' => 'postnatal'])
|
||||
->with('success', 'Delivery / postnatal note saved.');
|
||||
}
|
||||
|
||||
public function reports(
|
||||
Request $request,
|
||||
SpecialtyModuleService $modules,
|
||||
SpecialtyShellService $shell,
|
||||
MaternityAnalyticsService $analytics,
|
||||
): View {
|
||||
$this->authorizeAbility($request, 'consultations.view');
|
||||
$this->assertMaternityAccess($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.maternity.reports', [
|
||||
'moduleKey' => 'maternity',
|
||||
'definition' => $modules->definition('maternity'),
|
||||
'shellNav' => $shell->navItems('maternity'),
|
||||
'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->assertMaternityAccess($request, $modules);
|
||||
$this->assertVisit($request, $visit);
|
||||
|
||||
$visit->loadMissing(['patient', 'appointment.practitioner', 'branch']);
|
||||
|
||||
return view('care.specialty.maternity.print', [
|
||||
'visit' => $visit,
|
||||
'patient' => $visit->patient,
|
||||
'history' => $clinical->findForVisit($visit, 'maternity', 'anc_history'),
|
||||
'exam' => $clinical->findForVisit($visit, 'maternity', 'obstetric_exam'),
|
||||
'fetal' => $clinical->findForVisit($visit, 'maternity', 'fetal_notes'),
|
||||
'investigation' => $clinical->findForVisit($visit, 'maternity', 'mat_investigation'),
|
||||
'plan' => $clinical->findForVisit($visit, 'maternity', 'mat_plan'),
|
||||
'postnatal' => $clinical->findForVisit($visit, 'maternity', 'postnatal_note'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
<?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\Physiotherapy\PhysiotherapyAnalyticsService;
|
||||
use App\Services\Care\Physiotherapy\PhysiotherapyWorkflowService;
|
||||
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 PhysiotherapyWorkspaceController extends Controller
|
||||
{
|
||||
use ScopesToAccount;
|
||||
|
||||
protected function assertPhysiotherapyAccess(Request $request, SpecialtyModuleService $modules): void
|
||||
{
|
||||
$organization = $this->organization($request);
|
||||
abort_unless($modules->memberCanAccess($organization, $this->member($request), 'physiotherapy'), 403);
|
||||
}
|
||||
|
||||
protected function assertPhysiotherapyManage(Request $request, SpecialtyModuleService $modules): void
|
||||
{
|
||||
$organization = $this->organization($request);
|
||||
abort_unless($modules->memberCanManage($organization, $this->member($request), 'physiotherapy'), 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->assertPhysiotherapyManage($request, $modules);
|
||||
$this->assertVisit($request, $visit);
|
||||
|
||||
$validated = $request->validate([
|
||||
'stage' => ['required', 'string', 'max:32'],
|
||||
]);
|
||||
|
||||
try {
|
||||
$stages->setStage(
|
||||
$this->organization($request),
|
||||
$visit,
|
||||
'physiotherapy',
|
||||
$validated['stage'],
|
||||
$this->ownerRef($request),
|
||||
$this->actorRef($request),
|
||||
);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
return back()->with('error', $e->getMessage());
|
||||
}
|
||||
|
||||
return redirect()
|
||||
->route('care.specialty.workspace', [
|
||||
'module' => 'physiotherapy',
|
||||
'visit' => $visit,
|
||||
'tab' => $shell->workspaceTabForStage('physiotherapy', $validated['stage']),
|
||||
])
|
||||
->with('success', 'Visit stage updated.');
|
||||
}
|
||||
|
||||
public function saveSession(
|
||||
Request $request,
|
||||
Visit $visit,
|
||||
SpecialtyModuleService $modules,
|
||||
SpecialtyClinicalRecordService $clinical,
|
||||
SpecialtyVisitStageService $stages,
|
||||
PhysiotherapyWorkflowService $workflow,
|
||||
): RedirectResponse {
|
||||
$this->authorizeAbility($request, 'consultations.manage');
|
||||
$this->assertPhysiotherapyManage($request, $modules);
|
||||
$this->assertVisit($request, $visit);
|
||||
|
||||
$organization = $this->organization($request);
|
||||
$owner = $this->ownerRef($request);
|
||||
|
||||
$payload = (array) $request->input('payload', []);
|
||||
foreach ($clinical->fieldsFor('physiotherapy', 'pt_session') as $field) {
|
||||
if (($field['type'] ?? '') === 'boolean') {
|
||||
$payload[$field['name']] = $request->boolean('payload.'.$field['name']);
|
||||
}
|
||||
}
|
||||
$request->merge(['payload' => $payload, 'tab' => 'session']);
|
||||
|
||||
$validated = $request->validate(array_merge([
|
||||
'tab' => ['required', 'string'],
|
||||
], $clinical->validationRules('physiotherapy', 'pt_session')));
|
||||
|
||||
$record = $clinical->upsert(
|
||||
$organization,
|
||||
$visit,
|
||||
'physiotherapy',
|
||||
'pt_session',
|
||||
$clinical->payloadFromRequest($validated),
|
||||
$owner,
|
||||
$owner,
|
||||
PhysiotherapyWorkflowService::STAGE_SESSION,
|
||||
SpecialtyClinicalRecord::STATUS_COMPLETED,
|
||||
);
|
||||
|
||||
$suggested = $workflow->stageFromSession($record->payload ?? []);
|
||||
try {
|
||||
$stages->setStage($organization, $visit, 'physiotherapy', $suggested, $owner, $owner);
|
||||
} catch (\InvalidArgumentException) {
|
||||
}
|
||||
|
||||
if ($workflow->shouldCompleteVisit($record->payload ?? [])) {
|
||||
try {
|
||||
$stages->setStage(
|
||||
$organization,
|
||||
$visit,
|
||||
'physiotherapy',
|
||||
PhysiotherapyWorkflowService::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' => 'physiotherapy', 'visit' => $visit, 'tab' => 'session'])
|
||||
->with('success', 'Therapy session saved.');
|
||||
}
|
||||
|
||||
public function reports(
|
||||
Request $request,
|
||||
SpecialtyModuleService $modules,
|
||||
SpecialtyShellService $shell,
|
||||
PhysiotherapyAnalyticsService $analytics,
|
||||
): View {
|
||||
$this->authorizeAbility($request, 'consultations.view');
|
||||
$this->assertPhysiotherapyAccess($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.physiotherapy.reports', [
|
||||
'moduleKey' => 'physiotherapy',
|
||||
'definition' => $modules->definition('physiotherapy'),
|
||||
'shellNav' => $shell->navItems('physiotherapy'),
|
||||
'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->assertPhysiotherapyAccess($request, $modules);
|
||||
$this->assertVisit($request, $visit);
|
||||
|
||||
$visit->loadMissing(['patient', 'appointment.practitioner', 'branch']);
|
||||
|
||||
return view('care.specialty.physiotherapy.print', [
|
||||
'visit' => $visit,
|
||||
'patient' => $visit->patient,
|
||||
'assessment' => $clinical->findForVisit($visit, 'physiotherapy', 'pt_assessment'),
|
||||
'plan' => $clinical->findForVisit($visit, 'physiotherapy', 'pt_plan'),
|
||||
'session' => $clinical->findForVisit($visit, 'physiotherapy', 'pt_session'),
|
||||
'homeProgram' => $clinical->findForVisit($visit, 'physiotherapy', 'pt_home_program'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -154,6 +154,8 @@ class SpecialtyModuleController extends Controller
|
||||
'emergency' => 'triage',
|
||||
'blood_bank' => 'requests',
|
||||
'ophthalmology' => 'refraction',
|
||||
'physiotherapy' => 'assessment',
|
||||
'maternity' => 'history',
|
||||
default => (collect(array_keys($shellTabs))
|
||||
->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null)
|
||||
?? 'clinical_notes'),
|
||||
@@ -226,6 +228,8 @@ class SpecialtyModuleController extends Controller
|
||||
'emergency' => 'triage',
|
||||
'blood_bank' => 'requests',
|
||||
'ophthalmology' => 'refraction',
|
||||
'physiotherapy' => 'assessment',
|
||||
'maternity' => 'history',
|
||||
default => (collect(array_keys($shellTabs))
|
||||
->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null)
|
||||
?? 'clinical_notes'),
|
||||
@@ -409,6 +413,103 @@ class SpecialtyModuleController extends Controller
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if ($module === 'physiotherapy' && in_array($recordType, ['pt_assessment', 'pt_plan', 'pt_session', 'pt_home_program'], true)) {
|
||||
$workflow = app(\App\Services\Care\Physiotherapy\PhysiotherapyWorkflowService::class);
|
||||
$stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
|
||||
$suggested = match ($recordType) {
|
||||
'pt_assessment' => $workflow->stageFromAssessment($record->payload ?? []),
|
||||
'pt_plan' => $workflow->stageFromPlan($record->payload ?? []),
|
||||
'pt_session' => $workflow->stageFromSession($record->payload ?? []),
|
||||
'pt_home_program' => $workflow->stageFromHomeProgram($record->payload ?? []),
|
||||
default => null,
|
||||
};
|
||||
$current = $visit->specialty_stage;
|
||||
$early = ['check_in', 'waiting', null, ''];
|
||||
$order = [
|
||||
'check_in' => 0,
|
||||
'assessment' => 1,
|
||||
'treatment_plan' => 2,
|
||||
'session' => 3,
|
||||
'progress' => 4,
|
||||
'completed' => 5,
|
||||
];
|
||||
if ($suggested && (! $current || in_array($current, $early, true))) {
|
||||
try {
|
||||
$stageService->setStage(
|
||||
$organization,
|
||||
$visit,
|
||||
'physiotherapy',
|
||||
$suggested,
|
||||
$this->ownerRef($request),
|
||||
$this->ownerRef($request),
|
||||
);
|
||||
} catch (\InvalidArgumentException) {
|
||||
}
|
||||
} elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
|
||||
try {
|
||||
$stageService->setStage(
|
||||
$organization,
|
||||
$visit,
|
||||
'physiotherapy',
|
||||
$suggested,
|
||||
$this->ownerRef($request),
|
||||
$this->ownerRef($request),
|
||||
);
|
||||
} catch (\InvalidArgumentException) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($module === 'maternity' && in_array($recordType, ['anc_history', 'obstetric_exam', 'fetal_notes', 'mat_investigation', 'mat_plan'], true)) {
|
||||
$workflow = app(\App\Services\Care\Maternity\MaternityWorkflowService::class);
|
||||
$stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
|
||||
$suggested = match ($recordType) {
|
||||
'anc_history' => $workflow->stageFromHistory($record->payload ?? []),
|
||||
'obstetric_exam' => $workflow->stageFromExam($record->payload ?? []),
|
||||
'fetal_notes' => $workflow->stageFromFetal($record->payload ?? []),
|
||||
'mat_investigation' => \App\Services\Care\Maternity\MaternityWorkflowService::STAGE_INVESTIGATION,
|
||||
'mat_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,
|
||||
'postnatal' => 5,
|
||||
'completed' => 6,
|
||||
];
|
||||
if ($suggested && (! $current || in_array($current, $early, true))) {
|
||||
try {
|
||||
$stageService->setStage(
|
||||
$organization,
|
||||
$visit,
|
||||
'maternity',
|
||||
$suggested,
|
||||
$this->ownerRef($request),
|
||||
$this->ownerRef($request),
|
||||
);
|
||||
} catch (\InvalidArgumentException) {
|
||||
}
|
||||
} elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
|
||||
try {
|
||||
$stageService->setStage(
|
||||
$organization,
|
||||
$visit,
|
||||
'maternity',
|
||||
$suggested,
|
||||
$this->ownerRef($request),
|
||||
$this->ownerRef($request),
|
||||
);
|
||||
} catch (\InvalidArgumentException) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return redirect()
|
||||
->route('care.specialty.workspace', [
|
||||
'module' => $module,
|
||||
@@ -809,6 +910,20 @@ class SpecialtyModuleController extends Controller
|
||||
$ophthalmologyProcedure = null;
|
||||
$ophthalmologyStageCodes = [];
|
||||
$ophthalmologyStageFlow = [];
|
||||
$physiotherapyAssessment = null;
|
||||
$physiotherapyPlan = null;
|
||||
$physiotherapySession = null;
|
||||
$physiotherapyHomeProgram = null;
|
||||
$physiotherapyStageCodes = [];
|
||||
$physiotherapyStageFlow = [];
|
||||
$maternityHistory = null;
|
||||
$maternityExam = null;
|
||||
$maternityFetal = null;
|
||||
$maternityInvestigation = null;
|
||||
$maternityPlan = null;
|
||||
$maternityPostnatal = null;
|
||||
$maternityStageCodes = [];
|
||||
$maternityStageFlow = [];
|
||||
$activeTab = (string) $request->query('tab', array_key_first($shell->workspaceTabs($module)) ?: 'overview');
|
||||
$clinical = app(SpecialtyClinicalRecordService::class);
|
||||
|
||||
@@ -925,6 +1040,26 @@ class SpecialtyModuleController extends Controller
|
||||
$ophthalmologyStageFlow = app(\App\Services\Care\Ophthalmology\OphthalmologyWorkflowService::class)->stageFlow();
|
||||
}
|
||||
|
||||
if ($module === 'physiotherapy') {
|
||||
$physiotherapyAssessment = $clinical->findForVisit($workspaceVisit, 'physiotherapy', 'pt_assessment');
|
||||
$physiotherapyPlan = $clinical->findForVisit($workspaceVisit, 'physiotherapy', 'pt_plan');
|
||||
$physiotherapySession = $clinical->findForVisit($workspaceVisit, 'physiotherapy', 'pt_session');
|
||||
$physiotherapyHomeProgram = $clinical->findForVisit($workspaceVisit, 'physiotherapy', 'pt_home_program');
|
||||
$physiotherapyStageCodes = collect($shell->stages('physiotherapy'))->pluck('code')->all();
|
||||
$physiotherapyStageFlow = app(\App\Services\Care\Physiotherapy\PhysiotherapyWorkflowService::class)->stageFlow();
|
||||
}
|
||||
|
||||
if ($module === 'maternity') {
|
||||
$maternityHistory = $clinical->findForVisit($workspaceVisit, 'maternity', 'anc_history');
|
||||
$maternityExam = $clinical->findForVisit($workspaceVisit, 'maternity', 'obstetric_exam');
|
||||
$maternityFetal = $clinical->findForVisit($workspaceVisit, 'maternity', 'fetal_notes');
|
||||
$maternityInvestigation = $clinical->findForVisit($workspaceVisit, 'maternity', 'mat_investigation');
|
||||
$maternityPlan = $clinical->findForVisit($workspaceVisit, 'maternity', 'mat_plan');
|
||||
$maternityPostnatal = $clinical->findForVisit($workspaceVisit, 'maternity', 'postnatal_note');
|
||||
$maternityStageCodes = collect($shell->stages('maternity'))->pluck('code')->all();
|
||||
$maternityStageFlow = app(\App\Services\Care\Maternity\MaternityWorkflowService::class)->stageFlow();
|
||||
}
|
||||
|
||||
if ($patientHeader !== null) {
|
||||
$patientHeader['clinical_alerts'] = $clinicalAlerts;
|
||||
}
|
||||
@@ -1019,6 +1154,20 @@ class SpecialtyModuleController extends Controller
|
||||
'ophthalmologyProcedure' => $ophthalmologyProcedure,
|
||||
'ophthalmologyStageCodes' => $ophthalmologyStageCodes,
|
||||
'ophthalmologyStageFlow' => $ophthalmologyStageFlow,
|
||||
'physiotherapyAssessment' => $physiotherapyAssessment,
|
||||
'physiotherapyPlan' => $physiotherapyPlan,
|
||||
'physiotherapySession' => $physiotherapySession,
|
||||
'physiotherapyHomeProgram' => $physiotherapyHomeProgram,
|
||||
'physiotherapyStageCodes' => $physiotherapyStageCodes,
|
||||
'physiotherapyStageFlow' => $physiotherapyStageFlow,
|
||||
'maternityHistory' => $maternityHistory,
|
||||
'maternityExam' => $maternityExam,
|
||||
'maternityFetal' => $maternityFetal,
|
||||
'maternityInvestigation' => $maternityInvestigation,
|
||||
'maternityPlan' => $maternityPlan,
|
||||
'maternityPostnatal' => $maternityPostnatal,
|
||||
'maternityStageCodes' => $maternityStageCodes,
|
||||
'maternityStageFlow' => $maternityStageFlow,
|
||||
'queueStubs' => $modules->queueStubsFor($organization, $module),
|
||||
'branchId' => $branchId,
|
||||
'branchLabel' => $branchLabel,
|
||||
|
||||
@@ -1015,6 +1015,8 @@ class DemoTenantSeeder
|
||||
$this->seedDentistryClinicalDemo($organization, $ownerRef);
|
||||
$this->seedBloodBankInventoryDemo($organization, $ownerRef);
|
||||
$this->seedOphthalmologyClinicalDemo($organization, $ownerRef);
|
||||
$this->seedPhysiotherapyClinicalDemo($organization, $ownerRef);
|
||||
$this->seedMaternityClinicalDemo($organization, $ownerRef);
|
||||
|
||||
return $count;
|
||||
}
|
||||
@@ -1242,6 +1244,269 @@ class DemoTenantSeeder
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Seed assessment + plan (+ optional session) on open physiotherapy visits.
|
||||
*/
|
||||
private function seedPhysiotherapyClinicalDemo(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', 'physiotherapy')
|
||||
->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;
|
||||
}
|
||||
|
||||
$highPain = $index === 0;
|
||||
$clinical->upsert(
|
||||
$organization,
|
||||
$visit,
|
||||
'physiotherapy',
|
||||
'pt_assessment',
|
||||
[
|
||||
'chief_complaint' => $highPain ? 'Severe low back pain after lifting' : 'Knee stiffness post-injury',
|
||||
'onset' => $highPain ? 'Acute — 3 days ago' : 'Subacute — 3 weeks',
|
||||
'pain_score' => $highPain ? 9 : 4,
|
||||
'body_region' => $highPain ? 'Back / lumbar' : 'Knee',
|
||||
'rom' => $highPain ? 'Lumbar flexion limited, guarded' : 'Knee flexion 90°, extension -5°',
|
||||
'strength' => $highPain ? 'Core activation poor' : 'Quadriceps 4/5',
|
||||
'special_tests' => $highPain ? 'SLR positive right' : 'McMurray negative',
|
||||
'red_flags' => $highPain ? 'Night pain; no saddle anaesthesia' : '',
|
||||
'goals' => $highPain ? 'Reduce pain and restore safe lifting' : 'Restore full ROM and return to sport',
|
||||
],
|
||||
$ownerRef,
|
||||
$ownerRef,
|
||||
'assessment',
|
||||
);
|
||||
|
||||
$clinical->upsert(
|
||||
$organization,
|
||||
$visit,
|
||||
'physiotherapy',
|
||||
'pt_plan',
|
||||
[
|
||||
'diagnosis' => $highPain ? 'Acute lumbar strain' : 'Post-traumatic knee stiffness',
|
||||
'frequency' => '2–3× / week',
|
||||
'duration_weeks' => $highPain ? 4 : 6,
|
||||
'interventions' => $highPain
|
||||
? 'Manual therapy, core activation, graded activity'
|
||||
: 'ROM drills, strengthening, proprioception',
|
||||
'precautions' => $highPain ? 'Avoid heavy flexion under load' : 'No pivoting until week 4',
|
||||
'goals' => 'Pain <3/10 and functional mobility',
|
||||
'outcome_measures' => 'VAS, Oswestry / LEFS',
|
||||
],
|
||||
$ownerRef,
|
||||
$ownerRef,
|
||||
'treatment_plan',
|
||||
);
|
||||
|
||||
if ($highPain) {
|
||||
$clinical->upsert(
|
||||
$organization,
|
||||
$visit,
|
||||
'physiotherapy',
|
||||
'pt_session',
|
||||
[
|
||||
'session_number' => 1,
|
||||
'modalities' => 'Heat, soft-tissue mobilisation',
|
||||
'exercises' => 'Pelvic tilts, bird-dog, walking',
|
||||
'pain_before' => 9,
|
||||
'pain_after' => 6,
|
||||
'response' => 'Tolerated well; pain eased post-session',
|
||||
'outcome' => 'Completed — continue plan',
|
||||
'next_review' => '2 days',
|
||||
'notes' => 'Demo physio session.',
|
||||
],
|
||||
$ownerRef,
|
||||
$ownerRef,
|
||||
'session',
|
||||
);
|
||||
}
|
||||
|
||||
if (! $visit->specialty_stage) {
|
||||
$visit->update(['specialty_stage' => $highPain ? 'session' : 'treatment_plan']);
|
||||
}
|
||||
|
||||
$index++;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Seed ANC history + exam (+ optional plan) on open maternity visits.
|
||||
*/
|
||||
private function seedMaternityClinicalDemo(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', 'maternity')
|
||||
->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,
|
||||
'maternity',
|
||||
'anc_history',
|
||||
[
|
||||
'gravida' => $highRisk ? 3 : 1,
|
||||
'para' => $highRisk ? 1 : 0,
|
||||
'lmp' => '12 Jan 2026',
|
||||
'edd' => '19 Oct 2026',
|
||||
'gestational_age_weeks' => $highRisk ? 34 : 22,
|
||||
'anc_visit_number' => $highRisk ? 6 : 3,
|
||||
'obstetric_history' => $highRisk ? 'Previous CS; one miscarriage' : 'Primigravida',
|
||||
'medical_history' => $highRisk ? 'Hypertension in pregnancy' : 'None significant',
|
||||
'allergies' => 'None known',
|
||||
'medications' => 'IFAS, calcium',
|
||||
'social_history' => 'Lives with partner; support available',
|
||||
],
|
||||
$ownerRef,
|
||||
$ownerRef,
|
||||
'history',
|
||||
);
|
||||
|
||||
$clinical->upsert(
|
||||
$organization,
|
||||
$visit,
|
||||
'maternity',
|
||||
'obstetric_exam',
|
||||
[
|
||||
'bp' => $highRisk ? '158/102' : '118/74',
|
||||
'pulse' => $highRisk ? 92 : 78,
|
||||
'weight_kg' => 72,
|
||||
'fundal_height' => $highRisk ? 33 : 22,
|
||||
'presentation' => 'Cephalic',
|
||||
'lie' => 'Longitudinal',
|
||||
'engagement' => $highRisk ? '3/5' : 'Free',
|
||||
'oedema' => $highRisk ? 'Moderate' : 'None',
|
||||
'urine' => $highRisk ? 'Protein +1' : 'NAD',
|
||||
'danger_signs' => $highRisk ? 'Headache; visual spots' : '',
|
||||
'findings' => $highRisk
|
||||
? 'Hypertension with oedema — escalate high-risk ANC'
|
||||
: 'Normal ANC examination',
|
||||
],
|
||||
$ownerRef,
|
||||
$ownerRef,
|
||||
'exam',
|
||||
);
|
||||
|
||||
$clinical->upsert(
|
||||
$organization,
|
||||
$visit,
|
||||
'maternity',
|
||||
'fetal_notes',
|
||||
[
|
||||
'fetal_heart_rate' => $highRisk ? 168 : 142,
|
||||
'fetal_movements' => $highRisk ? 'Reduced' : 'Normal',
|
||||
'presentation' => 'Cephalic',
|
||||
'liquor' => 'Adequate clinically',
|
||||
'ctg_summary' => $highRisk ? 'Baseline raised; observe' : 'Not indicated',
|
||||
'notes' => 'Demo fetal notes for maternity suite.',
|
||||
],
|
||||
$ownerRef,
|
||||
$ownerRef,
|
||||
'exam',
|
||||
);
|
||||
|
||||
if ($highRisk) {
|
||||
$clinical->upsert(
|
||||
$organization,
|
||||
$visit,
|
||||
'maternity',
|
||||
'mat_plan',
|
||||
[
|
||||
'risk_category' => 'High risk',
|
||||
'plan' => 'Urgent senior review; BP control; fetal monitoring; consider admission.',
|
||||
'medications' => 'Continue antihypertensives as prescribed',
|
||||
'education' => 'Return immediately if headache, bleeding, or reduced movements',
|
||||
'postnatal_needed' => false,
|
||||
'follow_up' => 'Same day review',
|
||||
'referral' => 'Obstetric high-risk clinic',
|
||||
],
|
||||
$ownerRef,
|
||||
$ownerRef,
|
||||
'plan',
|
||||
);
|
||||
}
|
||||
|
||||
if (! $visit->specialty_stage) {
|
||||
$visit->update(['specialty_stage' => $highRisk ? 'plan' : 'exam']);
|
||||
}
|
||||
|
||||
$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\Maternity;
|
||||
|
||||
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 MaternityAnalyticsService
|
||||
{
|
||||
public function __construct(
|
||||
protected SpecialtyShellService $shell,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* arrivals_today: int,
|
||||
* completed_today: int,
|
||||
* high_risk_open: int,
|
||||
* risk_breakdown: Collection,
|
||||
* postnatal_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, 'maternity', $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', 'maternity')
|
||||
->where('record_type', 'mat_plan')
|
||||
->whereIn('visit_id', $openVisitIds->isEmpty() ? [0] : $openVisitIds)
|
||||
->get()
|
||||
->filter(function (SpecialtyClinicalRecord $r) {
|
||||
$risk = strtolower((string) ($r->payload['risk_category'] ?? ''));
|
||||
|
||||
return str_contains($risk, 'high');
|
||||
})
|
||||
->count();
|
||||
|
||||
$planRecords = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'maternity')
|
||||
->where('record_type', 'mat_plan')
|
||||
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
|
||||
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
|
||||
->get();
|
||||
|
||||
$riskBreakdown = $planRecords
|
||||
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['risk_category'] ?? 'Unknown'))
|
||||
->map(fn (Collection $rows, string $risk) => [
|
||||
'risk' => $risk,
|
||||
'total' => $rows->count(),
|
||||
])
|
||||
->values()
|
||||
->sortByDesc('total')
|
||||
->values();
|
||||
|
||||
$postnatalRecords = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'maternity')
|
||||
->where('record_type', 'postnatal_note')
|
||||
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
|
||||
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
|
||||
->get();
|
||||
|
||||
$postnatalOutcomes = $postnatalRecords
|
||||
->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, 'maternity'))
|
||||
->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,
|
||||
'postnatal_outcomes' => $postnatalOutcomes,
|
||||
'avg_los_minutes' => $avgLos,
|
||||
'revenue_by_service' => $revenueByService,
|
||||
'from' => $rangeFrom->toDateString(),
|
||||
'to' => $rangeTo->toDateString(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Care\Maternity;
|
||||
|
||||
/**
|
||||
* Map maternity / ANC clinical progress onto visit stages.
|
||||
*/
|
||||
class MaternityWorkflowService
|
||||
{
|
||||
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_POSTNATAL = 'postnatal';
|
||||
|
||||
public const STAGE_COMPLETED = 'completed';
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromHistory(array $payload): string
|
||||
{
|
||||
if (isset($payload['gravida']) || isset($payload['gestational_age_weeks'])) {
|
||||
return self::STAGE_HISTORY;
|
||||
}
|
||||
|
||||
return self::STAGE_CHECK_IN;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromExam(array $payload): string
|
||||
{
|
||||
$findings = trim((string) ($payload['findings'] ?? ''));
|
||||
$danger = strtolower((string) ($payload['danger_signs'] ?? ''));
|
||||
|
||||
if ($findings !== '' || $danger !== '') {
|
||||
return self::STAGE_EXAM;
|
||||
}
|
||||
|
||||
return self::STAGE_HISTORY;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromFetal(array $payload): string
|
||||
{
|
||||
if (isset($payload['fetal_heart_rate']) && $payload['fetal_heart_rate'] !== '') {
|
||||
return self::STAGE_EXAM;
|
||||
}
|
||||
|
||||
return self::STAGE_EXAM;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromPlan(array $payload): string
|
||||
{
|
||||
if (! empty($payload['postnatal_needed'])) {
|
||||
return self::STAGE_POSTNATAL;
|
||||
}
|
||||
|
||||
$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, 'discharged')
|
||||
|| str_contains($outcome, 'continue anc');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array{next: string, label: string}>
|
||||
*/
|
||||
public function stageFlow(): array
|
||||
{
|
||||
return [
|
||||
self::STAGE_CHECK_IN => ['next' => self::STAGE_HISTORY, 'label' => 'Start ANC history'],
|
||||
self::STAGE_HISTORY => ['next' => self::STAGE_EXAM, 'label' => 'Move to exam / vitals'],
|
||||
self::STAGE_EXAM => ['next' => self::STAGE_INVESTIGATION, 'label' => 'Move to investigations'],
|
||||
self::STAGE_INVESTIGATION => ['next' => self::STAGE_PLAN, 'label' => 'Move to care plan'],
|
||||
self::STAGE_PLAN => ['next' => self::STAGE_POSTNATAL, 'label' => 'Move to delivery / postnatal'],
|
||||
self::STAGE_POSTNATAL => ['next' => self::STAGE_COMPLETED, 'label' => 'Complete visit'],
|
||||
self::STAGE_COMPLETED => ['next' => self::STAGE_COMPLETED, 'label' => 'Completed'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Care\Physiotherapy;
|
||||
|
||||
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 PhysiotherapyAnalyticsService
|
||||
{
|
||||
public function __construct(
|
||||
protected SpecialtyShellService $shell,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* arrivals_today: int,
|
||||
* completed_today: int,
|
||||
* high_pain_open: int,
|
||||
* diagnosis_breakdown: Collection,
|
||||
* session_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, 'physiotherapy', $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');
|
||||
|
||||
$highPainOpen = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'physiotherapy')
|
||||
->where('record_type', 'pt_assessment')
|
||||
->whereIn('visit_id', $openVisitIds->isEmpty() ? [0] : $openVisitIds)
|
||||
->get()
|
||||
->filter(fn (SpecialtyClinicalRecord $r) => (int) ($r->payload['pain_score'] ?? 0) >= 8)
|
||||
->count();
|
||||
|
||||
$planRecords = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'physiotherapy')
|
||||
->where('record_type', 'pt_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();
|
||||
|
||||
$sessionRecords = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'physiotherapy')
|
||||
->where('record_type', 'pt_session')
|
||||
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
|
||||
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
|
||||
->get();
|
||||
|
||||
$sessionOutcomes = $sessionRecords
|
||||
->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, 'physiotherapy'))
|
||||
->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_pain_open' => $highPainOpen,
|
||||
'diagnosis_breakdown' => $diagnosisBreakdown,
|
||||
'session_outcomes' => $sessionOutcomes,
|
||||
'avg_los_minutes' => $avgLos,
|
||||
'revenue_by_service' => $revenueByService,
|
||||
'from' => $rangeFrom->toDateString(),
|
||||
'to' => $rangeTo->toDateString(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Care\Physiotherapy;
|
||||
|
||||
/**
|
||||
* Map physiotherapy clinical progress onto visit stages.
|
||||
*/
|
||||
class PhysiotherapyWorkflowService
|
||||
{
|
||||
public const STAGE_CHECK_IN = 'check_in';
|
||||
|
||||
public const STAGE_ASSESSMENT = 'assessment';
|
||||
|
||||
public const STAGE_TREATMENT_PLAN = 'treatment_plan';
|
||||
|
||||
public const STAGE_SESSION = 'session';
|
||||
|
||||
public const STAGE_PROGRESS = 'progress';
|
||||
|
||||
public const STAGE_COMPLETED = 'completed';
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromAssessment(array $payload): string
|
||||
{
|
||||
$complaint = trim((string) ($payload['chief_complaint'] ?? ''));
|
||||
$goals = trim((string) ($payload['goals'] ?? ''));
|
||||
|
||||
if ($complaint !== '' || $goals !== '') {
|
||||
return self::STAGE_ASSESSMENT;
|
||||
}
|
||||
|
||||
return self::STAGE_CHECK_IN;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromPlan(array $payload): string
|
||||
{
|
||||
$diagnosis = trim((string) ($payload['diagnosis'] ?? ''));
|
||||
$interventions = trim((string) ($payload['interventions'] ?? ''));
|
||||
|
||||
if ($diagnosis !== '' || $interventions !== '') {
|
||||
return self::STAGE_TREATMENT_PLAN;
|
||||
}
|
||||
|
||||
return self::STAGE_ASSESSMENT;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromSession(array $payload): string
|
||||
{
|
||||
$outcome = strtolower((string) ($payload['outcome'] ?? ''));
|
||||
|
||||
if (str_contains($outcome, 'progress review') || str_contains($outcome, 'discharge')) {
|
||||
return self::STAGE_PROGRESS;
|
||||
}
|
||||
|
||||
if (str_contains($outcome, 'completed') || trim((string) ($payload['modalities'] ?? '')) !== '') {
|
||||
return self::STAGE_SESSION;
|
||||
}
|
||||
|
||||
return self::STAGE_TREATMENT_PLAN;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromHomeProgram(array $payload): string
|
||||
{
|
||||
$outcome = strtolower((string) ($payload['outcome'] ?? ''));
|
||||
|
||||
if (str_contains($outcome, 'discharge') || str_contains($outcome, 'goals met')) {
|
||||
return self::STAGE_PROGRESS;
|
||||
}
|
||||
|
||||
if (trim((string) ($payload['exercises'] ?? '')) !== ''
|
||||
|| trim((string) ($payload['progress_notes'] ?? '')) !== '') {
|
||||
return self::STAGE_PROGRESS;
|
||||
}
|
||||
|
||||
return self::STAGE_SESSION;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function shouldCompleteVisit(array $payload): bool
|
||||
{
|
||||
$outcome = strtolower((string) ($payload['outcome'] ?? ''));
|
||||
|
||||
return str_contains($outcome, 'discharge');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array{next: string, label: string}>
|
||||
*/
|
||||
public function stageFlow(): array
|
||||
{
|
||||
return [
|
||||
self::STAGE_CHECK_IN => ['next' => self::STAGE_ASSESSMENT, 'label' => 'Start assessment'],
|
||||
self::STAGE_ASSESSMENT => ['next' => self::STAGE_TREATMENT_PLAN, 'label' => 'Move to treatment plan'],
|
||||
self::STAGE_TREATMENT_PLAN => ['next' => self::STAGE_SESSION, 'label' => 'Move to therapy session'],
|
||||
self::STAGE_SESSION => ['next' => self::STAGE_PROGRESS, 'label' => 'Move to progress review'],
|
||||
self::STAGE_PROGRESS => ['next' => self::STAGE_COMPLETED, 'label' => 'Complete visit'],
|
||||
self::STAGE_COMPLETED => ['next' => self::STAGE_COMPLETED, 'label' => 'Completed'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -295,6 +295,84 @@ class SpecialtyClinicalRecordService
|
||||
}
|
||||
}
|
||||
|
||||
if ($moduleKey === 'physiotherapy' && $recordType === 'pt_assessment') {
|
||||
$pain = (int) ($payload['pain_score'] ?? 0);
|
||||
if ($pain >= 8) {
|
||||
$alerts[] = [
|
||||
'code' => 'pt.severe_pain',
|
||||
'severity' => 'warning',
|
||||
'message' => 'Severe pain score (≥8) on physio assessment.',
|
||||
];
|
||||
}
|
||||
$red = trim((string) ($payload['red_flags'] ?? ''));
|
||||
if ($red !== '') {
|
||||
$alerts[] = [
|
||||
'code' => 'pt.red_flags',
|
||||
'severity' => 'critical',
|
||||
'message' => 'Physio red flags recorded — review urgently.',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
if ($moduleKey === 'maternity' && $recordType === 'obstetric_exam') {
|
||||
$danger = trim((string) ($payload['danger_signs'] ?? ''));
|
||||
if ($danger !== '') {
|
||||
$alerts[] = [
|
||||
'code' => 'mat.danger_signs',
|
||||
'severity' => 'critical',
|
||||
'message' => 'Maternity danger signs flagged.',
|
||||
];
|
||||
}
|
||||
$bp = (string) ($payload['bp'] ?? '');
|
||||
if (preg_match('/(\d{2,3})\s*[\/]\s*(\d{2,3})/', $bp, $m)) {
|
||||
$sys = (int) $m[1];
|
||||
$dia = (int) $m[2];
|
||||
if ($sys >= 160 || $dia >= 110) {
|
||||
$alerts[] = [
|
||||
'code' => 'mat.severe_hypertension',
|
||||
'severity' => 'critical',
|
||||
'message' => 'Severe hypertension on obstetric exam.',
|
||||
];
|
||||
} elseif ($sys >= 140 || $dia >= 90) {
|
||||
$alerts[] = [
|
||||
'code' => 'mat.hypertension',
|
||||
'severity' => 'warning',
|
||||
'message' => 'Elevated BP on obstetric exam.',
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($moduleKey === 'maternity' && $recordType === 'fetal_notes') {
|
||||
$fhr = isset($payload['fetal_heart_rate']) ? (int) $payload['fetal_heart_rate'] : null;
|
||||
if ($fhr !== null && ($fhr < 110 || $fhr > 160)) {
|
||||
$alerts[] = [
|
||||
'code' => 'mat.abnormal_fhr',
|
||||
'severity' => 'critical',
|
||||
'message' => 'Fetal heart rate outside 110–160 bpm.',
|
||||
];
|
||||
}
|
||||
$movements = strtolower((string) ($payload['fetal_movements'] ?? ''));
|
||||
if (str_contains($movements, 'reduced') || str_contains($movements, 'absent')) {
|
||||
$alerts[] = [
|
||||
'code' => 'mat.reduced_movements',
|
||||
'severity' => 'critical',
|
||||
'message' => 'Reduced or absent fetal movements.',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
if ($moduleKey === 'maternity' && $recordType === 'mat_plan') {
|
||||
$risk = strtolower((string) ($payload['risk_category'] ?? ''));
|
||||
if (str_contains($risk, 'high')) {
|
||||
$alerts[] = [
|
||||
'code' => 'mat.high_risk',
|
||||
'severity' => 'warning',
|
||||
'message' => 'High-risk maternity care plan.',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $alerts;
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,8 @@ use App\Models\Visit;
|
||||
use App\Services\Care\BloodBank\BloodBankWorkflowService;
|
||||
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 Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
@@ -56,6 +58,8 @@ class SpecialtyShellService
|
||||
'emergency' => 'care.specialty.emergency.stage',
|
||||
'blood_bank' => 'care.specialty.blood-bank.stage',
|
||||
'ophthalmology' => 'care.specialty.ophthalmology.stage',
|
||||
'physiotherapy' => 'care.specialty.physiotherapy.stage',
|
||||
'maternity' => 'care.specialty.maternity.stage',
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
@@ -71,6 +75,8 @@ class SpecialtyShellService
|
||||
'emergency' => app(EmergencyWorkflowService::class)->stageFlow(),
|
||||
'blood_bank' => app(BloodBankWorkflowService::class)->stageFlow(),
|
||||
'ophthalmology' => app(OphthalmologyWorkflowService::class)->stageFlow(),
|
||||
'physiotherapy' => app(PhysiotherapyWorkflowService::class)->stageFlow(),
|
||||
'maternity' => app(MaternityWorkflowService::class)->stageFlow(),
|
||||
'dentistry' => [
|
||||
'waiting' => ['next' => 'chair', 'label' => 'Seat at chair'],
|
||||
'chair' => ['next' => 'procedure', 'label' => 'Start procedure'],
|
||||
@@ -370,7 +376,7 @@ class SpecialtyShellService
|
||||
) {
|
||||
$code = (string) ($stage['code'] ?? '');
|
||||
|
||||
if (in_array($moduleKey, ['dentistry', 'emergency', 'blood_bank', 'ophthalmology'], true) && $visitIds->isNotEmpty()) {
|
||||
if (in_array($moduleKey, ['dentistry', 'emergency', 'blood_bank', 'ophthalmology', 'physiotherapy', 'maternity'], true) && $visitIds->isNotEmpty()) {
|
||||
$count = Visit::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->whereIn('id', $visitIds)
|
||||
@@ -401,6 +407,8 @@ class SpecialtyShellService
|
||||
'emergency' => $clinical->countOpenByType($organization, 'emergency', 'triage', $branchScope),
|
||||
'blood_bank' => $clinical->countOpenByType($organization, 'blood_bank', 'blood_request', $branchScope),
|
||||
'ophthalmology' => $clinical->countOpenByType($organization, 'ophthalmology', 'eye_exam', $branchScope),
|
||||
'physiotherapy' => $clinical->countOpenByType($organization, 'physiotherapy', 'pt_assessment', $branchScope),
|
||||
'maternity' => $clinical->countOpenByType($organization, 'maternity', 'anc_history', $branchScope),
|
||||
'dentistry' => \App\Models\DentalPlanItem::query()
|
||||
->whereHas('plan', function ($q) use ($organization, $ownerRef) {
|
||||
$q->owned($ownerRef)
|
||||
|
||||
@@ -104,6 +104,22 @@ class SpecialtyVisitStageService
|
||||
: ($stages[1] ?? ($stages[0] ?? null));
|
||||
}
|
||||
|
||||
if ($moduleKey === 'physiotherapy') {
|
||||
$stages = $this->allowedStages($moduleKey);
|
||||
|
||||
return in_array(\App\Services\Care\Physiotherapy\PhysiotherapyWorkflowService::STAGE_ASSESSMENT, $stages, true)
|
||||
? \App\Services\Care\Physiotherapy\PhysiotherapyWorkflowService::STAGE_ASSESSMENT
|
||||
: ($stages[1] ?? ($stages[0] ?? null));
|
||||
}
|
||||
|
||||
if ($moduleKey === 'maternity') {
|
||||
$stages = $this->allowedStages($moduleKey);
|
||||
|
||||
return in_array(\App\Services\Care\Maternity\MaternityWorkflowService::STAGE_HISTORY, $stages, true)
|
||||
? \App\Services\Care\Maternity\MaternityWorkflowService::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)) {
|
||||
|
||||
Reference in New Issue
Block a user