magentwo 0.1.4 → 0.1.5

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
  SHA256:
3
- metadata.gz: a3a841b7d66c45e36a63b99466fd49e7bedfd056f9077e2cdf2e93dd0b7bf9d1
4
- data.tar.gz: 46906bc86d4c0da2517334e916e61b0a647d181587324be4a8f5f5058ae3079e
3
+ metadata.gz: 692e463d7482eb7a4badc478f415deccc4085bb5b19a7d3d84bcc0a671108a8e
4
+ data.tar.gz: 9d4615302038000aa1c322190484d139e34e1fc6a122ef6c68ceae9e7296f617
5
5
  SHA512:
6
- metadata.gz: aa0c925bd64c60d046266bfed1a8f0c6c1c50ab9f69e2f2b5e5fb6700a5fef715db656a11c65c065f4fae273ba994422c9ec810c3903ffdb671d1d723a9242c0
7
- data.tar.gz: 2a49d67d5c11fb054d23cc0d2ac24cb87d813c0704111dadeb75cf7a80626139f579f653ae86d7e61789debe02ef2c5951d178bfac0604b121ebfda4e77b236d
6
+ metadata.gz: c2cbcd9f5ee6814e5fba49f3422c9df1d18f9fb86fef3608945201c307c28e3e53c479ed8361373a1ff20b52ab61d961ee34e69dce33618df8be588c946c5d4f
7
+ data.tar.gz: 5add378c0c94715979a40d9d53c6d9d0c704e11f9daa2891627d7cb82b44fb59dea62af33aafb532cb4fcd28b303b640ac30790528be861cd1da65211dd8e34c
data/README.md CHANGED
@@ -1,4 +1,99 @@
1
- # magentwo
2
- Simple Ruby-Wrapper for the Magento 2 REST API
3
1
 
4
- under developement
2
+ This gem is under developement and nowhere near finished but feel free to play around with it.
3
+ I am grateful for any ideas and suggestions
4
+
5
+ # Magentwo
6
+ Ruby-Wrapper for the Magento 2 REST API
7
+
8
+
9
+ # How to install
10
+ To install the Gem directly use
11
+ ```
12
+ gem install magentwo
13
+ ```
14
+
15
+ or add the following line to your Gemfile
16
+ ```
17
+ gem 'magentwo'
18
+ ```
19
+ and call bundler
20
+ ```
21
+ bundle
22
+ ```
23
+
24
+
25
+ # How to connect to your magento 2 shop
26
+ Currently there is only one connection at a time possible
27
+ ```
28
+ Magentwo.connect http://example.com, username, password
29
+ ```
30
+
31
+ # How to use
32
+ In Magentwo you interact with the API using Models. These are named according the the REST-API specifications of Magento 2
33
+ The basic functionality is the same for all Models. For products some simple requests would look like this
34
+
35
+ ```
36
+ Magentwo::Product.all #fetches all Products
37
+ Magentwo::Product.first #fetches the first product
38
+ Magentwo::Product.count #returns the number of available products
39
+ Magentwo::Product.fields #returns an array of productfields
40
+ ```
41
+
42
+ # Filtering
43
+ You can filter requests to search for specific elements
44
+ Here are some examples
45
+
46
+ Look for all customers whose firstname is Foobar
47
+ ```
48
+ Magentwo::Customer.filter(:firstname => "Foobar").all
49
+ ```
50
+
51
+ Look for all customers whose id is not 42
52
+ ```
53
+ Magentwo::Customer.exclude(:id => 42).all
54
+ ```
55
+
56
+ You can also combine these
57
+ ```
58
+ Magentwo::Customer.filter(:firstname => "Foobar").exclude(:id => 42).all
59
+ ```
60
+ The `filter` and `exclude` methods can also be used to filter for a set. To Request all Customers whose firstname is either Foo or Bar you could write
61
+ ```
62
+ Magentwo::Customer.filter(:firstname => ["Foo", "bar"]).all
63
+ ```
64
+
65
+ Look for all Products whose name includes the word "Computer"
66
+ ```
67
+ Magentwo::Product.like(:name => "%Computer%").all
68
+ ```
69
+
70
+ # Pagination
71
+ On default the pagesize is set to 20, you can change this with
72
+ ```
73
+ Magentwo.default_page_size=42
74
+ ```
75
+
76
+ The pagesize can also be set on the fly
77
+ To request page 2 with a pagesize of 100 simply write the following. The second paramter is optional
78
+ ```
79
+ Magentwo::Product.exclude(:name => "foobar").page(2, 100).all
80
+ ```
81
+
82
+ To iterate threw all the pages use `each_page`. Again the pagesize parameter is optional
83
+ ```
84
+ Magentwo::Product.each_page(512) do |page|
85
+ p page
86
+ end
87
+ ```
88
+
89
+ # Updates
90
+ To update Models back to Magento 2 use the `save` method
91
+ This switches the first and last name of the Customer Foo Bar
92
+ ```
93
+ customer = Magentwo::Customer.filter(:first_name => "Foo").filter(:last_name => "Bar").first
94
+ customer.firstname = "Bar"
95
+ customer.lastname = "Foo"
96
+ customer.save
97
+ ```
98
+
99
+ to be continued
data/lib/adapter.rb CHANGED
@@ -10,12 +10,13 @@ module Magentwo
10
10
  end
11
11
 
12
12
  response = self.send(http_method, path, params)
13
+ Magentwo.logger.debug response.body
13
14
 
14
15
  parsed_response = case method
15
16
  when :get_with_meta_data, :put, :post, :delete then transform( parse( response))
16
17
  when :get
17
18
  parsed = parse(response)
18
- if parsed[:items]
19
+ if parsed.is_a?(Hash) && parsed[:items]
19
20
  parsed[:items].map do |item|
20
21
  transform item
21
22
  end
@@ -38,11 +39,14 @@ module Magentwo
38
39
  end
39
40
 
40
41
  def transform item
41
- date_transform item if item
42
+ if(item && item.is_a?(Hash))
43
+ date_transform item
44
+ else
45
+ item
46
+ end
42
47
  end
43
48
 
44
49
  def date_transform item
45
- p "datetransform: #{item}"
46
50
  DateFields.each do |date_field|
47
51
  item[date_field] = Time.new item[date_field] if item[date_field]
48
52
  end
data/lib/connection.rb CHANGED
@@ -2,27 +2,26 @@ module Magentwo
2
2
  class Connection
3
3
  attr_accessor :host, :port, :user, :password, :token, :base_path
4
4
 
5
- def initialize host, user, password, base_path:nil
6
- if host.include? ":"
7
- @host = host.split(":").first
8
- @port = host.split(":").last.to_i
9
- else
10
- @host = host
11
- @port = 80
12
- end
5
+ def initialize uri, user, password, base_path:nil
6
+ uri = URI(uri)
7
+ @host = uri.host
8
+ @port = uri.port
13
9
  @user = user
14
10
  @password = password
15
- @base_path = base_path || "/rest/default/V1"
11
+ @base_path = base_path || "/rest/V1"
16
12
  request_token
17
13
  end
18
14
 
19
15
  def request_token
20
16
  Net::HTTP.start(self.host,self.port) do |http|
21
- req = Net::HTTP::Post.new("#{base_path}/integration/admin/token")
17
+ url = "#{base_path}/integration/admin/token"
18
+ Magentwo.logger.info "POST #{url}"
19
+ req = Net::HTTP::Post.new(url)
22
20
  req.body = {:username=> self.user, :password=> self.password}.to_json
23
21
  req['Content-Type'] = "application/json"
24
22
  req['Content-Length'] = req.body.length
25
- @token = JSON.parse http.request(req).body
23
+ response = http.request(req).body
24
+ @token = JSON.parse response
26
25
  end
27
26
  end
28
27
 
data/lib/dataset.rb CHANGED
@@ -7,7 +7,7 @@ module Magentwo
7
7
  :filters => [],
8
8
  :pagination => {
9
9
  :current_page => Filter::CurrentPage.new(1),
10
- :page_size => Filter::PageSize.new(Magentwo.default_page_size)
10
+ :page_size => Filter::PageSize.new(0)
11
11
  },
12
12
  :ordering => [],
13
13
  :fields => nil
@@ -18,21 +18,22 @@ module Magentwo
18
18
  # Filters
19
19
  ################
20
20
  def filter hash_or_other, invert:false
21
- filter = case hash_or_other
21
+ filters = case hash_or_other
22
22
  when Hash
23
23
  raise ArgumentError, "empty hash supplied" if hash_or_other.empty?
24
- key, value = hash_or_other.first
25
- klass = case value
26
- when Array
27
- invert ? Filter::Nin : Filter::In
28
- else
29
- invert ? Filter::Neq : Filter::Eq
24
+ hash_or_other.map do |key, value|
25
+ klass = case value
26
+ when Array
27
+ invert ? Filter::Nin : Filter::In
28
+ else
29
+ invert ? Filter::Neq : Filter::Eq
30
+ end
31
+ klass.new(key, value)
30
32
  end
31
- klass.new(key, value)
32
33
  else
33
34
  raise ArgumentError, "filter function expects Hash as input"
34
35
  end
35
- Dataset.new self.model, self.opts.merge(:filters => self.opts[:filters] + [filter])
36
+ Dataset.new self.model, self.opts.merge(:filters => self.opts[:filters] + filters)
36
37
  end
37
38
 
38
39
  def exclude args
@@ -124,5 +125,20 @@ module Magentwo
124
125
  raise ArgumentError, "no block given" unless block_given?
125
126
  self.model.all.each(&block)
126
127
  end
128
+
129
+ def each_page page_size=Magentwo.default_page_size, &block
130
+ raise ArgumentError, "no block given" unless block_given?
131
+
132
+ received_element_count = page_size
133
+ current_page = 1
134
+ while(received_element_count == page_size) do
135
+ page = self.page(current_page, page_size).all
136
+
137
+ block.call(page)
138
+
139
+ received_element_count = page.count
140
+ current_page += 1
141
+ end
142
+ end
127
143
  end
128
144
  end
data/lib/filter.rb CHANGED
@@ -10,7 +10,7 @@ module Magentwo
10
10
  def to_query idx
11
11
  [
12
12
  "searchCriteria[filter_groups][#{idx}][filters][0][field]=#{self.field}",
13
- "searchCriteria[filter_groups][#{idx}][filters][0][value]=#{URI::encode(self.value)}",
13
+ "searchCriteria[filter_groups][#{idx}][filters][0][value]=#{URI::encode(self.value.to_s)}",
14
14
  "searchCriteria[filter_groups][#{idx}][filters][0][condition_type]=#{self.class.name.split("::").last.downcase}"]
15
15
  .join("&")
16
16
  end
@@ -20,7 +20,7 @@ module Magentwo
20
20
  def to_query idx
21
21
  [
22
22
  "searchCriteria[filter_groups][#{idx}][filters][0][field]=#{self.field}",
23
- "searchCriteria[filter_groups][#{idx}][filters][0][value]=#{URI::encode(self.value.join(","))}",
23
+ "searchCriteria[filter_groups][#{idx}][filters][0][value]=#{URI::encode(self.value.join(",").map(&:to_s))}",
24
24
  "searchCriteria[filter_groups][#{idx}][filters][0][condition_type]=#{self.class.name.split("::").last.downcase}"]
25
25
  .join("&")
26
26
  end
data/lib/magentwo.rb CHANGED
@@ -4,8 +4,11 @@ require 'json'
4
4
  require 'logger'
5
5
 
6
6
  module Magentwo
7
- Models = %w(base product customer order coupon sales_rule)
8
- def self.connect host, user_name, password
7
+ Models = %w(base product customer order coupon sales_rule category)
8
+ def self.connect host=nil, user_name=nil, password=nil
9
+ raise ArgumentError, "no host specified" unless host
10
+ raise ArgumentError, "no user_name specified" unless user_name
11
+ raise ArgumentError, "no password specified" unless password
9
12
  Base.adapter = Adapter.new host, user_name, password
10
13
  end
11
14
 
@@ -14,7 +17,7 @@ module Magentwo
14
17
  end
15
18
 
16
19
  def self.logger
17
- @@logger ||= Logger.new STDOUT, {:level => Logger::DEBUG}
20
+ @@logger ||= Logger.new STDOUT, {:level => Logger::INFO}
18
21
  end
19
22
 
20
23
  def self.default_page_size
@@ -25,7 +28,14 @@ module Magentwo
25
28
  @@default_page_size = page_size
26
29
  end
27
30
 
28
-
31
+ def self.models
32
+ Models.map do |model_file_name|
33
+ model_file_name
34
+ .split('_')
35
+ .map(&:capitalize)
36
+ .join
37
+ end
38
+ end
29
39
  end
30
40
 
31
41
  require_relative 'connection.rb'
data/lib/model/base.rb CHANGED
@@ -2,8 +2,6 @@ module Magentwo
2
2
  class Base
3
3
  DatasetMethods = %i(filter exclude select fields count fields info page order_by like)
4
4
 
5
- attr_accessor :base_path
6
-
7
5
  def initialize args
8
6
  args.each do |key, value|
9
7
  key_sym = :"@#{key}"
@@ -64,6 +62,10 @@ module Magentwo
64
62
  class << self
65
63
  attr_accessor :adapter
66
64
 
65
+ def [] unique_identifier
66
+ self.new (Magentwo::Base.get nil, path:"#{base_path}/#{unique_identifier}")
67
+ end
68
+
67
69
  def lower_case_name
68
70
  name = self.name.split(/::/).last
69
71
  "#{name[0,1].downcase}#{name[1..-1]}"
@@ -88,6 +90,18 @@ module Magentwo
88
90
  self.new self.get(ds.page(1, 1).to_query).first
89
91
  end
90
92
 
93
+ def each_page page_size=Magentwo.default_page_size, &block
94
+ self.dataset.each_page page_size, &block
95
+ end
96
+
97
+ def each &block
98
+ self.dataset.each &block
99
+ end
100
+
101
+ def map &block
102
+ self.dataset.map &block
103
+ end
104
+
91
105
  def dataset
92
106
  Magentwo::Dataset.new(self)
93
107
  end
@@ -108,7 +122,7 @@ module Magentwo
108
122
  end
109
123
 
110
124
  def call method, path=self.base_path, params
111
- Magentwo::Base.adapter.call(method, path, params)
125
+ Magentwo::Base.adapter.call(method, path, params)
112
126
  end
113
127
 
114
128
  end
@@ -0,0 +1,9 @@
1
+ module Magentwo
2
+ class Category < Base
3
+ class << self
4
+ def base_path
5
+ "categories"
6
+ end
7
+ end
8
+ end
9
+ end
data/lib/model/coupon.rb CHANGED
@@ -11,7 +11,7 @@ module Magentwo
11
11
  def generate rule_id, quantity:1, length:16, format:(:alpha), delimiter:"-", delimiter_at_every:4
12
12
  format = format.to_sym
13
13
  Magentwo::Validator.one_of format, :num, :alpha, :alphanum
14
- self.call :post, "coupons/generate",
14
+ self.call :post, "#{base_path}/generate",
15
15
  {
16
16
  :couponSpec => {
17
17
  :rule_id => rule_id,
data/lib/model/product.rb CHANGED
@@ -2,5 +2,11 @@ module Magentwo
2
2
  class Product < Base
3
3
  Attributes = %i(id sku name attribute_set_id price status visibility type_id created_at updated_at extension_attributes product_links options media_gallery_entries tier_prices custom_attributes)
4
4
  Attributes.each do |attr| attr_accessor attr end
5
+
6
+ class << self
7
+ def types
8
+ Magentwo::Base.get nil, path:"#{base_path}/types"
9
+ end
10
+ end
5
11
  end
6
12
  end
@@ -3,6 +3,15 @@ module Magentwo
3
3
  Attributes = %i(rule_id name store_labels description website_ids customer_group_ids uses_per_customer is_active condition action_condition stop_rules_processing is_advanced sort_order simple_action discount_amount discount_step apply_to_shipping times_used is_rss coupon_type use_auto_generation uses_per_coupon simple_free_shipping)
4
4
  Attributes.each do |attr| attr_accessor attr end
5
5
 
6
+ def generate quantity:1, length:16, format:(:alpha), delimiter:"-", delimiter_at_every:4
7
+ Magentwo::Coupon.generate self.rule_id, quantity:quantity, length:length, format:format, delimiter:delimiter, delimiter_at_every:delimiter_at_every
8
+ end
9
+
10
+ def coupons
11
+ Magentwo::Coupon.filter(:rule_id => self.rule_id).all
12
+ end
13
+
14
+
6
15
  class << self
7
16
  def get_path
8
17
  "#{base_path}/search"
data/magentwo.gemspec CHANGED
@@ -1,6 +1,6 @@
1
1
  Gem::Specification.new do |s|
2
2
  s.name = 'magentwo'
3
- s.version = '0.1.4'
3
+ s.version = '0.1.5'
4
4
  s.date = '2019-01-17'
5
5
  s.summary = "Magento 2 API Wrapper"
6
6
  s.description = "Provides a simple Ruby Interface to interact with the Magento 2 API"
data/spec/dataset_spec.rb CHANGED
@@ -18,9 +18,9 @@ describe Magentwo::Dataset do
18
18
  expect(dataset.opts[:pagination]).to have_key :current_page
19
19
  expect(dataset.opts[:pagination]).to have_key :page_size
20
20
  end
21
- it "requests #{Magentwo::Dataset::DefaultPageSize} items on default" do
21
+ it "requests all items on default" do
22
22
  expect(initial_query).to include "searchCriteria[current_page]=1"
23
- expect(initial_query).to include "searchCriteria[page_size]=#{Magentwo::Dataset::DefaultPageSize}"
23
+ expect(initial_query).to include "searchCriteria[page_size]=0"
24
24
  end
25
25
  end
26
26
 
@@ -37,6 +37,31 @@ describe Magentwo::Dataset do
37
37
  end
38
38
  end
39
39
 
40
+ context "multi filter" do
41
+ let(:multi_filter_ds) {dataset.filter(:name => "foobar").filter(:id => 42)}
42
+ let(:multi_filter_query) {multi_filter_ds.to_query}
43
+ let(:multi_filter_in_one_ds) {dataset.filter(:name => "foobar", :id => 42)}
44
+ let(:multi_filter_in_one_query) {multi_filter_in_one_ds.to_query}
45
+ it "contains filter with type Filter::Eq" do
46
+ expect(multi_filter_ds.opts[:filters]).to include Magentwo::Filter::Eq
47
+ end
48
+ it "contains two filters" do
49
+ expect(multi_filter_ds.opts[:filters].count).to eq 2
50
+ end
51
+ it "compute query" do
52
+ expect(multi_filter_query).to include "searchCriteria[filter_groups][0][filters][0][field]=name"
53
+ expect(multi_filter_query).to include "searchCriteria[filter_groups][0][filters][0][condition_type]=eq"
54
+ expect(multi_filter_query).to include "searchCriteria[filter_groups][0][filters][0][value]=foobar"
55
+ expect(multi_filter_query).to include "searchCriteria[filter_groups][1][filters][0][field]=id"
56
+ expect(multi_filter_query).to include "searchCriteria[filter_groups][1][filters][0][condition_type]=eq"
57
+ expect(multi_filter_query).to include "searchCriteria[filter_groups][1][filters][0][value]=42"
58
+ end
59
+ it "is the same for multiple keys in one filter" do
60
+ expect(multi_filter_ds.opts.count).to eq multi_filter_in_one_ds.opts.count
61
+ expect(multi_filter_query).to eq multi_filter_in_one_query
62
+ end
63
+ end
64
+
40
65
  context "select" do
41
66
  let(:name_select_ds) {dataset.select(:name)}
42
67
  let(:name_select_query) {name_select_ds.to_query}
data/spec/product_spec.rb CHANGED
@@ -1,4 +1,83 @@
1
1
  require_relative '../lib/magentwo.rb'
2
2
 
3
3
  describe Magentwo::Product do
4
+ before(:all) do
5
+ Magentwo.logger = Logger.new STDOUT, {:level => Logger::ERROR}
6
+ @original_count = Magentwo::Product.count
7
+ end
8
+
9
+ context "#dataset" do
10
+ let(:dataset) {Magentwo::Product.dataset}
11
+ it "returns dataset" do
12
+ expect(dataset).to be_a Magentwo::Dataset
13
+ end
14
+ end
15
+
16
+ context "#count" do
17
+ let(:count) {Magentwo::Product.count}
18
+ it "responds to :count" do
19
+ expect(Magentwo::Product).to respond_to :count
20
+ end
21
+ it "correct count" do
22
+ expect(count).to eq @original_count
23
+ end
24
+ it "count is integer" do
25
+ expect(count).to be_a Integer
26
+ end
27
+ end
28
+
29
+ context "#all" do
30
+ let(:products) {Magentwo::Product.all}
31
+ let(:ds) {Magentwo::Product.dataset}
32
+
33
+ it "responds to all" do
34
+ expect(Magentwo::Product).to respond_to :all
35
+ end
36
+ it "returns an array" do
37
+ expect(products).to be_a Array
38
+ end
39
+ it "requested all" do
40
+ expect(products.count).to eq @original_count
41
+ end
42
+ end
43
+
44
+ context "#fields" do
45
+ let(:fields) {Magentwo::Product.fields}
46
+
47
+ it "returns array of symbols" do
48
+ expect(fields).to be_a Array
49
+ fields.each do |field|
50
+ expect(field).to be_a Symbol
51
+ end
52
+ end
53
+ end
54
+
55
+ context "#first" do
56
+ let(:product) {Magentwo::Product.first}
57
+
58
+ it "returns a product" do
59
+ expect(product).to be_a Magentwo::Product
60
+ end
61
+ end
62
+
63
+ context "#types" do
64
+ let(:types) {Magentwo::Product.types}
65
+
66
+ it "returns array" do
67
+ expect(types).to be_a Array
68
+ end
69
+ end
70
+
71
+ context "#[]" do
72
+ let(:first_product) {Magentwo::Product.first}
73
+ let(:by_sku_product) {Magentwo::Product[first_product.sku]}
74
+
75
+ it "returns a product" do
76
+ expect(by_sku_product).to be_a Magentwo::Product
77
+ end
78
+
79
+ it "returns product by :sku" do
80
+ expect(first_product.sku).to eq by_sku_product.sku
81
+ end
82
+ end
4
83
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: magentwo
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.4
4
+ version: 0.1.5
5
5
  platform: ruby
6
6
  authors:
7
7
  - André Mueß
@@ -27,6 +27,7 @@ files:
27
27
  - lib/filter.rb
28
28
  - lib/magentwo.rb
29
29
  - lib/model/base.rb
30
+ - lib/model/category.rb
30
31
  - lib/model/coupon.rb
31
32
  - lib/model/customer.rb
32
33
  - lib/model/order.rb