Class: Shipping::Freightquote
- Inherits:
-
Base
- Object
- Base
- Shipping::Freightquote
show all
- Defined in:
- app/services/shipping/freightquote.rb
Overview
Freightquote (CH Robinson Navisphere) LTL rating, label, void, and tracking
service. Wraps the Navisphere REST API documented at
https://developer.chrobinson.com/api-reference and the legacy SOAP service at
https://b2b.freightquote.com/WebService/QuoteService.asmx.
The per-method ABC/length metrics here exceed the project's general
thresholds on purpose: the request/response builders mirror the API's flat
JSON shape and the get_*_hash names match sibling carrier classes, so they
are part of the public surface used by subclasses, presenters, and tests.
rubocop:disable Metrics/ClassLength, Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
Constant Summary
collapse
- BLACKLIST_SERVICE_CODES =
Blacklist 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'
].freeze
- WHITELIST_SERVICE_CODES =
['UPS Freight'].freeze
- COST_DISCREPANCY_THRESHOLD =
Threshold for cost discrepancy.
200.0
- COST_DISCREPANCY_THRESHOLD_RATIO =
max ratio of discrepancy by total shipping cost
0.5
- COST_DISCREPANCY_THRESHOLD_BY_TOTAL_VALUE_RATIO =
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, #last_request_payload, #last_request_quote_id, #last_response_payload, #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, #paperless, #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, #response_headers, #response_status, #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
#cancel_event_present?(freight_order_number, since_time) ⇒ Boolean
Returns true if CHR has emitted a LOAD CANCELLED or ORDER CANCELED
event for the given freight_order_number at or after since_time.
Polls GET /v2/events directly — does NOT require the Events
Callback (webhook) subscription to be configured on CHR's side.
Authenticates with the same OAuth bearer we mint for rate/label/
void calls.
Used by FreightquoteVoidConfirmationWorker as a fallback when the
local FreightEvent projection (populated by webhooks) has no row —
so the worker is operationally useful before Travis / the CHR
Customer Integration Team has configured the webhook subscription
on their side, and remains a defense-in-depth check after.
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
|
# File 'app/services/shipping/freightquote.rb', line 668
def cancel_event_present?(freight_order_number, since_time)
return false if freight_order_number.blank? || since_time.blank?
logger ||= Rails.logger
@required += %i[freightquote_authorization_url freightquote_events_url freightquote_client_id freightquote_client_secret]
access_token = fetch_access_token
events_url = "#{freightquote_events_url}?to=#{DateTime.current.utc.iso8601}&orderNumber=#{freight_order_number}"
get_simple_get_response(events_url, { 'Authorization' => "Bearer #{access_token}", 'Content-Type' => 'application/json' })
logger.info 'Shipping Freightquote cancel-confirmation poll Request:'
logger.info events_url.to_s
results = if @response.is_a?(Hash)
Array(@response['results'])
elsif @response.is_a?(Array)
@response.flat_map { |r| Array(r['results']) }
else
[]
end
cancel_types = ['LOAD CANCELLED', 'ORDER CANCELED'].freeze
results.any? do |entry|
event = entry['event'] || {}
next false unless cancel_types.include?(event['eventType'])
event_time_str = entry['eventTime'] || event['eventTime']
next false if event_time_str.blank?
parsed = begin
Time.zone.parse(event_time_str.to_s)
rescue ArgumentError, TypeError
nil
end
parsed && parsed >= since_time
end
end
|
#check_events_for_load_number(freight_order_number) ⇒ Object
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
|
# File 'app/services/shipping/freightquote.rb', line 619
def check_events_for_load_number(freight_order_number)
logger ||= Rails.logger
@required += %i[freightquote_authorization_url freightquote_events_url freightquote_client_id freightquote_client_secret]
raise ShippingError, 'Freight Order Number required to get Load Number' if freight_order_number.blank?
access_token = fetch_access_token events_url = "#{freightquote_events_url}?to=#{DateTime.current.utc.iso8601}&orderNumber=#{freight_order_number}"
get_simple_get_response(events_url, { 'Authorization' => "Bearer #{access_token}", 'Content-Type' => 'application/json' })
logger.info 'Shipping Freightquote events Request:'
logger.info events_url.to_s
logger.info 'Shipping Freightquote events Response:'
logger.info @response.to_s
resp_hash = @response.with_indifferent_access if @response.is_a?(Hash)
resp_hash = @response.first.with_indifferent_access if @response.is_a?(Array)
load_number = resp_hash[:results].find { |r| r.dig(:event, :eventType) == 'LOAD CREATED' }&.dig(:event, :loadNumber)
e_bol_enabled = resp_hash[:results].find { |r| r.dig(:event, :eventType) == 'LOAD BOOKED' }&.dig(:event, :customers)&.any? { |ch| ch[:ebolEnabledWithCarrier].to_b } && resp_hash[:results].find do |r|
r.dig(:event, :eventType) == 'LOAD BOOKED'
end&.dig(:event, :carrier, :eBolEnabled)&.to_b
pro_number = resp_hash[:results].find { |r| r.dig(:event, :eventType) == 'PRO NUMBER ADDED' }&.dig(:event, :carrier, :proNumber)
{ load_number:, e_bol_enabled:, pro_number:,
request: events_url, response: @response,
response_status: @response_status, response_headers: @response_headers }
end
|
#check_events_for_pro_number(freight_order_number) ⇒ Object
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
|
# File 'app/services/shipping/freightquote.rb', line 706
def check_events_for_pro_number(freight_order_number)
logger ||= Rails.logger
@required += %i[freightquote_authorization_url freightquote_events_url freightquote_client_id freightquote_client_secret]
raise ShippingError, 'Freight Order Number required to get Load Number' if freight_order_number.blank?
access_token = fetch_access_token events_url = "#{freightquote_events_url}?to=#{DateTime.current.utc.iso8601}&orderNumber=#{freight_order_number}"
get_simple_get_response(events_url, { 'Authorization' => "Bearer #{access_token}", 'Content-Type' => 'application/json' })
logger.info 'Shipping Freightquote events Request:'
logger.info events_url.to_s
logger.info 'Shipping Freightquote events Response:'
logger.info @response.to_s
resp_hash = @response.with_indifferent_access if @response.is_a?(Hash)
resp_hash = @response.first.with_indifferent_access if @response.is_a?(Array)
e_bol_enabled = resp_hash[:results].find { |r| r.dig(:event, :eventType) == 'LOAD BOOKED' }&.dig(:event, :customers)&.any? { |ch| ch[:ebolEnabledWithCarrier].to_b } && resp_hash[:results].find do |r|
r.dig(:event, :eventType) == 'LOAD BOOKED'
end&.dig(:event, :carrier, :eBolEnabled)&.to_b
pro_number = resp_hash[:results].find { |r| r.dig(:event, :eventType) == 'PRO NUMBER ADDED' }&.dig(:event, :carrier, :proNumber)
{ e_bol_enabled:, pro_number:,
request: events_url, response: @response,
response_status: @response_status, response_headers: @response_headers }
end
|
#cull_rate_estimates(rate_estimates) ⇒ Object
774
775
776
|
# File 'app/services/shipping/freightquote.rb', line 774
def cull_rate_estimates(rate_estimates)
(rate_estimates.sort_by { |e| e[:price] }.reject { |e| BLACKLIST_SERVICE_CODES.include?(e[:service_code]) }.slice(0..5) + rate_estimates.select { |e| WHITELIST_SERVICE_CODES.include?(e[:service_code]) }).uniq
end
|
#fetch_access_token ⇒ Object
38
39
40
41
42
43
|
# File 'app/services/shipping/freightquote.rb', line 38
def fetch_access_token
Rails.cache.fetch(:freightquote_access_token, expires_in: 24.hours) do
fetch_fresh_access_token
end
end
|
#fetch_fresh_access_token ⇒ Object
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
|
# File 'app/services/shipping/freightquote.rb', line 45
def fetch_fresh_access_token
logger ||= Rails.logger
auth_payload_hash = {
client_id: @freightquote_client_id,
client_secret: @freightquote_client_secret,
audience: 'https://inavisphere.chrobinson.com',
grant_type: 'client_credentials'
}
@data = auth_payload_hash.to_json
= {
'Content-Type' => 'application/json', 'Cache-Control' => 'no-cache'
}
get_response(@freightquote_authorization_url, )
logger.debug 'Shipping Freightquote fetch_fresh_access_token Request:'
logger.debug @freightquote_authorization_url.to_s
logger.debug auth_payload_hash.merge(client_secret: '[FILTERED]').to_json
logger.debug 'Shipping Freightquote fetch_fresh_access_token Response:'
logger.debug(
if @response.is_a?(Hash)
@response.except('access_token').merge(access_token: '[FILTERED]').to_json
else
'[FILTERED]'
end
)
@response['access_token']
end
|
#find_rates(logger = nil) ⇒ Object
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
|
# File 'app/services/shipping/freightquote.rb', line 78
def find_rates(logger = nil)
logger ||= Rails.logger
@required = %i[zip country sender_state sender_zip sender_country packages]
@required += %i[freightquote_authorization_url freightquote_rating_url freightquote_customer_code freightquote_client_id freightquote_client_secret insured_value]
@insured_value = 50_000.0 if @insured_value.to_f > 50_000.0 @insured_value = 1.00 if @insured_value < 1.0
@country ||= 'US'
@sender_country ||= 'US'
access_token = fetch_access_token @data = get_rate_hash.to_json
get_response(@freightquote_rating_url, { 'Authorization' => "Bearer #{access_token}", 'Content-Type' => 'application/json' })
logger.debug('Shipping Freightquote find_rates Request', url: @freightquote_rating_url)
logger.debug('Shipping Freightquote find_rates Response')
resp_hash = @response.with_indifferent_access if @response.is_a?(Hash)
resp_hash = @response.first.with_indifferent_access if @response.is_a?(Array)
rate_estimates = get_rate_estimates_from_response_hash(resp_hash)
successful = true
msg = ''
if rate_estimates.empty?
successful = false
err_types = []
err_msgs = []
errs = []
resp_arr = [resp_hash]
resp_arr = resp_hash if resp_hash.is_a?(Array)
resp_arr.each do |err_hsh|
err_types << (err_hsh['type'] || err_hsh['error'])
err_msgs << err_hsh['message']
end
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 = {}
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)
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_freight_class_from_package(package) ⇒ Object
762
763
764
765
766
767
768
769
770
771
772
|
# File 'app/services/shipping/freightquote.rb', line 762
def get_freight_class_from_package(package)
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
UpsFreight::FREIGHT_CLASS_BY_PCF.to_a.last.first.to_f
end
|
#get_label_hash(quote_id:) ⇒ Object
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
|
# File 'app/services/shipping/freightquote.rb', line 461
def get_label_hash(quote_id:)
notes = 'N/A'
notes_arr = []
notes_arr << @special_instructions if @special_instructions
customer_contacts = []
bill_to_contacts = []
sender_contact_hash = {
name: @sender_company,
type: 'Contact',
companyName: @sender_company,
contactMethods: [
{
method: 'Phone',
value: @sender_phone
},
{
method: 'Email',
value: @sender_email
}
]
}
customer_contacts << sender_contact_hash
bill_to_contacts << sender_contact_hash
reference_hash_array = get_reference_number_hash_array
shid = reference_hash_array.find { |rh| rh[:type] == 'SHID' }&.dig(:value)
customer_reference_number_hash_array = [
{
type: 'MBOL',
value: shid
}
]
bill_to_reference_number_hash_array = reference_hash_array + [{
type: 'CRID',
value: freightquote_customer_code
}]
origin_instructions_arr = []
origin_instructions_arr << "#{Delivery::CROSS_BORDER_BROKER_INSTRUCTIONS}, #{Delivery::CROSS_BORDER_COUNTRY_SPECIFIC_BROKER_TEXT[@country]}" if @sender_country != @country
if @sender_requires_liftgate || @sender_requires_inside_delivery || @sender_limited_access
reqs = []
reqs << 'ORIGIN LIFTGATE' if @sender_requires_liftgate
reqs << 'INSIDE PICKUP' if @sender_requires_inside_delivery
reqs << 'LIMITED ACCESS PICKUP' if @sender_limited_access
origin_instructions_arr << "#{reqs.join(', ')} REQUESTED"
end
origin_instructions = origin_instructions_arr.join('. ')
notes_arr << origin_instructions if origin_instructions
if @requires_liftgate || @requires_inside_delivery || @limited_access || @requires_appointment || (@sender_country != @country)
reqs = []
reqs << 'DESTINATION LIFTGATE' if @requires_liftgate
reqs << 'INSIDE DELIVERY' if @requires_inside_delivery
reqs << 'LIMITED ACCESS DELIVERY' if @limited_access
reqs << 'DELIVERY APPOINTMENT' if @requires_appointment
destination_instructions = "#{reqs.join(', ')} REQUESTED"
notes_arr << destination_instructions
end
notes = notes_arr.join('. ') if notes_arr.any?
origin_open_datetime = nil
origin_close_datetime = nil
tz = @sender_timezone || 'America/Chicago'
Time.use_zone(tz) do
origin_open_datetime = Time.zone.parse('10:00:00')
origin_close_datetime = Time.zone.parse('16:30:00')
pickup_datetime = 1.hour.from_now
if pickup_datetime > Time.zone.parse('12:00pm')
pickup_datetime = 1.working.day.since(Time.zone.parse('10:00:00'))
origin_open_datetime = pickup_datetime
origin_close_datetime = 1.working.day.since(Time.zone.parse('16:30:00'))
end
end
origin_address = {
address1: @sender_address,
city: @sender_city,
stateProvinceCode: @sender_state,
country: @sender_country,
postalCode: @sender_zip
}
origin_address['address2'] = @sender_address2 if @sender_address2.present?
origin_hash = {
name: @sender_company,
address: origin_address,
phone: @sender_phone,
emailAddress: @sender_email,
contactName: @sender_company,
openDateTime: origin_open_datetime.iso8601,
closeDateTime: origin_close_datetime.iso8601
}
origin_hash['specialInstructions'] = origin_instructions if origin_instructions.present?
origin_hash['referenceNumbers'] = reference_hash_array
destination_address = {
address1: @address,
city: @city,
stateProvinceCode: @state,
country: @country,
postalCode: @zip
}
destination_address['address2'] = @address2 if @address2.present?
destination_hash = {
name: @attention_name || @company,
address: destination_address,
phone: @phone,
emailAddress: @email,
contactName: @attention_name
}
destination_hash['referenceNumbers'] = reference_hash_array
[{
quoteId: quote_id,
customer: {
'customerCode' => @freightquote_customer_code,
contacts: customer_contacts,
referenceNumbers: customer_reference_number_hash_array
},
billTo: {
currencyCode: 'USD',
contacts: bill_to_contacts,
referenceNumbers: bill_to_reference_number_hash_array
},
service: {
referenceNumbers: reference_hash_array
},
origin: origin_hash,
destination: destination_hash,
notes: notes
}]
end
|
797
798
799
800
801
|
# File 'app/services/shipping/freightquote.rb', line 797
def get_nmfc_code_to_navishpere_format(nmfc_code)
res = nmfc_code
res = "#{nmfc_code}-01" if nmfc_code.index('-0').blank?
res
end
|
#get_package_type(container_type, package_length, package_width, _package_height) ⇒ Object
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
|
# File 'app/services/shipping/freightquote.rb', line 735
def get_package_type(container_type, package_length, package_width, _package_height)
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
|
#get_rate_estimates_from_response_hash(resp_hash) ⇒ Object
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
|
# File 'app/services/shipping/freightquote.rb', line 251
def get_rate_estimates_from_response_hash(resp_hash)
rate_estimates = []
(resp_hash[:quoteSummaries] || []).each do |quote_hash|
quote_id = quote_hash[:quoteId]
quote_expiration = (Date.current + 1.day).to_s carrier_hash = quote_hash[:carrier]
carrier_option_id = carrier_hash&.dig(:carrierCode)
service_code = carrier_hash&.dig(:carrierName)
scac = carrier_hash&.dig(:scac)
days_in_transit = (quote_hash.dig(:transit, :minimumTransitDays) || 3).to_i + 3 price = quote_hash[:totalCharge]
service_options_charges = quote_hash[:totalAccessorialCharge]
transportation_charges = quote_hash[:totalFreightCharge] || (price - service_options_charges)
currency = quote_hash[:rates].first&.dig(:currencyCode)
next unless price && currency && service_code
estimate = {}
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
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
rate_estimates
end
|
#get_rate_hash ⇒ Object
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
|
# File 'app/services/shipping/freightquote.rb', line 140
def get_rate_hash
if @pickup_datetime
datetime = @pickup_datetime
else
tz = @sender_timezone || 'America/Chicago'
datetime = Time.current
Time.use_zone(tz) do
datetime = 1.hour.from_now
datetime = 1.working.day.since(Time.zone.parse('10:00:00')) if datetime > Time.zone.parse('3:00pm') || datetime.on_weekend?
end
end
items = []
@packages.each_with_index do |package, _i|
freight_class = get_freight_class_from_package(package)
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
container_type = (if package.pallet?
'PLT'
else
(package.crate? ? 'CRT' : 'CTN')
end)
items << {
description: 'Radiant Heating Elements and Controls',
weight: package_weight,
freightClass: freight_class,
nationalMotorFreightClass: get_nmfc_code_to_navishpere_format(package.nmfc_code || ProductCategoryConstants::FALLBACK_NMFC_CODE),
weightUnitOfMeasure: 'Pounds',
pallets: 1,
palletSpaces: 1,
quantity: 1,
insuranceValue: @insured_value,
packagingType: container_type,
packagingUnitOfMeasure: 'Inches',
packagingLength: package_length,
packagingWidth: package_width,
packagingHeight: package_height
}
end
origin_hash = {
name: @sender_company,
address1: @sender_address,
city: @sender_city,
stateProvinceCode: @sender_state,
countryCode: @sender_country,
postalCode: @sender_zip,
specialRequirement: {
liftGate: (@sender_requires_liftgate || false).to_s,
insidePickup: (@sender_requires_inside_delivery || false).to_s,
insideDelivery: (@sender_requires_inside_delivery || false).to_s,
residentialNonCommercial: (@sender_address_residential || false).to_s,
limitedAccess: (@sender_limited_access || false).to_s,
tradeShoworConvention: (@sender_is_trade_show || false).to_s,
constructionSite: (@sender_is_construction_site || false).to_s,
dropOffAtCarrierTerminal: 'false',
pickupAtCarrierTerminal: 'false'
}
}
origin_hash['address2'] = @sender_address2 if @sender_address2.present?
destination_hash = {
name: @attention_name.presence || @company,
address1: @address,
city: @city,
stateProvinceCode: @state,
countryCode: @country,
postalCode: @zip,
specialRequirement: {
liftGate: (@requires_liftgate || false).to_s,
insidePickup: (@requires_inside_delivery || false).to_s,
insideDelivery: (@requires_inside_delivery || false).to_s,
residentialNonCommercial: (@address_residential || false).to_s,
limitedAccess: (@limited_access || false).to_s,
tradeShoworConvention: (@is_trade_show || false).to_s,
constructionSite: (@is_construction_site || false).to_s,
dropOffAtCarrierTerminal: 'false',
pickupAtCarrierTerminal: 'false'
}
}
destination_hash['address2'] = @address2 if @address2.present?
{
items: items,
origin: origin_hash,
destination: destination_hash,
shipDate: (@ship_date.presence || DateTime.current).to_datetime.utc.iso8601,
customerCode: @freightquote_customer_code,
transportModes: [
{
mode: 'LTL',
equipments: [
{
equipmentType: 'Van',
quantity: 1
}
]
}
] }
end
|
#get_reference_number_hash_array ⇒ Object
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
|
# File 'app/services/shipping/freightquote.rb', line 778
def get_reference_number_hash_array
delivery = Shipment.where(id: @packages&.first&.shipment_id)&.last&.delivery
shid = delivery&.id || @reference_number_1 || @packages&.first&.shipment_id || @packages&.first&.container_code
refhash = {}
refhash['SHID'] = shid.to_s if shid refhash['CON'] = @reference_number_1 if @reference_number_1.presence refhash['XXXX'] = @reference_number_2 if @reference_number_2.presence refhash['CUSTPO'] = @reference_number_3 if @reference_number_3.presence refhash.map do |type, value|
{
type: type,
value: value
}
end
end
|
#label(_return_label = false, logger = nil) ⇒ Object
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
|
# File 'app/services/shipping/freightquote.rb', line 334
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[freightquote_authorization_url freightquote_shipping_url freightquote_customer_code freightquote_client_id freightquote_client_secret rate_data delivery_total_value insured_value]
check_required
quote_id = @rate_data['quote_id'] carrier_option_id = @rate_data['carrier_option_id'] scac = @rate_data['scac'] quote_expiration = @rate_data['quote_expiration']
original_scac = scac
original_total_price = @rate_data['total_price'].to_f
estimate_res = find_rates
rate_request_xml = @data.to_s
rate_reply_xml = @response
rate_response_status = @response_status
= @response_headers
estimate = nil
estimate = estimate_res[:rates].find { |e| e.dig(:rate_data, :scac) == original_scac } if original_scac.present? new_total_price = estimate&.dig(:price)&.to_f
diff = new_total_price && original_total_price ? (new_total_price - original_total_price).abs : nil
use_rerated_quote = false
if estimate.present? if (diff && original_total_price.positive? &&
(diff < COST_DISCREPANCY_THRESHOLD) &&
(diff / original_total_price < COST_DISCREPANCY_THRESHOLD_RATIO)
) ||
(diff && (@delivery_total_value.to_f > COST_DISCREPANCY_THRESHOLD * 10.0) &&
(diff / @delivery_total_value.to_f < COST_DISCREPANCY_THRESHOLD_BY_TOTAL_VALUE_RATIO)
) ||
@skip_rate_test
use_rerated_quote = true
quote_id = estimate.dig(:rate_data, :quote_id)
carrier_option_id = estimate.dig(:rate_data, :carrier_option_id)
scac = estimate.dig(:rate_data, :scac)
end
elsif quote_expiration && Date.current >= Date.parse(quote_expiration)
raise ShippingError, 'Rate has expired, please HOLD order and refresh shipping rates/methods'
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? || scac.blank?
access_token = fetch_access_token @data = get_label_hash(quote_id: quote_id).to_json
get_response(@freightquote_shipping_url, { 'Authorization' => "Bearer #{access_token}", 'Content-Type' => 'application/json' })
logger.info 'Shipping Freightquote label Request:'
logger.info @freightquote_shipping_url.to_s
logger.info @data.to_s
logger.info 'Shipping Freightquote label Response:'
logger.info @response.to_s
resp_hash = @response.with_indifferent_access if @response.is_a?(Hash)
resp_hash = @response.first.with_indifferent_access if @response.is_a?(Array)
quote_id = resp_hash['quoteId']
order_number = resp_hash['orderNumber']
tracking_number = resp_hash['trackingNumber']
successful = true
msg = ''
if quote_id == '0' || quote_id.nil? || order_number == '0' || order_number.nil? || tracking_number == '0' || tracking_number.nil?
successful = false
err_types = []
err_msgs = []
errs = []
resp_arr = [resp_hash]
resp_arr = resp_hash if resp_hash.is_a?(Array)
resp_arr.each do |err_hsh|
err_types << (err_hsh[:type] || err_hsh[:error])
err_msgs << err_hsh[:message]
end
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 = {}
raise ShippingError, msg unless successful
total_price = use_rerated_quote ? new_total_price : original_total_price
response[:tracking_number] = tracking_number
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: tracking_number, carrier_bol: quote_id, freight_order_number: order_number, pickup_confirmation_number: quote_id, total_charges: total_price,
ship_request_xml: @data.to_s,
ship_reply_xml: @response.to_s,
response_status: @response_status,
response_headers: @response_headers,
rate_request_xml: rate_request_xml,
rate_reply_xml: rate_reply_xml,
rate_response_status: rate_response_status,
rate_response_headers: }
end
|
#void(freight_order_number) ⇒ Object
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
|
# File 'app/services/shipping/freightquote.rb', line 601
def void(freight_order_number)
logger ||= Rails.logger
@required += %i[freightquote_authorization_url freightquote_voiding_url freightquote_client_id freightquote_client_secret]
raise ShippingError, 'Freight Order Number required to void a Freightquote delivery' if freight_order_number.blank?
access_token = fetch_access_token void_url = "#{@freightquote_voiding_url}/#{freight_order_number}"
get_delete_response(void_url, { 'Authorization' => "Bearer #{access_token}", 'Content-Type' => 'application/json' })
logger.info 'Shipping Freightquote void Request:'
logger.info void_url.to_s
logger.info 'Shipping Freightquote void Response:'
logger.info @response.to_s
{ void_request_xml: void_url, void_response_xml: @response,
response_status: @response_status, response_headers: @response_headers }
end
|