Skip to content

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

FEATURE: Make "Who's posting?" category filter multi-select (#41837)

Osama Sayegh7fcdb84c44db
diff --git a/app/assets/stylesheets/admin/dashboard/engagement.scss b/app/assets/stylesheets/admin/dashboard/engagement.scss
index 8a9d500ddfd..613160da7c8 100644
--- a/app/assets/stylesheets/admin/dashboard/engagement.scss
+++ b/app/assets/stylesheets/admin/dashboard/engagement.scss
@@ -111,21 +111,12 @@
@container db-whos-posting (width < 22rem) {
width: 100%;
- .select-kit.combo-box.category-chooser {
+ .select-kit.multi-select.category-selector {
max-width: none;
}
}
}
- &__subcategories {
- display: flex;
- align-items: center;
- gap: var(--space-1);
- font-size: var(--font-down-1-rem);
- color: var(--primary-medium);
- cursor: pointer;
- }
-
&__bars {
display: grid;
grid-template-columns: minmax(0, auto) minmax(200px, 1fr) 2.5rem;
diff --git a/app/models/concerns/reports/posters_by_member_type.rb b/app/models/concerns/reports/posters_by_member_type.rb
index a35695bf964..08ae0f9bf94 100644
--- a/app/models/concerns/reports/posters_by_member_type.rb
+++ b/app/models/concerns/reports/posters_by_member_type.rb
@@ -4,6 +4,7 @@ module Reports::PostersByMemberType
extend ActiveSupport::Concern
MEMBER_TYPES = %i[new_members returning staff].freeze
+ MAX_CATEGORY_IDS = 50
class_methods do
def report_posters_by_member_type(report)
@@ -21,50 +22,62 @@ module Reports::PostersByMemberType
},
]
- category_id, include_subcategories = report.add_category_filter
+ raw_ids = report.filters[:category_ids]
+ filter_requested = raw_ids.present?
+ requested_ids =
+ if filter_requested
+ parsed_ids = Array(raw_ids.is_a?(String) ? raw_ids.split(",") : raw_ids).map(&:to_i)
+ if parsed_ids.present?
+ # in_order_of keeps the admin's requested order and drops nonexistent ids
+ Category.in_order_of(:id, parsed_ids).limit(MAX_CATEGORY_IDS).pluck(:id)
+ else
+ []
+ end
+ else
+ nil
+ end
+ report.add_filter("category_ids", type: "category_list", default: requested_ids)
+
+ empty_selection = filter_requested && requested_ids.empty?
- builder = DB.build <<~SQL
- SELECT
- CASE
- WHEN u.admin OR u.moderator THEN 'staff'
- WHEN u.created_at >= :start_date THEN 'new_members'
- ELSE 'returning'
- END AS bucket,
- COUNT(*) AS post_count
- FROM posts p
- INNER JOIN topics t ON t.id = p.topic_id
- INNER JOIN users u ON u.id = p.user_id
- /*join*/
- /*where*/
- GROUP BY bucket
- SQL
+ counts = Hash.new(0)
- builder.where("p.created_at >= :start_date", start_date: report.start_date)
- builder.where("p.created_at <= :end_date", end_date: report.end_date)
- builder.where("p.deleted_at IS NULL")
- builder.where("p.post_type = :regular_post_type", regular_post_type: Post.types[:regular])
- builder.where("t.deleted_at IS NULL")
- builder.where("t.archetype = 'regular'")
- builder.where("u.id > 0")
+ unless empty_selection
+ builder = DB.build <<~SQL
+ SELECT
+ CASE
+ WHEN u.admin OR u.moderator THEN 'staff'
+ WHEN u.created_at >= :start_date THEN 'new_members'
+ ELSE 'returning'
+ END AS bucket,
+ COUNT(*) AS post_count
+ FROM posts p
+ INNER JOIN topics t ON t.id = p.topic_id
+ INNER JOIN users u ON u.id = p.user_id
+ /*join*/
+ /*where*/
+ GROUP BY bucket
+ SQL
- if category_id
- if include_subcategories
- builder.where(
- "t.category_id IN (:category_ids)",
- category_ids: Category.subcategory_ids(category_id),
- )
- else
- builder.where("t.category_id = :category_id", category_id: category_id)
+ builder.where("p.created_at >= :start_date", start_date: report.start_date)
+ builder.where("p.created_at <= :end_date", end_date: report.end_date)
+ builder.where("p.deleted_at IS NULL")
+ builder.where("p.post_type = :regular_post_type", regular_post_type: Post.types[:regular])
+ builder.where("t.deleted_at IS NULL")
+ builder.where("t.archetype = 'regular'")
+ builder.where("u.id > 0")
+
+ if requested_ids.present?
+ builder.where("t.category_id IN (:category_ids)", category_ids: requested_ids)
end
- end
- unless report.current_user&.admin?
- builder.join "categories c ON c.id = t.category_id"
- builder.secure_category(Guardian.new(report.current_user).secure_category_ids)
- end
+ unless report.current_user&.admin?
+ builder.join "categories c ON c.id = t.category_id"
+ builder.secure_category(Guardian.new(report.current_user).secure_category_ids)
+ end
- counts = Hash.new(0)
- builder.query.each { |row| counts[row.bucket.to_sym] = row.post_count }
+ builder.query.each { |row| counts[row.bucket.to_sym] = row.post_count }
+ end
total = counts.values.sum
report.total = total
diff --git a/app/services/admin_dashboard_engagement.rb b/app/services/admin_dashboard_engagement.rb
index 99d7806be48..ac83b8047c7 100644
--- a/app/services/admin_dashboard_engagement.rb
+++ b/app/services/admin_dashboard_engagement.rb
@@ -109,6 +109,13 @@ class AdminDashboardEngagement
def build_posters
args = { start_date: start_date, end_date: end_date, current_user: current_user }
+ selected_category_ids =
+ AdminDashboardSectionConfiguration.settings_for("engagement").dig(
+ "whos_posting",
+ "category_ids",
+ )
+ args[:filters] = { category_ids: selected_category_ids } if selected_category_ids.present?
+
report = Report.find_cached("posters_by_member_type", args)
if report.nil?
report = Report.find("posters_by_member_type", args)
@@ -117,7 +124,11 @@ class AdminDashboardEngagement
return nil if report.nil? || report_error?(report)
- { rows: report_data(report), total: report.is_a?(Hash) ? report[:total] : report.total }
+ {
+ rows: report_data(report),
+ total: report.is_a?(Hash) ? report[:total] : report.total,
+ category_ids: visible_category_ids(selected_category_ids),
+ }
end
def build_activity_by_category
diff --git a/app/services/admin_dashboard_section_configuration.rb b/app/services/admin_dashboard_section_configuration.rb
index 1e7396ec953..51f3897c249 100644
--- a/app/services/admin_dashboard_section_configuration.rb
+++ b/app/services/admin_dashboard_section_configuration.rb
@@ -4,6 +4,7 @@ class AdminDashboardSectionConfiguration
KNOWN_SECTIONS = %w[highlights reports traffic engagement search].freeze
ACTIVITY_BY_CATEGORY_MAX = 10
+ WHOS_POSTING_MAX = 10
SUPPORTED_SETTINGS = {
"engagement" => {
@@ -24,6 +25,26 @@ class AdminDashboardSectionConfiguration
raise Discourse::InvalidParameters.new(:category_ids)
end
+ { "category_ids" => parsed }
+ end,
+ },
+ "whos_posting" => {
+ permit: [{ category_ids: [] }],
+ validate: ->(attrs) do
+ ids = attrs[:category_ids]
+ raise Discourse::InvalidParameters.new(:category_ids) if !ids.is_a?(Array)
+
+ parsed = ids.map { |id| Integer(id, exception: false) }
+
+ if parsed.size > WHOS_POSTING_MAX || parsed.any?(&:nil?) ||
+ parsed.uniq.size != parsed.size
+ raise Discourse::InvalidParameters.new(:category_ids)
+ end
+
+ if parsed.present? && Category.where(id: parsed).count != parsed.size
+ raise Discourse::InvalidParameters.new(:category_ids)
+ end
+
{ "category_ids" => parsed }
end,
},
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 13729182ed9..dd195b63996 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -7269,12 +7269,11 @@ en:
save_error: "Couldn't save your selection for next time."
whos_posting:
title: "Who's posting?"
- all_categories: "All categories"
- include_subcategories: "Include subcategories"
new_members: "New members"
returning: "Returning"
staff: "Staff"
empty: "No posts in the selected period."
+ save_error: "Couldn't save your selection for next time."
trust_level_pipeline:
title: "Trust level pipeline"
trust_levels:
diff --git a/frontend/discourse/admin/components/admin-report.gjs b/frontend/discourse/admin/components/admin-report.gjs
index 0259494695c..8d6e8787551 100644
--- a/frontend/discourse/admin/components/admin-report.gjs
+++ b/frontend/discourse/admin/components/admin-report.gjs
@@ -16,6 +16,7 @@ import AdminReportStorageStats from "discourse/admin/components/admin-report-sto
import AdminReportTable from "discourse/admin/components/admin-report-table";
import ReportFilterBoolComponent from "discourse/admin/components/report-filters/bool";
import ReportFilterCategoryComponent from "discourse/admin/components/report-filters/category";
+import ReportFilterCategoryListComponent from "discourse/admin/components/report-filters/category-list";
import ReportFilterGroupComponent from "discourse/admin/components/report-filters/group";
import ReportFilterListComponent from "discourse/admin/components/report-filters/list";
import { REPORT_MODES } from "discourse/admin/lib/constants";
@@ -242,6 +243,8 @@ export default class AdminReport extends Component {
return ReportFilterBoolComponent;
case "category":
return ReportFilterCategoryComponent;
+ case "category_list":
+ return ReportFilterCategoryListComponent;
case "group":
return ReportFilterGroupComponent;
case "list":
@@ -292,10 +295,13 @@ export default class AdminReport extends Component {
isTesting() ? "end" : formattedEndDate.replace(/-/g, ""),
"[:prev_period]",
this.args.reportOptions?.table?.limit,
- // Convert all filter values to strings to ensure unique serialization
+ // Convert all filter values to strings to ensure unique serialization.
+ // Arrays (e.g. a category_list filter's selected ids) are mapped
+ // element-wise rather than stringified whole, so the key stays valid
+ // JSON and matches the server's own `MultiJson.dump(report.filters)`.
this.args.filters?.customFilters
? JSON.stringify(this.args.filters?.customFilters, (k, v) =>
- k ? `${v}` : v
+ Array.isArray(v) ? v.map(String) : k ? `${v}` : v
)
: null,
SCHEMA_VERSION,
diff --git a/frontend/discourse/admin/components/dashboard/engagement/whos-posting.gjs b/frontend/discourse/admin/components/dashboard/engagement/whos-posting.gjs
index 8fcab686c7c..ff5fd5b7e5b 100644
--- a/frontend/discourse/admin/components/dashboard/engagement/whos-posting.gjs
+++ b/frontend/discourse/admin/components/dashboard/engagement/whos-posting.gjs
@@ -1,49 +1,42 @@
import Component from "@glimmer/component";
import { tracked } from "@glimmer/tracking";
import { hash } from "@ember/helper";
-import { on } from "@ember/modifier";
import { action } from "@ember/object";
import didUpdate from "@ember/render-modifiers/modifiers/did-update";
import { LinkTo } from "@ember/routing";
+import { service } from "@ember/service";
import { trustHTML } from "@ember/template";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import Category from "discourse/models/category";
-import CategoryChooser from "discourse/select-kit/components/category-chooser";
+import CategorySelector from "discourse/select-kit/components/category-selector";
import { i18n } from "discourse-i18n";
const ROW_ORDER = ["new_members", "returning", "staff"];
+const MAX_CATEGORIES = 10;
export default class WhosPosting extends Component {
- @tracked categoryId = null;
- @tracked includeSubcategories = false;
+ @service currentUser;
+ @service toasts;
+
+ @tracked selectedCategories = [];
@tracked overridePosters = null;
@tracked loading = false;
- get hasSubcategories() {
- if (!this.categoryId) {
- return false;
- }
- const category = Category.findById(this.categoryId);
- return (category?.subcategories?.length ?? 0) > 0;
- }
+ constructor() {
+ super(...arguments);
- get #categoryFilters() {
- if (!this.categoryId) {
- return null;
- }
- const filters = { category: this.categoryId };
- if (this.includeSubcategories) {
- filters.include_subcategories = true;
- }
- return filters;
+ this.selectedCategories = (this.args.posters?.category_ids ?? [])
+ .map((id) => Category.findById(id))
+ .filter(Boolean);
+ this.appliedCategoryIds = this.selectedCategories.map((c) => c.id);
}
get reportQuery() {
const query = {};
- const filters = this.#categoryFilters;
- if (filters) {
- query.filters = filters;
+ const ids = this.selectedCategories.map((c) => c.id);
+ if (ids.length > 0) {
+ query.filters = { category_ids: ids.join(",") };
}
if (this.args.startDate) {
query.start_date = this.args.startDate.toISOString().slice(0, 10);
@@ -88,23 +81,53 @@ export default class WhosPosting extends Component {
}
@action
- onCategoryChange(categoryId) {
- this.categoryId = categoryId;
- if (!categoryId) {
- this.includeSubcategories = false;
- }
- this.refetch();
+ onCategoriesChange(categories) {
+ this.selectedCategories = categories;
}
@action
- onSubcategoriesToggle(event) {
- this.includeSubcategories = event.target.checked;
+ onClose() {
+ const ids = this.selectedCategories.map((c) => c.id);
+ const unchanged =
+ ids.length === this.appliedCategoryIds.length &&
+ ids.every((id) => this.appliedCategoryIds.includes(id));
+
+ // apply and save once the picker closes, not on every individual pick
+ if (unchanged) {
+ return;
+ }
+
+ this.appliedCategoryIds = ids;
this.refetch();
+ this.#persistSelection();
+ }
+
+ #persistSelection() {
+ if (!this.currentUser?.admin) {
+ return;
+ }
+
+ ajax("/admin/dashboard/sections/engagement/settings/whos_posting.json", {
+ type: "PUT",
+ contentType: "application/json",
+ data: JSON.stringify({
+ category_ids: this.selectedCategories.map((c) => c.id),
+ }),
+ }).catch(() => {
+ this.toasts.error({
+ duration: "short",
+ data: {
+ message: i18n(
+ "admin.dashboard.sections.engagement.whos_posting.save_error"
+ ),
+ },
+ });
+ });
}
@action
onPeriodChange() {
- if (!this.categoryId) {
+ if (this.selectedCategories.length === 0) {
this.overridePosters = null;
} else {
this.refetch();
@@ -118,9 +141,9 @@ export default class WhosPosting extends Component {
start_date: this.args.startDate?.toISOString().slice(0, 10),
end_date: this.args.endDate?.toISOString().slice(0, 10),
};
- const filters = this.#categoryFilters;
- if (filters) {
- data.filters = filters;
+ const ids = this.selectedCategories.map((c) => c.id);
+ if (ids.length > 0) {
+ data.filters = { category_ids: ids.join(",") };
}
try {
@@ -153,23 +176,12 @@ export default class WhosPosting extends Component {
{{i18n "admin.dashboard.sections.engagement.whos_posting.title"}}
</LinkTo>
<div class="db-whos-posting__filter">
- <CategoryChooser
- @value={{this.categoryId}}
- @onChange={{this.onCategoryChange}}
- @options={{hash none="category.all" autoInsertNoneItem=true}}
+ <CategorySelector
+ @categories={{this.selectedCategories}}
+ @onChange={{this.onCategoriesChange}}
+ @onClose={{this.onClose}}
+ @options={{hash maximum=MAX_CATEGORIES none="category.all"}}
/>
- {{#if this.hasSubcategories}}
- <label class="db-whos-posting__subcategories">
- <input
- type="checkbox"
- checked={{this.includeSubcategories}}
- {{on "change" this.onSubcategoriesToggle}}
- />
- {{i18n
- "admin.dashboard.sections.engagement.whos_posting.include_subcategories"
- }}
- </label>
- {{/if}}
</div>
</div>
diff --git a/frontend/discourse/admin/components/report-filters/category-list.gjs b/frontend/discourse/admin/components/report-filters/category-list.gjs
new file mode 100644
index 00000000000..49635407816
--- /dev/null
+++ b/frontend/discourse/admin/components/report-filters/category-list.gjs
@@ -0,0 +1,48 @@
+import { tracked } from "@glimmer/tracking";
+import { hash } from "@ember/helper";
+import { action } from "@ember/object";
+import FilterComponent from "discourse/admin/components/report-filters/filter";
+import Category from "discourse/models/category";
+import CategorySelector from "discourse/select-kit/components/category-selector";
+
+export default class CategoryList extends FilterComponent {
+ @tracked selectedCategories;
+
+ init() {
+ super.init(...arguments);
+ this.selectedCategories = (this.filter?.default || [])
+ .map((id) => Category.findById(id))
+ .filter(Boolean);
+ }
+
+ @action
+ onChange(categories) {
+ this.selectedCategories = categories;
+ }
+
+ @action
+ onClose() {
+ const ids = this.selectedCategories.map((category) => category.id);
+ const current = this.filter.default || [];
+
+ // apply (and re-run the report) only once the picker closes, and only when
+ // the selection actually changed, so each individual pick doesn't refetch
+ if (
+ ids.length === current.length &&
+ ids.every((id) => current.includes(id))
+ ) {
+ return;
+ }
+
+ this.applyFilter(this.filter.id, ids.length ? ids : undefined);
+ }
+
+ <template>
+ <CategorySelector
+ @categories={{this.selectedCategories}}
+ @onChange={{this.onChange}}
+ @onClose={{this.onClose}}
+ @options={{hash disabled=this.filter.disabled none="category.all"}}
+ />
+ </template>
+}
diff --git a/frontend/discourse/tests/integration/components/dashboard/whos-posting-test.gjs b/frontend/discourse/tests/integration/components/dashboard/whos-posting-test.gjs
index 7a169141307..96e7124636d 100644
--- a/frontend/discourse/tests/integration/components/dashboard/whos-posting-test.gjs
+++ b/frontend/discourse/tests/integration/components/dashboard/whos-posting-test.gjs
@@ -2,6 +2,8 @@ import { render } from "@ember/test-helpers";
import { module, test } from "qunit";
import WhosPosting from "discourse/admin/components/dashboard/engagement/whos-posting";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import selectKit from "discourse/tests/helpers/select-kit-helper";
+import { i18n } from "discourse-i18n";
module("Integration | Component | Dashboard | WhosPosting", function (hooks) {
setupRenderingTest(hooks);
@@ -55,7 +57,40 @@ module("Integration | Component | Dashboard | WhosPosting", function (hooks) {
.dom("a.db-section__row-block-title.--label")
.hasText("Who's posting?")
.hasAttribute("href", /\/admin\/reports\/posters_by_member_type/);
- assert.dom(".category-chooser").exists();
+ assert.dom(".category-selector").exists();
+ });
+
+ test("shows an 'All categories' placeholder when nothing is selected", async function (assert) {
+ await render(
+ <template>
+ <WhosPosting
+ @posters={{posters}}
+ @startDate={{start}}
+ @endDate={{end}}
+ />
+ </template>
+ );
+
+ assert.strictEqual(
+ selectKit(".category-selector").header().label(),
+ i18n("category.all")
+ );
+ });
+
+ test("prefills the selector with the persisted category selection", async function (assert) {
+ const withSelection = { ...posters, category_ids: [1, 2] };
+
+ await render(
+ <template>
+ <WhosPosting
+ @posters={{withSelection}}
+ @startDate={{start}}
+ @endDate={{end}}
+ />
+ </template>
+ );
+
+ assert.strictEqual(selectKit(".category-selector").header().value(), "1,2");
});
test("falls back to an empty-state message when there are no posts", async function (assert) {
diff --git a/spec/models/concerns/reports/posters_by_member_type_spec.rb b/spec/models/concerns/reports/posters_by_member_type_spec.rb
index 5f0e4d1bcd0..9cb7c864bbe 100644
--- a/spec/models/concerns/reports/posters_by_member_type_spec.rb
+++ b/spec/models/concerns/reports/posters_by_member_type_spec.rb
@@ -120,7 +120,7 @@ describe Reports::PostersByMemberType do
expect(row(report, :returning)[:count]).to eq(0)
end
- it "filters by category when the category filter is provided" do
+ it "filters by category when the category_ids filter is provided" do
user = Fabricate(:user, created_at: start_date - 30.days)
target_category = Fabricate(:category)
other_category = Fabricate(:category)
@@ -129,18 +129,103 @@ describe Reports::PostersByMemberType do
Fabricate(:post, user: user, topic: target_topic, created_at: start_date + 1.day)
Fabricate(:post, user: user, topic: other_topic, created_at: start_date + 1.day)
- report = build(filters: { category: target_category.id })
+ report = build(filters: { category_ids: [target_category.id] })
expect(row(report, :returning)[:count]).to eq(1)
end
+ it "filters by the union of multiple categories" do
+ user = Fabricate(:user, created_at: start_date - 30.days)
+ first_category = Fabricate(:category)
+ second_category = Fabricate(:category)
+ other_category = Fabricate(:category)
+ first_topic = Fabricate(:topic, category: first_category)
+ second_topic = Fabricate(:topic, category: second_category)
+ other_topic = Fabricate(:topic, category: other_category)
+ Fabricate(:post, user: user, topic: first_topic, created_at: start_date + 1.day)
+ Fabricate(:post, user: user, topic: second_topic, created_at: start_date + 1.day)
+ Fabricate(:post, user: user, topic: other_topic, created_at: start_date + 1.day)
+
+ report = build(filters: { category_ids: [first_category.id, second_category.id] })
+
+ expect(row(report, :returning)[:count]).to eq(2)
+ end
+
+ it "accepts a comma-separated string of category ids" do
+ user = Fabricate(:user, created_at: start_date - 30.days)
+ target_category = Fabricate(:category)
+ other_category = Fabricate(:category)
+ target_topic = Fabricate(:topic, category: target_category)
+ other_topic = Fabricate(:topic, category: other_category)
+ Fabricate(:post, user: user, topic: target_topic, created_at: start_date + 1.day)
+ Fabricate(:post, user: user, topic: other_topic, created_at: start_date + 1.day)
+
+ report = build(filters: { category_ids: target_category.id.to_s })
+
+ expect(row(report, :returning)[:count]).to eq(1)
+ end
+
+ it "returns zero counts when a requested filter resolves to no valid ids" do
+ user = Fabricate(:user, created_at: start_date - 30.days)
+ topic = Fabricate(:topic, category: Fabricate(:category))
+ Fabricate(:post, user: user, topic: topic, created_at: start_date + 1.day)
+
+ report = build(filters: { category_ids: "foo,bar" })
+
+ expect(report.total).to eq(0)
+ expect(report.data.sum { |r| r[:count] }).to eq(0)
+ end
+
+ it "strips category ids that don't correspond to an existing category" do
+ nonexistent_id = Category.unscoped.maximum(:id).to_i + 1
+
+ report = build(filters: { category_ids: [nonexistent_id] })
+
+ expect(report.available_filters["category_ids"][:default]).to eq([])
+ end
+
+ it "keeps only the existing ids when the filter mixes real and nonexistent categories" do
+ user = Fabricate(:user, created_at: start_date - 30.days)
+ target_category = Fabricate(:category)
+ target_topic = Fabricate(:topic, category: target_category)
+ Fabricate(:post, user: user, topic: target_topic, created_at: start_date + 1.day)
+ nonexistent_id = Category.unscoped.maximum(:id).to_i + 1
+
+ report = build(filters: { category_ids: [target_category.id, nonexistent_id] })
+
+ expect(report.available_filters["category_ids"][:default]).to eq([target_category.id])
+ expect(row(report, :returning)[:count]).to eq(1)
+ end
+
+ it "preserves the requested order of the category ids" do
+ first = Fabricate(:category)
+ second = Fabricate(:category)
+ third = Fabricate(:category)
+
+ report = build(filters: { category_ids: [third.id, first.id, second.id] })
+
+ expect(report.available_filters["category_ids"][:default]).to eq(
+ [third.id, first.id, second.id],
+ )
+ end
+
+ it "caps the requested ids at MAX_CATEGORY_IDS" do
+ cats = Array.new(60) { Fabricate(:category) }
+
+ report = build(filters: { category_ids: cats.map(&:id).join(",") })
+
+ expect(report.available_filters["category_ids"][:default].length).to eq(
+ Reports::PostersByMemberType::MAX_CATEGORY_IDS,
+ )
+ end
+
it "renders a unicode category name without errors" do
user = Fabricate(:user, created_at: start_date - 30.days)
cat = Fabricate(:category, name: "字テスト")
topic = Fabricate(:topic, category: cat)
Fabricate(:post, user: user, topic: topic, created_at: start_date + 1.day)
- expect { build(filters: { category: cat.id }) }.not_to raise_error
+ expect { build(filters: { category_ids: [cat.id] }) }.not_to raise_error
end
describe "secured categories" do
@@ -165,7 +250,7 @@ describe Reports::PostersByMemberType do
topic = Fabricate(:topic, category: private_category)
Fabricate(:post, user: poster, topic: topic, created_at: start_date + 1.day)
- report = build(filters: { category: private_category.id }, current_user: moderator)
+ report = build(filters: { category_ids: [private_category.id] }, current_user: moderator)
expect(row(report, :returning)[:count]).to eq(0)
end
@@ -176,7 +261,7 @@ describe Reports::PostersByMemberType do
topic = Fabricate(:topic, category: private_category)
Fabricate(:post, user: poster, topic: topic, created_at: start_date + 1.day)
- report = build(filters: { category: private_category.id }, current_user: admin)
+ report = build(filters: { category_ids: [private_category.id] }, current_user: admin)
expect(row(report, :returning)[:count]).to eq(1)
end
diff --git a/spec/requests/admin/dashboard_controller_spec.rb b/spec/requests/admin/dashboard_controller_spec.rb
index 8eda61a463e..87d20756ae8 100644
--- a/spec/requests/admin/dashboard_controller_spec.rb
+++ b/spec/requests/admin/dashboard_controller_spec.rb
@@ -790,6 +790,32 @@ RSpec.describe Admin::DashboardController do
expect(AdminDashboardSectionConfiguration.settings_for("engagement")).to eq({})
end
+ it "persists the selected category ids and returns 204 for whos_posting" do
+ sign_in(admin)
+
+ put "/admin/dashboard/sections/engagement/settings/whos_posting.json",
+ params: {
+ category_ids: [category_3.id, category.id, category_2.id],
+ }
+
+ expect(response.status).to eq(204)
+ expect(AdminDashboardSectionConfiguration.settings_for("engagement")).to eq(
+ { "whos_posting" => { "category_ids" => [category_3.id, category.id, category_2.id] } },
+ )
+ end
+
+ it "returns 400 when more than ten categories are given for whos_posting" do
+ sign_in(admin)
+
+ put "/admin/dashboard/sections/engagement/settings/whos_posting.json",
+ params: {
+ category_ids: (1..11).to_a,
+ }
+
+ expect(response.status).to eq(400)
+ expect(AdminDashboardSectionConfiguration.settings_for("engagement")).to eq({})
+ end
+
it "returns 400 when a category with the given id does not exist" do
sign_in(admin)
diff --git a/spec/services/admin_dashboard_engagement_spec.rb b/spec/services/admin_dashboard_engagement_spec.rb
index 0375e828a54..50cae94932e 100644
--- a/spec/services/admin_dashboard_engagement_spec.rb
+++ b/spec/services/admin_dashboard_engagement_spec.rb
@@ -166,6 +166,75 @@ describe AdminDashboardEngagement do
expect(result[:posters][:total]).to eq(1)
end
+
+ it "restricts counted posts to the persisted category selection" do
+ selected = Fabricate(:category)
+ other = Fabricate(:category)
+ poster = Fabricate(:user, created_at: Time.zone.local(2026, 3, 1))
+ selected_topic = Fabricate(:topic, category: selected)
+ other_topic = Fabricate(:topic, category: other)
+ Fabricate(
+ :post,
+ user: poster,
+ topic: selected_topic,
+ created_at: Time.zone.local(2026, 4, 10),
+ )
+ Fabricate(:post, user: poster, topic: other_topic, created_at: Time.zone.local(2026, 4, 10))
+
+ AdminDashboardSectionConfiguration.update_setting(
+ section_id: "engagement",
+ key: "whos_posting",
+ attrs: {
+ category_ids: [selected.id],
+ },
+ )
+
+ result = described_class.build(start_date: "2026-04-01", end_date: "2026-04-28")
+
+ expect(result[:posters][:total]).to eq(1)
+ end
+
+ it "omits categories the current user cannot see from the persisted selection" do
+ moderator = Fabricate(:moderator)
+ visible = Fabricate(:category)
+ private_group = Fabricate(:group)
+ restricted = Fabricate(:private_category, group: private_group, read_restricted: true)
+
+ AdminDashboardSectionConfiguration.update_setting(
+ section_id: "engagement",
+ key: "whos_posting",
+ attrs: {
+ category_ids: [visible.id, restricted.id],
+ },
+ )
+
+ result =
+ described_class.build(
+ start_date: "2026-04-01",
+ end_date: "2026-04-28",
+ current_user: moderator,
+ )
+
+ expect(result[:posters][:category_ids]).to contain_exactly(visible.id)
+ end
+
+ it "preserves the saved order of the persisted category selection" do
+ first = Fabricate(:category)
+ second = Fabricate(:category)
+ third = Fabricate(:category)
+
+ AdminDashboardSectionConfiguration.update_setting(
+ section_id: "engagement",
+ key: "whos_posting",
+ attrs: {
+ category_ids: [third.id, first.id, second.id],
+ },
+ )
+
+ result = described_class.build(start_date: "2026-04-01", end_date: "2026-04-28")
+
+ expect(result[:posters][:category_ids]).to eq([third.id, first.id, second.id])
+ end
end
describe "activity_by_category" do
diff --git a/spec/services/admin_dashboard_section_configuration_spec.rb b/spec/services/admin_dashboard_section_configuration_spec.rb
index ed8245fcab8..b525d1bb6c4 100644
--- a/spec/services/admin_dashboard_section_configuration_spec.rb
+++ b/spec/services/admin_dashboard_section_configuration_spec.rb
@@ -184,6 +184,34 @@ describe AdminDashboardSectionConfiguration do
{ "activity_by_category" => { "category_ids" => [category.id, category_2.id] } },
)
end
+
+ it "returns the persisted settings for whos_posting independently of activity_by_category" do
+ described_class.update_setting(
+ section_id: "engagement",
+ key: "activity_by_category",
+ attrs: {
+ category_ids: [category.id],
+ },
+ )
+ described_class.update_setting(
+ section_id: "engagement",
+ key: "whos_posting",
+ attrs: {
+ category_ids: [category_2.id],
+ },
+ )
+
+ expect(described_class.settings_for("engagement")).to eq(
+ {
+ "activity_by_category" => {
+ "category_ids" => [category.id],
+ },
+ "whos_posting" => {
+ "category_ids" => [category_2.id],
+ },
+ },
+ )
+ end
end
describe ".update_setting" do
@@ -201,6 +229,32 @@ describe AdminDashboardSectionConfiguration do
)
end
+ it "persists a valid selection for whos_posting under its key" do
+ described_class.update_setting(
+ section_id: "engagement",
+ key: "whos_posting",
+ attrs: {
+ category_ids: [category.id, category_2.id],
+ },
+ )
+
+ expect(described_class.settings_for("engagement")).to eq(
+ { "whos_posting" => { "category_ids" => [category.id, category_2.id] } },
+ )
+ end
+
+ it "raises when more than the allowed number of categories are given for whos_posting" do
+ expect {
+ described_class.update_setting(
+ section_id: "engagement",
+ key: "whos_posting",
+ attrs: {
+ category_ids: (1..11).to_a,
+ },
+ )
+ }.to raise_error(Discourse::InvalidParameters)
+ end
+
it "raises when a category with the given id does not exist" do
expect {
described_class.update_setting(
diff --git a/spec/system/admin_dashboard_redesign/engagement_section_spec.rb b/spec/system/admin_dashboard_redesign/engagement_section_spec.rb
index 21cea85df3c..09c11bf8645 100644
--- a/spec/system/admin_dashboard_redesign/engagement_section_spec.rb
+++ b/spec/system/admin_dashboard_redesign/engagement_section_spec.rb
@@ -34,7 +34,7 @@ describe "Admin Dashboard Redesign | Engagement section" do
expect(dashboard).to have_section("engagement")
expect(engagement).to have_activity_row(category_alpha)
- engagement.deselect_category(category_alpha)
+ engagement.deselect_activity_category(category_alpha)
expect(engagement).to have_no_activity_row(category_alpha)
expect(engagement).to have_activity_row(category_bravo)
@@ -52,7 +52,7 @@ describe "Admin Dashboard Redesign | Engagement section" do
dashboard.visit
expect(engagement).to have_activity_row(category_alpha)
- engagement.deselect_category(category_alpha)
+ engagement.deselect_activity_category(category_alpha)
expect(engagement).to have_no_activity_row(category_alpha)
@@ -78,9 +78,40 @@ describe "Admin Dashboard Redesign | Engagement section" do
expect(engagement).to have_activity_row(category_alpha)
expect(engagement).to have_no_activity_row(category_dormant)
- engagement.expand_category_filter
+ engagement.expand_activity_category_filter
- expect(engagement).to have_selected_category(category_alpha)
- expect(engagement).to have_selected_category(category_dormant)
+ expect(engagement).to have_selected_activity_category(category_alpha)
+ expect(engagement).to have_selected_activity_category(category_dormant)
+ end
+
+ it "saves an admin's 'Who's posting' selection when the picker closes, and persists it across a refresh",
+ time: Time.zone.local(2026, 6, 15, 12, 0, 0) do
+ dashboard.visit
+ expect(dashboard).to have_section("engagement")
+
+ engagement.select_whos_posting_category(category_alpha)
+ engagement.close_whos_posting_category_filter
+
+ engagement.expand_whos_posting_category_filter
+ expect(engagement).to have_selected_whos_posting_category(category_alpha)
+
+ dashboard.visit
+
+ engagement.expand_whos_posting_category_filter
+ expect(engagement).to have_selected_whos_posting_category(category_alpha)
+ end
+
+ it "does not persist a moderator's 'Who's posting' selection",
+ time: Time.zone.local(2026, 6, 15, 12, 0, 0) do
+ sign_in(moderator)
+
+ dashboard.visit
+ engagement.select_whos_posting_category(category_alpha)
+ engagement.close_whos_posting_category_filter
+
+ dashboard.visit
+ engagement.expand_whos_posting_category_filter
+
+ expect(engagement).to have_no_selected_whos_posting_category(category_alpha)
end
end
diff --git a/spec/system/admin_reports_spec.rb b/spec/system/admin_reports_spec.rb
index 1bd92a439b4..a46beae049b 100644
--- a/spec/system/admin_reports_spec.rb
+++ b/spec/system/admin_reports_spec.rb
@@ -49,6 +49,24 @@ describe "Admin Reports" do
)
end
+ it "lets admins pick multiple categories to filter a report" do
+ category_1 = Fabricate(:category)
+ category_2 = Fabricate(:category)
+
+ reports_page.visit_report("activity_by_category")
+
+ expect(reports_page).to have_rendered_report("activity_by_category")
+ expect(reports_page).to have_category_filter
+
+ filter = reports_page.category_filter
+ filter.expand
+ filter.select_row_by_value(category_1.id)
+ filter.select_row_by_value(category_2.id)
+
+ expect(reports_page).to have_selected_category(category_1)
+ expect(reports_page).to have_selected_category(category_2)
+ end
+
it "lets admins filter report groups from URLs and controls" do
reports_page.visit_index(group: "engagement")
diff --git a/spec/system/page_objects/components/admin_dashboard_engagement.rb b/spec/system/page_objects/components/admin_dashboard_engagement.rb
index 1f4446c5f04..c63c1537793 100644
--- a/spec/system/page_objects/components/admin_dashboard_engagement.rb
+++ b/spec/system/page_objects/components/admin_dashboard_engagement.rb
@@ -4,21 +4,48 @@ module PageObjects
module Components
class AdminDashboardEngagement < PageObjects::Components::Base
SECTION = "[data-section-id='engagement']"
- CATEGORY_FILTER = "#{SECTION} .category-selector"
+ ACTIVITY_CATEGORY_FILTER = "#{SECTION} .db-activity .category-selector"
+ WHOS_POSTING_CATEGORY_FILTER = "#{SECTION} .db-whos-posting .category-selector"
ACTIVITY_CATEGORY_CELL = "#{SECTION} .db-activity-table__cell-category"
- def category_filter
- PageObjects::Components::SelectKit.new(CATEGORY_FILTER)
+ def activity_category_filter
+ PageObjects::Components::SelectKit.new(ACTIVITY_CATEGORY_FILTER)
end
- def expand_category_filter
- category_filter.expand
+ def whos_posting_category_filter
+ PageObjects::Components::SelectKit.new(WHOS_POSTING_CATEGORY_FILTER)
+ end
+
+ def expand_activity_category_filter
+ activity_category_filter.expand
+ self
+ end
+
+ def expand_whos_posting_category_filter
+ whos_posting_category_filter.expand
+ self
+ end
+
+ def deselect_activity_category(category)
+ expand_activity_category_filter
+ find("#{ACTIVITY_CATEGORY_FILTER} .selected-choice[data-value='#{category.id}']").click
+ self
+ end
+
+ def deselect_whos_posting_category(category)
+ expand_whos_posting_category_filter
+ find("#{WHOS_POSTING_CATEGORY_FILTER} .selected-choice[data-value='#{category.id}']").click
+ self
+ end
+
+ def select_whos_posting_category(category)
+ expand_whos_posting_category_filter
+ whos_posting_category_filter.select_row_by_value(category.id)
self
end
- def deselect_category(category)
- expand_category_filter
- find("#{CATEGORY_FILTER} .selected-choice[data-value='#{category.id}']").click
+ def close_whos_posting_category_filter
+ whos_posting_category_filter.collapse
self
end
@@ -30,8 +57,16 @@ module PageObjects
has_no_css?(ACTIVITY_CATEGORY_CELL, text: category.name)
end
- def has_selected_category?(category)
- has_css?("#{CATEGORY_FILTER} .selected-choice[data-value='#{category.id}']")
+ def has_selected_activity_category?(category)
+ has_css?("#{ACTIVITY_CATEGORY_FILTER} .selected-choice[data-value='#{category.id}']")
+ end
+
+ def has_selected_whos_posting_category?(category)
+ has_css?("#{WHOS_POSTING_CATEGORY_FILTER} .selected-choice[data-value='#{category.id}']")
+ end
+
+ def has_no_selected_whos_posting_category?(category)
+ has_no_css?("#{WHOS_POSTING_CATEGORY_FILTER} .selected-choice[data-value='#{category.id}']")
end
end
end
diff --git a/spec/system/page_objects/pages/admin_report.rb b/spec/system/page_objects/pages/admin_report.rb
index bdd0338c81c..bf19d6b0ed4 100644
--- a/spec/system/page_objects/pages/admin_report.rb
+++ b/spec/system/page_objects/pages/admin_report.rb
@@ -40,6 +40,29 @@ module PageObjects
PageObjects::Components::DFilterControls.new(".d-filter-controls")
end
+ CATEGORY_FILTER = ".admin-report .chart__additional-filters .category-selector"
+
+ def visit_report(type)
+ page.visit("/admin/reports/#{type}")
+ self
+ end
+
+ def has_rendered_report?(type)
+ page.has_css?(".admin-report.#{type.tr("_", "-")}")
+ end
+
+ def has_category_filter?
+ page.has_css?(CATEGORY_FILTER)
+ end
+
+ def category_filter
+ PageObjects::Components::SelectKit.new(CATEGORY_FILTER)
+ end
+
+ def has_selected_category?(category)
+ page.has_css?("#{CATEGORY_FILTER} .selected-choice[data-value='#{category.id}']")
+ end
+
def has_group?(name)
page.has_css?(".admin-reports-group__title", text: name)
end