<commit_before>class ChargebackRateController < ApplicationController
  before_action :check_privileges
  before_action :get_session_data
  after_action :cleanup_action
  after_action :set_session_data

  include Mixins::GenericButtonMixin
  include Mixins::GenericListMixin
  include Mixins::GenericSessionMixin
  include Mixins::GenericFormMixin
  include Mixins::GenericShowMixin
  include Mixins::BreadcrumbsMixin

  BUTTON_ALLOWED_ACTIONS = {
    'chargeback_rates_copy'   => :cb_rate_edit,
    'chargeback_rates_delete' => :cb_rates_delete,
    'chargeback_rates_edit'   => :cb_rate_edit,
    'chargeback_rates_new'    => :cb_rate_edit
  }.freeze

  def button
    @edit = session[:edit]    # Restore @edit for adv search box
    @refresh_div = "main_div" # Default div for button.rjs to refresh
    action = params[:pressed]

    evaluate_button(action, BUTTON_ALLOWED_ACTIONS)

    return if performed?

    if action.ends_with?("_copy", "_edit", "_new") && @flash_array.nil?
      javascript_redirect(:action => @refresh_partial,  :id => @redirect_id, :pressed => action)
    elsif action.ends_with?("_delete")
      javascript_redirect(:action => 'show_list')
    elsif @refresh_div == "main_div" && @lastaction == "show_list"
      replace_gtl_main_div
    else
      super
    end
  end

  def show_list
    super
    # only need these gtl type buttons on the screen
    @gtl_buttons = %w[view_list view_tree]
    cb_rates_build_tree if @gtl_type == 'tree'
  end

  #TODO clean this up after the new trees are in and do the redirect in the TreeBuilder directly instead
  def tree_select
    id = parse_nodetype_and_id(params[:id]).last
    render :update do |page|
      page << javascript_prologue
      page.redirect_to :action => 'show', :id => id
    end
  end

  def cb_rate_edit
    @_params[:id] ||= find_checked_items[0]
    rate = new_rate_edit? ? ChargebackRate.new : ChargebackRate.find(params[:id])
    if params[:pressed] == 'chargeback_rates_edit' && rate.default?
      add_flash(_("Default Chargeback Rate \"%{name}\" cannot be edited.") % {:name => rate.description}, :error)
      return
    end
    @redirect_id = params[:id] if params[:id]
    @refresh_partial = "edit"
  end

  def edit
    assert_privileges(params[:pressed]) if params[:pressed]
    case params[:button]
    when "cancel"
      if params[:id]
        add_flash(_("Edit of Chargeback Rate \"%{name}\" was cancelled by the user") % {:name => session[:edit][:new][:description]})
      else
        add_flash(_("Add of new Chargeback Rate was cancelled by the user"))
      end
      @edit = session[:edit] = nil # clean out the saved info
      session[:changed] = false
      javascript_redirect(:action => @lastaction, :id => params[:id], :flash_msg  => @flash_array[0][:message])
    when "save", "add"
      id = params[:button] == "save" ? params[:id] : "new"
      return unless load_edit("cbrate_edit__#{id}")

      @rate = params[:button] == "add" ? ChargebackRate.new : ChargebackRate.find(params[:id])
      if @edit[:new][:description].nil? || @edit[:new][:description] == ""
        render_flash(_("Description is required"), :error)
        return
      end
      @rate.description = @edit[:new][:description]
      @rate.rate_type   = @edit[:new][:rate_type] if @edit[:new][:rate_type]

      cb_rate_set_record_vars
      # Detect errors saving tiers
      tiers_valid = @rate_tiers.all? { |tiers| tiers.all?(&:valid?) }

      @rate.chargeback_rate_details.replace(@rate_details)
      @rate.chargeback_rate_details.each_with_index do |_detail, i|
        @rate_details[i].save_tiers(@rate_tiers[i])
      end

      tiers_valid &&= @rate_details.all? { |rate_detail| rate_detail.errors.messages.blank? }

      if tiers_valid && @rate.save
        if params[:button] == "add"
          AuditEvent.success(build_created_audit(@rate, @edit))
          add_flash(_("Chargeback Rate \"%{name}\" was added") % {:name => @rate.description})
        else
          AuditEvent.success(build_saved_audit(@rate, @edit))
          add_flash(_("Chargeback Rate \"%{name}\" was saved") % {:name => @rate.description})
        end
        @edit = session[:edit] = nil # clean out the saved info
        session[:changed] = @changed = false
        javascript_redirect(:action => @lastaction, :id => params[:id], :flash_msg  => @flash_array[0][:message])
      else
        @rate.errors.each do |field, msg|
          add_flash("#{field.to_s.capitalize} #{msg}", :error)
        end
        @rate_details.each do |detail|
          display_detail_errors(detail, detail.errors)
        end
        @rate_tiers.each_with_index do |tiers, detail_index|
          tiers.each do |tier|
            display_detail_errors(@rate_details[detail_index], tier.errors)
          end
        end
        @changed = session[:changed] = (@edit[:new] != @edit[:current])
        javascript_flash
      end
    when "reset", nil # displaying edit from for actions: new, edit or copy
      @in_a_form = true
      session[:changed] = params[:pressed] == 'chargeback_rates_copy'
      @rate = new_rate_edit? ? ChargebackRate.new : ChargebackRate.find(params[:id])
      cb_rate_set_form_vars
      if params[:button] == "reset"
        add_flash(_("All changes have been reset"), :warning)
        render :update do |page|
          page << javascript_prologue
          page.replace("form_div", :partial => "edit")
          page << "miqSparkle(false);"
        end
      end
    end
  end

  # AJAX driven routine to check for changes in ANY field on the form
  def cb_rate_form_field_changed
    return unless load_edit("cbrate_edit__#{params[:id]}")
    cb_rate_get_form_vars
    render :update do |page|
      page << javascript_prologue
      changed = (@edit[:new] != @edit[:current])
      # Update the new column with the code of the currency selected by the user
      page.replace('chargeback_rate_currency', :partial => 'cb_rate_currency')
      page << javascript_for_miq_button_visibility(changed)
    end
  end

  # Delete all selected or single displayed action(s)
  def cb_rates_delete
    assert_privileges("chargeback_rates_delete")
    rates = []
    if !params[:id] # showing a list
      rates = find_checked_items
      if rates.empty?
        add_flash(_("No Chargeback Rates were selected for deletion"), :error)
      end
    else # showing 1 rate, delete it
      cb_rate = ChargebackRate.find_by(:id => params[:id])
      if cb_rate.nil?
        add_flash(_("Chargeback Rate no longer exists"), :error)
      else<commit_msg>Simplified javascript_redirect calls<commit_after>class ChargebackRateController < ApplicationController
  before_action :check_privileges
  before_action :get_session_data
  after_action :cleanup_action
  after_action :set_session_data

  include Mixins::GenericButtonMixin
  include Mixins::GenericListMixin
  include Mixins::GenericSessionMixin
  include Mixins::GenericFormMixin
  include Mixins::GenericShowMixin
  include Mixins::BreadcrumbsMixin

  BUTTON_ALLOWED_ACTIONS = {
    'chargeback_rates_copy'   => :cb_rate_edit,
    'chargeback_rates_delete' => :cb_rates_delete,
    'chargeback_rates_edit'   => :cb_rate_edit,
    'chargeback_rates_new'    => :cb_rate_edit
  }.freeze

  def button
    @edit = session[:edit]    # Restore @edit for adv search box
    @refresh_div = "main_div" # Default div for button.rjs to refresh
    action = params[:pressed]

    evaluate_button(action, BUTTON_ALLOWED_ACTIONS)

    return if performed?

    if action.ends_with?("_copy", "_edit", "_new") && @flash_array.nil?
      javascript_redirect(:action => @refresh_partial,  :id => @redirect_id, :pressed => action)
    elsif action.ends_with?("_delete")
      javascript_redirect(:action => 'show_list')
    elsif @refresh_div == "main_div" && @lastaction == "show_list"
      replace_gtl_main_div
    else
      super
    end
  end

  def show_list
    super
    # only need these gtl type buttons on the screen
    @gtl_buttons = %w[view_list view_tree]
    cb_rates_build_tree if @gtl_type == 'tree'
  end

  #TODO clean this up after the new trees are in and do the redirect in the TreeBuilder directly instead
  def tree_select
    id = parse_nodetype_and_id(params[:id]).last
    render :update do |page|
      page << javascript_prologue
      page.redirect_to :action => 'show', :id => id
    end
  end

  def cb_rate_edit
    @_params[:id] ||= find_checked_items[0]
    rate = new_rate_edit? ? ChargebackRate.new : ChargebackRate.find(params[:id])
    if params[:pressed] == 'chargeback_rates_edit' && rate.default?
      add_flash(_("Default Chargeback Rate \"%{name}\" cannot be edited.") % {:name => rate.description}, :error)
      return
    end
    @redirect_id = params[:id] if params[:id]
    @refresh_partial = "edit"
  end

  def edit
    assert_privileges(params[:pressed]) if params[:pressed]
    case params[:button]
    when "cancel"
      if params[:id]
        flash_msg = _("Edit of Chargeback Rate \"%{name}\" was cancelled by the user") % {:name => session[:edit][:new][:description]}
      else
        flash_msg = _("Add of new Chargeback Rate was cancelled by the user")
      end
      @edit = session[:edit] = nil # clean out the saved info
      session[:changed] = false
      javascript_redirect(:action => @lastaction, :id => params[:id], :flash_msg  => flash_msg)
    when "save", "add"
      id = params[:button] == "save" ? params[:id] : "new"
      return unless load_edit("cbrate_edit__#{id}")

      @rate = params[:button] == "add" ? ChargebackRate.new : ChargebackRate.find(params[:id])
      if @edit[:new][:description].nil? || @edit[:new][:description] == ""
        render_flash(_("Description is required"), :error)
        return
      end
      @rate.description = @edit[:new][:description]
      @rate.rate_type   = @edit[:new][:rate_type] if @edit[:new][:rate_type]

      cb_rate_set_record_vars
      # Detect errors saving tiers
      tiers_valid = @rate_tiers.all? { |tiers| tiers.all?(&:valid?) }

      @rate.chargeback_rate_details.replace(@rate_details)
      @rate.chargeback_rate_details.each_with_index do |_detail, i|
        @rate_details[i].save_tiers(@rate_tiers[i])
      end

      tiers_valid &&= @rate_details.all? { |rate_detail| rate_detail.errors.messages.blank? }

      if tiers_valid && @rate.save
        if params[:button] == "add"
          AuditEvent.success(build_created_audit(@rate, @edit))
          flash_msg = _("Chargeback Rate \"%{name}\" was added") % {:name => @rate.description}
        else
          AuditEvent.success(build_saved_audit(@rate, @edit))
          flash_msg = _("Chargeback Rate \"%{name}\" was saved") % {:name => @rate.description}
        end
        @edit = session[:edit] = nil # clean out the saved info
        session[:changed] = @changed = false
        javascript_redirect(:action => @lastaction, :id => params[:id], :flash_msg  => flash_msg)
      else
        @rate.errors.each do |field, msg|
          add_flash("#{field.to_s.capitalize} #{msg}", :error)
        end
        @rate_details.each do |detail|
          display_detail_errors(detail, detail.errors)
        end
        @rate_tiers.each_with_index do |tiers, detail_index|
          tiers.each do |tier|
            display_detail_errors(@rate_details[detail_index], tier.errors)
          end
        end
        @changed = session[:changed] = (@edit[:new] != @edit[:current])
        javascript_flash
      end
    when "reset", nil # displaying edit from for actions: new, edit or copy
      @in_a_form = true
      session[:changed] = params[:pressed] == 'chargeback_rates_copy'
      @rate = new_rate_edit? ? ChargebackRate.new : ChargebackRate.find(params[:id])
      cb_rate_set_form_vars
      javascript_redirect(:action        => 'edit',
                          :id            => params[:id],
                          :flash_msg     => _("All changes have been reset"),
                          :flash_warning => true) if params[:button] == "reset"

    end
  end

  # AJAX driven routine to check for changes in ANY field on the form
  def cb_rate_form_field_changed
    return unless load_edit("cbrate_edit__#{params[:id]}")
    cb_rate_get_form_vars
    render :update do |page|
      page << javascript_prologue
      changed = (@edit[:new] != @edit[:current])
      # Update the new column with the code of the currency selected by the user
      page.replace('chargeback_rate_currency', :partial => 'cb_rate_currency')
      page << javascript_for_miq_button_visibility(changed)
    end
  end

  # Delete all selected or single displayed action(s)
  def cb_rates_delete
    assert_privileges("chargeback_rates_delete")
    rates = []
    if !params[:id] # showing a list
      rates = find_checked_items
      if rates.empty?
        add_flash(_("No Chargeback Rates were selected for deletion"), :error)
      end
    else # showing 1 rate, delete it
      cb_rate = ChargebackRate.find_by(:id => params[:id])
      if cb_rate.nil?
        add_flash(_("Chargeback Rate no longer exists"), :error)
      else
{'fraction_non_alphanumeric': 0.11946360153256705, 'fraction_numerical': 0.0004597701149425287, 'mean_word_length': 3.263639333551127, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 52, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4772895', 'n_tokens_mistral': 4155, 'n_tokens_neox': 4013, 'n_words': 978}