Class: Deliveries::Couriers::CorreosExpress::Labels::Generate

Inherits:
Object
  • Object
show all
Includes:
HTTParty
Defined in:
lib/deliveries/couriers/correos_express/labels/generate.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tracking_codes:) ⇒ Generate

Returns a new instance of Generate.



12
13
14
# File 'lib/deliveries/couriers/correos_express/labels/generate.rb', line 12

def initialize(tracking_codes:)
  self.tracking_codes = tracking_codes.respond_to?(:each) ? tracking_codes : [tracking_codes]
end

Instance Attribute Details

#tracking_codesObject

Returns the value of attribute tracking_codes.



10
11
12
# File 'lib/deliveries/couriers/correos_express/labels/generate.rb', line 10

def tracking_codes
  @tracking_codes
end

Instance Method Details

#executeObject



16
17
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
50
51
52
53
# File 'lib/deliveries/couriers/correos_express/labels/generate.rb', line 16

def execute
  auth = {
    username: CorreosExpress.config(:username),
    password: CorreosExpress.config(:password)
  }
  decoded_labels = []
  tracking_codes.each do |tracking_code|
    params = {
      keyCli: CorreosExpress.config(:shipment_sender_code),
      nenvio: tracking_code,
      tipo: '1' # "1" - pdf, "2" - zpl image
    }.to_json

    headers = { 'Content-Type' => 'application/json' }
    response = self.class.post(
      api_endpoint,
      basic_auth: auth,
      body: params,
      headers: headers,
      debug_output: Deliveries.debug ? Deliveries.logger : nil
    )
    parsed_response = JSON.parse(response.body)
    if (parsed_response['codErr']).zero?
      if parsed_response['listaEtiquetas'].any?
        parsed_response['listaEtiquetas'].each do |encoded_label|
          decoded_labels << Base64.decode64(encoded_label).force_encoding('binary')
        end
      end
    else
      raise Deliveries::APIError.new(
        parsed_response['desErr'],
        parsed_response['codErr']
      )
    end
  end

  decoded_labels
end