Class: Kaui::AccountsController

Inherits:
EngineController
  • Object
show all
Defined in:
app/controllers/kaui/accounts_controller.rb

Instance Method Summary collapse

Instance Method Details

#blockObject



395
396
397
# File 'app/controllers/kaui/accounts_controller.rb', line 395

def block
  @account = Kaui::.find_by_id(params.require(:account_id), false, false, options_for_klient)
end

#createObject



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# File 'app/controllers/kaui/accounts_controller.rb', line 187

def create
  @account = Kaui::.new(params.require(:account).permit!.to_h.compact_blank)

  @account.errors.add(:phone, :invalid_phone) if !@account.phone.nil? && !@account.

  @account.errors.add(:check_account_details_bill_cycle_day_local, :invalid_bill_cycle_day_local) if !@account.bill_cycle_day_local.nil? && !@account.

  unless @account.errors.empty?
    flash.now[:errors] = @account.errors.messages.values.flatten
    render action: :new and return
  end

  # Transform "1" into boolean
  @account.is_migrated = @account.is_migrated == '1'

  begin
    @account = @account.create(current_user.kb_username, params[:reason], params[:comment], options_for_klient)

    redirect_to (@account.), notice: 'Account was successfully created'
  rescue StandardError => e
    flash.now[:error] = "Error while creating account: #{as_string(e)}"
    render action: :new
  end
end

#destroyObject

rubocop:enable Style/MultilineBlockChain



228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'app/controllers/kaui/accounts_controller.rb', line 228

def destroy
   = params.require(:account_id)
  options = params[:options] || []

  cancel_subscriptions = options.include?('cancel_all_subscriptions')
  writeoff_unpaid_invoices = options.include?('writeoff_unpaid_invoices')
  item_adjust_unpaid_invoices = options.include?('item_adjust_unpaid_invoices')
  cached_options_for_klient = options_for_klient

  begin
    @account = Kaui::.find_by_id_or_key(, false, false, cached_options_for_klient)
    @account.close(cancel_subscriptions, writeoff_unpaid_invoices, item_adjust_unpaid_invoices, current_user.kb_username, nil, nil, cached_options_for_klient)

    flash[:notice] = "Account #{account_id} successfully closed"
  rescue StandardError => e
    flash[:error] = "Error while closing account: #{as_string(e)}"
  end

  redirect_to ()
end

#do_blockObject



399
400
401
402
403
404
405
406
407
408
# File 'app/controllers/kaui/accounts_controller.rb', line 399

def do_block
   = params.require(:account_id)
   = Kaui::.new(account_id:)
  .set_blocking_state(params.require(:state_name), params.require(:service),
                             params[:is_block_change] == '1', params[:is_block_entitlement] == '1',
                             params[:is_block_billing] == '1', params[:requested_date].presence,
                             current_user.kb_username, params[:reason], params[:comment], options_for_klient)

  redirect_to (), notice: 'Blocking state was successfully created'
end

#downloadObject



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

def download
  start_date = params[:startDate]
  end_date = params[:endDate]
  all_fields_checked = params[:allFieldsChecked] == 'true'
  query_string = params[:search]

  if all_fields_checked
    columns = KillBillClient::Model::AccountAttributes.instance_variable_get(:@json_attributes)
    csv_headers = columns.dup
    Kaui::::REMAPPING_FIELDS.each do |k, v|
      index = csv_headers.index(k)
      csv_headers[index] = v if index
    end
  else
    columns = params.require(:columnsString).split(',').map { |attr| attr.split.join('_').downcase }
    csv_headers = columns.dup
    Kaui::::REMAPPING_FIELDS.each do |k, v|
      index = columns.index(v)
      columns[index] = k if index
    end
  end

  start_date = begin
    Date.parse(start_date)
  rescue StandardError
    nil
  end
  end_date = begin
    Date.parse(end_date)
  rescue StandardError
    nil
  end
  query_string = remapping_addvanced_search_fields(query_string, Kaui::::ADVANCED_SEARCH_NAME_CHANGES)
  accounts = Kaui::.list_or_search(query_string, 0, MAXIMUM_NUMBER_OF_RECORDS_DOWNLOAD, options_for_klient)

  csv_string = CSV.generate(headers: true) do |csv|
    csv << csv_headers
    accounts.each do ||
      change_date = Date.parse(.reference_time)
      data = columns.map do |attr|
        &.send(attr.downcase)
      end
      next if start_date && end_date && change_date && (change_date < start_date || change_date > end_date)

      csv << data
    end
  end
  send_data csv_string, filename: "accounts-#{Time.zone.today}.csv", type: 'text/csv'
end

#editObject



185
# File 'app/controllers/kaui/accounts_controller.rb', line 185

def edit; end

#events_to_considerObject



384
385
386
387
388
# File 'app/controllers/kaui/accounts_controller.rb', line 384

def events_to_consider
  json_response do
    { data: Dependencies::Kenui::EmailNotification.get_events_to_consider(options_for_klient) }
  end
end

#export_accountObject



390
391
392
393
# File 'app/controllers/kaui/accounts_controller.rb', line 390

def 
  data = KillBillClient::Model::Export.(params[:account_id], current_user.kb_username, options_for_klient)
  send_data data, filename: "account#{params[:account_id]}.txt", type: :txt
end

#indexObject



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

def index
  @search_query = params[:q]
  @advance_search_query = @search_query.presence || params[:advance_search_query].presence
  if @search_query.present?
     = Kaui::.list_or_search(@search_query, -1, 1, options_for_klient).first
    if .nil?
      flash[:error] = "No account matches \"#{@search_query}\""
      redirect_to kaui_engine.home_path
    else
      redirect_to kaui_engine.(.)
    end
    return
  end
  @search_fields = Kaui::::ADVANCED_SEARCH_COLUMNS.map { |attr| [attr, attr.split('_').join(' ').capitalize] }
  @dropdown_default = default_columns(Kaui..call[2], Kaui::::DEFAULT_VISIBLE_COLUMNS)
  @visible_columns = @dropdown_default

  @ordering = params[:ordering] || (@search_query.blank? ? 'desc' : 'asc')
  @offset = params[:offset] || 0
  @limit = params[:limit] || 50

  @max_nb_records = @search_query.blank? ? Kaui::.list_or_search(nil, 0, 0, options_for_klient).pagination_max_nb_records : 0
end


319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
# File 'app/controllers/kaui/accounts_controller.rb', line 319

def link_to_parent
  @account = Kaui::.new(params.require(:account).permit!.to_h.compact_blank)
  @account. = params.require(:account_id)
  @account.is_payment_delegated_to_parent = @account.is_payment_delegated_to_parent == '1'

  raise('Account id and account parent id cannot be equal.') if @account. == @account.

  cached_options_for_klient = options_for_klient

  # check if parent id is valid
  Kaui::.find_by_id(@account., false, false, cached_options_for_klient)

  @account.update(false, current_user.kb_username, params[:reason], params[:comment], cached_options_for_klient)

  redirect_to (@account.), notice: 'Account successfully updated'
rescue StandardError => e
  flash[:error] = if e.is_a?(KillBillClient::API::NotFound)
                    "Parent account id not found: #{@account.parent_account_id}"
                  else
                    "Error while linking parent account: #{as_string(e)}"
                  end
  redirect_to (@account.)
end

#newObject



181
182
183
# File 'app/controllers/kaui/accounts_controller.rb', line 181

def new
  @account = Kaui::.new
end

#next_invoice_dateObject

Fetched asynchronously, as it takes time. This also helps with enforcing permissions.



282
283
284
285
286
287
# File 'app/controllers/kaui/accounts_controller.rb', line 282

def next_invoice_date
  json_response do
    next_invoice = Kaui::Invoice.trigger_invoice_dry_run(params.require(:account_id), nil, true, [], current_user.kb_username, params[:reason], params[:comment], options_for_klient)
    next_invoice ? next_invoice.target_date.to_json : nil
  end
end

#paginationObject



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'app/controllers/kaui/accounts_controller.rb', line 30

def pagination
  cached_options_for_klient = options_for_klient
  searcher = lambda do |search_key, offset, limit|
    search_key = remapping_addvanced_search_fields(search_key, Kaui::::ADVANCED_SEARCH_NAME_CHANGES)
    Kaui::.list_or_search(search_key, offset, limit, cached_options_for_klient)
  end

  data_extractor = lambda do |, column|
    [
      .,
      .,
      .external_key,
      .
    ][column]
  end

  formatter = lambda do ||
    Kaui..call(, view_context)[1]
  end

  paginate searcher, data_extractor, formatter, default_columns(Kaui..call[2], Kaui::::DEFAULT_VISIBLE_COLUMNS)
end

#pay_all_invoicesObject



298
299
300
301
302
303
304
# File 'app/controllers/kaui/accounts_controller.rb', line 298

def pay_all_invoices
  payment = Kaui::InvoicePayment.new(account_id: params.require(:account_id))

  payment.bulk_create(params[:is_external_payment] == 'true', nil, nil, current_user.kb_username, params[:reason], params[:comment], options_for_klient)

  redirect_to (payment.), notice: 'Successfully triggered a payment for all unpaid invoices'
end

#set_default_payment_methodObject



289
290
291
292
293
294
295
296
# File 'app/controllers/kaui/accounts_controller.rb', line 289

def set_default_payment_method
   = params.require(:account_id)
  payment_method_id = params.require(:payment_method_id)

  Kaui::PaymentMethod.set_default(payment_method_id, , current_user.kb_username, params[:reason], params[:comment], options_for_klient)

  redirect_to (), notice: "Successfully set #{payment_method_id} as default"
end

#set_email_notifications_configurationObject



360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
# File 'app/controllers/kaui/accounts_controller.rb', line 360

def set_email_notifications_configuration
  configuration = params.require(:configuration)
   = configuration[:account_id]
  event_types = configuration[:event_types]
  cached_options_for_klient = options_for_klient

  is_success, message = Dependencies::Kenui::EmailNotification.email_notification_plugin_available?(cached_options_for_klient)

  if is_success
    is_success, message = Dependencies::Kenui::EmailNotification.(,
                                                                                               event_types,
                                                                                               current_user.kb_username,
                                                                                               params[:reason],
                                                                                               params[:comment],
                                                                                               cached_options_for_klient)
  end
  if is_success
    flash[:notice] = message
  else
    flash[:error] = message
  end
  redirect_to ()
end

#showObject

rubocop:disable Style/MultilineBlockChain



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
141
142
143
144
145
146
147
148
149
150
151
152
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
# File 'app/controllers/kaui/accounts_controller.rb', line 104

def show
  # Go to the database once
  cached_options_for_klient = options_for_klient

  # Re-fetch the account with balance and CBA
  @account = Kaui::.find_by_id_or_key(params.require(:account_id), true, true, cached_options_for_klient)

  fetch_children = promise { @account.children(false, false, 'NONE', cached_options_for_klient) }
  fetch_parent = @account..nil? ? nil : promise { Kaui::.find_by_id(@account., false, false, cached_options_for_klient) }
  fetch_overdue_state = promise { @account.overdue(cached_options_for_klient) }
   = promise { @account.tags(false, 'NONE', cached_options_for_klient).sort }
   = promise { @account.custom_fields('NONE', cached_options_for_klient).sort { |cf_a, cf_b| cf_a.name.downcase <=> cf_b.name.downcase } }
   = promise { Kaui::AccountEmail.(@account., 'NONE', cached_options_for_klient) }
  fetch_payments = promise { @account.payments(cached_options_for_klient).map! { |payment| Kaui::Payment.build_from_raw_payment(payment) } }
  fetch_payment_methods = promise { Kaui::PaymentMethod.(@account., false, cached_options_for_klient) }
  is_email_notifications_plugin_available = Dependencies::Kenui::EmailNotification.email_notification_plugin_available?(cached_options_for_klient).first
  fetch_email_notification_configuration = if is_email_notifications_plugin_available
                                             promise do
                                               Dependencies::Kenui::EmailNotification.(params.require(:account_id), cached_options_for_klient)
                                             end.then do |configuration|
                                               if configuration.first.is_a?(FalseClass)
                                                 Rails.logger.warn(configuration[1])
                                                 configuration = []
                                               end
                                               configuration
                                             end
                                           else
                                             nil
                                           end

  fetch_payment_methods_with_details = fetch_payment_methods.then do |pms|
    ops = pms.map do |pm|
      promise do
        Kaui::PaymentMethod.find_by_id(pm.payment_method_id, false, true, [], 'NONE', cached_options_for_klient)
      rescue StandardError => e
        # Maybe the plugin is not registered or the plugin threw an exception
        Rails.logger.warn(e)
        nil
      end
    end
    ops
  end
  fetch_available_tags = promise { Kaui::TagDefinition.(cached_options_for_klient) }
  fetch_bundles = promise { @account.bundles(cached_options_for_klient) }

  @overdue_state = wait(fetch_overdue_state)
  @tags = wait()
  @custom_fields = wait()
  @account_emails = wait()
  wait(fetch_payment_methods)
  @payment_methods = wait(fetch_payment_methods_with_details).filter_map { |pm_f| wait(pm_f) }
  @available_tags = wait(fetch_available_tags)
  @children = wait(fetch_children)
  @account_parent = @account..nil? ? nil : wait(fetch_parent)
  @email_notification_configuration = is_email_notifications_plugin_available ? wait(fetch_email_notification_configuration) : []
  @bundles = begin
    wait(fetch_bundles)
  rescue KillBillClient::API::ResponseError => e
    # e.g. a subscription references a plan that no longer exists in the currently loaded catalog.
    # Don't fail the whole account page for this, just warn and show it without bundle-derived data.
    Rails.logger.warn("Unable to fetch bundles for account #{@account.account_id}: #{as_string(e)}")
    flash.now[:warning] = "Unable to load some subscription details: #{as_string(e)}"
    []
  end

  @last_transaction_by_payment_method_id = {}
  wait(fetch_payments).each do |payment|
    transaction = payment.transactions.last
    transaction_date = Date.parse(transaction.effective_date)

    last_seen_transaction_date = @last_transaction_by_payment_method_id[payment.payment_method_id]
    @last_transaction_by_payment_method_id[payment.payment_method_id] = transaction if last_seen_transaction_date.nil? || Date.parse(last_seen_transaction_date.effective_date) < transaction_date
  end

  params.permit!
end

#trigger_invoiceObject



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

def trigger_invoice
   = params.require(:account_id)
  target_date = params[:target_date].presence
  dry_run = params[:dry_run].nil? ? false : params[:dry_run] == '1'

  invoice = nil
  begin
    invoice = if dry_run
                Kaui::Invoice.trigger_invoice_dry_run(, target_date, false, [], current_user.kb_username, params[:reason], params[:comment], options_for_klient)
              else
                Kaui::Invoice.trigger_invoice(, target_date, current_user.kb_username, params[:reason], params[:comment], options_for_klient)
              end
  rescue KillBillClient::API::NotFound
    # Null invoice
  end

  if invoice.nil?
    redirect_to (), notice: "Nothing to generate for target date #{target_date.nil? ? 'today' : target_date}"
  elsif dry_run
    @invoice = Kaui::Invoice.build_from_raw_invoice(invoice)
    @invoice_tags = []
    @available_invoice_tags = []
    @payments = []
    @payment_methods = nil
    @account = Kaui::.find_by_id(, false, false, options_for_klient)
    render template: 'kaui/invoices/show'
  else
    # Redirect to fetch payments, etc.
    redirect_to invoice_path(invoice.invoice_id, account_id:), notice: "Generated invoice #{invoice.invoice_number} for target date #{invoice.target_date}"
  end
end


343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
# File 'app/controllers/kaui/accounts_controller.rb', line 343

def unlink_to_parent
   = params.require(:account_id)
  cached_options_for_klient = options_for_klient

  # search for the account and remove the parent account id
  # check if parent id is valid
   = Kaui::.find_by_id(, false, false, cached_options_for_klient)
  .is_payment_delegated_to_parent = false
  . = nil
  .update(true, current_user.kb_username, params[:reason], params[:comment], cached_options_for_klient)

  redirect_to (@account.), notice: 'Account successfully updated'
rescue StandardError => e
  flash[:error] = "Error while un-linking parent account: #{as_string(e)}"
  redirect_to (@account.)
end

#updateObject



212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'app/controllers/kaui/accounts_controller.rb', line 212

def update
  @account = Kaui::.new(params.require(:account).permit!.to_h.compact_blank)
  @account. = params.require(:account_id)

  # Transform "1" into boolean
  @account.is_migrated = @account.is_migrated == '1'

  @account.update(true, current_user.kb_username, params[:reason], params[:comment], options_for_klient)

  redirect_to (@account.), notice: 'Account successfully updated'
rescue StandardError => e
  flash.now[:error] = "Error while updating account: #{as_string(e)}"
  render action: :edit
end

#validate_external_keyObject



306
307
308
309
310
311
312
313
314
315
316
317
# File 'app/controllers/kaui/accounts_controller.rb', line 306

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

    begin
       = Kaui::.find_by_external_key(external_key, false, false, options_for_klient)
    rescue KillBillClient::API::NotFound
       = nil
    end
    { is_found: !.nil? }
  end
end