freight_kit 0.1.27 → 0.1.29

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: 654499f996bc56f1f5de3bb76a35fa741620a112b07ae14f5bf9955cbb13905e
4
- data.tar.gz: 6e7362fcc10f25baec9aed2fddd314f2f4a96e6f315524fd49b9377c68894e5d
3
+ metadata.gz: bf3ea6e676c65d106c9054209d3dc987b68183fc02768ddaf17eefbae715d51e
4
+ data.tar.gz: e6a948691289653bf0d800b0cd7a16a7965d8be9024125f4b7816f730b08a8aa
5
5
  SHA512:
6
- metadata.gz: 26450318b8a6d9a3b107b781efe0d85ee5e18aed8ebde54161be1c9b5266a19902c886113f8a776b0f2d708a6bb6006ec2c6c39b35ab2df6ecb2019b175e5153
7
- data.tar.gz: e422938482548ea69ce4e8cb70428a981c7031497b3956f841507c3ec3f0150fa98499196da2d1618631afaa46e47a78afdfd1e5db3382ceb41b23b175b72a2d
6
+ metadata.gz: 7723ff1d4188bd6068d8f643e96cd5dab5d9fb0a09db727f69d881bb6e387c44658d9c543fbb6b74a2111e9ac9921dd32e28e02a1f1f54f75dc4b57a57bf5731
7
+ data.tar.gz: 62d7a36e391bf9274380af3ecb5c03bbc4909ecf603c07d21424bfc14f1d42fb9b2c15fb56dcafc25064019293d836591a55b8588d22b537a5f5d1aaaf47df2e
data/Gemfile.lock CHANGED
@@ -1,7 +1,7 @@
1
1
  PATH
2
2
  remote: .
3
3
  specs:
4
- freight_kit (0.1.25)
4
+ freight_kit (0.1.28)
5
5
  StreetAddress (~> 2.0)
6
6
  active_utils (>= 3.3.1, < 3.7.0)
7
7
  activemodel (>= 7.1, < 8.1.5)
data/MIT-LICENSE CHANGED
@@ -4,12 +4,8 @@ ActiveShipping.
4
4
  Portions of this project are © 2018 Sub Pop Records from project
5
5
  RectiveShipping.
6
6
 
7
- Portions of this project are © 2020 Brody Hoskins from project ReactiveFreight.
8
-
9
- Portions of this project are © 2021 Brody Hoskins from project HyperCarrier.
10
-
11
- Copyright for all later portions this project are held by Third Party Logistics
12
- Management Systems LLC.
7
+ Copyright for all later portions this project are held by FreightKit
8
+ contributors.
13
9
 
14
10
  Permission is hereby granted, free of charge, to any person obtaining
15
11
  a copy of this software and associated documentation files (the
data/README.md CHANGED
@@ -26,29 +26,31 @@ __Note:__ `Carrier`s may extend `Platform`s and override them when their behavio
26
26
  ## Supported Platforms
27
27
 
28
28
  * [Carrier Logistics](https://carrierlogistics.com)
29
+ * [RoadVision](https://www.roadvision.com)
29
30
  * [The Great Information Factory](https://www.tgifsoftware.com)
30
31
 
31
32
  ## Supported Carriers
32
33
 
33
- |Carrier |Scanned BOL|POD|Pickups|Rates|Tracking|
34
- |-----------------------------------|-----------|---|-------|-----|--------|
35
- |ABF Freight System | | | |✓ | |
36
- |Best Overnite Express |✓ |✓ |✓ |✓ |✓ |
37
- |Clear Lane Freight Systems | | | |✓ | |
38
- |DC Logistics |✓ |✓ |✓ |✓ |✓ |
39
- |The Custom Companies | | | |✓ |✓ |
40
- |Dependable Highway Express |✓ |✓ | |✓ |✓ |
41
- |Forward Air |✓ |✓ |✓ |✓ |✓ |
42
- |Frontline Freight |✓ |✓ | |✓ |✓ |
43
- |Numark Transportation |✓ |✓ |✓ |✓ |✓ |
44
- |OnTrac | | | |✓ | |
45
- |Peninsula Truck Lines | | | |✓ | |
46
- |Roadrunner Transportation Services |✓ |✓ | |✓ |✓ |
47
- |Saia | | |✓ |✓ |✓ |
48
- |Southeastern Freight Lines | | | |✓ | |
49
- |Tforce Worldwide |✓ |✓ |✓ |✓ | |
50
- |Total Transportation & Distribution|✓ |✓ | |✓ |✓ |
51
- |Western Regional Delivery Service | |✓ | | |✓ |
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 | |✓ | | | |✓ |
52
54
 
53
55
  ## Installation
54
56
 
@@ -146,6 +148,10 @@ carrier.bol(tracking_number) # BOL generated by carrier
146
148
  carrier.scanned_bol(tracking_number) # BOL scanned by carrier
147
149
 
148
150
  carrier.pod(tracking_number)
151
+
152
+ invoice = carrier.invoice(tracking_number) # amounts and lines, plus the document
153
+ invoice.balance_cents
154
+ invoice.data
149
155
  ```
150
156
 
151
157
  ### Tracking
data/VERSION CHANGED
@@ -1 +1 @@
1
- 0.1.27
1
+ 0.1.29
@@ -433,6 +433,12 @@ module FreightKit
433
433
  raise NotImplementedError, "#{name}: #find_tracking_number_from_pickup_number not supported"
434
434
  end
435
435
 
436
+ # Asks the carrier for the shipment's invoice: its amounts and lines, and its document.
437
+ #
438
+ # @param [String] tracking_number Tracking number.
439
+ # @return [InvoiceResponse]
440
+ def invoice(tracking_number) = raise NotImplementedError, "#{name}: #invoice not supported"
441
+
436
442
  # Asks the carrier for the scanned proof of delivery that the carrier would provide after delivery.
437
443
  #
438
444
  # @param [String] tracking_number Tracking number.
@@ -69,6 +69,7 @@ module FreightKit
69
69
  'FRES': { city: 'Fresno', province: 'CA', state: 'CA' },
70
70
  'KENT': { city: 'Kent', province: 'WA', state: 'WA' },
71
71
  'LA': { city: 'Los Angeles', province: 'CA', state: 'CA' },
72
+ 'MGUL': { city: 'Denver', province: 'CO', state: 'CO' },
72
73
  'PDX': { city: 'Portland', province: 'OR', state: 'OR' },
73
74
  'SAC': { city: 'Sacramento', province: 'CA', state: 'CA' },
74
75
  'SJ': { city: 'San Jose', province: 'CA', state: 'CA' },
@@ -56,6 +56,12 @@ module FreightKit
56
56
  },
57
57
  ports: { rates: 10_010, track: 10_010 }
58
58
  ).freeze
59
+ EVENTS = Platforms::TheGreatInformationFactory::EVENTS.deep_merge(
60
+ locations: {
61
+ '45': { city: 'Fresno', province: 'CA', state: 'CA' },
62
+ '85': { city: 'Vernon', province: 'CA', state: 'CA' }
63
+ }
64
+ ).freeze
59
65
 
60
66
  def build_calculated_accessorials(packages)
61
67
  longest_dimension = packages.map { |package| [package.length(:in), package.width(:in)].max }.max.ceil
@@ -1,6 +1,6 @@
1
1
  module FreightKit
2
2
  module Carriers
3
- class RELogistics < Carrier
3
+ class RELogistics < Platforms::RoadVision
4
4
  class << self
5
5
  def check_mailing_addresses
6
6
  [
@@ -16,7 +16,11 @@ module FreightKit
16
16
  end
17
17
 
18
18
  def id = '65f1b231-59fa-4432-af2e-e5398b01bac6'
19
+ def legal_name = 'RE Logistics Corp'
19
20
  def name = 'RE Logistics'
21
+ def scac = 'RELM'
22
+ def us_dot_number = 3_236_760
23
+ def us_mc_number = 1_015_860
20
24
  end
21
25
  end
22
26
  end
@@ -1,6 +1,7 @@
1
1
  module FreightKit
2
2
  # Represents the response to calls:
3
3
  # - {FreightKit::Carrier#bol}
4
+ # - {FreightKit::Carrier#invoice}, as an {InvoiceResponse}
4
5
  # - {FreightKit::Carrier#pod}
5
6
  # - {FreightKit::Carrier#scanned_bol}
6
7
  #
@@ -0,0 +1,45 @@
1
+ module FreightKit
2
+ # A shipment billed on an invoice (see {InvoiceResponse#lines}).
3
+ #
4
+ # @attribute balance_cents
5
+ # @return [Integer] What remains to be paid for the shipment.
6
+ #
7
+ # @attribute bol_number
8
+ # @return [String]
9
+ #
10
+ # @attribute delivered_on
11
+ # @return [Date]
12
+ #
13
+ # @attribute destination
14
+ # @return [FreightKit::Location]
15
+ #
16
+ # @attribute order_number
17
+ # @return [String]
18
+ #
19
+ # @attribute origin
20
+ # @return [FreightKit::Location]
21
+ #
22
+ # @attribute picked_up_on
23
+ # @return [Date]
24
+ #
25
+ # @attribute po_number
26
+ # @return [String]
27
+ #
28
+ # @attribute total_cents
29
+ # @return [Integer] What the invoice originally billed for the shipment.
30
+ #
31
+ # @attribute tracking_number
32
+ # @return [String]
33
+ class InvoiceLine < Model
34
+ attr_accessor :balance_cents,
35
+ :bol_number,
36
+ :delivered_on,
37
+ :destination,
38
+ :order_number,
39
+ :origin,
40
+ :picked_up_on,
41
+ :po_number,
42
+ :total_cents,
43
+ :tracking_number
44
+ end
45
+ end
@@ -0,0 +1,24 @@
1
+ module FreightKit
2
+ # Represents the response to a {FreightKit::Carrier#invoice} call: what the invoice bills, and its document.
3
+ #
4
+ # @attribute balance_cents
5
+ # @return [Integer] What remains to be paid.
6
+ #
7
+ # @attribute currency
8
+ # @return [String] ISO 4217 code of the amounts.
9
+ #
10
+ # @attribute issued_on
11
+ # @return [Date]
12
+ #
13
+ # @attribute lines
14
+ # @return [Array<FreightKit::InvoiceLine>] The shipments billed.
15
+ #
16
+ # @attribute number
17
+ # @return [String] Invoice number.
18
+ #
19
+ # @attribute total_cents
20
+ # @return [Integer] What the invoice originally billed.
21
+ class InvoiceResponse < DocumentResponse
22
+ attr_accessor :balance_cents, :currency, :issued_on, :lines, :number, :total_cents
23
+ end
24
+ end
@@ -4,6 +4,7 @@ module FreightKit
4
4
  # @!attribute accessorials [Hash<Symbol>] Acceessorials requested.
5
5
  # @!attribute declared_value_cents [Integer] Declared value in cents.
6
6
  # @!attribute destination [FreightKit::Location] Where the package will go.
7
+ # @!attribute estimate_reference [String] Quote number from {Rate#estimate_reference}, which books the quoted price.
7
8
  # @!attribute origin [FreightKit::Location] Where the shipment will originate from.
8
9
  # @!attribute order_number [String] Order number (also known as shipper number, SO #).
9
10
  # @!attribute packages [Array<FreightKit::Package>] The list of packages that will
@@ -11,7 +12,15 @@ module FreightKit
11
12
  # @!attribute po_number [String] Purchase order number (also known as PO #).
12
13
  # @!attribute pickup_at [FreightKit::DateTime] Pickup date/time.
13
14
  class Shipment < Model
14
- attr_accessor :accessorials, :declared_value_cents, :destination, :origin, :order_number, :packages, :po_number, :pro
15
+ attr_accessor :accessorials,
16
+ :declared_value_cents,
17
+ :destination,
18
+ :estimate_reference,
19
+ :order_number,
20
+ :origin,
21
+ :packages,
22
+ :po_number,
23
+ :pro
15
24
  attr_reader :pickup_at
16
25
 
17
26
  def hazmat?
@@ -365,7 +365,7 @@ module FreightKit
365
365
  end
366
366
 
367
367
  location ||= case event
368
- when :delivered then destination
368
+ when :delivered, :out_for_delivery then destination
369
369
  when :departed then last_location
370
370
  when :picked_up, :pickup_scheduled then origin
371
371
  end
@@ -163,8 +163,8 @@ module FreightKit
163
163
  # Downloads the invoice that the API key's customer received. {ORM::Invoice} lists them.
164
164
  #
165
165
  # @param tracking_number [String] The load ID, or the carrier's PRO.
166
- # @return [DocumentResponse] With a {DocumentNotFoundError} when the shipment is not invoiced yet.
167
- def invoice(tracking_number) = document(tracking_number, :INVOICE)
166
+ # @return [InvoiceResponse] With only the document, and a {DocumentNotFoundError} when the shipment is not invoiced yet.
167
+ def invoice(tracking_number) = document(tracking_number, :INVOICE, InvoiceResponse)
168
168
 
169
169
  # Runs a {GraphQLClient::Mutation} as the API key's user, never from {FreightKit.cache}.
170
170
  #
@@ -276,9 +276,9 @@ module FreightKit
276
276
  DateTime.new(date_time_with_zone: value.in_time_zone(address&.time_zone_name || 'UTC'))
277
277
  end
278
278
 
279
- def document(tracking_number, kind)
279
+ def document(tracking_number, kind, response_class = DocumentResponse)
280
280
  data = find_shipment_data(tracking_number, :shipment_documents)
281
- document_response = DocumentResponse.new(request: last_request, response: data)
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
 
284
284
  document = data[:documents].find { |item| item[:kind] == kind.to_s }
@@ -0,0 +1,389 @@
1
+ module FreightKit
2
+ module Platforms
3
+ # Carriers that run RoadVision, which serves the same JSON API for each of them. Subclasses on another domain override
4
+ # `API[:domain]`. Requests send the carrier's logon code and password: in the query of GETs, and in the body of POSTs.
5
+ #
6
+ # Keys are camelized in {#commit} and underscored in {#parse}, so everything else uses snake_case symbols.
7
+ class RoadVision < Platform
8
+ class << self
9
+ def required_credential_types = %i[api]
10
+
11
+ def requirements
12
+ return %i[credentials tariff] if overlength_fees_require_tariff?
13
+
14
+ %i[credentials]
15
+ end
16
+
17
+ def services = %i[standard]
18
+ end
19
+
20
+ include FreightKit::Pickupable
21
+ include FreightKit::Rateable
22
+ include FreightKit::Trackable
23
+
24
+ API = {
25
+ domain: 'relmapi.roadvision.com',
26
+ endpoints: {
27
+ bol: '/api/FetchBOL',
28
+ invoice: '/api/FetchInvoiceData',
29
+ invoice_pdf: '/api/FetchInvPDF',
30
+ invoices: '/api/FetchInvoiceListByPro',
31
+ pickup: '/api/SubmitPickupRequest',
32
+ pod: '/api/FetchPOD',
33
+ rates: '/api/FetchQuoteRequest',
34
+ track: '/api/GetShipmentStatus',
35
+ transit_time: '/api/TransitTime'
36
+ },
37
+ methods: { pickup: :post, rates: :post },
38
+ # Seconds. Invoices that bill many shipments take longer than {HTTPClient::TIMEOUTS} allows.
39
+ read_timeouts: { invoice: 120, invoice_pdf: 120 }
40
+ }.freeze
41
+ # Request keys that `String#camelize` misses
42
+ CAMELIZED_KEYS = { bol: 'BOL', cod_amount_in_cents: 'CODAmountInCents', ponum: 'PONUM', ppd_or_col: 'PPDorCOL', sid: 'SID' }.freeze
43
+ # {ShipmentEvent#type_code} => EDI X12 214 status code
44
+ EVENTS = { arrived_at_terminal: 'X4', delivered: 'D1', departed: 'P1', out_for_delivery: 'X6', picked_up: 'AF' }.freeze
45
+ JSON_HEADERS = { Accept: 'application/json', 'Content-Type': 'application/json' }.freeze
46
+ # The `ErrorInfo` of `FetchInvoiceListByPro` for shipments that are not invoiced yet
47
+ NO_INVOICES_MESSAGE = /no corresponding invoices/i
48
+ # The `SearchType` that looks shipments up by PRO
49
+ PRO_SEARCH_TYPE = 1
50
+ # Response keys that `String#underscore` misses
51
+ UNDERSCORED_KEYS = {
52
+ 'BOLnumber' => :bol_number,
53
+ 'POnumber' => :po_number,
54
+ 'SIDnumber' => :sid_number,
55
+ **CAMELIZED_KEYS.invert
56
+ }.freeze
57
+
58
+ # Fetches the shipment's latest invoice, with its PDF.
59
+ #
60
+ # @param tracking_number [String] The PRO.
61
+ # @return [InvoiceResponse] With a {DocumentNotFoundError} when the shipment is not invoiced yet, or the invoice has
62
+ # no PDF. The amounts and lines are set in the second case.
63
+ def invoice(tracking_number)
64
+ list = parse(commit(:invoices, { pro_number: tracking_number }))
65
+ error = parse_error(list)
66
+ error = DocumentNotFoundError.new(error.message) if error&.message&.match?(NO_INVOICES_MESSAGE)
67
+ invoice_response = InvoiceResponse.new(error:, request: last_request, response: list)
68
+ return invoice_response if invoice_response.error
69
+
70
+ number = list[:invoice_pick_list].to_a.filter_map { |item| text(item[:invoice_number]) }.max_by(&:to_i)
71
+ return invoice_response.tap { |response| response.error = DocumentNotFoundError.new } if number.nil?
72
+
73
+ data = parse(commit(:invoice, { invoice_number: number }))
74
+ invoice_response = InvoiceResponse.new(error: parse_error(data), request: last_request, response: data)
75
+ return invoice_response if invoice_response.error
76
+
77
+ pdf = document(:invoice_pdf, { doc_number: number })
78
+
79
+ invoice_response.tap do |response|
80
+ response.assign_attributes(
81
+ balance_cents: cents(data[:invoice_balance]),
82
+ content_type: pdf.content_type,
83
+ currency: 'USD',
84
+ data: pdf.data,
85
+ error: pdf.error,
86
+ issued_on: date(data[:invoice_date]),
87
+ lines: data[:invoice_details].to_a.map { |detail| invoice_line(detail) },
88
+ number: text(data[:invoice_number]) || number,
89
+ total_cents: cents(data[:invoice_amount])
90
+ )
91
+ end
92
+ end
93
+
94
+ # @param tracking_number [String] The PRO.
95
+ # @return [DocumentResponse] With a {DocumentNotFoundError} when the shipment has none yet.
96
+ def pod(tracking_number) = document(:pod, build_tracking_request(tracking_number))
97
+
98
+ # @param tracking_number [String] The PRO.
99
+ # @return [DocumentResponse] With a {DocumentNotFoundError} when the shipment has none yet.
100
+ def scanned_bol(tracking_number) = document(:bol, build_tracking_request(tracking_number))
101
+
102
+ protected
103
+
104
+ # Raises {UnserviceableAccessorialsError} rather than quote without accessorials that the carrier does not map
105
+ def build_accessorials(shipment)
106
+ accessorials = shipment.accessorials.to_a
107
+ return [] if accessorials.empty?
108
+ raise UnserviceableAccessorialsError.new(accessorials:) unless serviceable_accessorials?(accessorials)
109
+
110
+ codes = accessorials.flat_map { |accessorial| Array(mappable_accessorials[accessorial]) }
111
+ codes.uniq.map { |code| { accessorial_code: code } }
112
+ end
113
+
114
+ def build_freight_list(shipment)
115
+ shipment.packages.map do |package|
116
+ {
117
+ freight_class: package.freight_class.to_s,
118
+ freight_description: package.description,
119
+ height: package.height(:in).ceil,
120
+ length: package.length(:in).ceil,
121
+ pallet_count: package.packaging.pallet? ? package.quantity : 0,
122
+ piece_count: package.quantity,
123
+ weight: package.pounds(:total).ceil,
124
+ width: package.width(:in).ceil
125
+ }.compact
126
+ end
127
+ end
128
+
129
+ # The API keeps only the local wall-clock time of the pickup hours. The quote number books the quoted price.
130
+ def build_pickup_request(pickup_from:, pickup_to:, shipment:, **)
131
+ {
132
+ accessorial_list: build_accessorials(shipment),
133
+ closing_time: pickup_to&.strftime('%H:%M'),
134
+ cod_amount_in_cents: 0,
135
+ freight_list: build_freight_list(shipment),
136
+ pickup_date: pickup_from.strftime('%m/%d/%Y'),
137
+ ponum: shipment.po_number,
138
+ ppd_or_col: 'PPD',
139
+ quote_num: shipment.estimate_reference.presence&.to_i,
140
+ ready_by_time: pickup_from.strftime('%H:%M'),
141
+ sid: shipment.order_number
142
+ }.merge(stop(:consignee, shipment.destination), stop(:shipper, shipment.origin)).compact
143
+ end
144
+
145
+ def build_rate_request(shipment:)
146
+ destination = shipment.destination
147
+ origin = shipment.origin
148
+
149
+ {
150
+ accessorial_list: build_accessorials(shipment),
151
+ cod_amount_in_cents: 0,
152
+ freight_list: build_freight_list(shipment),
153
+ inbound: 'N',
154
+ ppd_or_col: 'PPD',
155
+ ship_from_city: origin.city,
156
+ ship_from_state: origin.province,
157
+ ship_from_zip: zip(origin),
158
+ ship_to_city: destination.city,
159
+ ship_to_state: destination.province,
160
+ ship_to_zip: zip(destination)
161
+ }
162
+ end
163
+
164
+ def build_tracking_request(tracking_number) = { search_for: tracking_number, search_type: PRO_SEARCH_TYPE }
165
+
166
+ def camelize_keys(hash) = hash.deep_transform_keys { |key| CAMELIZED_KEYS[key] || key.to_s.camelize }
167
+
168
+ # Amounts are strings or numbers in dollars
169
+ def cents(amount) = (amount.to_s.delete('^0-9.-').to_d * 100).round.to_i
170
+
171
+ def commit(action, params)
172
+ api = self.class::API
173
+ credential = fetch_credential(:api)
174
+ url = "https://#{api[:domain]}#{api.dig(:endpoints, action)}"
175
+
176
+ request = if api.dig(:methods, action) == :post
177
+ body = camelize_keys({ logon: credential.username, pass: credential.password }.merge(params)).to_json
178
+ { body:, headers: JSON_HEADERS, method: :post, url: }
179
+ else
180
+ query = camelize_keys({ pass: credential.password, user: credential.username }.merge(params))
181
+ { headers: JSON_HEADERS.slice(:Accept), method: :get, query:, url: }
182
+ end
183
+
184
+ save_request(request)
185
+ read_timeout = api.dig(:read_timeouts, action)
186
+ response = HTTPClient.request(request[:method], url, **request.slice(:body, :headers, :query), proxy_url:, read_timeout:)
187
+ raise HTTPError.new(body: response.body, code: response.code) unless response.code == 200
188
+
189
+ response
190
+ end
191
+
192
+ # Dates are `MM/DD/YYYY`
193
+ def date(value)
194
+ value = text(value)
195
+ return if value.nil?
196
+
197
+ value.match?(/\A\d{4}-/) ? ::Date.iso8601(value.first(10)) : ::Date.strptime(value.split.first.tr('-', '/'), '%m/%d/%Y')
198
+ rescue ::Date::Error
199
+ nil
200
+ end
201
+
202
+ # Times are `HH:MM`, on a 24-hour clock, and `00:00` when the status has none
203
+ def date_time(status, location)
204
+ local_date = date(status[:status_date])
205
+ return if local_date.nil?
206
+
207
+ time = text(status[:status_time])
208
+ return DateTime.new(local_date:, location:) unless time&.match?(/\A\d{1,2}:\d{2}\z/) && time.delete(':').to_i.positive?
209
+
210
+ DateTime.new(local_date_time: "#{local_date.iso8601} #{time.rjust(5, '0')}:00", location:)
211
+ end
212
+
213
+ # The API returns documents as PDFs, and anything else when they are missing
214
+ def document(action, params)
215
+ response = commit(action, params)
216
+ document_response = DocumentResponse.new(request: last_request)
217
+ return document_response.tap { |item| item.error = DocumentNotFoundError.new } unless response.body.start_with?('%PDF')
218
+
219
+ document_response.tap { |item| item.assign_attributes(content_type: 'application/pdf', data: response.body) }
220
+ end
221
+
222
+ def invoice_line(detail)
223
+ InvoiceLine.new(
224
+ balance_cents: cents(detail[:balance_due]),
225
+ bol_number: text(detail[:bol]),
226
+ delivered_on: date(detail[:delivery_date]),
227
+ destination: location(detail.transform_keys { |key| key.to_s.delete_prefix('consignee_').to_sym }),
228
+ order_number: text(detail[:sid]),
229
+ origin: location(detail.transform_keys { |key| key.to_s.delete_prefix('shipper_').to_sym }),
230
+ picked_up_on: date(detail[:pickup_date]),
231
+ po_number: text(detail[:po_number]),
232
+ total_cents: cents(detail[:original_charges]),
233
+ tracking_number: text(detail[:pro_number])
234
+ )
235
+ end
236
+
237
+ # Canadian postal codes have letters
238
+ def location(fields)
239
+ return if fields.blank? || fields.values_at(:city, :state, :zip).none? { |value| text(value) }
240
+
241
+ name = text(fields[:name])
242
+ postal_code = text(fields[:zip])
243
+
244
+ Location.new(
245
+ address1: text(fields[:address1]),
246
+ address2: text(fields[:address2]),
247
+ address3: text(fields[:address3]),
248
+ city: text(fields[:city])&.titleize,
249
+ contact: (Contact.new(company_name: name) if name),
250
+ country: ActiveUtils::Country.find(postal_code.to_s.match?(/[a-z]/i) ? 'CA' : 'US'),
251
+ postal_code:,
252
+ province: text(fields[:state])&.upcase
253
+ )
254
+ end
255
+
256
+ # @return [Hash, Object] The parsed JSON response, with snake_case symbol keys.
257
+ def parse(response)
258
+ data = response.parsed_response
259
+ data.is_a?(Hash) ? data.deep_transform_keys { |key| UNDERSCORED_KEYS[key] || key.to_s.underscore.to_sym } : data
260
+ end
261
+
262
+ # Every response has an error message field, which is blank on success
263
+ def parse_error(data, key: :error_info)
264
+ return ResponseError.new("Unexpected response: #{data.to_s.truncate(200)}") unless data.is_a?(Hash)
265
+
266
+ text(data[key])&.then { |message| ResponseError.new(message) }
267
+ end
268
+
269
+ def parse_pickup_response(response)
270
+ data = parse(response)
271
+ pickup_response = PickupResponse.new(error: parse_error(data), request: last_request, response: data)
272
+ return pickup_response if pickup_response.error
273
+
274
+ pickup_number = data[:pickup_number].to_i
275
+ return pickup_response.tap { |item| item.error = ResponseError.new('Pickup number is blank') } unless pickup_number.positive?
276
+
277
+ pickup_response.tap { |item| item.pickup_number = pickup_number.to_s }
278
+ end
279
+
280
+ # Prices are the quote's line items, plus whatever they leave of its total
281
+ def parse_rate_response(shipment:, response:)
282
+ data = parse(response)
283
+ rate_response = RateResponse.new(error: parse_error(data), request: last_request, response: data)
284
+ return rate_response if rate_response.error
285
+
286
+ total_cents = cents(data[:total])
287
+ return rate_response.tap { |item| item.error = ResponseError.new('Total is blank') } unless total_cents.positive?
288
+
289
+ prices = data[:quote_details].to_a.map do |line|
290
+ Price.new(blame: :api, cents: cents(line[:amount]), description: text(line[:description]))
291
+ end
292
+
293
+ remainder_cents = total_cents - prices.sum(&:cents)
294
+ prices << Price.new(blame: :api, cents: remainder_cents, description: prices.empty? ? 'Total' : 'Other') if remainder_cents.nonzero?
295
+
296
+ if self.class.overlength_fees_require_tariff?
297
+ overlength_cents = shipment.packages.sum { |package| overlength_fee(tariff, package) }
298
+ prices << Price.new(blame: :tariff, cents: overlength_cents, description: 'Overlength fees') if overlength_cents.nonzero?
299
+ end
300
+
301
+ rate = Rate.new(
302
+ carrier: self,
303
+ carrier_name: name,
304
+ currency: 'USD',
305
+ estimate_reference: data[:quote_number].presence&.to_s,
306
+ prices:,
307
+ scac:,
308
+ service_name: :standard,
309
+ shipment:,
310
+ transit_days: transit_days(shipment),
311
+ with_excessive_length_fees: rates_with_excessive_length_fees?
312
+ )
313
+
314
+ rate_response.tap { |item| item.rates = [rate] }
315
+ end
316
+
317
+ def parse_tracking_response(tracking_number, response:)
318
+ data = parse(response)
319
+ tracking_response = TrackingResponse.new(carrier: self, carrier_name: name, request: last_request, response: data, tracking_number:)
320
+ tracking_response.error = parse_error(data, key: :error_message)
321
+ return tracking_response if tracking_response.error
322
+
323
+ info = data[:general_info].to_h
324
+ return tracking_response.tap { |item| item.error = ShipmentNotFoundError.new } if text(info[:pro_number]).nil?
325
+
326
+ destination = location(data[:ship_to])
327
+ origin = location(data[:ship_from])
328
+ statuses = data[:status_list].to_a
329
+ shipment_events = statuses.filter_map { |status| shipment_event(status, destination:, origin:) }
330
+
331
+ tracking_response.assign_attributes(
332
+ actual_delivery_date: shipment_events.find { |event| event.type_code == :delivered }&.date_time,
333
+ delivery_signature: text(info[:who_signed]),
334
+ destination:,
335
+ origin:,
336
+ ship_time: date(info[:shipment_date])&.then { |local_date| DateTime.new(local_date:, location: origin) },
337
+ shipment_events:,
338
+ shipper_address: origin,
339
+ status: shipment_events.last&.type_code,
340
+ status_code: text(statuses.last.to_h[:status_code]),
341
+ status_description: text(statuses.last.to_h[:status_definition]),
342
+ tracking_number: text(info[:pro_number])
343
+ )
344
+
345
+ tracking_response
346
+ end
347
+
348
+ # Statuses have no location, so events take the origin or destination when they happen there
349
+ def shipment_event(status, destination:, origin:)
350
+ type_code = self.class::EVENTS.key(text(status[:status_code])&.upcase)
351
+ return if type_code.nil?
352
+
353
+ location = type_code == :picked_up ? origin : (destination if %i[delivered out_for_delivery].include?(type_code))
354
+
355
+ ShipmentEvent.new(date_time: date_time(status, location), location:, type_code:)
356
+ end
357
+
358
+ # A pickup request's fields for the shipper or consignee, which the API limits to 30 characters
359
+ def stop(role, location)
360
+ contact = location.contact
361
+ fields = {
362
+ address: location.address1,
363
+ city: location.city,
364
+ contact: contact&.name,
365
+ name: contact&.company_name || contact&.name,
366
+ phone: contact&.phone,
367
+ state: location.province,
368
+ zip: zip(location)
369
+ }
370
+
371
+ fields.to_h { |key, value| [:"#{role}_#{key}", value&.to_s&.first(30)] }
372
+ end
373
+
374
+ def text(value) = value.to_s.squish.presence
375
+
376
+ # A transit time lookup that fails leaves the rate without transit days, rather than without the rate
377
+ def transit_days(shipment)
378
+ data = parse(commit(:transit_time, { destination_zip: zip(shipment.destination), origin_zip: zip(shipment.origin) }))
379
+
380
+ text(data[:transit_days])&.to_i if parse_error(data).nil?
381
+ rescue Error, HTTPX::Error, SystemCallError
382
+ nil
383
+ end
384
+
385
+ # 5-digit US ZIP codes, and Canadian postal codes without spaces
386
+ def zip(location) = location.postal_code.to_s.delete(' ').split('-').first
387
+ end
388
+ end
389
+ end
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.27
4
+ version: 0.1.29
5
5
  platform: ruby
6
6
  authors:
7
7
  - Third Party Transportation Systems LLC
@@ -878,6 +878,8 @@ files:
878
878
  - lib/freight_kit/models/credential.rb
879
879
  - lib/freight_kit/models/date_time.rb
880
880
  - lib/freight_kit/models/document_response.rb
881
+ - lib/freight_kit/models/invoice_line.rb
882
+ - lib/freight_kit/models/invoice_response.rb
881
883
  - lib/freight_kit/models/label.rb
882
884
  - lib/freight_kit/models/lane.rb
883
885
  - lib/freight_kit/models/location.rb
@@ -926,6 +928,7 @@ files:
926
928
  - lib/freight_kit/platforms/next_tms/orm/invoice.rb
927
929
  - lib/freight_kit/platforms/next_tms/orm/record_not_found_error.rb
928
930
  - lib/freight_kit/platforms/next_tms/orm/shipment.rb
931
+ - lib/freight_kit/platforms/road_vision.rb
929
932
  - lib/freight_kit/platforms/the_great_information_factory.rb
930
933
  - lib/freight_kit/regions.rb
931
934
  - lib/freight_kit/shipment_packer.rb