Skip to content

armgit / spree

Public Imported from GitHub
0

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.

Coupon code batches support :moneybag:

Damian Legawiec027b1dc9451f
diff --git a/api/spec/requests/spree/api/v2/platform/promotions_spec.rb b/api/spec/requests/spree/api/v2/platform/promotions_spec.rb
index 9b7012f852..df52f56484 100644
--- a/api/spec/requests/spree/api/v2/platform/promotions_spec.rb
+++ b/api/spec/requests/spree/api/v2/platform/promotions_spec.rb
@@ -82,7 +82,7 @@ describe 'Promotion API v2 spec', type: :request do
it 'creates and returns a promotion' do
# promotion
expect(json_response['data']).to have_attribute(:name).with_value(new_promotion_attributes[:name])
- expect(json_response['data']).to have_attribute(:code).with_value(new_promotion_attributes[:code])
+ expect(json_response['data']).to have_attribute(:code).with_value(new_promotion_attributes[:code].downcase)
expect(json_response['data']).to have_attribute(:match_policy).with_value(new_promotion_attributes[:match_policy])
expect(json_response['data']).to have_attribute(:type).with_value(new_promotion_attributes[:type])
expect(json_response['data']).to have_attribute(:description).with_value(new_promotion_attributes[:description])
@@ -117,7 +117,7 @@ describe 'Promotion API v2 spec', type: :request do
it 'updates and returns a promotion' do
# promotion
expect(json_response['data']).to have_attribute(:name).with_value(update_promotion_attributes[:name])
- expect(json_response['data']).to have_attribute(:code).with_value(update_promotion_attributes[:code])
+ expect(json_response['data']).to have_attribute(:code).with_value(update_promotion_attributes[:code].downcase)
expect(json_response['data']).to have_attribute(:match_policy).with_value(update_promotion_attributes[:match_policy])
expect(json_response['data']).to have_attribute(:type).with_value(update_promotion_attributes[:type])
expect(json_response['data']).to have_attribute(:description).with_value(update_promotion_attributes[:description])
diff --git a/api/spec/serializers/spree/api/v2/platform/promotion_serializer_spec.rb b/api/spec/serializers/spree/api/v2/platform/promotion_serializer_spec.rb
index 0f2c9bd9f5..98e83bd702 100644
--- a/api/spec/serializers/spree/api/v2/platform/promotion_serializer_spec.rb
+++ b/api/spec/serializers/spree/api/v2/platform/promotion_serializer_spec.rb
@@ -30,7 +30,11 @@ describe Spree::Api::V2::Platform::PromotionSerializer do
public_metadata: {},
private_metadata: {},
created_at: resource.created_at,
- updated_at: resource.updated_at
+ updated_at: resource.updated_at,
+ multi_codes: resource.multi_codes,
+ code_prefix: resource.code_prefix,
+ number_of_codes: resource.number_of_codes,
+ kind: resource.kind
},
relationships: {
promotion_category: {
diff --git a/core/app/jobs/spree/coupon_codes/bulk_generate_job.rb b/core/app/jobs/spree/coupon_codes/bulk_generate_job.rb
new file mode 100644
index 0000000000..88140fcad2
--- /dev/null
+++ b/core/app/jobs/spree/coupon_codes/bulk_generate_job.rb
@@ -0,0 +1,15 @@
+module Spree
+ module CouponCodes
+ class BulkGenerateJob < Spree::BaseJob
+ def perform(promotion_id, quantity)
+ promotion = Spree::Promotion.find(promotion_id)
+ return unless promotion.present?
+
+ Spree::CouponCodes::BulkGenerate.call(
+ promotion: promotion,
+ quantity: quantity
+ )
+ end
+ end
+ end
+end
diff --git a/core/app/jobs/spree/stock_locations/stock_items/create_job.rb b/core/app/jobs/spree/stock_locations/stock_items/create_job.rb
index 28781b4147..fa656ae603 100644
--- a/core/app/jobs/spree/stock_locations/stock_items/create_job.rb
+++ b/core/app/jobs/spree/stock_locations/stock_items/create_job.rb
@@ -2,8 +2,6 @@ module Spree
module StockLocations
module StockItems
class CreateJob < Spree::BaseJob
- queue_as :spree_stock_location_stock_items
-
def perform(stock_location)
Spree::StockLocations::StockItems::Create.call(stock_location: stock_location)
end
diff --git a/core/app/models/spree/coupon_code.rb b/core/app/models/spree/coupon_code.rb
new file mode 100644
index 0000000000..574b4aaadd
--- /dev/null
+++ b/core/app/models/spree/coupon_code.rb
@@ -0,0 +1,34 @@
+module Spree
+ class CouponCode < Spree::Base
+ include Spree::Security::CouponCodes if defined?(Spree::Security::CouponCodes)
+
+ enum state: %i(unused used)
+
+ acts_as_paranoid
+
+ scope :used_with_code, ->(code) { used.where(code: code.downcase) }
+ scope :with_order, ->(order_id) { where(order_id: order_id) }
+ scope :in_promotions, ->(promotion_ids) { where(promotion_id: promotion_ids) }
+ scope :not_in_promotions, ->(promotion_ids) { where.not(promotion_id: promotion_ids) }
+
+ belongs_to :promotion, class_name: 'Spree::Promotion'
+ belongs_to :order, class_name: 'Spree::Order'
+
+ validates :code, presence: true, uniqueness: { scope: spree_base_uniqueness_scope }
+ validates :state, :promotion, presence: true
+
+ self.whitelisted_ransackable_attributes = %w[state code]
+
+ def self.used?(code)
+ used_with_code(code).any?
+ end
+
+ def apply_order!(order)
+ update(order: order)
+ end
+
+ def display_code
+ code.upcase
+ end
+ end
+end
diff --git a/core/app/models/spree/order.rb b/core/app/models/spree/order.rb
index 84ce771497..1f8cdb1663 100644
--- a/core/app/models/spree/order.rb
+++ b/core/app/models/spree/order.rb
@@ -454,17 +454,16 @@ module Spree
end
def empty!
- Spree::Deprecation.warn(<<-DEPRECATION, caller)
- `Order#empty!` is deprecated and will be removed in Spree 5.0.
- Please use `Spree::Cart::Empty.call(order: order)` instead.
- DEPRECATION
-
raise Spree.t(:cannot_empty_completed_order) if completed?
result = Spree::Dependencies.cart_empty_service.constantize.call(order: self)
result.value
end
+ def use_all_coupon_codes
+ Spree::CouponCodes::CouponCodesHandler.new(order: self).use_all_codes
+ end
+
def has_step?(step)
checkout_steps.include?(step)
end
@@ -657,7 +656,7 @@ module Spree
alias fully_discounted fully_discounted?
def promo_code
- promotions.pluck(:code).compact.first
+ Spree::CouponCode.find_by(order: self, promotion: promotions).try(:code) || promotions.pluck(:code).compact.first
end
def validate_payments_attributes(attributes)
diff --git a/core/app/models/spree/order/checkout.rb b/core/app/models/spree/order/checkout.rb
index 2ec504070f..46a6b6734a 100644
--- a/core/app/models/spree/order/checkout.rb
+++ b/core/app/models/spree/order/checkout.rb
@@ -115,6 +115,7 @@ module Spree
before_transition to: :resumed, do: proc { |order| order.state_machine_resumed = true }
after_transition to: :complete, do: :finalize!
+ after_transition to: :complete, do: :use_all_coupon_codes
after_transition to: :resumed, do: :after_resume
after_transition to: :canceled, do: :after_cancel
diff --git a/core/app/models/spree/promotion.rb b/core/app/models/spree/promotion.rb
index 7c486acd16..4e3377ac97 100644
--- a/core/app/models/spree/promotion.rb
+++ b/core/app/models/spree/promotion.rb
@@ -14,32 +14,63 @@ module Spree
attr_reader :eligibility_errors, :generate_code
- belongs_to :promotion_category, optional: true
+ #
+ # Magic methods
+ #
+ auto_strip_attributes :code, :path, :name
+
+ #
+ # Enums
+ #
+ enum :kind, { coupon_code: 0, automatic: 1 }
+ #
+ # Associations
+ #
+ belongs_to :promotion_category, optional: true
has_many :promotion_rules, autosave: true, dependent: :destroy
alias rules promotion_rules
-
has_many :promotion_actions, autosave: true, dependent: :destroy
alias actions promotion_actions
-
+ has_many :coupon_codes, -> { order(created_at: :asc) }, dependent: :destroy, class_name: 'Spree::CouponCode'
has_many :order_promotions, class_name: 'Spree::OrderPromotion'
has_many :orders, through: :order_promotions, class_name: 'Spree::Order'
-
has_many :store_promotions, class_name: 'Spree::StorePromotion'
has_many :stores, class_name: 'Spree::Store', through: :store_promotions
-
accepts_nested_attributes_for :promotion_actions, :promotion_rules
+ #
+ # Callbacks
+ #
+ before_validation :set_code_to_nil, if: -> { multi_codes? || automatic? }
+ before_validation :set_number_of_codes_to_nil, if: -> { automatic? || !multi_codes? }
+ before_validation :set_usage_limit_to_nil, if: -> { multi_codes? }
+ before_validation :set_kind
+ before_validation :downcase_code, if: -> { code.present? }
+ after_commit :generate_coupon_codes, if: -> { multi_codes? }, on: [:create, :update]
+ after_commit :remove_coupons, unless: -> { multi_codes? }, on: :update
+ before_destroy :not_used?
+
+ #
+ # Validations
+ #
validates_associated :rules
-
validates :name, presence: true
validates :usage_limit, numericality: { greater_than: 0, allow_nil: true }
validates :description, length: { maximum: 255 }, allow_blank: true
validate :expires_at_must_be_later_than_starts_at, if: -> { starts_at && expires_at }
-
- auto_strip_attributes :code, :path, :name
-
- scope :coupons, -> { where.not(code: nil) }
+ validates :code, presence: true, if: -> { coupon_code? && !multi_codes? }
+ validates :number_of_codes, numericality: {
+ only_integer: true,
+ greater_than: 0,
+ less_than_or_equal_to: ENV.fetch('SPREE_PROMOTION_MAX_NUMBER_OF_CODES', 5000).to_i
+ }, if: -> { multi_codes? }
+
+ #
+ # Scopes
+ #
+ scope :expired, -> { where('expires_at < ?', Time.current) }
+ scope :coupons, -> { where(kind: :coupon_code) }
scope :advertised, -> { where(advertise: true) }
scope :applied, lambda {
joins(<<-SQL).distinct
@@ -48,12 +79,22 @@ module Spree
SQL
}
- self.whitelisted_ransackable_attributes = ['path', 'promotion_category_id', 'code']
+ #
+ # Ransack
+ #
+ self.whitelisted_ransackable_attributes = ['path', 'promotion_category_id', 'code', 'starts_at', 'expires_at']
+ self.whitelisted_ransackable_associations = %w[coupon_codes]
def self.with_coupon_code(coupon_code)
- where("lower(#{table_name}.code) = ?", coupon_code.strip.downcase).
- includes(:promotion_actions).where.not(spree_promotion_actions: { id: nil }).
- last
+ return nil unless coupon_code.present?
+
+ coupon_code = coupon_code.strip.downcase
+
+ coupons.includes(:promotion_actions).
+ where.not(spree_promotion_actions: { id: nil }).
+ where(code: coupon_code).or(
+ where(id: Spree::CouponCode.where(code: coupon_code).select(:promotion_id))
+ ).last
end
def self.active
@@ -209,8 +250,71 @@ module Spree
where(spree_adjustments: { source_type: 'Spree::PromotionAction', eligible: true }).any?
end
+ def name_for_order(order)
+ if coupon_code?
+ code_for_order(order)
+ else
+ name
+ end.to_s.upcase
+ end
+
+ def code_for_order(order)
+ if multi_codes?
+ coupon_codes.find_by(order: order)&.code
+ else
+ code
+ end
+ end
+
private
+ def not_used?
+ return true if orders.empty?
+
+ errors.add(:base, Spree.t('promotion_already_used'))
+ throw(:abort)
+ end
+
+ def set_kind
+ if (code.present? || (multi_codes? && number_of_codes.present?)) && kind == 'automatic'
+ self.kind = :coupon_code
+ end
+ end
+
+ def downcase_code
+ self.code = code.downcase.strip
+ end
+
+ def set_code_to_nil
+ self.code = nil
+ end
+
+ def set_usage_limit_to_nil
+ self.usage_limit = nil
+ end
+
+ def set_number_of_codes_to_nil
+ self.number_of_codes = nil
+ self.code_prefix = nil
+ self.multi_codes = false
+ end
+
+ def generate_coupon_codes
+ return if number_of_codes.nil?
+ return if number_of_codes <= coupon_codes.count
+ return unless saved_change_to_number_of_codes?
+
+ if number_of_codes > 500
+ Spree::CouponCodes::BulkGenerateJob.perform_later(id, number_of_codes - coupon_codes.count)
+ else
+ Spree::CouponCodes::BulkGenerate.call(promotion: self, quantity: number_of_codes - coupon_codes.count)
+ end
+ end
+
+ def remove_coupons
+ coupon_codes.where(deleted_at: nil).update_all(deleted_at: Time.current)
+ end
+
def blacklisted?(promotable)
case promotable
when Spree::LineItem
diff --git a/core/app/models/spree/promotion_handler/cart.rb b/core/app/models/spree/promotion_handler/cart.rb
index dca8aeebfd..c4a30d5e9b 100644
--- a/core/app/models/spree/promotion_handler/cart.rb
+++ b/core/app/models/spree/promotion_handler/cart.rb
@@ -35,7 +35,7 @@ module Spree
private
def promotions
- promotion_scope.find_by_sql("#{order.promotions.active.to_sql} UNION #{promotion_scope.active.where(code: nil, path: nil).to_sql}")
+ promotion_scope.find_by_sql("#{order.promotions.active.to_sql} UNION #{promotion_scope.active.automatic.to_sql}")
end
def promotion_scope
diff --git a/core/app/models/spree/promotion_handler/coupon.rb b/core/app/models/spree/promotion_handler/coupon.rb
index d9f7f9cf58..da86635b49 100644
--- a/core/app/models/spree/promotion_handler/coupon.rb
+++ b/core/app/models/spree/promotion_handler/coupon.rb
@@ -47,9 +47,9 @@ module Spree
@success = Spree.t(code)
end
- def set_error_code(code)
+ def set_error_code(code, locale_options = {})
@status_code = code
- @error = Spree.t(code)
+ @error = Spree.t(code, locale_options)
end
def promotion
@@ -82,10 +82,11 @@ module Spree
end
def handle_present_promotion
+ return set_error_code :coupon_code_used if promotion.coupon_codes.used.where(code: order.coupon_code).exists?
return promotion_usage_limit_exceeded if promotion.usage_limit_exceeded?(order)
return promotion_applied if promotion_exists_on_order?
- unless promotion.eligible?(order)
+ unless promotion.eligible?(order, options)
self.error = promotion.eligibility_errors.full_messages.first unless promotion.eligibility_errors.blank?
return (error || ineligible_for_this_order)
end
@@ -116,9 +117,12 @@ module Spree
end
def determine_promotion_application_result
+ coupon_code = order.coupon_code.downcase
+
# Check for applied adjustments.
discount = order.all_adjustments.promotion.eligible.detect do |p|
- p.source.promotion.code.try(:downcase) == order.coupon_code.downcase
+ p.source.promotion.code.try(:downcase) == coupon_code ||
+ p.source.promotion.coupon_codes.unused.where(code: coupon_code).exists?
end
# Check for applied line items.
@@ -129,18 +133,29 @@ module Spree
end
if discount || created_line_items
+ handle_coupon_code(discount, coupon_code) if discount
+
order.update_totals
order.persist_totals
set_success_code :coupon_code_applied
elsif order.promotions.with_coupon_code(order.coupon_code)
- # if the promotion exists on an order, but wasn't found above,
- # we've already selected a better promotion
- set_error_code :coupon_code_better_exists
+ # since CouponCode is disposable...
+ if Spree::CouponCode.used?(order.coupon_code)
+ set_error_code :coupon_code_max_usage
+ else
+ # if the promotion exists on an order, but wasn't found above,
+ # we've already selected a better promotion
+ set_error_code :coupon_code_better_exists
+ end
else
# if the promotion was created after the order
set_error_code :coupon_code_not_found
end
end
+
+ def handle_coupon_code(discount, coupon_code)
+ discount.source.promotion.coupon_codes.unused.find_by(code: coupon_code)&.apply_order!(order)
+ end
end
end
end
diff --git a/core/app/services/spree/coupon_codes/bulk_generate.rb b/core/app/services/spree/coupon_codes/bulk_generate.rb
new file mode 100644
index 0000000000..cbdbd1e1d1
--- /dev/null
+++ b/core/app/services/spree/coupon_codes/bulk_generate.rb
@@ -0,0 +1,35 @@
+module Spree
+ module CouponCodes
+ class BulkGenerate
+ prepend Spree::ServiceModule::Base
+
+ def call(promotion:, quantity: 10)
+ coupon_codes = []
+
+ Spree::CouponCode.transaction do
+ quantity.times do
+ coupon_codes << coupon_attributes(promotion).merge(code: create_code(promotion.code_prefix))
+ end
+ Spree::CouponCode.insert_all coupon_codes
+ end
+
+ success(promotion.reload.coupon_codes)
+ end
+
+ private
+
+ def create_code(prefix = nil)
+ loop do
+ code = "#{prefix}#{SecureRandom.hex(8)}".downcase
+ break code unless Spree::CouponCode.exists?(code: code)
+ end
+ end
+
+ def coupon_attributes(promotion)
+ {
+ promotion_id: promotion.id
+ }
+ end
+ end
+ end
+end
diff --git a/core/app/services/spree/coupon_codes/coupon_codes_handler.rb b/core/app/services/spree/coupon_codes/coupon_codes_handler.rb
new file mode 100644
index 0000000000..cc449f1932
--- /dev/null
+++ b/core/app/services/spree/coupon_codes/coupon_codes_handler.rb
@@ -0,0 +1,34 @@
+module Spree
+ module CouponCodes
+ class CouponCodesHandler
+ attr_reader :order, :codes
+
+ def initialize(order:)
+ @order = order
+ @codes = Spree::CouponCode.where(order_id: order.id)
+ end
+
+ def use_all_codes
+ return unless codes.any?
+
+ promotion_ids = find_current_promotions_ids
+ use_all_current(promotion_ids)
+ clear_all_unused(promotion_ids)
+ end
+
+ private
+
+ def find_current_promotions_ids
+ order.all_adjustments.promotion.eligible.map { |a| a.source.try(:promotion_id) }.compact
+ end
+
+ def use_all_current(promotion_ids)
+ codes.in_promotions(promotion_ids).update_all(state: 1)
+ end
+
+ def clear_all_unused(promotion_ids)
+ codes.not_in_promotions(promotion_ids).update_all(order_id: nil)
+ end
+ end
+ end
+end
diff --git a/core/config/locales/en.yml b/core/config/locales/en.yml
index 133cc3dac4..f842212175 100644
--- a/core/config/locales/en.yml
+++ b/core/config/locales/en.yml
@@ -722,6 +722,7 @@ en:
coupon_code_not_found: The coupon code you entered doesn't exist. Please try again.
coupon_code_removed: The coupon code was successfully removed from your order.
coupon_code_unknown_error: This coupon code could not be applied to the cart at this time.
+ coupon_code_used: The coupon code you entered has already been used. Please try again.
create: Create
create_a_new_account: Create a new account
create_new_order: Create new order
diff --git a/core/db/migrate/20241004181911_create_spree_coupon_codes.rb b/core/db/migrate/20241004181911_create_spree_coupon_codes.rb
new file mode 100644
index 0000000000..39b21d8635
--- /dev/null
+++ b/core/db/migrate/20241004181911_create_spree_coupon_codes.rb
@@ -0,0 +1,15 @@
+class CreateSpreeCouponCodes < ActiveRecord::Migration[6.1]
+ def change
+ return if table_exists?(:spree_coupon_codes)
+
+ create_table :spree_coupon_codes do |t|
+ t.string :code, index: { unique: true, where: 'deleted_at IS NULL' }
+ t.references :promotion, index: true
+ t.references :order, index: true
+ t.integer :state, default: 0, null: false, index: true
+ t.datetime :deleted_at, index: true
+
+ t.timestamps
+ end
+ end
+end
diff --git a/core/db/migrate/20241005093437_add_multi_code_to_spree_promotions.rb b/core/db/migrate/20241005093437_add_multi_code_to_spree_promotions.rb
new file mode 100644
index 0000000000..029220b1ed
--- /dev/null
+++ b/core/db/migrate/20241005093437_add_multi_code_to_spree_promotions.rb
@@ -0,0 +1,14 @@
+class AddMultiCodeToSpreePromotions < ActiveRecord::Migration[7.2]
+ def change
+ add_column :spree_promotions, :code_prefix, :string, if_not_exists: true
+ add_column :spree_promotions, :number_of_codes, :integer, if_not_exists: true
+ add_column :spree_promotions, :kind, :integer, default: 0, if_not_exists: true
+ add_column :spree_promotions, :multi_codes, :boolean, default: false, if_not_exists: true
+
+ add_index :spree_promotions, :kind, if_not_exists: true
+
+ Spree::Promotion.reset_column_information
+ # set all promotions without a code to automatic
+ Spree::Promotion.where(code: [nil, '']).update_all(kind: 1)
+ end
+end
diff --git a/core/lib/spree/testing_support/factories/calculator_factory.rb b/core/lib/spree/testing_support/factories/calculator_factory.rb
index 4c74c6b7c2..430c461ba4 100644
--- a/core/lib/spree/testing_support/factories/calculator_factory.rb
+++ b/core/lib/spree/testing_support/factories/calculator_factory.rb
@@ -17,4 +17,16 @@ FactoryBot.define do
factory :shipping_no_amount_calculator, class: Spree::Calculator::Shipping::FlatRate do
after(:create) { |c| c.set_preference(:amount, 0) }
end
+
+ factory :flat_rate_calculator, class: Spree::Calculator::FlatRate do
+ preferred_amount { 10 }
+ end
+
+ factory :flat_percent_item_total_calculator, class: Spree::Calculator::FlatPercentItemTotal do
+ preferred_flat_percent { 10 }
+ end
+
+ factory :non_free_shipping_calculator, class: Spree::Calculator::Shipping::FlatRate do
+ after(:create) { |c| c.set_preference(:amount, 20.0) }
+ end
end
diff --git a/core/lib/spree/testing_support/factories/coupon_code_factory.rb b/core/lib/spree/testing_support/factories/coupon_code_factory.rb
new file mode 100644
index 0000000000..4117692019
--- /dev/null
+++ b/core/lib/spree/testing_support/factories/coupon_code_factory.rb
@@ -0,0 +1,7 @@
+FactoryBot.define do
+ factory :coupon_code, class: Spree::CouponCode do
+ sequence(:code) { |n| "PROMO#{n}" }
+ state { :unused }
+ promotion
+ end
+end
diff --git a/core/lib/spree/testing_support/factories/promotion_factory.rb b/core/lib/spree/testing_support/factories/promotion_factory.rb
index 09b1f4c71b..6a9c509782 100644
--- a/core/lib/spree/testing_support/factories/promotion_factory.rb
+++ b/core/lib/spree/testing_support/factories/promotion_factory.rb
@@ -18,6 +18,9 @@ FactoryBot.define do
factory :promotion, class: Spree::Promotion do
name { 'Promo' }
+ sequence :code do |n|
+ "CODE-#{n}"
+ end
before(:create) do |promotion, _evaluator|
if promotion.stores.empty?
diff --git a/core/spec/models/spree/adjustable/adjuster/promotion_spec.rb b/core/spec/models/spree/adjustable/adjuster/promotion_spec.rb
index 3c37e23ebf..b9e7c24512 100644
--- a/core/spec/models/spree/adjustable/adjuster/promotion_spec.rb
+++ b/core/spec/models/spree/adjustable/adjuster/promotion_spec.rb
@@ -82,6 +82,7 @@ describe Spree::Adjustable::Adjuster::Promotion, type: :model do
create(:promotion,
:with_order_adjustment,
:with_item_total_rule,
+ kind: :automatic,
weighted_order_adjustment_amount: 5,
item_total_threshold_amount: 10)
end
@@ -90,6 +91,7 @@ describe Spree::Adjustable::Adjuster::Promotion, type: :model do
create(:promotion,
:with_order_adjustment,
:with_item_total_rule,
+ kind: :automatic,
weighted_order_adjustment_amount: 10,
item_total_threshold_amount: 20)
end
@@ -100,6 +102,7 @@ describe Spree::Adjustable::Adjuster::Promotion, type: :model do
create(:promotion,
:with_line_item_adjustment,
:with_item_total_rule,
+ kind: :automatic,
adjustment_rate: 2.5,
item_total_threshold_amount: 10)
end
@@ -108,6 +111,7 @@ describe Spree::Adjustable::Adjuster::Promotion, type: :model do
create(:promotion,
:with_line_item_adjustment,
:with_item_total_rule,
+ kind: :automatic,
adjustment_rate: 5,
item_total_threshold_amount: 20)
end
diff --git a/core/spec/models/spree/order/adjustments_spec.rb b/core/spec/models/spree/order/adjustments_spec.rb
index b7aec2d0f8..1ecf826c98 100644
--- a/core/spec/models/spree/order/adjustments_spec.rb
+++ b/core/spec/models/spree/order/adjustments_spec.rb
@@ -54,7 +54,7 @@ describe Spree::Order do
end
let!(:free_shipping_promotion) {
- create(:free_shipping_promotion, code: 'freeship')
+ create(:free_shipping_promotion, code: 'freeship', kind: :coupon_code)
}
before do
diff --git a/core/spec/models/spree/order/totals_spec.rb b/core/spec/models/spree/order/totals_spec.rb
index 2f3756ce90..912c73f583 100644
--- a/core/spec/models/spree/order/totals_spec.rb
+++ b/core/spec/models/spree/order/totals_spec.rb
@@ -7,7 +7,7 @@ module Spree
let(:shirt) { create(:variant) }
context 'adds item to cart and activates promo' do
- let(:promotion) { create(:promotion, name: 'Huhu', stores: [store]) }
+ let(:promotion) { create(:promotion, name: 'Huhu', stores: [store], kind: :automatic) }
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_contents_spec.rb b/core/spec/models/spree/order_contents_spec.rb
index 2dfca196b5..c40791a1f8 100644
--- a/core/spec/models/spree/order_contents_spec.rb
+++ b/core/spec/models/spree/order_contents_spec.rb
@@ -65,7 +65,7 @@ describe Spree::OrderContents, type: :model do
end
context 'running promotions' do
- let(:promotion) { create(:promotion, stores: [store]) }
+ let(:promotion) { create(:promotion, stores: [store], kind: :automatic) }
let(:calculator) { Spree::Calculator::FlatRate.new(preferred_amount: 10) }
shared_context 'discount changes order total' do
diff --git a/core/spec/models/spree/order_spec.rb b/core/spec/models/spree/order_spec.rb
index 6aa031ab8e..e2fb03385a 100644
--- a/core/spec/models/spree/order_spec.rb
+++ b/core/spec/models/spree/order_spec.rb
@@ -1110,22 +1110,48 @@ describe Spree::Order, type: :model do
end
describe '#promo_code' do
- let(:new_order_x) { create(:order) }
-
- context 'without promo_code applied' do
- it { expect(new_order_x.promo_code).to eq nil }
+ context 'without promo code' do
+ let(:order) { build_stubbed(:order, user: nil, email: nil) }
+ it 'returns nil' do
+ expect(order.promo_code).to be_nil
+ end
end
- context 'with_promo_code applied' do
- let(:promo_code) { '10off' }
- let(:promotion) { create :promotion, code: promo_code }
+ context 'with promo code' do
+ let(:order) { create(:order_with_line_items, line_items_count: 2, store: Spree::Store.default) }
+ let(:promotion) { create(:free_shipping_promotion, code: 'GWP', kind: :coupon_code) }
- before do
- promotion.orders << new_order_x
+ context 'with single coupon code' do
+ before do
+ order.coupon_code = promotion.code
+ Spree::PromotionHandler::Coupon.new(order).apply
+ order.reload
+ end
+
+ it 'returns the promotion code' do
+ expect(order.promo_code).to eq('gwp')
+ end
end
- it 'returns applied promo_code' do
- expect(new_order_x.promo_code).to eq promo_code
+ context 'with coupon code batches' do
+ let(:promotion) { create(:free_shipping_promotion, kind: :coupon_code, code: nil, multi_codes: true, number_of_codes: 1) }
+ let(:coupon_code) { promotion.coupon_codes.first }
+
+ before do
+ order.coupon_code = coupon_code.code
+ Spree::PromotionHandler::Coupon.new(order).apply
+ order.reload
+ end
+
+ it 'returns the promotion code' do
+ expect(order.promo_code).to eq(coupon_code.code)
+ expect(coupon_code.reload.order).to eq(order)
+ end
+
+ it 'returns the same promotion code after line item removal' do
+ Spree::Cart::RemoveLineItem.call(order: order, line_item: order.line_items.first)
+ expect(order.reload.promo_code).to eq(coupon_code.code)
+ end
end
end
end
@@ -1330,7 +1356,7 @@ describe Spree::Order, type: :model do
end
context 'with promotions' do
- let(:free_shipping_promotion) { create(:free_shipping_promotion, code: 'freeship') }
+ let(:free_shipping_promotion) { create(:free_shipping_promotion, code: 'freeship', kind: :coupon_code) }
let(:line_item_promotion) { create(:promotion_with_item_adjustment, code: 'li_discount', adjustment_rate: 10) }
let(:order_promotion) { create(:promotion_with_order_adjustment, code: 'discount', weighted_order_adjustment_amount: 10) }
@@ -1406,7 +1432,7 @@ describe Spree::Order, type: :model do
let(:line_items_count) { 10 }
context 'when promotion is applied' do
- let(:free_shipping_promotion) { create(:free_shipping_promotion, code: 'freeship') }
+ let(:free_shipping_promotion) { create(:free_shipping_promotion, code: 'freeship', kind: :coupon_code) }
before do
order.coupon_code = free_shipping_promotion.code
@@ -1418,6 +1444,7 @@ describe Spree::Order, type: :model do
context 'when free shipping promotion has item total rule' do
let(:free_shipping_promotion) do
create(:free_shipping_promotion_with_item_total_rule,
+ kind: :coupon_code,
code: 'freeship',
starts_at: 1.day.ago,
expires_at: 1.day.from_now)
diff --git a/core/spec/models/spree/promotion/actions/create_item_adjustments_spec.rb b/core/spec/models/spree/promotion/actions/create_item_adjustments_spec.rb
index a78ec0d039..f3ca1283c8 100644
--- a/core/spec/models/spree/promotion/actions/create_item_adjustments_spec.rb
+++ b/core/spec/models/spree/promotion/actions/create_item_adjustments_spec.rb
@@ -98,7 +98,7 @@ module Spree
before do
order.update_with_updater!
- 2.times { create :promotion_with_order_adjustment }
+ 2.times { create :promotion_with_order_adjustment, kind: :automatic }
Spree::PromotionHandler::Cart.new(order).activate
allow(action.calculator).to receive(:compute).and_return(3)
diff --git a/core/spec/models/spree/promotion_handler/cart_spec.rb b/core/spec/models/spree/promotion_handler/cart_spec.rb
index 71b5103a83..80688d3f11 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 Spree
let(:line_item) { create(:line_item) }
let(:order) { line_item.order }
- let(:promotion) { create(:promotion, name: 'At line items', stores: [order.store]) }
+ let(:promotion) { create(:promotion, name: 'At line items', stores: [order.store], kind: :automatic) }
let(:calculator) { Calculator::FlatPercentItemTotal.new(preferred_flat_percent: 10) }
context 'activates in LineItem level' do
diff --git a/core/spec/models/spree/promotion_handler/coupon_spec.rb b/core/spec/models/spree/promotion_handler/coupon_spec.rb
index 156feeb96d..557af067a6 100644
--- a/core/spec/models/spree/promotion_handler/coupon_spec.rb
+++ b/core/spec/models/spree/promotion_handler/coupon_spec.rb
@@ -49,7 +49,7 @@ module Spree
end
context 'coupon code promotion doesnt exist' do
- before { create(:promotion, name: 'promo', code: nil) }
+ before { create(:promotion, name: 'promo', code: nil, kind: :automatic) }
it 'doesnt fetch any promotion' do
expect(subject.promotion).to be_blank
@@ -300,6 +300,135 @@ module Spree
end
end
end
+
+ context 'with coupon codes' do
+ let!(:user) { create(:user) }
+ let(:calculator) { create(:flat_rate_calculator) }
+ let(:flat_percent_calculator) { create(:flat_percent_item_total_calculator, preferred_flat_percent: 10) }
+ let(:order) do
+ create(:order_with_line_items, line_items_count: 3, user: user, store: Spree::Store.default)
+ end
+ let!(:promotion) { create(:promotion, name: 'promo', code: nil, multi_codes: true, number_of_codes: 1) }
+ let!(:coupon_code) { promotion.coupon_codes.first }
+ let!(:action) { Spree::Promotion::Actions::CreateItemAdjustments.create(promotion: promotion, calculator: calculator) }
+
+ context 'valid coupon' do
+ before { order.coupon_code = coupon_code.code }
+
+ it 'successfully activates promo' do
+ expect(order.total).to eq(130)
+ subject.apply
+ expect(subject.success).to be_present
+ order.line_items.each do |line_item|
+ expect(line_item.adjustments.count).to eq(1)
+ end
+ expect(order.reload.total).to eq(100)
+ end
+
+ it 'coupon already applied to the order' do
+ subject.apply
+ expect(subject.success).to be_present
+ subject.apply
+ expect(subject.error).to eq Spree.t(:coupon_code_already_applied)
+ end
+
+ context 'with used coupon code' do
+ before { coupon_code.update!(state: :used) }
+
+ it 'does not activate promo' do
+ subject.apply
+
+ expect(subject.success).to be_nil
+ expect(subject.error).to eq Spree.t(:coupon_code_used)
+ end
+ end
+ end
+ end
+
+ context 'number of usages for' do
+ let!(:user) { create(:user) }
+ let(:calculator) { create(:flat_rate_calculator) }
+ let(:order) { create(:order_with_line_items, line_items_count: 3, user: user, store: Spree::Store.default) }
+ subject { Spree::PromotionHandler::Coupon.new(order) }
+
+ context 'one common promotion code' do
+ let!(:promotion) { create(:promotion, name: 'promo', code: '10off', usage_limit: 1) }
+ let!(:action) do
+ Spree::Promotion::Actions::CreateItemAdjustments.create(promotion: promotion,
+ calculator: calculator)
+ end
+ let!(:order_2) { create(:order_with_line_items, line_items_count: 3, user: user) }
+ let!(:subject_2) { Spree::PromotionHandler::Coupon.new(order_2) }
+
+ before do
+ order.coupon_code = '10off'
+ order_2.coupon_code = '10off'
+ end
+
+ it 'hits max usage' do
+ subject.apply
+ expect(subject.successful?).to be true
+ subject_2.apply
+ expect(subject_2.successful?).to be false
+ expect(subject_2.error).to eq Spree.t(:coupon_code_max_usage)
+ end
+ end
+
+ context 'one-time unique promotion codes' do
+ let!(:order_2) { create(:order_with_line_items, line_items_count: 3, user: user) }
+ let!(:subject_2) { Spree::PromotionHandler::Coupon.new(order_2) }
+ let!(:promotion) do
+ create(:promotion, name: 'promo',
+ code: nil,
+ usage_limit: 1,
+ multi_codes: true,
+ number_of_codes: 2,
+ coupon_codes: [create(:coupon_code, code: 'first_one_time_code'), create(:coupon_code, code: 'second_one_time_code')])
+ end
+ let!(:action) do
+ Spree::Promotion::Actions::CreateItemAdjustments.create(promotion: promotion,
+ calculator: calculator)
+ end
+
+ shared_examples 'allows to use coupon code one time only' do |coupon_code|
+ before do
+ order.coupon_code = coupon_code
+ order_2.coupon_code = coupon_code
+ end
+
+ it do
+ subject.apply
+ expect(subject.successful?).to be true
+ # Simulate the order has been completed so the coupon code is marked as used
+ Spree::CouponCodes::CouponCodesHandler.new(order: order).use_all_codes
+ expect(Spree::CouponCode.find_by(code: coupon_code).state).to eq 'used'
+
+ subject_2.apply
+ expect(subject_2.successful?).to be false
+ expect(subject_2.error).to eq Spree.t(:coupon_code_used)
+ end
+ end
+
+ it_behaves_like 'allows to use coupon code one time only', 'first_one_time_code'
+ it_behaves_like 'allows to use coupon code one time only', 'second_one_time_code'
+
+ it 'promotion can be used as many times as it has coupon codes' do
+ order.coupon_code = 'first_one_time_code'
+ subject.apply
+ expect(subject.successful?).to be true
+ # Simulate the order has been completed so the coupon code is marked as used
+ Spree::CouponCodes::CouponCodesHandler.new(order: order).use_all_codes
+ expect(Spree::CouponCode.find_by(code: 'first_one_time_code').state).to eq 'used'
+
+ order_2.coupon_code = 'second_one_time_code'
+ subject_2.apply
+ expect(subject_2.successful?).to be true
+ # Simulate the order has been completed so the coupon code is marked as used
+ Spree::CouponCodes::CouponCodesHandler.new(order: order_2).use_all_codes
+ expect(Spree::CouponCode.find_by(code: 'second_one_time_code').state).to eq 'used'
+ end
+ end
+ end
end
end
end
diff --git a/core/spec/models/spree/promotion_handler/free_shipping_spec.rb b/core/spec/models/spree/promotion_handler/free_shipping_spec.rb
index 8754d907bb..89fd5262cf 100644
--- a/core/spec/models/spree/promotion_handler/free_shipping_spec.rb
+++ b/core/spec/models/spree/promotion_handler/free_shipping_spec.rb
@@ -8,36 +8,42 @@ module Spree
let(:order) { create(:order) }
let(:shipment) { create(:shipment, order: order) }
- 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) }
context 'activates in Shipment level' do
+ let(:promotion) { create(:promotion, name: 'Free Shipping', stores: [order.store], kind: :automatic) }
+ let!(:action) { Promotion::Actions::FreeShipping.create(promotion: promotion) }
+
it 'creates the adjustment' do
expect { subject.activate }.to change { shipment.adjustments.count }.by(1)
end
end
context 'if promo has a code' do
- before do
- promotion.update_column(:code, 'code')
- end
+ let(:promotion) { create(:promotion, name: 'Free Shipping', stores: [order.store], code: 'code') }
+ let!(:action) { Spree::Promotion::Actions::FreeShipping.create(promotion: promotion) }
it 'does adjust the shipment when applied to order' do
order.promotions << promotion
expect { subject.activate }.to change { shipment.adjustments.count }
end
+ end
- it 'does not adjust the shipment when not applied to order' do
- expect { subject.activate }.not_to change { shipment.adjustments.count }
+ context 'if promo has multiple codes' do
+ let(:promotion) { create(:promotion, name: 'Free Shipping', stores: [order.store], multi_codes: true, number_of_codes: 1) }
+ let!(:action) { Spree::Promotion::Actions::FreeShipping.create(promotion: promotion) }
+
+ it 'does adjust the shipment when applied to order' do
+ order.promotions << promotion
+
+ expect { subject.activate }.to change { shipment.adjustments.count }
end
end
context 'if promo has a path' do
- before do
- promotion.update_column(:path, 'path')
- end
+ let(:promotion) { create(:promotion, name: 'Free Shipping', stores: [order.store], kind: :automatic, path: 'path') }
+ let!(:action) { Promotion::Actions::FreeShipping.create(promotion: promotion) }
it 'does not adjust the shipment' do
expect { subject.activate }.not_to change { shipment.adjustments.count }
diff --git a/core/spec/models/spree/promotion_spec.rb b/core/spec/models/spree/promotion_spec.rb
index e41fba918d..2b75d1ce52 100644
--- a/core/spec/models/spree/promotion_spec.rb
+++ b/core/spec/models/spree/promotion_spec.rb
@@ -4,10 +4,10 @@ describe Spree::Promotion, type: :model do
it_behaves_like 'metadata'
let(:store) { create(:store) }
- let(:promotion) { create(:promotion) }
+ let(:promotion) { create(:promotion, kind: :automatic) }
describe 'validations' do
- let!(:valid_promotion) { build(:promotion, name: 'A promotion', stores: [create(:store)]) }
+ let!(:valid_promotion) { build(:promotion, name: 'A promotion', stores: [create(:store)], kind: :automatic) }
it 'valid_promotion is valid' do
expect(valid_promotion).to be_valid
@@ -69,11 +69,33 @@ describe Spree::Promotion, type: :model do
end
end
+ describe 'callbacks' do
+ describe 'set_usage_limit_to_nil' do
+ let(:promotion) { create(:promotion, kind: :coupon_code, usage_limit: 100) }
+
+ context 'when promo has one code for all customers' do
+ it 'does not change usage_limit' do
+ promotion.multi_codes = false
+
+ expect{ promotion.save }.not_to change{ promotion.usage_limit }
+ end
+ end
+
+ context 'when promo has unique codes' do
+ it 'sets usage_limit to nil' do
+ promotion.multi_codes = true
+
+ expect{ promotion.save }.to change{ promotion.usage_limit }.from(100).to(nil)
+ end
+ end
+ end
+ end
+
describe 'scopes' do
describe '.coupons' do
subject { described_class.coupons }
- let!(:promotion_without_code) { create :promotion, name: 'test', code: '' }
+ let!(:promotion_without_code) { create :promotion, name: 'test', code: nil, kind: :automatic }
let!(:promotion_with_code) { create :promotion, name: 'test1', code: 'code' }
it 'is expected to not include promotion without code' do
@@ -88,10 +110,10 @@ describe Spree::Promotion, type: :model do
describe '.applied' do
subject { described_class.applied }
- let!(:promotion_not_applied) { create :promotion, name: 'test', code: '' }
+ let!(:promotion_not_applied) { create :promotion, name: 'test', kind: :automatic }
let(:order) { create(:order) }
let!(:promotion_applied) do
- promotion = create(:promotion, name: 'test1', code: '')
+ promotion = create(:promotion, name: 'test1', kind: :automatic)
promotion.orders << order
promotion
end
@@ -108,8 +130,8 @@ describe Spree::Promotion, type: :model do
describe '.advertised' do
subject { described_class.advertised }
- let!(:promotion_not_advertised) { create :promotion, name: 'test', advertise: false }
- let!(:promotion_advertised) { create :promotion, name: 'test1', advertise: true }
+ let!(:promotion_not_advertised) { create :promotion, name: 'test', advertise: false, kind: :automatic }
+ let!(:promotion_advertised) { create :promotion, name: 'test1', advertise: true, kind: :automatic }
it 'is expected to not include promotion not advertised' do
expect(subject).not_to include(promotion_not_advertised)
@@ -122,26 +144,39 @@ describe Spree::Promotion, type: :model do
end
describe '#destroy' do
- let(:promotion) { create(:promotion, name: 'delete me') }
+ let(:promotion) { create(:promotion, name: 'delete me', kind: :automatic) }
before do
promotion.actions << Spree::Promotion::Actions::CreateAdjustment.new
promotion.rules << Spree::Promotion::Rules::FirstOrder.new
promotion.save!
- promotion.destroy
end
it 'deletes actions' do
+ promotion.destroy!
+
expect(Spree::PromotionAction.count).to eq(0)
end
it 'deletes rules' do
+ promotion.destroy!
+
expect(Spree::PromotionRule.count).to eq(0)
end
+
+ context 'if promotion was already used' do
+ it 'does not destroy the promotion' do
+ promotion.orders << create(:order)
+ promotion.destroy
+
+ expect(promotion.reload.errors).to be_present
+ expect(promotion.errors.full_messages).to eq [Spree.t('promotion_already_used')]
+ end
+ end
end
describe '#save' do
- let(:promotion) { create(:promotion, name: 'delete me') }
+ let(:promotion) { create(:promotion, name: 'delete me', kind: :automatic) }
before do
promotion.actions << Spree::Promotion::Actions::CreateAdjustment.new
@@ -154,6 +189,48 @@ describe Spree::Promotion, type: :model do
promotion.save!
expect(Spree::Calculator.first.preferred_flat_percent).to eq(10)
end
+
+ it 'allows to change promotion type from automatic to single discount code' do
+ promotion.kind = :coupon_code
+ promotion.code = 'abc'
+ promotion.multi_codes = false
+
+ promotion.save!
+
+ expect(promotion.kind).to eq 'coupon_code'
+ expect(promotion.code).to eq 'abc'
+ expect(promotion.multi_codes).to eq false
+ end
+
+ it 'allows to change promotion type from automatic to multiple discount codes' do
+ promotion.kind = :coupon_code
+ promotion.multi_codes = true
+ promotion.number_of_codes = 10
+
+ promotion.save!
+
+ expect(promotion.kind).to eq 'coupon_code'
+ expect(promotion.multi_codes).to eq true
+ expect(promotion.number_of_codes).to eq 10
+ end
+
+ it 'allows to change promotion type from single discount code to automatic' do
+ promotion = create(:promotion, code: 'ABC', multi_codes: false, kind: :coupon_code)
+
+ promotion.kind = :automatic
+ promotion.save
+
+ expect(promotion.kind).to eq 'automatic'
+ end
+
+ it 'allows to change promotion type from multiple discount codes to automatic' do
+ promotion = create(:promotion, multi_codes: true, number_of_codes: 10, kind: :coupon_code)
+
+ promotion.kind = :automatic
+ promotion.save
+
+ expect(promotion.kind).to eq 'automatic'
+ end
end
describe '#activate' do
@@ -162,7 +239,7 @@ describe Spree::Promotion, type: :model do
let(:user) { create(:user) }
let(:order) { create(:order, user: user) }
let(:payload) { { order: order, user: user } }
-
+
before do
allow(action1).to receive_messages perform: true
allow(action2).to receive_messages perform: true
@@ -356,7 +433,7 @@ describe Spree::Promotion, type: :model do
context '#products' do
let(:product) { create(:product, stores: [store]) }
- let(:promotion) { create(:promotion) }
+ let(:promotion) { create(:promotion, kind: :automatic) }
context 'when it has product rules with products associated' do
let(:promotion_rule) { create(:promotion_rule, promotion: promotion, type: 'Spree::Promotion::Rules::Product') }
@@ -503,7 +580,7 @@ describe Spree::Promotion, type: :model do
end
context "with 'any' match policy" do
- let(:promotion) { create(:promotion, name: 'Promo', match_policy: 'any') }
+ let(:promotion) { create(:promotion, name: 'Promo', match_policy: 'any', kind: :automatic) }
let(:promotable) { double('Promotable') }
it 'has eligible rules if any of the rules are eligible' do
@@ -602,7 +679,7 @@ describe Spree::Promotion, type: :model do
# admin form posts the code and path as empty string
describe 'normalize blank values for code & path' do
it 'will save blank value as nil value instead' do
- promotion = create(:promotion, name: 'A promotion', code: '', path: '')
+ promotion = create(:promotion, name: 'A promotion', code: '', path: '', kind: :automatic)
expect(promotion.code).to be_nil
expect(promotion.path).to be_nil
end
@@ -631,12 +708,25 @@ describe Spree::Promotion, type: :model do
expect(described_class.with_coupon_code('MY-COUPON-123')).to eq(promotion_with_actions_2)
end
end
+
+ context 'coupon from coupon code batch' do
+ let(:coupon_code) { promotion.coupon_codes.first }
+ let(:promotion) { create(:promotion, :with_order_adjustment, code: nil, multi_codes: true, number_of_codes: 1) }
+
+ it 'finds the code with lowercase' do
+ expect(described_class.with_coupon_code(coupon_code.code.downcase)).to eql promotion
+ end
+
+ it 'finds the code with uppercase' do
+ expect(described_class.with_coupon_code(coupon_code.code.upcase)).to eql promotion
+ end
+ end
end
describe '#used_by?' do
subject { promotion.used_by? user, [excluded_order] }
- let(:promotion) { create :promotion, :with_order_adjustment }
+ let(:promotion) { create :promotion, :with_order_adjustment, kind: :automatic }
let(:user) { create :user }
let(:order) { create :order_with_line_items, user: user }
let(:excluded_order) { create :order_with_line_items, user: user }
@@ -711,6 +801,7 @@ describe Spree::Promotion, type: :model do
end
end
+ # this is a legacy method
describe '#generate_code' do
let(:promotion) { create(:promotion, code: 'spree123') }
@@ -727,4 +818,25 @@ describe Spree::Promotion, type: :model do
end
end
end
+
+ describe '#generate_coupon_codes' do
+ let(:promotion) { create(:promotion, code: nil, multi_codes: true, number_of_codes: 1) }
+
+ it 'has a generated code' do
+ expect(promotion.coupon_codes.count).to eq 1
+ end
+
+ it 'generates new codes when number_of_codes is changed' do
+ promotion.update(number_of_codes: 2)
+ expect(promotion.coupon_codes.count).to eq 2
+ end
+
+ context 'with prefix' do
+ let(:promotion) { create(:promotion, code: nil, multi_codes: true, number_of_codes: 1, code_prefix: 'ABC') }
+
+ it 'has a generated code with prefix' do
+ expect(promotion.coupon_codes.first.display_code).to start_with('ABC')
+ end
+ end
+ end
end
diff --git a/core/spec/models/spree/shipment_spec.rb b/core/spec/models/spree/shipment_spec.rb
index 6e35bb4c27..032639b7a2 100644
--- a/core/spec/models/spree/shipment_spec.rb
+++ b/core/spec/models/spree/shipment_spec.rb
@@ -218,7 +218,7 @@ describe Spree::Shipment, type: :model do
context '#free?' do
let!(:order) { create(:order) }
let!(:shipment) { create(:shipment, cost: 10, order: order) }
- let(:free_shipping_promotion) { create(:free_shipping_promotion, code: 'freeship') }
+ let(:free_shipping_promotion) { create(:free_shipping_promotion, code: 'freeship', kind: :coupon_code) }
it 'returns true if final_price is equal to 0' do
shipment.adjustment_total = -10
diff --git a/core/spec/models/spree/shipping_rate_spec.rb b/core/spec/models/spree/shipping_rate_spec.rb
index 38ee81805f..7e2e60bd9f 100644
--- a/core/spec/models/spree/shipping_rate_spec.rb
+++ b/core/spec/models/spree/shipping_rate_spec.rb
@@ -153,7 +153,7 @@ describe Spree::ShippingRate, type: :model do
end
context '#final_price' do
- let(:free_shipping_promotion) { create(:free_shipping_promotion, code: 'freeship') }
+ let(:free_shipping_promotion) { create(:free_shipping_promotion, code: 'freeship', kind: :coupon_code) }
let(:order) { shipment.order }
it 'returns 0 if free shipping promotion is applied' do
diff --git a/core/spec/services/spree/cart/add_item_spec.rb b/core/spec/services/spree/cart/add_item_spec.rb
index 0804f368fe..ceb4114fb8 100644
--- a/core/spec/services/spree/cart/add_item_spec.rb
+++ b/core/spec/services/spree/cart/add_item_spec.rb
@@ -63,7 +63,7 @@ module Spree
end
context 'running promotions' do
- let(:promotion) { create(:promotion) }
+ let(:promotion) { create(:promotion, kind: :automatic) }
let(:calculator) { Spree::Calculator::FlatRate.new(preferred_amount: 10) }
context 'one active order promotion' do
diff --git a/core/spec/services/spree/checkout/get_shipping_rates_spec.rb b/core/spec/services/spree/checkout/get_shipping_rates_spec.rb
index d9bdfa1abd..a068bdf530 100644
--- a/core/spec/services/spree/checkout/get_shipping_rates_spec.rb
+++ b/core/spec/services/spree/checkout/get_shipping_rates_spec.rb
@@ -24,7 +24,7 @@ module Spree
let!(:zone_member) { create(:zone_member, zone: zone, zoneable: country) }
let(:address) { create(:address, country: country) }
- let(:free_shipping_promotion) { create(:free_shipping_promotion) }
+ let(:free_shipping_promotion) { create(:free_shipping_promotion, kind: :automatic) }
shared_examples 'generates shipping rates' do
it 'returns shipping rates' do