Class: AppManager::PlansController

Inherits:
ApplicationController show all
Defined in:
app/controllers/app_manager/plans_controller.rb

Constant Summary collapse

ALLOWED_SORTS =
%w[name shopify_email created_at].freeze

Instance Method Summary collapse

Instance Method Details

#active_without_planObject



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
# File 'app/controllers/app_manager/plans_controller.rb', line 202

def active_without_plan
  if params[:shop_domain].present? && params[:plan_id].present? && model
    @shop = shop_data
    @trial_activated_field = AppManager.configuration.field_names['trial_activated_at']
    plan_obj = AppManager::Client.new
    plan_data = plan_obj.get_plan(params[:plan_id], params[:shop_domain]) rescue nil
    # Only stamp the trial start the first time; re-assigning a no-charge plan must
    # not restart the trial clock (that would hand back trial days already consumed).
    existing_trial_activated_at = @shop[@trial_activated_field] rescue nil
    update_info = {@plan_field => params[:plan_id]}
    update_info[@trial_activated_field] = DateTime.now if existing_trial_activated_at.blank?
    if !config_trial_days.nil? && !plan_data.nil?
      trial_days = plan_data['trial_days'] || 0
      update_info[config_trial_days] = trial_days
    end
    if @shop.update(update_info)
      begin
        AppManager.clear_cache
        AppManager::EventHandler.new('charge_created', {
            "plan" => plan_data,
            "charge" => nil,
            "previous_charge" => nil,
            "choose_later" => true,
            "shopify_domain" => params[:shop_domain]
        })
      rescue Exception => e
        Rollbar.error("APP MANAGER Error in Active without plan method #{e}")
      end
      render json: {'status' => true}
    else
      render json: {'status' => false, 'error' => "#{@shop.errors.full_messages.to_sentence}"}, status: 422
    end
  else
    render json: {'status' => false, 'error' => 'Shop not found or missing shop'}, status: 422
  end
end

#burst_cacheObject



240
241
242
243
# File 'app/controllers/app_manager/plans_controller.rb', line 240

def burst_cache
  AppManager.clear_cache
  head :ok
end

#fail_safe_backupObject



246
247
248
249
250
251
252
253
254
255
# File 'app/controllers/app_manager/plans_controller.rb', line 246

def fail_safe_backup
  params_permit
  backup_type = params[:backup_type] || "full"
  if (backup_type == "incremental")
      fail_safe_incremental_backup
  else
      rebuild_failsafe
  end
  head :ok
end

#fail_safe_incremental_backupObject



257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'app/controllers/app_manager/plans_controller.rb', line 257

def fail_safe_incremental_backup
  Thread.new do
    @fs = AppManager::FailSafe.new
    begin
      @fs.sync_app_manager
    rescue Exception => e
      Rails.logger.info "APP MANAGER >>>> LOCAL DB couldn't sync with POTAL DB #{e.inspect}"
    end

    begin
      @fs.fail_safe_incremental_backup(params)
    rescue Exception => e
      Rails.logger.info "APP MANAGER fail_safe_incremental_backup >>>> #{e.inspect}"
    end
    AppManager.clear_cache
  end
end

#indexObject



11
12
13
# File 'app/controllers/app_manager/plans_controller.rb', line 11

def index
  render :json => {"features" => AppManager.configuration.plan_features || []}
end

#plansObject



16
17
18
19
20
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
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'app/controllers/app_manager/plans_controller.rb', line 16

def plans
  most_popular_plan_ids_raw = AppManager.configuration.most_popular_plan_ids || []
  most_popular_plan_ids = Array(most_popular_plan_ids_raw).filter_map { |v| v.to_s =~ /\A\d+\z/ ? v.to_i : nil }.uniq
  active_plan_id_or_name = nil
  shopify_plan = nil
  plan = nil
  active_charge = nil
  default_plan_id = nil
  choose_later = false
  trial_activated_at = nil
  bundle_plan = nil
  plan_obj = AppManager::Client.new
  plans = []
  if params[:shop_domain].present? && !AppManager.configuration.plan_features.nil?
    @shop = shop_data
    if !@shop.nil?
      active_plan_id_or_name = @shop[@plan_field] rescue nil
      sdk_versions = {
        'backend' => AppManager::VERSION,
        'frontend' => params[:frontend_sdk_version]
      }
      plans = plan_obj.get_plans(params[:shop_domain], active_plan_id_or_name, sdk_versions)
      # render json: plans and return #use this to test plan failsafe api
      if !@field_names.nil? && @field_names.has_key?('shopify_plan') && !@field_names.nil?
        shopify_plan_field = AppManager.configuration.field_names['shopify_plan']
        shopify_plan = @shop[shopify_plan_field] rescue nil
        plan = plans && plans.any? && !active_plan_id_or_name.nil? ? (plans.find { |x| x["id"] == active_plan_id_or_name }.present? ? plans.find { |x| x["id"] == active_plan_id_or_name } : nil) : nil
        # global_plan = plans&.find { |x| x["is_global"] == 1 or x["is_global"] == true }
        @trial_activated_field = AppManager.configuration.field_names['trial_activated_at']
        trial_activated_at = @shop[@trial_activated_field] rescue nil
        active_charge = plan_obj.get_charge(params[:shop_domain])
        if (plan.nil? || plan.empty?) && (active_charge.present? && active_charge.any? && !active_charge['bundle_charge'].nil?)
          global_plan_obj = AppManager::Client.new
          plan = global_plan_obj.get_bundle_plan(active_plan_id_or_name)
        end
        if active_charge && active_charge.any? && active_charge['active_charge'].nil? && active_charge['cancelled_charge'].nil? && !trial_activated_at && !plan
          choose_later = true
        end

      end
    else
      Rollbar.error("APP MANAGER >>>>  Either model is defined wrong or config.plan_id_or_name_field is nil in initializer ===")
    end
  else
    Rollbar.error("APP MANAGER >>>>  Either params missing store_domain or config.plan_features is nil in initializer ===")
  end


  plans = plan_obj.get_plans(params[:shop_domain]) if plans && plans.blank?
  default_plan_data = plans.select { |x| x['choose_later_plan'] == true }
  if default_plan_data.any?
    if default_plan_data.select { |x| x['store_base_plan'] == true }.size > 0
      shopify_plans = plans.select { |x| x['interval'] == 'EVERY_30_DAYS' }
      shopify_plans.each do |shp|
        if shp && shp["shopify_plans"].include?(shopify_plan)
          default_plan_id = shp["id"]
          break
        end
      end
    else
      default_plan_id = default_plan_data.map { |e| e['id'] }.first if default_plan_data.any? rescue nil
    end
  end

  promotional_discount = []
  if params[:discount_code].present? && !params[:discount_code].nil? && @shop
    discount_local_storage = params[:discount_code]
    plan_obj = AppManager::Client.new
    promotional_discount = plan_obj.get_promotional_discount(params[:shop_domain],discount_local_storage)
    promotional_discount = [] if promotional_discount.class.to_s == "Hash" && promotional_discount.has_key?('status') && promotional_discount['status'] == 404
  end

  if plan.present? && (plan["is_global"] == 1 or plan["is_global"] == true)
   bundle_plan = plan
  else
    global_plan_obj = AppManager::Client.new
    bundle_plan = global_plan_obj.get_bundle_plan
  end

  bundle_obj = AppManager::Client.new
  app_bundle_data = bundle_obj.get_app_bundle_data

  app_faqs_obj = AppManager::Client.new
  app_faqs = app_faqs_obj.get_app_faqs || []

  # Embed the active charge's effective pricing onto the matching plan(s), so it
  # travels with the plan payload the frontend already consumes.
  active_charge_pricing = nil
  if active_charge.is_a?(Hash) && active_charge['active_charge'].is_a?(Hash) && active_charge['active_charge']['effective_price']
    ac = active_charge['active_charge']
    active_charge_pricing = {
        'plan_id' => ac['plan_id'],
        'interval' => ac['interval'],
        'effective_price' => ac['effective_price'],
        'strike_price' => ac['strike_price'],
        'is_discount_active' => ac['is_discount_active'] || false,
        'discount_ends_on' => ac['discount_ends_on'],
        'remaining_intervals' => ac['remaining_intervals'],
        'discount_value' => ac['discount_value'],
        'discount_type' => ac['discount_type'],
        'discount_duration_intervals' => ac['discount_duration_intervals']
    }
  end

  if active_charge_pricing.present?
    plans = plans.map { |p| with_active_charge_pricing(p, active_charge_pricing) } if plans.is_a?(Array)
    plan = with_active_charge_pricing(plan, active_charge_pricing)
  end

  response = {
      'plans' => plans,
      'promotional_discount' => promotional_discount,
      'shopify_plan' => shopify_plan,
      'plan' => plan,
      'bundle_plan' => bundle_plan,
      'bundle_details' => app_bundle_data,
      'default_plan_id' => default_plan_id,
      'most_popular_plan_ids' => most_popular_plan_ids,
      'choose_later' => choose_later,
      'has_active_charge' => (((active_charge && active_charge.any? && !active_charge['active_charge'].nil?) || (plan.present? && plan['price'].to_f == 0) || !trial_activated_at) ? true : false),
      'global_plan_charge' => plan.present? && plan['is_global'] && active_charge.present? && active_charge.any? && !active_charge['active_charge'].nil? && !active_charge['bundle_charge'].nil?,
      'app_faqs' => app_faqs
  }
  render json: response
end

#rebuild_failsafeObject



276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# File 'app/controllers/app_manager/plans_controller.rb', line 276

def rebuild_failsafe
  params_permit
  Thread.new do
    @fs = AppManager::FailSafe.new
    begin
      @fs.sync_app_manager
    rescue Exception => e
      Rails.logger.info "APP MANAGER >>>> LOCAL DB couldn't sync with POTAL DB #{e.inspect}"
    end

    begin
      @fs.save_api_data(params)
    rescue Exception => e
      Rails.logger.info "APP MANAGER >>>> #{e.inspect}"
    end
    AppManager.clear_cache
  end
  head :ok
end

#usersObject



153
154
155
156
157
158
159
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
# File 'app/controllers/app_manager/plans_controller.rb', line 153

def users
  if model

    search = params[:search]
    sort_param = params[:sort]&.downcase
    sort = ALLOWED_SORTS.include?(sort_param) ? AppManager.configuration.field_names[sort_param] : 'created_at'
    order_param = params[:order]&.downcase
    order = %w[asc desc].include?(order_param) ? order_param : 'asc'
    plans = params[:plans] || nil
    plans = plans.values if !plans.nil?
    shopify_plans = params[:shopify_plans] || nil
    shopify_plans = shopify_plans.values if !shopify_plans.nil?
    items_per_page = params[:itemsPerPage] || 25
    @shopify_email = AppManager.configuration.field_names['shopify_email']
    @shopify_plan_name_field = AppManager.configuration.field_names['shopify_plan']
    if params[:search]
      data = model.where("#{@shopify_domain} LIKE :search OR #{@shopify_email} LIKE :search", search: "%#{search}%").order(sort => order)
      data = data.where(@plan_field => plans) if !plans.nil?
      data = data.where(@shopify_plan_name_field => shopify_plans) if !shopify_plans.nil?
      data = data.page(params[:page]).per(items_per_page)
    else
      data = model.order(sort => order)
      data = data.where(@plan_field => plans) if !plans.nil?
      data = data.where(@shopify_plan_name_field => shopify_plans) if !shopify_plans.nil?
      data = data.page(params[:page]).per(items_per_page)
    end
    all_user_count = model.count
    users = {
        "current_page" => data && data.current_page ? data.current_page : 0,
        "data" => data ? data.collect { |st| @field_names.except('shopify_token').map { |key, value| [key, "#{st[value]}"] }.to_h } : [],
        "first_page_url" => "#{app_url}/api/app-manager/users?page=1",
        "from" => data && data.total_pages ? data.current_page == 1 ? 1 : ((data.current_page-1)*items_per_page)+1 : 0,
        "last_page" => data && data.total_pages ? data.total_pages : 0,
        "last_page_url" => data && data.total_pages ? "#{app_url}/api/app-manager/users?page=#{data.total_pages}" : nil,
        "links" => '',
        "next_page_url" => data && data.next_page ? "#{app_url}/api/app-manager/users?page=#{data.next_page}" : nil,
        "path" => "#{app_url}/api/app-manager/users",
        "per_page" => items_per_page,
        "prev_page_url" => data && data.prev_page ? "#{app_url}/api/app-manager/users?page=#{data.prev_page}" : nil,
        "to" => data && data.total_pages ? data.current_page == data.total_pages ? all_user_count : ((data && data.current_page ? data.current_page : 0)*data.size) : 0,
        "total" => all_user_count,
    }
    render json: users

  else
    render json: nil
  end
end

#with_active_charge_pricing(plan, pricing) ⇒ Object

Attaches active_charge_pricing to a plan only when it is the plan the active charge belongs to (same id and, when known, same interval).



144
145
146
147
148
149
150
151
# File 'app/controllers/app_manager/plans_controller.rb', line 144

def with_active_charge_pricing(plan, pricing)
  return plan unless plan.is_a?(Hash) && plan.present?
  matches_plan = plan['id'].to_s == pricing['plan_id'].to_s
  plan_interval = plan['interval'].is_a?(Hash) ? plan['interval']['value'] : plan['interval']
  matches_interval = pricing['interval'].blank? || plan_interval == pricing['interval']
  plan = plan.merge('active_charge_pricing' => pricing) if matches_plan && matches_interval
  plan
end