Class: AppManager::FailSafe

Inherits:
Object
  • Object
show all
Defined in:
lib/app_manager/fail_safe.rb

Instance Method Summary collapse

Constructor Details

#initialize(db_name = 'app_manager_local') ⇒ FailSafe

Returns a new instance of FailSafe.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/app_manager/fail_safe.rb', line 10

def initialize(db_name='app_manager_local')
	@apm_db = SQLite3::Database.open "db/#{db_name}.db"
	begin
		FileUtils.chmod 0664, "db/#{db_name}.db"
	rescue Exception => e
		puts ">>>>>> #{e.inspect}"
	end			
	@apm_db.results_as_hash = true
	create_plan_table
	create_charges_table
	create_apps_table
	create_app_structures_table
	create_discount_plans_table
	create_extend_trials_table
	create_plan_users_table
end

Instance Method Details

#create_app_structures_tableObject



233
234
235
# File 'lib/app_manager/fail_safe.rb', line 233

def create_app_structures_table
	@apm_db.execute "CREATE TABLE IF NOT EXISTS app_structures(banners text)"	
end

#create_apps_tableObject



229
230
231
# File 'lib/app_manager/fail_safe.rb', line 229

def create_apps_table
	@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)"
end

#create_charges_tableObject



225
226
227
# File 'lib/app_manager/fail_safe.rb', line 225

def create_charges_table
	@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))"
end

#create_discount_plans_tableObject



237
238
239
# File 'lib/app_manager/fail_safe.rb', line 237

def create_discount_plans_table
	@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))"
end

#create_extend_trials_tableObject



241
242
243
# File 'lib/app_manager/fail_safe.rb', line 241

def create_extend_trials_table
	@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)"
end

#create_plan_tableObject



221
222
223
# File 'lib/app_manager/fail_safe.rb', line 221

def create_plan_table
	@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)"	
end

#create_plan_users_tableObject



245
246
247
# File 'lib/app_manager/fail_safe.rb', line 245

def create_plan_users_table
	@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)"
end

#get_local_app_structuresObject



206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/app_manager/fail_safe.rb', line 206

def get_local_app_structures
	app_structures = {}
	app_structures = @apm_db.execute( "SELECT * FROM app_structures;" ) rescue {}
	if app_structures.any?
		new_app_structure = {}
		app_structures.first.each_with_index do |(key, value), index|
			val = eval(value) 
			new_app_structure[key] = val unless key.class == Integer
  	end
  	app_structures = new_app_structure
	end
	
	return app_structures
end

#get_local_charge(params, options) ⇒ Object



472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
# File 'lib/app_manager/fail_safe.rb', line 472

def get_local_charge(params,options)
	charge_data = nil
	if params["shop_domain"].present?
		@apm_db.execute( "SELECT * FROM charges WHERE status = ? AND shop_domain = ? ",'active',params["shop_domain"]) do |charge|
			if charge
			charge_values = {}
				charge.each_with_index do |(key, value), index|
					charge_values[key] = value unless key.class == Integer
				end
			charge_data = charge_values
			break
			end
		end
	end
	return charge_data
end

#get_local_plan(params) ⇒ Object



379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
# File 'lib/app_manager/fail_safe.rb', line 379

def get_local_plan(params)
	plan_data = {}
	if params.any?
		if params["plan_id"].present? && !params["plan_id"].nil?
		@apm_db.execute( "SELECT * FROM plans WHERE id = ?", params["plan_id"]) do |plan|
		new_plan = {}
			plan.each_with_index do |(key, value), index|
				if ['interval'].include?(key)
				 val = eval(value) 
				 new_plan[key] = val
				elsif ['shopify_plans','affiliate','features'].include?(key)
				 new_plan[key] = eval(value)
				elsif ['is_custom','public','store_base_plan','choose_later_plan'].include?(key)
				 new_plan[key] = (value == 0 ? false : true)
				elsif ['test'].include?(key)
				 new_plan[key] = (value == 0 ? nil : true)
				else
				 new_plan[key] = value unless key.class == Integer
				end
			end
			plan_data = new_plan
			app = {}
			@apm_db.execute( "SELECT * FROM apps;") do |app|
				app_data = {}
				app.each_with_index do |(key, value), index|
					app_data[key] = value unless key.class == Integer
				end
				plan_data['app'] = app_data
			end
			plan_data['old_plan_id'] = nil # Temporary for migration puspose only
			if params["shop_domain"].present? && plan_data
				@apm_db.execute( "SELECT * FROM discount_plans WHERE plan_id = ? AND shop_domain = ? ", params["plan_id"],params["shop_domain"]) do |cd|
					plan_data['discount'] = cd['discount'] if cd rescue plan_data['discount']
					plan_data['discount_type'] = cd['discount_type'] if cd rescue plan_data['discount_type']
					plan_data['cycle_count'] = cd['cycle_count'] if cd rescue plan_data['cycle_count']
				end
			end


		end
	end

	end

	return plan_data
end

#get_local_plans(params) ⇒ Object



250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
# File 'lib/app_manager/fail_safe.rb', line 250

def get_local_plans(params)

    plans_data = []

          active_plan_id = nil
          active_charge_price = nil

          charges = @apm_db.execute( "SELECT * FROM charges WHERE shop_domain = ? ",params['shop_domain'])
          
	if charges.any?
		active_plan_id = charges.first['plan_id'] 
		active_charge_price = charges.first['price'] 
	elsif params['active_plan_id'].present? && !params['active_plan_id'].nil?
		active_plan_id = params['active_plan_id']
		plan_data = @apm_db.execute( "SELECT * FROM plans WHERE id = ?", active_plan_id)
		active_charge_price = plan_data.first['price'] if plan_data.any?
	end

          custom_plan_ids = []
          plan_users = @apm_db.execute( "SELECT * FROM plan_users WHERE shop_domain = ? ",params['shop_domain'])
          custom_plan_ids = plan_users.collect{|e|e['plan_id']} if plan_users.any?

          custom_plan_base_ids = []
          plan_data = @apm_db.execute( "SELECT * FROM plans WHERE id IN (?) AND base_plan IS NOT NULL;",custom_plan_ids)
          custom_plan_base_ids = plan_data.collect{|e|e['base_plan']} if plan_data.any? 

	if active_plan_id && custom_plan_base_ids.include?(active_plan_id)
	custom_plan_base_ids.delete(active_plan_id)
	end

	if custom_plan_base_ids.any?
	plans = @apm_db.execute( "SELECT * FROM plans WHERE (public = ? OR id IN (?)) AND id NOT IN (?)", 1,custom_plan_ids,custom_plan_base_ids) 
	else
	plans = @apm_db.execute( "SELECT * FROM plans WHERE (public = ? OR id IN (?))", 1,custom_plan_ids) 
	end

	if plans.any? 

		plans.each do |plan|
			new_plan = {}
			plan.each_with_index do |(key, value), index|
				if ['interval'].include?(key)
					val = eval(value) 
					new_plan[key] = val
					new_plan[key] = val['value'] if val rescue {}
				elsif ['shopify_plans'].include?(key)
					val = eval(value) 
					new_plan[key] = val.collect{|e|e['value']}
				elsif ['affiliate'].include?(key)
					new_plan[key] = eval(value)
				elsif ['is_custom','public','store_base_plan','choose_later_plan'].include?(key)
					new_plan[key] = (value == 0 ? false : true)
				elsif ['test'].include?(key)
					new_plan[key] = (value == 0 ? nil : true)
				elsif ['features'].include?(key)
					value = eval(value)
					value = value.each {|e| e.delete("id")}.each {|e| e.delete("created_at")}.each {|e| e.delete("updated_at")}
					new_plan[key] = value
				else
					new_plan[key] = value unless key.class == Integer
				end
			end
	    	plans_data.push(new_plan)
	    end

	features_by_plans = plans_data.collect{|e|e['features']}
	if features_by_plans.any? && AppManager.configuration.plan_features.any?
		features_by_plans_data = []
		features = AppManager.configuration.plan_features
		features_by_plans.each do |features_by_plan|
			features_by_plan.each do |fp|
			fp['name'] = features.find{|e| e['uuid'] == fp['feature_id']}['name'] rescue nil
			fp['format'] = features.find{|e| e['uuid'] == fp['feature_id']}['format'] rescue nil
			fp['slug'] = features.find{|e| e['uuid'] == fp['feature_id']}['slug'] rescue nil
			features_by_plans_data.push(fp)
			end
		end
	end


	custom_discounts_data = []
	if params["shop_domain"].present? && plan_data
				custom_discounts = @apm_db.execute( "SELECT * FROM discount_plans WHERE shop_domain = ? ORDER BY created_at DESC", params["shop_domain"]) 
				if custom_discounts.any?
					custom_discounts.each do |custom_discount|
						new_custom_discount = {}
						custom_discount.each_with_index do |(key, value), index|
							new_custom_discount[key] = value unless key.class == Integer
						end
						custom_discounts_data.push(new_custom_discount)
					end
				end
	end

		plans_data.each do |plan|
			if (!active_plan_id.nil? && plan['id'] == active_plan_id) 
			plan['price'] = active_charge_price
			end

			if custom_discounts_data.any? && custom_discounts_data.select{|e| e['plan_id'] == plan['id']}.size > 0 
				cd_hash = {}
				custom_discounts_data.select{|e| e['plan_id'] == plan['id']}.each do |cd|
			 		plan['discount'] = cd['discount']  
					plan['discount_type'] = cd['discount_type']  
					plan['cycle_count'] = cd['cycle_count']  
			 	end
			end

			if features_by_plans_data.select{|e| e['plan_id'] == plan['id']}.size > 0 
			 feature_hash = {}
			 features_by_plans_data.select{|e| e['plan_id'] == plan['id']}.each do |fp|
			 	feature_hash[fp["feature_id"]] = fp
			 end
			 features = feature_hash
			else
			 features = nil
			end
			plan['features'] = features
			plan['old_plan_id'] = nil

		end

		plans = plans_data
	end
	

	return plans
end

#get_local_remaining_days(params, options) ⇒ Object



426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
# File 'lib/app_manager/fail_safe.rb', line 426

def get_local_remaining_days(params,options)
      @remaining_days = 0
      @shop_domain = params['shop_domain']
      if params && params['trial_activated_at'].present? && !params['trial_activated_at'].nil? && params['shop_domain'].present? && params['plan_id'].present? && !params['plan_id'].nil?
			@trial_activated_at = params['trial_activated_at']
			@plan_id = params['plan_id']
			plan_data = @apm_db.execute( "SELECT * FROM plans WHERE id = ?", @plan_id)
      	if plan_data.any?
      		trial_days = plan_data.first['trial_days'] 
    				trial_start_date = Date.parse(@trial_activated_at)
    				trial_end_date = trial_start_date + trial_days.days
    				if trial_end_date > DateTime.now
    					remaining_days = (trial_end_date - DateTime.now).to_i      				
    				end
    				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)
    				if trial_extension_data.any? 
    					trial_extension_data = trial_extension_data.first
    					extend_trial_date = Date.parse(trial_extension_data['created_at']) + trial_extension_data['days'].to_i.days
    					remaining_extended_days = DateTime.now < extend_trial_date ? (extend_trial_date - DateTime.now).to_i : 0
    					@remaining_days = @remaining_days + remaining_extended_days
    				end
      	end
      	 return @remaining_days
      end

      @charges = @apm_db.execute( "SELECT * FROM charges WHERE shop_domain = ? ORDER BY created_at DESC ",@shop_domain)
      if @charges.any?
      	charge = @charges.first
      	if charge['trial_days']
      		trial_end_date = Date.parse(charge['trial_ends_on'])
      		if DateTime.now < trial_end_date
      			@remaining_days = (trial_end_date - DateTime.now).to_i   
      		end
      		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"])
    				if trial_extension_data.any? 
    					trial_extension_data = trial_extension_data.first
    					extend_trial_date = Date.parse(trial_extension_data['created_at']) + trial_extension_data['days'].to_i.days
    					remaining_extended_days = DateTime.now < extend_trial_date ? (extend_trial_date - DateTime.now).to_i : 0
    					@remaining_days = @remaining_days + remaining_extended_days
    				end
      	end
      	return @remaining_days
      end
end

#save_api_app_structures(app_structures) ⇒ Object



167
168
169
170
171
172
173
# File 'lib/app_manager/fail_safe.rb', line 167

def save_api_app_structures(app_structures)
	@apm_db.execute("DROP TABLE IF EXISTS app_structures;")
	create_app_structures_table
	if !app_structures.nil?
	@apm_db.execute("INSERT INTO app_structures (banners) VALUES (?)", "#{app_structures.to_h}")
	end
end

#save_api_apps(apps) ⇒ Object



156
157
158
159
160
161
162
163
164
# File 'lib/app_manager/fail_safe.rb', line 156

def save_api_apps(apps)
	@apm_db.execute("DROP TABLE IF EXISTS apps;")
	create_apps_table
  if apps.any?
	apps.each do |app|
	@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'])
  end
  end
end

#save_api_charges(charges) ⇒ Object



144
145
146
147
148
149
150
151
152
153
# File 'lib/app_manager/fail_safe.rb', line 144

def save_api_charges(charges)
	@apm_db.execute("DROP TABLE IF EXISTS charges;")
	create_charges_table
	if charges.any?
			charges.each do |charge|
			charge_test = charge['test'] ? 1 : 0
			@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)
			end
	end
end

#save_api_data(params) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/app_manager/fail_safe.rb', line 27

def save_api_data(params)	
		begin
			save_api_plans(params["plans"])
		rescue Exception => e
			Rails.logger.info "APP MANAGER >>>> #{e.inspect}"	
			begin
				create_plan_table
				save_api_plans(params["plans"])
			rescue Exception => e
				Rails.logger.info "APP MANAGER FailSafe >>>> #{e.inspect}"
			end
		end

		
		begin
			save_api_charges(params["charges"])
		rescue Exception => e
			Rails.logger.info "APP MANAGER >>>> #{e.inspect}"
			begin
				create_charges_table
				save_api_charges(params["charges"])
			rescue Exception => e
				Rails.logger.info "APP MANAGER FailSafe >>>> #{e.inspect}"
			end	
		end


		begin
			save_api_apps(params["apps"])
		rescue Exception => e
			Rails.logger.info "APP MANAGER >>>> #{e.inspect}"
			begin
				create_apps_table
				save_api_apps(params["apps"])
			rescue Exception => e
				Rails.logger.info "APP MANAGER FailSafe >>>> #{e.inspect}"
			end	
		end


		begin
			save_api_app_structures(params["app_structures"])
		rescue Exception => e
			Rails.logger.info "APP MANAGER >>>> #{e.inspect}"
			begin
				create_app_structures_table
				save_api_app_structures(params["app_structures"])
			rescue Exception => e
				Rails.logger.info "APP MANAGER FailSafe >>>> #{e.inspect}"
			end	
		end


		begin
			save_api_discount_plans(params["discount_plans"])
		rescue Exception => e
			Rails.logger.info "APP MANAGER >>>> #{e.inspect}"	
			begin
				create_discount_plans_table
				save_api_discount_plans(params["discount_plans"])
			rescue Exception => e
				Rails.logger.info "APP MANAGER FailSafe >>>> #{e.inspect}"
			end
		end


		begin
			save_api_extend_trials(params["extend_trials"])
		rescue Exception => e
			Rails.logger.info "APP MANAGER >>>> #{e.inspect}"
			begin
				create_extend_trials_table
				save_api_extend_trials(params["extend_trials"])
			rescue Exception => e
				Rails.logger.info "APP MANAGER FailSafe >>>> #{e.inspect}"
			end	
		end


		begin
			save_api_plan_users(params["plan_users"])
		rescue Exception => e
			Rails.logger.info "APP MANAGER >>>> #{e.inspect}"
			begin
				create_plan_users_table
				save_api_plan_users(params["plan_users"])
			rescue Exception => e
				Rails.logger.info "APP MANAGER FailSafe >>>> #{e.inspect}"
			end	
		end
end

#save_api_discount_plans(discount_plans) ⇒ Object



175
176
177
178
179
180
181
182
183
# File 'lib/app_manager/fail_safe.rb', line 175

def save_api_discount_plans(discount_plans)
@apm_db.execute("DROP TABLE IF EXISTS discount_plans;")
create_discount_plans_table
     if discount_plans.any?
		discount_plans.each do |discount_plan|
		@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'])
		end
	end
end

#save_api_extend_trials(extend_trials) ⇒ Object



185
186
187
188
189
190
191
192
193
# File 'lib/app_manager/fail_safe.rb', line 185

def save_api_extend_trials(extend_trials)
	@apm_db.execute("DROP TABLE IF EXISTS extend_trials;")
	create_extend_trials_table
	if extend_trials.any?
		extend_trials.each do |extend_trial|
		@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'])
		end
	end
end

#save_api_plan_users(plan_users) ⇒ Object



195
196
197
198
199
200
201
202
203
# File 'lib/app_manager/fail_safe.rb', line 195

def save_api_plan_users(plan_users)
	@apm_db.execute("DROP TABLE IF EXISTS plan_users;")
          create_plan_users_table
          if plan_users.any?
		plan_users.each do |plan_user|
		@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'])
		end
	end
end

#save_api_plans(plans) ⇒ Object



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/app_manager/fail_safe.rb', line 119

def save_api_plans(plans)
   	@apm_db.execute("DROP TABLE IF EXISTS plans;")
	create_plan_table

   if plans.any?
		plans.each do |plan|
			interval = {}
			shopify_plans = []
			affiliate = []
			features = {}
			interval = plan["interval"].each{|e|e}  if plan["interval"] rescue {}
			shopify_plans = plan["shopify_plans"].map{|e| e.to_h}  if plan["shopify_plans"] rescue []
			affiliate = plan["affiliate"].map{|e|e.to_h} if plan["affiliate"] rescue []
			features = plan["features"].map{|e|e.to_h} rescue []
			plan_test = plan['test'].nil? ? 0 : plan['test']
			is_custom = plan['is_custom'] ? 1 : 0
			public_val = plan['public'] ? 1 : 0
			store_base_plan = plan['store_base_plan'] ? 1 : 0
			choose_later_plan = plan['choose_later_plan'] ? 1 : 0
			@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"])
		end
    end
end

#store_cancel_charge(params, options) ⇒ Object



510
511
512
513
514
515
516
517
518
# File 'lib/app_manager/fail_safe.rb', line 510

def store_cancel_charge(params,options)
		message = {"message" => 'fail'}
    if options && options[:shop_domain].present? && options[:plan_id].present?
    	time = "#{DateTime.now}"
      @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]) 
      message = {"message" => 'success'}
    end
    return message
end

#store_local_charge(params, options) ⇒ Object



490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
# File 'lib/app_manager/fail_safe.rb', line 490

def store_local_charge(params,options)
	message = {"message" => 'fail'}
	if options
		options.gsub!('null','nil') rescue nil
		charge = eval(options) rescue nil
		if charge
		charge = charge.as_json if charge.class == Hash
		test_value = charge["test"] == true ? 1 : 0
		plan_id = charge["plan_id"].to_i
			begin
			@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)	
			  message = {"message" => 'success'}
			rescue Exception => e
				Rails.logger.info ">>>>>>>>> 	Charge not saved on local DB due to #{e.inspect}"
			end
		end
	end
	return message
end

#sync_app_managerObject



522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
# File 'lib/app_manager/fail_safe.rb', line 522

def sync_app_manager
	plan_obj = AppManager::Client.new
	response = plan_obj.get_status
	if response && response.code == 200
		@apm_db.execute( "SELECT * FROM charges WHERE sync = ?", 0) do |charge|
			if charge
				if !charge["cancelled_on"].nil?
					charge["cancelled_on"] = Date.parse(charge["cancelled_on"])
				end
				plan_ob = AppManager::Client.new(nil,json_req=true)
				res = plan_ob.sync_charge(charge.to_json)
				if res && res["message"] == "success"
					@apm_db.execute( "UPDATE charges SET sync= ? WHERE charge_id = ?",1,charge['charge_id'])
				end
			end
		end
	end
end