spree_avalara 6.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,123 @@
1
+ require 'avatax'
2
+ require 'spree_core'
3
+ require 'spree_avalara/engine'
4
+
5
+ module SpreeAvalara
6
+ # Stamped on every Spree::TaxLine this gem writes, and the value it scopes its
7
+ # own rows by when it sweeps them. Also what the Integration's wire shorthand
8
+ # derives to, so the two can never drift apart.
9
+ PROVIDER_ID = 'avalara'.freeze
10
+
11
+ # The name and the identifier Avalara issued for the certified Spree
12
+ # integration, sent as the first two fields of the X-Avalara-Client header —
13
+ # renaming either detaches the gem from that certification.
14
+ APP_NAME = 'SpreebySpark;a0n0b00000PqwGxAAJ'.freeze
15
+ APP_VERSION = Spree.version
16
+
17
+ # Deployment configuration rather than merchant preferences: how long a
18
+ # checkout waits on Avalara is an infrastructure decision, and an estimate runs
19
+ # inside the cart's own transaction, so a slow response holds a lock.
20
+ DEFAULT_OPEN_TIMEOUT = 2.0
21
+ DEFAULT_READ_TIMEOUT = 6.0
22
+
23
+ class Error < StandardError; end
24
+
25
+ # Raised when a store has no active Avalara integration but its market points
26
+ # at this provider. Tax calculation fails closed, so this surfaces rather than
27
+ # letting an order be placed with no tax at all.
28
+ class NotConfiguredError < Error; end
29
+
30
+ # An AvaTax call that did not succeed, carrying the HTTP status and Avalara's
31
+ # own parsed error payload so callers can tell a duplicate document from a
32
+ # rejected credential without re-reading the response.
33
+ # An AvaTax call that did not do what was asked — deliberately this gem's own
34
+ # class and nothing of core's. Whether a given failure means "could not ask"
35
+ # or "was told no" is a judgement about status codes, and TaxProvider makes it
36
+ # at the contract boundary rather than the hierarchy making it here.
37
+ class RequestError < Error
38
+ attr_reader :status, :details
39
+
40
+ # @param message [String, nil]
41
+ # @param status [Integer, nil] the HTTP status, nil for a transport failure
42
+ # @param details [Hash, nil] Avalara's `error` object, parsed
43
+ def initialize(message = nil, status: nil, details: nil)
44
+ @status = status
45
+ @details = details
46
+
47
+ super(message)
48
+ end
49
+ end
50
+
51
+ # @return [Float] seconds to wait for a connection to Avalara
52
+ def self.open_timeout
53
+ Float(ENV.fetch('SPREE_AVALARA_OPEN_TIMEOUT', DEFAULT_OPEN_TIMEOUT))
54
+ end
55
+
56
+ # @return [Float] seconds to wait for Avalara's response
57
+ def self.read_timeout
58
+ Float(ENV.fetch('SPREE_AVALARA_READ_TIMEOUT', DEFAULT_READ_TIMEOUT))
59
+ end
60
+
61
+ # Avalara keys exemption certificates and reporting to this, so it has to be
62
+ # stable for the buyer rather than per order.
63
+ #
64
+ # @param owner [Spree::Cart, Spree::Order]
65
+ # @return [String]
66
+ def self.customer_code(owner)
67
+ owner.customer&.prefixed_id.presence || owner.email.presence || owner.prefixed_id
68
+ end
69
+
70
+ # Where a sale ships from, which decides the origin jurisdiction. Avalara
71
+ # refuses a document with no origin at all, and a cart has no fulfillment
72
+ # until delivery is proposed — every recalculation before that would fail — so
73
+ # the store's own default location stands in until one exists.
74
+ #
75
+ # Deliberately read-only: Store#default_stock_location creates a location when
76
+ # the store has none, and pricing tax must not write inventory records.
77
+ #
78
+ # @param owner [Spree::Cart, Spree::Order]
79
+ # @param item [Spree::LineItem, Spree::Fulfillment, Spree::Fee, Spree::ExchangeLineItem, nil]
80
+ # @return [Spree::StockLocation, nil]
81
+ def self.origin_location(owner, item: nil)
82
+ from_item = case item
83
+ when Spree::Fulfillment then item.stock_location
84
+ when Spree::LineItem then item.fulfillments.first&.stock_location
85
+ when Spree::ExchangeLineItem then item.exchange&.stock_location
86
+ end
87
+ return from_item if from_item
88
+
89
+ locations = owner.store&.stock_locations&.first_party
90
+
91
+ owner.fulfillments.first&.stock_location || locations&.find_by(default: true) || locations&.first
92
+ end
93
+
94
+ # Avalara's length limit for a reporting location code.
95
+ REPORTING_LOCATION_CODE_LIMIT = 50
96
+
97
+ # Which of the merchant's locations a document is reported under: the admin
98
+ # names of the locations its items ship from, read through the same origins
99
+ # the line-level shipFrom uses so the two cannot disagree.
100
+ #
101
+ # @param owner [Spree::Cart, Spree::Order]
102
+ # @param items [Array<Spree::LineItem, Spree::Fulfillment, Spree::Fee, Spree::ExchangeLineItem>]
103
+ # @return [String, nil] nil when no location has an admin name
104
+ def self.reporting_location_code(owner, items)
105
+ items = [nil] if items.blank?
106
+ names = items.filter_map { |item| origin_location(owner, item: item)&.admin_name.presence }.uniq
107
+
108
+ names.join(',').first(REPORTING_LOCATION_CODE_LIMIT).presence
109
+ end
110
+
111
+ # The return, claim or exchange a post-sale line belongs to, whose number
112
+ # keys the documents filed for it.
113
+ #
114
+ # @param item [Spree::ReturnLineItem, Spree::ClaimLineItem, Spree::ExchangeLineItem, nil]
115
+ # @return [Spree::Return, Spree::Claim, Spree::Exchange, nil]
116
+ def self.post_sale_record(item)
117
+ case item
118
+ when Spree::ReturnLineItem then item.return
119
+ when Spree::ClaimLineItem then item.claim
120
+ when Spree::ExchangeLineItem then item.exchange
121
+ end
122
+ end
123
+ end
@@ -0,0 +1,257 @@
1
+ # Migration off the legacy spree_avatax_official extension. Gem-owned, because
2
+ # core knows nothing about that extension — and every step is guarded, so a
3
+ # fresh install runs it as a no-op.
4
+ namespace :spree_avalara do
5
+ desc 'Move a store from spree_avatax_official onto spree_avalara (idempotent)'
6
+ task upgrade: :environment do
7
+ SpreeAvalara::Upgrader.new.call
8
+ end
9
+
10
+ namespace :upgrade do
11
+ desc 'Drop the legacy spree_avatax_official schema (destructive; run after spree_avalara:upgrade)'
12
+ task drop_legacy_schema: :environment do
13
+ SpreeAvalara::Upgrader.new.drop_legacy_schema!
14
+ end
15
+ end
16
+ end
17
+
18
+ module SpreeAvalara
19
+ # Defined here rather than in app/ so it ships with the task and nothing else
20
+ # can call it by accident.
21
+ class Upgrader
22
+ LEGACY_INTEGRATION_TYPE = 'Spree::Integrations::Avalara'.freeze
23
+ LEGACY_USER_TABLE = 'spree_users'.freeze
24
+ LEGACY_TRANSACTIONS_TABLE = 'spree_avatax_official_transactions'.freeze
25
+
26
+ # Prefixes that identify the VAT regime a number belongs to. EL is Greece's
27
+ # VAT prefix and XI is Northern Ireland's, both of which file as EU numbers.
28
+ EU_VAT_PREFIXES = %w[AT BE BG CY CZ DE DK EE EL ES FI FR HR HU IE IT LT LU
29
+ LV MT NL PL PT RO SE SI SK XI].freeze
30
+
31
+ def call
32
+ say 'Upgrading to spree_avalara'
33
+ say " integrations retyped: #{retype_integrations}"
34
+ say " commit settings translated: #{translate_commit_setting}"
35
+ say " tax identifiers created from vat_id: #{migrate_vat_ids}"
36
+ report_preserved_exemption_data
37
+ say " synthesized tax rates deleted: #{delete_synthesized_tax_rates}"
38
+ say " markets pointed at Avalara: #{point_markets_at_avalara}"
39
+ say " tax exemption reasons added: #{create_exemption_reasons}"
40
+ say
41
+ say ' Legacy schema is left in place. Once you have checked the result, drop it with:'
42
+ say ' bin/rails spree_avalara:upgrade:drop_legacy_schema'
43
+ say ' A document id is not carried over for orders filed by the legacy extension: it recorded'
44
+ say ' the document code (the order number), which void and refund derive anyway.'
45
+ end
46
+
47
+ # Deliberately keeps spree_users.exemption_number, avatax_entity_use_code_id
48
+ # and the entity-use-code table: they are the migration source for whichever
49
+ # answer customer-level exemptions get, and nothing reads them meanwhile.
50
+ def drop_legacy_schema!
51
+ say 'Dropping legacy spree_avatax_official schema'
52
+
53
+ if connection.table_exists?(LEGACY_TRANSACTIONS_TABLE)
54
+ connection.drop_table(LEGACY_TRANSACTIONS_TABLE)
55
+ say " dropped #{LEGACY_TRANSACTIONS_TABLE}"
56
+ end
57
+
58
+ %w[spree_line_items spree_shipments spree_fulfillments].each do |table|
59
+ next unless connection.table_exists?(table) && connection.column_exists?(table, :avatax_uuid)
60
+
61
+ connection.remove_column(table, :avatax_uuid)
62
+ say " dropped #{table}.avatax_uuid"
63
+ end
64
+
65
+ drop_column(LEGACY_USER_TABLE, :vat_id)
66
+ drop_column('spree_stores', :avatax_company_code)
67
+
68
+ say ' Kept: exemption_number, avatax_entity_use_code_id and the entity use code table.'
69
+ end
70
+
71
+ private
72
+
73
+ def retype_integrations
74
+ return 0 unless connection.table_exists?(Spree::Integration.table_name)
75
+
76
+ Spree::Integration.where(type: LEGACY_INTEGRATION_TYPE).update_all(type: 'SpreeAvalara::Integration')
77
+ end
78
+
79
+ # The legacy "commit transactions" switch became a choice of how documents
80
+ # are recorded. Off meant filed but left Saved, which is "record without
81
+ # committing"; on is the new default, so only off needs writing. A row that
82
+ # already holds a choice is left alone, which keeps a second run a no-op.
83
+ #
84
+ # Read and written as the stored column rather than through the model, which
85
+ # fills in the new choice's default and would hide that none was ever made.
86
+ def translate_commit_setting
87
+ return 0 unless connection.table_exists?(Spree::Integration.table_name)
88
+
89
+ rows = Spree::Integration.where(type: 'SpreeAvalara::Integration').pluck(:id, :preferences)
90
+ rows.sum do |id, stored|
91
+ preferences = (stored || {}).with_indifferent_access
92
+ next 0 if preferences.key?(:document_recording)
93
+ next 0 unless preferences[:commit_transaction_enabled].to_s == 'false'
94
+
95
+ Spree::Integration.where(id: id).update_all(preferences: preferences.merge(document_recording: 'save'))
96
+ 1
97
+ end
98
+ end
99
+
100
+ # The legacy extension stored one VAT number per user; core stores a typed
101
+ # registration per owner. Kind comes from the number itself where it says so,
102
+ # then from where the customer is, and eu_vat last — a wrong kind is a failed
103
+ # validation later, not a wrong tax charge.
104
+ def migrate_vat_ids
105
+ source = legacy_vat_id_source
106
+ return 0 if source.nil?
107
+
108
+ migrated = 0
109
+ rejected = []
110
+
111
+ source.where.not(vat_id: [nil, '']).find_each do |row|
112
+ customer = Spree.customer_class.find_by(id: row.id)
113
+ next if customer.nil?
114
+
115
+ kind = vat_kind_for(row.vat_id, customer)
116
+ next if customer.tax_identifiers.exists?(kind: kind)
117
+
118
+ identifier = customer.tax_identifiers.new(kind: kind, value: row.vat_id.to_s.strip)
119
+
120
+ # The legacy column was free text, so some values will not validate as
121
+ # the registration they claim to be. One of those must not abort the
122
+ # upgrade: a missing identifier means the buyer is charged as a consumer,
123
+ # which is the safe direction, and the merchant can reconcile the list.
124
+ if identifier.save
125
+ migrated += 1
126
+ else
127
+ rejected << "customer #{customer.id}: #{row.vat_id.inspect} (#{identifier.errors.full_messages.to_sentence})"
128
+ end
129
+ end
130
+
131
+ report_rejected_vat_ids(rejected)
132
+
133
+ migrated
134
+ end
135
+
136
+ def report_rejected_vat_ids(rejected)
137
+ return if rejected.empty?
138
+
139
+ say " ! #{rejected.size} vat_id value(s) did not validate and were left behind:"
140
+ rejected.each { |line| say " #{line}" }
141
+ end
142
+
143
+ def vat_kind_for(value, customer)
144
+ number = value.to_s.strip.upcase
145
+ return 'gb_vat' if number.start_with?('GB')
146
+ return 'ch_vat' if number.start_with?('CHE')
147
+ return 'eu_vat' if EU_VAT_PREFIXES.any? { |prefix| number.start_with?(prefix) }
148
+
149
+ country = customer_country(customer)
150
+ return 'gb_vat' if country == 'GB'
151
+ return 'ch_vat' if country == 'CH'
152
+ return 'eu_vat' if EU_VAT_PREFIXES.include?(country)
153
+
154
+ say " ! #{value.inspect} names no VAT regime and customer #{customer.id} none either — filed as eu_vat"
155
+ 'eu_vat'
156
+ end
157
+
158
+ def customer_country(customer)
159
+ address = %i[default_bill_address bill_address default_address].filter_map do |reader|
160
+ customer.public_send(reader) if customer.respond_to?(reader)
161
+ end.first
162
+
163
+ address&.country_code.to_s.upcase.presence
164
+ end
165
+
166
+ def report_preserved_exemption_data
167
+ source = legacy_user_table
168
+ return if source.nil?
169
+
170
+ columns = source.column_names & %w[exemption_number avatax_entity_use_code_id]
171
+ return if columns.empty?
172
+
173
+ carrying = source.where(columns.map { |column| "#{column} IS NOT NULL" }.join(' OR ')).count
174
+ return if carrying.zero?
175
+
176
+ say " #{carrying} legacy user(s) carry exemption data (#{columns.join(', ')}), left untouched"
177
+ say ' Company certificates migrate through core; individual exemptions have no home yet.'
178
+ end
179
+
180
+ # The legacy extension synthesized a rate row to hang its adjustments on.
181
+ # Left behind, the Internal engine would read it as real configuration.
182
+ def delete_synthesized_tax_rates
183
+ name = ENV.fetch('AVATAX_TAX_RATE_NAME', 'AvaTax Official Tax Rate')
184
+
185
+ Spree::TaxRate.where(name: name).destroy_all.size
186
+ end
187
+
188
+ # The legacy extension kept Avalara's entity use codes in an editable table
189
+ # merchants picked from; each store connected to Avalara gets them as tax
190
+ # exemption reasons instead. Found by code or name, so a reason the merchant
191
+ # already added or renamed is left alone. TAXABLE is not a reason to be exempt.
192
+ def create_exemption_reasons
193
+ created = 0
194
+
195
+ Spree::Store.find_each do |store|
196
+ next if SpreeAvalara::Integration.active_for(store).nil?
197
+
198
+ SpreeAvalara::EntityUseCodes::ALL.except('TAXABLE').each do |code, label|
199
+ reason = store.tax_exemption_reasons.find_or_create_by_code_or_name!(code: code, name: "#{label.capitalize} (#{code})")
200
+ created += 1 if reason.previously_new_record?
201
+ end
202
+ end
203
+
204
+ created
205
+ end
206
+
207
+ # Only where nothing is set. The legacy extension was store-global, so a
208
+ # blank market on an upgrading merchant means "was calculating through
209
+ # Avalara" — and leaving it blank falls back to Internal, whose rate table is
210
+ # empty for exactly these merchants. An explicit choice is never rewritten.
211
+ def point_markets_at_avalara
212
+ pointed = 0
213
+
214
+ Spree::Market.where(tax_provider: [nil, '']).find_each do |market|
215
+ next if SpreeAvalara::Integration.active_for(market.store).nil?
216
+
217
+ market.update_column(:tax_provider, 'SpreeAvalara::TaxProvider')
218
+ say " #{market.name} now calculates through Avalara"
219
+ pointed += 1
220
+ end
221
+
222
+ pointed
223
+ end
224
+
225
+ # An anonymous reader: the legacy table has no model in 6.0, and the column
226
+ # may sit on either the legacy user table or the customer table depending on
227
+ # whether the host copied or renamed.
228
+ def legacy_vat_id_source
229
+ [legacy_user_table, Spree.customer_class].compact.find do |model|
230
+ model.column_names.include?('vat_id')
231
+ end
232
+ end
233
+
234
+ def legacy_user_table
235
+ return @legacy_user_table if defined?(@legacy_user_table)
236
+
237
+ @legacy_user_table = if connection.table_exists?(LEGACY_USER_TABLE)
238
+ Class.new(ActiveRecord::Base) { self.table_name = LEGACY_USER_TABLE }
239
+ end
240
+ end
241
+
242
+ def drop_column(table, column)
243
+ return unless connection.table_exists?(table) && connection.column_exists?(table, column)
244
+
245
+ connection.remove_column(table, column)
246
+ say " dropped #{table}.#{column}"
247
+ end
248
+
249
+ def connection
250
+ ActiveRecord::Base.connection
251
+ end
252
+
253
+ def say(message = '')
254
+ puts message
255
+ end
256
+ end
257
+ end
metadata ADDED
@@ -0,0 +1,109 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: spree_avalara
3
+ version: !ruby/object:Gem::Version
4
+ version: 6.0.6
5
+ platform: ruby
6
+ authors:
7
+ - Spark Solutions Sp. z o.o.
8
+ - Vendo Connect Inc.
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 1980-01-02 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: avatax
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '19.3'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '19.3'
27
+ - !ruby/object:Gem::Dependency
28
+ name: spree_core
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - '='
32
+ - !ruby/object:Gem::Version
33
+ version: 6.0.6
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - '='
39
+ - !ruby/object:Gem::Version
40
+ version: 6.0.6
41
+ - !ruby/object:Gem::Dependency
42
+ name: vcr
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ description: The officially supported Avalara AvaTax extension for Spree Commerce
56
+ using Avalara REST API v2 — sales tax, VAT and GST calculation, exemptions, address
57
+ validation and document filing
58
+ email: hello@spreecommerce.org
59
+ executables: []
60
+ extensions: []
61
+ extra_rdoc_files: []
62
+ files:
63
+ - LICENSE
64
+ - README.md
65
+ - Rakefile
66
+ - app/models/spree_avalara/entity_use_codes.rb
67
+ - app/models/spree_avalara/integration.rb
68
+ - app/models/spree_avalara/tax_provider.rb
69
+ - app/models/spree_avalara/transaction_line.rb
70
+ - app/presenters/spree_avalara/address_presenter.rb
71
+ - app/presenters/spree_avalara/item_presenter.rb
72
+ - app/presenters/spree_avalara/refund_presenter.rb
73
+ - app/presenters/spree_avalara/transaction_presenter.rb
74
+ - app/services/spree_avalara/address/validate.rb
75
+ - app/services/spree_avalara/client.rb
76
+ - app/services/spree_avalara/estimate_cache_key.rb
77
+ - app/services/spree_avalara/validate_checkout_address.rb
78
+ - config/locales/en.yml
79
+ - lib/spree_avalara.rb
80
+ - lib/spree_avalara/engine.rb
81
+ - lib/spree_avalara/factories.rb
82
+ - lib/spree_avalara/testing_support/factories/integration_factory.rb
83
+ - lib/tasks/upgrade.rake
84
+ homepage: https://spreecommerce.org
85
+ licenses:
86
+ - MIT
87
+ metadata:
88
+ bug_tracker_uri: https://github.com/spree/spree/issues
89
+ changelog_uri: https://github.com/spree/spree/releases/tag/v6.0.6
90
+ documentation_uri: https://spreecommerce.org/docs/integrations/tax/avalara
91
+ source_code_uri: https://github.com/spree/spree/tree/v6.0.6
92
+ rdoc_options: []
93
+ require_paths:
94
+ - lib
95
+ required_ruby_version: !ruby/object:Gem::Requirement
96
+ requirements:
97
+ - - ">="
98
+ - !ruby/object:Gem::Version
99
+ version: '3.2'
100
+ required_rubygems_version: !ruby/object:Gem::Requirement
101
+ requirements:
102
+ - - ">="
103
+ - !ruby/object:Gem::Version
104
+ version: '0'
105
+ requirements: []
106
+ rubygems_version: 4.0.20
107
+ specification_version: 4
108
+ summary: The official Avalara AvaTax extension for Spree Commerce
109
+ test_files: []