dellin_info_api 0.0.1

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
+ SHA1:
3
+ metadata.gz: 8acb30e84ca701ed30db08571b4132b4b6a32a9b
4
+ data.tar.gz: fa7be481254d32bf362d75786fbe6f0a2f2752ce
5
+ SHA512:
6
+ metadata.gz: 87781cfa612de089eacb717507329e0d10e375dee58cb7ecc9a61a3c1af216627aabd61738552ce5c39d6ce5402836a678a0f51acaf69ccbc8e19987ce756a46
7
+ data.tar.gz: 30aa73d6309cada45f87475bc756d47d9f506185774ec055cd3fb3ee52317a5ddc32c0e3cba9215128f48be24021af3746c8eff215afc70d11842c324e1520aa
data/README.txt ADDED
@@ -0,0 +1,45 @@
1
+ gem для взаимодействия с ресурсом dellin.ru.
2
+ Поиск накладной по неполным данным
3
+ Поиск накладной по номеру
4
+ Подписка к накладной по номеру и получения изменения по накладной
5
+ Расчет стоимости
6
+ Хранения бызы адресов (страна, город, населенный пункт, улица)
7
+
8
+ ============================================================================================
9
+
10
+ DellinInfo::API.find_oders
11
+
12
+
13
+ на выходе получиться объект DellinInfo::API::OrderCollection
14
+
15
+ Пример:
16
+
17
+ oders = DellinInfo::API.find_oders(params)
18
+
19
+ oders.each {|oder| puts oder.docNumber}
20
+
21
+ ============================================================================================
22
+
23
+
24
+ DellinInfo::API.status_oder
25
+
26
+ Спомощью этого метода можно получить статус накладной по номеру, возвращается объетк класса DellinInfo::API::OrderStatus
27
+
28
+ пример
29
+ p DellinInfo::API.status_oder('16-00011096893')
30
+
31
+
32
+ ============================================================================================
33
+
34
+ DellinInfo::API.reference
35
+
36
+ Метод для получения ссылки на данные справочников с сайта Деловые Линии
37
+ http://dev.dellin.ru/api/public/tables/
38
+
39
+ p DellinInfo::API.reference('countries')
40
+
41
+ Возвможные параметры:
42
+ countries
43
+ cities
44
+ places
45
+ streets
@@ -0,0 +1,78 @@
1
+ require 'yaml'
2
+ require 'active_support/all'
3
+ require 'date'
4
+ require_relative 'dellininfo/valide_data'
5
+ require_relative 'dellininfo/client'
6
+ require_relative 'dellininfo/reference'
7
+ require_relative 'dellininfo/order_collection'
8
+ require_relative 'dellininfo/reference'
9
+ require_relative 'dellininfo/order_status'
10
+ module DellinInfo
11
+ module API
12
+
13
+ # Приложение можно сконфигурировать, для конфикурации необходимо указать в константе DellinInfo::API::PATH путь до файла yml
14
+ # где ключ - название класса в snakecase, а значение - пара (параметр - значение)
15
+ PATH = 'path to config.yml'
16
+
17
+
18
+
19
+ # Все основные настройки хранятся в отдельном файле, данный метод рализует конфигурацию всех классов модуля
20
+ def self.configure!
21
+
22
+ YAML.load_file(PATH).each_pair do |config_class, params|
23
+ params.each_pair do |param, value|
24
+ "DellinInfo::API::#{config_class.camelize}".constantize.config[param] = value
25
+ end
26
+ end
27
+ end
28
+
29
+
30
+ # Данный метод получает ссылку на csv с данными справочников Деловых линиях
31
+ # http://dev.dellin.ru/api/public/tables/
32
+ # и хэш, по которому можно отследить актуальность данных
33
+ # возвращается объект класса DellinInfo::API::Reference
34
+ def self.reference(type)
35
+ type = type.to_sym
36
+ url_type = Reference::TYPE[type]
37
+ data = client_request(url_type)
38
+
39
+ Reference.new(data)
40
+ end
41
+
42
+ # метод поиска накладных по неполным данным
43
+ def self.find_oders(params = {})
44
+ if params[:date_start].nil?
45
+ set_time!
46
+ params[:date_start] = @start_date
47
+ params[:date_end] = @end_day
48
+ end
49
+ data = client_request(OrderCollection, params)
50
+ OrderCollection.new data
51
+
52
+ end
53
+
54
+ # метод проверяющий статусы накладной по номеру
55
+ def self.status_oder(id_oder)
56
+ data = client_request(OrderStatus, docid: id_oder)
57
+ DellinInfo::API::OrderStatus.new data
58
+
59
+ end
60
+
61
+ def self.client_request(dellin_class, params = {})
62
+ client = Client.new()
63
+ data = client.request(dellin_class.config['partial_url'], params).body
64
+ JSON.parse data
65
+
66
+ end
67
+
68
+ def self.set_time!
69
+
70
+ @start_date = 6.day.ago.strftime('%Y-%m-%d')
71
+ @end_day = Time.now.strftime('%Y-%m-%d')
72
+
73
+
74
+ end
75
+
76
+
77
+ end
78
+ end
@@ -0,0 +1,36 @@
1
+ require 'httparty'
2
+ require 'json'
3
+
4
+ module DellinInfo
5
+ module API
6
+ class Client
7
+ include ActiveSupport::Configurable
8
+
9
+ # в проекте используется только публичные API, поэтому данный метод в годе больше не затронут,
10
+ # но оставлен для возможности расширить функционал
11
+ def auth(options = {})
12
+ response = HTTParty.post('https://api.dellin.ru/v1/customers/login.json',
13
+ :body => {:login => options[:username], :password => options[:password], :appKey => @app_key}.to_json,
14
+ :headers => {'Content-Type' => 'application/json'})
15
+ print response
16
+ response['sessionID']
17
+ end
18
+
19
+ def request(op, params = {})
20
+ params[:appKey] = @app_key
21
+ response = HTTParty.post("https://api.dellin.ru/v1/#{op}.json",
22
+ :body => params.to_json,
23
+ :headers => {'Content-Type' => 'application/json'})
24
+ response
25
+ end
26
+
27
+ private
28
+
29
+ def initialize()
30
+ raise "No app key given" unless config['app_key']
31
+ @app_key = config['app_key']
32
+ end
33
+
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,65 @@
1
+ require 'date'
2
+ module DellinInfo
3
+ module API
4
+ class Order
5
+ include ValideData
6
+ ATTRIBUTES = [
7
+ :availableAD,
8
+ :estimatedDeliveryDate,
9
+ :terminalSender,
10
+ :unvailableSfRequestReason,
11
+ :isSfRequestOrdered,
12
+ :availableSfRequest,
13
+ :opf,
14
+ :terminalReceiver,
15
+ :docNumber,
16
+ :comment,
17
+ :sizedWeight,
18
+ :ordNum,
19
+ :sizedVolume,
20
+ :docDate,
21
+ :sqlUuid,
22
+ :height,
23
+ :width,
24
+ :length,
25
+ :aviaDeliveryType,
26
+ :numAvia,
27
+ :giveoutDate,
28
+ :conditionAvia,
29
+ :oversizedVolume,
30
+ :oversizedWeight,
31
+ ]
32
+
33
+ attr_accessor :state, :city_sender, :city_receiver, *ATTRIBUTES
34
+
35
+ def to_s
36
+ "накладная № #{@docNumber} от #{Date.parse docDate}\nОтправление из города #{@city_sender} в город #{@city_receiver}\nстатус: #{@state}\n#{'-'*10}\n"
37
+
38
+ end
39
+
40
+
41
+
42
+
43
+
44
+
45
+ private
46
+ def initialize(hash_track)
47
+ data = parse_hash_response(hash_track, 'order')
48
+
49
+ ATTRIBUTES.each do |attribute|
50
+
51
+ self.send(set_attr_method(attribute), data[attribute])
52
+
53
+ end
54
+
55
+ @state = 'не установлен'
56
+
57
+ end
58
+
59
+
60
+ end
61
+ end
62
+ end
63
+
64
+
65
+
@@ -0,0 +1,56 @@
1
+ require_relative 'order.rb'
2
+ module DellinInfo
3
+ module API
4
+ class OrderCollection
5
+ include Enumerable
6
+ include ValideData
7
+ include ActiveSupport::Configurable
8
+
9
+ config['partial_url'] = 'public/tracker_advanced'
10
+
11
+
12
+ attr_reader :errors, :orders, :cash
13
+
14
+ def each
15
+ @orders.each {|oder| yield oder}
16
+
17
+ end
18
+
19
+
20
+
21
+ private
22
+ def initialize(oders_hash)
23
+ @errors = oders_hash['errormsg']
24
+ @orders = []
25
+ @cash = there_tracks(oders_hash)
26
+
27
+ unless @cash.nil?
28
+ @cash.each do |track|
29
+ @orders << Order.new(track)
30
+ end
31
+ end
32
+
33
+ determine_state!
34
+
35
+ end
36
+
37
+ def determine_state!
38
+
39
+ @orders.each do |order|
40
+ id_oder = order.docNumber
41
+ status = DellinInfo::API.status_oder(id_oder)
42
+ order.state = status.state
43
+ order.city_sender = status.receive['city']
44
+ order.city_receiver = status.giveout['city']
45
+ end
46
+
47
+ self
48
+
49
+ end
50
+
51
+
52
+
53
+
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,33 @@
1
+ module DellinInfo
2
+ module API
3
+ class OrderStatus
4
+ include ValideData
5
+ include ActiveSupport::Configurable
6
+
7
+ config['partial_url'] = 'public/tracker'
8
+
9
+ ATTRIBUTES = [:errors, :estimatedDeliveryDate, :state, :giveout, :availableSfRequest, :receive]
10
+
11
+ attr_accessor *ATTRIBUTES
12
+
13
+ def to_s
14
+ "Отправление из города: #{@receive['city']} в город #{@giveout['city']}\nСтатус: #{@state}\nОжидаемая дата прихода #{@estimatedDeliveryDate}\nТерминал прибытия: #{@giveout['terminal']}"
15
+
16
+ end
17
+
18
+ private
19
+ def initialize(hash_status)
20
+ valid_hash = delete_spase_key(hash_status)
21
+
22
+ ATTRIBUTES.each do |attribute|
23
+
24
+ self.send(set_attr_method(attribute), valid_hash[attribute.to_s])
25
+
26
+ end
27
+
28
+ end
29
+
30
+
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,26 @@
1
+ module DellinInfo
2
+ module API
3
+ class Reference
4
+ attr_reader :hash, :url
5
+
6
+ TYPE = {
7
+ countries: 'public/countries',
8
+ cities: 'public/cities',
9
+ places: 'public/places',
10
+ streets: 'public/streets'
11
+ }
12
+
13
+
14
+
15
+
16
+ private
17
+ def initialize(hash)
18
+ @hash = hash['hash']
19
+ @url = hash['url']
20
+ self
21
+ end
22
+
23
+
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,47 @@
1
+ module DellinInfo
2
+ module API
3
+ module ValideData
4
+
5
+ def there_tracks (oders_hash)
6
+ if oders_hash['orders'].empty?
7
+ p errors
8
+ nil
9
+ else
10
+ oders_hash.dig('orders', 'tracker')
11
+ end
12
+
13
+ end
14
+
15
+
16
+ def parse_hash_response(track, key_is_hash)
17
+
18
+ simple_hash = {}
19
+
20
+ track.each_pair do |param, val|
21
+ unless param.to_s == key_is_hash.to_s
22
+ simple_hash[param.to_sym] = val
23
+ else
24
+ val.each_pair { |key, val_oder| simple_hash[key.to_sym] = val_oder }
25
+ end
26
+ end
27
+
28
+ simple_hash
29
+
30
+ end
31
+
32
+ def set_attr_method(attr_sym)
33
+ atr = attr_sym.to_s + '='
34
+ atr.to_sym
35
+
36
+ end
37
+
38
+ def delete_spase_key(hash)
39
+ valid_hash = {}
40
+ hash.each_pair { |key, val| valid_hash[key.strip] = val }
41
+ valid_hash
42
+
43
+ end
44
+
45
+ end
46
+ end
47
+ end
metadata ADDED
@@ -0,0 +1,83 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: dellin_info_api
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Alexander Shvaykin
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2016-04-07 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activesupport
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '4.2'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '4.2'
27
+ - !ruby/object:Gem::Dependency
28
+ name: httparty
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: 0.13.7
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: 0.13.7
41
+ description: Gem implements the methods of public api dellin.ru site
42
+ email: skiline.alex@gmail.com
43
+ executables: []
44
+ extensions: []
45
+ extra_rdoc_files: []
46
+ files:
47
+ - "./README.txt"
48
+ - lib/dellin_info.rb
49
+ - lib/dellininfo/client.rb
50
+ - lib/dellininfo/order.rb
51
+ - lib/dellininfo/order_collection.rb
52
+ - lib/dellininfo/order_status.rb
53
+ - lib/dellininfo/reference.rb
54
+ - lib/dellininfo/valide_data.rb
55
+ homepage: https://github.com/AlexanderShvaykin/dellininfo/
56
+ licenses:
57
+ - MIT
58
+ metadata: {}
59
+ post_install_message:
60
+ rdoc_options: []
61
+ require_paths:
62
+ - lib
63
+ required_ruby_version: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - ">="
66
+ - !ruby/object:Gem::Version
67
+ version: '0'
68
+ required_rubygems_version: !ruby/object:Gem::Requirement
69
+ requirements:
70
+ - - ">="
71
+ - !ruby/object:Gem::Version
72
+ version: '0'
73
+ requirements:
74
+ - Internet connection
75
+ - A good mood
76
+ rubyforge_project:
77
+ rubygems_version: 2.5.1
78
+ signing_key:
79
+ specification_version: 4
80
+ summary: Search shipments by incomplete data and check the status of sending in a
81
+ transport company
82
+ test_files: []
83
+ has_rdoc: