Class: WyShipping

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

Constant Summary collapse

COMMERCIAL_INVOICE_COMMENTS =
'PLEASE USE UPS OMD FOR BROKER AND REFERENCE NRI ACCT# W50R74'
MARKETPLACE_CARRIERS =
%w[AmazonSeller WalmartSeller].freeze
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
STANDALONE_RATE_DATA_CARRIERS =
%w[SpeedeeDelivery Freightquote RlCarriers Roadrunner Saia YrcFreight].freeze
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).



1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
# File 'app/services/wy_shipping.rb', line 1031

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.



1570
1571
1572
1573
1574
1575
1576
1577
1578
# File 'app/services/wy_shipping.rb', line 1570

def self.build_amz_per_shipment_rate(base_rate, pkg_rate)
  pkg_rate = pkg_rate.respond_to?(:with_indifferent_access) ? pkg_rate.with_indifferent_access : pkg_rate
  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



1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
# File 'app/services/wy_shipping.rb', line 1585

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],
    available_value_added_services: rate_data[:available_value_added_services],
    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



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
# File 'app/services/wy_shipping.rb', line 95

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?
    if options[:origin_country_iso3] == 'USA'
      # shippers << Shipping::UpsFreight.new(shipper_config.merge(origin).merge(destination)) if carriers.include?('UPSFreight')
      shippers << Shipping::RlCarriers.new(shipper_config.merge(origin).merge(destination)) if carriers.include?('RlCarriers')
      # shippers << Shipping::Roadrunner.new(shipper_config.merge(origin).merge(destination)) if carriers.include?('Roadrunner')
      # shippers << Shipping::Saia.new(shipper_config.merge(origin).merge(destination)) if carriers.include?('Saia')
      # shippers << Shipping::YrcFreight.new(shipper_config.merge(origin).merge(destination)) if carriers.include?('YrcFreight')
      # shippers << Shipping::FedExFreight.new(shipper_config.merge(origin).merge(destination)) if carriers.include?('FedExFreight')
      # shippers << Shipping::ShipengineFedExFreight.new(shipper_config.merge(origin).merge(destination)) if carriers.include?('ShipengineFedExFreight')
      if options[:ltl_freight_guaranteed] # need to use shipping options or better mechanism
        # shippers.detect{|s| s.is_a?(Shipping::UpsFreight) }&.service_code = '309'
        shippers.detect { |s| s.is_a?(Shipping::RlCarriers) }&.service_type = 'Guaranteed' # Only return those R+L Carriers service codes that are guaranteed
        # shippers.detect{|s| s.is_a?(Shipping::Saia) }&.service_type = 'Guaranteed' # Only return those SAIA shipping estimates that can be guaranteed
        # shippers.detect{|s| s.is_a?(Shipping::YrcFreight) }&.service_type = 'Guaranteed' # Only return those YRC Freight shipping estimates that can be guaranteed
      elsif carriers.include?('Freightquote')
        shippers << Shipping::Freightquote.new(shipper_config.merge(origin).merge(destination))
      end
    # Freightquote has no way of requiring guaranteed, though some carriers might return a guaranteed time frame
    elsif options[:origin_country_iso3] == 'CAN'
      shippers << Shipping::Freightquote.new(shipper_config.merge(origin).merge(destination)) if carriers.include?('Freightquote')
      # shippers << Shipping::YrcFreight.new(shipper_config.merge(origin).merge(destination)) if carriers.include?('YrcFreight')
      # shippers << Shipping::FedExFreight.new(shipper_config.merge(origin).merge(destination)) if carriers.include?('FedExFreight')
      # shippers << Shipping::ShipengineFedExFreight.new(shipper_config.merge(origin).merge(destination)) if carriers.include?('ShipengineFedExFreight')
    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 Roadrunner Saia YrcFreight FedExFreight ShipengineFedExFreight].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
      valid_carrier = false if options[:destination_address].present? && !options[:destination_address].not_a_po_box?(carrier)
      # for cart checkout on www, skip non supported carriers
      if options[:www]
        www_carriers = WWW_SHIPPING_CARRIERS[options[:origin_country_iso3].to_sym]
        if options[:destination_address].present? && options[:destination_address].po_box?
          www_carriers = PO_BOX_CARRIERS_BY_COUNTRY[options[:origin_country_iso3].to_sym]
        end # use postal carriers if destination is a 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? { |ct| ct == 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[: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[:service_options_charges].to_f # apply surcharge
      end
      Rails.logger.debug 'AFTER value[:cost]: ' + value[:cost].to_s
    end
  end
  shipping_costs
end

.calculate_ups_canada_billing_weight(options) ⇒ Object



1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
# File 'app/services/wy_shipping.rb', line 1881

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

.check_freightquote_events_for_load_number(delivery) ⇒ Object



1981
1982
1983
1984
1985
# File 'app/services/wy_shipping.rb', line 1981

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



1987
1988
1989
1990
1991
# File 'app/services/wy_shipping.rb', line 1987

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

Raises:

  • (ArgumentError)


28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'app/services/wy_shipping.rb', line 28

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

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

.coerce_standalone_stored_rate_data(raw) ⇒ Object



1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
# File 'app/services/wy_shipping.rb', line 1063

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
           else nil
           end
  return nil unless parsed.is_a?(Hash)

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

.estimate_shipping_cost(options) ⇒ Object



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
463
464
465
466
467
468
469
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
# File 'app/services/wy_shipping.rb', line 349

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 = {}
  futures = []
  default_box_size = Packaging::DEFAULT_BOX_SIZE

  require 'concurrent'

  start_time = Time.current
  Rails.logger.debug { "TIMING! WyShipping.estimate_shipping_cost, time START: #{start_time}" }
  shippers.each do |shipper|
    futures << ConcurrentRails::Promises.delay do
      start_time_shipper = Time.current
      Rails.logger.debug { "TIMING! WyShipping.estimate_shipping_cost, shipper: #{shipper.class.to_s.split('::').last}, time START: #{start_time_shipper}" }
      Rails.logger.debug { "WyShipping.estimate_shipping_cost, shipper: #{shipper}" }
      packages = []
      carrier = shipper.class.to_s.split('::').last # yikes, but need carrier

      # if delivery.present?

      #   packages = []
      #   total_weight = 0
      #   delivery.shipments.top_level.awaiting_label.order('shipments.id ASC').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.container_code, 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{|p| p.lbs}.reverse # may as well sort by heaviest here, making the heaviest box have the master tracking number

      # else

      ship_weights = [ship_weights] unless ship_weights.is_a?(Array)
      # Rails.logger.debug "WyShipping.estimate_shipping_cost, ship_weights: #{ship_weights.inspect}"

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

      # end
      # Rails.logger.debug "WyShipping.estimate_shipping_cost, packages: #{packages.inspect}"
      begin

        shipper.packages = packages.sort_by { |p| p.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 delivery.present?
          # 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,
          # NOTE WE MUST USE THIS FORM OF
          # delivery.line_items.select{|li| li.tax_class == 'g' && li.parent_id == nil}
          # because this code can be called in the before_save callback nightmare and using scopes unexpectedly yields empty arrays, especially when doing store_transfers
          # puts "!!!#{shipper.class}, delivery.line_items.map{|li| [li.id, li.sku, li.quantity]}: #{delivery.line_items.map{|li| [li.id, li.sku, li.quantity]}}"
          # puts "!!!#{shipper.class}, delivery.line_items.goods.map{|li| [li.id, li.sku, li.quantity]}: #{delivery.line_items.goods.map{|li| [li.id, li.sku, li.quantity]}}"
          # puts "!!!#{shipper.class}, delivery.line_items.parents_only.map{|li| [li.id, li.sku, li.quantity]}: #{delivery.line_items.parents_only.map{|li| [li.id, li.sku, li.quantity]}}"
          # puts "!!!#{shipper.class}, delivery.line_items.parents_only.goods.map{|li| [li.id, li.sku, li.quantity]}: #{delivery.line_items.parents_only.goods.map{|li| [li.id, li.sku, li.quantity]}}"
          Rails.logger.debug do
            "!!!#{shipper.class}, delivery.line_items.select{|li| li.tax_class == 'g' && li.parent_id == nil}.map{|li| [li.id, li.sku, li.quantity]}: #{delivery.line_items.select do |li|
              li.tax_class == 'g' && li.parent_id.nil?
            end.map { |li| [li.id, li.sku, li.quantity] }}"
          end
          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 callback path called out above) and report the upstream anomaly so the real
          # source — not the customs payload — gets fixed. Defaulting to 1 here would silently ship
          # incorrect customs 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
          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, '')&.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 # FedEx requires weight
        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
        Rails.logger.warn("#{shipper} rating exception", error: e.message)
        ErrorReporting.warning(e)
        status_descriptions << e.to_s if e.present? && e.to_s.present?
      rescue *Retryable::TIMEOUT_CLASSES => e
        response = nil
        Rails.logger.warn("#{shipper} rating timeout", error: e.message)
        ErrorReporting.warning(e, { carrier: shipper.class.to_s.split('::').last })
        status_descriptions << e.to_s if e.present? && e.to_s.present?
      rescue StandardError => e
        response = nil
        Rails.logger.error "#{shipper} rating exception: #{e.inspect}"
        ErrorReporting.error(e)
        status_descriptions << e.to_s if e.present? && e.to_s.present?
      end
      carrier = shipper.class.to_s.split('::').last # yikes, but need list of carriers
      responses[carrier] = response
      Rails.logger.debug { "TIMING! WyShipping.estimate_shipping_cost, shipper: #{shipper.class.to_s.split('::').last}, time END: #{Time.current}" }
      end_time_shipper = Time.current
      Rails.logger.debug { "TIMING! WyShipping.estimate_shipping_cost, shipper: #{shipper.class.to_s.split('::').last}, time END: #{end_time_shipper}, processing time = #{end_time_shipper - start_time_shipper}" }
      response
      # }
    end
  end
  Rails.logger.debug { "BEFORE futures.map(&:touch), futures.map(&:state): #{futures.map(&:state)}" }
  futures.map(&:touch)
  Rails.logger.debug { "AFTER futures.map(&:touch), futures.map(&:state): #{futures.map(&:state)}" }
  Rails.logger.debug 'AFTER futures.map(&:touch), futures.map(&:value!):'
  futures.map do |f|
    Rails.logger.debug "#{f.value!}"
  end
  Rails.logger.debug { "AFTER futures.map(&:value), futures.map(&:state): #{futures.map(&:state)}" }
  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].to_s + "\n" + response.request
      shipping_costs_status_hash[:rate_response_xml] = shipping_costs_status_hash[:rate_response_xml].to_s + "\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.include?(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}" }
        shipping_option = shipping_options.detect { |so| (rate.service_code == so.service_code) && !service_codes_used.include?(rate.service_code) }
        shipping_option ||= shipping_options.detect { |so| so.carrier == 'Freightquote' && options[:is_freight] }
        if shipping_option.nil? && MARKETPLACE_CARRIERS.include?(carrier)
          notify_missing_marketplace_shipping_option(rate, carrier, shipper.sender_country)
        end
        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
      Rails.logger.info "#{shipper} rating failed: #{response.try(:message)}"
      status_descriptions << response.try(:message) if response.try(:message).present?

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

    if 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
  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.include?(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



788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
# File 'app/services/wy_shipping.rb', line 788

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



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

def self.find_shipengine_postal_mps_rates(shipper, packages)
  futures = packages.map do |package|
    pkg_shipper = shipper.dup
    pkg_shipper.packages = [package]
    ConcurrentRails::Promises.future { pkg_shipper.find_rates }
  end
  begin
    rate_responses = futures.map(&:value!)
  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.map { |r| r[:message] }.join('. ')
  mps_response[:request] = rate_responses.map { |r| r[:request] }.join(' | ')
  mps_response[:xml] = rate_responses.map { |r| r[: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.detect { |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



916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
# File 'app/services/wy_shipping.rb', line 916

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

.get_equivalent_cost_from_ups(shipping_option_sym, shipping_costs_hash) ⇒ Object



687
688
689
690
691
692
693
694
# File 'app/services/wy_shipping.rb', line 687

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



343
344
345
346
347
# File 'app/services/wy_shipping.rb', line 343

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



1969
1970
1971
1972
1973
1974
1975
# File 'app/services/wy_shipping.rb', line 1969

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)


767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
# File 'app/services/wy_shipping.rb', line 767

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

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



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
2023
2024
2025
2026
2027
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
# File 'app/services/wy_shipping.rb', line 1996

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
  )

  InternalMailer.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



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'app/services/wy_shipping.rb', line 47

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:



877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
# File 'app/services/wy_shipping.rb', line 877

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 { |p| p.lbs }.reverse # may as well sort by heaviest here

  shipper
end

.populate_shipper_data_for_standalone_delivery(standalone_delivery, carrier) ⇒ Object



989
990
991
992
993
994
995
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
# File 'app/services/wy_shipping.rb', line 989

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 { |p| p.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



1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
# File 'app/services/wy_shipping.rb', line 1543

def self.refresh_amzbs_rates_if_stale(delivery, selected_shipping_cost)
  return selected_shipping_cost unless selected_shipping_cost&.rate_data.present?

  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 unless rate_data[:amz_request_token].present?

  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

.sanitize_phone(phone) ⇒ Object



1977
1978
1979
# File 'app/services/wy_shipping.rb', line 1977

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



1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
# File 'app/services/wy_shipping.rb', line 1838

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



1078
1079
1080
1081
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
1107
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
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
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
# File 'app/services/wy_shipping.rb', line 1078

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
  if Edi::MarketplaceLabelPurchaser.supports_marketplace_labels?(delivery)
    return ship_marketplace_delivery(delivery, additional_status_message)
  end

  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 # FedEx requires weight

  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 = +''

  if delivery.bill_shipping_to_customer && delivery.chosen_shipping_method&. && delivery.ship_natively_key.nil?
    # Rails.logger.debug "WyShipping.ship_delivery: delivery.chosen_shipping_method.shipping_account_number: #{delivery.chosen_shipping_method.shipping_account_number.inspect}"
    shipper.pay_type = 'bill_third_party'
    shipper. = delivery.chosen_shipping_method..
    shipper.billing_zip = delivery.chosen_shipping_method..billing_zip.delete(' ').delete('-')
    shipper.billing_country = delivery.country.iso
  elsif ['Canadapost'].include?(delivery.carrier) && delivery.ship_natively_key.present? # need to support Canada Post pattern for ship_natively
    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.to_s + ', ' + delivery.order&.label_instructions.to_s).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}" # "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}" # This corresponds to INV, use the Zoro Sales Order number, if any
    shipper.reference_number_2 = "#{customer_order_number}" # This corresponds to REF, this is the Zoro Customer Order Number
    shipper.reference_number_3 = "#{delivery.order.po_number.to_s.gsub(/\P{ASCII}/u, '')&.first(char_limit)}" #  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'
    # implement the R+L Carrers scheme for ref numbers:
    # ReferenceNumbers:
    #   1) ShipperNumber
    #   2) QuoteNumber
    #   3) PONumber
    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 == 'Saia'
    # implement the SAIA scheme for PO Number:
    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 Roadrunner Saia YrcFreight FedExFreight ShipengineFedExFreight].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 Roadrunner Saia YrcFreight].include?(delivery.carrier)
    # need extra rate data here to ship
    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 { |p| p.lbs }.reverse # may as well sort by heaviest here, making the heaviest box have the master tracking number

  shipper.packages = packages

  if %w[Canadapost USPS].include?(delivery.carrier) && awaiting_label_shipments.length > 1
    return ship_shipengine_postal_mps_delivery(delivery, shipper, packages, total_weight, additional_status_message)
  end
  shipper.skip_png_download = !delivery.is_rma_return?
  begin
    Rails.logger.debug { "WYSHIPPING#ship_delivery: shipper.insured_value: #{shipper.insured_value}, delivery.calculate_declared_value: #{delivery.calculate_declared_value}" }
    label_result = shipper.label(false)
  rescue ShipEngineRb::Exceptions::ShipEngineError => e
    Rails.logger.warn("WYSHIPPING#ship_delivery: ShipEngine error", error: e.message)
    status_code = :error
    status_message = e.to_s
    ErrorReporting.error(e)
  rescue StandardError => e
    status_code = :error
    status_message = e.to_s
    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'
    return { status_code: status_code, status_message: "Shipping Error: #{status_message}#{additional_status_message}" }
  end
  { status_code: status_code, status_message: "#{status_message}#{additional_status_message}", shipment: label_result }
end

.ship_mail_activity(mail_activity) ⇒ Object



829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
# File 'app/services/wy_shipping.rb', line 829

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



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

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
  unless selected_shipping_cost&.rate_data.present?
    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)
    unless selected_shipping_cost&.rate_data.present?
      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

  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)

      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,
    shipment: label_results.first # Return first for compatibility with existing code
  }
end

.ship_shipengine_postal_mps_delivery(_delivery, shipper, packages, _total_weight, additional_status_message = '') ⇒ Object



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

def self.ship_shipengine_postal_mps_delivery(_delivery, shipper, packages, _total_weight, additional_status_message = '')
  status_code = :ok
  status_message = +''
  label_results = []
  concatenated_ship_request_xml = +''
  concatenated_ship_reply_xml = +''
  total_price = 0.0

  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
    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
    label_results << label_result[:labels].first
    concatenated_ship_request_xml += label_result[:ship_request_xml]
    concatenated_ship_reply_xml += 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: concatenated_ship_request_xml, ship_reply_xml: concatenated_ship_reply_xml } }
end

.ship_standalone_delivery(standalone_delivery) ⇒ Object



936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
# File 'app/services/wy_shipping.rb', line 936

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

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



1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
# File 'app/services/wy_shipping.rb', line 1043

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.



1959
1960
1961
1962
1963
1964
1965
1966
1967
# File 'app/services/wy_shipping.rb', line 1959

def self.start_tracking_for_carrier(tracking_number, carrier_name)
  carrier_class = class_for_carrier(carrier_name)
  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



1897
1898
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
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
# File 'app/services/wy_shipping.rb', line 1897

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
    unless carrier_name.present?
      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.
  # Only override carrier_name if class_for_carrier can resolve it; otherwise
  # keep 'AmazonSeller' so the Amazon tracking client handles it.
  if carrier_name == 'AmazonSeller'
    amz_carrier = shipment.amz_carrier
    if amz_carrier.present?
      begin
        class_for_carrier(amz_carrier)
        carrier_name = amz_carrier
      rescue ArgumentError, NameError
        Rails.logger.warn { "[WyShipping] Unknown Amazon carrier '#{amz_carrier}' for shipment #{shipment.id}, falling back to AmazonSeller tracking" }
      end
    else
      return {
        status_code: :error,
        status_message: 'Cannot track AmazonSeller shipment: underlying carrier not set in amz_metadata'
      }
    end
  end

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

  carrier_class = class_for_carrier(carrier_name)
  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)


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
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
# File 'app/services/wy_shipping.rb', line 696

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



1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
# File 'app/services/wy_shipping.rb', line 1747

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

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

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



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

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 = UPS_VOID_TEST_MODE) ⇒ Object



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

def self.void_delivery(delivery, test = UPS_VOID_TEST_MODE)
  # Handle Walmart "Ship with Walmart" label voiding separately
  if delivery.carrier == 'WalmartSeller' && delivery.order&.edi_orchestrator_partner&.start_with?('walmart_seller')
    return void_walmart_sww_delivery(delivery)
  end

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

  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)

    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_mail_activity(mail_activity, test = UPS_VOID_TEST_MODE) ⇒ Object



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

def self.void_mail_activity(mail_activity, test = 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



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

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 = UPS_VOID_TEST_MODE) ⇒ Object



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

def self.void_standalone_delivery(standalone_delivery, test = 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



1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
# File 'app/services/wy_shipping.rb', line 1691

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)
  if shipments_with_labels.empty?
    shipments_with_labels = delivery.shipments.where("sww_metadata IS NOT NULL AND sww_metadata != '{}'::jsonb")
  end

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