Class: FreightKit::CarrierLogistics

Inherits:
Platform show all
Includes:
Rateable, Trackable
Defined in:
lib/freight_kit/platforms/carrier_logistics.rb

Direct Known Subclasses

CTBV, DCHA, DLDS, FCSY, TOTL

Constant Summary collapse

REACTIVE_FREIGHT_PLATFORM =
true
EXPIRED_CREDENTIALS_MESSAGES =
[
  'Your password has expired',
].freeze
INVALID_CREDENTIALS_MESSAGES =
[
  'Unable to log in',
  'Your Username or Password is Incorrect',
].freeze

Constants inherited from Carrier

FreightKit::Carrier::BOL_NUMBER_TRACKING_URL_TEMPLATE, FreightKit::Carrier::NUMBERS, FreightKit::Carrier::ORDER_NUMBER_TRACKING_URL_TEMPLATE, FreightKit::Carrier::PICKUP_NUMBER_TRACKING_URL_TEMPLATE, FreightKit::Carrier::PO_NUMBER_TRACKING_URL_TEMPLATE, FreightKit::Carrier::TRACKING_NUMBER_TRACKING_URL_TEMPLATE, FreightKit::Carrier::VALID_BOL_NUMBER_REGEX, FreightKit::Carrier::VALID_ORDER_NUMBER_REGEX, FreightKit::Carrier::VALID_PICKUP_NUMBER_REGEX, FreightKit::Carrier::VALID_PO_NUMBER_REGEX, FreightKit::Carrier::VALID_TRACKING_NUMBER_REGEX

Instance Attribute Summary

Attributes inherited from Carrier

#conf, #credentials, #customer_location, #last_request, #rates_with_excessive_length_fees, #tariff, #tmpdir

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Rateable

#find_rates

Methods included from Trackable

#find_tracking_info

Methods inherited from Platform

#initialize

Methods inherited from Carrier

#available_services, #bol, bol_requires_tracking_number?, #cancel_shipment, #create_pickup, default_location, #fetch_credential, #find_estimate, #find_locations, #find_rates, find_rates_with_declared_value?, #find_tracking_info, #find_tracking_number_from_pickup_number, implemented?, #initialize, maximum_address_field_length, maximum_height, maximum_weight, minimum_length_for_overlength_fees, #overlength_fee, overlength_fees_require_tariff?, pickup_number_is_tracking_number?, #serviceable_accessorials?, tracking_url_template, #valid_credentials?, valid_number_regex, #valid_tracking_number?, #validate_packages

Constructor Details

This class inherits a constructor from FreightKit::Platform

Class Method Details

.required_credential_typesObject



6
7
8
# File 'lib/freight_kit/platforms/carrier_logistics.rb', line 6

def required_credential_types
  %i[api]
end

.requirementsObject



10
11
12
13
14
# File 'lib/freight_kit/platforms/carrier_logistics.rb', line 10

def requirements
  return %i[credentials tariff] if overlength_fees_require_tariff?

  %i[credentials]
end

Instance Method Details

#build_calculated_accessorials(shipment) ⇒ Object

Rates



289
290
291
# File 'lib/freight_kit/platforms/carrier_logistics.rb', line 289

def build_calculated_accessorials(shipment)
  []
end

#build_rate_request(shipment:) ⇒ Object



318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
# File 'lib/freight_kit/platforms/carrier_logistics.rb', line 318

def build_rate_request(shipment:)
  api_credentials = fetch_credential(:api)

  query = {
            xmlv: 'yes', # must be first
            quotenumber: 'YES',
            vdzip: shipment.destination.postal_code,
            vozip: shipment.origin.postal_code,
            xmlpass: api_credentials.password,
            xmluser: api_credentials.username
          }

  i = 0
  shipment.packages.each do |package|
    i += 1 # API starts at 1 (not 0)

    query["vclass[#{i}]"] = package.freight_class
    query["wheight[#{i}]"] = package.height(:in).ceil
    query["wlength[#{i}]"] = package.length(:in).ceil
    query["wpallets[#{i}]"] = package.quantity
    query["wpieces[#{i}]"] = package.quantity
    query["wweight[#{i}]"] = package.pounds(:total).ceil
    query["wwidth[#{i}]"] = package.width(:in).ceil
  end

  accessorials = []

  if shipment.accessorials.present?
    serviceable_accessorials?(shipment.accessorials)

    shipment
    .accessorials
    .reject { |accessorial| conf.dig(:accessorials, :unquotable).include?(accessorial) }
    .each do |shipment_accessorial|
      conf_accessorial = conf.dig(:accessorials, :mappable, shipment_accessorial)

      case conf_accessorial
      when Array then accessorials += conf_accessorial
      when String then accessorials << conf_accessorial
      end
    end
  end

  accessorials += build_calculated_accessorials(shipment)

  accessorials.uniq.compact.each { |accessorial| query[accessorial] = 'Yes' } if accessorials.any?

  query
end

#build_tracking_request(tracking_number) ⇒ Object

Tracking



119
120
121
122
123
# File 'lib/freight_kit/platforms/carrier_logistics.rb', line 119

def build_tracking_request(tracking_number)
  api_credentials = fetch_credential(:api)

  { pronum: tracking_number, xmlpass: api_credentials.password, xmluser: api_credentials.username }
end

#build_url(action, query:) ⇒ Object

protected



46
47
48
49
50
51
52
53
54
55
# File 'lib/freight_kit/platforms/carrier_logistics.rb', line 46

def build_url(action, query:)
  scheme = @conf.dig(:api, :use_ssl, action) ? 'https://' : 'http://'

  uri = URI.parse("#{scheme}#{@conf.dig(:api, :domain)}#{@conf.dig(:api, :endpoints, action)}")
  uri.query = query.to_query
  url = uri.to_s
  return url if url.exclude?('@CARRIER_CODE@')

  url.sub('@CARRIER_CODE@', @conf.dig(:api, :carrier_code))
end

#commit(action, query) ⇒ Object



57
58
59
60
61
62
# File 'lib/freight_kit/platforms/carrier_logistics.rb', line 57

def commit(action, query)
  url = build_url(action, query:)
  save_request(url)

  HTTParty.get(url, logger: Logger.new($stdout))
end

#map_response_errors(response, not_found_error: DocumentNotFoundError) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
# File 'lib/freight_kit/platforms/carrier_logistics.rb', line 64

def map_response_errors(response, not_found_error: DocumentNotFoundError)
  return ResponseError.new('Unknown response') if response.blank?

  webspeed_error = (response.is_a?(String) || response.is_a?(HTTParty::Response)) &&
                   response.include?('WebSpeed error')
  return ResponseError.new('Temporary error (WebSpeed error)') if webspeed_error

  return if response.code == 200

  response.code == 400 ? not_found_error.new : ResponseError.new("HTTP #{response.code}")
end

#parse_amount(amount) ⇒ Object



293
294
295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/freight_kit/platforms/carrier_logistics.rb', line 293

def parse_amount(amount)
  negative = amount.include?('-')

  ['$', ',', '-'].each do |char|
    amount = amount.sub(char, '')
  end

  return 0 if amount.blank?

  amount = (amount.to_f * 100).to_i
  return amount unless negative

  amount * -1
end

#parse_api_city_state(str) ⇒ Object



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/freight_kit/platforms/carrier_logistics.rb', line 125

def parse_api_city_state(str)
  return if str.blank?

  city = str.split(', ')[0].titleize
  province = str.split(', ')[1].upcase

  if province == '*'
    province = case city
               when 'Albuquerque' then 'NM'
               end
  end

  Location.new(
    city:,
    province:,
    country: ActiveUtils::Country.find('USA'),
  )
end

#parse_api_city_state_zip(str) ⇒ Object



144
145
146
147
148
149
150
151
152
153
154
# File 'lib/freight_kit/platforms/carrier_logistics.rb', line 144

def parse_api_city_state_zip(str)
  return if str.blank?

  parts = str.split(', ')

  Location.new(
    city: parts.first.titleize,
    province: parts.last.upcase,
    country: ActiveUtils::Country.find('USA'),
  )
end

#parse_api_date(date, location) ⇒ Object



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/freight_kit/platforms/carrier_logistics.rb', line 156

def parse_api_date(date, location)
  return if date.blank?

  separator = ['?', '-'].find { |separator| date.include?(separator) }
  return if separator.blank?

  format = case date
           when /^\d{4}#{separator}/
             ['%Y', '%m', '%d'].join(separator)
           when /^\d{2}#{separator}/
             ['%m', '%d', '%Y'].join(separator)
           end
  return if format.blank?

  local_date = ::Date.strptime(date, format)
  ::FreightKit::DateTime.new(local_date:, location:)
end

#parse_api_date_time(date_time, location) ⇒ Object



174
175
176
177
178
179
180
181
182
183
# File 'lib/freight_kit/platforms/carrier_logistics.rb', line 174

def parse_api_date_time(date_time, location)
  return if date_time.blank?

  local_date_time = ::Time.strptime(date_time, '%Y-%m-%d %H:%M').to_fs(:db)
  ::FreightKit::DateTime.new(local_date_time:, location:)
rescue Date::Error
  raise if local_date_time.present?

  parse_api_date(local_date_time, location)
end

#parse_document_response(tracking_response, document_type) ⇒ Object

Documents



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/freight_kit/platforms/carrier_logistics.rb', line 78

def parse_document_response(tracking_response, document_type)
  document_response = DocumentResponse.new
  document_response.error = map_response_errors(tracking_response)
  return document_response if document_response.error.present?

  tracking_response.deep_symbolize_keys!

  image_type_code = case document_type
                    when :bol then 'B'
                    when :pod then 'P'
                    end

  api_images = tracking_response.dig(:protrace, :images, :image)
  api_images = [api_images] if api_images.is_a?(Hash)

  image = api_images&.find { |image| image[:imagetypecode] == image_type_code }
  url = image.blank? ? nil : (image[:directurl].presence || image[:imageurl])

  if url.blank?
    document_response.error = DocumentNotFoundError.new
    return document_response
  end

  begin
    response = HTTParty.get(url)
  rescue StandardError => e
    document_response.error = e
    return document_response
  end

  unless response.code == 200
    document_response.error = DocumentNotFoundError.new
    return document_response
  end

  document_response.assign_attributes(content_type: response.headers['content-type'], data: response.body)
  document_response
end

#parse_rate_response(shipment:, response:) ⇒ Object



368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
# File 'lib/freight_kit/platforms/carrier_logistics.rb', line 368

def parse_rate_response(shipment:, response:)
  rate_response = RateResponse.new(request: last_request, response:)

  rate_response.error = map_response_errors(response)
  return rate_response if rate_response.error.present?

  error = response.dig('error', 'errormessage')

  if error.present?
    rate_response.error = InvalidCredentialsError.new if error.downcase.include?('invalid username/password')

    if error.downcase.include?('is not available') || error.downcase.include?('out of the serviceable area')
      rate_response.error = UnserviceableError.new(error)
    end

    rate_response.error = ResponseError.new(error) if rate_response.error.blank?

    return rate_response
  end

  if response.dig('ratequote', 'quotetotal').blank?
    rate_response.error = ResponseError.new('Cost is blank')
    return rate_response
  end

  total_cents = parse_amount(response.dig('ratequote', 'quotetotal'))

  transit_days = response.dig('ratequote', 'busdays').to_i
  estimate_reference = response.dig('ratequote', 'quotenumber')

  ratequote_lines = response.dig('ratequote', 'ratequoteline')
  prices = []

  ratequote_lines.each do |ratequote_line|
    next if ratequote_line['chrg'].blank?
    next if ratequote_line['chargedesc'] == 'FREIGHT'

    cents = parse_amount(ratequote_line['chrg'])
    next if cents.zero?

    prices << Price.new(
      blame: :api,
      cents:,
      description: ratequote_line_description(ratequote_line),
    )
  end

  prices = [
             Price.new(
               blame: :api,
               cents: total_cents - prices.sum(&:cents),
               description: 'Freight',
             ),
           ] + prices

  if self.class.overlength_fees_require_tariff?
    cents = 0

    shipment.packages.each do |package|
      cents += overlength_fee(tariff, package)
    end

    prices << Price.new(blame: :tariff, cents:, description: 'Overlength fees') if cents.nonzero?
  end

  rate = Rate.new(
    carrier: self,
    carrier_name: self.class.name,
    currency: 'USD',
    estimate_reference:,
    scac: self.class.scac.upcase,
    service_name: :standard,
    shipment:,
    prices:,
    transit_days:,
    with_excessive_length_fees: @conf.dig(:attributes, :rates, :with_excessive_length_fees),
  )

  rate_response.rates = [rate]
  rate_response
end

#parse_tracking_response(tracking_number, response:) ⇒ Object



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/freight_kit/platforms/carrier_logistics.rb', line 185

def parse_tracking_response(tracking_number, response:)
  tracking_response = TrackingResponse.new(carrier: self, request: last_request, response:)
  tracking_response.error = map_response_errors(response, not_found_error: ShipmentNotFoundError)
  return tracking_response if tracking_response.error.present?

  response.deep_symbolize_keys!

  api_events = response.dig(:protrace, :shiphists, :shiphist)
  if api_events.blank?
    tracking_response.error = ResponseError.new('Empty response')
    return tracking_response
  end

  origin = Location.new(
    address1: response.dig(:protrace, :shipaddr)&.titleize,
    address2: response.dig(:protrace, :shipaddr2)&.titleize,
    city: response.dig(:protrace, :origcity)&.titleize,
    province: response.dig(:protrace, :origstate)&.upcase,
    country: ActiveUtils::Country.find('USA'),
  )

  destination = Location.new(
    address1: response.dig(:protrace, :consaddr)&.titleize,
    address2: response.dig(:protrace, :consaddr2)&.titleize,
    city: response.dig(:protrace, :destcity)&.titleize,
    province: response.dig(:protrace, :deststate)&.upcase,
    country: ActiveUtils::Country.find('USA'),
  )

  deldateiso = response.dig(:protrace, :deldateiso)
  actual_delivery_date = (parse_api_date(deldateiso, destination) if deldateiso.present?)

  estdeliverydateiso = response.dig(:protrace, :estdeliverydateiso)
  estdeliverytimestart = response.dig(:protrace, :estdeliverytimestart)
  estimated_delivery_date = if estdeliverydateiso.present? && estdeliverytimestart.present?
                              parse_api_date_time([estdeliverydateiso, estdeliverytimestart].join(' '), destination)
                            elsif estdeliverydateiso.present?
                              parse_api_date(estdeliverydateiso, destination)
                            end

  scheduled_delivery_date = nil
  ship_time = nil

  api_events = response.dig(:protrace, :shiphists, :shiphist)
  api_events = [api_events] if api_events.is_a?(Hash)

  last_location = origin

  shipment_events = api_events.reverse.map do |api_event|
    hist_code = api_event[:histcode]&.downcase
    next if hist_code.blank?

    event = conf.dig(:events, :types).key(hist_code)
    next if event.blank?

    remarks = api_event[:histremarks]

    location = if remarks.present? && remarks.match?(/, \w{2}/) # ends in state abbreviation
                 parse_api_city_state(api_event[:histremarks])
               end

    location ||= case event
                 when :delivered then destination
                 when :departed then last_location
                 when :picked_up, :pickup_scheduled then origin
                 end

    date = api_event[:histdate]
    time = api_event[:histtime]
    # Some api_event[:histtime] returns a string with missing hours and minutes like '  :  '
    time = nil if (time =~ /\d/).blank?

    date_time = if [date, time].all?(&:present?)
                  parse_api_date_time([date, time].compact.join(' '), location)
                elsif date.present?
                  parse_api_date(date, location)
                end

    last_location = location

    ShipmentEvent.new(location:, date_time:, type_code: event)
  end

  shipment_events.compact!

  status = shipment_events.last&.type_code

  tracking_response.assign_attributes(
    actual_delivery_date:,
    destination:,
    estimated_delivery_date:,
    origin:,
    scheduled_delivery_date:,
    ship_time:,
    shipment_events:,
    status:,
    tracking_number:,
  )

  tracking_response
end

#pod(tracking_number) ⇒ Object

Documents



32
33
34
35
36
# File 'lib/freight_kit/platforms/carrier_logistics.rb', line 32

def pod(tracking_number)
  query = build_tracking_request(tracking_number)
  response = commit(:track, query)
  parse_document_response(response, :pod)
end

#ratequote_line_description(ratequote_line) ⇒ Object



308
309
310
311
312
313
314
315
316
# File 'lib/freight_kit/platforms/carrier_logistics.rb', line 308

def ratequote_line_description(ratequote_line)
  description = ratequote_line['chargedesc'] || ''
  description = description.capitalize

  code = ratequote_line['chargecode']&.upcase || ''
  description = "#{description} (#{code})" if code.present?

  description.squish
end

#scanned_bol(tracking_number) ⇒ Object



38
39
40
41
42
# File 'lib/freight_kit/platforms/carrier_logistics.rb', line 38

def scanned_bol(tracking_number)
  query = build_tracking_request(tracking_number)
  response = commit(:track, query)
  parse_document_response(response, :bol)
end