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/MethodLength, Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity, Metrics/BlockLength, Naming/AccessorMethodName, Naming/PredicatePrefix, Naming/PredicateMethod

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 =
35

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, #include_first_class_mail_options, #insured_value, #is_construction_site, #is_trade_show, #label_type, #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, #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, #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

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

Instance Method Details

#find_rates(logger = nil) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
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
149
150
151
# File 'app/services/shipping/shipengine_base.rb', line 34

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",
               carrier: carrier,
               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", carrier: carrier, 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.detect { |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.detect { |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
    def estimate.method_missing(name, *args)
      key?(name) ? self[name] : super
    end

    def estimate.respond_to_missing?(name, include_private = false)
      key?(name) || super
    end
    # 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?
  def response.method_missing(name, *args)
    key?(name) ? self[name] : super
  end

  def response.respond_to_missing?(name, include_private = false)
    key?(name) || super
  end

  # 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) ⇒ Object



400
401
402
403
404
# File 'app/services/shipping/shipengine_base.rb', line 400

def get_separate_labels_per_package_from_label_pdf_url(label_url)
  # Annoyingly Shipengine Canpar gets the label as a single presumably multi-page asset.
  # Splitting is delegated to Pdf::Utility::PageSplitter to follow our convention.
  Pdf::Utility::PageSplitter.split_from_url(label_url)
end

#label(_return_label = false, logger = nil) ⇒ Object

rubocop:disable Style/OptionalBooleanParameter -- positional signature shared across all Shipping::* carriers



153
154
155
156
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
# File 'app/services/shipping/shipengine_base.rb', line 153

def label(_return_label = false, logger = nil) # rubocop:disable Style/OptionalBooleanParameter -- positional signature shared across all Shipping::* carriers
  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.detect { |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.detect { |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.detect { |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)

  logger.debug("Shipping #{carrier} label request", carrier: carrier)

  res = get_label(label_options)

  logger.debug("Shipping #{carrier} label response",
               carrier: carrier,
               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
  #     }
  #   ]
  # }

  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[:packages].all? do |p|
    p[:label_download].present?
  end)
    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 CI and package labels in parallel using futures
    require 'concurrent'

    ci_future = (ConcurrentRails::Promises.future { download_ci_pdf(res[:form_download][:href]) } if res[:form_download])

    # Determine how package labels are provided
    label_image_array = nil
    if res[:packages].all? { |p| p[:label_download].present? }
      # Each package has its own label URL -- download all in parallel
      pkg_futures = res[:packages].map do |package|
        ConcurrentRails::Promises.future { download_package_label(package, skip_png: skip_png_download) }
      end
    elsif res[:label_download].present?
      # Canpar etc: combined MPS label, must split synchronously (single download)
      label_pdf_url = res[:label_download][:pdf]
      logger.info "URL of MPS label is here: #{label_pdf_url}"
      label_image_array = get_separate_labels_per_package_from_label_pdf_url(label_pdf_url)
      pkg_futures = nil
    else
      raise ShippingError, "#{res[:status].inspect}, data sent to #{carrier}: #{label_options&.to_hash&.inspect}"
    end

    # Join CI future
    ci = ci_future&.value!

    # Join package download futures (if per-package downloads were used)
    pkg_download_results = pkg_futures&.map(&:value!)

    # 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]
      else
        response[:image] = label_image_array[i][:image]
      end

      def response.method_missing(name, *args)
        key?(name) ? self[name] : super
      end

      def response.respond_to_missing?(name, include_private = false)
        key?(name) || super
      end
      response_array << response
    end
  else
    raise ShippingError, "#{res[:status].inspect}, data sent to #{carrier}: #{label_options&.to_hash&.inspect}"
  end

  { labels: response_array, shipment_identification_number: res[:tracking_number], shipengine_label_id: res[:label_id], total_charges: total_price, ci:, ship_request_xml: label_options.to_hash.inspect, ship_reply_xml: res.to_hash.inspect }
end

#start_tracking(tracking_number) ⇒ Object



372
373
374
375
376
377
# File 'app/services/shipping/shipengine_base.rb', line 372

def start_tracking(tracking_number)
  # Registers a tracking number for webhook push updates.
  # ShipEngine will send tracking events to our configured webhook URL as the
  # package moves through the carrier network.
  shipengine_call(:start_tracking, carrier_code, tracking_number)
end

#track(tracking_number) ⇒ Object



379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
# File 'app/services/shipping/shipengine_base.rb', line 379

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", carrier: carrier, 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: lambda { |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
  tracking_result.delete(:events)
  logger.debug("Shipping #{carrier} track response",
               carrier: carrier,
               tracking_number: tracking_number,
               status: tracking_result&.dig(:status_description))
  tracking_result.with_indifferent_access
end

#valid_address?(logger = nil) ⇒ Boolean

Returns:

  • (Boolean)


20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'app/services/shipping/shipengine_base.rb', line 20

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))

  { 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) ⇒ Object

Raises:



348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
# File 'app/services/shipping/shipengine_base.rb', line 348

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",
               carrier: carrier,
               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