Add full Dermatology, Podiatry, and Fertility specialty clinical suites.
Deploy Ladill Care / deploy (push) Successful in 35s

Bring thin catalog modules to the same depth as Cardiology with stages, clinical tabs, reports/print, demo seed, and suite tests.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
isaacclad
2026-07-19 22:03:01 +00:00
co-authored by Cursor
parent 7b722c71d0
commit 8c18ecc5c9
35 changed files with 3937 additions and 39 deletions
@@ -0,0 +1,215 @@
<?php
namespace App\Http\Controllers\Care;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Http\Controllers\Controller;
use App\Models\SpecialtyClinicalRecord;
use App\Models\Visit;
use App\Services\Care\Dermatology\DermatologyAnalyticsService;
use App\Services\Care\Dermatology\DermatologyWorkflowService;
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 DermatologyWorkspaceController extends Controller
{
use ScopesToAccount;
protected function assertDermatologyAccess(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanAccess($organization, $this->member($request), 'dermatology'), 403);
}
protected function assertDermatologyManage(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanManage($organization, $this->member($request), 'dermatology'), 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->assertDermatologyManage($request, $modules);
$this->assertVisit($request, $visit);
$validated = $request->validate([
'stage' => ['required', 'string', 'max:32'],
]);
try {
$stages->setStage(
$this->organization($request),
$visit,
'dermatology',
$validated['stage'],
$this->ownerRef($request),
$this->actorRef($request),
);
} catch (\InvalidArgumentException $e) {
return back()->with('error', $e->getMessage());
}
return redirect()
->route('care.specialty.workspace', [
'module' => 'dermatology',
'visit' => $visit,
'tab' => $shell->workspaceTabForStage('dermatology', $validated['stage']),
])
->with('success', 'Visit stage updated.');
}
public function saveProcedure(
Request $request,
Visit $visit,
SpecialtyModuleService $modules,
SpecialtyClinicalRecordService $clinical,
SpecialtyVisitStageService $stages,
DermatologyWorkflowService $workflow,
): RedirectResponse {
$this->authorizeAbility($request, 'consultations.manage');
$this->assertDermatologyManage($request, $modules);
$this->assertVisit($request, $visit);
$organization = $this->organization($request);
$owner = $this->ownerRef($request);
$payload = (array) $request->input('payload', []);
foreach ($clinical->fieldsFor('dermatology', 'derm_procedure') as $field) {
if (($field['type'] ?? '') === 'boolean') {
$payload[$field['name']] = $request->boolean('payload.'.$field['name']);
}
}
$request->merge(['payload' => $payload, 'tab' => 'procedure']);
$validated = $request->validate(array_merge([
'tab' => ['required', 'string'],
], $clinical->validationRules('dermatology', 'derm_procedure')));
$record = $clinical->upsert(
$organization,
$visit,
'dermatology',
'derm_procedure',
$clinical->payloadFromRequest($validated),
$owner,
$owner,
DermatologyWorkflowService::STAGE_PROCEDURE,
SpecialtyClinicalRecord::STATUS_COMPLETED,
);
try {
$stages->setStage(
$organization,
$visit,
'dermatology',
DermatologyWorkflowService::STAGE_PROCEDURE,
$owner,
$owner,
);
} catch (\InvalidArgumentException) {
}
if ($workflow->shouldCompleteVisit($record->payload ?? [])) {
try {
$stages->setStage(
$organization,
$visit,
'dermatology',
DermatologyWorkflowService::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' => 'dermatology', 'visit' => $visit, 'tab' => 'procedure'])
->with('success', 'Procedure / treatment saved.');
}
public function reports(
Request $request,
SpecialtyModuleService $modules,
SpecialtyShellService $shell,
DermatologyAnalyticsService $analytics,
): View {
$this->authorizeAbility($request, 'consultations.view');
$this->assertDermatologyAccess($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.dermatology.reports', [
'moduleKey' => 'dermatology',
'definition' => $modules->definition('dermatology'),
'shellNav' => $shell->navItems('dermatology'),
'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->assertDermatologyAccess($request, $modules);
$this->assertVisit($request, $visit);
$visit->loadMissing(['patient', 'appointment.practitioner', 'branch']);
return view('care.specialty.dermatology.print', [
'visit' => $visit,
'patient' => $visit->patient,
'history' => $clinical->findForVisit($visit, 'dermatology', 'derm_history'),
'exam' => $clinical->findForVisit($visit, 'dermatology', 'skin_exam'),
'investigation' => $clinical->findForVisit($visit, 'dermatology', 'derm_investigation'),
'plan' => $clinical->findForVisit($visit, 'dermatology', 'derm_plan'),
'procedure' => $clinical->findForVisit($visit, 'dermatology', 'derm_procedure'),
]);
}
}
@@ -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\Fertility\FertilityAnalyticsService;
use App\Services\Care\Fertility\FertilityWorkflowService;
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 FertilityWorkspaceController extends Controller
{
use ScopesToAccount;
protected function assertFertilityAccess(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanAccess($organization, $this->member($request), 'fertility'), 403);
}
protected function assertFertilityManage(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanManage($organization, $this->member($request), 'fertility'), 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->assertFertilityManage($request, $modules);
$this->assertVisit($request, $visit);
$validated = $request->validate([
'stage' => ['required', 'string', 'max:32'],
]);
try {
$stages->setStage(
$this->organization($request),
$visit,
'fertility',
$validated['stage'],
$this->ownerRef($request),
$this->actorRef($request),
);
} catch (\InvalidArgumentException $e) {
return back()->with('error', $e->getMessage());
}
return redirect()
->route('care.specialty.workspace', [
'module' => 'fertility',
'visit' => $visit,
'tab' => $shell->workspaceTabForStage('fertility', $validated['stage']),
])
->with('success', 'Visit stage updated.');
}
public function saveCycle(
Request $request,
Visit $visit,
SpecialtyModuleService $modules,
SpecialtyClinicalRecordService $clinical,
SpecialtyVisitStageService $stages,
FertilityWorkflowService $workflow,
): RedirectResponse {
$this->authorizeAbility($request, 'consultations.manage');
$this->assertFertilityManage($request, $modules);
$this->assertVisit($request, $visit);
$organization = $this->organization($request);
$owner = $this->ownerRef($request);
$payload = (array) $request->input('payload', []);
foreach ($clinical->fieldsFor('fertility', 'fert_cycle') as $field) {
if (($field['type'] ?? '') === 'boolean') {
$payload[$field['name']] = $request->boolean('payload.'.$field['name']);
}
}
$request->merge(['payload' => $payload, 'tab' => 'cycle']);
$validated = $request->validate(array_merge([
'tab' => ['required', 'string'],
], $clinical->validationRules('fertility', 'fert_cycle')));
$record = $clinical->upsert(
$organization,
$visit,
'fertility',
'fert_cycle',
$clinical->payloadFromRequest($validated),
$owner,
$owner,
FertilityWorkflowService::STAGE_CYCLE,
SpecialtyClinicalRecord::STATUS_COMPLETED,
);
try {
$stages->setStage(
$organization,
$visit,
'fertility',
FertilityWorkflowService::STAGE_CYCLE,
$owner,
$owner,
);
} catch (\InvalidArgumentException) {
}
if ($workflow->shouldCompleteVisit($record->payload ?? [])) {
try {
$stages->setStage(
$organization,
$visit,
'fertility',
FertilityWorkflowService::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' => 'fertility', 'visit' => $visit, 'tab' => 'cycle'])
->with('success', 'Cycle / procedure note saved.');
}
public function reports(
Request $request,
SpecialtyModuleService $modules,
SpecialtyShellService $shell,
FertilityAnalyticsService $analytics,
): View {
$this->authorizeAbility($request, 'consultations.view');
$this->assertFertilityAccess($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.fertility.reports', [
'moduleKey' => 'fertility',
'definition' => $modules->definition('fertility'),
'shellNav' => $shell->navItems('fertility'),
'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->assertFertilityAccess($request, $modules);
$this->assertVisit($request, $visit);
$visit->loadMissing(['patient', 'appointment.practitioner', 'branch']);
return view('care.specialty.fertility.print', [
'visit' => $visit,
'patient' => $visit->patient,
'history' => $clinical->findForVisit($visit, 'fertility', 'fert_history'),
'exam' => $clinical->findForVisit($visit, 'fertility', 'fert_exam'),
'investigation' => $clinical->findForVisit($visit, 'fertility', 'fert_investigation'),
'plan' => $clinical->findForVisit($visit, 'fertility', 'fert_plan'),
'cycle' => $clinical->findForVisit($visit, 'fertility', 'fert_cycle'),
]);
}
}
@@ -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\Podiatry\PodiatryAnalyticsService;
use App\Services\Care\Podiatry\PodiatryWorkflowService;
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 PodiatryWorkspaceController extends Controller
{
use ScopesToAccount;
protected function assertPodiatryAccess(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanAccess($organization, $this->member($request), 'podiatry'), 403);
}
protected function assertPodiatryManage(Request $request, SpecialtyModuleService $modules): void
{
$organization = $this->organization($request);
abort_unless($modules->memberCanManage($organization, $this->member($request), 'podiatry'), 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->assertPodiatryManage($request, $modules);
$this->assertVisit($request, $visit);
$validated = $request->validate([
'stage' => ['required', 'string', 'max:32'],
]);
try {
$stages->setStage(
$this->organization($request),
$visit,
'podiatry',
$validated['stage'],
$this->ownerRef($request),
$this->actorRef($request),
);
} catch (\InvalidArgumentException $e) {
return back()->with('error', $e->getMessage());
}
return redirect()
->route('care.specialty.workspace', [
'module' => 'podiatry',
'visit' => $visit,
'tab' => $shell->workspaceTabForStage('podiatry', $validated['stage']),
])
->with('success', 'Visit stage updated.');
}
public function saveProcedure(
Request $request,
Visit $visit,
SpecialtyModuleService $modules,
SpecialtyClinicalRecordService $clinical,
SpecialtyVisitStageService $stages,
PodiatryWorkflowService $workflow,
): RedirectResponse {
$this->authorizeAbility($request, 'consultations.manage');
$this->assertPodiatryManage($request, $modules);
$this->assertVisit($request, $visit);
$organization = $this->organization($request);
$owner = $this->ownerRef($request);
$payload = (array) $request->input('payload', []);
foreach ($clinical->fieldsFor('podiatry', 'pod_procedure') as $field) {
if (($field['type'] ?? '') === 'boolean') {
$payload[$field['name']] = $request->boolean('payload.'.$field['name']);
}
}
$request->merge(['payload' => $payload, 'tab' => 'procedure']);
$validated = $request->validate(array_merge([
'tab' => ['required', 'string'],
], $clinical->validationRules('podiatry', 'pod_procedure')));
$record = $clinical->upsert(
$organization,
$visit,
'podiatry',
'pod_procedure',
$clinical->payloadFromRequest($validated),
$owner,
$owner,
PodiatryWorkflowService::STAGE_PROCEDURE,
SpecialtyClinicalRecord::STATUS_COMPLETED,
);
try {
$stages->setStage(
$organization,
$visit,
'podiatry',
PodiatryWorkflowService::STAGE_PROCEDURE,
$owner,
$owner,
);
} catch (\InvalidArgumentException) {
}
if ($workflow->shouldCompleteVisit($record->payload ?? [])) {
try {
$stages->setStage(
$organization,
$visit,
'podiatry',
PodiatryWorkflowService::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' => 'podiatry', 'visit' => $visit, 'tab' => 'procedure'])
->with('success', 'Procedure saved.');
}
public function reports(
Request $request,
SpecialtyModuleService $modules,
SpecialtyShellService $shell,
PodiatryAnalyticsService $analytics,
): View {
$this->authorizeAbility($request, 'consultations.view');
$this->assertPodiatryAccess($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.podiatry.reports', [
'moduleKey' => 'podiatry',
'definition' => $modules->definition('podiatry'),
'shellNav' => $shell->navItems('podiatry'),
'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->assertPodiatryAccess($request, $modules);
$this->assertVisit($request, $visit);
$visit->loadMissing(['patient', 'appointment.practitioner', 'branch']);
return view('care.specialty.podiatry.print', [
'visit' => $visit,
'patient' => $visit->patient,
'history' => $clinical->findForVisit($visit, 'podiatry', 'pod_history'),
'exam' => $clinical->findForVisit($visit, 'podiatry', 'foot_exam'),
'investigation' => $clinical->findForVisit($visit, 'podiatry', 'pod_investigation'),
'plan' => $clinical->findForVisit($visit, 'podiatry', 'pod_plan'),
'procedure' => $clinical->findForVisit($visit, 'podiatry', 'pod_procedure'),
]);
}
}
@@ -168,6 +168,9 @@ class SpecialtyModuleController extends Controller
'vaccination' => 'eligibility',
'pathology' => 'request',
'infusion' => 'assessment',
'dermatology' => 'history',
'podiatry' => 'history',
'fertility' => 'history',
default => (collect(array_keys($shellTabs))
->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null)
?? 'clinical_notes'),
@@ -254,6 +257,9 @@ class SpecialtyModuleController extends Controller
'vaccination' => 'eligibility',
'pathology' => 'request',
'infusion' => 'assessment',
'dermatology' => 'history',
'podiatry' => 'history',
'fertility' => 'history',
default => (collect(array_keys($shellTabs))
->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null)
?? 'clinical_notes'),
@@ -1019,6 +1025,108 @@ class SpecialtyModuleController extends Controller
}
}
if ($module === 'dermatology' && in_array($recordType, ['derm_history', 'skin_exam', 'derm_investigation', 'derm_plan'], true)) {
$workflow = app(\App\Services\Care\Dermatology\DermatologyWorkflowService::class);
$stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
$suggested = match ($recordType) {
'derm_history' => $workflow->stageFromHistory($record->payload ?? []),
'skin_exam' => $workflow->stageFromExam($record->payload ?? []),
'derm_investigation' => $workflow->stageFromInvestigation($record->payload ?? []),
'derm_plan' => $workflow->stageFromPlan($record->payload ?? []),
default => null,
};
$current = $visit->specialty_stage;
$early = ['check_in', 'waiting', null, ''];
$order = [
'check_in' => 0,
'history' => 1,
'exam' => 2,
'investigation' => 3,
'plan' => 4,
'procedure' => 5,
'completed' => 6,
];
if ($suggested && (! $current || in_array($current, $early, true))) {
try {
$stageService->setStage($organization, $visit, 'dermatology', $suggested, $this->ownerRef($request), $this->ownerRef($request));
} catch (\InvalidArgumentException) {
}
} elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
try {
$stageService->setStage($organization, $visit, 'dermatology', $suggested, $this->ownerRef($request), $this->ownerRef($request));
} catch (\InvalidArgumentException) {
}
}
}
if ($module === 'podiatry' && in_array($recordType, ['pod_history', 'foot_exam', 'pod_investigation', 'pod_plan'], true)) {
$workflow = app(\App\Services\Care\Podiatry\PodiatryWorkflowService::class);
$stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
$suggested = match ($recordType) {
'pod_history' => $workflow->stageFromHistory($record->payload ?? []),
'foot_exam' => $workflow->stageFromExam($record->payload ?? []),
'pod_investigation' => $workflow->stageFromInvestigation($record->payload ?? []),
'pod_plan' => $workflow->stageFromPlan($record->payload ?? []),
default => null,
};
$current = $visit->specialty_stage;
$early = ['check_in', 'waiting', null, ''];
$order = [
'check_in' => 0,
'history' => 1,
'exam' => 2,
'investigation' => 3,
'plan' => 4,
'procedure' => 5,
'completed' => 6,
];
if ($suggested && (! $current || in_array($current, $early, true))) {
try {
$stageService->setStage($organization, $visit, 'podiatry', $suggested, $this->ownerRef($request), $this->ownerRef($request));
} catch (\InvalidArgumentException) {
}
} elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
try {
$stageService->setStage($organization, $visit, 'podiatry', $suggested, $this->ownerRef($request), $this->ownerRef($request));
} catch (\InvalidArgumentException) {
}
}
}
if ($module === 'fertility' && in_array($recordType, ['fert_history', 'fert_exam', 'fert_investigation', 'fert_plan'], true)) {
$workflow = app(\App\Services\Care\Fertility\FertilityWorkflowService::class);
$stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
$suggested = match ($recordType) {
'fert_history' => $workflow->stageFromHistory($record->payload ?? []),
'fert_exam' => $workflow->stageFromExam($record->payload ?? []),
'fert_investigation' => $workflow->stageFromInvestigation($record->payload ?? []),
'fert_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,
'cycle' => 5,
'completed' => 6,
];
if ($suggested && (! $current || in_array($current, $early, true))) {
try {
$stageService->setStage($organization, $visit, 'fertility', $suggested, $this->ownerRef($request), $this->ownerRef($request));
} catch (\InvalidArgumentException) {
}
} elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
try {
$stageService->setStage($organization, $visit, 'fertility', $suggested, $this->ownerRef($request), $this->ownerRef($request));
} catch (\InvalidArgumentException) {
}
}
}
return redirect()
->route('care.specialty.workspace', [
'module' => $module,
@@ -1515,6 +1623,27 @@ class SpecialtyModuleController extends Controller
$infusionMonitoring = null;
$infusionStageCodes = [];
$infusionStageFlow = [];
$dermatologyHistory = null;
$dermatologyExam = null;
$dermatologyInvestigation = null;
$dermatologyPlan = null;
$dermatologyProcedure = null;
$dermatologyStageCodes = [];
$dermatologyStageFlow = [];
$podiatryHistory = null;
$podiatryExam = null;
$podiatryInvestigation = null;
$podiatryPlan = null;
$podiatryProcedure = null;
$podiatryStageCodes = [];
$podiatryStageFlow = [];
$fertilityHistory = null;
$fertilityExam = null;
$fertilityInvestigation = null;
$fertilityPlan = null;
$fertilityCycle = null;
$fertilityStageCodes = [];
$fertilityStageFlow = [];
$activeTab = (string) $request->query('tab', array_key_first($shell->workspaceTabs($module)) ?: 'overview');
$clinical = app(SpecialtyClinicalRecordService::class);
@@ -1767,6 +1896,36 @@ class SpecialtyModuleController extends Controller
$infusionStageFlow = app(\App\Services\Care\Infusion\InfusionWorkflowService::class)->stageFlow();
}
if ($module === 'dermatology') {
$dermatologyHistory = $clinical->findForVisit($workspaceVisit, 'dermatology', 'derm_history');
$dermatologyExam = $clinical->findForVisit($workspaceVisit, 'dermatology', 'skin_exam');
$dermatologyInvestigation = $clinical->findForVisit($workspaceVisit, 'dermatology', 'derm_investigation');
$dermatologyPlan = $clinical->findForVisit($workspaceVisit, 'dermatology', 'derm_plan');
$dermatologyProcedure = $clinical->findForVisit($workspaceVisit, 'dermatology', 'derm_procedure');
$dermatologyStageCodes = collect($shell->stages('dermatology'))->pluck('code')->all();
$dermatologyStageFlow = app(\App\Services\Care\Dermatology\DermatologyWorkflowService::class)->stageFlow();
}
if ($module === 'podiatry') {
$podiatryHistory = $clinical->findForVisit($workspaceVisit, 'podiatry', 'pod_history');
$podiatryExam = $clinical->findForVisit($workspaceVisit, 'podiatry', 'foot_exam');
$podiatryInvestigation = $clinical->findForVisit($workspaceVisit, 'podiatry', 'pod_investigation');
$podiatryPlan = $clinical->findForVisit($workspaceVisit, 'podiatry', 'pod_plan');
$podiatryProcedure = $clinical->findForVisit($workspaceVisit, 'podiatry', 'pod_procedure');
$podiatryStageCodes = collect($shell->stages('podiatry'))->pluck('code')->all();
$podiatryStageFlow = app(\App\Services\Care\Podiatry\PodiatryWorkflowService::class)->stageFlow();
}
if ($module === 'fertility') {
$fertilityHistory = $clinical->findForVisit($workspaceVisit, 'fertility', 'fert_history');
$fertilityExam = $clinical->findForVisit($workspaceVisit, 'fertility', 'fert_exam');
$fertilityInvestigation = $clinical->findForVisit($workspaceVisit, 'fertility', 'fert_investigation');
$fertilityPlan = $clinical->findForVisit($workspaceVisit, 'fertility', 'fert_plan');
$fertilityCycle = $clinical->findForVisit($workspaceVisit, 'fertility', 'fert_cycle');
$fertilityStageCodes = collect($shell->stages('fertility'))->pluck('code')->all();
$fertilityStageFlow = app(\App\Services\Care\Fertility\FertilityWorkflowService::class)->stageFlow();
}
if ($patientHeader !== null) {
$patientHeader['clinical_alerts'] = $clinicalAlerts;
}
@@ -1955,6 +2114,27 @@ class SpecialtyModuleController extends Controller
'infusionMonitoring' => $infusionMonitoring,
'infusionStageCodes' => $infusionStageCodes,
'infusionStageFlow' => $infusionStageFlow,
'dermatologyHistory' => $dermatologyHistory,
'dermatologyExam' => $dermatologyExam,
'dermatologyInvestigation' => $dermatologyInvestigation,
'dermatologyPlan' => $dermatologyPlan,
'dermatologyProcedure' => $dermatologyProcedure,
'dermatologyStageCodes' => $dermatologyStageCodes,
'dermatologyStageFlow' => $dermatologyStageFlow,
'podiatryHistory' => $podiatryHistory,
'podiatryExam' => $podiatryExam,
'podiatryInvestigation' => $podiatryInvestigation,
'podiatryPlan' => $podiatryPlan,
'podiatryProcedure' => $podiatryProcedure,
'podiatryStageCodes' => $podiatryStageCodes,
'podiatryStageFlow' => $podiatryStageFlow,
'fertilityHistory' => $fertilityHistory,
'fertilityExam' => $fertilityExam,
'fertilityInvestigation' => $fertilityInvestigation,
'fertilityPlan' => $fertilityPlan,
'fertilityCycle' => $fertilityCycle,
'fertilityStageCodes' => $fertilityStageCodes,
'fertilityStageFlow' => $fertilityStageFlow,
'queueStubs' => $modules->queueStubsFor($organization, $module),
'branchId' => $branchId,
'branchLabel' => $branchLabel,
+341
View File
@@ -1029,6 +1029,9 @@ class DemoTenantSeeder
$this->seedVaccinationClinicalDemo($organization, $ownerRef);
$this->seedPathologyClinicalDemo($organization, $ownerRef);
$this->seedInfusionClinicalDemo($organization, $ownerRef);
$this->seedDermatologyClinicalDemo($organization, $ownerRef);
$this->seedPodiatryClinicalDemo($organization, $ownerRef);
$this->seedFertilityClinicalDemo($organization, $ownerRef);
return $count;
}
@@ -2669,6 +2672,344 @@ class DemoTenantSeeder
}
}
private function seedDermatologyClinicalDemo(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', 'dermatology')
->where('is_active', true)
->pluck('id');
if ($departmentIds->isEmpty()) {
return;
}
$appointments = Appointment::owned($ownerRef)
->where('organization_id', $organization->id)
->whereIn('department_id', $departmentIds)
->whereIn('status', [Appointment::STATUS_WAITING, Appointment::STATUS_CHECKED_IN])
->whereNotNull('visit_id')
->with('visit')
->orderBy('branch_id')
->orderBy('id')
->get();
if ($appointments->isEmpty()) {
return;
}
$clinical = app(SpecialtyClinicalRecordService::class);
$index = 0;
foreach ($appointments as $appointment) {
$visit = $appointment->visit;
if (! $visit) {
continue;
}
$urgent = $index === 0;
$clinical->upsert(
$organization,
$visit,
'dermatology',
'derm_history',
[
'history' => $urgent
? 'Changing pigmented lesion on forearm noticed by partner'
: 'Itchy rash on elbows for 6 weeks',
'past_skin' => $urgent ? 'Prior atypical naevus excised 2018' : 'Childhood eczema',
'medications' => $urgent ? 'None' : 'Emollients PRN',
'allergies' => 'NKDA',
'triggers' => $urgent ? 'Sun exposure' : 'Dry weather; detergents',
'family_history' => $urgent ? 'Mother melanoma' : 'None relevant',
],
$ownerRef,
$ownerRef,
'history',
);
$clinical->upsert(
$organization,
$visit,
'dermatology',
'skin_exam',
[
'chief_complaint' => $urgent ? 'Changing mole' : 'Elbow rash',
'urgency' => $urgent ? 'Suspected malignancy' : 'Routine',
'duration' => $urgent ? '3 months' : '6 weeks',
'distribution' => $urgent ? 'Left forearm' : 'Bilateral elbows',
'morphology' => $urgent
? 'Asymmetric pigmented plaque with irregular border'
: 'Erythematous plaques with silvery scale',
'itch_pain' => $urgent ? 'None' : 'Moderate itch',
'dermoscopy' => $urgent ? 'Atypical pigment network' : 'Regular scale pattern',
'differential' => $urgent ? 'Melanoma vs atypical naevus' : 'Psoriasis vs eczema',
],
$ownerRef,
$ownerRef,
'exam',
);
if ($urgent) {
$clinical->upsert(
$organization,
$visit,
'dermatology',
'derm_plan',
[
'diagnosis' => 'Suspicious pigmented lesion — rule out melanoma',
'plan' => 'Excision biopsy; sun protection counselling',
'medications' => 'None pending histology',
'procedure_planned' => true,
'follow_up' => 'Histology results in 1014 days',
'advice' => 'Avoid sunburn; photograph lesion site',
],
$ownerRef,
$ownerRef,
'plan',
);
}
if (! $visit->specialty_stage) {
$visit->update(['specialty_stage' => $urgent ? 'plan' : 'exam']);
}
$index++;
}
}
private function seedPodiatryClinicalDemo(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', 'podiatry')
->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,
'podiatry',
'pod_history',
[
'history' => $highRisk
? 'Non-healing plantar ulcer for 3 weeks'
: 'Ingrown toenail with intermittent pain',
'diabetes_history' => $highRisk ? 'Type 2 DM 12 years; peripheral neuropathy' : 'No diabetes',
'medications' => $highRisk ? 'Metformin, insulin' : 'None',
'allergies' => 'NKDA',
'footwear' => $highRisk ? 'Ill-fitting sandals' : 'Closed shoes at work',
'prior_ulcers' => $highRisk ? 'Prior healed ulcer right foot 2022' : 'None',
],
$ownerRef,
$ownerRef,
'history',
);
$clinical->upsert(
$organization,
$visit,
'podiatry',
'foot_exam',
[
'chief_complaint' => $highRisk ? 'Plantar ulcer' : 'Ingrown toenail',
'side' => $highRisk ? 'Right' : 'Left',
'diabetes' => $highRisk ? 'Active ulcer' : 'N/A',
'pulses' => $highRisk ? 'Dorsalis pedis weak' : 'Present bilaterally',
'sensation' => $highRisk ? 'Reduced monofilament' : 'Intact',
'skin_nails' => $highRisk ? 'Callus surrounding ulcer' : 'Medial nail fold inflamed',
'ulcer' => $highRisk ? '2 cm plantar ulcer, clean base' : '',
'offloading' => $highRisk ? 'Felt pad interim' : 'Wide toe box advised',
],
$ownerRef,
$ownerRef,
'exam',
);
if ($highRisk) {
$clinical->upsert(
$organization,
$visit,
'podiatry',
'pod_plan',
[
'diagnosis' => 'Diabetic foot ulcer — high risk',
'plan' => 'Debridement; offloading; wound care; vascular review if needed',
'offloading' => 'Total contact cast or removable boot',
'medications' => 'Dressings; analgesia as needed',
'procedure_planned' => true,
'follow_up' => '1 week wound clinic',
'advice' => 'Daily foot check; avoid barefoot walking',
],
$ownerRef,
$ownerRef,
'plan',
);
}
if (! $visit->specialty_stage) {
$visit->update(['specialty_stage' => $highRisk ? 'plan' : 'exam']);
}
$index++;
}
}
private function seedFertilityClinicalDemo(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', 'fertility')
->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;
}
$priority = $index === 0;
$clinical->upsert(
$organization,
$visit,
'fertility',
'fert_history',
[
'history' => $priority
? 'Trying to conceive 28 months; age 38; prior miscarriage'
: 'Trying to conceive 14 months; regular cycles',
'trying_months' => $priority ? 28 : 14,
'obstetric_history' => $priority ? 'G1P0; miscarriage at 8 weeks 2024' : 'G0P0; cycles 2830 days',
'partner_notes' => $priority ? 'Partner semen analysis pending' : 'Partner well; no known issues',
'medications' => 'Folic acid',
'allergies' => 'NKDA',
],
$ownerRef,
$ownerRef,
'history',
);
$clinical->upsert(
$organization,
$visit,
'fertility',
'fert_exam',
[
'chief_complaint' => $priority ? 'Primary infertility — time-sensitive' : 'Fertility workup',
'priority' => $priority ? 'Time-sensitive' : 'Routine',
'partner_present' => true,
'cycle_day' => $priority ? 3 : 10,
'bmi' => $priority ? 27 : 23,
'exam_findings' => 'Pelvic exam unremarkable; uterus anteverted',
'notes' => $priority ? 'Discussed AMH and early referral pathway' : 'Baseline counselling given',
],
$ownerRef,
$ownerRef,
'exam',
);
if ($priority) {
$clinical->upsert(
$organization,
$visit,
'fertility',
'fert_plan',
[
'diagnosis' => 'Primary infertility — age-related priority',
'plan' => 'Complete AMH/hormones; semen analysis; pelvic scan; consider IUI counselling',
'medications' => 'Continue folic acid; ovulation induction if indicated',
'cycle_planned' => true,
'follow_up' => 'Cycle day 3 labs; review with results',
'advice' => 'Timed intercourse education; lifestyle counselling',
],
$ownerRef,
$ownerRef,
'plan',
);
}
if (! $visit->specialty_stage) {
$visit->update(['specialty_stage' => $priority ? '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\Dermatology;
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 DermatologyAnalyticsService
{
public function __construct(
protected SpecialtyShellService $shell,
) {}
/**
* @return array{
* arrivals_today: int,
* completed_today: int,
* urgent_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, 'dermatology', $ownerRef, $branchId);
$appointmentBase = Appointment::owned($ownerRef)
->where('organization_id', $organization->id)
->when($departmentIds !== [], fn ($q) => $q->whereIn('department_id', $departmentIds))
->when($departmentIds === [], fn ($q) => $q->whereRaw('1 = 0'))
->when($branchId, fn ($q) => $q->where('branch_id', $branchId));
$arrivalsToday = (clone $appointmentBase)
->where('checked_in_at', '>=', $todayStart)
->count();
$completedToday = (clone $appointmentBase)
->where('status', Appointment::STATUS_COMPLETED)
->where('completed_at', '>=', $todayStart)
->count();
$visitIds = (clone $appointmentBase)->whereNotNull('visit_id')->pluck('visit_id');
$openVisitIds = Visit::owned($ownerRef)
->where('organization_id', $organization->id)
->whereIn('id', $visitIds->isEmpty() ? [0] : $visitIds)
->whereIn('status', [Visit::STATUS_OPEN, Visit::STATUS_IN_PROGRESS])
->pluck('id');
$urgentOpen = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'dermatology')
->where('record_type', 'skin_exam')
->whereIn('visit_id', $openVisitIds->isEmpty() ? [0] : $openVisitIds)
->get()
->filter(function (SpecialtyClinicalRecord $r) {
$urgency = (string) ($r->payload['urgency'] ?? '');
return in_array($urgency, ['High', 'Suspected malignancy'], true);
})
->count();
$planRecords = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'dermatology')
->where('record_type', 'derm_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', 'dermatology')
->where('record_type', 'derm_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, 'dermatology'))
->pluck('label')
->filter()
->values()
->all();
$revenueByService = BillLineItem::query()
->where('owner_ref', $ownerRef)
->where('source_type', 'specialty_service')
->whereIn('description', $serviceLabels ?: ['__none__'])
->whereBetween('created_at', [$rangeFrom, $rangeTo])
->whereHas('bill', function ($q) use ($organization, $visitIds) {
$q->where('organization_id', $organization->id)
->whereIn('visit_id', $visitIds->isEmpty() ? [0] : $visitIds)
->whereNotIn('status', [Bill::STATUS_VOID]);
})
->selectRaw('description, count(*) as total, sum(total_minor) as amount_minor')
->groupBy('description')
->orderByDesc('amount_minor')
->get();
return [
'arrivals_today' => $arrivalsToday,
'completed_today' => $completedToday,
'urgent_open' => $urgentOpen,
'diagnosis_breakdown' => $diagnosisBreakdown,
'procedure_breakdown' => $procedureBreakdown,
'avg_los_minutes' => $avgLos,
'revenue_by_service' => $revenueByService,
'from' => $rangeFrom->toDateString(),
'to' => $rangeTo->toDateString(),
];
}
}
@@ -0,0 +1,104 @@
<?php
namespace App\Services\Care\Dermatology;
/**
* Map dermatology clinical progress onto visit stages.
*/
class DermatologyWorkflowService
{
public const STAGE_CHECK_IN = 'check_in';
public const STAGE_HISTORY = 'history';
public const STAGE_EXAM = 'exam';
public const STAGE_INVESTIGATION = 'investigation';
public const STAGE_PLAN = 'plan';
public const STAGE_PROCEDURE = 'procedure';
public const STAGE_COMPLETED = 'completed';
/**
* @param array<string, mixed> $payload
*/
public function stageFromHistory(array $payload): string
{
$history = trim((string) ($payload['history'] ?? ''));
if ($history !== '') {
return self::STAGE_HISTORY;
}
return self::STAGE_CHECK_IN;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromExam(array $payload): string
{
if (! empty($payload['morphology']) || ! empty($payload['chief_complaint'])) {
return self::STAGE_EXAM;
}
return self::STAGE_HISTORY;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromInvestigation(array $payload): string
{
$findings = trim((string) ($payload['findings'] ?? ''));
if ($findings !== '') {
return self::STAGE_INVESTIGATION;
}
return self::STAGE_EXAM;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromPlan(array $payload): string
{
if (! empty($payload['procedure_planned'])) {
return self::STAGE_PROCEDURE;
}
$plan = trim((string) ($payload['plan'] ?? ''));
if ($plan !== '') {
return self::STAGE_PLAN;
}
return self::STAGE_INVESTIGATION;
}
/**
* @param array<string, mixed> $payload
*/
public function shouldCompleteVisit(array $payload): bool
{
$outcome = strtolower((string) ($payload['outcome'] ?? ''));
return str_contains($outcome, 'completed');
}
/**
* @return array<string, array{next: string, label: string}>
*/
public function stageFlow(): array
{
return [
self::STAGE_CHECK_IN => ['next' => self::STAGE_HISTORY, 'label' => 'Start history'],
self::STAGE_HISTORY => ['next' => self::STAGE_EXAM, 'label' => 'Move to skin exam'],
self::STAGE_EXAM => ['next' => self::STAGE_INVESTIGATION, 'label' => 'Move to investigations'],
self::STAGE_INVESTIGATION => ['next' => self::STAGE_PLAN, 'label' => 'Move to diagnosis & plan'],
self::STAGE_PLAN => ['next' => self::STAGE_PROCEDURE, 'label' => 'Move to procedure'],
self::STAGE_PROCEDURE => ['next' => self::STAGE_COMPLETED, 'label' => 'Complete visit'],
self::STAGE_COMPLETED => ['next' => self::STAGE_COMPLETED, 'label' => 'Completed'],
];
}
}
@@ -0,0 +1,168 @@
<?php
namespace App\Services\Care\Fertility;
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 FertilityAnalyticsService
{
public function __construct(
protected SpecialtyShellService $shell,
) {}
/**
* @return array{
* arrivals_today: int,
* completed_today: int,
* priority_open: int,
* diagnosis_breakdown: Collection,
* cycle_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, 'fertility', $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');
$priorityOpen = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'fertility')
->where('record_type', 'fert_exam')
->whereIn('visit_id', $openVisitIds->isEmpty() ? [0] : $openVisitIds)
->get()
->filter(function (SpecialtyClinicalRecord $r) {
$priority = (string) ($r->payload['priority'] ?? '');
return in_array($priority, ['Urgent', 'Time-sensitive'], true);
})
->count();
$planRecords = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'fertility')
->where('record_type', 'fert_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();
$cycleRecords = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'fertility')
->where('record_type', 'fert_cycle')
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
->get();
$cycleBreakdown = $cycleRecords
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['cycle_type'] ?? 'Unknown'))
->map(fn (Collection $rows, string $cycleType) => [
'procedure' => $cycleType,
'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, 'fertility'))
->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,
'priority_open' => $priorityOpen,
'diagnosis_breakdown' => $diagnosisBreakdown,
'cycle_breakdown' => $cycleBreakdown,
'avg_los_minutes' => $avgLos,
'revenue_by_service' => $revenueByService,
'from' => $rangeFrom->toDateString(),
'to' => $rangeTo->toDateString(),
];
}
}
@@ -0,0 +1,104 @@
<?php
namespace App\Services\Care\Fertility;
/**
* Map fertility clinical progress onto visit stages.
*/
class FertilityWorkflowService
{
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_CYCLE = 'cycle';
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['exam_findings']) || ! empty($payload['chief_complaint'])) {
return self::STAGE_EXAM;
}
return self::STAGE_HISTORY;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromInvestigation(array $payload): string
{
$findings = trim((string) ($payload['findings'] ?? ''));
if ($findings !== '') {
return self::STAGE_INVESTIGATION;
}
return self::STAGE_EXAM;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromPlan(array $payload): string
{
if (! empty($payload['cycle_planned'])) {
return self::STAGE_CYCLE;
}
$plan = trim((string) ($payload['plan'] ?? ''));
if ($plan !== '') {
return self::STAGE_PLAN;
}
return self::STAGE_INVESTIGATION;
}
/**
* @param array<string, mixed> $payload
*/
public function shouldCompleteVisit(array $payload): bool
{
$outcome = strtolower((string) ($payload['outcome'] ?? ''));
return str_contains($outcome, 'completed');
}
/**
* @return array<string, array{next: string, label: string}>
*/
public function stageFlow(): array
{
return [
self::STAGE_CHECK_IN => ['next' => self::STAGE_HISTORY, 'label' => 'Start history'],
self::STAGE_HISTORY => ['next' => self::STAGE_EXAM, 'label' => 'Move to exam'],
self::STAGE_EXAM => ['next' => self::STAGE_INVESTIGATION, 'label' => 'Move to investigations'],
self::STAGE_INVESTIGATION => ['next' => self::STAGE_PLAN, 'label' => 'Move to diagnosis & plan'],
self::STAGE_PLAN => ['next' => self::STAGE_CYCLE, 'label' => 'Move to cycle note'],
self::STAGE_CYCLE => ['next' => self::STAGE_COMPLETED, 'label' => 'Complete visit'],
self::STAGE_COMPLETED => ['next' => self::STAGE_COMPLETED, 'label' => 'Completed'],
];
}
}
@@ -0,0 +1,168 @@
<?php
namespace App\Services\Care\Podiatry;
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 PodiatryAnalyticsService
{
public function __construct(
protected SpecialtyShellService $shell,
) {}
/**
* @return array{
* arrivals_today: int,
* completed_today: int,
* high_risk_open: int,
* diagnosis_breakdown: Collection,
* procedure_breakdown: Collection,
* avg_los_minutes: ?float,
* revenue_by_service: Collection,
* from: string,
* to: string
* }
*/
public function report(
Organization $organization,
string $ownerRef,
?int $branchId = null,
?string $from = null,
?string $to = null,
): array {
$todayStart = now()->startOfDay();
$rangeFrom = $from ? Carbon::parse($from)->startOfDay() : now()->startOfMonth();
$rangeTo = $to ? Carbon::parse($to)->endOfDay() : now()->endOfDay();
$departmentIds = $this->shell->departmentIds($organization, 'podiatry', $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', 'podiatry')
->where('record_type', 'foot_exam')
->whereIn('visit_id', $openVisitIds->isEmpty() ? [0] : $openVisitIds)
->get()
->filter(function (SpecialtyClinicalRecord $r) {
$risk = (string) ($r->payload['diabetes'] ?? '');
return in_array($risk, ['High', 'Active ulcer'], true);
})
->count();
$planRecords = SpecialtyClinicalRecord::owned($ownerRef)
->where('organization_id', $organization->id)
->where('module_key', 'podiatry')
->where('record_type', 'pod_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', 'podiatry')
->where('record_type', 'pod_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, 'podiatry'))
->pluck('label')
->filter()
->values()
->all();
$revenueByService = BillLineItem::query()
->where('owner_ref', $ownerRef)
->where('source_type', 'specialty_service')
->whereIn('description', $serviceLabels ?: ['__none__'])
->whereBetween('created_at', [$rangeFrom, $rangeTo])
->whereHas('bill', function ($q) use ($organization, $visitIds) {
$q->where('organization_id', $organization->id)
->whereIn('visit_id', $visitIds->isEmpty() ? [0] : $visitIds)
->whereNotIn('status', [Bill::STATUS_VOID]);
})
->selectRaw('description, count(*) as total, sum(total_minor) as amount_minor')
->groupBy('description')
->orderByDesc('amount_minor')
->get();
return [
'arrivals_today' => $arrivalsToday,
'completed_today' => $completedToday,
'high_risk_open' => $highRiskOpen,
'diagnosis_breakdown' => $diagnosisBreakdown,
'procedure_breakdown' => $procedureBreakdown,
'avg_los_minutes' => $avgLos,
'revenue_by_service' => $revenueByService,
'from' => $rangeFrom->toDateString(),
'to' => $rangeTo->toDateString(),
];
}
}
@@ -0,0 +1,104 @@
<?php
namespace App\Services\Care\Podiatry;
/**
* Map podiatry clinical progress onto visit stages.
*/
class PodiatryWorkflowService
{
public const STAGE_CHECK_IN = 'check_in';
public const STAGE_HISTORY = 'history';
public const STAGE_EXAM = 'exam';
public const STAGE_INVESTIGATION = 'investigation';
public const STAGE_PLAN = 'plan';
public const STAGE_PROCEDURE = 'procedure';
public const STAGE_COMPLETED = 'completed';
/**
* @param array<string, mixed> $payload
*/
public function stageFromHistory(array $payload): string
{
$history = trim((string) ($payload['history'] ?? ''));
if ($history !== '') {
return self::STAGE_HISTORY;
}
return self::STAGE_CHECK_IN;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromExam(array $payload): string
{
if (! empty($payload['chief_complaint']) || ! empty($payload['ulcer']) || ! empty($payload['skin_nails'])) {
return self::STAGE_EXAM;
}
return self::STAGE_HISTORY;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromInvestigation(array $payload): string
{
$findings = trim((string) ($payload['findings'] ?? ''));
if ($findings !== '') {
return self::STAGE_INVESTIGATION;
}
return self::STAGE_EXAM;
}
/**
* @param array<string, mixed> $payload
*/
public function stageFromPlan(array $payload): string
{
if (! empty($payload['procedure_planned'])) {
return self::STAGE_PROCEDURE;
}
$plan = trim((string) ($payload['plan'] ?? ''));
if ($plan !== '') {
return self::STAGE_PLAN;
}
return self::STAGE_INVESTIGATION;
}
/**
* @param array<string, mixed> $payload
*/
public function shouldCompleteVisit(array $payload): bool
{
$outcome = strtolower((string) ($payload['outcome'] ?? ''));
return str_contains($outcome, 'completed');
}
/**
* @return array<string, array{next: string, label: string}>
*/
public function stageFlow(): array
{
return [
self::STAGE_CHECK_IN => ['next' => self::STAGE_HISTORY, 'label' => 'Start history'],
self::STAGE_HISTORY => ['next' => self::STAGE_EXAM, 'label' => 'Move to foot exam'],
self::STAGE_EXAM => ['next' => self::STAGE_INVESTIGATION, 'label' => 'Move to investigations'],
self::STAGE_INVESTIGATION => ['next' => self::STAGE_PLAN, 'label' => 'Move to diagnosis & plan'],
self::STAGE_PLAN => ['next' => self::STAGE_PROCEDURE, 'label' => 'Move to procedure'],
self::STAGE_PROCEDURE => ['next' => self::STAGE_COMPLETED, 'label' => 'Complete visit'],
self::STAGE_COMPLETED => ['next' => self::STAGE_COMPLETED, 'label' => 'Completed'],
];
}
}
@@ -419,6 +419,39 @@ class SpecialtyClinicalRecordService
}
}
if ($moduleKey === 'dermatology' && $recordType === 'skin_exam') {
$urgency = (string) ($payload['urgency'] ?? '');
if (in_array($urgency, ['High', 'Suspected malignancy'], true)) {
$alerts[] = [
'code' => 'der.urgency_high',
'severity' => $urgency === 'Suspected malignancy' ? 'critical' : 'warning',
'message' => 'Skin exam urgency: '.$urgency.'.',
];
}
}
if ($moduleKey === 'podiatry' && $recordType === 'foot_exam') {
$risk = (string) ($payload['diabetes'] ?? '');
if (in_array($risk, ['High', 'Active ulcer'], true)) {
$alerts[] = [
'code' => 'pod.diabetes_high',
'severity' => $risk === 'Active ulcer' ? 'critical' : 'warning',
'message' => 'Diabetic foot risk: '.$risk.'.',
];
}
}
if ($moduleKey === 'fertility' && $recordType === 'fert_exam') {
$priority = (string) ($payload['priority'] ?? '');
if (in_array($priority, ['Urgent', 'Time-sensitive'], true)) {
$alerts[] = [
'code' => 'fer.priority_high',
'severity' => $priority === 'Urgent' ? 'critical' : 'warning',
'message' => 'Fertility priority: '.$priority.'.',
];
}
}
if ($moduleKey === 'pediatrics' && $recordType === 'pediatric_exam') {
$concern = (string) ($payload['growth_concern'] ?? '');
if ($concern !== '' && $concern !== 'None') {
+13 -1
View File
@@ -26,6 +26,9 @@ use App\Services\Care\Surgery\SurgeryWorkflowService;
use App\Services\Care\Vaccination\VaccinationWorkflowService;
use App\Services\Care\Pathology\PathologyWorkflowService;
use App\Services\Care\Infusion\InfusionWorkflowService;
use App\Services\Care\Dermatology\DermatologyWorkflowService;
use App\Services\Care\Podiatry\PodiatryWorkflowService;
use App\Services\Care\Fertility\FertilityWorkflowService;
use Illuminate\Support\Collection;
/**
@@ -84,6 +87,9 @@ class SpecialtyShellService
'vaccination' => 'care.specialty.vaccination.stage',
'pathology' => 'care.specialty.pathology.stage',
'infusion' => 'care.specialty.infusion.stage',
'dermatology' => 'care.specialty.dermatology.stage',
'podiatry' => 'care.specialty.podiatry.stage',
'fertility' => 'care.specialty.fertility.stage',
default => null,
};
}
@@ -113,6 +119,9 @@ class SpecialtyShellService
'vaccination' => app(VaccinationWorkflowService::class)->stageFlow(),
'pathology' => app(PathologyWorkflowService::class)->stageFlow(),
'infusion' => app(InfusionWorkflowService::class)->stageFlow(),
'dermatology' => app(DermatologyWorkflowService::class)->stageFlow(),
'podiatry' => app(PodiatryWorkflowService::class)->stageFlow(),
'fertility' => app(FertilityWorkflowService::class)->stageFlow(),
'dentistry' => [
'waiting' => ['next' => 'chair', 'label' => 'Seat at chair'],
'chair' => ['next' => 'procedure', 'label' => 'Start procedure'],
@@ -412,7 +421,7 @@ class SpecialtyShellService
) {
$code = (string) ($stage['code'] ?? '');
if (in_array($moduleKey, ['dentistry', 'emergency', 'blood_bank', 'ophthalmology', 'physiotherapy', 'maternity', 'radiology', 'cardiology', 'psychiatry', 'pediatrics', 'orthopedics', 'ent', 'oncology', 'renal', 'surgery', 'vaccination', 'pathology', 'infusion'], true) && $visitIds->isNotEmpty()) {
if (in_array($moduleKey, ['dentistry', 'emergency', 'blood_bank', 'ophthalmology', 'physiotherapy', 'maternity', 'radiology', 'cardiology', 'psychiatry', 'pediatrics', 'orthopedics', 'ent', 'oncology', 'renal', 'surgery', 'vaccination', 'pathology', 'infusion', 'dermatology', 'podiatry', 'fertility'], true) && $visitIds->isNotEmpty()) {
$count = Visit::owned($ownerRef)
->where('organization_id', $organization->id)
->whereIn('id', $visitIds)
@@ -457,6 +466,9 @@ class SpecialtyShellService
'vaccination' => $clinical->countOpenByType($organization, 'vaccination', 'vax_eligibility', $branchScope),
'pathology' => $clinical->countOpenByType($organization, 'pathology', 'path_request', $branchScope),
'infusion' => $clinical->countOpenByType($organization, 'infusion', 'infusion_assessment', $branchScope),
'dermatology' => $clinical->countOpenByType($organization, 'dermatology', 'skin_exam', $branchScope),
'podiatry' => $clinical->countOpenByType($organization, 'podiatry', 'foot_exam', $branchScope),
'fertility' => $clinical->countOpenByType($organization, 'fertility', 'fert_exam', $branchScope),
'dentistry' => \App\Models\DentalPlanItem::query()
->whereHas('plan', function ($q) use ($organization, $ownerRef) {
$q->owned($ownerRef)
@@ -168,6 +168,30 @@ class SpecialtyVisitStageService
: ($stages[1] ?? ($stages[0] ?? null));
}
if ($moduleKey === 'dermatology') {
$stages = $this->allowedStages($moduleKey);
return in_array(\App\Services\Care\Dermatology\DermatologyWorkflowService::STAGE_HISTORY, $stages, true)
? \App\Services\Care\Dermatology\DermatologyWorkflowService::STAGE_HISTORY
: ($stages[1] ?? ($stages[0] ?? null));
}
if ($moduleKey === 'podiatry') {
$stages = $this->allowedStages($moduleKey);
return in_array(\App\Services\Care\Podiatry\PodiatryWorkflowService::STAGE_HISTORY, $stages, true)
? \App\Services\Care\Podiatry\PodiatryWorkflowService::STAGE_HISTORY
: ($stages[1] ?? ($stages[0] ?? null));
}
if ($moduleKey === 'fertility') {
$stages = $this->allowedStages($moduleKey);
return in_array(\App\Services\Care\Fertility\FertilityWorkflowService::STAGE_HISTORY, $stages, true)
? \App\Services\Care\Fertility\FertilityWorkflowService::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)) {