Class: Swisspost::BarcodeService

Inherits:
BaseService show all
Defined in:
lib/swisspost/barcode_service.rb

Defined Under Namespace

Classes: GenerateResult

Constant Summary collapse

API_SCOPE =
"DCAPI_BARCODE_READ"
API_URL =
"https://dcapi.apis.post.ch/barcode/v1"
FRANKING_LICENSE =
"60170283"
GENERATE_VALIDATOR =
Dry::Validation.Contract do
  params do
    required(:sender).value(Types::Instance(Model::Address))
    required(:recipient).value(Types::Instance(Model::Address))
    required(:item).value(Types::Instance(Model::BarcodeItem))
  end
end

Instance Method Summary collapse

Methods inherited from BaseService

#access_token, #httpx_apikey, #httpx_oauth

Instance Method Details

#generate(attributes) ⇒ Object

Raises:



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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/swisspost/barcode_service.rb', line 24

def generate(attributes)
  path = "/generateAddressLabel"

  result = GENERATE_VALIDATOR.call(attributes)
  raise Model::ValidationError, result.errors.to_h.inspect if result.failure?

  validated_data = result.to_h
  sender = validated_data[:sender]
  recipient = validated_data[:recipient]
  item = validated_data[:item]

  client = httpx_oauth(API_SCOPE)

  payload = {
    language: 'DE',
    frankingLicense: FRANKING_LICENSE,
    ppFranking: false,
    customer: {
      name1: sender.full_name,
      street: sender.full_street,
      zip: sender.zip,
      city: sender.city,
    },
    labelDefinition: {
      labelLayout: 'A6',
      printAddresses: 'ONLY_RECIPIENT',
      imageFileType: 'PNG',
      imageResolution: 300,
      printPreview: false
    },
    item: {
      recipient: {
        name1: recipient.full_name,
        street: recipient.street,
        houseNo: recipient.house_number,
        zip: recipient.zip,
        city: recipient.city,
      },
      attributes: {
        przl: [item.service_code],
        weight: item.weight,
      }
    }
  }

  response = client.post(API_URL + path, json: payload)

  response.raise_for_status

  result = response.json

  return GenerateResult.new(
    image: result[:item][:label],
    file_type: result[:labelDefinition][:imageFileType],
  )
end