Activate Care workflows across check-in and financial clearance.
Deploy Ladill Care / deploy (push) Failing after 1m9s

Enforce service-queue gates, cashier settlements, and clinical stage progression so patient journeys cannot bypass configured payment or authorization rules.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
isaacclad
2026-07-17 21:13:06 +00:00
co-authored by Cursor
parent 86bfce1e17
commit 3ee59a0956
38 changed files with 1953 additions and 107 deletions
@@ -2,15 +2,21 @@
namespace App\Http\Controllers\Care;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Http\Controllers\Controller;
use App\Models\Appointment;
use App\Models\Branch;
use App\Models\Department;
use App\Models\Organization;
use App\Models\Patient;
use App\Models\Practitioner;
use App\Services\Care\AppointmentService;
use App\Services\Care\CareFeatures;
use App\Services\Care\CarePermissions;
use App\Services\Care\OrganizationResolver;
use App\Services\Care\Workflow\WorkflowEngine;
use App\Services\Care\Workflow\WorkflowQueueGate;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
@@ -108,6 +114,11 @@ class AppointmentController extends Controller
$this->ownerRef($request),
);
if (app(CareFeatures::class)->enabled($organization, CareFeatures::WORKFLOW_ENGINE)) {
return redirect()->route('care.appointments.show', $appointment)
->with('success', 'Walk-in checked in. Complete the current patient journey stage before Queue release.');
}
return redirect()->route('care.queue.index')
->with('success', 'Walk-in added to queue.');
}
@@ -119,16 +130,47 @@ class AppointmentController extends Controller
$appointment->load(['patient', 'practitioner', 'branch', 'department', 'visit', 'consultation']);
$canManage = app(\App\Services\Care\CarePermissions::class)
$canManage = app(CarePermissions::class)
->can($this->member($request), 'appointments.manage');
$canConsult = app(\App\Services\Care\CarePermissions::class)
$canConsult = app(CarePermissions::class)
->can($this->member($request), 'consultations.manage');
$canViewBills = app(CarePermissions::class)
->can($this->member($request), 'bills.view');
$organization = $this->organization($request);
$workflowEnabled = $appointment->visit
&& app(CareFeatures::class)->enabled($organization, CareFeatures::WORKFLOW_ENGINE);
$workflowEngine = app(WorkflowEngine::class);
$currentAdvance = $workflowEnabled
? $workflowEngine->refreshGate($appointment->visit)
: null;
$currentObligation = $currentAdvance?->stage
? $appointment->visit->financialObligations()
->where('workflow_stage_id', $currentAdvance->stage->id)
->latest('id')
->first()
: null;
$canStartConsultation = $canConsult && (! $workflowEnabled || app(WorkflowQueueGate::class)->canRelease(
$organization,
$appointment->visit,
$this->appointments->queueContextFor($organization, $appointment),
));
return view('care.appointments.show', [
'appointment' => $appointment,
'statuses' => config('care.appointment_statuses'),
'canManage' => $canManage,
'canConsult' => $canConsult,
'canViewBills' => $canViewBills,
'canStartConsultation' => $canStartConsultation,
'workflowEnabled' => $workflowEnabled,
'currentAdvance' => $currentAdvance,
'currentObligation' => $currentObligation,
'workflowHistory' => $workflowEnabled
? $appointment->visit->stageAdvances()->with('stage')->orderBy('id')->get()
: collect(),
'canAdvanceWorkflow' => $canManage
&& $workflowEnabled
&& $workflowEngine->canManuallyAdvance($appointment->visit),
]);
}
@@ -137,7 +179,12 @@ class AppointmentController extends Controller
$this->authorizeAbility($request, 'appointments.manage');
$this->authorizeAppointment($request, $appointment);
$this->appointments->checkIn($appointment, $this->ownerRef($request), $this->ownerRef($request));
$appointment = $this->appointments->checkIn($appointment, $this->ownerRef($request), $this->ownerRef($request));
if (app(CareFeatures::class)->enabled($this->organization($request), CareFeatures::WORKFLOW_ENGINE)) {
return redirect()->route('care.appointments.show', $appointment)
->with('success', 'Patient checked in. Complete the current patient journey stage before Queue release.');
}
return redirect()->route('care.queue.index')
->with('success', 'Patient checked in and added to queue.');
@@ -177,7 +224,7 @@ class AppointmentController extends Controller
/**
* @return array<string, mixed>
*/
protected function formData(Request $request, \App\Models\Organization $organization): array
protected function formData(Request $request, Organization $organization): array
{
$ownerRef = $this->ownerRef($request);
$branchQuery = Branch::owned($ownerRef)->where('organization_id', $organization->id)->where('is_active', true);
@@ -214,7 +261,7 @@ class AppointmentController extends Controller
}
/**
* @return \Illuminate\Database\Eloquent\Collection<int, Practitioner>
* @return Collection<int, Practitioner>
*/
protected function activePractitioners(Request $request, int $organizationId)
{
@@ -2,13 +2,14 @@
namespace App\Http\Controllers\Care;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Http\Controllers\Controller;
use App\Models\Assessment;
use App\Models\AssessmentTemplate;
use App\Models\Consultation;
use App\Models\InvestigationType;
use App\Models\Practitioner;
use App\Models\Assessment;
use App\Models\AssessmentTemplate;
use App\Services\Care\AssessmentService;
use App\Services\Care\CareFeatures;
use App\Services\Care\CarePermissions;
use App\Services\Care\ConsultationReturnContext;
@@ -105,7 +106,7 @@ class ConsultationController extends Controller
if ($universalTemplate) {
try {
app(\App\Services\Care\AssessmentService::class)
app(AssessmentService::class)
->assertCaptureAllowed($member, $universalTemplate);
$canCaptureUniversal = true;
} catch (\Throwable) {
@@ -197,9 +198,9 @@ class ConsultationController extends Controller
public function update(Request $request, Consultation $consultation): RedirectResponse
{
$canManage = app(\App\Services\Care\CarePermissions::class)
$canManage = app(CarePermissions::class)
->can($this->member($request), 'consultations.manage');
$canVitals = app(\App\Services\Care\CarePermissions::class)
$canVitals = app(CarePermissions::class)
->can($this->member($request), 'vitals.manage');
abort_unless($canManage || $canVitals, 403);
@@ -232,7 +233,7 @@ class ConsultationController extends Controller
$this->authorizeAbility($request, 'consultations.manage');
$this->authorizeConsultation($request, $consultation);
$this->consultations->complete(
$completed = $this->consultations->complete(
$consultation,
$this->ownerRef($request),
$this->ownerRef($request),
@@ -240,6 +241,17 @@ class ConsultationController extends Controller
app(ConsultationReturnContext::class)->forget();
$completed->loadMissing(['appointment.organization']);
if ($completed->appointment
&& $completed->appointment->organization
&& app(CareFeatures::class)->enabled(
$completed->appointment->organization,
CareFeatures::WORKFLOW_ENGINE,
)) {
return redirect()->route('care.appointments.show', $completed->appointment)
->with('success', 'Consultation completed. Continue the patient journey from the next stage.');
}
return redirect()->route('care.queue.index')
->with('success', 'Consultation completed.');
}
@@ -0,0 +1,205 @@
<?php
namespace App\Http\Controllers\Care;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Http\Controllers\Controller;
use App\Models\FinancialObligation;
use App\Models\Payment;
use App\Models\WorkflowStage;
use App\Services\Care\AuditLogger;
use App\Services\Care\BillService;
use App\Services\Care\CareFeatures;
use App\Services\Care\CarePermissions;
use App\Services\Care\CareQueueContexts;
use App\Services\Care\OrganizationResolver;
use App\Services\Care\Workflow\FinancialGateService;
use App\Services\Care\Workflow\WorkflowEngine;
use App\Services\Care\Workflow\WorkflowQueueReleaseService;
use App\Services\Care\Workflow\WorkflowStageCompletionService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;
class FinancialObligationController extends Controller
{
use ScopesToAccount;
public function __construct(
protected CareFeatures $features,
protected FinancialGateService $gates,
protected WorkflowEngine $workflows,
protected WorkflowQueueReleaseService $queueRelease,
protected WorkflowStageCompletionService $workflowCompletion,
protected BillService $bills,
) {}
public function index(Request $request): View
{
$this->authorizeAbility($request, 'bills.view');
$organization = $this->organization($request);
abort_unless($this->features->enabled($organization, CareFeatures::WORKFLOW_ENGINE), 404);
$branchScope = app(OrganizationResolver::class)->branchScope($this->member($request));
$status = (string) $request->query('status', FinancialObligation::STATUS_PENDING);
$obligations = FinancialObligation::owned($this->ownerRef($request))
->where('organization_id', $organization->id)
->when($branchScope, fn ($query) => $query->where('branch_id', $branchScope))
->when($status !== '', fn ($query) => $query->where('status', $status))
->with(['patient', 'branch', 'stage', 'visit', 'bill'])
->latest('created_at')
->paginate(20)
->withQueryString();
return view('care.financial-obligations.index', [
'obligations' => $obligations,
'statuses' => config('care_workflows.obligation_statuses', []),
'clearanceMethods' => config('care_workflows.clearance_methods', []),
'paymentModes' => config('care_workflows.payment_modes', []),
'paymentMethods' => collect(config('care.payment_methods', []))->except(['gateway'])->all(),
'canClear' => app(CarePermissions::class)
->can($this->member($request), 'payments.manage'),
]);
}
public function clear(Request $request, FinancialObligation $financialObligation): RedirectResponse
{
$this->authorizeAbility($request, 'payments.manage');
$this->authorizeObligation($request, $financialObligation);
if ($financialObligation->status !== FinancialObligation::STATUS_PENDING) {
return back()->with('info', 'This financial obligation is no longer pending.');
}
$manualPaymentMethods = array_keys(
collect(config('care.payment_methods', []))->except(['gateway'])->all()
);
$validated = $request->validate([
'method' => ['required', Rule::in(array_keys(config('care_workflows.clearance_methods', [])))],
'payment_mode' => ['nullable', Rule::in(array_keys(config('care_workflows.payment_modes', [])))],
'payment_method' => ['nullable', Rule::in($manualPaymentMethods)],
'reference' => ['nullable', 'string', 'max:100'],
]);
$stage = $financialObligation->stage;
$method = (string) $validated['method'];
$paymentMode = $validated['payment_mode'] ?? null;
$reference = trim((string) ($validated['reference'] ?? '')) ?: null;
$this->validateClearanceRules($stage, $method, $paymentMode, $reference);
if ($method === 'bank_receipt') {
$paymentMode = 'external_bank';
}
$settled = DB::transaction(function () use ($financialObligation, $validated, $method, $paymentMode, $reference, $request) {
$locked = FinancialObligation::query()->lockForUpdate()->findOrFail($financialObligation->id);
if ($locked->status !== FinancialObligation::STATUS_PENDING) {
return $locked;
}
if (in_array($method, ['payment', 'bank_receipt'], true) && $locked->amount_minor > 0) {
$bill = $this->bills->billForObligation(
$locked,
$this->ownerRef($request),
$this->ownerRef($request),
);
$this->bills->recordPayment($bill, $this->ownerRef($request), [
'amount_minor' => $locked->amount_minor,
'method' => $method === 'bank_receipt'
? Payment::METHOD_OTHER
: ($validated['payment_method'] ?? Payment::METHOD_CASH),
'reference' => $reference,
'notes' => 'Workflow financial obligation '.$locked->uuid,
], $this->ownerRef($request));
}
$this->gates->clear(
$locked,
$method,
$this->ownerRef($request),
$paymentMode,
$reference,
);
AuditLogger::record(
$this->ownerRef($request),
'financial_obligation.cleared',
$locked->organization_id,
$this->ownerRef($request),
FinancialObligation::class,
$locked->id,
['method' => $method, 'amount_minor' => $locked->amount_minor],
);
return $locked->fresh();
});
$visit = $settled->visit;
if ($visit) {
$advance = $this->workflows->refreshGate($visit);
if ($advance?->stage?->type === 'payment') {
$this->workflowCompletion->complete(
$this->organization($request),
$visit,
CareQueueContexts::BILLING,
$this->ownerRef($request),
$this->ownerRef($request),
);
} else {
$this->queueRelease->releaseCurrent($this->organization($request), $visit);
}
}
return back()->with('success', 'Financial obligation cleared. The patient may now continue.');
}
protected function validateClearanceRules(?WorkflowStage $stage, string $method, ?string $paymentMode, ?string $reference): void
{
if ($method === 'insurance' && ! $stage?->insurance_eligible) {
throw ValidationException::withMessages(['method' => 'Insurance is not allowed for this stage.']);
}
if ($method === 'credit' && ! $stage?->credit_allowed) {
throw ValidationException::withMessages(['method' => 'Credit is not allowed for this stage.']);
}
if (in_array($method, ['waiver', 'override'], true) && ! $stage?->allow_override) {
throw ValidationException::withMessages(['method' => 'Waivers and overrides are not allowed for this stage.']);
}
if ($method === 'bank_receipt' && $reference === null) {
throw ValidationException::withMessages(['reference' => 'Enter the external bank receipt or slip number.']);
}
if ($method === 'bank_receipt' && $stage && ! in_array('external_bank', (array) $stage->payment_modes, true)) {
throw ValidationException::withMessages(['method' => 'External bank receipts are not allowed for this stage.']);
}
if ($method === 'payment') {
$allowedModes = (array) ($stage?->payment_modes ?? []);
if ($paymentMode === null || ($allowedModes !== [] && ! in_array($paymentMode, $allowedModes, true))) {
throw ValidationException::withMessages(['payment_mode' => 'Select a payment mode allowed for this stage.']);
}
if ($paymentMode === 'external_bank') {
throw ValidationException::withMessages(['method' => 'Use external bank receipt verification for bank payments.']);
}
}
}
protected function authorizeObligation(Request $request, FinancialObligation $obligation): void
{
$this->authorizeOwner($request, $obligation);
abort_unless($obligation->organization_id === $this->organization($request)->id, 404);
$branchId = app(OrganizationResolver::class)->branchScope($this->member($request));
if ($branchId !== null && $obligation->branch_id !== $branchId) {
abort(404);
}
}
}
+14 -9
View File
@@ -2,12 +2,13 @@
namespace App\Http\Controllers\Care;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Http\Controllers\Controller;
use App\Models\Appointment;
use App\Models\Branch;
use App\Models\Practitioner;
use App\Services\Care\AppointmentService;
use App\Services\Care\CarePermissions;
use App\Services\Care\CareQueueBridge;
use App\Services\Care\CareQueueContexts;
use App\Services\Care\ConsultationService;
@@ -63,9 +64,9 @@ class QueueController extends Controller
->orderBy('started_at')
->get();
$canManageQueue = app(\App\Services\Care\CarePermissions::class)
$canManageQueue = app(CarePermissions::class)
->can($this->member($request), 'queue.manage');
$canConsult = app(\App\Services\Care\CarePermissions::class)
$canConsult = app(CarePermissions::class)
->can($this->member($request), 'consultations.manage');
$heroStats = [
@@ -162,12 +163,16 @@ class QueueController extends Controller
? (int) $request->input('practitioner_id')
: $appointment->practitioner_id;
$this->appointments->startConsultation(
$appointment,
$this->ownerRef($request),
$practitionerId,
$this->ownerRef($request),
);
try {
$this->appointments->startConsultation(
$appointment,
$this->ownerRef($request),
$practitionerId,
$this->ownerRef($request),
);
} catch (\InvalidArgumentException $e) {
return back()->with('error', $e->getMessage());
}
$consultation = $this->consultations->startFromAppointment(
$appointment->fresh(),
@@ -2,9 +2,12 @@
namespace App\Http\Controllers\Care;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Http\Controllers\Controller;
use App\Models\Branch;
use App\Models\Organization;
use App\Services\Billing\PlatformEmailClient;
use App\Services\Billing\PlatformSmsClient;
use App\Services\Care\AppointmentPatientNotifier;
use App\Services\Care\AuditLogger;
use App\Services\Care\CareFeatures;
@@ -13,8 +16,8 @@ use App\Services\Care\CareQueueBridge;
use App\Services\Care\CareQueueContexts;
use App\Services\Care\CareQueueProvisioner;
use App\Services\Care\PlanService;
use App\Services\Billing\PlatformEmailClient;
use App\Services\Billing\PlatformSmsClient;
use App\Services\Care\Workflow\WorkflowTemplateInstaller;
use App\Services\Care\Workflow\WorkflowTemplateRegistry;
use App\Services\Messaging\MessagingCredentialsService;
use App\Services\Queue\QueueClient;
use App\Support\OrganizationBranding;
@@ -63,18 +66,16 @@ class SettingsController extends Controller
'canUseQueueIntegration' => $plans->canUseQueueIntegration($organization),
'canUseSpecialtyModules' => $plans->canUseSpecialtyModules($organization),
'assessmentsEngineEnabled' => $careFeatures->enabled($organization, CareFeatures::ASSESSMENTS_ENGINE),
'workflowEngineEnabled' => $careFeatures->enabled($organization, CareFeatures::WORKFLOW_ENGINE),
'financialGatesEnabled' => $careFeatures->enabled($organization, CareFeatures::FINANCIAL_GATES),
'hasBillingFeature' => $plans->hasFeature($organization, 'billing'),
'messagingSmsReady' => $suiteSmsReady || $credential->hasValidSms(),
'messagingEmailReady' => $suiteEmailReady || $credential->hasValidBird(),
'suiteMessagingReady' => $suiteEmailReady || $suiteSmsReady,
'messagingSettingsUrl' => function_exists('ladill_account_url')
? ladill_account_url('/account/settings/messaging')
: (string) config('smtp.messaging_settings_url', 'https://account.ladill.com/account/settings/messaging'),
'facilityTypes' => [
'clinic' => 'Clinic',
'hospital' => 'Hospital',
'diagnostic' => 'Diagnostic laboratory',
'specialist' => 'Specialist practice',
],
'facilityTypes' => app(WorkflowTemplateRegistry::class)->categoryOptions(),
]);
}
@@ -88,11 +89,17 @@ class SettingsController extends Controller
$validated = $request->validate([
'name' => ['required', 'string', 'max:255'],
'timezone' => ['required', 'timezone'],
'facility_type' => ['required', 'string', 'in:clinic,hospital,diagnostic,specialist'],
'facility_type' => [
'required',
'string',
'in:'.implode(',', array_keys(app(WorkflowTemplateRegistry::class)->categories())),
],
'logo' => ['nullable', 'image', 'mimes:jpeg,png,jpg,webp,svg', 'max:2048'],
'remove_logo' => ['nullable', 'boolean'],
'queue_integration_enabled' => ['nullable', 'boolean'],
'assessments_engine' => ['nullable', 'boolean'],
'workflow_engine' => ['nullable', 'boolean'],
'financial_gates' => ['nullable', 'boolean'],
'notify_appointment_booked_sms' => ['nullable', 'boolean'],
'notify_appointment_booked_email' => ['nullable', 'boolean'],
'notify_video_scheduled_sms' => ['nullable', 'boolean'],
@@ -102,10 +109,17 @@ class SettingsController extends Controller
$settings = $organization->settings ?? [];
$settings['onboarded'] = true;
$settings['facility_type'] = $validated['facility_type'];
$settings['facility_category'] = $validated['facility_type'];
$settings['modules'] = app(WorkflowTemplateRegistry::class)
->modulesForCategory($validated['facility_type']);
$rollout = is_array($settings['rollout'] ?? null) ? $settings['rollout'] : [];
// Explicit save so opt-out is stored (engine defaults ON when unset).
$rollout[CareFeatures::ASSESSMENTS_ENGINE] = $request->boolean('assessments_engine');
$rollout[CareFeatures::WORKFLOW_ENGINE] = $request->boolean('workflow_engine');
$rollout[CareFeatures::FINANCIAL_GATES] = $request->boolean('financial_gates')
&& $rollout[CareFeatures::WORKFLOW_ENGINE]
&& $plans->hasFeature($organization, 'billing');
$settings['rollout'] = $rollout;
if ($rollout[CareFeatures::ASSESSMENTS_ENGINE]) {
app(CareFeatures::class)->ensureAssessmentCatalog();
@@ -155,6 +169,21 @@ class SettingsController extends Controller
'settings' => $settings,
]);
if ($rollout[CareFeatures::WORKFLOW_ENGINE] && ! $organization->facilityWorkflows()->where('is_active', true)->exists()) {
$branch = Branch::owned($owner)
->where('organization_id', $organization->id)
->orderBy('id')
->first();
if ($branch) {
app(WorkflowTemplateInstaller::class)->install(
$organization->fresh(),
$branch,
(string) ($settings['workflow_template'] ?? config('care_workflows.default_template', 'legacy_clinic')),
['category' => $settings['facility_category'] ?? $settings['facility_type'] ?? 'clinic'],
);
}
}
if ($wantsQueue && $queue->configured()) {
try {
$organization = $organization->fresh();
@@ -178,7 +207,7 @@ class SettingsController extends Controller
}
}
AuditLogger::record($owner, 'organization.updated', $organization->id, $owner, \App\Models\Organization::class, $organization->id);
AuditLogger::record($owner, 'organization.updated', $organization->id, $owner, Organization::class, $organization->id);
return back()->with('success', 'Settings saved.');
}
@@ -0,0 +1,81 @@
<?php
namespace App\Http\Controllers\Care;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Http\Controllers\Controller;
use App\Models\Visit;
use App\Models\VisitStageAdvance;
use App\Services\Care\AuditLogger;
use App\Services\Care\CareFeatures;
use App\Services\Care\OrganizationResolver;
use App\Services\Care\Workflow\WorkflowEngine;
use App\Services\Care\Workflow\WorkflowQueueReleaseService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
class VisitWorkflowController extends Controller
{
use ScopesToAccount;
public function __construct(
protected CareFeatures $features,
protected WorkflowEngine $workflows,
protected WorkflowQueueReleaseService $queueRelease,
) {}
public function advance(Request $request, Visit $visit): RedirectResponse
{
$this->authorizeAbility($request, 'appointments.manage');
$this->authorizeVisit($request, $visit);
$organization = $this->organization($request);
abort_unless($this->features->enabled($organization, CareFeatures::WORKFLOW_ENGINE), 404);
$validated = $request->validate([
'to_code' => ['nullable', 'string', 'max:100'],
]);
if (! $this->workflows->canManuallyAdvance($visit)) {
return back()->with('error', 'Complete this clinical service from its own workspace before advancing the visit.');
}
try {
$advance = $this->workflows->advance($visit, $validated['to_code'] ?? null);
} catch (\DomainException $e) {
return back()->with('error', $e->getMessage());
}
if ($advance === null) {
return back()->with('info', 'This visit has no next workflow stage.');
}
AuditLogger::record(
$this->ownerRef($request),
'visit.workflow_advanced',
$visit->organization_id,
$this->ownerRef($request),
VisitStageAdvance::class,
$advance->id,
['stage_code' => $advance->stage_code, 'status' => $advance->status],
);
$this->queueRelease->releaseCurrent($organization, $visit);
$message = $advance->isBlocked()
? "Visit moved to {$advance->stage?->name}; financial clearance is required before service."
: "Visit moved to {$advance->stage?->name}.";
return back()->with($advance->isBlocked() ? 'warning' : 'success', $message);
}
protected function authorizeVisit(Request $request, Visit $visit): void
{
$this->authorizeOwner($request, $visit);
abort_unless($visit->organization_id === $this->organization($request)->id, 404);
$branchId = app(OrganizationResolver::class)->branchScope($this->member($request));
if ($branchId !== null && $visit->branch_id !== $branchId) {
abort(404);
}
}
}