Class: Coupon::OverlappingPromoValidator

Inherits:
ActiveModel::Validator
  • Object
show all
Defined in:
app/validators/coupon/overlapping_promo_validator.rb

Overview

Validates that a coupon does not overlap with any other active coupons that target the same items.

This validator checks if the coupon being validated has any overlapping promotional periods and item targets
with other active coupons. If any overlaps are found, it adds an error to the record's errors collection
with a detailed message describing the overlaps.

Returns:

  • (void)

Instance Method Summary collapse

Instance Method Details

#validate(record) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'app/validators/coupon/overlapping_promo_validator.rb', line 11

def validate(record)
  return if record.is_inactive
  return unless record.promo_tracking

  overlapping_date_scope = Coupon.active.where.not(id: record.id).where(promo_tracking: true).where(customer_filter_id: record.customer_filter_id)
                                 .where(effective_date: [nil, ...(record.expiration_date || Date::Infinity.new)])
                                 .where(expiration_date: [nil, (record.effective_date || Date.current)..])
  all_overlapping_item_ids = []
  overlapping_coupons = overlapping_date_scope.select do |other_coupon|
    overlapping_item_ids = other_coupon.all_applicable_item_ids & record.all_applicable_item_ids
    all_overlapping_item_ids += overlapping_item_ids
    overlapping_item_ids.any?
  end

  return unless overlapping_coupons.any?

  all_overlapping_item_ids = all_overlapping_item_ids.compact.uniq
  overlapping_item_skus = Item.where(id: all_overlapping_item_ids).order(:sku).pluck(:sku)
  error_message = "#{record.code} [#{record.id}] has overlapping promotional periods #{record.effective_date || '-'} to #{record.expiration_date || '-'} and items found with coupons: "
  error_message << overlapping_coupons.map do |c|
    "#{c.code} [#{c.id}] (#{c.effective_date || '-'} - #{c.expiration_date || '-'})"
  end.join(', ')
  error_message << ". Targetting the same items #{overlapping_item_skus.join(', ')}, make sure the period and items do not overlap"
  record.errors.add(:base, error_message)
end