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



316
317
318
319
320
321
322
323
# File 'lib/app_manager/fail_safe.rb', line 316

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



568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
# File 'lib/app_manager/fail_safe.rb', line 568

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_discount(params, options) ⇒ Object



608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
# File 'lib/app_manager/fail_safe.rb', line 608

def get_local_discount(params, options)
  code = [params['code']].pack('H*')
  shop_domain = params['shop_domain']
  now = Time.now

  discount_data = AppManager::Discount.where(enabled: true)
                      .where('valid_from <= ?', now)
                      .where('valid_to IS NULL OR valid_to >= ?', now)
                      .where(code: code)
                      .first
  return [] if discount_data.nil?

  discount_shop = AppManager::DiscountShop.where(discount_id: discount_data.discount_id).count

  discount_plan = AppManager::DiscountLinkPlan.where(discount_id: discount_data.discount_id).pluck('plan_id')

  discount_usage = AppManager::DiscountUsageLog.where(discount_id: discount_data.discount_id).count

  discount_usage_by_domain = AppManager::DiscountUsageLog.where(discount_id: discount_data.discount_id)
                                 .where(domain: shop_domain)
                                 .count
  if discount_shop > 0
    discount_shop_specific = AppManager::DiscountShop.where(discount_id: discount_data.discount_id)
                                 .where(domain: shop_domain)
                                 .first
    return [] if discount_shop_specific.nil?
  end

  if discount_data.max_usage.present? && discount_data.max_usage != 0
    return [] if discount_usage >= discount_data.max_usage
  end

  if discount_data.multiple_uses == false && discount_usage_by_domain >= 1
    return []
  end

  if discount_data.multiple_apps == false
    discount_usage_by_app = AppManager::DiscountUsageLog
                                .where(discount_id: discount_data.discount_id, domain: shop_domain)
                                .where.not(app_id: discount_data.app_id)
                                .first
    return [] if discount_usage_by_app.present?
  end


  discount_data = discount_data.attributes.symbolize_keys
  discount_data[:plan_relation] = discount_plan
  final_mapped_data = {
      "id" => discount_data[:discount_id],
      "name" => discount_data[:name],
      "type" => discount_data[:discount_type],
      "value" => discount_data[:value].to_f,
      "duration_intervals" => discount_data[:duration_intervals],
      "plan_relation" => discount_data[:plan_relation]
  } rescue {}

  return JSON.parse(final_mapped_data.to_json)

end

#get_local_has_plan(params, options) ⇒ Object



587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
# File 'lib/app_manager/fail_safe.rb', line 587

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



463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
# File 'lib/app_manager/fail_safe.rb', line 463

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)
          elsif ['plan_id'].include?(key)
            new_plan["id"] = value if value rescue nil
          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



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

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
        elsif ['plan_id'].include?(key)
          # puts value.inspect
          new_plan["id"] = value if value rescue {}
        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


668
669
670
671
# File 'lib/app_manager/fail_safe.rb', line 668

def get_local_related_discounted_plans(params, options)
  discounted_plans = DiscountLinkPlan.where(discount_id: params['discount_id']).pluck(:plan_id) rescue []
  return discounted_plans
end

#get_local_remaining_days(params, options) ⇒ Object



515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
# File 'lib/app_manager/fail_safe.rb', line 515

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



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

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



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

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



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/app_manager/fail_safe.rb', line 120

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
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
# 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("[Extend 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

  begin
    save_api_promotional_discounts(params["promotional_discounts"])
  rescue Exception => e
    Rollbar.error("[Promotional discounts] APP MANAGER >>>> #{e.inspect}")
  end

  begin
    save_api_promotional_discounts_shops(params["promotional_discounts_shops"])
  rescue Exception => e
    Rollbar.error("[Promotional discounts shops] APP MANAGER >>>> #{e.inspect}")
  end

  begin
  save_api_promotional_discounts_link_plans(params["promotional_discounts_plans"])
  rescue Exception => e
    Rollbar.error("[Promotional discounts plans] APP MANAGER >>>> #{e.inspect}")
  end

  begin
    save_api_promotional_discounts_usage_log(params["promotional_discounts_usage_log"])
  rescue Exception => e
    Rollbar.error("[Promotional discounts usage log] APP MANAGER >>>> #{e.inspect}")
  end

end

#save_api_discount_plans(discount_plans) ⇒ Object



166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/app_manager/fail_safe.rb', line 166

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



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/app_manager/fail_safe.rb', line 183

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



200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/app_manager/fail_safe.rb', line 200

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::PlanUser.bulk_import extend_plan_users
  end
end

#save_api_plans(plans) ⇒ Object



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 90

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

#save_api_promotional_discounts(promotional_discounts) ⇒ Object



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

def save_api_promotional_discounts(promotional_discounts)
  begin
    AppManager::Discount.connection.truncate(AppManager::Discount.table_name)
  rescue
    AppManager::Discount.delete_all
  end
  if promotional_discounts.any?
    promotional_discounts_data = []
    promotional_discounts.each do |promotional_discount|

       promotional_discounts_data << AppManager::Discount.new(
          discount_id: promotional_discount['id'],
          name: promotional_discount['name'],
          code: promotional_discount['code'],
          discount_type: promotional_discount['type'] || 'amount',
          value: promotional_discount['value'] || 0,
          duration_intervals: promotional_discount['duration_intervals'],
          max_usage: promotional_discount['max_usage'],
          enabled: promotional_discount['enabled'],
          valid_from: promotional_discount['valid_from'],
          valid_to: promotional_discount['valid_to'],
          priority: promotional_discount['priority'] || 0,
          multiple_uses: promotional_discount['multiple_uses'],
          multiple_apps: promotional_discount['multiple_apps'],
          app_id: promotional_discount['app_id'] || 0,
          created_at: promotional_discount['created_at'],
          updated_at: promotional_discount['updated_at'],
          deleted_at: promotional_discount['deleted_at']
       )
    end

    AppManager::Discount.bulk_import promotional_discounts_data
  end
end


272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/app_manager/fail_safe.rb', line 272

def save_api_promotional_discounts_link_plans(promotional_discounts_plans)

  begin
    AppManager::DiscountLinkPlan.connection.truncate(AppManager::DiscountLinkPlan.table_name)
  rescue
    AppManager::DiscountLinkPlan.delete_all
  end

  if promotional_discounts_plans.any?
    discount_link_plans_data = []
    promotional_discounts_plans.each do |link_plan|
      discount_link_plans_data << AppManager::DiscountLinkPlan.new(
          discount_id: link_plan['discount_id'],
          plan_id: link_plan['plan_id']
      )
    end
    AppManager::DiscountLinkPlan.bulk_import discount_link_plans_data
  end
end

#save_api_promotional_discounts_shops(promotional_discounts_shops) ⇒ Object



252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/app_manager/fail_safe.rb', line 252

def save_api_promotional_discounts_shops(promotional_discounts_shops)

  begin
    AppManager::DiscountShop.connection.truncate(AppManager::DiscountShop.table_name)
  rescue
    AppManager::DiscountShop.delete_all
  end

  if promotional_discounts_shops.any?
    promotional_discounts_shop_data = []
    promotional_discounts_shops.each do |promotional_discounts_shop|
      promotional_discounts_shop_data << AppManager::DiscountShop.new(
          discount_id: promotional_discounts_shop['discount_id'],
          domain: promotional_discounts_shop['domain']
      )
    end
    AppManager::DiscountShop.bulk_import promotional_discounts_shop_data
  end
end

#save_api_promotional_discounts_usage_log(promotional_discounts_usage_log) ⇒ Object



292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
# File 'lib/app_manager/fail_safe.rb', line 292

def save_api_promotional_discounts_usage_log(promotional_discounts_usage_log)
  begin
    AppManager::DiscountUsageLog.connection.truncate(AppManager::DiscountUsageLog.table_name)
  rescue
    AppManager::DiscountUsageLog.delete_all
  end

  if promotional_discounts_usage_log.any?
    promotional_discounts_usage_log_data = []
     promotional_discounts_usage_log.each do |log|
       promotional_discounts_usage_log_data << AppManager::DiscountUsageLog.new(
          discount_id: log['discount_id'],
          app_id: log['app_id'],
          domain: log['domain'],
          sync: log['sync'],
          process_type: log['process_type'],
          created_at: log['created_at'],
          updated_at: log['updated_at']
       )
    end
    AppManager::DiscountUsageLog.bulk_import promotional_discounts_usage_log_data
  end
end

#store_cancel_charge(params, options) ⇒ Object



693
694
695
696
697
698
699
700
701
# File 'lib/app_manager/fail_safe.rb', line 693

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_discount_used(params, options) ⇒ Object



703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
# File 'lib/app_manager/fail_safe.rb', line 703

def store_discount_used(params,options)
  if options && options[:shop_domain].present? && options[:discount_id].present?
    app_id = AppManager::Discount.where(discount_id: options[:discount_id])
                 .pluck(:app_id)
                 .first rescue nil
    data = {
        'discount_id' => options[:discount_id],
        'domain' => options[:shop_domain],
        'sync' => false,
        'process_type' => 'use-discount',
        'app_id' => app_id
    }
    discount_usage_log = AppManager::DiscountUsageLog.create(data)
    return { 'message' => discount_usage_log ? 'success' : 'fail' }
  else
    return {"message" => 'fail'}
  end
end

#store_local_charge(params, options) ⇒ Object



673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
# File 'lib/app_manager/fail_safe.rb', line 673

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, process_type: 'store-charge')
        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



723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
# File 'lib/app_manager/fail_safe.rb', line 723

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)
    discounts_usage_logs = AppManager::DiscountUsageLog.where(sync: false, process_type: 'use-discount')
    charges.each do |charge|
      if charge
        if !charge["cancelled_on"].nil?
          charge["cancelled_on"] = charge["cancelled_on"].to_s if charge["cancelled_on"].is_a?(ActiveSupport::TimeWithZone)
          charge["cancelled_on"] = Date.parse(charge["cancelled_on"]) if charge["cancelled_on"].is_a?(String)
        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

    if discounts_usage_logs.any?
      discounts_usage_logs.each do |discount_usage_log|
        discount_obj = AppManager::Client.new
        discount_response = discount_obj.sync_discount_usage_log(shop_domain: discount_usage_log['domain'], discount_id: discount_usage_log['discount_id'].to_i)
        if discount_response && discount_response["data"] == "Saved"
          AppManager::DiscountUsageLog.find_by(discount_id: discount_usage_log['discount_id'],sync: false).update(sync: true, process_type: nil)
        end
      end
    end

  end
end