external_data_source_controller.rb 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. search_context = params.fetch(:search_context, {})
  32. result = [::Ticket, ::Group, ::User, ::Organization].each_with_object({}) do |model, memo|
  33. param_value = search_context["#{model.name.downcase}_id"]
  34. next if !param_value
  35. memo[model.name.downcase.to_sym] = model.find_by(id: 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. result
  41. end
  42. def inject_ticket(search_context, result)
  43. return if result[:ticket]
  44. return if !search_context['customer_id']
  45. customer = ::User.find_by(id: search_context['customer_id'])
  46. return if !customer
  47. result[:ticket] = ::Ticket.new(customer: customer)
  48. end
  49. end