Class: DHLEcommerceAPI::Tracking

Inherits:
Base
  • Object
show all
Defined in:
lib/dhl_ecommerce_api/resources/tracking.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#account_ids, #attributes_with_account_ids, #custom_key_format, #handle_errors

Constructor Details

#initialize(attributes = {}, persisted = false) ⇒ Tracking

Returns a new instance of Tracking.



6
7
8
9
# File 'lib/dhl_ecommerce_api/resources/tracking.rb', line 6

def initialize(attributes = {}, persisted = false)
  attributes = .merge(attributes)
  super
end

Class Method Details

.find(arguments) ⇒ Object



11
12
13
14
15
16
17
18
19
# File 'lib/dhl_ecommerce_api/resources/tracking.rb', line 11

def self.find(arguments)
  tracking = self.new({
    "ePODRequired": "Y",
    "trackingReferenceNumber": arguments.is_a?(Array) ? arguments : [arguments]
  })
  tracking.save
    
  return tracking.shipment_items.presence || []
end

Instance Method Details

#createObject



21
22
23
24
25
26
27
# File 'lib/dhl_ecommerce_api/resources/tracking.rb', line 21

def create
  run_callbacks :create do
    connection.post(collection_path, request_data.to_json, self.class.headers).tap do |response|
      load_attributes_from_response(response)
    end
  end
end

#headersObject



65
66
67
68
69
70
71
72
# File 'lib/dhl_ecommerce_api/resources/tracking.rb', line 65

def headers
  {
    "messageType": "TRACKITEM",
    "messageDateTime": DateTime.now.to_s,
    "accessToken": DHLEcommerceAPI::Authentication.get_token,
    "messageVersion": "1.0"
  }
end

#load_attributes_from_response(response) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/dhl_ecommerce_api/resources/tracking.rb', line 29

def load_attributes_from_response(response)
  if response_code_allows_body?(response.code.to_i) &&
      (response["Content-Length"].nil? || response["Content-Length"] != "0") &&
      !response.body.nil? && response.body.strip.size > 0
    
    bd = self.class.format.decode(response.body)["bd"]
    response_status = bd["responseStatus"]
    code = response_status["code"]

    if code == "200"
      @persisted = true
    elsif code == "204"
      # handle partial success
      @persisted = false
    else
      error_messages = response_status["messageDetails"].map{|err| err["messageDetail"]}
      handle_errors(code, error_messages)
      @persisted = false
    end
    
    new_attributes = attributes.merge({response: JSON.parse(response.body)})
    new_attributes = new_attributes.merge({shipment_items: bd["shipmentItems"]})
    
    load(new_attributes, true, @persisted)
  end
end

#request_dataObject



56
57
58
59
60
61
62
63
# File 'lib/dhl_ecommerce_api/resources/tracking.rb', line 56

def request_data
  {
    "trackItemRequest": {
      "hdr": headers,
      "bd": attributes.except("response_status") # dont send responseStatus
    }
  }
end