Allow explicit multi-branch practitioner assignment for telemedicine.
Deploy Ladill Care / deploy (push) Successful in 1m29s

Replace optional “All branches” with required branch checkboxes; doctors may switch only among assigned sites, never org-wide by default.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
isaacclad
2026-07-18 08:50:03 +00:00
co-authored by Cursor
parent d643687335
commit 899b08179e
17 changed files with 478 additions and 103 deletions
@@ -58,12 +58,20 @@ trait ScopesToAccount
protected function scopeToBranch(Request $request, Builder $query, string $column = 'branch_id'): Builder
{
$branchId = app(OrganizationResolver::class)->branchScope($this->member($request));
$allowed = app(OrganizationResolver::class)->allowedBranchIds($this->member($request));
if ($branchId !== null) {
$query->where($column, $branchId);
if ($allowed !== null) {
$query->whereIn($column, $allowed !== [] ? $allowed : [0]);
}
return $query;
}
protected function authorizeBranch(Request $request, ?int $branchId): void
{
abort_unless(
app(OrganizationResolver::class)->mayAccessBranch($this->member($request), $branchId),
404,
);
}
}
+17 -2
View File
@@ -12,6 +12,7 @@ use App\Services\Identity\IdentityTeamClient;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\View\View;
class MemberController extends Controller
@@ -83,12 +84,22 @@ class MemberController extends Controller
$validated = $request->validate([
'email' => ['required', 'email', 'max:255'],
'role' => ['required', 'string', 'in:'.implode(',', array_keys(config('care.roles')))],
'branch_id' => ['nullable', 'integer', 'exists:care_branches,id'],
'branch_id' => [
Rule::requiredIf(fn () => $request->input('role') === 'doctor'),
'nullable',
'integer',
'exists:care_branches,id',
],
'create_practitioner' => ['sometimes', 'boolean'],
'practitioner_name' => ['nullable', 'string', 'max:255'],
'specialty' => ['nullable', 'string', 'max:255'],
]);
if (! empty($validated['branch_id'])) {
$branch = Branch::owned($owner)->findOrFail($validated['branch_id']);
abort_unless($branch->organization_id === $organization->id, 404);
}
$email = strtolower(trim($validated['email']));
if ($email === strtolower((string) $request->user()->email)) {
@@ -125,7 +136,7 @@ class MemberController extends Controller
$createPractitioner = $request->boolean('create_practitioner', $validated['role'] === 'doctor');
if ($createPractitioner) {
$name = trim((string) ($validated['practitioner_name'] ?? '')) ?: Str::headline(Str::before($email, '@'));
Practitioner::query()->firstOrCreate(
$practitioner = Practitioner::query()->firstOrCreate(
[
'organization_id' => $organization->id,
'member_id' => $member->id,
@@ -139,6 +150,10 @@ class MemberController extends Controller
'is_active' => true,
],
);
if (! empty($validated['branch_id'])) {
$practitioner->syncAssignedBranches([(int) $validated['branch_id']]);
}
}
return redirect()->route('care.members.index')->with('success', 'Invitation sent to '.$email.'.');
@@ -11,6 +11,7 @@ use App\Models\Practitioner;
use App\Services\Care\AuditLogger;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\View\View;
class PractitionerController extends Controller
@@ -25,7 +26,7 @@ class PractitionerController extends Controller
$practitioners = Practitioner::owned($owner)
->where('organization_id', $organization->id)
->with(['branch', 'department', 'member'])
->with(['branch', 'branches', 'department', 'member'])
->orderBy('name')
->get();
@@ -66,10 +67,12 @@ class PractitionerController extends Controller
? Member::owned($owner)->where('organization_id', $organization->id)->findOrFail($validated['member_id'])
: null;
$branchIds = array_map('intval', $validated['branch_ids']);
$practitioner = Practitioner::create([
'owner_ref' => $owner,
'organization_id' => $organization->id,
'branch_id' => $validated['branch_id'] ?? null,
'branch_id' => $branchIds[0],
'department_id' => $validated['department_id'] ?? null,
'member_id' => $member?->id,
'user_ref' => $member?->user_ref,
@@ -77,6 +80,7 @@ class PractitionerController extends Controller
'specialty' => $validated['specialty'] ?? null,
'is_active' => true,
]);
$practitioner->syncAssignedBranches($branchIds);
AuditLogger::record($owner, 'practitioner.created', $organization->id, $owner, Practitioner::class, $practitioner->id);
@@ -90,6 +94,8 @@ class PractitionerController extends Controller
$organization = $this->organization($request);
$owner = $this->ownerRef($request);
$practitioner->load('branches');
return view('care.admin.practitioners.edit', [
'practitioner' => $practitioner,
'branches' => $this->activeBranches($owner, $organization->id),
@@ -111,8 +117,10 @@ class PractitionerController extends Controller
? Member::owned($owner)->where('organization_id', $organization->id)->findOrFail($validated['member_id'])
: null;
$branchIds = array_map('intval', $validated['branch_ids']);
$practitioner->update([
'branch_id' => $validated['branch_id'] ?? null,
'branch_id' => $branchIds[0],
'department_id' => $validated['department_id'] ?? null,
'member_id' => $member?->id,
'user_ref' => $member?->user_ref,
@@ -120,6 +128,7 @@ class PractitionerController extends Controller
'specialty' => $validated['specialty'] ?? null,
'is_active' => $request->boolean('is_active', true),
]);
$practitioner->syncAssignedBranches($branchIds);
AuditLogger::record($owner, 'practitioner.updated', $organization->id, $owner, Practitioner::class, $practitioner->id);
@@ -141,23 +150,22 @@ class PractitionerController extends Controller
}
/**
* @return array{name: string, specialty?: string|null, branch_id?: int|null, department_id?: int|null, member_id?: int|null}
* @return array{name: string, specialty?: string|null, branch_ids: list<int>, department_id?: int|null, member_id?: int|null}
*/
protected function validated(Request $request, string $owner, int $organizationId): array
{
$validated = $request->validate([
'name' => ['required', 'string', 'max:255'],
'specialty' => ['nullable', 'string', 'max:255'],
'branch_id' => ['nullable', 'integer', 'exists:care_branches,id'],
'branch_ids' => ['required', 'array', 'min:1'],
'branch_ids.*' => [
'integer',
Rule::exists('care_branches', 'id')->where(fn ($q) => $q->where('organization_id', $organizationId)->where('owner_ref', $owner)),
],
'department_id' => ['nullable', 'integer', 'exists:care_departments,id'],
'member_id' => ['nullable', 'integer', 'exists:care_members,id'],
]);
if (! empty($validated['branch_id'])) {
$branch = Branch::owned($owner)->findOrFail($validated['branch_id']);
abort_unless($branch->organization_id === $organizationId, 404);
}
if (! empty($validated['department_id'])) {
$department = Department::owned($owner)->with('branch')->findOrFail($validated['department_id']);
abort_unless($department->branch?->organization_id === $organizationId, 404);
@@ -240,10 +240,6 @@ class QueueController extends Controller
{
$this->authorizeOwner($request, $appointment);
abort_unless($appointment->organization_id === $this->organization($request)->id, 404);
$branchId = app(OrganizationResolver::class)->branchScope($this->member($request));
if ($branchId !== null && $appointment->branch_id !== $branchId) {
abort(404);
}
$this->authorizeBranch($request, (int) $appointment->branch_id);
}
}
+38
View File
@@ -5,6 +5,7 @@ namespace App\Models;
use App\Models\Concerns\BelongsToOwner;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
@@ -34,6 +35,15 @@ class Practitioner extends Model
return $this->belongsTo(Branch::class, 'branch_id');
}
/**
* Explicitly assigned branches (telemedicine may include several). Empty = unassigned.
*/
public function branches(): BelongsToMany
{
return $this->belongsToMany(Branch::class, 'care_practitioner_branch', 'practitioner_id', 'branch_id')
->withTimestamps();
}
public function department(): BelongsTo
{
return $this->belongsTo(Department::class, 'department_id');
@@ -53,4 +63,32 @@ class Practitioner extends Model
{
return $this->hasMany(Appointment::class, 'practitioner_id');
}
/**
* @return list<int>
*/
public function assignedBranchIds(): array
{
$ids = $this->relationLoaded('branches')
? $this->branches->pluck('id')->all()
: $this->branches()->pluck('care_branches.id')->all();
if ($ids === [] && $this->branch_id) {
return [(int) $this->branch_id];
}
return array_values(array_unique(array_map('intval', $ids)));
}
/**
* @param list<int|string> $branchIds
*/
public function syncAssignedBranches(array $branchIds): void
{
$ids = array_values(array_unique(array_filter(array_map('intval', $branchIds))));
$this->branches()->sync($ids);
$this->forceFill([
'branch_id' => $ids[0] ?? null,
])->save();
}
}
+32 -31
View File
@@ -11,9 +11,9 @@ use Illuminate\Support\Collection;
/**
* Resolves which Care branch the current user is working in.
*
* Staff with a member.branch_id stay locked to that site. Hospital admins (and
* similar all-branch roles) pick a branch via the queue filters; that choice is
* remembered in session so Patient / Pharmacy / Lab / Billing queues stay aligned.
* Doctors may be assigned to multiple sites (telemedicine) but only those
* explicitly linked on their practitioner desks never org-wide by default.
* Hospital admins pick among all branches; that choice is remembered in session.
*/
class BranchContext
{
@@ -29,9 +29,12 @@ class BranchContext
return false;
}
// Site clinicians are assigned to one branch — never a branch picker.
if ($member->role === 'doctor') {
return count($this->organizations->doctorAssignedBranchIds($member)) > 1;
}
// Other site clinicians stay on their assigned branch — never a picker.
if (in_array($member->role, [
'doctor',
'nurse',
'pharmacist',
'lab_technician',
@@ -41,30 +44,29 @@ class BranchContext
return false;
}
return $this->organizations->branchScope($member) === null;
return $this->organizations->allowedBranchIds($member) === null;
}
/**
* Active branches the member may see (one site for scoped staff, all for admins).
* Active branches the member may see.
*
* @return Collection<int, Branch>
*/
public function branches(Request $request, Organization $organization, ?Member $member): Collection
{
$scope = $this->organizations->branchScope($member);
$ids = $this->organizations->allowedBranchIds($member);
return Branch::owned((string) $organization->owner_ref)
->where('organization_id', $organization->id)
->where('is_active', true)
// Scope 0 = no site assigned — must not fall through to every branch.
->when($scope !== null, fn ($q) => $q->where('id', $scope))
->when($ids !== null, fn ($q) => $q->whereIn('id', $ids !== [] ? $ids : [0]))
->orderBy('name')
->get();
}
/**
* Preferred working branch id (0 when the org has no active branches).
* Persists admin selections from ?branch_id= into the session.
* Preferred working branch id (0 when none allowed).
* Persists switcher selections from ?branch_id= into the session.
*/
public function resolve(Request $request, Organization $organization, ?Member $member): int
{
@@ -74,28 +76,27 @@ class BranchContext
return 0;
}
$scope = $this->organizations->branchScope($member);
if ($scope !== null) {
return (int) $scope;
}
if ($this->canSwitch($member)) {
if ($request->filled('branch_id')) {
$requested = (int) $request->input('branch_id');
if (in_array($requested, $allowed, true)) {
$request->session()->put(self::SESSION_KEY, $requested);
if ($request->filled('branch_id')) {
$requested = (int) $request->input('branch_id');
if (in_array($requested, $allowed, true)) {
$request->session()->put(self::SESSION_KEY, $requested);
return $requested;
return $requested;
}
}
$preferred = (int) $request->session()->get(self::SESSION_KEY, 0);
if ($preferred > 0 && in_array($preferred, $allowed, true)) {
return $preferred;
}
$fallback = (int) $branches->first()->id;
$request->session()->put(self::SESSION_KEY, $fallback);
return $fallback;
}
$preferred = (int) $request->session()->get(self::SESSION_KEY, 0);
if ($preferred > 0 && in_array($preferred, $allowed, true)) {
return $preferred;
}
$fallback = (int) $branches->first()->id;
$request->session()->put(self::SESSION_KEY, $fallback);
return $fallback;
return (int) $allowed[0];
}
}
+6
View File
@@ -259,6 +259,10 @@ class DemoTenantSeeder
'member_id' => $member?->id,
'name' => $doctorName !== '' ? $doctorName : $practitioner->name,
])->save();
if ($homeBranchId > 0) {
$practitioner->syncAssignedBranches([$homeBranchId]);
}
}
/**
@@ -845,6 +849,7 @@ class DemoTenantSeeder
'deleted_at' => null,
],
);
$practitioner->syncAssignedBranches([(int) $branch->id]);
foreach ([Appointment::STATUS_WAITING, Appointment::STATUS_CHECKED_IN, Appointment::STATUS_COMPLETED] as $slot => $status) {
$patient = $patients[($branchIndex + $slot + $count) % count($patients)];
@@ -950,6 +955,7 @@ class DemoTenantSeeder
'deleted_at' => null,
],
);
$practitioners[array_key_last($practitioners)]->syncAssignedBranches([(int) $branch->id]);
}
return $practitioners;
+86 -20
View File
@@ -180,7 +180,73 @@ class OrganizationResolver
};
}
/** Branch ID the member may access; null = all branches (admins only). */
/**
* Branch IDs the member may access.
* null = all branches (admins). Empty array = none assigned.
*
* @return list<int>|null
*/
public function allowedBranchIds(?Member $member): ?array
{
if ($member === null) {
return null;
}
if (in_array($member->role, ['super_admin', 'hospital_admin', 'accountant'], true)) {
return null;
}
if ($member->role === 'doctor') {
return $this->doctorAssignedBranchIds($member);
}
if ($member->branch_id) {
return [(int) $member->branch_id];
}
return null;
}
/**
* Explicit branch IDs for a doctor's linked practitioner desks (pivot + legacy branch_id).
*
* @return list<int>
*/
public function doctorAssignedBranchIds(Member $member): array
{
$practitioners = Practitioner::query()
->where('is_active', true)
->where(function ($query) use ($member) {
$query->where('member_id', $member->id)
->orWhere('user_ref', $member->user_ref);
})
->with('branches')
->orderBy('id')
->get();
$ids = [];
foreach ($practitioners as $practitioner) {
$ids = array_merge($ids, $practitioner->assignedBranchIds());
}
return array_values(array_unique(array_map('intval', $ids)));
}
public function mayAccessBranch(?Member $member, ?int $branchId): bool
{
if ($branchId === null || $branchId <= 0) {
return false;
}
$allowed = $this->allowedBranchIds($member);
if ($allowed === null) {
return true;
}
return in_array((int) $branchId, $allowed, true);
}
/** Current working branch ID; null = all branches (admins only). */
public function branchScope(?Member $member): ?int
{
if ($member === null) {
@@ -191,30 +257,33 @@ class OrganizationResolver
return null;
}
if ($member->branch_id) {
return (int) $member->branch_id;
if ($member->role === 'doctor') {
$ids = $this->doctorAssignedBranchIds($member);
if ($ids === []) {
return 0;
}
if (count($ids) === 1) {
return $ids[0];
}
$preferred = (int) session(BranchContext::SESSION_KEY, 0);
if (in_array($preferred, $ids, true)) {
return $preferred;
}
return $ids[0];
}
// Doctors are always one site. Prefer linked desk when Identity omitted branch_id.
if ($member->role === 'doctor') {
$deskBranch = Practitioner::query()
->where('is_active', true)
->where(function ($query) use ($member) {
$query->where('member_id', $member->id)
->orWhere('user_ref', $member->user_ref);
})
->orderBy('id')
->value('branch_id');
return $deskBranch ? (int) $deskBranch : 0;
if ($member->branch_id) {
return (int) $member->branch_id;
}
return $member->branch_id;
}
/**
* Practitioner IDs a doctor is locked to (single branch). Null = no practitioner lock.
* Empty array = doctor with no linked desk on their branch.
* Practitioner IDs a doctor is locked to. Null = no practitioner lock.
* Empty array = doctor with no linked desk.
*
* @return list<int>|null
*/
@@ -224,12 +293,9 @@ class OrganizationResolver
return null;
}
$branchId = $this->branchScope($member);
return Practitioner::owned((string) $organization->owner_ref)
->where('organization_id', $organization->id)
->where('is_active', true)
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
->where(function ($query) use ($member) {
$query->where('member_id', $member->id)
->orWhere('user_ref', $member->user_ref);
+9 -3
View File
@@ -144,13 +144,19 @@ class SpecialtyModuleService
$practitioners = Practitioner::owned((string) $organization->owner_ref)
->where('organization_id', $organization->id)
->where('is_active', true)
->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
->where(function ($query) use ($member) {
$query->where('member_id', $member->id)
->orWhere('user_ref', $member->user_ref);
})
->with('department')
->get();
->with(['department', 'branches'])
->get()
->filter(function (Practitioner $practitioner) use ($branchId) {
if (! $branchId) {
return true;
}
return in_array((int) $branchId, $practitioner->assignedBranchIds(), true);
});
foreach ($practitioners as $practitioner) {
if ($provisionedIds !== [] && in_array((int) $practitioner->department_id, $provisionedIds, true)) {
@@ -0,0 +1,37 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('care_practitioner_branch', function (Blueprint $table) {
$table->id();
$table->foreignId('practitioner_id')->constrained('care_practitioners')->cascadeOnDelete();
$table->foreignId('branch_id')->constrained('care_branches')->cascadeOnDelete();
$table->timestamps();
$table->unique(['practitioner_id', 'branch_id']);
});
// Backfill explicit assignments from the legacy single branch_id (never invent "all branches").
$now = now();
foreach (DB::table('care_practitioners')->whereNotNull('branch_id')->get(['id', 'branch_id']) as $row) {
DB::table('care_practitioner_branch')->insertOrIgnore([
'practitioner_id' => $row->id,
'branch_id' => $row->branch_id,
'created_at' => $now,
'updated_at' => $now,
]);
}
}
public function down(): void
{
Schema::dropIfExists('care_practitioner_branch');
}
};
@@ -47,13 +47,19 @@
</div>
<div>
<label class="block text-sm font-medium text-slate-700">Branch (optional)</label>
<select name="branch_id" class="mt-1 w-full rounded-lg border-slate-300 text-sm">
<option value="">All branches</option>
<label class="block text-sm font-medium text-slate-700">
<span x-text="role === 'doctor' ? 'Home branch' : 'Branch (optional)'"></span>
</label>
<select name="branch_id" class="mt-1 w-full rounded-lg border-slate-300 text-sm"
:required="role === 'doctor'">
<option value="" x-text="role === 'doctor' ? 'Select a branch…' : 'No branch lock'"></option>
@foreach ($branches as $branch)
<option value="{{ $branch->id }}" @selected(old('branch_id') == $branch->id)>{{ $branch->name }}</option>
@endforeach
</select>
<p class="mt-1 text-xs text-slate-500" x-show="role === 'doctor'" x-cloak>
Required for doctors. Add more sites later under Practitioners (telemedicine).
</p>
</div>
<div class="rounded-xl border border-slate-100 bg-slate-50 p-4" x-show="role === 'doctor'" x-cloak>
@@ -14,15 +14,24 @@
<label class="block text-sm font-medium">Specialty (optional)</label>
<input type="text" name="specialty" value="{{ old('specialty') }}" class="mt-1 w-full rounded-lg border-slate-300 text-sm" placeholder="General practice">
</div>
<div>
<label class="block text-sm font-medium">Branch (optional)</label>
<select name="branch_id" class="mt-1 w-full rounded-lg border-slate-300 text-sm">
<option value="">All branches</option>
@foreach ($branches as $branch)
<option value="{{ $branch->id }}" @selected(old('branch_id') == $branch->id)>{{ $branch->name }}</option>
@endforeach
</select>
</div>
<fieldset>
<legend class="block text-sm font-medium">Branches</legend>
<p class="mt-1 text-xs text-slate-500">Select every site this clinician may serve (including telemedicine). Nothing is selected by default.</p>
<div class="mt-2 space-y-2 rounded-lg border border-slate-200 p-3">
@forelse ($branches as $branch)
<label class="flex items-center gap-2 text-sm text-slate-700">
<input type="checkbox" name="branch_ids[]" value="{{ $branch->id }}"
@checked(collect(old('branch_ids', []))->contains($branch->id))
class="rounded border-slate-300 text-sky-600">
{{ $branch->name }}
</label>
@empty
<p class="text-sm text-slate-500">Create a branch first under Settings Branches.</p>
@endforelse
</div>
@error('branch_ids')<p class="mt-1 text-sm text-red-600">{{ $message }}</p>@enderror
@error('branch_ids.*')<p class="mt-1 text-sm text-red-600">{{ $message }}</p>@enderror
</fieldset>
<div>
<label class="block text-sm font-medium">Department (optional)</label>
<select name="department_id" class="mt-1 w-full rounded-lg border-slate-300 text-sm">
@@ -13,15 +13,27 @@
<label class="block text-sm font-medium">Specialty (optional)</label>
<input type="text" name="specialty" value="{{ old('specialty', $practitioner->specialty) }}" class="mt-1 w-full rounded-lg border-slate-300 text-sm">
</div>
<div>
<label class="block text-sm font-medium">Branch (optional)</label>
<select name="branch_id" class="mt-1 w-full rounded-lg border-slate-300 text-sm">
<option value="">All branches</option>
@foreach ($branches as $branch)
<option value="{{ $branch->id }}" @selected(old('branch_id', $practitioner->branch_id) == $branch->id)>{{ $branch->name }}</option>
@endforeach
</select>
</div>
<fieldset>
<legend class="block text-sm font-medium">Branches</legend>
<p class="mt-1 text-xs text-slate-500">Select every site this clinician may serve (including telemedicine). Nothing is selected by default.</p>
@php
$selectedBranchIds = collect(old('branch_ids', $practitioner->assignedBranchIds()));
@endphp
<div class="mt-2 space-y-2 rounded-lg border border-slate-200 p-3">
@forelse ($branches as $branch)
<label class="flex items-center gap-2 text-sm text-slate-700">
<input type="checkbox" name="branch_ids[]" value="{{ $branch->id }}"
@checked($selectedBranchIds->contains($branch->id))
class="rounded border-slate-300 text-sky-600">
{{ $branch->name }}
</label>
@empty
<p class="text-sm text-slate-500">Create a branch first under Settings Branches.</p>
@endforelse
</div>
@error('branch_ids')<p class="mt-1 text-sm text-red-600">{{ $message }}</p>@enderror
@error('branch_ids.*')<p class="mt-1 text-sm text-red-600">{{ $message }}</p>@enderror
</fieldset>
<div>
<label class="block text-sm font-medium">Department (optional)</label>
<select name="department_id" class="mt-1 w-full rounded-lg border-slate-300 text-sm">
@@ -35,7 +35,16 @@
<tr>
<td class="px-4 py-3 font-medium">{{ $practitioner->name }}</td>
<td class="px-4 py-3">{{ $practitioner->specialty ?: '—' }}</td>
<td class="px-4 py-3">{{ $practitioner->branch?->name ?? 'All branches' }}</td>
<td class="px-4 py-3">
@php $branchNames = $practitioner->branches->pluck('name'); @endphp
@if ($branchNames->isNotEmpty())
{{ $branchNames->implode(', ') }}
@elseif ($practitioner->branch)
{{ $practitioner->branch->name }}
@else
<span class="text-amber-700">Unassigned</span>
@endif
</td>
<td class="px-4 py-3">{{ $practitioner->member?->user_ref ?? '—' }}</td>
<td class="px-4 py-3">
<span class="inline-flex rounded-full px-2 py-0.5 text-xs font-medium {{ $practitioner->is_active ? 'bg-emerald-50 text-emerald-700' : 'bg-slate-100 text-slate-600' }}">
+10 -7
View File
@@ -18,13 +18,16 @@
<form method="GET" class="flex flex-wrap gap-3 rounded-2xl border border-slate-200 bg-white p-4">
@if ($lockToPractitioner ?? false)
<p class="text-sm text-slate-500">
@if (isset($branches) && $branches->isNotEmpty())
<span class="font-medium text-slate-700">{{ $branches->first()->name }}</span>
<span class="text-slate-300"> · </span>
@endif
Showing patients assigned to you
</p>
@if (($canSwitchBranch ?? false) && isset($branches) && $branches->count() > 1)
<select name="branch_id" class="rounded-lg border-slate-300 text-sm" onchange="this.form.submit()">
@foreach ($branches as $branch)
<option value="{{ $branch->id }}" @selected($branchId == $branch->id)>{{ $branch->name }}</option>
@endforeach
</select>
@elseif (isset($branches) && $branches->isNotEmpty())
<span class="flex items-center text-sm font-medium text-slate-700">{{ $branches->first()->name }}</span>
@endif
<span class="flex items-center text-sm text-slate-500">Showing patients assigned to you</span>
@elseif ($canSwitchBranch ?? false)
<select name="branch_id" class="rounded-lg border-slate-300 text-sm" onchange="this.form.submit()">
@foreach ($branches as $branch)
@@ -0,0 +1,153 @@
<?php
namespace Tests\Feature;
use App\Http\Middleware\EnsurePlatformSession;
use App\Models\Branch;
use App\Models\Member;
use App\Models\Organization;
use App\Models\Practitioner;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class CarePractitionerBranchesTest extends TestCase
{
use RefreshDatabase;
public function test_practitioner_requires_explicit_branch_assignment(): void
{
$this->withoutMiddleware(EnsurePlatformSession::class);
[$owner, $organization, $east, $west] = $this->seedOrg();
$this->actingAs($owner)
->post(route('care.practitioners.store'), [
'name' => 'Dr. Tele',
'specialty' => 'General',
])
->assertSessionHasErrors('branch_ids');
$this->actingAs($owner)
->post(route('care.practitioners.store'), [
'name' => 'Dr. Tele',
'specialty' => 'General',
'branch_ids' => [$east->id, $west->id],
])
->assertRedirect(route('care.practitioners.index'));
$practitioner = Practitioner::query()->where('name', 'Dr. Tele')->firstOrFail();
$this->assertEqualsCanonicalizing(
[$east->id, $west->id],
$practitioner->assignedBranchIds(),
);
$this->assertSame($east->id, (int) $practitioner->branch_id);
$this->actingAs($owner)
->get(route('care.practitioners.index'))
->assertOk()
->assertSee('East Legon Care')
->assertSee('West Hills Care')
->assertDontSee('All branches');
}
public function test_doctor_with_multiple_assigned_branches_can_switch_among_them_only(): void
{
$this->withoutMiddleware(EnsurePlatformSession::class);
[$owner, $organization, $east, $west] = $this->seedOrg();
$other = Branch::create([
'owner_ref' => $owner->public_id,
'organization_id' => $organization->id,
'name' => 'Airport Clinic',
'is_active' => true,
]);
$doctor = User::create([
'public_id' => 'multi-branch-doc',
'name' => 'Tele Doctor',
'email' => 'tele-doc@example.com',
]);
$member = Member::create([
'owner_ref' => $owner->public_id,
'organization_id' => $organization->id,
'user_ref' => $doctor->public_id,
'role' => 'doctor',
'branch_id' => $east->id,
]);
$practitioner = Practitioner::create([
'owner_ref' => $owner->public_id,
'organization_id' => $organization->id,
'branch_id' => $east->id,
'member_id' => $member->id,
'user_ref' => $doctor->public_id,
'name' => 'Tele Doctor',
'is_active' => true,
]);
$practitioner->syncAssignedBranches([$east->id, $west->id]);
$this->actingAs($doctor)
->get(route('care.queue.index'))
->assertOk()
->assertSee('Showing patients assigned to you')
->assertSee('name="branch_id"', false)
->assertSee('East Legon Care')
->assertSee('West Hills Care')
->assertDontSee('Airport Clinic');
$this->actingAs($doctor)
->get(route('care.queue.index', ['branch_id' => $west->id]))
->assertOk()
->assertSee('West Hills Care');
$this->actingAs($doctor)
->get(route('care.queue.index', ['branch_id' => $other->id]))
->assertOk()
->assertDontSee('Airport Clinic');
}
/**
* @return array{0: User, 1: Organization, 2: Branch, 3: Branch}
*/
protected function seedOrg(): array
{
$owner = User::create([
'public_id' => 'prac-branch-owner',
'name' => 'Owner',
'email' => 'prac-owner@example.com',
]);
$organization = Organization::create([
'owner_ref' => $owner->public_id,
'name' => 'Multi Site Clinic',
'slug' => 'multi-site-clinic',
'timezone' => 'UTC',
'settings' => ['onboarded' => true, 'plan' => 'pro', 'plan_expires_at' => now()->addMonth()->toIso8601String()],
]);
Member::create([
'owner_ref' => $owner->public_id,
'organization_id' => $organization->id,
'user_ref' => $owner->public_id,
'role' => 'hospital_admin',
'branch_id' => null,
]);
$east = Branch::create([
'owner_ref' => $owner->public_id,
'organization_id' => $organization->id,
'name' => 'East Legon Care',
'is_active' => true,
]);
$west = Branch::create([
'owner_ref' => $owner->public_id,
'organization_id' => $organization->id,
'name' => 'West Hills Care',
'is_active' => true,
]);
return [$owner, $organization, $east, $west];
}
}
@@ -77,6 +77,7 @@ class CareStaffTenantScopeTest extends TestCase
'name' => 'Demo Pro Doctor',
'is_active' => true,
]);
$mine->syncAssignedBranches([$branch->id]);
$other = Practitioner::create([
'owner_ref' => $owner->public_id,
@@ -85,6 +86,7 @@ class CareStaffTenantScopeTest extends TestCase
'name' => 'Other Doctor',
'is_active' => true,
]);
$other->syncAssignedBranches([$branch->id]);
$assignedPatient = Patient::create([
'uuid' => (string) \Illuminate\Support\Str::uuid(),