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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 751810555f9e684de775dbb7be33c9860435ee093a1c372407c39c17ec18bc5e
4
- data.tar.gz: '0548b0bfd294c843e140913a44319f81c9c63388a6fd53ab2ecd8ca75ec1bf85'
3
+ metadata.gz: e3f30776ea757f9ac1e4bc2ef09b77b22847ea9d05c643ba8296961a5ac3e168
4
+ data.tar.gz: f390249f8bdeff06663008ec49ec5dd0d27cc81d0f88b6b47984f0968cff4902
5
5
  SHA512:
6
- metadata.gz: 1e1aeb2e18f027ee2852fb7aaa3e16604ba62820fb0357ee1009251f96d8250e3940e186294d524aaae41a44d47d5ea34c58860c1709cab14b556a20d0185072
7
- data.tar.gz: 3ef028c43bf9bce202f2343c5df1495b39adf5470f91ee99231889abe24865b3a77ded67f2a7247341e7bd40f47ff1110259df162f03e52cad4ced67264183f3
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.32)
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.33
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.
@@ -71,6 +71,7 @@ module FreightKit
71
71
  'LA': { city: 'Los Angeles', province: 'CA', state: 'CA' },
72
72
  'MGUL': { city: 'Denver', province: 'CO', state: 'CO' },
73
73
  'PDX': { city: 'Portland', province: 'OR', state: 'OR' },
74
+ 'RED': { city: 'Redding', province: 'CA', state: 'CA' },
74
75
  'SAC': { city: 'Sacramento', province: 'CA', state: 'CA' },
75
76
  'SJ': { city: 'San Jose', province: 'CA', state: 'CA' },
76
77
  'SLC': { city: 'Salt Lake City', province: 'UT', state: 'UT' }
@@ -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'
@@ -59,7 +59,10 @@ module FreightKit
59
59
  EVENTS = Platforms::TheGreatInformationFactory::EVENTS.deep_merge(
60
60
  locations: {
61
61
  '45': { city: 'Fresno', province: 'CA', state: 'CA' },
62
- '85': { city: 'Vernon', province: 'CA', state: 'CA' }
62
+ '55': { city: 'Stockton', province: 'CA', state: 'CA' },
63
+ '75': { city: 'San Leandro', province: 'CA', state: 'CA' },
64
+ '85': { city: 'Vernon', province: 'CA', state: 'CA' },
65
+ '96': { city: 'Phoenix', province: 'AZ', state: 'AZ' }
63
66
  }
64
67
  ).freeze
65
68
 
@@ -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