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.



8
9
10
11
# File 'lib/app_manager/fail_safe.rb', line 8

def initialize(db_name='app_manager_local')
  @apm_db = SQLite3::Database.open "db/#{db_name}.db"
  @apm_db.results_as_hash = true
end

Instance Method Details

#get_local_app_structuresObject



109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/app_manager/fail_safe.rb', line 109

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



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

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



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/app_manager/fail_safe.rb', line 160

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'].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

      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_plansObject



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/app_manager/fail_safe.rb', line 125

def get_local_plans
    plans = []
    @apm_db.execute( "SELECT * FROM plans;") 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'].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")}.group_by{|h| h['feature_id']}
        new_feature = {}
        value.each_with_index do |(k, v), index|
          new_feature[k] = v.first if v.class == Array
        end
        new_plan[key] = new_feature
      else
        new_plan[key] = value unless key.class == Integer
      end
    end
      plans.push(new_plan)
    end
  return plans
end

#get_local_remaining_days(params, options) ⇒ Object



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

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



80
81
82
83
84
85
86
# File 'lib/app_manager/fail_safe.rb', line 80

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

#save_api_apps(apps) ⇒ Object



69
70
71
72
73
74
75
76
77
# File 'lib/app_manager/fail_safe.rb', line 69

def save_api_apps(apps)
  @apm_db.execute("DROP TABLE IF EXISTS apps;")
  @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)"
  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



58
59
60
61
62
63
64
65
66
# File 'lib/app_manager/fail_safe.rb', line 58

def save_api_charges(charges)
  @apm_db.execute("DROP TABLE IF EXISTS charges;")
  @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))"
  if charges.any?
      charges.each do |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, 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



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/app_manager/fail_safe.rb', line 13

def save_api_data(params) 
  Thread.new do      
  save_api_plans(params["plans"])
  end
  Thread.new do
  save_api_charges(params["charges"])
  end
  Thread.new do
  save_api_apps(params["apps"])
  end
  Thread.new do
  save_api_app_structures(params["app_structures"])
  end
  Thread.new do
  save_api_discount_plans(params["discount_plans"])
  end
  Thread.new do
  save_api_extend_trials(params["extend_trials"])
    end
end

#save_api_discount_plans(discount_plans) ⇒ Object



88
89
90
91
92
93
94
95
96
# File 'lib/app_manager/fail_safe.rb', line 88

def save_api_discount_plans(discount_plans)
    @apm_db.execute("DROP TABLE IF EXISTS discount_plans;")
    @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))"
     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



98
99
100
101
102
103
104
105
106
# File 'lib/app_manager/fail_safe.rb', line 98

def save_api_extend_trials(extend_trials)
  @apm_db.execute("DROP TABLE IF EXISTS extend_trials;")
  @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)"
  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_plans(plans) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/app_manager/fail_safe.rb', line 34

def save_api_plans(plans)
    @apm_db.execute("DROP TABLE IF EXISTS plans;")
    @apm_db.execute "CREATE TABLE IF NOT EXISTS plans(id integer,type varchar(255),  name varchar(255),  price float,  offer_text varchar(255),  interval text,  shopify_plans text,  trial_days integer,  test boolean,  on_install integer,  is_custom boolean,  app_id integer,  base_plan integer,  created_at datetime,  updated_at datetime,  public boolean,  discount integer,  cycle_count integer,  store_base_plan boolean,  discount_type varchar(255),  affiliate text,  features text)"

   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
      @apm_db.execute("INSERT INTO plans (  id ,  type ,  name ,  price ,  offer_text ,  interval ,  shopify_plans ,  trial_days ,  test ,  on_install ,  is_custom ,  app_id ,  base_plan ,  created_at,  updated_at ,  public ,  discount ,  cycle_count ,  store_base_plan ,  discount_type,  affiliate,  features ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",plan["id"], plan["type"], plan["name"], plan["price"], plan["offer_text"], "#{interval}", "#{shopify_plans}", plan["trial_days"], plan_test, plan["on_install"], is_custom, plan["app_id"], plan["base_plan"], plan["created_at"], plan["updated_at"],public_val, plan["discount"], plan["cycle_count"], store_base_plan, plan["discount_type"], "#{affiliate}", "#{features}")
    end
    end
end

#store_cancel_charge(params, options) ⇒ Object



290
291
292
293
294
295
296
297
298
# File 'lib/app_manager/fail_safe.rb', line 290

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



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

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



302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
# File 'lib/app_manager/fail_safe.rb', line 302

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