Class: Workarea::Pricing::Discount::BuySomeGetSome::ProductApplication

Inherits:
Object
  • Object
show all
Defined in:
app/models/workarea/pricing/discount/buy_some_get_some/product_application.rb

Overview

This class is responsible determining the distribution of the discount across items within a product.

Instance Method Summary collapse

Constructor Details

#initialize(discount, product) ⇒ ProductApplication

Returns a new instance of ProductApplication.



10
11
12
13
# File 'app/models/workarea/pricing/discount/buy_some_get_some/product_application.rb', line 10

def initialize(discount, product)
  @discount = discount
  @product = product
end

Instance Method Details

#applicationsInteger

How many times the discount can be applied across items in the order for this product.

Returns:

  • (Integer)


44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'app/models/workarea/pricing/discount/buy_some_get_some/product_application.rb', line 44

def applications
  @applications ||=
    begin
      applications = @product.quantity / @discount.total_quantity

      if @discount.max_applications.present? &&
        applications > @discount.max_applications
        @discount.max_applications
      else
        applications
      end
    end
end

#itemsHash

Determines the quantity of each item for the product that can have the discount applied.

Returns:

  • (Hash)


20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'app/models/workarea/pricing/discount/buy_some_get_some/product_application.rb', line 20

def items
  @items ||= begin
    remaining = standard_quantity

    items_by_price.inject({}) do |hash, item|
      if remaining > item.quantity
        apply_quantity = 0
        remaining -= item.quantity
      else
        apply_quantity = item.quantity - remaining
        remaining = 0
      end

      hash[item] = apply_quantity
      hash
    end
  end
end

#items_by_priceArray<Workarea::Order::Item>

Items for the product sorted by the unit price of the item, ordered highest to lowest

Returns:



72
73
74
75
76
77
78
79
# File 'app/models/workarea/pricing/discount/buy_some_get_some/product_application.rb', line 72

def items_by_price
  @product.items.sort_by do |item|
    item.price_adjustments
      .adjusting('item')
      .map(&:unit)
      .sum
  end
end

#standard_quantityInteger

Quantity that should have standard pricing across items for the product.

Returns:

  • (Integer)


63
64
65
# File 'app/models/workarea/pricing/discount/buy_some_get_some/product_application.rb', line 63

def standard_quantity
  @product.quantity - applications * @discount.apply_quantity
end