summaryrefslogtreecommitdiff
path: root/lib/super_good/solidus_taxjar/addresses.rb
blob: 7fdf852613e9b2149787f66278d7fd909c15d03d (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
module SuperGood
  module SolidusTaxjar
    class Addresses
      class << self
        def normalize(spree_address)
          new.normalize(spree_address)
        end

        def possibilities(spree_address)
          new.possibilities(spree_address)
        end
      end

      def initialize(api: ::SuperGood::SolidusTaxjar.api)
        @api = api
      end

      def normalize(spree_address)
        taxjar_address = taxjar_addresses(spree_address).first

        return if taxjar_address.nil?

        Spree::Address.immutable_merge(spree_address, {
          country: us, # TaxJar only supports the US currently.
          state: state(taxjar_address.state),
          zipcode: taxjar_address.zip,
          city: taxjar_address.city,
          address1: taxjar_address.street
        })
      end

      def possibilities(spree_address)
        taxjar_addresses(spree_address).map { |taxjar_address|
          Spree::Address.immutable_merge(spree_address, {
            country: us, # TaxJar only supports the US currently.
            state: state(taxjar_address.state),
            zipcode: taxjar_address.zip,
            city: taxjar_address.city,
            address1: taxjar_address.street
          })
        }
      end

      private

      attr_reader :api

      def taxjar_addresses(spree_address)
        api.validate_spree_address(spree_address)
      rescue Taxjar::Error::NotFound
        []
      end

      def us
        Spree::Country.find_by iso: "US"
      end

      def state(abbr)
        us.states.find_by_abbr abbr
      end
    end
  end
end