tags_controller.rb 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class TagsController < ApplicationController
  3. prepend_before_action :authenticate_and_authorize!
  4. # GET /api/v1/tag_search?term=abc
  5. def search
  6. list = get_tag_list(params[:term], params[:limit] || 10)
  7. results = []
  8. list.each do |item|
  9. result = {
  10. id: item.id,
  11. value: item.name,
  12. }
  13. results.push result
  14. end
  15. render json: results
  16. end
  17. # GET /api/v1/tags
  18. def list
  19. list = Tag.tag_list(
  20. object: params[:object],
  21. o_id: params[:o_id],
  22. )
  23. # return result
  24. render json: {
  25. tags: list,
  26. }
  27. end
  28. # POST /api/v1/tags/add
  29. def add
  30. raise Exceptions::Forbidden if !::Tag.tag_allowed?(name: params[:item], user_id: UserInfo.current_user_id)
  31. success = Tag.tag_add(
  32. object: params[:object],
  33. o_id: params[:o_id],
  34. item: params[:item],
  35. )
  36. if success
  37. render json: success, status: :created
  38. else
  39. render json: success.errors, status: :unprocessable_entity
  40. end
  41. end
  42. # DELETE /api/v1/tags/remove
  43. def remove
  44. success = Tag.tag_remove(
  45. object: params[:object],
  46. o_id: params[:o_id],
  47. item: params[:item],
  48. )
  49. if success
  50. render json: success
  51. else
  52. render json: success.errors, status: :unprocessable_entity
  53. end
  54. end
  55. # GET /api/v1/tag_list
  56. def admin_list
  57. list = Tag::Item.reorder(name: :asc).limit(params[:limit] || 1000)
  58. results = []
  59. list.each do |item|
  60. result = {
  61. id: item.id,
  62. name: item.name,
  63. count: Tag.where(tag_item_id: item.id).count
  64. }
  65. results.push result
  66. end
  67. render json: results
  68. end
  69. # POST /api/v1/tag_list
  70. def admin_create
  71. Tag::Item.lookup_by_name_and_create(params[:name])
  72. render json: {}
  73. end
  74. # PUT /api/v1/tag_list/:id
  75. def admin_rename
  76. Tag::Item.rename(
  77. id: params[:id],
  78. name: params[:name],
  79. )
  80. render json: {}
  81. end
  82. # DELETE /api/v1/tag_list/:id
  83. def admin_delete
  84. Tag::Item.remove(params[:id])
  85. render json: {}
  86. end
  87. private
  88. def get_tag_list(term, limit)
  89. if term.blank?
  90. return Tag::Item.left_outer_joins(:tags).group(:id).reorder('COUNT(tags.tag_item_id) DESC, name ASC').limit(limit)
  91. end
  92. Tag::Item.where('name_downcase LIKE ?', "%#{SqlHelper.quote_like(term.strip.downcase)}%").reorder(name: :asc).limit(limit)
  93. end
  94. end