@@ -3,6 +3,8 @@ module Calculator
33 class AviorTaxCalculator < Spree ::Calculator
44 include Spree ::VatPriceCalculation
55
6+ CACHE_EXPIRATION_DURATION = 10 . minutes
7+
68 def self . description
79 Spree . t ( :avior_tax )
810 end
@@ -15,16 +17,17 @@ def compute_line_item(item)
1517 return 0 unless SpreeAviorTax ::Config [ :enabled ]
1618 return 0 if rate . included_in_price
1719
18- result = LineItemTax . call ( item : item )
19- round_to_two_places ( result . value )
20+ round_to_two_places ( tax_for_line_item ( item ) )
2021 end
2122
2223 def compute_shipment ( shipment )
2324 return 0 unless SpreeAviorTax ::Config [ :enabled ]
2425 return 0 if rate . included_in_price
2526
26- result = ShipmentTax . call ( shipment : shipment )
27- round_to_two_places ( result . value )
27+ round_to_two_places ( tax_for_shipment ( shipment ) )
28+ rescue SpreeAviorTax ::API ::Errors ::AviorTaxServerError => e
29+ errors . add ( :base , e . message )
30+ Rails . logger . error "AviorTax server error: #{ e . message } "
2831 end
2932
3033 def compute_shipping_rate ( _shipping_rate )
@@ -36,6 +39,44 @@ def compute_shipping_rate(_shipping_rate)
3639 def rate
3740 calculable
3841 end
42+
43+ def tax_for_line_item ( item )
44+ order = item . order
45+ tax_address = order . tax_address
46+
47+ rails_cache_key = cache_key ( order , item , tax_address )
48+
49+ Rails . cache . fetch ( rails_cache_key , expires_in : CACHE_EXPIRATION_DURATION ) do
50+ response = AviorTax . new . calculate_for_order ( order , item )
51+ body = response . first
52+ amount = BigDecimal ( body . fips_tax_amount_1 ) + BigDecimal ( body . fips_tax_amount_2 )
53+ amount
54+ end
55+ end
56+
57+ def tax_for_shipment ( shipment )
58+ order = shipment . order
59+ tax_address = order . tax_address
60+
61+ rails_cache_key = cache_key ( order , shipment , tax_address )
62+
63+ Rails . cache . fetch ( rails_cache_key , expires_in : CACHE_EXPIRATION_DURATION ) do
64+ response = AviorTax . new . calculate_for_shipment ( order , shipment )
65+ body = response . first
66+ amount = BigDecimal ( body . fips_tax_amount_1 ) + BigDecimal ( body . fips_tax_amount_2 )
67+ amount
68+ end
69+ end
70+
71+ def cache_key ( order , item , address )
72+ if item . is_a? ( Spree ::LineItem )
73+ [ Spree ::LineItem . to_s , order . id , item . id , address . state_id , address . zipcode , item . taxable_amount , :amount_to_collect ]
74+ else
75+ [ Spree ::Shipment . to_s , order . id , item . id , address . state_id , address . zipcode , item . cost , item . adjustments . reject do |adjustment |
76+ adjustment . source_type == Spree ::TaxRate . to_s
77+ end . map ( &:amount ) . sum . to_f , :amount_to_collect ]
78+ end
79+ end
3980 end
4081 end
4182end
0 commit comments