Class: SolidusPromotions::Calculators::FlatRate

Inherits:
Spree::Calculator
  • Object
show all
Includes:
PromotionCalculator
Defined in:
app/models/solidus_promotions/calculators/flat_rate.rb

Overview

A calculator that applies a flat rate discount amount.

This calculator returns a fixed discount amount if the item’s order currency matches the preferred currency, otherwise it returns zero.

Instance Method Summary collapse

Methods included from PromotionCalculator

#description

Instance Method Details

#compute_item(item) ⇒ BigDecimal Also known as: compute_line_item, compute_shipment, compute_shipping_rate

Computes the discount amount for an item.

Returns the preferred amount if the item’s order currency matches the preferred currency, otherwise returns 0.

Examples:

Computing discount for a line item with matching currency

calculator = FlatRate.new(preferred_amount: 10, preferred_currency: 'USD')
line_item.order.currency # => 'USD'
calculator.compute_item(line_item) # => 10.0

Computing discount for a line item with non-matching currency

calculator = FlatRate.new(preferred_amount: 10, preferred_currency: 'USD')
line_item.order.currency # => 'EUR'
calculator.compute_item(line_item) # => 0

Parameters:

  • item (Object)

    The item to calculate the discount for (e.g., LineItem, Shipment, ShippingRate)

Returns:

  • (BigDecimal)

    The discount amount (preferred_amount if currency matches, 0 otherwise)



35
36
37
38
39
40
41
42
# File 'app/models/solidus_promotions/calculators/flat_rate.rb', line 35

def compute_item(item)
  currency = item.order.currency
  if item && preferred_currency.casecmp(currency).zero?
    compute_for_amount(item.discountable_amount)
  else
    Spree::ZERO
  end
end

#compute_price(price, options = {}) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'app/models/solidus_promotions/calculators/flat_rate.rb', line 47

def compute_price(price, options = {})
  order = options[:order]
  quantity = options[:quantity]
  return preferred_amount unless order
  return Spree::ZERO if order.currency != preferred_currency
  line_item_with_variant = order.line_items.detect { _1.variant == price.variant }
  desired_extra_amount = quantity * price.discountable_amount
  current_discounted_amount = line_item_with_variant ? line_item_with_variant.discountable_amount : Spree::ZERO
  round_to_currency(
    (compute_for_amount(current_discounted_amount + desired_extra_amount.to_f) -
      compute_for_amount(current_discounted_amount)) / quantity,
    preferred_currency
  )
end