external_data_source_controller.rb 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class ExternalDataSourceController < ApplicationController
  3. prepend_before_action :authenticate_and_authorize!
  4. def fetch
  5. result = Service::ExternalDataSource::Search.new.execute(
  6. attribute: attribute,
  7. render_context: render_context,
  8. term: params[:query],
  9. limit: params[:limit].to_i || 10,
  10. )
  11. render json: {
  12. result: result,
  13. }
  14. end
  15. def preview
  16. result = Service::ExternalDataSource::Preview.new.execute(
  17. data_option: params[:data_option],
  18. render_context: render_context,
  19. term: params[:query],
  20. limit: params[:limit].to_i || 10,
  21. )
  22. render json: result
  23. end
  24. private
  25. def attribute
  26. ::ObjectManager::Attribute.get(object: params[:object], name: params[:attribute]).tap do |attribute|
  27. raise "Could not find object attribute for #{params}." if !attribute
  28. end
  29. end
  30. def render_context
  31. {}.tap do |result|
  32. search_context = params.fetch(:search_context, {})
  33. [::Ticket, ::Group, ::User, ::Organization].each do |model|
  34. param_value = search_context["#{model.name.downcase}_id"]
  35. result[model.name.downcase.to_sym] = model.find_by(id: param_value) if param_value
  36. end
  37. result[:user] ||= current_user
  38. # If ticket does not exist yet, fake it with a customer if present.
  39. inject_ticket(search_context, result)
  40. end
  41. end
  42. def inject_ticket(search_context, result)
  43. return if result[:ticket]
  44. customer = ::User.find_by(id: search_context['customer_id']) if search_context['customer_id']
  45. result[:ticket] = ::Ticket.new(customer: customer) if customer
  46. end
  47. end