diff --git a/app/models/concerns/product_on_demand.rb b/app/models/concerns/product_on_demand.rb new file mode 100644 index 0000000000..0ad101e7ca --- /dev/null +++ b/app/models/concerns/product_on_demand.rb @@ -0,0 +1,10 @@ +require 'active_support/concern' + +module ProductOnDemand + extend ActiveSupport::Concern + + def on_demand=(value) + raise 'cannot set on_demand of product with variants' if variants.any? + master.on_demand = value + end +end diff --git a/app/models/spree/product_decorator.rb b/app/models/spree/product_decorator.rb index 8c0571558a..a7aefcee48 100644 --- a/app/models/spree/product_decorator.rb +++ b/app/models/spree/product_decorator.rb @@ -1,8 +1,11 @@ require 'open_food_network/permalink_generator' require 'open_food_network/property_merge' +require 'concerns/product_on_demand' Spree::Product.class_eval do include PermalinkGenerator + include ProductOnDemand + # We have an after_destroy callback on Spree::ProductOptionType. However, if we # don't specify dependent => destroy on this association, it is not called. See: # https://github.com/rails/rails/issues/7618 diff --git a/app/serializers/api/admin/product_serializer.rb b/app/serializers/api/admin/product_serializer.rb index ed14f3a2f7..e84588128f 100644 --- a/app/serializers/api/admin/product_serializer.rb +++ b/app/serializers/api/admin/product_serializer.rb @@ -1,7 +1,7 @@ class Api::Admin::ProductSerializer < ActiveModel::Serializer - attributes :id, :name, :sku, :variant_unit, :variant_unit_scale, :variant_unit_name, :inherits_properties - - attributes :on_hand, :price, :available_on, :permalink_live, :tax_category_id, :import_date, :image_url, :thumb_url + attributes :id, :name, :sku, :variant_unit, :variant_unit_scale, :variant_unit_name, + :inherits_properties, :on_hand, :price, :available_on, :permalink_live, + :tax_category_id, :import_date, :image_url, :thumb_url has_one :supplier, key: :producer_id, embed: :id has_one :primary_taxon, key: :category_id, embed: :id diff --git a/spec/models/concerns/product_on_demand_spec.rb b/spec/models/concerns/product_on_demand_spec.rb new file mode 100644 index 0000000000..8ff11302cd --- /dev/null +++ b/spec/models/concerns/product_on_demand_spec.rb @@ -0,0 +1,28 @@ +require 'spec_helper' + +describe ProductOnDemand do + describe '#on_demand=' do + context 'when the product has no variants' do + let(:product) { create(:simple_product) } + + before do + product.variants.first.destroy + product.variants.reload + end + + it 'sets the value on master.on_demand' do + product.on_demand = false + expect(product.master.on_demand).to eq(false) + end + end + + context 'when the product has variants' do + let(:product) { create(:simple_product) } + + it 'raises' do + expect { product.on_demand = true } + .to raise_error(StandardError, /cannot set on_demand/) + end + end + end +end