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.



11
12
13
14
15
16
17
18
19
# File 'lib/app_manager/fail_safe.rb', line 11

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

Instance Method Details

#get_local_app_structuresObject



192
193
194
195
196
197
198
199
# File 'lib/app_manager/fail_safe.rb', line 192

def get_local_app_structures
  app_structure = AppManager::AppStructure.first
  app_structure_computed = {}
  if app_structure.present?
    app_structure_computed["banners"] = eval(app_structure.banners)
  end
  return app_structure_computed
end

#get_local_charge(params, options) ⇒ Object



439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
# File 'lib/app_manager/fail_safe.rb', line 439

def get_local_charge(params, options)
  charge_hash = {'active_charge' => nil, 'cancelled_charge' => nil}
  active_charge = nil
  cancelled_charge_val = nil
  if params["shop_domain"].present?
    # old get test ture new get test true
    charges = AppManager::Charge.where(status: 'active', shop_domain: params["shop_domain"])
    if charges.any?
      active_charge = charges.first.attributes
    end
    cancelled_charges = AppManager::Charge.where(status: 'cancelled', shop_domain: params["shop_domain"]).order(created_at: :desc)
    if cancelled_charges.any?
      cancelled_charge_val = cancelled_charges.first.attributes
    end
    charge_hash = {'active_charge' => active_charge, 'cancelled_charge' => cancelled_charge_val}
  end
  return charge_hash
end

#get_local_has_plan(params, options) ⇒ Object



458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
# File 'lib/app_manager/fail_safe.rb', line 458

def get_local_has_plan(params, options)
  if params["grandfathered"].present? && params["grandfathered"] == 1
    return {"has_plan" => true}
  end
  plans = AppManager::Plan.where(id: params["plan_id"])
  if plans.any? && plans.first.price == 0
    return {"has_plan" => true}
  end
  @remaining_days = get_local_remaining_days(params, options)
  if (@remaining_days && @remaining_days > 0)
    return {"has_plan" => true}
  end
  active_charge = AppManager::Charge.where(status: 'active', shop_domain: params["shop_domain"])
  if active_charge.any?
    return {"has_plan" => true}
  end

  return {"has_plan" => false}

end

#get_local_plan(params) ⇒ Object



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
378
379
380
381
382
383
384
# File 'lib/app_manager/fail_safe.rb', line 336

def get_local_plan(params)
  plan_data = {}
  if params.any?
    if params["plan_id"].present? && !params["plan_id"].nil?
      plans = AppManager::Plan.where(plan_id: params["plan_id"])
      plans.each do |plan|
        new_plan = {}
        plan.as_json.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 || value == false ? false : true)
          elsif ['test'].include?(key)
            new_plan[key] = (value == 0 || value == false ? nil : true)
          else
            new_plan[key] = value unless key.class == Integer
          end
        end
        plan_data = new_plan
        # app = {}
        apps = AppManager::App.all
        apps.each do |app|
          app_data = {}
          app.as_json.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
          discount_plans = AppManager::DiscountPlan.where(plan_id: params["plan_id"], shop_domain: params["shop_domain"])
          discount_plans.each 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



201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
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
# File 'lib/app_manager/fail_safe.rb', line 201

def get_local_plans(params)
  plans_data = []

  active_plan_id = nil
  active_charge_price = nil
  # apm_db = SQLite3::Database.open "db/app_manager_local.db"
  # apm_db.results_as_hash = true
  charges = AppManager::Charge.where(shop_domain: params['shop_domain'])
  if charges.present?
    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 = AppManager::Plan.where(plan_id: active_plan_id)
    active_charge_price = plan_data.first['price'] if plan_data.present?
  end

  custom_plan_ids = []
  plan_users = AppManager::PlanUser.where(shop_domain: params['shop_domain'])
  custom_plan_ids = plan_users.pluck(:plan_id) if plan_users.present?

  custom_plan_base_ids = []
  plan_data = AppManager::Plan.where(plan_id: custom_plan_ids).where.not(base_plan: nil)
  custom_plan_base_ids = plan_data.pluck(:base_plan) if plan_data.present?

  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?
    if custom_plan_ids.present?
      plans = AppManager::Plan.where("public = ? OR plan_id IN (?)",true,custom_plan_ids).where.not(plan_id: custom_plan_base_ids)
    else
      plans = AppManager::Plan.where(public: true).where.not(plan_id: custom_plan_base_ids)
    end
  else
    if custom_plan_ids.present?
      plans = AppManager::Plan.where("public = ? OR plan_id IN (?)",true,custom_plan_ids)
    else
      plans = AppManager::Plan.where(public: true)
    end
  end

  if plans.present?
    plans.each do |plan|
      new_plan = {}
      plan.as_json.each_with_index do |(key, value)|
        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 || value == false ? false : true)
        elsif ['test'].include?(key)
          new_plan[key] = (value == 0 || value == false ? 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 = AppManager::DiscountPlan.where(shop_domain: params['shop_domain']).order(created_at: :desc)
      if custom_discounts.present?
        custom_discounts.each do |custom_discount|
          new_custom_discount = {}
          custom_discount.as_json.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



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
425
426
427
428
429
430
431
432
433
434
435
# File 'lib/app_manager/fail_safe.rb', line 386

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 = AppManager::Plan.where(plan_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
      # return @remaining_days.inspect
      trial_extension_data = AppManager::ExtendTrial.where(shop_domain: @shop_domain, plan_id: @plan_id).order(extend_trial_start_at: :desc)
      if trial_extension_data.any?
        trial_extension_data = trial_extension_data.first
        extend_trial_date = trial_extension_data['created_at'].to_datetime + 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 = AppManager::Charge.where(shop_domain: @shop_domain).order(created_at: :desc)
  if @charges.any?
    charge = @charges.first

    if charge['trial_days']
      if charge['trial_ends_on'] && DateTime.now < charge['trial_ends_on']
        @remaining_days = (charge['trial_ends_on'].to_datetime - DateTime.now.to_datetime).to_i
      end

      # ADD EXTRA DAY
      if charge['created_at'] && ((charge['created_at'].to_datetime - DateTime.now.to_datetime).to_i == 0)
        @remaining_days = @remaining_days + 1
      end
      # TODO: Uncomment this code when we implement Shopify trial extension apis
      # trial_extension_data = AppManager::ExtendTrial.where(shop_domain: @shop_domain, plan_id: @plan_id).order(extend_trial_start_at: :desc)
      # if trial_extension_data.any?
      #   trial_extension_data = trial_extension_data.first
      #   extend_trial_date = 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

Complete



131
132
133
134
135
136
137
138
139
# File 'lib/app_manager/fail_safe.rb', line 131

def save_api_app_structures(app_structures)
  begin
    # ActiveRecord::Base.establish_connection(:app_manager).connection.execute("TRUNCATE app_structures RESTART IDENTITY")
    AppManager::AppStructure.connection.truncate(AppManager::AppStructure.table_name)
  rescue
    AppManager::AppStructure.delete_all
  end
  AppManager::AppStructure.create(banners: app_structures.to_h)
end

#save_api_apps(apps) ⇒ Object



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/app_manager/fail_safe.rb', line 113

def save_api_apps(apps)
  begin
    # ActiveRecord::Base.establish_connection(:app_manager).connection.execute("TRUNCATE apps RESTART IDENTITY")
    AppManager::App.connection.truncate(AppManager::App.table_name)
  rescue
    AppManager::App.delete_all
  end
  if apps.any?
    apps_data = []
    apps.each do |app|
      # apps_data << AppManager::App.new(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'])
      apps_data << AppManager::App.new(app_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'])
    end
    AppManager::Charge.bulk_import apps_data
  end
end

#save_api_charges(charges) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/app_manager/fail_safe.rb', line 95

def save_api_charges(charges)
  begin
    # ActiveRecord::Base.establish_connection(:app_manager).connection.execute("TRUNCATE charges RESTART IDENTITY")
    AppManager::Charge.connection.truncate(AppManager::Charge.table_name)
  rescue
    AppManager::Charge.delete_all
  end
  if charges.any?
    charge_data = []
    charges.each do |charge|
      charge_test = charge['test'] ? true : false
      charge_data << AppManager::Charge.new(c_id: charge["id"],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)
    end
    AppManager::Charge.bulk_import charge_data
  end
end

#save_api_data(params) ⇒ Object



21
22
23
24
25
26
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
# File 'lib/app_manager/fail_safe.rb', line 21

def save_api_data(params)
  begin
    save_api_plans(params["plans"])
  rescue Exception => e
    Rollbar.error("[api_plans] APP MANAGER >>>> #{e.inspect}")
  end

  begin
    save_api_charges(params["charges"])
  rescue Exception => e
    Rollbar.error("[api_charges] APP MANAGER >>>> #{e.inspect}")
  end

  begin
    save_api_apps(params["apps"])
  rescue Exception => e
    Rollbar.error("[save_api_apps] APP MANAGER >>>> #{e.inspect}")
  end

  begin
    save_api_app_structures(params["app_structures"])
  rescue Exception => e
    Rollbar.error("[save_api_app_structures] APP MANAGER >>>> #{e.inspect}")
  end

  begin
    save_api_discount_plans(params["discount_plans"])
  rescue Exception => e
    Rollbar.error("[Discount Plans] APP MANAGER >>>> #{e.inspect}")
  end

  begin
    save_api_extend_trials(params["extend_trials"])
  rescue Exception => e
    Rollbar.error("[Extens Trials] APP MANAGER >>>> #{e.inspect}")
  end

  begin
    save_api_plan_users(params["plan_users"])
  rescue Exception => e
    Rollbar.error("[Plan User] APP MANAGER >>>> #{e.inspect}")
  end
end

#save_api_discount_plans(discount_plans) ⇒ Object



141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/app_manager/fail_safe.rb', line 141

def save_api_discount_plans(discount_plans)
  begin
    # ActiveRecord::Base.establish_connection(:app_manager).connection.execute("TRUNCATE discount_plans RESTART IDENTITY")
    AppManager::DiscountPlan.connection.truncate(AppManager::DiscountPlan.table_name)
  rescue
    AppManager::DiscountPlan.delete_all
  end
  if discount_plans.any?
    discount_plans_data = []
    discount_plans.each do |discount_plan|
      discount_plans_data << AppManager::DiscountPlan.new(discount_plan_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'])
      # discount_plans_data << AppManager::DiscountPlan.new(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'])
    end
    AppManager::DiscountPlan.bulk_import discount_plans_data
  end
end

#save_api_extend_trials(extend_trials) ⇒ Object



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/app_manager/fail_safe.rb', line 158

def save_api_extend_trials(extend_trials)
  begin
    # ActiveRecord::Base.establish_connection(:app_manager).connection.execute("TRUNCATE extend_trials RESTART IDENTITY")
    AppManager::ExtendTrial.connection.truncate(AppManager::ExtendTrial.table_name)
  rescue
    AppManager::ExtendTrial.delete_all
  end
  if extend_trials.any?
    extend_trials_data = []
    extend_trials.each do |extend_trial|
      extend_trials_data << AppManager::ExtendTrial.new(extend_trial_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'])
      # extend_trials_data << AppManager::ExtendTrial.new(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'])
    end
    AppManager::ExtendTrial.bulk_import extend_trials_data
  end
end

#save_api_plan_users(plan_users) ⇒ Object



175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/app_manager/fail_safe.rb', line 175

def save_api_plan_users(plan_users)
  begin
    # ActiveRecord::Base.establish_connection(:app_manager).connection.execute("TRUNCATE plan_users RESTART IDENTITY")
    AppManager::PlanUser.connection.truncate(AppManager::PlanUser.table_name)
  rescue
    AppManager::PlanUser.delete_all
  end
  if plan_users.any?
    extend_plan_users = []
    plan_users.each do |plan_user|
      extend_plan_users << AppManager::PlanUser.new(plan_user_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'])
      # extend_plan_users << AppManager::PlanUser.new(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'])
    end
    AppManager::ExtendTrial.bulk_import extend_plan_users
  end
end

#save_api_plans(plans) ⇒ Object



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
# File 'lib/app_manager/fail_safe.rb', line 65

def save_api_plans(plans)
  begin
    # ActiveRecord::Base.establish_connection(:app_manager).connection.execute("TRUNCATE plans RESTART IDENTITY")
    AppManager::Plan.connection.truncate(AppManager::Plan.table_name)
  rescue
    AppManager::Plan.delete_all
  end
  if plans.any?
    plan_data = []
    plans.each do |plan|
      interval = {}
      shopify_plans = []
      affiliate = []
      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
      is_external_charge = plan['is_external_charge'] ? 1 : 0
      plan_data << AppManager::Plan.new(plan_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"],is_external_charge: plan["is_external_charge"],external_charge_limit: plan["external_charge_limit"],terms: plan["terms"])
    end
    AppManager::Plan.bulk_import plan_data
  end
end

#store_cancel_charge(params, options) ⇒ Object



499
500
501
502
503
504
505
506
507
# File 'lib/app_manager/fail_safe.rb', line 499

def store_cancel_charge(params, options)
  message = {"message" => 'fail'}
  if options && options[:shop_domain].present? && options[:plan_id].present?
    time = "#{DateTime.now}"
    AppManager::Charge.where(plan_id: options[:plan_id], shop_domain: options[:shop_domain]).update_all(status: 'cancelled',cancelled_on: time, sync: false)
    message = {"message" => 'success'}
  end
  return message
end

#store_local_charge(params, options) ⇒ Object



479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
# File 'lib/app_manager/fail_safe.rb', line 479

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"]
      plan_id = charge["plan_id"].to_i
      begin
        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)
        message = {"message" => 'success'}
      rescue Exception => e
        Rollbar.error("Charge not saved on local DB due to #{e.inspect}")
      end
    end
  end
  return message
end

#sync_app_managerObject



510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
# File 'lib/app_manager/fail_safe.rb', line 510

def sync_app_manager
  plan_obj = AppManager::Client.new
  response = plan_obj.get_status
  if response && response.code == 200
    charges = AppManager::Charge.where(sync: false)
    charges.each 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"
          AppManager::Charge.find_by(charge_id: charge['charge_id']).update(sync: true)
        end
      end
    end
  end
end