Files
ladill-care/app/Services/Care/BranchContext.php
T
isaaccladandCursor 5264035705
Deploy Ladill Care / deploy (push) Successful in 1m11s
Scope staff Care queries to the organization owner_ref.
Demo doctors were querying their own public_id, so branches/patients/queues looked empty even though the Pro tenant had data.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-18 06:20:31 +00:00

85 lines
2.6 KiB
PHP

<?php
namespace App\Services\Care;
use App\Models\Branch;
use App\Models\Member;
use App\Models\Organization;
use Illuminate\Http\Request;
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.
*/
class BranchContext
{
public const SESSION_KEY = 'care.preferred_branch_id';
public function __construct(
protected OrganizationResolver $organizations,
) {}
public function canSwitch(?Member $member): bool
{
return $this->organizations->branchScope($member) === null;
}
/**
* Active branches the member may see (one site for scoped staff, all for admins).
*
* @return Collection<int, Branch>
*/
public function branches(Request $request, Organization $organization, ?Member $member): Collection
{
$scope = $this->organizations->branchScope($member);
return Branch::owned((string) $organization->owner_ref)
->where('organization_id', $organization->id)
->where('is_active', true)
->when($scope, fn ($q) => $q->where('id', $scope))
->orderBy('name')
->get();
}
/**
* Preferred working branch id (0 when the org has no active branches).
* Persists admin selections from ?branch_id= into the session.
*/
public function resolve(Request $request, Organization $organization, ?Member $member): int
{
$branches = $this->branches($request, $organization, $member);
$allowed = $branches->pluck('id')->map(fn ($id) => (int) $id)->all();
if ($allowed === []) {
return 0;
}
$scope = $this->organizations->branchScope($member);
if ($scope !== null) {
return (int) $scope;
}
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;
}
}
$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;
}
}