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,306 @@
1
+ module SpreeAvalara
2
+ # One line of an AvaTax transaction response, translated into the vocabulary
3
+ # {Spree::TaxLine} stores. Named `TransactionLine` rather than `TaxLine` so a
4
+ # bare `TaxLine` inside this gem still resolves to core's model.
5
+ #
6
+ # Avalara answers per line, and Spree writes one row per line, so the
7
+ # jurisdiction breakdown collapses into a summed rate and a label — the whole
8
+ # breakdown rides along in `data` for anyone who needs to re-derive it.
9
+ class TransactionLine
10
+ include ActiveModel::Model
11
+ include ActiveModel::Attributes
12
+
13
+ # The member states, as ISO alpha-2 — which is what an address carries.
14
+ # Deliberately not the upgrade task's `EU_VAT_PREFIXES`: that list is VAT
15
+ # prefixes, where Greece is `EL` and Northern Ireland has an `XI` of its own,
16
+ # and neither is a country code. Great Britain is absent by virtue of Brexit,
17
+ # so a sale there reads as an export.
18
+ EU_COUNTRY_CODES = %w[AT BE BG CY CZ DE DK EE ES FI FR GR HR HU IE IT LT LU
19
+ LV MT NL PL PT RO SE SI SK].freeze
20
+
21
+ # Avalara says "absent" with an empty string or a zero, never a null, so
22
+ # every predicate below tests presence rather than nil-ness.
23
+ attribute :payload, default: -> { {} }
24
+
25
+ # What the request said, for the treatments Avalara reports but does not
26
+ # explain: whether a buyer registration was sent, whether an exemption was
27
+ # claimed, and the two countries the supply moved between.
28
+ attribute :context, default: -> { {} }
29
+
30
+ class << self
31
+ # @param body [Hash] a create/adjust transaction response
32
+ # @param context [Hash] request-side facts (see the +context+ attribute)
33
+ # @return [Array<SpreeAvalara::TransactionLine>]
34
+ def from_response(body, context: {})
35
+ Array(body['lines']).map { |line| new(payload: line, context: context) }
36
+ end
37
+ end
38
+
39
+ # @return [String, nil] the prefixed id this line was sent as
40
+ def line_number
41
+ payload['lineNumber'].presence
42
+ end
43
+
44
+ # The item this line priced. An unmatched lineNumber is a protocol
45
+ # violation, not a row to drop: Avalara answered about something we did not
46
+ # ask about, and silently ignoring it would leave an item untaxed.
47
+ #
48
+ # @param items [Array<Spree::LineItem, Spree::Fulfillment, Spree::Fee, Spree::ExchangeLineItem>]
49
+ # @return [Spree::LineItem, Spree::Fulfillment, Spree::Fee, Spree::ExchangeLineItem]
50
+ # @raise [SpreeAvalara::Error] when no item carries that prefixed id
51
+ def matching_item(items)
52
+ item = items.find { |candidate| candidate.prefixed_id.to_s == line_number.to_s }
53
+ return item if item
54
+
55
+ raise SpreeAvalara::Error, "AvaTax returned line #{line_number.inspect}, which was never sent"
56
+ end
57
+
58
+ # @param item [Spree::LineItem, Spree::Fulfillment, Spree::Fee]
59
+ # @param owner [Spree::Cart, Spree::Order]
60
+ # @return [Hash] attributes for Spree::TaxLine.create!
61
+ def to_tax_line_attributes(item:, owner:)
62
+ {
63
+ owner_key(owner) => owner,
64
+ foreign_key(item) => item.id,
65
+ tax_rate_id: nil,
66
+ amount: amount,
67
+ rate: rate,
68
+ label: label,
69
+ included: included?,
70
+ provider_id: SpreeAvalara::PROVIDER_ID,
71
+ taxability_reason: taxability_reason(item),
72
+ country_code: country_code,
73
+ state_code: state_code,
74
+ data: { 'avalara' => avalara_data }
75
+ }
76
+ end
77
+
78
+ # @return [BigDecimal] tax Avalara computed for this line
79
+ def amount
80
+ payload['taxCalculated'].to_d
81
+ end
82
+
83
+ # The jurisdictions' rates summed, since one row stands for all of them.
84
+ #
85
+ # @return [BigDecimal]
86
+ def rate
87
+ details.sum { |detail| detail['rate'].to_d }.round(6)
88
+ end
89
+
90
+ def included?
91
+ payload['taxIncluded'] == true
92
+ end
93
+
94
+ # The distinct tax names Avalara applied. A US line can carry state, county
95
+ # and city taxes; naming them all beats a generic label, and the full
96
+ # breakdown is in `data` either way.
97
+ #
98
+ # @return [String]
99
+ def label
100
+ names = details.filter_map { |detail| detail['taxName'].presence }.uniq
101
+ return 'Tax' if names.empty?
102
+
103
+ names.join(', ').truncate(255)
104
+ end
105
+
106
+ # Where the tax was levied, read off the jurisdiction that levied it and
107
+ # falling back to where the request said the goods went.
108
+ def country_code
109
+ details.first&.dig('country').presence || context[:ship_to_country]
110
+ end
111
+
112
+ # Only a region that genuinely is a subdivision of the country. For a tax
113
+ # levied at country level Avalara repeats the country in `region` — a German
114
+ # sale comes back `country: "DE", region: "DE"` — which core's geography
115
+ # validation rejects, and the whole estimate would fail with it. Resolving
116
+ # through core's own ISO data both filters and canonicalises.
117
+ def state_code
118
+ region = details.first&.dig('region').presence
119
+ return if region.nil? || country_code.blank?
120
+
121
+ Spree::IsoData.subdivision_code(country_code, region)
122
+ end
123
+
124
+ # The treatment, folded from Avalara's own reason fields. First match wins,
125
+ # and the order matters: a line with no nexus also reports
126
+ # `isItemTaxable: false`, so the product-exemption test has to be narrower
127
+ # than that flag.
128
+ #
129
+ # @param item [Spree::LineItem, Spree::Fulfillment, Spree::Fee]
130
+ # @return [String] one of Spree::TaxLine.taxability_reasons
131
+ def taxability_reason(item)
132
+ return 'customer_exempt' if customer_exempt?
133
+ return 'intra_community_supply' if intra_community_supply?(item)
134
+ return 'reverse_charge' if reverse_charge?(item)
135
+ return 'export' if export?
136
+ return 'product_exempt' if product_exempt?
137
+ return 'not_collecting' if not_collecting?
138
+ return 'not_subject_to_tax' if not_subject_to_tax?
139
+ return 'reduced_rated' if reduced_rated?
140
+ return 'standard_rated' if rate.positive? || amount.positive?
141
+
142
+ 'zero_rated'
143
+ end
144
+
145
+ private
146
+
147
+ def details
148
+ Array(payload['details'])
149
+ end
150
+
151
+ def line_amount
152
+ payload['lineAmount'].to_d
153
+ end
154
+
155
+ def exempt_amount
156
+ payload['exemptAmount'].to_d
157
+ end
158
+
159
+ # A certificate has to exist for *this line* to claim one. `exemptAmount`
160
+ # alone says nothing — a sale into a state with no nexus reports the whole
161
+ # line exempt — and neither does an order-wide "we sent something", because
162
+ # a claim may cover some lines and not others.
163
+ #
164
+ # Avalara echoes back the code it applied, so the line is its own evidence.
165
+ # Where it echoes nothing the row falls through to a zero-tax reason, which
166
+ # under-claims rather than naming a certificate that does not exist.
167
+ def customer_exempt?
168
+ return false unless exempt_amount.positive?
169
+
170
+ payload['exemptCertId'].to_i.positive? ||
171
+ payload['exemptNo'].to_s.present? ||
172
+ payload['entityUseCode'].to_s.present?
173
+ end
174
+
175
+ # Avalara reports the zero rate but not why it is zero, so the EU split
176
+ # comes from what the request described: a registered buyer, goods crossing
177
+ # an internal border.
178
+ def intra_community_supply?(item)
179
+ zero_vat? && context[:identifier_sent] == true && goods?(item) && intra_eu?
180
+ end
181
+
182
+ # A cross-border supply to a registered buyer that is not goods: the service
183
+ # case the EU reverse-charges. Deliberately narrow rather than "whatever
184
+ # intra-community supply did not claim" — a domestic zero-rated sale (books,
185
+ # food) to a customer who happens to hold a registration is zero_rated, and
186
+ # calling it reverse charge files it under the wrong e-invoice category.
187
+ #
188
+ # Domestic reverse charge (construction and the like) is indistinguishable
189
+ # from zero-rating in the payload, so it reads zero_rated until a cassette
190
+ # shows a marker that separates them.
191
+ def reverse_charge?(item)
192
+ zero_vat? && context[:identifier_sent] == true && intra_eu? && !goods?(item)
193
+ end
194
+
195
+ def zero_vat?
196
+ return false unless rate.zero?
197
+
198
+ details.any? { |detail| detail['rateTypeCode'].to_s == 'Z' } || payload['vatCode'].to_s.present?
199
+ end
200
+
201
+ def goods?(item)
202
+ item.is_a?(Spree::Fee) ? false : true
203
+ end
204
+
205
+ def cross_border?
206
+ from = ship_from_country.to_s
207
+ to = context[:ship_to_country].to_s
208
+
209
+ from.present? && to.present? && from != to
210
+ end
211
+
212
+ # Intra-community supply and reverse charge are EU constructs: they describe
213
+ # a supply crossing an *internal* border, between two member states. A
214
+ # zero-rated business sale out of the union — Poland to the United States,
215
+ # or to Great Britain since Brexit — is an export, and these reasons are
216
+ # e-invoice categories rather than labels, so filing one as the other is
217
+ # wrong in the place the distinction is read.
218
+ def intra_eu?
219
+ EU_COUNTRY_CODES.include?(ship_from_country.to_s.upcase) &&
220
+ EU_COUNTRY_CODES.include?(context[:ship_to_country].to_s.upcase) &&
221
+ cross_border?
222
+ end
223
+
224
+ # This line's own origin, since the request sent one per line. Falls back to
225
+ # the owner's origin for a line the caller did not map.
226
+ def ship_from_country
227
+ per_line = context[:ship_from_countries]
228
+ return context[:ship_from_country] unless per_line.is_a?(Hash)
229
+
230
+ per_line.fetch(line_number.to_s) { context[:ship_from_country] }
231
+ end
232
+
233
+ def export?
234
+ details.any? { |detail| detail['nonTaxableType'].to_s == 'Export' }
235
+ end
236
+
237
+ # Tax applies in this jurisdiction — the rate is real — but not to this
238
+ # line. That is a product rule, distinct from not being registered at all.
239
+ def product_exempt?
240
+ details.any? do |detail|
241
+ detail['taxType'].to_s == 'Sales' &&
242
+ detail['rate'].to_d.positive? &&
243
+ detail['nonTaxableAmount'].to_d == line_amount &&
244
+ line_amount.positive?
245
+ end
246
+ end
247
+
248
+ # `Use` is how Avalara says the seller is not registered to collect here, so
249
+ # whatever is owed is the buyer's use tax. The zeros are load-bearing:
250
+ # several states call what a *registered* out-of-state seller collects
251
+ # "seller's use tax", and that line is collected tax, not an absence of it.
252
+ def not_collecting?
253
+ return true if details.empty?
254
+ return true if details.any? { |detail| detail['nonTaxableType'].to_s == 'NexusRule' }
255
+
256
+ details.any? do |detail|
257
+ detail['taxType'].to_s == 'Use' && detail['rate'].to_d.zero? && detail['taxCalculated'].to_d.zero?
258
+ end
259
+ end
260
+
261
+ # The jurisdiction levies no such tax at all, which is a different statement
262
+ # from "zero-rated under this regime".
263
+ def not_subject_to_tax?
264
+ details.present? &&
265
+ details.all? { |detail| detail['rate'].to_d.zero? } &&
266
+ details.any? { |detail| detail['nonTaxableType'].to_s == 'RateRule' }
267
+ end
268
+
269
+ def reduced_rated?
270
+ rate.positive? && details.any? { |detail| detail['rateTypeCode'].to_s == 'R' }
271
+ end
272
+
273
+ def owner_key(owner)
274
+ owner.is_a?(Spree::Order) ? :order : :cart
275
+ end
276
+
277
+ def foreign_key(item)
278
+ case item
279
+ when Spree::LineItem then :line_item_id
280
+ when Spree::Fulfillment then :fulfillment_id
281
+ when Spree::Fee then :fee_id
282
+ when Spree::ExchangeLineItem then :exchange_line_item_id
283
+ else raise SpreeAvalara::Error, "#{item.class} is not taxable"
284
+ end
285
+ end
286
+
287
+ # Everything needed to explain or re-derive the row later, without keeping
288
+ # the whole response.
289
+ def avalara_data
290
+ {
291
+ 'details' => details,
292
+ 'exemptAmount' => payload['exemptAmount'],
293
+ 'exemptCertId' => payload['exemptCertId'],
294
+ 'exemptNo' => payload['exemptNo'],
295
+ 'entityUseCode' => payload['entityUseCode'],
296
+ 'isItemTaxable' => payload['isItemTaxable'],
297
+ 'taxCode' => payload['taxCode'],
298
+ 'vatCode' => payload['vatCode'],
299
+ # An exemption reason core does not share with Avalara is sent as
300
+ # OTHER/CUSTOM, so the reason the merchant actually recorded is kept here
301
+ # rather than lost to the translation.
302
+ 'sent_exemption_reasons' => context[:exemption_reasons].presence
303
+ }.compact
304
+ end
305
+ end
306
+ end
@@ -0,0 +1,28 @@
1
+ module SpreeAvalara
2
+ # An address or stock location as AvaTax's AddressLocationInfo. Both sides of
3
+ # a supply present the same way, and both records answer the same readers.
4
+ class AddressPresenter
5
+ # @param source [Spree::Address, Spree::StockLocation, nil]
6
+ def initialize(source)
7
+ @source = source
8
+ end
9
+
10
+ # @return [Hash, nil] nil when there is no address to describe
11
+ def call
12
+ return if source.nil?
13
+
14
+ {
15
+ line1: source.address1,
16
+ line2: source.address2,
17
+ city: source.city,
18
+ region: source.state_code,
19
+ country: source.country_code,
20
+ postalCode: source.zipcode
21
+ }.compact_blank
22
+ end
23
+
24
+ private
25
+
26
+ attr_reader :source
27
+ end
28
+ end
@@ -0,0 +1,191 @@
1
+ module SpreeAvalara
2
+ # One taxable item as AvaTax's LineItemModel.
3
+ class ItemPresenter
4
+ # Avalara's generic tangible-goods code, and its freight code. Used when the
5
+ # merchant has classified neither the item nor a default category, which is
6
+ # parity with the Internal engine taxing category-less items by default.
7
+ DEFAULT_TAX_CODE = 'P0000000'.freeze
8
+ FREIGHT_TAX_CODE = 'FR'.freeze
9
+
10
+ # Avalara's own field limits. A line longer than these is refused outright,
11
+ # so both are cut rather than sent whole.
12
+ DESCRIPTION_LIMIT = 256
13
+ ITEM_CODE_LIMIT = 50
14
+
15
+ # @param item [Spree::LineItem, Spree::Fulfillment, Spree::Fee, Spree::ExchangeLineItem]
16
+ # @param owner [Spree::Cart, Spree::Order]
17
+ # @param tax_included [Boolean] whether the sale's prices include tax
18
+ # @param exemptions [Array<Spree::TaxExemption>] entries to place on this
19
+ # line; empty when the claim was placed on the document instead
20
+ def initialize(item:, owner:, tax_included:, exemptions: [])
21
+ @item = item
22
+ @owner = owner
23
+ @tax_included = tax_included
24
+ @exemptions = exemptions
25
+ end
26
+
27
+ # @return [Hash]
28
+ def call
29
+ payload = {
30
+ number: item.prefixed_id,
31
+ quantity: quantity,
32
+ amount: amount,
33
+ taxIncluded: tax_included,
34
+ # 6.0 distributes order-level promotions into the taxable basis, so the
35
+ # line arrives already discounted. Telling Avalara to discount it again
36
+ # would take the reduction twice.
37
+ discounted: false,
38
+ discount: 0
39
+ }
40
+
41
+ payload[:description] = description if description.present?
42
+ payload[:itemCode] = item_code if item_code.present?
43
+ payload[:taxCode] = tax_code if tax_code.present?
44
+ addresses = line_addresses
45
+ payload[:addresses] = addresses if addresses
46
+ payload.merge!(exemption_payload)
47
+ payload
48
+ end
49
+
50
+ # Public so the estimate cache key can be built from the same resolution.
51
+ #
52
+ # @return [String, nil]
53
+ def tax_code
54
+ case item
55
+ when Spree::LineItem then item.tax_category&.tax_code.presence || default_tax_code || DEFAULT_TAX_CODE
56
+ when Spree::ExchangeLineItem
57
+ item.new_variant&.tax_category&.tax_code.presence || default_tax_code || DEFAULT_TAX_CODE
58
+ when Spree::Fulfillment then delivery_tax_code.presence || FREIGHT_TAX_CODE
59
+ else default_tax_code
60
+ end
61
+ end
62
+
63
+ private
64
+
65
+ attr_reader :item, :owner, :tax_included, :exemptions
66
+
67
+ # The first entry claiming both this line and the jurisdiction being taxed.
68
+ # Multiple certificates mean multiple entries, and one claim is enough —
69
+ # the same rule Internal applies.
70
+ def exemption_payload
71
+ entry = exemptions.find do |exemption|
72
+ exemption.covers_item?(exemption_subject) &&
73
+ exemption.covers_jurisdiction?(destination_country, destination_state)
74
+ end
75
+ return {} if entry.nil?
76
+
77
+ code = EntityUseCodes.for(entry.reason_code_for(exemption_subject))
78
+ payload = code ? { entityUseCode: code } : {}
79
+ # `exemptionCode` on a line, `exemptionNo` on the document. Strictly one
80
+ # each — all four combinations checked against the sandbox, and each name
81
+ # is ignored at the level it does not belong to:
82
+ #
83
+ # document exemptionNo -> certificate recorded
84
+ # document exemptionCode -> ignored
85
+ # line exemptionCode -> certificate recorded
86
+ # line exemptionNo -> ignored
87
+ #
88
+ # Ignored means silently: the sale is still exempt, because entityUseCode
89
+ # does that work on its own, so a wrong name here loses the certificate
90
+ # reference from the filing without anything failing.
91
+ payload[:exemptionCode] = entry.certificate_number if entry.certificate_number.present?
92
+ payload
93
+ end
94
+
95
+ # An exchange's replacement is claimed as the line it replaces was: a
96
+ # certificate's per-line carve-out names the sold line, and the
97
+ # replacement would otherwise match no carve-out and come out exempt.
98
+ def exemption_subject
99
+ item.is_a?(Spree::ExchangeLineItem) ? item.line_item || item : item
100
+ end
101
+
102
+ def destination_country
103
+ owner.tax_address&.country_code
104
+ end
105
+
106
+ def destination_state
107
+ owner.tax_address&.state_code
108
+ end
109
+
110
+ # An exchange line announces one quantity and may receive fewer; only
111
+ # what is credited ships a replacement.
112
+ def quantity
113
+ return item.credited_quantity if item.is_a?(Spree::ExchangeLineItem)
114
+
115
+ item.respond_to?(:quantity) ? item.quantity : 1
116
+ end
117
+
118
+ def amount
119
+ item.respond_to?(:taxable_basis) ? item.taxable_basis : item.amount
120
+ end
121
+
122
+ # What a merchant reads when they open the transaction in Avalara. Without
123
+ # it every line is an opaque prefixed id, so a filed document cannot be
124
+ # checked against the sale it came from — which is the whole reason for
125
+ # looking at one. Avalara echoes both fields back and neither changes what
126
+ # is taxed: the line's own taxCode still governs, confirmed against the
127
+ # sandbox by pricing the same line with and without an item code, including
128
+ # one coded non-taxable.
129
+ def description
130
+ text = case item
131
+ when Spree::LineItem then item.name
132
+ when Spree::ExchangeLineItem then item.new_variant&.name
133
+ when Spree::Fulfillment then delivery_description
134
+ when Spree::Fee then item.label.presence || item.kind
135
+ end
136
+
137
+ text.to_s.truncate(DESCRIPTION_LIMIT).presence
138
+ end
139
+
140
+ def delivery_description
141
+ name = item.selected_delivery_rate&.name.presence ||
142
+ item.selected_delivery_rate&.delivery_method&.name.presence
143
+ name ? "Delivery: #{name}" : 'Delivery'
144
+ end
145
+
146
+ # Only where the merchant has a real identifier for the thing sold. Avalara
147
+ # reads an item code against the company's own item catalogue, so inventing
148
+ # one for a fulfillment or a fee would put a value into that namespace that
149
+ # the merchant never assigned.
150
+ def item_code
151
+ variant = case item
152
+ when Spree::LineItem then item.variant
153
+ when Spree::ExchangeLineItem then item.new_variant
154
+ end
155
+
156
+ variant&.sku.presence&.first(ITEM_CODE_LIMIT)
157
+ end
158
+
159
+ # A fulfillment carries no tax category of its own — the delivery method it
160
+ # was rated with does.
161
+ def delivery_tax_code
162
+ item.selected_delivery_rate&.delivery_method&.tax_category&.tax_code
163
+ end
164
+
165
+ def default_tax_code
166
+ Spree::TaxCategory.default(owner.store)&.tax_code
167
+ end
168
+
169
+ # Both ends of the supply, or neither.
170
+ #
171
+ # A line-level block naming only a shipFrom makes AvaTax source the line
172
+ # *to* that origin: a California warehouse shipping to Montana came back
173
+ # taxed at 7.25% California sales tax instead of Montana's nothing, so every
174
+ # customer was charged the warehouse's state rather than their own. Verified
175
+ # against the sandbox — shipFrom alone re-sources, shipFrom with shipTo does
176
+ # not.
177
+ #
178
+ # The origin is per line, because an order can ship from several warehouses;
179
+ # the destination is the owner's, and identical on every line.
180
+ #
181
+ # Avalara expects the bill-to address beside them once lines carry their
182
+ # own addresses, so it repeats the document's.
183
+ def line_addresses
184
+ origin = AddressPresenter.new(SpreeAvalara.origin_location(owner, item: item)).call
185
+ destination = AddressPresenter.new(owner.tax_address).call
186
+ return if origin.blank? || destination.blank?
187
+
188
+ { shipFrom: origin, shipTo: destination, billTo: AddressPresenter.new(owner.bill_address).call }.compact
189
+ end
190
+ end
191
+ end
@@ -0,0 +1,167 @@
1
+ module SpreeAvalara
2
+ # The tax a return, claim or exchange gave back, as AvaTax's ReturnInvoice:
3
+ # each credited line at a negative amount, keyed to the record so filing it
4
+ # twice adjusts one document.
5
+ #
6
+ # The tax on each line is not Avalara's to work out again. Core has already
7
+ # written it as the line's credit rows, from what the sale charged, and
8
+ # refunded the customer exactly that (see Spree::TaxProvider::Base#refund).
9
+ # So every line carries it as a tax-amount override: re-quoting the credit
10
+ # against the list price, or against rates that have moved since, filed a
11
+ # figure the customer was never repaid.
12
+ #
13
+ # Deliberately line-level rather than the percentage RefundTransactionModel —
14
+ # the contract credits the lines that came back, not a share of the order.
15
+ class RefundPresenter
16
+ # @param order [Spree::Order]
17
+ # @param integration [SpreeAvalara::Integration]
18
+ # @param return_items [Array<Spree::ReturnLineItem, Spree::ClaimLineItem, Spree::ExchangeLineItem>]
19
+ # @param amount [BigDecimal, nil] what the customer was actually refunded,
20
+ # tax included; nil means the lines' full worth
21
+ # @param tax_date [Time, nil] the original supply date
22
+ # @param exemptions [Array<Spree::TaxExemption>] the same evidence the sale
23
+ # was filed with, so the credit is classified the way the sale was
24
+ # @param tax_identifier [Spree::TaxIdentifier, nil] the registration the sale
25
+ # was filed under, for the same reason
26
+ def initialize(order:, integration:, return_items:, amount: nil, tax_date: nil, exemptions: [],
27
+ tax_identifier: nil)
28
+ @order = order
29
+ @integration = integration
30
+ @return_items = Array(return_items)
31
+ @amount = amount
32
+ @tax_date = tax_date
33
+ @exemptions = exemptions
34
+ @tax_identifier = tax_identifier
35
+ end
36
+
37
+ # A refund of nothing is not a document.
38
+ def nothing_to_credit?
39
+ refunded.values.sum <= 0
40
+ end
41
+
42
+ # @return [Hash]
43
+ def call
44
+ payload = {
45
+ type: 'ReturnInvoice',
46
+ companyCode: integration.preferred_company_code,
47
+ code: code,
48
+ commit: integration.commits_documents?,
49
+ # Filed on the day the money went back, so the credit lands in the
50
+ # period it happened in rather than reopening the sale's.
51
+ date: date_in_store_zone(Time.current),
52
+ currencyCode: order.currency,
53
+ customerCode: SpreeAvalara.customer_code(order),
54
+ addresses: addresses,
55
+ lines: lines
56
+ }
57
+
58
+ # The registration is what made the sale an intra-community supply rather
59
+ # than a standard-rated one. A credit that drops it is re-priced as a
60
+ # consumer refund, which declares VAT the sale never collected — the same
61
+ # reasoning that keeps the tax code and exemption on every credit line.
62
+ payload[:businessIdentificationNo] = tax_identifier.value if tax_identifier&.value.present?
63
+ # Reported under the locations the credited lines were sold from.
64
+ location_code = SpreeAvalara.reporting_location_code(order, return_items.map(&:line_item))
65
+ payload[:reportingLocationCode] = location_code if location_code
66
+
67
+ payload
68
+ end
69
+
70
+ # Keyed to the return, claim or exchange rather than to the order, so a
71
+ # replayed refund adjusts this document and a second return of the same
72
+ # order files a document of its own.
73
+ #
74
+ # @return [String]
75
+ def code
76
+ "#{order.number}-#{SpreeAvalara.post_sale_record(return_items.first)&.number}"
77
+ end
78
+
79
+ private
80
+
81
+ attr_reader :order, :integration, :return_items, :amount, :tax_date, :exemptions, :tax_identifier
82
+
83
+ # Each credit line is the sale's line rebuilt — same tax code, same origin,
84
+ # same exemption — with the credited units, the money that went back for
85
+ # them before tax, and the tax that went back with it.
86
+ def lines
87
+ return_items.filter_map do |item|
88
+ money = refunded.fetch(item)
89
+ next if money <= 0
90
+
91
+ tax = item.credited_tax_total.to_d
92
+ as_sold(item.line_item).merge(
93
+ quantity: item.credited_quantity,
94
+ amount: -[money - tax, 0.to_d].max,
95
+ # Net by construction, as the override below is the whole tax.
96
+ taxIncluded: false,
97
+ # Classified as of the original supply: a return reverses that sale.
98
+ # The date rides here because Avalara refuses a header override
99
+ # alongside a line one.
100
+ taxOverride: { type: 'TaxAmount', reason: 'Refund', taxAmount: -tax, taxDate: supply_date }
101
+ )
102
+ end
103
+ end
104
+
105
+ def as_sold(line_item)
106
+ ItemPresenter.new(item: line_item, owner: order, tax_included: false, exemptions: exemptions).call
107
+ end
108
+
109
+ # The money each line got back, tax included. A short refund — a
110
+ # restocking fee, a part refund — is divided to the cent the way core
111
+ # divided it before writing the credit rows: by the refund agreed per line
112
+ # where the record carries one (a claim), otherwise by what each line is
113
+ # worth. A different split pairs one line's tax with another line's money.
114
+ #
115
+ # @return [Hash{Object => BigDecimal}]
116
+ def refunded
117
+ @refunded ||= begin
118
+ worth = return_items.index_with { |item| item.credited_worth.to_d }
119
+ total = worth.values.sum
120
+
121
+ if amount.nil? || amount.to_d >= total
122
+ worth
123
+ else
124
+ divide(amount.to_d, division_weights(worth))
125
+ end
126
+ end
127
+ end
128
+
129
+ def division_weights(worth)
130
+ agreed = return_items.index_with { |item| (item.try(:refund_amount) || item.credited_worth).to_d }
131
+
132
+ agreed.values.sum.positive? ? agreed : worth
133
+ end
134
+
135
+ def divide(money, weights)
136
+ cents_weights = weights.values.map { |value| to_minor_units(value) }
137
+ return weights.transform_values { 0.to_d } if cents_weights.sum.zero?
138
+
139
+ shares = Spree::Adjusters::LargestRemainder.largest_remainder_shares(to_minor_units(money), cents_weights)
140
+ weights.keys.zip(shares).to_h do |item, cents|
141
+ [item, Spree::Money::Rounding.from_minor_units(cents, order.currency)]
142
+ end
143
+ end
144
+
145
+ def to_minor_units(value)
146
+ Spree::Money::Rounding.to_minor_units(value, order.currency)
147
+ end
148
+
149
+ def supply_date
150
+ date_in_store_zone(tax_date || order.completed_at || Time.current)
151
+ end
152
+
153
+ def date_in_store_zone(time)
154
+ zone = Time.find_zone(order.store&.preferred_timezone) || Time.zone
155
+
156
+ time.in_time_zone(zone).to_date.iso8601
157
+ end
158
+
159
+ def addresses
160
+ {
161
+ shipFrom: AddressPresenter.new(SpreeAvalara.origin_location(order)).call,
162
+ shipTo: AddressPresenter.new(order.tax_address).call,
163
+ billTo: AddressPresenter.new(order.bill_address).call
164
+ }.compact
165
+ end
166
+ end
167
+ end