swisspost 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: fbd3ac04512275da8f1e0745fc3dcb2835a8668eac1b1ff2a64699d6e68c3906
4
+ data.tar.gz: 8c809ca4feb8765c5c8532134e18218944b171fe346847c8f9173b9cdc54c762
5
+ SHA512:
6
+ metadata.gz: cac944edd2ddb6f5119899211e4404b55ea49b7b2a506f56c6d5072c743cb321b71c2f5e03bcfbbae69bfd7efab31d1c4744dd1b551a44077ccf2c873571a895
7
+ data.tar.gz: 7ebdc16d1b5e4612e728dd09ab5c2291054fbbd872e5e4e6742df39ada735f20a0992ed079033f6d52b667335f43974ffc5672bf009d8bc8438ca78e8a8da8d2
@@ -0,0 +1,49 @@
1
+ // For format details, see https://aka.ms/devcontainer.json. For config options, see the
2
+ // README at: https://github.com/devcontainers/templates/tree/main/src/ruby
3
+ {
4
+ "name": "Ruby",
5
+ // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
6
+ "image": "mcr.microsoft.com/devcontainers/ruby:1-3.4-bullseye",
7
+
8
+ "mounts": [
9
+ "source=${localEnv:HOME}/.claude,target=/home/vscode/.claude,type=bind,consistency=cached",
10
+ "source=${localEnv:HOME}/.claude.json,target=/home/vscode/.claude.json,type=bind,consistency=cached"
11
+ ],
12
+
13
+ // Features to add to the dev container. More info: https://containers.dev/features.
14
+ "features": {
15
+ "ghcr.io/devcontainers/features/node:1": {
16
+ "version": "lts",
17
+ "nvmVersion": "0.40.3"
18
+ },
19
+ "ghcr.io/anthropics/devcontainer-features/claude-code:1.0.5": {}
20
+ },
21
+
22
+ // Use 'forwardPorts' to make a list of ports inside the container available locally.
23
+ // "forwardPorts": [],
24
+
25
+ // Use 'postCreateCommand' to run commands after the container is created.
26
+ "postCreateCommand": "bundle install",
27
+
28
+ // Configure tool-specific properties.
29
+ "customizations": {
30
+ "vscode": {
31
+ "extensions": [
32
+ "shardulm94.trailing-spaces",
33
+ "Fooo.ruby-spec-runner",
34
+ "tomoki1207.pdf",
35
+ "GitHub.copilot"
36
+ ],
37
+ "settings": {
38
+ "rubyLsp.rubyVersionManager": {
39
+ "identifier": "none"
40
+ },
41
+ "rubyLsp.formatter": "auto",
42
+ "editor.formatOnSaveMode": "file"
43
+ }
44
+ }
45
+ }
46
+
47
+ // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
48
+ // "remoteUser": "root"
49
+ }
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.standard.yml ADDED
@@ -0,0 +1,3 @@
1
+ # For available configuration options, see:
2
+ # https://github.com/standardrb/standard
3
+ ruby_version: 3.1
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-07-23
4
+
5
+ - Initial release
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Lukas_Skywalker
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,181 @@
1
+ # Swisspost
2
+
3
+ A Ruby gem for interacting with Swiss Post APIs, providing address validation, barcode generation, and price calculation services.
4
+
5
+ ## Installation
6
+
7
+ Install the gem and add to the application's Gemfile by executing:
8
+
9
+ ```bash
10
+ bundle add swisspost
11
+ ```
12
+
13
+ If bundler is not being used to manage dependencies, install the gem by executing:
14
+
15
+ ```bash
16
+ gem install swisspost
17
+ ```
18
+
19
+ ## Usage
20
+
21
+ ### Configuration
22
+
23
+ Before using any of the services, you need to configure your Swiss Post API credentials:
24
+
25
+ ```ruby
26
+ require 'swisspost'
27
+
28
+ # Configure your API credentials (required for all services)
29
+ Swisspost.configure do |config|
30
+ config.client_id = 'your_client_id'
31
+ config.client_secret = 'your_client_secret'
32
+ config.api_key = 'your_api_key' # Required for price service
33
+ end
34
+ ```
35
+
36
+ ### Address Validation Service
37
+
38
+ Validate Swiss addresses using the Swiss Post address validation API:
39
+
40
+ ```ruby
41
+ # Create an address object
42
+ address = Swisspost::Model::Address.new(
43
+ first_name: 'John',
44
+ last_name: 'Doe',
45
+ street: 'Bahnhofstrasse',
46
+ house_number: '1',
47
+ zip: 8001,
48
+ city: 'Zürich'
49
+ )
50
+
51
+ # Validate the address
52
+ service = Swisspost::AddressService.new
53
+ result = service.validate(address: address)
54
+
55
+ # Check the validation result
56
+ puts result.quality.description
57
+ # Possible qualities:
58
+ # - DOMICILE_CERTIFIED: The address, including the full name of the person, is certified by SwissPost
59
+ # - CERTIFIED: The address is certified by the Swiss Post
60
+ # - USABLE: Parts of the address have been recognized and the address is considered as reusable
61
+ # - FIXED: The address is USABLE, but some minor typos have been corrected
62
+ # - UNUSABLE: The system was not able to recognize an acceptable address
63
+ # - COMPROMISED: The address may have been modified by a man in the middle
64
+
65
+ # Get the validated address
66
+ validated_address = result.address
67
+ ```
68
+
69
+ ### Barcode Generation Service
70
+
71
+ Generate address labels with barcodes for shipping:
72
+
73
+ ```ruby
74
+ # Create sender and recipient addresses
75
+ sender = Swisspost::Model::Address.new(
76
+ first_name: 'Alice',
77
+ last_name: 'Smith',
78
+ street: 'Poststrasse',
79
+ house_number: '10',
80
+ zip: 3000,
81
+ city: 'Bern'
82
+ )
83
+
84
+ recipient = Swisspost::Model::Address.new(
85
+ first_name: 'Bob',
86
+ last_name: 'Johnson',
87
+ street: 'Hauptstrasse',
88
+ house_number: '5',
89
+ zip: 4000,
90
+ city: 'Basel'
91
+ )
92
+
93
+ # Create a barcode item with service type and weight
94
+ item = Swisspost::Model::BarcodeItem.new(
95
+ service_code: 'PRI', # Options: ECO, PRI, APOST, BPOST
96
+ weight: 100 # Weight in grams
97
+ )
98
+
99
+ # Generate the barcode label
100
+ service = Swisspost::BarcodeService.new
101
+ result = service.generate(
102
+ sender: sender,
103
+ recipient: recipient,
104
+ item: item
105
+ )
106
+
107
+ # The result contains the label image and content type
108
+ # result.image contains the base64-encoded label image
109
+ # result.content_type contains the image format (e.g., 'image/png')
110
+
111
+ # Save the label to a file
112
+ require 'base64'
113
+ File.open('shipping_label.png', 'wb') do |file|
114
+ file.write(Base64.decode64(result.image))
115
+ end
116
+ ```
117
+
118
+ ### Price Calculation Service
119
+
120
+ Calculate shipping prices for different countries and package formats:
121
+
122
+ ```ruby
123
+ service = Swisspost::PriceService.new
124
+
125
+ # Get available products for shipping
126
+ products = service.products(
127
+ country: 'DE', # ISO country code (e.g., 'DE' for Germany, 'FR' for France)
128
+ format: 'B5', # Package format: B4, B5, MB, PK, SP, RL, FF
129
+ weight: 500 # Weight in grams
130
+ )
131
+
132
+ # The result contains available shipping products with prices
133
+ products.each do |product|
134
+ puts "#{product['name']}: CHF #{product['price']}"
135
+ end
136
+ ```
137
+
138
+ ### Error Handling
139
+
140
+ All services raise appropriate errors when validation fails or API calls are unsuccessful:
141
+
142
+ ```ruby
143
+ begin
144
+ # Invalid address (ZIP code out of range)
145
+ address = Swisspost::Model::Address.new(
146
+ first_name: 'John',
147
+ last_name: 'Doe',
148
+ street: 'Invalid Street',
149
+ house_number: '999',
150
+ zip: 999, # Invalid Swiss ZIP code
151
+ city: 'Unknown'
152
+ )
153
+ rescue Swisspost::ValidationError => e
154
+ puts "Validation failed: #{e.message}"
155
+ end
156
+
157
+ begin
158
+ service = Swisspost::AddressService.new
159
+ result = service.validate(address: some_address)
160
+ rescue HTTPX::HTTPError => e
161
+ puts "API request failed: #{e.message}"
162
+ end
163
+ ```
164
+
165
+ ## Development
166
+
167
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
168
+
169
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
170
+
171
+ ## Contributing
172
+
173
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/swisspost. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/swisspost/blob/master/CODE_OF_CONDUCT.md).
174
+
175
+ ## License
176
+
177
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
178
+
179
+ ## Code of Conduct
180
+
181
+ Everyone interacting in the Swisspost project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/swisspost/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "standard/rake"
9
+
10
+ task default: %i[spec standard]
data/exe/swisspost ADDED
@@ -0,0 +1,157 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "swisspost"
6
+ require "swisspost/model/address"
7
+ require "swisspost/model/barcode_item"
8
+ require "swisspost/barcode_service"
9
+ require "cli/ui"
10
+ require "base64"
11
+
12
+ class SwisspostCLI
13
+ def self.run(args)
14
+ command = args.first
15
+
16
+ case command
17
+ when "barcode"
18
+ generate_barcode
19
+ when nil, "--help", "-h"
20
+ show_help
21
+ else
22
+ CLI::UI.puts(CLI::UI.fmt("{{red:Unknown command: #{command}}}"))
23
+ show_help
24
+ exit(1)
25
+ end
26
+ end
27
+
28
+ def self.show_help
29
+ CLI::UI::Frame.open("Swiss Post CLI") do
30
+ CLI::UI.puts <<~HELP
31
+ Usage: swisspost <command>
32
+
33
+ Commands:
34
+ barcode Generate a Swiss Post barcode interactively
35
+
36
+ Options:
37
+ --help, -h Show this help message
38
+ HELP
39
+ end
40
+ end
41
+
42
+ def self.generate_barcode
43
+ CLI::UI::Frame.open("Generate Swiss Post Barcode") do
44
+ # Sender information
45
+ CLI::UI.puts(CLI::UI.fmt("{{blue:Enter sender information:}}"))
46
+ sender_first_name = CLI::UI.ask("Sender first name:")
47
+ sender_last_name = CLI::UI.ask("Sender last name:")
48
+ sender_street = CLI::UI.ask("Sender street:")
49
+ sender_house_number = CLI::UI.ask("Sender house number:")
50
+ sender_zip = CLI::UI.ask("Sender ZIP code:").to_i
51
+ sender_city = CLI::UI.ask("Sender city:")
52
+
53
+ # Recipient information
54
+ CLI::UI.puts(CLI::UI.fmt("\n{{blue:Enter recipient information:}}"))
55
+ recipient_first_name = CLI::UI.ask("Recipient first name:")
56
+ recipient_last_name = CLI::UI.ask("Recipient last name:")
57
+ recipient_street = CLI::UI.ask("Recipient street:")
58
+ recipient_house_number = CLI::UI.ask("Recipient house number:")
59
+ recipient_zip = CLI::UI.ask("Recipient ZIP code:").to_i
60
+ recipient_city = CLI::UI.ask("Recipient city:")
61
+
62
+ # Display entered data and ask for confirmation
63
+ CLI::UI.puts(CLI::UI.fmt("\n{{blue:Please confirm the entered information:}}"))
64
+
65
+ CLI::UI.puts(CLI::UI.fmt("\n{{bold:Sender Address:}}"))
66
+ CLI::UI.puts(" #{sender_first_name} #{sender_last_name}")
67
+ CLI::UI.puts(" #{sender_street} #{sender_house_number}")
68
+ CLI::UI.puts(" #{sender_zip} #{sender_city}")
69
+
70
+ CLI::UI.puts(CLI::UI.fmt("\n{{bold:Recipient Address:}}"))
71
+ CLI::UI.puts(" #{recipient_first_name} #{recipient_last_name}")
72
+ CLI::UI.puts(" #{recipient_street} #{recipient_house_number}")
73
+ CLI::UI.puts(" #{recipient_zip} #{recipient_city}")
74
+
75
+ confirm_addresses = CLI::UI.confirm("\nIs this information correct?")
76
+ if !confirm_addresses
77
+ CLI::UI.puts(CLI::UI.fmt("{{yellow:Operation cancelled. Please run the command again.}}"))
78
+ exit(0)
79
+ end
80
+
81
+ # Service information
82
+ CLI::UI.puts(CLI::UI.fmt("\n{{blue:Enter service information:}}"))
83
+ service_codes = ["ECO", "PRI", "APOST", "BPOST"]
84
+ service_code = CLI::UI.ask("Select service code:") do |handler|
85
+ service_codes.each do |code|
86
+ handler.option(code) { code }
87
+ end
88
+ end
89
+ weight = CLI::UI.ask("Weight in grams:").to_i
90
+
91
+ # Create barcode
92
+ CLI::UI.puts("\nGenerating barcode...")
93
+
94
+ begin
95
+ barcode_service = Swisspost::BarcodeService.new
96
+
97
+ sender_address = Swisspost::Model::Address.new(
98
+ first_name: sender_first_name,
99
+ last_name: sender_last_name,
100
+ street: sender_street,
101
+ house_number: sender_house_number,
102
+ zip: sender_zip,
103
+ city: sender_city
104
+ )
105
+
106
+ recipient_address = Swisspost::Model::Address.new(
107
+ first_name: recipient_first_name,
108
+ last_name: recipient_last_name,
109
+ street: recipient_street,
110
+ house_number: recipient_house_number,
111
+ zip: recipient_zip,
112
+ city: recipient_city
113
+ )
114
+
115
+ barcode_item = Swisspost::Model::BarcodeItem.new(
116
+ service_code: service_code,
117
+ weight: weight
118
+ )
119
+
120
+ result = barcode_service.generate({
121
+ sender: sender_address,
122
+ recipient: recipient_address,
123
+ item: barcode_item
124
+ })
125
+
126
+ CLI::UI.puts(CLI::UI.fmt("{{green:✓}} Barcode label generated successfully!"))
127
+ CLI::UI.puts("Image type: #{result.file_type}")
128
+
129
+ # Ask if user wants to save the image
130
+ save_image = CLI::UI.confirm("Would you like to save the label image?")
131
+ if save_image
132
+ filename = CLI::UI.ask("Enter filename (without extension):", default: "barcode_label")
133
+ full_filename = "#{filename}.#{result.file_type}"
134
+
135
+ File.open(full_filename, "wb") do |file|
136
+ file.write(Base64.decode64(result.image))
137
+ end
138
+
139
+ CLI::UI.puts("Label saved to: #{CLI::UI.fmt("{{green:#{full_filename}}}")}")
140
+ end
141
+ rescue HTTPX::Error => e
142
+ CLI::UI.puts(CLI::UI.fmt("{{red:✗ Network Error: #{e.message}}}"))
143
+ CLI::UI.puts("\nPlease check your internet connection and try again.")
144
+ exit(1)
145
+ rescue Swisspost::Model::ValidationError => e
146
+ CLI::UI.puts(CLI::UI.fmt("{{red:✗ Validation Error: #{e.message}}}"))
147
+ exit(1)
148
+ rescue => e
149
+ CLI::UI.puts(CLI::UI.fmt("{{red:✗ Error: #{e.message}}}"))
150
+ CLI::UI.puts(CLI::UI.fmt("{{red:#{e.class}: #{e.backtrace.first}}}"))
151
+ exit(1)
152
+ end
153
+ end
154
+ end
155
+ end
156
+
157
+ SwisspostCLI.run(ARGV)
@@ -0,0 +1,85 @@
1
+ require "dry-validation"
2
+ require_relative "model/address"
3
+ require_relative "base_service"
4
+ require_relative "types"
5
+
6
+ module Swisspost
7
+ class AddressService < BaseService
8
+ API_SCOPE = "DCAPI_ADDRESS_VALIDATE"
9
+ API_URL = "https://dcapi.api.post.ch/address/v1"
10
+
11
+ VALIDATE_VALIDATOR = Dry::Validation.Contract do
12
+ params do
13
+ required(:address).value(Types::Instance(Model::Address))
14
+ end
15
+ end
16
+
17
+ def validate(attributes)
18
+ path = "/addresses/validation"
19
+
20
+ result = VALIDATE_VALIDATOR.call(attributes)
21
+ raise ValidationError, result.errors.to_h.inspect if result.failure?
22
+
23
+ validated_data = result.to_h
24
+ address = validated_data[:address]
25
+
26
+ response = httpx.post(API_URL + path, json: {
27
+ addressee: {
28
+ firstName: address.first_name,
29
+ lastName: address.last_name,
30
+ }, geographicalLocation: {
31
+ house: {
32
+ street: address.street,
33
+ houseNumber: address.house_number,
34
+ },
35
+ zip: {
36
+ zip: address.zip,
37
+ city: address.city,
38
+ }
39
+ },
40
+ fullValidation: true,
41
+ })
42
+
43
+ response.raise_for_status
44
+
45
+ result = response.json
46
+
47
+ address = Address.new(
48
+ first_name: result[:addressee][:first_name],
49
+ last_name: result[:addressee][:last_name],
50
+ street: result[:geographical_location][:house][:street],
51
+ house_number: result[:geographical_location][:house][:house_number],
52
+ zip: result[:geographical_location][:zip][:zip],
53
+ city: result[:geographical_location][:zip][:city],
54
+ )
55
+
56
+ quality = Qualities.for(result[:quality])
57
+
58
+ return Result.new(
59
+ address: address,
60
+ quality: quality,
61
+ )
62
+ end
63
+
64
+ Result = Struct.new(:address, :quality, keyword_init: true)
65
+
66
+ Quality = Struct.new(:value, :description, keyword_init: true) do
67
+ def to_s
68
+ description
69
+ end
70
+ end
71
+
72
+ module Qualities
73
+ DOMICILE_CERTIFIED = Quality.new(value: "DOMICILE_CERTIFIED", description: "The address, including the full name of the person, is certified by SwissPost")
74
+ CERTIFIED = Quality.new(value: "CERTIFIED", description: "The address is certified by the Swiss Post")
75
+ USABLE = Quality.new(value: "USABLE", description: "Parts of the address have been recognized and the address is considered as reusable in other contexts")
76
+ FIXED = Quality.new(value: "FIXED", description: "The returned address is USABLE, but some minor typos have been corrected (e.g. you sent only the zip and the SwissPost service add the city name)")
77
+ UNUSABLE = Quality.new(value: "UNUSABLE", description: "The system was not able to recognize an acceptable address in any field provided")
78
+ COMPROMISED = Quality.new(value: "COMPROMISED", description: "The address may have been modified by a man in the middle")
79
+
80
+ def self.for(value)
81
+ Qualities.send(value.to_sym)
82
+ end
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,22 @@
1
+ require "httpx"
2
+
3
+ module Swisspost
4
+ class Auth
5
+ AUTH_URL = "https://api.post.ch/OAuth/token"
6
+
7
+ def get_access_token(api_scope)
8
+ response = HTTPX.with(headers: {
9
+ "Content-Type" => "application/x-www-form-urlencoded",
10
+ }).post(AUTH_URL, form: {
11
+ grant_type: "client_credentials",
12
+ client_id: "bdf1cf1f9133fcde0087c5ed95f9a488",
13
+ client_secret: "151a4c935dd6bc83d3488a69e2e5fd02",
14
+ scope: api_scope,
15
+ })
16
+
17
+ response.raise_for_status
18
+
19
+ response.json["access_token"]
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,81 @@
1
+ require "dry-validation"
2
+ require_relative "model/address"
3
+ require_relative "model/barcode_item"
4
+ require_relative "model/validation_error"
5
+ require_relative "base_service"
6
+ require_relative "types"
7
+
8
+ module Swisspost
9
+ class BarcodeService < BaseService
10
+ API_SCOPE = "DCAPI_BARCODE_READ"
11
+ API_URL = "https://dcapi.apis.post.ch/barcode/v1"
12
+ FRANKING_LICENSE = "60170283"
13
+
14
+ GENERATE_VALIDATOR = Dry::Validation.Contract do
15
+ params do
16
+ required(:sender).value(Types::Instance(Model::Address))
17
+ required(:recipient).value(Types::Instance(Model::Address))
18
+ required(:item).value(Types::Instance(Model::BarcodeItem))
19
+ end
20
+ end
21
+
22
+ GenerateResult = Struct.new(:image, :file_type, keyword_init: true)
23
+
24
+ def generate(attributes)
25
+ path = "/generateAddressLabel"
26
+
27
+ result = GENERATE_VALIDATOR.call(attributes)
28
+ raise Model::ValidationError, result.errors.to_h.inspect if result.failure?
29
+
30
+ validated_data = result.to_h
31
+ sender = validated_data[:sender]
32
+ recipient = validated_data[:recipient]
33
+ item = validated_data[:item]
34
+
35
+ client = httpx_oauth(API_SCOPE)
36
+
37
+ payload = {
38
+ language: 'DE',
39
+ frankingLicense: FRANKING_LICENSE,
40
+ ppFranking: false,
41
+ customer: {
42
+ name1: sender.full_name,
43
+ street: sender.full_street,
44
+ zip: sender.zip,
45
+ city: sender.city,
46
+ },
47
+ labelDefinition: {
48
+ labelLayout: 'A6',
49
+ printAddresses: 'ONLY_RECIPIENT',
50
+ imageFileType: 'PNG',
51
+ imageResolution: 300,
52
+ printPreview: false
53
+ },
54
+ item: {
55
+ recipient: {
56
+ name1: recipient.full_name,
57
+ street: recipient.street,
58
+ houseNo: recipient.house_number,
59
+ zip: recipient.zip,
60
+ city: recipient.city,
61
+ },
62
+ attributes: {
63
+ przl: [item.service_code],
64
+ weight: item.weight,
65
+ }
66
+ }
67
+ }
68
+
69
+ response = client.post(API_URL + path, json: payload)
70
+
71
+ response.raise_for_status
72
+
73
+ result = response.json
74
+
75
+ return GenerateResult.new(
76
+ image: result[:item][:label],
77
+ file_type: result[:labelDefinition][:imageFileType],
78
+ )
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,24 @@
1
+ require 'httpx'
2
+ require_relative "auth"
3
+
4
+ module Swisspost
5
+ class BaseService
6
+ def httpx_oauth(scope)
7
+ @httpx_oauth ||= HTTPX.with(headers: {
8
+ "Authorization" => "Bearer #{access_token(scope)}",
9
+ "Content-Type" => "application/json"
10
+ })
11
+ end
12
+
13
+ def httpx_apikey
14
+ @httpx_apikey ||= HTTPX.with(headers: {
15
+ "X-Apim-Api-Key" => "77b97c82-5324-4964-b97c-825324f964cb",
16
+ "Content-Type" => "application/json"
17
+ })
18
+ end
19
+
20
+ def access_token(scope)
21
+ @access_token ||= Auth.new.get_access_token(scope)
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,48 @@
1
+ require_relative "validation_error"
2
+
3
+ module Swisspost
4
+ module Model
5
+ class Address
6
+ attr_reader :first_name, :last_name, :street, :house_number, :zip, :city
7
+
8
+ VALIDATOR = Dry::Validation.Contract do
9
+ params do
10
+ # Define all keys and their expected base types
11
+ required(:first_name).filled(:string)
12
+ required(:last_name).filled(:string)
13
+ required(:street).filled(:string)
14
+ required(:house_number).filled(:string)
15
+ required(:zip).value(:integer)
16
+ required(:city).filled(:string)
17
+ end
18
+
19
+ # Add more specific rules for keys that pass the initial check
20
+ rule(:zip) do
21
+ # Swiss ZIP codes are 4 digits, from 1000 to 9999
22
+ key.failure('must be a 4-digit Swiss ZIP code') unless value.between?(1000, 9999)
23
+ end
24
+ end
25
+
26
+ def initialize(attributes)
27
+ result = VALIDATOR.call(attributes)
28
+ raise ValidationError, result.errors.to_h.inspect if result.failure?
29
+
30
+ validated_data = result.to_h
31
+ @first_name = validated_data[:first_name]
32
+ @last_name = validated_data[:last_name]
33
+ @street = validated_data[:street]
34
+ @house_number = validated_data[:house_number]
35
+ @zip = validated_data[:zip]
36
+ @city = validated_data[:city]
37
+ end
38
+
39
+ def full_name
40
+ [@first_name, @last_name].compact.join(" ")
41
+ end
42
+
43
+ def full_street
44
+ [@street, @house_number].compact.join(" ")
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,34 @@
1
+ require_relative "validation_error"
2
+
3
+ module Swisspost
4
+ module Model
5
+ class BarcodeItem
6
+ attr_reader :service_code, :weight
7
+
8
+ VALIDATOR = Dry::Validation.Contract do
9
+ params do
10
+ required(:weight).value(:integer)
11
+ required(:service_code).value(:string)
12
+ end
13
+
14
+ rule(:weight) do
15
+ key.failure('must be greater than 0') if value <= 0
16
+ end
17
+
18
+ rule(:service_code) do
19
+ allowed_services = %w[ECO PRI APOST BPOST]
20
+ key.failure("must be one of: #{allowed_services.join(', ')}") unless allowed_services.include?(value)
21
+ end
22
+ end
23
+
24
+ def initialize(attributes)
25
+ result = VALIDATOR.call(attributes)
26
+ raise ValidationError, result.errors.to_h.inspect if result.failure?
27
+
28
+ validated_data = result.to_h
29
+ @weight = validated_data[:weight]
30
+ @service_code = validated_data[:service_code]
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,6 @@
1
+ module Swisspost
2
+ module Model
3
+ class ValidationError < StandardError
4
+ end
5
+ end
6
+ end
@@ -0,0 +1,41 @@
1
+ require "dry-validation"
2
+ require_relative "model/address"
3
+ require_relative "base_service"
4
+
5
+ module Swisspost
6
+ class PriceService < BaseService
7
+ API_URL = "https://vsc.apis.post.ch/product/v1"
8
+
9
+ PRODUCTS_VALIDATOR = Dry::Validation.Contract do
10
+ VALID_FORMATS = %w[B4 B5 MB PK SP RL FF].freeze
11
+ VALID_COUNTRIES = %w[AF EG AX AL DZ VI UM AD AO AI AQ AG GQ AR AM AW AZ ET AU BS BH BD BB BY BE BZ BJ BM BT BO BQ BA BW BV BR IO BN BG BF BI KY CL CN CK CR CW DK DE DJ DM DO EC CI SV ER EE SZ FK FO FJ FI FR GF PF TF GA GM GE GH GI GD GR GL GB GP GU GT GG GN GW GY HT HM HN HK IN ID IQ IR IE IS IL IT JM JP YE JE JO KH CM CA CV KZ KE KG KI CC CO KM CD CG KP KR XZ HR CU KW LA LS LV LB LR LY LI LT LU MO MG MW MY MV ML MT IM MP MA MH MQ MR MU YT MX FM MD MC MN ME MS MZ MM NA NR NP NC NZ NI NL NE NG NU MK NF NO OM AT PK PS PW PA PG PY PE PH PN PL PT PR QA RE RO RU RW SB ZM AS WS SM SA SE CH SN RS SC SL SG SK SI SO ES LK BL KN SH LC SX MF PM ST VC ZA SD GS SS SR SJ SY TJ TW TZ TH TL TG TK TO TT TD CZ TN TR TM TC TV UG UA HU UY US UZ VU VA VE AE US VN VG WF CX EH CF ZW CY].freeze
12
+
13
+ params do
14
+ required(:country).value(:string, included_in?: VALID_COUNTRIES)
15
+ required(:format).filled(:string, included_in?: VALID_FORMATS)
16
+ required(:weight).value(:integer, gteq?: 0)
17
+ end
18
+ end
19
+
20
+ def products(country, format, weight)
21
+ path = "/products"
22
+
23
+ result = PRODUCTS_VALIDATOR.call(country: country, format: format, weight: weight)
24
+ raise ValidationError, result.errors.to_h.inspect if result.failure?
25
+
26
+ response = httpx_apikey.get(API_URL + path, params: {
27
+ isoCode: country,
28
+ format: format,
29
+ weight: weight,
30
+ })
31
+
32
+ response.raise_for_status
33
+
34
+ result = response.json
35
+
36
+ return result
37
+ end
38
+
39
+ Result = Struct.new(:address, :quality, keyword_init: true)
40
+ end
41
+ end
@@ -0,0 +1,5 @@
1
+ require 'dry-types'
2
+
3
+ module Types
4
+ include Dry.Types()
5
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Swisspost
4
+ VERSION = "0.1.0"
5
+ end
data/lib/swisspost.rb ADDED
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "swisspost/address_service"
4
+ require_relative "swisspost/barcode_service"
5
+ require_relative "swisspost/price_service"
6
+ require_relative "swisspost/version"
7
+
8
+ module Swisspost
9
+ class Error < StandardError; end
10
+ # Your code goes here...
11
+ end
data/sig/swisspost.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module Swisspost
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,123 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: swisspost
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Lukas_Skywalker
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: httpx
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '1.5'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: '1.5'
26
+ - !ruby/object:Gem::Dependency
27
+ name: dry-validation
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - "~>"
31
+ - !ruby/object:Gem::Version
32
+ version: '1.11'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: '1.11'
40
+ - !ruby/object:Gem::Dependency
41
+ name: cli-ui
42
+ requirement: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - "~>"
45
+ - !ruby/object:Gem::Version
46
+ version: '2.2'
47
+ type: :runtime
48
+ prerelease: false
49
+ version_requirements: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - "~>"
52
+ - !ruby/object:Gem::Version
53
+ version: '2.2'
54
+ - !ruby/object:Gem::Dependency
55
+ name: base64
56
+ requirement: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - ">="
59
+ - !ruby/object:Gem::Version
60
+ version: '0'
61
+ type: :runtime
62
+ prerelease: false
63
+ version_requirements: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - ">="
66
+ - !ruby/object:Gem::Version
67
+ version: '0'
68
+ description: A Ruby gem for interacting with Swiss Post APIs including parcel tracking,
69
+ address validation, and other postal services
70
+ email:
71
+ - git@lukasdiener.ch
72
+ executables:
73
+ - swisspost
74
+ extensions: []
75
+ extra_rdoc_files: []
76
+ files:
77
+ - ".devcontainer/devcontainer.json"
78
+ - ".rspec"
79
+ - ".standard.yml"
80
+ - CHANGELOG.md
81
+ - CODE_OF_CONDUCT.md
82
+ - LICENSE.txt
83
+ - README.md
84
+ - Rakefile
85
+ - exe/swisspost
86
+ - lib/swisspost.rb
87
+ - lib/swisspost/address_service.rb
88
+ - lib/swisspost/auth.rb
89
+ - lib/swisspost/barcode_service.rb
90
+ - lib/swisspost/base_service.rb
91
+ - lib/swisspost/model/address.rb
92
+ - lib/swisspost/model/barcode_item.rb
93
+ - lib/swisspost/model/validation_error.rb
94
+ - lib/swisspost/price_service.rb
95
+ - lib/swisspost/types.rb
96
+ - lib/swisspost/version.rb
97
+ - sig/swisspost.rbs
98
+ homepage: https://github.com/code-fabrik/swisspost
99
+ licenses:
100
+ - MIT
101
+ metadata:
102
+ allowed_push_host: https://rubygems.org
103
+ homepage_uri: https://github.com/code-fabrik/swisspost
104
+ source_code_uri: https://github.com/code-fabrik/swisspost
105
+ changelog_uri: https://github.com/code-fabrik/swisspost/blob/main/CHANGELOG.md
106
+ rdoc_options: []
107
+ require_paths:
108
+ - lib
109
+ required_ruby_version: !ruby/object:Gem::Requirement
110
+ requirements:
111
+ - - ">="
112
+ - !ruby/object:Gem::Version
113
+ version: 3.1.0
114
+ required_rubygems_version: !ruby/object:Gem::Requirement
115
+ requirements:
116
+ - - ">="
117
+ - !ruby/object:Gem::Version
118
+ version: '0'
119
+ requirements: []
120
+ rubygems_version: 3.6.7
121
+ specification_version: 4
122
+ summary: Swiss Post API client for Ruby
123
+ test_files: []