where('is_default', true) ->first() ?? PosLocation::owned($ownerRef)->orderBy('id')->first(); if ($existing) { return $existing; } return PosLocation::create([ 'owner_ref' => $ownerRef, 'name' => 'Main register', 'currency' => config('pos.default_currency', 'GHS'), 'is_default' => true, ]); } public function resolve(Request $request): PosLocation { $acting = $request->attributes->get('actingLocation'); if ($acting instanceof PosLocation) { return $acting; } return $this->ensureDefault($this->ownerRefFromRequest($request)); } /** @return Collection */ public function accessible(string $ownerRef, ?int $locationScope): Collection { $query = PosLocation::owned($ownerRef)->orderBy('name'); if ($locationScope !== null) { $query->where('id', $locationScope); } return $query->get(); } public function switch(Request $request, int $locationId): PosLocation { $ownerRef = $this->ownerRefFromRequest($request); $scope = $request->attributes->get('pos.locationScope'); $location = PosLocation::owned($ownerRef)->whereKey($locationId)->firstOrFail(); if ($scope !== null && (int) $scope !== $location->id) { abort(403, 'You do not have access to that branch.'); } if (! $request->is('api/*')) { $request->session()->put('ladill_pos_location', $location->id); } $request->attributes->set('actingLocation', $location); return $location; } private function ownerRefFromRequest(Request $request): string { $user = ladill_account() ?? $request->user(); return (string) $user->public_id; } }