From da78e06a39fe45cfa612036c6bf0068fcc05e761 Mon Sep 17 00:00:00 2001 From: Mohamed ABDELLANI Date: Wed, 22 Mar 2023 10:23:52 +0100 Subject: [PATCH] load customers of managed enterprises only --- .../api/v1/customers_controller.rb | 13 ++++----- spec/requests/api/v1/customers_spec.rb | 29 +++++++++++++++++++ 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/app/controllers/api/v1/customers_controller.rb b/app/controllers/api/v1/customers_controller.rb index 86bf05fc65..53d9cb163e 100644 --- a/app/controllers/api/v1/customers_controller.rb +++ b/app/controllers/api/v1/customers_controller.rb @@ -80,9 +80,12 @@ module Api end def visible_customers - current_api_user.customers.or( - Customer.where(enterprise_id: editable_enterprises) - ) + Customer.of(managed_enterprise_ids) + end + + def managed_enterprise_ids + @managed_enterprise_ids ||= Enterprise.managed_by(current_api_user). + select('enterprises.id') end def customer_params @@ -106,10 +109,6 @@ module Api attributes end - def editable_enterprises - OpenFoodNetwork::Permissions.new(current_api_user).editable_enterprises.select(:id) - end - def include_options fields = [params.fetch(:include, [])].flatten diff --git a/spec/requests/api/v1/customers_spec.rb b/spec/requests/api/v1/customers_spec.rb index 3a4b7b38bb..a44a753a16 100644 --- a/spec/requests/api/v1/customers_spec.rb +++ b/spec/requests/api/v1/customers_spec.rb @@ -5,6 +5,8 @@ require "swagger_helper" describe "Customers", type: :request do let!(:enterprise1) { create(:enterprise, name: "The Farm") } let!(:enterprise2) { create(:enterprise) } + let!(:enterprise3) { create(:enterprise) } + let!(:customer1) { create( :customer, @@ -74,6 +76,33 @@ describe "Customers", type: :request do end end + context "as a user who manages the enterprise" do + let!(:user){ enterprise3.users.first } + before do + EnterpriseRole.create!(user: user, enterprise: enterprise1) + login_as user + end + + it "returns customers of enterprises the user manages" do + get "/api/v1/customers" + expect(json_response_ids).to eq [customer1.id.to_s, customer2.id.to_s] + end + end + + context "as an enterprise that has edit profile permission" do + let!(:user){ enterprise3.users.first } + before do + EnterpriseRelationship.create!(parent: enterprise1, child: enterprise3, + permissions_list: [:edit_profile]) + login_as user + end + + it "shoult not return customers of the managed enterprise" do + get "/api/v1/customers" + expect(json_response_ids).to eq [] + end + end + context "with ransack params searching for specific customers" do before { login_as enterprise2.owner }