Add full Oncology, Renal Care, and Surgery specialty clinical suites.
Deploy Ladill Care / deploy (push) Successful in 32s
Deploy Ladill Care / deploy (push) Successful in 32s
Match Pediatrics/ENT depth with stages, workspace tabs, clinical records, reports/print, demo seed, and suite tests. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -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\Oncology\OncologyAnalyticsService;
|
||||
use App\Services\Care\Oncology\OncologyWorkflowService;
|
||||
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 OncologyWorkspaceController extends Controller
|
||||
{
|
||||
use ScopesToAccount;
|
||||
|
||||
protected function assertOncologyAccess(Request $request, SpecialtyModuleService $modules): void
|
||||
{
|
||||
$organization = $this->organization($request);
|
||||
abort_unless($modules->memberCanAccess($organization, $this->member($request), 'oncology'), 403);
|
||||
}
|
||||
|
||||
protected function assertOncologyManage(Request $request, SpecialtyModuleService $modules): void
|
||||
{
|
||||
$organization = $this->organization($request);
|
||||
abort_unless($modules->memberCanManage($organization, $this->member($request), 'oncology'), 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->assertOncologyManage($request, $modules);
|
||||
$this->assertVisit($request, $visit);
|
||||
|
||||
$validated = $request->validate([
|
||||
'stage' => ['required', 'string', 'max:32'],
|
||||
]);
|
||||
|
||||
try {
|
||||
$stages->setStage(
|
||||
$this->organization($request),
|
||||
$visit,
|
||||
'oncology',
|
||||
$validated['stage'],
|
||||
$this->ownerRef($request),
|
||||
$this->actorRef($request),
|
||||
);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
return back()->with('error', $e->getMessage());
|
||||
}
|
||||
|
||||
return redirect()
|
||||
->route('care.specialty.workspace', [
|
||||
'module' => 'oncology',
|
||||
'visit' => $visit,
|
||||
'tab' => $shell->workspaceTabForStage('oncology', $validated['stage']),
|
||||
])
|
||||
->with('success', 'Visit stage updated.');
|
||||
}
|
||||
|
||||
public function saveTreatment(
|
||||
Request $request,
|
||||
Visit $visit,
|
||||
SpecialtyModuleService $modules,
|
||||
SpecialtyClinicalRecordService $clinical,
|
||||
SpecialtyVisitStageService $stages,
|
||||
OncologyWorkflowService $workflow,
|
||||
): RedirectResponse {
|
||||
$this->authorizeAbility($request, 'consultations.manage');
|
||||
$this->assertOncologyManage($request, $modules);
|
||||
$this->assertVisit($request, $visit);
|
||||
|
||||
$organization = $this->organization($request);
|
||||
$owner = $this->ownerRef($request);
|
||||
|
||||
$payload = (array) $request->input('payload', []);
|
||||
foreach ($clinical->fieldsFor('oncology', 'onc_treatment') as $field) {
|
||||
if (($field['type'] ?? '') === 'boolean') {
|
||||
$payload[$field['name']] = $request->boolean('payload.'.$field['name']);
|
||||
}
|
||||
}
|
||||
$request->merge(['payload' => $payload, 'tab' => 'treatment']);
|
||||
|
||||
$validated = $request->validate(array_merge([
|
||||
'tab' => ['required', 'string'],
|
||||
], $clinical->validationRules('oncology', 'onc_treatment')));
|
||||
|
||||
$record = $clinical->upsert(
|
||||
$organization,
|
||||
$visit,
|
||||
'oncology',
|
||||
'onc_treatment',
|
||||
$clinical->payloadFromRequest($validated),
|
||||
$owner,
|
||||
$owner,
|
||||
OncologyWorkflowService::STAGE_TREATMENT,
|
||||
SpecialtyClinicalRecord::STATUS_COMPLETED,
|
||||
);
|
||||
|
||||
try {
|
||||
$stages->setStage(
|
||||
$organization,
|
||||
$visit,
|
||||
'oncology',
|
||||
OncologyWorkflowService::STAGE_TREATMENT,
|
||||
$owner,
|
||||
$owner,
|
||||
);
|
||||
} catch (\InvalidArgumentException) {
|
||||
}
|
||||
|
||||
if ($workflow->shouldCompleteVisit($record->payload ?? [])) {
|
||||
try {
|
||||
$stages->setStage(
|
||||
$organization,
|
||||
$visit,
|
||||
'oncology',
|
||||
OncologyWorkflowService::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' => 'oncology', 'visit' => $visit, 'tab' => 'treatment'])
|
||||
->with('success', 'Oncology treatment saved.');
|
||||
}
|
||||
|
||||
public function reports(
|
||||
Request $request,
|
||||
SpecialtyModuleService $modules,
|
||||
SpecialtyShellService $shell,
|
||||
OncologyAnalyticsService $analytics,
|
||||
): View {
|
||||
$this->authorizeAbility($request, 'consultations.view');
|
||||
$this->assertOncologyAccess($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.oncology.reports', [
|
||||
'moduleKey' => 'oncology',
|
||||
'definition' => $modules->definition('oncology'),
|
||||
'shellNav' => $shell->navItems('oncology'),
|
||||
'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->assertOncologyAccess($request, $modules);
|
||||
$this->assertVisit($request, $visit);
|
||||
|
||||
$visit->loadMissing(['patient', 'appointment.practitioner', 'branch']);
|
||||
|
||||
return view('care.specialty.oncology.print', [
|
||||
'visit' => $visit,
|
||||
'patient' => $visit->patient,
|
||||
'history' => $clinical->findForVisit($visit, 'oncology', 'onc_history'),
|
||||
'staging' => $clinical->findForVisit($visit, 'oncology', 'onc_staging'),
|
||||
'investigation' => $clinical->findForVisit($visit, 'oncology', 'onc_investigation'),
|
||||
'plan' => $clinical->findForVisit($visit, 'oncology', 'onc_plan'),
|
||||
'treatment' => $clinical->findForVisit($visit, 'oncology', 'onc_treatment'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -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\Renal\RenalAnalyticsService;
|
||||
use App\Services\Care\Renal\RenalWorkflowService;
|
||||
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 RenalWorkspaceController extends Controller
|
||||
{
|
||||
use ScopesToAccount;
|
||||
|
||||
protected function assertRenalAccess(Request $request, SpecialtyModuleService $modules): void
|
||||
{
|
||||
$organization = $this->organization($request);
|
||||
abort_unless($modules->memberCanAccess($organization, $this->member($request), 'renal'), 403);
|
||||
}
|
||||
|
||||
protected function assertRenalManage(Request $request, SpecialtyModuleService $modules): void
|
||||
{
|
||||
$organization = $this->organization($request);
|
||||
abort_unless($modules->memberCanManage($organization, $this->member($request), 'renal'), 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->assertRenalManage($request, $modules);
|
||||
$this->assertVisit($request, $visit);
|
||||
|
||||
$validated = $request->validate([
|
||||
'stage' => ['required', 'string', 'max:32'],
|
||||
]);
|
||||
|
||||
try {
|
||||
$stages->setStage(
|
||||
$this->organization($request),
|
||||
$visit,
|
||||
'renal',
|
||||
$validated['stage'],
|
||||
$this->ownerRef($request),
|
||||
$this->actorRef($request),
|
||||
);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
return back()->with('error', $e->getMessage());
|
||||
}
|
||||
|
||||
return redirect()
|
||||
->route('care.specialty.workspace', [
|
||||
'module' => 'renal',
|
||||
'visit' => $visit,
|
||||
'tab' => $shell->workspaceTabForStage('renal', $validated['stage']),
|
||||
])
|
||||
->with('success', 'Visit stage updated.');
|
||||
}
|
||||
|
||||
public function savePlan(
|
||||
Request $request,
|
||||
Visit $visit,
|
||||
SpecialtyModuleService $modules,
|
||||
SpecialtyClinicalRecordService $clinical,
|
||||
SpecialtyVisitStageService $stages,
|
||||
RenalWorkflowService $workflow,
|
||||
): RedirectResponse {
|
||||
$this->authorizeAbility($request, 'consultations.manage');
|
||||
$this->assertRenalManage($request, $modules);
|
||||
$this->assertVisit($request, $visit);
|
||||
|
||||
$organization = $this->organization($request);
|
||||
$owner = $this->ownerRef($request);
|
||||
|
||||
$payload = (array) $request->input('payload', []);
|
||||
foreach ($clinical->fieldsFor('renal', 'renal_plan') as $field) {
|
||||
if (($field['type'] ?? '') === 'boolean') {
|
||||
$payload[$field['name']] = $request->boolean('payload.'.$field['name']);
|
||||
}
|
||||
}
|
||||
$request->merge(['payload' => $payload, 'tab' => 'plan']);
|
||||
|
||||
$validated = $request->validate(array_merge([
|
||||
'tab' => ['required', 'string'],
|
||||
], $clinical->validationRules('renal', 'renal_plan')));
|
||||
|
||||
$record = $clinical->upsert(
|
||||
$organization,
|
||||
$visit,
|
||||
'renal',
|
||||
'renal_plan',
|
||||
$clinical->payloadFromRequest($validated),
|
||||
$owner,
|
||||
$owner,
|
||||
RenalWorkflowService::STAGE_PLAN,
|
||||
SpecialtyClinicalRecord::STATUS_COMPLETED,
|
||||
);
|
||||
|
||||
try {
|
||||
$stages->setStage(
|
||||
$organization,
|
||||
$visit,
|
||||
'renal',
|
||||
RenalWorkflowService::STAGE_PLAN,
|
||||
$owner,
|
||||
$owner,
|
||||
);
|
||||
} catch (\InvalidArgumentException) {
|
||||
}
|
||||
|
||||
if ($workflow->shouldCompleteVisit($record->payload ?? [])) {
|
||||
try {
|
||||
$stages->setStage(
|
||||
$organization,
|
||||
$visit,
|
||||
'renal',
|
||||
RenalWorkflowService::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' => 'renal', 'visit' => $visit, 'tab' => 'plan'])
|
||||
->with('success', 'Renal care plan saved.');
|
||||
}
|
||||
|
||||
public function reports(
|
||||
Request $request,
|
||||
SpecialtyModuleService $modules,
|
||||
SpecialtyShellService $shell,
|
||||
RenalAnalyticsService $analytics,
|
||||
): View {
|
||||
$this->authorizeAbility($request, 'consultations.view');
|
||||
$this->assertRenalAccess($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.renal.reports', [
|
||||
'moduleKey' => 'renal',
|
||||
'definition' => $modules->definition('renal'),
|
||||
'shellNav' => $shell->navItems('renal'),
|
||||
'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->assertRenalAccess($request, $modules);
|
||||
$this->assertVisit($request, $visit);
|
||||
|
||||
$visit->loadMissing(['patient', 'appointment.practitioner', 'branch']);
|
||||
|
||||
return view('care.specialty.renal.print', [
|
||||
'visit' => $visit,
|
||||
'patient' => $visit->patient,
|
||||
'history' => $clinical->findForVisit($visit, 'renal', 'renal_history'),
|
||||
'exam' => $clinical->findForVisit($visit, 'renal', 'renal_exam'),
|
||||
'dialysis' => $clinical->findForVisit($visit, 'renal', 'renal_session'),
|
||||
'plan' => $clinical->findForVisit($visit, 'renal', 'renal_plan'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -162,6 +162,9 @@ class SpecialtyModuleController extends Controller
|
||||
'pediatrics' => 'history',
|
||||
'orthopedics' => 'history',
|
||||
'ent' => 'history',
|
||||
'oncology' => 'history',
|
||||
'renal' => 'history',
|
||||
'surgery' => 'history',
|
||||
default => (collect(array_keys($shellTabs))
|
||||
->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null)
|
||||
?? 'clinical_notes'),
|
||||
@@ -242,6 +245,9 @@ class SpecialtyModuleController extends Controller
|
||||
'pediatrics' => 'history',
|
||||
'orthopedics' => 'history',
|
||||
'ent' => 'history',
|
||||
'oncology' => 'history',
|
||||
'renal' => 'history',
|
||||
'surgery' => 'history',
|
||||
default => (collect(array_keys($shellTabs))
|
||||
->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null)
|
||||
?? 'clinical_notes'),
|
||||
@@ -806,6 +812,109 @@ class SpecialtyModuleController extends Controller
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if ($module === 'oncology' && in_array($recordType, ['onc_history', 'onc_staging', 'onc_investigation', 'onc_plan'], true)) {
|
||||
$workflow = app(\App\Services\Care\Oncology\OncologyWorkflowService::class);
|
||||
$stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
|
||||
$suggested = match ($recordType) {
|
||||
'onc_history' => $workflow->stageFromHistory($record->payload ?? []),
|
||||
'onc_staging' => $workflow->stageFromStaging($record->payload ?? []),
|
||||
'onc_investigation' => $workflow->stageFromInvestigation($record->payload ?? []),
|
||||
'onc_plan' => $workflow->stageFromPlan($record->payload ?? []),
|
||||
default => null,
|
||||
};
|
||||
$current = $visit->specialty_stage;
|
||||
$early = ['check_in', 'waiting', null, ''];
|
||||
$order = [
|
||||
'check_in' => 0,
|
||||
'history' => 1,
|
||||
'staging' => 2,
|
||||
'investigation' => 3,
|
||||
'plan' => 4,
|
||||
'treatment' => 5,
|
||||
'completed' => 6,
|
||||
];
|
||||
if ($suggested && (! $current || in_array($current, $early, true))) {
|
||||
try {
|
||||
$stageService->setStage($organization, $visit, 'oncology', $suggested, $this->ownerRef($request), $this->ownerRef($request));
|
||||
} catch (\InvalidArgumentException) {
|
||||
}
|
||||
} elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
|
||||
try {
|
||||
$stageService->setStage($organization, $visit, 'oncology', $suggested, $this->ownerRef($request), $this->ownerRef($request));
|
||||
} catch (\InvalidArgumentException) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($module === 'renal' && in_array($recordType, ['renal_history', 'renal_exam', 'renal_session'], true)) {
|
||||
$workflow = app(\App\Services\Care\Renal\RenalWorkflowService::class);
|
||||
$stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
|
||||
$suggested = match ($recordType) {
|
||||
'renal_history' => $workflow->stageFromHistory($record->payload ?? []),
|
||||
'renal_exam' => $workflow->stageFromExam($record->payload ?? []),
|
||||
'renal_session' => $workflow->stageFromDialysis($record->payload ?? []),
|
||||
default => null,
|
||||
};
|
||||
$current = $visit->specialty_stage;
|
||||
$early = ['check_in', 'waiting', null, ''];
|
||||
$order = [
|
||||
'check_in' => 0,
|
||||
'history' => 1,
|
||||
'exam' => 2,
|
||||
'dialysis' => 3,
|
||||
'plan' => 4,
|
||||
'completed' => 5,
|
||||
];
|
||||
if ($suggested && (! $current || in_array($current, $early, true))) {
|
||||
try {
|
||||
$stageService->setStage($organization, $visit, 'renal', $suggested, $this->ownerRef($request), $this->ownerRef($request));
|
||||
} catch (\InvalidArgumentException) {
|
||||
}
|
||||
} elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
|
||||
try {
|
||||
$stageService->setStage($organization, $visit, 'renal', $suggested, $this->ownerRef($request), $this->ownerRef($request));
|
||||
} catch (\InvalidArgumentException) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($module === 'surgery' && in_array($recordType, ['surg_history', 'surg_exam', 'surg_investigation', 'surg_plan', 'surg_procedure'], true)) {
|
||||
$workflow = app(\App\Services\Care\Surgery\SurgeryWorkflowService::class);
|
||||
$stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
|
||||
$suggested = match ($recordType) {
|
||||
'surg_history' => $workflow->stageFromHistory($record->payload ?? []),
|
||||
'surg_exam' => $workflow->stageFromExam($record->payload ?? []),
|
||||
'surg_investigation' => $workflow->stageFromInvestigation($record->payload ?? []),
|
||||
'surg_plan' => $workflow->stageFromPlan($record->payload ?? []),
|
||||
'surg_procedure' => $workflow->stageFromProcedure($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,
|
||||
'postop' => 6,
|
||||
'completed' => 7,
|
||||
];
|
||||
if ($suggested && (! $current || in_array($current, $early, true))) {
|
||||
try {
|
||||
$stageService->setStage($organization, $visit, 'surgery', $suggested, $this->ownerRef($request), $this->ownerRef($request));
|
||||
} catch (\InvalidArgumentException) {
|
||||
}
|
||||
} elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
|
||||
try {
|
||||
$stageService->setStage($organization, $visit, 'surgery', $suggested, $this->ownerRef($request), $this->ownerRef($request));
|
||||
} catch (\InvalidArgumentException) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return redirect()
|
||||
->route('care.specialty.workspace', [
|
||||
'module' => $module,
|
||||
@@ -1262,6 +1371,27 @@ class SpecialtyModuleController extends Controller
|
||||
$entProcedure = null;
|
||||
$entStageCodes = [];
|
||||
$entStageFlow = [];
|
||||
$oncologyHistory = null;
|
||||
$oncologyStaging = null;
|
||||
$oncologyInvestigation = null;
|
||||
$oncologyPlan = null;
|
||||
$oncologyTreatment = null;
|
||||
$oncologyStageCodes = [];
|
||||
$oncologyStageFlow = [];
|
||||
$renalHistory = null;
|
||||
$renalExam = null;
|
||||
$renalDialysis = null;
|
||||
$renalPlan = null;
|
||||
$renalStageCodes = [];
|
||||
$renalStageFlow = [];
|
||||
$surgeryHistory = null;
|
||||
$surgeryExam = null;
|
||||
$surgeryInvestigation = null;
|
||||
$surgeryPlan = null;
|
||||
$surgeryProcedure = null;
|
||||
$surgeryPostop = null;
|
||||
$surgeryStageCodes = [];
|
||||
$surgeryStageFlow = [];
|
||||
$activeTab = (string) $request->query('tab', array_key_first($shell->workspaceTabs($module)) ?: 'overview');
|
||||
$clinical = app(SpecialtyClinicalRecordService::class);
|
||||
|
||||
@@ -1456,6 +1586,36 @@ class SpecialtyModuleController extends Controller
|
||||
$entStageFlow = app(\App\Services\Care\Ent\EntWorkflowService::class)->stageFlow();
|
||||
}
|
||||
|
||||
if ($module === 'oncology') {
|
||||
$oncologyHistory = $clinical->findForVisit($workspaceVisit, 'oncology', 'onc_history');
|
||||
$oncologyStaging = $clinical->findForVisit($workspaceVisit, 'oncology', 'onc_staging');
|
||||
$oncologyInvestigation = $clinical->findForVisit($workspaceVisit, 'oncology', 'onc_investigation');
|
||||
$oncologyPlan = $clinical->findForVisit($workspaceVisit, 'oncology', 'onc_plan');
|
||||
$oncologyTreatment = $clinical->findForVisit($workspaceVisit, 'oncology', 'onc_treatment');
|
||||
$oncologyStageCodes = collect($shell->stages('oncology'))->pluck('code')->all();
|
||||
$oncologyStageFlow = app(\App\Services\Care\Oncology\OncologyWorkflowService::class)->stageFlow();
|
||||
}
|
||||
|
||||
if ($module === 'renal') {
|
||||
$renalHistory = $clinical->findForVisit($workspaceVisit, 'renal', 'renal_history');
|
||||
$renalExam = $clinical->findForVisit($workspaceVisit, 'renal', 'renal_exam');
|
||||
$renalDialysis = $clinical->findForVisit($workspaceVisit, 'renal', 'renal_session');
|
||||
$renalPlan = $clinical->findForVisit($workspaceVisit, 'renal', 'renal_plan');
|
||||
$renalStageCodes = collect($shell->stages('renal'))->pluck('code')->all();
|
||||
$renalStageFlow = app(\App\Services\Care\Renal\RenalWorkflowService::class)->stageFlow();
|
||||
}
|
||||
|
||||
if ($module === 'surgery') {
|
||||
$surgeryHistory = $clinical->findForVisit($workspaceVisit, 'surgery', 'surg_history');
|
||||
$surgeryExam = $clinical->findForVisit($workspaceVisit, 'surgery', 'surg_exam');
|
||||
$surgeryInvestigation = $clinical->findForVisit($workspaceVisit, 'surgery', 'surg_investigation');
|
||||
$surgeryPlan = $clinical->findForVisit($workspaceVisit, 'surgery', 'surg_plan');
|
||||
$surgeryProcedure = $clinical->findForVisit($workspaceVisit, 'surgery', 'surg_procedure');
|
||||
$surgeryPostop = $clinical->findForVisit($workspaceVisit, 'surgery', 'surg_postop');
|
||||
$surgeryStageCodes = collect($shell->stages('surgery'))->pluck('code')->all();
|
||||
$surgeryStageFlow = app(\App\Services\Care\Surgery\SurgeryWorkflowService::class)->stageFlow();
|
||||
}
|
||||
|
||||
if ($patientHeader !== null) {
|
||||
$patientHeader['clinical_alerts'] = $clinicalAlerts;
|
||||
}
|
||||
@@ -1604,6 +1764,27 @@ class SpecialtyModuleController extends Controller
|
||||
'entProcedure' => $entProcedure,
|
||||
'entStageCodes' => $entStageCodes,
|
||||
'entStageFlow' => $entStageFlow,
|
||||
'oncologyHistory' => $oncologyHistory,
|
||||
'oncologyStaging' => $oncologyStaging,
|
||||
'oncologyInvestigation' => $oncologyInvestigation,
|
||||
'oncologyPlan' => $oncologyPlan,
|
||||
'oncologyTreatment' => $oncologyTreatment,
|
||||
'oncologyStageCodes' => $oncologyStageCodes,
|
||||
'oncologyStageFlow' => $oncologyStageFlow,
|
||||
'renalHistory' => $renalHistory,
|
||||
'renalExam' => $renalExam,
|
||||
'renalDialysis' => $renalDialysis,
|
||||
'renalPlan' => $renalPlan,
|
||||
'renalStageCodes' => $renalStageCodes,
|
||||
'renalStageFlow' => $renalStageFlow,
|
||||
'surgeryHistory' => $surgeryHistory,
|
||||
'surgeryExam' => $surgeryExam,
|
||||
'surgeryInvestigation' => $surgeryInvestigation,
|
||||
'surgeryPlan' => $surgeryPlan,
|
||||
'surgeryProcedure' => $surgeryProcedure,
|
||||
'surgeryPostop' => $surgeryPostop,
|
||||
'surgeryStageCodes' => $surgeryStageCodes,
|
||||
'surgeryStageFlow' => $surgeryStageFlow,
|
||||
'queueStubs' => $modules->queueStubsFor($organization, $module),
|
||||
'branchId' => $branchId,
|
||||
'branchLabel' => $branchLabel,
|
||||
|
||||
@@ -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\SpecialtyClinicalRecordService;
|
||||
use App\Services\Care\SpecialtyModuleService;
|
||||
use App\Services\Care\SpecialtyShellService;
|
||||
use App\Services\Care\SpecialtyVisitStageService;
|
||||
use App\Services\Care\Surgery\SurgeryAnalyticsService;
|
||||
use App\Services\Care\Surgery\SurgeryWorkflowService;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class SurgeryWorkspaceController extends Controller
|
||||
{
|
||||
use ScopesToAccount;
|
||||
|
||||
protected function assertSurgeryAccess(Request $request, SpecialtyModuleService $modules): void
|
||||
{
|
||||
$organization = $this->organization($request);
|
||||
abort_unless($modules->memberCanAccess($organization, $this->member($request), 'surgery'), 403);
|
||||
}
|
||||
|
||||
protected function assertSurgeryManage(Request $request, SpecialtyModuleService $modules): void
|
||||
{
|
||||
$organization = $this->organization($request);
|
||||
abort_unless($modules->memberCanManage($organization, $this->member($request), 'surgery'), 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->assertSurgeryManage($request, $modules);
|
||||
$this->assertVisit($request, $visit);
|
||||
|
||||
$validated = $request->validate([
|
||||
'stage' => ['required', 'string', 'max:32'],
|
||||
]);
|
||||
|
||||
try {
|
||||
$stages->setStage(
|
||||
$this->organization($request),
|
||||
$visit,
|
||||
'surgery',
|
||||
$validated['stage'],
|
||||
$this->ownerRef($request),
|
||||
$this->actorRef($request),
|
||||
);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
return back()->with('error', $e->getMessage());
|
||||
}
|
||||
|
||||
return redirect()
|
||||
->route('care.specialty.workspace', [
|
||||
'module' => 'surgery',
|
||||
'visit' => $visit,
|
||||
'tab' => $shell->workspaceTabForStage('surgery', $validated['stage']),
|
||||
])
|
||||
->with('success', 'Visit stage updated.');
|
||||
}
|
||||
|
||||
public function savePostop(
|
||||
Request $request,
|
||||
Visit $visit,
|
||||
SpecialtyModuleService $modules,
|
||||
SpecialtyClinicalRecordService $clinical,
|
||||
SpecialtyVisitStageService $stages,
|
||||
SurgeryWorkflowService $workflow,
|
||||
): RedirectResponse {
|
||||
$this->authorizeAbility($request, 'consultations.manage');
|
||||
$this->assertSurgeryManage($request, $modules);
|
||||
$this->assertVisit($request, $visit);
|
||||
|
||||
$organization = $this->organization($request);
|
||||
$owner = $this->ownerRef($request);
|
||||
|
||||
$payload = (array) $request->input('payload', []);
|
||||
foreach ($clinical->fieldsFor('surgery', 'surg_postop') as $field) {
|
||||
if (($field['type'] ?? '') === 'boolean') {
|
||||
$payload[$field['name']] = $request->boolean('payload.'.$field['name']);
|
||||
}
|
||||
}
|
||||
$request->merge(['payload' => $payload, 'tab' => 'postop']);
|
||||
|
||||
$validated = $request->validate(array_merge([
|
||||
'tab' => ['required', 'string'],
|
||||
], $clinical->validationRules('surgery', 'surg_postop')));
|
||||
|
||||
$record = $clinical->upsert(
|
||||
$organization,
|
||||
$visit,
|
||||
'surgery',
|
||||
'surg_postop',
|
||||
$clinical->payloadFromRequest($validated),
|
||||
$owner,
|
||||
$owner,
|
||||
SurgeryWorkflowService::STAGE_POSTOP,
|
||||
SpecialtyClinicalRecord::STATUS_COMPLETED,
|
||||
);
|
||||
|
||||
try {
|
||||
$stages->setStage(
|
||||
$organization,
|
||||
$visit,
|
||||
'surgery',
|
||||
SurgeryWorkflowService::STAGE_POSTOP,
|
||||
$owner,
|
||||
$owner,
|
||||
);
|
||||
} catch (\InvalidArgumentException) {
|
||||
}
|
||||
|
||||
if ($workflow->shouldCompleteVisit($record->payload ?? [])) {
|
||||
try {
|
||||
$stages->setStage(
|
||||
$organization,
|
||||
$visit,
|
||||
'surgery',
|
||||
SurgeryWorkflowService::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' => 'surgery', 'visit' => $visit, 'tab' => 'postop'])
|
||||
->with('success', 'Post-op note saved.');
|
||||
}
|
||||
|
||||
public function reports(
|
||||
Request $request,
|
||||
SpecialtyModuleService $modules,
|
||||
SpecialtyShellService $shell,
|
||||
SurgeryAnalyticsService $analytics,
|
||||
): View {
|
||||
$this->authorizeAbility($request, 'consultations.view');
|
||||
$this->assertSurgeryAccess($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.surgery.reports', [
|
||||
'moduleKey' => 'surgery',
|
||||
'definition' => $modules->definition('surgery'),
|
||||
'shellNav' => $shell->navItems('surgery'),
|
||||
'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->assertSurgeryAccess($request, $modules);
|
||||
$this->assertVisit($request, $visit);
|
||||
|
||||
$visit->loadMissing(['patient', 'appointment.practitioner', 'branch']);
|
||||
|
||||
return view('care.specialty.surgery.print', [
|
||||
'visit' => $visit,
|
||||
'patient' => $visit->patient,
|
||||
'history' => $clinical->findForVisit($visit, 'surgery', 'surg_history'),
|
||||
'exam' => $clinical->findForVisit($visit, 'surgery', 'surg_exam'),
|
||||
'investigation' => $clinical->findForVisit($visit, 'surgery', 'surg_investigation'),
|
||||
'plan' => $clinical->findForVisit($visit, 'surgery', 'surg_plan'),
|
||||
'procedure' => $clinical->findForVisit($visit, 'surgery', 'surg_procedure'),
|
||||
'postop' => $clinical->findForVisit($visit, 'surgery', 'surg_postop'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -1023,6 +1023,9 @@ class DemoTenantSeeder
|
||||
$this->seedPediatricsClinicalDemo($organization, $ownerRef);
|
||||
$this->seedOrthopedicsClinicalDemo($organization, $ownerRef);
|
||||
$this->seedEntClinicalDemo($organization, $ownerRef);
|
||||
$this->seedOncologyClinicalDemo($organization, $ownerRef);
|
||||
$this->seedRenalClinicalDemo($organization, $ownerRef);
|
||||
$this->seedSurgeryClinicalDemo($organization, $ownerRef);
|
||||
|
||||
return $count;
|
||||
}
|
||||
@@ -2222,6 +2225,226 @@ class DemoTenantSeeder
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private function seedOncologyClinicalDemo(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', 'oncology')
|
||||
->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, 'oncology', 'onc_history', [
|
||||
'history' => $highRisk
|
||||
? 'New diagnosis work-up; progressive fatigue and weight loss'
|
||||
: 'On adjuvant regimen; here for cycle review',
|
||||
'cancer_history' => $highRisk ? 'Breast mass biopsied last month' : 'Stage II breast Ca — surgery 4 months ago',
|
||||
'medications' => $highRisk ? 'Analgesia PRN' : 'Current chemo cycle medications',
|
||||
'allergies' => 'NKDA',
|
||||
'comorbidities' => $highRisk ? 'Hypertension' : 'None significant',
|
||||
'social' => 'Family support available',
|
||||
], $ownerRef, $ownerRef, 'history');
|
||||
$clinical->upsert($organization, $visit, 'oncology', 'onc_staging', [
|
||||
'diagnosis' => $highRisk ? 'Suspected metastatic breast carcinoma' : 'Breast carcinoma — adjuvant',
|
||||
'stage' => $highRisk ? 'cT4 N2 M1' : 'pT2 N1 M0',
|
||||
'histology' => 'Invasive ductal carcinoma',
|
||||
'performance_status' => $highRisk ? '3' : '1',
|
||||
'exam_findings' => $highRisk ? 'Cachexia; axillary nodes; hepatic tenderness' : 'Well; surgical scar healed',
|
||||
'sites' => $highRisk ? 'Breast, axilla, liver' : 'None residual known',
|
||||
], $ownerRef, $ownerRef, 'staging');
|
||||
if ($highRisk) {
|
||||
$clinical->upsert($organization, $visit, 'oncology', 'onc_plan', [
|
||||
'diagnosis' => 'Metastatic breast carcinoma',
|
||||
'plan' => 'Staging imaging; MDT; supportive care; consider palliative systemic therapy',
|
||||
'intent' => 'Palliative',
|
||||
'medications' => 'Analgesia; antiemetics PRN',
|
||||
'treatment_planned' => true,
|
||||
'follow_up' => 'Chemo day-care after MDT',
|
||||
'advice' => 'Return if fever or uncontrolled pain',
|
||||
], $ownerRef, $ownerRef, 'plan');
|
||||
}
|
||||
if (! $visit->specialty_stage) {
|
||||
$visit->update(['specialty_stage' => $highRisk ? 'plan' : 'staging']);
|
||||
}
|
||||
$index++;
|
||||
}
|
||||
}
|
||||
|
||||
private function seedRenalClinicalDemo(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', 'renal')
|
||||
->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, 'renal', 'renal_history', [
|
||||
'history' => $highRisk
|
||||
? 'Missed last dialysis; progressive dyspnoea and oedema'
|
||||
: 'Routine thrice-weekly haemodialysis review',
|
||||
'ckd_stage' => $highRisk ? 'CKD 5D — 2 years on HD' : 'CKD 5D — 8 months on HD',
|
||||
'access_history' => 'Left AV fistula',
|
||||
'medications' => 'EPO; phosphate binders; antihypertensives',
|
||||
'allergies' => 'NKDA',
|
||||
'comorbidities' => $highRisk ? 'Diabetes; heart failure' : 'Hypertension',
|
||||
], $ownerRef, $ownerRef, 'history');
|
||||
$clinical->upsert($organization, $visit, 'renal', 'renal_exam', [
|
||||
'chief_complaint' => $highRisk ? 'Fluid overload / missed dialysis' : 'Routine dialysis session',
|
||||
'bp' => $highRisk ? '168/98' : '132/78',
|
||||
'weight_kg' => $highRisk ? 78.5 : 65.2,
|
||||
'fluid_status' => $highRisk ? 'Overload' : 'Euvolemic',
|
||||
'access' => 'Left AVF thrills present',
|
||||
'exam_findings' => $highRisk ? 'Bilateral basal crackles; sacral oedema' : 'Chest clear; no oedema',
|
||||
'uremic_symptoms' => $highRisk ? 'Nausea; pruritus' : 'None',
|
||||
], $ownerRef, $ownerRef, 'exam');
|
||||
if ($highRisk) {
|
||||
$clinical->upsert($organization, $visit, 'renal', 'renal_session', [
|
||||
'session_type' => 'Hemodialysis',
|
||||
'pre_weight_kg' => 78.5,
|
||||
'uf_goal_l' => 3.5,
|
||||
'access' => 'Left AVF',
|
||||
'bp_pre' => '168/98',
|
||||
'labs_summary' => 'K 5.8; Cr elevated; Hb 9.1',
|
||||
'complications' => 'Hypotension mid-session anticipated',
|
||||
'notes' => 'Urgent HD for fluid overload after missed session',
|
||||
], $ownerRef, $ownerRef, 'dialysis');
|
||||
}
|
||||
if (! $visit->specialty_stage) {
|
||||
$visit->update(['specialty_stage' => $highRisk ? 'dialysis' : 'exam']);
|
||||
}
|
||||
$index++;
|
||||
}
|
||||
}
|
||||
|
||||
private function seedSurgeryClinicalDemo(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', 'surgery')
|
||||
->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, 'surgery', 'surg_history', [
|
||||
'history' => $highRisk
|
||||
? 'Right inguinal hernia with intermittent pain; electing repair'
|
||||
: 'Post-appendicectomy wound check',
|
||||
'past_surgical' => $highRisk ? 'None' : 'Laparoscopic appendicectomy 10 days ago',
|
||||
'medications' => $highRisk ? 'None' : 'Analgesia; antibiotics completed',
|
||||
'allergies' => 'NKDA',
|
||||
'comorbidities' => $highRisk ? 'Well-controlled diabetes' : 'None',
|
||||
'anaesthesia_history' => 'No prior issues',
|
||||
], $ownerRef, $ownerRef, 'history');
|
||||
$clinical->upsert($organization, $visit, 'surgery', 'surg_exam', [
|
||||
'chief_complaint' => $highRisk ? 'Inguinal hernia — pre-op' : 'Wound review',
|
||||
'exam_findings' => $highRisk
|
||||
? 'Right reducible inguinal hernia; no strangulation'
|
||||
: 'Wound clean; mild erythema; no discharge',
|
||||
'asa_class' => $highRisk ? 'II' : 'I',
|
||||
'fitness' => 'Fit for day-case anaesthesia',
|
||||
'site_marking' => $highRisk,
|
||||
], $ownerRef, $ownerRef, 'exam');
|
||||
if ($highRisk) {
|
||||
$clinical->upsert($organization, $visit, 'surgery', 'surg_plan', [
|
||||
'diagnosis' => 'Right inguinal hernia',
|
||||
'proposed_procedure' => 'Open mesh hernia repair',
|
||||
'plan' => 'Day-case repair; consent discussed including mesh risks',
|
||||
'consent_obtained' => true,
|
||||
'procedure_planned' => true,
|
||||
'follow_up' => 'Wound check 7–10 days',
|
||||
'advice' => 'NPO from midnight; bring meds list',
|
||||
], $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,163 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Care\Oncology;
|
||||
|
||||
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 OncologyAnalyticsService
|
||||
{
|
||||
public function __construct(
|
||||
protected SpecialtyShellService $shell,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* arrivals_today: int,
|
||||
* completed_today: int,
|
||||
* chemo_open: int,
|
||||
* diagnosis_breakdown: Collection,
|
||||
* regimen_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, 'oncology', $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');
|
||||
|
||||
$chemoOpen = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'oncology')
|
||||
->where('record_type', 'onc_treatment')
|
||||
->whereIn('visit_id', $openVisitIds->isEmpty() ? [0] : $openVisitIds)
|
||||
->where('status', '!=', SpecialtyClinicalRecord::STATUS_COMPLETED)
|
||||
->count();
|
||||
|
||||
$stagingRecords = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'oncology')
|
||||
->where('record_type', 'onc_staging')
|
||||
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
|
||||
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
|
||||
->get();
|
||||
|
||||
$diagnosisBreakdown = $stagingRecords
|
||||
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['diagnosis'] ?? 'Unknown'))
|
||||
->map(fn (Collection $rows, string $diagnosis) => [
|
||||
'diagnosis' => $diagnosis,
|
||||
'total' => $rows->count(),
|
||||
])
|
||||
->values()
|
||||
->sortByDesc('total')
|
||||
->values();
|
||||
|
||||
$treatmentRecords = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'oncology')
|
||||
->where('record_type', 'onc_treatment')
|
||||
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
|
||||
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
|
||||
->get();
|
||||
|
||||
$regimenBreakdown = $treatmentRecords
|
||||
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['regimen'] ?? ($r->payload['treatment'] ?? 'Unknown')))
|
||||
->map(fn (Collection $rows, string $regimen) => [
|
||||
'regimen' => $regimen,
|
||||
'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, 'oncology'))
|
||||
->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,
|
||||
'chemo_open' => $chemoOpen,
|
||||
'diagnosis_breakdown' => $diagnosisBreakdown,
|
||||
'regimen_breakdown' => $regimenBreakdown,
|
||||
'avg_los_minutes' => $avgLos,
|
||||
'revenue_by_service' => $revenueByService,
|
||||
'from' => $rangeFrom->toDateString(),
|
||||
'to' => $rangeTo->toDateString(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Care\Oncology;
|
||||
|
||||
/**
|
||||
* Map oncology clinical progress onto visit stages.
|
||||
*/
|
||||
class OncologyWorkflowService
|
||||
{
|
||||
public const STAGE_CHECK_IN = 'check_in';
|
||||
|
||||
public const STAGE_HISTORY = 'history';
|
||||
|
||||
public const STAGE_STAGING = 'staging';
|
||||
|
||||
public const STAGE_INVESTIGATION = 'investigation';
|
||||
|
||||
public const STAGE_PLAN = 'plan';
|
||||
|
||||
public const STAGE_TREATMENT = 'treatment';
|
||||
|
||||
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 stageFromStaging(array $payload): string
|
||||
{
|
||||
if (! empty($payload['diagnosis'])
|
||||
|| ! empty($payload['stage'])
|
||||
|| ! empty($payload['exam_findings'])) {
|
||||
return self::STAGE_STAGING;
|
||||
}
|
||||
|
||||
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_STAGING;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromPlan(array $payload): string
|
||||
{
|
||||
if (! empty($payload['treatment_planned'])) {
|
||||
return self::STAGE_TREATMENT;
|
||||
}
|
||||
|
||||
$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_STAGING, 'label' => 'Move to staging / exam'],
|
||||
self::STAGE_STAGING => ['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_TREATMENT, 'label' => 'Move to treatment'],
|
||||
self::STAGE_TREATMENT => ['next' => self::STAGE_COMPLETED, 'label' => 'Complete visit'],
|
||||
self::STAGE_COMPLETED => ['next' => self::STAGE_COMPLETED, 'label' => 'Completed'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Care\Renal;
|
||||
|
||||
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 RenalAnalyticsService
|
||||
{
|
||||
public function __construct(
|
||||
protected SpecialtyShellService $shell,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* arrivals_today: int,
|
||||
* completed_today: int,
|
||||
* dialysis_open: int,
|
||||
* session_breakdown: Collection,
|
||||
* diagnosis_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, 'renal', $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');
|
||||
|
||||
$dialysisOpen = Visit::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->whereIn('id', $openVisitIds->isEmpty() ? [0] : $openVisitIds)
|
||||
->where('specialty_stage', 'dialysis')
|
||||
->count();
|
||||
|
||||
$sessionRecords = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'renal')
|
||||
->where('record_type', 'renal_session')
|
||||
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
|
||||
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
|
||||
->get();
|
||||
|
||||
$sessionBreakdown = $sessionRecords
|
||||
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['session_type'] ?? 'Unknown'))
|
||||
->map(fn (Collection $rows, string $type) => [
|
||||
'session_type' => $type,
|
||||
'total' => $rows->count(),
|
||||
])
|
||||
->values()
|
||||
->sortByDesc('total')
|
||||
->values();
|
||||
|
||||
$planRecords = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'renal')
|
||||
->where('record_type', 'renal_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();
|
||||
|
||||
$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, 'renal'))
|
||||
->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,
|
||||
'dialysis_open' => $dialysisOpen,
|
||||
'session_breakdown' => $sessionBreakdown,
|
||||
'diagnosis_breakdown' => $diagnosisBreakdown,
|
||||
'avg_los_minutes' => $avgLos,
|
||||
'revenue_by_service' => $revenueByService,
|
||||
'from' => $rangeFrom->toDateString(),
|
||||
'to' => $rangeTo->toDateString(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Care\Renal;
|
||||
|
||||
/**
|
||||
* Map renal / nephrology clinical progress onto visit stages.
|
||||
*/
|
||||
class RenalWorkflowService
|
||||
{
|
||||
public const STAGE_CHECK_IN = 'check_in';
|
||||
|
||||
public const STAGE_HISTORY = 'history';
|
||||
|
||||
public const STAGE_EXAM = 'exam';
|
||||
|
||||
public const STAGE_DIALYSIS = 'dialysis';
|
||||
|
||||
public const STAGE_PLAN = 'plan';
|
||||
|
||||
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['chief_complaint'])
|
||||
|| ! empty($payload['exam_findings'])
|
||||
|| ! empty($payload['fluid_status'])) {
|
||||
return self::STAGE_EXAM;
|
||||
}
|
||||
|
||||
return self::STAGE_HISTORY;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromDialysis(array $payload): string
|
||||
{
|
||||
if (! empty($payload['session_type']) || ! empty($payload['notes'])) {
|
||||
return self::STAGE_DIALYSIS;
|
||||
}
|
||||
|
||||
return self::STAGE_EXAM;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromPlan(array $payload): string
|
||||
{
|
||||
$plan = trim((string) ($payload['plan'] ?? ''));
|
||||
if ($plan !== '') {
|
||||
return self::STAGE_PLAN;
|
||||
}
|
||||
|
||||
return self::STAGE_DIALYSIS;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function shouldCompleteVisit(array $payload): bool
|
||||
{
|
||||
$outcome = strtolower((string) ($payload['outcome'] ?? ''));
|
||||
|
||||
return str_contains($outcome, 'completed') || str_contains($outcome, 'discharged');
|
||||
}
|
||||
|
||||
/**
|
||||
* @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'],
|
||||
self::STAGE_EXAM => ['next' => self::STAGE_DIALYSIS, 'label' => 'Move to dialysis / labs'],
|
||||
self::STAGE_DIALYSIS => ['next' => self::STAGE_PLAN, 'label' => 'Move to care plan'],
|
||||
self::STAGE_PLAN => ['next' => self::STAGE_COMPLETED, 'label' => 'Complete visit'],
|
||||
self::STAGE_COMPLETED => ['next' => self::STAGE_COMPLETED, 'label' => 'Completed'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -471,6 +471,39 @@ class SpecialtyClinicalRecordService
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if ($moduleKey === 'oncology' && $recordType === 'onc_staging') {
|
||||
$ecog = (string) ($payload['performance_status'] ?? '');
|
||||
if (in_array($ecog, ['3', '4'], true)) {
|
||||
$alerts[] = [
|
||||
'code' => 'onc.ecog_high',
|
||||
'severity' => 'warning',
|
||||
'message' => 'High ECOG performance status ('.$ecog.') — review treatment fitness.',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
if ($moduleKey === 'renal' && $recordType === 'renal_exam') {
|
||||
$fluid = strtolower((string) ($payload['fluid_status'] ?? ''));
|
||||
if (str_contains($fluid, 'overload')) {
|
||||
$alerts[] = [
|
||||
'code' => 'ren.fluid_overload',
|
||||
'severity' => 'warning',
|
||||
'message' => 'Fluid overload recorded on renal exam.',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
if ($moduleKey === 'surgery' && $recordType === 'surg_plan') {
|
||||
if (empty($payload['consent_obtained']) && ! empty($payload['procedure_planned'])) {
|
||||
$alerts[] = [
|
||||
'code' => 'sur.consent_missing',
|
||||
'severity' => 'critical',
|
||||
'message' => 'Procedure planned without documented consent.',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
if ($moduleKey === 'psychiatry' && $recordType === 'risk_assessment') {
|
||||
$level = strtolower((string) ($payload['overall_risk'] ?? ''));
|
||||
if (str_contains($level, 'imminent')) {
|
||||
|
||||
@@ -20,6 +20,9 @@ use App\Services\Care\Psychiatry\PsychiatryWorkflowService;
|
||||
use App\Services\Care\Pediatrics\PediatricsWorkflowService;
|
||||
use App\Services\Care\Orthopedics\OrthopedicsWorkflowService;
|
||||
use App\Services\Care\Ent\EntWorkflowService;
|
||||
use App\Services\Care\Oncology\OncologyWorkflowService;
|
||||
use App\Services\Care\Renal\RenalWorkflowService;
|
||||
use App\Services\Care\Surgery\SurgeryWorkflowService;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
@@ -72,6 +75,9 @@ class SpecialtyShellService
|
||||
'pediatrics' => 'care.specialty.pediatrics.stage',
|
||||
'orthopedics' => 'care.specialty.orthopedics.stage',
|
||||
'ent' => 'care.specialty.ent.stage',
|
||||
'oncology' => 'care.specialty.oncology.stage',
|
||||
'renal' => 'care.specialty.renal.stage',
|
||||
'surgery' => 'care.specialty.surgery.stage',
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
@@ -95,6 +101,9 @@ class SpecialtyShellService
|
||||
'pediatrics' => app(PediatricsWorkflowService::class)->stageFlow(),
|
||||
'orthopedics' => app(OrthopedicsWorkflowService::class)->stageFlow(),
|
||||
'ent' => app(EntWorkflowService::class)->stageFlow(),
|
||||
'oncology' => app(OncologyWorkflowService::class)->stageFlow(),
|
||||
'renal' => app(RenalWorkflowService::class)->stageFlow(),
|
||||
'surgery' => app(SurgeryWorkflowService::class)->stageFlow(),
|
||||
'dentistry' => [
|
||||
'waiting' => ['next' => 'chair', 'label' => 'Seat at chair'],
|
||||
'chair' => ['next' => 'procedure', 'label' => 'Start procedure'],
|
||||
@@ -394,7 +403,7 @@ class SpecialtyShellService
|
||||
) {
|
||||
$code = (string) ($stage['code'] ?? '');
|
||||
|
||||
if (in_array($moduleKey, ['dentistry', 'emergency', 'blood_bank', 'ophthalmology', 'physiotherapy', 'maternity', 'radiology', 'cardiology', 'psychiatry', 'pediatrics', 'orthopedics', 'ent'], true) && $visitIds->isNotEmpty()) {
|
||||
if (in_array($moduleKey, ['dentistry', 'emergency', 'blood_bank', 'ophthalmology', 'physiotherapy', 'maternity', 'radiology', 'cardiology', 'psychiatry', 'pediatrics', 'orthopedics', 'ent', 'oncology', 'renal', 'surgery'], true) && $visitIds->isNotEmpty()) {
|
||||
$count = Visit::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->whereIn('id', $visitIds)
|
||||
@@ -433,6 +442,9 @@ class SpecialtyShellService
|
||||
'pediatrics' => $clinical->countOpenByType($organization, 'pediatrics', 'pediatric_exam', $branchScope),
|
||||
'orthopedics' => $clinical->countOpenByType($organization, 'orthopedics', 'ortho_exam', $branchScope),
|
||||
'ent' => $clinical->countOpenByType($organization, 'ent', 'ent_exam', $branchScope),
|
||||
'oncology' => $clinical->countOpenByType($organization, 'oncology', 'onc_staging', $branchScope),
|
||||
'renal' => $clinical->countOpenByType($organization, 'renal', 'renal_exam', $branchScope),
|
||||
'surgery' => $clinical->countOpenByType($organization, 'surgery', 'surg_exam', $branchScope),
|
||||
'dentistry' => \App\Models\DentalPlanItem::query()
|
||||
->whereHas('plan', function ($q) use ($organization, $ownerRef) {
|
||||
$q->owned($ownerRef)
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Care\Surgery;
|
||||
|
||||
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 SurgeryAnalyticsService
|
||||
{
|
||||
public function __construct(
|
||||
protected SpecialtyShellService $shell,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* arrivals_today: int,
|
||||
* completed_today: int,
|
||||
* preop_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, 'surgery', $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');
|
||||
|
||||
$preopOpen = Visit::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->whereIn('id', $openVisitIds->isEmpty() ? [0] : $openVisitIds)
|
||||
->whereIn('specialty_stage', ['history', 'exam', 'investigation', 'plan'])
|
||||
->count();
|
||||
|
||||
$planRecords = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'surgery')
|
||||
->where('record_type', 'surg_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', 'surgery')
|
||||
->where('record_type', 'surg_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, 'surgery'))
|
||||
->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,
|
||||
'preop_open' => $preopOpen,
|
||||
'diagnosis_breakdown' => $diagnosisBreakdown,
|
||||
'procedure_breakdown' => $procedureBreakdown,
|
||||
'avg_los_minutes' => $avgLos,
|
||||
'revenue_by_service' => $revenueByService,
|
||||
'from' => $rangeFrom->toDateString(),
|
||||
'to' => $rangeTo->toDateString(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Care\Surgery;
|
||||
|
||||
/**
|
||||
* Map surgical OPD / pre-op clinic progress onto visit stages.
|
||||
*/
|
||||
class SurgeryWorkflowService
|
||||
{
|
||||
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_POSTOP = 'postop';
|
||||
|
||||
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['chief_complaint']) || ! empty($payload['exam_findings'])) {
|
||||
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 stageFromProcedure(array $payload): string
|
||||
{
|
||||
if (! empty($payload['procedure']) || ! empty($payload['outcome'])) {
|
||||
return self::STAGE_PROCEDURE;
|
||||
}
|
||||
|
||||
return self::STAGE_PLAN;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function shouldCompleteVisit(array $payload): bool
|
||||
{
|
||||
$outcome = strtolower((string) ($payload['outcome'] ?? ''));
|
||||
|
||||
return str_contains($outcome, 'completed') || str_contains($outcome, 'discharged');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array{next: string, label: string}>
|
||||
*/
|
||||
public function stageFlow(): array
|
||||
{
|
||||
return [
|
||||
self::STAGE_CHECK_IN => ['next' => self::STAGE_HISTORY, 'label' => 'Start pre-op history'],
|
||||
self::STAGE_HISTORY => ['next' => self::STAGE_EXAM, 'label' => 'Move to exam'],
|
||||
self::STAGE_EXAM => ['next' => self::STAGE_INVESTIGATION, 'label' => 'Move to investigations'],
|
||||
self::STAGE_INVESTIGATION => ['next' => self::STAGE_PLAN, 'label' => 'Move to consent / plan'],
|
||||
self::STAGE_PLAN => ['next' => self::STAGE_PROCEDURE, 'label' => 'Move to procedure'],
|
||||
self::STAGE_PROCEDURE => ['next' => self::STAGE_POSTOP, 'label' => 'Move to post-op'],
|
||||
self::STAGE_POSTOP => ['next' => self::STAGE_COMPLETED, 'label' => 'Complete visit'],
|
||||
self::STAGE_COMPLETED => ['next' => self::STAGE_COMPLETED, 'label' => 'Completed'],
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user