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(),
@@ -0,0 +1,52 @@
<?php
namespace App\Http\Middleware;
use App\Services\Care\DeviceService;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class AuthenticateCareDevice
{
public function __construct(
protected DeviceService $devices,
) {}
public function handle(Request $request, Closure $next): Response
{
$token = $this->extractToken($request);
abort_unless(is_string($token) && $token !== '', 401, 'Device token required.');
$device = $this->devices->findByToken($token);
abort_unless($device, 401, 'Invalid device token.');
$request->attributes->set('care.device', $device);
return $next($request);
}
protected function extractToken(Request $request): ?string
{
$header = $request->header('X-Care-Device-Token');
if (is_string($header) && $header !== '') {
return $header;
}
// Compatibility with Frontdesk-style header.
$legacy = $request->header('X-Device-Token');
if (is_string($legacy) && $legacy !== '') {
return $legacy;
}
$bearer = $request->bearerToken();
if (is_string($bearer) && $bearer !== '') {
return $bearer;
}
$input = $request->input('token');
return is_string($input) && $input !== '' ? $input : null;
}
}
+80
View File
@@ -0,0 +1,80 @@
<?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 Device extends Model
{
use BelongsToOwner, SoftDeletes;
public const STATUS_ACTIVE = 'active';
public const STATUS_OFFLINE = 'offline';
public const STATUS_DISABLED = 'disabled';
public const MODE_BROWSER_WEDGE = 'browser_wedge';
public const MODE_AGENT = 'agent';
public const MODE_WEB_BLUETOOTH = 'web_bluetooth';
public const MODE_MANUAL = 'manual';
protected $table = 'care_devices';
protected $fillable = [
'owner_ref', 'organization_id', 'branch_id', 'name', 'type',
'status', 'connection_mode', 'device_token_hash', 'last_seen_at', 'metadata',
];
protected $hidden = [
'device_token_hash',
];
protected function casts(): array
{
return [
'metadata' => 'array',
'last_seen_at' => 'datetime',
];
}
public function organization(): BelongsTo
{
return $this->belongsTo(Organization::class, 'organization_id');
}
public function branch(): BelongsTo
{
return $this->belongsTo(Branch::class, 'branch_id');
}
public function vitalSigns(): HasMany
{
return $this->hasMany(VitalSign::class, 'device_id');
}
public function isOnline(int $staleMinutes = 10): bool
{
return $this->status === self::STATUS_ACTIVE
&& $this->last_seen_at
&& $this->last_seen_at->gte(now()->subMinutes($staleMinutes));
}
public function requiresAgent(): bool
{
return $this->connection_mode === self::MODE_AGENT
|| in_array($this->type, config('care.device_agent_types', []), true);
}
public function hasToken(): bool
{
return filled($this->device_token_hash);
}
}
+13 -1
View File
@@ -12,10 +12,16 @@ class VitalSign extends Model
protected $table = 'care_vital_signs';
public const SOURCE_MANUAL = 'manual';
public const SOURCE_DEVICE = 'device';
public const SOURCE_IMPORT = 'import';
protected $fillable = [
'owner_ref', 'consultation_id', 'bp_systolic', 'bp_diastolic', 'pulse',
'temperature', 'weight_kg', 'height_cm', 'spo2', 'respiratory_rate',
'recorded_by', 'recorded_at',
'recorded_by', 'recorded_at', 'source', 'device_id', 'raw_payload',
];
protected function casts(): array
@@ -25,6 +31,7 @@ class VitalSign extends Model
'weight_kg' => 'decimal:2',
'height_cm' => 'decimal:1',
'recorded_at' => 'datetime',
'raw_payload' => 'array',
];
}
@@ -32,4 +39,9 @@ class VitalSign extends Model
{
return $this->belongsTo(Consultation::class, 'consultation_id');
}
public function device(): BelongsTo
{
return $this->belongsTo(Device::class, 'device_id');
}
}
+12
View File
@@ -7,7 +7,10 @@ use App\Listeners\PlatformServiceEventListener;
use App\Models\User;
use App\Services\Care\OrganizationResolver;
use App\Services\Care\PlanService;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
@@ -22,6 +25,15 @@ class AppServiceProvider extends ServiceProvider
{
Event::listen(ServiceEventOccurred::class, PlatformServiceEventListener::class);
RateLimiter::for('care-device', function (Request $request) {
$token = $request->header('X-Care-Device-Token')
?? $request->header('X-Device-Token')
?? $request->bearerToken()
?? $request->ip();
return Limit::perMinute(60)->by((string) $token);
});
View::composer([
'partials.sidebar',
'partials.topbar-desktop-widgets',
+1
View File
@@ -51,6 +51,7 @@ class CarePermissions
'admin.practitioners.view', 'admin.practitioners.manage',
'admin.members.view', 'admin.members.manage',
'settings.view', 'settings.manage',
'devices.view', 'devices.manage',
'audit.view', 'audit.export',
];
+19 -5
View File
@@ -97,14 +97,25 @@ class ConsultationService
/**
* @param array<string, mixed> $vitals
* @param array{source?: string, device_id?: int|null, raw_payload?: array<string, mixed>|null} $provenance
*/
protected function saveVitals(Consultation $consultation, string $ownerRef, array $vitals, ?string $actorRef): void
{
if (empty(array_filter($vitals))) {
return;
public function saveVitals(
Consultation $consultation,
string $ownerRef,
array $vitals,
?string $actorRef = null,
array $provenance = [],
): ?VitalSign {
$numeric = collect($vitals)->only([
'bp_systolic', 'bp_diastolic', 'pulse', 'temperature',
'weight_kg', 'height_cm', 'spo2', 'respiratory_rate',
])->filter(fn ($v) => $v !== null && $v !== '')->all();
if ($numeric === []) {
return null;
}
VitalSign::create([
return VitalSign::create([
'owner_ref' => $ownerRef,
'consultation_id' => $consultation->id,
'bp_systolic' => $vitals['bp_systolic'] ?? null,
@@ -117,6 +128,9 @@ class ConsultationService
'respiratory_rate' => $vitals['respiratory_rate'] ?? null,
'recorded_by' => $actorRef,
'recorded_at' => now(),
'source' => $provenance['source'] ?? VitalSign::SOURCE_MANUAL,
'device_id' => $provenance['device_id'] ?? null,
'raw_payload' => $provenance['raw_payload'] ?? null,
]);
}
+55
View File
@@ -13,6 +13,7 @@ use App\Models\BillLineItem;
use App\Models\Branch;
use App\Models\Consultation;
use App\Models\Department;
use App\Models\Device;
use App\Models\Drug;
use App\Models\DrugBatch;
use App\Models\InvestigationRequest;
@@ -122,6 +123,7 @@ class DemoTenantSeeder
$ownerRef,
$volumes,
);
$this->seedDevices($organization, $branches, $ownerRef);
}
if ($volumes['assessments'] > 0) {
@@ -196,6 +198,8 @@ class DemoTenantSeeder
DB::table('care_vital_signs')->where('owner_ref', $ownerRef)->delete();
DB::table('care_consultations')->where('owner_ref', $ownerRef)->delete();
DB::table('care_devices')->where('owner_ref', $ownerRef)->delete();
DB::table('care_appointments')->where('owner_ref', $ownerRef)->delete();
DB::table('care_visits')->where('owner_ref', $ownerRef)->delete();
@@ -678,6 +682,57 @@ class DemoTenantSeeder
* @param list<Patient> $patients
* @param array<string, mixed> $volumes
*/
/**
* Demo hardware inventory: browser wedge scanner + agent thermometer per branch (Pro+).
*
* @param list<Branch> $branches
*/
private function seedDevices(Organization $organization, array $branches, string $ownerRef): void
{
$deviceService = app(DeviceService::class);
foreach ($branches as $i => $branch) {
Device::withTrashed()->updateOrCreate(
[
'organization_id' => $organization->id,
'branch_id' => $branch->id,
'name' => 'Demo barcode scanner',
],
[
'owner_ref' => $ownerRef,
'type' => 'barcode_scanner',
'connection_mode' => Device::MODE_BROWSER_WEDGE,
'status' => Device::STATUS_OFFLINE,
'device_token_hash' => null,
'metadata' => ['demo' => true],
'deleted_at' => null,
],
);
$thermo = Device::withTrashed()->updateOrCreate(
[
'organization_id' => $organization->id,
'branch_id' => $branch->id,
'name' => 'Demo thermometer',
],
[
'owner_ref' => $ownerRef,
'type' => 'thermometer',
'connection_mode' => Device::MODE_AGENT,
'status' => Device::STATUS_OFFLINE,
'metadata' => ['demo' => true, 'note' => 'Token issued on first seed only if missing'],
'deleted_at' => null,
],
);
if (! $thermo->device_token_hash) {
// Deterministic demo token so sales can reuse docs examples after reseed.
$plain = 'demo-care-device-'.$organization->id.'-'.$branch->id.'-thermo';
$thermo->update(['device_token_hash' => $deviceService->hashToken($plain)]);
}
}
}
private function seedPaidModules(
Organization $organization,
array $branches,
+99
View File
@@ -0,0 +1,99 @@
<?php
namespace App\Services\Care;
use App\Models\Device;
use App\Models\Organization;
use Illuminate\Support\Str;
class DeviceService
{
public function generateToken(): string
{
return Str::random(48);
}
public function hashToken(string $token): string
{
return hash('sha256', $token);
}
public function findByToken(string $token): ?Device
{
if ($token === '') {
return null;
}
return Device::query()
->where('device_token_hash', $this->hashToken($token))
->where('status', '!=', Device::STATUS_DISABLED)
->first();
}
public function issueToken(Device $device): string
{
$plain = $this->generateToken();
$device->update(['device_token_hash' => $this->hashToken($plain)]);
return $plain;
}
public function revokeToken(Device $device): Device
{
$device->update(['device_token_hash' => null]);
return $device->fresh();
}
public function recordHeartbeat(Device $device, ?array $metadata = null): Device
{
$payload = [
'status' => Device::STATUS_ACTIVE,
'last_seen_at' => now(),
];
if ($metadata !== null) {
$payload['metadata'] = array_merge($device->metadata ?? [], [
'agent' => $metadata,
]);
}
$device->update($payload);
return $device->fresh();
}
public function defaultConnectionMode(string $type): string
{
return match ($type) {
'barcode_scanner', 'qr_scanner' => Device::MODE_BROWSER_WEDGE,
'badge_printer' => Device::MODE_MANUAL,
'thermometer', 'bp_monitor', 'pulse_ox', 'weight_scale', 'lab_analyzer', 'agent' => Device::MODE_AGENT,
default => Device::MODE_MANUAL,
};
}
public function typeRequiresPro(string $type): bool
{
return in_array($type, config('care.device_agent_types', []), true);
}
public function canRegisterType(Organization $organization, string $type, PlanService $plans): bool
{
if (! $this->typeRequiresPro($type)) {
return true;
}
return $plans->hasPaidPlan($organization);
}
public function connectionHint(string $type, string $mode): string
{
return match ($mode) {
Device::MODE_BROWSER_WEDGE => 'Works in the browser today as a USB keyboard wedge (scan into the focused field). No local agent required.',
Device::MODE_AGENT => 'Needs the Care Device Agent on a local machine (serial / BLE / vendor SDK). Browser alone cannot talk to this hardware.',
Device::MODE_WEB_BLUETOOTH => 'Experimental Web Bluetooth path — not broadly supported; prefer the local agent for clinical devices.',
default => 'Manual / inventory only — no automated capture path configured.',
};
}
}
+34
View File
@@ -72,6 +72,40 @@ class PatientService
return $query->paginate((int) ($filters['per_page'] ?? 20))->withQueryString();
}
/**
* Exact patient_number match first, then fall back to broad search (first hit).
*/
public function findByScanCode(string $ownerRef, int $organizationId, string $code, ?int $branchId = null): ?Patient
{
$code = trim($code);
if ($code === '') {
return null;
}
$base = $this->queryForOrganization($ownerRef, $organizationId)
->when($branchId !== null, fn ($q) => $q->where('branch_id', $branchId));
$exact = (clone $base)->where('patient_number', $code)->first();
if ($exact) {
return $exact;
}
// Case-insensitive exact patient number.
$ci = (clone $base)->whereRaw('lower(patient_number) = ?', [strtolower($code)])->first();
if ($ci) {
return $ci;
}
return (clone $base)
->where(function (Builder $inner) use ($code) {
$inner->where('patient_number', 'like', "%{$code}%")
->orWhere('national_id', $code)
->orWhere('phone', 'like', "%{$code}%");
})
->orderByDesc('created_at')
->first();
}
/**
* @param array<string, mixed> $data
*/