authorizeAbility($request, 'admin.branches.view'); $branches = Branch::owned($this->ownerRef($request)) ->where('organization_id', $this->organization($request)->id) ->orderBy('name') ->get() ->map(fn (Branch $b) => [ 'id' => $b->id, 'name' => $b->name, 'code' => $b->code, 'is_active' => $b->is_active, ]); return response()->json(['data' => $branches]); } public function store(Request $request): JsonResponse { $this->authorizeAbility($request, 'admin.branches.manage'); $organization = $this->organization($request); $owner = $this->ownerRef($request); $validated = $request->validate([ 'name' => ['required', 'string', 'max:255'], 'code' => ['nullable', 'string', 'max:50'], 'address' => ['nullable', 'string', 'max:500'], 'phone' => ['nullable', 'string', 'max:50'], 'is_active' => ['nullable', 'boolean'], ]); $existing = Branch::owned($owner) ->where('organization_id', $organization->id) ->whereRaw('LOWER(name) = ?', [strtolower($validated['name'])]) ->first(); if ($existing) { $existing->update([ 'code' => $validated['code'] ?? $existing->code, 'address' => $validated['address'] ?? $existing->address, 'phone' => $validated['phone'] ?? $existing->phone, 'is_active' => array_key_exists('is_active', $validated) ? (bool) $validated['is_active'] : true, ]); return response()->json([ 'data' => [ 'id' => $existing->id, 'name' => $existing->name, 'code' => $existing->code, 'is_active' => $existing->is_active, ], ]); } $currentCount = Branch::owned($owner)->where('organization_id', $organization->id)->count(); abort_unless(app(PlanService::class)->canAddBranch($organization, $currentCount), 422, 'Branch limit reached for current plan.'); $branch = Branch::create([ 'owner_ref' => $owner, 'organization_id' => $organization->id, 'name' => $validated['name'], 'code' => $validated['code'] ?? null, 'address' => $validated['address'] ?? null, 'phone' => $validated['phone'] ?? null, 'is_active' => array_key_exists('is_active', $validated) ? (bool) $validated['is_active'] : true, ]); AuditLogger::record($owner, 'branch.created', $organization->id, $owner, Branch::class, $branch->id); return response()->json([ 'data' => [ 'id' => $branch->id, 'name' => $branch->name, 'code' => $branch->code, 'is_active' => $branch->is_active, ], ], 201); } }