Sha256: 13a5812fa50b80bcece09361ae4498271b592ea4b06afdf0b75d1859e70d1fa0

Contents?: true

Size: 1.22 KB

Versions: 5

Compression:

Stored size: 1.22 KB

Contents

# frozen_string_literal: true

class Spree::PromotionCode < Spree::Base
  belongs_to :promotion, inverse_of: :codes, optional: true
  belongs_to :promotion_code_batch, class_name: "Spree::PromotionCodeBatch", optional: true
  has_many :adjustments

  validates :value, presence: true, uniqueness: { allow_blank: true }
  validates :promotion, presence: true

  before_save :normalize_code

  self.whitelisted_ransackable_attributes = ['value']

  # Whether the promotion code has exceeded its usage restrictions
  #
  # @param excluded_orders [Array<Spree::Order>] Orders to exclude from usage limit
  # @return true or false
  def usage_limit_exceeded?(excluded_orders: [])
    if usage_limit
      usage_count(excluded_orders: excluded_orders) >= usage_limit
    end
  end

  # Number of times the code has been used overall
  #
  # @param excluded_orders [Array<Spree::Order>] Orders to exclude from usage count
  # @return [Integer] usage count
  def usage_count(excluded_orders: [])
    adjustments.
    eligible.
    in_completed_orders(excluded_orders: excluded_orders).
    count(:order_id)
  end

  def usage_limit
    promotion.per_code_usage_limit
  end

  private

  def normalize_code
    self.value = value.downcase.strip
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
solidus_core-2.10.5 app/models/spree/promotion_code.rb
solidus_core-2.10.3 app/models/spree/promotion_code.rb
solidus_core-2.10.2 app/models/spree/promotion_code.rb
solidus_core-2.10.1 app/models/spree/promotion_code.rb
solidus_core-2.10.0 app/models/spree/promotion_code.rb