menu_item_update_action.rb 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. class KnowledgeBase
  2. class MenuItemUpdateAction
  3. def initialize(kb_locale, location, menu_items_data)
  4. @kb_locale = kb_locale
  5. @location = location
  6. @menu_items_data = menu_items_data
  7. end
  8. def scope
  9. @kb_locale.menu_items.location(@location)
  10. end
  11. def perform!
  12. raise_unprocessable unless all_ids_present?
  13. KnowledgeBase::MenuItem.transaction do
  14. KnowledgeBase::MenuItem.acts_as_list_no_update do
  15. remove_deleted
  16. update_order
  17. end
  18. end
  19. end
  20. # Mass-update KB menu items
  21. #
  22. # @param [KnowledgeBase] knowledge_base
  23. # @param [[<Hash>]] params @see .update_location_params!
  24. #
  25. # @return [<KnowledgeBase::MenuItem>]
  26. def self.update_using_params!(knowledge_base, params)
  27. return if params.blank?
  28. params
  29. .map { |location_params| update_location_using_params! knowledge_base, location_params }
  30. .map(&:reload)
  31. .reduce(:+)
  32. end
  33. # Mass-update KB menu items in a given location
  34. #
  35. # @param [KnowledgeBase] knowledge_base
  36. # @param [Hash] location_params
  37. #
  38. # @option location_params [Integer] :kb_locale_id
  39. # @option location_params [String] :location header or footer
  40. # @option location_params [[<Hash>]] :menu_items @see #update_order
  41. def self.update_location_using_params!(knowledge_base, location_params)
  42. action = new(
  43. knowledge_base.kb_locales.find(location_params[:kb_locale_id]),
  44. location_params[:location],
  45. location_params[:menu_items]
  46. )
  47. action.perform!
  48. action.scope
  49. end
  50. private
  51. def update_order
  52. old_items = scope.to_a
  53. @menu_items_data
  54. .reject { |elem| elem[:_destroy] }
  55. .each_with_index do |data_elem, index|
  56. item = old_items.find { |record| record.id == data_elem[:id] } || scope.build
  57. item.position = index
  58. item.title = data_elem[:title]
  59. item.url = data_elem[:url]
  60. item.new_tab = data_elem[:new_tab]
  61. item.save!
  62. end
  63. end
  64. def remove_deleted
  65. @menu_items_data
  66. .select { |elem| elem[:_destroy] }
  67. .map { |elem| elem[:id] }
  68. .tap { |array| @kb_locale.menu_items.where(id: array).destroy_all }
  69. end
  70. def all_ids_present?
  71. old_ids = scope.pluck(:id)
  72. new_ids = @menu_items_data.map { |elem| elem[:id]&.to_i }.compact
  73. old_ids.sort == new_ids.sort
  74. end
  75. def raise_unprocessable
  76. raise Exceptions::UnprocessableEntity, 'Provide position of all items in scope'
  77. end
  78. end
  79. end