merge_ticket.rb 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. module Gql::Queries
  3. class AutocompleteSearch::MergeTicket < BaseQuery
  4. description 'Search for tickets'
  5. argument :input, Gql::Types::Input::AutocompleteSearch::MergeTicketInputType, required: true, description: 'The input object for the autocomplete search'
  6. type [Gql::Types::AutocompleteSearch::MergeTicketEntryType], null: false
  7. def self.authorize(_obj, ctx)
  8. ctx.current_user.permissions?('ticket.agent')
  9. end
  10. def resolve(input:)
  11. search_tickets(query: input.query, limit: input.limit || 10, source_ticket: input.source_ticket).map { |t| coerce_to_result(t) }
  12. end
  13. def search_tickets(query:, limit:, source_ticket:)
  14. if query.strip.empty?
  15. return search_db(limit: limit, source_ticket: source_ticket)
  16. end
  17. search_index(query: query, limit: limit, source_ticket: source_ticket)
  18. end
  19. def search_db(limit:, source_ticket:)
  20. TicketPolicy::ChangeScope.new(context.current_user).resolve.where.not(state_id: ignore_state_ids).where.not(id: source_ticket.id).reorder(created_at: :desc).limit(limit)
  21. end
  22. def search_index(query:, limit:, source_ticket:)
  23. # We have to filter out the states afterwards, because the search method can only handle either query OR condition.
  24. ::Ticket.search(
  25. current_user: context.current_user,
  26. query: query,
  27. scope: TicketPolicy::ChangeScope,
  28. limit: limit,
  29. sort_by: 'created_at',
  30. order_by: 'desc',
  31. ).reject do |ticket|
  32. ignore_state_ids.include?(ticket.state_id) || source_ticket.id == ticket.id
  33. end
  34. end
  35. def coerce_to_result(ticket)
  36. {
  37. value: Gql::ZammadSchema.id_from_object(ticket),
  38. label: ticket.title,
  39. heading: "##{ticket.number} · #{ticket.customer.fullname}",
  40. ticket: ticket,
  41. }
  42. end
  43. private
  44. def ignore_state_ids
  45. ::Ticket::State.where(state_type_id: ::Ticket::StateType.where(name: %w[merged removed]).map(&:id)).map(&:id)
  46. end
  47. end
  48. end