app_manager 1.2.7 → 1.3.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.
@@ -5,540 +5,472 @@ require "fileutils"
5
5
 
6
6
  module AppManager
7
7
 
8
- class FailSafe
9
-
10
- def initialize(db_name='app_manager_local')
11
- @apm_db = SQLite3::Database.open "db/#{db_name}.db"
12
- begin
13
- FileUtils.chmod 0664, "db/#{db_name}.db"
14
- rescue Exception => e
15
- puts ">>>>>> #{e.inspect}"
16
- end
17
- @apm_db.results_as_hash = true
18
- create_plan_table
19
- create_charges_table
20
- create_apps_table
21
- create_app_structures_table
22
- create_discount_plans_table
23
- create_extend_trials_table
24
- create_plan_users_table
25
- end
26
-
27
- def save_api_data(params)
28
- begin
29
- save_api_plans(params["plans"])
30
- rescue Exception => e
31
- Rails.logger.info "APP MANAGER >>>> #{e.inspect}"
32
- begin
33
- create_plan_table
34
- save_api_plans(params["plans"])
35
- rescue Exception => e
36
- Rails.logger.info "APP MANAGER FailSafe >>>> #{e.inspect}"
37
- end
38
- end
39
-
40
-
41
- begin
42
- save_api_charges(params["charges"])
43
- rescue Exception => e
44
- Rails.logger.info "APP MANAGER >>>> #{e.inspect}"
45
- begin
46
- create_charges_table
47
- save_api_charges(params["charges"])
48
- rescue Exception => e
49
- Rails.logger.info "APP MANAGER FailSafe >>>> #{e.inspect}"
50
- end
51
- end
52
-
53
-
54
- begin
55
- save_api_apps(params["apps"])
56
- rescue Exception => e
57
- Rails.logger.info "APP MANAGER >>>> #{e.inspect}"
58
- begin
59
- create_apps_table
60
- save_api_apps(params["apps"])
61
- rescue Exception => e
62
- Rails.logger.info "APP MANAGER FailSafe >>>> #{e.inspect}"
63
- end
64
- end
65
-
66
-
67
- begin
68
- save_api_app_structures(params["app_structures"])
69
- rescue Exception => e
70
- Rails.logger.info "APP MANAGER >>>> #{e.inspect}"
71
- begin
72
- create_app_structures_table
73
- save_api_app_structures(params["app_structures"])
74
- rescue Exception => e
75
- Rails.logger.info "APP MANAGER FailSafe >>>> #{e.inspect}"
76
- end
77
- end
78
-
79
-
80
- begin
81
- save_api_discount_plans(params["discount_plans"])
82
- rescue Exception => e
83
- Rails.logger.info "APP MANAGER >>>> #{e.inspect}"
84
- begin
85
- create_discount_plans_table
86
- save_api_discount_plans(params["discount_plans"])
87
- rescue Exception => e
88
- Rails.logger.info "APP MANAGER FailSafe >>>> #{e.inspect}"
89
- end
90
- end
91
-
92
-
93
- begin
94
- save_api_extend_trials(params["extend_trials"])
95
- rescue Exception => e
96
- Rails.logger.info "APP MANAGER >>>> #{e.inspect}"
97
- begin
98
- create_extend_trials_table
99
- save_api_extend_trials(params["extend_trials"])
100
- rescue Exception => e
101
- Rails.logger.info "APP MANAGER FailSafe >>>> #{e.inspect}"
102
- end
103
- end
104
-
105
-
106
- begin
107
- save_api_plan_users(params["plan_users"])
108
- rescue Exception => e
109
- Rails.logger.info "APP MANAGER >>>> #{e.inspect}"
110
- begin
111
- create_plan_users_table
112
- save_api_plan_users(params["plan_users"])
113
- rescue Exception => e
114
- Rails.logger.info "APP MANAGER FailSafe >>>> #{e.inspect}"
115
- end
116
- end
117
- end
118
-
119
- def save_api_plans(plans)
120
- @apm_db.execute("DROP TABLE IF EXISTS plans;")
121
- create_plan_table
122
-
123
- if plans.any?
124
- plans.each do |plan|
125
- interval = {}
126
- shopify_plans = []
127
- affiliate = []
128
- features = {}
129
- interval = plan["interval"].each{|e|e} if plan["interval"] rescue {}
130
- shopify_plans = plan["shopify_plans"].map{|e| e.to_h} if plan["shopify_plans"] rescue []
131
- affiliate = plan["affiliate"].map{|e|e.to_h} if plan["affiliate"] rescue []
132
- features = plan["features"].map{|e|e.to_h} rescue []
133
- plan_test = plan['test'].nil? ? 0 : plan['test']
134
- is_custom = plan['is_custom'] ? 1 : 0
135
- public_val = plan['public'] ? 1 : 0
136
- store_base_plan = plan['store_base_plan'] ? 1 : 0
137
- choose_later_plan = plan['choose_later_plan'] ? 1 : 0
138
- @apm_db.execute("INSERT INTO plans ( id , type , name , price , offer_text, description , 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, choose_later_plan , discount_type, affiliate, features, deleted_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",plan["id"], plan["type"], plan["name"], plan["price"], plan["offer_text"], plan["description"], "#{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, choose_later_plan, plan["discount_type"], "#{affiliate}", "#{features}",plan["deleted_at"])
139
- end
140
- end
141
- end
142
-
143
-
144
- def save_api_charges(charges)
145
- @apm_db.execute("DROP TABLE IF EXISTS charges;")
146
- create_charges_table
147
- if charges.any?
148
- charges.each do |charge|
149
- charge_test = charge['test'] ? 1 : 0
150
- @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)
151
- end
152
- end
153
- end
154
-
155
-
156
- def save_api_apps(apps)
157
- @apm_db.execute("DROP TABLE IF EXISTS apps;")
158
- create_apps_table
159
- if apps.any?
160
- apps.each do |app|
161
- @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'])
162
- end
163
- end
164
- end
165
-
166
-
167
- def save_api_app_structures(app_structures)
168
- @apm_db.execute("DROP TABLE IF EXISTS app_structures;")
169
- create_app_structures_table
170
- if !app_structures.nil?
171
- @apm_db.execute("INSERT INTO app_structures (banners) VALUES (?)", "#{app_structures.to_h}")
172
- end
173
- end
174
-
175
- def save_api_discount_plans(discount_plans)
176
- @apm_db.execute("DROP TABLE IF EXISTS discount_plans;")
177
- create_discount_plans_table
178
- if discount_plans.any?
179
- discount_plans.each do |discount_plan|
180
- @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'])
181
- end
182
- end
183
- end
184
-
185
- def save_api_extend_trials(extend_trials)
186
- @apm_db.execute("DROP TABLE IF EXISTS extend_trials;")
187
- create_extend_trials_table
188
- if extend_trials.any?
189
- extend_trials.each do |extend_trial|
190
- @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'])
191
- end
192
- end
193
- end
194
-
195
- def save_api_plan_users(plan_users)
196
- @apm_db.execute("DROP TABLE IF EXISTS plan_users;")
197
- create_plan_users_table
198
- if plan_users.any?
199
- plan_users.each do |plan_user|
200
- @apm_db.execute("INSERT INTO plan_users (id ,shop_domain, plan_id, created_by, created_at, updated_at ) VALUES (?,?,?,?,?,?)", plan_user['id'], plan_user['shop_domain'], plan_user['plan_id'], plan_user['created_by'], plan_user['created_at'], plan_user['updated_at'])
201
- end
202
- end
203
- end
204
-
205
-
206
- def get_local_app_structures
207
- app_structures = {}
208
- app_structures = @apm_db.execute( "SELECT * FROM app_structures;" ) rescue {}
209
- if app_structures.any?
210
- new_app_structure = {}
211
- app_structures.first.each_with_index do |(key, value), index|
212
- val = eval(value)
213
- new_app_structure[key] = val unless key.class == Integer
214
- end
215
- app_structures = new_app_structure
216
- end
217
-
218
- return app_structures
219
- end
220
-
221
- def create_plan_table
222
- @apm_db.execute "CREATE TABLE IF NOT EXISTS plans(id integer,type varchar(255), name varchar(255), price float, offer_text varchar(255), description 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, choose_later_plan boolean, discount_type varchar(255), affiliate text, features text, deleted_at datetime)"
223
- end
224
-
225
- def create_charges_table
226
- @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))"
227
- end
228
-
229
- def create_apps_table
230
- @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)"
231
- end
232
-
233
- def create_app_structures_table
234
- @apm_db.execute "CREATE TABLE IF NOT EXISTS app_structures(banners text)"
235
- end
236
-
237
- def create_discount_plans_table
238
- @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))"
239
- end
240
-
241
- def create_extend_trials_table
242
- @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)"
243
- end
244
-
245
- def create_plan_users_table
246
- @apm_db.execute "CREATE TABLE IF NOT EXISTS plan_users(id integer,shop_domain varchar(255),plan_id integer,created_by integer,created_at datetime,updated_at datetime)"
247
- end
248
-
249
-
250
- def get_local_plans(params)
251
-
252
- plans_data = []
253
-
254
- active_plan_id = nil
255
- active_charge_price = nil
256
-
257
- charges = @apm_db.execute( "SELECT * FROM charges WHERE shop_domain = ? ",params['shop_domain'])
258
-
259
- if charges.any?
260
- active_plan_id = charges.first['plan_id']
261
- active_charge_price = charges.first['price']
262
- elsif params['active_plan_id'].present? && !params['active_plan_id'].nil?
263
- active_plan_id = params['active_plan_id']
264
- plan_data = @apm_db.execute( "SELECT * FROM plans WHERE id = ?", active_plan_id)
265
- active_charge_price = plan_data.first['price'] if plan_data.any?
266
- end
267
-
268
- custom_plan_ids = []
269
- plan_users = @apm_db.execute( "SELECT * FROM plan_users WHERE shop_domain = ? ",params['shop_domain'])
270
- custom_plan_ids = plan_users.collect{|e|e['plan_id']} if plan_users.any?
271
-
272
- custom_plan_base_ids = []
273
- plan_data = @apm_db.execute( "SELECT * FROM plans WHERE id IN (?) AND base_plan IS NOT NULL;",custom_plan_ids)
274
- custom_plan_base_ids = plan_data.collect{|e|e['base_plan']} if plan_data.any?
275
-
276
- if active_plan_id && custom_plan_base_ids.include?(active_plan_id)
277
- custom_plan_base_ids.delete(active_plan_id)
278
- end
279
-
280
- if custom_plan_base_ids.any?
281
- plans = @apm_db.execute( "SELECT * FROM plans WHERE (public = ? OR id IN (?)) AND id NOT IN (?)", 1,custom_plan_ids,custom_plan_base_ids)
282
- else
283
- plans = @apm_db.execute( "SELECT * FROM plans WHERE (public = ? OR id IN (?))", 1,custom_plan_ids)
284
- end
285
-
286
- if plans.any?
287
-
288
- plans.each do |plan|
289
- new_plan = {}
290
- plan.each_with_index do |(key, value), index|
291
- if ['interval'].include?(key)
292
- val = eval(value)
293
- new_plan[key] = val
294
- new_plan[key] = val['value'] if val rescue {}
295
- elsif ['shopify_plans'].include?(key)
296
- val = eval(value)
297
- new_plan[key] = val.collect{|e|e['value']}
298
- elsif ['affiliate'].include?(key)
299
- new_plan[key] = eval(value)
300
- elsif ['is_custom','public','store_base_plan','choose_later_plan'].include?(key)
301
- new_plan[key] = (value == 0 ? false : true)
302
- elsif ['test'].include?(key)
303
- new_plan[key] = (value == 0 ? nil : true)
304
- elsif ['features'].include?(key)
305
- value = eval(value)
306
- value = value.each {|e| e.delete("id")}.each {|e| e.delete("created_at")}.each {|e| e.delete("updated_at")}
307
- new_plan[key] = value
308
- else
309
- new_plan[key] = value unless key.class == Integer
310
- end
311
- end
312
- plans_data.push(new_plan)
313
- end
314
-
315
- features_by_plans = plans_data.collect{|e|e['features']}
316
- if features_by_plans.any? && AppManager.configuration.plan_features.any?
317
- features_by_plans_data = []
318
- features = AppManager.configuration.plan_features
319
- features_by_plans.each do |features_by_plan|
320
- features_by_plan.each do |fp|
321
- fp['name'] = features.find{|e| e['uuid'] == fp['feature_id']}['name'] rescue nil
322
- fp['format'] = features.find{|e| e['uuid'] == fp['feature_id']}['format'] rescue nil
323
- fp['slug'] = features.find{|e| e['uuid'] == fp['feature_id']}['slug'] rescue nil
324
- features_by_plans_data.push(fp)
325
- end
326
- end
327
- end
328
-
329
-
330
- custom_discounts_data = []
331
- if params["shop_domain"].present? && plan_data
332
- custom_discounts = @apm_db.execute( "SELECT * FROM discount_plans WHERE shop_domain = ? ORDER BY created_at DESC", params["shop_domain"])
333
- if custom_discounts.any?
334
- custom_discounts.each do |custom_discount|
335
- new_custom_discount = {}
336
- custom_discount.each_with_index do |(key, value), index|
337
- new_custom_discount[key] = value unless key.class == Integer
338
- end
339
- custom_discounts_data.push(new_custom_discount)
340
- end
341
- end
342
- end
343
-
344
- plans_data.each do |plan|
345
- if (!active_plan_id.nil? && plan['id'] == active_plan_id)
346
- plan['price'] = active_charge_price
347
- end
348
-
349
- if custom_discounts_data.any? && custom_discounts_data.select{|e| e['plan_id'] == plan['id']}.size > 0
350
- cd_hash = {}
351
- custom_discounts_data.select{|e| e['plan_id'] == plan['id']}.each do |cd|
352
- plan['discount'] = cd['discount']
353
- plan['discount_type'] = cd['discount_type']
354
- plan['cycle_count'] = cd['cycle_count']
355
- end
356
- end
357
-
358
- if features_by_plans_data.select{|e| e['plan_id'] == plan['id']}.size > 0
359
- feature_hash = {}
360
- features_by_plans_data.select{|e| e['plan_id'] == plan['id']}.each do |fp|
361
- feature_hash[fp["feature_id"]] = fp
362
- end
363
- features = feature_hash
364
- else
365
- features = nil
366
- end
367
- plan['features'] = features
368
- plan['old_plan_id'] = nil
369
-
370
- end
371
-
372
- plans = plans_data
373
- end
374
-
375
-
376
- return plans
377
- end
378
-
379
- def get_local_plan(params)
380
- plan_data = {}
381
- if params.any?
382
- if params["plan_id"].present? && !params["plan_id"].nil?
383
- @apm_db.execute( "SELECT * FROM plans WHERE id = ?", params["plan_id"]) do |plan|
384
- new_plan = {}
385
- plan.each_with_index do |(key, value), index|
386
- if ['interval'].include?(key)
387
- val = eval(value)
388
- new_plan[key] = val
389
- elsif ['shopify_plans','affiliate','features'].include?(key)
390
- new_plan[key] = eval(value)
391
- elsif ['is_custom','public','store_base_plan','choose_later_plan'].include?(key)
392
- new_plan[key] = (value == 0 ? false : true)
393
- elsif ['test'].include?(key)
394
- new_plan[key] = (value == 0 ? nil : true)
395
- else
396
- new_plan[key] = value unless key.class == Integer
397
- end
398
- end
399
- plan_data = new_plan
400
- app = {}
401
- @apm_db.execute( "SELECT * FROM apps;") do |app|
402
- app_data = {}
403
- app.each_with_index do |(key, value), index|
404
- app_data[key] = value unless key.class == Integer
405
- end
406
- plan_data['app'] = app_data
407
- end
408
- plan_data['old_plan_id'] = nil # Temporary for migration puspose only
409
- if params["shop_domain"].present? && plan_data
410
- @apm_db.execute( "SELECT * FROM discount_plans WHERE plan_id = ? AND shop_domain = ? ", params["plan_id"],params["shop_domain"]) do |cd|
411
- plan_data['discount'] = cd['discount'] if cd rescue plan_data['discount']
412
- plan_data['discount_type'] = cd['discount_type'] if cd rescue plan_data['discount_type']
413
- plan_data['cycle_count'] = cd['cycle_count'] if cd rescue plan_data['cycle_count']
414
- end
415
- end
416
-
417
-
418
- end
419
- end
420
-
421
- end
422
-
423
- return plan_data
424
- end
425
-
426
- def get_local_remaining_days(params,options)
427
- @remaining_days = 0
428
- @shop_domain = params['shop_domain']
429
- if params && params['trial_activated_at'].present? && !params['trial_activated_at'].nil? && params['shop_domain'].present? && params['plan_id'].present? && !params['plan_id'].nil?
430
- @trial_activated_at = params['trial_activated_at']
431
- @plan_id = params['plan_id']
432
- plan_data = @apm_db.execute( "SELECT * FROM plans WHERE id = ?", @plan_id)
433
- if plan_data.any?
434
- trial_days = plan_data.first['trial_days']
435
- trial_start_date = Date.parse(@trial_activated_at)
436
- trial_end_date = trial_start_date + trial_days.days
437
- if trial_end_date > DateTime.now
438
- remaining_days = (trial_end_date - DateTime.now).to_i
439
- end
440
- 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)
441
- if trial_extension_data.any?
442
- trial_extension_data = trial_extension_data.first
443
- extend_trial_date = Date.parse(trial_extension_data['created_at']) + trial_extension_data['days'].to_i.days
444
- remaining_extended_days = DateTime.now < extend_trial_date ? (extend_trial_date - DateTime.now).to_i : 0
445
- @remaining_days = @remaining_days + remaining_extended_days
446
- end
447
- end
448
- return @remaining_days
8
+ class FailSafe
9
+
10
+ def initialize(db_name = 'app_manager_local')
11
+ begin
12
+ FileUtils.chmod 0664, "db/#{db_name}.db"
13
+ rescue Exception => e
14
+ puts ">>>>>> #{e.inspect}"
15
+ end
16
+ # @apm_db = SQLite3::Database.open "db/#{db_name}.db"
17
+ # @apm_db.results_as_hash = true
18
+ end
19
+
20
+ def save_api_data(params)
21
+ begin
22
+ save_api_plans(params["plans"])
23
+ rescue Exception => e
24
+ Rollbar.error("[api_plans] APP MANAGER >>>> #{e.inspect}")
25
+ end
26
+
27
+ begin
28
+ save_api_charges(params["charges"])
29
+ rescue Exception => e
30
+ Rollbar.error("[api_charges] APP MANAGER >>>> #{e.inspect}")
31
+ end
32
+
33
+ begin
34
+ save_api_apps(params["apps"])
35
+ rescue Exception => e
36
+ Rollbar.error("[save_api_apps] APP MANAGER >>>> #{e.inspect}")
37
+ end
38
+
39
+ begin
40
+ save_api_app_structures(params["app_structures"])
41
+ rescue Exception => e
42
+ Rollbar.error("[save_api_app_structures] APP MANAGER >>>> #{e.inspect}")
43
+ end
44
+
45
+ begin
46
+ save_api_discount_plans(params["discount_plans"])
47
+ rescue Exception => e
48
+ Rollbar.error("[Discount Plans] APP MANAGER >>>> #{e.inspect}")
49
+ end
50
+
51
+ begin
52
+ save_api_extend_trials(params["extend_trials"])
53
+ rescue Exception => e
54
+ Rollbar.error("[Extens Trials] APP MANAGER >>>> #{e.inspect}")
55
+ end
56
+
57
+ begin
58
+ save_api_plan_users(params["plan_users"])
59
+ rescue Exception => e
60
+ Rollbar.error("[Plan User] APP MANAGER >>>> #{e.inspect}")
61
+ end
62
+ end
63
+
64
+ def save_api_plans(plans)
65
+ AppManager::Plan.destroy_all
66
+ if plans.any?
67
+ plans.each do |plan|
68
+ interval = {}
69
+ shopify_plans = []
70
+ affiliate = []
71
+ interval = plan["interval"].each { |e| e } if plan["interval"] rescue {}
72
+ shopify_plans = plan["shopify_plans"].map { |e| e.to_h } if plan["shopify_plans"] rescue []
73
+ affiliate = plan["affiliate"].map { |e| e.to_h } if plan["affiliate"] rescue []
74
+ features = plan["features"].map { |e| e.to_h } rescue []
75
+ plan_test = plan['test'].nil? ? 0 : plan['test']
76
+ is_custom = plan['is_custom'] ? 1 : 0
77
+ public_val = plan['public'] ? 1 : 0
78
+ store_base_plan = plan['store_base_plan'] ? 1 : 0
79
+ choose_later_plan = plan['choose_later_plan'] ? 1 : 0
80
+ AppManager::Plan.create(id: plan["id"], type: plan["type"], name: plan["name"], price: plan["price"], offer_text: plan["offer_text"], description: plan["description"], interval: interval, shopify_plans: shopify_plans, trial_days: plan["trial_days"], test: plan_test, on_install: plan["on_install"], is_custom: is_custom, app_id: plan["app_id"], base_plan: plan["base_plan"], created_at: plan["created_at"], updated_at: plan["updated_at"], public: public_val, discount: plan["discount"], cycle_count: plan["cycle_count"], store_base_plan: store_base_plan, choose_later_plan: choose_later_plan, discount_type: plan["discount_type"], affiliate: affiliate, features: features, deleted_at: plan["deleted_at"])
81
+ end
82
+ end
83
+ end
84
+
85
+
86
+ def save_api_charges(charges)
87
+ AppManager::Charge.destroy_all
88
+ if charges.any?
89
+ charges.each do |charge|
90
+ charge_test = charge['test'] ? true : false
91
+ AppManager::Charge.create(charge_id: charge["charge_id"], test: charge_test, status: charge["status"], name: charge["name"], type: charge["type"], price: charge["price"], interval: charge["interval"], trial_days: charge["trial_days"], billing_on: charge["billing_on"], activated_on: charge["activated_on"], trial_ends_on: charge["trial_ends_on"], cancelled_on: charge["cancelled_on"], expires_on: charge["expires_on"], plan_id: charge["plan_id"], description: charge["description"], shop_domain: charge["shop_domain"], created_at: charge["created_at"], updated_at: charge["updated_at"], app_id: charge["app_id"], sync: true)
92
+ end
93
+ end
94
+ end
95
+
96
+
97
+ def save_api_apps(apps)
98
+ AppManager::App.destroy_all
99
+ if apps.any?
100
+ apps.each do |app|
101
+ AppManager::App.create(id: app['id'], name: app['name'], slug: app['slug'], url: app['url'], image: app['image'], api_token: app['api_token'], slack: app['slack'], created_at: app['created_at'], updated_at: app['updated_at'])
102
+ end
103
+ end
104
+ end
105
+
106
+ #Complete
107
+ def save_api_app_structures(app_structures)
108
+ AppManager::AppStructure.destroy_all
109
+ AppManager::AppStructure.create(banners: app_structures.to_h)
110
+ end
111
+
112
+ def save_api_discount_plans(discount_plans)
113
+ AppManager::DiscountPlan.destroy_all
114
+ if discount_plans.any?
115
+ discount_plans.each do |discount_plan|
116
+ AppManager::DiscountPlan.create(id: discount_plan['id'], discount: discount_plan['discount'], shop_domain: discount_plan['shop_domain'], cycle_count: discount_plan['cycle_count'], plan_id: discount_plan['plan_id'], created_by: discount_plan['created_by'], created_at: discount_plan['created_at'], updated_at: discount_plan['updated_at'], app_id: discount_plan['app_id'], discount_type: discount_plan['discount_type'])
449
117
  end
118
+ end
119
+ end
450
120
 
451
- @charges = @apm_db.execute( "SELECT * FROM charges WHERE shop_domain = ? ORDER BY created_at DESC ",@shop_domain)
452
- if @charges.any?
453
- charge = @charges.first
454
- if charge['trial_days']
455
- trial_end_date = Date.parse(charge['trial_ends_on'])
456
- if DateTime.now < trial_end_date
457
- @remaining_days = (trial_end_date - DateTime.now).to_i
458
- end
459
- 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"])
460
- if trial_extension_data.any?
461
- trial_extension_data = trial_extension_data.first
462
- extend_trial_date = Date.parse(trial_extension_data['created_at']) + trial_extension_data['days'].to_i.days
463
- remaining_extended_days = DateTime.now < extend_trial_date ? (extend_trial_date - DateTime.now).to_i : 0
464
- @remaining_days = @remaining_days + remaining_extended_days
465
- end
466
- end
467
- return @remaining_days
121
+ def save_api_extend_trials(extend_trials)
122
+ AppManager::ExtendTrial.destroy_all
123
+ if extend_trials.any?
124
+ extend_trials.each do |extend_trial|
125
+ AppManager::ExtendTrial.create(id: extend_trial['id'], shop_domain: extend_trial['shop_domain'], plan_id: extend_trial['plan_id'], app_id: extend_trial['app_id'], days: extend_trial['days'], created_by: extend_trial['created_by'], created_at: extend_trial['created_at'], updated_at: extend_trial['updated_at'], extend_trial_start_at: extend_trial['extend_trial_start_at'])
468
126
  end
469
- end
470
-
471
-
472
- def get_local_charge(params,options)
473
- charge_data = nil
474
- if params["shop_domain"].present?
475
- @apm_db.execute( "SELECT * FROM charges WHERE status = ? AND shop_domain = ? ",'active',params["shop_domain"]) do |charge|
476
- if charge
477
- charge_values = {}
478
- charge.each_with_index do |(key, value), index|
479
- charge_values[key] = value unless key.class == Integer
480
- end
481
- charge_data = charge_values
482
- break
483
- end
484
- end
485
- end
486
- return charge_data
487
- end
488
-
489
-
490
- def store_local_charge(params,options)
491
- message = {"message" => 'fail'}
492
- if options
493
- options.gsub!('null','nil') rescue nil
494
- charge = eval(options) rescue nil
495
- if charge
496
- charge = charge.as_json if charge.class == Hash
497
- test_value = charge["test"] == true ? 1 : 0
498
- plan_id = charge["plan_id"].to_i
499
- begin
500
- @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)
501
- message = {"message" => 'success'}
502
- rescue Exception => e
503
- Rails.logger.info ">>>>>>>>> Charge not saved on local DB due to #{e.inspect}"
504
- end
505
- end
506
- end
507
- return message
508
- end
509
-
510
- def store_cancel_charge(params,options)
511
- message = {"message" => 'fail'}
127
+ end
128
+ end
129
+
130
+ def save_api_plan_users(plan_users)
131
+ AppManager::PlanUser.destroy_all
132
+ if plan_users.any?
133
+ plan_users.each do |plan_user|
134
+ AppManager::PlanUser.create(id: plan_user['id'], shop_domain: plan_user['shop_domain'], plan_id: plan_user['plan_id'], created_by: plan_user['created_by'], created_at: plan_user['created_at'], updated_at: plan_user['updated_at'])
135
+ end
136
+ end
137
+ end
138
+
139
+ def get_local_app_structures
140
+ app_structure = AppManager::AppStructure.first
141
+ app_structure_computed = {}
142
+ if app_structure.present?
143
+ app_structure_computed["banners"] = eval(app_structure.banners)
144
+ end
145
+ return app_structure_computed
146
+ end
147
+
148
+ def get_local_plans(params)
149
+ plans_data = []
150
+
151
+ active_plan_id = nil
152
+ active_charge_price = nil
153
+ # apm_db = SQLite3::Database.open "db/app_manager_local.db"
154
+ # apm_db.results_as_hash = true
155
+ charges = AppManager::Charge.where(shop_domain: params['shop_domain'])
156
+ if charges.present?
157
+ active_plan_id = charges.first['plan_id']
158
+ active_charge_price = charges.first['price']
159
+ elsif params['active_plan_id'].present? && !params['active_plan_id'].nil?
160
+ active_plan_id = params['active_plan_id']
161
+ plan_data = AppManager::Plan.where(id: active_plan_id)
162
+ active_charge_price = plan_data.first['price'] if plan_data.present?
163
+ end
164
+
165
+ custom_plan_ids = []
166
+ plan_users = AppManager::PlanUser.where(shop_domain: params['shop_domain'])
167
+ custom_plan_ids = plan_users.pluck(:plan_id) if plan_users.present?
168
+
169
+ custom_plan_base_ids = []
170
+ plan_data = AppManager::Plan.where(id: custom_plan_ids).where.not(base_plan: nil)
171
+ custom_plan_base_ids = plan_data.pluck(:base_plan) if plan_data.present?
172
+
173
+ if active_plan_id && custom_plan_base_ids.include?(active_plan_id)
174
+ custom_plan_base_ids.delete(active_plan_id)
175
+ end
176
+
177
+ if custom_plan_base_ids.any?
178
+ if custom_plan_ids.present?
179
+ plans = AppManager::Plan.where("public = ? OR id IN (?)",true,custom_plan_ids).where.not(id: custom_plan_base_ids)
180
+ else
181
+ plans = AppManager::Plan.where(public: true).where.not(id: custom_plan_base_ids)
182
+ end
183
+ else
184
+ if custom_plan_ids.present?
185
+ plans = AppManager::Plan.where("public = ? OR id IN (?)",true,custom_plan_ids)
186
+ else
187
+ plans = AppManager::Plan.where(public: true)
188
+ end
189
+ end
190
+
191
+ if plans.present?
192
+ plans.each do |plan|
193
+ new_plan = {}
194
+ plan.as_json.each_with_index do |(key, value)|
195
+ if ['interval'].include?(key)
196
+ val = eval(value)
197
+ new_plan[key] = val
198
+ new_plan[key] = val['value'] if val rescue {}
199
+ elsif ['shopify_plans'].include?(key)
200
+ val = eval(value)
201
+ new_plan[key] = val.collect { |e| e['value'] }
202
+ elsif ['affiliate'].include?(key)
203
+ new_plan[key] = eval(value)
204
+ elsif ['is_custom', 'public', 'store_base_plan', 'choose_later_plan'].include?(key)
205
+ new_plan[key] = (value == 0 || value == false ? false : true)
206
+ elsif ['test'].include?(key)
207
+ new_plan[key] = (value == 0 || value == false ? nil : true)
208
+ elsif ['features'].include?(key)
209
+ value = eval(value)
210
+ value = value.each { |e| e.delete("id") }.each { |e| e.delete("created_at") }.each { |e| e.delete("updated_at") }
211
+ new_plan[key] = value
212
+ else
213
+ new_plan[key] = value unless key.class == Integer
214
+ end
215
+ end
216
+ plans_data.push(new_plan)
217
+ end
218
+
219
+ features_by_plans = plans_data.collect { |e| e['features'] }
220
+ if features_by_plans.any? && AppManager.configuration.plan_features.any?
221
+ features_by_plans_data = []
222
+ features = AppManager.configuration.plan_features
223
+ features_by_plans.each do |features_by_plan|
224
+ features_by_plan.each do |fp|
225
+ fp['name'] = features.find { |e| e['uuid'] == fp['feature_id'] }['name'] rescue nil
226
+ fp['format'] = features.find { |e| e['uuid'] == fp['feature_id'] }['format'] rescue nil
227
+ fp['slug'] = features.find { |e| e['uuid'] == fp['feature_id'] }['slug'] rescue nil
228
+ features_by_plans_data.push(fp)
229
+ end
230
+ end
231
+ end
232
+
233
+
234
+ custom_discounts_data = []
235
+ if params["shop_domain"].present? && plan_data
236
+ custom_discounts = AppManager::DiscountPlan.where(shop_domain: params['shop_domain']).order(created_at: :desc)
237
+ if custom_discounts.present?
238
+ custom_discounts.each do |custom_discount|
239
+ new_custom_discount = {}
240
+ custom_discount.as_json.each_with_index do |(key, value), index|
241
+ new_custom_discount[key] = value unless key.class == Integer
242
+ end
243
+ custom_discounts_data.push(new_custom_discount)
244
+ end
245
+ end
246
+ end
247
+
248
+ plans_data.each do |plan|
249
+ if (!active_plan_id.nil? && plan['id'] == active_plan_id)
250
+ plan['price'] = active_charge_price
251
+ end
252
+
253
+ if custom_discounts_data.any? && custom_discounts_data.select { |e| e['plan_id'] == plan['id'] }.size > 0
254
+ cd_hash = {}
255
+ custom_discounts_data.select { |e| e['plan_id'] == plan['id'] }.each do |cd|
256
+ plan['discount'] = cd['discount']
257
+ plan['discount_type'] = cd['discount_type']
258
+ plan['cycle_count'] = cd['cycle_count']
259
+ end
260
+ end
261
+
262
+ if features_by_plans_data.select { |e| e['plan_id'] == plan['id'] }.size > 0
263
+ feature_hash = {}
264
+ features_by_plans_data.select { |e| e['plan_id'] == plan['id'] }.each do |fp|
265
+ feature_hash[fp["feature_id"]] = fp
266
+ end
267
+ features = feature_hash
268
+ else
269
+ features = nil
270
+ end
271
+ plan['features'] = features
272
+ plan['old_plan_id'] = nil
273
+
274
+ end
275
+
276
+ plans = plans_data
277
+ end
278
+
279
+
280
+ return plans
281
+ end
282
+
283
+ def get_local_plan(params)
284
+ plan_data = {}
285
+ if params.any?
286
+ if params["plan_id"].present? && !params["plan_id"].nil?
287
+ plans = AppManager::Plan.where(id: params["plan_id"])
288
+ plans.each do |plan|
289
+ new_plan = {}
290
+ plan.as_json.each_with_index do |(key, value), index|
291
+ if ['interval'].include?(key)
292
+ val = eval(value)
293
+ new_plan[key] = val
294
+ elsif ['shopify_plans', 'affiliate', 'features'].include?(key)
295
+ new_plan[key] = eval(value)
296
+ elsif ['is_custom', 'public', 'store_base_plan', 'choose_later_plan'].include?(key)
297
+ new_plan[key] = (value == 0 || value == false ? false : true)
298
+ elsif ['test'].include?(key)
299
+ new_plan[key] = (value == 0 || value == false ? nil : true)
300
+ else
301
+ new_plan[key] = value unless key.class == Integer
302
+ end
303
+ end
304
+ plan_data = new_plan
305
+ # app = {}
306
+ apps = AppManager::App.all
307
+ apps.each do |app|
308
+ app_data = {}
309
+ app.as_json.each_with_index do |(key, value), index|
310
+ app_data[key] = value unless key.class == Integer
311
+ end
312
+ plan_data['app'] = app_data
313
+ end
314
+ plan_data['old_plan_id'] = nil # Temporary for migration puspose only
315
+ if params["shop_domain"].present? && plan_data
316
+ discount_plans = AppManager::DiscountPlan.where(plan_id: params["plan_id"], shop_domain: params["shop_domain"])
317
+ discount_plans.each do |cd|
318
+ plan_data['discount'] = cd['discount'] if cd rescue plan_data['discount']
319
+ plan_data['discount_type'] = cd['discount_type'] if cd rescue plan_data['discount_type']
320
+ plan_data['cycle_count'] = cd['cycle_count'] if cd rescue plan_data['cycle_count']
321
+ end
322
+ end
323
+
324
+
325
+ end
326
+ end
327
+
328
+ end
329
+
330
+ return plan_data
331
+ end
332
+
333
+ def get_local_remaining_days(params, options)
334
+ @remaining_days = 0
335
+ @shop_domain = params['shop_domain']
336
+ if params && params['trial_activated_at'].present? && !params['trial_activated_at'].nil? && params['shop_domain'].present? && params['plan_id'].present? && !params['plan_id'].nil?
337
+ @trial_activated_at = params['trial_activated_at']
338
+ @plan_id = params['plan_id']
339
+ plan_data = AppManager::Plan.where(id: @plan_id)
340
+ if plan_data.any?
341
+ trial_days = plan_data.first['trial_days']
342
+ trial_start_date = Date.parse(@trial_activated_at)
343
+ trial_end_date = trial_start_date + trial_days.days
344
+ if trial_end_date > DateTime.now
345
+ @remaining_days = (trial_end_date - DateTime.now).to_i
346
+ end
347
+ # return @remaining_days.inspect
348
+ trial_extension_data = AppManager::ExtendTrial.where(shop_domain: @shop_domain, plan_id: @plan_id).order(extend_trial_start_at: :desc)
349
+ if trial_extension_data.any?
350
+ trial_extension_data = trial_extension_data.first
351
+ extend_trial_date = trial_extension_data['created_at'].to_datetime + trial_extension_data['days'].to_i.days
352
+ remaining_extended_days = DateTime.now < extend_trial_date ? (extend_trial_date - DateTime.now).to_i : 0
353
+ @remaining_days = @remaining_days + remaining_extended_days
354
+ end
355
+ end
356
+ return @remaining_days
357
+ end
358
+ @charges = AppManager::Charge.where(shop_domain: @shop_domain).order(created_at: :desc)
359
+ if @charges.any?
360
+ charge = @charges.first
361
+
362
+ if charge['trial_days']
363
+ if charge['trial_ends_on'] && DateTime.now < charge['trial_ends_on']
364
+ @remaining_days = (charge['trial_ends_on'].to_datetime - DateTime.now.to_datetime).to_i
365
+ end
366
+ # TODO: Uncomment this code when we implement Shopify trial extension apis
367
+ # trial_extension_data = AppManager::ExtendTrial.where(shop_domain: @shop_domain, plan_id: @plan_id).order(extend_trial_start_at: :desc)
368
+ # if trial_extension_data.any?
369
+ # trial_extension_data = trial_extension_data.first
370
+ # extend_trial_date = trial_extension_data['created_at'] + trial_extension_data['days'].to_i.days
371
+ # remaining_extended_days = DateTime.now < extend_trial_date ? (extend_trial_date - DateTime.now).to_i : 0
372
+ # @remaining_days = @remaining_days + remaining_extended_days
373
+ # end
374
+ end
375
+ return @remaining_days
376
+ end
377
+ end
378
+
379
+
380
+
381
+ def get_local_charge(params, options)
382
+ charge_hash = {'active_charge' => nil, 'cancelled_charge' => nil}
383
+ active_charge = nil
384
+ cancelled_charge_val = nil
385
+ if params["shop_domain"].present?
386
+ # old get test ture new get test true
387
+ charges = AppManager::Charge.where(status: 'active', shop_domain: params["shop_domain"])
388
+ if charges.any?
389
+ active_charge = charges.first.attributes
390
+ end
391
+ cancelled_charges = AppManager::Charge.where(status: 'cancelled', shop_domain: params["shop_domain"]).order(created_at: :desc)
392
+ if cancelled_charges.any?
393
+ cancelled_charge_val = cancelled_charges.first.attributes
394
+ end
395
+ charge_hash = {'active_charge' => active_charge, 'cancelled_charge' => cancelled_charge_val}
396
+ end
397
+ return charge_hash
398
+ end
399
+
400
+ def get_local_has_plan(params, options)
401
+ if params["grandfathered"].present? && params["grandfathered"] == 1
402
+ return {:has_plan => true}
403
+ end
404
+ plans = AppManager::Plan.where(id: params["plan_id"])
405
+ if plans.any? && plans.first.price == 0
406
+ return {:has_plan => true}
407
+ end
408
+ @remaining_days = get_local_remaining_days(params, options)
409
+ puts @remaining_days.inspect
410
+ if (@remaining_days && @remaining_days > 0)
411
+ return {:has_plan => true}
412
+ end
413
+ active_charge = AppManager::Charge.where(status: 'active', shop_domain: params["shop_domain"])
414
+ if active_charge.any?
415
+ return {:has_plan => true}
416
+ end
417
+
418
+ return {:has_plan => false}
419
+
420
+ end
421
+
422
+ def store_local_charge(params, options)
423
+ message = {"message" => 'fail'}
424
+ if options
425
+ options.gsub!('null', 'nil') rescue nil
426
+ charge = eval(options) rescue nil
427
+ if charge
428
+ charge = charge.as_json if charge.class == Hash
429
+ test_value = charge["test"]
430
+ plan_id = charge["plan_id"].to_i
431
+ begin
432
+ AppManager::Charge.create(charge_id: charge["charge_id"], test: test_value, status: charge["status"], name: charge["name"], type: charge["type"], price: charge["price"], interval: charge["interval"], trial_days: charge["trial_days"], billing_on: charge["billing_on"], activated_on: charge["activated_on"], trial_ends_on: charge["trial_ends_on"], cancelled_on: charge["cancelled_on"], expires_on: charge["expires_on"], plan_id: plan_id, description: charge["description"], shop_domain: charge["shop_domain"], created_at: charge["created_at"], updated_at: charge["updated_at"], sync: 0)
433
+ message = {"message" => 'success'}
434
+ rescue Exception => e
435
+ Rollbar.error("Charge not saved on local DB due to #{e.inspect}")
436
+ end
437
+ end
438
+ end
439
+ return message
440
+ end
441
+
442
+ def store_cancel_charge(params, options)
443
+ message = {"message" => 'fail'}
512
444
  if options && options[:shop_domain].present? && options[:plan_id].present?
513
- time = "#{DateTime.now}"
514
- @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])
445
+ time = "#{DateTime.now}"
446
+ AppManager::Charge.where(plan_id: options[:plan_id], shop_domain: options[:shop_domain]).update_all(status: 'cancelled',cancelled_on: time, sync: false)
515
447
  message = {"message" => 'success'}
516
448
  end
517
449
  return message
518
- end
519
-
520
-
521
-
522
- def sync_app_manager
523
- plan_obj = AppManager::Client.new
524
- response = plan_obj.get_status
525
- if response && response.code == 200
526
- @apm_db.execute( "SELECT * FROM charges WHERE sync = ?", 0) do |charge|
527
- if charge
528
- if !charge["cancelled_on"].nil?
529
- charge["cancelled_on"] = Date.parse(charge["cancelled_on"])
530
- end
531
- plan_ob = AppManager::Client.new(nil,json_req=true)
532
- res = plan_ob.sync_charge(charge.to_json)
533
- if res && res["message"] == "success"
534
- @apm_db.execute( "UPDATE charges SET sync= ? WHERE charge_id = ?",1,charge['charge_id'])
535
- end
536
- end
537
- end
538
- end
539
- end
540
-
541
-
542
- end
450
+ end
451
+
452
+
453
+ def sync_app_manager
454
+ plan_obj = AppManager::Client.new
455
+ response = plan_obj.get_status
456
+ if response && response.code == 200
457
+ charges = AppManager::Charge.where(sync: false)
458
+ charges.each do |charge|
459
+ if charge
460
+ if !charge["cancelled_on"].nil?
461
+ charge["cancelled_on"] = Date.parse(charge["cancelled_on"])
462
+ end
463
+ plan_ob = AppManager::Client.new(nil, json_req = true)
464
+ res = plan_ob.sync_charge(charge.to_json)
465
+ if res && res["message"] == "success"
466
+ AppManager::Charge.find_by(charge_id: charge['charge_id']).update(sync: true)
467
+ end
468
+ end
469
+ end
470
+ end
471
+ end
472
+
473
+
474
+ end
543
475
 
544
476
  end