can_selector.rb 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. module Ticket::CanSelector
  3. extend ActiveSupport::Concern
  4. include ::CanSelector
  5. class_methods do
  6. =begin
  7. get count of tickets and tickets which match on selector
  8. @param [Hash] selectors hash with conditions
  9. @oparam [Hash] options
  10. @option options [String] :access can be 'full', 'read', 'create' or 'ignore' (ignore means a selector over all tickets), defaults to 'full'
  11. @option options [Integer] :limit of tickets to return
  12. @option options [User] :user is a current user
  13. @option options [Integer] :execution_time is a current user
  14. @return [Integer, [<Ticket>]]
  15. @example
  16. ticket_count, tickets = Ticket.selectors(params[:condition], limit: limit, current_user: current_user, access: 'full')
  17. ticket_count # count of found tickets
  18. tickets # tickets
  19. =end
  20. def selectors(selectors, options = {})
  21. limit = options[:limit] || 10
  22. current_user = options[:current_user]
  23. access = options[:access] || 'full'
  24. raise 'no selectors given' if !selectors
  25. query, bind_params, tables = selector2sql(selectors, options)
  26. return [] if !query
  27. ActiveRecord::Base.transaction(requires_new: true) do
  28. relation = if !current_user || access == 'ignore'
  29. Ticket.all
  30. else
  31. "TicketPolicy::#{access.camelize}Scope".constantize.new(current_user).resolve
  32. end
  33. tickets = relation
  34. .distinct
  35. .where(query, *bind_params)
  36. .joins(tables)
  37. .reorder(options[:order_by])
  38. [tickets.count, tickets.limit(limit)]
  39. rescue ActiveRecord::StatementInvalid => e
  40. Rails.logger.error e
  41. raise ActiveRecord::Rollback
  42. end
  43. end
  44. end
  45. end