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,118 @@
1
+ module SpreeAvalara
2
+ # A whole cart or order as AvaTax's CreateTransactionModel, shared by the
3
+ # estimate and the filing so the two can never describe the same sale
4
+ # differently.
5
+ class TransactionPresenter
6
+ # @param owner [Spree::Cart, Spree::Order]
7
+ # @param integration [SpreeAvalara::Integration]
8
+ # @param items [Array<Spree::LineItem, Spree::Fulfillment, Spree::Fee>]
9
+ # @param type [String] 'SalesOrder' to quote, 'SalesInvoice' to file
10
+ # @param code [String, nil] document code; Avalara generates one for a quote
11
+ # @param commit [Boolean] file the document as committed
12
+ # @param tax_date [Time, nil] the date whose rates apply
13
+ # @param tax_identifier [Spree::TaxIdentifier, nil] the buyer's registration
14
+ # @param exemptions [Array<Spree::TaxExemption>] accepted; placement is Phase 4
15
+ # @param tax_inclusive [Boolean, nil] whether the prices include tax, as core
16
+ # passes it; nil = ask the owner
17
+ def initialize(owner:, integration:, items:, type:, code: nil, commit: false,
18
+ tax_date: nil, tax_identifier: nil, exemptions: [], tax_inclusive: nil)
19
+ @owner = owner
20
+ @integration = integration
21
+ @items = items
22
+ @type = type
23
+ @code = code
24
+ @commit = commit
25
+ @tax_date = tax_date
26
+ @tax_identifier = tax_identifier
27
+ @exemptions = exemptions
28
+ @tax_inclusive = tax_inclusive.nil? ? owner.tax_inclusive? : tax_inclusive
29
+ end
30
+
31
+ # @return [Hash]
32
+ def call
33
+ payload = {
34
+ type: type,
35
+ companyCode: integration.preferred_company_code,
36
+ date: document_date,
37
+ commit: commit,
38
+ currencyCode: owner.currency,
39
+ customerCode: SpreeAvalara.customer_code(owner),
40
+ addresses: addresses,
41
+ lines: lines
42
+ }
43
+
44
+ payload[:code] = code if code.present?
45
+ payload[:businessIdentificationNo] = tax_identifier.value if tax_identifier&.value.present?
46
+ payload[:purchaseOrderNo] = owner.po_number if owner.po_number.present?
47
+ location_code = SpreeAvalara.reporting_location_code(owner, items)
48
+ payload[:reportingLocationCode] = location_code if location_code
49
+
50
+ # `exemptionNo` here, `exemptionCode` on a line — see ItemPresenter for the
51
+ # matrix. Each name is ignored at the other level, silently.
52
+ if (entry = document_exemption)
53
+ entity_use_code = EntityUseCodes.for(entry.reason_code)
54
+ payload[:entityUseCode] = entity_use_code if entity_use_code
55
+ payload[:exemptionNo] = entry.certificate_number if entry.certificate_number.present?
56
+ end
57
+
58
+ payload
59
+ end
60
+
61
+ # A single claim covering the whole destination with no per-line carve-outs
62
+ # is an order-wide exemption, and saying so once is clearer to Avalara — and
63
+ # to whoever reads the filing — than repeating it on every line. Anything
64
+ # narrower is placed per line instead.
65
+ #
66
+ # @return [Spree::TaxExemption, nil]
67
+ def document_exemption
68
+ return if exemptions.size != 1
69
+
70
+ entry = exemptions.first
71
+ return if entry.item_overrides.present?
72
+ return unless entry.covers_jurisdiction?(destination_country, destination_state)
73
+
74
+ entry
75
+ end
76
+
77
+ private
78
+
79
+ attr_reader :owner, :integration, :items, :type, :code, :commit,
80
+ :tax_date, :tax_identifier, :exemptions, :tax_inclusive
81
+
82
+ # Which day's rates apply, read in the store's own zone: a merchant closing
83
+ # a sale late on the 31st means their 31st, not the server's next morning.
84
+ def document_date
85
+ zone = Time.find_zone(owner.store&.preferred_timezone) || Time.zone
86
+
87
+ (tax_date || Time.current).in_time_zone(zone).to_date.iso8601
88
+ end
89
+
90
+ # The bill-to address rides along for the record; tax follows the tax
91
+ # address, which shipTo already carries.
92
+ def addresses
93
+ {
94
+ shipFrom: AddressPresenter.new(SpreeAvalara.origin_location(owner)).call,
95
+ shipTo: AddressPresenter.new(owner.tax_address).call,
96
+ billTo: AddressPresenter.new(owner.bill_address).call
97
+ }.compact
98
+ end
99
+
100
+ def lines
101
+ # Placed once on the document, or line by line — never both.
102
+ line_exemptions = document_exemption ? [] : exemptions
103
+
104
+ items.map do |item|
105
+ ItemPresenter.new(item: item, owner: owner, tax_included: tax_inclusive,
106
+ exemptions: line_exemptions).call
107
+ end
108
+ end
109
+
110
+ def destination_country
111
+ owner.tax_address&.country_code
112
+ end
113
+
114
+ def destination_state
115
+ owner.tax_address&.state_code
116
+ end
117
+ end
118
+ end
@@ -0,0 +1,91 @@
1
+ module SpreeAvalara
2
+ module Address
3
+ # Resolves an address against Avalara's validation service. Public so a
4
+ # storefront can offer feedback at the address step; the checkout handler
5
+ # uses the same service at completion.
6
+ #
7
+ # Avalara validates US and Canadian addresses only. Anything else resolves
8
+ # trivially rather than failing — there is no opinion to be had.
9
+ class Validate
10
+ SUPPORTED_COUNTRIES = %w[US CA].freeze
11
+
12
+ # The outcome, kept as a value object so callers read intent rather than
13
+ # inspecting a response body.
14
+ class Result
15
+ include ActiveModel::Model
16
+ include ActiveModel::Attributes
17
+
18
+ attribute :body, default: -> { {} }
19
+ attribute :error
20
+
21
+ def success?
22
+ error.nil?
23
+ end
24
+ end
25
+
26
+ # Why an address was not accepted. `transport?` separates "Avalara judged
27
+ # this address" from "no judgement was obtained", which the two callers
28
+ # treat very differently.
29
+ class Failure
30
+ include ActiveModel::Model
31
+ include ActiveModel::Attributes
32
+
33
+ attribute :messages, default: -> { [] }
34
+ attribute :transport, :boolean, default: false
35
+
36
+ def transport?
37
+ transport
38
+ end
39
+
40
+ def summary
41
+ messages.compact_blank.join('; ').presence ||
42
+ I18n.t('spree.integrations.avalara.errors.address_unresolved')
43
+ end
44
+ end
45
+
46
+ # @param address [Spree::Address, nil]
47
+ # @param store [Spree::Store]
48
+ # @return [Result]
49
+ def call(address:, store:)
50
+ return Result.new if address.nil? || !supported?(address)
51
+
52
+ integration = Integration.active_for(store)
53
+ # Nothing connected to ask, so nothing to say about the address. Advisory
54
+ # validation never blocks on configuration.
55
+ return Result.new if integration.nil?
56
+
57
+ body = integration.client.resolve_address(AddressPresenter.new(address).call)
58
+ messages = error_messages(body)
59
+
60
+ return Result.new(body: body, error: Failure.new(messages: messages)) if messages.any?
61
+
62
+ Result.new(body: body)
63
+ rescue SpreeAvalara::RequestError => error
64
+ # Every raised failure is a missing judgement, not a bad address. A
65
+ # refusal Avalara actually made about the address arrives as `messages`
66
+ # in a successful response; a raise means the service was unreachable,
67
+ # degraded (5xx), or the credentials were rotated (401) — none of which
68
+ # says anything about where the customer lives, and all of which would
69
+ # otherwise block every checkout until somebody noticed.
70
+ Result.new(error: Failure.new(messages: [error.message], transport: true))
71
+ end
72
+
73
+ private
74
+
75
+ def supported?(address)
76
+ SUPPORTED_COUNTRIES.include?(address.country_code.to_s.upcase)
77
+ end
78
+
79
+ # Avalara reports what it could not resolve in `messages`, and only
80
+ # `Error`-severity entries mean the address is unusable — an
81
+ # informational note about a corrected street name is not a refusal.
82
+ def error_messages(body)
83
+ Array(body['messages']).filter_map do |message|
84
+ next unless message['severity'].to_s.casecmp?('error')
85
+
86
+ message['summary'].presence || message['details'].presence
87
+ end
88
+ end
89
+ end
90
+ end
91
+ end
@@ -0,0 +1,253 @@
1
+ module SpreeAvalara
2
+ # The only place this gem talks to AvaTax. Wraps Avalara's SDK client so
3
+ # callers deal in Spree vocabulary: a parsed body on success, a
4
+ # {SpreeAvalara::RequestError} on anything else.
5
+ #
6
+ # The legacy extension achieved the same by monkey-patching the SDK's request
7
+ # method. Nothing is patched here — error translation lives in this wrapper,
8
+ # which is also what makes the SDK upgradable.
9
+ class Client
10
+ # The SDK's constructor subscribes a listener to every Faraday notification
11
+ # and never removes it, so each client built (one per integration loaded)
12
+ # would stay in memory for the life of the process. This sets the same
13
+ # options without subscribing; the listener only logs, which is off anyway.
14
+ class SdkClient < ::AvaTax::Client
15
+ def initialize(options = {}) # rubocop:disable Lint/MissingSuper
16
+ options = ::AvaTax.options.merge(options)
17
+ ::AvaTax::Configuration::VALID_OPTIONS_KEYS.each { |key| send("#{key}=", options[key]) }
18
+ end
19
+ end
20
+
21
+ # Nothing was answered, so these become a statusless RequestError and the
22
+ # caller reports the engine as unavailable.
23
+ #
24
+ # Deliberately translated but never repeated here. Repeating means sleeping
25
+ # inside the request, which holds a thread — and the completion lock — while
26
+ # a customer waits, and a timeout has already spent the whole read budget
27
+ # before it even begins. Retrying belongs to the caller: the response says
28
+ # 503, and the SDK retries that with backoff of its own.
29
+ TRANSPORT_ERRORS = [Faraday::ConnectionFailed, Faraday::TimeoutError, Faraday::SSLError].freeze
30
+
31
+ # Fields of Avalara's answers that identify the merchant's account rather
32
+ # than the sale; the ping names the account number as the user name.
33
+ UNLOGGED_FIELDS = %w[authenticatedAccountId authenticatedUserId authenticatedUserName accountId
34
+ createdUserId modifiedUserId crmid].freeze
35
+
36
+ # Avalara's most per request. A broad word matches hundreds of codes
37
+ # ("clothing" matches over 200), and a smaller cap sorted by code cut off
38
+ # whole families, such as every business-to-consumer clothing code.
39
+ TAX_CODE_SEARCH_LIMIT = 1000
40
+
41
+ attr_reader :account_number, :license_key, :endpoint, :company_code, :logging
42
+
43
+ # @param account_number [String] AvaTax account number, sent as the username
44
+ # @param license_key [String] AvaTax license key, sent as the password
45
+ # @param endpoint [String] AvaTax host, sandbox or production
46
+ # @param company_code [String, nil] the company documents are filed against
47
+ # @param logging [Boolean] write every call to the Rails log
48
+ def initialize(account_number:, license_key:, endpoint:, company_code: nil, logging: false)
49
+ @account_number = account_number
50
+ @license_key = license_key
51
+ @endpoint = endpoint
52
+ @company_code = company_code
53
+ @logging = logging
54
+ end
55
+
56
+ # Whether these credentials authenticate, plus the account they belong to.
57
+ #
58
+ # @return [Hash]
59
+ def ping
60
+ request(:ping) { avatax_client.ping }
61
+ end
62
+
63
+ # @param model [Hash] a CreateTransactionModel
64
+ # @return [Hash] the created transaction
65
+ def create_transaction(model)
66
+ request(:create_transaction, model) { avatax_client.create_transaction(model) }
67
+ end
68
+
69
+ # Files a transaction, adjusting it in place when the document code has been
70
+ # filed before — which is what makes committing an order replayable.
71
+ #
72
+ # @param model [Hash] a CreateOrAdjustTransactionModel
73
+ # @return [Hash] the filed transaction
74
+ def create_or_adjust_transaction(model)
75
+ request(:create_or_adjust_transaction, model) { avatax_client.create_or_adjust_transaction(model) }
76
+ end
77
+
78
+ # @param transaction_code [String] the document code to void
79
+ # @param code [String] AvaTax's void reason
80
+ # @return [Hash] the voided transaction
81
+ def void_transaction(transaction_code, code: 'DocVoided')
82
+ model = { code: code }
83
+ request(:void_transaction, model.merge(transaction_code: transaction_code)) do
84
+ avatax_client.void_transaction(company_code, transaction_code, model)
85
+ end
86
+ end
87
+
88
+ # Whether the account holds a company with this code. A ping proves the
89
+ # credentials and nothing else, so a mistyped code would otherwise surface
90
+ # only at the first checkout.
91
+ #
92
+ # @param code [String]
93
+ # @return [Boolean]
94
+ def company_exists?(code)
95
+ options = { '$filter' => "companyCode eq #{odata_literal(code)}", '$top' => 1 }
96
+ body = request(:query_companies, options) { avatax_client.query_companies(options) }
97
+
98
+ Array(body['value']).any?
99
+ end
100
+
101
+ # Avalara's active tax codes whose code or description contains the query.
102
+ #
103
+ # @param query [String]
104
+ # @return [Array<Hash>] Avalara's tax code records
105
+ def list_tax_codes(query)
106
+ term = odata_literal(query)
107
+ options = {
108
+ '$filter' => "(taxCode contains #{term} OR description contains #{term}) AND isActive eq true",
109
+ '$top' => TAX_CODE_SEARCH_LIMIT,
110
+ '$orderBy' => 'taxCode ASC'
111
+ }
112
+
113
+ Array(request(:list_tax_codes, options) { avatax_client.list_tax_codes(options) }['value'])
114
+ end
115
+
116
+ # @param params [Hash] address parts (line1, city, region, postalCode, country)
117
+ # @return [Hash] the resolved address with Avalara's messages
118
+ def resolve_address(params)
119
+ request(:resolve_address, params) { avatax_client.resolve_address(params) }
120
+ end
121
+
122
+ # Whether a refusal means the document is already filed. Commit is
123
+ # replayable — a crash between the order commit and the cart stamp leaves
124
+ # completion to re-run — so filing the same code twice has to count as
125
+ # success rather than raise.
126
+ #
127
+ # @param error [SpreeAvalara::RequestError]
128
+ # @return [Boolean]
129
+ def duplicate_document_error?(error)
130
+ # The two names remain unconfirmed — no recording has produced them.
131
+ return true if error_code(error).in?(%w[DocumentAlreadyExists DuplicateDocumentException])
132
+
133
+ # What a replay actually answers: a committed document with this code cannot
134
+ # be recreated or adjusted, so AvaTax refuses with GetTaxError / DocStatusError
135
+ # ("Expected Saved|Posted") rather than naming a duplicate. The document
136
+ # is filed, which is the state the caller wanted.
137
+ fault_sub_codes(error).include?('DocStatusError')
138
+ end
139
+
140
+ # Whether a refusal means there is nothing left to void: already voided, or
141
+ # never filed at all. Both leave the ledger where the caller wanted it.
142
+ #
143
+ # @param error [SpreeAvalara::RequestError]
144
+ # @return [Boolean]
145
+ def already_voided_error?(error)
146
+ # TransactionAlreadyCancelled is what AvaTax actually answers, confirmed
147
+ # against a recorded cassette: "The transaction ... is already in a
148
+ # 'Cancelled' status. There is nothing to be done." EntityNotFoundError
149
+ # covers a document that was never filed, which leaves the ledger where
150
+ # the caller wanted it just the same.
151
+ error_code(error).in?(%w[TransactionAlreadyCancelled EntityNotFoundError])
152
+ end
153
+
154
+ private
155
+
156
+ def error_code(error)
157
+ details = error.try(:details)
158
+
159
+ details.is_a?(Hash) ? details['code'].to_s : ''
160
+ end
161
+
162
+ def fault_sub_codes(error)
163
+ details = error.try(:details)
164
+ return [] unless details.is_a?(Hash)
165
+
166
+ Array(details['details']).filter_map { |entry| entry['faultSubCode'] if entry.is_a?(Hash) }
167
+ end
168
+
169
+ # Every option the SDK reads is passed explicitly: its initializer merges the
170
+ # process-wide `AvaTax.options` underneath, so an unset option silently
171
+ # inherits whatever a host app configured globally.
172
+ def avatax_client
173
+ @avatax_client ||= SdkClient.new(
174
+ username: account_number,
175
+ password: license_key,
176
+ endpoint: endpoint,
177
+ app_name: SpreeAvalara::APP_NAME,
178
+ app_version: SpreeAvalara::APP_VERSION,
179
+ machine_name: nil,
180
+ # Replaces the SDK's own 20-minute request timeout: an estimate runs
181
+ # inside the cart's transaction, so waiting that long holds a lock.
182
+ connection_options: ::AvaTax::Configuration::DEFAULT_CONNECTION_OPTIONS.merge(
183
+ request: { open_timeout: SpreeAvalara.open_timeout, timeout: SpreeAvalara.read_timeout }
184
+ ),
185
+ # The status is needed to tell a duplicate document from a rejection, and
186
+ # the SDK hands it over only with the whole response.
187
+ faraday_response: true,
188
+ logger: false,
189
+ custom_logger: nil,
190
+ proxy: nil,
191
+ response_big_decimal_conversion: false
192
+ )
193
+ end
194
+
195
+ def request(operation, payload = nil)
196
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
197
+
198
+ begin
199
+ response = yield
200
+ rescue *TRANSPORT_ERRORS => error
201
+ log_call(operation, payload, started, outcome: error.class.name)
202
+ # No status: nothing was answered, so the failure is the network rather
203
+ # than a decision by Avalara.
204
+ raise RequestError.new(error.message, status: nil, details: nil)
205
+ end
206
+
207
+ log_call(operation, payload, started, outcome: response.status, response: response.body)
208
+ interpret(response)
209
+ end
210
+
211
+ # One line per call, for a merchant tracing what was sent and what came back.
212
+ # Bodies only, since the credentials travel in the Authorization header, and
213
+ # with the account's own identifiers taken out of the answers.
214
+ def log_call(operation, payload, started, outcome:, response: nil)
215
+ return unless logging
216
+
217
+ duration = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round
218
+ Rails.logger.info(
219
+ "[AVATAX] #{operation} #{outcome} #{duration}ms request=#{payload.to_json} response=#{without_account(response).to_json}"
220
+ )
221
+ end
222
+
223
+ def without_account(body)
224
+ @account_filter ||= ActiveSupport::ParameterFilter.new(UNLOGGED_FIELDS.map { |field| /\A#{field}\z/ })
225
+ body.is_a?(Hash) ? @account_filter.filter(body) : body
226
+ end
227
+
228
+ # OData quotes a literal with single quotes and escapes one inside it by
229
+ # doubling it.
230
+ def odata_literal(value)
231
+ "'#{value.to_s.gsub("'", "''")}'"
232
+ end
233
+
234
+ # AvaTax reports refusals two ways — an HTTP status and an `error` object in
235
+ # an otherwise successful body — and both mean the call did not do what was
236
+ # asked.
237
+ def interpret(response)
238
+ status = response.status
239
+ body = response.body
240
+ details = body.is_a?(Hash) ? body['error'] : nil
241
+
242
+ return body if status.to_i.between?(200, 299) && details.blank?
243
+
244
+ raise RequestError.new(failure_message(status, details), status: status, details: details)
245
+ end
246
+
247
+ def failure_message(status, details)
248
+ details_message = details.is_a?(Hash) ? details['message'].presence : nil
249
+
250
+ details_message || "AvaTax request failed with status #{status}"
251
+ end
252
+ end
253
+ end
@@ -0,0 +1,83 @@
1
+ module SpreeAvalara
2
+ # The fingerprint of an estimate request. Avalara prices a whole document per
3
+ # call while Spree re-estimates per item change, so several call sites in one
4
+ # request would otherwise each pay a round trip inside the cart's own
5
+ # transaction.
6
+ #
7
+ # Everything that can change the answer belongs in the key, including whether
8
+ # the prices include tax: a market change that flips it has to bust the key
9
+ # instead of serving a calculation stated the wrong way round.
10
+ class EstimateCacheKey
11
+ EXPIRES_IN = 5.minutes
12
+
13
+ # @param owner [Spree::Cart, Spree::Order]
14
+ # @param items [Array<Spree::LineItem, Spree::Fulfillment, Spree::Fee>]
15
+ # @param integration [SpreeAvalara::Integration]
16
+ # @param tax_identifier [Spree::TaxIdentifier, nil]
17
+ # @param exemptions [Array<Spree::TaxExemption>]
18
+ # @param tax_inclusive [Boolean]
19
+ def initialize(owner:, items:, integration:, tax_identifier: nil, exemptions: [], tax_inclusive: false)
20
+ @owner = owner
21
+ @items = items
22
+ @integration = integration
23
+ @tax_identifier = tax_identifier
24
+ @exemptions = exemptions
25
+ @tax_inclusive = tax_inclusive
26
+ end
27
+
28
+ # @return [String]
29
+ def key
30
+ [
31
+ 'spree_avalara/estimate',
32
+ owner.class.name.demodulize.downcase,
33
+ owner.id,
34
+ Digest::SHA256.hexdigest(fingerprint.to_json)
35
+ ].join('/')
36
+ end
37
+
38
+ private
39
+
40
+ attr_reader :owner, :items, :integration, :tax_identifier, :exemptions, :tax_inclusive
41
+
42
+ def fingerprint
43
+ {
44
+ integration: [integration.id, integration.updated_at.to_i, integration.preferred_company_code],
45
+ tax_address: tax_address,
46
+ market: owner.market&.id,
47
+ # Avalara applies the certificates it holds for this code, so a guest
48
+ # signing in on the same cart can change the answer.
49
+ customer: SpreeAvalara.customer_code(owner),
50
+ tax_included: tax_inclusive,
51
+ currency: owner.currency,
52
+ identifier: tax_identifier && [tax_identifier.kind, tax_identifier.value],
53
+ exemptions: exemptions.map(&:to_snapshot),
54
+ items: items.map { |item| item_fingerprint(item) }
55
+ }
56
+ end
57
+
58
+ def tax_address
59
+ address = owner.tax_address
60
+ return if address.nil?
61
+
62
+ [address.address1, address.address2, address.city, address.state_code,
63
+ address.country_code, address.zipcode]
64
+ end
65
+
66
+ # The tax code and origin are keyed as sent rather than by record id: editing
67
+ # a category's code or a location's address in place keeps the id.
68
+ def item_fingerprint(item)
69
+ [
70
+ item.prefixed_id,
71
+ item.respond_to?(:quantity) ? item.quantity : 1,
72
+ (item.respond_to?(:taxable_basis) ? item.taxable_basis : item.amount).to_s,
73
+ ItemPresenter.new(item: item, owner: owner, tax_included: tax_inclusive).tax_code,
74
+ origin(item)
75
+ ]
76
+ end
77
+
78
+ def origin(item)
79
+ location = SpreeAvalara.origin_location(owner, item: item)
80
+ location && [location.id, AddressPresenter.new(location).call]
81
+ end
82
+ end
83
+ end
@@ -0,0 +1,32 @@
1
+ module SpreeAvalara
2
+ # Refuses to complete a checkout whose tax address Avalara cannot resolve.
3
+ #
4
+ # Registered on `carts.complete.validate` rather than
5
+ # `Spree.validators.addresses`: that registry fires on every address save —
6
+ # the customer's address book, an admin editing a record — with no checkout
7
+ # context, so a validation belonging to one sale would block a merchant from
8
+ # saving a legitimate address.
9
+ class ValidateCheckoutAddress
10
+ # @param workflow [Spree::Carts::Complete]
11
+ # @return [void]
12
+ def call(workflow)
13
+ cart = workflow.cart
14
+ integration = Integration.active_for(cart&.store)
15
+ return unless integration&.preferred_address_validation_enabled
16
+
17
+ address = cart.tax_address
18
+ return if address.nil?
19
+ return unless Address::Validate::SUPPORTED_COUNTRIES.include?(address.country_code.to_s.upcase)
20
+
21
+ result = Address::Validate.new.call(address: address, store: cart.store)
22
+ return if result.success?
23
+ # Advisory validation must not import Avalara's downtime into checkout.
24
+ # Only estimate fails closed, because under-collecting tax is a liability
25
+ # while an unverified address is a delivery risk the merchant already runs.
26
+ return if result.error.transport?
27
+
28
+ workflow.errors.add(:base, :avalara_address_invalid, message: result.error.summary)
29
+ workflow.reject!
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,11 @@
1
+ ---
2
+ en:
3
+ spree:
4
+ integrations:
5
+ avalara:
6
+ description: Calculate sales tax, VAT and GST at checkout through your Avalara AvaTax account, and file every order against the same transaction.
7
+ errors:
8
+ address_unresolved: Avalara could not verify this address
9
+ company_not_found: Company code %{company_code} was not found in this Avalara account
10
+ connection_failed: Could not connect to AvaTax
11
+ invalid_credentials: Invalid credentials
@@ -0,0 +1,19 @@
1
+ require 'rails/engine'
2
+
3
+ module SpreeAvalara
4
+ class Engine < Rails::Engine
5
+ engine_name 'spree_avalara'
6
+
7
+ config.generators do |g|
8
+ g.test_framework :rspec
9
+ end
10
+
11
+ # Core assigns the registries in its own after_initialize, so appending has
12
+ # to happen in a later one — engine callbacks run in load order.
13
+ config.after_initialize do
14
+ Spree.integrations << 'SpreeAvalara::Integration' unless Spree.integrations.include?('SpreeAvalara::Integration')
15
+ Spree.tax_providers << SpreeAvalara::TaxProvider unless Spree.tax_providers.include?(SpreeAvalara::TaxProvider)
16
+ Spree.hooks.register('carts.complete.validate', 'SpreeAvalara::ValidateCheckoutAddress')
17
+ end
18
+ end
19
+ end
@@ -0,0 +1 @@
1
+ Dir["#{File.dirname(__FILE__)}/testing_support/factories/**/*.rb"].sort.each { |f| load File.expand_path(f) }
@@ -0,0 +1,29 @@
1
+ FactoryBot.define do
2
+ factory :avalara_integration, class: 'SpreeAvalara::Integration' do
3
+ store { Spree::Store.default || create(:store) }
4
+ # Inactive by default: activating verifies the connection, and an example
5
+ # that only needs credentials on file should not reach for the network.
6
+ active { false }
7
+
8
+ preferred_account_number { ENV.fetch('AVATAX_ACCOUNT_NUMBER', '2000000000') }
9
+ preferred_license_key { ENV.fetch('AVATAX_LICENSE_KEY', 'test_license_key') }
10
+ # Not ENV-driven like the credentials: the model now allows only Avalara's
11
+ # two published hosts, so an override could only ever build an invalid
12
+ # record. Cassettes are recorded against the sandbox.
13
+ preferred_endpoint { SpreeAvalara::Integration::SANDBOX_ENDPOINT }
14
+ preferred_company_code { ENV.fetch('AVATAX_COMPANY_CODE', 'DEFAULT') }
15
+ preferred_document_recording { 'commit' }
16
+ preferred_address_validation_enabled { false }
17
+ preferred_show_rate_in_label { false }
18
+
19
+ # An integration a store can actually calculate through, without a cassette
20
+ # or a stub in every example that wants one.
21
+ trait :active do
22
+ active { true }
23
+
24
+ after(:build) do |integration|
25
+ integration.define_singleton_method(:can_connect?) { true }
26
+ end
27
+ end
28
+ end
29
+ end