<commit_before>class UsersController < OrganizationAwareController

  #-----------------------------------------------------------------------------
  # Protect controller methods using the cancan ability
  #-----------------------------------------------------------------------------
  authorize_resource :user, except: :popup

  #-----------------------------------------------------------------------------
  add_breadcrumb "Home",  :root_path
  add_breadcrumb "Users", :users_path

  #-----------------------------------------------------------------------------
  skip_before_action :get_organization_selections,      :only => [:authorizations]
  before_action :set_viewable_organizations,      :only => [:authorizations]


  before_action :set_user, :only => [:show, :edit, :settings, :update, :destroy, :change_password, :update_password, :profile_photo, :reset_password, :authorizations]
  before_action :check_for_cancel, :only => [:create, :update, :update_password]



  #-----------------------------------------------------------------------------
  INDEX_KEY_LIST_VAR    = "user_key_list_cache_var"
  SESSION_VIEW_TYPE_VAR = 'users_subnav_view_type'

  FILTERS_IGNORED = Rails.application.config.try(:user_organization_filters_ignored).present?

  #-----------------------------------------------------------------------------
  # GET /users
  # GET /users.json
  #-----------------------------------------------------------------------------
  def index

    @organization_id = params[:organization_id].to_i
    @search_text = params[:search_text]
    if params[:role] && params[:role].include?(",")
      @role = params[:role].split(",")
    else
      @role = params[:role]
    end
    @id_filter_list = params[:ids]

    # Start to set up the query
    conditions  = []
    values      = []

    if @organization_id.to_i > 0
      conditions << 'users_organizations.organization_id = ?'
      values << @organization_id
    else
      conditions << 'users_organizations.organization_id IN (?)'
      values << @organization_list
    end


    unless @search_text.blank?
      # get the list of searchable fields from the asset class
      searchable_fields = User.new.searchable_fields
      # create an OR query for each field
      query_str = []
      first = true
      # parameterize the search based on the selected search parameter
      search_value = get_search_value(@search_text, @search_param)
      # Construct the query based on the searchable fields for the model
      searchable_fields.each do |field|
        if first
          first = false
          query_str << '('
        else
          query_str << ' OR '
        end

        query_str << "UPPER(users.#{field})"
        query_str << ' LIKE ? '
        # add the value in for this sub clause
        values << search_value.upcase
      end
      query_str << ')' unless searchable_fields.empty?

      conditions << [query_str.join]
    end

    unless @id_filter_list.blank?
      conditions << 'object_key in (?)'
      values << @id_filter_list
    end

    if params[:show_active_only].nil?
      @show_active_only = 'active'
    else
      @show_active_only = params[:show_active_only]
    end

    if @show_active_only == 'active'
      conditions << 'users.active = ?'
      values << true
    elsif @show_active_only == 'inactive'
      conditions << 'users.active = ?'
      values << false
    end

    # Get the Users but check to see if a role was selected
    @users = User.unscoped.distinct.joins(:organization).order('organizations.organization_type_id', 'organizations.short_name', :last_name).joins(:organizations).includes(:organization,:roles).where(conditions.join(' AND '), *values)
    if !@role.blank?
      if @role.kind_of?(Array)
        all_users = @users
        @users = @users.with_role(@role[0])
        @role[1..-1].each do |r|
          @users = @users.or(all_users.with_role(r))
        end
      else
        @users = @users.with_role(@role)
      end
    end

    if params[:sort] && params[:order]
      case params[:sort]
      when 'organization'
        @users = @users.reorder("organizations.short_name #{params[:order]}")
      # figure out sorting by role + privilege some other way
      # when 'role_name'
      #   @users = @users.joins(:roles).merge(Role.unscoped.order(name: params[:order]))
      # when 'privilege_names'
      #   @users = @users.joins(:roles).merge(Role.order(privilege: params[:order]))
      else
        @users = @users.reorder(params[:sort] => params[:order])
      end
    end

    # Set the breadcrumbs
    if @organization_list.count == 1
      org = Organization.find(@organization_list.first)
      add_breadcrumb org.short_name, users_path(:organization_id => org.id)
    end
    if @role.present?
      role_string = @role.kind_of?(Array) ? Role.find_by(name: @role).label.parameterize.underscore : @role
      add_breadcrumb role_string.titleize, users_path(:role => role_string)
    end

    # remember the view type
    @view_type = get_view_type(SESSION_VIEW_TYPE_VAR)

    respond_to do |format|
      format.html # index.html.erb
      format.json {
        render :json => {
          :total => @users.count,
          :rows => @users.limit(params[:limit]).offset(params[:offset]).collect{ |u|
            u.as_json.merge!({
                 organization_short_name: u.organization.short_name,
                 organization_name: u.organization.name,
                 role_name: !@role.blank? && (@role.kind_of?(Array) ? !Role.find_by(name:@role.first).privilege : !Role.find_by(name: @role).privilege) ? (@role.kind_of?(Array) ? u.roles.roles.where(name: @role).last.label : u.roles.roles.find_by(name: @role).label) : u.roles.roles.last.label,
                 privilege_names: u.roles.privileges.collect{|x| x.label}.join(', '),
                 all_orgs: u.organizations.map{ |o| o.to_s }.join(', ')
            })
          }
        }
      }

    end
  end

  #-----------------------------------------------------------------------------
  # Show the list of current sessions. Only available for admin users
  # TODO: MOST of this will be moved to a shareable module
  #-----------------------------------------------------------------------------
  def table
    count = User.all.count 
    page = (table_params[:page] || 0).to_i
    page_size = (table_params[:page_size] || count).to_i
    search = (table_params[:search])<commit_msg>take out unneeded json resopnse<commit_after>class UsersController < OrganizationAwareController

  #-----------------------------------------------------------------------------
  # Protect controller methods using the cancan ability
  #-----------------------------------------------------------------------------
  authorize_resource :user, except: :popup

  #-----------------------------------------------------------------------------
  add_breadcrumb "Home",  :root_path
  add_breadcrumb "Users", :users_path

  #-----------------------------------------------------------------------------
  skip_before_action :get_organization_selections,      :only => [:authorizations]
  before_action :set_viewable_organizations,      :only => [:authorizations]


  before_action :set_user, :only => [:show, :edit, :settings, :update, :destroy, :change_password, :update_password, :profile_photo, :reset_password, :authorizations]
  before_action :check_for_cancel, :only => [:create, :update, :update_password]



  #-----------------------------------------------------------------------------
  INDEX_KEY_LIST_VAR    = "user_key_list_cache_var"
  SESSION_VIEW_TYPE_VAR = 'users_subnav_view_type'

  FILTERS_IGNORED = Rails.application.config.try(:user_organization_filters_ignored).present?

  #-----------------------------------------------------------------------------
  # GET /users
  # GET /users.json
  #-----------------------------------------------------------------------------
  def index

    @organization_id = params[:organization_id].to_i
    @search_text = params[:search_text]
    if params[:role] && params[:role].include?(",")
      @role = params[:role].split(",")
    else
      @role = params[:role]
    end
    @id_filter_list = params[:ids]

    # Start to set up the query
    conditions  = []
    values      = []

    if @organization_id.to_i > 0
      conditions << 'users_organizations.organization_id = ?'
      values << @organization_id
    else
      conditions << 'users_organizations.organization_id IN (?)'
      values << @organization_list
    end


    unless @search_text.blank?
      # get the list of searchable fields from the asset class
      searchable_fields = User.new.searchable_fields
      # create an OR query for each field
      query_str = []
      first = true
      # parameterize the search based on the selected search parameter
      search_value = get_search_value(@search_text, @search_param)
      # Construct the query based on the searchable fields for the model
      searchable_fields.each do |field|
        if first
          first = false
          query_str << '('
        else
          query_str << ' OR '
        end

        query_str << "UPPER(users.#{field})"
        query_str << ' LIKE ? '
        # add the value in for this sub clause
        values << search_value.upcase
      end
      query_str << ')' unless searchable_fields.empty?

      conditions << [query_str.join]
    end

    unless @id_filter_list.blank?
      conditions << 'object_key in (?)'
      values << @id_filter_list
    end

    if params[:show_active_only].nil?
      @show_active_only = 'active'
    else
      @show_active_only = params[:show_active_only]
    end

    if @show_active_only == 'active'
      conditions << 'users.active = ?'
      values << true
    elsif @show_active_only == 'inactive'
      conditions << 'users.active = ?'
      values << false
    end

    # Get the Users but check to see if a role was selected
    @users = User.unscoped.distinct.joins(:organization).order('organizations.organization_type_id', 'organizations.short_name', :last_name).joins(:organizations).includes(:organization,:roles).where(conditions.join(' AND '), *values)
    if !@role.blank?
      if @role.kind_of?(Array)
        all_users = @users
        @users = @users.with_role(@role[0])
        @role[1..-1].each do |r|
          @users = @users.or(all_users.with_role(r))
        end
      else
        @users = @users.with_role(@role)
      end
    end

    if params[:sort] && params[:order]
      case params[:sort]
      when 'organization'
        @users = @users.reorder("organizations.short_name #{params[:order]}")
      # figure out sorting by role + privilege some other way
      # when 'role_name'
      #   @users = @users.joins(:roles).merge(Role.unscoped.order(name: params[:order]))
      # when 'privilege_names'
      #   @users = @users.joins(:roles).merge(Role.order(privilege: params[:order]))
      else
        @users = @users.reorder(params[:sort] => params[:order])
      end
    end

    # Set the breadcrumbs
    if @organization_list.count == 1
      org = Organization.find(@organization_list.first)
      add_breadcrumb org.short_name, users_path(:organization_id => org.id)
    end
    if @role.present?
      role_string = @role.kind_of?(Array) ? Role.find_by(name: @role).label.parameterize.underscore : @role
      add_breadcrumb role_string.titleize, users_path(:role => role_string)
    end

    # remember the view type
    @view_type = get_view_type(SESSION_VIEW_TYPE_VAR)

    respond_to do |format|
      format.html # index.html.erb
      # format.json {
      #   render :json => {
      #     :total => @users.count,
      #     :rows => @users.limit(params[:limit]).offset(params[:offset]).collect{ |u|
      #       u.as_json.merge!({
      #            organization_short_name: u.organization.short_name,
      #            organization_name: u.organization.name,
      #            role_name: !@role.blank? && (@role.kind_of?(Array) ? !Role.find_by(name:@role.first).privilege : !Role.find_by(name: @role).privilege) ? (@role.kind_of?(Array) ? u.roles.roles.where(name: @role).last.label : u.roles.roles.find_by(name: @role).label) : u.roles.roles.last.label,
      #            privilege_names: u.roles.privileges.collect{|x| x.label}.join(', '),
      #            all_orgs: u.organizations.map{ |o| o.to_s }.join(', ')
      #       })
      #     }
      #   }
      # }

    end
  end

  #-----------------------------------------------------------------------------
  # Show the list of current sessions. Only available for admin users
  # TODO: MOST of this will be moved to a shareable module
  #-----------------------------------------------------------------------------
  def table
    count = User.all.count 
    page = (table_params[:page] || 0).to_i
    page_size = (table_params[:page_size] || count).to_i
    search = (table_params[:search])
{'fraction_non_alphanumeric': 0.21746548782379402, 'fraction_numerical': 0.0009306654257794323, 'mean_word_length': 1.952828028394779, 'pattern_counts': {'":': 0, '<': 73, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2996657', 'n_tokens_mistral': 3742, 'n_tokens_neox': 3644, 'n_words': 771}