Class: Spree::Promotion

Inherits:
Object
  • Object
show all
Includes:
HasCustomFields, Metadata, Security::Promotions, SingleStoreResource
Defined in:
app/models/spree/promotion.rb,
app/models/spree/promotion/rules/user.rb,
app/models/spree/promotion/rules/taxon.rb,
app/models/spree/promotion/rules/market.rb,
app/models/spree/promotion/rules/channel.rb,
app/models/spree/promotion/rules/country.rb,
app/models/spree/promotion/rules/product.rb,
app/models/spree/promotion/rules/category.rb,
app/models/spree/promotion/rules/currency.rb,
app/models/spree/promotion/rules/item_total.rb,
app/models/spree/promotion/rules/first_order.rb,
app/models/spree/promotion/rules/option_value.rb,
app/models/spree/promotion/rules/customer_group.rb,
app/models/spree/promotion/rules/user_logged_in.rb,
app/models/spree/promotion/actions/free_shipping.rb,
app/models/spree/promotion/rules/one_use_per_user.rb,
app/models/spree/promotion/actions/create_adjustment.rb,
app/models/spree/promotion/actions/create_line_items.rb,
app/models/spree/promotion/actions/create_item_adjustments.rb

Defined Under Namespace

Modules: Actions, Rules

Constant Summary collapse

MATCH_POLICIES =
%w(all any)
UNACTIVATABLE_ORDER_STATES =
['complete', 'awaiting_return', 'returned']

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Metadata

#private_metadata, #private_metadata=

Instance Attribute Details

#eligibility_errors ⇒ Object (readonly)

Returns the value of attribute eligibility_errors.



17
18
19
# File 'app/models/spree/promotion.rb', line 17

def eligibility_errors
  @eligibility_errors
end

#generate_code ⇒ Object

Returns the value of attribute generate_code.



17
18
19
# File 'app/models/spree/promotion.rb', line 17

def generate_code
  @generate_code
end

Class Method Details

.active ⇒ Object



110
111
112
113
# File 'app/models/spree/promotion.rb', line 110

def self.active
  where('spree_promotions.starts_at IS NULL OR spree_promotions.starts_at < ?', Time.current).
    where('spree_promotions.expires_at IS NULL OR spree_promotions.expires_at > ?', Time.current)
end

.held_by_saved_coupon_code(purchase) ⇒ Array<Spree::Promotion>

The promotion a purchase's PERSISTED coupon code names, which keeps it in candidacy even before it ever applied — the discount activates on the exact recalculation where the cart first qualifies, and deactivates the same way (Shopify-parity for cart-level discount codes). In-memory assignments deliberately don't participate: unsaved codes belong to the explicit PromotionHandler::Coupon path. A batch code counts only while the purchase holds it (see #eligible?).

Parameters:

Returns:



125
126
127
128
129
130
131
132
133
134
135
# File 'app/models/spree/promotion.rb', line 125

def self.held_by_saved_coupon_code(purchase)
  return [] unless purchase.class.respond_to?(:column_names) && purchase.class.column_names.include?('coupon_code')

  code = purchase.read_attribute(:coupon_code)
  return [] if code.blank?

  promotion = purchase.store.promotions.active.with_coupon_code(code)
  return [] if promotion.nil? || promotion.usage_limit_exceeded?(purchase)

  [promotion]
end

.order_activatable?(promotable) ⇒ Boolean

Returns:

  • (Boolean)


137
138
139
140
# File 'app/models/spree/promotion.rb', line 137

def self.order_activatable?(promotable)
  # Carts have no cancellation concept — only placed orders can be canceled.
  promotable && !promotable.completed? && !(promotable.is_a?(Spree::Order) && promotable.canceled?)
end

.with_coupon_code(coupon_code) ⇒ Object



98
99
100
101
102
103
104
105
106
107
108
# File 'app/models/spree/promotion.rb', line 98

def self.with_coupon_code(coupon_code)
  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

Instance Method Details

#actions=(rows) ⇒ Object

Mirrors rules= for promotion actions.



155
156
157
# File 'app/models/spree/promotion.rb', line 155

def actions=(rows)
  assign_typed_association(:promotion_actions, rows)
end

#activate(payload) ⇒ Object



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'app/models/spree/promotion.rb', line 179

def activate(payload)
  order = payload[:order]
  return unless self.class.order_activatable?(order)

  payload[:promotion] = self

  # Track results from actions to see if any action has been taken.
  # Actions should return nil/false if no action has been taken.
  # If an action returns true, then an action has been taken.
  results = actions.map do |action|
    action.perform(payload)
  end
  # If an action has been taken, report back to whatever activated this promotion.
  action_taken = results.include?(true)

  if action_taken
    # connect to the order
    # create the join_table entry.
    order.promotions << self unless order.promotions.include?(self)
    order.save
  end

  action_taken
end

#active? ⇒ Boolean

Returns:

  • (Boolean)


163
164
165
# File 'app/models/spree/promotion.rb', line 163

def active?
  starts_at.present? && starts_at < Time.current && (expires_at.blank? || !expired?)
end

#adjusted_credits_count(promotable) ⇒ Object



278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'app/models/spree/promotion.rb', line 278

def adjusted_credits_count(promotable)
  own_credits = case promotable
                when Spree::Cart
                  # Cart-side discount rows carry no order_id and are
                  # never part of credits_count — nothing to subtract.
                  0
                when Order
                  # A checkout that divided across sellers left a discount
                  # row on every child, so what this promotable already
                  # accounts for is its whole group, not just itself.
                  checkouts_credited(credits.where(order_id: promotable.sibling_order_ids))
                else
                  checkouts_credited(credits.where(line_item_id: promotable.id))
                end
  credits_count - own_credits
end

#all_codes_used? ⇒ Boolean

Returns:

  • (Boolean)


175
176
177
# File 'app/models/spree/promotion.rb', line 175

def all_codes_used?
  coupon_codes.used.count == coupon_codes.count
end

#code_for_order(order) ⇒ Object



346
347
348
349
350
351
352
# File 'app/models/spree/promotion.rb', line 346

def code_for_order(order)
  if multi_codes?
    coupon_codes.held_by(order).first&.code
  else
    code
  end
end

#credits ⇒ Object



295
296
297
# File 'app/models/spree/promotion.rb', line 295

def credits
  Spree::Discount.promotion.where(promotion_action_id: actions.map(&:id))
end

#credits_count ⇒ Object

How many times this promotion has been redeemed.

Counted in checkouts rather than orders: a basket spanning several sellers becomes several orders, each carrying its own discount rows, and counting those as separate uses would spend a limited promotion two or three times over on one customer's single redemption.



305
306
307
# File 'app/models/spree/promotion.rb', line 305

def credits_count
  checkouts_credited(credits)
end

#deactivate(payload) ⇒ Object

Called when a promotion is removed from the cart



205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'app/models/spree/promotion.rb', line 205

def deactivate(payload)
  order = payload[:order]
  return unless self.class.order_activatable?(order)

  payload[:promotion] = self

  # Track results from actions to see if any action has been taken.
  # Actions should return nil/false if no action has been taken.
  # If an action returns true, then an action has been taken.
  results = actions.map do |action|
    action.revert(payload) if action.respond_to?(:revert)
  end

  # If an action has been taken, report back to whatever `d this promotion.
  action_taken = results.include?(true)

  if action_taken
    # connect to the order
    # create the join_table entry.
    order.promotions << self unless order.promotions.include?(self)
    order.save
  end

  action_taken
end

#eligible?(promotable, options = {}) ⇒ Boolean

called anytime order.recalculate_totals! happens

Returns:

  • (Boolean)


232
233
234
235
236
# File 'app/models/spree/promotion.rb', line 232

def eligible?(promotable, options = {})
  return false if expired? || usage_limit_exceeded?(promotable) || blacklisted?(promotable) || !code_held_by?(promotable)

  !!eligible_rules(promotable, options)
end

#eligible_rules(promotable, options = {}) ⇒ Object

eligible_rules returns an array of promotion rules where eligible? is true for the promotable if there are no such rules, an empty array is returned if the rules make this promotable ineligible, then nil is returned (i.e. this promotable is not eligible)



241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'app/models/spree/promotion.rb', line 241

def eligible_rules(promotable, options = {})
  # Promotions without rules are eligible by default.
  return [] if rules.none?

  specific_rules = rules.select { |rule| rule.applicable?(promotable) }
  return [] if specific_rules.none?

  rule_eligibility = Hash[specific_rules.map do |rule|
    [rule, rule.eligible?(promotable, options)]
  end]

  if match_all?
    # If there are rules for this promotion, but no rules for this
    # particular promotable, then the promotion is ineligible by default.
    unless rule_eligibility.values.all?
      @eligibility_errors = specific_rules.map(&:eligibility_errors).detect(&:present?)
      return nil
    end
    specific_rules
  else
    unless rule_eligibility.values.any?
      @eligibility_errors = specific_rules.map(&:eligibility_errors).detect(&:present?)
      return nil
    end

    [rule_eligibility.detect { |_, eligibility| eligibility }.first]
  end
end

#expired? ⇒ Boolean

Returns:

  • (Boolean)


171
172
173
# File 'app/models/spree/promotion.rb', line 171

def expired?
  !!(starts_at && Time.current < starts_at || expires_at && Time.current > expires_at)
end

#inactive? ⇒ Boolean

Returns:

  • (Boolean)


167
168
169
# File 'app/models/spree/promotion.rb', line 167

def inactive?
  !active?
end

#line_item_actionable?(order, line_item, options = {}) ⇒ Boolean

Returns:

  • (Boolean)


309
310
311
312
313
314
315
316
317
318
319
320
321
322
# File 'app/models/spree/promotion.rb', line 309

def line_item_actionable?(order, line_item, options = {})
  if eligible?(order, options)
    rules = eligible_rules(order, options)
    if rules.blank?
      true
    else
      rules.send(match_all? ? :all? : :any?) do |rule|
        rule.actionable? line_item
      end
    end
  else
    false
  end
end

#name_for_order(order) ⇒ Object



338
339
340
341
342
343
344
# File 'app/models/spree/promotion.rb', line 338

def name_for_order(order)
  if coupon_code?
    code_for_order(order)
  else
    name
  end.to_s.upcase
end

#pending_rules_or_actions? ⇒ Boolean

Returns:

  • (Boolean)


159
160
161
# File 'app/models/spree/promotion.rb', line 159

def pending_rules_or_actions?
  @pending_promotion_rules.present? || @pending_promotion_actions.present?
end

#products ⇒ Object



270
271
272
# File 'app/models/spree/promotion.rb', line 270

def products
  rules.where(type: 'Spree::Promotion::Rules::Product').map(&:products).flatten.uniq
end

#rules=(rows) ⇒ Object

Flat-payload writer for rules. See TypedAssociations#assign_typed_association.



150
151
152
# File 'app/models/spree/promotion.rb', line 150

def rules=(rows)
  assign_typed_association(:promotion_rules, rows)
end

#usage_limit_exceeded?(promotable) ⇒ Boolean

Returns:

  • (Boolean)


274
275
276
# File 'app/models/spree/promotion.rb', line 274

def usage_limit_exceeded?(promotable)
  usage_limit.present? && usage_limit > 0 && adjusted_credits_count(promotable) >= usage_limit
end

#used_by?(user, excluded_orders = []) ⇒ Boolean

Parameters:

  • excluded_orders (Array<Spree::Order>) (defaults to: []) —

    orders whose own use does not count — an order asking on its own behalf. Excluding one of a split checkout's orders excludes its siblings too, since they are one redemption between them rather than several.

Returns:

  • (Boolean)


328
329
330
331
332
333
334
335
336
# File 'app/models/spree/promotion.rb', line 328

def used_by?(user, excluded_orders = [])
  # A cart is not an order and has no siblings; it simply has nothing to
  # exclude, since its own discounts carry no order_id.
  excluded_ids = excluded_orders.flat_map { |record| record.try(:sibling_order_ids) || [] }.uniq

  user.orders.complete.joins(:discounts).
    where.not(spree_orders: { id: excluded_ids }).
    where(Spree::Discount.table_name => { promotion_id: id, kind: 'promotion' }).any?
end