app_manager 0.1.2 → 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,40 @@
1
+ module AppManager
2
+ class Client
3
+ module Plans
4
+
5
+ def get_plans(options = {})
6
+ get("/plans", options)
7
+ end
8
+
9
+ def get_plan(plan_id,shop_domain=nil)
10
+ get("/plan?plan_id=#{plan_id}&shop_domain=#{shop_domain}")
11
+ end
12
+
13
+ def store_charge(options = {})
14
+ post("/store-charge", options)
15
+ end
16
+
17
+ def cancel_charge(shop_domain,plan_id)
18
+ post("/cancel-charge", {shop_domain: shop_domain,plan_id: plan_id})
19
+ end
20
+
21
+ def sync_charge(options = {})
22
+ post("/sync-charge", options)
23
+ end
24
+
25
+ def get_remaining_days(shop_domain,trial_activated_at=nil,plan_id=nil)
26
+ get("/get-remaining-days?shop_domain=#{shop_domain}&trial_activated_at=#{trial_activated_at}&plan_id=#{plan_id}")
27
+ end
28
+
29
+ def get_charge(shop_domain)
30
+ get("/get-charge?shop_domain=#{shop_domain}")
31
+ end
32
+
33
+ def get_status(options = {})
34
+ get("/get-status", options)
35
+ end
36
+
37
+
38
+ end
39
+ end
40
+ end
@@ -1,25 +1,31 @@
1
1
  require "app_manager/client/connection"
2
2
  require "app_manager/client/banners"
3
+ require "app_manager/client/plans"
3
4
 
4
5
  module AppManager
5
6
  class Client
6
7
  include HTTParty
7
8
  include AppManager::Client::Connection
8
9
  include AppManager::Client::Banners
9
-
10
+ include AppManager::Client::Plans
10
11
 
11
12
  # debug_output $stderr if Rails.env.development?
12
13
  # base_uri "https://app-manager.hulkapps.com/api"
13
14
  format :json
14
15
 
15
16
 
16
- def initialize(access_token = nil)
17
+ def initialize(access_token = nil,json_req=false)
17
18
  access_token ||= ENV["APP_MANAGER_ACCESS_TOKEN"]
18
19
  hostport = ENV['APP_MANAGER_API_URL'] || 'https://app-manager.hulkapps.com'
19
20
  self.class.base_uri "#{hostport}/api"
20
- self.class.default_options.merge!(headers: { 'token' => "#{access_token}" })
21
+ header = { 'token' => "#{access_token}"}
22
+ header.merge!('Content-Type' => 'application/json') if json_req
23
+ self.class.default_options.merge!(headers: header)
21
24
  end
22
25
 
26
+ def is_json
27
+
28
+ end
23
29
 
24
30
  end
25
31
 
@@ -0,0 +1,82 @@
1
+ module AppManager
2
+ class Config
3
+
4
+ attr_accessor :cache_by_headers
5
+ attr_accessor :expires_in
6
+ attr_accessor :enable_caching
7
+ attr_accessor :plan_features
8
+ attr_accessor :app_url
9
+ attr_accessor :shopify_api_key
10
+ attr_accessor :shopify_api_version
11
+ attr_accessor :shopify_table_name
12
+ attr_accessor :shopify_domain_field
13
+ attr_accessor :plan_id_or_name_field
14
+ attr_accessor :field_names
15
+
16
+
17
+
18
+ def initialize
19
+ @expires_in = 1.day
20
+ @enable_caching = true
21
+ @app_url = nil
22
+ @shopify_api_key = nil
23
+ @shopify_api_version = nil
24
+ @shopify_table_name = 'shops'
25
+ @shopify_domain_field = 'shopify_domain'
26
+ @plan_id_or_name_field = nil
27
+ @field_names = {
28
+ 'name' => 'shopify_domain', # sample example: demo-chirag-parmar.myshopify.com
29
+ 'shopify_email' => 'email', # chirag.p@hulkapps.com
30
+ 'shopify_token' => 'shopify_token',
31
+ 'shopify_plan' => 'plan_name', # partner_test
32
+ 'plan_id' => 'plan_id', # 1
33
+ 'created_at' => 'created_at', # 2022-04-15 10:43:05
34
+ 'trial_activated_at' => 'trial_activated_at',
35
+ 'email' => 'email'
36
+ }
37
+ @fs = AppManager::FailSafe.new
38
+ end
39
+
40
+ def expires_in
41
+ @expires_in
42
+ end
43
+
44
+ def enable_caching
45
+ @enable_caching
46
+ end
47
+
48
+ def plan_features
49
+ @plan_features
50
+ end
51
+
52
+ def app_url
53
+ @app_url
54
+ end
55
+
56
+ def shopify_api_key
57
+ @shopify_api_key
58
+ end
59
+
60
+ def shopify_api_version
61
+ @shopify_api_version
62
+ end
63
+
64
+ def shopify_table_name
65
+ @shopify_table_name
66
+ end
67
+
68
+ def shopify_domain_field
69
+ @shopify_domain_field
70
+ end
71
+
72
+ def plan_id_or_name_field
73
+ @plan_id_or_name_field
74
+ end
75
+
76
+ def field_names
77
+ @field_names
78
+ end
79
+
80
+
81
+ end
82
+ end
@@ -0,0 +1,324 @@
1
+ require 'json'
2
+ require 'date'
3
+ require 'time'
4
+ module AppManager
5
+
6
+ class FailSafe
7
+
8
+ def initialize(db_name='app_manager_local')
9
+ @apm_db = SQLite3::Database.open "db/#{db_name}.db"
10
+ @apm_db.results_as_hash = true
11
+ end
12
+
13
+ def save_api_data(params)
14
+ Thread.new do
15
+ save_api_plans(params["plans"])
16
+ end
17
+ Thread.new do
18
+ save_api_charges(params["charges"])
19
+ end
20
+ Thread.new do
21
+ save_api_apps(params["apps"])
22
+ end
23
+ Thread.new do
24
+ save_api_app_structures(params["app_structures"])
25
+ end
26
+ Thread.new do
27
+ save_api_discount_plans(params["discount_plans"])
28
+ end
29
+ Thread.new do
30
+ save_api_extend_trials(params["extend_trials"])
31
+ end
32
+ end
33
+
34
+ def save_api_plans(plans)
35
+ @apm_db.execute("DROP TABLE IF EXISTS plans;")
36
+ @apm_db.execute "CREATE TABLE IF NOT EXISTS plans(id integer,type varchar(255), name varchar(255), price float, offer_text varchar(255), interval text, shopify_plans text, trial_days integer, test boolean, on_install integer, is_custom boolean, app_id integer, base_plan integer, created_at datetime, updated_at datetime, public boolean, discount integer, cycle_count integer, store_base_plan boolean, discount_type varchar(255), affiliate text, features text)"
37
+
38
+ if plans.any?
39
+ plans.each do |plan|
40
+ interval = {}
41
+ shopify_plans = []
42
+ affiliate = []
43
+ features = {}
44
+ interval = plan["interval"].each{|e|e} if plan["interval"] rescue {}
45
+ shopify_plans = plan["shopify_plans"].map{|e| e.to_h} if plan["shopify_plans"] rescue []
46
+ affiliate = plan["affiliate"].map{|e|e.to_h} if plan["affiliate"] rescue []
47
+ features = plan["features"].map{|e|e.to_h} rescue []
48
+ plan_test = plan['test'].nil? ? 0 : plan['test']
49
+ is_custom = plan['is_custom'] ? 1 : 0
50
+ public_val = plan['public'] ? 1 : 0
51
+ store_base_plan = plan['store_base_plan'] ? 1 : 0
52
+ @apm_db.execute("INSERT INTO plans ( id , type , name , price , offer_text , interval , shopify_plans , trial_days , test , on_install , is_custom , app_id , base_plan , created_at, updated_at , public , discount , cycle_count , store_base_plan , discount_type, affiliate, features ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",plan["id"], plan["type"], plan["name"], plan["price"], plan["offer_text"], "#{interval}", "#{shopify_plans}", plan["trial_days"], plan_test, plan["on_install"], is_custom, plan["app_id"], plan["base_plan"], plan["created_at"], plan["updated_at"],public_val, plan["discount"], plan["cycle_count"], store_base_plan, plan["discount_type"], "#{affiliate}", "#{features}")
53
+ end
54
+ end
55
+ end
56
+
57
+
58
+ def save_api_charges(charges)
59
+ @apm_db.execute("DROP TABLE IF EXISTS charges;")
60
+ @apm_db.execute "CREATE TABLE IF NOT EXISTS charges(id INTEGER PRIMARY KEY,charge_id varchar(255),test boolean, status varchar(255),name varchar(255), type varchar(255), price float,interval varchar(255),trial_days integer,billing_on datetime,activated_on datetime,trial_ends_on datetime,cancelled_on datetime, expires_on datetime,plan_id integer,description text,shop_domain varchar(255),created_at datetime, updated_at datetime, app_id integer, sync boolean DEFAULT 0,process_type varchar(255))"
61
+ if charges.any?
62
+ charges.each do |charge|
63
+ @apm_db.execute("INSERT INTO charges (id ,charge_id ,test , status ,name , type , price ,interval ,trial_days ,billing_on ,activated_on ,trial_ends_on ,cancelled_on , expires_on ,plan_id ,description ,shop_domain ,created_at , updated_at, app_id, sync ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", nil,charge["charge_id"],charge["test"],charge["status"],charge["name"],charge["type"],charge["price"],charge["interval"],charge["trial_days"],charge["billing_on"],charge["activated_on"],charge["trial_ends_on"],charge["cancelled_on"],charge["expires_on"],charge["plan_id"],charge["description"],charge["shop_domain"],charge["created_at"],charge["updated_at"],charge["app_id"],1)
64
+ end
65
+ end
66
+ end
67
+
68
+
69
+ def save_api_apps(apps)
70
+ @apm_db.execute("DROP TABLE IF EXISTS apps;")
71
+ @apm_db.execute "CREATE TABLE IF NOT EXISTS apps(id integer,name varchar(255),slug varchar(255),url varchar(255),image varchar(255),api_token varchar(255),slack varchar(255), created_at datetime, updated_at datetime)"
72
+ if apps.any?
73
+ apps.each do |app|
74
+ @apm_db.execute("INSERT INTO apps (id ,name ,slug ,url ,image ,api_token ,slack , created_at , updated_at ) VALUES (?,?,?,?,?,?,?,?,?)", app['id'],app['name'],app['slug'],app['url'],app['image'],app['api_token'],app['slack'],app['created_at'],app['updated_at'])
75
+ end
76
+ end
77
+ end
78
+
79
+
80
+ def save_api_app_structures(app_structures)
81
+ @apm_db.execute("DROP TABLE IF EXISTS app_structures;")
82
+ @apm_db.execute "CREATE TABLE IF NOT EXISTS app_structures(banners text)"
83
+ if !app_structures.nil?
84
+ @apm_db.execute("INSERT INTO app_structures (banners) VALUES (?)", "#{app_structures.to_h}")
85
+ end
86
+ end
87
+
88
+ def save_api_discount_plans(discount_plans)
89
+ @apm_db.execute("DROP TABLE IF EXISTS discount_plans;")
90
+ @apm_db.execute "CREATE TABLE IF NOT EXISTS discount_plans(id integer,discount integer,shop_domain varchar(255),cycle_count integer,plan_id integer, created_by integer,created_at datetime,updated_at datetime,app_id integer,discount_type varchar(255))"
91
+ if discount_plans.any?
92
+ discount_plans.each do |discount_plan|
93
+ @apm_db.execute("INSERT INTO discount_plans (id ,discount ,shop_domain ,cycle_count ,plan_id , created_by ,created_at ,updated_at ,app_id ,discount_type ) VALUES (?,?,?,?,?,?,?,?,?,?)", discount_plan['id'],discount_plan['discount'],discount_plan['shop_domain'],discount_plan['cycle_count'],discount_plan['plan_id'],discount_plan['created_by'],discount_plan['created_at'],discount_plan['updated_at'],discount_plan['app_id'],discount_plan['discount_type'])
94
+ end
95
+ end
96
+ end
97
+
98
+ def save_api_extend_trials(extend_trials)
99
+ @apm_db.execute("DROP TABLE IF EXISTS extend_trials;")
100
+ @apm_db.execute "CREATE TABLE IF NOT EXISTS extend_trials(id integer,shop_domain varchar(255),plan_id integer,app_id integer,days integer,created_by integer,created_at datetime,updated_at datetime,extend_trial_start_at datetime)"
101
+ if extend_trials.any?
102
+ extend_trials.each do |extend_trial|
103
+ @apm_db.execute("INSERT INTO extend_trials (id ,shop_domain ,plan_id ,app_id ,days ,created_by ,created_at ,updated_at ,extend_trial_start_at ) VALUES (?,?,?,?,?,?,?,?,?)", extend_trial['id'], extend_trial['shop_domain'], extend_trial['plan_id'], extend_trial['app_id'], extend_trial['days'], extend_trial['created_by'], extend_trial['created_at'], extend_trial['updated_at'], extend_trial['extend_trial_start_at'])
104
+ end
105
+ end
106
+ end
107
+
108
+
109
+ def get_local_app_structures
110
+ app_structures = {}
111
+ app_structures = @apm_db.execute( "SELECT * FROM app_structures;" ) rescue {}
112
+ if app_structures.any?
113
+ new_app_structure = {}
114
+ app_structures.first.each_with_index do |(key, value), index|
115
+ val = eval(value)
116
+ new_app_structure[key] = val unless key.class == Integer
117
+ end
118
+ app_structures = new_app_structure
119
+ end
120
+
121
+ return app_structures
122
+ end
123
+
124
+
125
+ def get_local_plans
126
+ plans = []
127
+ @apm_db.execute( "SELECT * FROM plans;") do |plan|
128
+ new_plan = {}
129
+ plan.each_with_index do |(key, value), index|
130
+ if ['interval'].include?(key)
131
+ val = eval(value)
132
+ new_plan[key] = val
133
+ new_plan[key] = val['value'] if val rescue {}
134
+ elsif ['shopify_plans'].include?(key)
135
+ val = eval(value)
136
+ new_plan[key] = val.collect{|e|e['value']}
137
+ elsif ['affiliate'].include?(key)
138
+ new_plan[key] = eval(value)
139
+ elsif ['is_custom','public','store_base_plan'].include?(key)
140
+ new_plan[key] = (value == 0 ? false : true)
141
+ elsif ['test'].include?(key)
142
+ new_plan[key] = (value == 0 ? nil : true)
143
+ elsif ['features'].include?(key)
144
+ value = eval(value)
145
+ value = value.each {|e| e.delete("id")}.each {|e| e.delete("created_at")}.each {|e| e.delete("updated_at")}.group_by{|h| h['feature_id']}
146
+ new_feature = {}
147
+ value.each_with_index do |(k, v), index|
148
+ new_feature[k] = v.first if v.class == Array
149
+ end
150
+ new_plan[key] = new_feature
151
+ else
152
+ new_plan[key] = value unless key.class == Integer
153
+ end
154
+ end
155
+ plans.push(new_plan)
156
+ end
157
+ return plans
158
+ end
159
+
160
+ def get_local_plan(params)
161
+ plan_data = {}
162
+ if params.any?
163
+ if params["plan_id"].present? && !params["plan_id"].nil?
164
+ @apm_db.execute( "SELECT * FROM plans WHERE id = ?", params["plan_id"]) do |plan|
165
+ new_plan = {}
166
+ plan.each_with_index do |(key, value), index|
167
+ if ['interval'].include?(key)
168
+ val = eval(value)
169
+ new_plan[key] = val
170
+ elsif ['shopify_plans','affiliate','features'].include?(key)
171
+ new_plan[key] = eval(value)
172
+ elsif ['is_custom','public','store_base_plan'].include?(key)
173
+ new_plan[key] = (value == 0 ? false : true)
174
+ elsif ['test'].include?(key)
175
+ new_plan[key] = (value == 0 ? nil : true)
176
+ else
177
+ new_plan[key] = value unless key.class == Integer
178
+ end
179
+ end
180
+ plan_data = new_plan
181
+ app = {}
182
+ @apm_db.execute( "SELECT * FROM apps;") do |app|
183
+ app_data = {}
184
+ app.each_with_index do |(key, value), index|
185
+ app_data[key] = value unless key.class == Integer
186
+ end
187
+ plan_data['app'] = app_data
188
+ end
189
+
190
+ if params["shop_domain"].present? && plan_data
191
+ @apm_db.execute( "SELECT * FROM discount_plans WHERE plan_id = ? AND shop_domain = ? ", params["plan_id"],params["shop_domain"]) do |cd|
192
+ plan_data['discount'] = cd['discount'] if cd rescue plan_data['discount']
193
+ plan_data['discount_type'] = cd['discount_type'] if cd rescue plan_data['discount_type']
194
+ plan_data['cycle_count'] = cd['cycle_count'] if cd rescue plan_data['cycle_count']
195
+ end
196
+ end
197
+
198
+
199
+ end
200
+ end
201
+
202
+ end
203
+ return plan_data
204
+ end
205
+
206
+ def get_local_remaining_days(params,options)
207
+ @remaining_days = 0
208
+ @shop_domain = params['shop_domain']
209
+ if params && params['trial_activated_at'].present? && !params['trial_activated_at'].nil? && params['shop_domain'].present? && params['plan_id'].present? && !params['plan_id'].nil?
210
+ @trial_activated_at = params['trial_activated_at']
211
+ @plan_id = params['plan_id']
212
+ plan_data = @apm_db.execute( "SELECT * FROM plans WHERE id = ?", @plan_id)
213
+ if plan_data.any?
214
+ trial_days = plan_data.first['trial_days']
215
+ trial_start_date = Date.parse(@trial_activated_at)
216
+ trial_end_date = trial_start_date + trial_days.days
217
+ if trial_end_date > DateTime.now
218
+ remaining_days = (trial_end_date - DateTime.now).to_i
219
+ end
220
+ trial_extension_data = @apm_db.execute( "SELECT * FROM extend_trials WHERE shop_domain = ? AND plan_id = ? ORDER BY extend_trial_start_at DESC ",@shop_domain, @plan_id)
221
+ if trial_extension_data.any?
222
+ trial_extension_data = trial_extension_data.first
223
+ extend_trial_date = Date.parse(trial_extension_data['created_at']) + trial_extension_data['days'].to_i.days
224
+ remaining_extended_days = DateTime.now < extend_trial_date ? (extend_trial_date - DateTime.now).to_i : 0
225
+ @remaining_days = @remaining_days + remaining_extended_days
226
+ end
227
+ end
228
+ return @remaining_days
229
+ end
230
+
231
+ @charges = @apm_db.execute( "SELECT * FROM charges WHERE shop_domain = ? ORDER BY created_at DESC ",@shop_domain)
232
+ if @charges.any?
233
+ charge = @charges.first
234
+ if charge['trial_days']
235
+ trial_end_date = Date.parse(charge['trial_ends_on'])
236
+ if DateTime.now < trial_end_date
237
+ @remaining_days = (trial_end_date - DateTime.now).to_i
238
+ end
239
+ trial_extension_data = @apm_db.execute( "SELECT * FROM extend_trials WHERE shop_domain = ? AND plan_id = ? ORDER BY extend_trial_start_at DESC ",@shop_domain, charge["plan_id"])
240
+ if trial_extension_data.any?
241
+ trial_extension_data = trial_extension_data.first
242
+ extend_trial_date = Date.parse(trial_extension_data['created_at']) + trial_extension_data['days'].to_i.days
243
+ remaining_extended_days = DateTime.now < extend_trial_date ? (extend_trial_date - DateTime.now).to_i : 0
244
+ @remaining_days = @remaining_days + remaining_extended_days
245
+ end
246
+ end
247
+ return @remaining_days
248
+ end
249
+ end
250
+
251
+
252
+ def get_local_charge(params,options)
253
+ charge_data = nil
254
+ if params["shop_domain"].present?
255
+ @apm_db.execute( "SELECT * FROM charges WHERE status = ? AND shop_domain = ? ",'active',params["shop_domain"]) do |charge|
256
+ if charge
257
+ charge_values = {}
258
+ charge.each_with_index do |(key, value), index|
259
+ charge_values[key] = value unless key.class == Integer
260
+ end
261
+ charge_data = charge_values
262
+ break
263
+ end
264
+ end
265
+ end
266
+ return charge_data
267
+ end
268
+
269
+
270
+ def store_local_charge(params,options)
271
+ message = {"message" => 'fail'}
272
+ if options
273
+ options.gsub!('null','nil') rescue nil
274
+ charge = eval(options) rescue nil
275
+ if charge
276
+ charge = charge.as_json if charge.class == Hash
277
+ test_value = charge["test"] == true ? 1 : 0
278
+ plan_id = charge["plan_id"].to_i
279
+ begin
280
+ @charge = @apm_db.execute("INSERT INTO charges (id, charge_id ,test , status ,name , type , price ,interval ,trial_days ,billing_on ,activated_on ,trial_ends_on ,cancelled_on , expires_on ,plan_id ,description ,shop_domain ,created_at , updated_at, sync ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",nil,"#{charge["charge_id"]}",test_value,charge["status"],charge["name"],charge["type"],charge["price"],charge["interval"],charge["trial_days"],charge["billing_on"],charge["activated_on"],charge["trial_ends_on"],charge["cancelled_on"],charge["expires_on"],plan_id,charge["description"],charge["shop_domain"],charge["created_at"],charge["updated_at"],0)
281
+ message = {"message" => 'success'}
282
+ rescue Exception => e
283
+ Rails.logger.info ">>>>>>>>> Charge not saved on local DB due to #{e.inspect}"
284
+ end
285
+ end
286
+ end
287
+ return message
288
+ end
289
+
290
+ def store_cancel_charge(params,options)
291
+ message = {"message" => 'fail'}
292
+ if options && options[:shop_domain].present? && options[:plan_id].present?
293
+ time = "#{DateTime.now}"
294
+ @apm_db.execute( "UPDATE charges SET status= ?, cancelled_on = ?, sync = ? WHERE plan_id = ? AND shop_domain = ? ",'cancelled',time,0,options[:plan_id],options[:shop_domain])
295
+ message = {"message" => 'success'}
296
+ end
297
+ return message
298
+ end
299
+
300
+
301
+
302
+ def sync_app_manager
303
+ plan_obj = AppManager::Client.new
304
+ response = plan_obj.get_status
305
+ if response && response.code == 200
306
+ @apm_db.execute( "SELECT * FROM charges WHERE sync = ?", 0) do |charge|
307
+ if charge
308
+ if !charge["cancelled_on"].nil?
309
+ charge["cancelled_on"] = Date.parse(charge["cancelled_on"])
310
+ end
311
+ plan_ob = AppManager::Client.new(nil,json_req=true)
312
+ res = plan_ob.sync_charge(charge.to_json)
313
+ if res && res["message"] == "success"
314
+ @apm_db.execute( "UPDATE charges SET sync= ? WHERE charge_id = ?",1,charge['charge_id'])
315
+ end
316
+ end
317
+ end
318
+ end
319
+ end
320
+
321
+
322
+ end
323
+
324
+ end
@@ -0,0 +1,125 @@
1
+ module AppManager
2
+ class GraphqlHelper
3
+
4
+ def initialize(shopify_domain,shopify_token)
5
+ @api_key = AppManager.configuration.shopify_api_key || nil
6
+ @api_version = AppManager.configuration.shopify_api_version || nil
7
+ @shopify_domain = shopify_domain
8
+ @shopify_token = shopify_token
9
+ end
10
+
11
+ def rest_client
12
+
13
+ end
14
+
15
+ def api_call(query,is_json=false)
16
+ require 'uri'
17
+ require 'net/http'
18
+ if !@api_key.nil? && !@api_version.nil? && !@shopify_domain.nil? && !@shopify_token.nil?
19
+ url = URI("https://#{@api_key}:#{@shopify_token}@#{@shopify_domain}/admin/api/#{@api_version}/graphql.json")
20
+ http = Net::HTTP.new(url.host, url.port)
21
+ http.use_ssl = true
22
+ http.verify_mode = OpenSSL::SSL::VERIFY_PEER
23
+ request = Net::HTTP::Post.new(url)
24
+ request["X-Shopify-Access-Token"] = @shopify_token
25
+ request.body = query
26
+ request["Accept"] = 'application/json'
27
+ if is_json.present?
28
+ request["Content-Type"] = 'application/json'
29
+ else
30
+ request["Content-Type"] = 'application/graphql'
31
+ end
32
+ response = http.request(request)
33
+ response = ActiveSupport::JSON.decode(response.read_body) rescue nil
34
+ return response
35
+ else
36
+ Rails.logger.info "=== params missing from any of these api_key, api_version, shopify_domain, shopify_token ==="
37
+ return []
38
+ end
39
+ end
40
+
41
+ def run_graph_api(query,variables = '',is_retrieve_all = false,after = '',is_json = true)
42
+ query = query.dup.force_encoding("UTF-8")
43
+ if variables.present?
44
+ query = {"query": "#{query}","variables": variables }
45
+ end
46
+ if is_json
47
+ response = api_call(query.to_json,true)
48
+ else
49
+ response = api_call(query,false)
50
+ end
51
+ return response
52
+ end
53
+
54
+
55
+ def recurring_charge_api_call(plan,return_url,shop)
56
+ plan_test = nil
57
+ shop_plan_field = AppManager.configuration.field_names['shopify_plan'] rescue nil
58
+ if !plan['affiliate'].nil? && plan['affiliate'].any? && !shop_plan_field.nil? && plan['affiliate'].map{|e| e['value']}.include?(shop[shop_plan_field])
59
+ plan_test = true
60
+ end
61
+ trial_days = plan['trial_days'] || 0
62
+
63
+ if shop && shop.shopify_domain && trial_days
64
+ trial_activated_at_field = AppManager.configuration.field_names['trial_activated_at'] rescue nil
65
+ trial_activated_at = shop[trial_activated_at] rescue nil
66
+ plan_field = AppManager.configuration.plan_id_or_name_field rescue nil
67
+ plan_id_field = shop[@plan_field] rescue nil
68
+ remaining_obj = AppManager::Client.new
69
+ remaining = remaining_obj.get_remaining_days(shop.shopify_domain,trial_activated_at,plan_id_field)
70
+ trial_days = !remaining.nil? ? remaining : trial_days
71
+ end
72
+
73
+ discount_type = plan['discount_type'] || "percentage"
74
+ discount_val = discount_type == "percentage" ? (plan['discount'].to_f/ 100) : plan['discount']
75
+ plan_discount = plan['discount'] ? { "durationLimitInIntervals" => (plan['discount_interval'] || nil), "value" => {"#{discount_type}" => discount_val} } : {}
76
+
77
+ price_details = {
78
+ "price": { "amount": plan['price'], "currencyCode": 'USD' },
79
+ "interval": plan['interval']['value']
80
+ }
81
+ price_details << plan_discount if plan_discount.any?
82
+
83
+ query = 'mutation(
84
+ $name: String!,
85
+ $returnUrl: URL!,
86
+ $trialDays: Int,
87
+ $test: Boolean,
88
+ $lineItems: [AppSubscriptionLineItemInput!]!
89
+ ) {
90
+ appSubscriptionCreate(
91
+ name: $name,
92
+ returnUrl: $returnUrl,
93
+ trialDays: $trialDays,
94
+ test: $test,
95
+ lineItems: $lineItems
96
+ ) {
97
+ userErrors {
98
+ field
99
+ message
100
+ }
101
+ confirmationUrl
102
+ appSubscription {
103
+ id
104
+ }
105
+ }
106
+ }'
107
+
108
+ variables = {
109
+ "name": plan['name'],
110
+ "returnUrl": return_url,
111
+ "trialDays": trial_days,
112
+ "test": plan_test,
113
+ "lineItems": [{
114
+ "plan": {
115
+ "appRecurringPricingDetails": price_details
116
+ }
117
+ }]
118
+ }
119
+ data = run_graph_api(query,variables)
120
+ return data
121
+ end
122
+
123
+ end
124
+ end
125
+