Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Associate Promotions with Store(s)
Damian Legawieca6b6f490e3eb
diff --git a/api/spec/controllers/spree/api/v1/promotion_application_spec.rb b/api/spec/controllers/spree/api/v1/promotion_application_spec.rbindex fa52be882e..9ee0681897 100644--- a/api/spec/controllers/spree/api/v1/promotion_application_spec.rb+++ b/api/spec/controllers/spree/api/v1/promotion_application_spec.rb@@ -11,7 +11,7 @@ module Spreecontext 'with an available promotion' dolet!(:order) { create(:order_with_line_items, line_items_count: 1) }let!(:promotion) do- promotion = Spree::Promotion.create(name: '10% off', code: '10off')+ promotion = create(:promotion, name: '10% off', code: '10off')calculator = Spree::Calculator::FlatPercentItemTotal.create(preferred_flat_percent: '10')action = Spree::Promotion::Actions::CreateItemAdjustments.create(calculator: calculator)promotion.actions << actiondiff --git a/api/spec/requests/spree/api/v2/storefront/cart_spec.rb b/api/spec/requests/spree/api/v2/storefront/cart_spec.rbindex 8ed7a8495b..b0eb93a3f9 100644--- a/api/spec/requests/spree/api/v2/storefront/cart_spec.rb+++ b/api/spec/requests/spree/api/v2/storefront/cart_spec.rb@@ -21,7 +21,7 @@ describe 'API V2 Storefront Cart Spec', type: :request doshared_context 'coupon codes' dolet!(:line_item) { create(:line_item, order: order) }let!(:shipment) { create(:shipment, order: order) }- let!(:promotion) { Spree::Promotion.create(name: 'Free shipping', code: 'freeship') }+ let!(:promotion) { create(:promotion, name: 'Free shipping', code: 'freeship', stores: [store]) }let(:coupon_code) { promotion.code }let!(:promotion_action) { Spree::PromotionAction.create(promotion_id: promotion.id, type: 'Spree::Promotion::Actions::FreeShipping') }enddiff --git a/backend/app/controllers/spree/admin/promotion_actions_controller.rb b/backend/app/controllers/spree/admin/promotion_actions_controller.rbindex 8c74f33eea..4cb51cd3d3 100644--- a/backend/app/controllers/spree/admin/promotion_actions_controller.rb+++ b/backend/app/controllers/spree/admin/promotion_actions_controller.rb@@ -29,7 +29,7 @@ class Spree::Admin::PromotionActionsController < Spree::Admin::BaseControllerprivatedef load_promotion- @promotion = Spree::Promotion.find(params[:promotion_id])+ @promotion = current_store.promotions.find(params[:promotion_id])enddef validate_promotion_action_typediff --git a/backend/app/controllers/spree/admin/promotion_rules_controller.rb b/backend/app/controllers/spree/admin/promotion_rules_controller.rbindex 380fc22767..9dea34e3f1 100644--- a/backend/app/controllers/spree/admin/promotion_rules_controller.rb+++ b/backend/app/controllers/spree/admin/promotion_rules_controller.rb@@ -30,7 +30,7 @@ class Spree::Admin::PromotionRulesController < Spree::Admin::BaseControllerprivatedef load_promotion- @promotion = Spree::Promotion.find(params[:promotion_id])+ @promotion = current_store.promotions.find(params[:promotion_id])enddef validate_promotion_rule_typediff --git a/backend/app/controllers/spree/admin/promotions_controller.rb b/backend/app/controllers/spree/admin/promotions_controller.rbindex 9a0b0f7def..1f313f14d5 100644--- a/backend/app/controllers/spree/admin/promotions_controller.rb+++ b/backend/app/controllers/spree/admin/promotions_controller.rb@@ -6,7 +6,7 @@ module Spreehelper 'spree/admin/promotion_rules'def clone- promotion = Spree::Promotion.find(params[:id])+ promotion = current_store.promotions.find(params[:id])duplicator = Spree::PromotionHandler::PromotionDuplicator.new(promotion)@new_promo = duplicator.duplicatediff --git a/backend/app/views/spree/admin/products/_form.html.erb b/backend/app/views/spree/admin/products/_form.html.erbindex 88c4d951d0..7c430850e1 100644--- a/backend/app/views/spree/admin/products/_form.html.erb+++ b/backend/app/views/spree/admin/products/_form.html.erb@@ -237,12 +237,12 @@<% end %></div>- <p data-hook="admin_product_form_stores" class="omega two columns">+ <div data-hook="admin_product_form_stores"><%= f.field_container :stores, class: ['form-group'] do %><%= f.label :product_stores, Spree.t(:stores) %><%= collection_select(:product, :store_ids, @stores, :id, :unique_name, {}, { multiple: true, class: 'select2' }) %><% end %>- </p>+ </div><div data-hook="admin_product_form_meta"><div data-hook="admin_product_form_meta_title">diff --git a/backend/app/views/spree/admin/promotions/_form.html.erb b/backend/app/views/spree/admin/promotions/_form.html.erbindex 6832225e1d..724ae6dd00 100644--- a/backend/app/views/spree/admin/promotions/_form.html.erb+++ b/backend/app/views/spree/admin/promotions/_form.html.erb@@ -45,6 +45,11 @@<%= f.label :promotion_category %><%= f.collection_select(:promotion_category_id, @promotion_categories, :id, :name, { include_blank: Spree.t('match_choices.none') }, { class: 'select2 w-100' }) %><% end %>++ <%= f.field_container :stores, class: ['form-group'] do %>+ <%= f.label :promotion_stores, Spree.t(:stores) %>+ <%= collection_select(:promotion, :store_ids, @stores, :id, :unique_name, {}, { multiple: true, class: 'select2' }) %>+ <% end %></div><div id="expiry_fields" class="col-12 col-lg-4">diff --git a/backend/spec/controllers/spree/admin/promotions_controller_spec.rb b/backend/spec/controllers/spree/admin/promotions_controller_spec.rbindex b3b3afd171..ed54c25268 100644--- a/backend/spec/controllers/spree/admin/promotions_controller_spec.rb+++ b/backend/spec/controllers/spree/admin/promotions_controller_spec.rb@@ -3,11 +3,15 @@ require 'spec_helper'describe Spree::Admin::PromotionsController, type: :controller dostub_authorization!- let!(:promotion1) { create(:promotion, name: 'name1', code: 'code1', path: 'path1') }- let!(:promotion2) { create(:promotion, name: 'name2', code: 'code2', path: 'path2') }+ let(:store) { Spree::Store.default }+ let(:store_2) { create(:store) }++ let!(:promotion1) { create(:promotion, name: 'name1', code: 'code1', path: 'path1', stores: [store, store_2]) }+ let!(:promotion2) { create(:promotion, name: 'name2', code: 'code2', path: 'path2', stores: [store]) }+ let!(:promotion3) { create(:promotion, name: 'name3', code: 'code3', path: 'path3', stores: [store_2]) }let!(:category) { create :promotion_category }- context '#index' do+ describe '#index' doit 'succeeds' doget :indexexpect(assigns[:promotions]).to match_array [promotion2, promotion1]@@ -41,7 +45,7 @@ describe Spree::Admin::PromotionsController, type: :controller doendend- context '#clone' do+ describe '#clone' docontext 'cloning valid promotion' dosubject dopost :clone, params: { id: promotion1.id }@@ -62,15 +66,15 @@ describe Spree::Admin::PromotionsController, type: :controller docontext 'cloning invalid promotion' dosubject do- post :clone, params: { id: promotion3.id }+ post :clone, params: { id: promotion4.id }end- let!(:promotion3) { create(:promotion, name: 'Name3', code: 'code3', path: '') }+ let(:promotion4) { create(:promotion, stores: [store]) }before do- promotion_duplicator_mock = Spree::PromotionHandler::PromotionDuplicator.new(promotion3, random_string: "ABCD")+ promotion_duplicator_mock = Spree::PromotionHandler::PromotionDuplicator.new(promotion4, random_string: "ABCD")allow(Spree::PromotionHandler::PromotionDuplicator).to receive(:new).- with(promotion3).and_return(promotion_duplicator_mock)+ with(promotion4).and_return(promotion_duplicator_mock)create(:promotion, name: 'Name4', code: 'code4', path: '_ABCD') # promotion 4end@@ -86,4 +90,29 @@ describe Spree::Admin::PromotionsController, type: :controller doendendend++ describe '#destroy' do+ subject(:send_request) do+ delete :destroy, params: { id: promotion, format: :js }+ end++ context 'will successfully destroy promotion' do+ let!(:promotion) { create(:promotion, stores: [store, store_2]) }++ describe 'returns response' do+ before { send_request }++ it { expect(assigns(:promotion)).to eq(promotion) }+ it { expect(response).to have_http_status(:ok) }+ it { expect(flash[:success]).to eq("Promotion \"#{promotion.name}\" has been successfully removed!") }+ end+ end++ context 'cannot destroy promotion from different store' do+ let!(:promotion) { create(:promotion, stores: [store_2]) }++ it { expect(send_request).to redirect_to(spree.admin_promotions_path) }+ it { expect { send_request }.not_to change { Spree::Promotion.count } }+ end+ endenddiff --git a/backend/spec/features/admin/promotions/promotion_spec.rb b/backend/spec/features/admin/promotions/promotion_spec.rbindex 8cdbcfed48..65d73dafa7 100644--- a/backend/spec/features/admin/promotions/promotion_spec.rb+++ b/backend/spec/features/admin/promotions/promotion_spec.rb@@ -3,6 +3,9 @@ require 'spec_helper'describe 'Create New Promotion', type: :feature, js: true dostub_authorization!+ let(:store) { Spree::Store.default }+ let!(:store_2) { create(:store) }+context 'coupon promotions' dobefore dovisit spree.new_admin_promotion_path@@ -14,8 +17,9 @@ describe 'Create New Promotion', type: :feature, js: true doclick_button 'Create'- promotion = Spree::Promotion.find_by(name: 'Promotion 1')+ promotion = store.promotions.find_by!(name: 'Promotion 1')expect(page).to have_field(id: 'promotion_code', with: promotion.code)+ expect(promotion.stores).to eq([store])endit 'Allows you to set a promotion with start and end time' do@@ -30,5 +34,17 @@ describe 'Create New Promotion', type: :feature, js: true doexpect(page).to have_field(id: 'promotion_starts_at', type: :hidden, with: '2012-01-24 16:45')expect(page).to have_field(id: 'promotion_expires_at', type: :hidden, with: '2012-01-25 22:10')end++ it 'allows assigning multiple stores' do+ fill_in 'Name', with: 'Promotion 3'+ select2 store_2.unique_name, from: 'Stores'++ click_button 'Create'++ expect(page).to have_content('successfully created')++ promotion = store.promotions.find_by!(name: 'Promotion 3')+ expect(promotion.stores).to contain_exactly(store, store_2)+ endendenddiff --git a/backend/spec/helpers/spree/admin/promotion_rules_helper_spec.rb b/backend/spec/helpers/spree/admin/promotion_rules_helper_spec.rbindex 3197763e93..6cbde1318e 100644--- a/backend/spec/helpers/spree/admin/promotion_rules_helper_spec.rb+++ b/backend/spec/helpers/spree/admin/promotion_rules_helper_spec.rb@@ -2,7 +2,7 @@ require 'spec_helper'module Spreedescribe Spree::Admin::PromotionRulesHelper, type: :helper doit 'does not include existing rules in options' do- promotion = Spree::Promotion.new+ promotion = build(:promotion)promotion.promotion_rules << Spree::Promotion::Rules::ItemTotal.newoptions = helper.options_for_promotion_rule_types(promotion)diff --git a/core/app/models/spree/promotion.rb b/core/app/models/spree/promotion.rbindex a267c93d4a..5fd49437ba 100644--- a/core/app/models/spree/promotion.rb+++ b/core/app/models/spree/promotion.rb@@ -1,5 +1,7 @@module Spreeclass Promotion < Spree::Base+ include MultiStoreResource+MATCH_POLICIES = %w(all any)UNACTIVATABLE_ORDER_STATES = ['complete', 'awaiting_return', 'returned']@@ -16,6 +18,8 @@ module Spreehas_many :order_promotions, class_name: 'Spree::OrderPromotion'has_many :orders, through: :order_promotions, class_name: 'Spree::Order'+ has_and_belongs_to_many :stores, class_name: 'Spree::Store', join_table: 'spree_promotions_stores'+accepts_nested_attributes_for :promotion_actions, :promotion_rulesvalidates_associated :rulesdiff --git a/core/app/models/spree/promotion/rules/first_order.rb b/core/app/models/spree/promotion/rules/first_order.rbindex 7cd39fcec0..269a800493 100644--- a/core/app/models/spree/promotion/rules/first_order.rb+++ b/core/app/models/spree/promotion/rules/first_order.rb@@ -2,7 +2,7 @@ module Spreeclass Promotionmodule Rulesclass FirstOrder < PromotionRule- attr_reader :user, :email+ attr_reader :user, :email, :storedef applicable?(promotable)promotable.is_a?(Spree::Order)@@ -11,6 +11,7 @@ module Spreedef eligible?(order, options = {})@user = order.try(:user) || options[:user]@email = order.email+ @store = order.storeif user || emailif !completed_orders.blank? && completed_orders.first != order@@ -26,12 +27,11 @@ module Spreeprivatedef completed_orders- user ? user.orders.complete : orders_by_email+ user ? user.orders.for_store(store).complete : orders_by_emailenddef orders_by_email- # FIXME: this will need a change after we associate Promotion with Store- Spree::Order.where(email: email).complete+ store.orders.where(email: email).completeendendenddiff --git a/core/app/models/spree/promotion/rules/taxon.rb b/core/app/models/spree/promotion/rules/taxon.rbindex 97a2c31a10..b2765ec066 100644--- a/core/app/models/spree/promotion/rules/taxon.rb+++ b/core/app/models/spree/promotion/rules/taxon.rb@@ -30,7 +30,12 @@ module Spreeenddef actionable?(line_item)- taxon_product_ids.include? line_item.variant.product_id+ store = line_item.order.store++ store.products.+ joins(:classifications).+ where(Spree::Classification.table_name => { taxon_id: taxon_ids, product_id: line_item.product_id }).+ exists?enddef taxon_ids_string@@ -39,14 +44,16 @@ module Spreedef taxon_ids_string=(s)ids = s.to_s.split(',').map(&:strip)- self.taxons = Spree::Taxon.find(ids)+ self.taxons = Spree::Taxon.for_stores(stores).find(ids)endprivate# All taxons in an orderdef order_taxons(order)- Spree::Taxon.joins(products: { variants_including_master: :line_items }).where(spree_line_items: { order_id: order.id }).distinct+ taxon_ids = Spree::Classification.where(product_id: order.product_ids).pluck(:taxon_id).uniq++ order.store.taxons.where(id: taxon_ids)end# ids of taxons rules and taxons rules children@@ -62,10 +69,6 @@ module Spreedef taxons_in_order_including_parents(order)order_taxons_in_taxons_and_children(order).inject([]) { |taxons, taxon| taxons << taxon.self_and_ancestors }.flatten.uniqend-- def taxon_product_ids- Spree::Product.joins(:taxons).where(spree_taxons: { id: taxons.pluck(:id) }).pluck(:id).uniq- endendendenddiff --git a/core/app/models/spree/promotion_handler/cart.rb b/core/app/models/spree/promotion_handler/cart.rbindex 571134c447..dca8aeebfd 100644--- a/core/app/models/spree/promotion_handler/cart.rb+++ b/core/app/models/spree/promotion_handler/cart.rb@@ -13,12 +13,13 @@ module Spree# the promotions system accurate and performant. Here they can plug custom# handler to activate promos as they wish once an item is added to cartclass Cart- attr_reader :line_item, :order+ attr_reader :line_item, :order, :storeattr_accessor :error, :successdef initialize(order, line_item = nil)@order = order@line_item = line_item+ @store = order.storeenddef activate@@ -34,7 +35,11 @@ module Spreeprivatedef promotions- Promotion.find_by_sql("#{order.promotions.active.to_sql} UNION #{Promotion.active.where(code: nil, path: nil).to_sql}")+ promotion_scope.find_by_sql("#{order.promotions.active.to_sql} UNION #{promotion_scope.active.where(code: nil, path: nil).to_sql}")+ end++ def promotion_scope+ ::Spree::Promotion.for_store(store)endendenddiff --git a/core/app/models/spree/promotion_handler/coupon.rb b/core/app/models/spree/promotion_handler/coupon.rbindex bc6796d8ee..a2093e8e41 100644--- a/core/app/models/spree/promotion_handler/coupon.rb+++ b/core/app/models/spree/promotion_handler/coupon.rb@@ -1,18 +1,19 @@module Spreemodule PromotionHandlerclass Coupon- attr_reader :order+ attr_reader :order, :storeattr_accessor :error, :success, :status_codedef initialize(order)@order = order+ @store = order.storeenddef applyif order.coupon_code.present?if promotion.present? && promotion.actions.exists?handle_present_promotion- elsif Promotion.with_coupon_code(order.coupon_code).try(:expired?)+ elsif store.promotions.with_coupon_code(order.coupon_code).try(:expired?)set_error_code :coupon_code_expiredelseset_error_code :coupon_code_not_found@@ -51,7 +52,7 @@ module Spreeenddef promotion- @promotion ||= Promotion.active.includes(+ @promotion ||= store.promotions.active.includes(:promotion_rules, :promotion_actions).with_coupon_code(order.coupon_code)enddiff --git a/core/app/models/spree/promotion_handler/free_shipping.rb b/core/app/models/spree/promotion_handler/free_shipping.rbindex da26abb7e6..cc76b879b0 100644--- a/core/app/models/spree/promotion_handler/free_shipping.rb+++ b/core/app/models/spree/promotion_handler/free_shipping.rb@@ -2,12 +2,13 @@ module Spreemodule PromotionHandler# Used for activating promotions with shipping rulesclass FreeShipping- attr_reader :order, :order_promo_ids+ attr_reader :order, :order_promo_ids, :storeattr_accessor :error, :successdef initialize(order)@order = order- @order_promo_ids = order.promotions.pluck(:id)+ @store = order.store+ @order_promo_ids = order.promotions.idsenddef activate@@ -21,10 +22,8 @@ module Spreeprivatedef promotions- Spree::Promotion.active.where(- id: Spree::Promotion::Actions::FreeShipping.pluck(:promotion_id),- path: nil- )+ store.promotions.active.joins(:promotion_actions).+ where(Spree::PromotionAction.table_name => { type: 'Spree::Promotion::Actions::FreeShipping' }, path: nil).distinctendendenddiff --git a/core/app/models/spree/promotion_handler/page.rb b/core/app/models/spree/promotion_handler/page.rbindex f468ea83ef..3886bbc9d7 100644--- a/core/app/models/spree/promotion_handler/page.rb+++ b/core/app/models/spree/promotion_handler/page.rb@@ -1,10 +1,11 @@module Spreemodule PromotionHandlerclass Page- attr_reader :order, :path+ attr_reader :order, :path, :storedef initialize(order, path)@order = order+ @store = order.store@path = path.gsub(/\A\//, '')end@@ -17,7 +18,7 @@ module Spreeprivatedef promotion- @promotion ||= Promotion.active.find_by(path: path)+ @promotion ||= store.promotions.active.find_by(path: path)endendenddiff --git a/core/app/models/spree/promotion_handler/promotion_duplicator.rb b/core/app/models/spree/promotion_handler/promotion_duplicator.rbindex f6d45b8858..e88c34bb96 100644--- a/core/app/models/spree/promotion_handler/promotion_duplicator.rb+++ b/core/app/models/spree/promotion_handler/promotion_duplicator.rb@@ -11,6 +11,7 @@ module Spree@new_promotion.path = "#{@promotion.path}_#{@random_string}"@new_promotion.name = "New #{@promotion.name}"@new_promotion.code = "#{@promotion.code}_#{@random_string}"+ @new_promotion.stores = @promotion.storesActiveRecord::Base.transaction do@new_promotion.savediff --git a/core/app/models/spree/promotion_rule.rb b/core/app/models/spree/promotion_rule.rbindex 5e11e3925d..43ed52310c 100644--- a/core/app/models/spree/promotion_rule.rb+++ b/core/app/models/spree/promotion_rule.rb@@ -3,6 +3,8 @@ module Spreeclass PromotionRule < Spree::Basebelongs_to :promotion, class_name: 'Spree::Promotion', inverse_of: :promotion_rules+ delegate :stores, to: :promotion+scope :of_type, ->(t) { where(type: t) }validate :unique_per_promotion, on: :creatediff --git a/core/app/models/spree/store.rb b/core/app/models/spree/store.rbindex 08aced0d0d..c40a507f0e 100644--- a/core/app/models/spree/store.rb+++ b/core/app/models/spree/store.rb@@ -29,6 +29,9 @@ module Spreehas_many :taxonomies, class_name: 'Spree::Taxonomy'has_many :taxons, through: :taxonomies, class_name: 'Spree::Taxon'+ has_many :store_promotions, class_name: 'Spree::StorePromotion'+ has_many :promotions, through: :store_promotions, class_name: 'Spree::Promotion'+belongs_to :default_country, class_name: 'Spree::Country'belongs_to :checkout_zone, class_name: 'Spree::Zone'diff --git a/core/app/models/spree/store_promotion.rb b/core/app/models/spree/store_promotion.rbnew file mode 100644index 0000000000..ba0514ef05--- /dev/null+++ b/core/app/models/spree/store_promotion.rb@@ -0,0 +1,11 @@+module Spree+ class StorePromotion < Spree::Base+ self.table_name = 'spree_promotions_stores'++ belongs_to :store, class_name: 'Spree::Store', touch: true+ belongs_to :promotion, class_name: 'Spree::Promotion', touch: true++ validates :store, :promotion, presence: true+ validates :store_id, uniqueness: { scope: :promotion_id }+ end+enddiff --git a/core/app/models/spree/taxon.rb b/core/app/models/spree/taxon.rbindex 6f89c14d91..d7d59c1b11 100644--- a/core/app/models/spree/taxon.rb+++ b/core/app/models/spree/taxon.rb@@ -39,6 +39,8 @@ module Spreeself.whitelisted_ransackable_associations = %w[taxonomy]+ scope :for_stores, ->(stores) { joins(:taxonomy).where(spree_taxonomies: { store_id: stores.ids }) }+# indicate which filters should be used for a taxon# this method should be customized to your own sitedef applicable_filtersdiff --git a/core/db/migrate/20210721125657_create_spree_promotions_stores.rb b/core/db/migrate/20210721125657_create_spree_promotions_stores.rbnew file mode 100644index 0000000000..df5a0a0b97--- /dev/null+++ b/core/db/migrate/20210721125657_create_spree_promotions_stores.rb@@ -0,0 +1,29 @@+class CreateSpreePromotionsStores < ActiveRecord::Migration[5.2]+ def up+ unless table_exists?(:spree_promotions_stores)+ create_table :spree_promotions_stores do |t|+ t.references :promotion, index: true+ t.references :store, index: true+ t.timestamps++ t.index [:promotion_id, :store_id], unique: true+ end++ stores = Spree::Store.all+ promotion_ids = Spree::Promotion.order(:id).ids++ stores.find_each do |store|+ prepared_values = promotion_ids.map { |id| "(#{id}, #{store.id}, '#{Time.current.to_s(:db)}', '#{Time.current.to_s(:db)}')" }.join(', ')+ next if prepared_values.empty?++ begin+ execute "INSERT INTO spree_promotions_stores (promotion_id, store_id, created_at, updated_at) VALUES #{prepared_values};"+ rescue ActiveRecord::RecordNotUnique; end+ end+ end+ end++ def down+ drop_table :spree_promotions_stores+ end+enddiff --git a/core/lib/spree/testing_support/factories/promotion_factory.rb b/core/lib/spree/testing_support/factories/promotion_factory.rbindex a1fdc8a3c6..09b1f4c71b 100644--- a/core/lib/spree/testing_support/factories/promotion_factory.rb+++ b/core/lib/spree/testing_support/factories/promotion_factory.rb@@ -19,6 +19,15 @@ FactoryBot.define dofactory :promotion, class: Spree::Promotion doname { 'Promo' }+ before(:create) do |promotion, _evaluator|+ if promotion.stores.empty?+ default_store = Spree::Store.default.persisted? ? Spree::Store.default : nil+ store = default_store || create(:store)++ promotion.stores << [store]+ end+ end+trait :with_line_item_adjustment dotransient doadjustment_rate { 10 }@@ -57,17 +66,17 @@ FactoryBot.define dofactory :promotion_with_order_adjustment, traits: [:with_order_adjustment]factory :promotion_with_item_total_rule, traits: [:with_item_total_rule]- end- factory :free_shipping_promotion, class: Spree::Promotion do- name { 'Free Shipping Promotion' }+ factory :free_shipping_promotion do+ name { 'Free Shipping Promotion' }- after(:create) do |promotion|- action = Spree::Promotion::Actions::FreeShipping.new- action.promotion = promotion- action.save- end+ after(:create) do |promotion|+ action = Spree::Promotion::Actions::FreeShipping.new+ action.promotion = promotion+ action.save+ end- factory :free_shipping_promotion_with_item_total_rule, traits: [:with_item_total_rule]+ factory :free_shipping_promotion_with_item_total_rule, traits: [:with_item_total_rule]+ endendenddiff --git a/core/spec/models/spree/adjustable/adjuster/tax_spec.rb b/core/spec/models/spree/adjustable/adjuster/tax_spec.rbindex 1d7b142b64..c0464fc903 100644--- a/core/spec/models/spree/adjustable/adjuster/tax_spec.rb+++ b/core/spec/models/spree/adjustable/adjuster/tax_spec.rb@@ -13,7 +13,7 @@ describe Spree::Adjustable::Adjuster::Tax, type: :model doendlet!(:promotion) do- Spree::Promotion.create(name: '$10 off')+ create(:promotion, name: '$10 off')endlet!(:promotion_action) dodiff --git a/core/spec/models/spree/order/totals_spec.rb b/core/spec/models/spree/order/totals_spec.rbindex 438791ed43..2f3756ce90 100644--- a/core/spec/models/spree/order/totals_spec.rb+++ b/core/spec/models/spree/order/totals_spec.rb@@ -2,11 +2,12 @@ require 'spec_helper'module Spreedescribe Order, type: :model do- let(:order) { Order.create }+ let(:store) { create(:store) }+ let(:order) { create(:order, store: store) }let(:shirt) { create(:variant) }context 'adds item to cart and activates promo' do- let(:promotion) { Promotion.create name: 'Huhu' }+ let(:promotion) { create(:promotion, name: 'Huhu', stores: [store]) }let(:calculator) { Calculator::FlatPercentItemTotal.new(preferred_flat_percent: 10) }let!(:action) { Promotion::Actions::CreateAdjustment.create(promotion: promotion, calculator: calculator) }diff --git a/core/spec/models/spree/order_updater_spec.rb b/core/spec/models/spree/order_updater_spec.rbindex abcd6dac32..77aba9259d 100644--- a/core/spec/models/spree/order_updater_spec.rb+++ b/core/spec/models/spree/order_updater_spec.rb@@ -29,7 +29,7 @@ module Spreeendcontext 'with order promotion followed by line item addition' do- let(:promotion) { Spree::Promotion.create!(name: '10% off') }+ let(:promotion) { create(:promotion, name: '10% off') }let(:calculator) { Calculator::FlatPercentItemTotal.new(preferred_flat_percent: 10) }let(:promotion_action) dodiff --git a/core/spec/models/spree/promotion/rules/first_order_spec.rb b/core/spec/models/spree/promotion/rules/first_order_spec.rbindex bd17b72b3a..70d0e0d244 100644--- a/core/spec/models/spree/promotion/rules/first_order_spec.rb+++ b/core/spec/models/spree/promotion/rules/first_order_spec.rb@@ -1,12 +1,15 @@require 'spec_helper'describe Spree::Promotion::Rules::FirstOrder, type: :model do- let(:rule) { Spree::Promotion::Rules::FirstOrder.new }- let(:order) { mock_model(Spree::Order, user: nil, email: nil) }- let(:user) { mock_model(Spree::LegacyUser) }+ let(:store) { create(:store) }+ let(:rule) { described_class.new }+ let(:user) { create(:user) }context 'without a user or email' do+ let(:order) { create(:order, store: store, email: nil, user: nil) }+it { expect(rule).not_to be_eligible(order) }+it 'sets an error message' dorule.eligible?(order)expect(rule.eligibility_errors.full_messages.first).@@ -16,11 +19,9 @@ describe Spree::Promotion::Rules::FirstOrder, type: :model docontext 'first order' docontext 'for a signed user' do- context 'with no completed orders' do- before do- allow(user).to receive_message_chain(:orders, complete: [])- end+ let(:order) { create(:order, store: store, user: user) }+ context 'with no completed orders' dospecify doallow(order).to receive_messages(user: user)expect(rule).to be_eligible(order)@@ -32,19 +33,19 @@ describe Spree::Promotion::Rules::FirstOrder, type: :model doendcontext 'with completed orders' do- before do- allow(order).to receive_messages(user: user)- end+ let(:order) { create(:completed_order_with_totals, store: store, user: user) }it 'is eligible when checked against first completed order' do- allow(user).to receive_message_chain(:orders, complete: [order])expect(rule).to be_eligible(order)endcontext 'with another order' do- before { allow(user).to receive_message_chain(:orders, complete: [mock_model(Spree::Order)]) }+ before do+ create(:completed_order_with_totals, user: user, store: store)+ endit { expect(rule).not_to be_eligible(order) }+it 'sets an error message' dorule.eligible?(order)expect(rule.eligibility_errors.full_messages.first).@@ -57,16 +58,17 @@ describe Spree::Promotion::Rules::FirstOrder, type: :model docontext 'for a guest user' dolet(:email) { '[email protected]' }- before { allow(order).to receive_messages email: '[email protected]' }+ let(:order) { create(:order, store: store, email: email, user: nil) }context 'with no other orders' doit { expect(rule).to be_eligible(order) }endcontext 'with another order' do- before { allow(rule).to receive_messages(orders_by_email: [mock_model(Spree::Order)]) }+ before { create(:completed_order_with_totals, email: email, store: store, user: nil) }it { expect(rule).not_to be_eligible(order) }+it 'sets an error message' dorule.eligible?(order)expect(rule.eligibility_errors.full_messages.first).diff --git a/core/spec/models/spree/promotion/rules/taxon_spec.rb b/core/spec/models/spree/promotion/rules/taxon_spec.rbindex 3d59fcf102..3c63fdc45f 100644--- a/core/spec/models/spree/promotion/rules/taxon_spec.rb+++ b/core/spec/models/spree/promotion/rules/taxon_spec.rb@@ -6,8 +6,9 @@ describe Spree::Promotion::Rules::Taxon, type: :model dolet(:store) { create(:store) }context '#elegible?(order)' do- let(:taxon) { create :taxon, name: 'first' }- let(:taxon2) { create :taxon, name: 'second' }+ let(:taxonomy) { create(:taxonomy, store: store) }+ let(:taxon) { create :taxon, name: 'first', taxonomy: taxonomy }+ let(:taxon2) { create :taxon, name: 'second', taxonomy: taxonomy }let(:order) { create :order_with_line_items, store: store }before do@@ -89,7 +90,7 @@ describe Spree::Promotion::Rules::Taxon, type: :model doendcontext 'when a product has a taxon child of a taxon rule' do- let(:taxon3) { create :taxon }+ let(:taxon3) { create :taxon, taxonomy: taxonomy }before dotaxon.children << taxon2diff --git a/core/spec/models/spree/promotion_handler/cart_spec.rb b/core/spec/models/spree/promotion_handler/cart_spec.rbindex 024ee40835..71b5103a83 100644--- a/core/spec/models/spree/promotion_handler/cart_spec.rb+++ b/core/spec/models/spree/promotion_handler/cart_spec.rb@@ -8,7 +8,7 @@ module Spreelet(:line_item) { create(:line_item) }let(:order) { line_item.order }- let(:promotion) { Promotion.create(name: 'At line items') }+ let(:promotion) { create(:promotion, name: 'At line items', stores: [order.store]) }let(:calculator) { Calculator::FlatPercentItemTotal.new(preferred_flat_percent: 10) }context 'activates in LineItem level' dodiff --git a/core/spec/models/spree/promotion_handler/coupon_spec.rb b/core/spec/models/spree/promotion_handler/coupon_spec.rbindex d9f4a52dc1..4db976cc1a 100644--- a/core/spec/models/spree/promotion_handler/coupon_spec.rb+++ b/core/spec/models/spree/promotion_handler/coupon_spec.rb@@ -66,7 +66,7 @@ module Spreeendcontext 'existing coupon code promotion' do- let!(:promotion) { create(:promotion, :with_line_item_adjustment, adjustment_rate: 10, code: '10off') }+ let!(:promotion) { create(:promotion, :with_line_item_adjustment, adjustment_rate: 10, code: '10off', stores: [store]) }it 'fetches with given code' doexpect(subject.promotion).to eq promotion@@ -121,7 +121,7 @@ module Spreebefore doallow(order).to receive_messages coupon_code: '10off'calculator = Calculator::FlatRate.new(preferred_amount: 10)- general_promo = Promotion.create name: 'General Promo'+ general_promo = create(:promotion, name: 'General Promo', stores: [order.store])Promotion::Actions::CreateItemAdjustments.create(promotion: general_promo, calculator: calculator) # general_actionSpree::Cart::AddItem.call(order: order, variant: create(:variant))@@ -260,7 +260,7 @@ module Spreeendcontext 'and multiple quantity per line item' do- let(:promotion) { create(:promotion, :with_line_item_adjustment, adjustment_rate: 20, code: '20off') }+ let(:promotion) { create(:promotion, :with_line_item_adjustment, adjustment_rate: 20, code: '20off', stores: [store]) }let(:product_list) { create_list(:product, 3, tax_category: tax_category, price: 10.0, stores: [store]) }before dodiff --git a/core/spec/models/spree/promotion_handler/free_shipping_spec.rb b/core/spec/models/spree/promotion_handler/free_shipping_spec.rbindex acd5c83bdf..8754d907bb 100644--- a/core/spec/models/spree/promotion_handler/free_shipping_spec.rb+++ b/core/spec/models/spree/promotion_handler/free_shipping_spec.rb@@ -8,7 +8,7 @@ module Spreelet(:order) { create(:order) }let(:shipment) { create(:shipment, order: order) }- let(:promotion) { Promotion.create(name: 'Free Shipping') }+ let(:promotion) { create(:promotion, name: 'Free Shipping', stores: [order.store]) }let(:calculator) { Calculator::FlatPercentItemTotal.new(preferred_flat_percent: 10) }let!(:action) { Promotion::Actions::FreeShipping.create(promotion: promotion) }diff --git a/core/spec/models/spree/promotion_handler/page_spec.rb b/core/spec/models/spree/promotion_handler/page_spec.rbindex ccd08ab32c..25e8c21a4e 100644--- a/core/spec/models/spree/promotion_handler/page_spec.rb+++ b/core/spec/models/spree/promotion_handler/page_spec.rb@@ -5,7 +5,7 @@ module Spreedescribe Page, type: :model dolet(:order) { create(:order_with_line_items, line_items_count: 1) }- let(:promotion) { Promotion.create(name: '10% off', path: '10off') }+ let(:promotion) { create(:promotion, name: '10% off', path: '10off', stores: [order.store]) }before docalculator = Calculator::FlatPercentItemTotal.new(preferred_flat_percent: 10)diff --git a/core/spec/models/spree/promotion_handler/promotion_duplicator_spec.rb b/core/spec/models/spree/promotion_handler/promotion_duplicator_spec.rbindex 848b960d9a..3516efd698 100644--- a/core/spec/models/spree/promotion_handler/promotion_duplicator_spec.rb+++ b/core/spec/models/spree/promotion_handler/promotion_duplicator_spec.rb@@ -6,6 +6,8 @@ describe Spree::PromotionHandler::PromotionDuplicator dolet!(:promo_category) { create(:promotion_category) }let!(:calculator) { create(:calculator) }+ let(:store) { create(:store) }+ let(:store_2) { create(:store) }let!(:promotion) docreate(:promotion_with_item_total_rule,description: 'Test description',@@ -16,7 +18,8 @@ describe Spree::PromotionHandler::PromotionDuplicator docode: 'test1',advertise: true,path: 'test1',- promotion_category: promo_category)+ promotion_category: promo_category,+ stores: [store, store_2])endbefore do@@ -70,6 +73,10 @@ describe Spree::PromotionHandler::PromotionDuplicator doexpect(promotion.promotion_actions.size).to eq new_promotion.promotion_actions.sizeend+ it 'copies promotion stores' do+ expect(promotion.store_ids).to eq new_promotion.store_ids+ end+it "promotion action's fields (except promotion_id) are the same" doold_action = promotion.promotion_actions.firstnew_action = new_promotion.promotion_actions.firstdiff --git a/core/spec/models/spree/promotion_spec.rb b/core/spec/models/spree/promotion_spec.rbindex 1cb5c5693e..fa9b00335e 100644--- a/core/spec/models/spree/promotion_spec.rb+++ b/core/spec/models/spree/promotion_spec.rb@@ -2,11 +2,11 @@ require 'spec_helper'describe Spree::Promotion, type: :model dolet(:store) { create(:store) }- let(:promotion) { Spree::Promotion.new }+ let(:promotion) { create(:promotion) }describe 'validations' dobefore do- @valid_promotion = Spree::Promotion.new name: 'A promotion'+ @valid_promotion = build(:promotion, name: 'A promotion', stores: [create(:store)])endit 'valid_promotion is valid' do@@ -38,7 +38,7 @@ describe Spree::Promotion, type: :model doendcontext 'code is not unique' do- let!(:promotion_with_code) { Spree::Promotion.create! name: 'test1', code: code }+ let!(:promotion_with_code) { create :promotion, name: 'test1', code: code }context 'code is identical' dobefore do@@ -99,8 +99,8 @@ describe Spree::Promotion, type: :model dodescribe '.coupons' dosubject { Spree::Promotion.coupons }- let!(:promotion_without_code) { Spree::Promotion.create! name: 'test', code: '' }- let!(:promotion_with_code) { Spree::Promotion.create! name: 'test1', code: 'code' }+ let!(:promotion_without_code) { create :promotion, name: 'test', code: '' }+ let!(:promotion_with_code) { create :promotion, name: 'test1', code: 'code' }it 'is expected to not include promotion without code' doexpect(subject).not_to include(promotion_without_code)@@ -114,10 +114,10 @@ describe Spree::Promotion, type: :model dodescribe '.applied' dosubject { Spree::Promotion.applied }- let!(:promotion_not_applied) { Spree::Promotion.create! name: 'test', code: '' }+ let!(:promotion_not_applied) { create :promotion, name: 'test', code: '' }let(:order) { create(:order) }let!(:promotion_applied) do- promotion = Spree::Promotion.create!(name: 'test1', code: '')+ promotion = create(:promotion, name: 'test1', code: '')promotion.orders << orderpromotionend@@ -134,8 +134,8 @@ describe Spree::Promotion, type: :model dodescribe '.advertised' dosubject { Spree::Promotion.advertised }- let!(:promotion_not_advertised) { Spree::Promotion.create! name: 'test', advertise: false }- let!(:promotion_advertised) { Spree::Promotion.create! name: 'test1', advertise: true }+ let!(:promotion_not_advertised) { create :promotion, name: 'test', advertise: false }+ let!(:promotion_advertised) { create :promotion, name: 'test1', advertise: true }it 'is expected to not include promotion not advertised' doexpect(subject).not_to include(promotion_not_advertised)@@ -148,7 +148,7 @@ describe Spree::Promotion, type: :model doenddescribe '#destroy' do- let(:promotion) { Spree::Promotion.create(name: 'delete me') }+ let(:promotion) { create(:promotion, name: 'delete me') }before dopromotion.actions << Spree::Promotion::Actions::CreateAdjustment.new@@ -167,7 +167,7 @@ describe Spree::Promotion, type: :model doenddescribe '#save' do- let(:promotion) { Spree::Promotion.create(name: 'delete me') }+ let(:promotion) { create(:promotion, name: 'delete me') }before dopromotion.actions << Spree::Promotion::Actions::CreateAdjustment.new@@ -301,12 +301,7 @@ describe Spree::Promotion, type: :model doendcontext '#credits_count' do- let!(:promotion) do- promotion = Spree::Promotion.new- promotion.name = 'Foo'- promotion.code = 'XXX'- promotion.tap(&:save)- end+ let!(:promotion) { create(:promotion, name: 'Foo', code: 'XXX') }let!(:action) docalculator = Spree::Calculator::FlatRate.new@@ -342,7 +337,7 @@ describe Spree::Promotion, type: :model docontext '#adjusted_credits_count' dolet(:order) { create :order }let(:line_item) { create :line_item, order: order }- let(:promotion) { Spree::Promotion.create name: 'promo', code: '10off' }+ let(:promotion) { create(:promotion, name: 'promo', code: '10off') }let(:order_action) doaction = Spree::Promotion::Actions::CreateAdjustment.create(calculator: Spree::Calculator::FlatPercentItemTotal.new)promotion.actions << action@@ -525,7 +520,7 @@ describe Spree::Promotion, type: :model doendcontext "with 'any' match policy" do- let(:promotion) { Spree::Promotion.create(name: 'Promo', match_policy: 'any') }+ let(:promotion) { create(:promotion, name: 'Promo', match_policy: 'any') }let(:promotable) { double('Promotable') }it 'has eligible rules if any of the rules are eligible' do@@ -624,7 +619,7 @@ describe Spree::Promotion, type: :model do# admin form posts the code and path as empty stringdescribe 'normalize blank values for code & path' doit 'will save blank value as nil value instead' do- promotion = Spree::Promotion.create(name: 'A promotion', code: '', path: '')+ promotion = create(:promotion, name: 'A promotion', code: '', path: '')expect(promotion.code).to be_nilexpect(promotion.path).to be_nilenddiff --git a/core/spec/models/spree/store_spec.rb b/core/spec/models/spree/store_spec.rbindex 88ffd71aa7..90db7b887c 100644--- a/core/spec/models/spree/store_spec.rb+++ b/core/spec/models/spree/store_spec.rb@@ -132,6 +132,13 @@ describe Spree::Store, type: :model doit { expect(subject.taxons).to match_array([taxonomy.root, taxon]) }endend++ describe '#promotions' do+ let!(:promotion) { create(:promotion, stores: [subject, create(:store)]) }+ let!(:promotion_2) { create(:promotion, stores: [create(:store)]) }++ it { expect(subject.promotions).to eq([promotion]) }+ endenddescribe 'validations' dodiff --git a/frontend/spec/features/automatic_promotion_adjustments_spec.rb b/frontend/spec/features/automatic_promotion_adjustments_spec.rbindex 7a8a37e13c..8e46dce484 100644--- a/frontend/spec/features/automatic_promotion_adjustments_spec.rb+++ b/frontend/spec/features/automatic_promotion_adjustments_spec.rb@@ -11,7 +11,7 @@ describe 'Automatic promotions', type: :feature, js: true docreate(:shipping_method)create(:check_payment_method)- promotion = Spree::Promotion.create!(name: '$10 off when you spend more than $100')+ promotion = create(:promotion, name: '$10 off when you spend more than $100')calculator = Spree::Calculator::FlatRate.newcalculator.preferred_amount = 10diff --git a/frontend/spec/features/cart_spec.rb b/frontend/spec/features/cart_spec.rbindex 5b617fb2fa..ef7a055065 100644--- a/frontend/spec/features/cart_spec.rb+++ b/frontend/spec/features/cart_spec.rb@@ -52,7 +52,7 @@ describe 'Cart', type: :feature, inaccessible: true, js: true doenddescribe 'add promotion coupon on cart page' do- let!(:promotion) { Spree::Promotion.create!(name: 'Huhuhu', code: 'huhu') }+ let!(:promotion) { create(:promotion, name: 'Huhuhu', code: 'huhu') }let!(:calculator) { Spree::Calculator::FlatPercentItemTotal.create!(preferred_flat_percent: '10') }let!(:action) { Spree::Promotion::Actions::CreateAdjustment.create!(calculator: calculator) }@@ -103,7 +103,7 @@ describe 'Cart', type: :feature, inaccessible: true, js: true doenddescribe 'subtotal' do- let!(:promotion) { Spree::Promotion.create!(name: 'Huhuhu', code: 'huhu') }+ let!(:promotion) { create(:promotion, name: 'Huhuhu', code: 'huhu') }let!(:calculator) { Spree::Calculator::FlatPercentItemTotal.create!(preferred_flat_percent: '10') }let!(:action) { Spree::Promotion::Actions::CreateAdjustment.create!(calculator: calculator) }diff --git a/frontend/spec/features/checkout_spec.rb b/frontend/spec/features/checkout_spec.rbindex ab472a6e28..1203f9383c 100644--- a/frontend/spec/features/checkout_spec.rb+++ b/frontend/spec/features/checkout_spec.rb@@ -448,7 +448,7 @@ describe 'Checkout', type: :feature, inaccessible: true, js: true doendcontext 'if coupon promotion, submits coupon along with payment', js: true do- let!(:promotion) { Spree::Promotion.create(name: 'Huhuhu', code: 'huhu') }+ let!(:promotion) { create(:promotion, name: 'Huhuhu', code: 'huhu') }let!(:calculator) { Spree::Calculator::FlatPercentItemTotal.create(preferred_flat_percent: '10') }let!(:action) { Spree::Promotion::Actions::CreateItemAdjustments.create(calculator: calculator) }@@ -495,7 +495,7 @@ describe 'Checkout', type: :feature, inaccessible: true, js: true doendcontext 'the promotion makes order free (downgrade it total to 0.0)' do- let(:promotion2) { Spree::Promotion.create(name: 'test-7450', code: 'test-7450') }+ let(:promotion2) { create(:promotion, name: 'test-7450', code: 'test-7450') }let(:calculator2) doSpree::Calculator::FlatRate.create(preferences: { currency: 'USD', amount: BigDecimal('99999') })enddiff --git a/frontend/spec/features/coupon_code_spec.rb b/frontend/spec/features/coupon_code_spec.rbindex caa8ecc43b..9d6d5aa56c 100644--- a/frontend/spec/features/coupon_code_spec.rb+++ b/frontend/spec/features/coupon_code_spec.rb@@ -15,10 +15,10 @@ describe 'Coupon code promotions', type: :feature, js: true docontext 'visitor makes checkout as guest without registration' dodef create_basic_coupon_promotion(code)- promotion = Spree::Promotion.create!(name: code.titleize,- code: code,- starts_at: 1.day.ago,- expires_at: 1.day.from_now)+ promotion = create(:promotion, name: code.titleize,+ code: code,+ starts_at: 1.day.ago,+ expires_at: 1.day.from_now)calculator = Spree::Calculator::FlatRate.newcalculator.preferred_amount = 10diff --git a/frontend/spec/features/page_promotions_spec.rb b/frontend/spec/features/page_promotions_spec.rbindex 332b0e0658..efcaa2c874 100644--- a/frontend/spec/features/page_promotions_spec.rb+++ b/frontend/spec/features/page_promotions_spec.rb@@ -4,10 +4,10 @@ describe 'page promotions', type: :feature, js: true dolet(:mug) { create(:product, name: 'RoR Mug', price: 20) }before do- promotion = Spree::Promotion.create!(name: '$10 off',- path: 'test',- starts_at: 1.day.ago,- expires_at: 1.day.from_now)+ promotion = create(:promotion, name: '$10 off',+ path: 'test',+ starts_at: 1.day.ago,+ expires_at: 1.day.from_now)calculator = Spree::Calculator::FlatRate.newcalculator.preferred_amount = 10diff --git a/sample/db/samples/promotions.rb b/sample/db/samples/promotions.rbindex 8c42e77e0b..ecc0fe4233 100644--- a/sample/db/samples/promotions.rb+++ b/sample/db/samples/promotions.rb@@ -1,3 +1,4 @@+Spree::Sample.load_sample('stores')Spree::Sample.load_sample('option_values')Spree::Sample.load_sample('products')@@ -12,7 +13,9 @@ promotion = Spree::Promotion.where(path: nil,match_policy: 'any',description: ''-).first_or_create!+).first_or_create do |promo|+ promo.stores = Spree::Store.all+endSpree::PromotionRule.where(promotion_id: promotion.id,diff --git a/sample/db/samples/taxonomies.rb b/sample/db/samples/taxonomies.rbindex 2f0013ee2f..56e245c0c7 100644--- a/sample/db/samples/taxonomies.rb+++ b/sample/db/samples/taxonomies.rb@@ -1,3 +1,5 @@+Spree::Sample.load_sample('stores')+taxonomies = [{name: I18n.t('spree.taxonomy_categories_name'),