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,420 @@
1
+ module SpreeAvalara
2
+ # Computes tax through Avalara AvaTax. The only sanctioned writer of this
3
+ # gem's Spree::TaxLine rows.
4
+ #
5
+ # Avalara prices a whole document per call, so +estimate+ ignores the +items+
6
+ # subset it is handed and always sends the whole owner, rewriting every row it
7
+ # owns. That is legitimate under the contract — a provider may rewrite beyond
8
+ # the subset provided it rewrites everything it deletes — and the response
9
+ # cache is what keeps the single-item call sites affordable.
10
+ class TaxProvider < Spree::TaxProvider::Base
11
+ # Answers that name a temporary condition rather than a problem with the
12
+ # request: rate limiting and a timeout Avalara reported itself. They arrive
13
+ # as 4xx, but telling a shopper their address is wrong when the next attempt
14
+ # would have worked is the wrong end of the contract.
15
+ RETRYABLE_STATUSES = [408, 429].freeze
16
+
17
+ # Avalara's tax code catalogue changes rarely, and a merchant types several
18
+ # searches in a row while classifying a category.
19
+ TAX_CODES_EXPIRE_IN = 1.hour
20
+
21
+ # AvaTax handles US local tax, reverse charge and proportional delivery tax
22
+ # natively. EU one-stop-shop thresholds depend on the merchant's own Avalara
23
+ # company profile rather than on this gem, so there is nothing here to warn
24
+ # a merchant about.
25
+ def self.unsupported_capabilities
26
+ []
27
+ end
28
+
29
+ def self.display_name
30
+ 'Avalara AvaTax'
31
+ end
32
+
33
+ # AvaTax decides an exemption by its entity use code, so these are the
34
+ # codes a merchant's exemption reasons should store.
35
+ def self.exemption_reason_codes
36
+ EntityUseCodes::ALL
37
+ end
38
+
39
+ # Avalara's own tax codes matching the query, for the tax category form.
40
+ # Nothing is searched with nothing connected.
41
+ #
42
+ # @see Spree::TaxProvider::Base.tax_codes
43
+ def self.tax_codes(store, query:)
44
+ integration = Integration.active_for(store)
45
+ return [] if integration.nil?
46
+
47
+ # Keyed on the limit too: an answer cut to a smaller page is not the answer
48
+ # to the same search under a larger one.
49
+ Rails.cache.fetch(['spree_avalara/tax_codes', integration.preferred_endpoint,
50
+ SpreeAvalara::Client::TAX_CODE_SEARCH_LIMIT, query.downcase],
51
+ expires_in: TAX_CODES_EXPIRE_IN) do
52
+ integration.client.list_tax_codes(query).map do |record|
53
+ { code: record['taxCode'], description: record['description'] }
54
+ end
55
+ end
56
+ rescue SpreeAvalara::Error => error
57
+ raise tax_failure(error)
58
+ end
59
+
60
+ # Which of core's two failures an AvaTax error is, decided by whether
61
+ # Avalara answered at all.
62
+ #
63
+ # No status means nothing was answered — the network, or a timeout — and a
64
+ # later attempt may well succeed. A 5xx is the same shape: Avalara's own
65
+ # fault, not the request's.
66
+ #
67
+ # Anything else is Avalara saying no to this particular request: an address
68
+ # it will not accept, a company code that does not exist. The service is
69
+ # working and retrying is pointless, so the caller must be able to tell the
70
+ # customer what was wrong instead of asking them to try again. Avalara's own
71
+ # message is carried across, because it names the problem better than
72
+ # anything this gem could invent.
73
+ #
74
+ # @param error [SpreeAvalara::Error]
75
+ # @return [Spree::Tax::ProviderError]
76
+ def self.tax_failure(error)
77
+ # A protocol violation carries no status at all, and lands as unavailable:
78
+ # the sale is refused either way, and telling a customer to correct an
79
+ # address when the response shape was wrong would send them nowhere.
80
+ status = error.try(:status).to_i
81
+ unavailable = error.try(:status).nil? || status >= 500 || RETRYABLE_STATUSES.include?(status)
82
+
83
+ failure = unavailable ? Spree::Tax::ProviderUnavailable : Spree::Tax::CalculationRefused
84
+ failure.new(error.message, provider_key: SpreeAvalara::PROVIDER_ID)
85
+ end
86
+
87
+ # Fails closed on a service failure — an Avalara that refuses or cannot be
88
+ # reached raises, because silently under-collecting is a liability the
89
+ # merchant discovers in a filing.
90
+ #
91
+ # Being *disconnected* is different, and deliberately not a failure. An
92
+ # integration is an operational toggle: a merchant connects providers at
93
+ # different stages, deactivates one to change credentials, activates it
94
+ # again. None of that may decide whether a customer can add to their cart or
95
+ # place an order, so an unconnected provider simply has no opinion and writes
96
+ # no rows.
97
+ #
98
+ # @see Spree::TaxProvider::Base#estimate
99
+ def estimate(owner, items = nil, tax_date: nil, tax_identifier: nil, exemptions: [], tax_inclusive: nil, context: {})
100
+ integration = Integration.active_for(owner.store)
101
+ taxable = owner.taxable_items
102
+
103
+ # Nothing to price: no items, nowhere to ship, or nothing connected to ask.
104
+ # The stale rows go and nothing replaces them — each item is worth its whole
105
+ # basis again, which is what Internal does when no rate matches.
106
+ if integration.nil? || taxable.empty? || owner.tax_address.nil?
107
+ report_disconnected(owner) if integration.nil?
108
+ sweep!(owner)
109
+ taxable.each { |item| reset_pre_tax_amount(item) }
110
+ return
111
+ end
112
+
113
+ tax_inclusive = owner.tax_inclusive? if tax_inclusive.nil?
114
+ body = fetch(owner, taxable, integration, tax_date, tax_identifier, exemptions, tax_inclusive)
115
+ lines = TransactionLine.from_response(
116
+ body, context: response_context(owner, taxable, tax_identifier, exemptions)
117
+ )
118
+
119
+ ApplicationRecord.transaction do
120
+ sweep!(owner)
121
+ write_lines(owner, taxable, lines)
122
+ end
123
+ rescue SpreeAvalara::Error => error
124
+ # The whole family, not just a refused request: reading the response back
125
+ # raises on a line we never sent or an item we cannot tax, and those left
126
+ # unmapped escaped as a 500 — the failure this contract exists to remove.
127
+ raise tax_failure(error)
128
+ end
129
+
130
+ # Files the sale with Avalara once it is placed.
131
+ #
132
+ # Idempotent, because completion is replayable: a crash between the order
133
+ # commit and the cart stamp leaves Carts::Complete to re-run its finalize
134
+ # phase. create_or_adjust_transaction keyed on the order number adjusts the
135
+ # document rather than filing a second one, and a duplicate refusal counts
136
+ # as the success it describes.
137
+ #
138
+ # @param order [Spree::Order]
139
+ # @return [void]
140
+ def commit(order)
141
+ integration = filing_integration(order)
142
+ return if integration.nil?
143
+
144
+ body = integration.client.create_or_adjust_transaction(
145
+ createTransactionModel: TransactionPresenter.new(
146
+ owner: order, integration: integration, items: order.taxable_items,
147
+ type: 'SalesInvoice', code: order.number,
148
+ commit: integration.commits_documents?,
149
+ tax_date: order.completed_at,
150
+ # The order's frozen snapshot, not a fresh resolution: what was
151
+ # filed has to match what was charged.
152
+ tax_identifier: order.resolved_tax_identifier,
153
+ exemptions: order.usable_exemptions
154
+ ).call
155
+ )
156
+
157
+ stamp_document_id(order, body['id'])
158
+ rescue SpreeAvalara::RequestError => error
159
+ raise tax_failure(error) unless integration.client.duplicate_document_error?(error)
160
+ end
161
+
162
+ # Reverses the filed document when the order is cancelled.
163
+ #
164
+ # @param order [Spree::Order]
165
+ # @return [void]
166
+ def void(order)
167
+ # Nothing was ever filed through an integration that is not connected, so
168
+ # there is nothing to reverse and nothing to report. Unlike estimate, this
169
+ # does not fail closed: refusing to cancel an order because a tax service
170
+ # is unreachable helps nobody.
171
+ integration = filing_integration(order, report_missing: false)
172
+ return if integration.nil?
173
+
174
+ integration.client.void_transaction(order.number)
175
+ rescue SpreeAvalara::RequestError => error
176
+ raise tax_failure(error) unless integration.client.already_voided_error?(error)
177
+ end
178
+
179
+ # Gives back exactly the tax the sale charged on the credited units, read
180
+ # off the sale's own rows rather than quoted again: the customer is owed
181
+ # what they paid, and Avalara would price the credit at today's rates and
182
+ # the list price. Needs no connected integration, since nothing is asked.
183
+ #
184
+ # @see Spree::TaxProvider::Base#estimate_refund
185
+ def estimate_refund(order, items, amounts: nil, tax_date: nil)
186
+ Spree::TaxProvider::RecordedShare.new(order: order, items: items, amounts: amounts).call
187
+ end
188
+
189
+ # Quotes an exchange's replacement as a new sale and writes its tax as
190
+ # charge rows on the exchange lines. Fails closed like +estimate+; with
191
+ # nothing connected it has no opinion and writes no rows.
192
+ #
193
+ # @see Spree::TaxProvider::Base#estimate_replacement
194
+ def estimate_replacement(order, items, tax_date: nil, tax_identifier: nil, exemptions: [], tax_inclusive: nil)
195
+ items = Array(items)
196
+ return if items.empty?
197
+
198
+ integration = Integration.active_for(order.store)
199
+ shipped = items.select { |item| item.credited_quantity.to_i.positive? }
200
+
201
+ if integration.nil? || shipped.empty? || order.tax_address.nil?
202
+ report_disconnected(order) if integration.nil?
203
+ sweep_replacement!(items)
204
+ return
205
+ end
206
+
207
+ body = integration.client.create_transaction(
208
+ TransactionPresenter.new(
209
+ owner: order, integration: integration, items: shipped, type: 'SalesOrder',
210
+ tax_date: tax_date, tax_identifier: tax_identifier, exemptions: exemptions,
211
+ tax_inclusive: tax_inclusive
212
+ ).call
213
+ )
214
+ lines = TransactionLine.from_response(
215
+ body, context: response_context(order, shipped, tax_identifier, exemptions)
216
+ )
217
+
218
+ ApplicationRecord.transaction do
219
+ sweep_replacement!(items)
220
+ lines.each do |line|
221
+ Spree::TaxLine.create!(line.to_tax_line_attributes(item: line.matching_item(shipped), owner: order))
222
+ end
223
+ end
224
+ rescue SpreeAvalara::Error => error
225
+ raise tax_failure(error)
226
+ end
227
+
228
+ # Files an exchange's replacement as a sale of its own once it ships,
229
+ # keyed to the exchange so a replay adjusts one document. Its credit is a
230
+ # separate ReturnInvoice (see #refund), so the two carry different codes.
231
+ #
232
+ # @see Spree::TaxProvider::Base#commit_replacement
233
+ def commit_replacement(order, items)
234
+ shipped = Array(items).select { |item| item.credited_quantity.to_i.positive? }
235
+ return if shipped.empty?
236
+
237
+ integration = filing_integration(order)
238
+ return if integration.nil?
239
+
240
+ exchange = SpreeAvalara.post_sale_record(shipped.first)
241
+ integration.client.create_or_adjust_transaction(
242
+ createTransactionModel: TransactionPresenter.new(
243
+ owner: order, integration: integration, items: shipped, type: 'SalesInvoice',
244
+ code: "#{order.number}-#{exchange&.number}-REPLACEMENT",
245
+ # Dated when the exchange was fulfilled, so a replay on a later day
246
+ # adjusts the document without moving it to another period.
247
+ tax_date: exchange.try(:fulfilled_at),
248
+ commit: integration.commits_documents?,
249
+ tax_identifier: order.resolved_tax_identifier,
250
+ exemptions: order.usable_exemptions
251
+ ).call
252
+ )
253
+ rescue SpreeAvalara::RequestError => error
254
+ raise tax_failure(error) unless integration.client.duplicate_document_error?(error)
255
+ end
256
+
257
+ # Credits the lines of a return, claim or exchange against the filed
258
+ # document, with the tax their credit rows gave back.
259
+ #
260
+ # @param order [Spree::Order]
261
+ # @param return_items [Array<Spree::ReturnLineItem, Spree::ClaimLineItem, Spree::ExchangeLineItem>]
262
+ # @param amount [BigDecimal, nil] the refund issued; nil = the lines' worth
263
+ # @param tax_date [Time, nil] the original supply date
264
+ # @return [void]
265
+ def refund(order, return_items, amount: nil, tax_date: nil)
266
+ integration = filing_integration(order)
267
+ return if integration.nil?
268
+
269
+ presenter = RefundPresenter.new(
270
+ order: order, integration: integration, return_items: return_items,
271
+ amount: amount, tax_date: tax_date, exemptions: order.usable_exemptions,
272
+ # The order's frozen snapshot, as commit uses: the credit has to be
273
+ # filed under the registration the sale was.
274
+ tax_identifier: order.resolved_tax_identifier
275
+ )
276
+ return if presenter.nothing_to_credit?
277
+
278
+ integration.client.create_transaction(presenter.call)
279
+ rescue SpreeAvalara::RequestError => error
280
+ raise tax_failure(error) unless integration.client.duplicate_document_error?(error)
281
+ end
282
+
283
+ private
284
+
285
+ def tax_failure(error)
286
+ self.class.tax_failure(error)
287
+ end
288
+
289
+ # The integration to file a sale, void or credit with, or nil when nothing
290
+ # is to be filed: nothing is connected, or the merchant leaves recording to
291
+ # another system. A missing integration is reported rather than raised —
292
+ # refusing an order the customer has paid for is worse than a sale the
293
+ # merchant files by hand.
294
+ def filing_integration(order, report_missing: true)
295
+ integration = Integration.active_for(order.store)
296
+ report_disconnected(order) if integration.nil? && report_missing
297
+
298
+ integration if integration&.records_documents?
299
+ end
300
+
301
+ # A market calculating through Avalara with nothing connected produces no tax
302
+ # at all, which is visible in the storefront and the dashboard — but the
303
+ # reason is not, so it is reported where the host collects errors.
304
+ def report_disconnected(owner)
305
+ Rails.error.report(
306
+ SpreeAvalara::NotConfiguredError.new(
307
+ "Store #{owner.store_id.inspect} calculates tax through Avalara, but no integration is connected"
308
+ ),
309
+ handled: true,
310
+ context: { store_id: owner.store_id, owner: owner.class.name, owner_id: owner.id },
311
+ source: 'spree_avalara'
312
+ )
313
+
314
+ nil
315
+ end
316
+
317
+ # Informational: void and refund key on the document code, which is the
318
+ # order number. update_column because completion may replay and there is
319
+ # nothing here to validate.
320
+ def stamp_document_id(order, document_id)
321
+ return if document_id.blank?
322
+
323
+ order.metadata = (order.metadata || {}).merge('avalara_transaction_id' => document_id.to_s)
324
+ order.update_column(:metadata, order.metadata)
325
+ end
326
+
327
+ # Provider-scoped: another engine's rows on the same owner — the import VAT
328
+ # a landed-cost provider writes against a duty — are not ours to delete.
329
+ def sweep!(owner)
330
+ owner.tax_lines.where(provider_id: SpreeAvalara::PROVIDER_ID).delete_all
331
+
332
+ nil
333
+ end
334
+
335
+ # Only the replacement's charge rows: the credit rows on the same lines are
336
+ # what the customer is refunded, and the order's own rows are the sale.
337
+ def sweep_replacement!(items)
338
+ Spree::TaxLine.charges.where(exchange_line_item_id: items.map(&:id), provider_id: SpreeAvalara::PROVIDER_ID).delete_all
339
+
340
+ nil
341
+ end
342
+
343
+ def fetch(owner, taxable, integration, tax_date, tax_identifier, exemptions, tax_inclusive)
344
+ cache_key = EstimateCacheKey.new(
345
+ owner: owner, items: taxable, integration: integration,
346
+ tax_identifier: tax_identifier, exemptions: exemptions, tax_inclusive: tax_inclusive
347
+ )
348
+
349
+ # Only successes are cached: the block raises on a refusal, which
350
+ # Rails.cache does not store.
351
+ Rails.cache.fetch(cache_key.key, expires_in: EstimateCacheKey::EXPIRES_IN) do
352
+ integration.client.create_transaction(
353
+ TransactionPresenter.new(
354
+ owner: owner, integration: integration, items: taxable, type: 'SalesOrder',
355
+ tax_date: tax_date, tax_identifier: tax_identifier, exemptions: exemptions,
356
+ tax_inclusive: tax_inclusive
357
+ ).call
358
+ )
359
+ end
360
+ end
361
+
362
+ def write_lines(owner, taxable, lines)
363
+ lines.each do |line|
364
+ item = line.matching_item(taxable)
365
+ Spree::TaxLine.create!(line.to_tax_line_attributes(item: item, owner: owner))
366
+ end
367
+
368
+ taxable.each { |item| store_pre_tax_amount(item, lines) }
369
+ end
370
+
371
+ def reset_pre_tax_amount(item)
372
+ return unless item.respond_to?(:pre_tax_amount)
373
+
374
+ item.update_column(:pre_tax_amount, basis_for(item))
375
+ end
376
+
377
+ def basis_for(item)
378
+ item.respond_to?(:taxable_basis) ? item.taxable_basis : item.amount
379
+ end
380
+
381
+ # Mirrors Internal#store_pre_tax_amount: what the item is worth before tax,
382
+ # which the refund path reads back. Only included-in-price tax comes out of
383
+ # the basis; additional tax sits on top of it.
384
+ def store_pre_tax_amount(item, lines)
385
+ return unless item.respond_to?(:pre_tax_amount)
386
+
387
+ basis = basis_for(item)
388
+ line = lines.find { |candidate| candidate.line_number.to_s == item.prefixed_id.to_s }
389
+ basis -= line.amount if line&.included?
390
+
391
+ item.update_column(:pre_tax_amount, basis)
392
+ end
393
+
394
+ # What the response cannot say for itself: whether a registration was sent,
395
+ # whether an exemption was claimed, and the two ends of the supply.
396
+ #
397
+ # Origins are per line as well as owner-wide, because the request sends a
398
+ # shipFrom per line: an order allocated across warehouses in different
399
+ # countries has no single origin, and classifying every line against one of
400
+ # them reads a domestic line as an intra-community supply, or the reverse.
401
+ # The owner-level value stays as the fallback for a line whose item is not
402
+ # in this set.
403
+ def response_context(owner, taxable, tax_identifier, exemptions)
404
+ {
405
+ identifier_sent: tax_identifier&.value.present?,
406
+ exemption_reasons: Array(exemptions).map(&:reason_code).compact,
407
+ ship_from_country: SpreeAvalara.origin_location(owner)&.country_code,
408
+ ship_from_countries: origin_countries_by_line(owner, taxable),
409
+ ship_to_country: owner.tax_address&.country_code
410
+ }
411
+ end
412
+
413
+ # Keyed by the line number the request used, which is the item's prefixed id.
414
+ def origin_countries_by_line(owner, taxable)
415
+ taxable.each_with_object({}) do |item, countries|
416
+ countries[item.prefixed_id.to_s] = SpreeAvalara.origin_location(owner, item: item)&.country_code
417
+ end
418
+ end
419
+ end
420
+ end