From 06f986ff52ce359e398e4eeba18cd838a1cc1ffb Mon Sep 17 00:00:00 2001 From: Gaetan Craig-Riou Date: Tue, 8 Aug 2023 16:13:04 +1000 Subject: [PATCH] Allow for creating a voucher with either flat or percentage rate In the scenario when you get an error when trying to create a percentage voucher, on the subsequent try we would be dealing with a "percentage rate voucher". The code now handle any type of voucher --- app/controllers/admin/vouchers_controller.rb | 12 ++++++++++-- spec/requests/admin/vouchers_controller_spec.rb | 9 +++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/app/controllers/admin/vouchers_controller.rb b/app/controllers/admin/vouchers_controller.rb index 01ca689b91..cad08ab833 100644 --- a/app/controllers/admin/vouchers_controller.rb +++ b/app/controllers/admin/vouchers_controller.rb @@ -9,9 +9,13 @@ module Admin end def create + # In the scenario where you get an error when trying to create a percentage voucher, we'll + # now have percentage rate voucher instanciated. Hence why we check for both params type + voucher_type = params.dig(:vouchers_flat_rate, :voucher_type) || + params[:vouchers_percentage_rate][:voucher_type] + # The use of "safe_constantize" here will trigger a Brakeman error, it can safely be ignored # as it's a false positive : https://github.com/openfoodfoundation/openfoodnetwork/pull/10821 - voucher_type = params[:vouchers_flat_rate][:voucher_type] if Voucher::TYPES.include?(voucher_type) @voucher = voucher_type.safe_constantize.create( permitted_resource_params.merge(enterprise: @enterprise) @@ -44,7 +48,11 @@ module Admin end def permitted_resource_params - params.require(:vouchers_flat_rate).permit(:code, :amount) + if params[:vouchers_flat_rate].present? + return params.require(:vouchers_flat_rate).permit(:code, :amount) + end + + params.require(:vouchers_percentage_rate).permit(:code, :amount) end end end diff --git a/spec/requests/admin/vouchers_controller_spec.rb b/spec/requests/admin/vouchers_controller_spec.rb index 60b0f34e17..935255fff7 100644 --- a/spec/requests/admin/vouchers_controller_spec.rb +++ b/spec/requests/admin/vouchers_controller_spec.rb @@ -50,6 +50,15 @@ describe Admin::VouchersController, type: :request do end context "with a percentage rate voucher" do + let(:params) do + { + vouchers_percentage_rate: { + code: code, + amount: amount, + voucher_type: type + } + } + end let(:type) { "Vouchers::PercentageRate" } it "creates a new voucher" do