summaryrefslogtreecommitdiff
path: root/lib/super_good/solidus_taxjar/api.rb
blob: 250421673fa3a76c678fe52d70c161296f8809eb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
module SuperGood
  module SolidusTaxJar
    class API
      def self.default_taxjar_client
        ::Taxjar::Client.new(
          api_key: ENV.fetch("TAXJAR_API_KEY"),
          api_url: ENV.fetch("TAXJAR_API_URL") { 'https://api.taxjar.com' } # Sandbox URL: https://api.sandbox.taxjar.com
        )
      end

      def initialize(taxjar_client: self.class.default_taxjar_client)
        @taxjar_client = taxjar_client
      end

      def tax_for(order)
        taxjar_client.tax_for_order order_params(order)
      end

      def tax_rates_for(address)
        taxjar_client.rates_for_location(
          address.zipcode,
          street: address.address1,
          city: address.city,
          state: address&.state&.abbr || address.state_name,
          country: address.country.iso
        )
      end

      def order_params(order)
        tax_address = order.tax_address

        {
          to_country: tax_address.country.iso,
          to_zip: tax_address.zipcode,
          to_city: tax_address.city,
          to_state: tax_address&.state&.abbr || tax_address.state_name,
          to_street: tax_address.address1,

          shipping: order.shipment_total,

          line_items: order.line_items.map do |line_item|
            {
              id: line_item.id,
              quantity: line_item.quantity,
              unit_price: line_item.price,
              discount: discount(line_item),
              product_tax_code: line_item.tax_category&.tax_code
            }
          end
        }
      end

      private

      attr_reader :taxjar_client

      def discount(line_item)
        ::SuperGood::SolidusTaxJar.discount_calculator.new(line_item).discount
      end
    end
  end
end