Class: Shipping::RlCarriers

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

Overview

Service class wrapping the R+L Carriers SOAP API for LTL freight rate quoting,
bill-of-lading creation, and BOL PDF retrieval.

See: https://b2b.freightquote.com/WebService/QuoteService.asmx

find_rates and label here are deliberately long, top-to-bottom XML builders
that mirror the R+L request schema; method_length / abc_size / block_length
metrics are kept on purpose for readability. @reference_number_2/_3 are
carried verbatim from Delivery to align with the carrier's quote/PO refs.
rubocop:disable Metrics/ClassLength, Metrics/MethodLength, Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity, Metrics/BlockLength, Naming/VariableNumber

Constant Summary collapse

COST_DISCREPANCY_THRESHOLD =
200.0
COST_DISCREPANCY_THRESHOLD_RATIO =

this is max ratio of discrepancy by total shipping cost

0.5
COST_DISCREPANCY_THRESHOLD_BY_TOTAL_VALUE_RATIO =

this is max ratio of discrepancy by total delivery value

0.05

Instance Attribute Summary

Attributes inherited from Base

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

Instance Method Summary collapse

Methods inherited from Base

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

Constructor Details

This class inherits a constructor from Shipping::Base

Instance Method Details

#find_rates(logger = nil) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
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
# File 'app/services/shipping/rl_carriers.rb', line 17

def find_rates(logger = nil)
  logger ||= Rails.logger
  @required = %i[zip country sender_state sender_zip sender_country packages]
  @required += %i[rl_carriers_api_key insured_value]

  @insured_value = 50_000.0 if @insured_value.to_f > 50_000.0 # UPS limits this to 50000.0 for domestic
  @country ||= 'US'
  @sender_country ||= 'US'
  country_iso3 = Country.iso_to_iso3_map[@country]
  sender_country_iso3 = Country.iso_to_iso3_map[@sender_country]
  @rl_carriers_rating_url ||= 'https://api.rlcarriers.com/1.0.3/RateQuoteService.asmx'

  @data = +''
  b = Builder::XmlMarkup.new target: @data
  b.instruct!

  b.tag!('soap:Envelope', { 'xmlns:soap' => 'http://schemas.xmlsoap.org/soap/envelope/', 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance', 'xmlns:xsd' => 'http://www.w3.org/2001/XMLSchema' }) do |b|
    b.tag!('soap:Body') do |b|
      b.GetRateQuote(xmlns: 'http://www.rlcarriers.com/') do |b|
        b.APIKey @rl_carriers_api_key
        b.request do |b|
          quote_type = 'Domestic'
          quote_type = 'International' if (@sender_country != @country) && (%w[US CA].exclude?(@country) || %w[US CA].exclude?(@sender_country)) # CA to US or vice versa is considered domestic, apparently
          quote_type = 'AlaskaHawaii' if %w[AK HI].include?(@state) && quote_type == 'Domestic'
          b.QuoteType quote_type # Domestic or AlaskaHawaii or International
          b.CODAmount 0.00
          b.Origin do |b|
            b.City @sender_city
            b.StateOrProvince @sender_state
            b.ZipOrPostalCode @sender_zip
            b.CountryCode sender_country_iso3
          end
          b.Destination do |b|
            b.City @city
            b.StateOrProvince @state
            b.ZipOrPostalCode @zip
            b.CountryCode country_iso3
          end
          b.Items do |b|
            @packages.each_with_index do |package, _i|
              freight_class = get_freight_class_from_package(package)
              b.Item do |b|
                b.Class freight_class
                # Freight quote uses US units, lbs, inches
                value = package.lbs
                package_weight = [value, 1.0].max.round
                value = package.inches(:length)
                package_length = [value, 0.1].max.round
                value = package.inches(:width)
                package_width = [value, 0.1].max.round
                value = package.inches(:height)
                package_height = [value, 0.1].max.round
                b.Weight package_weight
                b.Width package_width
                b.Height package_height
                b.Length package_length
              end
            end
          end
          b.DeclaredValue @insured_value.to_f.round(2)
          # Valid R+L accessorials: InsideDelivery, ResidentialPickup, ResidentialDelivery,
          # OriginLiftgate, DestinationLiftgate, DeliveryNotification, SortAndSegregate, Freezable,
          # Hazmat, InsidePickup, LimitedAccessPickup, DockPickup, DockDelivery, AirportPickup,
          # AirportDelivery, LimitedAccessDelivery, CubicFeet, KeepFromFreezing, DoorToDoor,
          # COD, OverDimension.
          b.Accessorials do |b|
            {
              InsidePickup: @sender_requires_inside_delivery || false,
              ResidentialPickup: @sender_address_residential || false,
              OriginLiftgate: @sender_requires_liftgate || false,
              DockPickup: @sender_has_loading_dock || false,
              LimitedAccessPickup: @sender_limited_access || false,
              InsideDelivery: @requires_inside_delivery || false,
              ResidentialDelivery: @address_residential || false,
              DestinationLiftgate: @requires_liftgate.nil? || @requires_liftgate,
              DockDelivery: @has_loading_dock || false,
              LimitedAccessDelivery: @limited_access || false,
              DeliveryNotification: @requires_appointment || false
            }.each do |acc, apply_acc|
              b.RqAccessorial acc.to_s if apply_acc
            end
          end
        end
      end
    end
  end

  get_response(@rl_carriers_rating_url, { 'Content-Type' => 'text/xml' })
  logger.info 'Shipping RlCarriers find_rates Request:'
  logger.info @rl_carriers_rating_url.to_s
  logger.info @data.to_s
  logger.info 'Shipping RlCarriers find_rates Response:'
  logger.info @response.to_s
  rate_estimates = []
  successful, = nil
  success = REXML::XPath.first(@response, '//soap:Envelope/soap:Body/GetRateQuoteResponse/GetRateQuoteResult/WasSuccess').text
  successful = true if success == 'true'
  if successful
    REXML::XPath.each(@response, '//soap:Envelope/soap:Body/GetRateQuoteResponse/GetRateQuoteResult/Result/ServiceLevels/ServiceLevel') do |service_levels|
      service_xml = REXML::Document.new(service_levels.to_s)
      service_title = REXML::XPath.first(service_xml, '//Title').text
      service_code = REXML::XPath.first(service_xml, '//Code').text
      price = REXML::XPath.first(service_xml, '//NetCharge').text.delete('$').delete(',').to_f
      days_in_transit = REXML::XPath.first(service_xml, '//ServiceDays').text.to_i + 3 # per Christian and JJ
      quote_number = REXML::XPath.first(service_xml, '//QuoteNumber').text
      transportation_charges = price
      skip = false
      # skip GSHW which requires defining a one hour window for delivery, problematic... Also skip non guaranteed services if guaranteed was requested
      skip = true if service_code == 'GSHW' || (@service_type != 'Guaranteed' && service_title.to_s.downcase.index('guaranteed').present?) || (@service_type == 'Guaranteed' && service_title.to_s.downcase.index('guaranteed').nil?)
      next unless price && service_code && skip != true

      estimate = {}
      estimate[:service_code] = service_code
      estimate[:price] = price
      estimate[:total_charges] = price
      estimate[:transportation_charges] = transportation_charges
      estimate[:service_options_charges] = 0.0
      estimate[:insured_value] = @insured_value.to_f.round(2)
      estimate[:currency] = 'USD'
      rate_data = {
        quote_number:,
        total_price: price,
        days_in_transit:
      }
      estimate[:rate_data] = rate_data
      # allows for things like estimate.service_code
      def estimate.method_missing(name, *args)
        key?(name) ? self[name] : super
      end

      def estimate.respond_to_missing?(name, include_private = false)
        key?(name) || super
      end
      rate_estimates << estimate
    end
  end

  msg = ''
  if rate_estimates.empty?
    err_msgs = []
    REXML::XPath.first(@response, '//soap:Envelope/soap:Body/GetRateQuoteResponse/GetRateQuoteResult/Messages') do |err_msg|
      err_msgs << err_msg
    end
    msg = "No shipping rates could be found for the destination address: #{err_msgs.join(', ')}" if msg.blank?
  end

  response = {}
  response[:success] = successful
  response[:message] = "R+L Carriers: #{msg}" if msg.present?
  response[:request] = @data.to_s
  response[:xml] = @response.to_s
  response[:rates] = rate_estimates

  # allows for things like fedex.success?
  def response.method_missing(name, *args)
    key?(name) ? self[name] : super
  end

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

  response
end

#get_bol_pdf_file(bol_id) ⇒ Object

if successful
enc_label_image = REXML::XPath.first(@response, "//soap:Envelope/soap:Body/GetBillOfLadingLabelPDFResponse/GetBillOfLadingLabelPDFResult/PdfDocument").text
shipping_label_pdf_file = Tempfile.new("shipping_label")
shipping_label_pdf_file.binmode
shipping_label_pdf_file.write Base64.decode64(enc_label_image)
shipping_label_pdf_file.rewind
return shipping_label_pdf_file
else
err_msgs = []
REXML::XPath.first(@response, "//soap:Envelope/soap:Body/GetBillOfLadingLabelPDFResponse/GetBillOfLadingLabelPDFResult/Messages") do |err_msg|
err_msgs << err_msg
end
msg = "GetBillOfLadingLabelPDF did not succeed: #')" if msg.blank?
successful = false
raise ShippingError, msg
end
end



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
# File 'app/services/shipping/rl_carriers.rb', line 491

def get_bol_pdf_file(bol_id)
  logger ||= Rails.logger
  @data = +''
  b = Builder::XmlMarkup.new target: @data
  b.instruct!
  b.tag!('soap:Envelope', { 'xmlns:soap' => 'http://schemas.xmlsoap.org/soap/envelope/', 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance', 'xmlns:xsd' => 'http://www.w3.org/2001/XMLSchema' }) do |b|
    b.tag!('soap:Body') do |b|
      b.GetBillOfLadingPdf(xmlns: 'http://www.rlcarriers.com/') do |b|
        b.APIKey @rl_carriers_api_key
        b.billOfLadingId bol_id
      end
    end
  end

  get_response(@rl_carriers_shipping_url, { 'Content-Type' => 'text/xml' })
  logger.info 'Shipping RlCarriers GetBillOfLadingPdf Request:'
  logger.info @rl_carriers_shipping_url.to_s
  logger.info @data.to_s
  logger.info 'Shipping RlCarriers GetBillOfLadingPdf Response:'
  logger.info @response.to_s

  successful, msg = nil
  success = REXML::XPath.first(@response, '//soap:Envelope/soap:Body/GetBillOfLadingPdfResponse/GetBillOfLadingPdfResult/WasSuccess').text
  successful = true if success == 'true'

  if successful
    enc_label_image = REXML::XPath.first(@response, '//soap:Envelope/soap:Body/GetBillOfLadingPdfResponse/GetBillOfLadingPdfResult/PdfDocument').text
    bol_pdf_file = Tempfile.new('bol')
    bol_pdf_file.binmode
    bol_pdf_file.write Base64.decode64(enc_label_image)
    bol_pdf_file.rewind
    bol_pdf_file.flush
    bol_pdf_file.fsync
    bol_pdf_file
  else
    err_msgs = []
    REXML::XPath.first(@response, '//soap:Envelope/soap:Body/GetBillOfLadingPdfResponse/GetBillOfLadingPdfResult/Messages') do |err_msg|
      err_msgs << err_msg
    end
    msg = "GetBillOfLadingPdf did not succeed: #{err_msgs.join(', ')}" if msg.blank?
    raise ShippingError, "#{msg}, data sent to #{@rl_carriers_shipping_url}: #{@data}"
  end
end

#get_freight_class_from_package(package) ⇒ Object



433
434
435
436
437
438
439
440
441
442
443
# File 'app/services/shipping/rl_carriers.rb', line 433

def get_freight_class_from_package(package)
  # get total weight in lbs and cubic feet of package, and figure out density in lbs per cubic foot or PCF
  total_weight = package.lbs.to_f
  total_cubic_ft = package.inches(:length).to_f * package.inches(:width).to_f * package.inches(:height).to_f / 1728.0
  pcf = total_weight / total_cubic_ft
  UpsFreight::FREIGHT_CLASS_BY_PCF.each do |freight_class, pcf_limits|
    return freight_class if pcf >= pcf_limits[:lower] && pcf < pcf_limits[:upper]
  end
  # worst case return the highest freight class
  UpsFreight::FREIGHT_CLASS_BY_PCF.to_a.last.first.to_f
end

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

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



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

def label(_return_label = false, logger = nil) # rubocop:disable Style/OptionalBooleanParameter -- positional signature shared across all Shipping::* carriers
  logger ||= Rails.logger
  @required = %i[zip country sender_state sender_zip sender_country packages service_code]
  @required += %i[rl_carriers_api_key rate_data insured_value]
  @skip_rate_test = true # workaround for now until we can fix the consisten issue we are seeing with Rl Carriers...

  check_required

  unless @skip_rate_test # here we have an ST, and don't care about comparing rates

    # Here we need to re-rate quote, because we have no way to get a total price charged for a bill of lading from R+L Carriers so we re-quote just before

    total_price = @rate_data['total_price'].to_f
    # So let's re-find rates, but with the new criteria for the label
    estimate_res = find_rates
    # find the matching rate based on the service code
    estimate = estimate_res[:rates].detect { |e| e[:service_code] == @service_code }

    raise ShippingError, 'Rate has expired or now exceeds thresholds, please HOLD order and refresh shipping rates/methods' unless estimate.present? && (new_total_price = estimate.dig(:rate_data, :total_price)) && total_price

    diff = (new_total_price - total_price).abs
    if diff && (
        ((diff < COST_DISCREPANCY_THRESHOLD) && (diff / total_price < COST_DISCREPANCY_THRESHOLD_RATIO)) ||
        ((@delivery_total_value.to_f > 0.0) && (@delivery_total_value.to_f > COST_DISCREPANCY_THRESHOLD * 10.0) && (diff / @delivery_total_value.to_f < COST_DISCREPANCY_THRESHOLD_BY_TOTAL_VALUE_RATIO)
        )
      )
      # we have a matching rate using the @service_code matching
      total_price = new_total_price
      @reference_number_2 = estimate.dig(:rate_data, :quote_number) || @rate_data['quote_number']
    else
      # no match or pricing threshold exceeded
      raise ShippingError, 'Rate has expired or now exceeds thresholds, please HOLD order and refresh shipping rates/methods'
    end

    # no match or pricing threshold exceeded

  end

  @insured_value = 50_000.0 if @insured_value.to_f > 50_000.0 # UPS limits this to 50000.0 for domestic
  @country ||= 'US'
  @sender_country ||= 'US'
  country_iso3 = Country.iso_to_iso3_map[@country]
  sender_country_iso3 = Country.iso_to_iso3_map[@sender_country]
  shipper_country_iso3 = Country.iso_to_iso3_map[@shipper_country]
  @rl_carriers_shipping_url ||= 'https://api.rlcarriers.com/sandbox/BillOfLadingService.asmx'

  datetime = Time.current
  tz = 'America/Chicago'
  tz = 'Eastern Time (US & Canada)' if @sender_country == 'CA'
  Time.use_zone(tz) do
    datetime = Time.current
    datetime = 1.working.day.since(Time.zone.parse('10:00:00')) if datetime > Time.zone.parse('3:00pm')
  end

  @data = +''
  b = Builder::XmlMarkup.new target: @data
  b.instruct!

  b.tag!('soap:Envelope', { 'xmlns:soap' => 'http://schemas.xmlsoap.org/soap/envelope/', 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance', 'xmlns:xsd' => 'http://www.w3.org/2001/XMLSchema' }) do |b|
    b.tag!('soap:Body') do |b|
      b.CreateBillOfLading(xmlns: 'http://www.rlcarriers.com/') do |b|
        b.APIKey @rl_carriers_api_key
        b.request do |b|
          b.BillOfLading do |b|
            b.BOLDate datetime.strftime('%m/%d/%Y')
            b.Shipper do |b| # TBD rb_any_ship_from populate BillTo for drop-shipping
              b.Name @sender_company
              b.EmailAddress(Rails.env.production? ? @sender_email : 'rblatt@warmlyyours.com') # they do send email notifications even in dev
              b.AddressLine1 @sender_address
              b.AddressLine2 @sender_address2
              b.ISO3Country sender_country_iso3
              b.ZipCode @sender_zip
              b.City @sender_city
              b.State @sender_state
              b.PhoneNumber @sender_phone
            end
            b.Consignee do |b|
              b.Attention @attention_name
              b.Name @company
              b.EmailAddress(Rails.env.production? ? @email : 'rblatt@warmlyyours.com') # they do send email notifications even in dev
              b.AddressLine1 @address
              b.AddressLine2 @address2
              b.ISO3Country country_iso3
              b.ZipCode @zip
              b.City @city
              b.State @state
              b.PhoneNumber @phone
            end
            origin_same_as_shipper = true
            # Sometimes the addresses can be similar but not the same, for e.g:
            # @sender_address "300 GRANTON DR"
            # @shipper_address "300 Granton Drive"
            # so use this test
            origin_same_as_shipper = false if @sender_address.to_s.downcase.index(@shipper_address.to_s.downcase).nil? && @shipper_address.to_s.downcase.index(@sender_address.to_s.downcase).nil?
            if origin_same_as_shipper != true
              b.BillTo do |b| # TBD rb_any_ship_from populate BillTo for drop-shipping
                b.Name @shipper_company
                b.EmailAddress(Rails.env.production? ? @shipper_email : 'rblatt@warmlyyours.com') # they do send email notifications even in dev
                b.AddressLine1 @shipper_address
                b.AddressLine2 @shipper_address2
                b.ISO3Country shipper_country_iso3
                b.ZipCode @shipper_zip
                b.City @shipper_city
                b.State @shipper_state
                b.PhoneNumber @shipper_phone
              end
            end
            if @sender_country != @country
              b.Broker do |b|
                # Hardcoded Willson International (CA: Toronto / US: NY)
                b.Name 'Willson International'
                b.EmailAddress 'service@willsonintl.com'
                if @country.index('CA')
                  b.AddressLine1 '2345 Argentia Road'
                  b.AddressLine2 'Suite 201'
                  b.ISO3Country 'CAN'
                  b.ZipCode 'L5N 8K4'
                  b.City 'Mississauga'
                  b.State 'ON'
                  b.PhoneNumber '905-643-9054'
                else
                  b.AddressLine1 '160 Wales Avenue'
                  b.AddressLine2 'Suite 100'
                  b.ISO3Country 'USA'
                  b.ZipCode '14150'
                  b.City 'Tonawanda'
                  b.State 'NY'
                  b.PhoneNumber '800-315-1918'
                end
                # Here we are hardcoding Willson International
              end
            end
            b.AdditionalServices do |b| # OriginLiftgate or DestinationLiftgate or InsidePickup or InsideDelivery or LimitedAccessPickup or LimitedAccessDelivery or FreezeProtection or DeliveryNotification
              {
                OriginLiftgate: @sender_requires_liftgate || false,
                DestinationLiftgate: @requires_liftgate || false,
                InsidePickup: @sender_requires_inside_delivery || false,
                InsideDelivery: @requires_inside_delivery || false,
                LimitedAccessPickup: @sender_limited_access || false,
                LimitedAccessDelivery: @limited_access || false,
                DeliveryNotification: @requires_appointment || false # this is not a notification but a flag to create an appointment per rlcarriers.com site, strangely no corresponding PickupNotification flag is in the docs
              }.each do |acc, apply_acc|
                b.BOLAccessorial acc.to_s if apply_acc
              end
            end
            b.Items do |b|
              @packages.each_with_index do |package, _i|
                freight_class = get_freight_class_from_package(package)
                b.Item do |b|
                  container_type = (if package.pallet?
                                      'PLT'
                                    else
                                      (package.crate? ? 'CRT' : 'CTN')
                                    end)
                  b.IsHazMat false
                  b.Pieces 1
                  b.PackageType container_type
                  # R&L has strict NMFC code and subclass match to FreightClass so forgetaboutit
                  # b.NMFCItemNumber package.nmfc_code if package.nmfc_code
                  # b.NMFCClass package.nmfc_class
                  b.Class freight_class
                  # Freight quote uses US units, lbs, inches
                  value = package.lbs
                  package_weight = [value, 1.0].max.round
                  # value = package.inches(:length)
                  # package_length = [value,0.1].max.round
                  # value = package.inches(:width)
                  # package_width = [value,0.1].max.round
                  # value = package.inches(:height)
                  # package_height = [value,0.1].max.round
                  b.Weight package_weight
                  # b.Width package_width
                  # b.Height package_height
                  # b.Length package_length
                  b.Description 'Radiant Heating Elements and Controls'
                end
              end
            end
            b.DeclaredValue do |b|
              b.Value @insured_value.to_f.round(2)
              b.Per 'entire shipment'
            end
            # Here we add in ALL CAPS the special services requested to the special instructions, since there have been issues with inside delivery and liftgate at destination
            if @sender_requires_liftgate || @requires_liftgate || @sender_requires_inside_delivery || @requires_inside_delivery || @sender_limited_access || @limited_access || @requires_appointment
              reqs = []
              reqs << 'ORIGIN LIFTGATE' if @sender_requires_liftgate
              reqs << 'DESTINATION LIFTGATE' if @requires_liftgate
              reqs << 'INSIDE PICKUP' if @sender_requires_inside_delivery
              reqs << 'INSIDE DELIVERY' if @requires_inside_delivery
              reqs << 'LIMITED ACCESS PICKUP' if @sender_limited_access
              reqs << 'LIMITED ACCESS DELIVERY' if @limited_access
              reqs << 'DELIVERY APPOINTMENT' if @requires_appointment
              b.SpecialInstructions "#{@special_instructions} #{reqs.join(', ')} REQUESTED"
            end
            b.ReferenceNumbers do |b|
              b.ShipperNumber @reference_number_1
              b.QuoteNumber @reference_number_2
              b.PONumber @reference_number_3
            end
            b.FreightChargePaymentMethod 'Prepaid'
          end
          b.AddPickupRequest true
          b.PickupRequestInfo do |b|
            b.PickupDate datetime.strftime('%m/%d/%Y')
            b.ReadyTime datetime.strftime('%I:%M %p')
            b.CloseTime '05:00 PM'
          end
        end
      end
    end
  end

  logger.info 'Shipping RlCarriers label Request:'
  logger.info @rl_carriers_shipping_url.to_s
  logger.info @data.to_s
  get_response(@rl_carriers_shipping_url, { 'Content-Type' => 'text/xml' })
  logger.info 'Shipping RlCarriers label Response:'
  logger.info @response.to_s

  successful, msg = nil
  success = REXML::XPath.first(@response, '//soap:Envelope/soap:Body/CreateBillOfLadingResponse/CreateBillOfLadingResult/WasSuccess').text
  successful = true if success == 'true'

  response = {}
  if successful
    bol_id = REXML::XPath.first(@response, '//soap:Envelope/soap:Body/CreateBillOfLadingResponse/CreateBillOfLadingResult/BolID').text
    web_pro_number = REXML::XPath.first(@response, '//soap:Envelope/soap:Body/CreateBillOfLadingResponse/CreateBillOfLadingResult/WebProNumber').text
    pickup_req_number = REXML::XPath.first(@response, '//soap:Envelope/soap:Body/CreateBillOfLadingResponse/CreateBillOfLadingResult/PickupRequestNumber').text
    response[:tracking_number] = web_pro_number
    response[:bol_image] = get_bol_pdf_file(bol_id)
  else
    err_msgs = []
    REXML::XPath.first(@response, '//soap:Envelope/soap:Body/CreateBillOfLadingResponse/CreateBillOfLadingResult/Messages') do |err_msg|
      err_msgs << err_msg
    end
    msg = "Ship Labeling did not succeed: #{err_msgs.join(', ')}" if msg.blank?
    raise ShippingError, "#{msg}, data sent to #{@rl_carriers_shipping_url}: #{@data}"
  end

  # allows for things like fedex.success?
  def response.method_missing(name, *args)
    key?(name) ? self[name] : super
  end

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

  { labels: [response], shipment_identification_number: web_pro_number, carrier_bol: bol_id, pickup_confirmation_number: pickup_req_number, total_charges: total_price, ship_request_xml: @data.to_s, ship_reply_xml: @response.to_s }
end