Add ward MAR board plus nursing notes and SBAR handovers.
Deploy Ladill Care / deploy (push) Successful in 52s

Nurses can chart given/held/refused doses from active prescriptions on placed patients, and document chronologic notes and unit shift handovers.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
isaacclad
2026-07-20 10:15:58 +00:00
co-authored by Cursor
parent 45a1a95142
commit cb6e59e5ed
20 changed files with 2021 additions and 1 deletions
+112
View File
@@ -0,0 +1,112 @@
<?php
namespace App\Http\Controllers\Care;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Models\CareUnit;
use App\Models\MarOrder;
use App\Models\Visit;
use App\Services\Care\CarePermissions;
use App\Services\Care\MarService;
use Carbon\Carbon;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\View\View;
class MarController extends Controller
{
use ScopesToAccount;
public function unitBoard(Request $request, CareUnit $careUnit, MarService $mar): View
{
$this->authorizeAbility($request, 'mar.view');
$this->authorizeOwner($request, $careUnit);
$organization = $this->organization($request);
abort_unless((int) $careUnit->organization_id === (int) $organization->id, 404);
$day = $request->filled('date')
? Carbon::parse($request->input('date'))->startOfDay()
: now()->startOfDay();
$rows = $mar->unitRoundBoard($careUnit, $this->ownerRef($request), $day);
$canAdminister = app(CarePermissions::class)->can($this->member($request), 'mar.administer');
return view('care.nursing.mar-board', [
'unit' => $careUnit->load('department.branch'),
'day' => $day,
'rows' => $rows,
'canAdminister' => $canAdminister,
'statuses' => config('care.mar_administration_statuses'),
'stateLabels' => config('care.mar_slot_states'),
]);
}
public function visitChart(Request $request, Visit $visit, MarService $mar): View
{
$this->authorizeAbility($request, 'mar.view');
$this->authorizeOwner($request, $visit);
$this->authorizeBranch($request, (int) $visit->branch_id);
$day = $request->filled('date')
? Carbon::parse($request->input('date'))->startOfDay()
: now()->startOfDay();
$orders = $mar->syncOrdersForVisit($visit, $this->ownerRef($request));
$chart = [];
foreach ($orders as $order) {
$chart[] = [
'order' => $order,
'slots' => $mar->dueSlotsForOrder($order, $day),
];
}
return view('care.nursing.mar-visit', [
'visit' => $visit->load(['patient', 'careUnit', 'bed']),
'day' => $day,
'chart' => $chart,
'canAdminister' => app(CarePermissions::class)->can($this->member($request), 'mar.administer'),
'statuses' => config('care.mar_administration_statuses'),
'stateLabels' => config('care.mar_slot_states'),
'frequencies' => config('care.mar_frequency_codes'),
]);
}
public function administer(Request $request, MarOrder $marOrder, MarService $mar): RedirectResponse
{
$this->authorizeAbility($request, 'mar.administer');
$this->authorizeOwner($request, $marOrder);
$validated = $request->validate([
'status' => ['required', 'string', Rule::in(array_keys(config('care.mar_administration_statuses')))],
'scheduled_for' => ['nullable', 'date'],
'dose_given' => ['nullable', 'string', 'max:255'],
'route' => ['nullable', 'string', 'max:100'],
'witness_by' => ['nullable', 'string', 'max:255'],
'reason' => ['nullable', 'string', 'max:500'],
'notes' => ['nullable', 'string', 'max:2000'],
'redirect_to' => ['nullable', 'string', 'max:500'],
]);
$mar->recordAdministration(
$marOrder,
$validated['status'],
$this->ownerRef($request),
$this->actorRef($request),
isset($validated['scheduled_for']) ? Carbon::parse($validated['scheduled_for']) : null,
$validated['dose_given'] ?? null,
$validated['route'] ?? null,
$validated['witness_by'] ?? null,
$validated['reason'] ?? null,
$validated['notes'] ?? null,
);
$redirect = $validated['redirect_to'] ?? null;
if ($redirect && str_starts_with($redirect, url('/'))) {
return redirect()->to($redirect)->with('success', 'MAR entry recorded.');
}
return back()->with('success', 'MAR entry recorded.');
}
}
@@ -0,0 +1,189 @@
<?php
namespace App\Http\Controllers\Care;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Models\CareUnit;
use App\Models\Visit;
use App\Models\WardHandover;
use App\Services\Care\CarePermissions;
use App\Services\Care\NursingDocumentationService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\View\View;
class NursingDocumentationController extends Controller
{
use ScopesToAccount;
public function unitNotes(Request $request, CareUnit $careUnit, NursingDocumentationService $docs): View
{
$this->authorizeAbility($request, 'nursing.notes.view');
$this->authorizeOwner($request, $careUnit);
abort_unless((int) $careUnit->organization_id === (int) $this->organization($request)->id, 404);
$placedVisits = Visit::owned($this->ownerRef($request))
->where('care_unit_id', $careUnit->id)
->whereIn('status', [Visit::STATUS_OPEN, Visit::STATUS_IN_PROGRESS])
->with(['patient', 'bed'])
->orderBy('placed_at')
->get();
return view('care.nursing.notes', [
'unit' => $careUnit->load('department.branch'),
'notes' => $docs->notesForUnit($careUnit, $this->ownerRef($request)),
'placedVisits' => $placedVisits,
'canWrite' => app(CarePermissions::class)->can($this->member($request), 'nursing.notes.manage'),
'noteTypes' => config('care.nursing_note_types'),
'shiftCodes' => config('care.staff_shift_codes'),
]);
}
public function storeNote(Request $request, CareUnit $careUnit, NursingDocumentationService $docs): RedirectResponse
{
$this->authorizeAbility($request, 'nursing.notes.manage');
$this->authorizeOwner($request, $careUnit);
$validated = $request->validate([
'visit_id' => ['required', 'integer', 'exists:care_visits,id'],
'note_type' => ['required', 'string', Rule::in(array_keys(config('care.nursing_note_types')))],
'shift_code' => ['nullable', 'string', Rule::in(array_keys(config('care.staff_shift_codes')))],
'body' => ['required', 'string', 'max:5000'],
]);
$visit = Visit::owned($this->ownerRef($request))
->where('organization_id', $this->organization($request)->id)
->findOrFail($validated['visit_id']);
$this->authorizeBranch($request, (int) $visit->branch_id);
$docs->addNote(
$visit,
$this->ownerRef($request),
$this->actorRef($request),
$validated['body'],
$validated['note_type'],
$validated['shift_code'] ?? null,
$careUnit->id,
);
return redirect()
->route('care.care-units.notes', $careUnit)
->with('success', 'Nursing note saved.');
}
public function handovers(Request $request, CareUnit $careUnit): View
{
$this->authorizeAbility($request, 'nursing.handover.view');
$this->authorizeOwner($request, $careUnit);
abort_unless((int) $careUnit->organization_id === (int) $this->organization($request)->id, 404);
$handovers = WardHandover::owned($this->ownerRef($request))
->where('care_unit_id', $careUnit->id)
->orderByDesc('created_at')
->limit(30)
->get();
return view('care.nursing.handovers', [
'unit' => $careUnit->load('department.branch'),
'handovers' => $handovers,
'canWrite' => app(CarePermissions::class)->can($this->member($request), 'nursing.handover.manage'),
'shiftCodes' => config('care.staff_shift_codes'),
'statuses' => config('care.ward_handover_statuses'),
]);
}
public function createHandover(Request $request, CareUnit $careUnit, NursingDocumentationService $docs): View
{
$this->authorizeAbility($request, 'nursing.handover.manage');
$this->authorizeOwner($request, $careUnit);
return view('care.nursing.handover-form', [
'unit' => $careUnit->load('department.branch'),
'handover' => null,
'patientSummaries' => $docs->defaultPatientSummaries($careUnit, $this->ownerRef($request)),
'shiftCodes' => config('care.staff_shift_codes'),
]);
}
public function storeHandover(Request $request, CareUnit $careUnit, NursingDocumentationService $docs): RedirectResponse
{
$this->authorizeAbility($request, 'nursing.handover.manage');
$this->authorizeOwner($request, $careUnit);
$validated = $this->validatedHandover($request);
$complete = $request->boolean('complete');
$handover = $docs->createHandover(
$careUnit,
$this->ownerRef($request),
$this->actorRef($request),
$validated,
$complete,
);
return redirect()
->route('care.care-units.handovers', $careUnit)
->with('success', $complete ? 'Handover completed.' : 'Handover draft saved.');
}
public function showHandover(Request $request, CareUnit $careUnit, WardHandover $wardHandover): View
{
$this->authorizeAbility($request, 'nursing.handover.view');
$this->authorizeOwner($request, $careUnit);
$this->authorizeOwner($request, $wardHandover);
abort_unless((int) $wardHandover->care_unit_id === (int) $careUnit->id, 404);
return view('care.nursing.handover-show', [
'unit' => $careUnit->load('department.branch'),
'handover' => $wardHandover,
'shiftCodes' => config('care.staff_shift_codes'),
'statuses' => config('care.ward_handover_statuses'),
'canWrite' => app(CarePermissions::class)->can($this->member($request), 'nursing.handover.manage')
&& $wardHandover->status === WardHandover::STATUS_DRAFT,
]);
}
public function completeHandover(
Request $request,
CareUnit $careUnit,
WardHandover $wardHandover,
NursingDocumentationService $docs,
): RedirectResponse {
$this->authorizeAbility($request, 'nursing.handover.manage');
$this->authorizeOwner($request, $careUnit);
$this->authorizeOwner($request, $wardHandover);
abort_unless((int) $wardHandover->care_unit_id === (int) $careUnit->id, 404);
$validated = $this->validatedHandover($request);
$docs->completeHandover($wardHandover, $this->ownerRef($request), $this->actorRef($request), $validated);
return redirect()
->route('care.care-units.handovers', $careUnit)
->with('success', 'Handover completed.');
}
/**
* @return array<string, mixed>
*/
protected function validatedHandover(Request $request): array
{
$validated = $request->validate([
'from_shift' => ['nullable', 'string', Rule::in(array_keys(config('care.staff_shift_codes')))],
'to_shift' => ['nullable', 'string', Rule::in(array_keys(config('care.staff_shift_codes')))],
'received_by' => ['nullable', 'string', 'max:255'],
'situation' => ['nullable', 'string', 'max:5000'],
'background' => ['nullable', 'string', 'max:5000'],
'assessment' => ['nullable', 'string', 'max:5000'],
'recommendation' => ['nullable', 'string', 'max:5000'],
'patient_summaries' => ['nullable', 'array'],
'patient_summaries.*.visit_id' => ['nullable', 'integer'],
'patient_summaries.*.patient_name' => ['nullable', 'string', 'max:255'],
'patient_summaries.*.bed' => ['nullable', 'string', 'max:100'],
'patient_summaries.*.note' => ['nullable', 'string', 'max:2000'],
]);
return $validated;
}
}
+68
View File
@@ -0,0 +1,68 @@
<?php
namespace App\Models;
use App\Models\Concerns\BelongsToOwner;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class MarAdministration extends Model
{
use BelongsToOwner;
public const STATUS_GIVEN = 'given';
public const STATUS_HELD = 'held';
public const STATUS_REFUSED = 'refused';
public const STATUS_MISSED = 'missed';
protected $table = 'care_mar_administrations';
protected $fillable = [
'owner_ref',
'organization_id',
'mar_order_id',
'visit_id',
'patient_id',
'care_unit_id',
'scheduled_for',
'recorded_at',
'status',
'dose_given',
'route',
'administered_by',
'witness_by',
'reason',
'notes',
];
protected function casts(): array
{
return [
'scheduled_for' => 'datetime',
'recorded_at' => 'datetime',
];
}
public function order(): BelongsTo
{
return $this->belongsTo(MarOrder::class, 'mar_order_id');
}
public function visit(): BelongsTo
{
return $this->belongsTo(Visit::class, 'visit_id');
}
public function patient(): BelongsTo
{
return $this->belongsTo(Patient::class, 'patient_id');
}
public function careUnit(): BelongsTo
{
return $this->belongsTo(CareUnit::class, 'care_unit_id');
}
}
+76
View File
@@ -0,0 +1,76 @@
<?php
namespace App\Models;
use App\Models\Concerns\BelongsToOwner;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
class MarOrder extends Model
{
use BelongsToOwner, SoftDeletes;
public const STATUS_ACTIVE = 'active';
public const STATUS_PAUSED = 'paused';
public const STATUS_STOPPED = 'stopped';
protected $table = 'care_mar_orders';
protected $fillable = [
'owner_ref',
'organization_id',
'visit_id',
'patient_id',
'prescription_id',
'prescription_item_id',
'drug_name',
'dosage',
'route',
'frequency_code',
'times_of_day',
'is_prn',
'status',
'starts_at',
'ends_at',
'instructions',
];
protected function casts(): array
{
return [
'times_of_day' => 'array',
'is_prn' => 'boolean',
'starts_at' => 'datetime',
'ends_at' => 'datetime',
];
}
public function visit(): BelongsTo
{
return $this->belongsTo(Visit::class, 'visit_id');
}
public function patient(): BelongsTo
{
return $this->belongsTo(Patient::class, 'patient_id');
}
public function prescription(): BelongsTo
{
return $this->belongsTo(Prescription::class, 'prescription_id');
}
public function prescriptionItem(): BelongsTo
{
return $this->belongsTo(PrescriptionItem::class, 'prescription_item_id');
}
public function administrations(): HasMany
{
return $this->hasMany(MarAdministration::class, 'mar_order_id')->orderByDesc('recorded_at');
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
namespace App\Models;
use App\Models\Concerns\BelongsToOwner;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
class NursingNote extends Model
{
use BelongsToOwner, SoftDeletes;
protected $table = 'care_nursing_notes';
protected $fillable = [
'owner_ref',
'organization_id',
'visit_id',
'patient_id',
'care_unit_id',
'note_type',
'shift_code',
'body',
'recorded_by',
'recorded_at',
];
protected function casts(): array
{
return [
'recorded_at' => 'datetime',
];
}
public function visit(): BelongsTo
{
return $this->belongsTo(Visit::class, 'visit_id');
}
public function patient(): BelongsTo
{
return $this->belongsTo(Patient::class, 'patient_id');
}
public function careUnit(): BelongsTo
{
return $this->belongsTo(CareUnit::class, 'care_unit_id');
}
}
+54
View File
@@ -0,0 +1,54 @@
<?php
namespace App\Models;
use App\Models\Concerns\BelongsToOwner;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
class WardHandover extends Model
{
use BelongsToOwner, SoftDeletes;
public const STATUS_DRAFT = 'draft';
public const STATUS_COMPLETED = 'completed';
protected $table = 'care_ward_handovers';
protected $fillable = [
'owner_ref',
'organization_id',
'care_unit_id',
'from_shift',
'to_shift',
'handed_over_at',
'handed_over_by',
'received_by',
'situation',
'background',
'assessment',
'recommendation',
'patient_summaries',
'status',
];
protected function casts(): array
{
return [
'handed_over_at' => 'datetime',
'patient_summaries' => 'array',
];
}
public function careUnit(): BelongsTo
{
return $this->belongsTo(CareUnit::class, 'care_unit_id');
}
public function organization(): BelongsTo
{
return $this->belongsTo(Organization::class, 'organization_id');
}
}
+9
View File
@@ -584,10 +584,19 @@ class CarePermissions
if (in_array('vitals.manage', $abilities, true)) {
$abilities[] = 'inpatient.placement.view';
$abilities[] = 'inpatient.placement.manage';
$abilities[] = 'mar.view';
$abilities[] = 'mar.administer';
$abilities[] = 'nursing.notes.view';
$abilities[] = 'nursing.notes.manage';
$abilities[] = 'nursing.handover.view';
$abilities[] = 'nursing.handover.manage';
}
if (in_array('analytics.department.view', $abilities, true)) {
$abilities[] = 'inpatient.placement.view';
$abilities[] = 'mar.view';
$abilities[] = 'nursing.notes.view';
$abilities[] = 'nursing.handover.view';
}
return array_values(array_unique($abilities));
+339
View File
@@ -0,0 +1,339 @@
<?php
namespace App\Services\Care;
use App\Models\CareUnit;
use App\Models\MarAdministration;
use App\Models\MarOrder;
use App\Models\Prescription;
use App\Models\PrescriptionItem;
use App\Models\Visit;
use Carbon\Carbon;
use Carbon\CarbonInterface;
use Illuminate\Support\Collection;
use Illuminate\Validation\ValidationException;
class MarService
{
/**
* Default clock times by frequency code.
*
* @var array<string, list<string>>
*/
protected array $defaultTimes = [
'od' => ['08:00'],
'bd' => ['08:00', '20:00'],
'tds' => ['08:00', '14:00', '20:00'],
'qds' => ['06:00', '12:00', '18:00', '22:00'],
'q4h' => ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00'],
'q6h' => ['00:00', '06:00', '12:00', '18:00'],
'q8h' => ['06:00', '14:00', '22:00'],
'prn' => [],
'stat' => [],
'custom' => ['08:00'],
];
/**
* Sync MAR orders from active/dispensed prescriptions on a visit.
*
* @return Collection<int, MarOrder>
*/
public function syncOrdersForVisit(Visit $visit, string $ownerRef): Collection
{
$prescriptions = Prescription::owned($ownerRef)
->where('visit_id', $visit->id)
->whereIn('status', [Prescription::STATUS_ACTIVE, Prescription::STATUS_DISPENSED])
->with('items')
->get();
foreach ($prescriptions as $prescription) {
foreach ($prescription->items as $item) {
if ($item->is_procedure) {
continue;
}
$this->upsertOrderFromItem($visit, $prescription, $item, $ownerRef);
}
}
return MarOrder::owned($ownerRef)
->where('visit_id', $visit->id)
->where('status', MarOrder::STATUS_ACTIVE)
->orderBy('drug_name')
->get();
}
public function upsertOrderFromItem(
Visit $visit,
Prescription $prescription,
PrescriptionItem $item,
string $ownerRef,
?string $frequencyCode = null,
): MarOrder {
$parsed = $this->parseFrequency((string) ($item->frequency ?? ''), $frequencyCode);
return MarOrder::query()->updateOrCreate(
['prescription_item_id' => $item->id],
[
'owner_ref' => $ownerRef,
'organization_id' => $visit->organization_id,
'visit_id' => $visit->id,
'patient_id' => $visit->patient_id,
'prescription_id' => $prescription->id,
'drug_name' => $item->name,
'dosage' => $item->dosage,
'route' => $item->route,
'frequency_code' => $parsed['code'],
'times_of_day' => $parsed['times'],
'is_prn' => $parsed['is_prn'],
'status' => MarOrder::STATUS_ACTIVE,
'starts_at' => $visit->placed_at ?? $visit->checked_in_at ?? now(),
'instructions' => $item->instructions,
],
);
}
/**
* Due / overdue / PRN slots for placed patients on a care unit for a calendar day.
*
* @return list<array<string, mixed>>
*/
public function unitRoundBoard(CareUnit $unit, string $ownerRef, ?CarbonInterface $day = null): array
{
$day = Carbon::parse($day ?? now())->startOfDay();
$visits = Visit::owned($ownerRef)
->where('organization_id', $unit->organization_id)
->where('care_unit_id', $unit->id)
->whereIn('status', [Visit::STATUS_OPEN, Visit::STATUS_IN_PROGRESS])
->with(['patient', 'bed'])
->get();
$rows = [];
foreach ($visits as $visit) {
$orders = $this->syncOrdersForVisit($visit, $ownerRef);
foreach ($orders as $order) {
foreach ($this->dueSlotsForOrder($order, $day) as $slot) {
$rows[] = $slot + [
'visit' => $visit,
'patient' => $visit->patient,
'bed' => $visit->bed,
'order' => $order,
];
}
}
}
usort($rows, function (array $a, array $b) {
$aTime = $a['scheduled_for']?->timestamp ?? PHP_INT_MAX;
$bTime = $b['scheduled_for']?->timestamp ?? PHP_INT_MAX;
if ($aTime === $bTime) {
return strcmp((string) ($a['patient']?->fullName() ?? ''), (string) ($b['patient']?->fullName() ?? ''));
}
return $aTime <=> $bTime;
});
return $rows;
}
/**
* @return list<array{scheduled_for: ?Carbon, state: string, administration: ?MarAdministration}>
*/
public function dueSlotsForOrder(MarOrder $order, CarbonInterface $day): array
{
$day = Carbon::parse($day)->startOfDay();
$end = $day->copy()->endOfDay();
if ($order->status !== MarOrder::STATUS_ACTIVE) {
return [];
}
if ($order->starts_at && $order->starts_at->gt($end)) {
return [];
}
if ($order->ends_at && $order->ends_at->lt($day)) {
return [];
}
$existing = MarAdministration::query()
->where('mar_order_id', $order->id)
->where(function ($q) use ($day, $end) {
$q->whereBetween('scheduled_for', [$day, $end])
->orWhere(function ($q2) use ($day, $end) {
$q2->whereNull('scheduled_for')
->whereBetween('recorded_at', [$day, $end]);
});
})
->get();
if ($order->is_prn || $order->frequency_code === 'prn') {
$givenToday = $existing->where('status', MarAdministration::STATUS_GIVEN);
return [[
'scheduled_for' => null,
'state' => $givenToday->isNotEmpty() ? 'prn_given' : 'prn_due',
'administration' => $givenToday->sortByDesc('recorded_at')->first(),
]];
}
if ($order->frequency_code === 'stat') {
$admin = $existing->first();
return [[
'scheduled_for' => $order->starts_at ?? $day->copy()->setTime(8, 0),
'state' => $admin ? $admin->status : 'due',
'administration' => $admin,
]];
}
$times = $order->times_of_day ?: ($this->defaultTimes[$order->frequency_code] ?? ['08:00']);
$slots = [];
foreach ($times as $time) {
[$h, $m] = array_map('intval', explode(':', $time) + [0, 0]);
$scheduled = $day->copy()->setTime($h, $m);
if ($order->starts_at && $scheduled->lt($order->starts_at)) {
continue;
}
$admin = $existing->first(function (MarAdministration $a) use ($scheduled) {
return $a->scheduled_for && $a->scheduled_for->equalTo($scheduled);
});
$state = 'due';
if ($admin) {
$state = $admin->status;
} elseif ($scheduled->lt(now()->subMinutes(30))) {
$state = 'overdue';
}
$slots[] = [
'scheduled_for' => $scheduled,
'state' => $state,
'administration' => $admin,
];
}
return $slots;
}
public function recordAdministration(
MarOrder $order,
string $status,
string $ownerRef,
?string $actorRef,
?CarbonInterface $scheduledFor = null,
?string $doseGiven = null,
?string $route = null,
?string $witnessBy = null,
?string $reason = null,
?string $notes = null,
?int $careUnitId = null,
): MarAdministration {
if (! in_array($status, [
MarAdministration::STATUS_GIVEN,
MarAdministration::STATUS_HELD,
MarAdministration::STATUS_REFUSED,
MarAdministration::STATUS_MISSED,
], true)) {
throw ValidationException::withMessages(['status' => 'Invalid MAR status.']);
}
if ($order->status !== MarOrder::STATUS_ACTIVE) {
throw ValidationException::withMessages(['mar_order_id' => 'This MAR order is not active.']);
}
if (in_array($status, [MarAdministration::STATUS_HELD, MarAdministration::STATUS_REFUSED, MarAdministration::STATUS_MISSED], true)
&& blank($reason) && blank($notes)) {
throw ValidationException::withMessages([
'reason' => 'Provide a reason when holding, refusing, or marking missed.',
]);
}
$visit = $order->visit ?? Visit::query()->findOrFail($order->visit_id);
if ($scheduledFor && ! $order->is_prn) {
$duplicate = MarAdministration::query()
->where('mar_order_id', $order->id)
->where('scheduled_for', $scheduledFor)
->exists();
if ($duplicate) {
throw ValidationException::withMessages([
'scheduled_for' => 'This dose slot is already recorded.',
]);
}
}
$admin = MarAdministration::create([
'owner_ref' => $ownerRef,
'organization_id' => $order->organization_id,
'mar_order_id' => $order->id,
'visit_id' => $order->visit_id,
'patient_id' => $order->patient_id,
'care_unit_id' => $careUnitId ?? $visit->care_unit_id,
'scheduled_for' => $scheduledFor,
'recorded_at' => now(),
'status' => $status,
'dose_given' => $doseGiven ?? $order->dosage,
'route' => $route ?? $order->route,
'administered_by' => $actorRef,
'witness_by' => $witnessBy,
'reason' => $reason,
'notes' => $notes,
]);
AuditLogger::record(
$ownerRef,
'mar.'.$status,
$order->organization_id,
$actorRef,
MarAdministration::class,
$admin->id,
['mar_order_id' => $order->id, 'visit_id' => $order->visit_id],
);
return $admin;
}
/**
* @return array{code: string, times: list<string>, is_prn: bool}
*/
public function parseFrequency(string $frequency, ?string $override = null): array
{
if ($override && isset($this->defaultTimes[$override])) {
return [
'code' => $override,
'times' => $this->defaultTimes[$override],
'is_prn' => $override === 'prn',
];
}
$raw = strtolower(trim($frequency));
$map = [
'od' => 'od', 'once daily' => 'od', 'daily' => 'od', 'once a day' => 'od', '1x' => 'od',
'bd' => 'bd', 'bid' => 'bd', 'twice daily' => 'bd', 'twice a day' => 'bd', '2x' => 'bd',
'tds' => 'tds', 'tid' => 'tds', 'three times' => 'tds', '3x' => 'tds',
'qds' => 'qds', 'qid' => 'qds', 'four times' => 'qds', '4x' => 'qds',
'q4h' => 'q4h', 'every 4' => 'q4h',
'q6h' => 'q6h', 'every 6' => 'q6h',
'q8h' => 'q8h', 'every 8' => 'q8h',
'prn' => 'prn', 'as needed' => 'prn', 'when required' => 'prn',
'stat' => 'stat', 'immediately' => 'stat', 'now' => 'stat',
];
foreach ($map as $needle => $code) {
if ($raw === $needle || str_contains($raw, $needle)) {
return [
'code' => $code,
'times' => $this->defaultTimes[$code],
'is_prn' => $code === 'prn',
];
}
}
return [
'code' => 'od',
'times' => $this->defaultTimes['od'],
'is_prn' => false,
];
}
}
@@ -0,0 +1,165 @@
<?php
namespace App\Services\Care;
use App\Models\CareUnit;
use App\Models\NursingNote;
use App\Models\Visit;
use App\Models\WardHandover;
use Illuminate\Support\Collection;
class NursingDocumentationService
{
public function addNote(
Visit $visit,
string $ownerRef,
?string $actorRef,
string $body,
string $noteType = 'progress',
?string $shiftCode = null,
?int $careUnitId = null,
): NursingNote {
$note = NursingNote::create([
'owner_ref' => $ownerRef,
'organization_id' => $visit->organization_id,
'visit_id' => $visit->id,
'patient_id' => $visit->patient_id,
'care_unit_id' => $careUnitId ?? $visit->care_unit_id,
'note_type' => $noteType,
'shift_code' => $shiftCode,
'body' => $body,
'recorded_by' => $actorRef,
'recorded_at' => now(),
]);
AuditLogger::record(
$ownerRef,
'nursing_note.created',
$visit->organization_id,
$actorRef,
NursingNote::class,
$note->id,
);
return $note;
}
/**
* @return Collection<int, NursingNote>
*/
public function notesForUnit(CareUnit $unit, string $ownerRef, int $limit = 50): Collection
{
return NursingNote::owned($ownerRef)
->where('care_unit_id', $unit->id)
->with(['patient', 'visit'])
->orderByDesc('recorded_at')
->limit($limit)
->get();
}
/**
* @return Collection<int, NursingNote>
*/
public function notesForVisit(Visit $visit, string $ownerRef, int $limit = 50): Collection
{
return NursingNote::owned($ownerRef)
->where('visit_id', $visit->id)
->orderByDesc('recorded_at')
->limit($limit)
->get();
}
/**
* @param array<string, mixed> $data
*/
public function createHandover(
CareUnit $unit,
string $ownerRef,
?string $actorRef,
array $data,
bool $complete = false,
): WardHandover {
$handover = WardHandover::create([
'owner_ref' => $ownerRef,
'organization_id' => $unit->organization_id,
'care_unit_id' => $unit->id,
'from_shift' => $data['from_shift'] ?? null,
'to_shift' => $data['to_shift'] ?? null,
'handed_over_at' => $complete ? now() : ($data['handed_over_at'] ?? null),
'handed_over_by' => $actorRef,
'received_by' => $data['received_by'] ?? null,
'situation' => $data['situation'] ?? null,
'background' => $data['background'] ?? null,
'assessment' => $data['assessment'] ?? null,
'recommendation' => $data['recommendation'] ?? null,
'patient_summaries' => $data['patient_summaries'] ?? $this->defaultPatientSummaries($unit, $ownerRef),
'status' => $complete ? WardHandover::STATUS_COMPLETED : WardHandover::STATUS_DRAFT,
]);
AuditLogger::record(
$ownerRef,
$complete ? 'ward_handover.completed' : 'ward_handover.created',
$unit->organization_id,
$actorRef,
WardHandover::class,
$handover->id,
);
return $handover;
}
/**
* @param array<string, mixed> $data
*/
public function completeHandover(
WardHandover $handover,
string $ownerRef,
?string $actorRef,
array $data = [],
): WardHandover {
$handover->update([
'from_shift' => $data['from_shift'] ?? $handover->from_shift,
'to_shift' => $data['to_shift'] ?? $handover->to_shift,
'received_by' => $data['received_by'] ?? $handover->received_by,
'situation' => $data['situation'] ?? $handover->situation,
'background' => $data['background'] ?? $handover->background,
'assessment' => $data['assessment'] ?? $handover->assessment,
'recommendation' => $data['recommendation'] ?? $handover->recommendation,
'patient_summaries' => $data['patient_summaries'] ?? $handover->patient_summaries,
'handed_over_at' => now(),
'handed_over_by' => $actorRef ?? $handover->handed_over_by,
'status' => WardHandover::STATUS_COMPLETED,
]);
AuditLogger::record(
$ownerRef,
'ward_handover.completed',
$handover->organization_id,
$actorRef,
WardHandover::class,
$handover->id,
);
return $handover->fresh();
}
/**
* @return list<array{visit_id: int, patient_name: string, bed: ?string, note: string}>
*/
public function defaultPatientSummaries(CareUnit $unit, string $ownerRef): array
{
$visits = Visit::owned($ownerRef)
->where('care_unit_id', $unit->id)
->whereIn('status', [Visit::STATUS_OPEN, Visit::STATUS_IN_PROGRESS])
->with(['patient', 'bed'])
->orderBy('placed_at')
->get();
return $visits->map(fn (Visit $visit) => [
'visit_id' => $visit->id,
'patient_name' => $visit->patient?->fullName() ?? 'Unknown',
'bed' => $visit->bed?->label,
'note' => '',
])->all();
}
}