Class: ColissimoLabel::GenerateLabel

Inherits:
Object
  • Object
show all
Defined in:
lib/colissimo_label/generate_label.rb

Instance Method Summary collapse

Constructor Details

#initialize(filename, destination_country, shipping_fees, sender_data, addressee_data, options = {}) ⇒ GenerateLabel

Returns a new instance of GenerateLabel.



7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/colissimo_label/generate_label.rb', line 7

def initialize(filename, destination_country, shipping_fees, sender_data, addressee_data, options = {})
  @filename             = filename
  @destination_country  = destination_country
  @shipping_fees        = shipping_fees
  @sender_data          = sender_data
  @addressee_data       = addressee_data
  @pickup_id            = options.fetch(:pickup_id, nil)
  @pickup_type          = options.fetch(:pickup_type, nil)
  @customs_total_weight = options.fetch(:customs_total_weight, nil)
  @customs_data         = options.fetch(:customs_data, nil)
  @errors               = []
end

Instance Method Details

#performObject



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
54
55
56
57
58
59
60
61
# File 'lib/colissimo_label/generate_label.rb', line 20

def perform
  response       = perform_request
  status         = response.code
  parts          = response.to_a.last.force_encoding('BINARY').split('Content-ID: ')
  label_filename = @filename + '.pdf'

  if ColissimoLabel.s3_bucket
    colissimo_pdf = ColissimoLabel.s3_bucket.object(ColissimoLabel.s3_path.chomp('/') + '/' + label_filename)
    colissimo_pdf.put(acl: 'public-read', body: parts[2])
  else
    File.open(ColissimoLabel.colissimo_local_path.chomp('/') + '/' + label_filename, 'wb') do |file|
      file.write(parts[2])
    end
  end

  if require_customs?
    customs_filename = @filename + '-customs.pdf'

    if ColissimoLabel.s3_bucket
      customs_pdf = ColissimoLabel.s3_bucket.object(ColissimoLabel.s3_path.chomp('/') + '/' + customs_filename)
      customs_pdf.put(acl: 'public-read', body: parts[3])
    else
      File.open(ColissimoLabel.colissimo_local_path.chomp('/') + '/' + customs_filename, 'wb') do |file|
        file.write(parts[3])
      end
    end
  end

  if status == 400
    error_message = response.body.to_s.encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '').scan(/"messageContent":"(.*?)"/).last&.first
    raise StandardError, error_message
  else
    if (response_message = response.body.to_s.encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '').scan(/"parcelNumber":"(.*?)",/).last)
      parcel_number = response_message.first

      return parcel_number
    else
      error_message = response.body.to_s.encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '').scan(/"messageContent":"(.*?)"/).last&.first
      raise StandardError, error_message
    end
  end
end