links_controller.rb 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class LinksController < ApplicationController
  3. prepend_before_action -> { authorize! }, only: %i[add remove]
  4. prepend_before_action :authentication_check
  5. # GET /api/v1/links
  6. def index
  7. links = Link.list(
  8. link_object: params[:link_object],
  9. link_object_value: params[:link_object_value],
  10. user: current_user,
  11. )
  12. linked_objects = links
  13. .filter_map { |elem| elem['link_object']&.safe_constantize&.lookup(id: elem['link_object_value']) }
  14. # return result
  15. render json: {
  16. links: links,
  17. assets: ApplicationModel::CanAssets.reduce(linked_objects),
  18. }
  19. end
  20. # POST /api/v1/links/add
  21. def add
  22. object = case params[:link_object_source]
  23. when 'Ticket'
  24. Ticket.find_by(number: params[:link_object_source_number])
  25. when 'KnowledgeBase::Answer::Translation'
  26. KnowledgeBase::Answer::Translation.find_by(id: params[:link_object_source_number])
  27. end
  28. if !object
  29. render json: { error: __('The object could not be found.') }, status: :unprocessable_entity
  30. return
  31. end
  32. link = Link.add(
  33. link_type: params[:link_type],
  34. link_object_target: params[:link_object_target],
  35. link_object_target_value: params[:link_object_target_value],
  36. link_object_source: params[:link_object_source],
  37. link_object_source_value: object.id,
  38. )
  39. if link
  40. render json: link, status: :created
  41. else
  42. render json: link.errors, status: :unprocessable_entity
  43. end
  44. end
  45. # DELETE /api/v1/links/remove
  46. def remove
  47. link = Link.remove(params)
  48. if link
  49. render json: link, status: :created
  50. else
  51. render json: link.errors, status: :unprocessable_entity
  52. end
  53. end
  54. end