discourse/app/services/sidebar_section_links_updater.rb
Alan Guo Xiang Tan 0a56274596
FIX: Seed all categories and tags configured as defaults for nav menu (#22793)
Context of this change:

There are two site settings which an admin can configured to set the
default categories and tags that are shown for a new user. `default_navigation_menu_categories`
is used to determine the default categories while
`default_navigation_menu_tags` is used to determine the default tags.

Prior to this change when seeding the defaults, we will filter out the
categories/tags that the user do not have permission to see. However,
this means that when the user does eventually gain permission down the
line, the default categories and tags do not appear.

What does this change do?

With this commit, we have changed it such that all the categories and tags
configured in the `default_navigation_menu_categories` and
`default_navigation_menu_tags` site settings are seeded regardless of
whether the user's visibility of the categories or tags. During
serialization, we will then filter out the categories and tags which the
user does not have visibility of.
2023-07-27 10:52:33 +08:00

52 lines
1.7 KiB
Ruby

# frozen_string_literal: true
class SidebarSectionLinksUpdater
def self.update_category_section_links(user, category_ids:)
if category_ids.blank?
delete_section_links(user: user, linkable_type: "Category")
else
category_ids = Category.where(id: category_ids).pluck(:id)
update_section_links(user: user, linkable_type: "Category", new_linkable_ids: category_ids)
end
end
def self.update_tag_section_links(user, tag_ids:)
if tag_ids.blank?
delete_section_links(user: user, linkable_type: "Tag")
else
update_section_links(user: user, linkable_type: "Tag", new_linkable_ids: tag_ids)
end
end
def self.delete_section_links(user:, linkable_type:)
SidebarSectionLink.where(user: user, linkable_type: linkable_type).delete_all
end
private_class_method :delete_section_links
def self.update_section_links(user:, linkable_type:, new_linkable_ids:)
SidebarSectionLink.transaction do
existing_linkable_ids =
SidebarSectionLink.where(user: user, linkable_type: linkable_type).pluck(:linkable_id)
to_delete = existing_linkable_ids - new_linkable_ids
to_insert = new_linkable_ids - existing_linkable_ids
to_insert_attributes =
to_insert.map do |linkable_id|
{ linkable_type: linkable_type, linkable_id: linkable_id, user_id: user.id }
end
if to_delete.present?
SidebarSectionLink.where(
user: user,
linkable_type: linkable_type,
linkable_id: to_delete,
).delete_all
end
SidebarSectionLink.insert_all(to_insert_attributes) if to_insert_attributes.present?
end
end
private_class_method :update_section_links
end