Class: WyShipping

Inherits:
Object
  • Object
show all
Defined in:
app/services/wy_shipping.rb

Overview

Service object: wy shipping.

Constant Summary collapse

COMMERCIAL_INVOICE_COMMENTS =

Commercial invoice comments.

'PLEASE USE UPS OMD FOR BROKER AND REFERENCE NRI ACCT# W50R74'
MARKETPLACE_CARRIERS =

Marketplace carriers.

%w[AmazonSeller WalmartSeller].freeze
AMAZON_BUY_SHIPPING_ADMIN_ONLY =

Amazon buy shipping admin only.

false
MAILING_EXTRA_CARRIERS =

Additional carriers to query for mailing postage rates (alongside the default postal carrier)

{
  USA: %w[UPS FedEx],
  CAN: %w[UPS FedEx Purolator Canpar]
}.with_indifferent_access.freeze
MAILING_GROUND_SERVICE_CODES =

Only show ground/economy service codes from these carriers for mailings
(postal carriers like USPS/Canadapost return all their services unfiltered)

{
  'UPS'       => %w[03],                                       # UPS Ground
  'FedEx'     => %w[FEDEX_GROUND GROUND_HOME_DELIVERY],        # FedEx Ground, FedEx Home Delivery
  'Purolator' => %w[PurolatorGround PurolatorGroundEvening],   # Purolator Ground, Ground Evening
  'Canpar'    => %w[Ground]                                    # Canpar Ground
}.freeze
CARRIER_PER_PACKAGE_WEIGHT_LIMIT_LBS =

Per-package weight ceilings for small-parcel carriers, in pounds. When any
single package in a shipment exceeds the carrier's cap, the carrier rejects
the rate request — so we drop that carrier from the quote upstream and let
LTL/freight options fill the gap.

AppSignal #3658: UPS rejected an oversize shipment with "UPS weight limit
per package is 150 lbs" deep inside Shipping::ShipengineBase#shipengine_call,
surfacing as a generic 500 to the operator with no actionable next step.
Filtering at carrier-list build time means the rate request is never sent,
the noise stops, and the operator sees only the carriers that can actually
carry the package.

Conservative list — only carriers with a stable, well-known per-package cap.
Postal/express carriers (USPS, Canadapost, DhlExpress) have service-code-
specific caps that don't fit a single threshold; let them fail-once-and-add.

{
  'UPS'   => 150, # UPS Ground / Worldwide Express (USA + CAN)
  'FedEx' => 150  # FedEx Ground / Express small-parcel (USA + CAN)
}.freeze
STANDALONE_RATE_DATA_CARRIERS =

Standalone rate data carriers.
Includes both legacy (Saia, Roadrunner = Freightquote-brokered historical shipments)
and new (ShipengineSaia, ShipengineRoadrunner = direct ShipEngine LTL) so label/regen
paths work for either era of shipments.carrier rows.

%w[SpeedeeDelivery Freightquote RlCarriers ShipengineRlCarriers Roadrunner ShipengineRoadrunner Saia ShipengineSaia ShipengineXpo YrcFreight ShipengineFedExFreight ShipengineFedExFreightEconomy].freeze
AMZBS_TOKEN_STALE_THRESHOLD_MINUTES =

Amzbs token stale threshold minutes.

8

Class Method Summary collapse

Class Method Details

.assign_standalone_shipper_rate_extras!(shipper, standalone_delivery, carrier) ⇒ Object

Carriers that persist quoted rate details on ShippingMethod / rate shop and need them again at label time.
Mirrors ship_delivery (see %w[SpeedeeDelivery Freightquote ...] there).



1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
# File 'app/services/wy_shipping.rb', line 1155

def self.assign_standalone_shipper_rate_extras!(shipper, standalone_delivery, carrier)
  return unless STANDALONE_RATE_DATA_CARRIERS.include?(carrier)

  selected = standalone_delivery.shipping_rates&.find do |sr|
    ActiveSupport::HashWithIndifferentAccess.new(sr)[:service_code].to_s == standalone_delivery.service_code.to_s
  end

  shipper.rate_data = standalone_shipper_rate_data_from_selection(selected)
  shipper.delivery_total_value = standalone_delivery.shipments.awaiting_label.sum { |s| s.compute_shipment_declared_value.to_f }
end

.build_amz_per_shipment_rate(base_rate, pkg_rate) ⇒ Object

Build a single-shipment rate from a multi-package per_package_rate entry.
Replaces the top-level request_token/rate_id/doc-specs with the per-package values
and strips per_package_rates so ShippingLabelPurchaser uses create_label_single.



1780
1781
1782
1783
1784
1785
1786
1787
1788
# File 'app/services/wy_shipping.rb', line 1780

def self.build_amz_per_shipment_rate(base_rate, pkg_rate)
  pkg_rate = pkg_rate.with_indifferent_access if pkg_rate.respond_to?(:with_indifferent_access)
  base_rate.except(:per_package_rates).merge(
    amz_request_token: pkg_rate[:request_token],
    amz_rate_id: pkg_rate[:rate_id],
    amz_supported_document_specifications: pkg_rate[:supported_document_specifications] || base_rate[:amz_supported_document_specifications],
    available_value_added_services: pkg_rate[:available_value_added_services] || base_rate[:available_value_added_services]
  )
end

.build_marketplace_rate(rate_data) ⇒ Hash

Build a marketplace-agnostic rate hash from stored rate_data
Each marketplace stores different fields, so we normalize them here

Parameters:

  • rate_data (Hash)

    The rate data from ShippingCost

Returns:

  • (Hash)

    Normalized rate hash



1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
# File 'app/services/wy_shipping.rb', line 1795

def self.build_marketplace_rate(rate_data)
  {
    # Walmart SWW fields
    carrier_id: rate_data[:sww_carrier_id],
    service_type: rate_data[:sww_service_type],
    price: rate_data[:sww_price] || rate_data[:price],
    # Amazon Buy Shipping fields — must match what ShippingLabelPurchaser#purchase_label reads
    amz_request_token: rate_data[:amz_request_token],
    amz_rate_id: rate_data[:amz_rate_id],
    amz_carrier_id: rate_data[:amz_carrier_id],
    amz_carrier_name: rate_data[:amz_carrier_name],
    amz_service_id: rate_data[:amz_service_id],
    amz_service_name: rate_data[:amz_service_name],
    amz_total_charge: rate_data[:amz_total_charge],
    amz_transit_days: rate_data[:amz_transit_days],
    amz_supported_document_specifications: rate_data[:amz_supported_document_specifications],
    # VAS groups are stored under `raw.availableValueAddedServiceGroups` on
    # rates fetched before May 2026; newer rates also carry the structured
    # key at the top level. Read either so Amazon's required-VAS validation
    # (e.g. UPS Ground's `VAS_GROUP_ID_CONFIRMATION`) gets a populated
    # selection instead of nil — Amazon rejects rates that require a VAS
    # group when `requestedValueAddedServices` is missing.
    available_value_added_services: rate_data[:available_value_added_services] ||
      rate_data.dig(:raw, :availableValueAddedServiceGroups) ||
      rate_data.dig('raw', 'availableValueAddedServiceGroups'),
    per_package_rates: rate_data[:per_package_rates],
    # Generic fields
    carrier: rate_data[:carrier],
    service: rate_data[:service]
  }.compact
end

.calculate_shipping_from_options(options) ⇒ Object



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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
# File 'app/services/wy_shipping.rb', line 206

def self.calculate_shipping_from_options(options)
  # Rails.logger.debug "WyShipping.calculate_shipping_from_options: #{options.inspect}"
  shipper_config = SHIPPING_BASE_CONFIGURATION.merge(SHIPPING_SHIPPER_CONFIGURATION[options[:origin_country_iso3].to_sym] || SHIPPING_SHIPPER_CONFIGURATION[:USA]) # fall back to USA config for international drop-ship
  destination = { state: options[:state], country: options[:country_iso], zip: options[:postal_code].delete(' ').delete('-'), address_residential: options[:is_residential], city: options[:city] }
  destination[:city] = destination[:city].upcase if destination[:city].present?
  origin = populate_origin_sender_data(address: options[:origin_address], shipper_config: shipper_config)
  if options[:destination_address].present?
    destination[:attention_name] = options[:destination_address].person_name.to_s.gsub(/[^0-9a-z\s]/i, '')
    destination[:company] = options[:destination_address].company_name.to_s.gsub(/[^0-9a-z\s]/i, '')
    destination[:address] = options[:destination_address].street1
    destination[:address2] = options[:destination_address].street2
    destination[:state] = options[:destination_address].state_code
    destination[:address_residential] = is_address_residential?(options[:destination_address]) # here we test this and override what is saved in the address
    destination[:has_loading_dock] = options[:destination_address].has_loading_dock
    destination[:is_construction_site] = options[:destination_address].is_construction_site
    destination[:requires_inside_delivery] = options[:destination_address].requires_inside_delivery
    destination[:is_trade_show] = options[:destination_address].is_trade_show
    destination[:requires_liftgate] = options[:destination_address].requires_liftgate
    destination[:limited_access] = options[:destination_address].limited_access
    destination[:requires_appointment] = options[:destination_address].requires_appointment
  end
  is_domestic = destination[:country] == options[:origin_country_iso3].to_s[0..1]
  shippers = []
  is_freight = options[:ltl_freight] || options[:ltl_freight_guaranteed]
  purolator_ltl = is_freight && (options[:origin_country_iso3] == 'CAN') # kludge
  # Rails.logger.debug "WyShipping.calculate_shipping_from_options: purolator_ltl: #{purolator_ltl}"
  if is_freight && options[:destination_address].present? && !options[:destination_address].is_valid_for_freight?
    shippers = [] # here we hijack the process and prevent freight shipping quotes unless the address is valid for freight, ie the freight fields are populated
  elsif is_freight
    # limit freight carriers to those supported for WWW if necessary
    carriers = []
    carriers = options[:origin_address].supported_carriers if options[:origin_address] && options[:origin_address].supported_carriers.present?
    if options[:www] || options[:is_www_ship_by_zip]
      carriers = WWW_FREIGHT_CARRIERS[options[:origin_country_iso3].to_sym]
    elsif !is_domestic
      carriers += NON_DOMESTIC_SHIPPING_CARRIERS[options[:origin_country_iso3].to_sym]
    else
      carriers = SUPPORTED_SHIPPING_CARRIERS[options[:origin_country_iso3].to_sym]
    end
    # Filter to explicitly allowed carriers (e.g., RMA-assigned)
    carriers &= Array(options[:allowed_carriers]).map(&:to_s) if options[:allowed_carriers].present?
    ltl_address_records = { origin_address: options[:origin_address], destination_address: options[:destination_address] }
    # Propagate the orchestrator's ship_date to LTL carriers so quoted
    # arrival dates account for non-working days (matching the same-day
    # cutoff used by the customer-facing banner).
    ship_date_opts = options[:ship_date].present? ? { ship_date: options[:ship_date] } : {}
    ltl_base_opts = -> { shipper_config.merge(origin).merge(destination).merge(ship_date_opts) }
    ltl_shipengine_opts = -> { ltl_base_opts.call.merge(ltl_address_records) }
    if options[:origin_country_iso3] == 'USA'
      shippers << Shipping::RlCarriers.new(ltl_base_opts.call) if carriers.include?('RlCarriers')
      shippers << Shipping::ShipengineRlCarriers.new(ltl_shipengine_opts.call) if carriers.include?('ShipengineRlCarriers')
      shippers << Shipping::ShipengineFedExFreight.new(ltl_shipengine_opts.call) if carriers.include?('ShipengineFedExFreight')
      shippers << Shipping::ShipengineFedExFreightEconomy.new(ltl_shipengine_opts.call) if carriers.include?('ShipengineFedExFreightEconomy')
      shippers << Shipping::ShipengineSaia.new(ltl_shipengine_opts.call) if carriers.include?('ShipengineSaia')
      shippers << Shipping::ShipengineRoadrunner.new(ltl_shipengine_opts.call) if carriers.include?('ShipengineRoadrunner')
      shippers << Shipping::ShipengineXpo.new(ltl_shipengine_opts.call) if carriers.include?('ShipengineXpo')
      if options[:ltl_freight_guaranteed]
        shippers.detect { |s| s.is_a?(Shipping::RlCarriers) }&.service_type = 'Guaranteed'
        shippers.select { |s| s.is_a?(Shipping::ShipengineLtlBase) }.each { |s| s.service_type = 'Guaranteed' }
      elsif carriers.include?('Freightquote')
        shippers << Shipping::Freightquote.new(ltl_base_opts.call)
      end
    elsif options[:origin_country_iso3] == 'CAN'
      shippers << Shipping::Freightquote.new(ltl_base_opts.call) if carriers.include?('Freightquote')
      shippers << Shipping::ShipengineFedExFreight.new(ltl_shipengine_opts.call) if carriers.include?('ShipengineFedExFreight')
      shippers << Shipping::ShipengineFedExFreightEconomy.new(ltl_shipengine_opts.call) if carriers.include?('ShipengineFedExFreightEconomy')
    end
  else
    carriers = []
    # if we have a forced carrier, ie EDI shipping option we only use that (if it is a valid supported carrier, otherwise we will need the usual logic to find the 3rd party carrier)
    if options[:force_shipping_carrier] && SUPPORTED_SHIPPING_CARRIERS.include?(options[:force_shipping_carrier])
      carriers << options[:force_shipping_carrier]
    elsif options[:origin_address] && options[:origin_address].supported_carriers.present?
      carriers = options[:origin_address].supported_carriers
    end
    # if there are none, then step through carrier selection
    unless carriers.any?
      carriers += if is_domestic
                    SUPPORTED_SHIPPING_CARRIERS[options[:origin_country_iso3].to_sym] || []
                  else
                    NON_DOMESTIC_SHIPPING_CARRIERS[options[:origin_country_iso3].to_sym] || []
                  end
    end
    # Filter to explicitly allowed carriers (e.g., RMA-assigned)
    carriers &= Array(options[:allowed_carriers]).map(&:to_s) if options[:allowed_carriers].present?
    # Catalog-level carrier exclusions (e.g. Speedee excluded for Amazon Seller US)
    if (catalog = options[:catalog]) && catalog.excluded_carriers.present?
      carriers = carriers.reject { |c| catalog.carrier_excluded?(c) }
      Rails.logger.debug { "Catalog #{catalog.id} excluded carriers: #{catalog.excluded_carriers.inspect}, remaining: #{carriers.inspect}" }
    end
    carriers.each do |carrier|
      Rails.logger.debug { "Carrier: #{carrier}" }
      valid_carrier = true
      valid_carrier = false if carrier.blank? # apparently, blank carriers can get through via supplier address supported carriers
      valid_carrier = false if is_freight
      valid_carrier = false if carrier == 'FedEx' && !(!options[:myprojects_legacy] && !options[:cod_collection_type])
      valid_carrier = false if carrier == 'Purolator' && !(options[:city] && !options[:cod_collection_type])
      if %w[UPSFreight Freightquote RlCarriers ShipengineRlCarriers ShipengineRoadrunner ShipengineSaia ShipengineXpo YrcFreight FedExFreight ShipengineFedExFreight ShipengineFedExFreightEconomy].include?(carrier)
        valid_carrier = false # here as a kludge to prevent Freight unless explcitly requested above
      end
      # check for PO box and that carrier is postal — mirror of the ship_delivery
      # guard below which checks both ship_to and ship_from. Without the origin-side
      # check, RMA returns from PO Box addresses still surface FedEx/UPS quotes that
      # are guaranteed to fail at label generation.
      valid_carrier = false if options[:destination_address].present? && !options[:destination_address].not_a_po_box?(carrier)
      valid_carrier = false if options[:origin_address].present? && !options[:origin_address].not_a_po_box?(carrier)
      # Drop small-parcel carriers when any package exceeds their per-package
      # weight cap (AppSignal #3658). The rate request would otherwise reach
      # the carrier and come back as a generic SystemError; filtering here
      # surfaces only the carriers that can actually carry the shipment.
      valid_carrier = false if carrier_exceeds_per_package_weight_limit?(carrier, options[:shipping_weights])
      # for cart checkout on www, skip non supported carriers
      if options[:www]
        www_carriers = WWW_SHIPPING_CARRIERS[options[:origin_country_iso3].to_sym]
        www_carriers = PO_BOX_CARRIERS_BY_COUNTRY[options[:origin_country_iso3].to_sym] if options[:destination_address].present? && options[:destination_address].po_box?
        valid_carrier = false unless www_carriers.include?(carrier)
      end
      # for estimate shipping by zip www, only use carriers that support zip only rating
      if options[:is_www_ship_by_zip]
        www_carriers = WWW_SHIPPING_BY_ZIP_CARRIERS[options[:origin_country_iso3].to_sym]
        valid_carrier = false unless www_carriers.include?(carrier)
      end
      Rails.logger.debug { "options[:www]: #{options[:www]}" }
      Rails.logger.debug { "options[:is_www_ship_by_zip]: #{options[:is_www_ship_by_zip]}" }
      Rails.logger.debug { "is_freight: #{is_freight}" }
      Rails.logger.debug { "valid_carrier: #{valid_carrier}" }
      if valid_carrier
        carrier_class = class_for_carrier(carrier)
        Rails.logger.debug { "adding #{carrier} to shippers" }
        carrier_options = (shipper_config || SHIPPING_SHIPPER_CONFIGURATION[:USA]).merge(origin).merge(destination)
        # Pass ship_date for accurate delivery estimates from ShipEngine
        carrier_options[:ship_date] = options[:ship_date] if options[:ship_date].present?
        shippers << carrier_class.new(carrier_options)
        Rails.logger.debug { "Shipper: #{shippers.last.inspect}" }
      else
        Rails.logger.debug { "disallowing #{carrier}" }
      end
    end
  end

  # Add Walmart "Ship with Walmart" carrier for Walmart marketplace orders
  # This provides discounted shipping rates through Walmart's carrier partnerships
  # Only enabled if the partner has ship_with_walmart_enabled in orchestrator config
  if options[:walmart_order_info].present? && !is_freight
    begin
      orchestrator = Edi::Walmart::Orchestrator.new(options[:walmart_order_info][:partner])
      if orchestrator.ship_with_walmart_enabled?
        walmart_options = (shipper_config || SHIPPING_SHIPPER_CONFIGURATION[:USA])
                          .merge(origin)
                          .merge(destination)
                          .merge(
            walmart_partner: options[:walmart_order_info][:partner],
            purchase_order_id: options[:walmart_order_info][:po_number],
            deliver_by_date: options[:walmart_order_info][:deliver_by_date],
            ship_by_date: options[:walmart_order_info][:ship_by_date]
          )
        shippers << Shipping::WalmartSeller.new(walmart_options)
        Rails.logger.debug { "adding WalmartSeller to shippers for PO: #{options[:walmart_order_info][:po_number]}" }
      else
        Rails.logger.debug { "Ship with Walmart not enabled for partner #{options[:walmart_order_info][:partner]}" }
      end
    rescue StandardError => e
      Rails.logger.warn { "Failed to check Ship with Walmart availability: #{e.message}" }
    end
  end

  # Add Amazon Buy Shipping carrier for Amazon marketplace orders
  # Provides Amazon's negotiated rates with A-to-Z Buy Shipping protections
  if options[:amazon_order_info].present? && !is_freight
    begin
      orchestrator = Edi::Amazon::Orchestrator.new(options[:amazon_order_info][:partner])
      if orchestrator.buy_shipping_enabled?
        amazon_options = (shipper_config || SHIPPING_SHIPPER_CONFIGURATION[:USA])
                         .merge(origin)
                         .merge(destination)
                         .merge(
            amazon_partner: options[:amazon_order_info][:partner],
            amazon_order_id: options[:amazon_order_info][:order_id],
            deliver_by_date: options[:amazon_order_info][:deliver_by_date],
            ship_by_date: options[:amazon_order_info][:ship_by_date]
          )
        shippers << Shipping::AmazonSeller.new(amazon_options)
        Rails.logger.debug { "adding AmazonSeller to shippers for order: #{options[:amazon_order_info][:order_id]}" }
      else
        Rails.logger.debug { "Amazon Buy Shipping not enabled for partner #{options[:amazon_order_info][:partner]}" }
      end
    rescue StandardError => e
      Rails.logger.warn { "Failed to check Amazon Buy Shipping availability: #{e.message}" }
    end
  end

  # The shipping weights and dimensions should have been fed in, the package determination is decoupled from this now since it can have multiple origins
  packages_hash = { weights: options[:shipping_weights], dimensions: options[:shipping_dimensions], flat_rate_package_types: options[:flat_rate_package_types], container_types: options[:container_types], package_values: options[:package_values] }

  # Rails.logger.debug "WyShipping.calculate_shipping_from_items, packages_hash: #{packages_hash.inspect}"
  ship_weights = packages_hash[:weights]
  ship_dimensions = packages_hash[:dimensions]
  if ship_weights.empty?
    ship_weights = [0.1] # need some minimum, even for quoting
  end
  ship_weight = ship_weights.sum # assume container weights all included

  estimate_options = {}
  estimate_options[:delivery] = options[:delivery]
  estimate_options[:resource_shipping_method] = options[:resource_shipping_method]
  estimate_options[:shippers] = shippers
  estimate_options[:ship_weights] = ship_weights
  estimate_options[:saturday_delivery] = options[:saturday_delivery]
  estimate_options[:ship_dimensions] = ship_dimensions
  estimate_options[:flat_rate_package_types] = packages_hash[:flat_rate_package_types]
  estimate_options[:container_types] = packages_hash[:container_types]
  estimate_options[:package_values] = packages_hash[:package_values]
  estimate_options[:is_residential] = options[:is_residential]
  estimate_options[:signature_confirmation] = options[:signature_confirmation]
  estimate_options[:myprojects_legacy] = options[:myprojects_legacy]
  estimate_options[:cod_collection_type] = options[:cod_collection_type]
  estimate_options[:cod_amount] = options[:cod_amount]
  estimate_options[:purolator_ltl] = purolator_ltl
  estimate_options[:is_domestic] = is_domestic
  estimate_options[:origin_address] = options[:origin_address]
  estimate_options[:media_mail] = options[:media_mail] if options[:media_mail]
  estimate_options[:insured_value] = options[:insured_value] if options[:insured_value].present?
  estimate_options[:is_freight] = is_freight
  estimate_options[:catalog] = options[:catalog]
  Rails.logger.debug { "WYSHIPPING#calculate_shipping_from_options: estimate_options[:insured_value]: #{estimate_options[:insured_value]}, options[:insured_value]: #{options[:insured_value]}" }

  shipping_costs = estimate_shipping_cost(estimate_options)
  # Rails.logger.debug "shipping_costs.first[:status_code.to_s: "+shipping_costs.first[:status_code].to_s
  if !shipping_costs.empty? && (shipping_costs.first[:status_code] == '1')
    shipping_costs.first[:packages] = packages_hash
    Rails.logger.debug { "shipping_costs: #{shipping_costs.inspect}" }
    shipping_costs.last.each do |option, value|
      Rails.logger.debug { "BEFORE option: #{option}" }
      Rails.logger.debug { "BEFORE value[option_name]: #{value[:option_name]}" }
      Rails.logger.debug { "BEFORE value: #{value.inspect}" }
      next unless value.present? && value.is_a?(Hash)

      unless value[:third_party] && (value[:cost] == 0.0 || value[:cost].nil?)
        additional_charge = 0.0
        if option.to_s.index('fedex_') && option.to_s.index('_ca')
          additional_charge += 4.0 # FedEx Canada has a 4$ pick up fee
        end
        if packages_hash[:container_types].any?(Shipment.container_types.keys[3]) # palleted_crate
          additional_charge += ExchangeRate.convert_currency('CAD', value[:currency_code], Date.current, 250.00) # $CAD250 charged for crating fee by Lumidesign -- as of 6/11/2021
        end
        Rails.logger.debug { "additional_charge: #{additional_charge}" }
        value[:cost] = ((1.0 + get_shipping_surcharge_factor(options[:store], ship_weight, options[:state], is_freight, value[:carrier])) * value[:cost]) + additional_charge # apply surcharge
        # apply handling charge to transportation, and surcharge to both transportation and service options charges
        value[:transportation_charges] = value[:transportation_charges].to_f
        value[:transportation_charges] = ((1.0 + get_shipping_surcharge_factor(options[:store], ship_weight, options[:state], is_freight, value[:carrier])) * value[:transportation_charges]) + additional_charge # apply surcharge
        value[:service_options_charges] = (1.0 + get_shipping_surcharge_factor(options[:store], ship_weight, options[:state], is_freight, value[:carrier])) * value[:service_options_charges].to_f # apply surcharge
      end
      Rails.logger.debug { "AFTER value[:cost]: #{value[:cost]}" }
    end
  end
  shipping_costs
end

.calculate_ups_canada_billing_weight(options) ⇒ Object



2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
# File 'app/services/wy_shipping.rb', line 2158

def self.calculate_ups_canada_billing_weight(options)
  # this was carefully developed to match UPS Canada's formula for billing weight, see: http://www.ups.com/content/us/en/resources/prepare/oversize.html
  # UPS Canada always uses greater of the dimensional weight vs actual weight
  weight = 0.0
  dim_weight = 0.0
  139.0 if options[:service].to_s.downcase.index('express') && Date.strptime(options[:pickup_date], '%m/%d/%Y') >= Date.strptime('1/1/2011', '%m/%d/%Y')
  # assume imperial units, so for e.g. convert lengths to cm, and 166 cubic inch/lb denominator becomes 166*2.54*2.54*2.54 = 2720.252624 cubic cm/lb, 5 lbs = 5*2.20462
  options[:lengths].each_index do |i|
    weight += (options[:weights][i] / 2.20462).round * 2.20462
    dim_weight += (options[:lengths][i] * 2.54).round * (options[:widths][i] * 2.54).round * (options[:heights][i] * 2.54).round / (166.0 * 2.54 * 2.54 * 2.54)
    # puts weight.to_s
    # puts dim_weight.to_s
  end
  [dim_weight.ceil, weight.ceil].max
end

.carrier_exceeds_per_package_weight_limit?(carrier, ship_weights) ⇒ Boolean

Returns true when any package in ship_weights exceeds the carrier's
per-package weight ceiling (see CARRIER_PER_PACKAGE_WEIGHT_LIMIT_LBS).

Carriers without a configured limit always return false — we only filter
carriers we have an authoritative cap for.

Parameters:

  • carrier (String)

    Internal carrier name (e.g. "UPS").

  • ship_weights (Array<Numeric>, Numeric, nil)

    Per-package weights in lbs.

Returns:

  • (Boolean)


93
94
95
96
97
98
# File 'app/services/wy_shipping.rb', line 93

def self.carrier_exceeds_per_package_weight_limit?(carrier, ship_weights)
  limit = CARRIER_PER_PACKAGE_WEIGHT_LIMIT_LBS[carrier]
  return false unless limit

  Array(ship_weights).any? { |w| w.to_f > limit }
end

.check_freightquote_events_for_load_number(delivery) ⇒ Object



2264
2265
2266
2267
2268
# File 'app/services/wy_shipping.rb', line 2264

def self.check_freightquote_events_for_load_number(delivery)
  carrier_class = class_for_carrier('Freightquote')
  shipper = carrier_class.new SHIPPING_BASE_CONFIGURATION.merge(SHIPPING_SHIPPER_CONFIGURATION[delivery.ship_natively_key || delivery.country.iso3.to_sym])
  shipper.check_events_for_load_number(delivery.freight_order_number)
end

.check_freightquote_events_for_pro_number(delivery) ⇒ Object



2270
2271
2272
2273
2274
# File 'app/services/wy_shipping.rb', line 2270

def self.check_freightquote_events_for_pro_number(delivery)
  carrier_class = class_for_carrier('Freightquote')
  shipper = carrier_class.new SHIPPING_BASE_CONFIGURATION.merge(SHIPPING_SHIPPER_CONFIGURATION[delivery.ship_natively_key || delivery.country.iso3.to_sym])
  shipper.check_events_for_pro_number(delivery.freight_order_number)
end

.class_for_carrier(carrier, tracking_number: nil) ⇒ Object

Determines the appropriate carrier class to initialize
With the new naming convention we can't just rely on constantize to always
find the correct class.

shipments.carrier is free-form text in production and frequently
carries the carrier service level baked in ("UPS Standard",
"FedEx Ground®", "Canpar Express", "fedex_international_ground",
"PUROLATOR_GROUND", "Canada Post Expedited Parcel"). Those strings
used to fail "Shipping::<name>".constantize with NameError, which
silently skipped tracking for ~2,300 shipments / year. We normalize
via Heatwave::Normalizers.shipping_carrier here so the dispatch
works regardless of how the carrier name was captured upstream.
Strings the normalizer doesn't recognize are returned untouched, so
any genuinely-unknown carrier keeps surfacing NameError instead of
being silently mis-routed.

When the carrier string can't be normalized (placeholders like
"Override", "Standard", "Shipping override, please confirm") and a
tracking number is provided, falls back to
Heatwave::Normalizers.shipping_carrier_from_tracking_number
matches high-confidence prefixes (UPS 1Z…, USPS international
[A-Z]{2}\d{9}US) to recover the carrier from the tracking number
itself. Amazon Logistics (TBA…) is intentionally NOT in the
sniff set — those need direct SP-API tracking via
Edi::Amazon::ShipWithAmazon#get_tracking, not the ShipEngine path.

Parameters:

  • carrier (String)

    free-form shipments.carrier value

  • tracking_number (String, nil) (defaults to: nil)

    optional tracking number used
    as a fallback when the carrier string is unmappable

Raises:

  • (ArgumentError)


129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'app/services/wy_shipping.rb', line 129

def self.class_for_carrier(carrier, tracking_number: nil)
  raise ArgumentError, "carrier cannot be blank (check that the rate hash includes a 'carrier' key)" if carrier.blank?

  normalized = Heatwave::Normalizers.shipping_carrier(carrier)
  # If name-based normalization left the input unchanged, attempt to
  # recover the carrier from the tracking number's format.
  if tracking_number.present? && normalized == carrier
    sniffed = Heatwave::Normalizers.shipping_carrier_from_tracking_number(tracking_number)
    normalized = sniffed if sniffed
  end

  case normalized
  when 'UPS'
    Shipping::Ups
  when 'USPS'
    Shipping::Usps
  when 'UPSFreight'
    Shipping::UpsFreight
  when 'WalmartSeller'
    Shipping::WalmartSeller
  when 'AmazonSeller'
    Shipping::AmazonSeller
  when 'Amazon Shipping'
    Shipping::AmazonShipping
  else
    "Shipping::#{normalized}".constantize
  end
end

.classify_third_party_billing(delivery) ⇒ Symbol

Decide how a delivery should be billed at carrier label time.

Single decision input: Delivery#third_party_billed? — whether a
ShippingAccountNumber is attached to the chosen shipping method.
Selecting a SAN (auto when the owner's bill_shipping_to_customer makes
it the default, OR manually from the rate-shop dropdown even when it
is off) IS the instruction to bill it, and the attached SAN carries
the account number to bill — no parent/subsidiary flag resolution is
needed. The SAME predicate drives the customer invoice
(Delivery#adjusted_actual_shipping_cost, ShippingCost#calculated_cost)
and the on-screen account labels, so the carrier label, the invoice,
and the views stay aligned by construction.

Returns one of:

  • :third_party — a SAN is attached. Label prints bill_third_party
    against that account; customer invoice shows $0 shipping (the
    customer pays the carrier directly).
  • :native — Canada Post ship_natively flow.
  • :prepaid — no SAN attached. Customer is invoiced for the actual
    shipping cost; label prints prepaid on WarmlyYours's account.

Pure: no side effects on delivery or shipper. Safe to call from
tests without ShipEngine/ActiveShipping setup.

Parameters:

Returns:

  • (Symbol)

    one of :third_party, :native, :prepaid



76
77
78
79
80
81
82
# File 'app/services/wy_shipping.rb', line 76

def self.classify_third_party_billing(delivery)
  return :native if ['Canadapost'].include?(delivery.carrier) && delivery.ship_natively_key.present?

  return :third_party if delivery.third_party_billed? && delivery.ship_natively_key.nil?

  :prepaid
end

.coerce_standalone_stored_rate_data(raw) ⇒ Object



1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
# File 'app/services/wy_shipping.rb', line 1187

def self.coerce_standalone_stored_rate_data(raw)
  return nil if raw.blank?

  parsed = case raw
           when String then JSON.parse(raw)
           when Hash   then raw
           end
  return nil unless parsed.is_a?(Hash)

  parsed.deep_stringify_keys
rescue JSON::ParserError, TypeError
  nil
end

.estimate_shipping_cost(options) ⇒ Object



470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
# File 'app/services/wy_shipping.rb', line 470

def self.estimate_shipping_cost(options)
  delivery = options[:delivery]
  char_limit = 34
  char_limit = 30 if ['FedEx'].include?(delivery.carrier)
  char_limit = 44 if ['Canadapost'].include?(delivery.carrier)
  Rails.logger.debug { "WYSHIPPING#estimate_shipping_cost: options[:insured_value]: #{options[:insured_value]}" }
  status_descriptions = []
  resource_shipping_method = options[:resource_shipping_method]
  shippers = options[:shippers]
  ship_weights = options[:ship_weights]
  saturday_delivery = options[:saturday_delivery]
  ship_dimensions = options[:ship_dimensions]
  flat_rate_package_types = options[:flat_rate_package_types]
  container_types = options[:container_types]
  package_values = options[:package_values]
  is_residential = options[:is_residential]
  signature_confirmation = options[:signature_confirmation]
  myprojects_legacy = options[:myprojects_legacy]
  cod_collection_type = options[:cod_collection_type]
  cod_amount = options[:cod_amount]
  purolator_ltl = options[:purolator_ltl]
  options[:is_domestic]
  origin_address = options[:origin_address]
  media_mail = options[:media_mail]
  # insured_value =  options[:insured_value] # YEESH, every carrier is different because some qualify for Shipsurance and some don't, need to set this within for each shipper options[:insured_value]
  # status_descriptions << "Insured Value of $ #{insured_value.round(2)} used." if insured_value
  # Rails.logger.debug "WyShipping.estimate_shipping_cost: purolator_ltl: #{purolator_ltl}"
  signature_confirmation_option = nil unless signature_confirmation
  signature_confirmation_option = 'signature' if signature_confirmation
  # shipping_costs = [{:status_description=>"", :status_code=>"-1", :rate_request_xml=>"", :rate_response_xml=>""}, {}]
  shipping_costs_status_hash = { status_description: '', status_code: '-1', rate_request_xml: '', rate_response_xml: '' }
  shipping_costs_data_hash = {}
  # Rails.logger.debug "WyShipping.estimate_shipping_cost, shippers: #{shippers}"
  carriers = []

  responses = {}
  rating_errors = {}
  default_box_size = Packaging::DEFAULT_BOX_SIZE

  start_time = Time.current
  Rails.logger.debug { "TIMING! WyShipping.estimate_shipping_cost, time START: #{start_time}" }
  # Quote every carrier in parallel — each shipper runs on its own thread,
  # wrapped in the Rails executor by Heatwave::Parallel so ActiveRecord
  # connections and the query cache are managed correctly. Each block returns
  # its own result hash rather than mutating shared state, so there is no
  # cross-thread data race on `responses` / `rating_errors` / `status_descriptions`.
  #
  # Resolve customs line items up front, on the main thread: each worker would
  # otherwise lazy-load the `delivery.line_items` association (and every
  # line_item's `item`) concurrently, racing on the shared AR connection.
  customs_line_items = nil
  if delivery.present?
    # Use `delivery.line_items` + in-memory `select` (not a scope): this runs
    # inside the before_save callback path, where scopes re-query and can
    # yield empty arrays — especially for store transfers.
    customs_lis = delivery.line_items.select { |li| li.tax_class == 'g' && li.parent_id.nil? }
    # AppSignal #4681: ShipEngine rejects customs items with missing quantity. Skip lines whose
    # quantity isn't a positive integer (typically in-memory/unsaved lines reaching this code via
    # the before_save path) and report the upstream anomaly so the real source — not the customs
    # payload — gets fixed. Defaulting to 1 here would silently ship incorrect declarations.
    invalid_qty_lis, customs_lis = customs_lis.partition { |li| li.quantity.to_i <= 0 }
    if invalid_qty_lis.any?
      ErrorReporting.warning(
        "WyShipping: skipping #{invalid_qty_lis.size} customs line item(s) with non-positive quantity",
        {
          delivery_id: delivery.id,
          line_item_ids: invalid_qty_lis.map(&:id),
          skus: invalid_qty_lis.map(&:sku),
          quantities: invalid_qty_lis.map(&:quantity)
        }
      )
    end
    customs_lis.each(&:item) # warm the belongs_to :item cache so worker threads only read it
    customs_line_items = customs_lis
  end
  parallel_results = Heatwave::Parallel.map(shippers) do |shipper|
    start_time_shipper = Time.current
    carrier = shipper.class.to_s.split('::').last # yikes, but need carrier
    Rails.logger.debug { "TIMING! WyShipping.estimate_shipping_cost, shipper: #{carrier}, time START: #{start_time_shipper}" }
    Rails.logger.debug { "WyShipping.estimate_shipping_cost, shipper: #{shipper}" }
    packages = []
    response = nil
    rating_error = nil
    status_description = nil

    # Normalize to an array in a block-local — the method-level `ship_weights`
    # is shared across the worker threads and must not be reassigned here.
    shipper_ship_weights = ship_weights.is_a?(Array) ? ship_weights : [ship_weights]

    shipper_ship_weights.each_index do |i|
      dims = default_box_size # nominal default box size for simple shipments
      dims = ship_dimensions[i] unless ship_dimensions.empty?
      packages << Shipping::Package.new(shipper_ship_weights[i] * 16, # lbs, times 16 oz/lb.
                                        dims.reverse, # HxWxL inches
                                        pallet: %w[pallet palleted_crate].include?(container_types[i]), crate: container_types[i] == 'crate', units: :imperial, value: package_values[i], flat_rate_package_type: (begin
                                          flat_rate_package_types[i]
                                        rescue StandardError
                                          nil
                                        end), nmfc_code: ProductCategoryConstants::FALLBACK_NMFC_CODE) # not grams, not centimetres
      Rails.logger.debug { "WyShipping.estimate_shipping_cost, packages[i].inspect:#{packages[i].inspect}" }
    end

    begin
      shipper.packages = packages.sort_by(&:lbs).reverse # may as well sort by heaviest here
      raise Shipping::ShippingRatingError, 'package dimensions are not defined!' if ship_dimensions.empty?

      shipper.saturday_delivery = saturday_delivery
      shipper.signature_confirmation = signature_confirmation_option
      shipper.cod_collection_type = cod_collection_type
      shipper.cod_amount = cod_amount unless cod_collection_type.nil?
      shipper.negotiated_rates = true
      shipper.media_mail = media_mail if media_mail
      insured_value = options[:insured_value]
      insured_value = 0.0 if Shipping::ShippingInsurance.new.carrier_qualifies_for_rating?(carrier) || MARKETPLACE_CARRIERS.include?(carrier)
      shipper.insured_value = insured_value.abs if insured_value.present?

      if customs_line_items
        # `customs_line_items` was resolved on the main thread above; the
        # worker only reads it (and the already-warmed `li.item`) — no
        # association lazy-loads race here.
        shipper.line_items = customs_line_items.map do |li|
          {
            description: li.item.name.to_s.gsub(/[^0-9a-z ]/i, '')&.first(char_limit),
            detailed_description: (li.item.short_description || li.item.name).to_s.gsub(/[^0-9a-z ]/i, '')&.first(450), # FedEx requires detailed description up to 450 characters
            quantity: li.quantity,
            price: [li.discounted_price, li.unit_cogs.to_f].max,
            part_number: li.item.sku.to_s.gsub(/[^0-9a-z -_.]/i, ''),
            origin_country_code: (li.item.coo.to_s.strip.blank? ? 'CN' : li.item.coo.to_s.strip.first(2)),
            commodity_code: li.item.harmonization_code,
            weight: get_weight_by_country_units(li.item.base_weight || 0.01, shipper.sender_country),
            edi_line_number: li.edi_line_number,
            edi_reference: li.edi_reference
          }
        end
      end
      response = if (shipper.is_a?(Shipping::Canadapost) || shipper.is_a?(Shipping::Usps)) && shipper.packages.size > 1
                   find_shipengine_postal_mps_rates(shipper, shipper.packages)
                 else
                   shipper.find_rates
                 end
    rescue Shipping::ShippingRatingError => e
      response = nil
      rating_error = e.message
      Rails.logger.warn("#{shipper} rating exception", error: e.message)
      ErrorReporting.warning(e)
      status_description = e.to_s if e.present? && e.to_s.present?
    rescue *Retryable::TIMEOUT_CLASSES => e
      response = nil
      rating_error = e.message
      Rails.logger.warn("#{shipper} rating timeout", error: e.message)
      ErrorReporting.warning(e, { carrier: })
      status_description = e.to_s if e.present? && e.to_s.present?
    rescue StandardError => e
      response = nil
      rating_error = e.message
      Rails.logger.error "#{shipper} rating exception: #{e.inspect}"
      ErrorReporting.error(e)
      status_description = e.to_s if e.present? && e.to_s.present?
    end
    end_time_shipper = Time.current
    Rails.logger.debug { "TIMING! WyShipping.estimate_shipping_cost, shipper: #{carrier}, time END: #{end_time_shipper}, processing time = #{end_time_shipper - start_time_shipper}" }
    { carrier:, response:, rating_error:, status_description: }
  end

  # Fold the per-thread results back into the method-level collections on the
  # main thread, keeping those Hash/Array writes single-threaded.
  parallel_results.each do |result|
    responses[result[:carrier]] = result[:response]
    rating_errors[result[:carrier]] = result[:rating_error] if result[:rating_error]
    status_descriptions << result[:status_description] if result[:status_description]
  end
  end_time = Time.current
  Rails.logger.debug { "TIMING! WyShipping.estimate_shipping_cost, time END: #{end_time}, processing time = #{end_time - start_time}" }

  shippers.each_with_index do |shipper, _i|
    carrier = shipper.class.to_s.split('::').last # yikes, but need list of carriers
    response = responses[carrier]
    if response&.success
      carriers << carrier
      shipping_costs_status_hash[:rate_request_xml] = "#{shipping_costs_status_hash[:rate_request_xml]}\n#{response.request}"
      shipping_costs_status_hash[:rate_response_xml] = "#{shipping_costs_status_hash[:rate_response_xml]}\n#{response.xml}"
      shipping_costs_status_hash[:status_code] = '1'
      service_codes_used = []
      shipping_options = ShippingOption.active.where(country: shipper.sender_country)
      allowed_codes = Array(options[:limit_service_codes]).compact
      catalog_for_exclusion = options[:catalog]
      response.rates.each do |rate|
        # When restricting RMAs to specific service codes, skip non-matching rates
        next if allowed_codes.present? && rate.service_code.present? && allowed_codes.exclude?(rate.service_code)

        # Catalog-level marketplace carrier exclusions (SWW/AMZBS sub-carrier filtering)
        if catalog_for_exclusion && rate.service_code.present? && catalog_for_exclusion.marketplace_rate_excluded?(rate.service_code)
          Rails.logger.debug { "Catalog #{catalog_for_exclusion.id} excluded marketplace rate: #{rate.service_code}" }
          next
        end

        Rails.logger.debug { "finding shipping option for: #{rate.service_code}" }
        # Prefer a ShippingOption whose carrier matches this shipper. Multiple rows can
        # share a service_code (e.g. legacy 'saia_std' and ShipEngine 'SAIA5700' both
        # carry service_code 'SAIA5700' but live under carriers 'Saia' vs 'ShipengineSaia');
        # without the carrier predicate the legacy row wins by id order and a ShipEngine
        # rate gets attributed to the legacy carrier, breaking BETA-panel partitioning
        # and surcharge lookup.
        shipping_option = shipping_options.find { |so| (rate.service_code == so.service_code) && so.carrier == carrier && service_codes_used.exclude?(rate.service_code) }
        shipping_option ||= shipping_options.find { |so| (rate.service_code == so.service_code) && service_codes_used.exclude?(rate.service_code) }
        shipping_option ||= shipping_options.find { |so| so.carrier == 'Freightquote' && options[:is_freight] }
        notify_missing_marketplace_shipping_option(rate, carrier, shipper.sender_country) if shipping_option.nil? && MARKETPLACE_CARRIERS.include?(carrier)
        next unless shipping_option

        Rails.logger.debug { "response found shipping option: rate.inspect: #{rate.inspect}" }
        shipping_costs_data_hash[(rate.service_code || shipping_option.name).to_sym] = {
          option_name: shipping_option.name.to_sym,
          cost: rate.price,
          transportation_charges: rate.transportation_charges,
          service_options_charges: rate.service_options_charges,
          insured_value: rate.insured_value,
          currency_code: rate.currency,
          service_name: shipping_option.description,
          service_code: rate.service_code || shipping_option.service_code,
          rate_data: rate[:rate_data],
          third_party: false,
          carrier: shipping_option.carrier
        }
        service_codes_used << rate.service_code
        Rails.logger.debug { "response FOUND: #{shipping_option.name}: #{rate.price}" }
      end
    else
      if response.respond_to?(:[], true) && response[:exclusion_reason].present?
        Rails.logger.info "#{shipper} excluded: #{response[:exclusion_reason]}"
        status_descriptions << response[:exclusion_reason]
        (shipping_costs_status_hash[:ltl_exclusion_reasons] ||= []) << response[:exclusion_reason]
      else
        Rails.logger.info "#{shipper} rating failed: #{response.try(:message)}"
        status_descriptions << response.try(:message) if response.try(:message).present?
      end

      notify_marketplace_api_failure(carrier, response.try(:message).presence || rating_errors[carrier], options[:delivery]) if MARKETPLACE_CARRIERS.include?(carrier)
    end

    next unless MARKETPLACE_CARRIERS.include?(carrier) && shipper.respond_to?(:api_log) && shipper.api_log.present?

    order = options[:delivery]&.order
    if order.respond_to?(:merge_shipper_api_log)
      order.merge_shipper_api_log(shipper)
      order.save_early_label_api_log
    end
  end

  ShippingOption.get_appropriate(origin_address.country.iso, is_residential, purolator_ltl).each do |shipping_option|
    Rails.logger.debug { "finding 3rd party shipping option: #{shipping_option.description}: #{shipping_option.name}" }
    # next unless shipping_option.is_third_party_only && shipping_costs_data_hash[EQUIVALENT_3RD_PARTY_SHIPPING_COST[shipping_option.name.to_sym]] && !carriers.include?(shipping_option.carrier) && !myprojects_legacy

    skip = true
    if shippers.any? && shipping_option.is_third_party_only && (shipping_costs_data_hash[EQUIVALENT_3RD_PARTY_SHIPPING_COST[shipping_option.name.to_sym]] || (resource_shipping_method.present? && shipping_option.name == resource_shipping_method)) && carriers.exclude?(shipping_option.carrier) && !myprojects_legacy
      skip = false
    end

    # skip unless this is a third party shipping option, supported for ST and this is not domestic, or if we want an equivalent shipping cost for this
    next if skip
    # check to make sure there isn't already something in there for this shipping option or it will get overwritten by $0.00 cost
    next if shipping_costs_data_hash[shipping_option.name.to_sym]

    currency_code = Country.where(iso: shippers.first.country).first&.currency_code || 'USD'

    Rails.logger.debug { "NOT FOUND: #{shipping_option.name}" }
    Rails.logger.debug { "adding third party shipping options: #{shipping_option.name}" }
    shipping_costs_data_hash[shipping_option.name.to_sym] =
      { option_name: shipping_option.name.to_sym, cost: get_equivalent_cost_from_ups(shipping_option.name.to_sym, shipping_costs_data_hash), currency_code: currency_code, service_name: shipping_option.description,
        service_code: shipping_option.service_code, third_party: true, carrier: shipping_option.carrier }
  end
  shipping_costs_status_hash[:status_description] = status_descriptions.join(' ')
  [shipping_costs_status_hash, shipping_costs_data_hash]
end

.find_mail_activity_shipping_rates(mail_activity) ⇒ Object



909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
# File 'app/services/wy_shipping.rb', line 909

def self.find_mail_activity_shipping_rates(mail_activity)
  all_rates = []
  errors = []
  country_key = mail_activity.store_country_iso3 || 'USA'

  # Start with the default postal carrier (USPS or Canadapost)
  carriers_to_query = [mail_activity.default_carrier] + (MAILING_EXTRA_CARRIERS[country_key] || [])

  carriers_to_query.each do |carrier_name|
    shipper = populate_shipper_data_for(mail_activity, carrier_override: carrier_name)
    # Only enable first-class mail options for postal carriers
    shipper.include_first_class_mail_options = true if carrier_name.in?(%w[USPS Canadapost])
    rates_result = shipper.find_rates
    rates = rates_result[:rates] || []

    # Filter non-postal carriers to ground-only service codes
    ground_codes = MAILING_GROUND_SERVICE_CODES[carrier_name]
    rates = rates.select { |r| ground_codes.include?(r[:service_code]) } if ground_codes

    # Encode composite service_code: "CarrierName::RawServiceCode" so we can
    # resolve the carrier later when generating labels or voiding
    rates.each do |r|
      r[:service_code] = "#{carrier_name}::#{r[:service_code]}"
      r[:service_name] = "#{carrier_name}: #{r[:service_name]}" unless r[:service_name]&.start_with?(carrier_name)
    end

    all_rates.concat(rates)
  rescue StandardError => e
    errors << "#{carrier_name}: #{e.message}"
    Rails.logger.warn("[Mailing] Failed to get #{carrier_name} rates for mail_activity #{mail_activity.id}: #{e.message}")
  end

  if all_rates.any?
    { status_code: :ok, status_message: '', request_response: { rates: all_rates } }
  else
    { status_code: :error, status_message: "No postal rates found. #{errors.join('; ')}" }
  end
end

.find_shipengine_postal_mps_rates(shipper, packages) ⇒ Object



744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
# File 'app/services/wy_shipping.rb', line 744

def self.find_shipengine_postal_mps_rates(shipper, packages)
  begin
    # Quote each package on its own Rails-executor-wrapped thread; `dup`
    # gives every thread an independent shipper (and ShipEngine client).
    rate_responses = Heatwave::Parallel.map(packages) do |package|
      pkg_shipper = shipper.dup
      pkg_shipper.packages = [package]
      pkg_shipper.find_rates
    end
  rescue *Retryable::TIMEOUT_CLASSES => e
    ErrorReporting.warning(e, { carrier: shipper.class.to_s.split('::').last, package_count: packages.size })
    failed = { success: false, message: "Carrier timeout: #{e.message}", request: '', xml: '', rates: [] }
    def failed.method_missing(name, *args) = key?(name) ? self[name] : super
    return failed
  end
  mps_response = {}
  mps_response[:success] = rate_responses.all? { |r| r[:success] == true }
  mps_response[:message] = rate_responses.pluck(:message).join('. ')
  mps_response[:request] = rate_responses.pluck(:request).join(' | ')
  mps_response[:xml] = rate_responses.pluck(:xml).join(' | ')
  mps_rates = []
  rate_responses.each do |response|
    # estimate = {}
    # estimate[:service_code] = hw_service_code
    # 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] = currency.upcase
    # estimate[:rate_data] = rate_hash[:rate_data]
    response[:rates].each do |estimate|
      if (mps_rate = mps_rates.find { |mps_estimate| mps_estimate[:service_code] == estimate[:service_code] }).present?
        mps_rate[:price] += estimate[:price]
        mps_rate[:total_charges] += estimate[:total_charges]
        mps_rate[:transportation_charges] += estimate[:transportation_charges]
        mps_rate[:service_options_charges] += estimate[:service_options_charges]
        mps_rate[:insured_value] += estimate[:insured_value]
      else
        mps_rate = {}
        mps_rate[:service_code] = estimate[:service_code]
        mps_rate[:price] = estimate[:price]
        mps_rate[:total_charges] = estimate[:total_charges]
        mps_rate[:transportation_charges] = estimate[:transportation_charges]
        mps_rate[:service_options_charges] = estimate[:service_options_charges]
        mps_rate[:insured_value] = estimate[:insured_value]
        mps_rate[:currency] = estimate[:currency]
        mps_rate[:rate_data] = estimate[:rate_data]
        # allows for things like mps_rate.service_code
        def mps_rate.method_missing(name, *args)
          key?(name) ? self[name] : super
        end
        mps_rates << mps_rate
      end
    end
  end
  mps_response[:rates] = mps_rates
  # allows for things like shipper.success?
  def mps_response.method_missing(name, *args)
    key?(name) ? self[name] : super
  end
  mps_response
end

.find_standalone_delivery_shipping_rates(standalone_delivery) ⇒ Object



1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
# File 'app/services/wy_shipping.rb', line 1035

def self.find_standalone_delivery_shipping_rates(standalone_delivery)
  all_rate_results = []
  SUPPORTED_SHIPPING_CARRIERS[standalone_delivery.origin_address.country_iso3.to_sym].each do |carrier|
    status_code = :ok
    status_message = ''
    rates_result = nil
    shipper = populate_shipper_data_for_standalone_delivery(standalone_delivery, carrier)
    begin
      rates_result = shipper.find_rates
    rescue StandardError => e
      status_code = :error
      status_message = e.to_s
      { status_code: status_code, status_message: "Shipping Rates Error: #{status_message}" }
    end
    res = { status_code: status_code, status_message: status_message, request_response: rates_result }
    all_rate_results << res
  end
  all_rate_results
end

.freightquote_cancel_event_present?(freight_order_number, since_time) ⇒ Boolean

Standalone poll of CHR /v2/events for a LOAD CANCELLED / ORDER
CANCELED echo of a void we issued. Takes a raw order_number rather
than a Delivery so FreightquoteVoidConfirmationWorker can call it
without resolving the delivery row (which may have been deleted or
mutated since the void). Defaults to the USA shipper config — the
events GET endpoint doesn't actually use any of the sender-address
fields, so country choice here is immaterial.

Returns:

  • (Boolean)


2325
2326
2327
2328
2329
# File 'app/services/wy_shipping.rb', line 2325

def self.freightquote_cancel_event_present?(freight_order_number, since_time)
  carrier_class = class_for_carrier('Freightquote')
  shipper = carrier_class.new(SHIPPING_BASE_CONFIGURATION.merge(SHIPPING_SHIPPER_CONFIGURATION[:USA]))
  shipper.cancel_event_present?(freight_order_number, since_time)
end

.get_equivalent_cost_from_ups(shipping_option_sym, shipping_costs_hash) ⇒ Object



808
809
810
811
812
813
814
815
# File 'app/services/wy_shipping.rb', line 808

def self.get_equivalent_cost_from_ups(shipping_option_sym, shipping_costs_hash)
  cost = (begin
    shipping_costs_hash[EQUIVALENT_3RD_PARTY_SHIPPING_COST[shipping_option_sym]][:cost]
  rescue StandardError
    nil
  end) || 0.0
  cost * 1.1 # add 10% to get Purolator to show as cheaper option
end

.get_shipping_surcharge_factor(store, _ship_weight, _destination_state, is_freight, carrier = nil) ⇒ Object



464
465
466
467
468
# File 'app/services/wy_shipping.rb', line 464

def self.get_shipping_surcharge_factor(store, _ship_weight, _destination_state, is_freight, carrier = nil)
  surcharge_percentage = SHIPPING_SURCHARGE_PERCENT_BY_CARRIER[store&.country&.iso3&.upcase]&.dig(carrier) || SHIPPING_SURCHARGE_PERCENT
  surcharge_percentage = SHIPPING_LTL_FREIGHT_SURCHARGE_PERCENT_BY_CARRIER[store&.country&.iso3&.upcase]&.dig(carrier) || SHIPPING_LTL_FREIGHT_SURCHARGE_PERCENT if is_freight
  surcharge_percentage / 100.0
end

.get_weight_by_country_units(weight_in_lbs, sender_country) ⇒ Object



2252
2253
2254
2255
2256
2257
2258
# File 'app/services/wy_shipping.rb', line 2252

def self.get_weight_by_country_units(weight_in_lbs, sender_country)
  if sender_country == 'CA'
    weight_in_lbs * 0.455 # return weight in KG
  else
    weight_in_lbs
  end
end

.is_address_residential?(address) ⇒ Boolean

Returns:

  • (Boolean)


888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
# File 'app/services/wy_shipping.rb', line 888

def self.is_address_residential?(address)
  res_address_residential = address.is_residential # default to whatever it is set to unless we specifically get a mismatch
  force_carrier = 'UPS' # UPS returns a solid answer for US addresses
  force_carrier = 'Purolator' if address.country_iso3 == 'CAN' # Purolator now returns a solid answer for Canadian addresses
  res_validation = WyShipping.valid_address?(address, force_carrier)
  if address.is_residential == true && # be conservative here and tend to residential unless all suggested addressed say address_residential_indicator 'no'
     res_validation[:suggested_address_hashes].all? do |ah|
       ah['address_residential_indicator'] == 'no'
     end
    res_address_residential = false
    Rails.logger.debug { "is_address_residential?, mismatch setting res_address_residential to: #{res_address_residential}" }
  elsif address.is_residential == false && # be conservative here and tend to residential if any suggested addressed say address_residential_indicator 'yes'
        res_validation[:suggested_address_hashes].any? do |ah|
          ah['address_residential_indicator'] == 'yes'
        end
    res_address_residential = true
    Rails.logger.debug { "is_address_residential?, mismatch setting res_address_residential to: #{res_address_residential}" }
  end
  res_address_residential
end

.marketplace_log_requests(api_log) ⇒ Object

Pluck the request side of every captured API call so Delivery#shipping_api_log
has the exact JSON we sent — UUIDs, VAS, document specs, package dims — for
post-hoc debugging of carrier rejections.



1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
# File 'app/services/wy_shipping.rb', line 1717

def self.marketplace_log_requests(api_log)
  Array(api_log).map do |entry|
    entry = entry.with_indifferent_access if entry.respond_to?(:with_indifferent_access)
    {
      operation: entry[:operation],
      method: entry[:method],
      url: entry[:url],
      payload: entry[:request_payload],
      timestamp: entry[:timestamp]
    }.compact
  end
end

.marketplace_log_responses(api_log) ⇒ Object



1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
# File 'app/services/wy_shipping.rb', line 1730

def self.marketplace_log_responses(api_log)
  Array(api_log).map do |entry|
    entry = entry.with_indifferent_access if entry.respond_to?(:with_indifferent_access)
    {
      operation: entry[:operation],
      status: entry[:response_status],
      body: entry[:response_body],
      success: entry[:success],
      error: entry[:error]
    }.compact
  end
end

.notify_missing_marketplace_shipping_option(rate, carrier, country) ⇒ Object

Notify the team when a marketplace carrier returns a rate with a service code
that has no matching ShippingOption record. The rate is skipped (not shown to the user)
until an admin reviews and approves the new shipping option via the approval link.



2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
# File 'app/services/wy_shipping.rb', line 2334

def self.notify_missing_marketplace_shipping_option(rate, carrier, country)
  service_code = rate.service_code
  return if service_code.blank?

  cache_key = "missing_marketplace_so:#{carrier}:#{service_code}:#{country}"
  return if Rails.cache.read(cache_key)

  Rails.cache.write(cache_key, true, expires_in: 1.hour)

  description = rate.try(:service_name) || service_code
  days_in_transit = rate.try(:days_in_transit)
  Rails.logger.warn("[WyShipping] Missing marketplace ShippingOption: carrier=#{carrier} service_code=#{service_code} country=#{country} description=#{description}")

  approval_url = build_approval_url(
    carrier: carrier,
    service_code: service_code,
    description: description,
    country: country,
    days_in_transit: days_in_transit
  )

  SystemMailer.generic_mailer(
    subject: "Action Required: New #{carrier} shipping service — #{description} (#{service_code})",
    body: <<~MSG,
      A #{carrier} rate was returned by the marketplace API but has no matching
      ShippingOption record in Heatwave. This rate is being SKIPPED for customers
      until an admin approves it.

      ── Rate Details ────────────────────────────────────────

      Carrier:        #{carrier}
      Service Code:   #{service_code}
      Description:    #{description}
      Country:        #{country}
      Transit Days:   #{days_in_transit || 'unknown'}

      ── What Will Be Created ────────────────────────────────

      Item:
        SKU:              #{service_code.upcase}
        Name:             #{carrier} #{description}
        Tax Class:        shp
        Product Category: Shipping and Handling (66)

      Shipping Option:
        Name:             #{service_code.downcase}
        Description:      #{description}
        Carrier:          #{carrier}
        Service Code:     #{service_code}
        Country:          #{country}
        Days Commitment:  #{days_in_transit || 5.0}

      ── Approve or Dismiss ──────────────────────────────────

      Review and approve this shipping option (admin login required):
      #{approval_url}

      This link expires in 7 days. Only administrators can approve.
    MSG
    to: ADMINISTRATOR_EMAIL,
    from: ADMINISTRATOR_EMAIL
  ).deliver_later
rescue StandardError => e
  Rails.logger.error("[WyShipping] Failed to send missing ShippingOption notification: #{e.message}")
end

.populate_origin_sender_data(shipper_config:, address: nil, phone: nil, char_limit: 34) ⇒ Object



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
# File 'app/services/wy_shipping.rb', line 158

def self.populate_origin_sender_data(shipper_config:, address: nil, phone: nil, char_limit: 34)
  origin = {}
  if address.present?
    origin[:sender_attention_name] = address.person_name.to_s.gsub(/\P{ASCII}/u, '').gsub(%r{[^0-9a-z -_.,/\s]}i, '')&.first(char_limit) if address.person_name.present?
    origin[:sender_attention_name] ||= address.company_name.to_s.gsub(/\P{ASCII}/u, '').gsub(%r{[^0-9a-z -_.,/\s]}i, '')&.first(char_limit) if address.company_name.present?
    origin[:sender_attention_name] ||= shipper_config[:shipper_attention_name] # yeesh, deal with empty person_name as it seems to be for some warehouse addresses, Shipengine wants ship from to have name populated
    origin[:sender_company] = address.company_name.present? ? address.company_name.to_s.gsub(/\P{ASCII}/u, '').gsub(%r{[^0-9a-z -_.,/\s]}i, '')&.first(char_limit) : origin[:sender_attention_name]
    origin[:sender_address] = address.street1
    origin[:sender_address2] = address.street2
    origin[:sender_city] = address.city
    origin[:sender_state] = address.state_code
    origin[:sender_country] = address.country_iso
    origin[:sender_zip] = address.zip
    origin[:sender_address_residential] = address.is_residential
    origin[:sender_country] = address.country_iso
    origin[:sender_has_loading_dock] = address.has_loading_dock
    origin[:sender_is_construction_site] = address.is_construction_site
    origin[:sender_requires_inside_delivery] = address.requires_inside_delivery
    origin[:sender_is_trade_show] = address.is_trade_show
    origin[:sender_requires_liftgate] = address.requires_liftgate
    origin[:sender_limited_access] = address.limited_access
    origin[:sender_requires_appointment] = address.requires_appointment
    origin[:sender_timezone] = address.timezone_name
  else
    origin[:sender_attention_name] = shipper_config[:shipper_attention_name]
    origin[:sender_company] = shipper_config[:shipper_company]
    origin[:sender_address] = shipper_config[:shipper_address]
    origin[:sender_address2] = shipper_config[:shipper_address2]
    origin[:sender_city] = shipper_config[:shipper_city]
    origin[:sender_state] = shipper_config[:shipper_state]
    origin[:sender_country] = shipper_config[:shipper_country]
    origin[:sender_zip] = shipper_config[:shipper_zip]
    origin[:sender_address_residential] = shipper_config[:shipper_address_residential]
    origin[:sender_country] = shipper_config[:shipper_country]
    origin[:sender_has_loading_dock] = shipper_config[:shipper_has_loading_dock]
    origin[:sender_is_construction_site] = shipper_config[:shipper_is_construction_site]
    origin[:sender_requires_inside_delivery] = shipper_config[:shipper_requires_inside_delivery]
    origin[:sender_is_trade_show] = shipper_config[:shipper_is_trade_show]
    origin[:sender_requires_liftgate] = shipper_config[:shipper_requires_liftgate]
    origin[:sender_limited_access] = shipper_config[:shipper_limited_access]
    origin[:sender_requires_appointment] = shipper_config[:shipper_requires_appointment]
    origin[:sender_timezone] = shipper_config[:shipper_country] == 'CA' ? 'America/Toronto' : 'America/Chicago'
  end
  origin[:sender_phone] = sanitize_phone(phone) || shipper_config[:shipper_phone] # yeesh, Shipengine wants ship from to have phone populated
  origin[:sender_email] = shipper_config[:shipper_email]
  origin
end

.populate_shipper_data_for(mail_activity, carrier_override: nil) ⇒ Shipping::Base

Build a shipper instance for a mail activity.

Parameters:

  • mail_activity (MailActivity)
  • carrier_override (String, nil) (defaults to: nil)

    Carrier name to use instead of mail_activity.carrier
    (used when fetching rates from multiple carriers)

Returns:



996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
# File 'app/services/wy_shipping.rb', line 996

def self.populate_shipper_data_for(mail_activity, carrier_override: nil)
  carrier_name = carrier_override || mail_activity.carrier
  shipper_config = SHIPPING_BASE_CONFIGURATION.merge(SHIPPING_SHIPPER_CONFIGURATION[(mail_activity.store_country_iso3 || 'USA').to_sym])
  origin = populate_origin_sender_data(shipper_config: shipper_config)
  carrier_class = class_for_carrier(carrier_name)
  shipper = carrier_class.new shipper_config.merge(origin)

  shipper.company = mail_activity.company_name
  shipper.attention_name = mail_activity.person_name
  shipper.zip = mail_activity.address.zip_compact.to_s.upcase.strip.squeeze(' ')
  shipper.address = mail_activity.address.street1
  shipper.address2 = mail_activity.address.street2
  shipper.city = mail_activity.address.city
  shipper.state = mail_activity.address.state_code
  shipper.country = mail_activity.address.country.iso
  shipper.address_residential = is_address_residential?(mail_activity.address) # here we test this and override what is saved in the address
  # shipper.media_mail = true # apparently only for educational materials, see:https://about.usps.com/notices/not121/not121_tech.htm

  assigned_resource = mail_activity.activity.assigned_resource
  shipper.sender_attention_name = assigned_resource.name.to_s.gsub(/[^0-9a-z\s]/i, '')[0..34]
  shipper.sender_company = 'WarmlyYours' # company and name are simply aliases
  shipper.sender_phone = sanitize_phone(assigned_resource&.phone) || '8475407775'
  shipper.sender_email = assigned_resource.email
  # Use the raw service code (without carrier prefix) for the shipper
  shipper.service_code = mail_activity.selected_service_code

  shipper.negotiated_rates = true

  packages = []
  total_weight = 0
  mail_activity.shipments.awaiting_label.order('shipments.id ASC').each do |shipment|
    packages << Shipping::Package.new(shipment.weight * 16, [shipment.height, shipment.width, shipment.length], shipment_id: shipment.id, units: :imperial, flat_rate_package_type: shipment.flat_rate_package_type)
    total_weight += shipment.weight * 16
  end
  shipper.packages = packages.sort_by(&:lbs).reverse # may as well sort by heaviest here

  shipper
end

.populate_shipper_data_for_standalone_delivery(standalone_delivery, carrier) ⇒ Object



1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
# File 'app/services/wy_shipping.rb', line 1108

def self.populate_shipper_data_for_standalone_delivery(standalone_delivery, carrier)
  shipper_config = SHIPPING_BASE_CONFIGURATION.merge(SHIPPING_SHIPPER_CONFIGURATION[(standalone_delivery.store_country_iso3 || 'USA').to_sym])
  origin = populate_origin_sender_data(address: standalone_delivery.origin_address, shipper_config: shipper_config)
  carrier_class = class_for_carrier(carrier)
  shipper = carrier_class.new shipper_config.merge(origin)

  shipper.company = standalone_delivery.company_name
  shipper.attention_name = standalone_delivery.person_name
  shipper.zip = standalone_delivery.destination_address.zip_compact.to_s.upcase.strip.squeeze(' ')
  shipper.address = standalone_delivery.destination_address.street1
  shipper.address2 = standalone_delivery.destination_address.street2
  shipper.city = standalone_delivery.destination_address.city
  shipper.state = standalone_delivery.destination_address.state_code
  shipper.country = standalone_delivery.destination_address.country.iso
  shipper.address_residential = is_address_residential?(standalone_delivery.destination_address) # here we test this and override what is saved in the address

  # shipper.sender_phone = sanitize_phone(standalone_delivery.updater&.phone) || '8475407775'
  # shipper.sender_email = standalone_delivery.updater.email
  shipper.service_code = standalone_delivery.service_code

  shipper.negotiated_rates = true

  shipper.reference_number_1 = "STANDALONE #{standalone_delivery.updater.try(:show_name_4)}"
  shipper.reference_number_2 = standalone_delivery.reference_number

  packages = []
  total_weight = 0
  standalone_delivery.shipments.awaiting_label.order('shipments.id ASC').each do |shipment|
    packages << Shipping::Package.new(shipment.weight * 16, [shipment.height, shipment.width, shipment.length], container_code: shipment.reference_number, shipment_id: shipment.id, units: :imperial,
flat_rate_package_type: shipment.flat_rate_package_type)
    total_weight += shipment.weight * 16
  end
  shipper.packages = packages.sort_by(&:lbs).reverse # may as well sort by heaviest here

  assign_standalone_shipper_rate_extras!(shipper, standalone_delivery, carrier)

  shipper
end

.refresh_amzbs_rates_if_stale(delivery, selected_shipping_cost) ⇒ ShippingCost

Re-fetch Amazon Buy Shipping rates when the stored request_token is older
than AMZBS_TOKEN_STALE_THRESHOLD_MINUTES. Tokens expire after ~10 minutes;
an 8-minute threshold gives a 2-minute safety margin.

Parameters:

Returns:

  • (ShippingCost)

    the original or refreshed shipping cost



1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
# File 'app/services/wy_shipping.rb', line 1753

def self.refresh_amzbs_rates_if_stale(delivery, selected_shipping_cost)
  return selected_shipping_cost if selected_shipping_cost&.rate_data.blank?

  rate_data = selected_shipping_cost.rate_data
  rate_data = rate_data.with_indifferent_access if rate_data.respond_to?(:with_indifferent_access)
  return selected_shipping_cost if rate_data[:amz_request_token].blank?

  age_minutes = ((Time.current - selected_shipping_cost.updated_at) / 60.0).round(1)
  return selected_shipping_cost if age_minutes < AMZBS_TOKEN_STALE_THRESHOLD_MINUTES

  Rails.logger.info("[AMZBS] Rate token is #{age_minutes} min old (>#{AMZBS_TOKEN_STALE_THRESHOLD_MINUTES} min threshold). Auto-refreshing rates for delivery #{delivery.id}")
  delivery.retrieve_shipping_costs
  delivery.reload

  refreshed = delivery.selected_shipping_cost
  if refreshed&.rate_data.present?
    Rails.logger.info("[AMZBS] Rates refreshed successfully for delivery #{delivery.id}. New shipping cost id=#{refreshed.id}")
  else
    Rails.logger.error("[AMZBS] Rate refresh failed for delivery #{delivery.id} — no selected_shipping_cost after refresh")
  end

  refreshed
end

.rl_carriers_tracking(delivery) ⇒ ActiveSupport::HashWithIndifferentAccess?

Poll R&L Carriers' Shipment Tracing SOAP service for a direct-R&L freight
delivery's PRO (its master_tracking_number / WebProNumber). Returns the
trace payload (HashWithIndifferentAccess) or nil for non-R&L / no-PRO /
error. Only the API key is needed, so the bare SHIPPING_BASE_CONFIGURATION
is sufficient.

Parameters:

Returns:

  • (ActiveSupport::HashWithIndifferentAccess, nil)


2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
# File 'app/services/wy_shipping.rb', line 2305

def self.rl_carriers_tracking(delivery)
  return nil unless delivery.shipping_option&.carrier == Shipping::RlCarriersTracker::CARRIER

  pro = delivery.master_tracking_number
  return nil if pro.blank?

  class_for_carrier('RlCarriers').new(SHIPPING_BASE_CONFIGURATION).trace_shipment(pro)
rescue StandardError => e
  Rails.logger.warn("WYSHIPPING#rl_carriers_tracking: delivery #{delivery.id} pro #{delivery.master_tracking_number}: #{e.class}: #{e.message}")
  ErrorReporting.warning(e)
  nil
end

.sanitize_phone(phone) ⇒ Object



2260
2261
2262
# File 'app/services/wy_shipping.rb', line 2260

def self.sanitize_phone(phone)
  PhoneNumber.parse_and_format(phone, display_format: :strict_10)
end

.schedule_pickup(carrier, store_country_sym, deliveries, date_time) ⇒ Object

return { status_code: status_code, status_message: "Ship Pickup Error: #status_message" }
end
{ status_code: status_code, status_message: pickup_result[:status], request_response: pickup_result[:request_response] }
end



2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
# File 'app/services/wy_shipping.rb', line 2115

def self.schedule_pickup(carrier, store_country_sym, deliveries, date_time)
  status_code = :ok
  pickup_result = nil

  shipper = class_for_carrier(carrier).new SHIPPING_BASE_CONFIGURATION.merge(SHIPPING_SHIPPER_CONFIGURATION[store_country_sym])
  begin
    pickup_result = shipper.schedule_pickup(deliveries, date_time)
  rescue StandardError => e
    status_code = :error
    status_message = e.to_s
    ErrorReporting.error(e)

    return { status_code: status_code, status_message: "Ship Pickup Error: #{status_message}" }
  end
  { status_code: status_code, status_message: pickup_result[:status], request_response: pickup_result[:request_response] }
end

.ship_delivery(delivery, additional_status_message = '') ⇒ Object



1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
# File 'app/services/wy_shipping.rb', line 1201

def self.ship_delivery(delivery, additional_status_message = '')
  # Handle marketplace labels (Walmart, Amazon, etc.) separately
  # These use the marketplace's discounted carrier rates and require their API for label purchase
  # Check this before has_supported_carrier? since marketplace carriers aren't in the standard carrier list
  return ship_marketplace_delivery(delivery, additional_status_message) if Edi::MarketplaceLabelPurchaser.supports_marketplace_labels?(delivery)

  return { status_code: :error, status_message: "Invalid carrier.#{additional_status_message}" } unless delivery.has_supported_carrier?

  awaiting_label_shipments = delivery.shipments.top_level.awaiting_label.order('shipments.id ASC')

  if awaiting_label_shipments.none?
    status_message = 'No top-level shipments awaiting labels for delivery.'
    Rails.logger.warn("WYSHIPPING#ship_delivery: no top-level awaiting-label shipments", delivery_id: delivery.id, carrier: delivery.carrier)
    return { status_code: :error, status_message: "Shipping Error: #{status_message}#{additional_status_message}" }
  end

  unless PO_BOX_CARRIERS.include?(delivery.carrier)
    ship_to_attrs_for_check = delivery.ship_to_attributes
    ship_from_attrs_for_check = delivery.ship_from_attributes
    [[ship_to_attrs_for_check, 'destination'], [ship_from_attrs_for_check, 'origin']].each do |attrs, direction|
      addr = attrs[:address]
      next unless addr&.po_box?

      msg = "#{delivery.carrier} cannot ship to/from a PO Box (#{direction} address). " \
            "Please update the address or choose a postal carrier (#{PO_BOX_CARRIERS.join(', ')})."
      Rails.logger.warn("WYSHIPPING#ship_delivery: PO Box rejected",
                        delivery_id: delivery.id, carrier: delivery.carrier, direction: direction)
      return { status_code: :error, status_message: "Shipping Error: #{msg}#{additional_status_message}" }
    end
  end

  status_code = :ok
  status_message = +''
  label_result = nil
  carrier_class = class_for_carrier(delivery.carrier)
  shipper_configuration = SHIPPING_SHIPPER_CONFIGURATION[delivery.ship_natively_key || delivery.origin_address.country.iso3.to_sym]

  ship_to_attributes = delivery.ship_to_attributes
  ship_from_attributes = delivery.ship_from_attributes

  Rails.logger.debug { "ship_from_attributes: #{ship_from_attributes.inspect}" }

  char_limit = 34
  char_limit = 30 if ['FedEx'].include?(delivery.carrier)
  char_limit = 44 if ['Canadapost'].include?(delivery.carrier)

  origin = populate_origin_sender_data(address: ship_from_attributes[:address], phone: ship_from_attributes[:phone], shipper_config: shipper_configuration, char_limit: char_limit)
  shipper = carrier_class.new SHIPPING_BASE_CONFIGURATION.merge(shipper_configuration.merge(origin))
  shipper.special_instructions = [delivery.carrier_bol.presence, delivery.label_instructions.presence].compact.join(', ')

  shipper.attention_name = ship_to_attributes[:attention_name].to_s.gsub(/\P{ASCII}/u, '').gsub(%r{[^0-9a-z -_.,/\s]}i, '')[0..29]
  shipper.name = ship_to_attributes[:name].to_s.gsub(/\P{ASCII}/u, '').gsub(%r{[^0-9a-z -_.,/\s]}i, '')&.first(char_limit) # company and name are simply aliases
  shipper.phone = sanitize_phone(ship_to_attributes[:phone]) || sanitize_phone(ship_from_attributes[:phone]) || '8475407775' # need something here, including when ship to or ship from phone is invalid, as can happen in EDI for e.g. or returns, too late at this point to give feedback, just get this rated or labeled.
  shipper.email = ship_to_attributes[:email]
  shipper.address = ship_to_attributes[:address].street1.to_s.gsub(/\P{ASCII}/u, '')
  shipper.address2 = ship_to_attributes[:address].street2.to_s.gsub(/\P{ASCII}/u, '')
  shipper.city = ship_to_attributes[:address].city.to_s.gsub(/\P{ASCII}/u, '').upcase
  shipper.state = ship_to_attributes[:address].state_code
  shipper.zip = ship_to_attributes[:address].zip_compact.to_s.upcase.strip.squeeze(' ')
  shipper.country = ship_to_attributes[:address].country.iso
  shipper.address_residential = ship_to_attributes[:address].is_residential
  shipper.has_loading_dock = ship_to_attributes[:address].has_loading_dock
  shipper.is_construction_site = ship_to_attributes[:address].is_construction_site
  shipper.requires_inside_delivery = ship_to_attributes[:address].requires_inside_delivery
  shipper.is_trade_show = ship_to_attributes[:address].is_trade_show
  shipper.requires_liftgate = ship_to_attributes[:address].requires_liftgate
  shipper.limited_access = ship_to_attributes[:address].limited_access
  shipper.requires_appointment = ship_to_attributes[:address].requires_appointment
  # shipper.media_mail = true if delivery.line_items.goods.all?{|li| li.is_publication?} # apparently only for educational materials, see:https://about.usps.com/notices/not121/not121_tech.htm

  # Here we assume shipper.line_items is an array of line item hashes with keys :description (alpha numeric only), :quantity, :price, :part_number (sku), :origin_country_code, :commodity_code,
  customs_lis = delivery.line_items.parents_only.goods.to_a
  # See AppSignal #4681 in the rate-estimation block above: drop lines with no positive quantity so
  # ShipEngine doesn't reject the entire customs payload, and report the upstream anomaly.
  invalid_qty_lis, customs_lis = customs_lis.partition { |li| li.quantity.to_i <= 0 }
  if invalid_qty_lis.any?
    ErrorReporting.warning(
      "WyShipping: skipping #{invalid_qty_lis.size} customs line item(s) with non-positive quantity",
      {
        delivery_id: delivery.id,
        line_item_ids: invalid_qty_lis.map(&:id),
        skus: invalid_qty_lis.map(&:sku),
        quantities: invalid_qty_lis.map(&:quantity)
      }
    )
  end
  shipper.line_items = customs_lis.map do |li|
    {
      description: li.item.name.to_s.gsub(/[^0-9a-z ]/i, '')&.first(char_limit),
      detailed_description: (li.item.short_description || li.item.name).to_s.gsub(/[^0-9a-z ]/i, '')[0..450], # FedEx requires detailed description up to 450 characters
      quantity: li.quantity,
      price: li.unit_value_for_commercial_invoice,
      part_number: li.item.sku.to_s.gsub(/[^0-9a-z -_.]/i, ''),
      origin_country_code: (li.item.coo.to_s.strip.blank? ? 'CN' : li.item.coo.to_s.strip[0..1]),
      commodity_code: li.item.harmonization_code,
      weight: get_weight_by_country_units(li.item.shipping_weight || li.item.base_weight || 0.01, shipper.sender_country)
    }
  end

  shipper.delivery_total_value = delivery.subtotal
  shipper.tax_identification_number = delivery.customer.store.tax_identification_number_for_shipping.to_s.strip.delete(' ').delete('-')[0..14] if ship_to_attributes[:address].is_warehouse?
  shipper.sender_tax_identification_number = delivery.store.tax_identification_number_for_shipping.to_s.strip.delete(' ').delete('-')[0..14] if ship_from_attributes[:address].is_warehouse?
  shipper.ci_comments = COMMERCIAL_INVOICE_COMMENTS
  shipper.delivery_instructions = COMMERCIAL_INVOICE_COMMENTS
  shipper.pickup_instructions = COMMERCIAL_INVOICE_COMMENTS

  # Use chosen_shipping_method to get the actual selected shipping option's service code
  # delivery.shipping_option may point to 'override' for ships_economy orders while the actual
  # selected carrier (via selected_shipping_cost) has the correct service code
  shipper.service_code = delivery.chosen_shipping_method&.shipping_option&.service_code || delivery.shipping_option&.service_code
  shipper.currency_code = delivery.currency
  shipper.reference_number_1 = delivery.reference_number_for_label
  shipper.reference_number_code_1 = +''

  case classify_third_party_billing(delivery)
  when :third_party
    san = delivery.chosen_shipping_method.
    shipper.pay_type = 'bill_third_party'
    shipper. = san.
    shipper.billing_zip = san.billing_zip.delete(' ').delete('-')
    shipper.billing_country = delivery.country.iso
  when :native
    shipper.pay_type = 'bill_third_party'
    shipper. = shipper.send(:"shipengine_#{delivery.carrier.downcase}_parent_account_number")
    shipper.billing_zip = delivery.chosen_shipping_method&.&.billing_zip&.delete(' ')&.delete('-')
    shipper.billing_country = delivery.country.iso
  end

  if %w[UPS UPSFreight Purolator].include?(delivery.carrier)
    if delivery.order&.is_sales_order? && delivery.customer.is_overstock_com?
      # overstock.com requires our partner number ie  in ref line 1
      shipper.reference_number_1 = OVERSTOCK_COM_PARTNER_ID_NUMBER.to_s
      # overstock.com requires their order number ie our PO number in ref line 2
      shipper.reference_number_2 = delivery.order.po_number.to_s.gsub(/\P{ASCII}/u, '')&.first(char_limit)
    else
      shipper.reference_number_2 = if delivery.order&.po_number&.blank?
                                     delivery.order&.label_instructions.to_s.gsub(/\P{ASCII}/u, '')&.first(char_limit)
                                   else
                                     "#{delivery.order&.formatted_po_number}, #{delivery.order&.label_instructions}".gsub(/\P{ASCII}/u, '')&.first(char_limit)
                                   end
    end
    shipper.reference_number_code_2 = ''
    if delivery.chosen_shipping_method&.cod?
      shipper.cod_amount = delivery.order&.total_cod
      shipper.cod_collection_type = delivery.order&.cod_collection_type
      if delivery.signature_confirmation
        status_code = :warning
        status_message = 'Removed signature confirmation option for the COD package.'
      end
    else
      shipper.signature_confirmation = delivery.signature_confirmation
    end
  else
    shipper.reference_number_2 = delivery.order&.label_instructions.to_s.gsub(/\P{ASCII}/u, '')&.first(char_limit)
    shipper.reference_number_code_2 = ''
    reference_3_char_limit = char_limit
    reference_3_char_limit = 30 if ['CanadaPost'].include?(delivery.carrier)
    shipper.reference_number_3 = delivery.order&.po_number&.to_s&.gsub(/\P{ASCII}/u, '')&.first(reference_3_char_limit) # FedEx supports PO field here and labels it as such, so don't include the prefix
    shipper.signature_confirmation = delivery.signature_confirmation
    if delivery.chosen_shipping_method&.cod?
      status_code = :error
      status_message = 'Heatwave does not support COD shipments.'
      return { status_code: status_code, status_message: "Shipping Error: #{status_message}#{additional_status_message}" }
    end
  end
  if delivery.order&.is_sales_order? && delivery.customer.billing_entity.is_home_depot_usa?
    # this is to comply with Home Depot USA's label policy
    shipper.reference_number_1 = delivery.order.formatted_po_number.to_s.gsub(/\P{ASCII}/u, '')&.first(char_limit)
    shipper.reference_number_2 = CustomerConstants::HOME_DEPOT_STORE_NUMBER&.first(char_limit)
  end
  if delivery.order&.is_sales_order? && (delivery.customer.billing_entity.is_walmart_ca? || delivery.order.is_costco_ca?)
    # this is to comply with Walmart.ca's and Costco.ca's label policy
    shipper.reference_number_1 = delivery.order.po_number.to_s.gsub(/\P{ASCII}/u, '')&.first(char_limit)
    shipper.reference_number_2 = "ORD: #{delivery.order.reference_number}"
  end
  if delivery.order&.is_sales_order? && delivery.customer.billing_entity.is_canadian_tire? && !delivery.is_rma_return?
    # this is to comply with Canadian Tire's labeling policy
    # enforce sender name unless already using it:
    unless shipper.sender_attention_name.index(CustomerConstants::CANADIAN_TIRE_VENDOR_NUMBER)
      shipper.sender_attention_name = "CTC C OA Warmly Yours #{CustomerConstants::CANADIAN_TIRE_VENDOR_NUMBER}".gsub(/\P{ASCII}/u, '').gsub(%r{[^0-9a-z -_.,/\s]}i, '')&.first(char_limit)
      shipper.sender_company = shipper.sender_attention_name
    end
    shipper.reference_number_1 = delivery.order.po_number.to_s.gsub(/\P{ASCII}/u, '')&.first(char_limit)
    shipper.reference_number_2 = CustomerConstants::CANADIAN_TIRE_LABEL_REFERENCE_NUMBER_2.to_s # "8201256 720018"
    shipper.attention_name = "##{shipper.company.split('#').last}" # according to Canadian Tire they need the receiver name to be the store number
    unless !!(shipper.name =~ CustomerConstants::CANADIAN_TIRE_STORE_NAME_REGEX) # /^(CTC|CTA|CTR|CTS|Canadian Tire Store) #\d{4}$/ # regex for store address name must use CTX #ABCD where X is C or R or A etc. and NNNN is the store number
      raise Shipping::ShippingLabelError, CustomerConstants::CANADIAN_TIRE_STORE_NAME_ERROR_MESSAGE # "Canadian Tire ship to address name must be CTC, CTA, CTR, CTS or 'Canadian Tire Store' with the 4 digit store number in format #NNNN"
    end
  end
  if delivery.order&.is_sales_order? && delivery.customer.is_zoro? && !delivery.is_rma_return?
    # this is to comply with Zoro's labeling policy, per shipping guide
    # enforce sender name:
    shipper.sender_attention_name = 'WarmlyYours, Inc.'
    shipper.sender_company = 'C/O Zoro'
    shipper.shipper_attention_name = 'WarmlyYours, Inc.'
    shipper.shipper_company = 'C/O Zoro'
    customer_order_number = delivery.order.customer_reference.to_s.split(': ').last.to_s.split(' | ').first
    sales_order_number = delivery.order.customer_reference.to_s.split(': ').last.to_s.split(' | ').last
    shipper.reference_number_1 = sales_order_number.to_s # This corresponds to INV, use the Zoro Sales Order number, if any
    shipper.reference_number_2 = customer_order_number.to_s # 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, '')&.first(char_limit).to_s #  This corresponds to PO, Zoro PO number here
  end
  insured_value = delivery.calculate_declared_value.to_f.abs
  # for qualifying deliveries that will be ship-labeled natively in Heatwave, we set this to nil so we do not use the carrier declared value but use third party Shipping Insurance (Shipsurance service)
  insured_value = 0.0 if delivery.do_not_ship_insure_via_carrier?
  shipper.insured_value = insured_value
  shipper.signature_confirmation = true if delivery.must_be_signature_confirmation?
  if delivery.order&.is_sales_order? && delivery.customer.billing_entity.is_amazon_com?
    # this is to comply with Amazon.com's FBA label policy
    shipper.reference_number_1 = delivery.order.po_number.to_s.gsub(/\P{ASCII}/u, '')&.first(char_limit)
    shipper.reference_number_2 = "ORD: #{delivery.order.reference_number}"
  end
  if delivery.order&.is_sales_order? && delivery.customer.billing_entity.is_houzz?
    # this is to comply with Houzz label policy
    shipper.reference_number_1 = ''
    shipper.reference_number_2 = delivery.order.po_number.to_s.gsub(/\P{ASCII}/u, '')&.first(char_limit)
    shipper.reference_number_3 = 'orders@warmlyyours.com'
  end
  if delivery.carrier == 'RlCarriers'
    shipper.reference_number_1 = delivery.reference_number_for_label
    shipper.reference_number_2 = delivery.chosen_shipping_method.rate_data['quote_number'].to_s.gsub(/\P{ASCII}/u, '')&.first(char_limit)
    shipper.reference_number_3 = delivery.order&.po_number.to_s.gsub(/\P{ASCII}/u, '')&.first(char_limit)
  end
  if delivery.carrier == 'ShipengineRlCarriers'
    rd = (delivery.chosen_shipping_method&.rate_data || {}).with_indifferent_access
    shipper.reference_number_1 = delivery.reference_number_for_label
    shipper.reference_number_2 = rd[:quote_id].to_s.gsub(/\P{ASCII}/u, '')&.first(char_limit)
    shipper.reference_number_3 = delivery.order&.po_number.to_s.gsub(/\P{ASCII}/u, '')&.first(char_limit)
  end
  if %w[Saia ShipengineSaia].include?(delivery.carrier)
    # implement the SAIA scheme for PO Number (applies to both legacy and ShipEngine direct):
    shipper.reference_number_1 = delivery.reference_number_for_label.to_s.first(20) # 20 char limit for SAIA PO numbers
    shipper.reference_number_2 = delivery.order&.po_number&.to_s&.gsub(/\P{ASCII}/u, '')&.first(20) # 20 char limit for SAIA PO numbers
  end

  if delivery.carrier == 'YrcFreight'
    # implement the YRC scheme for reference numbers:
    shipper.reference_number_1 = delivery.reference_number_for_label
    shipper.reference_number_2 = delivery.order&.po_number&.to_s&.gsub(/\P{ASCII}/u, '')
  end

  shipper.saturday_delivery = delivery.saturday_delivery
  shipper.negotiated_rates = true

  if %w[UPSFreight Freightquote RlCarriers ShipengineRlCarriers Roadrunner ShipengineRoadrunner Saia ShipengineSaia ShipengineXpo YrcFreight FedExFreight ShipengineFedExFreight
        ShipengineFedExFreightEconomy].include?(delivery.carrier) && delivery.order&.is_store_transfer?
    # force commercial address here and skip the liftgate service
    shipper.address_residential = false
    shipper.has_loading_dock = true
    shipper.is_construction_site = false
    shipper.requires_inside_delivery = false
    shipper.is_trade_show = false
    shipper.requires_liftgate = false
    shipper.limited_access = false
    shipper.requires_appointment = false
    shipper.pickup_datetime = delivery.order.get_scheduled_ship_date_time
    shipper.skip_rate_test = true # this is used to skip any rate comparison tests on quoted LTL rate vs booked shipment
  end

  if %w[SpeedeeDelivery Freightquote RlCarriers ShipengineRlCarriers Roadrunner ShipengineRoadrunner Saia ShipengineSaia ShipengineXpo YrcFreight ShipengineFedExFreight ShipengineFedExFreightEconomy].include?(delivery.carrier)
    shipper.rate_data = delivery.chosen_shipping_method.rate_data
  end

  if delivery.is_rma_return?
    # set RMA reference numbers on return shipment
    shipper.reference_number_1 = "RMA: #{delivery.rma_for_return.rma_number}"
    shipper.reference_number_code_1 = 'RZ'
    shipper.reference_number_2 = ''
    shipper.reference_number_2 = "REF ORD: #{delivery.rma_for_return.original_order.reference_number}" if delivery.rma_for_return.original_order
    shipper.reference_number_code_2 = ''
  end

  packages = []
  total_weight = 0
  awaiting_label_shipments.each do |shipment|
    packages << Shipping::Package.new(shipment.weight * 16, [shipment.height, shipment.width, shipment.length], pallet: shipment.pallet?, crate: shipment.crate?, units: :imperial, value: shipment.compute_shipment_declared_value,
                                                                                                                container_code: shipment.reference_number, shipment_id: shipment.id, flat_rate_package_type: shipment.flat_rate_package_type, nmfc_code: shipment.effective_nmfc_code)
    total_weight += shipment.weight # here only FedEx uses this and they require lbs, but strangely ignore this field using the package details
  end
  packages = packages.sort_by(&:lbs).reverse # may as well sort by heaviest here, making the heaviest box have the master tracking number

  shipper.packages = packages

  # Multi-box returns must be one single-package return label per box: once
  # `is_return_label: true` is set, FedEx rejects multi-package shipments
  # ("Number of packages exceeds maximum") and UPS too ("Only one package is
  # allowed for this movement") — carrier return labels are single-package.
  # Postal multi-box already split here (for per-package rating); route every
  # multi-box RMA return through the same per-package path so each box gets its
  # own single-package return label. (Outbound multi-package MPS is unaffected.)
  if awaiting_label_shipments.length > 1 &&
     (%w[Canadapost USPS].include?(delivery.carrier) || delivery.is_rma_return?)
    return ship_per_package_single_label_delivery(delivery, shipper, packages, total_weight, additional_status_message)
  end

  shipper.skip_png_download = !delivery.is_rma_return?
  # Paperless is gated on the chosen shipping option's
  # `paperless_eligible` flag (USPS only at the moment), separately
  # from is_return_label/charge_event which always apply on RMA returns.
  shipper.paperless = delivery.paperless_return? if shipper.respond_to?(:paperless=)
  error_payload = nil
  begin
    Rails.logger.debug { "WYSHIPPING#ship_delivery: shipper.insured_value: #{shipper.insured_value}, delivery.calculate_declared_value: #{delivery.calculate_declared_value}" }
    # Pass `is_rma_return?` so ShipEngine carriers opt the request into
    # the RMA-return shape: `is_return_label: true` and `charge_event:
    # 'on_carrier_acceptance'`. Non-ShipEngine carriers ignore the arg
    # (their `label` signatures all accept the positional flag).
    label_result = shipper.label(delivery.is_rma_return?)
  rescue ShipEngineRb::Exceptions::ShipEngineError => e
    # Capture the structured fields the gem attaches to every ShipEngineError
    # (request_id, code, type, source, plus the raw HTTP body/status/url from
    # our shipengine_rb fork) so shipping_api_log carries the full transaction
    # — `e.to_s` alone drops all of it.
    Rails.logger.warn("WYSHIPPING#ship_delivery: ShipEngine error",
                      error: e.message, request_id: e.request_id, code: e.code, type: e.type)
    status_code = :error
    status_message = e.to_s
    error_payload = build_error_payload(e)
    ErrorReporting.error(e)
  rescue StandardError => e
    status_code = :error
    status_message = e.to_s
    error_payload = build_error_payload(e)
    ErrorReporting.error(e)
    additional_status_message += ' FedEx Home Delivery to a non residential address marked residential.' if status_message.index('4074') && status_message.index('Rating failed SASV') && delivery.carrier == 'FedEx'
    # Prefer the structured response the shipper stashed (e.g. LTL book_pickup
    # returns 200 OK with missing fields, raises ShippingError, and stashes
    # @last_response_payload before raising) over the bare {error_class, message}
    # blob — the response is the actual diagnostic the orders team needs.
    last_response = shipper.respond_to?(:last_response_payload) ? shipper.last_response_payload : nil
    return {
      status_code: status_code,
      status_message: "Shipping Error: #{status_message}#{additional_status_message}",
      shipment: { ship_request_xml: shipper.respond_to?(:last_request_payload) ? shipper.last_request_payload : nil, ship_reply_xml: last_response || error_payload }
    }
  end

  # On ShipEngineError the begin block falls through here with label_result
  # still nil — synthesize a shipment hash so the caller's append_to_shipping_api_log!
  # captures the request body and the structured error.
  if label_result.nil? && error_payload
    last_response = shipper.respond_to?(:last_response_payload) ? shipper.last_response_payload : nil
    label_result = {
      ship_request_xml: shipper.respond_to?(:last_request_payload) ? shipper.last_request_payload : nil,
      ship_reply_xml: last_response || error_payload
    }
  end

  { status_code: status_code, status_message: "#{status_message}#{additional_status_message}", shipment: label_result }
end

.ship_mail_activity(mail_activity) ⇒ Object



948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
# File 'app/services/wy_shipping.rb', line 948

def self.ship_mail_activity(mail_activity)
  status_code = :ok
  status_message = ''
  label_result = nil
  shipper = populate_shipper_data_for(mail_activity)
  begin
    label_result = shipper.label(false)
  rescue StandardError => e
    status_code = :error
    status_message = e.to_s
    ErrorReporting.error(e)
    return { status_code: status_code, status_message: "Shipping Error: #{status_message}" }
  end
  { status_code: status_code, status_message: status_message, shipment: label_result }
end

.ship_marketplace_delivery(delivery, additional_status_message = '') ⇒ Hash

Ship a delivery using a marketplace's discounted shipping rates (Walmart, Amazon, etc.)
This uses the marketplace's API for label purchase instead of our standard carriers

Parameters:

  • delivery (Delivery)

    The delivery to ship

  • additional_status_message (String) (defaults to: '')

    Additional message to append

Returns:

  • (Hash)

    Result with :status_code, :status_message, :shipment keys



1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
# File 'app/services/wy_shipping.rb', line 1558

def self.ship_marketplace_delivery(delivery, additional_status_message = '')
  status_code = :ok
  status_message = +''

  purchaser_class = Edi::MarketplaceLabelPurchaser.for_delivery(delivery)
  marketplace_name = Edi::MarketplaceLabelPurchaser.marketplace_name(delivery.order)

  unless purchaser_class
    return {
      status_code: :error,
      status_message: "Cannot ship via #{marketplace_name}: No label purchaser available.#{additional_status_message}"
    }
  end

  # Get the selected shipping cost which should have the marketplace rate data
  selected_shipping_cost = delivery.selected_shipping_cost
  if selected_shipping_cost&.rate_data.blank?
    return {
      status_code: :error,
      status_message: "Cannot ship via #{marketplace_name}: No rate data found on selected shipping cost. Please refresh shipping rates.#{additional_status_message}"
    }
  end

  if marketplace_name == 'Amazon'
    selected_shipping_cost = refresh_amzbs_rates_if_stale(delivery, selected_shipping_cost)
    if selected_shipping_cost&.rate_data.blank?
      return {
        status_code: :error,
        status_message: "Cannot ship via Amazon: Rate refresh failed — no rate data. Please refresh shipping rates manually.#{additional_status_message}"
      }
    end
  end

  # Extract the rate info from the stored rate data (marketplace-agnostic)
  rate_data = selected_shipping_cost.rate_data.with_indifferent_access
  rate = build_marketplace_rate(rate_data)

  # Validate that the rate has required marketplace fields
  if marketplace_name == 'Walmart'
    unless rate[:carrier_id].present? && rate[:service_type].present?
      Rails.logger.warn("[#{marketplace_name}] Rate data missing required fields. carrier_id=#{rate[:carrier_id]}, service_type=#{rate[:service_type]}, rate_data=#{rate_data.inspect}")
      return {
        status_code: :error,
        status_message: "Cannot ship via #{marketplace_name}: Selected shipping rate is missing required data (carrier_id or service_type). Please refresh shipping rates and select a #{marketplace_name} shipping method again.#{additional_status_message}"
      }
    end
  elsif marketplace_name == 'Amazon'
    unless rate[:amz_request_token].present? && rate[:amz_rate_id].present?
      Rails.logger.warn("[#{marketplace_name}] Rate data missing required fields. amz_request_token=#{rate[:amz_request_token].present?}, amz_rate_id=#{rate[:amz_rate_id]}, rate_data keys=#{rate_data.keys}")
      return {
        status_code: :error,
        status_message: "Cannot ship via #{marketplace_name}: Selected shipping rate is missing Amazon Buy Shipping data (request_token or rate_id). Please refresh shipping rates and select an Amazon shipping method again.#{additional_status_message}"
      }
    end
  end

  # Process each awaiting_label shipment
  shipments = delivery.shipments.awaiting_label
  if shipments.empty?
    return {
      status_code: :error,
      status_message: "No shipments awaiting labels for delivery.#{additional_status_message}"
    }
  end

  label_results = []

  # For Amazon multi-package orders, each shipment maps 1:1 to its own
  # per-package rate entry (request_token, rate_id, doc specs, VAS).
  # Without this, the first purchase_label would try to buy ALL package
  # labels via create_label_multi_package while subsequent shipments fail.
  per_pkg = rate[:per_package_rates]
  amz_multi_package = marketplace_name == 'Amazon' && per_pkg.is_a?(Array) && per_pkg.size > 1

  # Accumulated request/response trace from every marketplace API call this
  # flow makes — surfaced into Delivery#shipping_api_log so the orders team
  # can post-mortem failures without digging through rotated Rails logs.
  aggregated_api_log = []

  shipments.each_with_index do |shipment, idx|
    # Skip if label already exists (e.g., purchased early or already generated)
    if shipment.tracking_number.present? && shipment.ship_label_pdf.present?
      Rails.logger.info("[#{marketplace_name}] Shipment #{shipment.id} already has label (tracking: #{shipment.tracking_number}), skipping purchase")
      shipment.label_generated! if shipment.can_label_generated?
      label_results << {
        shipment: shipment,
        tracking_number: shipment.tracking_number,
        carrier: shipment.carrier,
        label_id: shipment.sww_label_id,
        label_upload: shipment.ship_label_pdf
      }
      next
    end

    # Skip fallback-only packages (synthetic items added for getRates, not real shipments)
    if amz_multi_package && idx < per_pkg.size
      pkg_entry = per_pkg[idx].respond_to?(:with_indifferent_access) ? per_pkg[idx].with_indifferent_access : per_pkg[idx]
      if pkg_entry[:fallback_only]
        Rails.logger.info("[#{marketplace_name}] Skipping fallback-only package #{idx + 1} for shipment #{shipment.id}")
        next
      end
    end

    begin
      shipment_rate = if amz_multi_package && idx < per_pkg.size
                        build_amz_per_shipment_rate(rate, per_pkg[idx])
                      else
                        rate
                      end

      purchaser = purchaser_class.new(shipment)
      result = purchaser.purchase_label(shipment_rate)
      aggregated_api_log.concat(Array(result.api_log))

      if result.success
        label_results << {
          shipment: shipment,
          tracking_number: result.tracking_number,
          carrier: result.carrier,
          label_id: result.label_id,
          label_upload: result.label_upload
        }
        Rails.logger.info("[#{marketplace_name}] Label created for shipment #{shipment.id}: #{result.tracking_number}")
      else
        status_code = :error
        status_message += "Failed to create label for shipment #{shipment.id}: #{result.error}. "
        Rails.logger.error("[#{marketplace_name}] Label creation failed for shipment #{shipment.id}: #{result.error}")
      end
    rescue StandardError => e
      status_code = :error
      status_message += "Error creating label for shipment #{shipment.id}: #{e.message}. "
      Rails.logger.error("[#{marketplace_name}] Exception creating label: #{e.message}")
      ErrorReporting.error(e, shipment_id: shipment.id, delivery_id: delivery.id)
    end
  end

  if label_results.any?
    label_results.each do |lr|
      lr[:shipment].label_generated! if lr[:shipment].can_label_generated?
    end

    status_code = :ok if status_code != :error
    status_message = "#{marketplace_name} labels created successfully. " + status_message if label_results.size == shipments.size
  end

  {
    status_code: status_code,
    status_message: "#{status_message}#{additional_status_message}".strip,
    # ship_request_xml / ship_reply_xml are JSON-native here (not XML) — the
    # column is JSONB so Delivery#append_to_shipping_api_log! takes them as-is.
    ship_request_xml: marketplace_log_requests(aggregated_api_log),
    ship_reply_xml: marketplace_log_responses(aggregated_api_log),
    shipment: label_results.first # Return first for compatibility with existing code
  }
end

.ship_per_package_single_label_delivery(delivery, shipper, packages, _total_weight, additional_status_message = '') ⇒ Object

Produce one single-package label per box by re-labeling each package on its
own. Despite the historical "mps" name this is NOT a multi-package shipment
(MPS) call — it loops over packages, sets shipper.packages = [package],
and calls shipper.label once per box, yielding N single-package labels.

Two callers route here from ship_delivery: USPS/Canadapost multi-box
(postal carriers rate per-package) and multi-box RMA returns on any carrier
(FedEx/UPS reject multi-package return labels — see ship_delivery).



1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
# File 'app/services/wy_shipping.rb', line 1835

def self.ship_per_package_single_label_delivery(delivery, shipper, packages, _total_weight, additional_status_message = '')
  status_code = :ok
  status_message = +''
  label_results = []
  # Per-package request/response payloads are now Hashes (shipengine_base.rb
  # returns `.to_hash` rather than `.to_hash.inspect` so the Shipping API
  # Log tab can render them as a navigable JSON tree). Aggregate as an
  # Array of Hashes so the per-package shape survives, and downstream
  # JSON.pretty_generate handles arrays of hashes natively.
  per_package_requests = []
  per_package_responses = []
  total_price = 0.0

  # USPS/Canadapost multi-box returns walk this path; pass `is_rma_return?`
  # into each per-package label call so the RMA-return payload
  # (`is_return_label`, `charge_event`) is requested for each box.
  # Paperless is gated separately on the option's `paperless_eligible`
  # flag (USPS only). Tests sometimes call this with `delivery: nil`;
  # safe-nav defaults both flags to false in that case.
  return_label = delivery&.is_rma_return? || false
  shipper.paperless = (delivery&.paperless_return? || false) if shipper.respond_to?(:paperless=)

  package_ind = 0
  master_tracking_number = ''
  # shipper.total_shipment_weight = total_weight
  # shipper.package_count = packages.length
  # shipper.multiple_piece_shipping = true
  # shipper.packages = packages
  packages.each do |package|
    label_result = nil
    package_ind += 1
    shipper.packages = [package]
    begin
      label_result = shipper.label(return_label)
    rescue StandardError => e
      status_code = :error
      status_message = e.to_s
      ErrorReporting.error(e)

      return { status_code: status_code, status_message: "Shipping Error: #{status_message}#{additional_status_message}" }
    end
    pkg_label_entry = label_result[:labels].first
    # Each per-package call is a single-shipment ShipEngine request, so
    # shipment-level paperless (`label_result[:shipment_paperless]`) IS
    # the per-package paperless artifact for this box. Fold it onto the
    # label entry so downstream (Delivery#generate_labels) sees a
    # uniform per-package paperless shape regardless of which path
    # produced the labels.
    if (sp = label_result[:shipment_paperless])
      pkg_label_entry[:paperless_png] = sp[:png]
      pkg_label_entry[:paperless_instructions] = sp[:instructions]
      pkg_label_entry[:paperless_handoff_code] = sp[:handoff_code]
    end
    label_results << pkg_label_entry
    per_package_requests  << label_result[:ship_request_xml]
    per_package_responses << label_result[:ship_reply_xml]
    master_tracking_number = label_result[:shipment_identification_number] if package_ind == 1
    total_price += label_result[:total_charges].to_f
  end

  { status_code: status_code, status_message: "#{status_message}#{additional_status_message}",
    shipment: { labels: label_results, shipment_identification_number: master_tracking_number, total_charges: total_price, ship_request_xml: per_package_requests, ship_reply_xml: per_package_responses } }
end

.ship_standalone_delivery(standalone_delivery) ⇒ Object



1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
# File 'app/services/wy_shipping.rb', line 1055

def self.ship_standalone_delivery(standalone_delivery)
  status_code = :ok
  status_message = ''
  label_result = nil
  shipper = populate_shipper_data_for_standalone_delivery(standalone_delivery, standalone_delivery.carrier)
  if standalone_delivery..present? && standalone_delivery.billing_postal_code.present?
    shipper.pay_type = 'bill_third_party'
    shipper. = standalone_delivery.
    shipper.billing_zip = standalone_delivery.billing_postal_code.delete(' ').delete('-')
    shipper.billing_country = standalone_delivery.country.iso
  end
  begin
    label_result = shipper.label(false)
  rescue ShipEngineRb::Exceptions::BusinessRulesError => e
    status_code = :error
    status_message = e.to_s
    ErrorReporting.warning(e)
    return { status_code: status_code, status_message: "Shipping Error: #{status_message}" }
  rescue StandardError => e
    status_code = :error
    status_message = e.to_s
    ErrorReporting.error(e)
    return { status_code: status_code, status_message: "Shipping Error: #{status_message}" }
  end
  { status_code: status_code, status_message: status_message, shipment: label_result }
end

.shipengine_ltl_tracking(delivery) ⇒ ActiveSupport::HashWithIndifferentAccess?

Poll ShipEngine's LTL tracking endpoint for a freight delivery's PRO.
Returns the raw tracking payload (HashWithIndifferentAccess) or nil when
the delivery isn't a ShipEngine LTL shipment, has no PRO, or the call
errors. The track call only needs the API key + the carrier's SCAC, so
the bare SHIPPING_BASE_CONFIGURATION is sufficient (no shipper-address
merge — the tracking GET doesn't use sender fields).

Parameters:

Returns:

  • (ActiveSupport::HashWithIndifferentAccess, nil)


2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
# File 'app/services/wy_shipping.rb', line 2285

def self.shipengine_ltl_tracking(delivery)
  carrier = delivery.shipping_option&.carrier
  return nil unless ShippingOption::SHIPENGINE_LTL_CARRIERS.include?(carrier)
  return nil if delivery.ltl_pro_number.blank?

  class_for_carrier(carrier).new(SHIPPING_BASE_CONFIGURATION).track(delivery.ltl_pro_number)
rescue StandardError => e
  Rails.logger.warn("WYSHIPPING#shipengine_ltl_tracking: delivery #{delivery.id} pro #{delivery.ltl_pro_number}: #{e.class}: #{e.message}")
  ErrorReporting.warning(e)
  nil
end

.standalone_shipper_rate_data_from_selection(selected_rate) ⇒ Object

Builds a String-keyed rate_data hash for standalone label purchase (hstore may store nested JSON as String).



1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
# File 'app/services/wy_shipping.rb', line 1167

def self.standalone_shipper_rate_data_from_selection(selected_rate)
  return nil unless selected_rate

  sr = ActiveSupport::HashWithIndifferentAccess.new(selected_rate)
  coerced = coerce_standalone_stored_rate_data(sr[:rate_data])
  return coerced if coerced.present?

  total = sr[:total_charges]
  return nil if total.blank?

  {
    'total_price' => total.to_f,
    'base_price' => total.to_f,
    'sort_code' => '',
    'days_in_transit' => nil,
    'signature_confirmation' => false,
    'extra_charges_hash' => {}
  }
end

.start_tracking_for_carrier(tracking_number, carrier_name) ⇒ Object

Registers a tracking number with ShipEngine for webhook push updates.
Only works for carriers that use ShipEngine (inherits from Shipping::ShipengineBase).
Returns nil (silently) for unsupported carriers like SpeedeeDelivery.



2242
2243
2244
2245
2246
2247
2248
2249
2250
# File 'app/services/wy_shipping.rb', line 2242

def self.start_tracking_for_carrier(tracking_number, carrier_name)
  carrier_class = class_for_carrier(carrier_name, tracking_number: tracking_number)
  unless carrier_class.ancestors.include?(Shipping::ShipengineBase)
    Rails.logger.info "[WyShipping] start_tracking_for_carrier: #{carrier_name} does not use ShipEngine, skipping webhook registration for #{tracking_number}"
    return nil
  end
  shipper = carrier_class.new(SHIPPING_BASE_CONFIGURATION.merge(SHIPPING_SHIPPER_CONFIGURATION[:USA]))
  shipper.start_tracking(tracking_number)
end

.track_shipment(shipment) ⇒ Object



2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
# File 'app/services/wy_shipping.rb', line 2174

def self.track_shipment(shipment)
  status_code = :ok
  status_message = ''
  tracking_result = nil

  # For Ship with Walmart (SWW) labels, use the actual carrier from sww_metadata
  # Walmart provides labels from carriers like FedEx/USPS, tracking is via those carriers
  carrier_name = shipment.carrier
  if carrier_name == 'WalmartSeller'
    carrier_name = shipment.sww_carrier
    if carrier_name.blank?
      return {
        status_code: :error,
        status_message: 'Cannot track WalmartSeller shipment: underlying carrier not set in sww_metadata'
      }
    end
  end

  # For Amazon Buy Shipping labels, resolve the actual carrier from amz_metadata.
  # Shipping::AmazonSeller is a rate-shopping / label-purchase client and does
  # not implement #track, so we redirect to the underlying carrier:
  #   - Standard carriers (UPS, USPS, ...) → their existing Shipping::* client
  #   - Amazon Logistics ('Amazon Shipping') → Shipping::AmazonShipping
  #     (ShipEngine carrier_code 'amazon_shipping_us', se-6604086)
  if carrier_name == 'AmazonSeller'
    amz_carrier = shipment.amz_carrier
    if amz_carrier.blank?
      return {
        status_code: :error,
        status_message: 'Cannot track AmazonSeller shipment: underlying carrier not set in amz_metadata'
      }
    end

    begin
      class_for_carrier(amz_carrier)
      carrier_name = amz_carrier
    rescue ArgumentError, NameError
      return {
        status_code: :error,
        status_message: "Cannot track AmazonSeller shipment: no carrier client for '#{amz_carrier}'"
      }
    end
  end

  if shipment.tracking_number.blank?
    return {
      status_code: :error,
      status_message: "Cannot track shipment ##{shipment.id}: tracking number is blank"
    }
  end

  carrier_class = class_for_carrier(carrier_name, tracking_number: shipment.tracking_number)
  shipper = carrier_class.new SHIPPING_BASE_CONFIGURATION.merge(SHIPPING_SHIPPER_CONFIGURATION[shipment&.delivery&.ship_natively_key || shipment&.delivery&.country&.iso3&.to_sym])

  begin
    tracking_result = shipper.track(shipment.tracking_number)
  rescue StandardError => e
    status_code = :error
    status_message = e.to_s
    ErrorReporting.error(e)
    return { status_code: status_code, status_message: "Ship Tracking Error: #{status_message}" }
  end
  { status_code: status_code, status_message: status_message, tracking_result: tracking_result }
end

.valid_address?(address, force_carrier = nil) ⇒ Boolean

Returns:

  • (Boolean)


817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
# File 'app/services/wy_shipping.rb', line 817

def self.valid_address?(address, force_carrier = nil)
  return { status_code: :ok, status_message: 'Skipping address validation, address marked override_all_address_validation', valid_address: true, suggested_address_hashes: [] } if address.override_all_address_validation

  # Rails.logger.debug "!!!!!!!!!!!!!WyShipping.valid_address?"
  Store.find_by(country_iso3: address.country.iso3)
  use_carrier = address.validate_with_carrier || force_carrier
  if address.country.iso3 == 'USA'
    # UPS only supports US addresses, but may want to override UPS for FedEx, for e.g. on quote or order shipping addresses when carrier is already determined to be FedEx
    shipper = if use_carrier && %w[FedEx UPS].include?(use_carrier)
                class_for_carrier(use_carrier).new SHIPPING_BASE_CONFIGURATION.merge(SHIPPING_SHIPPER_CONFIGURATION[:USA])
              else # default to UPS
                Shipping::Ups.new SHIPPING_BASE_CONFIGURATION.merge(SHIPPING_SHIPPER_CONFIGURATION[:USA])
              end
  elsif address.country.iso3 == 'CAN'
    shipper = if use_carrier && %w[FedEx Purolator].include?(use_carrier)
                class_for_carrier(use_carrier).new SHIPPING_BASE_CONFIGURATION.merge(SHIPPING_SHIPPER_CONFIGURATION[:CAN])
              else # default to Purolator city/postal code validation for Canadian addresses
                Shipping::FedEx.new SHIPPING_BASE_CONFIGURATION.merge(SHIPPING_SHIPPER_CONFIGURATION[:CAN])
              end
  else
    return { status_code: :ok, status_message: 'Skipping address validation, only US and Canadian addresses are currently supported', valid_address: true, suggested_address_hashes: [] }
  end
  shipper.name = address.company_name.to_s.gsub(/[^0-9a-z\s]/i, '')
  shipper.attention_name = address.person_name.to_s.gsub(/[^0-9a-z\s]/i, '')
  shipper.zip = address.zip_compact.to_s.upcase.strip.squeeze(' ')
  shipper.address = address.street1
  shipper.address2 = address.street2
  shipper.city = address.city.upcase
  shipper.state = address.state_code
  shipper.country = address.country.iso
  shipper.address_residential = false
  shipper.address_residential = true if address.is_residential

  if shipper.sender_address.nil? # yeesh deal with shipper vs sender
    shipper.sender_address = shipper.shipper_address
    shipper.sender_address2 ||= shipper.shipper_address2
    shipper.sender_city ||= shipper.shipper_city
    shipper.sender_state ||= shipper.shipper_state
    shipper.sender_country ||= shipper.shipper_country
    shipper.sender_zip ||= shipper.shipper_zip
    shipper.sender_address_residential ||= shipper.shipper_address_residential
  end

  # first test for address name lengths
  status_code = :ok
  status_message_arr = []
  # if shipper.name.length > 35
  #   status_code = :error
  #   status_message_arr << "company name is too long (maximum 35 characters)"
  # end
  # if shipper.attention_name.length > 30
  #   status_code = :error
  #   status_message_arr << "address person name is too long (maximum 30 characters)"
  # end
  return { status_code: :error, status_message: "Address validation issue: #{status_message_arr.join(', ')}.", valid_address: false, suggested_address_hashes: [] } if status_code == :error

  # ok now validate address
  begin
    shipper.valid_address?(address.logger) # after much experimentation this seems an ok threshold though the UPS validation scheme leaves a lot to be desired... Purolator ignores this
  rescue StandardError => e
    status_code = :error
    status_message = e.to_s
    if status_message.index('service unavailable') || status_message.index('execution expired')
      # let these go through
      { status_code: :ok, status_message: "Shipping Error: #{status_message}", valid_address: true, suggested_address_hashes: [] }
    else
      { status_code: status_code, status_message: "Shipping Error: #{status_message}", valid_address: false, suggested_address_hashes: [] }
    end
  end
end

.void_amazon_buy_shipping_delivery(delivery) ⇒ Hash

Void Amazon Buy Shipping labels for a delivery

Parameters:

  • delivery (Delivery)

    The delivery whose labels to void

Returns:

  • (Hash)

    Result with :status_code, :status_message keys



2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
# File 'app/services/wy_shipping.rb', line 2028

def self.void_amazon_buy_shipping_delivery(delivery)
  status_code = :ok
  status_message = +''

  shipments_with_labels = delivery.shipments.where.not(amz_shipment_id: nil)
  shipments_with_labels = delivery.shipments.where("amz_metadata IS NOT NULL AND amz_metadata != '{}'::jsonb") if shipments_with_labels.empty?

  if shipments_with_labels.empty?
    return {
      status_code: :ok,
      status_message: 'No Amazon Buy Shipping labels found to void (no AMZ metadata on shipments).'
    }
  end

  voided_count = 0
  failed_count = 0

  shipments_with_labels.each do |shipment|
    purchaser = Edi::Amazon::ShippingLabelPurchaser.new(shipment)
    result = purchaser.void_label

    if result[:success]
      voided_count += 1
      Rails.logger.info("[AMZ-BS] Voided label for shipment #{shipment.id}")
    else
      failed_count += 1
      status_message += "Failed to void label for shipment #{shipment.id}: #{result[:error]}. "
      Rails.logger.error("[AMZ-BS] Failed to void label for shipment #{shipment.id}: #{result[:error]}")
    end
  rescue StandardError => e
    failed_count += 1
    status_message += "Error voiding label for shipment #{shipment.id}: #{e.message}. "
    Rails.logger.error("[AMZ-BS] Exception voiding label: #{e.message}")
    ErrorReporting.error(e, shipment_id: shipment.id, delivery_id: delivery.id)
  end

  if failed_count > 0
    status_code = voided_count > 0 ? :warning : :error
  else
    status_message = "Successfully voided #{voided_count} Amazon Buy Shipping label(s)."
  end

  { status_code: status_code, status_message: status_message.strip }
end

.void_by_identifier(delivery, identifier) ⇒ Object



2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
# File 'app/services/wy_shipping.rb', line 2073

def self.void_by_identifier(delivery, identifier)
  status_code = :ok
  status_message = ''
  void_result = nil

  carrier_class = class_for_carrier(delivery.carrier)
  shipper = carrier_class.new SHIPPING_BASE_CONFIGURATION.merge(SHIPPING_SHIPPER_CONFIGURATION[delivery.ship_natively_key || delivery.country.iso3.to_sym])
  if %w[FedExFreight USPS Canadapost].include?(delivery.carrier)
    # FedEx requires you to tell it whether it's FDXG or FDXE; USPS and Canadapost require service_code for MPS voids
    shipper.service_code = delivery.chosen_shipping_method.shipping_option.service_code
  end

  begin
    void_result = shipper.void(identifier)
  rescue StandardError => e
    status_code = :error
    status_message = e.to_s
    ErrorReporting.error(e)

    return { status_code: status_code, status_message: "Ship Voiding Error: #{status_message}" }
  end
  { status_code: status_code, status_message: status_message, void_request_xml: void_result[:void_request_xml], void_response_xml: void_result[:void_response_xml] }
end

.void_delivery(delivery, test = Rails.application.config.x.shipping.ups_void_test_mode) ⇒ Object



1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
# File 'app/services/wy_shipping.rb', line 1899

def self.void_delivery(delivery, test = Rails.application.config.x.shipping.ups_void_test_mode)
  # Handle Walmart "Ship with Walmart" label voiding separately
  return void_walmart_sww_delivery(delivery) if delivery.carrier == 'WalmartSeller' && delivery.order&.edi_orchestrator_partner&.start_with?('walmart_seller')

  # Handle Amazon Buy Shipping label voiding separately
  return void_amazon_buy_shipping_delivery(delivery) if delivery.carrier == 'AmazonSeller' && delivery.order&.edi_orchestrator_partner&.start_with?('amazon_seller')

  status_code = :ok
  status_message = ''
  void_result = nil

  carrier_class = class_for_carrier(delivery.carrier)
  shipper = carrier_class.new SHIPPING_BASE_CONFIGURATION.merge(SHIPPING_SHIPPER_CONFIGURATION[delivery.ship_natively_key || delivery.country.iso3.to_sym])
  if %w[FedExFreight USPS Canadapost].include?(delivery.carrier)
    # FedEx requires you to tell it whether it's FDXG or FDXE; multi-package shipments must be voided sequentially
    shipper.service_code = delivery.chosen_shipping_method.shipping_option.service_code
    return void_mps_delivery(delivery, shipper, test) if delivery.shipments.label_complete.length > 1
  end

  identifier = delivery.master_tracking_number
  identifier = delivery.shipengine_label_id if delivery.shipengine_label_id.present? # annoyingly Shipengine uses its own label_id to void, not the master tracking number
  identifier = delivery.freight_order_number if delivery.freight_order_number.present? # annoyingly Freightquote/CH Robinson uses its own freight_order_number to void, not the master tracking number

  begin
    void_result = shipper.void(identifier)
  rescue StandardError => e
    status_code = :error unless test
    status_code = :warning if test
    status_message = e.to_s
    ErrorReporting.error(e)

    # Carry whatever request/response the shipper stashed before the raise
    # (LTL shipper does; others fall through as nil) into the returned hash
    # so Delivery#append_to_shipping_api_log!(kind: 'void', …) persists
    # something more useful than request: null, response: null.
    return {
      status_code: status_code,
      status_message: "Ship Voiding Error: #{status_message}",
      void_request_xml: shipper.respond_to?(:last_request_payload) ? shipper.last_request_payload : nil,
      void_response_xml: shipper.respond_to?(:last_response_payload) && shipper.last_response_payload ? shipper.last_response_payload : build_error_payload(e)
    }
  end
  { status_code: status_code, status_message: status_message,
    void_request_xml: void_result[:void_request_xml], void_response_xml: void_result[:void_response_xml],
    response_status: void_result[:response_status], response_headers: void_result[:response_headers] }
end

.void_mail_activity(mail_activity, test = Rails.application.config.x.shipping.ups_void_test_mode) ⇒ Object



964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
# File 'app/services/wy_shipping.rb', line 964

def self.void_mail_activity(mail_activity, test = Rails.application.config.x.shipping.ups_void_test_mode)
  status_code = :ok
  status_message = +''
  void_result = nil

  carrier_class = class_for_carrier(mail_activity.carrier)
  shipper = carrier_class.new SHIPPING_BASE_CONFIGURATION.merge(SHIPPING_SHIPPER_CONFIGURATION[mail_activity.address.country_iso3.to_sym])
  shipper.service_code = mail_activity.selected_service_code
  return void_mps_delivery(mail_activity, shipper, test) if mail_activity.shipments.label_complete.length > 1

  s = mail_activity.shipments.order('shipments.id ASC').first
  identifier = s.tracking_number
  identifier = s.shipengine_label_id if s.shipengine_label_id.present? # annoyingly Shipengine uses its own label_id to void, not the master tracking number

  begin
    void_result = shipper.void(identifier)
  rescue StandardError => e
    status_code = :error unless test
    status_code = :warning if test
    status_message = e.to_s
    ErrorReporting.error(e)
    return { status_code: status_code, status_message: "Ship Voiding Error: #{status_message}" }
  end
  { status_code: status_code, status_message: status_message, void_request_xml: void_result[:void_request_xml], void_response_xml: void_result[:void_response_xml] }
end

.void_mps_delivery(delivery, shipper, test) ⇒ Object



2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
# File 'app/services/wy_shipping.rb', line 2132

def self.void_mps_delivery(delivery, shipper, test)
  status_code = :ok
  status_message = ''
  concatenated_void_request_xml = +''
  concatenated_void_response_xml = +''

  delivery.shipments.label_complete.order('shipments.id ASC').each do |s|
    identifier = s.tracking_number
    identifier = s.shipengine_label_id if s.shipengine_label_id.present? # annoyingly Shipengine uses its own label_id to void, not the tracking number

    begin
      void_result = shipper.void(identifier)
    rescue StandardError => e
      status_code = :error unless test
      status_code = :warning if test
      ErrorReporting.error(e)

      return { status_code: status_code, status_message: "Ship Voiding Error: #{status_message}" }
    end
    concatenated_void_request_xml += void_result[:void_request_xml]
    concatenated_void_response_xml += void_result[:void_response_xml]
  end

  { status_code: status_code, status_message: status_message, void_request_xml: concatenated_void_request_xml, void_response_xml: concatenated_void_response_xml }
end

.void_standalone_delivery(standalone_delivery, test = Rails.application.config.x.shipping.ups_void_test_mode) ⇒ Object



1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
# File 'app/services/wy_shipping.rb', line 1082

def self.void_standalone_delivery(standalone_delivery, test = Rails.application.config.x.shipping.ups_void_test_mode)
  status_code = :ok
  status_message = +''
  void_result = nil

  carrier_class = class_for_carrier(standalone_delivery.carrier)
  shipper = carrier_class.new SHIPPING_BASE_CONFIGURATION.merge(SHIPPING_SHIPPER_CONFIGURATION[standalone_delivery.origin_address.country_iso3.to_sym])
  shipper.service_code = standalone_delivery.service_code
  return void_mps_delivery(standalone_delivery, shipper, test) if standalone_delivery.shipments.label_complete.length > 1

  s = standalone_delivery.shipments.order('shipments.id ASC').first
  identifier = s.tracking_number
  identifier = s.shipengine_label_id if s.shipengine_label_id.present? # annoyingly Shipengine uses its own label_id to void, not the master tracking number

  begin
    void_result = shipper.void(identifier)
  rescue StandardError => e
    status_code = :error unless test
    status_code = :warning if test
    status_message = e.to_s
    ErrorReporting.error(e)
    return { status_code: status_code, status_message: "Ship Voiding Error: #{status_message}" }
  end
  { status_code: status_code, status_message: status_message, void_request_xml: void_result[:void_request_xml], void_response_xml: void_result[:void_response_xml] }
end

.void_walmart_sww_delivery(delivery) ⇒ Hash

Void Walmart "Ship with Walmart" labels for a delivery

Parameters:

  • delivery (Delivery)

    The delivery whose labels to void

Returns:

  • (Hash)

    Result with :status_code, :status_message keys



1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
# File 'app/services/wy_shipping.rb', line 1976

def self.void_walmart_sww_delivery(delivery)
  status_code = :ok
  status_message = +''

  # Find all shipments with SWW labels
  # Primary: sww_label_id is set (ideal but rarely populated by Walmart API)
  # Fallback: sww_metadata is populated (always set when SWW labels are purchased)
  shipments_with_labels = delivery.shipments.where.not(sww_label_id: nil)
  shipments_with_labels = delivery.shipments.where("sww_metadata IS NOT NULL AND sww_metadata != '{}'::jsonb") if shipments_with_labels.empty?

  if shipments_with_labels.empty?
    return {
      status_code: :ok,
      status_message: 'No Ship with Walmart labels found to void (no SWW metadata on shipments).'
    }
  end

  voided_count = 0
  failed_count = 0

  shipments_with_labels.each do |shipment|
    purchaser = Edi::Walmart::ShippingLabelPurchaser.new(shipment)
    result = purchaser.void_label(fallback_tracking_number: delivery.master_tracking_number)

    if result[:success]
      voided_count += 1
      Rails.logger.info("[SWW] Voided label for shipment #{shipment.id}")
    else
      failed_count += 1
      status_message += "Failed to void label for shipment #{shipment.id}: #{result[:error]}. "
      Rails.logger.error("[SWW] Failed to void label for shipment #{shipment.id}: #{result[:error]}")
    end
  rescue StandardError => e
    failed_count += 1
    status_message += "Error voiding label for shipment #{shipment.id}: #{e.message}. "
    Rails.logger.error("[SWW] Exception voiding label: #{e.message}")
    ErrorReporting.error(e, shipment_id: shipment.id, delivery_id: delivery.id)
  end

  if failed_count > 0
    status_code = voided_count > 0 ? :warning : :error
  else
    status_message = "Successfully voided #{voided_count} Ship with Walmart label(s)."
  end

  { status_code: status_code, status_message: status_message.strip }
end