Add clinical device registry, browser wedge scan, and local agent API.
Deploy Ladill Care / deploy (push) Successful in 1m39s

Branch-scoped Care devices with hashed agent tokens, patient barcode lookup/labels, and provenance-aware vitals from a minimal device agent (Pro for agent hardware; wedge free).

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
isaacclad
2026-07-17 14:28:46 +00:00
co-authored by Cursor
parent 1da90203e8
commit e0a7a64d38
37 changed files with 1970 additions and 10 deletions
@@ -0,0 +1,165 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Consultation;
use App\Models\Device;
use App\Models\InvestigationRequest;
use App\Models\Visit;
use App\Models\VitalSign;
use App\Services\Care\ConsultationService;
use App\Services\Care\DeviceService;
use App\Services\Care\InvestigationService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class DeviceAgentController extends Controller
{
public function __construct(
protected DeviceService $devices,
protected ConsultationService $consultations,
protected InvestigationService $investigations,
) {}
public function heartbeat(Request $request): JsonResponse
{
/** @var Device $device */
$device = $request->attributes->get('care.device');
$validated = $request->validate([
'agent_version' => ['nullable', 'string', 'max:50'],
'hostname' => ['nullable', 'string', 'max:255'],
'meta' => ['nullable', 'array'],
]);
$this->devices->recordHeartbeat($device, $validated);
return response()->json([
'status' => 'active',
'device' => [
'id' => $device->id,
'name' => $device->name,
'type' => $device->type,
'branch_id' => $device->branch_id,
],
'last_seen_at' => $device->fresh()->last_seen_at?->toIso8601String(),
]);
}
public function storeVitals(Request $request): JsonResponse
{
/** @var Device $device */
$device = $request->attributes->get('care.device');
$validated = $request->validate([
'consultation_uuid' => ['nullable', 'uuid'],
'visit_uuid' => ['nullable', 'uuid'],
'vitals' => ['required', 'array'],
'vitals.bp_systolic' => ['nullable', 'integer', 'min:40', 'max:300'],
'vitals.bp_diastolic' => ['nullable', 'integer', 'min:20', 'max:200'],
'vitals.pulse' => ['nullable', 'integer', 'min:20', 'max:300'],
'vitals.temperature' => ['nullable', 'numeric', 'min:30', 'max:45'],
'vitals.weight_kg' => ['nullable', 'numeric', 'min:0', 'max:500'],
'vitals.height_cm' => ['nullable', 'numeric', 'min:0', 'max:300'],
'vitals.spo2' => ['nullable', 'integer', 'min:50', 'max:100'],
'vitals.respiratory_rate' => ['nullable', 'integer', 'min:5', 'max:80'],
'raw' => ['nullable', 'array'],
]);
abort_unless(
filled($validated['consultation_uuid'] ?? null) || filled($validated['visit_uuid'] ?? null),
422,
'consultation_uuid or visit_uuid is required.',
);
$consultation = $this->resolveConsultation($device, $validated);
abort_unless($consultation, 404, 'Consultation not found for this device scope.');
$vital = $this->consultations->saveVitals(
$consultation,
$device->owner_ref,
$validated['vitals'],
'device:'.$device->id,
[
'source' => VitalSign::SOURCE_DEVICE,
'device_id' => $device->id,
'raw_payload' => $validated['raw'] ?? $request->all(),
],
);
$this->devices->recordHeartbeat($device);
return response()->json([
'vital_sign_id' => $vital?->id,
'consultation_uuid' => $consultation->uuid,
'source' => VitalSign::SOURCE_DEVICE,
'device_id' => $device->id,
], 201);
}
public function collectSample(Request $request): JsonResponse
{
/** @var Device $device */
$device = $request->attributes->get('care.device');
$validated = $request->validate([
'investigation_uuid' => ['required', 'uuid'],
'sample_barcode' => ['nullable', 'string', 'max:100'],
]);
$investigation = InvestigationRequest::query()
->where('uuid', $validated['investigation_uuid'])
->where('organization_id', $device->organization_id)
->when($device->branch_id, fn ($q) => $q->where('branch_id', $device->branch_id))
->first();
abort_unless($investigation, 404, 'Investigation not found for this device scope.');
$updated = $this->investigations->collectSample(
$investigation,
$device->owner_ref,
$validated['sample_barcode'] ?? null,
'device:'.$device->id,
);
$this->devices->recordHeartbeat($device);
return response()->json([
'investigation_uuid' => $updated->uuid,
'status' => $updated->status,
'sample_barcode' => $updated->sample_barcode,
]);
}
/**
* @param array<string, mixed> $validated
*/
protected function resolveConsultation(Device $device, array $validated): ?Consultation
{
if (! empty($validated['consultation_uuid'])) {
return Consultation::query()
->where('uuid', $validated['consultation_uuid'])
->whereHas('visit', function ($q) use ($device) {
$q->where('organization_id', $device->organization_id)
->when($device->branch_id, fn ($inner) => $inner->where('branch_id', $device->branch_id));
})
->first();
}
$visit = Visit::query()
->where('uuid', $validated['visit_uuid'])
->where('organization_id', $device->organization_id)
->when($device->branch_id, fn ($q) => $q->where('branch_id', $device->branch_id))
->first();
if (! $visit) {
return null;
}
return Consultation::query()
->where('visit_id', $visit->id)
->orderByDesc('id')
->first();
}
}
@@ -0,0 +1,255 @@
<?php
namespace App\Http\Controllers\Care;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Models\Branch;
use App\Models\Device;
use App\Services\Care\DeviceService;
use App\Services\Care\OrganizationResolver;
use App\Services\Care\PlanService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
class DeviceController extends Controller
{
use ScopesToAccount;
public function __construct(
protected DeviceService $devices,
protected PlanService $plans,
) {}
public function index(Request $request): View
{
$this->authorizeAbility($request, 'devices.view');
$organization = $this->organization($request);
$branchScope = app(OrganizationResolver::class)->branchScope($this->member($request));
$query = Device::owned($this->ownerRef($request))
->where('organization_id', $organization->id)
->with('branch')
->when($branchScope, fn ($q) => $q->where('branch_id', $branchScope))
->orderBy('name');
$devices = (clone $query)->paginate(25);
$heroStats = [
'total' => (clone $query)->count(),
'online' => (clone $query)
->where('status', Device::STATUS_ACTIVE)
->where('last_seen_at', '>=', now()->subMinutes(10))
->count(),
'agent' => (clone $query)->where('connection_mode', Device::MODE_AGENT)->count(),
];
return view('care.devices.index', [
'organization' => $organization,
'devices' => $devices,
'deviceTypes' => config('care.device_types'),
'connectionModes' => config('care.device_connection_modes'),
'heroStats' => $heroStats,
'canManage' => app(\App\Services\Care\CarePermissions::class)
->can($this->member($request), 'devices.manage'),
'hasAgentDevices' => $this->plans->hasPaidPlan($organization),
]);
}
public function create(Request $request): View
{
$this->authorizeAbility($request, 'devices.manage');
$organization = $this->organization($request);
return view('care.devices.create', [
'organization' => $organization,
'deviceTypes' => config('care.device_types'),
'connectionModes' => config('care.device_connection_modes'),
'branches' => $this->branches($request, $organization->id),
'hasAgentDevices' => $this->plans->hasPaidPlan($organization),
'agentTypes' => config('care.device_agent_types'),
'defaultModes' => collect(config('care.device_types'))
->keys()
->mapWithKeys(fn ($type) => [$type => $this->devices->defaultConnectionMode($type)])
->all(),
]);
}
public function store(Request $request): RedirectResponse
{
$this->authorizeAbility($request, 'devices.manage');
$organization = $this->organization($request);
$validated = $this->validatedDevice($request, $organization);
if (! $this->devices->canRegisterType($organization, $validated['type'], $this->plans)) {
return back()->withInput()->with(
'error',
'Agent-connected clinical devices require Care Pro or Enterprise. USB barcode/QR scanners work on Free.',
);
}
$mode = $validated['connection_mode']
?? $this->devices->defaultConnectionMode($validated['type']);
$device = Device::create([
'owner_ref' => $this->ownerRef($request),
'organization_id' => $organization->id,
'branch_id' => $validated['branch_id'] ?? null,
'name' => $validated['name'],
'type' => $validated['type'],
'connection_mode' => $mode,
'status' => Device::STATUS_OFFLINE,
'metadata' => [],
]);
$plainToken = null;
if ($mode === Device::MODE_AGENT || in_array($validated['type'], config('care.device_agent_types', []), true)) {
$plainToken = $this->devices->issueToken($device);
}
$redirect = redirect()->route('care.devices.edit', $device)
->with('success', 'Device registered.');
if ($plainToken) {
$redirect->with('device_token', $plainToken);
}
return $redirect;
}
public function edit(Request $request, Device $device): View
{
$this->authorizeAbility($request, 'devices.manage');
$this->authorizeDevice($request, $device);
return view('care.devices.edit', [
'device' => $device,
'organization' => $this->organization($request),
'deviceTypes' => config('care.device_types'),
'connectionModes' => config('care.device_connection_modes'),
'deviceStatuses' => config('care.device_statuses'),
'branches' => $this->branches($request, $device->organization_id),
'hasAgentDevices' => $this->plans->hasPaidPlan($this->organization($request)),
'agentTypes' => config('care.device_agent_types'),
'connectionHint' => $this->devices->connectionHint($device->type, $device->connection_mode),
'plainToken' => session('device_token'),
]);
}
public function update(Request $request, Device $device): RedirectResponse
{
$this->authorizeAbility($request, 'devices.manage');
$this->authorizeDevice($request, $device);
$organization = $this->organization($request);
$validated = $this->validatedDevice($request, $organization, updating: true);
if (
isset($validated['type'])
&& $validated['type'] !== $device->type
&& ! $this->devices->canRegisterType($organization, $validated['type'], $this->plans)
) {
return back()->withInput()->with(
'error',
'Agent-connected clinical devices require Care Pro or Enterprise.',
);
}
$device->update([
'name' => $validated['name'],
'type' => $validated['type'],
'branch_id' => $validated['branch_id'] ?? null,
'connection_mode' => $validated['connection_mode']
?? $device->connection_mode
?? $this->devices->defaultConnectionMode($validated['type']),
'status' => $validated['status'] ?? $device->status,
]);
return redirect()->route('care.devices.index')->with('success', 'Device updated.');
}
public function destroy(Request $request, Device $device): RedirectResponse
{
$this->authorizeAbility($request, 'devices.manage');
$this->authorizeDevice($request, $device);
$device->delete();
return redirect()->route('care.devices.index')->with('success', 'Device removed.');
}
public function regenerateToken(Request $request, Device $device): RedirectResponse
{
$this->authorizeAbility($request, 'devices.manage');
$this->authorizeDevice($request, $device);
$plain = $this->devices->issueToken($device);
return back()
->with('success', 'Device token regenerated. Copy it now — it will not be shown again.')
->with('device_token', $plain);
}
public function revokeToken(Request $request, Device $device): RedirectResponse
{
$this->authorizeAbility($request, 'devices.manage');
$this->authorizeDevice($request, $device);
$this->devices->revokeToken($device);
return back()->with('success', 'Device token revoked.');
}
protected function authorizeDevice(Request $request, Device $device): void
{
$this->authorizeOwner($request, $device);
abort_unless($device->organization_id === $this->organization($request)->id, 404);
$branchId = app(OrganizationResolver::class)->branchScope($this->member($request));
if ($branchId !== null && $device->branch_id !== null && $device->branch_id !== $branchId) {
abort(404);
}
}
/**
* @return array<string, mixed>
*/
protected function validatedDevice(Request $request, $organization, bool $updating = false): array
{
$rules = [
'name' => ['required', 'string', 'max:255'],
'type' => ['required', 'string', 'in:'.implode(',', array_keys(config('care.device_types')))],
'branch_id' => ['nullable', 'integer', 'exists:care_branches,id'],
'connection_mode' => ['nullable', 'string', 'in:'.implode(',', array_keys(config('care.device_connection_modes')))],
];
if ($updating) {
$rules['status'] = ['nullable', 'string', 'in:'.implode(',', array_keys(config('care.device_statuses')))];
}
$validated = $request->validate($rules);
if (! empty($validated['branch_id'])) {
$ok = Branch::owned($this->ownerRef($request))
->where('organization_id', $organization->id)
->where('id', $validated['branch_id'])
->exists();
abort_unless($ok, 422);
}
return $validated;
}
/** @return \Illuminate\Database\Eloquent\Collection<int, Branch> */
protected function branches(Request $request, int $organizationId)
{
$branchScope = app(OrganizationResolver::class)->branchScope($this->member($request));
return Branch::owned($this->ownerRef($request))
->where('organization_id', $organizationId)
->where('is_active', true)
->when($branchScope, fn ($q) => $q->where('id', $branchScope))
->orderBy('name')
->get();
}
}
@@ -10,6 +10,7 @@ use App\Services\Care\CareFeatures;
use App\Services\Care\CarePermissions;
use App\Services\Care\OrganizationResolver;
use App\Services\Care\PatientService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
@@ -49,6 +50,58 @@ class PatientController extends Controller
return view('care.patients.index', compact('patients', 'organization', 'heroStats'));
}
public function scanLookup(Request $request): JsonResponse|RedirectResponse
{
$this->authorizeAbility($request, 'patients.view');
$organization = $this->organization($request);
$branchScope = app(OrganizationResolver::class)->branchScope($this->member($request));
$code = trim((string) $request->query('code', ''));
abort_unless($code !== '', 422, 'Scan code required.');
$patient = $this->patients->findByScanCode(
$this->ownerRef($request),
$organization->id,
$code,
$branchScope,
);
if ($request->expectsJson() || $request->wantsJson() || $request->ajax()) {
if (! $patient) {
return response()->json(['message' => 'No patient found for that barcode.'], 404);
}
return response()->json([
'patient' => [
'uuid' => $patient->uuid,
'patient_number' => $patient->patient_number,
'name' => $patient->fullName(),
'url' => route('care.patients.show', $patient),
],
]);
}
if (! $patient) {
return redirect()
->route('care.patients.index', ['q' => $code])
->with('error', 'No patient found for that barcode.');
}
return redirect()->route('care.patients.show', $patient);
}
public function label(Request $request, Patient $patient): View
{
$this->authorizeAbility($request, 'patients.view');
$this->authorizePatient($request, $patient);
return view('care.patients.label', [
'patient' => $patient,
'organization' => $this->organization($request),
'genders' => config('care.genders'),
]);
}
public function create(Request $request): View
{
$this->authorizeAbility($request, 'patients.manage');
@@ -54,7 +54,9 @@ class SettingsController extends Controller
'branchCount' => $branchCount,
'canViewBranches' => $permissions->can($member, 'admin.branches.view'),
'canViewTeam' => $permissions->can($member, 'admin.members.view'),
'canViewDevices' => $permissions->can($member, 'devices.view'),
'hasBranchesFeature' => $plans->hasFeature($organization, 'branches'),
'hasClinicalDevicesFeature' => $plans->hasFeature($organization, 'clinical_devices'),
'canUseQueueIntegration' => $plans->canUseQueueIntegration($organization),
'assessmentsEngineEnabled' => $careFeatures->enabled($organization, CareFeatures::ASSESSMENTS_ENGINE),
'messagingSmsReady' => $suiteSmsReady || $credential->hasValidSms(),