Add full Blood Bank specialty suite on shared shell.
Deploy Ladill Care / deploy (push) Successful in 37s
Deploy Ladill Care / deploy (push) Successful in 37s
Mirror Emergency: stage workflow, issue/transfusion records, analytics, print, and action-menu stage flow without a parallel EHR. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,318 @@
|
||||
<?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\BloodBank\BloodBankAnalyticsService;
|
||||
use App\Services\Care\BloodBank\BloodBankWorkflowService;
|
||||
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 BloodBankWorkspaceController extends Controller
|
||||
{
|
||||
use ScopesToAccount;
|
||||
|
||||
protected function assertBloodBankAccess(Request $request, SpecialtyModuleService $modules): void
|
||||
{
|
||||
$organization = $this->organization($request);
|
||||
abort_unless($modules->memberCanAccess($organization, $this->member($request), 'blood_bank'), 403);
|
||||
}
|
||||
|
||||
protected function assertBloodBankManage(Request $request, SpecialtyModuleService $modules): void
|
||||
{
|
||||
$organization = $this->organization($request);
|
||||
abort_unless($modules->memberCanManage($organization, $this->member($request), 'blood_bank'), 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,
|
||||
): RedirectResponse {
|
||||
$this->authorizeAbility($request, 'consultations.manage');
|
||||
$this->assertBloodBankManage($request, $modules);
|
||||
$this->assertVisit($request, $visit);
|
||||
|
||||
$validated = $request->validate([
|
||||
'stage' => ['required', 'string', 'max:32'],
|
||||
]);
|
||||
|
||||
try {
|
||||
$stages->setStage(
|
||||
$this->organization($request),
|
||||
$visit,
|
||||
'blood_bank',
|
||||
$validated['stage'],
|
||||
$this->ownerRef($request),
|
||||
$this->actorRef($request),
|
||||
);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
return back()->with('error', $e->getMessage());
|
||||
}
|
||||
|
||||
return redirect()
|
||||
->route('care.specialty.workspace', ['module' => 'blood_bank', 'visit' => $visit, 'tab' => 'overview'])
|
||||
->with('success', 'Visit stage updated.');
|
||||
}
|
||||
|
||||
public function confirmIssue(
|
||||
Request $request,
|
||||
Visit $visit,
|
||||
SpecialtyModuleService $modules,
|
||||
SpecialtyClinicalRecordService $clinical,
|
||||
SpecialtyVisitStageService $stages,
|
||||
SpecialtyShellService $shell,
|
||||
BloodBankWorkflowService $workflow,
|
||||
): RedirectResponse {
|
||||
$this->authorizeAbility($request, 'consultations.manage');
|
||||
$this->assertBloodBankManage($request, $modules);
|
||||
$this->assertVisit($request, $visit);
|
||||
|
||||
$organization = $this->organization($request);
|
||||
$owner = $this->ownerRef($request);
|
||||
|
||||
$payload = (array) $request->input('payload', []);
|
||||
foreach ($clinical->fieldsFor('blood_bank', 'issue_note') as $field) {
|
||||
if (($field['type'] ?? '') === 'boolean') {
|
||||
$payload[$field['name']] = $request->boolean('payload.'.$field['name']);
|
||||
}
|
||||
}
|
||||
$request->merge(['payload' => $payload, 'tab' => 'issue']);
|
||||
|
||||
$validated = $request->validate(array_merge([
|
||||
'tab' => ['required', 'string'],
|
||||
'bill_product' => ['nullable', 'boolean'],
|
||||
'bill_crossmatch' => ['nullable', 'boolean'],
|
||||
], $clinical->validationRules('blood_bank', 'issue_note')));
|
||||
|
||||
$issuePayload = $clinical->payloadFromRequest($validated);
|
||||
$units = max(1, (int) ($issuePayload['units_issued'] ?? 1));
|
||||
|
||||
$record = $clinical->upsert(
|
||||
$organization,
|
||||
$visit,
|
||||
'blood_bank',
|
||||
'issue_note',
|
||||
$issuePayload,
|
||||
$owner,
|
||||
$owner,
|
||||
BloodBankWorkflowService::STAGE_ISSUE,
|
||||
SpecialtyClinicalRecord::STATUS_COMPLETED,
|
||||
);
|
||||
|
||||
// Keep the request record in sync with issued units / cross-match status.
|
||||
$requestRecord = $clinical->findForVisit($visit, 'blood_bank', 'blood_request');
|
||||
if ($requestRecord) {
|
||||
$requestPayload = array_merge($requestRecord->payload ?? [], [
|
||||
'issued_units' => $units,
|
||||
'crossmatch_status' => 'Issued',
|
||||
'product' => $issuePayload['product'] ?? ($requestRecord->payload['product'] ?? null),
|
||||
]);
|
||||
$clinical->upsert(
|
||||
$organization,
|
||||
$visit,
|
||||
'blood_bank',
|
||||
'blood_request',
|
||||
$requestPayload,
|
||||
$owner,
|
||||
$owner,
|
||||
BloodBankWorkflowService::STAGE_ISSUE,
|
||||
SpecialtyClinicalRecord::STATUS_ACTIVE,
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
$stages->setStage(
|
||||
$organization,
|
||||
$visit,
|
||||
'blood_bank',
|
||||
BloodBankWorkflowService::STAGE_ISSUE,
|
||||
$owner,
|
||||
$owner,
|
||||
);
|
||||
} catch (\InvalidArgumentException) {
|
||||
// Stage already issue or map empty.
|
||||
}
|
||||
|
||||
if ($request->boolean('bill_crossmatch')) {
|
||||
try {
|
||||
$shell->addCatalogServiceToVisit($organization, $visit, 'blood_bank', 'bb.crossmatch', $owner, $owner);
|
||||
} catch (\InvalidArgumentException) {
|
||||
}
|
||||
}
|
||||
|
||||
if ($request->boolean('bill_product', true)) {
|
||||
$serviceCode = $workflow->serviceCodeForProduct($issuePayload['product'] ?? null);
|
||||
if ($serviceCode) {
|
||||
try {
|
||||
$shell->addCatalogServiceToVisit(
|
||||
$organization,
|
||||
$visit,
|
||||
'blood_bank',
|
||||
$serviceCode,
|
||||
$owner,
|
||||
$owner,
|
||||
$units,
|
||||
);
|
||||
} catch (\InvalidArgumentException) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return redirect()
|
||||
->route('care.specialty.workspace', ['module' => 'blood_bank', 'visit' => $visit, 'tab' => 'issue'])
|
||||
->with('success', 'Product issue confirmed.');
|
||||
}
|
||||
|
||||
public function saveTransfusion(
|
||||
Request $request,
|
||||
Visit $visit,
|
||||
SpecialtyModuleService $modules,
|
||||
SpecialtyClinicalRecordService $clinical,
|
||||
SpecialtyVisitStageService $stages,
|
||||
BloodBankWorkflowService $workflow,
|
||||
): RedirectResponse {
|
||||
$this->authorizeAbility($request, 'consultations.manage');
|
||||
$this->assertBloodBankManage($request, $modules);
|
||||
$this->assertVisit($request, $visit);
|
||||
|
||||
$organization = $this->organization($request);
|
||||
$owner = $this->ownerRef($request);
|
||||
|
||||
$payload = (array) $request->input('payload', []);
|
||||
foreach ($clinical->fieldsFor('blood_bank', 'transfusion_note') as $field) {
|
||||
if (($field['type'] ?? '') === 'boolean') {
|
||||
$payload[$field['name']] = $request->boolean('payload.'.$field['name']);
|
||||
}
|
||||
}
|
||||
$request->merge(['payload' => $payload, 'tab' => 'transfusion']);
|
||||
|
||||
$validated = $request->validate(array_merge([
|
||||
'tab' => ['required', 'string'],
|
||||
], $clinical->validationRules('blood_bank', 'transfusion_note')));
|
||||
|
||||
$record = $clinical->upsert(
|
||||
$organization,
|
||||
$visit,
|
||||
'blood_bank',
|
||||
'transfusion_note',
|
||||
$clinical->payloadFromRequest($validated),
|
||||
$owner,
|
||||
$owner,
|
||||
BloodBankWorkflowService::STAGE_TRANSFUSION,
|
||||
SpecialtyClinicalRecord::STATUS_COMPLETED,
|
||||
);
|
||||
|
||||
try {
|
||||
$stages->setStage(
|
||||
$organization,
|
||||
$visit,
|
||||
'blood_bank',
|
||||
BloodBankWorkflowService::STAGE_TRANSFUSION,
|
||||
$owner,
|
||||
$owner,
|
||||
);
|
||||
} catch (\InvalidArgumentException) {
|
||||
}
|
||||
|
||||
if ($workflow->shouldCompleteVisit($record->payload ?? [])) {
|
||||
try {
|
||||
$stages->setStage(
|
||||
$organization,
|
||||
$visit,
|
||||
'blood_bank',
|
||||
BloodBankWorkflowService::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' => 'blood_bank', 'visit' => $visit, 'tab' => 'transfusion'])
|
||||
->with('success', 'Transfusion record saved.');
|
||||
}
|
||||
|
||||
public function reports(
|
||||
Request $request,
|
||||
SpecialtyModuleService $modules,
|
||||
SpecialtyShellService $shell,
|
||||
BloodBankAnalyticsService $analytics,
|
||||
): View {
|
||||
$this->authorizeAbility($request, 'consultations.view');
|
||||
$this->assertBloodBankAccess($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.blood-bank.reports', [
|
||||
'moduleKey' => 'blood_bank',
|
||||
'definition' => $modules->definition('blood_bank'),
|
||||
'shellNav' => $shell->navItems('blood_bank'),
|
||||
'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->assertBloodBankAccess($request, $modules);
|
||||
$this->assertVisit($request, $visit);
|
||||
|
||||
$visit->loadMissing(['patient', 'appointment.practitioner', 'branch', 'bill.lineItems']);
|
||||
|
||||
return view('care.specialty.blood-bank.print', [
|
||||
'visit' => $visit,
|
||||
'patient' => $visit->patient,
|
||||
'bloodRequest' => $clinical->findForVisit($visit, 'blood_bank', 'blood_request'),
|
||||
'inventoryNote' => $clinical->findForVisit($visit, 'blood_bank', 'inventory_note'),
|
||||
'issueNote' => $clinical->findForVisit($visit, 'blood_bank', 'issue_note'),
|
||||
'transfusionNote' => $clinical->findForVisit($visit, 'blood_bank', 'transfusion_note'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -169,6 +169,7 @@ class SpecialtyModuleController extends Controller
|
||||
$preferredTab = match ($module) {
|
||||
'dentistry' => 'odontogram',
|
||||
'emergency' => 'triage',
|
||||
'blood_bank' => 'requests',
|
||||
default => (collect(array_keys($shellTabs))
|
||||
->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null)
|
||||
?? 'clinical_notes'),
|
||||
@@ -226,7 +227,7 @@ class SpecialtyModuleController extends Controller
|
||||
} catch (\InvalidArgumentException) {
|
||||
// Stage map may be empty for some modules.
|
||||
}
|
||||
} elseif ($nextStage && in_array($visit->specialty_stage, ['waiting', 'arrival'], true)) {
|
||||
} elseif ($nextStage && in_array($visit->specialty_stage, ['waiting', 'arrival', 'request'], true)) {
|
||||
try {
|
||||
$stageService->setStage($organization, $visit, $module, $nextStage, $owner, $owner);
|
||||
$visit = $visit->fresh();
|
||||
@@ -239,6 +240,7 @@ class SpecialtyModuleController extends Controller
|
||||
$preferredTab = match ($module) {
|
||||
'dentistry' => 'odontogram',
|
||||
'emergency' => 'triage',
|
||||
'blood_bank' => 'requests',
|
||||
default => (collect(array_keys($shellTabs))
|
||||
->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null)
|
||||
?? 'clinical_notes'),
|
||||
@@ -335,6 +337,42 @@ class SpecialtyModuleController extends Controller
|
||||
}
|
||||
}
|
||||
|
||||
if ($module === 'blood_bank' && $recordType === 'blood_request') {
|
||||
$workflow = app(\App\Services\Care\BloodBank\BloodBankWorkflowService::class);
|
||||
$stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
|
||||
$suggested = $workflow->stageFromRequest($record->payload ?? []);
|
||||
$current = $visit->specialty_stage;
|
||||
if (! $current || in_array($current, ['request', 'waiting'], true)) {
|
||||
try {
|
||||
$stageService->setStage(
|
||||
$organization,
|
||||
$visit,
|
||||
'blood_bank',
|
||||
$suggested,
|
||||
$this->ownerRef($request),
|
||||
$this->ownerRef($request),
|
||||
);
|
||||
} catch (\InvalidArgumentException) {
|
||||
}
|
||||
} elseif ($suggested !== $current && in_array($suggested, ['crossmatch', 'issue'], true)) {
|
||||
// Advance when cross-match / issue status progresses on an existing request.
|
||||
$order = ['request' => 0, 'crossmatch' => 1, 'issue' => 2, 'transfusion' => 3, 'completed' => 4];
|
||||
if (($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
|
||||
try {
|
||||
$stageService->setStage(
|
||||
$organization,
|
||||
$visit,
|
||||
'blood_bank',
|
||||
$suggested,
|
||||
$this->ownerRef($request),
|
||||
$this->ownerRef($request),
|
||||
);
|
||||
} catch (\InvalidArgumentException) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return redirect()
|
||||
->route('care.specialty.workspace', [
|
||||
'module' => $module,
|
||||
@@ -726,6 +764,12 @@ class SpecialtyModuleController extends Controller
|
||||
$emergencyLatestVitals = null;
|
||||
$emergencyStageCodes = [];
|
||||
$emergencyStageFlow = [];
|
||||
$bloodBankRequest = null;
|
||||
$bloodBankInventory = null;
|
||||
$bloodBankIssue = null;
|
||||
$bloodBankTransfusion = null;
|
||||
$bloodBankStageCodes = [];
|
||||
$bloodBankStageFlow = [];
|
||||
$activeTab = (string) $request->query('tab', array_key_first($shell->workspaceTabs($module)) ?: 'overview');
|
||||
$clinical = app(SpecialtyClinicalRecordService::class);
|
||||
|
||||
@@ -842,6 +886,15 @@ class SpecialtyModuleController extends Controller
|
||||
$emergencyStageFlow = app(\App\Services\Care\Emergency\EmergencyWorkflowService::class)->stageFlow();
|
||||
}
|
||||
|
||||
if ($module === 'blood_bank') {
|
||||
$bloodBankRequest = $clinical->findForVisit($workspaceVisit, 'blood_bank', 'blood_request');
|
||||
$bloodBankInventory = $clinical->findForVisit($workspaceVisit, 'blood_bank', 'inventory_note');
|
||||
$bloodBankIssue = $clinical->findForVisit($workspaceVisit, 'blood_bank', 'issue_note');
|
||||
$bloodBankTransfusion = $clinical->findForVisit($workspaceVisit, 'blood_bank', 'transfusion_note');
|
||||
$bloodBankStageCodes = collect($shell->stages('blood_bank'))->pluck('code')->all();
|
||||
$bloodBankStageFlow = app(\App\Services\Care\BloodBank\BloodBankWorkflowService::class)->stageFlow();
|
||||
}
|
||||
|
||||
if ($patientHeader !== null) {
|
||||
$patientHeader['clinical_alerts'] = $clinicalAlerts;
|
||||
}
|
||||
@@ -921,6 +974,12 @@ class SpecialtyModuleController extends Controller
|
||||
'emergencyLatestVitals' => $emergencyLatestVitals,
|
||||
'emergencyStageCodes' => $emergencyStageCodes,
|
||||
'emergencyStageFlow' => $emergencyStageFlow,
|
||||
'bloodBankRequest' => $bloodBankRequest,
|
||||
'bloodBankInventory' => $bloodBankInventory,
|
||||
'bloodBankIssue' => $bloodBankIssue,
|
||||
'bloodBankTransfusion' => $bloodBankTransfusion,
|
||||
'bloodBankStageCodes' => $bloodBankStageCodes,
|
||||
'bloodBankStageFlow' => $bloodBankStageFlow,
|
||||
'queueStubs' => $modules->queueStubsFor($organization, $module),
|
||||
'branchId' => $branchId,
|
||||
'branchLabel' => $branchLabel,
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Care\BloodBank;
|
||||
|
||||
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 BloodBankAnalyticsService
|
||||
{
|
||||
public function __construct(
|
||||
protected SpecialtyShellService $shell,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* requests_today: int,
|
||||
* completed_today: int,
|
||||
* high_urgency_open: int,
|
||||
* urgency_mix: Collection,
|
||||
* products_issued: Collection,
|
||||
* low_stock_flags: int,
|
||||
* 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, 'blood_bank', $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));
|
||||
|
||||
$visitIds = (clone $appointmentBase)->whereNotNull('visit_id')->pluck('visit_id');
|
||||
|
||||
$requestsToday = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'blood_bank')
|
||||
->where('record_type', 'blood_request')
|
||||
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
|
||||
->where('recorded_at', '>=', $todayStart)
|
||||
->count();
|
||||
|
||||
$completedToday = (clone $appointmentBase)
|
||||
->where('status', Appointment::STATUS_COMPLETED)
|
||||
->where('completed_at', '>=', $todayStart)
|
||||
->count();
|
||||
|
||||
$requestRecords = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'blood_bank')
|
||||
->where('record_type', 'blood_request')
|
||||
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
|
||||
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
|
||||
->get();
|
||||
|
||||
$urgencyMix = $requestRecords
|
||||
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['urgency'] ?? 'Unknown'))
|
||||
->map(fn (Collection $rows, string $urgency) => [
|
||||
'urgency' => $urgency,
|
||||
'total' => $rows->count(),
|
||||
])
|
||||
->values()
|
||||
->sortByDesc('total')
|
||||
->values();
|
||||
|
||||
$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');
|
||||
|
||||
$highUrgencyOpen = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'blood_bank')
|
||||
->where('record_type', 'blood_request')
|
||||
->whereIn('visit_id', $openVisitIds->isEmpty() ? [0] : $openVisitIds)
|
||||
->get()
|
||||
->filter(function (SpecialtyClinicalRecord $r) {
|
||||
$urgency = strtolower((string) ($r->payload['urgency'] ?? ''));
|
||||
|
||||
return str_contains($urgency, 'urgent')
|
||||
|| str_contains($urgency, 'emergency')
|
||||
|| str_contains($urgency, 'massive');
|
||||
})
|
||||
->count();
|
||||
|
||||
$issueRecords = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'blood_bank')
|
||||
->where('record_type', 'issue_note')
|
||||
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
|
||||
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
|
||||
->get();
|
||||
|
||||
$productsIssued = $issueRecords
|
||||
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['product'] ?? 'Unknown'))
|
||||
->map(fn (Collection $rows, string $product) => [
|
||||
'product' => $product,
|
||||
'total' => $rows->sum(fn (SpecialtyClinicalRecord $r) => (int) ($r->payload['units_issued'] ?? 0)),
|
||||
'issues' => $rows->count(),
|
||||
])
|
||||
->values()
|
||||
->sortByDesc('total')
|
||||
->values();
|
||||
|
||||
// Fall back to request issued_units when no dedicated issue notes exist.
|
||||
if ($productsIssued->isEmpty()) {
|
||||
$productsIssued = $requestRecords
|
||||
->filter(fn (SpecialtyClinicalRecord $r) => (int) ($r->payload['issued_units'] ?? 0) > 0)
|
||||
->groupBy(fn (SpecialtyClinicalRecord $r) => (string) ($r->payload['product'] ?? 'Unknown'))
|
||||
->map(fn (Collection $rows, string $product) => [
|
||||
'product' => $product,
|
||||
'total' => $rows->sum(fn (SpecialtyClinicalRecord $r) => (int) ($r->payload['issued_units'] ?? 0)),
|
||||
'issues' => $rows->count(),
|
||||
])
|
||||
->values()
|
||||
->sortByDesc('total')
|
||||
->values();
|
||||
}
|
||||
|
||||
$lowStockFlags = SpecialtyClinicalRecord::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->where('module_key', 'blood_bank')
|
||||
->where('record_type', 'inventory_note')
|
||||
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
|
||||
->whereBetween('recorded_at', [$rangeFrom, $rangeTo])
|
||||
->get()
|
||||
->filter(function (SpecialtyClinicalRecord $r) {
|
||||
if (! empty($r->payload['low_stock_alert'])) {
|
||||
return true;
|
||||
}
|
||||
foreach (['whole_blood_units', 'packed_rbc_units', 'platelet_units', 'ffp_units'] as $key) {
|
||||
if (isset($r->payload[$key]) && (int) $r->payload[$key] <= 2) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
})
|
||||
->count();
|
||||
|
||||
$serviceLabels = collect($this->shell->provisionedServices($organization, 'blood_bank'))
|
||||
->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 [
|
||||
'requests_today' => $requestsToday,
|
||||
'completed_today' => $completedToday,
|
||||
'high_urgency_open' => $highUrgencyOpen,
|
||||
'urgency_mix' => $urgencyMix,
|
||||
'products_issued' => $productsIssued,
|
||||
'low_stock_flags' => $lowStockFlags,
|
||||
'revenue_by_service' => $revenueByService,
|
||||
'from' => $rangeFrom->toDateString(),
|
||||
'to' => $rangeTo->toDateString(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Care\BloodBank;
|
||||
|
||||
/**
|
||||
* Map blood request / issue payloads onto Blood Bank visit stages.
|
||||
*/
|
||||
class BloodBankWorkflowService
|
||||
{
|
||||
public const STAGE_REQUEST = 'request';
|
||||
|
||||
public const STAGE_CROSSMATCH = 'crossmatch';
|
||||
|
||||
public const STAGE_ISSUE = 'issue';
|
||||
|
||||
public const STAGE_TRANSFUSION = 'transfusion';
|
||||
|
||||
public const STAGE_COMPLETED = 'completed';
|
||||
|
||||
/**
|
||||
* Suggested next visit stage after a blood request payload is saved.
|
||||
*
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function stageFromRequest(array $payload): string
|
||||
{
|
||||
$crossmatch = strtolower((string) ($payload['crossmatch_status'] ?? ''));
|
||||
$issued = (int) ($payload['issued_units'] ?? 0);
|
||||
$urgency = strtolower((string) ($payload['urgency'] ?? ''));
|
||||
|
||||
if ($issued > 0 || $crossmatch === 'issued') {
|
||||
return self::STAGE_ISSUE;
|
||||
}
|
||||
|
||||
if (in_array($crossmatch, ['compatible', 'incompatible', 'in progress'], true)) {
|
||||
return self::STAGE_CROSSMATCH;
|
||||
}
|
||||
|
||||
if (str_contains($urgency, 'emergency') || str_contains($urgency, 'massive')) {
|
||||
return self::STAGE_CROSSMATCH;
|
||||
}
|
||||
|
||||
return self::STAGE_REQUEST;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a transfusion payload should close the visit episode.
|
||||
*
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function shouldCompleteVisit(array $payload): bool
|
||||
{
|
||||
$outcome = strtolower((string) ($payload['outcome'] ?? ''));
|
||||
|
||||
return $outcome !== '' && (
|
||||
str_contains($outcome, 'completed')
|
||||
|| str_contains($outcome, 'stopped')
|
||||
|| str_contains($outcome, 'complete')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Map product label to catalog service code for billing.
|
||||
*/
|
||||
public function serviceCodeForProduct(?string $product): ?string
|
||||
{
|
||||
$normalized = strtolower(trim((string) $product));
|
||||
|
||||
return match (true) {
|
||||
str_contains($normalized, 'whole') => 'bb.whole_blood',
|
||||
str_contains($normalized, 'packed') || str_contains($normalized, 'rbc') => 'bb.packed_rbc',
|
||||
str_contains($normalized, 'platelet') => 'bb.platelets',
|
||||
str_contains($normalized, 'ffp') || str_contains($normalized, 'plasma') => 'bb.ffp',
|
||||
str_contains($normalized, 'cryo') => 'bb.cryo',
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Default stage progression for action buttons.
|
||||
*
|
||||
* @return array<string, array{next: string, label: string}>
|
||||
*/
|
||||
public function stageFlow(): array
|
||||
{
|
||||
return [
|
||||
self::STAGE_REQUEST => ['next' => self::STAGE_CROSSMATCH, 'label' => 'Start cross-match'],
|
||||
self::STAGE_CROSSMATCH => ['next' => self::STAGE_ISSUE, 'label' => 'Ready to issue'],
|
||||
self::STAGE_ISSUE => ['next' => self::STAGE_TRANSFUSION, 'label' => 'Start transfusion'],
|
||||
self::STAGE_TRANSFUSION => ['next' => self::STAGE_COMPLETED, 'label' => 'Complete visit'],
|
||||
self::STAGE_COMPLETED => ['next' => self::STAGE_COMPLETED, 'label' => 'Completed'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -196,6 +196,12 @@ class SpecialtyClinicalRecordService
|
||||
'severity' => 'critical',
|
||||
'message' => 'Emergency / massive transfusion request.',
|
||||
];
|
||||
} elseif (str_contains(strtolower($urgency), 'urgent')) {
|
||||
$alerts[] = [
|
||||
'code' => 'bb.urgent_request',
|
||||
'severity' => 'warning',
|
||||
'message' => 'Urgent blood product request.',
|
||||
];
|
||||
}
|
||||
if (($payload['crossmatch_status'] ?? '') === 'Incompatible') {
|
||||
$alerts[] = [
|
||||
@@ -214,7 +220,7 @@ class SpecialtyClinicalRecordService
|
||||
'message' => 'Blood products flagged as low stock.',
|
||||
];
|
||||
}
|
||||
foreach (['whole_blood_units', 'packed_rbc_units', 'platelet_units'] as $key) {
|
||||
foreach (['whole_blood_units', 'packed_rbc_units', 'platelet_units', 'ffp_units', 'cryo_units'] as $key) {
|
||||
if (isset($payload[$key]) && (int) $payload[$key] <= 2) {
|
||||
$alerts[] = [
|
||||
'code' => 'bb.unit_critical',
|
||||
@@ -225,6 +231,24 @@ class SpecialtyClinicalRecordService
|
||||
}
|
||||
}
|
||||
|
||||
if ($moduleKey === 'blood_bank' && $recordType === 'transfusion_note') {
|
||||
$reaction = strtolower((string) ($payload['reaction'] ?? ''));
|
||||
if (str_contains($reaction, 'severe') || str_contains($reaction, 'stop')) {
|
||||
$alerts[] = [
|
||||
'code' => 'bb.transfusion_reaction',
|
||||
'severity' => 'critical',
|
||||
'message' => 'Severe transfusion reaction — stop and escalate.',
|
||||
];
|
||||
}
|
||||
if (($payload['vitals_ok'] ?? true) === false) {
|
||||
$alerts[] = [
|
||||
'code' => 'bb.vitals_concern',
|
||||
'severity' => 'warning',
|
||||
'message' => 'Transfusion vitals not acceptable.',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $alerts;
|
||||
}
|
||||
|
||||
|
||||
@@ -270,7 +270,7 @@ class SpecialtyShellService
|
||||
) {
|
||||
$code = (string) ($stage['code'] ?? '');
|
||||
|
||||
if (in_array($moduleKey, ['dentistry', 'emergency'], true) && $visitIds->isNotEmpty()) {
|
||||
if (in_array($moduleKey, ['dentistry', 'emergency', 'blood_bank'], true) && $visitIds->isNotEmpty()) {
|
||||
$count = Visit::owned($ownerRef)
|
||||
->where('organization_id', $organization->id)
|
||||
->whereIn('id', $visitIds)
|
||||
@@ -502,6 +502,7 @@ class SpecialtyShellService
|
||||
string $serviceCode,
|
||||
string $ownerRef,
|
||||
?string $actorRef = null,
|
||||
int $quantity = 1,
|
||||
): Bill {
|
||||
$service = collect($this->provisionedServices($organization, $moduleKey))
|
||||
->first(fn ($s) => ($s['code'] ?? '') === $serviceCode);
|
||||
@@ -510,12 +511,21 @@ class SpecialtyShellService
|
||||
throw new \InvalidArgumentException("Unknown specialty service [{$serviceCode}].");
|
||||
}
|
||||
|
||||
$bill = $this->bills->generateFromVisit($visit, $ownerRef, $actorRef);
|
||||
// Reuse an open visit bill without syncLineItemsFromVisit — that sync deletes
|
||||
// prior specialty_service lines and would wipe multi-item issue/billing batches.
|
||||
$bill = Bill::owned($ownerRef)
|
||||
->where('visit_id', $visit->id)
|
||||
->whereNotIn('status', [Bill::STATUS_VOID])
|
||||
->first();
|
||||
|
||||
if (! $bill) {
|
||||
$bill = $this->bills->generateFromVisit($visit, $ownerRef, $actorRef);
|
||||
}
|
||||
|
||||
return $this->bills->addManualLineItem($bill, $ownerRef, [
|
||||
'type' => $service['type'] ?? 'misc',
|
||||
'description' => $service['label'],
|
||||
'quantity' => 1,
|
||||
'quantity' => max(1, $quantity),
|
||||
'unit_price_minor' => (int) ($service['amount_minor'] ?? 0),
|
||||
'source_type' => 'specialty_service',
|
||||
'source_id' => null,
|
||||
|
||||
@@ -88,6 +88,14 @@ class SpecialtyVisitStageService
|
||||
: ($stages[1] ?? ($stages[0] ?? null));
|
||||
}
|
||||
|
||||
if ($moduleKey === 'blood_bank') {
|
||||
$stages = $this->allowedStages($moduleKey);
|
||||
|
||||
return in_array(\App\Services\Care\BloodBank\BloodBankWorkflowService::STAGE_CROSSMATCH, $stages, true)
|
||||
? \App\Services\Care\BloodBank\BloodBankWorkflowService::STAGE_CROSSMATCH
|
||||
: ($stages[1] ?? ($stages[0] ?? null));
|
||||
}
|
||||
|
||||
$stages = $this->allowedStages($moduleKey);
|
||||
foreach (['chair', 'in_care', 'exam', 'assessment', 'treatment'] as $preferred) {
|
||||
if (in_array($preferred, $stages, true)) {
|
||||
|
||||
Reference in New Issue
Block a user