Class: Shipping::FreightquoteLegacy

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

Overview

Constant Summary collapse

BLACKLIST_SERVICE_CODES =

Here we are blacklisting R+L Carriers because our direct integration with them is much cheaper and we don't want to inadvertently book a more costly version of it through Freightquote

['Pilot Freight Services- Economy', 'Valley Cartage', 'Midland Transport', 'R+L Carriers', 'YRC Freight', 'Panther Deferred (LTL)', 'US Road Freight Express', 'US Special Delivery', 'TST Overland Express Canada', 'Sutton Transport', 'Estes Express Lines']
WHITELIST_SERVICE_CODES =
['UPS Freight']
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

#cull_rate_estimates(rate_estimates) ⇒ Object



576
577
578
# File 'app/services/shipping/freightquote_legacy.rb', line 576

def cull_rate_estimates(rate_estimates)
  (rate_estimates.sort_by{|e| e[:price]}.reject{|e| BLACKLIST_SERVICE_CODES.include?(e[:service_code])}.slice(0..2) + rate_estimates.reject{|e| !WHITELIST_SERVICE_CODES.include?(e[:service_code])}).uniq
end

#find_rates(logger = nil) ⇒ Object



12
13
14
15
16
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
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
# File 'app/services/shipping/freightquote_legacy.rb', line 12

def find_rates(logger=nil)

  logger ||= Rails.logger
  @required = [:zip, :country, :sender_state, :sender_zip, :sender_country, :packages]
  @required += [:freightquote_account_id, :freightquote_user_name, :freightquote_password, :insured_value]

  @insured_value = 50000.0 if @insured_value.to_f > 50000.0 # UPS limits this to 50000.0 for domestic
  @country ||= 'US'
  @sender_country ||= 'US'
  @freightquote_url ||= "https://b2b.Freightquote.com/WebService/QuoteService.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"}) {|b|
    b.tag!("soap:Body") {|b|
      b.GetRatingEngineQuote(xmlns: "http://tempuri.org/") { |b|
        b.request { |b|
          b.CustomerId @freightquote_account_id
          b.QuoteType 'B2B' # [B2B, eBay, Freightview]
          b.ServiceType 'LTL' # LTL, Truckload, Groupage, Haulage, All
          b.QuoteShipment { |b|
            b.IsBlind false
            if @pickup_datetime
              datetime = @pickup_datetime
            else
              tz = @sender_timezone || "America/Chicago"
              datetime = Time.current
              Time.use_zone(tz) do
                datetime = (Time.current + 1.hour)
                if datetime > Time.zone.parse("3:00pm") || datetime.on_weekend?
                  datetime = 1.working.day.since(Time.zone.parse("10:00:00"))
                end
              end
            end
            b.PickupDate datetime.iso8601
            b.SortAndSegregate false
            b.UseStackableFlag false
            b.DeclaredValue @insured_value.to_f.round(2)
            # b.MaxPickupDate

            b.ShipmentLocations {|b|
              b.Location { |b|
                b.LocationType 'Origin' # Origin, Destination, StopoffPickupDelivery, StopoffDelivery, StopoffPickup
                b.HasLoadingDock @sender_has_loading_dock || false
                b.IsConstructionSite @sender_is_construction_site || false
                b.RequiresInsideDelivery @sender_requires_inside_delivery || false
                b.IsTradeShow @sender_is_trade_show || false
                b.RequiresLiftgate @sender_requires_liftgate || false
                b.IsLimitedAccess @sender_limited_access || false
                b.HasDeliveryAppointment @sender_requires_appointment || false
                b.IsResidential @sender_address_residential || false
                b.ContactName @sender_company
                b.ContactPhone @sender_phone
                b.ContactEmail @sender_email
                b.LocationAddress { |b|
                  b.AddressName @sender_company
                  b.StreetAddress @sender_address
                  b.AdditionalAddress @sender_address2
                  b.City @sender_city
                  b.StateCode @sender_state
                  b.PostalCode @sender_zip
                  b.CountryCode @sender_country
                }
              }
              b.Location { |b|
                b.LocationType 'Destination' # Origin, Destination, StopoffPickupDelivery, StopoffDelivery, StopoffPickup
                b.RequiresArrivalNotification (@email.present?)
                b.HasLoadingDock @has_loading_dock || false
                b.IsConstructionSite @is_construction_site || false
                b.RequiresInsideDelivery @requires_inside_delivery || false
                b.IsTradeShow @is_trade_show || false
                b.RequiresLiftgate @requires_liftgate || false
                b.IsLimitedAccess @limited_access || false
                b.HasDeliveryAppointment @requires_appointment || false
                b.IsResidential @address_residential || false
                b.ContactName (@attention_name || @company)
                b.ContactPhone @phone if @phone.present?
                b.ContactEmail @email if @email.present?
                b.BeforeTime '17:00:00'
                b.AfterTime '9:00:00'
                b.LocationNote @address3 if @address3.present?
                # b.NotificationMethod 'email' if @email.present? # None, Email, Fax, Internal Email
                b.LocationAddress { |b|
                  b.AddressName (@attention_name || @company)
                  b.StreetAddress @address
                  b.AdditionalAddress @address2
                  b.City @city
                  b.StateCode @state
                  b.PostalCode @zip
                  b.CountryCode @country
                }
              }
            }
            b.ShipmentProducts {|b|
              @packages.each_with_index do |package, i|
                freight_class = get_freight_class_from_package(package)
                b.Product {|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.Length package_length
                  b.Width package_width
                  b.Height package_height
                  b.ProductDescription 'Radiant Heating Elements and Controls'
                  container_type = (package.pallet? ? 'pallet' : (package.crate? ? 'crate' : 'carton'))
                  b.PackageType get_package_type(container_type, package_length, package_width, package_height)
                  b.IsStackable false
                  b.CommodityType 'GeneralMerchandise'
                  b.ContentType 'NewCommercialGoods'
                  b.IsHazardousMaterial false
                  b.NMFC package.nmfc_code if package.nmfc_code.present?
                  b.PieceCount 1
                  b.ItemNumber i+1
                }
              end
            }
            b.ShipmentContacts {|b|
              b.ContactAddress {|b|
                # Here we are hardcoding Willson International
                b.ContactName 'Willson International'
                b.ContactPhone '905-643-9054'
                b.EmailAddress 'service@willsonintl.com'
                b.ContactAddressType 'CanadianBroker'
                b.ContactNote ''
              }
            } if @sender_country != @country
          }
          b.BillCollect 'SHIPPER' # NONE, SITE, SHIPPER, RECEIVER
        }
        b.user {|b|
          b.Name @freightquote_user_name
          b.Password @freightquote_password
          b.CredentialType 'Default'
        }
      }
    }
  }

  get_response(@freightquote_url, {'Content-Type' => 'text/xml'})
  logger.info "Shipping Freightquote find_rates Request:"
  logger.info "#{@freightquote_url}"
  logger.info "#{@data}"
  logger.info "Shipping Freightquote find_rates Response:"
  logger.info "#{@response}"

  rates = []
  rate_estimates = []
  successful, msg = nil
  quote_id_element = REXML::XPath.first(@response, "//soap:Envelope/soap:Body/GetRatingEngineQuoteResponse/GetRatingEngineQuoteResult/QuoteId")
  if quote_id_element
    quote_id = quote_id_element.text
    quote_expiration = REXML::XPath.first(@response, "//soap:Envelope/soap:Body/GetRatingEngineQuoteResponse/GetRatingEngineQuoteResult/QuoteExpiration").text
    # use at least the total charges or the negotiated rate if appropriate
    REXML::XPath.each(@response, "//soap:Envelope/soap:Body/GetRatingEngineQuoteResponse/GetRatingEngineQuoteResult/QuoteCarrierOptions/CarrierOption") do |carrier_option|
      carrier_option_xml = REXML::Document.new(carrier_option.to_s)
      service_code = REXML::XPath.first(carrier_option_xml, "//CarrierName").text
      scac = REXML::XPath.first(carrier_option_xml, "//SCAC").text
      price = REXML::XPath.first(carrier_option_xml, "//QuoteAmount").text.to_f
      days_in_transit = REXML::XPath.first(carrier_option_xml, "//Transit").text.to_i + 3 # per Christian and JJ
      service_options_charges = 0.0
      REXML::XPath.each(carrier_option_xml, "//CarrierAccessorials/Accessorial") do |a|
        acharge = REXML::XPath.first(a, "//AccessorialCharge").text.to_f
        service_options_charges += acharge
      end
      transportation_charges = price - service_options_charges
      currency = REXML::XPath.first(carrier_option_xml, "//Currency").text
      carrier_option_id = REXML::XPath.first(carrier_option_xml, "//CarrierOptionId").text
      if price and currency and service_code
        estimate = Hash.new
        estimate[:service_code] = 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.to_f.round(2)
        estimate[:currency] = currency
        rate_data = {
          quote_id: quote_id,
          carrier_option_id: carrier_option_id,
          total_price: price,
          carrier_name: service_code,
          scac: scac,
          days_in_transit: days_in_transit,
          quote_expiration: quote_expiration
        }
        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

  successful = true
  msg = ""
  if rate_estimates.empty?
     successful = false
     err_types = []
     err_msgs = []
     REXML::XPath.first(@response, "//soap:Envelope/soap:Body/GetRatingEngineQuoteResponse/GetRatingEngineQuoteResult/QuoteCarrierOptions/ValidationErrors/B2BError/ErrorType") do |err_typ|
      err_types << err_type
     end
     REXML::XPath.first(@response, "//soap:Envelope/soap:Body/GetRatingEngineQuoteResponse/GetRatingEngineQuoteResult/QuoteCarrierOptions/ValidationErrors/B2BError/ErrorMessage") do |err_msg|
      err_msgs << err_msg
     end
     errs = []
     err_types.each_with_index do |err_type, i|
       errs << "#{err_type}: #{err_msgs[i]}"
     end
     msg = "No shipping rates could be found for the destination address: #{errs.join(', ')}" if msg.blank?
  end

  response = Hash.new
  response[:success] = successful
  response[:message] = "Freightquote: #{msg}" if msg.present?
  response[:request] = @data.to_s
  response[:xml] = @response.to_s
  response[:rates] = cull_rate_estimates(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}"

  return response

end

#get_freight_class_from_package(package) ⇒ Object



562
563
564
565
566
567
568
569
570
571
572
573
574
# File 'app/services/shipping/freightquote_legacy.rb', line 562

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|
    if pcf >= pcf_limits[:lower] and pcf < pcf_limits[:upper]
      return freight_class
    end
  end
  # worst case return the highest freight class
  return UpsFreight::FREIGHT_CLASS_BY_PCF.to_a.last.first.to_f
end

#get_package_type(container_type, package_length, package_width, package_height) ⇒ Object



537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
# File 'app/services/shipping/freightquote_legacy.rb', line 537

def get_package_type(container_type, package_length, package_width, package_height)
  # Unknown, Pallets_48x40, Pallets_other, Bags, Bales, Boxes, Bundles, Carpets, Coils, Crates, Cylinders, Drums, Pails, Reels, Rolls, TubesPipes, Motorcycle, ATV, Pallets_120x120, Pallets_120x100, Pallets_120x80, Pallets_europe, Pallets_48x48, Pallets_60x48, Slipsheets, Unit
  if container_type == 'pallet'
    package_type = 'Pallets_other'
    if (package_length == 48 && package_width == 48)
      package_type = 'Pallets_48x48'
    elsif (package_length == 48 && package_width == 40)
      package_type = 'Pallets_48x40'
    elsif (package_length == 60 && package_width == 60)
      package_type = 'Pallets_60x48'
    elsif (package_length == 120 && package_width == 120)
        package_type = 'Pallets_120x120'
    elsif (package_length == 120 && package_width == 80)
      package_type = 'Pallets_120x80'
    elsif (package_length == 120 && package_width == 100)
      package_type = 'Pallets_120x100'
    end
  elsif container_type == 'crate'
    package_type = "Crates"
  else
    package_type = "Boxes"
  end
  package_type
end

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

Raises:



255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
# File 'app/services/shipping/freightquote_legacy.rb', line 255

def label(return_label=false, logger=nil)

  logger ||= Rails.logger
  @required = [:zip, :country, :sender_state, :sender_zip, :sender_country, :packages, :service_code]
  @required += [:freightquote_account_id, :freightquote_user_name, :freightquote_password, :rate_data, :delivery_total_value, :insured_value]

  quote_id = @rate_data['quote_id'] # quote id fallback will be original quote_id
  carrier_option_id = @rate_data['carrier_option_id'] # carrier_option_id fallback will be original carrier_option_id
  quote_expiration = @rate_data['quote_expiration']

  # Here we need to re-rate quote, because you need to buy a specific Freightquote quote id and all the relevant criteria like packages, weights, addresses and options have to match the quote id you are 'buying'. This pattern is different than our other carriers which give you an estimate and then you buy the label using the same (one hopes) criteria

  original_scac = @rate_data['scac']
  original_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 SCAC (if we have it) or Carrier Name
  estimate = nil
  estimate = estimate_res[:rates].detect{|e| e.dig(:rate_data, :scac) == original_scac} if original_scac.present? # match on SCAC if we have it

  if estimate.present? # we have a matching rate using the SCAC code matching
    new_total_price = estimate.dig(:rate_data, :total_price)
    if (new_total_price && original_total_price &&
        ((diff = (new_total_price - original_total_price).abs) < COST_DISCREPANCY_THRESHOLD) &&
        (diff/original_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 match and the price is proportionately close enough, so grab new quote id and carrier option id
      quote_id = estimate.dig(:rate_data, :quote_id)
      carrier_option_id = estimate.dig(:rate_data, :carrier_option_id)
    elsif @skip_rate_test # here we have an ST, and don't care about comparing rates, so take the matching rate
      quote_id = estimate.dig(:rate_data, :quote_id)
      carrier_option_id = estimate.dig(:rate_data, :carrier_option_id)
    end
  else
    # no match or pricing threshold exceeded, test for quote expiration and let it go
    raise ShippingError, "Rate has expired, please HOLD order and refresh shipping rates/methods" if (quote_expiration && Date.current >= Date.parse(quote_expiration))
  end

  logger.debug "Shipping Freightquote @rate_data: #{@rate_data}"

  raise ShippingError, "Missing data, please HOLD order and refresh shipping rates/methods" if (quote_id.blank? || carrier_option_id.blank?)

  @insured_value = 50000.0 if @insured_value.to_f > 50000.0 # UPS limits this to 50000.0 for domestic
  @country ||= 'US'
  @sender_country ||= 'US'
  @freightquote_url ||= "https://b2b.Freightquote.com/WebService/QuoteService.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"}) {|b|
    b.tag!("soap:Body") {|b|
      b.RequestShipmentPickup(xmlns: "http://tempuri.org/") { |b|
        b.request { |b|
          b.CustomerId @freightquote_account_id
          b.QuoteId quote_id
          b.OptionId carrier_option_id
          b.QuoteShipment { |b|
            b.IsBlind false
            tz = @sender_timezone || "America/Chicago"
            datetime = Time.current
            Time.use_zone(tz) do
              datetime = (Time.current + 1.hour)
              if datetime > Time.zone.parse("2:00pm")
                datetime = 1.working.day.since(Time.zone.parse("10:00:00"))
              end
            end
            b.PickupDate datetime.iso8601
            b.SortAndSegregate false
            b.UseStackableFlag false
            b.DeclaredValue @insured_value.to_f.round(2)
            # b.MaxPickupDate
            b.ShipmentLocations {|b|
              b.Location { |b|
                b.LocationType 'Origin' # Origin, Destination, StopoffPickupDelivery, StopoffDelivery, StopoffPickup
                b.HasLoadingDock @sender_has_loading_dock || false
                b.IsConstructionSite @sender_is_construction_site || false
                b.RequiresInsideDelivery @sender_requires_inside_delivery || false
                b.IsTradeShow @sender_is_trade_show || false
                b.RequiresLiftgate @sender_requires_liftgate || false
                b.IsLimitedAccess @sender_limited_access || false
                b.HasDeliveryAppointment @sender_requires_appointment || false
                b.IsResidential @sender_address_residential || false
                b.ContactName @sender_company
                b.ContactPhone @sender_phone
                b.ContactEmail @sender_email
                b.LocationAddress { |b|
                  b.AddressName @sender_company
                  b.StreetAddress @sender_address
                  b.AdditionalAddress @sender_address2
                  b.City @sender_city
                  b.StateCode @sender_state
                  b.PostalCode @sender_zip
                  b.CountryCode @sender_country
                }
              }
              b.Location { |b|
                b.LocationType 'Destination' # Origin, Destination, StopoffPickupDelivery, StopoffDelivery, StopoffPickup
                b.RequiresArrivalNotification (@email.present?)
                b.HasLoadingDock @has_loading_dock || false
                b.IsConstructionSite @is_construction_site || false
                b.RequiresInsideDelivery @requires_inside_delivery || false
                b.IsTradeShow @is_trade_show || false
                b.RequiresLiftgate @requires_liftgate || false
                b.IsLimitedAccess @limited_access || false
                b.HasDeliveryAppointment @requires_appointment || false
                b.IsResidential @address_residential || false
                b.ContactName (@attention_name || @company)
                b.ContactPhone @phone if @phone.present?
                b.ContactEmail @email if @email.present?
                b.BeforeTime '17:00:00'
                b.AfterTime '9:00:00'
                b.LocationNote @address3 if @address3.present?
                # b.NotificationMethod 'email' if @email.present? # None, Email, Fax, Internal Email
                b.LocationAddress { |b|
                  b.AddressName (@company || @attention_name)
                  b.StreetAddress @address
                  b.AdditionalAddress @address2
                  b.City @city
                  b.StateCode @state
                  b.PostalCode @zip
                  b.CountryCode @country
                }
              }
            }
            b.ShipmentProducts {|b|
              @packages.each_with_index do |package, i|
                freight_class = get_freight_class_from_package(package)
                b.Product {|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.Length package_length
                  b.Width package_width
                  b.Height package_height
                  b.ProductDescription 'Radiant Heating Elements and Controls'
                  container_type = (package.pallet? ? 'pallet' : (package.crate? ? 'crate' : 'carton'))
                  b.PackageType get_package_type(container_type, package_length, package_width, package_height)
                  b.IsStackable false
                  b.CommodityType 'GeneralMerchandise'
                  b.ContentType 'NewCommercialGoods'
                  b.IsHazardousMaterial false
                  b.NMFC package.nmfc_code if package.nmfc_code.present?
                  b.PieceCount 1
                  b.ItemNumber i+1
                }
              end
            }
            b.ShipmentContacts {|b|
              b.ContactAddress {|b|
                # Here we are hardcoding Willson International
                b.ContactName 'Willson International'
                b.ContactPhone '905-643-9054'
                b.EmailAddress 'service@willsonintl.com'
                b.ContactAddressType 'CanadianBroker'
                b.ContactNote ''
              }
            } if @sender_country != @country
          }
          b.BillCollect 'SHIPPER' # NONE, SITE, SHIPPER, RECEIVER
        }
        b.user {|b|
          b.Name @freightquote_user_name
          b.Password @freightquote_password
          b.CredentialType 'Default'
        }
      }
    }
  }

  get_response(@freightquote_url, {'Content-Type' => 'text/xml'})
  logger.info "Shipping Freightquote label Request:"
  logger.info "#{@freightquote_url}"
  logger.info "#{@data}"
  logger.info "Shipping Freightquote label Response:"
  logger.info "#{@response}"

  quote_id = REXML::XPath.first(@response, "//soap:Envelope/soap:Body/RequestShipmentPickupResponse/RequestShipmentPickupResult/QuoteId").text

  successful = true
  msg = ""
  if quote_id == "0"
    successful = false
    err_types = []
    err_msgs = []
    REXML::XPath.each(@response, "//soap:Envelope/soap:Body/RequestShipmentPickupResponse/RequestShipmentPickupResult/ValidationErrors/B2BError") do |b2b_err|
      err_types << REXML::XPath.first(b2b_err, "//ErrorType").text
      err_msgs << REXML::XPath.first(b2b_err, "//ErrorMessage").text
    end
    errs = []
    err_types.each_with_index do |err_type, i|
     errs << "#{err_type}: #{err_msgs[i]}"
    end
    msg = "Shipping could not be confirmed: #{errs.join(', ')}"
  end

  response = Hash.new
  if successful
    total_price = new_total_price
    #logger.info "total_price: #{total_price}"
    response[:tracking_number] = quote_id
    # we will generate BOL from the delivery
  else
    raise ShippingError, msg
  end

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

  return {labels: [response], shipment_identification_number: quote_id, carrier_bol: quote_id, pickup_confirmation_number: quote_id, total_charges: total_price, ship_request_xml: "#{@data}", ship_reply_xml: "#{@response}"}
end

#void(quote_id) ⇒ Object

Raises:



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

def void(quote_id)
  logger ||= Rails.logger
  @required += [:freightquote_account_id, :freightquote_user_name, :freightquote_password]
  raise ShippingError, "Quote ID required to void a Freightquote delivery" unless (quote_id.present?)

  @freightquote_url ||= "https://b2b.Freightquote.com/WebService/QuoteService.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"}) {|b|
    b.tag!("soap:Body") {|b|
      b.RequestShipmentCancellation(xmlns: "http://tempuri.org/") { |b|
        b.request { |b|
          b.QuoteId quote_id
        }
        b.user {|b|
          b.Name @freightquote_user_name
          b.Password @freightquote_password
          b.CredentialType 'Default'
        }
      }
    }
  }

  get_response(@freightquote_url, {'Content-Type' => 'text/xml'})
  logger.info "Shipping Freightquote void Request:"
  logger.info "#{@freightquote_url}"
  logger.info "#{@data}"
  logger.info "Shipping Freightquote void Response:"
  logger.info "#{@response}"

  successful = true
  msg = ""
  err_types = []
  err_msgs = []
  REXML::XPath.each(@response, "//soap:Envelope/soap:Body/RequestShipmentCancellationResponse/RequestShipmentCancellationResult/ValidationErrors/B2BError") do |b2b_err|
    err_types << REXML::XPath.first(b2b_err, "//ErrorType").text
    err_msgs << REXML::XPath.first(b2b_err, "//ErrorMessage").text
  end
  if err_types.any?
    successful = false
    errs = []
    err_types.each_with_index do |err_type, i|
     errs << "#{err_type}: #{err_msgs[i]}"
    end
    msg = "Shipment Cancellation could not be completed for shipment with ID #{quote_id}: #{errs.join(', ')}"
  end

  raise ShippingError, msg unless successful
  return {:void_request_xml => @data, :void_response_xml => @response} if successful

end