organizations->branchScope($member) === null; } /** * Active branches the member may see (one site for scoped staff, all for admins). * * @return Collection */ public function branches(Request $request, Organization $organization, ?Member $member): Collection { $scope = $this->organizations->branchScope($member); return Branch::owned((string) $request->user()->public_id) ->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; } }