From fd218e16569a92b7137cfd59a20bf811c313fc72 Mon Sep 17 00:00:00 2001 From: lukaszreszke Date: Fri, 26 Jul 2024 16:36:22 +0200 Subject: [PATCH] Don't crash on price set to 0 https://github.com/RailsEventStore/ecommerce/issues/340 --- .../app/controllers/products_controller.rb | 23 +++++++++++++++++++ .../test/integration/products_test.rb | 18 +++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/rails_application/app/controllers/products_controller.rb b/rails_application/app/controllers/products_controller.rb index 472f879b..9e00462f 100644 --- a/rails_application/app/controllers/products_controller.rb +++ b/rails_application/app/controllers/products_controller.rb @@ -1,4 +1,19 @@ class ProductsController < ApplicationController + class CreateProduct + attr_reader :price, :vat_rate, :product_id, :name + + def initialize(price:, vat_rate:, product_id:, name:) + @price = price + @vat_rate = vat_rate + @product_id = product_id + @name = name + end + + def valid? + price.present? && vat_rate.present? && product_id.present? && name.present? && price.to_d > 0 && vat_rate.to_d > 0 + end + end + def index @products = Products::Product.all end @@ -16,6 +31,10 @@ def edit end def create + is_form_valid = CreateProduct.new(**product_params).valid? + + return head :bad_request unless is_form_valid + ActiveRecord::Base.transaction do create_product(params[:product_id], params[:name]) if params[:price].present? @@ -101,4 +120,8 @@ def set_product_future_price_cmd(product_id, price, valid_since) valid_since: valid_since ) end + + def product_params + params.permit(:name, :price, :vat_rate, :product_id).to_h.symbolize_keys.slice(:price, :vat_rate, :product_id, :name) + end end diff --git a/rails_application/test/integration/products_test.rb b/rails_application/test/integration/products_test.rb index 55f6e112..d2b91a38 100644 --- a/rails_application/test/integration/products_test.rb +++ b/rails_application/test/integration/products_test.rb @@ -45,4 +45,22 @@ def test_happy_path unit: "" ) end + + def test_does_not_crash_when_setting_products_price_to_0 + register_customer("Arkency") + product_id = SecureRandom.uuid + + get "/products/new" + assert_select "h1", "New Product" + post "/products", + params: { + "authenticity_token" => "[FILTERED]", + "product_id" => product_id, + "name" => "product name", + "price": "0", + "vat_rate" => "10" + } + + assert_response :bad_request + end end