Class: Shipping::ShipengineBase

Inherits:
Base
  • Object
show all
Defined in:
app/services/shipping/shipengine_base.rb

Overview

Base service class wrapping the ShipEngine HTTP API for rate quoting,
label generation, voiding, and tracking. Concrete carriers (UPS, FedEx,
USPS, etc.) subclass this and override service_code_map / carrier hooks.

Several method names (get_hash, is?) and the per-method ABC/length
metrics here exceed the project's general thresholds. They are kept on
purpose because the names are part of the public surface used by
subclasses, presenters, and tests, and the request/response builders
are deliberately written as flat construction blocks for readability.
rubocop:disable Metrics/ClassLength, Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity

Constant Summary collapse

RATES_TIMEOUT_MS =

Rates use a shorter timeout (fail fast) while labels/void/tracking keep
the full 60 s window — handled transparently by rates_timeout: in the gem.

20_000
MAX_LABEL_REFERENCE_LENGTH =

Maximum label reference length.

35
CDN_DOWNLOAD_TIMEOUTS =

Connect / read timeouts for ShipEngine CDN downloads. Without them Faraday
waits forever on a stalled CDN socket — hanging the whole label flow (and,
since downloads run on Heatwave::Parallel threads, never resolving the
join). With them a stall raises Faraday::TimeoutError, which is in
Heatwave::FaradayRetry::EXCEPTIONS, so the :retry middleware on
cdn_connection retries it.

{ open_timeout: 5, timeout: 20 }.freeze

Instance Attribute Summary

Attributes inherited from Base

#address, #address2, #address3, #address_residential, #attention_name, #billing_account, #billing_country, #billing_zip, #ci_comments, #city, #close_report_only, #cod_amount, #cod_collection_type, #company, #country, #currency_code, #data, #debug, #declared_value, #delivery_instructions, #delivery_total_value, #description, #discount_price, #dropoff_type, #email, #eta, #export_reason, #freight_class, #freightquote_authorization_url, #freightquote_client_id, #freightquote_client_secret, #freightquote_customer_code, #freightquote_events_url, #freightquote_rating_url, #freightquote_shipping_url, #freightquote_voiding_url, #handling_instructions, #has_loading_dock, #image_type, #importer_of_record, #include_first_class_mail_options, #insured_value, #is_construction_site, #is_trade_show, #label_type, #last_request_payload, #last_request_quote_id, #last_response_payload, #limited_access, #line_items, #master_tracking_number, #measure_height, #measure_length, #measure_units, #measure_width, #media_mail, #multiple_piece_shipping, #negotiated_rates, #package, #package_count, #package_sequence_number, #package_total, #packages, #packaging_type, #paperless, #pay_type, #phone, #pickup_datetime, #pickup_instructions, #plain_response, #price, #rate_data, #reference_number_1, #reference_number_2, #reference_number_3, #reference_number_code_1, #reference_number_code_2, #required, #requires_appointment, #requires_inside_delivery, #requires_liftgate, #response, #response_headers, #response_status, #return_to_address, #return_to_address2, #return_to_address3, #return_to_address_residential, #return_to_attention_name, #return_to_city, #return_to_company, #return_to_country, #return_to_email, #return_to_has_loading_dock, #return_to_is_construction_site, #return_to_is_trade_show, #return_to_limited_access, #return_to_name, #return_to_phone, #return_to_requires_appointment, #return_to_requires_inside_delivery, #return_to_requires_liftgate, #return_to_state, #return_to_zip, #rl_carriers_api_key, #rl_carriers_shipping_url, #saturday_delivery, #sender_address, #sender_address2, #sender_address3, #sender_address_residential, #sender_attention_name, #sender_city, #sender_company, #sender_country, #sender_email, #sender_has_loading_dock, #sender_is_construction_site, #sender_is_trade_show, #sender_limited_access, #sender_name, #sender_phone, #sender_requires_appointment, #sender_requires_inside_delivery, #sender_requires_liftgate, #sender_state, #sender_tax_identification_number, #sender_zip, #service_code, #service_type, #services, #ship_date, #shipengine_api_key, #shipengine_canadapost_account_id, #shipengine_canadapost_parent_account_number, #shipengine_canpar_account_id, #shipengine_dhl_express_account_id, #shipengine_fed_ex_account_id, #shipengine_fed_ex_ca_account_id, #shipengine_purolator_account_id, #shipengine_ups_account_id, #shipengine_ups_ca_account_id, #shipengine_usps_account_id, #shipper_address, #shipper_address2, #shipper_address3, #shipper_address_residential, #shipper_attention_name, #shipper_city, #shipper_company, #shipper_country, #shipper_email, #shipper_has_loading_dock, #shipper_is_construction_site, #shipper_is_trade_show, #shipper_limited_access, #shipper_name, #shipper_phone, #shipper_requires_appointment, #shipper_requires_inside_delivery, #shipper_requires_liftgate, #shipper_state, #shipper_zip, #signature_confirmation, #skip_png_download, #skip_rate_test, #special_instructions, #state, #tax_identification_number, #time_in_transit, #total_shipment_weight, #transaction_type, #weight, #weight_units, #zip

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#fedex, #initialize, #purolator, state_from_zip, #ups, #ups_freight

Constructor Details

This class inherits a constructor from Shipping::Base

Class Method Details

.cdn_connectionFaraday::Connection

Faraday connection for ShipEngine CDN downloads. The :retry middleware
provides the backoff/retry on transient transport failures (3 tries /
4**n) that the Retryable wrappers in #download_ci_pdf /
#download_package_label used to. :raise_error (kept) makes 4xx/5xx raise
— an expired/forbidden CDN URL must not write its HTML/JSON error page into
the label/CI Tempfile. Those ServerError/ClientError are NOT in the retry
set, matching the prior exception-only Retryable behavior; only timeouts
and connection failures are retried.

Returns:

  • (Faraday::Connection)


672
673
674
675
676
677
678
# File 'app/services/shipping/shipengine_base.rb', line 672

def self.cdn_connection
  Faraday.new(request: CDN_DOWNLOAD_TIMEOUTS) do |f|
    f.request :retry, **Heatwave::FaradayRetry.options(tries: 3, base: 4, methods: %i[get])
    f.response :raise_error
    f.adapter Faraday.default_adapter
  end
end

.cdn_fetch(url) ⇒ String

Network seam for #download_url_to_string. Exposed as a class method so
tests can stub it via Shipping::ShipengineBase.stub(:cdn_fetch, …)
without needing access to each shipper instance — Minitest's built-in
Object#stub only patches singleton methods, so instance-method stubs
would require any_instance-style mocking which the project doesn't use.

:raise_error makes 4xx/5xx raise instead of returning the body —
otherwise an expired/forbidden CDN URL writes its HTML/JSON error page
straight into the label/CI Tempfile and silently corrupts the file.

Parameters:

  • url (String)

    HTTP(S) URL to fetch

Returns:

  • (String)

    response body



658
659
660
# File 'app/services/shipping/shipengine_base.rb', line 658

def self.cdn_fetch(url)
  cdn_connection.get(url).body
end

Instance Method Details

#find_rates(logger = nil) ⇒ Hash

Fetches available shipping rates for the configured shipment.

Parameters:

  • logger (Logger, nil) (defaults to: nil)

    optional logger (defaults to Rails.logger)

Returns:

  • (Hash)

    response with :success, :rates, and debug request info



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'app/services/shipping/shipengine_base.rb', line 46

def find_rates(logger = nil)
  logger ||= Rails.logger

  @required = %i[shipengine_api_key zip country sender_state sender_zip sender_country packages]

  @country ||= 'US'
  @sender_country ||= 'US'

  rate_options = get_rate_options_hash()
  logger.debug { "Shipping #{carrier} find_rates request destination_zip=#{@zip} destination_country=#{@country}" }
  res = []
  ErrorReporting.scoped({ rate_options: }) do
    # Shipengine has a badly designed set of rate endpoints with different params setup, depending on if you
    # have a fully qualified address, so let's figure that all out in call_appropriate_shipengine_rates_endpoint
    res = call_appropriate_shipengine_rates_endpoint(rate_options)
  end
  rate_count = res.is_a?(Array) ? res.size : res.dig(:rate_response, :rates)&.size
  logger.debug { "Shipping #{carrier} find_rates response rate_count=#{rate_count}" }

  rate_estimates = []

  rate_hash_arr = if res.is_a?(Array)
                    res
                  else
                    res.dig(:rate_response, :rates)
                  end
  rate_hash_arr.each do |rate_hash|
    service_code = rate_hash[:service_code]
    service_code_hash = service_code_map.find { |h| h[:service_code] == service_code } || {}
    hw_service_code = service_code_hash[:hw_service_code]
    service_name = service_code_hash[:name]
    package_type = rate_hash[:package_type]
    hw_package_type = nil

    # determine if we use flat rate packaging to filter results
    # by default we do NOT use flat rate package types unless 1) it's USPS or CanadaPost and 2) we have a flat rate package map defined and 3) we only have a single flat rate package type used
    is_postal_carrier = %w[Usps Canadapost].include?(carrier)
    flat_rate_package_type_map_defined = self.class.method_defined?(:flat_rate_package_type_map) || self.class.private_method_defined?(:flat_rate_package_type_map)
    one_and_only_one_flat_rate_package_type_requested = @packages.any? && @packages.all? { |p| p.flat_rate_package_type.present? } && @packages.map(&:flat_rate_package_type).uniq.compact.size == 1
    use_package_type = is_postal_carrier && flat_rate_package_type_map_defined && one_and_only_one_flat_rate_package_type_requested
    if use_package_type
      package_type_hash = flat_rate_package_type_map.find { |h| h[:package_type] == package_type } || {}
      hw_package_type = package_type_hash[:hw_package_type]
    end
    transportation_charges = rate_hash.dig(:shipping_amount, :amount).to_f
    service_options_charges = rate_hash.dig(:other_amount, :amount).to_f + rate_hash.dig(:insurance_amount, :amount).to_f + rate_hash.dig(:confirmation_amount, :amount).to_f
    price = transportation_charges + service_options_charges
    currency = rate_hash.dig(:shipping_amount, :currency)&.upcase
    next unless price && currency && service_code && hw_service_code
    next unless (package_type.nil? || package_type == 'package') || (use_package_type && hw_package_type.present? && hw_package_type == @packages.first.flat_rate_package_type)
    next if service_code == 'First' && @include_first_class_mail_options != true

    # We need to deal with when sender_country currency is different from the currency returned by ShipEngine, for e.g. DhlExpress Canada because it is a US based import account returning USD costs but we need it in CAD
    currency_res = convert_currency_if_necessary(sender_country:, currency:, costs: [price, transportation_charges, service_options_charges])
    price, transportation_charges, service_options_charges = currency_res[:converted_costs]
    new_currency = currency_res[:new_currency]

    estimate = {}
    estimate[:carrier] = carrier
    estimate[:service_name] = service_name
    estimate[:service_code] = hw_service_code
    estimate[:hw_package_type] = hw_package_type
    estimate[:price] = price
    estimate[:total_charges] = price
    estimate[:transportation_charges] = transportation_charges
    estimate[:service_options_charges] = service_options_charges
    estimate[:insured_value] = @insured_value # get_total_insured_value.to_f.round(2)
    estimate[:currency] = new_currency
    estimate[:rate_data] = rate_hash[:rate_data] || {}
    # Store delivery date info from ShipEngine response
    estimate[:rate_data][:delivery_days] = rate_hash[:delivery_days] if rate_hash[:delivery_days].present?
    estimate[:rate_data][:estimated_delivery_date] = rate_hash[:estimated_delivery_date] if rate_hash[:estimated_delivery_date].present?
    estimate[:rate_data][:days_in_transit] = rate_hash[:delivery_days] if rate_hash[:delivery_days].present?
    # allows for things like estimate.service_code — via HashMethodAccess
    estimate.extend(HashMethodAccess)
    # logger.info "!!!ups find_rates estimate: #{estimate.inspect}"
    rate_estimates << estimate
  end

  successful = true
  msg = ''
  if rate_estimates.empty?
    successful = false
    msg = 'No shipping rates could be found for the destination address' if msg.blank?
  end

  response = {}
  response[:success] = successful
  response[:message] = "#{carrier}: #{msg}" if msg.present?
  response[:request] = rate_options.inspect
  response[:xml] = ''
  response[:rates] = rate_estimates

  # allows for things like fedex.success? — via HashMethodAccess
  response.extend(HashMethodAccess)

  # logger.info "Shipping UPS find_rates response:\n#{response.inspect}"

  response

  # rescue
  # raise ShippingError, get_error
end

#get_separate_labels_per_package_from_label_pdf_url(label_url) ⇒ Array<Hash>

Splits a single multi-page PDF label into one label per package.

Parameters:

  • label_url (String)

    URL of the combined PDF label

Returns:

  • (Array<Hash>)

    one entry per page, each with an :image Tempfile



476
477
478
# File 'app/services/shipping/shipengine_base.rb', line 476

def get_separate_labels_per_package_from_label_pdf_url(label_url)
  Pdf::Utility::PageSplitter.split_from_url(label_url)
end

#label(return_label = false, logger = nil) ⇒ Hash

Generates a shipping label through ShipEngine.

Parameters:

  • return_label (Boolean) (defaults to: false)

    true for an RMA/return label

  • logger (Logger, nil) (defaults to: nil)

    optional logger (defaults to Rails.logger)

Returns:

  • (Hash)

    label result with :labels, :total_charges,
    :shipment_identification_number, :shipengine_label_id, :ci,
    :shipment_paperless, :ship_request_xml, and :ship_reply_xml



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
# File 'app/services/shipping/shipengine_base.rb', line 157

def label(return_label = false, logger = nil)
  logger ||= Rails.logger

  @required = %i[
    shipengine_api_key
    phone company address city state zip
    sender_phone sender_email sender_company sender_address sender_city sender_state sender_zip
    packages service_code insured_value
  ]
  @required << :billing_account if %w[bill_third_party freight_collect].include?(@pay_type)
  @required.push(:billing_zip, :billing_country) if @pay_type == 'bill_third_party'

  @country ||= 'US'
  @sender_country ||= 'US'

  service_code_hash = service_code_map.find { |h| h[:hw_service_code] == @service_code } || {}
  # deal with transitional back and forth to match service codes
  se_service_code = service_code_hash[:service_code]
  if se_service_code.nil?
    service_code_hash = service_code_map.find { |h| h[:hw_service_code] == @service_code.split('SHIPENGINE_').last } || {}
    se_service_code = service_code_hash[:service_code]
  end
  if se_service_code.nil?
    service_code_hash = service_code_map.find { |h| h[:hw_service_code] == "SHIPENGINE_#{@service_code}" } || {}
    se_service_code = service_code_hash[:service_code]
  end

  if se_service_code.nil?
    # no match
    raise ShippingError, 'Cannot generate shipment no service_code found, please HOLD order and refresh shipping rates/methods'
  end

  # per our convention in WY_Shipping:
  # shipper.reference_number_1 = "#{sales_order_number}" # This corresponds to INV, use the Zoro Sales Order number, if any
  # shipper.reference_number_2 = "#{customer_order_number}" # This corresponds to REF, this is the Zoro Customer Order Number
  # shipper.reference_number_3 = "#{delivery.order.po_number.to_s.gsub(/\P{ASCII}/u, '')[0..char_limit]}" #  This corresponds to PO, Zoro PO number here

  # AND per https://www.shipengine.com/docs/labels/messages/ FedEx uses this scheme:
  # "label_messages": {
  #   "reference1": "customer reference number 1", # REF
  #   "reference2": "invoice number 1", # INV
  #   "reference3": "purchase order number 1" # PO
  # }

  # So remap to get it right:
  label_options = get_label_options_hash(, se_service_code, reference_number_array, return_label: return_label, paperless: @paperless)

  # Stash the request BEFORE the call so a failed label (which raises out of
  # get_label) still shows up in the Shipping API Log — the error path reads
  # `last_request_payload` (attr_reader), which was otherwise nil, leaving
  # REQUEST blank.
  @last_request_payload = label_options

  logger.debug { "Shipping #{carrier} label request" }

  res = get_label(label_options)

  logger.debug { "Shipping #{carrier} label response label_id=#{res&.dig(:label_id)} status=#{res&.dig(:status)}" }

  # {
  #   "label_id": "se-7764944",
  #   "status": "completed",
  #   "shipment_id": "se-21748537",
  #   "ship_date": "2020-04-17T00:00:00Z",
  #   "created_at": "2020-04-17T16:22:20.9879673Z",
  #   "shipment_cost": {
  #     "currency": "usd",
  #     "amount": 10.1900
  #   },
  #   "insurance_cost": {
  #     "currency": "usd",
  #     "amount": 0.0
  #   },
  #   "charge_event": "carrier_default",
  #   "tracking_number": "9405511899564088683810",
  #   "is_return_label": false,
  #   "rma_number": null,
  #   "is_international": false,
  #   "batch_id": "",
  #   "carrier_id": "se-169349",
  #   "service_code": "usps_priority_mail",
  #   "package_code": "package",
  #   "voided": false,
  #   "voided_at": null,
  #   "label_format": "pdf",
  #   "label_layout": "4x6",
  #   "trackable": true,
  #   "label_image_id": null,
  #   "carrier_code": "stamps_com",
  #   "tracking_status": "in_transit",
  #   "label_download": {
  #     "pdf": "https://api.shipengine.com/v1/downloads/10/XNGDhq7uZ0CAEt5LOnCxIg/label-7764944.pdf",
  #     "png": "https://api.shipengine.com/v1/downloads/10/XNGDhq7uZ0CAEt5LOnCxIg/label-7764944.png",
  #     "zpl": "https://api.shipengine.com/v1/downloads/10/XNGDhq7uZ0CAEt5LOnCxIg/label-7764944.zpl",
  #     "href": "https://api.shipengine.com/v1/downloads/10/XNGDhq7uZ0CAEt5LOnCxIg/label-7764944.pdf"
  #   },
  #   "form_download": null,
  #   "insurance_claim": null,
  #   "packages": [
  #     {
  #       "package_code": "package",
  #       "weight": {
  #         "value": 20.00,
  #         "unit": "ounce"
  #       },
  #       "dimensions": {
  #         "unit": "inch",
  #         "length": 0.0,
  #         "width": 0.0,
  #         "height": 0.0
  #       },
  #       "insured_value": {
  #         "currency": "usd",
  #         "amount": 0.00
  #       },
  #       "tracking_number": "9405511899564088683810",
  #       "label_messages": {
  #         "reference1": null,
  #         "reference2": null,
  #         "reference3": null
  #       },
  #       "external_package_id": null
  #     }
  #   ]
  # }

  # A response "completes" when there's a usable artifact for the
  # customer to drop off — either a printable label (`label_download`)
  # or a paperless QR/barcode with a non-empty `href`
  # (`paperless_download.href`). Per ShipEngine's spec the
  # `paperless_download` field is nullable, so we check for a
  # populated `href` rather than mere object presence (an empty/null
  # `href` means the carrier didn't issue a usable paperless asset
  # even when display_scheme: 'label_and_paperless' was accepted).
  if res[:status] == 'completed' && res[:label_id].present? && res[:shipment_cost].present? && res[:insurance_cost].present? && res[:tracking_number].present? && res[:packages].any? &&
     (res[:label_download].present? || res.dig(:paperless_download, :href).present? ||
      res[:packages].all? { |p| p[:label_download].present? || p.dig(:paperless_download, :href).present? })
    total_price = format('%.2f', res[:shipment_cost][:amount].to_f + res[:insurance_cost][:amount].to_f)
    currency = res[:shipment_cost][:currency].upcase

    # We need to deal with when sender_country currency is different from the currency returned by ShipEngine, for e.g. DhlExpress Canada because it is a US based import account returning USD costs but we need it in CAD
    currency_res = convert_currency_if_necessary(sender_country: @sender_country, currency:, costs: [total_price.to_f])
    total_price = currency_res[:converted_costs].first

    response_array = []

    # Download the commercial invoice (when present) and the package labels
    # concurrently — each task runs on its own Rails-executor-wrapped thread
    # (see Heatwave::Parallel).
    ci_task = (-> { download_ci_pdf(res[:form_download][:href]) } if res[:form_download])

    # Shipment-level paperless: some carriers (USPS Label Broker, typically)
    # emit a single `paperless_download` covering the whole MPS instead of
    # one per package. Download it in parallel with the labels/CI.
    shipment_paperless_task = (-> { download_paperless_qr(res[:paperless_download]) } if res.dig(:paperless_download, :href).present?)

    ci = nil
    shipment_paperless = nil
    label_image_array = nil
    pkg_download_results = nil

    if res[:packages].all? { |p| p[:label_download].present? }
      # Each package has its own label URL -- download all (plus CI and any
      # shipment-level paperless QR) in parallel. `download_package_label`
      # also fetches the per-package `paperless_download.href` when present.
      pkg_tasks = res[:packages].map do |package|
        -> { download_package_label(package, skip_png: skip_png_download) }
      end
      download_results = Heatwave::Parallel.all(*[ci_task, shipment_paperless_task, *pkg_tasks].compact)
      ci = download_results.shift if ci_task
      shipment_paperless = download_results.shift if shipment_paperless_task
      pkg_download_results = download_results
    elsif res[:label_download].present?
      # Canpar etc: combined MPS label, must be split into per-package labels.
      # Splitting downloads a PDF, so run it alongside the CI download.
      label_pdf_url = res[:label_download][:pdf]
      logger.info "URL of MPS label is here: #{label_pdf_url}"
      split_task = -> { get_separate_labels_per_package_from_label_pdf_url(label_pdf_url) }
      download_results = Heatwave::Parallel.all(*[ci_task, shipment_paperless_task, split_task].compact)
      ci = download_results.shift if ci_task
      shipment_paperless = download_results.shift if shipment_paperless_task
      label_image_array = download_results.first
    else
      raise ShippingError, "#{res[:status].inspect}, data sent to #{carrier}: #{label_options&.to_hash&.inspect}"
    end

    # Build response array from package data + downloaded files
    res[:packages].each_with_index do |package, i|
      response = {}
      response[:tracking_number] = package[:tracking_number] || res[:tracking_number]
      response[:shipengine_label_id] = res[:label_id]
      response[:shipengine_shipment_id] = package[:external_package_id]
      response[:shipengine_carrier_account_id] = 

      if pkg_download_results
        downloaded = pkg_download_results[i]
        response[:image] = downloaded[:image]
        response[:png] = downloaded[:png] if downloaded[:png]
        # Per-package paperless artifact (carriers that issue one
        # QR/barcode per box). `paperless_png` is the downloaded image
        # Tempfile; instructions/handoff_code mirror the response fields
        # for the PDF renderer.
        if downloaded[:paperless_png]
          response[:paperless_png] = downloaded[:paperless_png]
          response[:paperless_instructions] = package.dig(:paperless_download, :instructions)
          response[:paperless_handoff_code] = package.dig(:paperless_download, :handoff_code)
        end
      else
        response[:image] = label_image_array[i][:image]
      end

      response.extend(HashMethodAccess)
      response_array << response
    end
  else
    raise ShippingError, "#{res[:status].inspect}, data sent to #{carrier}: #{label_options&.to_hash&.inspect}"
  end

  # ship_request_xml / ship_reply_xml are stored as Hashes (despite the
  # legacy "_xml" suffix) so the Shipping API Log tab renders them as a
  # navigable JSON tree via pretty_json_tag. Calling `.inspect` here
  # would persist Ruby Hash#inspect output (`{key: "value"}` syntax),
  # which is not JSON-parseable and falls back to a verbatim <pre>.
  # `shipment_paperless` covers all boxes in an MPS with a single QR; nil
  # when the carrier issued per-package codes (handled inside each `labels`
  # entry) or didn't issue paperless at all.
  {
    labels: response_array,
    shipment_identification_number: res[:tracking_number],
    shipengine_label_id: res[:label_id],
    total_charges: total_price,
    ci:,
    shipment_paperless:,
    ship_request_xml: label_options.to_hash,
    ship_reply_xml: res.to_hash
  }
end

#recover_actual_delivery_date_from_events!(tracking_result) ⇒ String?

Returns recovered actual_delivery_date, or nil if none found.

Parameters:

  • tracking_result (Hash)

    ShipEngine tracking response to mutate

Returns:

  • (String, nil)

    recovered actual_delivery_date, or nil if none found



509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
# File 'app/services/shipping/shipengine_base.rb', line 509

def recover_actual_delivery_date_from_events!(tracking_result)
  return if tracking_result.blank?
  return if tracking_result[:actual_delivery_date].present?
  return unless DELIVERED_STATUS_CODES.include?(tracking_result[:status_code].to_s)

  events = Array(tracking_result[:events])
  return if events.empty?

  # Walk events in chronological order (oldest-first). The first DE / SP
  # scan IS the actual delivery moment; later events (proof-of-delivery
  # uploads, signature scans, paperwork) are administrative followups
  # and would push our actual_delivery_date later than reality. Use the
  # explicit per-event status_code when present (Canada Post / FedEx),
  # or infer from the description (Canpar).
  delivered_event = events.find do |event|
    code = event[:status_code].presence ||
           ShipmentEvent.infer_status_code(event[:event_description].presence || event[:description])
    DELIVERED_STATUS_CODES.include?(code.to_s)
  end
  return if delivered_event.nil?

  occurred_at = delivered_event[:occurred_at].presence
  return if occurred_at.nil?

  tracking_result[:actual_delivery_date] = occurred_at
end

#start_tracking(tracking_number) ⇒ Hash

Subscribes a tracking number to ShipEngine webhook push updates.

Parameters:

  • tracking_number (String)

    carrier tracking number

Returns:

  • (Hash)

    ShipEngine confirmation



424
425
426
# File 'app/services/shipping/shipengine_base.rb', line 424

def start_tracking(tracking_number)
  shipengine_call(:start_tracking, carrier_code, tracking_number)
end

#stop_tracking(tracking_number) ⇒ Hash

Releases a tracking subscription — the counterpart to #start_tracking.
ShipEngine stops pushing webhook events for this tracking number.

Called once a parcel reaches a terminal state; see
ShipmentsTrackingWorker for what counts as terminal and why we bother
(we subscribed every parcel and never released one, so subscriptions
accumulated without bound).

Parameters:

  • tracking_number (String)

Returns:

  • (Hash)

    ShipEngine's confirmation



438
439
440
# File 'app/services/shipping/shipengine_base.rb', line 438

def stop_tracking(tracking_number)
  shipengine_call(:stop_tracking, carrier_code, tracking_number)
end

#track(tracking_number) ⇒ ActiveSupport::HashWithIndifferentAccess

Polls ShipEngine for the current status of a tracking number.

Parameters:

  • tracking_number (String)

    carrier tracking number

Returns:

  • (ActiveSupport::HashWithIndifferentAccess)

    tracking result



446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
# File 'app/services/shipping/shipengine_base.rb', line 446

def track(tracking_number)
  logger ||= Rails.logger
  @required = [:shipengine_api_key]

  # See: https://shipengine.github.io/shipengine-openapi/#operation/get_tracking_log
  logger.debug { "Shipping #{carrier} track request tracking_number=#{tracking_number}" }
  tracking_result = {}
  # Retry on timeouts and transient ShipEngine errors like dropped keep-alive connections
  retry_exceptions = (Retryable::TIMEOUT_CLASSES + [ShipEngineRb::Exceptions::ShipEngineError])
  Retryable.retryable(tries: 2, sleep: ->(n) { 4**n }, on: retry_exceptions) do |attempt_number, _exception|
    logger.warn "Attempting tracking: #{tracking_number}, attempt ##{attempt_number}" if attempt_number > 1
    tracking_result = shipengine_call(:track, carrier_code, tracking_number)
  end
  # Recover actual_delivery_date from the matching delivered event when
  # ShipEngine returns the package in a delivered state but leaves the
  # top-level `actual_delivery_date` null. Canpar (and intermittently
  # other carriers) returns the status without populating the date even
  # when the corresponding event in `events[]` carries it. Surfaced
  # during a 2-Day shipping OTDR analysis (May 2026) — ~19 of 30
  # delivered Canpar shipments / 90 days were stuck without a date.
  recover_actual_delivery_date_from_events!(tracking_result)
  tracking_result.delete(:events)
  logger.debug { "Shipping #{carrier} track response tracking_number=#{tracking_number} status=#{tracking_result&.dig(:status_description)}" }
  tracking_result.with_indifferent_access
end

#valid_address?(logger = nil) ⇒ Hash

Validates the destination address through ShipEngine.

Parameters:

  • logger (Logger, nil) (defaults to: nil)

    optional logger (defaults to Rails.logger)

Returns:

  • (Hash)

    validation result with :valid_address, :status_code,
    :status_message, and :suggested_address_hashes



30
31
32
33
34
35
36
37
38
39
40
# File 'app/services/shipping/shipengine_base.rb', line 30

def valid_address?(logger = nil)
  logger ||= Rails.logger
  @required = %i[shipengine_api_key address city state zip]

  results = shipengine_call(:validate_address, [get_address_hash])
  res = results&.first || {}

  logger.debug { "#{carrier || 'Shipengine'} valid_address? status=#{res[:status]} messages=#{res[:messages]&.pluck(:message).inspect}" }

  { valid_address: (res[:status] == 'verified'), status_code: :ok, status_message: (res[:messages] || []).pluck(:message).join('. '), suggested_address_hashes: [res[:matched_address]].compact }
end

#void(label_id) ⇒ Hash

Voids a previously created ShipEngine label.

Parameters:

  • label_id (String)

    ShipEngine label ID to void

Returns:

  • (Hash)

    void request/response XML debug hashes

Raises:



399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
# File 'app/services/shipping/shipengine_base.rb', line 399

def void(label_id)
  logger ||= Rails.logger
  @required = [:shipengine_api_key]

  @country ||= 'US'
  @sender_country ||= 'US'

  res = void_label(label_id)

  # {
  #   "approved": true,
  #   "message": "Request for refund submitted.  This label has been voided."
  # }

  logger.debug { "Shipping #{carrier} void request/response approved=#{res&.dig(:approved)} message=#{res&.dig(:message)}" }

  raise ShippingError, "Void request failed: #{res[:message].inspect}, label_id sent to #{carrier}: #{label_id}" unless res[:approved]

  { void_request_xml: res&.to_hash&.inspect, void_response_xml: res&.to_hash&.inspect }
end