Class: Kaui::SubscriptionsController

Inherits:
EngineController show all
Defined in:
app/controllers/kaui/subscriptions_controller.rb

Constant Summary

Constants included from EngineControllerUtil

EngineControllerUtil::MAXIMUM_NUMBER_OF_RECORDS_DOWNLOAD, EngineControllerUtil::SIMPLE_PAGINATION_THRESHOLD

Instance Method Summary collapse

Methods inherited from EngineController

#check_for_redirect_to_tenant_screen, #current_ability, #current_user, #options_for_klient, #populate_account_details, #retrieve_allowed_users_for_current_user, #retrieve_tenants_for_current_user

Methods included from ErrorHandler

#perform_redirect_after_error

Instance Method Details

#createObject



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
# File 'app/controllers/kaui/subscriptions_controller.rb', line 35

def create
  plan_name = params.require(:plan_name)
  @base_product_name = params[:base_product_name]
  @subscription = Kaui::Subscription.new(params.require(:subscription).permit!.to_h.compact_blank)

  begin
    @bundle, plans_details = lookup_bundle_and_plan_details(@subscription, @base_product_name)

    plan_details = plans_details.find { |p| p.plan == plan_name }
    raise "Unable to find plan #{plan_name}" if plan_details.nil?

    @subscription.plan_name = plan_name
    requested_date = params[:type_change] == 'DATE' ? params[:requested_date].presence : nil

    # price override?
    override_fixed_price = begin
      plan_details.phases.first.prices.blank?
    rescue StandardError
      false
    end
    override_recurring_price = !override_fixed_price
    phase_type = @bundle.nil? ? plan_details.phases.first.type : @bundle.subscriptions.first.phase_type
    overrides = price_overrides(phase_type, override_fixed_price, override_recurring_price)
    @subscription.price_overrides = overrides if overrides.present?
    @subscription.quantity = params[:quantity].to_i if params[:quantity].present? && params[:quantity].to_i.positive?

    # un-set product_category since is not needed if plan name exist
    @subscription.product_category = nil
    @subscription = @subscription.create(current_user.kb_username, params[:reason], params[:comment], requested_date, false, options_for_klient)
    redirect_to kaui_engine.(@subscription.), notice: 'Subscription was successfully created'
  rescue StandardError => e
    @plans = plans_details.nil? ? [] : plans_details.map(&:plan)

    if e.is_a?(::KillBillClient::API::BadRequest) && !e.response.nil? && !e.response.body.nil?
      error_message = begin
        JSON.parse(e.response.body)
      rescue StandardError
        nil
      end
      if (!error_message.nil? & !error_message['code'].nil?) && error_message['code'] == 2010 # CAT_NO_PRICE_FOR_CURRENCY
        # Hack for lack of proper Kill Bill messaging (https://github.com/killbill/killbill-admin-ui/issues/266)
        flash.now[:error] = "Unable to create the subscription: a price for this currency hasn't been specified in the catalog"
        render :new and return
      end
    end

    flash.now[:error] = "Error while creating the subscription: #{as_string(e)}"
    render :new
  end
end

#create_usageObject



194
195
196
197
198
199
200
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
# File 'app/controllers/kaui/subscriptions_controller.rb', line 194

def create_usage
  subscription_id = params.require(:id)
  unit_type = params[:unit_type].to_s.strip
  amount_raw = params[:amount].to_s.strip
  record_date = params[:record_date].to_s.strip

  # Input validation
  errors = []
  errors << 'Unit type is required' if unit_type.blank?
  errors << 'Amount is required' if amount_raw.blank?
  amount = Integer(amount_raw, exception: false)
  errors << 'Amount must be a positive integer' if amount.nil? || amount <= 0
  errors << 'Date/time of usage is required' if record_date.blank?
  parsed_date = begin
    record_date.blank? ? nil : Time.iso8601(record_date)
  rescue ArgumentError
    nil
  end
  errors << 'Date/time of usage must be a valid ISO 8601 timestamp' if record_date.present? && parsed_date.nil?

  if errors.any?
    flash.now[:error] = errors.join('. ')
    @subscription = Kaui::Subscription.find_by_id(subscription_id, 'NONE', options_for_klient)
    @unit_type = unit_type
    @amount = amount_raw
    @record_date = record_date
    @tracking_id = params[:tracking_id]
    render :record_usage and return
  end

  begin
    usage_record = KillBillClient::Model::UsageRecordAttributes.new
    usage_record.record_date = parsed_date.utc.iso8601
    usage_record.amount = amount

    unit_usage_record = KillBillClient::Model::UnitUsageRecordAttributes.new
    unit_usage_record.unit_type = unit_type
    unit_usage_record.usage_records = [usage_record]

    usage = Kaui::Usage.new
    usage.subscription_id = subscription_id
    usage.tracking_id = params[:tracking_id].presence
    usage.unit_usage_records = [unit_usage_record]

    usage.create(current_user.kb_username, params[:reason], params[:comment], options_for_klient)

    subscription = Kaui::Subscription.find_by_id(subscription_id, 'NONE', options_for_klient)
    redirect_to kaui_engine.(subscription.), notice: 'Usage was successfully recorded'
  rescue StandardError => e
    Rails.logger.error("Failed to record usage for subscription #{subscription_id}: #{e.class}: #{e.message}")
    Rails.logger.error(e.backtrace.join("\n")) if e.backtrace
    flash.now[:error] = "Error while recording usage: #{as_string(e)}"
    @subscription = Kaui::Subscription.find_by_id(subscription_id, 'NONE', options_for_klient)
    @unit_type = unit_type
    @amount = amount_raw
    @record_date = record_date
    @tracking_id = params[:tracking_id]
    render :record_usage
  end
end

#destroyObject



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'app/controllers/kaui/subscriptions_controller.rb', line 120

def destroy
  requested_date = params[:requested_date].presence
  billing_policy = params[:policy].presence
  # START_OF_TERM is *not* a valid entitlement_policy and so would default to IMMEDIATE
  entitlement_policy = billing_policy && billing_policy == 'START_OF_TERM' ? 'IMMEDIATE' : billing_policy

  # true by default except default policy
  use_requested_date_for_billing = if requested_date
                                     (params[:use_requested_date_for_billing] || '1') == '1'
                                   else
                                     nil
                                   end
  subscription = Kaui::Subscription.find_by_id(params.require(:id), 'NONE', options_for_klient)
  subscription.cancel(current_user.kb_username, params[:reason], params[:comment], requested_date, entitlement_policy, billing_policy, use_requested_date_for_billing, options_for_klient)
  redirect_to kaui_engine.(subscription.), notice: 'Subscription was successfully cancelled'
end

#editObject



28
29
30
31
32
33
# File 'app/controllers/kaui/subscriptions_controller.rb', line 28

def edit
  @subscription = Kaui::Subscription.find_by_id(params.require(:id), 'NONE', options_for_klient)
  _, plans_details = lookup_bundle_and_plan_details(@subscription)
  # Use a Set to deal with multiple pricelists
  @plans = Set.new.merge(plans_details.map(&:plan))
end

#edit_bcdObject



145
146
147
# File 'app/controllers/kaui/subscriptions_controller.rb', line 145

def edit_bcd
  @subscription = Kaui::Subscription.find_by_id(params.require(:id), 'NONE', options_for_klient)
end

#edit_quantityObject



161
162
163
# File 'app/controllers/kaui/subscriptions_controller.rb', line 161

def edit_quantity
  @subscription = Kaui::Subscription.find_by_id(params.require(:id), 'NONE', options_for_klient)
end

#newObject



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'app/controllers/kaui/subscriptions_controller.rb', line 9

def new
  @base_product_name = params[:base_product_name]
  @subscription = Kaui::Subscription.new(bundle_id: params[:bundle_id],
                                         account_id: params[:account_id],
                                         product_category: params[:product_category] || 'BASE')

  @bundle, plans_details = lookup_bundle_and_plan_details(@subscription, @base_product_name)
  @plans = plans_details.map(&:plan)

  return unless @plans.empty?

  flash[:error] = if @subscription.product_category == 'BASE'
                    'No plan available in the catalog'
                  else
                    "No add-on available in the catalog for product #{@base_product_name}"
                  end
  redirect_to kaui_engine.(@subscription.), error: 'No available plan'
end

#record_usageObject



190
191
192
# File 'app/controllers/kaui/subscriptions_controller.rb', line 190

def record_usage
  @subscription = Kaui::Subscription.find_by_id(params.require(:id), 'NONE', options_for_klient)
end

#reinstateObject



137
138
139
140
141
142
143
# File 'app/controllers/kaui/subscriptions_controller.rb', line 137

def reinstate
  subscription = Kaui::Subscription.find_by_id(params.require(:id), 'NONE', options_for_klient)

  subscription.uncancel(current_user.kb_username, params[:reason], params[:comment], options_for_klient)

  redirect_to kaui_engine.(subscription.), notice: 'Subscription was successfully reinstated'
end

#restful_showObject



255
256
257
258
# File 'app/controllers/kaui/subscriptions_controller.rb', line 255

def restful_show
  subscription = Kaui::Subscription.find_by_id(params.require(:id), 'NONE', options_for_klient)
  redirect_to kaui_engine.(subscription.)
end

#showObject



5
6
7
# File 'app/controllers/kaui/subscriptions_controller.rb', line 5

def show
  restful_show
end

#show_jsonObject



260
261
262
263
264
265
266
267
# File 'app/controllers/kaui/subscriptions_controller.rb', line 260

def show_json
  raw_body = Kaui::Subscription.find_raw_by_id(params.require(:id), 'NONE', options_for_klient)
  render body: raw_body, content_type: 'application/json'
rescue KillBillClient::API::ResponseError => e
  render body: e.response.body, content_type: 'application/json', status: e.code
rescue StandardError => e
  render json: { error: e.message }, status: :internal_server_error
end

#updateObject



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
# File 'app/controllers/kaui/subscriptions_controller.rb', line 86

def update
  plan_name = params.require(:plan_name)

  requested_date = params[:type_change] == 'DATE' ? params[:requested_date].presence : nil
  billing_policy = params[:type_change] == 'POLICY' ? params[:policy].presence : nil

  wait_for_completion = params[:wait_for_completion] == '1'

  subscription = Kaui::Subscription.find_by_id(params.require(:id), 'NONE', options_for_klient)

  input = { planName: plan_name }

  # price override?
  current_plan = subscription.prices.select { |price| price['phaseType'] == subscription.phase_type }
  override_fixed_price = current_plan.last['recurringPrice'].nil?
  override_recurring_price = !override_fixed_price
  overrides = price_overrides(subscription.phase_type, override_fixed_price, override_recurring_price)
  input[:priceOverrides] = overrides if overrides.present?

  subscription.change_plan(input,
                           current_user.kb_username,
                           params[:reason],
                           params[:comment],
                           requested_date,
                           billing_policy,
                           nil,
                           wait_for_completion,
                           options_for_klient)

  redirect_to kaui_engine.(subscription.), notice: 'Subscription plan successfully changed'
rescue StandardError => e
  redirect_to edit_subscription_path(params.require(:id)), flash: { error: "Error while changing subscription: #{as_string(e)}" }
end

#update_bcdObject



149
150
151
152
153
154
155
156
157
158
159
# File 'app/controllers/kaui/subscriptions_controller.rb', line 149

def update_bcd
  input_subscription = params.require(:subscription)
  subscription = Kaui::Subscription.new
  subscription.subscription_id = params.require(:id)
  subscription.bill_cycle_day_local = input_subscription['bill_cycle_day_local']

  effective_from_date = params['effective_from_date']

  subscription.update_bcd(current_user.kb_username, params[:reason], params[:comment], effective_from_date, nil, options_for_klient)
  redirect_to kaui_engine.(input_subscription['account_id']), notice: 'Subscription BCD was successfully changed'
end

#update_quantityObject



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'app/controllers/kaui/subscriptions_controller.rb', line 165

def update_quantity
  id = params.require(:id)
  input_subscription = params.require(:subscription)

  quantity_raw = input_subscription['quantity'].to_s.strip
  quantity = Integer(quantity_raw, exception: false)
  if quantity.nil? || quantity <= 0
    flash.now[:error] = 'Quantity must be a positive integer'
    @subscription = Kaui::Subscription.find_by_id(id, 'NONE', options_for_klient)
    @subscription.quantity = quantity_raw
    render :edit_quantity and return
  end

  subscription = Kaui::Subscription.new
  subscription.subscription_id = id
  subscription.quantity = quantity

  effective_from_date = params['effective_from_date']

  subscription.update_quantity(current_user.kb_username, params[:reason], params[:comment], effective_from_date, nil, options_for_klient)
  redirect_to kaui_engine.(input_subscription['account_id']), notice: 'Subscription quantity was successfully changed'
rescue ActionController::ParameterMissing
  redirect_to kaui_engine.edit_quantity_path(params[:id]), flash: { error: 'Required parameter missing: subscription' }
end

#update_tagsObject



297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'app/controllers/kaui/subscriptions_controller.rb', line 297

def update_tags
  subscription_id = params.require(:id)
  subscription = Kaui::Subscription.find_by_id(subscription_id, 'NONE', options_for_klient)
  tags = []
  params.each_key do |key|
    next unless key.include? 'tag'

    tag_info = key.split('_')
    next if (tag_info.size != 2) || (tag_info[0] != 'tag')

    tags << tag_info[1]
  end

  Kaui::Tag.set_for_subscription(subscription_id, tags, current_user.kb_username, params[:reason], params[:comment], options_for_klient)
  redirect_to kaui_engine.(subscription.), notice: 'Subscription tags successfully set'
end

#validate_bundle_external_keyObject



269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'app/controllers/kaui/subscriptions_controller.rb', line 269

def validate_bundle_external_key
  json_response do
    external_key = params.require(:external_key)

    begin
      bundle = Kaui::Bundle.find_by_external_key(external_key, false, options_for_klient)
    rescue KillBillClient::API::NotFound
      bundle = nil
    end

    { is_found: !bundle.nil? }
  end
end

#validate_external_keyObject



283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'app/controllers/kaui/subscriptions_controller.rb', line 283

def validate_external_key
  json_response do
    external_key = params.require(:external_key)

    begin
      subscription = Kaui::Subscription.find_by_external_key(external_key, 'NONE', options_for_klient)
    rescue KillBillClient::API::NotFound
      subscription = nil
    end

    { is_found: !subscription.nil? }
  end
end