freight_kit 0.1.34 → 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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 4522fdf8cf8f10256946894b1f170a010a0fbca0f31e59bde4dd7911596142e6
4
- data.tar.gz: c12f00b6c32d934aba2b22e1da9399940f06152ee6c8fe84146c39e98662d0fd
3
+ metadata.gz: e3f30776ea757f9ac1e4bc2ef09b77b22847ea9d05c643ba8296961a5ac3e168
4
+ data.tar.gz: f390249f8bdeff06663008ec49ec5dd0d27cc81d0f88b6b47984f0968cff4902
5
5
  SHA512:
6
- metadata.gz: 8c01c2283acf775a73afb16df0c068c56b868cab9655150ea4e0ae13a6e47be16a04428f4439135be0f0bf538263f4dcf4d9a89abe4772dd5a67243d8eff7d4c
7
- data.tar.gz: 638901575460f6df3d07be5ba785ff3712fb27f5b098b5bbe2dc372bc3ec7cff37f0d112072fcbf5c7ec3ce9be0c7aaffc1b879e2d3d3c94e13c765a78ecdfa6
6
+ metadata.gz: 6f83f4a8d7cf1f540e2f27e195fa40f198693337dee3754bb8a65cfd4846c4b304da15afd68726a018d5b6ed7c0f1f525c86b9fd7371520dcb42f6ecdf256cce
7
+ data.tar.gz: b3d90778bd5fdf66c05d4e9e7164064436bde4384253996437f76b28aa92b2c3490c7ff3594ec30d15930157c1778bb904145957d5b9c1ba6a93243389d34e9c
data/Gemfile.lock CHANGED
@@ -1,7 +1,7 @@
1
1
  PATH
2
2
  remote: .
3
3
  specs:
4
- freight_kit (0.1.33)
4
+ freight_kit (0.1.34)
5
5
  StreetAddress (~> 2.0)
6
6
  active_utils (>= 3.3.1, < 3.7.0)
7
7
  activemodel (>= 7.1, < 8.1.5)
data/README.md CHANGED
@@ -5,6 +5,7 @@ This library interfaces with the web services of various shipping carriers. The
5
5
  FreightKit supports:
6
6
 
7
7
  - Downloading scanned documents
8
+ - Finding shipments by their references
8
9
  - Finding shipping rates
9
10
  - Tracking shipments
10
11
 
@@ -31,26 +32,26 @@ __Note:__ `Carrier`s may extend `Platform`s and override them when their behavio
31
32
 
32
33
  ## Supported Carriers
33
34
 
34
- |Carrier |Scanned BOL|POD|Invoices|Pickups|Rates|Tracking|
35
- |-----------------------------------|-----------|---|--------|-------|-----|--------|
36
- |ABF Freight System | | | | |✓ | |
37
- |Best Overnite Express |✓ |✓ | |✓ |✓ |✓ |
38
- |Clear Lane Freight Systems | | | | |✓ | |
39
- |DC Logistics |✓ |✓ | |✓ |✓ |✓ |
40
- |The Custom Companies | | | | |✓ |✓ |
41
- |Dependable Highway Express |✓ |✓ | | |✓ |✓ |
42
- |Forward Air |✓ |✓ | |✓ |✓ |✓ |
43
- |Frontline Freight |✓ |✓ | | |✓ |✓ |
44
- |Numark Transportation |✓ |✓ | |✓ |✓ |✓ |
45
- |OnTrac | | | | |✓ | |
46
- |Peninsula Truck Lines | | | | |✓ | |
47
- |RE Logistics |✓ |✓ |✓ |✓ |✓ |✓ |
48
- |Roadrunner Transportation Services |✓ |✓ | | |✓ |✓ |
49
- |Saia | | | |✓ |✓ |✓ |
50
- |Southeastern Freight Lines | | | | |✓ | |
51
- |Tforce Worldwide |✓ |✓ | |✓ |✓ | |
52
- |Total Transportation & Distribution|✓ |✓ | | |✓ |✓ |
53
- |Western Regional Delivery Service | |✓ | | | |✓ |
35
+ |Carrier |Scanned BOL|POD|Invoices|Pickups|Rates|Search|Tracking|
36
+ |-----------------------------------|-----------|---|--------|-------|-----|------|--------|
37
+ |ABF Freight System | | | | |✓ | | |
38
+ |Best Overnite Express |✓ |✓ | |✓ |✓ | |✓ |
39
+ |Clear Lane Freight Systems | | | | |✓ | | |
40
+ |DC Logistics |✓ |✓ | |✓ |✓ | |✓ |
41
+ |The Custom Companies | | | | |✓ | |✓ |
42
+ |Dependable Highway Express |✓ |✓ | | |✓ | |✓ |
43
+ |Forward Air |✓ |✓ | |✓ |✓ | |✓ |
44
+ |Frontline Freight |✓ |✓ | | |✓ | |✓ |
45
+ |Numark Transportation |✓ |✓ | |✓ |✓ | |✓ |
46
+ |OnTrac | | | | |✓ | | |
47
+ |Peninsula Truck Lines | | | | |✓ | | |
48
+ |RE Logistics |✓ |✓ |✓ |✓ |✓ |✓ |✓ |
49
+ |Roadrunner Transportation Services |✓ |✓ | | |✓ | |✓ |
50
+ |Saia | | | |✓ |✓ |✓ |✓ |
51
+ |Southeastern Freight Lines | | | | |✓ |✓ | |
52
+ |Tforce Worldwide |✓ |✓ | |✓ |✓ |✓ | |
53
+ |Total Transportation & Distribution|✓ |✓ | | |✓ | |✓ |
54
+ |Western Regional Delivery Service | |✓ | | | |✓ |✓ |
54
55
 
55
56
  ## Installation
56
57
 
data/VERSION CHANGED
@@ -1 +1 @@
1
- 0.1.34
1
+ 0.1.35
@@ -45,6 +45,10 @@ module FreightKit
45
45
  # @return [Boolean]
46
46
  def find_rates_with_declared_value? = false
47
47
 
48
+ # Whether {#find_shipment} is implemented.
49
+ # @return [Boolean]
50
+ def find_shipment_implemented? = implemented?(:search_reference)
51
+
48
52
  # The carrier's main office, from its public FMCSA registration.
49
53
  # @return [FreightKit::Address, nil]
50
54
  def headquarters = nil
@@ -70,14 +74,11 @@ module FreightKit
70
74
  # @return [String, nil]
71
75
  def legal_name = nil
72
76
 
73
- # The package's longest horizontal dimension (length or width), as a
74
- # Measured::Length so comparisons stay unit-agnostic.
77
+ # The package's longest horizontal dimension (length or width), rounded up to a whole inch as carriers measure it.
75
78
  #
76
79
  # @param package [FreightKit::Package]
77
80
  # @return [Measured::Length]
78
- def longest_dimension(package)
79
- [Measured::Length.new(package.length(:inches), :inches), Measured::Length.new(package.width(:inches), :inches)].max
80
- end
81
+ def longest_dimension(package) = Measured::Length.new([package.length(:inches), package.width(:inches)].max.ceil, :inches)
81
82
 
82
83
  # FreightKit accessorials the carrier prices, mapped to the carrier's codes.
83
84
  # @return [Hash{Symbol => Object}]
@@ -418,6 +419,62 @@ module FreightKit
418
419
  # includes 0 or more rate estimates for different shipping products
419
420
  def find_rates(shipment:) = raise NotImplementedError, "#find_rates is not supported by #{name}."
420
421
 
422
+ # Finds the one shipment at the carrier that matches our data. Carriers mix up which number is the BOL, the PO or the
423
+ # shipper number, so every reference is searched as every kind of number the carrier takes, and the carrier's
424
+ # shipments are then matched against our data in {SearchResult#assess}:
425
+ #
426
+ # 1. A shipment is ruled out when a postal code or country contradicts ours, or when its pickup or delivery date is
427
+ # more than {SearchResult::DATE_TOLERANCE} from ours. Data the carrier does not return contradicts nothing.
428
+ # 2. A shipment that has one of our references under the same label (our `:bol_number` as its BOL) passes with one
429
+ # matching postal code. Any other shipment must match both postal codes, because a number alone can be another
430
+ # customer's shipment.
431
+ # 3. Passing shipments rank by labeled references, then matching postal codes, then how many references found them,
432
+ # then matching dates, then the closest weight. Weight only ranks, since carriers reweigh.
433
+ # 4. The best one is the result, unless another one ranks the same.
434
+ #
435
+ # @example
436
+ # carrier.find_shipment(
437
+ # destination: Location.new(country: ActiveUtils::Country.find('US'), postal_code: '81625'),
438
+ # origin: Location.new(country: ActiveUtils::Country.find('US'), postal_code: '90039'),
439
+ # pickup_on: Date.new(2026, 11, 17),
440
+ # references: { bol_number: '68408', po_number: '26837' }
441
+ # ).result&.tracking_number # => "5056493"
442
+ #
443
+ # @param references [Hash{Symbol => String, Array<String>}, Array<String>] Our numbers for the shipment, by
444
+ # `NUMBERS` label, or unlabeled.
445
+ # @param delivered_on [Date, nil]
446
+ # @param destination [FreightKit::Location, nil] Compared by country and postal code.
447
+ # @param origin [FreightKit::Location, nil] Compared by country and postal code.
448
+ # @param pickup_on [Date, nil] Carriers that search by date also need it to find older shipments.
449
+ # @param weight [Measured::Weight, nil]
450
+ # @raise [ArgumentError] Without `destination` or `origin`, or with a label outside `NUMBERS`.
451
+ # @return [FreightKit::SearchResponse] With a {ShipmentNotFoundError} when no shipment passes, or an
452
+ # {AmbiguousShipmentError} when several rank the same.
453
+ def find_shipment(references:, delivered_on: nil, destination: nil, origin: nil, pickup_on: nil, weight: nil)
454
+ raise NotImplementedError, "#find_shipment is not supported by #{name}." unless self.class.find_shipment_implemented?
455
+ raise ArgumentError, "#{name}#find_shipment: pass `destination` or `origin`" if [destination, origin].none?
456
+
457
+ references = search_references(references)
458
+ values = references.values.flatten.flat_map { |reference| [reference, SearchResult.unlabel(reference)] }.uniq
459
+ candidates = values.flat_map do |reference|
460
+ search_reference(reference, destination:, origin:, pickup_on:).each { |candidate| candidate.matched_references = [reference] }
461
+ end
462
+ candidates = candidates.group_by(&:tracking_number).map do |_tracking_number, group|
463
+ group.first.tap { |candidate| candidate.matched_references = group.flat_map(&:matched_references).uniq }
464
+ end
465
+ criteria = { delivered_on:, destination:, origin:, pickup_on:, references:, weight: }
466
+ candidates = candidates.select { |candidate| candidate.assess(**criteria) }.sort_by(&:score).reverse
467
+ error = if candidates.empty?
468
+ ShipmentNotFoundError.new
469
+ elsif candidates.second&.score == candidates.first.score
470
+ AmbiguousShipmentError.new("#{candidates.count { |candidate| candidate.score == candidates.first.score }} shipments match")
471
+ end
472
+
473
+ SearchResponse.new(candidates:, error:, request: last_request, result: (candidates.first unless error))
474
+ rescue Error, HTTPX::Error, SystemCallError => e
475
+ SearchResponse.new(candidates: [], error: e, request: last_request)
476
+ end
477
+
421
478
  # Retrieves tracking information for a previous shipment
422
479
  #
423
480
  # @note Override with whatever you need to get a shipping label
@@ -471,6 +528,28 @@ module FreightKit
471
528
  # @return [void]
472
529
  def save_request(request) = @last_request = request
473
530
 
531
+ # Finds the carrier's shipments that have the reference as any kind of number, for {#find_shipment}.
532
+ #
533
+ # @param reference [String]
534
+ # @param destination [FreightKit::Location, nil] For carriers whose searches need it.
535
+ # @param origin [FreightKit::Location, nil] For carriers whose searches need it.
536
+ # @param pickup_on [Date, nil] For carriers whose searches need it.
537
+ # @return [Array<FreightKit::SearchResult>] Empty when no shipment has the reference.
538
+ def search_reference(reference, destination:, origin:, pickup_on:)
539
+ raise NotImplementedError, "#{name}: #search_reference not implemented"
540
+ end
541
+
542
+ # @param references [Hash{Symbol => String, Array<String>}, Array<String>]
543
+ # @raise [ArgumentError] With a label outside `NUMBERS`.
544
+ # @return [Hash{Symbol, nil => Array<String>}] The references by label, `nil` for unlabeled ones.
545
+ def search_references(references)
546
+ references = { nil => references } unless references.is_a?(Hash)
547
+ unknown = references.keys.compact - NUMBERS
548
+ raise ArgumentError, "#{name}#find_shipment: unknown labels #{unknown.join(', ')}" if unknown.any?
549
+
550
+ references.transform_values { |values| Array(values).map { |value| value.to_s.squish }.compact_blank.uniq }.compact_blank
551
+ end
552
+
474
553
  # Calculates a timestamp that corresponds a given number of business days in the future
475
554
  #
476
555
  # @param days [Integer] The number of business days from now.
@@ -125,7 +125,7 @@ module FreightKit
125
125
  }
126
126
  end
127
127
 
128
- def minimum_length_for_overlength_fees = Measured::Length.new(6, :feet)
128
+ def minimum_length_for_overlength_fees = Measured::Length.new(8, :feet)
129
129
  def name = 'CrossCountry Freight Solutions'
130
130
  def overlength_fees_require_tariff? = false
131
131
  def required_credential_types = %i[api_key]
@@ -170,11 +170,10 @@ module FreightKit
170
170
  accessorials << { Code: 'HAZMAT', Factor: 1 } if shipment.hazmat?
171
171
 
172
172
  shipment.packages.each do |package|
173
- longest_dimension = [package.width(:inches), package.length(:inches)].max.ceil
173
+ length = longest_dimension(package).value.to_i
174
+ next if length < self.class.minimum_length_for_overlength_fees.convert_to(:inches).value
174
175
 
175
- next if longest_dimension < 96
176
-
177
- package.quantity.times { accessorials << { Code: 'EXLEN', Factor: longest_dimension } }
176
+ package.quantity.times { accessorials << { Code: 'EXLEN', Factor: length } }
178
177
  end
179
178
 
180
179
  shipment.accessorials.map do |accessorial|
@@ -291,7 +290,7 @@ module FreightKit
291
290
  "HTTP #{response.code}"
292
291
  end
293
292
 
294
- raise FreightKit::InvalidCredentialsError, message if message == 'API key is inactive'
293
+ raise FreightKit::InvalidCredentialsError, message if response.code == 403 || message == 'API key is inactive'
295
294
 
296
295
  raise FreightKit::ResponseError, message
297
296
  end
@@ -299,6 +298,22 @@ module FreightKit
299
298
  JSON.parse(response.body)
300
299
  end
301
300
 
301
+ def parse_address(address)
302
+ return if address.blank?
303
+
304
+ postal_code = address['Zip'].presence
305
+ country = address['Country'].presence || (postal_code.to_s.match?(/[a-z]/i) ? 'CA' : 'US')
306
+
307
+ Location.new(
308
+ address1: address['Address1'].presence,
309
+ address2: address['Address2'].presence,
310
+ city: address['City'].presence&.titleize,
311
+ country: ActiveUtils::Country.find(country),
312
+ postal_code:,
313
+ province: address['State'].presence
314
+ )
315
+ end
316
+
302
317
  def parse_document_response(type, tracking_number)
303
318
  # Tracking Endpoint returns Images for the Shipment
304
319
  request = build_request(:track, query: { ReferenceNum: tracking_number })
@@ -352,6 +367,11 @@ module FreightKit
352
367
  return rate_response
353
368
  end
354
369
 
370
+ if response['Message'] == 'Rating profile is not active'
371
+ rate_response.error = InvalidCredentialsError.new(response['Message'])
372
+ return rate_response
373
+ end
374
+
355
375
  if response['Message'].include?('Quotes between these points are not available')
356
376
  rate_response.error = UnserviceableError.new(response['Message'])
357
377
  return rate_response
@@ -371,14 +391,17 @@ module FreightKit
371
391
 
372
392
  prices = []
373
393
 
374
- ['AccessorialCharge', 'FuelCharge', 'HighCostCharge', 'MinCharge'].each do |charge_line_key|
394
+ ['AccessorialCharge', 'BaseCharge', 'FuelCharge', 'HighCostCharge'].each do |charge_line_key|
375
395
  charge_line = response[charge_line_key]
376
396
  next unless charge_line
377
397
 
378
- cents = (charge_line.to_f * 100).to_i
398
+ cents = (charge_line.to_s.to_d * 100).round.to_i
379
399
  prices << Price.new(blame: :api, cents:, description: charge_line_key)
380
400
  end
381
401
 
402
+ unitemized_cents = (response['TotalCharge'].to_s.to_d * 100).round.to_i - prices.sum(&:cents)
403
+ prices << Price.new(blame: :api, cents: unitemized_cents, description: 'Unitemized charges') if unitemized_cents.nonzero?
404
+
382
405
  rate = Rate.new(
383
406
  carrier: self,
384
407
  carrier_name: name,
@@ -402,6 +425,39 @@ module FreightKit
402
425
 
403
426
  # TODO
404
427
  end
428
+
429
+ # @param type [String, nil] A reference's `Type`, e.g. "Pro Num".
430
+ # @return [Symbol] A `Carrier::NUMBERS` label, or `:other`.
431
+ # @note The other types are "Freight Bill Num", "Reference Num", "Related Freight Bill Num" and "Statement Num",
432
+ # and "Reference Num" holds BOL, PO and shipper numbers alike.
433
+ def reference_label(type) = type.to_s.casecmp?('Pro Num') ? :tracking_number : :other
434
+
435
+ # Searches any kind of reference, among shipments picked up within 3 days of `pickup_on`, or in the past week.
436
+ #
437
+ # @note The API searches at most 7 days of pickups, and only today's by default.
438
+ # @see Carrier#search_reference
439
+ def search_reference(reference, pickup_on:, **)
440
+ dates = pickup_on ? [pickup_on - 3.days, pickup_on + 3.days] : [::Date.current - 6.days, ::Date.current]
441
+ query = { BeginDate: dates.first.iso8601, EndDate: dates.last.iso8601, ReferenceNum: reference }
442
+
443
+ Array.wrap(commit(:track, build_request(:track, query:))).filter_map do |track|
444
+ next if track['ProNum'].blank?
445
+
446
+ references = track['Reference'].to_a.group_by { |reference| reference_label(reference['Type']) }
447
+ references = references.transform_values { |list| list.pluck('Number') }
448
+ references[:other] = [*references[:other], *track.values_at('FreightBillNum', 'PrimaryReferenceNum')]
449
+
450
+ SearchResult.new(
451
+ delivered_on: track['DeliveryDate'].presence&.to_date,
452
+ destination: parse_address(track['ConsigneeAddress']),
453
+ origin: parse_address(track['ShipperAddress']),
454
+ picked_up_on: track['PickupDate'].presence&.to_date,
455
+ references:,
456
+ tracking_number: track['ProNum'],
457
+ weight: (Measured::Weight.new(track['TotalWeight'].to_d, :pounds) if track['TotalWeight'].present?)
458
+ )
459
+ end
460
+ end
405
461
  end
406
462
  end
407
463
  end
@@ -25,7 +25,6 @@ module FreightKit
25
25
  def name = 'Forward Air'
26
26
  def overlength_fees_require_tariff? = false
27
27
  def pickup_number_is_tracking_number? = true
28
- def rates_with_excessive_length_fees? = false
29
28
  def required_credential_types = %i[api]
30
29
  def requirements = %i[credentials]
31
30
  def scac = 'FWDA'
@@ -189,6 +189,7 @@ module FreightKit
189
189
  trailer_closed: 'load trailer'
190
190
  }
191
191
  }.freeze
192
+ SEARCH_OPERATIONS = { BLNumber: :get_by_bl_number, PONumber: :get_by_po_number, ShipperNumber: :get_by_shipper_number }.freeze
192
193
 
193
194
  # Documents
194
195
 
@@ -278,7 +279,7 @@ module FreightKit
278
279
  request
279
280
  end
280
281
 
281
- def commit(action, request)
282
+ def commit(action, request, operation: API.dig(:actions, action))
282
283
  client_args = { wsdl: request_url(action), convert_request_keys_to: :none, env_namespace: :soap, element_form_default: :qualified }
283
284
 
284
285
  call_args = { message: request_blueprint.deep_merge(request) }
@@ -288,10 +289,24 @@ module FreightKit
288
289
  action:,
289
290
  client_args:,
290
291
  call_args:,
291
- soap_operation: API.dig(:actions, action)
292
+ soap_operation: operation
292
293
  ).call&.to_hash&.with_indifferent_access
293
294
  end
294
295
 
296
+ def parse_api_account_location(account)
297
+ return if account.blank?
298
+
299
+ address1 = account.values_at(:address1, :address2).compact_blank.map { |line| line.squish.titleize }.join(', ')
300
+
301
+ Location.new(
302
+ address1:,
303
+ city: account[:city]&.squish&.titleize,
304
+ country: ActiveUtils::Country.find('USA'),
305
+ postal_code: account[:zipcode]&.strip,
306
+ province: account[:state]&.strip&.upcase
307
+ )
308
+ end
309
+
295
310
  def parse_api_date_time(date_time, location)
296
311
  return if date_time.blank?
297
312
 
@@ -424,31 +439,8 @@ module FreightKit
424
439
  return tracking_response
425
440
  end
426
441
 
427
- address1 = [search_result.dig(:shipper, :address1), search_result.dig(:shipper, :address2)]
428
- .select(&:present?)
429
- .map { |line| line.squish.strip.titleize }
430
- .join(', ')
431
-
432
- shipper_location = Location.new(
433
- address1:,
434
- city: search_result.dig(:shipper, :city)&.squish&.titleize,
435
- province: search_result.dig(:shipper, :state)&.strip&.upcase,
436
- postal_code: search_result.dig(:shipper, :zipcode)&.strip,
437
- country: ActiveUtils::Country.find('USA')
438
- )
439
-
440
- address1 = [search_result.dig(:consignee, :address1), search_result.dig(:consignee, :address2)]
441
- .select(&:present?)
442
- .map { |line| line.squish.strip.titleize }
443
- .join(', ')
444
-
445
- receiver_location = Location.new(
446
- address1:,
447
- city: search_result.dig(:consignee, :city)&.squish&.titleize,
448
- province: search_result.dig(:consignee, :state)&.strip&.upcase,
449
- postal_code: search_result.dig(:consignee, :zipcode)&.strip,
450
- country: ActiveUtils::Country.find('USA')
451
- )
442
+ shipper_location = parse_api_account_location(search_result[:shipper])
443
+ receiver_location = parse_api_account_location(search_result[:consignee])
452
444
 
453
445
  api_date_time = search_result[:delivery_date_time_arrive]
454
446
  actual_delivery_date = parse_api_date_time(api_date_time, receiver_location)
@@ -507,6 +499,8 @@ module FreightKit
507
499
  tracking_response
508
500
  end
509
501
 
502
+ def postal_code(location) = location.postal_code.to_s.upcase.delete(' ').split('-').first
503
+
510
504
  def request_blueprint
511
505
  api_credentials = fetch_credential(:api)
512
506
 
@@ -525,6 +519,52 @@ module FreightKit
525
519
  scheme = API[:use_ssl] ? 'https://' : 'http://'
526
520
  "#{scheme}#{API[:domain]}#{API.dig(:endpoints, action)}"
527
521
  end
522
+
523
+ # Searches the reference as a BOL, PO and shipper number.
524
+ #
525
+ # @note The API needs both postal codes, and answers searches that find nothing with the `Code` `DNF`.
526
+ # @see Carrier#search_reference
527
+ def search_reference(reference, destination:, origin:, **)
528
+ return [] if destination&.postal_code.blank? || origin&.postal_code.blank?
529
+
530
+ postal_codes = { DestinationZipcode: postal_code(destination), OriginZipcode: postal_code(origin) }
531
+
532
+ SEARCH_OPERATIONS.filter_map do |field, operation|
533
+ request = { request: { field => reference, **postal_codes } }
534
+ save_request(request)
535
+ response = commit(:track, request, operation:)
536
+ raise response[:error] if response[:error].is_a?(Error)
537
+
538
+ result = response.dig(:"#{operation}_response", :"#{operation}_result")
539
+ next if result.blank? || result[:code] == 'DNF'
540
+
541
+ if result[:code].present?
542
+ message = result[:message].presence || result[:code]
543
+ raise InvalidCredentialsError, message if message.match?(/authenticat|password|user ?id/i)
544
+
545
+ raise ResponseError, message
546
+ end
547
+
548
+ next if result[:pro_number].to_i.zero?
549
+
550
+ references = {
551
+ bol_number: result[:bl_number],
552
+ order_number: result[:shipper_number],
553
+ other: result[:reference_number],
554
+ po_number: result[:po_number]
555
+ }
556
+
557
+ SearchResult.new(
558
+ delivered_on: result[:delivery_date_time].presence&.to_date,
559
+ destination: parse_api_account_location(result[:consignee]),
560
+ origin: parse_api_account_location(result[:shipper]),
561
+ picked_up_on: result[:pickup_date_time].presence&.to_date,
562
+ references: references.transform_values { |value| value unless value == 'NS' },
563
+ tracking_number: result[:pro_number].to_i.to_s,
564
+ weight: result[:shipping_weight].presence&.then { |value| Measured::Weight.new(value.to_d, :pounds) }
565
+ )
566
+ end
567
+ end
528
568
  end
529
569
  end
530
570
  end
@@ -156,11 +156,12 @@ module FreightKit
156
156
 
157
157
  API = {
158
158
  domain: 'www.sefl.com',
159
- endpoints: { rates: '/webconnect/ratequotes/rest/submitQuote' },
160
- methods: { get_rate: :get, rates: :post },
159
+ endpoints: { rates: '/webconnect/ratequotes/rest/submitQuote', search: '/webconnect/tracing' },
160
+ methods: { get_rate: :get, rates: :post, search: :get },
161
161
  use_ssl: false
162
162
  }.freeze
163
163
  JSON_HEADERS = { Accept: 'application/json', charset: 'utf-8', 'Content-Type' => 'application/x-www-form-urlencoded' }.freeze
164
+ SEARCH_TYPES = ['BL', 'PO'].freeze
164
165
 
165
166
  # Documents
166
167
 
@@ -314,6 +315,24 @@ module FreightKit
314
315
  end
315
316
  end
316
317
 
318
+ # @param element [Nokogiri::XML::Element, nil] A date, e.g. "05/04/2023".
319
+ # @return [Date, nil]
320
+ def parse_date(element) = element&.text.presence&.then { |value| ::Date.strptime(value, '%m/%d/%Y') }
321
+
322
+ def parse_location(element)
323
+ return if element.nil?
324
+
325
+ postal_code = element.at('zip')&.text.presence
326
+ country = postal_code.to_s.match?(/[a-z]/i) ? 'CA' : 'US'
327
+
328
+ Location.new(
329
+ city: element.at('city')&.text.presence&.titleize,
330
+ country: ActiveUtils::Country.find(country),
331
+ postal_code:,
332
+ province: element.at('state')&.text.presence
333
+ )
334
+ end
335
+
317
336
  def parse_rate_response(shipment:, response:, tries: 0)
318
337
  rate_response = RateResponse.new(request: last_request, response:)
319
338
 
@@ -436,6 +455,42 @@ module FreightKit
436
455
  end
437
456
 
438
457
  # Tracking
458
+
459
+ # Searches the reference as a BOL and PO, with the origin's postal code, or else the destination's.
460
+ #
461
+ # @note Without MySEFL credentials, results leave out references.
462
+ # @see Carrier#search_reference
463
+ def search_reference(reference, destination:, origin:, **)
464
+ postal_code = [origin, destination].filter_map { |location| location&.postal_code.presence }.first&.delete(' ')&.split('-')&.first
465
+ return [] if postal_code.nil?
466
+
467
+ credential = fetch_credential(:api)
468
+ query = { output: 'XML', Password: credential.password, RefNum1: reference, Username: credential.username, ZipCode: postal_code }
469
+
470
+ SEARCH_TYPES.flat_map do |type|
471
+ url = "#{build_url(:search)}?#{query.merge(Type: type).to_query}"
472
+ request = save_request(headers: { Accept: 'application/xml' }, method: :get, url:)
473
+ response = commit(request)
474
+ raise HTTPError.new(body: response.body, code: response.code) unless response.code == 200
475
+
476
+ Nokogiri::XML(response.body).xpath('//pro').filter_map do |pro|
477
+ tracking_number = pro.at('proNumber')&.text.presence
478
+ next if tracking_number.nil?
479
+
480
+ weight = pro.at('weight')&.text.presence
481
+
482
+ SearchResult.new(
483
+ delivered_on: parse_date(pro.at('deliveryDate')),
484
+ destination: parse_location(pro.at('consignee')),
485
+ origin: parse_location(pro.at('shipper')),
486
+ picked_up_on: parse_date(pro.at('pickupDate')),
487
+ references: { bol_number: pro.at('billOfLadingNumber')&.text, po_number: pro.at('purchaseOrderNumber')&.text },
488
+ tracking_number:,
489
+ weight: (Measured::Weight.new(weight.to_d, :pounds) if weight)
490
+ )
491
+ end
492
+ end
493
+ end
439
494
  end
440
495
  end
441
496
  end
@@ -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
 
@@ -152,8 +151,8 @@ module FreightKit
152
151
  when (96..143) then builder << 'XTRM8'
153
152
  when (144..191) then builder << 'XTRM12'
154
153
  when (192..239) then builder << 'XTRM16'
155
- when (240..311) then builder << 'XTRM20'
156
- when (312..) then builder << 'XTRM27'
154
+ when (240..323) then builder << 'XTRM20'
155
+ when (324..) then builder << 'XTRM27'
157
156
  end
158
157
  end
159
158
  end
@@ -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
@@ -227,6 +227,34 @@ module FreightKit
227
227
  submit(cookies, results, '__EVENTARGUMENT' => 'Select$0', '__EVENTTARGET' => 'ctl00$cphMain$grvInvoice')
228
228
  end
229
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
+
230
258
  def submit(cookies, page, fields)
231
259
  form = page.at('form')
232
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)
@@ -45,8 +45,8 @@ module FreightKit
45
45
  JSON_HEADERS = { Accept: 'application/json', 'Content-Type': 'application/json' }.freeze
46
46
  # The `ErrorInfo` of `FetchInvoiceListByPro` for shipments that are not invoiced yet
47
47
  NO_INVOICES_MESSAGE = /no corresponding invoices/i
48
- # The `SearchType` that looks shipments up by PRO
49
- PRO_SEARCH_TYPE = 1
48
+ # `SearchType`s, by the number that `SearchFor` holds
49
+ SEARCH_TYPES = { bol: 2, carrier_pro: 5, po: 3, pro: 1, sid: 4 }.freeze
50
50
  # Response keys that `String#underscore` misses
51
51
  UNDERSCORED_KEYS = {
52
52
  'BOLnumber' => :bol_number,
@@ -160,7 +160,7 @@ module FreightKit
160
160
  }
161
161
  end
162
162
 
163
- def build_tracking_request(tracking_number) = { search_for: tracking_number, search_type: PRO_SEARCH_TYPE }
163
+ def build_tracking_request(tracking_number) = { search_for: tracking_number, search_type: SEARCH_TYPES[:pro] }
164
164
 
165
165
  def camelize_keys(hash) = hash.deep_transform_keys { |key| CAMELIZED_KEYS[key] || key.to_s.camelize }
166
166
 
@@ -292,11 +292,6 @@ module FreightKit
292
292
  remainder_cents = total_cents - prices.sum(&:cents)
293
293
  prices << Price.new(blame: :api, cents: remainder_cents, description: prices.empty? ? 'Total' : 'Other') if remainder_cents.nonzero?
294
294
 
295
- if self.class.overlength_fees_require_tariff?
296
- overlength_cents = shipment.packages.sum { |package| overlength_fee(tariff, package) }
297
- prices << Price.new(blame: :tariff, cents: overlength_cents, description: 'Overlength fees') if overlength_cents.nonzero?
298
- end
299
-
300
295
  rate = Rate.new(
301
296
  carrier: self,
302
297
  carrier_name: name,
@@ -344,6 +339,34 @@ module FreightKit
344
339
  tracking_response
345
340
  end
346
341
 
342
+ # Searches the reference as each kind of number in `SEARCH_TYPES` but the PRO.
343
+ #
344
+ # @note The API answers searches that find nothing, and rejected logins, with an `ErrorMessage`.
345
+ # @see Carrier#search_reference
346
+ def search_reference(reference, **)
347
+ SEARCH_TYPES.except(:pro).values.filter_map do |search_type|
348
+ data = parse(commit(:track, { search_for: reference, search_type: }))
349
+ error = parse_error(data, key: :error_message)
350
+ raise InvalidCredentialsError, error.message if error&.message&.match?(/authenticat|logon|password/i)
351
+
352
+ info = data[:general_info].to_h if error.nil?
353
+ tracking_number = text(info.to_h[:pro_number])
354
+ next if tracking_number.nil?
355
+
356
+ delivered = data[:status_list].to_a.find { |status| text(status[:status_code])&.upcase == self.class::EVENTS[:delivered] }
357
+
358
+ SearchResult.new(
359
+ delivered_on: delivered&.then { |status| date(status[:status_date]) },
360
+ destination: location(data[:ship_to]),
361
+ origin: location(data[:ship_from]),
362
+ picked_up_on: date(info[:shipment_date]),
363
+ references: { bol_number: info[:bol_number], order_number: info[:sid_number], po_number: info[:po_number] },
364
+ tracking_number:,
365
+ weight: text(info[:total_weight])&.then { |value| Measured::Weight.new(value.delete('^0-9.').to_d, :pounds) }
366
+ )
367
+ end
368
+ end
369
+
347
370
  # Statuses have no location, so events take the origin or destination when they happen there
348
371
  def shipment_event(status, destination:, origin:)
349
372
  type_code = self.class::EVENTS.key(text(status[:status_code])&.upcase)
@@ -424,15 +424,6 @@ module FreightKit
424
424
  prices = [Price.new(blame: :api, cents: total_cents - prices.sum(&:cents), description: 'Freight')] + prices
425
425
  end
426
426
 
427
- if self.class.overlength_fees_require_tariff?
428
- shipment.packages.each do |package|
429
- cents = overlength_fee(tariff, package)
430
- next unless cents.positive?
431
-
432
- prices << Price.new(blame: :tariff, cents:, description: 'Overlength fee')
433
- end
434
- end
435
-
436
427
  transit_days = response.dig(:getquote_response, :return, :service, :days).to_i
437
428
 
438
429
  # Calculate real transit time based on information we have about the destination service days
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: freight_kit
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.34
4
+ version: 0.1.35
5
5
  platform: ruby
6
6
  authors:
7
7
  - Third Party Transportation Systems LLC
@@ -864,6 +864,7 @@ files:
864
864
  - lib/freight_kit/carriers/zentner_transportation.rb
865
865
  - lib/freight_kit/countries.rb
866
866
  - lib/freight_kit/error.rb
867
+ - lib/freight_kit/errors/ambiguous_shipment_error.rb
867
868
  - lib/freight_kit/errors/document_not_found_error.rb
868
869
  - lib/freight_kit/errors/expired_credentials_error.rb
869
870
  - lib/freight_kit/errors/http_error.rb
@@ -903,6 +904,8 @@ files:
903
904
  - lib/freight_kit/models/rate_response.rb
904
905
  - lib/freight_kit/models/region.rb
905
906
  - lib/freight_kit/models/response.rb
907
+ - lib/freight_kit/models/search_response.rb
908
+ - lib/freight_kit/models/search_result.rb
906
909
  - lib/freight_kit/models/shipment.rb
907
910
  - lib/freight_kit/models/shipment_event.rb
908
911
  - lib/freight_kit/models/terminal.rb