Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: user and group filters (#34400)

Sam8db7503d96a7
diff --git a/app/assets/javascripts/discourse/app/components/discovery/filter-navigation-menu.gjs b/app/assets/javascripts/discourse/app/components/discovery/filter-navigation-menu.gjs
index 46589b94d9c..e820592c953 100644
--- a/app/assets/javascripts/discourse/app/components/discovery/filter-navigation-menu.gjs
+++ b/app/assets/javascripts/discourse/app/components/discovery/filter-navigation-menu.gjs
@@ -211,8 +211,9 @@ export default class FilterNavigationMenu extends Component {
}
@action
- clearInput() {
- this.updateInput("", true);
+ async clearInput() {
+ await this.updateInput("", true);
+ await this.ensureFreshSuggestions();
this.inputElement?.focus();
}
diff --git a/app/assets/javascripts/discourse/app/lib/filter-suggestions.js b/app/assets/javascripts/discourse/app/lib/filter-suggestions.js
index ef07da4dfb5..aa1bd4245e0 100644
--- a/app/assets/javascripts/discourse/app/lib/filter-suggestions.js
+++ b/app/assets/javascripts/discourse/app/lib/filter-suggestions.js
@@ -152,6 +152,8 @@ export default class FilterSuggestions {
return await suggester.getTagSuggestions();
case "username":
return await suggester.getUserSuggestions();
+ case "group":
+ return await suggester.getGroupSuggestions();
case "username_group_list":
return await suggester.getUsernameGroupListSuggestions();
case "date":
@@ -352,12 +354,40 @@ class FilterTypeValueSuggester {
const response = await ajax("/u/search/users.json", { data });
- return response.users.map((user) => ({
+ let results = response.users.map((user) => ({
name: this.buildSuggestionName(user.username),
description: user.name || "",
term: user.username,
isSuggestion: true,
}));
+
+ results = this.prepareDelimiterSuggestions(results);
+ return results;
+ } catch {
+ return [];
+ }
+ }
+
+ async getGroupSuggestions() {
+ try {
+ const groupData = { limit: 10 };
+ if (this.searchTerm) {
+ groupData.term = this.searchTerm;
+ }
+
+ const groupResponse = await ajax("/groups/search.json", {
+ data: groupData,
+ });
+
+ let results = groupResponse.map((group) => ({
+ name: this.buildSuggestionName(group.name),
+ description: group.full_name || group.name,
+ term: group.name,
+ isSuggestion: true,
+ }));
+
+ results = this.prepareDelimiterSuggestions(results);
+ return results;
} catch {
return [];
}
diff --git a/app/assets/javascripts/discourse/tests/unit/lib/filter-suggestions-test.js b/app/assets/javascripts/discourse/tests/unit/lib/filter-suggestions-test.js
index a7ffb1471cf..e37a5447319 100644
--- a/app/assets/javascripts/discourse/tests/unit/lib/filter-suggestions-test.js
+++ b/app/assets/javascripts/discourse/tests/unit/lib/filter-suggestions-test.js
@@ -36,6 +36,27 @@ function buildTips() {
description: "Unsolved topics",
priority: 1,
},
+ {
+ name: "users:",
+ description: "Users",
+ type: "username",
+ priority: 1,
+ delimiters: [
+ { name: ",", description: "any" },
+ { name: "+", description: "all" },
+ ],
+ },
+ {
+ name: "group:",
+ alias: "groups:",
+ description: "Group",
+ type: "group",
+ priority: 1,
+ delimiters: [
+ { name: ",", description: "any" },
+ { name: "+", description: "all" },
+ ],
+ },
{
name: "after:",
description: "Filter by date",
@@ -72,7 +93,15 @@ module("Unit | Utility | FilterSuggestions", function (hooks) {
assert.deepEqual(
names,
- ["after:", "category:", "status:solved", "status:unsolved", "tag:"],
+ [
+ "after:",
+ "category:",
+ "group:",
+ "status:solved",
+ "status:unsolved",
+ "tag:",
+ "users:",
+ ],
"returns only top-level tips sorted alphabetically within same priority"
);
});
@@ -236,6 +265,37 @@ module("Unit | Utility | FilterSuggestions", function (hooks) {
assert.strictEqual(suggestions.length, 20, "limits results to 20");
});
+ test("username suggestions include delimiters when exact match is present", async function (assert) {
+ pretender.get("/u/search/users.json", () =>
+ response({ users: [{ username: "sam", name: "Sam" }] })
+ );
+
+ const res = await FilterSuggestions.getSuggestions(
+ "users:sam",
+ buildTips(),
+ buildContext()
+ );
+ const names = res.suggestions.map((s) => s.name);
+
+ assert.true(names.includes("users:sam+"), "offers + delimiter");
+ assert.true(names.includes("users:sam,"), "offers , delimiter");
+ });
+
+ test("group suggestions are fetched and include delimiters", async function (assert) {
+ pretender.get("/groups/search.json", () =>
+ response([{ name: "team", full_name: "Team" }])
+ );
+
+ const res = await FilterSuggestions.getSuggestions(
+ "group:te",
+ buildTips(),
+ buildContext()
+ );
+ const names = res.suggestions.map((s) => s.name);
+
+ assert.true(names.includes("group:team"), "includes group name suggestion");
+ });
+
test("username_group_list suggests users and filters out already-used values", async function (assert) {
pretender.get("/u/search/users.json", () =>
response({
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index af6bbcca35b..8fc20e2c4a8 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -2934,6 +2934,14 @@ en:
order_views_asc: "Sort by view count (least first)"
order_read: "Sort by when you last read (most recent first)"
order_read_asc: "Sort by when you last read (oldest first)"
+ order_hot: "Sort by hot score (most first)"
+ order_hot_asc: "Sort by hot score (least first)"
+ users: "Filter topics by participants"
+ users_any: "Show topics with any of the specified users (comma-separated)"
+ users_all: "Show topics with all of the specified users (plus-separated)"
+ group: "Filter topics by groups"
+ groups_any: "Show topics with any of the specified groups (comma-separated)"
+ groups_all: "Show topics with all of the specified groups (plus-separated)"
discourse_connect:
login_error: "Login Error"
diff --git a/lib/topics_filter.rb b/lib/topics_filter.rb
index dcb526a9209..a1bc057295c 100644
--- a/lib/topics_filter.rb
+++ b/lib/topics_filter.rb
@@ -10,7 +10,7 @@ class TopicsFilter
@topic_notification_levels = Set.new
end
- FILTER_ALIASES = { "categories" => "category", "tags" => "tag" }
+ FILTER_ALIASES = { "categories" => "category", "tags" => "tag", "groups" => "group" }
private_constant :FILTER_ALIASES
def filter_from_query_string(query_string)
@@ -64,6 +64,10 @@ class TopicsFilter
filter_by_number_of_likes_in_first_post(max: filter_values)
when "order"
order_by(values: filter_values)
+ when "users"
+ filter_users(values: filter_values)
+ when "group"
+ filter_groups(values: filter_values)
when "posts-min"
filter_by_number_of_posts(min: filter_values)
when "posts-max"
@@ -189,6 +193,16 @@ class TopicsFilter
type: "username",
delimiters: [{ name: ",", description: I18n.t("filter.description.created_by_multiple") }],
},
+ {
+ name: "users:",
+ description: I18n.t("filter.description.users"),
+ type: "username",
+ priority: 1,
+ delimiters: [
+ { name: ",", description: I18n.t("filter.description.users_any") },
+ { name: "+", description: I18n.t("filter.description.users_all") },
+ ],
+ },
{
name: "latest-post-before:",
description: I18n.t("filter.description.latest_post_before"),
@@ -255,6 +269,8 @@ class TopicsFilter
{ name: "order:title-asc", description: I18n.t("filter.description.order_title_asc") },
{ name: "order:views", description: I18n.t("filter.description.order_views") },
{ name: "order:views-asc", description: I18n.t("filter.description.order_views_asc") },
+ { name: "order:hot", description: I18n.t("filter.description.order_hot") },
+ { name: "order:hot-asc", description: I18n.t("filter.description.order_hot_asc") },
{ name: "order:read", description: I18n.t("filter.description.order_read") },
{ name: "order:read-asc", description: I18n.t("filter.description.order_read_asc") },
]
@@ -305,6 +321,21 @@ class TopicsFilter
)
end
+ # Group participation filter (any/all)
+ results.push(
+ {
+ name: "group:",
+ alias: "groups:",
+ description: I18n.t("filter.description.group"),
+ type: "group",
+ priority: 1,
+ delimiters: [
+ { name: ",", description: I18n.t("filter.description.groups_any") },
+ { name: "+", description: I18n.t("filter.description.groups_all") },
+ ],
+ },
+ )
+
# this modifier allows custom plugins to add UI tips in the /filter route
DiscoursePluginRegistry.apply_modifier(:topics_filter_options, results, guardian)
end
@@ -388,6 +419,125 @@ class TopicsFilter
filter_by_topic_range(column_name: "topics.views", min:, max:)
end
+ def calculate_all_or_any(value)
+ require_all = nil
+ names = nil
+
+ if value.include?("+")
+ names = value.split("+")
+ require_all = true
+ if value.include?(",")
+ # no mix and match
+ return nil, []
+ end
+ else
+ names = value.split(",")
+ require_all = false
+ if value.include?("+")
+ # no mix and match
+ return nil, []
+ end
+ end
+
+ [require_all, names.map(&:downcase).reject(&:blank?)]
+ end
+
+ # users:a,b => any of a or b participated in the topic
+ # users:a+b => both a and b participated in the topic
+ def filter_users(values:)
+ values.each do |value|
+ require_all, usernames = calculate_all_or_any(value)
+
+ if usernames.empty?
+ @scope = @scope.none
+ next
+ end
+
+ user_ids = User.not_staged.where("username_lower IN (?)", usernames).pluck(:id)
+
+ if user_ids.empty?
+ @scope = @scope.none
+ next
+ end
+
+ if require_all
+ if user_ids.length < usernames.length
+ @scope = @scope.none
+ next
+ end
+
+ # A possible alternative is to select the topics with the users with the least posts
+ # then expand to all of the rest of the users, this can limit the scanning
+ user_ids.each_with_index { |uid, idx| @scope = @scope.where(<<~SQL) }
+ EXISTS (
+ SELECT 1
+ FROM posts p#{idx}
+ WHERE p#{idx}.topic_id = topics.id AND p#{idx}.user_id = #{uid}
+ LIMIT 1
+ )
+ SQL
+ else
+ @scope = @scope.where(<<~SQL, user_ids: user_ids)
+ topics.id IN (
+ SELECT DISTINCT p.topic_id
+ FROM posts p
+ WHERE p.user_id IN (:user_ids)
+ )
+ SQL
+ end
+ end
+ end
+
+ # group:staff,moderators => any of the groups have participation
+ # group:staff+moderators => both groups have participation
+ def filter_groups(values:)
+ values.each do |value|
+ require_all, group_names = calculate_all_or_any(value)
+
+ if group_names.empty?
+ @scope = @scope.none
+ next
+ end
+
+ group_ids =
+ Group
+ .visible_groups(@guardian.user)
+ .members_visible_groups(@guardian.user)
+ .where("lower(name) IN (?)", group_names)
+ .pluck(:id)
+
+ if group_ids.empty?
+ @scope = @scope.none
+ next
+ end
+
+ if require_all
+ if group_ids.length < group_names.length
+ @scope = @scope.none
+ next
+ end
+
+ group_ids.each_with_index { |gid, idx| @scope = @scope.where(<<~SQL) }
+ EXISTS (
+ SELECT 1
+ FROM posts pg#{idx}
+ JOIN group_users gu#{idx} ON gu#{idx}.user_id = pg#{idx}.user_id
+ WHERE pg#{idx}.topic_id = topics.id AND gu#{idx}.group_id = #{gid}
+ )
+ SQL
+ else
+ @scope = @scope.where(<<~SQL, group_ids: group_ids)
+ topics.id IN (
+ SELECT DISTINCT p.topic_id
+ FROM posts p
+ JOIN group_users gu ON gu.user_id = p.user_id
+ WHERE gu.group_id IN (:group_ids)
+ )
+ SQL
+ end
+ end
+ end
+
def filter_categories(values:)
category_slugs = {
include: {
@@ -754,6 +904,12 @@ class TopicsFilter
"views" => {
column: "topics.views",
},
+ "hot" => {
+ column: "COALESCE(topic_hot_scores.score, 0)",
+ scope: -> do
+ @scope.joins("LEFT JOIN topic_hot_scores ON topic_hot_scores.topic_id = topics.id")
+ end,
+ },
"read" => {
column: "tu.last_visited_at",
scope: -> do
@@ -780,7 +936,6 @@ class TopicsFilter
if scope = ORDER_BY_MAPPINGS.dig(match_data[:order_by], :scope)
@scope = instance_exec(&scope)
end
-
@scope = @scope.order("#{column_name} #{match_data[:asc] ? "ASC" : "DESC"}")
else
match_data = value.match(/^(?<column>.*?)(?:-(?<asc>asc))?$/)
diff --git a/spec/lib/topics_filter_spec.rb b/spec/lib/topics_filter_spec.rb
index 050838f650c..b739bcb0a46 100644
--- a/spec/lib/topics_filter_spec.rb
+++ b/spec/lib/topics_filter_spec.rb
@@ -88,6 +88,109 @@ RSpec.describe TopicsFilter do
end
describe "#filter_from_query_string" do
+ describe "when filtering with the `users` and `group` filters" do
+ fab!(:u1) { Fabricate(:user, username: "alice") }
+ fab!(:u2) { Fabricate(:user, username: "bob") }
+ fab!(:u3) { Fabricate(:user, username: "cara") }
+ fab!(:g1) { Fabricate(:group, name: "group1") }
+ fab!(:g2) { Fabricate(:group, name: "group2") }
+
+ before do
+ g1.add(u1)
+ g2.add(u2)
+ end
+
+ fab!(:topic_by_u1) { Fabricate(:topic).tap { |t| Fabricate(:post, topic: t, user: u1) } }
+
+ fab!(:topic_by_u2) { Fabricate(:topic).tap { |t| Fabricate(:post, topic: t, user: u2) } }
+
+ fab!(:topic_by_u1_and_u2) do
+ Fabricate(:topic).tap do |t|
+ Fabricate(:post, topic: t, user: u1)
+ Fabricate(:post, topic: t, user: u2)
+ end
+ end
+
+ it "users:alice returns topics where alice participated" do
+ ids =
+ TopicsFilter
+ .new(guardian: Guardian.new)
+ .filter_from_query_string("users:alice")
+ .pluck(:id)
+ expect(ids).to include(topic_by_u1.id, topic_by_u1_and_u2.id)
+ expect(ids).not_to include(topic_by_u2.id)
+ end
+
+ it "users:alice,bob returns topics with either alice or bob" do
+ ids =
+ TopicsFilter
+ .new(guardian: Guardian.new)
+ .filter_from_query_string("users:alice,bob")
+ .pluck(:id)
+ expect(ids).to include(topic_by_u1.id, topic_by_u2.id, topic_by_u1_and_u2.id)
+ end
+
+ it "users:alice+bob returns only topics where both participated/allowed" do
+ ids =
+ TopicsFilter
+ .new(guardian: Guardian.new)
+ .filter_from_query_string("users:alice+bob")
+ .pluck(:id)
+ expect(ids).to contain_exactly(topic_by_u1_and_u2.id)
+ end
+
+ it "group:group1 returns topics with participants from the group or group-allowed PMs" do
+ ids =
+ TopicsFilter
+ .new(guardian: Guardian.new)
+ .filter_from_query_string("group:group1")
+ .pluck(:id)
+ expect(ids).to include(topic_by_u1.id, topic_by_u1_and_u2.id)
+ end
+
+ it "groups:group1,group2 returns union of both groups" do
+ ids =
+ TopicsFilter
+ .new(guardian: Guardian.new)
+ .filter_from_query_string("groups:group1,group2")
+ .pluck(:id)
+ expect(ids).to include(topic_by_u1.id, topic_by_u2.id, topic_by_u1_and_u2.id)
+ end
+
+ it "group:group1+group2 returns only topics with both groups represented" do
+ ids =
+ TopicsFilter
+ .new(guardian: Guardian.new)
+ .filter_from_query_string("group:group1+group2")
+ .pluck(:id)
+ expect(ids).to contain_exactly(topic_by_u1_and_u2.id)
+ end
+ end
+
+ describe "ordering by hot score" do
+ fab!(:t1) { Fabricate(:topic) }
+ fab!(:t2) { Fabricate(:topic) }
+
+ before do
+ TopicHotScore.create!(topic_id: t1.id, score: 2.0)
+ TopicHotScore.create!(topic_id: t2.id, score: 3.0)
+ end
+
+ it "order:hot sorts by topic_hot_scores.score desc" do
+ expect(
+ TopicsFilter.new(guardian: Guardian.new).filter_from_query_string("order:hot").pluck(:id),
+ ).to start_with(t2.id, t1.id)
+ end
+
+ it "order:hot-asc sorts ascending" do
+ expect(
+ TopicsFilter
+ .new(guardian: Guardian.new)
+ .filter_from_query_string("order:hot-asc")
+ .pluck(:id),
+ ).to start_with(t1.id, t2.id)
+ end
+ end
describe "when filtering with multiple filters" do
fab!(:tag) { Fabricate(:tag, name: "tag1") }
fab!(:tag2) { Fabricate(:tag, name: "tag2") }