freight_kit 0.1.33 → 0.1.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -95,10 +95,9 @@ module FreightKit
95
95
 
96
96
  def maximum_height = Measured::Length.new(105, :inches)
97
97
  def maximum_weight = Measured::Weight.new(10_000, :pounds)
98
- def minimum_length_for_overlength_fees = Measured::Length.new(12, :feet)
98
+ def minimum_length_for_overlength_fees = Measured::Length.new(8, :feet)
99
99
  def name = 'STG'
100
100
  def overlength_fees_require_tariff? = false
101
- def rates_with_excessive_length_fees? = false
102
101
  def scac = 'FCSY'
103
102
  def services = %i[standard]
104
103
 
@@ -129,7 +128,14 @@ module FreightKit
129
128
  end
130
129
  end
131
130
 
132
- API = Platforms::CarrierLogistics::API.deep_merge(carrier_code: 'fro').freeze
131
+ API = Platforms::CarrierLogistics::API.deep_merge(
132
+ carrier_code: 'fro',
133
+ endpoints: { notes: '/scripts/@CARRIER_CODE@.pol/boldetail.htm?' },
134
+ use_ssl: { notes: true }
135
+ ).freeze
136
+ NOTE = %r{\A(?<date_time>\d{2}/\d{2}/\d{4} \d{2}:\d{2}) (?<text>.+)\z}
137
+ NOTE_LOCATED = /\ALINE HAUL UNIT CURRENT LOCATION IS (?<city_state>[A-Z][A-Z .'-]*, [A-Z]{2})\b/
138
+ NOTE_TERMINAL = /\A(?:AVAILABLE|COMPLETED TRANSFER) (?<city_state>[A-Z][A-Z .'-]*, [A-Z]{2})\b/
133
139
 
134
140
  # Documents
135
141
 
@@ -145,16 +151,78 @@ module FreightKit
145
151
  when (96..143) then builder << 'XTRM8'
146
152
  when (144..191) then builder << 'XTRM12'
147
153
  when (192..239) then builder << 'XTRM16'
148
- when (240..311) then builder << 'XTRM20'
149
- when (312..) then builder << 'XTRM27'
154
+ when (240..323) then builder << 'XTRM20'
155
+ when (324..) then builder << 'XTRM27'
150
156
  end
151
157
  end
152
158
  end
153
159
 
154
160
  # Tracking
155
161
 
162
+ # @return [Array<Array(String, String)>] Each note's local date/time and text, oldest first.
163
+ def fetch_notes(tracking_number)
164
+ url = build_url(:notes, query: { language: 'ENGLISH', wbtn: 'PRO', wpro1: tracking_number })
165
+ cell = Nokogiri::HTML(HTTPClient.get(url, proxy_url:).body).at('th:contains("Notes:") + td')
166
+ return [] if cell.nil?
167
+
168
+ notes = cell.xpath('text()').filter_map do |node|
169
+ match = NOTE.match(node.text.squish)
170
+ [::Time.strptime(match[:date_time], '%m/%d/%Y %H:%M').to_fs(:db), match[:text]] if match
171
+ end
172
+
173
+ notes.reverse
174
+ rescue HTTPX::Error
175
+ []
176
+ end
177
+
178
+ def parse_tracking_response(tracking_number, response:)
179
+ tracking_response = super
180
+ return tracking_response if tracking_response.error.present?
181
+
182
+ notes = fetch_notes(tracking_number)
183
+ locate_arrivals(tracking_response.shipment_events, notes)
184
+
185
+ shipment_events = tracking_response.shipment_events + parse_located_events(notes)
186
+ if shipment_events.all? { |event| event.date_time&.date_time_with_zone }
187
+ shipment_events.sort_by! { |event| event.date_time.date_time_with_zone }
188
+ end
189
+
190
+ tracking_response.shipment_events = shipment_events
191
+ tracking_response
192
+ end
193
+
156
194
  # protected
157
195
 
196
+ def locate_arrivals(shipment_events, notes)
197
+ shipment_events.each do |event|
198
+ next if event.type_code != :arrived_at_terminal || event.location.present? || event.date_time.blank?
199
+
200
+ local_date_time = event.date_time.local_date_time
201
+ terminal = notes.lazy.filter_map do |note_date_time, text|
202
+ NOTE_TERMINAL.match(text) if note_date_time.to_date >= local_date_time.to_date
203
+ end.first
204
+ next if terminal.nil?
205
+
206
+ event.location = parse_api_city_state(terminal[:city_state])
207
+ event.date_time = ::FreightKit::DateTime.new(local_date_time:, location: event.location)
208
+ end
209
+ end
210
+
211
+ def parse_located_events(notes)
212
+ events = notes.filter_map do |local_date_time, text|
213
+ match = NOTE_LOCATED.match(text)
214
+ next if match.nil?
215
+
216
+ location = parse_api_city_state(match[:city_state])
217
+ date_time = ::FreightKit::DateTime.new(local_date_time:, location:)
218
+ next if date_time.date_time_with_zone.nil?
219
+
220
+ ShipmentEvent.new(date_time:, location:, type_code: :located)
221
+ end
222
+
223
+ events.chunk_while { |a, b| [a.location.city, a.location.province] == [b.location.city, b.location.province] }.map(&:first)
224
+ end
225
+
158
226
  # Documents
159
227
 
160
228
  # Rates
@@ -148,22 +148,25 @@ module FreightKit
148
148
  bol: 'connectapi.tfwwi.com',
149
149
  pickup: 'connectapi.tfwwi.com',
150
150
  pod: 'rrd.mercurygate.net',
151
- quote: 'connectapi.tfwwi.com'
151
+ quote: 'connectapi.tfwwi.com',
152
+ search: 'connectapi.tfwwi.com'
152
153
  },
153
154
  staging: {
154
155
  bol: 'connectapi-stage.tfwwi.com',
155
156
  pickup: 'connectapi-stage.tfwwi.com',
156
157
  pod: 'rrd.mercurygate.net',
157
- quote: 'connectapi-stage.tfwwi.com'
158
+ quote: 'connectapi-stage.tfwwi.com',
159
+ search: 'connectapi-stage.tfwwi.com'
158
160
  }
159
161
  },
160
162
  endpoints: {
161
163
  bol: '/services/api/v1/Shipment/documentExtract?primaryReferenceBol=%TRACKING_NUMBER%',
162
164
  pickup: '/services/api/v1/Shipment/Import',
163
165
  pod: '/MercuryGate/login/mgLogin.jsp?inline=true',
164
- quote: '/services/api/v1/RateShop/RateRequest'
166
+ quote: '/services/api/v1/RateShop/RateRequest',
167
+ search: '/services/api/v1/Shipment/Tracking'
165
168
  },
166
- methods: { bol: :get, pickup: :post, pod: :get, quote: :post }
169
+ methods: { bol: :get, pickup: :post, pod: :get, quote: :post, search: :get }
167
170
  }.freeze
168
171
  JSON_HEADERS = { Accept: 'application/json', 'Content-Type': 'application/json', charset: 'utf-8' }.freeze
169
172
  SERVICE_CODES = {
@@ -578,6 +581,18 @@ module FreightKit
578
581
  rate_response
579
582
  end
580
583
 
584
+ # @param value [String, nil] A location, e.g. "Wickliffe, KY 42087".
585
+ # @return [Location, nil] Without a postal code, `nil`.
586
+ def parse_location(value)
587
+ city, state_postal_code = value.to_s.split(',', 2).map(&:squish)
588
+ province, postal_code = state_postal_code.to_s.split
589
+ return if postal_code.blank?
590
+
591
+ country = postal_code.match?(/[a-z]/i) ? 'CA' : 'US'
592
+
593
+ Location.new(city: city&.titleize, country: ActiveUtils::Country.find(country), postal_code:, province:)
594
+ end
595
+
581
596
  def parse_response(response)
582
597
  case response.code
583
598
  when 204
@@ -597,6 +612,35 @@ module FreightKit
597
612
 
598
613
  def request_url(action) = "https://#{API.dig(:domains, :production, action)}#{API.dig(:endpoints, action)}"
599
614
 
615
+ # Searches the reference as a primary reference BOL and a PO.
616
+ #
617
+ # @note The API answers searches that find nothing with HTTP 204 or 404. Tracking numbers are primary reference
618
+ # BOLs, and the carrier's PRO is a reference.
619
+ # @see Carrier#search_reference
620
+ def search_reference(reference, **)
621
+ %i[primaryReferenceBol poNumber].flat_map do |key|
622
+ request = save_request(headers: build_headers, method: :get, url: "#{request_url(:search)}?#{{ key => reference }.to_query}")
623
+ response = commit(request)
624
+ next [] if response.code == 404
625
+
626
+ Array.wrap(parse_response(response).presence).filter_map do |tracking|
627
+ next if tracking['PrimaryReferenceBol'].blank?
628
+
629
+ weight = tracking['Weight'].to_s[/[\d.]+/]
630
+
631
+ SearchResult.new(
632
+ delivered_on: tracking['ActualDeliveryDate'].presence&.then { |value| ::Date.strptime(value, '%m/%d/%Y') },
633
+ destination: parse_location(tracking['Destination']),
634
+ origin: parse_location(tracking['Origin']),
635
+ picked_up_on: tracking['ActualPickupDate'].presence&.then { |value| ::Date.strptime(value, '%m/%d/%Y') },
636
+ references: { other: tracking.values_at('ProNumber', 'ShipmentReferenceNumber'), po_number: tracking['PoNumber'] },
637
+ tracking_number: tracking['PrimaryReferenceBol'],
638
+ weight: (Measured::Weight.new(weight.to_d, :pounds) if weight)
639
+ )
640
+ end
641
+ end
642
+ end
643
+
600
644
  # Tracking
601
645
  end
602
646
  end
@@ -90,6 +90,12 @@ module FreightKit
90
90
 
91
91
  protected
92
92
 
93
+ def dock
94
+ headquarters = self.class.headquarters
95
+
96
+ Location.new(city: headquarters.city, country: ActiveUtils::Country.find('USA'), province: headquarters.region_abbreviation)
97
+ end
98
+
93
99
  def document(type, tracking_number)
94
100
  document_response = DocumentResponse.new(request: { tracking_number:, type: })
95
101
  cookies = HTTPClient.cookie_jar
@@ -175,7 +181,7 @@ module FreightKit
175
181
 
176
182
  location = unless type_code == :delivery_appointment_scheduled
177
183
  city_state = event.downcase.split(text).last.delete(',')
178
- parse_api_city_state(city_state) unless city_state.include?('carrier')
184
+ city_state.include?('carrier') ? dock : parse_api_city_state(city_state)
179
185
  end
180
186
 
181
187
  ShipmentEvent.new(date_time: parse_api_date_time(date_time, location), location:, type_code:)
@@ -221,6 +227,34 @@ module FreightKit
221
227
  submit(cookies, results, '__EVENTARGUMENT' => 'Select$0', '__EVENTTARGET' => 'ctl00$cphMain$grvInvoice')
222
228
  end
223
229
 
230
+ # Searches the public tracking page, which finds every customer's shipments.
231
+ #
232
+ # @note The details swap pieces and weight, so the weight comes from the results.
233
+ # @see Carrier#search_reference
234
+ def search_reference(reference, **)
235
+ cookies = HTTPClient.cookie_jar
236
+ fields = { 'ctl00$cphMain$btnSearchRefNumber' => 'Search', 'ctl00$cphMain$txtRefNumber' => reference }
237
+ results = submit(cookies, fetch(cookies, request_url(:track)), fields)
238
+ rows = results.css('#cphMain_grvInvoice tr').map { |row| row.css('td').map { |cell| cell.text.squish } }
239
+ rows = rows.select { |cells| cells.size == 9 }
240
+
241
+ rows.each_with_index.filter_map do |(_, _, picked_up_on, delivered_on, _, _, _, weight, tracking_number), index|
242
+ next if tracking_number.blank?
243
+
244
+ details = submit(cookies, results, '__EVENTARGUMENT' => "Select$#{index}", '__EVENTTARGET' => 'ctl00$cphMain$grvInvoice')
245
+
246
+ SearchResult.new(
247
+ delivered_on: delivered_on.presence&.then { |value| ::Date.strptime(value, '%m/%d/%Y') },
248
+ destination: parse_api_city_state_zip(details.at('#cphMain_lblConsCSZ')&.text&.squish),
249
+ origin: parse_api_city_state_zip(details.at('#cphMain_lblShipperCSZ')&.text&.squish),
250
+ picked_up_on: picked_up_on.presence&.then { |value| ::Date.strptime(value, '%m/%d/%Y') },
251
+ references: { bol_number: details.at('#cphMain_lblBLNumber')&.text, po_number: details.at('#cphMain_lblPONumber')&.text },
252
+ tracking_number:,
253
+ weight: (Measured::Weight.new(weight.delete(',').to_d, :pounds) if weight.present?)
254
+ )
255
+ end
256
+ end
257
+
224
258
  def submit(cookies, page, fields)
225
259
  form = page.at('form')
226
260
  inputs = form.css('input[name]').reject { |input| ['button', 'image', 'submit'].include?(input['type']) }
@@ -155,7 +155,21 @@ module FreightKit
155
155
  def website_url = 'https://www.xpo.com'
156
156
  end
157
157
 
158
- API = { domain: 'api.ltl.xpo.com', endpoints: { rates: '/rating/1.0/ratequotes', token: '/token' }, use_ssl: true }.freeze
158
+ API = {
159
+ domain: 'api.ltl.xpo.com',
160
+ endpoints: { rates: '/rating/1.0/ratequotes', search: '/tracking/1.0/shipments/shipment-status-details', token: '/token' },
161
+ use_ssl: true
162
+ }.freeze
163
+ # `suppRef` `referenceTypeCd`s, as `Carrier::NUMBERS` labels
164
+ REFERENCE_LABELS = {
165
+ 'BL' => :bol_number,
166
+ 'BOL' => :bol_number,
167
+ 'PO' => :po_number,
168
+ 'PO#' => :po_number,
169
+ 'PRO#' => :tracking_number,
170
+ 'SI' => :order_number,
171
+ 'SN#' => :order_number
172
+ }.freeze
159
173
 
160
174
  # Documents
161
175
 
@@ -307,18 +321,38 @@ module FreightKit
307
321
 
308
322
  if error.blank?
309
323
  return json if (200..299).include?(response.code)
310
- else
311
- case response.code
312
- when 401
313
- raise FreightKit::InvalidCredentialsError
314
- end
324
+ elsif response.code == 401 || json[:error] == 'invalid_grant'
325
+ raise FreightKit::InvalidCredentialsError, error
315
326
  end
316
327
 
317
328
  raise FreightKit::ResponseError, error
318
329
  end
319
330
 
331
+ # @param address [Hash, nil] An address, e.g. `shipperAddr`.
332
+ # @return [Location, nil]
333
+ # @note `countryCd` is often blank, so the postal code tells Canada from the US.
334
+ def parse_address(address)
335
+ return if address.blank?
336
+
337
+ postal_code = address[:postalCd].presence
338
+ country = address[:countryCd].presence || (postal_code.to_s.match?(/[a-z]/i) ? 'CA' : 'US')
339
+
340
+ Location.new(
341
+ address1: address[:addressLine1].presence,
342
+ address2: address[:addressLine2].presence,
343
+ city: address[:cityName].presence&.titleize,
344
+ country: ActiveUtils::Country.find(country),
345
+ postal_code:,
346
+ province: address[:stateCd].presence
347
+ )
348
+ end
349
+
320
350
  def parse_amount(amount) = (amount.to_f * 100).to_i
321
351
 
352
+ # @param milliseconds [Integer, nil] Milliseconds since the epoch, which the API gives dates in.
353
+ # @return [Date, nil]
354
+ def parse_milliseconds(milliseconds) = milliseconds&.then { |value| Time.at(value / 1000).utc.to_date }
355
+
322
356
  def parse_rate_response(shipment:, response:)
323
357
  rate_response = RateResponse.new(request: last_request, response:)
324
358
 
@@ -409,6 +443,33 @@ module FreightKit
409
443
  "#{scheme}#{API.dig(:domains, action)}#{API.dig(:endpoints, action)}"
410
444
  end
411
445
 
446
+ # Searches any kind of reference.
447
+ #
448
+ # @note Pickup dates are milliseconds since the epoch.
449
+ # @see Carrier#search_reference
450
+ def search_reference(reference, **)
451
+ request = { headers: build_headers, method: :get, url: "#{build_url(:search)}?#{{ referenceNumbers: [reference] }.to_query}" }
452
+ save_request(request)
453
+
454
+ commit(request).dig(:data, :shipmentStatusDtls).to_a.filter_map do |details|
455
+ next if details[:proNbr].blank?
456
+
457
+ weight = details.dig(:totWeight, :weight)
458
+
459
+ references = details[:suppRef].to_a.group_by { |supp_ref| REFERENCE_LABELS.fetch(supp_ref[:referenceTypeCd].to_s.upcase, :other) }
460
+
461
+ SearchResult.new(
462
+ delivered_on: parse_milliseconds(details[:finalDlvrDate]),
463
+ destination: parse_address(details[:consigneeAddr]),
464
+ origin: parse_address(details[:shipperAddr]),
465
+ picked_up_on: parse_milliseconds(details[:pkupDate]),
466
+ references: references.transform_values { |supp_refs| supp_refs.pluck(:reference) },
467
+ tracking_number: details[:proNbr].to_s,
468
+ weight: (Measured::Weight.new(weight, :pounds) if weight.present?)
469
+ )
470
+ end
471
+ end
472
+
412
473
  # Tracking
413
474
  end
414
475
  end
@@ -0,0 +1,3 @@
1
+ module FreightKit
2
+ class AmbiguousShipmentError < Error; end
3
+ end
@@ -13,14 +13,26 @@ module FreightKit
13
13
  response = commit(:rates, request) if method(:commit).parameters.count == 2
14
14
  response ||= commit(request)
15
15
 
16
- return response if response.is_a?(RateResponse)
17
-
18
- parse_rate_response(shipment:, response:)
16
+ rate_response = response.is_a?(RateResponse) ? response : parse_rate_response(shipment:, response:)
17
+ add_tariff_overlength_fees(rate_response, shipment)
19
18
  rescue FreightKit::InvalidCredentialsError => e
20
19
  rate_response = RateResponse.new(request:, response:)
21
20
  rate_response.error = e
22
21
 
23
22
  rate_response
24
23
  end
24
+
25
+ private
26
+
27
+ # Adds the tariff's overlength fees to each rate when the carrier's API does not price them.
28
+ def add_tariff_overlength_fees(rate_response, shipment)
29
+ return rate_response unless self.class.overlength_fees_require_tariff?
30
+
31
+ cents = shipment.packages.sum { |package| overlength_fee(@tariff, package) }
32
+ return rate_response if cents.zero?
33
+
34
+ rate_response.rates&.each { |rate| rate.prices = [*rate.prices, Price.new(blame: :tariff, cents:, description: 'Overlength fees')] }
35
+ rate_response
36
+ end
25
37
  end
26
38
  end
@@ -0,0 +1,12 @@
1
+ module FreightKit
2
+ # Represents the response to a {FreightKit::Carrier#find_shipment} call.
3
+ #
4
+ # @!attribute candidates
5
+ # @return [Array<FreightKit::SearchResult>] The shipments that pass the rules, best match first.
6
+ #
7
+ # @!attribute result
8
+ # @return [FreightKit::SearchResult, nil] The one shipment that matches best.
9
+ class SearchResponse < Response
10
+ attr_accessor :candidates, :result
11
+ end
12
+ end
@@ -0,0 +1,121 @@
1
+ module FreightKit
2
+ # A shipment that {Carrier#find_shipment} found at the carrier by one of the references.
3
+ #
4
+ # @attribute delivered_on
5
+ # @return [Date, nil]
6
+ #
7
+ # @attribute destination
8
+ # @return [FreightKit::Location, nil]
9
+ #
10
+ # @attribute matched_references
11
+ # @return [Array<String>] The searched references that found the shipment.
12
+ #
13
+ # @attribute origin
14
+ # @return [FreightKit::Location, nil]
15
+ #
16
+ # @attribute picked_up_on
17
+ # @return [Date, nil]
18
+ #
19
+ # @attribute references
20
+ # @return [Hash{Symbol => Array<String>}] The shipment's references at the carrier, by `Carrier::NUMBERS` label as
21
+ # the carrier labels them, or `:other` when the carrier's label has no equivalent.
22
+ #
23
+ # @attribute score
24
+ # @return [Array<Numeric>] How well the shipment matches, compared element by element. Set by {#assess}.
25
+ #
26
+ # @attribute tracking_number
27
+ # @return [String]
28
+ #
29
+ # @attribute weight
30
+ # @return [Measured::Weight, nil]
31
+ class SearchResult < Model
32
+ class << self
33
+ # @param value [String]
34
+ # @return [String] The number without a typed label, e.g. "2087007" for "PO# 2087007".
35
+ def unlabel(value) = value.to_s.squish.sub(LABEL_PREFIX, '')
36
+ end
37
+
38
+ # How far the carrier's pickup and delivery dates can be from the searched ones. Appointments slip.
39
+ DATE_TOLERANCE = 3.days
40
+ # Labels that people type before numbers, e.g. "PO# "
41
+ LABEL_PREFIX = %r{\A(?:B/?L|BOL|P\.?O\.?|REF|SO)(?:\s*(?:#|NO\.?)\s*|[\s:-]+)}i
42
+
43
+ attr_accessor :delivered_on, :destination, :matched_references, :origin, :picked_up_on, :score, :tracking_number, :weight
44
+ attr_reader :references
45
+
46
+ # Compares the shipment with the searched data, and sets {#score}.
47
+ #
48
+ # @see Carrier#find_shipment The rules.
49
+ # @param references [Hash{Symbol, nil => Array<String>}] Our references by label, `nil` for unlabeled ones.
50
+ # @param delivered_on [Date, nil]
51
+ # @param destination [FreightKit::Location, nil]
52
+ # @param origin [FreightKit::Location, nil]
53
+ # @param pickup_on [Date, nil]
54
+ # @param weight [Measured::Weight, nil]
55
+ # @return [Boolean] Whether the shipment passes the rules.
56
+ def assess(references:, delivered_on: nil, destination: nil, origin: nil, pickup_on: nil, weight: nil)
57
+ locations = [compare_locations(destination, self.destination), compare_locations(origin, self.origin)]
58
+ dates = [compare_dates(pickup_on, picked_up_on), compare_dates(delivered_on, self.delivered_on)]
59
+ labeled_matches = labeled_matches(references)
60
+ self.score = [labeled_matches, locations.count(true), matched_references.to_a.size, dates.count(true), -weight_difference(weight)]
61
+ return false if locations.include?(false) || dates.include?(false)
62
+
63
+ locations.count(true) >= (labeled_matches.positive? ? 1 : 2)
64
+ end
65
+
66
+ # @param references [Hash{Symbol => String, Array<String>, nil}] Blank values are left out.
67
+ def references=(references)
68
+ references = references.to_h.transform_values { |values| Array(values).filter_map { |value| value.to_s.squish.presence } }
69
+ @references = references.compact_blank
70
+ end
71
+
72
+ protected
73
+
74
+ # @return [Boolean, nil] Whether the dates are within {DATE_TOLERANCE}, or `nil` when either is blank.
75
+ def compare_dates(expected, actual)
76
+ return if expected.nil? || actual.nil?
77
+
78
+ (actual - expected).abs <= DATE_TOLERANCE.in_days
79
+ end
80
+
81
+ # @return [Boolean, nil] Whether the countries and postal codes match, or `nil` when either is blank.
82
+ def compare_locations(expected, actual)
83
+ return if expected.nil? || actual.nil?
84
+
85
+ countries = [expected, actual].map { |location| location.country&.code(:alpha2)&.value }
86
+ return false if countries.all? && countries.uniq.size > 1
87
+
88
+ postal_codes = [expected, actual].map { |location| postal_code(location) }
89
+ postal_codes.uniq.one? if postal_codes.all?
90
+ end
91
+
92
+ # @param references [Hash{Symbol, nil => Array<String>}]
93
+ # @return [Integer] How many of our labeled references the carrier has under the same label.
94
+ def labeled_matches(references)
95
+ references.except(nil).sum do |label, values|
96
+ carrier_values = self.references.to_h.fetch(label, []).map { |value| normalize(value) }
97
+ values.count { |value| carrier_values.include?(normalize(value)) }
98
+ end
99
+ end
100
+
101
+ # @return [String] The number without a typed label, punctuation, spaces or leading zeros, e.g. "123" for
102
+ # "PO# 0123".
103
+ def normalize(value) = self.class.unlabel(value).upcase.delete('^0-9A-Z').sub(/\A0+(?=\d)/, '')
104
+
105
+ # @return [String, nil] 5-digit US ZIP Codes, and other postal codes without spaces.
106
+ def postal_code(location)
107
+ value = location.postal_code.to_s.upcase.delete('^0-9A-Z')
108
+ return if value.empty?
109
+
110
+ value.match?(/\A\d+\z/) ? value.first(5) : value
111
+ end
112
+
113
+ # @return [Float] The difference as a share of the searched weight, and 1 when either is unknown.
114
+ def weight_difference(expected)
115
+ expected_pounds = expected&.convert_to(:pounds)&.value
116
+ return 1.0 if expected_pounds.nil? || expected_pounds.zero? || weight.nil?
117
+
118
+ ((weight.convert_to(:pounds).value - expected_pounds).abs / expected_pounds).to_f
119
+ end
120
+ end
121
+ end
@@ -277,14 +277,6 @@ module FreightKit
277
277
 
278
278
  prices = [Price.new(blame: :api, cents: total_cents - prices.sum(&:cents), description: 'Freight')] + prices
279
279
 
280
- if self.class.overlength_fees_require_tariff?
281
- cents = 0
282
-
283
- shipment.packages.each { |package| cents += overlength_fee(tariff, package) }
284
-
285
- prices << Price.new(blame: :tariff, cents:, description: 'Overlength fees') if cents.nonzero?
286
- end
287
-
288
280
  rate = Rate.new(
289
281
  carrier: self,
290
282
  carrier_name: name,
@@ -132,7 +132,7 @@ module FreightKit
132
132
  # @return [TrackingResponse] With a {ShipmentNotFoundError} when no shipment has the number.
133
133
  def find_tracking_info(tracking_number)
134
134
  tracking_response = TrackingResponse.new(carrier: self, carrier_name: name, tracking_number:)
135
- shipment = find_shipment(tracking_number)
135
+ shipment = fetch_shipment(tracking_number)
136
136
  tracking_response.assign_attributes(request: last_request, response: shipment&.attributes)
137
137
  return tracking_response.tap { |response| response.error = ShipmentNotFoundError.new } if shipment.nil?
138
138
 
@@ -277,7 +277,7 @@ module FreightKit
277
277
  end
278
278
 
279
279
  def document(tracking_number, kind, response_class = DocumentResponse)
280
- data = find_shipment_data(tracking_number, :shipment_documents)
280
+ data = fetch_shipment_data(tracking_number, :shipment_documents)
281
281
  document_response = response_class.new(request: last_request, response: data)
282
282
  return document_response.tap { |response| response.error = ShipmentNotFoundError.new } if data.nil?
283
283
 
@@ -306,15 +306,15 @@ module FreightKit
306
306
  return labels.map { |label| Label.new(data: download(label[:url]).body) } if labels.any? || seconds.nil?
307
307
 
308
308
  sleep(seconds)
309
- documents = find_shipment_data(shipment_data[:load_id], :shipment_documents)&.dig(:documents).to_a
309
+ documents = fetch_shipment_data(shipment_data[:load_id], :shipment_documents)&.dig(:documents).to_a
310
310
  end
311
311
  rescue StandardError => e
312
312
  HTTPClient.logger.warn("Next TMS load #{shipment_data[:load_id]} booked without labels: #{e.class}: #{e.message}")
313
313
  []
314
314
  end
315
315
 
316
- def find_shipment(tracking_number)
317
- data = find_shipment_data(tracking_number)
316
+ def fetch_shipment(tracking_number)
317
+ data = fetch_shipment_data(tracking_number)
318
318
 
319
319
  self.class::ORM::Shipment.new(data[:id], loaded: true, **data.except(:id)) if data
320
320
  end
@@ -324,7 +324,7 @@ module FreightKit
324
324
  # `ORM.credentials`.
325
325
  #
326
326
  # @raise [ResponseError] When the number is the PRO of several shipments.
327
- def find_shipment_data(tracking_number, operation = :shipments)
327
+ def fetch_shipment_data(tracking_number, operation = :shipments)
328
328
  load_id = load_id(tracking_number)
329
329
  items = shipments_by_tracking_number(tracking_number.to_s, operation)
330
330
  data = (items.find { |item| item[:load_id] == load_id } if load_id) || (items.first if items.one?)
@@ -423,6 +423,37 @@ module FreightKit
423
423
  end
424
424
  end
425
425
 
426
+ # Searches the reference as each kind of shipment number, and as a load ID.
427
+ #
428
+ # @note Results have no weight, and their tracking numbers are load IDs.
429
+ # @see Carrier#search_reference
430
+ def search_reference(reference, **)
431
+ conditions = %i[bol_eq customer_reference_eq pickup_confirmation_eq shipper_bol_eq shipper_reference_eq].map do |key|
432
+ { key => reference }
433
+ end
434
+ conditions << { load_id_eq: load_id(reference) } if load_id(reference)
435
+ items = query(:shipments, filter: { or: conditions }, page_size: 25).dig(:shipments, :items).to_a
436
+
437
+ items.map do |data|
438
+ shipment = self.class::ORM::Shipment.new(data[:id], loaded: true, **data.except(:id))
439
+
440
+ SearchResult.new(
441
+ delivered_on: shipment.delivered_at&.to_date,
442
+ destination: shipment.receiver_address&.to_location,
443
+ origin: shipment.shipper_address&.to_location,
444
+ picked_up_on: shipment.pickup_on,
445
+ references: {
446
+ bol_number: data.values_at(:bol, :shipper_bol),
447
+ order_number: data[:shipper_reference],
448
+ pickup_number: data[:pickup_confirmation],
449
+ po_number: data[:customer_reference],
450
+ tracking_number: [data[:load_id], data[:pro]]
451
+ },
452
+ tracking_number: data[:load_id].to_s
453
+ )
454
+ end
455
+ end
456
+
426
457
  # The load ID comes first, since other shipments can have it as their PRO. Two PROs are enough to tell a unique PRO
427
458
  # from one that several carriers use.
428
459
  def shipments_by_tracking_number(tracking_number, operation = :shipments)