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
This commit is contained in:
Gaetan Craig-Riou
2023-08-08 16:13:04 +10:00
parent 61e6d55872
commit 06f986ff52
2 changed files with 19 additions and 2 deletions

View File

@@ -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

View File

@@ -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