Class: DHLEcommerceAPI::Shipment

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

Defined Under Namespace

Classes: ShipmentItem

Instance Method Summary collapse

Methods inherited from Base

#account_ids, #attributes_with_account_ids, #custom_key_format, #handle_errors

Instance Method Details

#createObject



9
10
11
12
13
14
15
16
# File 'lib/dhl_ecommerce_api/resources/shipment.rb', line 9

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

#headersObject



60
61
62
63
64
65
66
67
# File 'lib/dhl_ecommerce_api/resources/shipment.rb', line 60

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

#load_attributes_from_response(response) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/dhl_ecommerce_api/resources/shipment.rb', line 18

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"
      @persisted = false
    else
      error_messages = response_status["messageDetails"].map { |err| err["messageDetail"] }
      handle_errors(code, error_messages)
      @persisted = false
    end

    # service level
    new_attributes = attributes.merge({ response: JSON.parse(response.body) })

    # object level
    if bd["shipmentItems"].present?
      new_attributes["shipmentItems"] = new_attributes["shipmentItems"].map do |item|
        item.attributes.merge(bd["shipmentItems"].find { |i| i["shipmentID"] == item.shipmentID })
      end
    end

    load(new_attributes, true, @persisted)
  end
end

#manifest_requestObject



51
52
53
54
55
56
57
58
# File 'lib/dhl_ecommerce_api/resources/shipment.rb', line 51

def manifest_request
  {
    "manifestRequest": {
      "hdr": headers,
      "bd": 
    }
  }
end