class Deliveries::Couriers::Ups::Shipments::Trace

Attributes

language[RW]
tracking_code[RW]

Public Class Methods

new(tracking_code:, language: nil) click to toggle source
# File lib/deliveries/couriers/ups/shipments/trace.rb, line 10
def initialize(tracking_code:, language: nil)
  self.tracking_code = tracking_code
  self.language = language
end

Public Instance Methods

execute() click to toggle source
# File lib/deliveries/couriers/ups/shipments/trace.rb, line 15
def execute
  response = call nil, method: :get, url_params: { inquiry_number: tracking_code },
                       query_params: { locale: locale }

  package = response.dig(:trackResponse, :shipment, 0, :package, 0, :activity)
  raise Error, 'Cannot obtain package activity data' if package.blank?

  activities = package.map do |activity|
    {
      status: status(activity.dig(:status, :type), activity.dig(:status, :code)),
      location: activity.dig(:location, :address, :city),
      tracked_at: DateTime.parse("#{activity[:date]}T#{activity[:time]}"),
      description: activity.dig(:status, :description)
    }
  end

  activities.sort_by { |activity| activity[:tracked_at] }
end

Private Instance Methods

api_endpoint() click to toggle source
# File lib/deliveries/couriers/ups/shipments/trace.rb, line 36
def api_endpoint
  if Ups.live?
    'https://onlinetools.ups.com/track/v1/details/%<inquiry_number>s'
  else
    'https://wwwcie.ups.com/track/v1/details/%<inquiry_number>s'
  end
end
locale() click to toggle source
# File lib/deliveries/couriers/ups/shipments/trace.rb, line 44
def locale
  case language&.to_sym&.downcase
  when :es then 'es_ES'
  when :fr then 'fr_FR'
  when :pt then 'pt_PT'
  when :it then 'it_IT'
  when :de then 'de_DE'
  when :en then 'en_GB'
  when :pl then 'pl_PL'
  else 'en_US'
  end
end
status(type, code) click to toggle source
# File lib/deliveries/couriers/ups/shipments/trace.rb, line 57
def status(type, code)
  case type&.to_s&.upcase
  when 'M'
    :registered
  when 'I', 'P', 'O'
    :in_transit
  when 'D'
    if %w[2Q ZP].include?(code&.to_s&.upcase)
      :in_collection_point
    else
      :delivered
    end
  when 'MV'
    :canceled
  else
    :unknown_status
  end
end