Improve performance on summing adjustments and payment

:amount is a database field in these cases, as opposed to a method that returns a computed result. Calling `.sum(:amount)` is much more efficient here as it computes the sum at database level, as opposed to `.map(&:amount).sum`, which would fetch and instanciate all the objects first, and then sum the amounts after.
This commit is contained in:
Matt-Yorkley
2021-01-13 16:16:49 +00:00
parent 3877721209
commit 7d0ec48bcf
3 changed files with 7 additions and 7 deletions

View File

@@ -19,7 +19,7 @@ module CheckoutHelper
adjustments.reject! { |a| a.originator_type == 'EnterpriseFee' && a.source_type != 'Spree::LineItem' }
unless exclude.include? :admin_and_handling
adjustments << Spree::Adjustment.new(
label: I18n.t(:orders_form_admin), amount: enterprise_fee_adjustments.map(&:amount).sum
label: I18n.t(:orders_form_admin), amount: enterprise_fee_adjustments.sum(:amount)
)
end
@@ -28,7 +28,7 @@ module CheckoutHelper
def display_checkout_admin_and_handling_adjustments_total_for(order)
adjustments = order.adjustments.eligible.where('originator_type = ? AND source_type != ? ', 'EnterpriseFee', 'Spree::LineItem')
Spree::Money.new adjustments.map(&:amount).sum, currency: order.currency
Spree::Money.new adjustments.sum(:amount), currency: order.currency
end
def checkout_line_item_adjustments(order)
@@ -36,7 +36,7 @@ module CheckoutHelper
end
def checkout_subtotal(order)
order.item_total + checkout_line_item_adjustments(order).map(&:amount).sum
order.item_total + checkout_line_item_adjustments(order).sum(:amount)
end
def display_checkout_subtotal(order)

View File

@@ -397,11 +397,11 @@ module Spree
end
def ship_total
adjustments.shipping.map(&:amount).sum
adjustments.shipping.sum(:amount)
end
def tax_total
adjustments.tax.map(&:amount).sum
adjustments.tax.sum(:amount)
end
# Creates new tax charges if there are any applicable rates. If prices already

View File

@@ -55,9 +55,9 @@ module OrderManagement
# - adjustment_total - total value of all adjustments
# - total - order total, it's the equivalent to item_total plus adjustment_total
def update_totals
order.payment_total = payments.completed.map(&:amount).sum
order.payment_total = payments.completed.sum(:amount)
order.item_total = line_items.map(&:amount).sum
order.adjustment_total = adjustments.eligible.map(&:amount).sum
order.adjustment_total = adjustments.eligible.sum(:amount)
order.total = order.item_total + order.adjustment_total
end