Class: Shipping::SaiaLegacy

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

Overview

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
ERR_DESCRIPTIONS_BY_CODE_HASH =
{
  'IXD' => 'Invalid XML Document. The XML Document received was not formatted properly. The <Message> returned will contain additional information about the specific issue encountered. Please check that all required elements and casing are formated exactly as defined in the document specifications above. Also verify that proper start and ending element tags are correct.',
  'IMC' => 'Invalid Method Called. The XML Request Document received contains a root element method name which is not valid. Please verify the name of the method and proper casing.',
  'IED' => 'Invalid Element Data. The element received contains invalid data. This error is returned when an element is required to contain a specific set of information. Such as Yes or No, or Prepaid or Collect.',
  'IEL' => "Invalid Element Data Length. The element received contains data that does not meet the required length specifications. If an element is defined as a String with max-length of '10', you cannot exceed 10 characters. If an element is defined as a Decimal with a max-length of '4, 2', you cannot exceed 4 total digits with 2 of them being after the decimal point. If an element is defined as an Array with max-length of '5', you cannot pass more than 5 elements within the array.",
  'IEF' => "Invalid Element Data Format. The element received contains data that does not meet the required format. For example, all dates are in YYYY-MM-DD which translates to a 4 digit year, a 2 digit month, and a 2 digit day delimited with '-'. All times are in HH:MM:SS format which translates to a 2 digit hour, a 2 digit minute, and a 2 digit second in 24-hour format delimited with ':'.",
  'IER' => 'Invalid Element Data Range. The element received contains data that does not meet the required range. (Range 1 to 10 = 1 lowest and 10 highest)',
  'DNF' => 'Data Not Found. The element received contains data which was not found in our system.',
  'MRE' => 'Missing Required Element. The XML Document received is missing a required element.',
  'USE' => "Unexpected Server Exception. Saia's system has encountered an unexpected error while processing your request. Web Support has been notified with the details of this issue and will have it corrected as soon as possible.",
  'U01' => 'UserID and Password Incorrect',
  'U02' => 'UserID is Disabled. The specified UserID is currently listed as disabled. For more information please contact websupport@saia.com',
  'U03' => 'UserID is Currently Being Setup. The specified UserID is currently being setup. This process generally takes up to 2 business days to complete.',
  'U04' => 'Access Denied for Account Number Specified. The UserID supplied does not have access to the account number specified. Please contact your local Saia Sales Representative for more information.',
  'U05' => 'UserID is Missing Information UserID is missing valid Contact Name, Local Phone Number, or E-mail Address. To update contact information please login to Saia Secure and click the Update Account Information displayed at the bottom of all webpages.',
  'U06' => 'Account Number Specified is Listed as Inactive. The account number specified is currently listed as inactive, please contact your local Saia Sales Representative.',
  'U07' => 'Account Number Specified Cannot be Used for this Function. Please contact websupport@saia.com for more information.',
  'U08' => 'Web Service Disabled. Web Service requests have been disabled for the specified UserID. Please contact websupport@saia.com for more information.',
  'B01' => 'COD Amount limit is $15,000.00',
  'B02' => 'Actual Weight exceeds 15,000 lbs and cannot be auto-quoted',
  'B03' => 'Due to confidential agreement, disclosure of third party information is denied per customer request',
  'B04' => 'Rated Weight exceeds 20,000 lbs and cannot be auto-quoted',
  'B05' => 'Unable to auto-generate a quote for the specified Account',
  'B06' => 'Element of Dimension is greater than maximum.',
  'S01' => 'Origin City and State not within our direct coverage area',
  'S02' => 'Origin Zipcode not within our direct coverage area',
  'S03' => 'Origin City, State, and Zipcode do not match',
  'S04' => 'Destination City, State, and Zipcode do not match',
  'S05' => 'This point is not in our direct coverage for Mexico. Please contact rates@saia.com',
  'S06' => 'Unable to auto quote from Mexico to Mexico. Please contact rates@saia.com',
  'S07' => 'Unable to auto quote (specific accessorial) for Mexico. Please contact rates@saia.com',
  'S08' => 'Unable to auto quote with a COD Amount for Mexico Please contact rates@saia.com',
  'S09' => 'Unable to auto quote from Mexico to the location specified. Please contact rates@saia.com',
  'S10' => 'Invalid Xtreme Assurance shipper code',
  'S11' => 'Bill to account code cannot be used as an inbound or outbound point'
}.freeze

Instance Attribute Summary

Attributes inherited from Base

#address, #address2, #address3, #address_residential, #attention_name, #billing_account, #billing_country, #billing_zip, #ci_comments, #city, #close_report_only, #cod_amount, #cod_collection_type, #company, #country, #currency_code, #data, #debug, #declared_value, #delivery_instructions, #delivery_total_value, #description, #discount_price, #dropoff_type, #email, #eta, #export_reason, #freight_class, #freightquote_authorization_url, #freightquote_client_id, #freightquote_client_secret, #freightquote_customer_code, #freightquote_events_url, #freightquote_rating_url, #freightquote_shipping_url, #freightquote_voiding_url, #handling_instructions, #has_loading_dock, #image_type, #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



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

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

  if @insured_value.to_f > 50_000.0
    @insured_value = 50_000.0
  end # UPS limits this to 50000.0 for domestic
  @country ||= 'US'
  country_iso3 = 'USA' if @country == 'US'
  country_iso3 = 'CAN' if @country == 'CA'
  @sender_country ||= 'US'
  sender_country_iso3 = 'USA' if @sender_country == 'US'
  sender_country_iso3 = 'CAN' if @sender_country == 'CA'
  @saia_rating_url ||= 'http://www.saiasecure.com/webservice/ratequote/soap.asmx'

  if @state.present?
    state = STATES.has_value?(@state.downcase) ? STATES.index(@state.downcase).upcase : @state.upcase
  end
  if @sender_state.present?
    sender_state = STATES.has_value?(@sender_state.downcase) ? STATES.index(@sender_state.downcase).upcase : @sender_state.upcase
  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.Create(xmlns: 'http://www.saiasecure.com/WebService/ratequote/') do |b|
        b.request do |b|
          b.Details do |b|
            @packages.each_with_index do |package, _i|
              freight_class = get_freight_class_from_package(package)
              b.DetailItem do |b|
                # SAIA uses default US units of lbs, inches when units are not specified
                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.Width package_width
                b.Length package_length
                b.Height package_height
                b.Weight package_weight
                b.Class freight_class
              end
            end
          end
          b.Accessorials do |b|
            # SingleShipment
            # ArrivalNotice/Appointment
            # Marking/Tagging
            # LimitedAccessLocationPU
            # LimitedAccessLocation
            # LiftgateServicePU
            # LiftgateService
            # InBond
            # InsidePickup
            # InsideDelivery
            # ExcessiveLength
            # Hazardous
            # ProtectionFromFreezing
            # ResidentialPickup
            # ResidentialDelivery
            # Sorting/Segregating
            # Sorting/SegregatingPickup
            # BorderCrossing
            # TradeShowPickup
            # TradeShowDelivery
            # XtremeAssurance
            {
              InsidePickup: @sender_requires_inside_delivery || false,
              ResidentialPickup: @sender_address_residential || false,
              LiftgateServicePU: @sender_requires_liftgate || false,
              LimitedAccessLocationPU: @sender_limited_access || false,
              InsideDelivery: @requires_inside_delivery || false,
              ResidentialDelivery: @address_residential || false,
              LiftgateService: @requires_liftgate || false,
              BorderCrossing: (@sender_country != @country),
              TradeShowPickup: @sender_is_trade_show || false,
              LimitedAccessLocation: @limited_access || false,
              'ArrivalNotice/Appointment': @address_residential || @requires_appointment || false,
              TradeShowDelivery: @is_trade_show || false
              # BorderCrossing
            }.each do |acc, apply_acc|
              next unless apply_acc

              b.AccessorialItem do |b|
                b.Code acc.to_s
              end
            end
          end
          b.Dimensions do |b|
            @packages.each_with_index do |package, _i|
              b.DimensionItem do |b|
                # SAIA uses default US units of lbs, inches when units are not specified
                value = package.inches(:length)
                package_length = [value, 0.1].max.round(2)
                value = package.inches(:width)
                package_width = [value, 0.1].max.round(2)
                value = package.inches(:height)
                package_height = [value, 0.1].max.round(2)
                b.Length package_length
                b.Width package_width
                b.Height package_height
                b.Units 1
              end
            end
          end
          b.UserID @saia_user_name
          b.Password @saia_password
          b.TestMode Rails.env.production? ? 'N' : 'Y'
          b.BillingTerms 'Prepaid'
          b.AccountNumber @saia_account_id
          b.Application 'Outbound'
          b.DestinationCity @city
          b.DestinationState @state
          b.DestinationZipcode @zip
          b.FullValueCoverage @insured_value.round(2) if @insured_value&.positive?
          b.CommodityDescription 'Warming and Comfort products'
        end
      end
    end
  end

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

  rates = []
  rate_estimates = []
  successful, msg = nil
  soap_fault = REXML::XPath.first(@response, '//soap:Envelope/soap:Body/soap:Fault/faultstring')&.text
  result_code = REXML::XPath.first(@response, '//soap:Envelope/soap:Body/CreateResponse/CreateResult/Code')&.text
  fault = REXML::XPath.first(@response, '//soap:Envelope/soap:Body/CreateResponse/CreateResult/Fault')&.text
  direct_point = REXML::XPath.first(@response, '//soap:Envelope/soap:Body/CreateResponse/CreateResult/DirectPoint')&.text
  if soap_fault.blank? && result_code.blank? && fault.blank? && direct_point == 'Y'
    successful = true
  end # only take direct point deliveries served by SAIA, we don't want complicated shipments where customer has to get shipment from a terminal etc.
  if successful
    result_xml = REXML::Document.new(REXML::XPath.first(@response, '//soap:Envelope/soap:Body/CreateResponse/CreateResult').to_s)
    service_code = REXML::XPath.first(result_xml, '//Tariff').text
    price = REXML::XPath.first(result_xml, '//TotalInvoice').text.delete('$').to_f
    days_in_transit = REXML::XPath.first(result_xml, '//StandardServiceDays').text.to_i + 3 # per Christian and JJ
    quote_number = REXML::XPath.first(result_xml, '//QuoteNumber').text
    quote_expiration = REXML::XPath.first(result_xml, '//ExpirationDate').text
    service_options_charges = 0.0
    REXML::XPath.each(result_xml, '//RateAccessorials/RateAccessorialItem') do |a|
      acharge = REXML::XPath.first(a, '//Amount').text.to_f
      service_options_charges += acharge
    end
    transportation_charges = price - service_options_charges
    guarantee_option_codes = []
    guarantee_option_service_codes = []
    guarantee_option_amounts = []
    guarantee_option_amount = REXML::XPath.first(result_xml, '//GuaranteeAmount').text.to_f
    guarantee_am_option_amount = REXML::XPath.first(result_xml, '//GuaranteeAmount12pm').text.to_f
    skip = false
    # skip service if guaranteed was requested but can't be added, also specifically, address residential precludes it
    if (@service_type == 'Guaranteed') && ((@address_residential || false) || (guarantee_option_amount.zero? && guarantee_am_option_amount.zero?))
      skip = true
    elsif @service_type != 'Guaranteed'
      guarantee_option_codes = ['']
      guarantee_option_service_codes = ['']
      guarantee_option_amounts = [0.0] # start these arrays off with a blank entry so we can iterate once over standard (non guaranteed) service
    else
      if guarantee_option_amount.positive?
        guarantee_option_codes << 'GSS5'
        guarantee_option_service_codes << 'GSDS'
        guarantee_option_amounts << guarantee_option_amount
      end
      if guarantee_am_option_amount.positive?
        guarantee_option_codes << 'GSS12'
        guarantee_option_service_codes << 'GSAM'
        guarantee_option_amounts << guarantee_am_option_amount
      end
    end
    if price && service_code && (skip != true)
      guarantee_option_codes.each_with_index do |guarantee_option_code, i|
        estimate = {}
        estimate[:service_code] = service_code + guarantee_option_service_codes[i]
        estimate[:price] = price + guarantee_option_amounts[i]
        estimate[:total_charges] = price + guarantee_option_amounts[i]
        estimate[:transportation_charges] = transportation_charges + guarantee_option_amounts[i]
        estimate[:service_options_charges] = service_options_charges
        estimate[:insured_value] = @insured_value.to_f.round(2)
        estimate[:currency] = 'USD'
        rate_data = {
          quote_number:,
          total_price: price,
          days_in_transit:,
          quote_expiration:,
          guarantee_option_code:
        }
        estimate[:rate_data] = rate_data
        # allows for things like estimate.service_code
        def estimate.method_missing(name, *args)
          has_key?(name) ? self[name] : super
        end
        # logger.info "!!!ups find_rates estimate: #{estimate.inspect}"
        rate_estimates << estimate
      end
    end
  end

  msg = ''
  if rate_estimates.empty?
    err_msgs = []
    err_msg = REXML::XPath.first(@response, '//soap:Envelope/soap:Body/soap:Fault/faultstring')&.text
    err_msgs << err_msg if err_msg.present?
    err_msg = REXML::XPath.first(@response, '//soap:Envelope/soap:Body/CreateResponse/CreateResult/Message')&.text
    err_msgs << err_msg if err_msg.present?
    msg = if err_msgs.any?
            "No shipping rates could be found: #{err_msgs.join(', ')}"
          else
            'No shipping rates could be found for the destination address.'
          end
  end

  response = {}
  response[:success] = successful
  response[:message] = "Saia: #{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)
    has_key?(name) ? self[name] : super
  end

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

#get_freight_class_from_package(package) ⇒ Object



634
635
636
637
638
639
640
641
642
643
644
# File 'app/services/shipping/saia_legacy.rb', line 634

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



288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
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
# File 'app/services/shipping/saia_legacy.rb', line 288

def label(_return_label = false, logger = nil)
  logger ||= Rails.logger
  @required = %i[zip country sender_state sender_zip sender_country packages service_code]
  @required += %i[saia_user_name saia_password saia_account_id rate_data insured_value]

  quote_number = @rate_data['quote_number']
  guarantee_option_code = @rate_data['guarantee_option_code']

  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
    @service_type ||= 'Guaranteed' if @service_code.index('GSDS') || @service_code.index('GSAM')
    estimate_res = find_rates
    # find the matching rate based on the service code
    estimate = nil
    estimate = estimate_res[:rates].detect { |e| e.dig(: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
      quote_number = estimate.dig(:rate_data, :quote_number) || @rate_data['quote_number']
      guarantee_option_code = estimate.dig(:rate_data, :guarantee_option_code) || @rate_data['guarantee_option_code']
    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

  if @insured_value.to_f > 50_000.0
    @insured_value = 50_000.0
  end # UPS limits this to 50000.0 for domestic
  @country ||= 'US'
  country_iso3 = 'USA' if @country == 'US'
  country_iso3 = 'CAN' if @country == 'CA'
  @sender_country ||= 'US'
  sender_country_iso3 = 'USA' if @sender_country == 'US'
  sender_country_iso3 = 'CAN' if @sender_country == 'CA'
  @saia_shipping_url ||= 'http://www.saiasecure.com/WebService/BOL/soap.asmx'

  if @state.present?
    state = STATES.has_value?(@state.downcase) ? STATES.index(@state.downcase).upcase : @state.upcase
  end
  if @sender_state.present?
    sender_state = STATES.has_value?(@sender_state.downcase) ? STATES.index(@sender_state.downcase).upcase : @sender_state.upcase
  end
  datetime = Shipment.choose_carrier_pickup_date_time('Saia', Store.find(1))

  @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.Create(xmlns: 'http://www.SaiaSecure.com/WebService/BOL') do |b|
        b.request do |b|
          b.Shipper do |b|
            b.AccountNumber @saia_account_id
            # b.ContactName @sender_company
            # b.Address1 @sender_address
            # b.Address2 @sender_address2
            # b.City @sender_city
            # b.State @sender_state
            # b.Zipcode @sender_zip[0..4] # here we are US only and force 5 digits
          end
          b.Consignee do |b|
            b.ContactName @attention_name || @company
            b.Address1 @address
            b.Address2 @address2
            b.City @city
            b.State @state
            b.Zipcode @zip[0..4] # here we are US only and force 5 digits
          end
          b.BillTo do |b|
            b.AccountNumber @saia_account_id
            # b.ContactName @sender_company
            # b.Address1 @sender_address
            # b.Address2 @sender_address2
            # b.City @sender_city
            # b.State @sender_state
            # b.Zipcode @sender_zip[0..4] # here we are US only and force 5 digits
          end
          b.Details do |b|
            @packages.each_with_index do |package, _i|
              freight_class = get_freight_class_from_package(package)
              b.DetailItem do |b|
                b.Class freight_class
                container_type = (if package.pallet?
                                    'PT'
                                  else
                                    (package.crate? ? 'CR' : 'CT')
                                  end)
                b.Package container_type
                b.Pieces 1
                # SAIA uses default US units of lbs, inches when units are not specified
                value = package.lbs
                package_weight = [value, 1.0].max.round
                b.Weight package_weight
                b.FoodItem 'N'
                b.Hazardous 'N'
                b.Description 'Radiant Heating Elements and Controls'
              end
            end
          end
          b.Accessorials do |b|
            # SingleShipment
            # ArrivalNotice/Appointment
            # Marking/Tagging
            # LimitedAccessLocationPU
            # LimitedAccessLocation
            # LiftgateServicePU
            # LiftgateService
            # InBond
            # InsidePickup
            # InsideDelivery
            # ExcessiveLength
            # Hazardous
            # ProtectionFromFreezing
            # ResidentialPickup
            # ResidentialDelivery
            # Sorting/Segregating
            # Sorting/SegregatingPickup
            # BorderCrossing
            # TradeShowPickup
            # TradeShowDelivery
            # XtremeAssurance
            {
              InsidePickup: @sender_requires_inside_delivery || false,
              ResidentialPickup: @sender_address_residential || false,
              LiftgateServicePU: @sender_requires_liftgate || false,
              LimitedAccessLocationPU: @sender_limited_access || false,
              InsideDelivery: @requires_inside_delivery || false,
              ResidentialDelivery: @address_residential || false,
              LiftgateService: @requires_liftgate || false,
              BorderCrossing: (@sender_country != @country),
              TradeShowPickup: @sender_is_trade_show || false,
              LimitedAccessLocation: @limited_access || false,
              'ArrivalNotice/Appointment': @address_residential || @requires_appointment || false,
              TradeShowDelivery: @is_trade_show || false
              # BorderCrossing
            }.each do |acc, apply_acc|
              next unless apply_acc

              b.AccessorialItem do |b|
                b.Code acc.to_s
              end
            end
          end
          b.Dimensions do |b|
            @packages.each_with_index do |package, _i|
              b.DimensionItem do |b|
                # SAIA uses default US units of lbs, inches when units are not specified
                value = package.inches(:length)
                package_length = [value, 0.1].max.round(2)
                value = package.inches(:width)
                package_width = [value, 0.1].max.round(2)
                value = package.inches(:height)
                package_height = [value, 0.1].max.round(2)
                b.Length package_length
                b.Width package_width
                b.Height package_height
                b.Units 1
              end
            end
          end
          b.FullValueCoverage @insured_value.to_f.round(2) # if @insured_value&.positive?
          b.UserID @saia_user_name
          b.Password @saia_password
          b.TestMode Rails.env.production? ? 'N' : 'Y'
          b.ShipmentDate datetime.strftime('%Y-%m-%d')
          b.BillingTerms 'Prepaid'
          b.ShipperNumber @reference_number_1
          b.PONumber @reference_number_2
          b.QuoteNumber quote_number
          b.PrintRates 'N'
          b.Customs 'N'
          b.GuaranteedDelivery guarantee_option_code if guarantee_option_code.present?
          b.EmergencyPhone @sender_phone
          b.Application 'Outbound'
          b.VICS 'N'
          b.TotalCube 0.0
          b.DeclaredValue @insured_value.to_f.round(2) # if @insured_value&.positive?
        end
      end
    end
  end

  get_response(@saia_shipping_url, { 'Content-Type' => 'text/xml' })
  logger.info 'Shipping Saia label Request:'
  logger.info @saia_shipping_url.to_s
  logger.info @data.to_s
  logger.info 'Shipping Saia label Response:'
  logger.info @response.to_s
  successful, msg = nil
  soap_fault = REXML::XPath.first(@response, '//soap:Envelope/soap:Body/soap:Fault/faultstring')&.text
  result_code = REXML::XPath.first(@response, '//soap:Envelope/soap:Body/CreateResponse/CreateResult/Code')&.text
  fault = REXML::XPath.first(@response, '//soap:Envelope/soap:Body/CreateResponse/CreateResult/Fault')&.text
  pro_number = REXML::XPath.first(@response, '//soap:Envelope/soap:Body/CreateResponse/CreateResult/ProNumber').text
  check_digit = REXML::XPath.first(@response, '//soap:Envelope/soap:Body/CreateResponse/CreateResult/CheckDigit').text
  pdf_url = Rails.env.production? ? REXML::XPath.first(@response, '//soap:Envelope/soap:Body/CreateResponse/CreateResult/PDF')&.text : 'https://www.warmlyyours.com/images/pdf/saia_sample_bol.pdf'
  successful = true if soap_fault.blank? && result_code.blank? && fault.blank? && pro_number.present? && pdf_url.present?

  response = {}
  if successful
    response[:tracking_number] = pro_number
    logger.info "url of BOL is here: #{pdf_url}"
    response[:bol_image] = Tempfile.new('saia_bol')
    response[:bol_image].binmode
    # We do this because there's no guarantee the bol file will be at the URL because it may be asynchronous
    Retryable.retryable(tries: 3, on: Retryable::TIMEOUT_CLASSES) do |attempt_number, exception|
      logger.info "attempting to read label, attempt number: #{attempt_number}"
      response[:bol_image] << URI.open(pdf_url).read
    end
    response[:bol_image].rewind
    response[:bol_image].flush
    response[:bol_image].fsync
  else
    err_msgs = []
    err_msg = REXML::XPath.first(@response, '//soap:Envelope/soap:Body/soap:Fault/faultstring')&.text
    err_msgs << err_msg if err_msg.present?
    err_msg = REXML::XPath.first(@response, '//soap:Envelope/soap:Body/CreateResponse/CreateResult/Message')&.text
    err_msgs << err_msg if err_msg.present?
    msg = if err_msgs.any?
            "Ship Labeling did not succeed: #{err_msgs.join(', ')}"
          else
            'Ship Labeling did not succeed'
          end
    successful = false
    raise ShippingError, msg
  end

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

  { labels: [response], shipment_identification_number: pro_number, carrier_bol: pro_number, total_charges: total_price, ship_request_xml: @data.to_s, ship_reply_xml: @response.to_s }
end

#schedule_pickup(deliveries, datetime, logger = nil) ⇒ Object



539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
# File 'app/services/shipping/saia_legacy.rb', line 539

def schedule_pickup(deliveries, datetime, logger = nil)
  logger ||= Rails.logger
  @required += %i[saia_user_name saia_password saia_account_id]

  @sender_country ||= 'US'
  sender_country_iso3 = 'USA' if @sender_country == 'US'
  sender_country_iso3 = 'CAN' if @sender_country == 'CA'
  @saia_pickup_url ||= 'http://www.saiasecure.com/webservice/pickup/soap.asmx '

  if @sender_state.present?
    sender_state = STATES.has_value?(@sender_state.downcase) ? STATES.index(@sender_state.downcase).upcase : @sender_state.upcase
  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.Create(xmlns: 'http://www.SaiaSecure.com/WebService/Pickup') do |b|
        b.request do |b|
          b.Details do |b|
            deliveries.map { |d| d.shipments.top_level.to_a }.flatten.each_with_index do |shipment, _i|
              delivery = shipment.delivery
              b.DetailItem do |b|
                b.DestinationZipcode delivery.destination_address.zip[0..4] # here we are US only and force 5 digits
                b.DestinationCountry 'US'
                b.Pieces 1
                container_type = (if shipment.pallet?
                                    'PT'
                                  else
                                    (shipment.crate? ? 'CR' : 'CT')
                                  end)
                b.Package container_type
                # SAIA uses default US units of lbs, inches when units are not specified
                b.Weight [shipment.weight, 1.0].max.round
                b.Freezable 'N'
                guarantee_str = delivery.chosen_shipping_method.rate_data['guarantee_option_code'].split('GSS').last # 12 or 5 pm
                b.SaiaGuaranteed guarantee_str if guarantee_str.present?
              end
            end
          end
          b.UserID @saia_user_name
          b.Password @saia_password
          b.TestMode Rails.env.production? ? 'N' : 'Y'
          b.AccountNumber @saia_account_id
          b.ContactName @sender_company
          b.ContactPhone @sender_phone
          b.PickupDate datetime.strftime('%Y-%m-%d')
          b.ReadyTime datetime.strftime('%H:%M:%S') # format HH:MM:SS, 24-Hour Local Time
          b.CloseTime Time.zone.parse('5:30pm').strftime('%H:%M:%S') # format HH:MM:SS, 24-Hour Local Time
          b.SpecialInstructions @special_instructions if @special_instructions.present?
        end
      end
    end
  end

  get_response(@saia_pickup_url, { 'Content-Type' => 'text/xml' })
  logger.info 'Shipping Saia pickup Request:'
  logger.info @saia_pickup_url.to_s
  logger.info @data.to_s
  logger.info 'Shipping Saia pickup Response:'
  logger.info @response.to_s
  successful, msg = nil
  soap_fault = REXML::XPath.first(@response, '//soap:Envelope/soap:Body/soap:Fault/faultstring')&.text
  result_code = REXML::XPath.first(@response, '//soap:Envelope/soap:Body/CreateResponse/CreateResult/Code')&.text
  fault = REXML::XPath.first(@response, '//soap:Envelope/soap:Body/CreateResponse/CreateResult/Fault')&.text
  pickup_number = REXML::XPath.first(@response, '//soap:Envelope/soap:Body/CreateResponse/CreateResult/PickupNumber').text
  successful = true if soap_fault.blank? && result_code.blank? && fault.blank? && pickup_number.present?

  response = {}
  if successful
    deliveries.each { |d| d.update(pickup_confirmation_number: pickup_number) }
  else
    err_msgs = []
    err_msg = REXML::XPath.first(@response, '//soap:Envelope/soap:Body/soap:Fault/faultstring')&.text
    err_msgs << err_msg if err_msg.present?
    err_msg = REXML::XPath.first(@response, '//soap:Envelope/soap:Body/CreateResponse/CreateResult/Message')&.text
    err_msgs << err_msg if err_msg.present?
    msg = if err_msgs.any?
            "Saia Pickup did not succeed: #{err_msgs.join(', ')}"
          else
            'Saia Pickup did not succeed'
          end
    raise ShippingError, msg
  end

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

  { status: :ok, request_response: @response.to_s, confirmation_number: pickup_number, schedule_start_datetime: datetime, scheduled_end_datetime: Time.zone.parse("#{datetime.to_date} 17:30") }
end