pickpoint_api 0.1 → 0.2

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: 08af998b998f4ca9f2902135d967b5df4b5a31fe
4
- data.tar.gz: 484a27051f28e58a5a6fb4a93bd8d6dd6fd1d0e1
3
+ metadata.gz: ef1e97123ee49d134743d512ee9c86286ca1dafe
4
+ data.tar.gz: b4d7fe95f57f1cc33b08d6db78f68644d4d2761a
5
5
  SHA512:
6
- metadata.gz: b18c637a31a3741b4d3de4da5c907917a343e3faa2effb070938f066b31148fc0910d0495c0ebdc1483112e53e4b42fb89a81e0794af4ca64e925cc8b7a9d774
7
- data.tar.gz: 53c386ad19ca66bc492a5127c8c55b746d1a338254686c0b60e2fcd6812dc93a7b768f9432dd5dfd491c60c446b496b0c4c715128e9585a57851a07df9932d0c
6
+ metadata.gz: a58f2dc4bc46cfdb60baa7bd890da307cbca44625fa8c24ecab7e40a92d3f1aac9855bd1ace825cc2c821d1f0fd429013b6a63cb238941e4bcb5d2226a5be48e
7
+ data.tar.gz: 57f86a3c6d8e48d048f986c13d7581b84fb564f814fbfca79680e2088fcffb578b260fd8f5fd9acc4e7e09f145564352f1d335e6853b52886886454acadbe369
data/.gitignore CHANGED
@@ -0,0 +1 @@
1
+ /coverage
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --default-path spec
2
+ --color
data/.travis.yml CHANGED
@@ -2,6 +2,6 @@ language: ruby
2
2
  rvm:
3
3
  - 2.1.0
4
4
  - 1.9.3
5
- install: gem install rspec
6
- script: "rspec spec/*"
5
+ install: gem install rspec coveralls
6
+ script: "rspec"
7
7
 
data/README.md CHANGED
@@ -1,27 +1,72 @@
1
1
  # Pickpoint API
2
2
 
3
3
  [![Build Status](https://travis-ci.org/kinderly/pickpoint_api.png?branch=master)](https://travis-ci.org/kinderly/pickpoint_api)
4
+ [![Gem Version](https://badge.fury.io/rb/pickpoint_api.png)](http://badge.fury.io/rb/pickpoint_api)
5
+ [![Coverage Status](https://coveralls.io/repos/kinderly/pickpoint_api/badge.png)](https://coveralls.io/r/kinderly/pickpoint_api)
6
+ [![Code Climate](https://codeclimate.com/github/kinderly/pickpoint_api.png)](https://codeclimate.com/github/kinderly/pickpoint_api)
4
7
 
5
8
  ## Description
6
9
 
7
- This gem provides a basic Ruby wrapper over [Pickpoint](http://pickpoint.ru/) API.
10
+ This gem provides a Ruby wrapper over [Pickpoint](http://pickpoint.ru/) API. All API methods documented by Feb 1 2014 are implemented.
8
11
 
9
- ## Usage
12
+ ## Installation
10
13
 
11
- ```ruby
12
- require('pickpoint_api')
14
+ You can install this gem with the following command:
13
15
 
14
- PickpointApi.session('login', 'password', test: true) do |s|
15
- postamats = s.postamat_list
16
+ ```bash
17
+ gem install pickpoint_api
18
+ ```
16
19
 
17
- s.create_sending(@my_sending_hash)
20
+ Or, if you are using Bundler, add it to your Gemfile:
18
21
 
19
- tracking_response = s.track_sending(@invoice_id_1)
22
+ ```ruby
23
+ gem pickpoint_api
24
+ ```
20
25
 
21
- labels_response_pdf = s.make_label([@invoice_id_1, @invoice_id_2])
26
+ If you desire to have the most up-do-date development version, add Git URL to the Gemfile:
27
+ ```ruby
28
+ gem pickpoint_api, git: 'git@github.com:kinderly/pickpoint_api.git'
29
+ ```
30
+
31
+ ## Usage
22
32
 
23
- reestr_response_pdf = s.make_reestr([@invoice_id_1, @invoice_id_2])
33
+ ```ruby
34
+ require('pickpoint_api')
24
35
 
36
+ PickpointApi.session('login', 'password', test: true) do |s|
37
+ result = s.create_sending(@my_sending_hash)
38
+ result = s.create_shipment(@my_shipment_hash)
39
+ result = s.make_return(invoice_id: @invoice_id)
40
+ result = s.make_return(sender_invoice_number: @order_number)
41
+ return_invoices_list = s.get_return_invoices_list(DateTime.parse('2014-01-01'), DateTime.now)
42
+ tracking_response = s.track_sending(@invoice_id)
43
+ tracking_response = s.track_sending(nil, @order_number)
44
+ info = s.sending_info(@invoice_id)
45
+ info = s.sending_info(nil, @order_number)
46
+ cost_result = s.get_delivery_cost(@delivery_hash)
47
+ courier_result = s.courier(@courier_hash)
48
+ courier_cancel_result = s.courier_cancel(@courier_order_number)
49
+ reestr_response_pdf = s.make_reestr(@invoice_id)
50
+ reestr_response_pdf = s.make_reestr([@invoice_id1, @invoice_id2])
51
+ reestr_numbers = s.make_reestr_number(@invoice_id)
52
+ reestr_numbers = s.make_reestr_number([@invoice_id1, @invoice_id2])
53
+ reestr_pdf = get_reestr(@invoice_id)
54
+ reestr_pdf = get_reestr(nil, @reestr_number)
55
+ labels_pdf = make_label(invoice_id)
56
+ labels_pdf = make_label([@invoice_id1, @invoice_id2])
57
+ zebra_labels_pdf = make_zlabel(invoice_id)
58
+ zebra_labels_pdf = make_zlabel([@invoice_id1, @invoice_id2])
59
+ cities = s.city_list
60
+ postamats = s.postamat_list
61
+ zone_info = s.get_zone(@city_name)
62
+ zone_info = s.get_zone(@city_name, @postamat_num)
63
+ result = s.get_money_return_order(@ikn, @document_number, @date_from, @date_to)
64
+ result = s.get_product_return_order(@ikn, @document_number, @date_from, @date_to)
65
+ result = s.enclose_info(@barcode)
66
+ history = s.track_sendings(invoice_id)
67
+ history = s.track_sendings([@invoice_id1, @invoice_id2])
68
+ states = s.get_states
69
+ registered_invoices = s.get_invoices_change_state(101, @date_from, @date_to)
25
70
  end
26
71
  ```
27
72
 
@@ -32,6 +77,10 @@ require ('pickpoint_api')
32
77
 
33
78
  session = PickpointApi::Session.new(test: true)
34
79
  session.login('login', 'password')
35
- tracking_response = session.track_sending(@invoice_id_1)
80
+ cities = s.city_list
81
+ postamats = s.postamat_list
82
+ zone_info = s.get_zone(@city_name)
36
83
  session.logout
37
84
  ```
85
+
86
+ Please refer to the official [Pickpoint](http://pickpoint.ru/) API documentation to learn about method meanings, expected request arguments, data format etc.
data/lib/pickpoint_api.rb CHANGED
@@ -1,4 +1,18 @@
1
+ require('logger')
2
+
1
3
  module PickpointApi
4
+ VERSION = "0.2"
5
+
6
+ @logger = Logger.new($stdout)
7
+ @logger.level = Logger::INFO
8
+
9
+ def self.logger=(logger)
10
+ @logger = logger
11
+ end
12
+
13
+ def self.logger
14
+ @logger
15
+ end
2
16
 
3
17
  def self.session login, password, hash = {}
4
18
  begin
@@ -8,7 +22,7 @@ module PickpointApi
8
22
  rescue => ex
9
23
  raise ::PickpointApi::Exceptions::ApiError, ex.message
10
24
  ensure
11
- if !session.nil? && session.state != :closed
25
+ if !session.nil? && session.state == :started
12
26
  session.logout
13
27
  end
14
28
  end
@@ -16,6 +30,8 @@ module PickpointApi
16
30
 
17
31
  end
18
32
 
33
+ require_relative('pickpoint_api/exceptions.rb')
19
34
  require_relative('pickpoint_api/constants.rb')
20
35
  require_relative('pickpoint_api/session.rb')
21
- require_relative('pickpoint_api/exceptions.rb')
36
+
37
+
@@ -0,0 +1,252 @@
1
+ require('net/http')
2
+ require('json')
3
+ require('date')
4
+
5
+ module PickpointApi::ApiActions
6
+ include(::PickpointApi::Exceptions)
7
+ include(::PickpointApi::Constants)
8
+
9
+ # Начало сессии
10
+ def login(login, password)
11
+ ensure_session_state(:new)
12
+ data = {'Login' => login, 'Password' => password}
13
+ response = json_request(:login, data)
14
+ check_for_error(response, 'ErrorMessage', LoginError) do
15
+ @state = :error
16
+ end
17
+
18
+ @session_id = response['SessionId']
19
+ @state = :started
20
+ nil
21
+ end
22
+
23
+ # Завершение сессии
24
+ def logout
25
+ ensure_session_state
26
+ data = {'SessionId' => @session_id}
27
+ response = json_request(:logout, data)
28
+
29
+ if response['Success'] == true
30
+ @state = :closed
31
+ @session_id = nil
32
+ else
33
+ @state = :error
34
+ raise LogoutError
35
+ end
36
+ end
37
+
38
+ # Регистрация одноместных отправлений
39
+ def create_sending(data)
40
+ sendings_request(:create_sending, data)
41
+ end
42
+
43
+ # Регистрация многоместных отправлений
44
+ def create_shipment(data)
45
+ sendings_request(:create_shipment, data)
46
+ end
47
+
48
+ # Создание отправления клиентского возврата
49
+ def make_return(options)
50
+ ensure_session_state
51
+
52
+ if !options[:invoice_id].nil? && !options[:sender_invoice_number].nil?
53
+ raise ApiError 'Only :invoice_id or :sender_invoice_number parameter should be specified'
54
+ end
55
+
56
+ data = {
57
+ 'SessionId' => @session_id
58
+ }
59
+
60
+ if !options[:invoice_id].nil?
61
+ data['InvoiceNumber'] = options[:invoice_id]
62
+ elsif !options[:sender_invoice_number].nil?
63
+ data['GCInvoiceNumber'] = options[:sender_invoice_number]
64
+ else
65
+ raise ApiError 'Either :invoice_id or :sender_invoice_number parameter should be specified'
66
+ end
67
+
68
+ response = json_request(:make_return, data)
69
+
70
+ errors = res.select do |x|
71
+ !x['Error'].nil? && !x['Error'].empty?
72
+ end.map do |x|
73
+ x['Error']
74
+ end
75
+
76
+ if !errors.empty
77
+ raise ApiError errors.join(';')
78
+ end
79
+
80
+ res
81
+ end
82
+
83
+ # Получение списка возвратных отправлений
84
+ def get_return_invoices_list(date_from, date_to = DateTime.now)
85
+ ensure_session_state
86
+ data = {
87
+ 'SessionId' => @session_id,
88
+ 'DateFrom' => date_from.strftime(DATE_FORMAT),
89
+ 'DateTo' => date_to.strftime(DATE_FORMAT)
90
+ }
91
+ res = json_request(:get_return_invoice_list, data)
92
+ check_for_error(res, 'Error')
93
+ end
94
+
95
+ # Мониторинг отправления
96
+ def track_sending(invoice_id = nil, sender_invoice_number = nil)
97
+ request_by_invoice_id(:track_sending, invoice_id, sender_invoice_number)
98
+ end
99
+
100
+ # Получение информации по отправлению
101
+ def sending_info(invoice_id = nil, sender_invoice_number = nil)
102
+ request_by_invoice_id(:sending_info, invoice_id, sender_invoice_number)
103
+ end
104
+
105
+ # Получение стоимости доставки
106
+ def get_delivery_cost(options)
107
+ ensure_session_state
108
+
109
+ if !options[:invoice_ids].nil? && !options[:sender_invoice_numbers].nil?
110
+ raise ApiError 'Only :invoice_ids or :sender_invoice_numbers parameter should be specified'
111
+ end
112
+
113
+ data = if !options[:invoice_ids].nil?
114
+ options[:invoice_ids].map do |invoice_id|
115
+ {'InvoiceNumber' => invoice_id}
116
+ end
117
+ elsif !options[:sender_invoice_numbers].nil?
118
+ options[:invoice_ids].map do |invoice_id|
119
+ {'SenderInvoiceNumber' => invoice_id}
120
+ end
121
+ else
122
+ raise ApiError 'Either :invoice_ids or :sender_invoice_numbers parameter should be specified'
123
+ end
124
+
125
+ data = attach_session_id('Sendings', data)
126
+ json_request(:get_delivery_cost, data)
127
+ end
128
+
129
+ # Вызов курьера
130
+ def courier(data)
131
+ ensure_session_state
132
+ data = data.clone
133
+ data['SessionId'] = @session_id
134
+ res = json_request(:courier, data)
135
+ check_for_error(res, 'ErrorMessage', CourierError)
136
+ end
137
+
138
+ # Отмена вызова курьера
139
+ def courier_cancel(courier_order_number)
140
+ ensure_session_state
141
+ data = attach_session_id('OrderNumber', courier_order_number)
142
+ res = json_request(:courier_cancel, data)
143
+ res['Canceled']
144
+ end
145
+
146
+ # Формирование реестра по списку отправлений в PDF
147
+ def make_reestr(invoice_id)
148
+ request_by_invoice_ids(invoice_id, :make_reestr)
149
+ end
150
+
151
+ # Формирование реестра (по списку отправлений)
152
+ def make_reestr_number(invoice_ids)
153
+ ensure_session_state
154
+ response = request_by_invoice_ids(invoice_ids, :make_reestr_number)
155
+ res = JSON.parse(response)
156
+ check_for_error(res, 'ErrorMessage')
157
+ res['Numbers']
158
+ end
159
+
160
+ # Получение созданного реестра в PDF
161
+ def get_reestr(invoice_id = nil, reestr_number = nil)
162
+ ensure_session_state
163
+ data = {
164
+ 'SessionId' => @session_id
165
+ }
166
+ data['InvoiceNumber'] = invoice_id if !invoice_id.nil?
167
+ data['ReestrNumber'] = reestr_number if !reestr_number.nil?
168
+ response = execute_action(:get_reestr, data)
169
+
170
+ if response.start_with?('Error')
171
+ raise ApiError, response
172
+ else
173
+ return response
174
+ end
175
+ end
176
+
177
+ # Формирование этикеток в PDF
178
+ def make_label(invoice_id)
179
+ request_by_invoice_ids(invoice_id, :make_label)
180
+ end
181
+
182
+ # Формирование этикеток в PDF для принтера Zebra
183
+ def make_zlabel(invoice_id)
184
+ request_by_invoice_ids(invoice_id, :make_zlabel)
185
+ end
186
+
187
+ # Получение списка городов
188
+ def city_list
189
+ parameterless_request(:city_list)
190
+ end
191
+
192
+ # Получение списка терминалов
193
+ def postamat_list
194
+ parameterless_request(:postamat_list)
195
+ end
196
+
197
+ # Получение информации по зонам
198
+ def get_zone(city, pt = nil)
199
+ ensure_session_state
200
+ data = {
201
+ 'SessionId' => @session_id,
202
+ 'FromCity' => city
203
+ }
204
+
205
+ if !pt.nil?
206
+ data['ToPT'] = pt
207
+ end
208
+
209
+ json_request(:get_zone, data)
210
+ end
211
+
212
+ # Получение акта возврата денег
213
+ def get_money_return_order(ikn, document_number, date_from, date_to = DateTime.now)
214
+ return_request(:get_money_return_order, ikn, document_number, date_from, date_to)
215
+ end
216
+
217
+ # Получение акта возврата товара
218
+ def get_product_return_order(ikn, document_number, date_from, date_to = DateTime.now)
219
+ return_request(:get_product_return_order, ikn, document_number, date_from, date_to)
220
+ end
221
+
222
+ # Получение информации по вложимому
223
+ def enclose_info(barcode)
224
+ ensure_session_state
225
+ data = attach_session_id('Barcode', barcode)
226
+ res = json_request(:enclose_info, data)
227
+ check_for_error(res, 'Error')
228
+ end
229
+
230
+ # Получение истории по списку отправлений
231
+ def track_sendings(invoice_id)
232
+ request_by_invoice_ids(invoice_id, :track_sendings)
233
+ end
234
+
235
+ # Получение справочника статусов отправления
236
+ def get_states
237
+ parameterless_request(:get_states)
238
+ end
239
+
240
+ # Получение списка отправлений, прошедших этап (статус)
241
+ def get_invoices_change_state(state, date_from, date_to = DateTime.now)
242
+ ensure_session_state
243
+ data = {
244
+ 'SessionId' => @session_id,
245
+ 'DateFrom' => date_from.strftime(DATE_FORMAT),
246
+ 'DateTo' => date_to.strftime(DATE_FORMAT),
247
+ 'State' => state
248
+ }
249
+ json_request(:get_invoices_change_state, data)
250
+ end
251
+
252
+ end
@@ -4,6 +4,8 @@ module PickpointApi::Constants
4
4
  API_TEST_PATH = '/apitest'
5
5
  API_PROD_PATH = '/api'
6
6
 
7
+ DATE_FORMAT = '%d.%m.%y'
8
+
7
9
  ACTIONS = {
8
10
  login:
9
11
  {
@@ -1,5 +1,9 @@
1
1
  module PickpointApi::Exceptions
2
2
 
3
3
  ApiError = Class.new(StandardError)
4
-
4
+ InvalidSessionState = Class.new(ApiError)
5
+ LoginError = Class.new(ApiError)
6
+ LogoutError = Class.new(ApiError)
7
+ UnknownApiAction = Class.new(ApiError)
8
+ CourierError = Class.new(ApiError)
5
9
  end
@@ -1,7 +1,10 @@
1
- require('net/http')
2
- require('json')
1
+ require_relative('api_actions.rb')
3
2
 
4
3
  class PickpointApi::Session
4
+ include(::PickpointApi::Exceptions)
5
+ include(::PickpointApi::Constants)
6
+ include(::PickpointApi::ApiActions)
7
+
5
8
  attr_reader :state
6
9
  attr_reader :test
7
10
 
@@ -10,130 +13,101 @@ class PickpointApi::Session
10
13
  @test = hash[:test] == true
11
14
  end
12
15
 
13
- def login(login, password)
14
- if @state!= :new
15
- return nil
16
- end
17
-
18
- data = {'Login' => login, 'Password' => password}
19
- response = execute_action(:login, data)
20
- response = JSON.parse(response)
16
+ private
21
17
 
22
- if response['ErrorMessage'].nil? && !response['SessionId'].nil?
23
- @session_id = response['SessionId']
24
- @state = :started
18
+ def check_for_error(response, error_field, error = ApiError)
19
+ if !response[error_field].nil? && !response[error_field].empty?
20
+ yield if block_given?
21
+ raise error, response[error_field]
25
22
  else
26
- @state = :error
27
- raise ::PickpointApi::Exceptions::ApiError, response['ErrorMessage']
23
+ response
28
24
  end
29
25
  end
30
26
 
31
- def logout
32
- if !@session_id.nil? && @state == :started
33
- data = {'SessionId' => @session_id}
34
- response = execute_action :logout, data
35
- response = JSON.parse(response)
36
- if response['Success']
37
- @state = :closed
38
- @session_id = nil
39
- return true
40
- else
41
- return false
42
- end
43
- else
44
- return false
45
- end
27
+ def sendings_request(action, data)
28
+ ensure_session_state
29
+ data = attach_session_id(data, 'Sendings')
30
+ json_request(action, data)
46
31
  end
47
32
 
48
- def create_sending(data)
49
- if @state == :started
50
- data = attach_session_id(data, 'Sendings')
51
- response = execute_action(:create_sending, data)
52
- response = JSON.parse(response)
53
- end
33
+ def parameterless_request(action)
34
+ ensure_session_state
35
+ response = execute_action(action)
36
+ JSON.parse(response)
54
37
  end
55
38
 
56
- def track_sending(invoice_id)
57
- if @state != :started
58
- return nil
59
- end
60
-
61
- data = invoice_id
62
- data = attach_session_id(data, 'InvoiceNumber')
63
- response = execute_action(:track_sending, data)
64
-
65
- if response.nil? || response.empty?
66
- return nil
39
+ def ensure_session_state(state = :started)
40
+ if @state != state
41
+ raise InvalidSessionState
67
42
  end
68
-
69
- response = JSON.parse(response)
70
43
  end
71
44
 
72
- def postamat_list
73
- if @state == :started
74
- response = execute_action(:postamat_list)
75
- response = JSON.parse(response)
76
- end
45
+ def json_request(action, data)
46
+ response = execute_action(action, data)
47
+ JSON.parse(response)
77
48
  end
78
49
 
79
- def make_label(invoice_id)
80
- if @state != :started
81
- return nil
82
- end
83
-
84
- if invoice_id.kind_of?(Array)
85
- data = invoice_id
86
- elsif
87
- data = [invoice_id]
50
+ def request_by_invoice_ids(invoice_ids, action)
51
+ ensure_session_state
52
+ data = if invoice_ids.kind_of?(Array)
53
+ invoice_ids
54
+ else
55
+ [invoice_ids]
88
56
  end
89
57
 
90
58
  data = attach_session_id(data,'Invoices')
91
- response = execute_action(:make_label, data)
59
+ response = execute_action(action, data)
92
60
 
93
- if response.start_with?("Error")
94
- raise ::PickpointApi::Exceptions::ApiError, response
95
- return nil
61
+ if response.start_with?('Error')
62
+ raise ApiError, response
96
63
  else
97
64
  return response
98
65
  end
99
66
  end
100
67
 
101
- def make_reestr(invoice_id)
102
- if @state != :started
103
- return nil
104
- end
68
+ def return_request(action, ikn, document_number, date_from, date_to = DateTime.now)
69
+ ensure_session_state
70
+ data = {
71
+ 'SessionId' => @session_id,
72
+ 'IKN' => ikn,
73
+ 'DocumentNumber' => document_number,
74
+ 'DateFrom' => date_from.strftime(DATE_FORMAT),
75
+ 'DateEnd' => date_to.strftime(DATE_FORMAT)
76
+ }
77
+ json_request(action, data)
78
+ check_for_error(res, 'Error')
79
+ end
105
80
 
106
- if invoice_id.kind_of?(Array)
107
- data = invoice_id
108
- elsif
109
- data = [invoice_id]
110
- end
81
+ def request_by_invoice_id(action, invoice_id = nil, sender_invoice_number = nil)
82
+ ensure_session_state
83
+ data = {
84
+ 'SessionId' => @session_id
85
+ }
111
86
 
112
- data = attach_session_id(data,'Invoices')
113
- response = execute_action(:make_reestr, data)
87
+ if !invoice_id.nil?
88
+ data['InvoiceNumber'] = invoice_id
89
+ end
114
90
 
115
- if response.start_with?("Error")
116
- raise ::PickpointApi::Exceptions::ApiError, response
117
- return nil
118
- else
119
- return response
91
+ if !sender_invoice_number.nil?
92
+ data['SenderInvoiceNumber'] = sender_invoice_number
120
93
  end
121
- end
122
94
 
123
- private
95
+ json_request(action, data)
96
+ end
124
97
 
125
98
  def api_path
126
99
  if @test
127
- ::PickpointApi::Constants::API_TEST_PATH
100
+ API_TEST_PATH
128
101
  else
129
- ::PickpointApi::Constants::API_PROD_PATH
102
+ API_PROD_PATH
130
103
  end
131
104
  end
132
105
 
133
106
  def create_request(action)
134
- action_config = ::PickpointApi::Constants::ACTIONS[action]
107
+ action_config = ACTIONS[action]
108
+
135
109
  if action_config.nil?
136
- return nil
110
+ raise UnknownApiAction, action
137
111
  end
138
112
 
139
113
  action_path = "#{api_path}#{action_config[:path]}"
@@ -145,7 +119,6 @@ class PickpointApi::Session
145
119
  end
146
120
 
147
121
  req.content_type = 'application/json'
148
-
149
122
  req
150
123
  end
151
124
 
@@ -157,23 +130,36 @@ class PickpointApi::Session
157
130
  end
158
131
 
159
132
  def execute_action(action, data = {})
160
- req = create_request action
161
-
162
- if req.nil?
163
- return nil
164
- end
165
-
133
+ logger.debug("Request: action: #{action}; data: #{data.inspect}")
134
+ req = create_request(action)
166
135
  req.body = data.to_json
167
-
168
136
  response = send_request(req)
137
+ log_response(response)
138
+
139
+ if response.code != '200'
140
+ raise ApiError, response.body
141
+ end
169
142
 
170
143
  response.body
171
144
  end
172
145
 
173
146
  def send_request(req)
174
- ::Net::HTTP.start(::PickpointApi::Constants::API_HOST, ::PickpointApi::Constants::API_PORT) do |http|
147
+ ::Net::HTTP.start(API_HOST, API_PORT) do |http|
175
148
  http.request(req)
176
149
  end
177
150
  end
178
151
 
152
+ def log_response(response)
153
+ if !response.body.nil?
154
+ if response.body.start_with?('%PDF')
155
+ logger.debug("Response: #{response.code}; data: PDF")
156
+ else
157
+ logger.debug("Response: #{response.code}; data: #{response.body[0,200]}#{response.body.size > 200 ? '...' : ''}")
158
+ end
159
+ end
160
+ end
161
+
162
+ def logger
163
+ ::PickpointApi.logger
164
+ end
179
165
  end
@@ -1,6 +1,8 @@
1
+ require_relative('./lib/pickpoint_api.rb')
2
+
1
3
  Gem::Specification.new do |s|
2
4
  s.name = "pickpoint_api"
3
- s.version = "0.1"
5
+ s.version = ::PickpointApi::VERSION
4
6
  s.authors = ["Kinderly LTD"]
5
7
  s.email = ["nuinuhin@gmail.com"]
6
8
  s.homepage = "http://github.com/kinderly/pickpoint_api"
@@ -0,0 +1,137 @@
1
+ require_relative '../spec_helper.rb'
2
+
3
+ include DummyData
4
+
5
+ describe ::PickpointApi::Session do
6
+
7
+ before(:each) do
8
+ ::HttpMocking.clear_response_queue
9
+ @session = ::PickpointApi::Session.new(test: true)
10
+ ::HttpMocking.enqueue_response(LOGIN_SUCCESSFUL)
11
+ @session.login('login', 'password')
12
+ end
13
+
14
+ it 'should create instance' do
15
+ @session = ::PickpointApi::Session.new(test: true)
16
+ expect(@session).not_to be_nil
17
+ expect(@session.test).to eq true
18
+ expect(@session.state).to eq :new
19
+ end
20
+
21
+ it 'should raise error on invalid session state' do
22
+ ::HttpMocking.enqueue_response(LOGOUT_SUCCESSFUL)
23
+ @session.logout
24
+ expect {@session.city_list}.to raise_error ::PickpointApi::Exceptions::InvalidSessionState
25
+ end
26
+
27
+ describe '.login' do
28
+ it 'should log-in' do
29
+ expect(@session.state).to eq :started
30
+ end
31
+
32
+ it 'should handle incorrect login' do
33
+ @session = ::PickpointApi::Session.new(test: true)
34
+ ::HttpMocking.enqueue_response(LOGIN_FAILED)
35
+ expect { @session.login('login', 'password') }.to raise_error ::PickpointApi::Exceptions::LoginError
36
+ expect(@session.state).to eq(:error)
37
+ end
38
+ end
39
+
40
+ describe '.logout' do
41
+ it 'should log out' do
42
+ ::HttpMocking.enqueue_response(LOGOUT_SUCCESSFUL)
43
+ @session.logout
44
+ expect(@session.state).to eq(:closed)
45
+ end
46
+
47
+ it 'should raise error on logout fail' do
48
+ ::HttpMocking.enqueue_response(LOGOUT_FAIL)
49
+ expect{@session.logout}.to raise_error ::PickpointApi::Exceptions::LogoutError
50
+ expect(@session.state).to eq(:error)
51
+ end
52
+ end
53
+
54
+ describe '.create_sending' do
55
+ it 'should handle successfull request' do
56
+ ::HttpMocking.enqueue_response(CREATE_SENDING_SUCCESSFUL)
57
+ res = @session.create_sending(SAMPLE_SENDING_REQUEST)
58
+ expect(res['CreatedSendings']).not_to be_empty
59
+ expect(res['RejectedSendings']).to be_empty
60
+ end
61
+ end
62
+
63
+ [:track_sending, :sending_info].each do |m|
64
+ describe ".#{m}" do
65
+ it 'should handle successfull request' do
66
+ ::HttpMocking.enqueue_response({}.to_json)
67
+ res = @session.send(m, '21121312')
68
+ end
69
+ end
70
+ end
71
+
72
+ [:make_label, :make_zlabel, :make_reestr].each do |m|
73
+ describe ".#{m}" do
74
+ it 'should handle successfull request' do
75
+ ::HttpMocking.enqueue_response(PDF_SUCCESS)
76
+ @session.send(m, '12345')
77
+ end
78
+
79
+ it 'should handle multiple invoices' do
80
+ ::HttpMocking.enqueue_response(PDF_SUCCESS)
81
+ @session.send(m, ['123123','123213'])
82
+ end
83
+
84
+ it 'should handle api error' do
85
+ ::HttpMocking.enqueue_response(PDF_ERROR)
86
+ expect{@session.send(m, ['123123'])}.to raise_error PickpointApi::Exceptions::ApiError
87
+ end
88
+ end
89
+ end
90
+
91
+ describe '.city_list' do
92
+ it 'should handle successfull request' do
93
+ ::HttpMocking.enqueue_response(CITY_LIST_SUCCESS)
94
+ res = @session.city_list
95
+ expect(res.count).to eq(2)
96
+ end
97
+ end
98
+
99
+ describe '.get_states' do
100
+ it 'should handle successfull request' do
101
+ ::HttpMocking.enqueue_response(STATES_SUCCESS)
102
+ res = @session.get_states
103
+ expect(res.count).to eq(3)
104
+ end
105
+ end
106
+
107
+ describe '.postamat_list' do
108
+ it 'should handle successfull request' do
109
+ ::HttpMocking.enqueue_response({}.to_json)
110
+ @session.postamat_list
111
+ end
112
+ end
113
+
114
+ describe '.get_zone' do
115
+ it 'should handle successfull request' do
116
+ ::HttpMocking.enqueue_response(ZONES_SUCCESS)
117
+ res = @session.get_zone('Some city', '7801-035')
118
+ expect(res['Error']).to be_nil
119
+ end
120
+ end
121
+
122
+ describe '.get_invoices_change_state' do
123
+ it 'should handle successfull request' do
124
+ ::HttpMocking.enqueue_response(GET_STATE_SUCCESS)
125
+ res = @session.get_invoices_change_state(102, DateTime.parse('2014-01-01'), DateTime.parse('2014-03-01'))
126
+ expect(res.count).to eq(1)
127
+ end
128
+ end
129
+
130
+ describe '.courier' do
131
+ it 'should handle successfull request' do
132
+ ::HttpMocking.enqueue_response('{}')
133
+ res = @session.courier({})
134
+ end
135
+ end
136
+
137
+ end
@@ -0,0 +1,48 @@
1
+ require('logger')
2
+ require_relative 'spec_helper.rb'
3
+
4
+ include DummyData
5
+
6
+ describe 'PickpointApi' do
7
+ before(:each) do
8
+ HttpMocking.clear_response_queue
9
+ end
10
+
11
+ it 'should run session' do
12
+ HttpMocking.enqueue_response(LOGIN_SUCCESSFUL)
13
+ HttpMocking.enqueue_response(LOGOUT_SUCCESSFUL)
14
+
15
+ PickpointApi.session('login', 'password', test:true) do |s|
16
+ end
17
+ end
18
+
19
+ it 'should write logs' do
20
+ PickpointApi.logger.level = Logger::UNKNOWN
21
+ PickpointApi.logger.info('INFO')
22
+ PickpointApi.logger.error('ERROR')
23
+ PickpointApi.logger.warn('WARNING')
24
+ PickpointApi.logger.fatal('FATAL')
25
+ PickpointApi.logger.debug('DEBUG')
26
+ end
27
+
28
+ it 'should assign logger' do
29
+ PickpointApi.logger = nil
30
+ PickpointApi.logger = Logger.new($stderr)
31
+ expect(PickpointApi.logger).not_to be_nil
32
+ end
33
+
34
+ it 'should handle session error' do
35
+ PickpointApi.logger.level = Logger::UNKNOWN
36
+
37
+ HttpMocking.enqueue_response(LOGIN_SUCCESSFUL)
38
+ HttpMocking.enqueue_response(PDF_ERROR)
39
+ HttpMocking.enqueue_response(LOGOUT_SUCCESSFUL)
40
+
41
+ expect do
42
+ PickpointApi.session('login', 'password', test:true) do |s|
43
+ s.make_label('111111')
44
+ end
45
+ end.to raise_error PickpointApi::Exceptions::ApiError
46
+ end
47
+
48
+ end
@@ -0,0 +1,7 @@
1
+ require 'coveralls'
2
+ Coveralls.wear!
3
+
4
+ require_relative './support/dummy_data.rb'
5
+ require_relative './support/http_mocking.rb'
6
+ require_relative '../lib/pickpoint_api.rb'
7
+
@@ -3,43 +3,89 @@
3
3
  require ('json')
4
4
 
5
5
  module DummyData
6
- LOGIN_SUCCESSFULL = {'SessionId' => '111111111'}.to_json
6
+
7
+ LOGIN_SUCCESSFUL = {'SessionId' => '111111111'}.to_json
8
+
7
9
  LOGIN_FAILED = {'ErrorMessage' => 'Неверный логин или пароль'}.to_json
8
- LOGOUT_SUCCESSFULL = {'Success' => true}.to_json
9
- CREATE_SENDING_SUCCESSFULL = {
10
- "CreatedSendings" => [
10
+
11
+ LOGOUT_SUCCESSFUL = {'Success' => true}.to_json
12
+ LOGOUT_FAIL = {'Success' => false}.to_json
13
+
14
+ CREATE_SENDING_SUCCESSFUL = {
15
+ 'CreatedSendings' => [
11
16
  {
12
- 'EDTN' => "14",
13
- 'IKN' => "9990000000",
17
+ 'EDTN' => '14',
18
+ 'IKN' => '9990000000',
14
19
  'Barcode' => '200819647155'
15
20
  }
16
21
  ],
17
- "RejectedSendings" => []
22
+ 'RejectedSendings' => []
23
+ }.to_json
24
+
25
+ PDF_SUCCESS = '%PDF'
26
+
27
+ PDF_ERROR = 'Error: Произошла ошибка'
28
+
29
+ CITY_LIST_SUCCESS = [
30
+ {'Id'=>3926841, 'Name'=>'Борзые', 'Owner_Id'=>923, 'RegionName'=>'Московская обл.'},
31
+ {'Id'=>3940057, 'Name'=>'Северный', 'Owner_Id'=>5, 'RegionName'=>'Московская обл.'}
32
+ ].to_json
33
+
34
+ STATES_SUCCESS = [
35
+ {'State'=>101, 'StateText'=>'Зарегистрирован'},
36
+ {'State'=>102, 'StateText'=>'Сформирован для передачи Логисту'},
37
+ {'State'=>103, 'StateText'=>'Развоз до ПТ самостоятельно'}
38
+ ].to_json
39
+
40
+ ZONES_SUCCESS = {
41
+ 'Error' => nil,
42
+ 'Zones' => [
43
+ {
44
+ 'DeliveryMax' => 2,
45
+ 'DeliveryMin' => 1,
46
+ 'FromCity' => 'Химки',
47
+ 'Koeff' => 1,
48
+ 'ToCity' => 'Санкт-Петербург',
49
+ 'ToPT' => '7801-035',
50
+ 'Zone' => '0'
51
+ }
52
+ ]
18
53
  }.to_json
19
54
 
20
- SAMPLE_SENDING_REQUEST = {
21
- "EDTN" => 14,
22
- "IKN" => "9990000000",
23
- "Invoice" => {
24
- "SenderCode" => 2121,
25
- "Description" => "A description",
26
- "RecipientName" => "John Doe",
27
- "PostamatNumber" => "6101-004",
28
- "MobilePhone" => "+79030000000",
29
- "Email" => nil,
30
- "PostageType" => "10003",
31
- "GettingType" => "101",
32
- "PayType" => "1",
33
- "Sum" => 4490.0,
34
- "SubEncloses" => [
55
+ GET_STATE_SUCCESS = [
56
+ {
57
+ "ChangeDT" => "16.01.14 00:28",
58
+ "State" => 112,
59
+ "StateMessage" => "Невостребованное",
60
+ "InvoiceNumber"=>"0000000000000",
61
+ "SenderInvoiceNumber"=>"00000"
62
+ }
63
+ ].to_json
64
+
65
+
66
+ SAMPLE_SENDING_REQUEST = [{
67
+ 'EDTN' => 14,
68
+ 'IKN' => '9990000000',
69
+ 'Invoice' => {
70
+ 'SenderCode' => 2121,
71
+ 'Description' => 'A description',
72
+ 'RecipientName' => 'John Doe',
73
+ 'PostamatNumber' => '6101-004',
74
+ 'MobilePhone' => '+79030000000',
75
+ 'Email' => nil,
76
+ 'PostageType' => '10003',
77
+ 'GettingType' => '101',
78
+ 'PayType' => '1',
79
+ 'Sum' => 4490.0,
80
+ 'SubEncloses' => [
35
81
  {
36
- "Line" => 1,
37
- "ProductCode" => 4559802,
38
- "GoodsCode" => "79380-555",
39
- "Name" => "Fire extinguisher large",
40
- "Price" => 4290.0
82
+ 'Line' => 1,
83
+ 'ProductCode' => 4559802,
84
+ 'GoodsCode' => '79380-555',
85
+ 'Name' => 'Fire extinguisher large',
86
+ 'Price' => 4290.0
41
87
  }]
42
88
  }
43
- }
89
+ }]
44
90
 
45
91
  end
@@ -1,12 +1,19 @@
1
1
  require 'net/http'
2
2
 
3
-
4
3
  module HttpMocking
5
4
 
6
- def self.set_next_response(response_body, code = 200, msg='OK')
5
+ def self.clear_response_queue
6
+ @responses = []
7
+ end
8
+
9
+ def self.enqueue_response(response_body, code = '200', msg='OK')
10
+ @responses ||= []
11
+ @responses.push([response_body, code, msg])
12
+
7
13
  Net::HTTP.any_instance.stub(:request) do |req|
8
- response = Net::HTTPResponse.new(1.0, code, msg)
9
- response.stub(:body => response_body)
14
+ next_response = @responses.shift
15
+ response = Net::HTTPResponse.new(1.0, next_response[1], next_response[2])
16
+ response.stub(:body => next_response[0])
10
17
  response
11
18
  end
12
19
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: pickpoint_api
3
3
  version: !ruby/object:Gem::Version
4
- version: '0.1'
4
+ version: '0.2'
5
5
  platform: ruby
6
6
  authors:
7
7
  - Kinderly LTD
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2014-03-03 00:00:00.000000000 Z
11
+ date: 2014-03-08 00:00:00.000000000 Z
12
12
  dependencies: []
13
13
  description: This gem provides a Ruby wrapper over Pickpoint API.
14
14
  email:
@@ -18,16 +18,19 @@ extensions: []
18
18
  extra_rdoc_files: []
19
19
  files:
20
20
  - ".gitignore"
21
+ - ".rspec"
21
22
  - ".travis.yml"
22
23
  - LICENSE
23
24
  - README.md
24
25
  - lib/pickpoint_api.rb
26
+ - lib/pickpoint_api/api_actions.rb
25
27
  - lib/pickpoint_api/constants.rb
26
28
  - lib/pickpoint_api/exceptions.rb
27
29
  - lib/pickpoint_api/session.rb
28
30
  - pickpoint_api.gemspec
29
- - spec/pickpoint_api.rb
30
- - spec/session.rb
31
+ - spec/pickpoint_api/session_spec.rb
32
+ - spec/pickpoint_api_spec.rb
33
+ - spec/spec_helper.rb
31
34
  - spec/support/dummy_data.rb
32
35
  - spec/support/http_mocking.rb
33
36
  homepage: http://github.com/kinderly/pickpoint_api
@@ -1,15 +0,0 @@
1
- require_relative '../lib/pickpoint_api.rb'
2
- require_relative './support/dummy_data.rb'
3
- require_relative './support/http_mocking.rb'
4
-
5
- include DummyData
6
-
7
- describe 'PickpointApi' do
8
- it 'should run session' do
9
- HttpMocking.set_next_response(LOGIN_SUCCESSFULL)
10
-
11
- PickpointApi.session('login', 'password', test:true) do |s|
12
- HttpMocking.set_next_response(LOGOUT_SUCCESSFULL)
13
- end
14
- end
15
- end
data/spec/session.rb DELETED
@@ -1,111 +0,0 @@
1
- # coding: utf-8
2
-
3
- require_relative '../lib/pickpoint_api.rb'
4
- require_relative './support/dummy_data.rb'
5
- require_relative './support/http_mocking.rb'
6
-
7
- include DummyData
8
-
9
- describe ::PickpointApi::Session do
10
- before(:each) do
11
- @session = ::PickpointApi::Session.new(test: true)
12
-
13
- ::HttpMocking.set_next_response(LOGIN_SUCCESSFULL)
14
- end
15
-
16
- it 'can instatiate' do
17
- expect(@session).not_to be_nil
18
- expect(@session.test).to eq true
19
- expect(@session.state).to eq :new
20
- end
21
-
22
- describe '.login' do
23
- it 'should log-in' do
24
- @session.login('login', 'password')
25
- expect(@session.state).to eq :started
26
- end
27
-
28
- it 'should handle incorrect login' do
29
- ::HttpMocking.set_next_response(LOGIN_FAILED)
30
- expect { @session.login('login', 'password') }.to raise_error ::PickpointApi::Exceptions::ApiError
31
- expect(@session.state).to eq(:error)
32
- end
33
- end
34
-
35
- describe '.logout' do
36
- it 'should log out' do
37
- @session.login('login', 'password')
38
- ::HttpMocking.set_next_response(LOGOUT_SUCCESSFULL)
39
- expect(@session.logout).to eq(true)
40
- expect(@session.state).to eq(:closed)
41
- end
42
- end
43
-
44
- describe '.create_sending' do
45
- it 'should handle succesfull request' do
46
- @session.login('login', 'password')
47
- ::HttpMocking.set_next_response(CREATE_SENDING_SUCCESSFULL)
48
- res = @session.create_sending(SAMPLE_SENDING_REQUEST)
49
- expect(res['CreatedSendings']).not_to be_empty
50
- expect(res['RejectedSendings']).to be_empty
51
- end
52
- end
53
-
54
- describe '.track_sending' do
55
- it 'should handle succesfull request' do
56
- @session.login('login', 'password')
57
- ::HttpMocking.set_next_response({}.to_json)
58
- res = @session.track_sending('21121312')
59
- end
60
- end
61
-
62
- describe '.postamat_list' do
63
- it 'should handle succesfull request' do
64
- @session.login('login', 'password')
65
- ::HttpMocking.set_next_response({}.to_json)
66
- @session.postamat_list
67
- end
68
- end
69
-
70
- describe '.make_label' do
71
- it 'should handle succesfull request' do
72
- @session.login('login', 'password')
73
- ::HttpMocking.set_next_response('%PDF')
74
- @session.make_label('12345')
75
- end
76
-
77
- it 'should handle multiple invoices' do
78
- @session.login('login', 'password')
79
- ::HttpMocking.set_next_response('%PDF')
80
- @session.make_label(['123123','123213'])
81
- end
82
-
83
- it 'should handle api error' do
84
- @session.login('login', 'password')
85
- ::HttpMocking.set_next_response('Error: Случилось что-то ужасное')
86
- expect{@session.make_label(['123123'])}.to raise_error PickpointApi::Exceptions::ApiError
87
- end
88
- end
89
-
90
- describe '.make_reestr' do
91
- it 'should handle succesfull request' do
92
- @session.login('login', 'password')
93
- ::HttpMocking.set_next_response('%PDF')
94
- @session.make_reestr('12345')
95
- end
96
-
97
- it 'should handle multiple invoices' do
98
- @session.login('login', 'password')
99
- ::HttpMocking.set_next_response('%PDF')
100
- @session.make_reestr(['123123','123213'])
101
-
102
- end
103
-
104
- it 'should handle api error' do
105
- @session.login('login', 'password')
106
- ::HttpMocking.set_next_response('Error: Случилось что-то ужасное')
107
- expect{@session.make_reestr(['123123'])}.to raise_error PickpointApi::Exceptions::ApiError
108
- end
109
- end
110
-
111
- end