<commit_before># Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
module Ticket::Search

=begin

search tickets preferences

  result = Ticket.search_preferences(user_model)

returns if user has permissions to search

  result = {
    prio: 3000,
    direct_search_index: false
  }

returns if user has no permissions to search

  result = false

=end

  def search_preferences(_current_user)
    {
      prio: 3000,
      direct_search_index: false,
    }
  end

=begin

search tickets via search index

  result = Ticket.search(
    current_user: User.find(123),
    query:        'search something',
    limit:        15,
  )

returns

  result = [ticket_model1, ticket_model2]

search tickets via search index

  result = Ticket.search(
    current_user: User.find(123),
    query:        'search something',
    limit:        15,
    full:         false,
  )

returns

  result = [1,3,5,6,7]

search tickets via database

  result = Ticket.search(
    current_user: User.find(123),
    query: 'some query', # query or condition is required
    condition: {
      'tickets.owner_id' => {
        operator: 'is',
        value: user.id,
      },
      'tickets.state_id' => {
        operator: 'is',
        value: Ticket::State.where(
          state_type_id: Ticket::StateType.where(
            name: [
              'pending reminder',
              'pending action',
            ],
          ).map(&:id),
        },
      ),
    },
    limit: 15,
    full: false,
  )

returns

  result = [1,3,5,6,7]

=end

  def search(params)

    # get params
    query        = params[:query]
    condition    = params[:condition]
    limit        = params[:limit] || 12
    current_user = params[:current_user]
    full         = false
    if params[:full] || !params.key?(:full)
      full = true
    end

    # try search index backend
    if !condition && SearchIndexBackend.enabled?
      query_extention = {}
      query_extention['bool'] = {}
      query_extention['bool']['must'] = []

      if current_user.permissions?('ticket.agent')
        groups = Group.joins(:users)
                      .where('groups_users.user_id = ?', current_user.id)
                      .where('groups.active = ?', true)
        group_condition = []
        groups.each { |group|
          group_condition.push group.id
        }
        access_condition = {
          'query_string' => { 'default_field' => 'group_id', 'query' => "\"#{group_condition.join('" OR "')}\"" }
        }
      else
        access_condition = if !current_user.organization || ( !current_user.organization.shared || current_user.organization.shared == false )
                             {
                               'query_string' => { 'default_field' => 'customer_id', 'query' => current_user.id }
                             }
                           #  customer_id: XXX
                           #          conditions = [ 'customer_id = ?', current_user.id ]
                           else
                             {
                               'query_string' => { 'query' => "customer_id:#{current_user.id} OR organization_id:#{current_user.organization.id}" }
                             }
                             # customer_id: XXX OR organization_id: XXX
                             #          conditions = [ '( customer_id = ? OR organization_id = ? )', current_user.id, current_user.organization.id ]
                           end
      end

      query_extention['bool']['must'].push access_condition

      items = SearchIndexBackend.search(query, limit, 'Ticket', query_extention)
      if !full
        ids = []
        items.each { |item|
          ids.push item[:id]
        }
        return ids
      end
      tickets = []
      items.each { |item|
        ticket = Ticket.lookup(id: item[:id])
        next if !ticket
        tickets.push ticket
      }
      return tickets
    end

    # fallback do sql query
    access_condition = Ticket.access_condition(current_user)

    # do query
    # - stip out * we already search for *query* -
    if query
      query.delete! '*'
      tickets_all = Ticket.select('DISTINCT(tickets.id), tickets.created_at')
                          .where(access_condition)
                          .where('(tickets.title LIKE ? OR tickets.number LIKE ? OR ticket_articles.body LIKE ? OR ticket_articles.from LIKE ? OR ticket_articles.to LIKE ? OR ticket_articles.subject LIKE ?)', "%#{query}%", "%#{query}%", "%#{query}%", "%#{query}%", "%#{query}%", "%#{query}%" )
                          .joins(:articles)
                          .order('tickets.created_at DESC')
                          .limit(limit)
    else
      query_condition, bind_condition, tables = selector2sql(condition)
      tickets_all = Ticket.select('DISTINCT(tickets.id), tickets.created_at')
                          .from("tickets#{tables}")<commit_msg>Improved join.<commit_after># Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
module Ticket::Search

=begin

search tickets preferences

  result = Ticket.search_preferences(user_model)

returns if user has permissions to search

  result = {
    prio: 3000,
    direct_search_index: false
  }

returns if user has no permissions to search

  result = false

=end

  def search_preferences(_current_user)
    {
      prio: 3000,
      direct_search_index: false,
    }
  end

=begin

search tickets via search index

  result = Ticket.search(
    current_user: User.find(123),
    query:        'search something',
    limit:        15,
  )

returns

  result = [ticket_model1, ticket_model2]

search tickets via search index

  result = Ticket.search(
    current_user: User.find(123),
    query:        'search something',
    limit:        15,
    full:         false,
  )

returns

  result = [1,3,5,6,7]

search tickets via database

  result = Ticket.search(
    current_user: User.find(123),
    query: 'some query', # query or condition is required
    condition: {
      'tickets.owner_id' => {
        operator: 'is',
        value: user.id,
      },
      'tickets.state_id' => {
        operator: 'is',
        value: Ticket::State.where(
          state_type_id: Ticket::StateType.where(
            name: [
              'pending reminder',
              'pending action',
            ],
          ).map(&:id),
        },
      ),
    },
    limit: 15,
    full: false,
  )

returns

  result = [1,3,5,6,7]

=end

  def search(params)

    # get params
    query        = params[:query]
    condition    = params[:condition]
    limit        = params[:limit] || 12
    current_user = params[:current_user]
    full         = false
    if params[:full] || !params.key?(:full)
      full = true
    end

    # try search index backend
    if !condition && SearchIndexBackend.enabled?
      query_extention = {}
      query_extention['bool'] = {}
      query_extention['bool']['must'] = []

      if current_user.permissions?('ticket.agent')
        groups = Group.joins(:users)
                      .where('groups_users.user_id = ?', current_user.id)
                      .where('groups.active = ?', true)
        group_condition = []
        groups.each { |group|
          group_condition.push group.id
        }
        access_condition = {
          'query_string' => { 'default_field' => 'group_id', 'query' => "\"#{group_condition.join('" OR "')}\"" }
        }
      else
        access_condition = if !current_user.organization || ( !current_user.organization.shared || current_user.organization.shared == false )
                             {
                               'query_string' => { 'default_field' => 'customer_id', 'query' => current_user.id }
                             }
                           #  customer_id: XXX
                           #          conditions = [ 'customer_id = ?', current_user.id ]
                           else
                             {
                               'query_string' => { 'query' => "customer_id:#{current_user.id} OR organization_id:#{current_user.organization.id}" }
                             }
                             # customer_id: XXX OR organization_id: XXX
                             #          conditions = [ '( customer_id = ? OR organization_id = ? )', current_user.id, current_user.organization.id ]
                           end
      end

      query_extention['bool']['must'].push access_condition

      items = SearchIndexBackend.search(query, limit, 'Ticket', query_extention)
      if !full
        ids = []
        items.each { |item|
          ids.push item[:id]
        }
        return ids
      end
      tickets = []
      items.each { |item|
        ticket = Ticket.lookup(id: item[:id])
        next if !ticket
        tickets.push ticket
      }
      return tickets
    end

    # fallback do sql query
    access_condition = Ticket.access_condition(current_user)

    # do query
    # - stip out * we already search for *query* -
    if query
      query.delete! '*'
      tickets_all = Ticket.select('DISTINCT(tickets.id), tickets.created_at')
                          .where(access_condition)
                          .where('(tickets.title LIKE ? OR tickets.number LIKE ? OR ticket_articles.body LIKE ? OR ticket_articles.from LIKE ? OR ticket_articles.to LIKE ? OR ticket_articles.subject LIKE ?)', "%#{query}%", "%#{query}%", "%#{query}%", "%#{query}%", "%#{query}%", "%#{query}%" )
                          .joins(:articles)
                          .order('tickets.created_at DESC')
                          .limit(limit)
    else
      query_condition, bind_condition, tables = selector2sql(condition)
      tickets_all = Ticket.select('DISTINCT(tickets.id), tickets.created_at')
                          .joins(tables)
{'fraction_non_alphanumeric': 0.11851246424192889, 'fraction_numerical': 0.00939926440539436, 'mean_word_length': 1.8202247191011236, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2982866', 'n_tokens_mistral': 2904, 'n_tokens_neox': 2770, 'n_words': 604}