Skip to content

Commit

Permalink
Avoid re-creating tax adjustments
Browse files Browse the repository at this point in the history
Previously, ItemAdjuster#adjust! would always destroy all tax
adjustments on the item and recreate them. This was unnecessarily slow
in the common case of needing no changes (especially following solidusio#1479).

This changes ItemAdjuster#adjust! to instead update the adjustment for
a rate if it already exists, create adjustments if they are missing for
a matching rate, and destroy adjustments for rates which are no longer
matching.
  • Loading branch information
jhawthorn committed Nov 7, 2016
1 parent 3117564 commit c661c04
Showing 1 changed file with 23 additions and 4 deletions.
27 changes: 23 additions & 4 deletions core/app/models/spree/tax/item_adjuster.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,31 @@ def initialize(item, options = {})
@rates_for_default_zone = options[:rates_for_default_zone]
end

# Deletes all existing tax adjustments and creates new adjustments for all
# (geographically and category-wise) applicable tax rates.
# This updates the amounts for adjustments which already exist and
# creates and remove adjustments as needed to match the applicable
# (geographically and category-wise) tax rates.
def adjust!
item.adjustments.destroy(item.adjustments.select(&:tax?))
rates = rates_for_item(item)

rates_for_item(item).each { |rate| rate.adjust(nil, item) }
tax_adjustments = item.adjustments.select(&:tax?)
active_adjustments = rates.map do |rate|
# Find an existing adjustment from the same source.
# All tax adjustments already have source_type == 'Spree::TaxRate' so
# we need only check source_id.
adjustment = tax_adjustments.detect{|a| a.source_id == rate.id }
if adjustment
adjustment.update!
adjustment
else
# Create a new adjustment
rate.adjust(nil, item)
end
end

unmatched_adjustments = tax_adjustments - active_adjustments

# Remove any tax adjustments tied to rates which no longer match
item.adjustments.destroy(unmatched_adjustments)
end
end
end
Expand Down

0 comments on commit c661c04

Please sign in to comment.