summaryrefslogtreecommitdiff
path: root/lib/super_good/solidus_taxjar/api.rb
blob: 715eb5c4c8ba4410c6612fa04eee7287b87f2f1c (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
63
64
65
66
67
module SuperGood
  module SolidusTaxjar
    class Api
      def self.default_taxjar_client
        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
        )
        client.set_api_config('headers', {
          'x-api-version' => '2020-08-07',
          'plugin' => 'supergoodsolidustaxjar'
        })
        client
      end

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

      def tax_for(order)
        taxjar_client.tax_for_order(ApiParams.order_params(order)).tap do |taxes|
          next unless SuperGood::SolidusTaxjar.logging_enabled

          Rails.logger.info(
            "TaxJar response for #{order.number}: #{taxes.to_h.inspect}"
          )
        end
      end

      def tax_rate_for(address)
        taxjar_client.tax_for_order(ApiParams.tax_rate_address_params(address)).rate
      end

      def tax_rates_for(address)
        taxjar_client.rates_for_location(*ApiParams.address_params(address))
      end

      def create_transaction_for(order)
        taxjar_client.create_order ApiParams.transaction_params(order)
      end

      def update_transaction_for(order)
        taxjar_client.update_order ApiParams.transaction_params(order)
      end

      def delete_transaction_for(order)
        taxjar_client.delete_order order.number
      end

      def create_refund_for(reimbursement)
        taxjar_client.create_refund ApiParams.refund_params(reimbursement)
      end

      def validate_spree_address(spree_address)
        taxjar_client.validate_address ApiParams.validate_address_params(spree_address)
      end

      def nexus_regions
        taxjar_client.nexus_regions
      end

      private

      attr_reader :taxjar_client
    end
  end
end